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"
62 Signal handler (grabs Ctrl-C on POSIX systems)
65 bool g_killed = false;
67 bool * signal_handler_killstatus(void)
72 #if !defined(_WIN32) // POSIX
75 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();*/
91 (void)signal(SIGINT, SIG_DFL);
95 void signal_handler_init(void)
97 (void)signal(SIGINT, sigint_handler);
103 BOOL WINAPI event_handler(DWORD sig)
108 case CTRL_CLOSE_EVENT:
109 case CTRL_LOGOFF_EVENT:
110 case CTRL_SHUTDOWN_EVENT:
112 if(g_killed == false)
114 dstream<<DTIME<<"INFO: event_handler(): "
115 <<"Ctrl+C, Close Event, Logoff Event or Shutdown Event, shutting down."<<std::endl;
116 // Comment out for less clutter when testing scripts
117 /*dstream<<DTIME<<"INFO: event_handler(): "
118 <<"Printing debug stacks"<<std::endl;
119 debug_stacks_print();*/
125 (void)signal(SIGINT, SIG_DFL);
129 case CTRL_BREAK_EVENT:
136 void signal_handler_init(void)
138 SetConsoleCtrlHandler( (PHANDLER_ROUTINE)event_handler,TRUE);
145 Multithreading support
147 int getNumberOfProcessors() {
148 #if defined(_SC_NPROCESSORS_ONLN)
150 return sysconf(_SC_NPROCESSORS_ONLN);
152 #elif defined(__FreeBSD__) || defined(__APPLE__)
154 unsigned int len, count;
156 return sysctlbyname("hw.ncpu", &count, &len, NULL, 0);
158 #elif defined(_GNU_SOURCE)
162 #elif defined(_WIN32)
165 GetSystemInfo(&sysinfo);
166 return sysinfo.dwNumberOfProcessors;
168 #elif defined(PTW32_VERSION) || defined(__hpux)
170 return pthread_num_processors_np();
181 bool threadBindToProcessor(threadid_t tid, int pnumber) {
184 HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, 0, tid);
188 bool success = SetThreadAffinityMask(hThread, 1 << pnumber) != 0;
190 CloseHandle(hThread);
193 #elif (defined(__FreeBSD__) && (__FreeBSD_version >= 702106)) \
194 || defined(__linux) || defined(linux)
199 CPU_SET(pnumber, &cpuset);
200 return pthread_setaffinity_np(tid, sizeof(cpuset), &cpuset) == 0;
202 #elif defined(__sun) || defined(sun)
204 return processor_bind(P_LWPID, MAKE_LWPID_PTHREAD(tid),
209 return bindprocessor(BINDTHREAD, (tid_t)tid, pnumber) == 0;
211 #elif defined(__hpux) || defined(hpux)
213 pthread_spu_t answer;
215 return pthread_processor_bind_np(PTHREAD_BIND_ADVISORY_NP,
216 &answer, pnumber, tid) == 0;
218 #elif defined(__APPLE__)
220 struct thread_affinity_policy tapol;
222 thread_port_t threadport = pthread_mach_thread_np(tid);
223 tapol.affinity_tag = pnumber + 1;
224 return thread_policy_set(threadport, THREAD_AFFINITY_POLICY,
225 (thread_policy_t)&tapol, THREAD_AFFINITY_POLICY_COUNT) == KERN_SUCCESS;
235 bool threadSetPriority(threadid_t tid, int prio) {
238 HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, 0, tid);
242 bool success = SetThreadPriority(hThread, prio) != 0;
244 CloseHandle(hThread);
249 struct sched_param sparam;
252 if (pthread_getschedparam(tid, &policy, &sparam) != 0)
255 int min = sched_get_priority_min(policy);
256 int max = sched_get_priority_max(policy);
258 sparam.sched_priority = min + prio * (max - min) / THREAD_PRIORITY_HIGHEST;
259 return pthread_setschedparam(tid, policy, &sparam) == 0;
269 // Default to RUN_IN_PLACE style relative paths
270 std::string path_share = "..";
271 std::string path_user = "..";
273 std::string getDataPath(const char *subpath)
275 return path_share + DIR_DELIM + subpath;
278 void pathRemoveFile(char *path, char delim)
280 // Remove filename and path delimiter
282 for(i = strlen(path)-1; i>=0; i--)
290 bool detectMSVCBuildDir(char *c_path)
292 std::string path(c_path);
293 const char *ends[] = {
298 return (removeStringEnd(path, ends) != "");
301 std::string get_sysinfo()
305 std::ostringstream oss;
307 ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
308 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
310 tmp = osvi.szCSDVersion;
311 std::replace(tmp.begin(), tmp.end(), ' ', '_');
313 oss << "Windows/" << osvi.dwMajorVersion << "."
314 << osvi.dwMinorVersion;
315 if(osvi.szCSDVersion[0])
322 if(IsWow64Process(GetCurrentProcess(), &is64) && is64)
323 oss << "x86_64"; // 32-bit app on 64-bit OS
330 struct utsname osinfo;
332 return std::string(osinfo.sysname) + "/"
333 + osinfo.release + " " + osinfo.machine;
337 void initializePaths()
341 Use relative paths if RUN_IN_PLACE
344 infostream<<"Using relative paths (RUN_IN_PLACE)"<<std::endl;
351 const DWORD buflen = 1000;
355 // Find path of executable and set path_share relative to it
356 len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen);
357 assert(len < buflen);
358 pathRemoveFile(buf, '\\');
360 if(detectMSVCBuildDir(buf)){
361 infostream<<"MSVC build directory detected"<<std::endl;
362 path_share = std::string(buf) + "\\..\\..";
363 path_user = std::string(buf) + "\\..\\..";
366 path_share = std::string(buf) + "\\..";
367 path_user = std::string(buf) + "\\..";
376 memset(buf, 0, BUFSIZ);
377 // Get path to executable
378 FATAL_ERROR_IF(readlink("/proc/self/exe", buf, BUFSIZ-1) == -1, "Failed to get cwd");
380 pathRemoveFile(buf, '/');
382 path_share = std::string(buf) + "/..";
383 path_user = std::string(buf) + "/..";
388 #elif defined(__APPLE__)
390 CFBundleRef main_bundle = CFBundleGetMainBundle();
391 CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
393 if (CFURLGetFileSystemRepresentation(resources_url, TRUE, (UInt8 *)path, PATH_MAX)) {
394 path_share = std::string(path);
395 path_user = std::string(path) + "/../User";
397 dstream << "WARNING: Could not determine bundle resource path" << std::endl;
399 CFRelease(resources_url);
404 #elif defined(__FreeBSD__)
408 size_t len = sizeof(buf);
412 mib[2] = KERN_PROC_PATHNAME;
414 FATAL_ERROR_IF(sysctl(mib, 4, buf, &len, NULL, 0) == -1, "");
416 pathRemoveFile(buf, '/');
418 path_share = std::string(buf) + "/..";
419 path_user = std::string(buf) + "/..";
423 //TODO: Get path of executable. This assumes working directory is bin/
424 dstream<<"WARNING: Relative path not properly supported on this platform"
427 /* scriptapi no longer allows paths that start with "..", so assuming that
428 the current working directory is bin/, strip off the last component. */
429 char *cwd = getcwd(NULL, 0);
430 pathRemoveFile(cwd, '/');
431 path_share = std::string(cwd);
432 path_user = std::string(cwd);
436 #else // RUN_IN_PLACE
439 Use platform-specific paths otherwise
442 infostream<<"Using system-wide paths (NOT RUN_IN_PLACE)"<<std::endl;
449 const DWORD buflen = 1000; // FIXME: Surely there is a better way to do this
453 // Find path of executable and set path_share relative to it
454 len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen);
455 FATAL_ERROR_IF(len >= buflen, "Overlow");
456 pathRemoveFile(buf, '\\');
459 path_share = std::string(buf) + "\\..";
461 // Use "C:\Documents and Settings\user\Application Data\<PROJECT_NAME>"
462 len = GetEnvironmentVariable("APPDATA", buf, buflen);
463 FATAL_ERROR_IF(len >= buflen, "Overlow");
464 path_user = std::string(buf) + DIR_DELIM + lowercase(PROJECT_NAME);
471 // Get path to executable
472 std::string bindir = "";
475 memset(buf, 0, BUFSIZ);
476 if (readlink("/proc/self/exe", buf, BUFSIZ-1) == -1) {
477 errorstream << "Unable to read bindir "<< std::endl;
479 FATAL_ERROR("Unable to read bindir");
482 pathRemoveFile(buf, '/');
487 // Find share directory from these.
488 // It is identified by containing the subdirectory "builtin".
489 std::list<std::string> trylist;
490 std::string static_sharedir = STATIC_SHAREDIR;
491 if(static_sharedir != "" && static_sharedir != ".")
492 trylist.push_back(static_sharedir);
494 bindir + DIR_DELIM + ".." + DIR_DELIM + "share" + DIR_DELIM + lowercase(PROJECT_NAME));
495 trylist.push_back(bindir + DIR_DELIM + "..");
497 trylist.push_back(path_user);
500 for(std::list<std::string>::const_iterator i = trylist.begin();
501 i != trylist.end(); i++)
503 const std::string &trypath = *i;
504 if(!fs::PathExists(trypath) || !fs::PathExists(trypath + DIR_DELIM + "builtin")){
505 dstream<<"WARNING: system-wide share not found at \""
506 <<trypath<<"\""<<std::endl;
509 // Warn if was not the first alternative
510 if(i != trylist.begin()){
511 dstream<<"WARNING: system-wide share found at \""
512 <<trypath<<"\""<<std::endl;
514 path_share = trypath;
518 path_user = std::string(getenv("HOME")) + DIR_DELIM + "." + lowercase(PROJECT_NAME);
524 #elif defined(__APPLE__)
526 CFBundleRef main_bundle = CFBundleGetMainBundle();
527 CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
529 if (CFURLGetFileSystemRepresentation(resources_url, TRUE, (UInt8 *)path, PATH_MAX)) {
530 path_share = std::string(path);
532 dstream << "WARNING: Could not determine bundle resource path" << std::endl;
534 CFRelease(resources_url);
536 path_user = std::string(getenv("HOME")) + "/Library/Application Support/" + lowercase(PROJECT_NAME);
538 #else // FreeBSD, and probably many other POSIX-like systems.
540 path_share = STATIC_SHAREDIR;
541 path_user = std::string(getenv("HOME")) + DIR_DELIM + "." + lowercase(PROJECT_NAME);
545 #endif // RUN_IN_PLACE
548 static irr::IrrlichtDevice *device;
550 void initIrrlicht(irr::IrrlichtDevice *device_)
555 void setXorgClassHint(const video::SExposedVideoData &video_data,
556 const std::string &name)
559 if (video_data.OpenGLLinux.X11Display == NULL)
562 XClassHint *classhint = XAllocClassHint();
563 classhint->res_name = (char *)name.c_str();
564 classhint->res_class = (char *)name.c_str();
566 XSetClassHint((Display *)video_data.OpenGLLinux.X11Display,
567 video_data.OpenGLLinux.X11Window, classhint);
574 v2u32 getWindowSize()
576 return device->getVideoDriver()->getScreenSize();
580 std::vector<core::vector3d<u32> > getSupportedVideoModes()
582 IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
583 sanity_check(nulldevice != NULL);
585 std::vector<core::vector3d<u32> > mlist;
586 video::IVideoModeList *modelist = nulldevice->getVideoModeList();
588 u32 num_modes = modelist->getVideoModeCount();
589 for (u32 i = 0; i != num_modes; i++) {
590 core::dimension2d<u32> mode_res = modelist->getVideoModeResolution(i);
591 s32 mode_depth = modelist->getVideoModeDepth(i);
592 mlist.push_back(core::vector3d<u32>(mode_res.Width, mode_res.Height, mode_depth));
600 std::vector<irr::video::E_DRIVER_TYPE> getSupportedVideoDrivers()
602 std::vector<irr::video::E_DRIVER_TYPE> drivers;
604 for (int i = 0; i != irr::video::EDT_COUNT; i++) {
605 if (irr::IrrlichtDevice::isDriverSupported((irr::video::E_DRIVER_TYPE)i))
606 drivers.push_back((irr::video::E_DRIVER_TYPE)i);
612 const char *getVideoDriverName(irr::video::E_DRIVER_TYPE type)
614 static const char *driver_ids[] = {
625 return driver_ids[type];
629 const char *getVideoDriverFriendlyName(irr::video::E_DRIVER_TYPE type)
631 static const char *driver_names[] = {
642 return driver_names[type];
649 static float calcDisplayDensity()
651 const char* current_display = getenv("DISPLAY");
653 if (current_display != NULL) {
654 Display * x11display = XOpenDisplay(current_display);
656 if (x11display != NULL) {
659 floor(DisplayHeight(x11display, 0) /
660 (DisplayHeightMM(x11display, 0) * 0.039370) + 0.5);
662 floor(DisplayWidth(x11display, 0) /
663 (DisplayWidthMM(x11display, 0) * 0.039370) +0.5);
665 XCloseDisplay(x11display);
667 return std::max(dpi_height,dpi_width) / 96.0;
671 /* return manually specified dpi */
672 return g_settings->getFloat("screen_dpi")/96.0;
676 float getDisplayDensity()
678 static float cached_display_density = calcDisplayDensity();
679 return cached_display_density;
684 float getDisplayDensity()
686 return g_settings->getFloat("screen_dpi")/96.0;
690 v2u32 getDisplaySize()
692 IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
694 core::dimension2d<u32> deskres = nulldevice->getVideoModeList()->getDesktopResolution();
695 nulldevice -> drop();
702 } //namespace porting