SLProject  4.2.000
A platform independent 3D computer graphics framework for desktop OS, Android, iOS and online in web browsers
Utils.h
Go to the documentation of this file.
1 /**
2  * \file Utils.h
3  * \authors Marcus Hudritsch
4  * \date May 2019
5  * \copyright http://opensource.org/licenses/GPL-3.0
6  * \remarks Please use clangformat to format the code. See more code style on
7  * https://github.com/cpvrlab/SLProject4/wiki/SLProject-Coding-Style
8 */
9 
10 #ifndef CPLVRLAB_UTILS_H
11 #define CPLVRLAB_UTILS_H
12 
13 #include <string>
14 #include <vector>
15 #include <cfloat>
16 #include <memory>
17 #include <FileLog.h>
18 #include <CustomLog.h>
19 #include <functional>
20 
21 using std::function;
22 using std::string;
23 using std::stringstream;
24 using std::to_string;
25 using std::vector;
26 
27 // class FileLog;
28 //-----------------------------------------------------------------------------
29 //! Utils provides utilities for string & file handling, logging and math functions
30 /*!
31  Function are grouped into sections:
32  - String Handling Functions
33  - File Handling Functions
34  - Logging Functions
35  - Math Constants and Functions
36 */
37 namespace Utils
38 {
39 ///////////////////////////////
40 // String Handling Functions //
41 ///////////////////////////////
42 
43 //! Returns a string from a float with max. one trailing zero
44 string toString(float f, int roundedDecimals = 1);
45 
46 //! Returns a string from a double with max. one trailing zero
47 string toString(double d, int roundedDecimals = 1);
48 
49 //! Returns a string in lower case
50 string toLowerString(string s);
51 
52 //! Returns a string in upper case
53 string toUpperString(string s);
54 
55 //! Trims a string at both end
56 string trimString(const string& s, const string& drop = " ");
57 
58 //! trims a string at the right end
59 string trimRightString(const string& s, const string& drop);
60 
61 //! trims a string at the left end
62 string trimLeftString(const string& s, const string& drop);
63 
64 //! Splits an input string at a delimiter character into a string vector
65 void splitString(const string& s, char delimiter, vector<string>& splits);
66 
67 //! Replaces in the source string the from string by the to string
68 void replaceString(string& source, const string& from, const string& to);
69 
70 //! Returns a vector of string one per line of a multiline string
71 vector<string> getStringLines(const string& multiLineString);
72 
73 //! Reads a text file into a string and returns it
74 string readTextFileIntoString(const char* logTag,
75  const string& pathAndFilename);
76 
77 //! Writes a string into a text file
78 void writeStringIntoTextFile(const char* logTag,
79  const string& stringToWrite,
80  const string& pathAndFilename);
81 
82 //! replaces non-filename characters: /\|?%*:"<>'
83 string replaceNonFilenameChars(string source, char replaceChar = '-');
84 
85 //! Returns local time as string like "Wed Feb 13 15:46:11 2019"
86 string getLocalTimeString();
87 
88 //! Returns local time as string like "13.02.19-15:46"
89 string getDateTime1String();
90 
91 //! Returns local time as string like "20190213-154611"
92 string getDateTime2String();
93 
94 //! Returns the computer name
95 string getHostName();
96 
97 //! Returns a formatted string as sprintf
98 string formatString(string fmt_str, ...);
99 
100 //! Returns true if container contains the search string
101 bool containsString(const string& container, const string& search);
102 
103 //! Return true if the container string starts with the startStr
104 bool startsWithString(const string& container, const string& startStr);
105 
106 //! Return true if the container string ends with the endStr
107 bool endsWithString(const string& container, const string& endStr);
108 
109 //! Returns the inputDir string with unified forward slashes, e.g.: "dirA/dirB/"
110 string unifySlashes(const string& inputDir, bool withTrailingSlash = true);
111 
112 //! Returns true if content of file could be put in a vector of strings
113 bool getFileContent(const string& fileName,
114  vector<string>& vecOfStrings);
115 
116 //! Naturally compares two strings (used for filename sorting)
117 bool compareNatural(const string& a, const string& b);
118 
119 /////////////////////////////
120 // File Handling Functions //
121 /////////////////////////////
122 
123 //! Returns the path w. '\\' of path-filename string
124 string getPath(const string& pathFilename);
125 
126 //! Returns the filename of path-filename string
127 string getFileName(const string& pathFilename);
128 
129 //! Returns the filename without extension
130 string getFileNameWOExt(const string& pathFilename);
131 
132 //! Strip last component from file name
133 string getDirName(const string& pathFilename);
134 
135 //! Returns the file extension without dot in lower case
136 string getFileExt(const string& filename);
137 
138 //! Returns a vector directory names with path in dir
139 vector<string> getDirNamesInDir(const string& dirName, bool fullPath = true);
140 
141 //! Returns a vector of sorted names (files and directories) with path in dir
142 vector<string> getAllNamesInDir(const string& dirName, bool fullPath = true);
143 
144 //! Returns a vector of sorted filesnames in dirName
145 vector<string> getFileNamesInDir(const string& dirName, bool fullPath = true);
146 
147 //! Returns true if a directory exists.
148 bool dirExists(const string& path);
149 
150 //! Returns the file size in bytes
151 unsigned int getFileSize(const string& filename);
152 unsigned int getFileSize(std::ifstream& fs);
153 
154 //! Creates a directory with given path
155 bool makeDir(const string& path);
156 
157 //! Creates a directory with given path recursively
158 bool makeDirRecurse(string path);
159 
160 //! RemoveDir deletes a directory with given path
161 void removeDir(const string& path);
162 
163 //! RemoveFile deletes a file with given path
164 void removeFile(const string& path);
165 
166 //! Returns true if a file exists.
167 bool fileExists(const string& pathfilename);
168 
169 //! Returns the writable configuration directory
170 string getAppsWritableDir(string appName = "SLProject");
171 
172 //! Returns the working directory
173 string getCurrentWorkingDir();
174 
175 //! Deletes a file on the filesystem
176 bool deleteFile(string& pathfilename);
177 
178 //! process all files and folders recursively naturally sorted
179 void loopFileSystemRec(const string& path,
180  function<void(string path, string baseName, int depth)> processFile,
181  function<void(string path, string baseName, int depth)> processDir,
182  const int depth = 0);
183 
184 //! Dumps all folders and files recursovely
185 void dumpFileSystemRec(const char* logtag,
186  const string& folderpath);
187 
188 //! Tries to find a filename on various paths to check
189 string findFile(const string& filename,
190  const vector<string>& pathsToCheck);
191 
192 ///////////////////////
193 // Logging Functions //
194 ///////////////////////
195 
196 //! FileLog Instance for logging to logfile. If it is instantiated the logging methods
197 //! will also output into this file. Instantiate it with initFileLog function.
198 static std::unique_ptr<FileLog> fileLog;
199 
200 //! if this flag is set to true all calls to log get ignored
201 extern bool onlyErrorLogs;
202 
203 //! Instantiates FileLog instance
204 void initFileLog(const std::string& logDir, bool forceFlush);
205 
206 //! custom log instance, e.g. log to a ui log window
207 extern std::unique_ptr<CustomLog> customLog;
208 
209 //! logs a formatted string platform independently
210 void log(const char* tag, const char* format, ...);
211 
212 //! Terminates the application with a message. No leak checking.
213 [[noreturn]] void exitMsg(const char* tag,
214  const char* msg,
215  int line,
216  const char* file);
217 
218 //! Platform independent warn message output
219 void warnMsg(const char* tag,
220  const char* msg,
221  int line,
222  const char* file);
223 
224 //! Platform independent error message output
225 void errorMsg(const char* tag,
226  const char* msg,
227  int line,
228  const char* file);
229 
230 //! Returns in release config the max. NO. of threads otherwise 1
231 unsigned int maxThreads();
232 
233 //////////////////////////////////
234 // Math Constants and Functions //
235 //////////////////////////////////
236 
237 static const float PI = 3.14159265358979f;
238 static const float RAD2DEG = 180.0f / PI;
239 static const float DEG2RAD = PI / 180.0f;
240 static const float TWOPI = 2.0f * PI;
241 static const float ONEOVERPI = 1.0f / PI; // is faster than / PI
242 static const float HALFPI = PI * 0.5f;
243 
244 // clang-format off
245 template<class T> inline T sign(T a){return (T)((a > 0) ? 1 : (a < 0) ? -1 : 0);}
246 template<class T> inline T floor(T a){return (T)((int)a - ((a < 0 && a != (int)(a))));}
247 template<class T> inline T ceil(T a){return (T)((int)a + ((a > 0 && a != (int)(a))));}
248 template<class T> inline T fract(T a){return a - floor(a);}
249 template<class T> inline T abs(T a){return (a >= 0) ? a : -a;}
250 template<class T> inline T mod(T a, T b){return a - b * floor(a / b);}
251 template<class T> inline T step(T edge, T x){return (T)(x >= edge);}
252 template<class T> inline T pulse(T a, T b, T x){return (SL_step(a, x) - step(b, x));}
253 template<class T> inline T clamp(T a, T min, T max){return (a < min) ? min : (a > max) ? max : a;}
254 template<class T> inline T mix(T mix, T a, T b){return (1 - mix) * a + mix * b;}
255 template<class T> inline T lerp(T x, T a, T b){return (a + x * (b - a));}
256 //template<class T> inline T swap(T& a, T& b){T c = a; a = b; b = c;}
257 //-----------------------------------------------------------------------------
258 //! Returns true if a number is of power of 2
259 inline bool isPowerOf2(unsigned int a)
260 {
261  return a == 1 || (a & (a - 1)) == 0;
262 }
263 //-----------------------------------------------------------------------------
264 //! Returns a uniform distributed random float number between min and max
265 inline float random(float min, float max)
266 {
267  return ((float)rand() / (float)RAND_MAX) * (max - min) + min;
268 }
269 //-----------------------------------------------------------------------------
270 //! Returns a uniform distributed random int number between min and max
271 inline int random(int min, int max)
272 {
273  return min + (rand() % (int)(max - min + 1));
274 }
275 //-----------------------------------------------------------------------------
276 //! Greatest common divisor of two integer numbers (ggT = grösster gemeinsame Teiler)
277 int gcd(int a, int b);
278 //-----------------------------------------------------------------------------
279 //! Returns the closest power of 2 to a passed number.
280 unsigned closestPowerOf2(unsigned num);
281 //-----------------------------------------------------------------------------
282 //! Returns the next power of 2 to a passed number.
283 unsigned nextPowerOf2(unsigned num);
284 //-----------------------------------------------------------------------------
285 // clang-format on
286 //! Class for holding computer information
288 {
289 public:
290  static std::string user;
291  static std::string name;
292  static std::string brand;
293  static std::string model;
294  static std::string os;
295  static std::string osVer;
296  static std::string arch;
297  static std::string id;
298 
299  static std::string get();
300 };
301 
302 };
303 //-----------------------------------------------------------------------------
304 
305 #endif
The SLScene class represents the top level instance holding the scene structure.
Definition: SLScene.h:47
Class for holding computer information.
Definition: Utils.h:288
static std::string model
Definition: Utils.h:293
static std::string get()
Definition: Utils.cpp:1261
static std::string brand
Definition: Utils.h:292
static std::string user
Definition: Utils.h:290
static std::string os
Definition: Utils.h:294
static std::string id
Definition: Utils.h:297
static std::string osVer
Definition: Utils.h:295
static std::string arch
Definition: Utils.h:296
static std::string name
Definition: Utils.h:291
Utils provides utilities for string & file handling, logging and math functions.
Definition: Averaged.h:22
string findFile(const string &filename, const vector< string > &pathsToCheck)
Tries to find a filename on various paths to check.
Definition: Utils.cpp:1077
vector< string > getDirNamesInDir(const string &dirName, bool fullPath)
Returns a vector directory names with path in dir.
Definition: Utils.cpp:638
string getDateTime2String()
Returns local time as string like "20190213-154611".
Definition: Utils.cpp:289
static const float DEG2RAD
Definition: Utils.h:239
string unifySlashes(const string &inputDir, bool withTrailingSlash)
Returns the inputDir string with unified forward slashes, e.g.: "dirA/dirB/".
Definition: Utils.cpp:368
bool fileExists(const string &pathfilename)
Returns true if a file exists.
Definition: Utils.cpp:897
static const float HALFPI
Definition: Utils.h:242
bool dirExists(const string &path)
Returns true if a directory exists.
Definition: Utils.cpp:790
bool makeDir(const string &path)
Creates a directory with given path.
Definition: Utils.cpp:810
T sign(T a)
Definition: Utils.h:245
T abs(T a)
Definition: Utils.h:249
bool getFileContent(const string &fileName, vector< string > &vecOfStrings)
Returns true if content of file could be put in a vector of strings.
Definition: Utils.cpp:411
unsigned nextPowerOf2(unsigned num)
Returns the next power of 2 to a passed number.
Definition: Utils.cpp:1237
void removeDir(const string &path)
RemoveDir deletes a directory with given path.
Definition: Utils.cpp:854
string getHostName()
Returns the computer name.
Definition: Utils.cpp:310
bool containsString(const string &container, const string &search)
Returns true if container contains the search string.
Definition: Utils.cpp:345
void dumpFileSystemRec(const char *logtag, const string &folderPath)
Dumps all folders and files recursovely.
Definition: Utils.cpp:1051
vector< string > getStringLines(const string &multiLineString)
Returns a vector of string one per line of a multiline string.
Definition: Utils.cpp:195
void errorMsg(const char *tag, const char *msg, const int line, const char *file)
Platform independent error message output.
Definition: Utils.cpp:1168
string getFileNameWOExt(const string &pathFilename)
Returns the filename without extension.
Definition: Utils.cpp:616
bool compareNatural(const string &a, const string &b)
Naturally compares two strings (used for filename sorting)
Definition: Utils.cpp:464
T clamp(T a, T min, T max)
Definition: Utils.h:253
string trimLeftString(const string &s, const string &drop)
trims a string at the left end
Definition: Utils.cpp:144
std::unique_ptr< CustomLog > customLog
custom log instance, e.g. log to a ui log window
Definition: Utils.cpp:82
T lerp(T x, T a, T b)
Definition: Utils.h:255
unsigned int getFileSize(const string &pathfilename)
Returns the file size in bytes.
Definition: Utils.cpp:912
string formatString(string fmt_str,...)
Returns a formatted string as sprintf.
Definition: Utils.cpp:320
string getFileName(const string &pathFilename)
Returns the filename of path-filename string.
Definition: Utils.cpp:580
string replaceNonFilenameChars(string src, const char replaceChar)
replaces non-filename characters: /|?%*:"<>'
Definition: Utils.cpp:244
void splitString(const string &s, char delimiter, vector< string > &splits)
Splits an input string at a delimiter character into a string vector.
Definition: Utils.cpp:152
string getPath(const string &pathFilename)
Returns the path w. '\' of path-filename string.
Definition: Utils.cpp:392
void warnMsg(const char *tag, const char *msg, const int line, const char *file)
Platform independent warn message output.
Definition: Utils.cpp:1145
T ceil(T a)
Definition: Utils.h:247
static const float ONEOVERPI
Definition: Utils.h:241
T floor(T a)
Definition: Utils.h:246
void exitMsg(const char *tag, const char *msg, const int line, const char *file)
Terminates the application with a message. No leak checking.
Definition: Utils.cpp:1135
string toUpperString(string s)
Returns a string in upper case.
Definition: Utils.cpp:120
static const float RAD2DEG
Definition: Utils.h:238
static std::unique_ptr< FileLog > fileLog
Definition: Utils.h:198
unsigned int maxThreads()
Returns in release config the max. NO. of threads otherwise 1.
Definition: Utils.cpp:1191
vector< string > getFileNamesInDir(const string &dirName, bool fullPath)
Returns a vector of sorted filesnames in dirName.
Definition: Utils.cpp:737
string getDirName(const string &pathFilename)
Strip last component from file name.
Definition: Utils.cpp:598
void removeFile(const string &path)
RemoveFile deletes a file with given path.
Definition: Utils.cpp:875
vector< string > getAllNamesInDir(const string &dirName, bool fullPath)
Returns a vector of sorted names (files and directories) with path in dir.
Definition: Utils.cpp:691
T mix(T mix, T a, T b)
Definition: Utils.h:254
string getCurrentWorkingDir()
Returns the working directory.
Definition: Utils.cpp:976
unsigned closestPowerOf2(unsigned num)
Returns the closest power of 2 to a passed number.
Definition: Utils.cpp:1221
string getLocalTimeString()
Returns local time as string like "Wed Feb 13 15:46:11 2019".
Definition: Utils.cpp:258
string trimString(const string &s, const string &drop)
Trims a string at both end.
Definition: Utils.cpp:128
string getAppsWritableDir(string appName)
Returns the writable configuration directory.
Definition: Utils.cpp:942
static const float PI
Definition: Utils.h:237
int gcd(int a, int b)
Greatest common divisor of two integer numbers (ggT = grösster gemeinsame Teiler)
Definition: Utils.cpp:1207
static const float TWOPI
Definition: Utils.h:240
string trimRightString(const string &s, const string &drop)
trims a string at the right end
Definition: Utils.cpp:136
bool makeDirRecurse(std::string path)
Definition: Utils.cpp:826
bool startsWithString(const string &container, const string &startStr)
Return true if the container string starts with the startStr.
Definition: Utils.cpp:351
float random(float min, float max)
Returns a uniform distributed random float number between min and max.
Definition: Utils.h:265
bool isPowerOf2(unsigned int a)
Returns true if a number is of power of 2.
Definition: Utils.h:259
void loopFileSystemRec(const string &path, function< void(string path, string baseName, int depth)> processFile, function< void(string path, string baseName, int depth)> processDir, const int depth)
process all files and folders recursively naturally sorted
Definition: Utils.cpp:1016
string toString(float f, int roundedDecimals)
Returns a string from a float with max. one trailing zero.
Definition: Utils.cpp:92
bool endsWithString(const string &container, const string &endStr)
Return true if the container string ends with the endStr.
Definition: Utils.cpp:357
void replaceString(string &source, const string &from, const string &to)
Replaces in the source string the from string by the to string.
Definition: Utils.cpp:170
bool deleteFile(string &pathfilename)
Deletes a file on the filesystem.
Definition: Utils.cpp:1008
string readTextFileIntoString(const char *logTag, const string &pathAndFilename)
Reads a text file into a string and returns it.
Definition: Utils.cpp:212
string getDateTime1String()
Returns local time as string like "13.02.19-15:46".
Definition: Utils.cpp:269
T mod(T a, T b)
Definition: Utils.h:250
bool onlyErrorLogs
if this flag is set to true all calls to log get ignored
Definition: Utils.cpp:84
T pulse(T a, T b, T x)
Definition: Utils.h:252
string toLowerString(string s)
Returns a string in lower case.
Definition: Utils.cpp:112
void log(const char *tag, const char *format,...)
logs a formatted string platform independently
Definition: Utils.cpp:1103
void writeStringIntoTextFile(const char *logTag, const string &stringToWrite, const string &pathAndFilename)
Writes a string into a text file.
Definition: Utils.cpp:230
T fract(T a)
Definition: Utils.h:248
T step(T edge, T x)
Definition: Utils.h:251
void initFileLog(const string &logDir, bool forceFlush)
Definition: Utils.cpp:1097
string getFileExt(const string &filename)
Returns the file extension without dot in lower case.
Definition: Utils.cpp:629