]> git.lizzy.rs Git - minetest.git/blob - src/porting.cpp
OS X compatibility fixes
[minetest.git] / src / porting.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
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.
9
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.
14
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.
18 */
19
20 /*
21         Random portability stuff
22
23         See comments in porting.h
24 */
25
26 #include "porting.h"
27
28 #if defined(__FreeBSD__)
29         #include <sys/types.h>
30         #include <sys/sysctl.h>
31 #elif defined(_WIN32)
32         #include <algorithm>
33 #endif
34 #if !defined(_WIN32)
35         #include <unistd.h>
36         #include <sys/utsname.h>
37 #endif
38
39 #include "config.h"
40 #include "debug.h"
41 #include "filesys.h"
42 #include "log.h"
43 #include "util/string.h"
44 #include "main.h"
45 #include "settings.h"
46 #include <list>
47
48 namespace porting
49 {
50
51 /*
52         Signal handler (grabs Ctrl-C on POSIX systems)
53 */
54
55 bool g_killed = false;
56
57 bool * signal_handler_killstatus(void)
58 {
59         return &g_killed;
60 }
61
62 #if !defined(_WIN32) // POSIX
63         #include <signal.h>
64
65 void sigint_handler(int sig)
66 {
67         if(g_killed == false)
68         {
69                 dstream<<DTIME<<"INFO: sigint_handler(): "
70                                 <<"Ctrl-C pressed, shutting down."<<std::endl;
71
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();*/
76
77                 g_killed = true;
78         }
79         else
80         {
81                 (void)signal(SIGINT, SIG_DFL);
82         }
83 }
84
85 void signal_handler_init(void)
86 {
87         (void)signal(SIGINT, sigint_handler);
88 }
89
90 #else // _WIN32
91         #include <signal.h>
92
93         BOOL WINAPI event_handler(DWORD sig)
94         {
95                 switch(sig)
96                 {
97                 case CTRL_C_EVENT:
98                 case CTRL_CLOSE_EVENT:
99                 case CTRL_LOGOFF_EVENT:
100                 case CTRL_SHUTDOWN_EVENT:
101
102                         if(g_killed == false)
103                         {
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();*/
110
111                                 g_killed = true;
112                         }
113                         else
114                         {
115                                 (void)signal(SIGINT, SIG_DFL);
116                         }
117
118                         break;
119                 case CTRL_BREAK_EVENT:
120                         break;
121                 }
122
123                 return TRUE;
124         }
125
126 void signal_handler_init(void)
127 {
128         SetConsoleCtrlHandler( (PHANDLER_ROUTINE)event_handler,TRUE);
129 }
130
131 #endif
132
133
134 /*
135         Multithreading support
136 */
137 int getNumberOfProcessors() {
138 #if defined(_SC_NPROCESSORS_ONLN)
139
140         return sysconf(_SC_NPROCESSORS_ONLN);
141
142 #elif defined(__FreeBSD__) || defined(__APPLE__)
143
144         unsigned int len, count;
145         len = sizeof(count);
146         return sysctlbyname("hw.ncpu", &count, &len, NULL, 0);
147
148 #elif defined(_GNU_SOURCE)
149
150         return get_nprocs();
151
152 #elif defined(_WIN32)
153
154         SYSTEM_INFO sysinfo;
155         GetSystemInfo(&sysinfo);
156         return sysinfo.dwNumberOfProcessors;
157
158 #elif defined(PTW32_VERSION) || defined(__hpux)
159
160         return pthread_num_processors_np();
161
162 #else
163
164         return 1;
165
166 #endif
167 }
168
169
170 bool threadBindToProcessor(threadid_t tid, int pnumber) {
171 #if defined(_WIN32)
172
173         HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, 0, tid);
174         if (!hThread)
175                 return false;
176
177         bool success = SetThreadAffinityMask(hThread, 1 << pnumber) != 0;
178
179         CloseHandle(hThread);
180         return success;
181
182 #elif (defined(__FreeBSD__) && (__FreeBSD_version >= 702106)) \
183         || defined(__linux) || defined(linux)
184
185         cpu_set_t cpuset;
186
187         CPU_ZERO(&cpuset);
188         CPU_SET(pnumber, &cpuset);
189         return pthread_setaffinity_np(tid, sizeof(cpuset), &cpuset) == 0;
190
191 #elif defined(__sun) || defined(sun)
192
193         return processor_bind(P_LWPID, MAKE_LWPID_PTHREAD(tid),
194                                                 pnumber, NULL) == 0;
195
196 #elif defined(_AIX)
197         
198         return bindprocessor(BINDTHREAD, (tid_t)tid, pnumber) == 0;
199
200 #elif defined(__hpux) || defined(hpux)
201
202         pthread_spu_t answer;
203
204         return pthread_processor_bind_np(PTHREAD_BIND_ADVISORY_NP,
205                                                                         &answer, pnumber, tid) == 0;
206         
207 #elif defined(__APPLE__)
208
209         struct thread_affinity_policy tapol;
210         
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;
215
216 #else
217
218         return false;
219
220 #endif
221 }
222
223
224 bool threadSetPriority(threadid_t tid, int prio) {
225 #if defined(_WIN32)
226
227         HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, 0, tid);
228         if (!hThread)
229                 return false;
230
231         bool success = SetThreadPriority(hThread, prio) != 0;
232
233         CloseHandle(hThread);
234         return success;
235         
236 #else
237
238         struct sched_param sparam;
239         int policy;
240         
241         if (pthread_getschedparam(tid, &policy, &sparam) != 0)
242                 return false;
243                 
244         int min = sched_get_priority_min(policy);
245         int max = sched_get_priority_max(policy);
246
247         sparam.sched_priority = min + prio * (max - min) / THREAD_PRIORITY_HIGHEST;
248         return pthread_setschedparam(tid, policy, &sparam) == 0;
249         
250 #endif
251 }
252
253
254 /*
255         Path mangler
256 */
257
258 // Default to RUN_IN_PLACE style relative paths
259 std::string path_share = "..";
260 std::string path_user = "..";
261
262 std::string getDataPath(const char *subpath)
263 {
264         return path_share + DIR_DELIM + subpath;
265 }
266
267 void pathRemoveFile(char *path, char delim)
268 {
269         // Remove filename and path delimiter
270         int i;
271         for(i = strlen(path)-1; i>=0; i--)
272         {
273                 if(path[i] == delim)
274                         break;
275         }
276         path[i] = 0;
277 }
278
279 bool detectMSVCBuildDir(char *c_path)
280 {
281         std::string path(c_path);
282         const char *ends[] = {"bin\\Release", "bin\\Build", NULL};
283         return (removeStringEnd(path, ends) != "");
284 }
285
286 std::string get_sysinfo()
287 {
288 #ifdef _WIN32
289         OSVERSIONINFO osvi;
290         std::ostringstream oss;
291         std::string tmp;
292         ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
293         osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
294         GetVersionEx(&osvi);
295         tmp = osvi.szCSDVersion;
296         std::replace(tmp.begin(), tmp.end(), ' ', '_');
297
298         oss << "Windows/" << osvi.dwMajorVersion << "."
299                 << osvi.dwMinorVersion;
300         if(osvi.szCSDVersion[0])
301                 oss << "-" << tmp;
302         oss << " ";
303         #ifdef _WIN64
304         oss << "x86_64";
305         #else
306         BOOL is64 = FALSE;
307         if(IsWow64Process(GetCurrentProcess(), &is64) && is64)
308                 oss << "x86_64"; // 32-bit app on 64-bit OS
309         else
310                 oss << "x86";
311         #endif
312
313         return oss.str();
314 #else
315         struct utsname osinfo;
316         uname(&osinfo);
317         return std::string(osinfo.sysname) + "/"
318                 + osinfo.release + " " + osinfo.machine;
319 #endif
320 }
321
322 void initializePaths()
323 {
324 #if RUN_IN_PLACE
325         /*
326                 Use relative paths if RUN_IN_PLACE
327         */
328
329         infostream<<"Using relative paths (RUN_IN_PLACE)"<<std::endl;
330
331         /*
332                 Windows
333         */
334         #if defined(_WIN32)
335
336         const DWORD buflen = 1000;
337         char buf[buflen];
338         DWORD len;
339
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, '\\');
344
345         if(detectMSVCBuildDir(buf)){
346                 infostream<<"MSVC build directory detected"<<std::endl;
347                 path_share = std::string(buf) + "\\..\\..";
348                 path_user = std::string(buf) + "\\..\\..";
349         }
350         else{
351                 path_share = std::string(buf) + "\\..";
352                 path_user = std::string(buf) + "\\..";
353         }
354
355         /*
356                 Linux
357         */
358         #elif defined(linux)
359
360         char buf[BUFSIZ];
361         memset(buf, 0, BUFSIZ);
362         // Get path to executable
363         assert(readlink("/proc/self/exe", buf, BUFSIZ-1) != -1);
364
365         pathRemoveFile(buf, '/');
366
367         path_share = std::string(buf) + "/..";
368         path_user = std::string(buf) + "/..";
369
370         /*
371                 OS X
372         */
373         #elif defined(__APPLE__)
374
375         //https://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/dyld.3.html
376         //TODO: Test this code
377         char buf[BUFSIZ];
378         uint32_t len = sizeof(buf);
379         assert(_NSGetExecutablePath(buf, &len) != -1);
380
381         pathRemoveFile(buf, '/');
382
383         path_share = std::string(buf) + "/..";
384         path_user = std::string(buf) + "/..";
385
386         /*
387                 FreeBSD
388         */
389         #elif defined(__FreeBSD__)
390
391         int mib[4];
392         char buf[BUFSIZ];
393         size_t len = sizeof(buf);
394
395         mib[0] = CTL_KERN;
396         mib[1] = KERN_PROC;
397         mib[2] = KERN_PROC_PATHNAME;
398         mib[3] = -1;
399         assert(sysctl(mib, 4, buf, &len, NULL, 0) != -1);
400
401         pathRemoveFile(buf, '/');
402
403         path_share = std::string(buf) + "/..";
404         path_user = std::string(buf) + "/..";
405
406         #else
407
408         //TODO: Get path of executable. This assumes working directory is bin/
409         dstream<<"WARNING: Relative path not properly supported on this platform"
410                         <<std::endl;
411
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);
418
419         #endif
420
421 #else // RUN_IN_PLACE
422
423         /*
424                 Use platform-specific paths otherwise
425         */
426
427         infostream<<"Using system-wide paths (NOT RUN_IN_PLACE)"<<std::endl;
428
429         /*
430                 Windows
431         */
432         #if defined(_WIN32)
433
434         const DWORD buflen = 1000;
435         char buf[buflen];
436         DWORD len;
437
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, '\\');
442
443         // Use ".\bin\.."
444         path_share = std::string(buf) + "\\..";
445
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;
450
451         /*
452                 Linux
453         */
454         #elif defined(linux)
455
456         // Get path to executable
457         std::string bindir = "";
458         {
459                 char buf[BUFSIZ];
460                 memset(buf, 0, BUFSIZ);
461                 assert(readlink("/proc/self/exe", buf, BUFSIZ-1) != -1);
462                 pathRemoveFile(buf, '/');
463                 bindir = buf;
464         }
465
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);
472         trylist.push_back(
473                         bindir + DIR_DELIM + ".." + DIR_DELIM + "share" + DIR_DELIM + PROJECT_NAME);
474         trylist.push_back(bindir + DIR_DELIM + "..");
475
476         for(std::list<std::string>::const_iterator i = trylist.begin();
477                         i != trylist.end(); i++)
478         {
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;
483                         continue;
484                 }
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;
489                 }
490                 path_share = trypath;
491                 break;
492         }
493
494         path_user = std::string(getenv("HOME")) + DIR_DELIM + "." + PROJECT_NAME;
495
496         /*
497                 OS X
498         */
499         #elif defined(__APPLE__)
500
501         // Code based on
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);
505         char path[PATH_MAX];
506         if(CFURLGetFileSystemRepresentation(resources_url, TRUE, (UInt8 *)path, PATH_MAX))
507         {
508                 dstream<<"Bundle resource path: "<<path<<std::endl;
509                 //chdir(path);
510                 path_share = std::string(path) + DIR_DELIM + "share";
511         }
512         else
513         {
514                 // error!
515                 dstream<<"WARNING: Could not determine bundle resource path"<<std::endl;
516         }
517         CFRelease(resources_url);
518
519         path_user = std::string(getenv("HOME")) + "/Library/Application Support/" + PROJECT_NAME;
520
521         #else // FreeBSD, and probably many other POSIX-like systems.
522
523         path_share = STATIC_SHAREDIR;
524         path_user = std::string(getenv("HOME")) + DIR_DELIM + "." + PROJECT_NAME;
525
526         #endif
527
528 #endif // RUN_IN_PLACE
529 }
530
531 static irr::IrrlichtDevice* device;
532
533 void initIrrlicht(irr::IrrlichtDevice * _device) {
534         device = _device;
535 }
536
537 #ifndef SERVER
538 v2u32 getWindowSize() {
539         return device->getVideoDriver()->getScreenSize();
540 }
541
542
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;
548         }
549         if (getWindowSize().Y <= 1280) {
550                 return 1.0 * gui_scaling;
551         }
552
553         return (4.0/3.0) * gui_scaling;
554 }
555
556 v2u32 getDisplaySize() {
557         IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
558
559         core::dimension2d<u32> deskres = nulldevice->getVideoModeList()->getDesktopResolution();
560         nulldevice -> drop();
561
562         return deskres;
563 }
564 #endif
565
566 } //namespace porting
567