Fix build on OS X (Thanks neoascetic)
[oweals/minetest.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 #if defined(__hpux)
39         #define _PSTAT64
40         #include <sys/pstat.h>
41 #endif
42 #if !defined(_WIN32) && !defined(__APPLE__) && \
43         !defined(__ANDROID__) && !defined(SERVER)
44         #define XORG_USED
45 #endif
46 #ifdef XORG_USED
47         #include <X11/Xlib.h>
48         #include <X11/Xutil.h>
49 #endif
50
51 #include "config.h"
52 #include "debug.h"
53 #include "filesys.h"
54 #include "log.h"
55 #include "util/string.h"
56 #include "settings.h"
57 #include <list>
58
59 namespace porting
60 {
61
62 /*
63         Signal handler (grabs Ctrl-C on POSIX systems)
64 */
65
66 bool g_killed = false;
67
68 bool * signal_handler_killstatus(void)
69 {
70         return &g_killed;
71 }
72
73 #if !defined(_WIN32) // POSIX
74         #include <signal.h>
75
76 void sigint_handler(int sig)
77 {
78         if(g_killed == false)
79         {
80                 dstream<<DTIME<<"INFO: sigint_handler(): "
81                                 <<"Ctrl-C pressed, shutting down."<<std::endl;
82
83                 // Comment out for less clutter when testing scripts
84                 /*dstream<<DTIME<<"INFO: sigint_handler(): "
85                                 <<"Printing debug stacks"<<std::endl;
86                 debug_stacks_print();*/
87
88                 g_killed = true;
89         }
90         else
91         {
92                 (void)signal(SIGINT, SIG_DFL);
93         }
94 }
95
96 void signal_handler_init(void)
97 {
98         (void)signal(SIGINT, sigint_handler);
99 }
100
101 #else // _WIN32
102         #include <signal.h>
103
104 BOOL WINAPI event_handler(DWORD sig)
105 {
106         switch (sig) {
107         case CTRL_C_EVENT:
108         case CTRL_CLOSE_EVENT:
109         case CTRL_LOGOFF_EVENT:
110         case CTRL_SHUTDOWN_EVENT:
111                 if (g_killed == false) {
112                         dstream << DTIME << "INFO: event_handler(): "
113                                 << "Ctrl+C, Close Event, Logoff Event or Shutdown Event,"
114                                 " shutting down." << std::endl;
115                         g_killed = true;
116                 } else {
117                         (void)signal(SIGINT, SIG_DFL);
118                 }
119                 break;
120         case CTRL_BREAK_EVENT:
121                 break;
122         }
123
124         return TRUE;
125 }
126
127 void signal_handler_init(void)
128 {
129         SetConsoleCtrlHandler( (PHANDLER_ROUTINE)event_handler,TRUE);
130 }
131
132 #endif
133
134
135 /*
136         Multithreading support
137 */
138 int getNumberOfProcessors()
139 {
140 #if defined(_SC_NPROCESSORS_ONLN)
141
142         return sysconf(_SC_NPROCESSORS_ONLN);
143
144 #elif defined(__FreeBSD__) || defined(__APPLE__)
145
146         unsigned int len, count;
147         len = sizeof(count);
148         return sysctlbyname("hw.ncpu", &count, &len, NULL, 0);
149
150 #elif defined(_GNU_SOURCE)
151
152         return get_nprocs();
153
154 #elif defined(_WIN32)
155
156         SYSTEM_INFO sysinfo;
157         GetSystemInfo(&sysinfo);
158         return sysinfo.dwNumberOfProcessors;
159
160 #elif defined(PTW32_VERSION) || defined(__hpux)
161
162         return pthread_num_processors_np();
163
164 #else
165
166         return 1;
167
168 #endif
169 }
170
171
172 #ifndef __ANDROID__
173 bool threadBindToProcessor(threadid_t tid, int pnumber)
174 {
175 #if defined(_WIN32)
176
177         HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, 0, tid);
178         if (!hThread)
179                 return false;
180
181         bool success = SetThreadAffinityMask(hThread, 1 << pnumber) != 0;
182
183         CloseHandle(hThread);
184         return success;
185
186 #elif (defined(__FreeBSD__) && (__FreeBSD_version >= 702106)) \
187         || defined(__linux) || defined(linux)
188
189         cpu_set_t cpuset;
190
191         CPU_ZERO(&cpuset);
192         CPU_SET(pnumber, &cpuset);
193         return pthread_setaffinity_np(tid, sizeof(cpuset), &cpuset) == 0;
194
195 #elif defined(__sun) || defined(sun)
196
197         return processor_bind(P_LWPID, MAKE_LWPID_PTHREAD(tid),
198                 pnumber, NULL) == 0;
199
200 #elif defined(_AIX)
201
202         return bindprocessor(BINDTHREAD, (tid_t)tid, pnumber) == 0;
203
204 #elif defined(__hpux) || defined(hpux)
205
206         pthread_spu_t answer;
207
208         return pthread_processor_bind_np(PTHREAD_BIND_ADVISORY_NP,
209                 &answer, pnumber, tid) == 0;
210
211 #elif defined(__APPLE__)
212
213         struct thread_affinity_policy tapol;
214
215         thread_port_t threadport = pthread_mach_thread_np(tid);
216         tapol.affinity_tag = pnumber + 1;
217         return thread_policy_set(threadport, THREAD_AFFINITY_POLICY,
218                 (thread_policy_t)&tapol, THREAD_AFFINITY_POLICY_COUNT) == KERN_SUCCESS;
219
220 #else
221
222         return false;
223
224 #endif
225 }
226 #endif
227
228 bool threadSetPriority(threadid_t tid, int prio)
229 {
230 #if defined(_WIN32)
231
232         HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, 0, tid);
233         if (!hThread)
234                 return false;
235
236         bool success = SetThreadPriority(hThread, prio) != 0;
237
238         CloseHandle(hThread);
239         return success;
240
241 #else
242
243         struct sched_param sparam;
244         int policy;
245
246         if (pthread_getschedparam(tid, &policy, &sparam) != 0)
247                 return false;
248
249         int min = sched_get_priority_min(policy);
250         int max = sched_get_priority_max(policy);
251
252         sparam.sched_priority = min + prio * (max - min) / THREAD_PRIORITY_HIGHEST;
253         return pthread_setschedparam(tid, policy, &sparam) == 0;
254
255 #endif
256 }
257
258
259 /*
260         Path mangler
261 */
262
263 // Default to RUN_IN_PLACE style relative paths
264 std::string path_share = "..";
265 std::string path_user = "..";
266
267 std::string getDataPath(const char *subpath)
268 {
269         return path_share + DIR_DELIM + subpath;
270 }
271
272 void pathRemoveFile(char *path, char delim)
273 {
274         // Remove filename and path delimiter
275         int i;
276         for(i = strlen(path)-1; i>=0; i--)
277         {
278                 if(path[i] == delim)
279                         break;
280         }
281         path[i] = 0;
282 }
283
284 bool detectMSVCBuildDir(const std::string &path)
285 {
286         const char *ends[] = {
287                 "bin\\Release",
288                 "bin\\Debug",
289                 "bin\\Build",
290                 NULL
291         };
292         return (removeStringEnd(path, ends) != "");
293 }
294
295 std::string get_sysinfo()
296 {
297 #ifdef _WIN32
298         OSVERSIONINFO osvi;
299         std::ostringstream oss;
300         std::string tmp;
301         ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
302         osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
303         GetVersionEx(&osvi);
304         tmp = osvi.szCSDVersion;
305         std::replace(tmp.begin(), tmp.end(), ' ', '_');
306
307         oss << "Windows/" << osvi.dwMajorVersion << "."
308                 << osvi.dwMinorVersion;
309         if(osvi.szCSDVersion[0])
310                 oss << "-" << tmp;
311         oss << " ";
312         #ifdef _WIN64
313         oss << "x86_64";
314         #else
315         BOOL is64 = FALSE;
316         if(IsWow64Process(GetCurrentProcess(), &is64) && is64)
317                 oss << "x86_64"; // 32-bit app on 64-bit OS
318         else
319                 oss << "x86";
320         #endif
321
322         return oss.str();
323 #else
324         struct utsname osinfo;
325         uname(&osinfo);
326         return std::string(osinfo.sysname) + "/"
327                 + osinfo.release + " " + osinfo.machine;
328 #endif
329 }
330
331
332 bool getCurrentWorkingDir(char *buf, size_t len)
333 {
334 #ifdef _WIN32
335         DWORD ret = GetCurrentDirectory(len, buf);
336         return (ret != 0) && (ret <= len);
337 #else
338         return getcwd(buf, len);
339 #endif
340 }
341
342
343 bool getExecPathFromProcfs(char *buf, size_t buflen)
344 {
345 #ifndef _WIN32
346         buflen--;
347
348         ssize_t len;
349         if ((len = readlink("/proc/self/exe",     buf, buflen)) == -1 &&
350                 (len = readlink("/proc/curproc/file", buf, buflen)) == -1 &&
351                 (len = readlink("/proc/curproc/exe",  buf, buflen)) == -1)
352                 return false;
353
354         buf[len] = '\0';
355         return true;
356 #else
357         return false;
358 #endif
359 }
360
361 //// Windows
362 #if defined(_WIN32)
363
364 bool getCurrentExecPath(char *buf, size_t len)
365 {
366         DWORD written = GetModuleFileNameA(NULL, buf, len);
367         if (written == 0 || written == len)
368                 return false;
369
370         return true;
371 }
372
373
374 //// Linux
375 #elif defined(linux) || defined(__linux) || defined(__linux__)
376
377 bool getCurrentExecPath(char *buf, size_t len)
378 {
379         if (!getExecPathFromProcfs(buf, len))
380                 return false;
381
382         return true;
383 }
384
385
386 //// Mac OS X, Darwin
387 #elif defined(__APPLE__)
388
389 bool getCurrentExecPath(char *buf, size_t len)
390 {
391         uint32_t lenb = (uint32_t)len;
392         if (_NSGetExecutablePath(buf, &lenb) == -1)
393                 return false;
394
395         return true;
396 }
397
398
399 //// FreeBSD, NetBSD, DragonFlyBSD
400 #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
401
402 bool getCurrentExecPath(char *buf, size_t len)
403 {
404         // Try getting path from procfs first, since valgrind
405         // doesn't work with the latter
406         if (getExecPathFromProcfs(buf, len))
407                 return true;
408
409         int mib[4];
410
411         mib[0] = CTL_KERN;
412         mib[1] = KERN_PROC;
413         mib[2] = KERN_PROC_PATHNAME;
414         mib[3] = -1;
415
416         if (sysctl(mib, 4, buf, &len, NULL, 0) == -1)
417                 return false;
418
419         return true;
420 }
421
422
423 //// Solaris
424 #elif defined(__sun) || defined(sun)
425
426 bool getCurrentExecPath(char *buf, size_t len)
427 {
428         const char *exec = getexecname();
429         if (exec == NULL)
430                 return false;
431
432         if (strlcpy(buf, exec, len) >= len)
433                 return false;
434
435         return true;
436 }
437
438
439 // HP-UX
440 #elif defined(__hpux)
441
442 bool getCurrentExecPath(char *buf, size_t len)
443 {
444         struct pst_status psts;
445
446         if (pstat_getproc(&psts, sizeof(psts), 0, getpid()) == -1)
447                 return false;
448
449         if (pstat_getpathname(buf, len, &psts.pst_fid_text) == -1)
450                 return false;
451
452         return true;
453 }
454
455
456 #else
457
458 bool getCurrentExecPath(char *buf, size_t len)
459 {
460         return false;
461 }
462
463 #endif
464
465
466 //// Windows
467 #if defined(_WIN32)
468
469 bool setSystemPaths()
470 {
471         char buf[BUFSIZ];
472
473         // Find path of executable and set path_share relative to it
474         FATAL_ERROR_IF(!getCurrentExecPath(buf, sizeof(buf)),
475                 "Failed to get current executable path");
476         pathRemoveFile(buf, '\\');
477
478         // Use ".\bin\.."
479         path_share = std::string(buf) + "\\..";
480
481         // Use "C:\Documents and Settings\user\Application Data\<PROJECT_NAME>"
482         DWORD len = GetEnvironmentVariable("APPDATA", buf, sizeof(buf));
483         FATAL_ERROR_IF(len == 0 || len > sizeof(buf), "Failed to get APPDATA");
484
485         path_user = std::string(buf) + DIR_DELIM + lowercase(PROJECT_NAME);
486         return true;
487 }
488
489
490 //// Linux
491 #elif defined(linux) || defined(__linux)
492
493 bool setSystemPaths()
494 {
495         char buf[BUFSIZ];
496
497         if (!getCurrentExecPath(buf, sizeof(buf))) {
498 #ifdef __ANDROID__
499                 errorstream << "Unable to read bindir "<< std::endl;
500 #else
501                 FATAL_ERROR("Unable to read bindir");
502 #endif
503                 return false;
504         }
505
506         pathRemoveFile(buf, '/');
507         std::string bindir(buf);
508
509         // Find share directory from these.
510         // It is identified by containing the subdirectory "builtin".
511         std::list<std::string> trylist;
512         std::string static_sharedir = STATIC_SHAREDIR;
513         if (static_sharedir != "" && static_sharedir != ".")
514                 trylist.push_back(static_sharedir);
515
516         trylist.push_back(bindir + DIR_DELIM ".." DIR_DELIM "share"
517                 DIR_DELIM + lowercase(PROJECT_NAME));
518         trylist.push_back(bindir + DIR_DELIM "..");
519
520 #ifdef __ANDROID__
521         trylist.push_back(path_user);
522 #endif
523
524         for (std::list<std::string>::const_iterator
525                         i = trylist.begin(); i != trylist.end(); i++) {
526                 const std::string &trypath = *i;
527                 if (!fs::PathExists(trypath) ||
528                         !fs::PathExists(trypath + DIR_DELIM + "builtin")) {
529                         dstream << "WARNING: system-wide share not found at \""
530                                         << trypath << "\""<< std::endl;
531                         continue;
532                 }
533
534                 // Warn if was not the first alternative
535                 if (i != trylist.begin()) {
536                         dstream << "WARNING: system-wide share found at \""
537                                         << trypath << "\"" << std::endl;
538                 }
539
540                 path_share = trypath;
541                 break;
542         }
543
544 #ifndef __ANDROID__
545         path_user = std::string(getenv("HOME")) + DIR_DELIM "."
546                 + lowercase(PROJECT_NAME);
547 #endif
548
549         return true;
550 }
551
552
553 //// Mac OS X
554 #elif defined(__APPLE__)
555
556 bool setSystemPaths()
557 {
558         CFBundleRef main_bundle = CFBundleGetMainBundle();
559         CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
560         char path[PATH_MAX];
561         if (CFURLGetFileSystemRepresentation(resources_url,
562                         TRUE, (UInt8 *)path, PATH_MAX)) {
563                 path_share = std::string(path);
564         } else {
565                 dstream << "WARNING: Could not determine bundle resource path" << std::endl;
566         }
567         CFRelease(resources_url);
568
569         path_user = std::string(getenv("HOME"))
570                 + "/Library/Application Support/"
571                 + lowercase(PROJECT_NAME);
572         return true;
573 }
574
575
576 #else
577
578 bool setSystemPaths()
579 {
580         path_share = STATIC_SHAREDIR;
581         path_user  = std::string(getenv("HOME")) + DIR_DELIM "."
582                 + lowercase(PROJECT_NAME);
583         return true;
584 }
585
586
587 #endif
588
589
590 void initializePaths()
591 {
592 #if RUN_IN_PLACE
593         char buf[BUFSIZ];
594
595         infostream << "Using relative paths (RUN_IN_PLACE)" << std::endl;
596
597         bool success =
598                 getCurrentExecPath(buf, sizeof(buf)) ||
599                 getExecPathFromProcfs(buf, sizeof(buf));
600
601         if (success) {
602                 pathRemoveFile(buf, '/');
603                 std::string execpath(buf);
604
605                 path_share = execpath + DIR_DELIM "..";
606                 path_user  = execpath + DIR_DELIM "..";
607
608                 if (detectMSVCBuildDir(execpath)) {
609                         path_share += DIR_DELIM "..";
610                         path_user  += DIR_DELIM "..";
611                 }
612         } else {
613                 errorstream << "Failed to get paths by executable location, "
614                         "trying cwd" << std::endl;
615
616                 if (!getCurrentWorkingDir(buf, sizeof(buf)))
617                         FATAL_ERROR("Ran out of methods to get paths");
618
619                 size_t cwdlen = strlen(buf);
620                 if (cwdlen >= 1 && buf[cwdlen - 1] == DIR_DELIM_CHAR) {
621                         cwdlen--;
622                         buf[cwdlen] = '\0';
623                 }
624
625                 if (cwdlen >= 4 && !strcmp(buf + cwdlen - 4, DIR_DELIM "bin"))
626                         pathRemoveFile(buf, DIR_DELIM_CHAR);
627
628                 std::string execpath(buf);
629
630                 path_share = execpath;
631                 path_user  = execpath;
632         }
633
634 #else
635         infostream << "Using system-wide paths (NOT RUN_IN_PLACE)" << std::endl;
636
637         if (!setSystemPaths())
638                 errorstream << "Failed to get one or more system-wide path" << std::endl;
639
640 #endif
641
642         infostream << "Detected share path: " << path_share << std::endl;
643         infostream << "Detected user path: " << path_user << std::endl;
644 }
645
646
647
648 void setXorgClassHint(const video::SExposedVideoData &video_data,
649         const std::string &name)
650 {
651 #ifdef XORG_USED
652         if (video_data.OpenGLLinux.X11Display == NULL)
653                 return;
654
655         XClassHint *classhint = XAllocClassHint();
656         classhint->res_name  = (char *)name.c_str();
657         classhint->res_class = (char *)name.c_str();
658
659         XSetClassHint((Display *)video_data.OpenGLLinux.X11Display,
660                 video_data.OpenGLLinux.X11Window, classhint);
661         XFree(classhint);
662 #endif
663 }
664
665
666 ////
667 //// Video/Display Information (Client-only)
668 ////
669
670 #ifndef SERVER
671
672 static irr::IrrlichtDevice *device;
673
674 void initIrrlicht(irr::IrrlichtDevice *device_)
675 {
676         device = device_;
677 }
678
679 v2u32 getWindowSize()
680 {
681         return device->getVideoDriver()->getScreenSize();
682 }
683
684
685 std::vector<core::vector3d<u32> > getSupportedVideoModes()
686 {
687         IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
688         sanity_check(nulldevice != NULL);
689
690         std::vector<core::vector3d<u32> > mlist;
691         video::IVideoModeList *modelist = nulldevice->getVideoModeList();
692
693         u32 num_modes = modelist->getVideoModeCount();
694         for (u32 i = 0; i != num_modes; i++) {
695                 core::dimension2d<u32> mode_res = modelist->getVideoModeResolution(i);
696                 s32 mode_depth = modelist->getVideoModeDepth(i);
697                 mlist.push_back(core::vector3d<u32>(mode_res.Width, mode_res.Height, mode_depth));
698         }
699
700         nulldevice->drop();
701
702         return mlist;
703 }
704
705 std::vector<irr::video::E_DRIVER_TYPE> getSupportedVideoDrivers()
706 {
707         std::vector<irr::video::E_DRIVER_TYPE> drivers;
708
709         for (int i = 0; i != irr::video::EDT_COUNT; i++) {
710                 if (irr::IrrlichtDevice::isDriverSupported((irr::video::E_DRIVER_TYPE)i))
711                         drivers.push_back((irr::video::E_DRIVER_TYPE)i);
712         }
713
714         return drivers;
715 }
716
717 const char *getVideoDriverName(irr::video::E_DRIVER_TYPE type)
718 {
719         static const char *driver_ids[] = {
720                 "null",
721                 "software",
722                 "burningsvideo",
723                 "direct3d8",
724                 "direct3d9",
725                 "opengl",
726                 "ogles1",
727                 "ogles2",
728         };
729
730         return driver_ids[type];
731 }
732
733
734 const char *getVideoDriverFriendlyName(irr::video::E_DRIVER_TYPE type)
735 {
736         static const char *driver_names[] = {
737                 "NULL Driver",
738                 "Software Renderer",
739                 "Burning's Video",
740                 "Direct3D 8",
741                 "Direct3D 9",
742                 "OpenGL",
743                 "OpenGL ES1",
744                 "OpenGL ES2",
745         };
746
747         return driver_names[type];
748 }
749
750 #       ifndef __ANDROID__
751 #               ifdef XORG_USED
752
753 static float calcDisplayDensity()
754 {
755         const char* current_display = getenv("DISPLAY");
756
757         if (current_display != NULL) {
758                         Display * x11display = XOpenDisplay(current_display);
759
760                         if (x11display != NULL) {
761                                 /* try x direct */
762                                 float dpi_height =
763                                                 floor(DisplayHeight(x11display, 0) /
764                                                                 (DisplayHeightMM(x11display, 0) * 0.039370) + 0.5);
765                                 float dpi_width =
766                                                 floor(DisplayWidth(x11display, 0) /
767                                                                 (DisplayWidthMM(x11display, 0) * 0.039370) +0.5);
768
769                                 XCloseDisplay(x11display);
770
771                                 return std::max(dpi_height,dpi_width) / 96.0;
772                         }
773                 }
774
775         /* return manually specified dpi */
776         return g_settings->getFloat("screen_dpi")/96.0;
777 }
778
779
780 float getDisplayDensity()
781 {
782         static float cached_display_density = calcDisplayDensity();
783         return cached_display_density;
784 }
785
786
787 #               else // XORG_USED
788 float getDisplayDensity()
789 {
790         return g_settings->getFloat("screen_dpi")/96.0;
791 }
792 #               endif // XORG_USED
793
794 v2u32 getDisplaySize()
795 {
796         IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
797
798         core::dimension2d<u32> deskres = nulldevice->getVideoModeList()->getDesktopResolution();
799         nulldevice -> drop();
800
801         return deskres;
802 }
803 #       endif // __ANDROID__
804 #endif // SERVER
805
806 } //namespace porting
807