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>
43 #include "util/string.h"
52 Signal handler (grabs Ctrl-C on POSIX systems)
55 bool g_killed = false;
57 bool * signal_handler_killstatus(void)
62 #if !defined(_WIN32) // POSIX
65 void sigint_handler(int sig)
69 dstream<<DTIME<<"INFO: sigint_handler(): "
70 <<"Ctrl-C pressed, shutting down."<<std::endl;
72 // Comment out for less clutter when testing scripts
73 /*dstream<<DTIME<<"INFO: sigint_handler(): "
74 <<"Printing debug stacks"<<std::endl;
75 debug_stacks_print();*/
81 (void)signal(SIGINT, SIG_DFL);
85 void signal_handler_init(void)
87 (void)signal(SIGINT, sigint_handler);
93 BOOL WINAPI event_handler(DWORD sig)
98 case CTRL_CLOSE_EVENT:
99 case CTRL_LOGOFF_EVENT:
100 case CTRL_SHUTDOWN_EVENT:
102 if(g_killed == false)
104 dstream<<DTIME<<"INFO: event_handler(): "
105 <<"Ctrl+C, Close Event, Logoff Event or Shutdown Event, shutting down."<<std::endl;
106 // Comment out for less clutter when testing scripts
107 /*dstream<<DTIME<<"INFO: event_handler(): "
108 <<"Printing debug stacks"<<std::endl;
109 debug_stacks_print();*/
115 (void)signal(SIGINT, SIG_DFL);
119 case CTRL_BREAK_EVENT:
126 void signal_handler_init(void)
128 SetConsoleCtrlHandler( (PHANDLER_ROUTINE)event_handler,TRUE);
135 Multithreading support
137 int getNumberOfProcessors() {
138 #if defined(_SC_NPROCESSORS_ONLN)
140 return sysconf(_SC_NPROCESSORS_ONLN);
142 #elif defined(__FreeBSD__) || defined(__APPLE__)
144 unsigned int len, count;
146 return sysctlbyname("hw.ncpu", &count, &len, NULL, 0);
148 #elif defined(_GNU_SOURCE)
152 #elif defined(_WIN32)
155 GetSystemInfo(&sysinfo);
156 return sysinfo.dwNumberOfProcessors;
158 #elif defined(PTW32_VERSION) || defined(__hpux)
160 return pthread_num_processors_np();
171 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) {
228 HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, 0, tid);
232 bool success = SetThreadPriority(hThread, prio) != 0;
234 CloseHandle(hThread);
239 struct sched_param sparam;
242 if (pthread_getschedparam(tid, &policy, &sparam) != 0)
245 int min = sched_get_priority_min(policy);
246 int max = sched_get_priority_max(policy);
248 sparam.sched_priority = min + prio * (max - min) / THREAD_PRIORITY_HIGHEST;
249 return pthread_setschedparam(tid, policy, &sparam) == 0;
259 // Default to RUN_IN_PLACE style relative paths
260 std::string path_share = "..";
261 std::string path_user = "..";
263 std::string getDataPath(const char *subpath)
265 return path_share + DIR_DELIM + subpath;
268 void pathRemoveFile(char *path, char delim)
270 // Remove filename and path delimiter
272 for(i = strlen(path)-1; i>=0; i--)
280 bool detectMSVCBuildDir(char *c_path)
282 std::string path(c_path);
283 const char *ends[] = {"bin\\Release", "bin\\Build", NULL};
284 return (removeStringEnd(path, ends) != "");
287 std::string get_sysinfo()
291 std::ostringstream oss;
293 ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
294 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
296 tmp = osvi.szCSDVersion;
297 std::replace(tmp.begin(), tmp.end(), ' ', '_');
299 oss << "Windows/" << osvi.dwMajorVersion << "."
300 << osvi.dwMinorVersion;
301 if(osvi.szCSDVersion[0])
308 if(IsWow64Process(GetCurrentProcess(), &is64) && is64)
309 oss << "x86_64"; // 32-bit app on 64-bit OS
316 struct utsname osinfo;
318 return std::string(osinfo.sysname) + "/"
319 + osinfo.release + " " + osinfo.machine;
323 void initializePaths()
327 Use relative paths if RUN_IN_PLACE
330 infostream<<"Using relative paths (RUN_IN_PLACE)"<<std::endl;
337 const DWORD buflen = 1000;
341 // Find path of executable and set path_share relative to it
342 len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen);
343 assert(len < buflen);
344 pathRemoveFile(buf, '\\');
346 if(detectMSVCBuildDir(buf)){
347 infostream<<"MSVC build directory detected"<<std::endl;
348 path_share = std::string(buf) + "\\..\\..";
349 path_user = std::string(buf) + "\\..\\..";
352 path_share = std::string(buf) + "\\..";
353 path_user = std::string(buf) + "\\..";
362 memset(buf, 0, BUFSIZ);
363 // Get path to executable
364 assert(readlink("/proc/self/exe", buf, BUFSIZ-1) != -1);
366 pathRemoveFile(buf, '/');
368 path_share = std::string(buf) + "/..";
369 path_user = std::string(buf) + "/..";
374 #elif defined(__APPLE__)
376 //https://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/dyld.3.html
377 //TODO: Test this code
379 uint32_t len = sizeof(buf);
380 assert(_NSGetExecutablePath(buf, &len) != -1);
382 pathRemoveFile(buf, '/');
384 path_share = std::string(buf) + "/..";
385 path_user = std::string(buf) + "/..";
390 #elif defined(__FreeBSD__)
394 size_t len = sizeof(buf);
398 mib[2] = KERN_PROC_PATHNAME;
400 assert(sysctl(mib, 4, buf, &len, NULL, 0) != -1);
402 pathRemoveFile(buf, '/');
404 path_share = std::string(buf) + "/..";
405 path_user = std::string(buf) + "/..";
409 //TODO: Get path of executable. This assumes working directory is bin/
410 dstream<<"WARNING: Relative path not properly supported on this platform"
413 /* scriptapi no longer allows paths that start with "..", so assuming that
414 the current working directory is bin/, strip off the last component. */
415 char *cwd = getcwd(NULL, 0);
416 pathRemoveFile(cwd, '/');
417 path_share = std::string(cwd);
418 path_user = std::string(cwd);
422 #else // RUN_IN_PLACE
425 Use platform-specific paths otherwise
428 infostream<<"Using system-wide paths (NOT RUN_IN_PLACE)"<<std::endl;
435 const DWORD buflen = 1000;
439 // Find path of executable and set path_share relative to it
440 len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen);
441 assert(len < buflen);
442 pathRemoveFile(buf, '\\');
445 path_share = std::string(buf) + "\\..";
447 // Use "C:\Documents and Settings\user\Application Data\<PROJECT_NAME>"
448 len = GetEnvironmentVariable("APPDATA", buf, buflen);
449 assert(len < buflen);
450 path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME;
457 // Get path to executable
458 std::string bindir = "";
461 memset(buf, 0, BUFSIZ);
462 if (readlink("/proc/self/exe", buf, BUFSIZ-1) == -1) {
463 errorstream << "Unable to read bindir "<< std::endl;
465 assert("Unable to read bindir" == 0);
468 pathRemoveFile(buf, '/');
473 // Find share directory from these.
474 // It is identified by containing the subdirectory "builtin".
475 std::list<std::string> trylist;
476 std::string static_sharedir = STATIC_SHAREDIR;
477 if(static_sharedir != "" && static_sharedir != ".")
478 trylist.push_back(static_sharedir);
480 bindir + DIR_DELIM + ".." + DIR_DELIM + "share" + DIR_DELIM + PROJECT_NAME);
481 trylist.push_back(bindir + DIR_DELIM + "..");
483 trylist.push_back(DIR_DELIM "sdcard" DIR_DELIM PROJECT_NAME);
486 for(std::list<std::string>::const_iterator i = trylist.begin();
487 i != trylist.end(); i++)
489 const std::string &trypath = *i;
490 if(!fs::PathExists(trypath) || !fs::PathExists(trypath + DIR_DELIM + "builtin")){
491 dstream<<"WARNING: system-wide share not found at \""
492 <<trypath<<"\""<<std::endl;
495 // Warn if was not the first alternative
496 if(i != trylist.begin()){
497 dstream<<"WARNING: system-wide share found at \""
498 <<trypath<<"\""<<std::endl;
500 path_share = trypath;
504 path_user = std::string(getenv("HOME")) + DIR_DELIM + "." + PROJECT_NAME;
506 path_user = std::string(DIR_DELIM "sdcard" DIR_DELIM PROJECT_NAME DIR_DELIM);
512 #elif defined(__APPLE__)
515 // http://stackoverflow.com/questions/516200/relative-paths-not-working-in-xcode-c
516 CFBundleRef main_bundle = CFBundleGetMainBundle();
517 CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
519 if(CFURLGetFileSystemRepresentation(resources_url, TRUE, (UInt8 *)path, PATH_MAX))
521 dstream<<"Bundle resource path: "<<path<<std::endl;
523 path_share = std::string(path) + DIR_DELIM + "share";
528 dstream<<"WARNING: Could not determine bundle resource path"<<std::endl;
530 CFRelease(resources_url);
532 path_user = std::string(getenv("HOME")) + "/Library/Application Support/" + PROJECT_NAME;
534 #else // FreeBSD, and probably many other POSIX-like systems.
536 path_share = STATIC_SHAREDIR;
537 path_user = std::string(getenv("HOME")) + DIR_DELIM + "." + PROJECT_NAME;
541 #endif // RUN_IN_PLACE
544 static irr::IrrlichtDevice* device;
546 void initIrrlicht(irr::IrrlichtDevice * _device) {
551 v2u32 getWindowSize() {
552 return device->getVideoDriver()->getScreenSize();
557 float getDisplayDensity() {
558 float gui_scaling = g_settings->getFloat("gui_scaling");
559 // using Y here feels like a bug, this needs to be discussed later!
560 if (getWindowSize().Y <= 800) {
561 return (2.0/3.0) * gui_scaling;
563 if (getWindowSize().Y <= 1280) {
564 return 1.0 * gui_scaling;
567 return (4.0/3.0) * gui_scaling;
570 v2u32 getDisplaySize() {
571 IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
573 core::dimension2d<u32> deskres = nulldevice->getVideoModeList()->getDesktopResolution();
574 nulldevice -> drop();
581 } //namespace porting