-
Notifications
You must be signed in to change notification settings - Fork 141
Expand file tree
/
Copy pathUtilityFunctions.cpp
More file actions
1412 lines (1228 loc) · 36.9 KB
/
UtilityFunctions.cpp
File metadata and controls
1412 lines (1228 loc) · 36.9 KB
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
#include "StdAfx.h"
#include <iterator>
#include <fstream>
#include "macros.h"
#include <vector>
#include <algorithm>
#include <string>
// ReSharper disable CppUseAuto
namespace Utility
{
_locale_t m_locale = nullptr;
_locale_t GetLocale()
{
if (!m_locale) {
m_locale = _create_locale(LC_ALL, "C");
}
return m_locale;
}
#pragma region String conversion
// ********************************************************
// XmlFilenameToUnicode()
// ********************************************************
CStringW XmlFilenameToUnicode(CStringA s, bool utf8) {
USES_CONVERSION;
CStringW unicode = utf8 ? CA2W(s, CP_UTF8) : A2W(s);
return unicode;
}
// ********************************************************
// ConvertToUtf8()
// ********************************************************
CStringA ConvertToUtf8(CStringW unicode) {
USES_CONVERSION;
CStringA utf8 = CW2A(unicode, CP_UTF8);
return utf8;
}
// ********************************************************
// ConvertFromUtf8()
// ********************************************************
CStringW ConvertFromUtf8(CStringA utf8) {
USES_CONVERSION;
CStringW unicode = CA2W(utf8, CP_UTF8);
return unicode;
}
// ********************************************************
// StringToWideChar()
// ********************************************************
WCHAR* StringToWideChar(CString s)
{
WCHAR* wText = nullptr;
int size = MultiByteToWideChar(CP_ACP, 0, s.GetString(), -1, nullptr, 0);
wText = new WCHAR[size];
MultiByteToWideChar(CP_ACP, 0, s.GetString(), -1, wText, size);
return wText;
}
// ********************************************************
// SYS2A
// ********************************************************
//ConservesStackMemory
char* Utility::SYS2A(BSTR str)
{
USES_CONVERSION;
char* result = nullptr;
char* stackVersion = OLE2A(str);
if (stackVersion)
{
result = new char[_tcslen(stackVersion) + 1];
memcpy(result, stackVersion, _tcslen(stackVersion));
result[_tcslen(stackVersion)] = '\0';
}
else
{
result = new char[1];
result[0] = '\0';
}
return result;
}
// ********************************************************
// ConvertBSTRToLPSTR
// ********************************************************
//Rob Cairns 29-Aug-2009
char* ConvertBSTRToLPSTR(BSTR bstrIn, UINT codePage /* = CP_ACP */)
{
LPSTR pszOut = nullptr;
if (bstrIn != nullptr)
{
int nInputStrLen = SysStringLen(bstrIn);
// Double NULL Termination
int nOutputStrLen = WideCharToMultiByte(codePage, 0, bstrIn, nInputStrLen, nullptr, 0, nullptr, nullptr) + 2;
pszOut = new char[nOutputStrLen];
if (pszOut)
{
memset(pszOut, 0x00, sizeof(char) * nOutputStrLen);
WideCharToMultiByte(codePage, 0, bstrIn, nInputStrLen, pszOut, nOutputStrLen, nullptr, nullptr);
}
}
return pszOut;
}
// ********************************************************
// Variant2BSTR
// ********************************************************
// Converting variant to bstr; only several values are considered
// should be replaced by CComVariant.CopyTo
BSTR Variant2BSTR(VARIANT* val, CString floatFormat)
{
if (val->vt == VT_BSTR)
{
return OLE2BSTR(val->bstrVal);
}
else if (val->vt == VT_I4)
{
CString str;
str.Format("%d", val->lVal);
return str.AllocSysString();
}
else if (val->vt == VT_R8)
{
CString str;
str.Format(floatFormat, val->dblVal);
return str.AllocSysString();
}
else //if( val.vt == VT_NULL )
{
return A2BSTR("");
}
}
//from http://www.codeproject.com/Articles/260/Case-Insensitive-String-Replace
// instr: string to search in.
// oldstr: string to search for, ignoring the case.
// newstr: string replacing the occurrences of oldstr.
CString ReplaceNoCase(LPCTSTR instr, LPCTSTR oldstr, LPCTSTR newstr)
{
CString output(instr);
// lowercase-versions to search in.
CString input_lower(instr);
CString oldone_lower(oldstr);
input_lower.MakeLower();
oldone_lower.MakeLower();
// search in the lowercase versions,
// replace in the original-case version.
int pos = 0;
while ((pos = input_lower.Find(oldone_lower, pos)) != -1) {
// need for empty "newstr" cases.
input_lower.Delete(pos, lstrlen(oldstr));
input_lower.Insert(pos, newstr);
// actually replace.
output.Delete(pos, lstrlen(oldstr));
output.Insert(pos, newstr);
}
return output;
}
#pragma endregion
#pragma region Files
// *******************************************************************
// fileExists()
// *******************************************************************
BOOL Utility::FileExists(CString filename)
{
if (filename.GetLength() <= 0)
return FALSE;
FILE* file = fopen(filename, "rb");
if (file == nullptr)
return FALSE;
else
{
fclose(file);
return TRUE;
}
}
// *******************************************************************
// get_FileSize()
// *******************************************************************
long Utility::GetFileSize(CStringW filename)
{
if (filename.GetLength() <= 0)
return FALSE;
FILE* file = _wfopen(filename, L"rb");
long size = 0;
if (file)
{
fseek(file, 0, SEEK_END);
size = ftell(file);
fclose(file);
}
return size;
}
// *******************************************************************
// dirExists()
// *******************************************************************
bool DirExists(CStringW path)
{
DWORD ftyp = GetFileAttributesW(path);
if (ftyp == INVALID_FILE_ATTRIBUTES)
return false; //something is wrong with your path!
return (ftyp & FILE_ATTRIBUTE_DIRECTORY) ? true : false;
}
// *******************************************************************
// Utility::fileExistsW()
// *******************************************************************
bool FileExistsW(CStringW filename)
{
if (filename.GetLength() <= 0)
return FALSE;
FILE* file = _wfopen(filename, L"rb");
if (file == nullptr)
{
return false;
}
else
{
fclose(file);
return true;
}
}
// *******************************************************************
// Utility::fileExistsUnicode()
// *******************************************************************
bool Utility::FileExistsUnicode(CStringW filename)
{
if (filename.GetLength() <= 0)
return FALSE;
USES_CONVERSION;
FILE* file = _wfopen(filename, L"rb");
if (file == nullptr) {
return false;
}
fclose(file);
return true;
}
// returns list paths for all parent folders for current file from inner most to top most
void GetFoldersList(CStringW path, std::vector<CStringW>& list)
{
for (int i = path.GetLength() - 1; i >= 0; i--)
{
CStringW mid = path.Mid(i, 1);
if (mid == '\\' && i - 1 > 0)
{
list.push_back(path.Left(i));
}
}
}
// *********************************************************
// get_RelativePath()
// *********************************************************
CStringW Utility::GetRelativePath(CStringW ProjectName, CStringW Filename)
{
CStringW drive1, drive2;
wchar_t drive[1024];
wchar_t dir[1024];
wchar_t name[1024];
wchar_t ext[1024];
_wsplitpath(ProjectName, drive, dir, name, ext);
drive1 = drive;
_wsplitpath(Filename, drive, dir, name, ext);
drive2 = drive;
if (drive1 != drive2)
{
// files are on the different drives, no way to get a relative path
return Filename;
}
else
{
std::vector<CStringW> list1;
std::vector<CStringW> list2;
GetFoldersList(ProjectName, list1);
GetFoldersList(Filename, list2);
// searching for the match (inner-most folder common to both files)
unsigned int i, j;
for (i = 0; i < list1.size(); i++)
{
for (j = 0; j < list2.size(); j++)
{
if (_wcsicmp(list1[i], list2[j]) == 0)
{
goto match;
}
}
}
match:
CStringW path = L"";
for (unsigned int k = 0; k < i; k++)
{
// going to the parent folder
path += L"..\\";
}
// excluding folder part from the path
path += Filename.Mid(list1[i].GetLength() + 1);
return path;
}
}
// *********************************************************
// GetFolderFromPath()
// *********************************************************
CStringW Utility::GetFolderFromPath(CStringW path)
{
CStringW result = path;
for (int i = path.GetLength() - 1; i > 0; i--)
{
if (path.Mid(i, 1) == '\\')
{
result = path.Left(i); // -1
if (result.GetLength() == 2)
result += "\\";
break;
}
}
return result;
}
// *********************************************************
// GetNameFromPathWoExtension()
// *********************************************************
CStringW Utility::GetNameFromPathWoExtension(CStringW path)
{
path = GetNameFromPath(path);
return GetPathWOExtension(path);
}
// *********************************************************
// GetNameFromPath()
// *********************************************************
CStringW Utility::GetNameFromPath(CStringW path)
{
for (int i = path.GetLength() - 1; i > 0; i--)
{
if (path.Mid(i, 1) == '\\')
{
int length = path.GetLength() - 1 - i;
return length > 0 ? path.Right(length) : L"";
}
}
return path;
}
// *********************************************************
// EndsWith()
// *********************************************************
bool EndsWith(CStringW path, CStringW ext)
{
if (path.GetLength() < ext.GetLength() + 1 || ext.GetLength() < 2) {
return false;
}
else
{
return path.Right(ext.GetLength()).CompareNoCase(ext) == 0;
}
}
// *********************************************************
// GetPathWOExtension()
// *********************************************************
CStringW GetPathWOExtension(CStringW path)
{
for (int i = path.GetLength() - 1; i > 0; i--)
{
if (path.Mid(i, 1) == ".")
{
return path.Left(i);
}
}
return path;
}
// ****************************************************
// ReadFileToBuffer
// ****************************************************
// Reads the content of the file to buffer, return the number of bytes read
int ReadFileToBuffer(CStringW filename, unsigned char** buffer)
{
FILE* file = _wfopen(filename, L"rb");
long size = 0;
if (file)
{
fseek(file, 0, SEEK_END);
size = ftell(file);
if (size > 0)
{
*buffer = new unsigned char[size];
rewind(file);
size = fread(*buffer, sizeof(unsigned char), size, file);
}
fclose(file);
}
return size;
}
int ReadFileToBuffer(CStringW filename, char** buffer)
{
FILE* file = _wfopen(filename, L"rb");
long size = 0;
if (file)
{
fseek(file, 0, SEEK_END);
size = ftell(file);
if (size > 0)
{
*buffer = new char[size];
rewind(file);
size = fread(*buffer, sizeof(char), size, file);
}
fclose(file);
}
return size;
}
#define _SECOND ((__int64) 10000000)
// ********************************************************
// Utility::CompareCreationTime()
// ********************************************************
// returns: 1 = first file younger, -1 = vice versa, 0 = equal age; any other value = error
bool IsFileYounger(CStringW filename, CStringW thanFilename)
{
FILETIME time1, time2;
if (GetFileCreationTime(filename, time1) && GetFileCreationTime(thanFilename, time2))
{
// subtract several seconds
ULONGLONG qwResult;
// Copy the time into a quadword.
qwResult = (((ULONGLONG)time2.dwHighDateTime) << 32) + time2.dwLowDateTime;
// Add 30 days.
qwResult -= 10 * _SECOND;
// Copy the result back into the FILETIME structure.
time2.dwLowDateTime = (DWORD)(qwResult & 0xFFFFFFFF);
time2.dwHighDateTime = (DWORD)(qwResult >> 32);
int val = CompareFileTime(&time1, &time2);
return val == 1;
}
return false;
}
// ********************************************************
// Utility::get_FileCreationTime()
// ********************************************************
bool GetFileCreationTime(CStringW filename, FILETIME& time)
{
_WIN32_FILE_ATTRIBUTE_DATA data;
if (GetFileAttributesExW(filename, GetFileExInfoStandard, &data))
{
time = data.ftCreationTime;
return true;
}
return false;
}
// ********************************************************
// RemoveFile()
// ********************************************************
bool RemoveFile(CStringW filename)
{
if (Utility::FileExistsW(filename))
{
return _wremove(filename) == 0;
}
else {
return true; // no file and therefore no problem
}
}
// ********************************************************
// getProjectionFileName()
// ********************************************************
CStringW GetProjectionFilename(CStringW dataSourceName)
{
return ChangeExtension(dataSourceName, L"prj");
}
// ********************************************************
// ChangeExtension()
// ********************************************************
CStringW ChangeExtension(CStringW filename, CStringW ext)
{
int theDot = filename.ReverseFind('.');
if (theDot < 0)
return filename + ext;
return filename.Left(theDot + 1) + ext;
}
// ********************************************************
// GetTempFilename()
// ********************************************************
CString Utility::GetTempFilename(CString extensionWithLeadingPoint)
{
char* tmpfname = new char[MAX_BUFFER];
char* tmppath = new char[MAX_PATH + MAX_BUFFER + 1];
GetTempPath(MAX_PATH, tmppath);
//tmpnam(tmpfname);
// replacing tmpnam with the Windows call GetTempFileName
// because, at least under certain circumstances, tmpnam was
// returning a name including a path, which when concatenated
// with tmppath, resulted in an invalid filename.
::GetTempFileName(tmppath, "", 0, tmpfname);
//strcat(tmppath, tmpfname);
//strcat(tmppath, extensionWithLeadingPoint);
CString result = tmpfname;
result.MakeLower().Replace(".tmp", extensionWithLeadingPoint);
delete[] tmpfname;
delete[] tmppath;
return result;
}
#pragma endregion
#pragma region Unit conversion
// ****************************************************************
// GetLocalizedUnitsText()
// ****************************************************************
CStringW Utility::GetLocalizedUnitsText(tkUnitsOfMeasure units)
{
switch (units)
{
case umMiles:
return m_globalSettings.GetLocalizedString(tkLocalizedStrings::lsMiles);
case umFeets:
return m_globalSettings.GetLocalizedString(tkLocalizedStrings::lsFeet);
case umMeters:
return m_globalSettings.GetLocalizedString(tkLocalizedStrings::lsMeters);
case umKilometers:
return m_globalSettings.GetLocalizedString(tkLocalizedStrings::lsKilometers);
default:
USES_CONVERSION;
return A2W(Utility::GetUnitOfMeasureText(units));
}
}
// ****************************************************************
// GetUnitOfMeasureText
// ****************************************************************
// Returns the short name for units of measure
CString Utility::GetUnitOfMeasureText(tkUnitsOfMeasure units)
{
switch (units)
{
case umDecimalDegrees:
return "deg.";
case umMiliMeters:
return "mm";
case umCentimeters:
return "cm";
case umInches:
return "inches";
case umFeets:
return "feet";
case umYards:
return "yards";
case umMeters:
return "m";
case umMiles:
return "miles";
case umKilometers:
return "km";
default:
return "units";
}
}
// **********************************************************
// get_ConversionFactor()
// **********************************************************
/// Returns the conversion factor between the map units and inches
double Utility::GetConversionFactor(tkUnitsOfMeasure units)
{
switch (units)
{
// calculated considering sphere with radius 6378137 km, i.e. the one used WGS84/Google Mercator projection
// http://spatialreference.org/ref/sr-org/7483/html/
// cf = (2 * pi * R) / 360 / 0.0254
case umDecimalDegrees: return 4382657.117845416246;
case umMeters: return 39.3700787;
case umCentimeters: return 0.393700787;
case umFeets: return 12.0;
case umInches: return 1.0;
case umKilometers: return 39370.0787;
case umMiles: return 63360;
case umMiliMeters: return 0.0393700787;
case umYards: return 36.0;
default: return 0.0;
}
}
// **********************************************************
// ConvertDistance()
// **********************************************************
bool Utility::ConvertDistance(tkUnitsOfMeasure source, tkUnitsOfMeasure target, double& value)
{
value *= Utility::GetConversionFactor(source); // in inches
const double factor = Utility::GetConversionFactor(target);
if (factor != 0.0)
{
value /= factor;
return true;
}
value = 0.0;
return false;
}
#pragma endregion
#pragma region Numbers
double SquareMetersPerSquareMile()
{
return 2589975.2356;
}
double SquareMetersPerAcre()
{
return 4046.8564224; // according to International yard and pound agreement (1959)
}
double SquareMetersPerSquareFoot()
{
return 0.09290304;
}
// ****************************************************************
// FormatArea()
// ****************************************************************
CStringW Utility::FormatArea(double area, bool unknownUnits, tkAreaDisplayMode units, int precision)
{
CStringW str;
area = abs(area);
CStringW format = GetUnitsFormat(precision);
if (!unknownUnits)
{
tkLocalizedStrings localizedUnits;
switch (units)
{
case admMetric:
{
if (area < 1000.0)
{
localizedUnits = lsSquareMeters;
}
else if (area < 10000000.0)
{
area /= 10000.0;
localizedUnits = lsHectars;
}
else
{
area /= 1000000.0;
localizedUnits = lsSquareKilometers;
}
break;
}
case admHectars:
{
area /= 10000.0;
localizedUnits = lsHectars;
break;
}
case admAmerican:
{
double area2 = area / SquareMetersPerSquareMile();
localizedUnits = lsSquareMiles;
if (area2 < 100.0)
{
area2 = area / SquareMetersPerAcre();
localizedUnits = lsAcres;
if (area2 < 1.0)
{
area2 = area / SquareMetersPerSquareFoot();
localizedUnits = lsSquareFeet;
}
}
area = area2;
break;
}
default:
return str;
}
str.Format(format, area, m_globalSettings.GetLocalizedString(localizedUnits));
}
else
{
str.Format(format, area, m_globalSettings.GetLocalizedString(tkLocalizedStrings::lsSquareMapUnits));
}
return str;
}
// *********************************************************
// GetNumberFormat()
// *********************************************************
CStringW Utility::GetUnitsFormat(int precision)
{
CStringW temp;
temp.Format(L"%d", precision);
return L"%." + temp + L"f %s";
}
// *********************************************************
// FormatNumber()
// *********************************************************
CString Utility::FormatNumber(double val, CString& sFormat)
{
CString s;
if (val > 1000000000.0 && val < 1000000000000.0)
{
s.Format("%.2f", val / 1000000000.0);
if (s.GetLength() > 5)
s.Delete(5, 1);
s += "b";
}
else if (val > 1000000.0)
{
s.Format("%.2f", val / 1000000.0);
if (s.GetLength() > 5)
s.Delete(5, 1);
s += "m";
}
else if (val > 1000.0)
{
s.Format("%.2f", val / 1000.0);
if (s.GetLength() > 5)
s.Delete(5, 1);
s += "k";
}
else
{
s.Format(sFormat, val);
}
return s;
}
// *********************************************************
// Shade1974 Jan 10, 2006
// Explicit casting to int using rounding
// *********************************************************
int Utility::Rint(double value)
{
if (value < 0.0)
value -= 0.5;
else
value += 0.5;
int val = static_cast<int>(value);
return val;
}
// *********************************************************
// Factorial()
// *********************************************************
int Utility::Factorial(int n)
{
int ret = 1;
for (int i = 1; i <= n; ++i)
ret *= i;
return ret;
}
// *********************************************************
// atof_custom()
// *********************************************************
double atof_custom(CString s)
{
// as long as global locale set to std::locale("C") in MapWinGIS.cpp
// it's enough just to replace , by .
// if user defined locale would be used std::locale("") the logic should be more complex
s.Replace(',', '.');
double val = _atof_l(s, m_locale);
return val;
}
double wtof_custom(CStringW s)
{
// as long as global locale set to std::locale("C") in MapWinGIS.cpp
// it's enough just to replace , by .
// if user defined locale would be used std::locale("") the logic should be more complex
s.Replace(',', '.');
double val = _wtof_l(s, m_locale);
return val;
}
double FloatRound(double doValue, int nPrecision)
{
static const double doBase = 10.0;
double doComplete5, doComplete5i;
doComplete5 = doValue * pow(doBase, (double)(nPrecision + 1));
if (doValue < 0.0)
doComplete5 -= 5.0;
else
doComplete5 += 5.0;
doComplete5 /= doBase;
modf(doComplete5, &doComplete5i);
return doComplete5i / pow(doBase, (double)nPrecision);
}
bool FloatsEqual(const float& a, const float& b)
{
return (fabs(a - b) <= 1.0e-20f);
}
#pragma endregion
#pragma region Gdi
// ***********************************************************
// GetEncoderClsid()
// ***********************************************************
// Returns encoder for the specified image format
// The following call should be used for PNG fromat, for example: GetEncoderClsid(L"png", &pngClsid);
int Utility::GetEncoderClsid(const WCHAR* format, CLSID* pClsid)
{
UINT num = 0; // number of image encoders
UINT size = 0; // size of the image encoder array in bytes
Gdiplus::ImageCodecInfo* pImageCodecInfo = nullptr;
Gdiplus::GetImageEncodersSize(&num, &size);
if (size == 0)
return -1; // Failure
pImageCodecInfo = (Gdiplus::ImageCodecInfo*)(malloc(size));
if (pImageCodecInfo == nullptr)
return -1; // Failure
GetImageEncoders(num, size, pImageCodecInfo);
for (UINT j = 0; j < num; ++j)
{
if (wcscmp(pImageCodecInfo[j].MimeType, format) == 0)
{
*pClsid = pImageCodecInfo[j].Clsid;
free(pImageCodecInfo);
return j; // Success
}
}
free(pImageCodecInfo);
return -1; // Failure
}
Gdiplus::Font* GetGdiPlusFont(CString name, float size)
{
WCHAR* wFontName = StringToWideChar("Arial");
Gdiplus::FontFamily family(wFontName);
Gdiplus::Font* font = new Gdiplus::Font(&family, (Gdiplus::REAL)size);
delete wFontName;
return font;
}
void Utility::ClosePointer(Gdiplus::Bitmap** ptr)
{
if (*ptr) {
delete* ptr;
*ptr = nullptr;
}
}
void Utility::ClosePointer(Gdiplus::Font** ptr)
{
if (*ptr) {
delete* ptr;
*ptr = nullptr;
}
}
// **************************************************
// SaveBitmap
// **************************************************
// Saves provided array of pixels as png image (uses GDI+)
bool Utility::SaveBitmap(int width, int height, unsigned char* pixels, BSTR outputName)
{
int pad = (width * 24) % 32;
if (pad != 0)
{
pad = 32 - pad;
pad /= 8;
}
BITMAPINFOHEADER bih;
bih.biCompression = 0;
bih.biXPelsPerMeter = 0;
bih.biYPelsPerMeter = 0;
bih.biClrUsed = 0;
bih.biClrImportant = 0;
bih.biPlanes = 1;
bih.biSize = sizeof(BITMAPINFOHEADER);
bih.biBitCount = 24;
bih.biWidth = width;
bih.biHeight = height;
bih.biSizeImage = (width * 3 + pad) * height;
BITMAPINFO bif;
bif.bmiHeader = bih;
int nBytesInRow = width * 3 + pad;
// copying bits
unsigned char* bitsNew = new unsigned char[nBytesInRow * height];
for (int i = 0; i < height; i++)
memcpy(&bitsNew[i * nBytesInRow], &pixels[i * width * 3], width * 3);
// saing the image
Gdiplus::Bitmap* bmp = new Gdiplus::Bitmap(&bif, (void*)bitsNew);
CLSID pngClsid;
GetEncoderClsid(L"png", &pngClsid); // perhaps some other formats ?
USES_CONVERSION;
Gdiplus::Status status = bmp->Save(OLE2W(outputName), &pngClsid, nullptr);
if (bmp)
{
delete bmp;
}
if (bitsNew)
{
delete[] bitsNew;
}
return (status == Gdiplus::Ok);
}
DWORD* Utility::cvtUCharToDword(long inp, int& num)
{ /* Chris Michaelis and Michelle Hospodarsky 2-11-2004 */
/* this function creates a DWORD[] from a long : used to create the custom pen for a custom stipple*/
/* the first digit in inp is the multiplier for the remainder of the digits */
std::vector<long> temp;
int multiplier;
char inpStr[33];
_ltoa(inp, inpStr, 10);
int iter = 0;
for (; inpStr[iter] != 0; iter++)
{
temp.push_back(inpStr[iter]);
}