Remove threads.h and replace its definitions with their C++11 equivalents (#5957)
[oweals/minetest.git] / src / porting.h
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
24 #ifndef PORTING_HEADER
25 #define PORTING_HEADER
26
27 #ifdef _WIN32
28         #ifdef _WIN32_WINNT
29                 #undef _WIN32_WINNT
30         #endif
31         #define _WIN32_WINNT 0x0501 // We need to do this before any other headers
32                 // because those might include sdkddkver.h which defines _WIN32_WINNT if not already set
33 #endif
34
35 #include <string>
36 #include <vector>
37 #include "irrlicht.h"
38 #include "irrlichttypes.h" // u32
39 #include "irrlichttypes_extrabloated.h"
40 #include "debug.h"
41 #include "constants.h"
42 #include "gettime.h"
43
44 #ifdef _MSC_VER
45         #define SWPRINTF_CHARSTRING L"%S"
46 #else
47         #define SWPRINTF_CHARSTRING L"%s"
48 #endif
49
50 //currently not needed
51 //template<typename T> struct alignment_trick { char c; T member; };
52 //#define ALIGNOF(type) offsetof (alignment_trick<type>, member)
53
54 #ifdef _WIN32
55         #include <windows.h>
56
57         #define sleep_ms(x) Sleep(x)
58 #else
59         #include <unistd.h>
60         #include <stdint.h> //for uintptr_t
61
62         // Use standard Posix macro for Linux
63         #if (defined(linux) || defined(__linux)) && !defined(__linux__)
64                 #define __linux__ 
65         #endif
66         #if (defined(__linux__) || defined(__GNU__)) && !defined(_GNU_SOURCE)
67                 #define _GNU_SOURCE
68         #endif
69
70         #define sleep_ms(x) usleep(x*1000)
71 #endif
72
73 #ifdef _MSC_VER
74         #define ALIGNOF(x) __alignof(x)
75         #define strtok_r(x, y, z) strtok_s(x, y, z)
76         #define strtof(x, y) (float)strtod(x, y)
77         #define strtoll(x, y, z) _strtoi64(x, y, z)
78         #define strtoull(x, y, z) _strtoui64(x, y, z)
79         #define strcasecmp(x, y) stricmp(x, y)
80         #define strncasecmp(x, y, n) strnicmp(x, y, n)
81 #else
82         #define ALIGNOF(x) __alignof__(x)
83 #endif
84
85 #ifdef __MINGW32__
86         #define strtok_r(x, y, z) mystrtok_r(x, y, z)
87 #endif
88
89 // strlcpy is missing from glibc.  thanks a lot, drepper.
90 // strlcpy is also missing from AIX and HP-UX because they aim to be weird.
91 // We can't simply alias strlcpy to MSVC's strcpy_s, since strcpy_s by
92 // default raises an assertion error and aborts the program if the buffer is
93 // too small.
94 #if defined(__FreeBSD__) || defined(__NetBSD__)    || \
95         defined(__OpenBSD__) || defined(__DragonFly__) || \
96         defined(__APPLE__)   ||                           \
97         defined(__sun)       || defined(sun)           || \
98         defined(__QNX__)     || defined(__QNXNTO__)
99         #define HAVE_STRLCPY
100 #endif
101
102 // So we need to define our own.
103 #ifndef HAVE_STRLCPY
104         #define strlcpy(d, s, n) mystrlcpy(d, s, n)
105 #endif
106
107 #define PADDING(x, y) ((ALIGNOF(y) - ((uintptr_t)(x) & (ALIGNOF(y) - 1))) & (ALIGNOF(y) - 1))
108
109 #if defined(__APPLE__)
110         #include <mach-o/dyld.h>
111         #include <CoreFoundation/CoreFoundation.h>
112 #endif
113
114 #ifndef _WIN32 // Posix
115         #include <sys/time.h>
116         #include <time.h>
117         #if defined(__MACH__) && defined(__APPLE__)
118                 #include <mach/clock.h>
119                 #include <mach/mach.h>
120         #endif
121 #endif
122
123 namespace porting
124 {
125
126 /*
127         Signal handler (grabs Ctrl-C on POSIX systems)
128 */
129
130 void signal_handler_init(void);
131 // Returns a pointer to a bool.
132 // When the bool is true, program should quit.
133 bool * signal_handler_killstatus(void);
134
135 /*
136         Path of static data directory.
137 */
138 extern std::string path_share;
139
140 /*
141         Directory for storing user data. Examples:
142         Windows: "C:\Documents and Settings\user\Application Data\<PROJECT_NAME>"
143         Linux: "~/.<PROJECT_NAME>"
144         Mac: "~/Library/Application Support/<PROJECT_NAME>"
145 */
146 extern std::string path_user;
147
148 /*
149         Path to gettext locale files
150 */
151 extern std::string path_locale;
152
153 /*
154         Path to directory for storing caches.
155 */
156 extern std::string path_cache;
157
158 /*
159         Get full path of stuff in data directory.
160         Example: "stone.png" -> "../data/stone.png"
161 */
162 std::string getDataPath(const char *subpath);
163
164 /*
165         Move cache folder from path_user to the
166         system cache location if possible.
167 */
168 void migrateCachePath();
169
170 /*
171         Initialize path_*.
172 */
173 void initializePaths();
174
175 /*
176         Return system information
177         e.g. "Linux/3.12.7 x86_64"
178 */
179 std::string get_sysinfo();
180
181 void initIrrlicht(irr::IrrlichtDevice * );
182
183
184 // Monotonic counter getters.
185
186 #ifdef _WIN32 // Windows
187
188 extern double perf_freq;
189
190 inline u64 os_get_time(double mult)
191 {
192         LARGE_INTEGER t;
193         QueryPerformanceCounter(&t);
194         return static_cast<double>(t.QuadPart) / (perf_freq / mult);
195 }
196
197 // Resolution is <1us.
198 inline u64 getTimeS() { return os_get_time(1); }
199 inline u64 getTimeMs() { return os_get_time(1000); }
200 inline u64 getTimeUs() { return os_get_time(1000*1000); }
201 inline u64 getTimeNs() { return os_get_time(1000*1000*1000); }
202
203 #else // Posix
204
205 inline void os_get_clock(struct timespec *ts)
206 {
207 #if defined(__MACH__) && defined(__APPLE__)
208 // From http://stackoverflow.com/questions/5167269/clock-gettime-alternative-in-mac-os-x
209 // OS X does not have clock_gettime, use clock_get_time
210         clock_serv_t cclock;
211         mach_timespec_t mts;
212         host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
213         clock_get_time(cclock, &mts);
214         mach_port_deallocate(mach_task_self(), cclock);
215         ts->tv_sec = mts.tv_sec;
216         ts->tv_nsec = mts.tv_nsec;
217 #elif defined(CLOCK_MONOTONIC_RAW)
218         clock_gettime(CLOCK_MONOTONIC_RAW, ts);
219 #elif defined(_POSIX_MONOTONIC_CLOCK)
220         clock_gettime(CLOCK_MONOTONIC, ts);
221 #else
222         struct timeval tv;
223         gettimeofday(&tv, NULL);
224         TIMEVAL_TO_TIMESPEC(&tv, ts);
225 #endif
226 }
227
228 inline u64 getTimeS()
229 {
230         struct timespec ts;
231         os_get_clock(&ts);
232         return ts.tv_sec;
233 }
234
235 inline u64 getTimeMs()
236 {
237         struct timespec ts;
238         os_get_clock(&ts);
239         return ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
240 }
241
242 inline u64 getTimeUs()
243 {
244         struct timespec ts;
245         os_get_clock(&ts);
246         return ts.tv_sec * 1000000 + ts.tv_nsec / 1000;
247 }
248
249 inline u64 getTimeNs()
250 {
251         struct timespec ts;
252         os_get_clock(&ts);
253         return ts.tv_sec * 1000000000 + ts.tv_nsec;
254 }
255
256 #endif
257
258 inline u64 getTime(TimePrecision prec)
259 {
260         switch (prec) {
261         case PRECISION_SECONDS: return getTimeS();
262         case PRECISION_MILLI:   return getTimeMs();
263         case PRECISION_MICRO:   return getTimeUs();
264         case PRECISION_NANO:    return getTimeNs();
265         }
266         FATAL_ERROR("Called getTime with invalid time precision");
267 }
268
269 /**
270  * Delta calculation function arguments.
271  * @param old_time_ms old time for delta calculation
272  * @param new_time_ms new time for delta calculation
273  * @return positive delta value
274  */
275 inline u64 getDeltaMs(u64 old_time_ms, u64 new_time_ms)
276 {
277         if (new_time_ms >= old_time_ms) {
278                 return (new_time_ms - old_time_ms);
279         } else {
280                 return (old_time_ms - new_time_ms);
281         }
282 }
283
284
285 #ifndef SERVER
286 float getDisplayDensity();
287
288 v2u32 getDisplaySize();
289 v2u32 getWindowSize();
290
291 std::vector<core::vector3d<u32> > getSupportedVideoModes();
292 std::vector<irr::video::E_DRIVER_TYPE> getSupportedVideoDrivers();
293 const char *getVideoDriverName(irr::video::E_DRIVER_TYPE type);
294 const char *getVideoDriverFriendlyName(irr::video::E_DRIVER_TYPE type);
295 #endif
296
297 inline const char *getPlatformName()
298 {
299         return
300 #if defined(ANDROID)
301         "Android"
302 #elif defined(__linux__)
303         "Linux"
304 #elif defined(_WIN32) || defined(_WIN64)
305         "Windows"
306 #elif defined(__DragonFly__) || defined(__FreeBSD__) || \
307                 defined(__NetBSD__) || defined(__OpenBSD__)
308         "BSD"
309 #elif defined(__APPLE__) && defined(__MACH__)
310         #if TARGET_OS_MAC
311                 "OSX"
312         #elif TARGET_OS_IPHONE
313                 "iOS"
314         #else
315                 "Apple"
316         #endif
317 #elif defined(_AIX)
318         "AIX"
319 #elif defined(__hpux)
320         "HP-UX"
321 #elif defined(__sun) || defined(sun)
322         #if defined(__SVR4)
323                 "Solaris"
324         #else
325                 "SunOS"
326         #endif
327 #elif defined(__CYGWIN__)
328         "Cygwin"
329 #elif defined(__unix__) || defined(__unix)
330         #if defined(_POSIX_VERSION)
331                 "Posix"
332         #else
333                 "Unix"
334         #endif
335 #else
336         "?"
337 #endif
338         ;
339 }
340
341 void setXorgClassHint(const video::SExposedVideoData &video_data,
342         const std::string &name);
343
344 bool setWindowIcon(IrrlichtDevice *device);
345
346 bool setXorgWindowIconFromPath(IrrlichtDevice *device,
347         const std::string &icon_file);
348
349 // This only needs to be called at the start of execution, since all future
350 // threads in the process inherit this exception handler
351 void setWin32ExceptionHandler();
352
353 bool secure_rand_fill_buf(void *buf, size_t len);
354
355 // This attaches to the parents process console, or creates a new one if it doesnt exist.
356 void attachOrCreateConsole(void);
357 } // namespace porting
358
359 #ifdef __ANDROID__
360 #include "porting_android.h"
361 #endif
362
363 #endif // PORTING_HEADER
364