-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFunctions.cpp
1724 lines (1591 loc) · 68.4 KB
/
Functions.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//HEAD_DSCODES
/*
<DUALSPHYSICS> Copyright (c) 2020 by Dr Jose M. Dominguez et al. (see http://dual.sphysics.org/index.php/developers/).
EPHYSLAB Environmental Physics Laboratory, Universidade de Vigo, Ourense, Spain.
School of Mechanical, Aerospace and Civil Engineering, University of Manchester, Manchester, U.K.
This file is part of DualSPHysics.
DualSPHysics is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License
as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.
DualSPHysics is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with DualSPHysics. If not, see <http://www.gnu.org/licenses/>.
*/
/// \file Functions.cpp \brief Implements basic/general functions for the entire application.
#include "Functions.h"
#include <limits>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cfloat>
#include <cmath>
#include <climits>
#include <stdarg.h>
#include <algorithm>
#include <fstream>
#include <climits>
#include <iostream>
//#include <sstream>
#ifdef WIN32
#include <direct.h>
#else
#include <unistd.h>
#endif
#pragma warning(disable : 4996) //Cancels sprintf() deprecated.
using namespace std;
namespace fun{
//==============================================================================
/// Throws an exception related to a file or not.
//==============================================================================
void RunExceptioonFun(const std::string &srcfile,int srcline,const std::string &fun
,const std::string &msg,const std::string &file)
{ // fun::RunExceptioonFun(__FILE__,__LINE__,__func__,"msg");
std::string tx;
tx=fun::PrintStr("\n*** Exception (%s::%s:%d)\n",GetPathLevels(srcfile,3).c_str(),fun.c_str(),srcline);
if(!msg.empty())tx=tx+fun::PrintStr("Text: %s\n",msg.c_str());
if(!file.empty())tx=tx+fun::PrintStr("File: %s\n",file.c_str());
printf("%s\n",tx.c_str());
fflush(stdout);
throw string("#")+tx;
}
//==============================================================================
/// Returns date and time of the system + nseg using the format.
//==============================================================================
std::string GetDateTimeFormat(const char* format,int nseg){
time_t rawtime;
struct tm *timeinfo;
time(&rawtime);
rawtime+=nseg;
timeinfo=localtime(&rawtime);
//timeinfo=gmtime(&rawtime);
char bufftime[256];
strftime(bufftime,256,format,timeinfo);
return(bufftime);
}
//==============================================================================
/// Returns date and time of the system + nseg using the format.
/// day=1-31, month=1-12, hour=0-23, min=0-59, sec=0-59
//==============================================================================
std::string GetDateTimeFormatUTC(const char* format,int day,int month,int year,int hour,int min,int sec){
time_t rawtime;
struct tm *timeinfo;
time(&rawtime);
timeinfo=gmtime(&rawtime);
timeinfo->tm_year=year-1900;
timeinfo->tm_mon=month - 1;
timeinfo->tm_mday=day;
timeinfo->tm_hour=hour;
timeinfo->tm_min=min;
timeinfo->tm_sec=sec;
mktime(timeinfo);
char bufftime[256];
strftime(bufftime,256,format,timeinfo);
return(bufftime);
}
//==============================================================================
/// Returns weekday as a decimal number with Sunday as 0 (0-6).
/// day=1-31, month=1-12, hour=0-23, min=0-59, sec=0-59
//==============================================================================
int GetWeekDay(int day,int month,int year){
time_t rawtime;
struct tm *timeinfo;
time(&rawtime);
timeinfo=gmtime(&rawtime);
timeinfo->tm_year=year-1900;
timeinfo->tm_mon=month - 1;
timeinfo->tm_mday=day;
timeinfo->tm_hour=timeinfo->tm_min=timeinfo->tm_sec=0;
mktime(timeinfo);
return(timeinfo->tm_wday);
}
//==============================================================================
/// Returns days since January 1st).
/// day=1-31, month=1-12, hour=0-23, min=0-59, sec=0-59
//==============================================================================
int GetYearDay(int day,int month,int year){
time_t rawtime;
struct tm *timeinfo;
time(&rawtime);
timeinfo=gmtime(&rawtime);
timeinfo->tm_year=year-1900;
timeinfo->tm_mon=month - 1;
timeinfo->tm_mday=day;
timeinfo->tm_hour=timeinfo->tm_min=timeinfo->tm_sec=0;
mktime(timeinfo);
return(timeinfo->tm_yday);
}
//==============================================================================
/// Returns week number with the first Monday as the first day of week one (0-53).
/// day=1-31, month=1-12, hour=0-23, min=0-59, sec=0-59
//==============================================================================
int GetWeekNumber(int day,int month,int year){
string tx=GetDateTimeFormatUTC("%W",day,month,year);
int v=-1;
if(tx.size()==2)v=int(unsigned(tx[0]-'0')*10+unsigned(tx[1]-'0'));
return(v);
}
//==============================================================================
/// Pause for ms milliseconds.
//==============================================================================
void Delay(int ms){
const long pause=ms*(CLOCKS_PER_SEC/1000);
clock_t now,then;
now=then=clock();
while((now-then)<pause)now=clock();
}
//==============================================================================
/// Returns the processor time (seconds) consumed by the program.
//==============================================================================
double GetRuntime(){
return(clock()/double(CLOCKS_PER_SEC));
}
//==============================================================================
/// Returns duration in format xh ym zs.
//==============================================================================
std::string GetHoursOfSeconds(double s){
int hours=int(s/3600);
s-=double(hours*3600);
int mins=int(s/60);
s-=double(mins*60);
char cad[64];
sprintf(cad,"%dh %dm %.1fs",hours,mins,s);
return(cad);
}
//==============================================================================
/// Returns text with the random code.
//==============================================================================
std::string GetTextRandomCode(unsigned length){
const unsigned maxlength=1024;
if(length<1)length=1;
if(length>1024)length=1024;
char code[maxlength+1];
srand((unsigned)time(NULL));
for(unsigned c=0;c<length;c++){
char let=char(float(rand())/float(RAND_MAX)*36);
code[c]=(let<10? let+48: let+87);
}
code[length]=0;
return(code);
}
//==============================================================================
/// Returns string using the same parameters used in printf().
//==============================================================================
std::string PrintStr(const char *format,...){
std::string ret;
const unsigned SIZE=1024;
char buffer[SIZE+1];
va_list args;
va_start(args, format);
int size=vsnprintf(buffer,SIZE,format,args);
if(size>=0 && size<SIZE)ret=buffer;
else{
int rsize=-1;
int size2=SIZE+SIZE*2;
for(int c=0;c<10 && rsize<0;c++,size2+=SIZE*2){
char *buff2=new char[size2+1];
rsize=vsnprintf(buff2,size2,format,args);
if(rsize>=0)ret=buff2;
delete[] buff2;
}
if(rsize<0)Run_ExceptioonFun("Output text is too long.");
}
va_end(args);
return(ret);
}
//==============================================================================
/// Returns string using the same parameters used in printf() and the CSV
/// separator in format is corrected.
//==============================================================================
std::string PrintStrCsv(bool csvsepcoma,const char *format,...){
const std::string format2=StrCsvSep(csvsepcoma,format);
const char *formatok=format2.c_str();
std::string ret;
const unsigned SIZE=1024;
char buffer[SIZE+1];
va_list args;
va_start(args,format);
int size=vsnprintf(buffer,SIZE,formatok,args);
if(size>=0 && size<SIZE)ret=buffer;
else{
int rsize=-1;
int size2=SIZE+SIZE*2;
for(int c=0;c<10 && rsize<0;c++,size2+=SIZE*2){
char *buff2=new char[size2+1];
rsize=vsnprintf(buff2,size2,formatok,args);
if(rsize>=0)ret=buff2;
delete[] buff2;
}
if(rsize<0)Run_ExceptioonFun("Output text is too long.");
}
va_end(args);
return(ret);
}
//==============================================================================
/// Gets new string where the CSV separator is corrected.
//==============================================================================
std::string StrCsvSep(bool csvsepcoma,const std::string &cad){
const char sep0=(csvsepcoma? ';': ',');
const char sep1=(csvsepcoma? ',': ';');
std::string str=cad;
const unsigned size=unsigned(str.size());
for(unsigned c=0;c<size;c++)if(str[c]==sep0)str[c]=sep1;
return(str);
}
//==============================================================================
/// Returns format to obtain simplified number in a string.
//==============================================================================
std::string NaturalFmt(double v,unsigned ndigits,bool removezeros){
const string fmt0=string("%.")+IntStr(ndigits)+"f";
string tnat=DoubleStr(fabs(v),fmt0.c_str());
int pp=int(tnat.find("."));
int ne=(pp>=0? pp: int(tnat.length()));
if(ne==1 && tnat[0]=='0')ne=0;
//printf("----> tnat:[%s] ne:%d\n",tnat.c_str(),ne);
if(ne==0){
tnat=tnat.substr(pp+1);
for(int c=0;c<int(tnat.size()) && tnat[c]=='0';c++)ne--;
//printf(" --> tnat2:[%s] ne:%d\n",tnat.c_str(),ne);
}
int ndec=max(int(ndigits)-ne,0);
string fmt=string("%.")+IntStr(ndec)+"f";
if(removezeros){
string txv=DoubleStr(v,fmt.c_str());
for(int c=int(txv.size())-1;ndec>0 && c>=0 && txv[c]=='0';c--)ndec--;
fmt=string("%.")+IntStr(ndec)+"f";
}
//string txv=DoubleStr(v,fmt.c_str());
//printf(" --> fmt:[%s] v:%s \n",fmt.c_str(),txv.c_str());
//string txv1=DoubleStr(v,"%.10E");
//double v1=StrToDouble(txv1);
//double v2=StrToDouble(txv);
//printf(" --> Dif: v1:%s v2:%s dif:%g\n",txv1.c_str(),txv.c_str(),v2-v1);
return(fmt);
}
//==============================================================================
/// Converts unsigned value to string filling with zeros.
//==============================================================================
std::string IntStrFill(int v,int vmax){
unsigned len=unsigned(UintStr(vmax).length());
std::string value=IntStr(v);
while(unsigned(value.length())<len)value=std::string("0")+value;
return(value);
}
//==============================================================================
/// Converts unsigned value to string filling with zeros or other character.
//==============================================================================
std::string UintStrFill(unsigned v,unsigned vmax,const char fillchar){
unsigned len=unsigned(UintStr(vmax).length());
std::string value=UintStr(v);
std::string fill="."; fill[0]=fillchar;
while(unsigned(value.length())<len)value=fill+value;
return(value);
}
//==============================================================================
/// Converts long long value to string.
//==============================================================================
std::string LongStr(llong v){
char cad[128];
sprintf(cad,"%lld",v);
return(std::string(cad));
}
//==============================================================================
/// Converts unsigned long long value to string.
//==============================================================================
std::string UlongStr(ullong v){
char cad[128];
sprintf(cad,"%llu",v);
return(std::string(cad));
}
//==============================================================================
/// Converts unsigned value to string.
//==============================================================================
std::string UintStr(unsigned v,const char* fmt){
char cad[128];
sprintf(cad,fmt,v);
return(std::string(cad));
}
//==============================================================================
/// Converts int value to string.
//==============================================================================
std::string IntStr(int v){
char cad[128];
sprintf(cad,"%d",v);
return(std::string(cad));
}
//==============================================================================
/// Converts tint3 value to string.
//==============================================================================
std::string Int3Str(const tint3 &v){
char cad[128];
sprintf(cad,"%d,%d,%d",v.x,v.y,v.z);
return(std::string(cad));
}
//==============================================================================
/// Converts tuint3 value to string.
//==============================================================================
std::string Uint3Str(const tuint3 &v){
char cad[128];
sprintf(cad,"%u,%u,%u",v.x,v.y,v.z);
return(std::string(cad));
}
//==============================================================================
/// Converts real value to string.
//==============================================================================
std::string FloatStr(float v,const char* fmt){
char cad[128];
sprintf(cad,fmt,v);
return(std::string(cad));
}
//==============================================================================
/// Converts real value to string (-FLT_MAX=MIN and FLT_MAX=MAX).
//==============================================================================
std::string FloatxStr(float v,const char* fmt){
char cad[128];
sprintf(cad,fmt,v);
return(v==-FLT_MAX? std::string("MIN"): (v==FLT_MAX? std::string("MAX"): std::string(cad)));
}
//==============================================================================
/// Converts real value to string.
//==============================================================================
std::string Float3Str(const tfloat3 &v,const char* fmt){
char cad[1024];
sprintf(cad,fmt,v.x,v.y,v.z);
return(std::string(cad));
}
//==============================================================================
/// Converts real value to string.
//==============================================================================
std::string DoubleStr(double v,const char* fmt){
char cad[512];
sprintf(cad,fmt,v);
return(std::string(cad));
}
//==============================================================================
/// Converts real value to string (-DBL_MAX=MIN and DBL_MAX=MAX).
//==============================================================================
std::string DoublexStr(double v,const char* fmt){
char cad[512];
sprintf(cad,fmt,v);
return(v==-DBL_MAX? std::string("MIN"): (v==DBL_MAX? std::string("MAX"): std::string(cad)));
}
//==============================================================================
/// Converts real value to string.
//==============================================================================
std::string Double3Str(const tdouble3 &v,const char* fmt){
char cad[2048];
sprintf(cad,fmt,v.x,v.y,v.z);
return(std::string(cad));
}
//==============================================================================
/// Converts real value to string.
//==============================================================================
std::string Double4Str(const tdouble4 &v,const char* fmt){
char cad[2048];
sprintf(cad,fmt,v.x,v.y,v.z,v.w);
return(std::string(cad));
}
//==============================================================================
/// Converts vector of strings to string list.
//==============================================================================
std::string VectorStr(const std::vector<std::string> &v){
string ret;
const unsigned n=unsigned(v.size());
for(unsigned c=0;c<n;c++)ret=ret+(c? string(",")+v[c]: v[c]);
return(ret);
}
//==============================================================================
/// Returns true when str is a valid integer number.
//==============================================================================
bool StrIsIntegerNumber(const std::string &str){
bool valid=true;
byte state=0;
unsigned n=unsigned(str.size());
//-Avoid decimal part when it is null.
int point=int(str.find_last_of("."));
if(point>0){
for(unsigned c=point+1;c<n && valid;c++)valid=(str[c]=='0');
if(valid)n=point;
}
//-Checks integer format.
for(unsigned c=0;c<n && valid;c++){
const char let=str[c];
const bool num=('0'<=let && let<='9');
const bool sp=(let==' ' || let=='\t');
if(state==0){//-First character. Expected values:[\t, ,+,-,0-9].
if(let=='+' || let=='-')state=1;
else if(num)state=2;
else if(!sp)valid=false;
}
else if(state==1){//-After +/-. Expected values:[0-9]
if(num)state=2;
else valid=false;
}
else if(state==2){//-After +/- and some number. Expected values:[0-9\t, ]
if(sp)state=15;
else if(!num)valid=false;
}
else if(state==15 && !sp)valid=false; //-After some space. Expected values:[\t, ]
}
if(state==1)valid=false;
//printf("StrIsIntegerNumber(%s) => state:%d %s [%d]\n",str.c_str(),state,(valid? "Ok": "ERROR"),atoi(str.c_str()));
return(valid);
}
//==============================================================================
/// Returns true when str is a valid real number.
//==============================================================================
bool StrIsRealNumber(const std::string &str){
bool valid=true;
byte state=0;
const unsigned n=unsigned(str.size());
for(unsigned c=0;c<n && valid;c++){
const char let=str[c];
const bool num=('0'<=let && let<='9');
const bool sp=(let==' ' || let=='\t');
if(state==0){//-First character. Expected values:[\t, ,+,-,0-9,.].
if(let=='+' || let=='-')state=1;
else if(num)state=2;
else if(let=='.')state=3;
else if(!sp)valid=false;
}
else if(state==1){//-After +/-. Expected values:[0-9,.]
if(num)state=2;
else if(let=='.')state=3;
else valid=false;
}
else if(state==2){//-After +/- and some number. Expected values:[0-9,.,e,E,\t, ]
if(let=='.')state=3;
else if(let=='e' || let=='E')state=10;
else if(sp)state=15;
else if(!num)valid=false;
}
else if(state==3){//-After decimal point. Expected values:[0-9,e,E,\t, ]
if(let=='e' || let=='E')state=10;
else if(sp)state=15;
else if(!num)valid=false;
}
else if(state==10){//-After e/E. Expected values:[+,-,0-9]
if(let=='+' || let=='-')state=11;
else if(num)state=12;
else valid=false;
}
else if(state==11){//-After e/E and +/-. Expected values:[0-9]
if(num)state=12;
else valid=false;
}
else if(state==12){//-After e/E and +/- and some number. Expected values:[0-9,\t, ]
if(sp)state=15;
else if(!num)valid=false;
}
else if(state==15 && !sp)valid=false; //-After some space. Expected values:[\t, ]
}
if(state==1 || state==10 || state==11)valid=false;
//printf("StrIsRealNumber(%s) => state:%d %s [%g]\n",str.c_str(),state,(valid? "Ok": "ERROR"),atof(str.c_str()));
return(valid);
}
//==============================================================================
/// Converts string to int value.
//==============================================================================
int StrToInt(const std::string &v){
return(atoi(v.c_str()));
}
//==============================================================================
/// Converts string to tint3 value.
//==============================================================================
tint3 StrToInt3(std::string v){
tint3 res=TInt3(0);
if(!v.empty())res.x=atoi(fun::StrSplit(",",v).c_str());
if(!v.empty())res.y=atoi(fun::StrSplit(",",v).c_str());
if(!v.empty())res.z=atoi(fun::StrSplit(",",v).c_str());
return(res);
}
//==============================================================================
/// Converts string to double value.
//==============================================================================
double StrToDouble(const std::string &v){
return(atof(v.c_str()));
}
//==============================================================================
/// Converts string to tdouble3 value.
//==============================================================================
tdouble3 StrToDouble3(std::string v){
tdouble3 res=TDouble3(0);
if(!v.empty())res.x=atof(fun::StrSplit(",",v).c_str());
if(!v.empty())res.y=atof(fun::StrSplit(",",v).c_str());
if(!v.empty())res.z=atof(fun::StrSplit(",",v).c_str());
return(res);
}
//==============================================================================
/// Gets string in uppercase.
//==============================================================================
std::string StrUpper(const std::string &cad){
std::string ret;
for(unsigned c=0;c<cad.length();c++)ret=ret+char(toupper(cad[c]));
return(ret);
}
//==============================================================================
/// Gets string in lowercase.
//==============================================================================
std::string StrLower(const std::string &cad){
std::string ret;
for(unsigned c=0;c<cad.length();c++)ret=ret+char(tolower(cad[c]));
return(ret);
}
//==============================================================================
/// Gets string without spaces at the beginning and end.
//==============================================================================
std::string StrTrim(const std::string &cad){
std::string ret;
int lsp=0,rsp=0;
for(int c=0;c<int(cad.length())&&cad[c]==' ';c++)lsp++;
for(int c=int(cad.length())-1;c<int(cad.length())&&cad[c]==' ';c--)rsp++;
int size=int(cad.length())-(lsp+rsp);
return(size>0? cad.substr(lsp,size): "");
}
//==============================================================================
/// Gets string without spaces at the beginning.
//==============================================================================
std::string StrTrimBegin(const std::string &cad){
std::string ret;
int lsp=0;
for(int c=0;c<int(cad.length())&&cad[c]==' ';c++)lsp++;
int size=int(cad.length())-(lsp);
return(size>0? cad.substr(lsp,size): "");
}
//==============================================================================
/// Gets string without spaces at the end.
//==============================================================================
std::string StrTrimEnd(const std::string &cad){
std::string ret;
int rsp=0;
for(int c=int(cad.length())-1;c<int(cad.length())&&cad[c]==' ';c--)rsp++;
int size=int(cad.length())-(rsp);
return(size>0? cad.substr(0,size): "");
}
//==============================================================================
/// Gets string without repeated spaces.
//==============================================================================
std::string StrTrimRepeated(const std::string &cad){
std::string ret;
bool lastsp=false;
for(int c=0;c<int(cad.length());c++){
const char let=cad[c];
if(!lastsp || let!=' '){
ret=ret+let;
lastsp=(let==' ');
}
}
return(ret);
}
//==============================================================================
/// Gets string without the character indicated.
//==============================================================================
std::string StrWithoutChar(const std::string &cad,char let){
std::string ret;
for(int c=0;c<int(cad.length());c++)if(cad[c]!=let)ret=ret+cad[c];
return(ret);
}
//==============================================================================
/// Gets string with the string indicated n times.
//==============================================================================
std::string StrRepeat(const std::string &cad,unsigned count){
std::string ret;
for(unsigned c=0;c<count;c++)ret=ret+cad;
return(ret);
}
//==============================================================================
/// Gets new string where all key substring was replaced by newcad.
//==============================================================================
std::string StrReplace(const std::string &cad,const std::string &key,const std::string &newcad){
std::string str=cad;
int posini=0;
int pos=int(str.substr(posini).find(key));
int c=0;
while(pos>=0){
//:printf("Replace pos:%d substr[%s]\n",posini+pos,str.substr(posini).c_str());
str=str.replace(posini+pos,key.length(),newcad);
//:printf(" str[%s]\n",str.c_str());
posini=posini+pos+int(newcad.length());
pos=int(str.substr(posini).find(key));
c++;
}
return(str);
}
//==============================================================================
/// Replaces C-style escape sequences by normal text ("\n" -> "\\n").
/// Escape sequences: \a, \b, \f, \n, \r, \t, \v, \\, \', \".
//==============================================================================
std::string StrAddSlashes(const std::string &cad){
std::string ret;
const int len=int(cad.length());
for(int c=0;c<len;c++){
switch(cad[c]){
case '\a': ret=ret+"\\a"; break;
case '\b': ret=ret+"\\b"; break;
case '\f': ret=ret+"\\f"; break;
case '\n': ret=ret+"\\n"; break;
case '\r': ret=ret+"\\r"; break;
case '\t': ret=ret+"\\t"; break;
case '\v': ret=ret+"\\v"; break;
case '\\': ret=ret+"\\\\"; break;
case '\'': ret=ret+"\\\'"; break;
case '\"': ret=ret+"\\\""; break;
default: ret=ret+cad[c];
}
}
return(ret);
}
//==============================================================================
/// Replaces text by C-style escape sequences ("\\n" -> "\n").
/// Escape sequences: \a, \b, \f, \n, \r, \t, \v, \\, \', \".
//==============================================================================
std::string StrStripSlashes(const std::string &cad){
std::string ret;
const int len=int(cad.length());
for(int c=0;c<len;c++){
if(cad[c]=='\\' && c+1<len){
switch(cad[c+1]){
case 'a': ret=ret+"\a"; c++; break;
case 'b': ret=ret+"\b"; c++; break;
case 'f': ret=ret+"\f"; c++; break;
case 'n': ret=ret+"\n"; c++; break;
case 'r': ret=ret+"\r"; c++; break;
case 't': ret=ret+"\t"; c++; break;
case 'v': ret=ret+"\v"; c++; break;
case '\\': ret=ret+"\\"; c++; break;
case '\'': ret=ret+"\'"; c++; break;
case '\"': ret=ret+"\""; c++; break;
default: ret=ret+cad[c];
}
}
else ret=ret+cad[c];
}
return(ret);
}
//==============================================================================
/// Inidicates if the string cad only contains characters in the string chars.
//==============================================================================
bool StrOnlyChars(const std::string &cad,const std::string &chars){
bool ok=true;
const unsigned nc=unsigned(chars.length());
for(int c=0;c<int(cad.length()) && ok;c++){
const char let=cad[c];
unsigned c2=0;
for(;c2<nc && chars[c2]!=let;c2++);
if(c2>=nc)ok=false;
}
return(ok);
}
//==============================================================================
/// Loads lines from text file. Returns error code (0 no error).
//==============================================================================
int StrFileToVector(const std::string &file,std::vector<std::string> &lines){
int error=0;
ifstream pf;
pf.open(file.c_str());
if(pf){
while(!pf.eof() && !error){
char buff[2048];
pf.getline(buff,2048);
string tx=buff;
lines.push_back(tx);
}
if(!pf.eof()&&pf.fail())error=1; //-Error: Failure reading data from file.
pf.close();
}
else error=2; //-Error: Cannot open the file.
return(error);
}
//==============================================================================
/// Saves lines in a new text file. Returns error code (0 no error).
//==============================================================================
int StrVectorToFile(const std::string &file,const std::vector<std::string> &lines){
int error=0;
fstream pf;
pf.open(file.c_str(),ios::binary|ios::out);
if(!pf)error=3; //-Error: File could not be opened.
else{
const unsigned rows=unsigned(lines.size());
for(unsigned r=0;r<rows && !error;r++){
string tx=lines[r]+"\n";
pf.write(tx.c_str(),tx.size());
if(pf.fail())error=4; //-Error: File writing failure.
}
pf.close();
}
return(error);
}
//==============================================================================
/// Returns error code from StrFileToVector() or StrVectorToFile() in string.
//==============================================================================
std::string StrFileError(int error){
switch(error){
case 1: return("Error: Failure reading data from file.");
case 2: return("Error: Cannot open the file.");
case 3: return("Error: File could not be opened.");
case 4: return("Error: File writing failure.");
}
return("Error: ???");
}
//==============================================================================
/// Returns the text untill the indicated mark and saves the rest in text format.
//==============================================================================
std::string StrSplit(const std::string mark,std::string &text){
const unsigned smark=unsigned(mark.size());
int tpos=int(text.find(mark));
std::string ret=(tpos>=0? text.substr(0,tpos): text);
text=(tpos>=0? text.substr(tpos+smark): "");
return(ret);
}
//==============================================================================
/// Returns the number of pieces of a string.
//==============================================================================
unsigned StrSplitCount(const std::string mark,std::string text){
const unsigned smark=unsigned(mark.size());
unsigned count=0;
while(!text.empty()){
int tpos=int(text.find(mark));
//std::string ret=(tpos>=0? text.substr(0,tpos): text);
text=(tpos>=0? text.substr(tpos+smark): "");
count++;
}
return(count);
}
//==============================================================================
/// Returns the indicated piece of a string.
//==============================================================================
std::string StrSplitValue(const std::string mark,std::string text,unsigned value){
const unsigned smark=unsigned(mark.size());
std::string ret="";
unsigned count=0;
while(!text.empty()){
int tpos=int(text.find(mark));
if(count==value){
ret=(tpos>=0? text.substr(0,tpos): text);
text="";
}
else text=(tpos>=0? text.substr(tpos+smark): "");
count++;
}
return(ret);
}
//==============================================================================
/// Loads string list in a vector and returns size of vector.
//==============================================================================
unsigned VectorSplitStr(const std::string mark,const std::string &text,std::vector<std::string> &vec){
std::string aux=text;
while(!aux.empty()){
std::string txv=StrSplit(mark,aux);
if(!txv.empty())vec.push_back(txv.c_str());
}
return((unsigned)vec.size());
}
//==============================================================================
/// Loads unsigned list in a vector and returns size of vector.
//==============================================================================
unsigned VectorSplitInt(const std::string mark,const std::string &text,std::vector<int> &vec){
std::string aux=text;
while(!aux.empty()){
std::string txv=StrSplit(mark,aux);
if(!txv.empty())vec.push_back(atoi(txv.c_str()));
}
return((unsigned)vec.size());
}
//==============================================================================
/// Loads double list in a vector and returns size of vector.
//==============================================================================
unsigned VectorSplitDouble(const std::string mark,const std::string &text,std::vector<double> &vec){
std::string aux=text;
while(!aux.empty()){
std::string txv=StrSplit(mark,aux);
if(!txv.empty())vec.push_back(atof(txv.c_str()));
}
return((unsigned)vec.size());
}
//==============================================================================
/// Find string in a string vector vector since first position.
/// Returns UINT_MAX when it was not found.
//==============================================================================
unsigned VectorFind(const std::string &key,const std::vector<std::string> &vec
,unsigned first)
{
unsigned c=first;
const unsigned size=unsigned(vec.size());
for(;c<size && vec[c]!=key;c++);
return(c<size? c: UINT_MAX);
}
//==============================================================================
/// Find string mask (using *, ?, |) in a string vector vector since first position.
/// Returns UINT_MAX when it was not found.
//==============================================================================
unsigned VectorFindMask(const std::string &keymask,const std::vector<std::string> &vec
,unsigned first)
{
unsigned ret=UINT_MAX;
const unsigned size=unsigned(vec.size());
for(unsigned c=first;c<size && ret==UINT_MAX;c++){
const string v=vec[c];
//printf("---> v:[%s] keymask:[%s]\n",v.c_str(),keymask.c_str());
const bool usemask=(int(keymask.find('?'))>=0 || int(keymask.find('*'))>=0 || int(keymask.find('|'))>=0);
if(!usemask && v==keymask)ret=c;
if(usemask && FileMask(v,keymask))ret=c;
//printf("---> usemask:%d FileMask:%d\n",(usemask?1:0),FileMask(v,keymask)?1:0);
}
return(ret);
}
//==============================================================================
/// Returns first double value after "pretex".
//==============================================================================
double GetFirstValueDouble(std::string tex,std::string pretex){
if(!pretex.empty()){//-Elimina texto previo si lo hubiera.
int pre=int(tex.find(pretex));
if(pre>=0)tex=tex.substr(pre);
}
int pini=int(strcspn(tex.c_str(),"0123456789-"));//-Localiza principio de numero.
tex=tex.substr(pini);
int len=int(strspn(tex.c_str(),"0123456789-."));//-Calcula longitud de numero.
return(atof(tex.substr(0,len).c_str()));
}
//==============================================================================
/// Returns first double value after "pretex" and returns the remaining text.
//==============================================================================
double GetFirstValueDouble(std::string tex,std::string &endtex,std::string pretex){
if(!pretex.empty()){//-Elimina texto previo si lo hubiera.
int pre=int(tex.find(pretex));
if(pre>=0)tex=tex.substr(pre);
}
int pini=int(strcspn(tex.c_str(),"0123456789-"));//-Localiza principio de numero.
tex=tex.substr(pini);
int len=int(strspn(tex.c_str(),"0123456789-."));//-Calcula longitud de numero.
endtex=tex.substr(len);
return(atof(tex.substr(0,len).c_str()));
}
//==============================================================================
/// Returns first int value after "pretex".
//==============================================================================
int GetFirstValueInt(std::string tex,std::string pretex){
if(!pretex.empty()){//-Elimina texto previo si lo hubiera.
int pre=int(tex.find(pretex));
if(pre>=0)tex=tex.substr(pre);
}
int pini=int(strcspn(tex.c_str(),"0123456789-"));//-Localiza principio de numero.
tex=tex.substr(pini);
int len=int(strspn(tex.c_str(),"0123456789-"));//-Calcula longitud de numero.
return(atoi(tex.substr(0,len).c_str()));
}
//==============================================================================
/// Returns first int value after "pretex" and returns the remaining text.
//==============================================================================
int GetFirstValueInt(std::string tex,std::string &endtex,std::string pretex){
if(!pretex.empty()){//-Elimina texto previo si lo hubiera.
int pre=int(tex.find(pretex));
if(pre>=0)tex=tex.substr(pre);
}
int pini=int(strcspn(tex.c_str(),"0123456789-"));//-Localiza principio de numero.
tex=tex.substr(pini);
int len=int(strspn(tex.c_str(),"0123456789-"));//-Calcula longitud de numero.
endtex=tex.substr(len);
return(atoi(tex.substr(0,len).c_str()));
}
//==============================================================================
/// Compares version numbers and returns -1:1<v2, 0:v1=v2, 1:v1>v2.
//==============================================================================
int CompareVersions(std::string v1,std::string v2){
int ret=0;
if(!v1.empty() && (v1[0]=='v' || v1[0]=='V'))v1=v1.substr(1);
if(!v2.empty() && (v2[0]=='v' || v2[0]=='V'))v2=v2.substr(1);
if(v1.empty() && v2.empty())ret=0;
else if(v1.empty())ret=-1;
else if(v2.empty())ret=1;
else{
vector<int> vv1,vv2;
fun::VectorSplitInt(".",v1,vv1);
fun::VectorSplitInt(".",v2,vv2);
const unsigned n1=unsigned(vv1.size());
const unsigned n2=unsigned(vv2.size());
const unsigned n=max(n1,n2);
for(unsigned c=0;c<n && !ret;c++){
const int a1=(c<n1? vv1[c]: 0);
const int a2=(c<n2? vv2[c]: 0);
if(a1<a2)ret=-1;
else if(a1>a2)ret=1;
}
}
return(ret);
}
//==============================================================================
/// Returns variable and its value in text format.
//==============================================================================
std::string VarStr(const std::string &name,const char *value){ return(name+"=\""+value+"\""); }
std::string VarStr(const std::string &name,const std::string &value){ return(name+"=\""+value+"\""); }
std::string VarStr(const std::string &name,float value){ return(name+"="+FloatStr(value)); }
std::string VarStr(const std::string &name,tfloat3 value){ return(name+"=("+FloatStr(value.x)+","+FloatStr(value.y)+","+FloatStr(value.z)+")"); }
std::string VarStr(const std::string &name,double value){ return(name+"="+DoubleStr(value)); }