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();
170 bool threadBindToProcessor(threadid_t tid, int pnumber) {
173 HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, 0, tid);
177 bool success = SetThreadAffinityMask(hThread, 1 << pnumber) != 0;
179 CloseHandle(hThread);
182 #elif (defined(__FreeBSD__) && (__FreeBSD_version >= 702106)) \
183 || defined(__linux) || defined(linux)
188 CPU_SET(pnumber, &cpuset);
189 return pthread_setaffinity_np(tid, sizeof(cpuset), &cpuset) == 0;
191 #elif defined(__sun) || defined(sun)
193 return processor_bind(P_LWPID, MAKE_LWPID_PTHREAD(tid),
198 return bindprocessor(BINDTHREAD, (tid_t)tid, pnumber) == 0;
200 #elif defined(__hpux) || defined(hpux)
202 pthread_spu_t answer;
204 return pthread_processor_bind_np(PTHREAD_BIND_ADVISORY_NP,
205 &answer, pnumber, tid) == 0;
207 #elif defined(__APPLE__)
209 struct thread_affinity_policy tapol;
211 thread_port_t threadport = pthread_mach_thread_np(tid);
212 tapol.affinity_tag = pnumber + 1;
213 return thread_policy_set(threadport, THREAD_AFFINITY_POLICY,
214 (thread_policy_t)&tapol, THREAD_AFFINITY_POLICY_COUNT) == KERN_SUCCESS;
224 bool threadSetPriority(threadid_t tid, int prio) {
227 HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, 0, tid);
231 bool success = SetThreadPriority(hThread, prio) != 0;
233 CloseHandle(hThread);
238 struct sched_param sparam;
241 if (pthread_getschedparam(tid, &policy, &sparam) != 0)
244 int min = sched_get_priority_min(policy);
245 int max = sched_get_priority_max(policy);
247 sparam.sched_priority = min + prio * (max - min) / THREAD_PRIORITY_HIGHEST;
248 return pthread_setschedparam(tid, policy, &sparam) == 0;
258 // Default to RUN_IN_PLACE style relative paths
259 std::string path_share = "..";
260 std::string path_user = "..";
262 std::string getDataPath(const char *subpath)
264 return path_share + DIR_DELIM + subpath;
267 void pathRemoveFile(char *path, char delim)
269 // Remove filename and path delimiter
271 for(i = strlen(path)-1; i>=0; i--)
279 bool detectMSVCBuildDir(char *c_path)
281 std::string path(c_path);
282 const char *ends[] = {"bin\\Release", "bin\\Build", NULL};
283 return (removeStringEnd(path, ends) != "");
286 std::string get_sysinfo()
290 std::ostringstream oss;
292 ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
293 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
295 tmp = osvi.szCSDVersion;
296 std::replace(tmp.begin(), tmp.end(), ' ', '_');
298 oss << "Windows/" << osvi.dwMajorVersion << "."
299 << osvi.dwMinorVersion;
300 if(osvi.szCSDVersion[0])
307 if(IsWow64Process(GetCurrentProcess(), &is64) && is64)
308 oss << "x86_64"; // 32-bit app on 64-bit OS
315 struct utsname osinfo;
317 return std::string(osinfo.sysname) + "/"
318 + osinfo.release + " " + osinfo.machine;
322 void initializePaths()
326 Use relative paths if RUN_IN_PLACE
329 infostream<<"Using relative paths (RUN_IN_PLACE)"<<std::endl;
336 const DWORD buflen = 1000;
340 // Find path of executable and set path_share relative to it
341 len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen);
342 assert(len < buflen);
343 pathRemoveFile(buf, '\\');
345 if(detectMSVCBuildDir(buf)){
346 infostream<<"MSVC build directory detected"<<std::endl;
347 path_share = std::string(buf) + "\\..\\..";
348 path_user = std::string(buf) + "\\..\\..";
351 path_share = std::string(buf) + "\\..";
352 path_user = std::string(buf) + "\\..";
361 memset(buf, 0, BUFSIZ);
362 // Get path to executable
363 assert(readlink("/proc/self/exe", buf, BUFSIZ-1) != -1);
365 pathRemoveFile(buf, '/');
367 path_share = std::string(buf) + "/..";
368 path_user = std::string(buf) + "/..";
373 #elif defined(__APPLE__)
375 //https://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/dyld.3.html
376 //TODO: Test this code
378 uint32_t len = sizeof(buf);
379 assert(_NSGetExecutablePath(buf, &len) != -1);
381 pathRemoveFile(buf, '/');
383 path_share = std::string(buf) + "/..";
384 path_user = std::string(buf) + "/..";
389 #elif defined(__FreeBSD__)
393 size_t len = sizeof(buf);
397 mib[2] = KERN_PROC_PATHNAME;
399 assert(sysctl(mib, 4, buf, &len, NULL, 0) != -1);
401 pathRemoveFile(buf, '/');
403 path_share = std::string(buf) + "/..";
404 path_user = std::string(buf) + "/..";
408 //TODO: Get path of executable. This assumes working directory is bin/
409 dstream<<"WARNING: Relative path not properly supported on this platform"
412 /* scriptapi no longer allows paths that start with "..", so assuming that
413 the current working directory is bin/, strip off the last component. */
414 char *cwd = getcwd(NULL, 0);
415 pathRemoveFile(cwd, '/');
416 path_share = std::string(cwd);
417 path_user = std::string(cwd);
421 #else // RUN_IN_PLACE
424 Use platform-specific paths otherwise
427 infostream<<"Using system-wide paths (NOT RUN_IN_PLACE)"<<std::endl;
434 const DWORD buflen = 1000;
438 // Find path of executable and set path_share relative to it
439 len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen);
440 assert(len < buflen);
441 pathRemoveFile(buf, '\\');
444 path_share = std::string(buf) + "\\..";
446 // Use "C:\Documents and Settings\user\Application Data\<PROJECT_NAME>"
447 len = GetEnvironmentVariable("APPDATA", buf, buflen);
448 assert(len < buflen);
449 path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME;
456 // Get path to executable
457 std::string bindir = "";
460 memset(buf, 0, BUFSIZ);
461 assert(readlink("/proc/self/exe", buf, BUFSIZ-1) != -1);
462 pathRemoveFile(buf, '/');
466 // Find share directory from these.
467 // It is identified by containing the subdirectory "builtin".
468 std::list<std::string> trylist;
469 std::string static_sharedir = STATIC_SHAREDIR;
470 if(static_sharedir != "" && static_sharedir != ".")
471 trylist.push_back(static_sharedir);
473 bindir + DIR_DELIM + ".." + DIR_DELIM + "share" + DIR_DELIM + PROJECT_NAME);
474 trylist.push_back(bindir + DIR_DELIM + "..");
476 for(std::list<std::string>::const_iterator i = trylist.begin();
477 i != trylist.end(); i++)
479 const std::string &trypath = *i;
480 if(!fs::PathExists(trypath) || !fs::PathExists(trypath + DIR_DELIM + "builtin")){
481 dstream<<"WARNING: system-wide share not found at \""
482 <<trypath<<"\""<<std::endl;
485 // Warn if was not the first alternative
486 if(i != trylist.begin()){
487 dstream<<"WARNING: system-wide share found at \""
488 <<trypath<<"\""<<std::endl;
490 path_share = trypath;
494 path_user = std::string(getenv("HOME")) + DIR_DELIM + "." + PROJECT_NAME;
499 #elif defined(__APPLE__)
502 // http://stackoverflow.com/questions/516200/relative-paths-not-working-in-xcode-c
503 CFBundleRef main_bundle = CFBundleGetMainBundle();
504 CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
506 if(CFURLGetFileSystemRepresentation(resources_url, TRUE, (UInt8 *)path, PATH_MAX))
508 dstream<<"Bundle resource path: "<<path<<std::endl;
510 path_share = std::string(path) + DIR_DELIM + "share";
515 dstream<<"WARNING: Could not determine bundle resource path"<<std::endl;
517 CFRelease(resources_url);
519 path_user = std::string(getenv("HOME")) + "/Library/Application Support/" + PROJECT_NAME;
521 #else // FreeBSD, and probably many other POSIX-like systems.
523 path_share = STATIC_SHAREDIR;
524 path_user = std::string(getenv("HOME")) + DIR_DELIM + "." + PROJECT_NAME;
528 #endif // RUN_IN_PLACE
531 static irr::IrrlichtDevice* device;
533 void initIrrlicht(irr::IrrlichtDevice * _device) {
538 v2u32 getWindowSize() {
539 return device->getVideoDriver()->getScreenSize();
543 float getDisplayDensity() {
544 float gui_scaling = g_settings->getFloat("gui_scaling");
545 // using Y here feels like a bug, this needs to be discussed later!
546 if (getWindowSize().Y <= 800) {
547 return (2.0/3.0) * gui_scaling;
549 if (getWindowSize().Y <= 1280) {
550 return 1.0 * gui_scaling;
553 return (4.0/3.0) * gui_scaling;
556 v2u32 getDisplaySize() {
557 IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
559 core::dimension2d<u32> deskres = nulldevice->getVideoModeList()->getDesktopResolution();
560 nulldevice -> drop();
566 } //namespace porting