XPMP2
X-Plane multiplayer library 2 - using instancing
Utilities.h
Go to the documentation of this file.
1 
21 #ifndef _Utilities_h_
22 #define _Utilities_h_
23 
24 namespace XPMP2 {
25 
26 //
27 // MARK: General texts
28 //
29 
30 #define ERR_ASSERT "ASSERT FAILED: %s"
31 #define ERR_EXCEPTION "EXCEPTION CAUGHT: %s"
32 
33 // Required supplemental files
34 constexpr const char* RSRC_RELATED = "related.txt";
35 constexpr const char* RSRC_REL_OP = "relOp.txt";
36 constexpr const char* RSRC_DOC8643 = "Doc8643.txt";
37 constexpr const char* RSRC_MAP_ICONS = "MapIcons.png";
38 constexpr const char* RSRC_OBJ8DATAREFS = "Obj8DataRefs.txt";
39 
40 //
41 // MARK: Default configuration callbacks
42 //
43 
44 int PrefsFuncIntDefault (const char *, const char *, int _default);
45 
46 //
47 // MARK: File access helpers
48 //
49 
50 #if IBM
51 #define PATH_DELIM_STD '\\'
52 #else
53 #define PATH_DELIM_STD '/'
54 #endif
55 
57 bool ExistsFile (const std::string& filename);
58 
60 bool IsDir (const std::string& path);
61 
64 bool CreateDir(const std::string& path);
65 
68 bool CopyFileIfNewer(const std::string& source, const std::string& destDir);
69 
71 std::list<std::string> GetDirContents (const std::string& path);
72 
74 std::istream& safeGetline(std::istream& is, std::string& t);
75 
77 const std::string& GetXPSystemPath ();
78 
80 std::string StripXPSysDir (const std::string& path);
81 
83 void RemoveExtension (std::string& path);
84 
85 //
86 // MARK: String helpers
87 //
88 
89 #define WHITESPACE " \t\f\v\r\n"
90 
92 std::string& str_tolower(std::string& s);
93 
96 inline std::string& rtrim(std::string& s, const char* t = WHITESPACE)
97 {
98  s.erase(s.find_last_not_of(t) + 1);
99  return s;
100 }
101 
104 inline std::string& ltrim(std::string& s, const char* t = WHITESPACE)
105 {
106  s.erase(0, s.find_first_not_of(t));
107  return s;
108 }
109 
112 inline std::string& trim(std::string& s, const char* t = WHITESPACE)
113 {
114  return ltrim(rtrim(s, t), t);
115 }
116 
118 inline std::string leftOf(const std::string& s, const std::string& terminators)
119 {
120  return s.substr(0, std::min(s.find_first_of(terminators), s.size()));
121 }
122 
124 std::vector<std::string> str_tokenize (const std::string s,
125  const std::string tokens,
126  bool bSkipEmpty = true);
127 
128 //
129 // MARK: Math helpers
130 //
131 
133 constexpr double PI = 3.1415926535897932384626433832795028841971693993751;
134 
136 constexpr float EPSILON_F = 0.00001f;
137 
139 inline bool fequal (float a, float b)
140 { return ((a - EPSILON_F) < b) && ((a + EPSILON_F) > b); }
141 
142 
144 template <class T>
145 inline T rad2deg (const T _rad)
146 { return (_rad < T(0) ? T(360) : T(0)) + _rad * T(180) / T(PI); }
147 
149 template <class T>
150 inline T deg2rad (const T _deg)
151 { return _deg * T(PI) / T(180); }
152 
154 template <class T>
155 inline T sqr (const T a) { return a*a; }
156 
158 template <class T>
159 inline T dist (const T x1, const T y1, const T z1,
160  const T x2, const T y2, const T z2)
161 {
162  return std::sqrt(sqr(x1-x2) + sqr(y1-y2) + sqr(z1-z2));
163 }
164 
166 inline float atan2deg (float x, float y)
167 { return rad2deg(atan2(x,y)); }
168 
176 inline float angleLocCoord (float x1, float z1, float x2, float z2)
177 { return rad2deg(atan2(z2-z1,x2-x1) + float(PI/2.0)); }
178 
180 float headDiff (float head1, float head2);
181 
183 template <class numT>
184 numT headNormalize (numT _head)
185 {
186  if (_head < numT(0))
187  _head += std::ceil(_head/-numT(360)) * numT(360);
188  else if (_head >= numT(360))
189  _head -= std::floor(_head/numT(360)) * numT(360);
190  return _head;
191 }
192 
197 std::valarray<float> HeadPitch2Vec (const float head, const float pitch);
198 
200 std::valarray<float> HeadPitchRoll2Normal(const float head, const float pitch, const float roll);
201 
202 //
203 // MARK: Misc
204 //
205 
207 float GetMiscNetwTime ();
208 
211 std::string GetMiscNetwTimeStr (float _time = NAN);
212 
214 const char* GetGraphicsDriverTxt ();
215 
217 bool IsPaused ();
218 
220 bool IsViewExternal ();
221 
227 bool CheckEverySoOften (float& _lastCheck, float _interval, float _now);
228 
233 inline bool CheckEverySoOften (float& _lastCheck, float _interval)
234 { return CheckEverySoOften(_lastCheck, _interval, GetMiscNetwTime()); }
235 
236 //
237 // MARK: Logging Support
238 //
239 
242 #if defined(__clang__) || defined(__GNUC__)
243 #define XPMP2_FMTARGS(FMT) __attribute__((format(printf, FMT, FMT+1)))
244 #else
245 #define XPMP2_FMTARGS(FMT)
246 #endif
247 
250  logDEBUG = 0,
255  logMSG
256 };
257 
259 const char* LogGetString ( const char* szFile, int ln, const char* szFunc, logLevelTy lvl, const char* szMsg, va_list args );
260 
262 void LogMsg ( const char* szFile, int ln, const char* szFunc, logLevelTy lvl, const char* szMsg, ... ) XPMP2_FMTARGS(5);
263 
264 //
265 // MARK: Logging macros
266 //
267 
271 #define LOG_MSG(lvl,...) { \
272  if (lvl >= XPMP2::glob.logLvl) \
273  {LogMsg(__FILE__, __LINE__, __func__, lvl, __VA_ARGS__);} \
274 }
275 
279 #define LOG_MATCHING(lvl,...) { \
280  if (XPMP2::glob.bLogMdlMatch && lvl >= glob.logLvl) \
281  {LogMsg(__FILE__, __LINE__, __func__, lvl, __VA_ARGS__);} \
282 }
283 
287 #define THROW_ERROR(...) \
288 throw XPMP2Error(__FILE__, __LINE__, __func__, __VA_ARGS__);
289 
292 #define LOG_ASSERT(cond) \
293  if (!(cond)) { \
294  THROW_ERROR(ERR_ASSERT,#cond); \
295  }
296 
298 #define CATCH_AC(ac) \
299  catch (const std::exception& e) { \
300  LOG_MSG(logFATAL, ERR_EXCEPTION, e.what()); \
301  (ac).SetInvalid(); \
302  } \
303  catch (...) { \
304  LOG_MSG(logFATAL, ERR_EXCEPTION, "<unknown>"); \
305  (ac).SetInvalid(); \
306  }
307 
308 
309 //
310 // MARK: Compiler differences
311 //
312 
313 #if APL == 1 || LIN == 1
314 // not quite the same but close enough for our purposes
315 inline void strncpy_s(char * dest, size_t destsz, const char * src, size_t count)
316 {
317  strncpy(dest, src, std::min(destsz,count)); dest[destsz - 1] = 0;
318 }
319 
320 // these simulate the VC++ version, not the C standard versions!
321 inline struct tm *gmtime_s(struct tm * result, const time_t * time)
322 { return gmtime_r(time, result); }
323 inline struct tm *localtime_s(struct tm * result, const time_t * time)
324 { return localtime_r(time, result); }
325 
326 #endif
327 
329 #define STRCPY_S(dest,src) strncpy_s(dest,sizeof(dest),src,sizeof(dest)-1)
330 #define STRCPY_ATMOST(dest,src) strncpy_s(dest,sizeof(dest),strAtMost(src,sizeof(dest)-1).c_str(),sizeof(dest)-1)
331 
332 // XCode/Linux don't provide the _s functions, not even with __STDC_WANT_LIB_EXT1__ 1
333 #if APL
334 inline int strerror_s( char *buf, size_t bufsz, int errnum )
335 { return strerror_r(errnum, buf, bufsz); }
336 #elif LIN
337 inline int strerror_s( char *buf, size_t bufsz, int errnum )
338 { strerror_r(errnum, buf, bufsz); return 0; }
339 #endif
340 
341 // In case of Mac we need to prepare for HFS-to-Posix path conversion
342 #if APL
344 std::string TOPOSIX (const std::string& p);
346 std::string FROMPOSIX (const std::string& p);
347 #else
349 inline std::string TOPOSIX (const std::string& p) { return p; }
351 inline std::string FROMPOSIX (const std::string& p) { return p; }
352 #endif
353 
354 // MARK: Thread names
355 #ifdef DEBUG
356 // This might not work on older Windows version, which is why we don't publish it in release builds
357 #if IBM
358 #define SET_THREAD_NAME(sName) SetThreadDescription(GetCurrentThread(), L##sName)
359 #elif APL
360 #define SET_THREAD_NAME(sName) pthread_setname_np(sName)
361 #elif LIN
362 #define SET_THREAD_NAME(sName) pthread_setname_np(pthread_self(),sName)
363 #endif
364 #else
365 #define SET_THREAD_NAME(sName)
366 #endif
367 
368 } // namespace XPMP2
369 
370 #endif
#define WHITESPACE
Definition: Utilities.h:89
#define XPMP2_FMTARGS(FMT)
To apply printf-style warnings to our functions.
Definition: Utilities.h:245
Definition: XPMPAircraft.h:70
std::valarray< float > HeadPitch2Vec(const float head, const float pitch)
Convert heading/pitch to normalized x/y/z vector.
Definition: Utilities.cpp:675
T rad2deg(const T _rad)
Convert radians to degrees, normalized to [0..360)
Definition: Utilities.h:145
logLevelTy
Logging level.
Definition: Utilities.h:249
@ logFATAL
fatal is shortly before a crash
Definition: Utilities.h:254
@ logMSG
will always be output, no matter what has been configured, cannot be suppressed
Definition: Utilities.h:255
@ logDEBUG
Debug, highest level of detail.
Definition: Utilities.h:250
@ logWARN
warnings, i.e. unexpected, but uncritical events, maybe leading to unwanted display,...
Definition: Utilities.h:252
@ logERR
errors mean, aircraft can potentially not be displayed
Definition: Utilities.h:253
@ logINFO
regular info messages
Definition: Utilities.h:251
std::string leftOf(const std::string &s, const std::string &terminators)
Returns everything left of any of terminators.
Definition: Utilities.h:118
const char * LogGetString(const char *szPath, int ln, const char *szFunc, logLevelTy lvl, const char *szMsg, va_list args)
Returns ptr to static buffer filled with formatted log string.
Definition: Utilities.cpp:826
constexpr const char * RSRC_OBJ8DATAREFS
Definition: Utilities.h:38
std::string TOPOSIX(const std::string &p)
On Lin/Win there is no need for a conversion, but we do treat p now as std::string
Definition: Utilities.h:349
constexpr double PI
Pi.
Definition: Utilities.h:133
void LogMsg(const char *szPath, int ln, const char *szFunc, logLevelTy lvl, const char *szMsg,...)
Log Text to log file.
Definition: Utilities.cpp:866
bool CheckEverySoOften(float &_lastCheck, float _interval, float _now)
Convenience function to check on something at most every x seconds.
Definition: Utilities.cpp:782
std::string & ltrim(std::string &s, const char *t=WHITESPACE)
trimming of string (from left)
Definition: Utilities.h:104
std::string GetMiscNetwTimeStr(float _time)
Return the network time as a string like used in the XP's Log.txt.
Definition: Utilities.cpp:738
std::string FROMPOSIX(const std::string &p)
On Lin/Win there is no need for a conversion, but we do treat p now as std::string
Definition: Utilities.h:351
float angleLocCoord(float x1, float z1, float x2, float z2)
Angle of line from point (x1|z1) to point (x2|z2)
Definition: Utilities.h:176
void RemoveExtension(std::string &path)
Removes everything after the last dot, the dot including.
Definition: Utilities.cpp:490
std::list< std::string > GetDirContents(const std::string &path)
List of files in a directory (wrapper around XPLMGetDirectoryContents)
Definition: Utilities.cpp:421
constexpr const char * RSRC_RELATED
Definition: Utilities.h:34
std::valarray< float > HeadPitchRoll2Normal(const float head, const float pitch, const float roll)
Convert heading/pitch/roll to unit and normal vector, ie. returns 6 values, first 3 like HeadPitch2Ve...
Definition: Utilities.cpp:696
T sqr(const T a)
Square.
Definition: Utilities.h:155
float GetMiscNetwTime()
Get synched network time from X-Plane (sim/network/misc/network_time_sec) as used in Log....
Definition: Utilities.cpp:729
bool fequal(float a, float b)
Are these two float near-equal? (to avoid trying something like a == b)
Definition: Utilities.h:139
const std::string & GetXPSystemPath()
Returns XP's system directory, including a trailing slash.
Definition: Utilities.cpp:467
numT headNormalize(numT _head)
Normalize a heading value to [0..360), works for both float and double values.
Definition: Utilities.h:184
constexpr float EPSILON_F
Epsilon, a small number.
Definition: Utilities.h:136
const char * GetGraphicsDriverTxt()
Text string for current graphics driver in use.
Definition: Utilities.cpp:755
float headDiff(float head1, float head2)
(Shortest) difference between 2 angles: How much to turn to go from h1 to h2?
Definition: Utilities.cpp:655
bool ExistsFile(const std::string &filename)
Does a file path exist?
Definition: Utilities.cpp:337
bool CreateDir(const std::string &path)
Create directory if it does not exist.
Definition: Utilities.cpp:353
std::string & str_tolower(std::string &s)
change a std::string to uppercase
Definition: Utilities.cpp:601
bool CopyFileIfNewer(const std::string &source, const std::string &destDir)
Copy file if source is newer or destination missing.
Definition: Utilities.cpp:368
constexpr const char * RSRC_MAP_ICONS
Definition: Utilities.h:37
bool IsPaused()
X-Plane in a Pause state?
Definition: Utilities.cpp:768
bool IsViewExternal()
Is current X-Plane view an external view (outside a cockpit)?
Definition: Utilities.cpp:775
T dist(const T x1, const T y1, const T z1, const T x2, const T y2, const T z2)
Pythagorean distance between two points in a 3-D world.
Definition: Utilities.h:159
std::string & trim(std::string &s, const char *t=WHITESPACE)
trimming of string (from both ends)
Definition: Utilities.h:112
std::string StripXPSysDir(const std::string &path)
If a path starts with X-Plane's system directory it is stripped.
Definition: Utilities.cpp:480
T deg2rad(const T _deg)
Convert degree to radians.
Definition: Utilities.h:150
constexpr const char * RSRC_REL_OP
Definition: Utilities.h:35
std::string & rtrim(std::string &s, const char *t=WHITESPACE)
trimming of string (from right)
Definition: Utilities.h:96
bool IsDir(const std::string &path)
Is path a directory?
Definition: Utilities.cpp:344
float atan2deg(float x, float y)
atan2 converted to degrees: the angle between (0|0) and the given point
Definition: Utilities.h:166
int PrefsFuncIntDefault(const char *, const char *, int _default)
Default config function just always returns the provided default value.
Definition: Utilities.cpp:179
constexpr const char * RSRC_DOC8643
Definition: Utilities.h:36
std::vector< std::string > str_tokenize(const std::string s, const std::string tokens, bool bSkipEmpty)
separates string into tokens
Definition: Utilities.cpp:608
std::istream & safeGetline(std::istream &is, std::string &t)
Read a line from a text file, no matter if ending on CRLF or LF.
Definition: Utilities.cpp:454