3 Copyright (C) 2013 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 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.
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.
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.
21 Random portability stuff
23 See comments in porting.h
28 #if defined(__FreeBSD__)
29 #include <sys/types.h>
30 #include <sys/sysctl.h>
36 #include <sys/utsname.h>
40 #include <sys/pstat.h>
42 #if !defined(_WIN32) && !defined(__APPLE__) && \
43 !defined(__ANDROID__) && !defined(SERVER)
48 #include <X11/Xutil.h>
55 #include "util/string.h"
63 Signal handler (grabs Ctrl-C on POSIX systems)
66 bool g_killed = false;
68 bool * signal_handler_killstatus(void)
73 #if !defined(_WIN32) // POSIX
76 void sigint_handler(int sig)
79 dstream<<DTIME<<"INFO: sigint_handler(): "
80 <<"Ctrl-C pressed, shutting down."<<std::endl;
82 // Comment out for less clutter when testing scripts
83 /*dstream<<DTIME<<"INFO: sigint_handler(): "
84 <<"Printing debug stacks"<<std::endl;
85 debug_stacks_print();*/
89 (void)signal(SIGINT, SIG_DFL);
93 void signal_handler_init(void)
95 (void)signal(SIGINT, sigint_handler);
101 BOOL WINAPI event_handler(DWORD sig)
105 case CTRL_CLOSE_EVENT:
106 case CTRL_LOGOFF_EVENT:
107 case CTRL_SHUTDOWN_EVENT:
108 if (g_killed == false) {
109 dstream << DTIME << "INFO: event_handler(): "
110 << "Ctrl+C, Close Event, Logoff Event or Shutdown Event,"
111 " shutting down." << std::endl;
114 (void)signal(SIGINT, SIG_DFL);
117 case CTRL_BREAK_EVENT:
124 void signal_handler_init(void)
126 SetConsoleCtrlHandler((PHANDLER_ROUTINE)event_handler, TRUE);
133 Multithreading support
135 int getNumberOfProcessors()
137 #if defined(_SC_NPROCESSORS_ONLN)
139 return sysconf(_SC_NPROCESSORS_ONLN);
141 #elif defined(__FreeBSD__) || defined(__APPLE__)
143 unsigned int len, count;
145 return sysctlbyname("hw.ncpu", &count, &len, NULL, 0);
147 #elif defined(_GNU_SOURCE)
151 #elif defined(_WIN32)
154 GetSystemInfo(&sysinfo);
155 return sysinfo.dwNumberOfProcessors;
157 #elif defined(PTW32_VERSION) || defined(__hpux)
159 return pthread_num_processors_np();
170 bool threadBindToProcessor(threadid_t tid, int pnumber)
174 HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, 0, tid);
178 bool success = SetThreadAffinityMask(hThread, 1 << pnumber) != 0;
180 CloseHandle(hThread);
183 #elif (defined(__FreeBSD__) && (__FreeBSD_version >= 702106)) \
184 || defined(__linux) || defined(linux)
189 CPU_SET(pnumber, &cpuset);
190 return pthread_setaffinity_np(tid, sizeof(cpuset), &cpuset) == 0;
192 #elif defined(__sun) || defined(sun)
194 return processor_bind(P_LWPID, MAKE_LWPID_PTHREAD(tid),
199 return bindprocessor(BINDTHREAD, (tid_t)tid, pnumber) == 0;
201 #elif defined(__hpux) || defined(hpux)
203 pthread_spu_t answer;
205 return pthread_processor_bind_np(PTHREAD_BIND_ADVISORY_NP,
206 &answer, pnumber, tid) == 0;
208 #elif defined(__APPLE__)
210 struct thread_affinity_policy tapol;
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;
225 bool threadSetPriority(threadid_t tid, int prio)
229 HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, 0, tid);
233 bool success = SetThreadPriority(hThread, prio) != 0;
235 CloseHandle(hThread);
240 struct sched_param sparam;
243 if (pthread_getschedparam(tid, &policy, &sparam) != 0)
246 int min = sched_get_priority_min(policy);
247 int max = sched_get_priority_max(policy);
249 sparam.sched_priority = min + prio * (max - min) / THREAD_PRIORITY_HIGHEST;
250 return pthread_setschedparam(tid, policy, &sparam) == 0;
260 // Default to RUN_IN_PLACE style relative paths
261 std::string path_share = "..";
262 std::string path_user = "..";
264 std::string getDataPath(const char *subpath)
266 return path_share + DIR_DELIM + subpath;
269 void pathRemoveFile(char *path, char delim)
271 // Remove filename and path delimiter
273 for(i = strlen(path)-1; i>=0; i--)
281 bool detectMSVCBuildDir(const std::string &path)
283 const char *ends[] = {
289 return (removeStringEnd(path, ends) != "");
292 std::string get_sysinfo()
296 std::ostringstream oss;
298 ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
299 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
301 tmp = osvi.szCSDVersion;
302 std::replace(tmp.begin(), tmp.end(), ' ', '_');
304 oss << "Windows/" << osvi.dwMajorVersion << "."
305 << osvi.dwMinorVersion;
306 if (osvi.szCSDVersion[0])
313 if (IsWow64Process(GetCurrentProcess(), &is64) && is64)
314 oss << "x86_64"; // 32-bit app on 64-bit OS
321 struct utsname osinfo;
323 return std::string(osinfo.sysname) + "/"
324 + osinfo.release + " " + osinfo.machine;
329 bool getCurrentWorkingDir(char *buf, size_t len)
332 DWORD ret = GetCurrentDirectory(len, buf);
333 return (ret != 0) && (ret <= len);
335 return getcwd(buf, len);
340 bool getExecPathFromProcfs(char *buf, size_t buflen)
346 if ((len = readlink("/proc/self/exe", buf, buflen)) == -1 &&
347 (len = readlink("/proc/curproc/file", buf, buflen)) == -1 &&
348 (len = readlink("/proc/curproc/exe", buf, buflen)) == -1)
361 bool getCurrentExecPath(char *buf, size_t len)
363 DWORD written = GetModuleFileNameA(NULL, buf, len);
364 if (written == 0 || written == len)
372 #elif defined(linux) || defined(__linux) || defined(__linux__)
374 bool getCurrentExecPath(char *buf, size_t len)
376 if (!getExecPathFromProcfs(buf, len))
383 //// Mac OS X, Darwin
384 #elif defined(__APPLE__)
386 bool getCurrentExecPath(char *buf, size_t len)
388 uint32_t lenb = (uint32_t)len;
389 if (_NSGetExecutablePath(buf, &lenb) == -1)
396 //// FreeBSD, NetBSD, DragonFlyBSD
397 #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
399 bool getCurrentExecPath(char *buf, size_t len)
401 // Try getting path from procfs first, since valgrind
402 // doesn't work with the latter
403 if (getExecPathFromProcfs(buf, len))
410 mib[2] = KERN_PROC_PATHNAME;
413 if (sysctl(mib, 4, buf, &len, NULL, 0) == -1)
421 #elif defined(__sun) || defined(sun)
423 bool getCurrentExecPath(char *buf, size_t len)
425 const char *exec = getexecname();
429 if (strlcpy(buf, exec, len) >= len)
437 #elif defined(__hpux)
439 bool getCurrentExecPath(char *buf, size_t len)
441 struct pst_status psts;
443 if (pstat_getproc(&psts, sizeof(psts), 0, getpid()) == -1)
446 if (pstat_getpathname(buf, len, &psts.pst_fid_text) == -1)
455 bool getCurrentExecPath(char *buf, size_t len)
466 bool setSystemPaths()
470 // Find path of executable and set path_share relative to it
471 FATAL_ERROR_IF(!getCurrentExecPath(buf, sizeof(buf)),
472 "Failed to get current executable path");
473 pathRemoveFile(buf, '\\');
476 path_share = std::string(buf) + "\\..";
478 // Use "C:\Documents and Settings\user\Application Data\<PROJECT_NAME>"
479 DWORD len = GetEnvironmentVariable("APPDATA", buf, sizeof(buf));
480 FATAL_ERROR_IF(len == 0 || len > sizeof(buf), "Failed to get APPDATA");
482 path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME;
488 #elif defined(linux) || defined(__linux)
490 bool setSystemPaths()
494 if (!getCurrentExecPath(buf, sizeof(buf))) {
496 errorstream << "Unable to read bindir "<< std::endl;
498 FATAL_ERROR("Unable to read bindir");
503 pathRemoveFile(buf, '/');
504 std::string bindir(buf);
506 // Find share directory from these.
507 // It is identified by containing the subdirectory "builtin".
508 std::list<std::string> trylist;
509 std::string static_sharedir = STATIC_SHAREDIR;
510 if (static_sharedir != "" && static_sharedir != ".")
511 trylist.push_back(static_sharedir);
513 trylist.push_back(bindir + DIR_DELIM ".." DIR_DELIM "share"
514 DIR_DELIM + PROJECT_NAME);
515 trylist.push_back(bindir + DIR_DELIM "..");
518 trylist.push_back(path_user);
521 for (std::list<std::string>::const_iterator
522 i = trylist.begin(); i != trylist.end(); i++) {
523 const std::string &trypath = *i;
524 if (!fs::PathExists(trypath) ||
525 !fs::PathExists(trypath + DIR_DELIM + "builtin")) {
526 dstream << "WARNING: system-wide share not found at \""
527 << trypath << "\""<< std::endl;
531 // Warn if was not the first alternative
532 if (i != trylist.begin()) {
533 dstream << "WARNING: system-wide share found at \""
534 << trypath << "\"" << std::endl;
537 path_share = trypath;
542 path_user = std::string(getenv("HOME")) + DIR_DELIM "."
551 #elif defined(__APPLE__)
553 bool setSystemPaths()
555 CFBundleRef main_bundle = CFBundleGetMainBundle();
556 CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
558 if (CFURLGetFileSystemRepresentation(resources_url,
559 TRUE, (UInt8 *)path, PATH_MAX)) {
560 path_share = std::string(path);
562 dstream << "WARNING: Could not determine bundle resource path" << std::endl;
564 CFRelease(resources_url);
566 path_user = std::string(getenv("HOME"))
567 + "/Library/Application Support/"
575 bool setSystemPaths()
577 path_share = STATIC_SHAREDIR;
578 path_user = std::string(getenv("HOME")) + DIR_DELIM "."
579 + lowercase(PROJECT_NAME);
587 void initializePaths()
592 infostream << "Using relative paths (RUN_IN_PLACE)" << std::endl;
595 getCurrentExecPath(buf, sizeof(buf)) ||
596 getExecPathFromProcfs(buf, sizeof(buf));
599 pathRemoveFile(buf, DIR_DELIM_CHAR);
600 std::string execpath(buf);
602 path_share = execpath + DIR_DELIM "..";
603 path_user = execpath + DIR_DELIM "..";
605 if (detectMSVCBuildDir(execpath)) {
606 path_share += DIR_DELIM "..";
607 path_user += DIR_DELIM "..";
610 errorstream << "Failed to get paths by executable location, "
611 "trying cwd" << std::endl;
613 if (!getCurrentWorkingDir(buf, sizeof(buf)))
614 FATAL_ERROR("Ran out of methods to get paths");
616 size_t cwdlen = strlen(buf);
617 if (cwdlen >= 1 && buf[cwdlen - 1] == DIR_DELIM_CHAR) {
622 if (cwdlen >= 4 && !strcmp(buf + cwdlen - 4, DIR_DELIM "bin"))
623 pathRemoveFile(buf, DIR_DELIM_CHAR);
625 std::string execpath(buf);
627 path_share = execpath;
628 path_user = execpath;
632 infostream << "Using system-wide paths (NOT RUN_IN_PLACE)" << std::endl;
634 if (!setSystemPaths())
635 errorstream << "Failed to get one or more system-wide path" << std::endl;
639 infostream << "Detected share path: " << path_share << std::endl;
640 infostream << "Detected user path: " << path_user << std::endl;
645 void setXorgClassHint(const video::SExposedVideoData &video_data,
646 const std::string &name)
649 if (video_data.OpenGLLinux.X11Display == NULL)
652 XClassHint *classhint = XAllocClassHint();
653 classhint->res_name = (char *)name.c_str();
654 classhint->res_class = (char *)name.c_str();
656 XSetClassHint((Display *)video_data.OpenGLLinux.X11Display,
657 video_data.OpenGLLinux.X11Window, classhint);
664 //// Video/Display Information (Client-only)
669 static irr::IrrlichtDevice *device;
671 void initIrrlicht(irr::IrrlichtDevice *device_)
676 v2u32 getWindowSize()
678 return device->getVideoDriver()->getScreenSize();
682 std::vector<core::vector3d<u32> > getSupportedVideoModes()
684 IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
685 sanity_check(nulldevice != NULL);
687 std::vector<core::vector3d<u32> > mlist;
688 video::IVideoModeList *modelist = nulldevice->getVideoModeList();
690 u32 num_modes = modelist->getVideoModeCount();
691 for (u32 i = 0; i != num_modes; i++) {
692 core::dimension2d<u32> mode_res = modelist->getVideoModeResolution(i);
693 s32 mode_depth = modelist->getVideoModeDepth(i);
694 mlist.push_back(core::vector3d<u32>(mode_res.Width, mode_res.Height, mode_depth));
702 std::vector<irr::video::E_DRIVER_TYPE> getSupportedVideoDrivers()
704 std::vector<irr::video::E_DRIVER_TYPE> drivers;
706 for (int i = 0; i != irr::video::EDT_COUNT; i++) {
707 if (irr::IrrlichtDevice::isDriverSupported((irr::video::E_DRIVER_TYPE)i))
708 drivers.push_back((irr::video::E_DRIVER_TYPE)i);
714 const char *getVideoDriverName(irr::video::E_DRIVER_TYPE type)
716 static const char *driver_ids[] = {
727 return driver_ids[type];
731 const char *getVideoDriverFriendlyName(irr::video::E_DRIVER_TYPE type)
733 static const char *driver_names[] = {
744 return driver_names[type];
750 static float calcDisplayDensity()
752 const char* current_display = getenv("DISPLAY");
754 if (current_display != NULL) {
755 Display * x11display = XOpenDisplay(current_display);
757 if (x11display != NULL) {
760 floor(DisplayHeight(x11display, 0) /
761 (DisplayHeightMM(x11display, 0) * 0.039370) + 0.5);
763 floor(DisplayWidth(x11display, 0) /
764 (DisplayWidthMM(x11display, 0) * 0.039370) +0.5);
766 XCloseDisplay(x11display);
768 return std::max(dpi_height,dpi_width) / 96.0;
772 /* return manually specified dpi */
773 return g_settings->getFloat("screen_dpi")/96.0;
777 float getDisplayDensity()
779 static float cached_display_density = calcDisplayDensity();
780 return cached_display_density;
785 float getDisplayDensity()
787 return g_settings->getFloat("screen_dpi")/96.0;
791 v2u32 getDisplaySize()
793 IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
795 core::dimension2d<u32> deskres = nulldevice->getVideoModeList()->getDesktopResolution();
796 nulldevice -> drop();
800 # endif // __ANDROID__
803 } //namespace porting