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>
39 #if !defined(_WIN32) && !defined(__APPLE__) && \
40 !defined(__ANDROID__) && !defined(SERVER)
46 #include <X11/Xutil.h>
53 #include "util/string.h"
61 Signal handler (grabs Ctrl-C on POSIX systems)
64 bool g_killed = false;
66 bool * signal_handler_killstatus(void)
71 #if !defined(_WIN32) // POSIX
74 void sigint_handler(int sig)
78 dstream<<DTIME<<"INFO: sigint_handler(): "
79 <<"Ctrl-C pressed, shutting down."<<std::endl;
81 // Comment out for less clutter when testing scripts
82 /*dstream<<DTIME<<"INFO: sigint_handler(): "
83 <<"Printing debug stacks"<<std::endl;
84 debug_stacks_print();*/
90 (void)signal(SIGINT, SIG_DFL);
94 void signal_handler_init(void)
96 (void)signal(SIGINT, sigint_handler);
102 BOOL WINAPI event_handler(DWORD sig)
107 case CTRL_CLOSE_EVENT:
108 case CTRL_LOGOFF_EVENT:
109 case CTRL_SHUTDOWN_EVENT:
111 if(g_killed == false)
113 dstream<<DTIME<<"INFO: event_handler(): "
114 <<"Ctrl+C, Close Event, Logoff Event or Shutdown Event, shutting down."<<std::endl;
115 // Comment out for less clutter when testing scripts
116 /*dstream<<DTIME<<"INFO: event_handler(): "
117 <<"Printing debug stacks"<<std::endl;
118 debug_stacks_print();*/
124 (void)signal(SIGINT, SIG_DFL);
128 case CTRL_BREAK_EVENT:
135 void signal_handler_init(void)
137 SetConsoleCtrlHandler( (PHANDLER_ROUTINE)event_handler,TRUE);
144 Multithreading support
146 int getNumberOfProcessors() {
147 #if defined(_SC_NPROCESSORS_ONLN)
149 return sysconf(_SC_NPROCESSORS_ONLN);
151 #elif defined(__FreeBSD__) || defined(__APPLE__)
153 unsigned int len, count;
155 return sysctlbyname("hw.ncpu", &count, &len, NULL, 0);
157 #elif defined(_GNU_SOURCE)
161 #elif defined(_WIN32)
164 GetSystemInfo(&sysinfo);
165 return sysinfo.dwNumberOfProcessors;
167 #elif defined(PTW32_VERSION) || defined(__hpux)
169 return pthread_num_processors_np();
180 bool threadBindToProcessor(threadid_t tid, int pnumber) {
183 HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, 0, tid);
187 bool success = SetThreadAffinityMask(hThread, 1 << pnumber) != 0;
189 CloseHandle(hThread);
192 #elif (defined(__FreeBSD__) && (__FreeBSD_version >= 702106)) \
193 || defined(__linux) || defined(linux)
198 CPU_SET(pnumber, &cpuset);
199 return pthread_setaffinity_np(tid, sizeof(cpuset), &cpuset) == 0;
201 #elif defined(__sun) || defined(sun)
203 return processor_bind(P_LWPID, MAKE_LWPID_PTHREAD(tid),
208 return bindprocessor(BINDTHREAD, (tid_t)tid, pnumber) == 0;
210 #elif defined(__hpux) || defined(hpux)
212 pthread_spu_t answer;
214 return pthread_processor_bind_np(PTHREAD_BIND_ADVISORY_NP,
215 &answer, pnumber, tid) == 0;
217 #elif defined(__APPLE__)
219 struct thread_affinity_policy tapol;
221 thread_port_t threadport = pthread_mach_thread_np(tid);
222 tapol.affinity_tag = pnumber + 1;
223 return thread_policy_set(threadport, THREAD_AFFINITY_POLICY,
224 (thread_policy_t)&tapol, THREAD_AFFINITY_POLICY_COUNT) == KERN_SUCCESS;
234 bool threadSetPriority(threadid_t tid, int prio) {
237 HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, 0, tid);
241 bool success = SetThreadPriority(hThread, prio) != 0;
243 CloseHandle(hThread);
248 struct sched_param sparam;
251 if (pthread_getschedparam(tid, &policy, &sparam) != 0)
254 int min = sched_get_priority_min(policy);
255 int max = sched_get_priority_max(policy);
257 sparam.sched_priority = min + prio * (max - min) / THREAD_PRIORITY_HIGHEST;
258 return pthread_setschedparam(tid, policy, &sparam) == 0;
268 // Default to RUN_IN_PLACE style relative paths
269 std::string path_share = "..";
270 std::string path_user = "..";
272 std::string getDataPath(const char *subpath)
274 return path_share + DIR_DELIM + subpath;
277 void pathRemoveFile(char *path, char delim)
279 // Remove filename and path delimiter
281 for(i = strlen(path)-1; i>=0; i--)
289 bool detectMSVCBuildDir(char *c_path)
291 std::string path(c_path);
292 const char *ends[] = {
297 return (removeStringEnd(path, ends) != "");
300 std::string get_sysinfo()
304 std::ostringstream oss;
306 ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
307 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
309 tmp = osvi.szCSDVersion;
310 std::replace(tmp.begin(), tmp.end(), ' ', '_');
312 oss << "Windows/" << osvi.dwMajorVersion << "."
313 << osvi.dwMinorVersion;
314 if(osvi.szCSDVersion[0])
321 if(IsWow64Process(GetCurrentProcess(), &is64) && is64)
322 oss << "x86_64"; // 32-bit app on 64-bit OS
329 struct utsname osinfo;
331 return std::string(osinfo.sysname) + "/"
332 + osinfo.release + " " + osinfo.machine;
336 void initializePaths()
340 Use relative paths if RUN_IN_PLACE
343 infostream<<"Using relative paths (RUN_IN_PLACE)"<<std::endl;
350 const DWORD buflen = 1000;
354 // Find path of executable and set path_share relative to it
355 len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen);
356 assert(len < buflen);
357 pathRemoveFile(buf, '\\');
359 if(detectMSVCBuildDir(buf)){
360 infostream<<"MSVC build directory detected"<<std::endl;
361 path_share = std::string(buf) + "\\..\\..";
362 path_user = std::string(buf) + "\\..\\..";
365 path_share = std::string(buf) + "\\..";
366 path_user = std::string(buf) + "\\..";
372 #elif defined(linux) || defined(__linux)
375 memset(buf, 0, BUFSIZ);
376 // Get path to executable
377 FATAL_ERROR_IF(readlink("/proc/self/exe", buf, BUFSIZ-1) == -1, "Failed to get cwd");
379 pathRemoveFile(buf, '/');
381 path_share = std::string(buf) + "/..";
382 path_user = std::string(buf) + "/..";
387 #elif defined(__APPLE__)
389 CFBundleRef main_bundle = CFBundleGetMainBundle();
390 CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
392 if (CFURLGetFileSystemRepresentation(resources_url, TRUE, (UInt8 *)path, PATH_MAX)) {
393 path_share = std::string(path);
394 path_user = std::string(path) + "/../User";
396 dstream << "WARNING: Could not determine bundle resource path" << std::endl;
398 CFRelease(resources_url);
403 #elif defined(__FreeBSD__)
407 size_t len = sizeof(buf);
411 mib[2] = KERN_PROC_PATHNAME;
413 FATAL_ERROR_IF(sysctl(mib, 4, buf, &len, NULL, 0) == -1, "");
415 pathRemoveFile(buf, '/');
417 path_share = std::string(buf) + "/..";
418 path_user = std::string(buf) + "/..";
422 //TODO: Get path of executable. This assumes working directory is bin/
423 dstream<<"WARNING: Relative path not properly supported on this platform"
426 /* scriptapi no longer allows paths that start with "..", so assuming that
427 the current working directory is bin/, strip off the last component. */
428 char *cwd = getcwd(NULL, 0);
429 pathRemoveFile(cwd, '/');
430 path_share = std::string(cwd);
431 path_user = std::string(cwd);
435 #else // RUN_IN_PLACE
438 Use platform-specific paths otherwise
441 infostream<<"Using system-wide paths (NOT RUN_IN_PLACE)"<<std::endl;
448 const DWORD buflen = 1000; // FIXME: Surely there is a better way to do this
452 // Find path of executable and set path_share relative to it
453 len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen);
454 FATAL_ERROR_IF(len >= buflen, "Overlow");
455 pathRemoveFile(buf, '\\');
458 path_share = std::string(buf) + "\\..";
460 // Use "C:\Documents and Settings\user\Application Data\<PROJECT_NAME>"
461 len = GetEnvironmentVariable("APPDATA", buf, buflen);
462 FATAL_ERROR_IF(len >= buflen, "Overlow");
463 path_user = std::string(buf) + DIR_DELIM + lowercase(PROJECT_NAME);
468 #elif defined(linux) || defined(__linux)
470 // Get path to executable
471 std::string bindir = "";
474 memset(buf, 0, BUFSIZ);
475 if (readlink("/proc/self/exe", buf, BUFSIZ-1) == -1) {
476 errorstream << "Unable to read bindir "<< std::endl;
478 FATAL_ERROR("Unable to read bindir");
481 pathRemoveFile(buf, '/');
486 // Find share directory from these.
487 // It is identified by containing the subdirectory "builtin".
488 std::list<std::string> trylist;
489 std::string static_sharedir = STATIC_SHAREDIR;
490 if(static_sharedir != "" && static_sharedir != ".")
491 trylist.push_back(static_sharedir);
493 bindir + DIR_DELIM + ".." + DIR_DELIM + "share" + DIR_DELIM + lowercase(PROJECT_NAME));
494 trylist.push_back(bindir + DIR_DELIM + "..");
496 trylist.push_back(path_user);
499 for(std::list<std::string>::const_iterator i = trylist.begin();
500 i != trylist.end(); i++)
502 const std::string &trypath = *i;
503 if(!fs::PathExists(trypath) || !fs::PathExists(trypath + DIR_DELIM + "builtin")){
504 dstream<<"WARNING: system-wide share not found at \""
505 <<trypath<<"\""<<std::endl;
508 // Warn if was not the first alternative
509 if(i != trylist.begin()){
510 dstream<<"WARNING: system-wide share found at \""
511 <<trypath<<"\""<<std::endl;
513 path_share = trypath;
517 path_user = std::string(getenv("HOME")) + DIR_DELIM + "." + lowercase(PROJECT_NAME);
523 #elif defined(__APPLE__)
525 CFBundleRef main_bundle = CFBundleGetMainBundle();
526 CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
528 if (CFURLGetFileSystemRepresentation(resources_url, TRUE, (UInt8 *)path, PATH_MAX)) {
529 path_share = std::string(path);
531 dstream << "WARNING: Could not determine bundle resource path" << std::endl;
533 CFRelease(resources_url);
535 path_user = std::string(getenv("HOME")) + "/Library/Application Support/" + lowercase(PROJECT_NAME);
537 #else // FreeBSD, and probably many other POSIX-like systems.
539 path_share = STATIC_SHAREDIR;
540 path_user = std::string(getenv("HOME")) + DIR_DELIM + "." + lowercase(PROJECT_NAME);
544 #endif // RUN_IN_PLACE
547 static irr::IrrlichtDevice *device;
549 void initIrrlicht(irr::IrrlichtDevice *device_)
554 void setXorgClassHint(const video::SExposedVideoData &video_data,
555 const std::string &name)
558 if (video_data.OpenGLLinux.X11Display == NULL)
561 XClassHint *classhint = XAllocClassHint();
562 classhint->res_name = (char *)name.c_str();
563 classhint->res_class = (char *)name.c_str();
565 XSetClassHint((Display *)video_data.OpenGLLinux.X11Display,
566 video_data.OpenGLLinux.X11Window, classhint);
573 v2u32 getWindowSize()
575 return device->getVideoDriver()->getScreenSize();
579 std::vector<core::vector3d<u32> > getSupportedVideoModes()
581 IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
582 sanity_check(nulldevice != NULL);
584 std::vector<core::vector3d<u32> > mlist;
585 video::IVideoModeList *modelist = nulldevice->getVideoModeList();
587 u32 num_modes = modelist->getVideoModeCount();
588 for (u32 i = 0; i != num_modes; i++) {
589 core::dimension2d<u32> mode_res = modelist->getVideoModeResolution(i);
590 s32 mode_depth = modelist->getVideoModeDepth(i);
591 mlist.push_back(core::vector3d<u32>(mode_res.Width, mode_res.Height, mode_depth));
599 std::vector<irr::video::E_DRIVER_TYPE> getSupportedVideoDrivers()
601 std::vector<irr::video::E_DRIVER_TYPE> drivers;
603 for (int i = 0; i != irr::video::EDT_COUNT; i++) {
604 if (irr::IrrlichtDevice::isDriverSupported((irr::video::E_DRIVER_TYPE)i))
605 drivers.push_back((irr::video::E_DRIVER_TYPE)i);
611 const char *getVideoDriverName(irr::video::E_DRIVER_TYPE type)
613 static const char *driver_ids[] = {
624 return driver_ids[type];
628 const char *getVideoDriverFriendlyName(irr::video::E_DRIVER_TYPE type)
630 static const char *driver_names[] = {
641 return driver_names[type];
648 static float calcDisplayDensity()
650 const char* current_display = getenv("DISPLAY");
652 if (current_display != NULL) {
653 Display * x11display = XOpenDisplay(current_display);
655 if (x11display != NULL) {
658 floor(DisplayHeight(x11display, 0) /
659 (DisplayHeightMM(x11display, 0) * 0.039370) + 0.5);
661 floor(DisplayWidth(x11display, 0) /
662 (DisplayWidthMM(x11display, 0) * 0.039370) +0.5);
664 XCloseDisplay(x11display);
666 return std::max(dpi_height,dpi_width) / 96.0;
670 /* return manually specified dpi */
671 return g_settings->getFloat("screen_dpi")/96.0;
675 float getDisplayDensity()
677 static float cached_display_density = calcDisplayDensity();
678 return cached_display_density;
683 float getDisplayDensity()
685 return g_settings->getFloat("screen_dpi")/96.0;
689 v2u32 getDisplaySize()
691 IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
693 core::dimension2d<u32> deskres = nulldevice->getVideoModeList()->getDesktopResolution();
694 nulldevice -> drop();
701 } //namespace porting