forked from cataclysmbnteam/Cataclysm-BN
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cata_utility.cpp
774 lines (663 loc) · 20.7 KB
/
cata_utility.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
#include "cata_utility.h"
#include "fstream_utils.h"
#include <cctype>
#include <cmath>
#include <cstdio>
#include <exception>
#include <fstream>
#include <iterator>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <string>
#include "debug.h"
#include "enum_conversions.h"
#include "filesystem.h"
#include "json.h"
#include "options.h"
#include "output.h"
#include "rng.h"
#include "translations.h"
#include "units.h"
#if defined (_WIN32) && !defined (_MSC_VER)
#include <ext/stdio_filebuf.h>
#endif
static double pow10( unsigned int n )
{
double ret = 1;
double tmp = 10;
while( n ) {
if( n & 1 ) {
ret *= tmp;
}
tmp *= tmp;
n >>= 1;
}
return ret;
}
double round_up( double val, unsigned int dp )
{
// Some implementations of std::pow does not return the accurate result even
// for small powers of 10, so we use a specialized routine to calculate them.
const double denominator = pow10( dp );
return std::ceil( denominator * val ) / denominator;
}
int modulo( int v, int m )
{
// C++11: negative v and positive m result in negative v%m (or 0),
// but this is supposed to be mathematical modulo: 0 <= v%m < m,
const int r = v % m;
// Adding m in that (and only that) case.
return r >= 0 ? r : r + ( m * ( 1 - r / m ) );
}
bool isBetween( int test, int down, int up )
{
return test > down && test < up;
}
// --- Library functions ---
// This stuff could be moved elsewhere, but there
// doesn't seem to be a good place to put it right now.
double logarithmic( double t )
{
return 1 / ( 1 + std::exp( -t ) );
}
double logarithmic_range( int min, int max, int pos )
{
const double LOGI_CUTOFF = 4;
const double LOGI_MIN = logarithmic( -LOGI_CUTOFF );
const double LOGI_MAX = logarithmic( +LOGI_CUTOFF );
const double LOGI_RANGE = LOGI_MAX - LOGI_MIN;
if( min >= max ) {
debugmsg( "Invalid interval (%d, %d).", min, max );
return 0.0;
}
// Anything beyond (min,max) gets clamped.
if( pos <= min ) {
return 1.0;
} else if( pos >= max ) {
return 0.0;
}
// Normalize the pos to [0,1]
double range = max - min;
double unit_pos = ( pos - min ) / range;
// Scale and flip it to [+LOGI_CUTOFF,-LOGI_CUTOFF]
double scaled_pos = LOGI_CUTOFF - 2 * LOGI_CUTOFF * unit_pos;
// Get the raw logistic value.
double raw_logistic = logarithmic( scaled_pos );
// Scale the output to [0,1]
return ( raw_logistic - LOGI_MIN ) / LOGI_RANGE;
}
double normal_cdf( double x, double mean, double stddev )
{
return 0.5 * ( 1.0 + std::erf( ( x - mean ) / ( stddev * M_SQRT2 ) ) );
}
int bound_mod_to_vals( int val, int mod, int max, int min )
{
if( val + mod > max && max != 0 ) {
mod = std::max( max - val, 0 );
}
if( val + mod < min && min != 0 ) {
mod = std::min( min - val, 0 );
}
return mod;
}
double clamp_to_width( double value, int width, int &scale )
{
return clamp_to_width( value, width, scale, nullptr );
}
double clamp_to_width( double value, int width, int &scale, bool *out_truncated )
{
if( out_truncated != nullptr ) {
*out_truncated = false;
}
if( value >= std::pow( 10.0, width ) ) {
// above the maximum number we can fit in the width without decimal
// show the biggest number we can without decimal
// flag as truncated
value = std::pow( 10.0, width ) - 1.0;
scale = 0;
if( out_truncated != nullptr ) {
*out_truncated = true;
}
} else if( scale > 0 ) {
for( int s = 1; s <= scale; s++ ) {
// 1 decimal separator + "s"
int scale_width = 1 + s;
if( width > scale_width && value >= std::pow( 10.0, width - scale_width ) ) {
// above the maximum number we can fit in the width with "s" decimals
// show this number with one less decimal than "s"
scale = s - 1;
break;
}
}
}
return value;
}
float multi_lerp( const std::vector<std::pair<float, float>> &points, float x )
{
size_t i = 0;
while( i < points.size() && points[i].first <= x ) {
i++;
}
if( i == 0 ) {
return points.front().second;
} else if( i >= points.size() ) {
return points.back().second;
}
// How far are we along the way from last threshold to current one
const float t = ( x - points[i - 1].first ) /
( points[i].first - points[i - 1].first );
// Linear interpolation of values at relevant thresholds
return ( t * points[i].second ) + ( ( 1 - t ) * points[i - 1].second );
}
static std::ios_base::openmode cata_ios_mode_to_std( std::ios_base::openmode dir, cata_ios_mode m )
{
std::ios_base::openmode ret = dir;
if( static_cast<int>( m ) & static_cast<int>( cata_ios_mode::binary ) ) {
ret |= std::ios_base::binary;
}
if( static_cast<int>( m ) & static_cast<int>( cata_ios_mode::app ) ) {
ret |= std::ios_base::app;
}
return ret;
}
#if defined (_WIN32) && !defined (_MSC_VER)
// On Linux/MacOS, UTF-8 paths work out of the box, and we pass the string as is.
// On Windows, narrow API does not recognize paths encoded with UTF-8,
// so we have to jump through hoops to use wide API:
// * with Visual Studio, there's a non-standard fstream constructor that
// accepts wstring for path; we just need to convert UTF-8 to UTF-16.
// * when cross-compiling with mingw64, there's a non-standard __gnu_cxx::stdio_filebuf
// that allows creating fstream from FILE, and _wfopen that allows opening FILE
// using wide string for path.
// Although Windows 10 insider build 17035 (November 2017) enables narrow API to use UTF-8
// paths, we can't rely on it here for backwards compatibility.
static std::wstring cata_ios_mode_to_c( bool out, cata_ios_mode m )
{
std::wstring ret;
if( out ) {
if( static_cast<int>( m ) & static_cast<int>( cata_ios_mode::app ) ) {
ret = L"a";
} else {
ret = L"w";
}
} else {
ret = L"r";
}
if( static_cast<int>( m ) & static_cast<int>( cata_ios_mode::binary ) ) {
ret += L"b";
}
return ret;
}
cata_ofstream &cata_ofstream::operator=( cata_ofstream &&x )
{
_stream = std::move( x._stream );
_buffer = std::move( x._buffer );
_file = x._file;
x._file = nullptr;
_mode = x._mode;
return *this;
}
cata_ofstream &cata_ofstream::open( const std::string &path )
{
std::wstring mode = cata_ios_mode_to_c( true, _mode );
_file = _wfopen( utf8_to_wstr( path ).c_str(), mode.c_str() );
if( !_file ) {
// failed
return *this;
}
std::ios_base::openmode smode = cata_ios_mode_to_std( std::ios_base::out, _mode );
_buffer = std::make_unique<__gnu_cxx::stdio_filebuf<char>>( _file, smode );
_stream = std::make_unique<std::ostream>( &*_buffer );
return *this;
}
bool cata_ofstream::is_open()
{
return _file;
}
void cata_ofstream::close()
{
if( _stream ) {
_stream->flush();
_stream.reset();
}
_buffer.reset();
if( _file ) {
fclose( _file );
_file = nullptr;
}
}
#else // defined (_WIN32) && !defined (_MSC_VER)
cata_ofstream &cata_ofstream::operator=( cata_ofstream &&x )
{
_stream = std::move( x._stream );
_mode = x._mode;
return *this;
}
cata_ofstream &cata_ofstream::open( const std::string &path )
{
std::ios_base::openmode mode = cata_ios_mode_to_std( std::ios_base::out, _mode );
#if defined (_MSC_VER)
_stream = std::make_unique<std::ofstream>( utf8_to_wstr( path ), mode );
#else
_stream = std::make_unique<std::ofstream>( path, mode );
#endif
return *this;
}
bool cata_ofstream::is_open()
{
return _stream && _stream->is_open();
}
void cata_ofstream::close()
{
if( _stream ) {
_stream->close();
_stream.reset();
}
}
#endif // defined (_WIN32) && !defined (_MSC_VER)
cata_ofstream::cata_ofstream() = default;
cata_ofstream::cata_ofstream( cata_ofstream &&x )
{
*this = std::move( x );
}
cata_ofstream::~cata_ofstream()
{
close();
}
bool cata_ofstream::fail()
{
return !_stream || _stream->fail();
}
bool cata_ofstream::bad()
{
return !_stream || _stream->bad();
}
void cata_ofstream::flush()
{
_stream->flush();
}
std::ostream &cata_ofstream::operator*()
{
return *_stream;
}
std::ostream *cata_ofstream::operator->()
{
return &*_stream;
}
#if defined (_WIN32) && !defined (_MSC_VER)
cata_ifstream &cata_ifstream::operator=( cata_ifstream &&x )
{
_stream = std::move( x._stream );
_buffer = std::move( x._buffer );
_file = x._file;
x._file = nullptr;
_mode = x._mode;
return *this;
}
cata_ifstream &cata_ifstream::open( const std::string &path )
{
std::wstring mode = cata_ios_mode_to_c( false, _mode );
_file = _wfopen( utf8_to_wstr( path ).c_str(), mode.c_str() );
if( !_file ) {
// failed
return *this;
}
std::ios_base::openmode smode = cata_ios_mode_to_std( std::ios_base::in, _mode );
_buffer = std::make_unique<__gnu_cxx::stdio_filebuf<char>>( _file, smode );
_stream = std::make_unique<std::istream>( &*_buffer );
return *this;
}
bool cata_ifstream::is_open()
{
return _file;
}
void cata_ifstream::close()
{
if( _stream ) {
_stream.reset();
}
_buffer.reset();
if( _file ) {
fclose( _file );
_file = nullptr;
}
}
#else // defined (_WIN32) && !defined (_MSC_VER)
cata_ifstream &cata_ifstream::operator=( cata_ifstream &&x )
{
_stream = std::move( x._stream );
_mode = x._mode;
return *this;
}
cata_ifstream &cata_ifstream::open( const std::string &path )
{
std::ios_base::openmode mode = cata_ios_mode_to_std( std::ios_base::in, _mode );
#if defined (_MSC_VER)
_stream = std::make_unique<std::ifstream>( utf8_to_wstr( path ), mode );
#else
_stream = std::make_unique<std::ifstream>( path, mode );
#endif
return *this;
}
bool cata_ifstream::is_open()
{
return _stream && _stream->is_open();
}
void cata_ifstream::close()
{
if( _stream ) {
_stream->close();
_stream.reset();
}
}
#endif // defined (_WIN32) && !defined (_MSC_VER)
cata_ifstream::cata_ifstream() = default;
cata_ifstream::cata_ifstream( cata_ifstream &&x )
{
*this = std::move( x );
}
cata_ifstream::~cata_ifstream()
{
close();
}
bool cata_ifstream::fail()
{
return !_stream || _stream->fail();
}
bool cata_ifstream::bad()
{
return !_stream || _stream->bad();
}
std::istream &cata_ifstream::operator*()
{
return *_stream;
}
std::istream *cata_ifstream::operator->()
{
return &*_stream;
}
void write_to_file( const std::string &path, const std::function<void( std::ostream & )> &writer )
{
// Any of the below may throw. ofstream_wrapper will clean up the temporary path on its own.
ofstream_wrapper fout( path, cata_ios_mode::binary );
writer( fout.stream() );
fout.close();
}
bool write_to_file( const std::string &path, const std::function<void( std::ostream & )> &writer,
const char *const fail_message )
{
try {
write_to_file( path, writer );
return true;
} catch( const std::exception &err ) {
if( fail_message ) {
popup( _( "Failed to write %1$s to \"%2$s\": %3$s" ), fail_message, path.c_str(), err.what() );
}
return false;
}
}
ofstream_wrapper::ofstream_wrapper( const std::string &path, const cata_ios_mode mode )
: path( path )
{
open( mode );
}
ofstream_wrapper::~ofstream_wrapper()
{
try {
close();
} catch( ... ) {
// ignored in destructor
}
}
std::istream &safe_getline( std::istream &ins, std::string &str )
{
str.clear();
std::istream::sentry se( ins, true );
std::streambuf *sb = ins.rdbuf();
while( true ) {
int c = sb->sbumpc();
switch( c ) {
case '\n':
return ins;
case '\r':
if( sb->sgetc() == '\n' ) {
sb->sbumpc();
}
return ins;
case EOF:
if( str.empty() ) {
ins.setstate( std::ios::eofbit );
}
return ins;
default:
str += static_cast<char>( c );
}
}
}
bool read_from_file( const std::string &path, const std::function<void( std::istream & )> &reader )
{
try {
cata_ifstream fin = std::move( cata_ifstream().mode( cata_ios_mode::binary ).open( path ) );
if( !fin.is_open() ) {
throw std::runtime_error( "opening file failed" );
}
reader( *fin );
if( fin.bad() ) {
throw std::runtime_error( "reading file failed" );
}
return true;
} catch( const std::exception &err ) {
debugmsg( _( "Failed to read from \"%1$s\": %2$s" ), path.c_str(), err.what() );
return false;
}
}
bool read_from_file_json( const std::string &path, const std::function<void( JsonIn & )> &reader )
{
return read_from_file( path, [&]( std::istream & fin ) {
JsonIn jsin( fin, path );
reader( jsin );
} );
}
bool read_from_file( const std::string &path, JsonDeserializer &reader )
{
return read_from_file_json( path, [&reader]( JsonIn & jsin ) {
reader.deserialize( jsin );
} );
}
bool read_from_file_optional( const std::string &path,
const std::function<void( std::istream & )> &reader )
{
// Note: slight race condition here, but we'll ignore it. Worst case: the file
// exists and got removed before reading it -> reading fails with a message
// Or file does not exists, than everything works fine because it's optional anyway.
return file_exist( path ) && read_from_file( path, reader );
}
bool read_from_file_optional_json( const std::string &path,
const std::function<void( JsonIn & )> &reader )
{
return read_from_file_optional( path, [&]( std::istream & fin ) {
JsonIn jsin( fin, path );
reader( jsin );
} );
}
bool read_from_file_optional( const std::string &path, JsonDeserializer &reader )
{
return read_from_file_optional_json( path, [&reader]( JsonIn & jsin ) {
reader.deserialize( jsin );
} );
}
void ofstream_wrapper::open( cata_ios_mode mode )
{
if( dir_exist( path ) ) {
throw std::runtime_error( "target path is a directory" );
}
// Create a *unique* temporary path. No other running program should
// use this path. If the file exists, it must be of a *former* program
// instance and can savely be deleted.
temp_path = path + "." + get_pid_string() + ".temp";
if( file_exist( temp_path ) ) {
remove_file( temp_path );
}
file_stream = std::move( cata_ofstream().mode( mode ).open( temp_path ) );
if( !file_stream.is_open() ) {
throw std::runtime_error( "opening file failed" );
}
}
void ofstream_wrapper::close()
{
if( !file_stream.is_open() ) {
return;
}
file_stream.flush();
bool failed = file_stream.fail();
file_stream.close();
if( failed ) {
// Remove the incomplete or otherwise faulty file (if possible).
// Failures from it are ignored as we can't really do anything about them.
remove_file( temp_path );
throw std::runtime_error( "writing to file failed" );
}
if( !rename_file( temp_path, path ) ) {
// Leave the temp path, so the user can move it if possible.
throw std::runtime_error( "moving temporary file \"" + temp_path + "\" failed" );
}
}
std::string obscure_message( const std::string &str, std::function<char()> f )
{
//~ translators: place some random 1-width characters here in your language if possible, or leave it as is
std::string gibberish_narrow = _( "abcdefghijklmnopqrstuvwxyz" );
std::string gibberish_wide =
//~ translators: place some random 2-width characters here in your language if possible, or leave it as is
_( "に坂索トし荷測のンおク妙免イロコヤ梅棋厚れ表幌" );
std::wstring w_gibberish_narrow = utf8_to_wstr( gibberish_narrow );
std::wstring w_gibberish_wide = utf8_to_wstr( gibberish_wide );
std::wstring w_str = utf8_to_wstr( str );
// a trailing NULL terminator is necessary for utf8_width function
char transformation[2] = { 0 };
for( size_t i = 0; i < w_str.size(); ++i ) {
transformation[0] = f();
std::string this_char = wstr_to_utf8( std::wstring( 1, w_str[i] ) );
if( transformation[0] == -1 ) {
continue;
} else if( transformation[0] == 0 ) {
if( utf8_width( this_char ) == 1 ) {
w_str[i] = random_entry( w_gibberish_narrow );
} else {
w_str[i] = random_entry( w_gibberish_wide );
}
} else {
// Only support the case e.g. replace current character to symbols like # or ?
if( utf8_width( transformation ) != 1 ) {
debugmsg( "target character isn't narrow" );
}
// A 2-width wide character in the original string should be replace by two narrow characters
w_str.replace( i, 1, utf8_to_wstr( std::string( utf8_width( this_char ), transformation[0] ) ) );
}
}
std::string result = wstr_to_utf8( w_str );
if( utf8_width( str ) != utf8_width( result ) ) {
debugmsg( "utf8_width differ between original string and obscured string" );
}
return result;
}
std::string serialize_wrapper( const std::function<void( JsonOut & )> &callback )
{
std::ostringstream buffer;
JsonOut jsout( buffer );
callback( jsout );
return buffer.str();
}
void deserialize_wrapper( const std::function<void( JsonIn & )> &callback, const std::string &data )
{
std::istringstream buffer( data );
JsonIn jsin( buffer );
callback( jsin );
}
/* compare against table of easter dates */
static bool is_easter( int day, int month, int year )
{
if( month == 3 ) {
switch( year ) {
// *INDENT-OFF*
case 2024: return day == 31;
case 2027: return day == 28;
default: break;
// *INDENT-ON*
}
} else if( month == 4 ) {
switch( year ) {
// *INDENT-OFF*
case 2021: return day == 4;
case 2022: return day == 17;
case 2023: return day == 9;
case 2025: return day == 20;
case 2026: return day == 5;
case 2028: return day == 16;
case 2029: return day == 1;
case 2030: return day == 21;
default: break;
// *INDENT-ON*
}
}
return false;
}
holiday get_holiday_from_time( std::time_t time, bool force_refresh )
{
static holiday cached_holiday = holiday::none;
static bool is_cached = false;
if( force_refresh ) {
is_cached = false;
}
if( is_cached ) {
return cached_holiday;
}
is_cached = true;
bool success = false;
std::tm local_time;
std::time_t current_time = time == 0 ? std::time( nullptr ) : time;
/* necessary to pass LGTM, as threadsafe version of localtime differs by platform */
#if defined(_WIN32)
errno_t err = localtime_s( &local_time, ¤t_time );
if( err == 0 ) {
success = true;
}
#else
success = !!localtime_r( ¤t_time, &local_time );
#endif
if( success ) {
const int month = local_time.tm_mon + 1;
const int day = local_time.tm_mday;
const int wday = local_time.tm_wday;
const int year = local_time.tm_year + 1900;
/* check date against holidays */
if( month == 1 && day == 1 ) {
cached_holiday = holiday::new_year;
return cached_holiday;
}
// only run easter date calculation if currently March or April
else if( ( month == 3 || month == 4 ) && is_easter( day, month, year ) ) {
cached_holiday = holiday::easter;
return cached_holiday;
} else if( month == 7 && day == 4 ) {
cached_holiday = holiday::independence_day;
return cached_holiday;
}
// 13 days seems appropriate for Halloween
else if( month == 10 && day >= 19 ) {
cached_holiday = holiday::halloween;
return cached_holiday;
} else if( month == 11 && ( day >= 22 && day <= 28 ) && wday == 4 ) {
cached_holiday = holiday::thanksgiving;
return cached_holiday;
}
// For the 12 days of Christmas, my true love gave to me...
else if( month == 12 && ( day >= 14 && day <= 25 ) ) {
cached_holiday = holiday::christmas;
return cached_holiday;
}
}
// fall through to here if localtime fails, or none of the day tests hit
cached_holiday = holiday::none;
return cached_holiday;
}