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(__APPLE__)
29 #include <mach-o/dyld.h>
30 #include "CoreFoundation/CoreFoundation.h"
31 #elif defined(__FreeBSD__)
32 #include <sys/types.h>
33 #include <sys/sysctl.h>
39 #include <sys/utsname.h>
46 #include "util/string.h"
55 Signal handler (grabs Ctrl-C on POSIX systems)
58 bool g_killed = false;
60 bool * signal_handler_killstatus(void)
65 #if !defined(_WIN32) // POSIX
68 void sigint_handler(int sig)
72 dstream<<DTIME<<"INFO: sigint_handler(): "
73 <<"Ctrl-C pressed, shutting down."<<std::endl;
75 // Comment out for less clutter when testing scripts
76 /*dstream<<DTIME<<"INFO: sigint_handler(): "
77 <<"Printing debug stacks"<<std::endl;
78 debug_stacks_print();*/
84 (void)signal(SIGINT, SIG_DFL);
88 void signal_handler_init(void)
90 (void)signal(SIGINT, sigint_handler);
96 BOOL WINAPI event_handler(DWORD sig)
101 case CTRL_CLOSE_EVENT:
102 case CTRL_LOGOFF_EVENT:
103 case CTRL_SHUTDOWN_EVENT:
105 if(g_killed == false)
107 dstream<<DTIME<<"INFO: event_handler(): "
108 <<"Ctrl+C, Close Event, Logoff Event or Shutdown Event, shutting down."<<std::endl;
109 // Comment out for less clutter when testing scripts
110 /*dstream<<DTIME<<"INFO: event_handler(): "
111 <<"Printing debug stacks"<<std::endl;
112 debug_stacks_print();*/
118 (void)signal(SIGINT, SIG_DFL);
122 case CTRL_BREAK_EVENT:
129 void signal_handler_init(void)
131 SetConsoleCtrlHandler( (PHANDLER_ROUTINE)event_handler,TRUE);
138 Multithreading support
140 int getNumberOfProcessors() {
141 #if defined(_SC_NPROCESSORS_ONLN)
143 return sysconf(_SC_NPROCESSORS_ONLN);
145 #elif defined(__FreeBSD__) || defined(__APPLE__)
147 unsigned int len, count;
149 return sysctlbyname("hw.ncpu", &count, &len, NULL, 0);
151 #elif defined(_GNU_SOURCE)
155 #elif defined(_WIN32)
158 GetSystemInfo(&sysinfo);
159 return sysinfo.dwNumberOfProcessors;
161 #elif defined(PTW32_VERSION) || defined(__hpux)
163 return pthread_num_processors_np();
173 bool threadBindToProcessor(threadid_t tid, int pnumber) {
176 HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, 0, tid);
180 bool success = SetThreadAffinityMask(hThread, 1 << pnumber) != 0;
182 CloseHandle(hThread);
185 #elif (defined(__FreeBSD__) && (__FreeBSD_version >= 702106)) \
186 || defined(__linux) || defined(linux)
191 CPU_SET(pnumber, &cpuset);
192 return pthread_setaffinity_np(tid, sizeof(cpuset), &cpuset) == 0;
194 #elif defined(__sun) || defined(sun)
196 return processor_bind(P_LWPID, MAKE_LWPID_PTHREAD(tid),
201 return bindprocessor(BINDTHREAD, (tid_t)tid, pnumber) == 0;
203 #elif defined(__hpux) || defined(hpux)
205 pthread_spu_t answer;
207 return pthread_processor_bind_np(PTHREAD_BIND_ADVISORY_NP,
208 &answer, pnumber, tid) == 0;
210 #elif defined(__APPLE__)
212 struct thread_affinity_policy tapol;
214 thread_port_t threadport = pthread_mach_thread_np(tid);
215 tapol.affinity_tag = pnumber + 1;
216 return thread_policy_set(threadport, THREAD_AFFINITY_POLICY,
217 (thread_policy_t)&tapol, THREAD_AFFINITY_POLICY_COUNT) == KERN_SUCCESS;
227 bool threadSetPriority(threadid_t tid, int prio) {
230 HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, 0, tid);
234 bool success = SetThreadPriority(hThread, prio) != 0;
236 CloseHandle(hThread);
241 struct sched_param sparam;
244 if (pthread_getschedparam(tid, &policy, &sparam) != 0)
247 int min = sched_get_priority_min(policy);
248 int max = sched_get_priority_max(policy);
250 sparam.sched_priority = min + prio * (max - min) / THREAD_PRIORITY_HIGHEST;
251 return pthread_setschedparam(tid, policy, &sparam) == 0;
261 // Default to RUN_IN_PLACE style relative paths
262 std::string path_share = "..";
263 std::string path_user = "..";
265 std::string getDataPath(const char *subpath)
267 return path_share + DIR_DELIM + subpath;
270 void pathRemoveFile(char *path, char delim)
272 // Remove filename and path delimiter
274 for(i = strlen(path)-1; i>=0; i--)
282 bool detectMSVCBuildDir(char *c_path)
284 std::string path(c_path);
285 const char *ends[] = {"bin\\Release", "bin\\Build", NULL};
286 return (removeStringEnd(path, ends) != "");
289 std::string get_sysinfo()
293 std::ostringstream oss;
295 ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
296 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
298 tmp = osvi.szCSDVersion;
299 std::replace(tmp.begin(), tmp.end(), ' ', '_');
301 oss << "Windows/" << osvi.dwMajorVersion << "."
302 << osvi.dwMinorVersion;
303 if(osvi.szCSDVersion[0])
310 if(IsWow64Process(GetCurrentProcess(), &is64) && is64)
311 oss << "x86_64"; // 32-bit app on 64-bit OS
318 struct utsname osinfo;
320 return std::string(osinfo.sysname) + "/"
321 + osinfo.release + " " + osinfo.machine;
325 void initializePaths()
329 Use relative paths if RUN_IN_PLACE
332 infostream<<"Using relative paths (RUN_IN_PLACE)"<<std::endl;
339 const DWORD buflen = 1000;
343 // Find path of executable and set path_share relative to it
344 len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen);
345 assert(len < buflen);
346 pathRemoveFile(buf, '\\');
348 if(detectMSVCBuildDir(buf)){
349 infostream<<"MSVC build directory detected"<<std::endl;
350 path_share = std::string(buf) + "\\..\\..";
351 path_user = std::string(buf) + "\\..\\..";
354 path_share = std::string(buf) + "\\..";
355 path_user = std::string(buf) + "\\..";
364 memset(buf, 0, BUFSIZ);
365 // Get path to executable
366 assert(readlink("/proc/self/exe", buf, BUFSIZ-1) != -1);
368 pathRemoveFile(buf, '/');
370 path_share = std::string(buf) + "/..";
371 path_user = std::string(buf) + "/..";
376 #elif defined(__APPLE__)
378 //https://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/dyld.3.html
379 //TODO: Test this code
381 uint32_t len = sizeof(buf);
382 assert(_NSGetExecutablePath(buf, &len) != -1);
384 pathRemoveFile(buf, '/');
386 path_share = std::string(buf) + "/..";
387 path_user = std::string(buf) + "/..";
392 #elif defined(__FreeBSD__)
396 size_t len = sizeof(buf);
400 mib[2] = KERN_PROC_PATHNAME;
402 assert(sysctl(mib, 4, buf, &len, NULL, 0) != -1);
404 pathRemoveFile(buf, '/');
406 path_share = std::string(buf) + "/..";
407 path_user = std::string(buf) + "/..";
411 //TODO: Get path of executable. This assumes working directory is bin/
412 dstream<<"WARNING: Relative path not properly supported on this platform"
415 /* scriptapi no longer allows paths that start with "..", so assuming that
416 the current working directory is bin/, strip off the last component. */
417 char *cwd = getcwd(NULL, 0);
418 pathRemoveFile(cwd, '/');
419 path_share = std::string(cwd);
420 path_user = std::string(cwd);
424 #else // RUN_IN_PLACE
427 Use platform-specific paths otherwise
430 infostream<<"Using system-wide paths (NOT RUN_IN_PLACE)"<<std::endl;
437 const DWORD buflen = 1000;
441 // Find path of executable and set path_share relative to it
442 len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen);
443 assert(len < buflen);
444 pathRemoveFile(buf, '\\');
447 path_share = std::string(buf) + "\\..";
449 // Use "C:\Documents and Settings\user\Application Data\<PROJECT_NAME>"
450 len = GetEnvironmentVariable("APPDATA", buf, buflen);
451 assert(len < buflen);
452 path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME;
459 // Get path to executable
460 std::string bindir = "";
463 memset(buf, 0, BUFSIZ);
464 assert(readlink("/proc/self/exe", buf, BUFSIZ-1) != -1);
465 pathRemoveFile(buf, '/');
469 // Find share directory from these.
470 // It is identified by containing the subdirectory "builtin".
471 std::list<std::string> trylist;
472 std::string static_sharedir = STATIC_SHAREDIR;
473 if(static_sharedir != "" && static_sharedir != ".")
474 trylist.push_back(static_sharedir);
476 bindir + DIR_DELIM + ".." + DIR_DELIM + "share" + DIR_DELIM + PROJECT_NAME);
477 trylist.push_back(bindir + DIR_DELIM + "..");
479 for(std::list<std::string>::const_iterator i = trylist.begin();
480 i != trylist.end(); i++)
482 const std::string &trypath = *i;
483 if(!fs::PathExists(trypath) || !fs::PathExists(trypath + DIR_DELIM + "builtin")){
484 dstream<<"WARNING: system-wide share not found at \""
485 <<trypath<<"\""<<std::endl;
488 // Warn if was not the first alternative
489 if(i != trylist.begin()){
490 dstream<<"WARNING: system-wide share found at \""
491 <<trypath<<"\""<<std::endl;
493 path_share = trypath;
497 path_user = std::string(getenv("HOME")) + DIR_DELIM + "." + PROJECT_NAME;
502 #elif defined(__APPLE__)
505 // http://stackoverflow.com/questions/516200/relative-paths-not-working-in-xcode-c
506 CFBundleRef main_bundle = CFBundleGetMainBundle();
507 CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
509 if(CFURLGetFileSystemRepresentation(resources_url, TRUE, (UInt8 *)path, PATH_MAX))
511 dstream<<"Bundle resource path: "<<path<<std::endl;
513 path_share = std::string(path) + DIR_DELIM + "share";
518 dstream<<"WARNING: Could not determine bundle resource path"<<std::endl;
520 CFRelease(resources_url);
522 path_user = std::string(getenv("HOME")) + "/Library/Application Support/" + PROJECT_NAME;
524 #else // FreeBSD, and probably many other POSIX-like systems.
526 path_share = STATIC_SHAREDIR;
527 path_user = std::string(getenv("HOME")) + DIR_DELIM + "." + PROJECT_NAME;
531 #endif // RUN_IN_PLACE
534 static irr::IrrlichtDevice* device;
536 void initIrrlicht(irr::IrrlichtDevice * _device) {
541 v2u32 getWindowSize() {
542 return device->getVideoDriver()->getScreenSize();
546 float getDisplayDensity() {
547 float gui_scaling = g_settings->getFloat("gui_scaling");
548 // using Y here feels like a bug, this needs to be discussed later!
549 if (getWindowSize().Y <= 800) {
550 return (2.0/3.0) * gui_scaling;
552 if (getWindowSize().Y <= 1280) {
553 return 1.0 * gui_scaling;
556 return (4.0/3.0) * gui_scaling;
559 v2u32 getDisplaySize() {
560 IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
562 core::dimension2d<u32> deskres = nulldevice->getVideoModeList()->getDesktopResolution();
563 nulldevice -> drop();
569 } //namespace porting