-
-
Notifications
You must be signed in to change notification settings - Fork 842
/
strings.cpp
2190 lines (1882 loc) · 72.7 KB
/
strings.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
/*
* This file is part of OpenTTD.
* OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
* OpenTTD 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 General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file strings.cpp Handling of translated strings. */
#include "stdafx.h"
#include "currency.h"
#include "station_base.h"
#include "town.h"
#include "waypoint_base.h"
#include "depot_base.h"
#include "industry.h"
#include "newgrf_text.h"
#include "fileio_func.h"
#include "signs_base.h"
#include "fontdetection.h"
#include "error.h"
#include "strings_func.h"
#include "rev.h"
#include "core/endian_func.hpp"
#include "date_func.h"
#include "vehicle_base.h"
#include "engine_base.h"
#include "language.h"
#include "townname_func.h"
#include "string_func.h"
#include "company_base.h"
#include "smallmap_gui.h"
#include "window_func.h"
#include "debug.h"
#include "game/game_text.hpp"
#include "network/network_content_gui.h"
#include <stack>
#include "table/strings.h"
#include "table/control_codes.h"
#include "safeguards.h"
std::string _config_language_file; ///< The file (name) stored in the configuration.
LanguageList _languages; ///< The actual list of language meta data.
const LanguageMetadata *_current_language = nullptr; ///< The currently loaded language.
TextDirection _current_text_dir; ///< Text direction of the currently selected language.
#ifdef WITH_ICU_I18N
std::unique_ptr<icu::Collator> _current_collator; ///< Collator for the language currently in use.
#endif /* WITH_ICU_I18N */
static uint64 _global_string_params_data[20]; ///< Global array of string parameters. To access, use #SetDParam.
static WChar _global_string_params_type[20]; ///< Type of parameters stored in #_global_string_params
StringParameters _global_string_params(_global_string_params_data, 20, _global_string_params_type);
/** Reset the type array. */
void StringParameters::ClearTypeInformation()
{
assert(this->type != nullptr);
MemSetT(this->type, 0, this->num_param);
}
/**
* Read an int64 from the argument array. The offset is increased
* so the next time GetInt64 is called the next value is read.
*/
int64 StringParameters::GetInt64(WChar type)
{
if (this->offset >= this->num_param) {
Debug(misc, 0, "Trying to read invalid string parameter");
return 0;
}
if (this->type != nullptr) {
if (this->type[this->offset] != 0 && this->type[this->offset] != type) {
Debug(misc, 0, "Trying to read string parameter with wrong type");
return 0;
}
this->type[this->offset] = type;
}
return this->data[this->offset++];
}
/**
* Set DParam n to some number that is suitable for string size computations.
* @param n Index of the string parameter.
* @param max_value The biggest value which shall be displayed.
* For the result only the number of digits of \a max_value matter.
* @param min_count Minimum number of digits independent of \a max.
* @param size Font of the number
*/
void SetDParamMaxValue(uint n, uint64 max_value, uint min_count, FontSize size)
{
uint num_digits = 1;
while (max_value >= 10) {
num_digits++;
max_value /= 10;
}
SetDParamMaxDigits(n, std::max(min_count, num_digits), size);
}
/**
* Set DParam n to some number that is suitable for string size computations.
* @param n Index of the string parameter.
* @param count Number of digits which shall be displayable.
* @param size Font of the number
*/
void SetDParamMaxDigits(uint n, uint count, FontSize size)
{
uint front = 0;
uint next = 0;
GetBroadestDigit(&front, &next, size);
uint64 val = count > 1 ? front : next;
for (; count > 1; count--) {
val = 10 * val + next;
}
SetDParam(n, val);
}
/**
* Copy \a num string parameters from array \a src into the global string parameter array.
* @param offs Index in the global array to copy the first string parameter to.
* @param src Source array of string parameters.
* @param num Number of string parameters to copy.
*/
void CopyInDParam(int offs, const uint64 *src, int num)
{
MemCpyT(_global_string_params.GetPointerToOffset(offs), src, num);
}
/**
* Copy \a num string parameters from the global string parameter array to the \a dst array.
* @param dst Destination array of string parameters.
* @param offs Index in the global array to copy the first string parameter from.
* @param num Number of string parameters to copy.
*/
void CopyOutDParam(uint64 *dst, int offs, int num)
{
MemCpyT(dst, _global_string_params.GetPointerToOffset(offs), num);
}
/**
* Copy \a num string parameters from the global string parameter array to the \a dst array.
* Furthermore clone raw string parameters into \a strings and amend the data in \a dst.
* @param dst Destination array of string parameters.
* @param strings Destination array for clone of the raw strings. Must be of same length as dst. Deallocation left to the caller.
* @param string The string used to determine where raw strings are and where there are no raw strings.
* @param num Number of string parameters to copy.
*/
void CopyOutDParam(uint64 *dst, const char **strings, StringID string, int num)
{
char buf[DRAW_STRING_BUFFER];
GetString(buf, string, lastof(buf));
MemCpyT(dst, _global_string_params.GetPointerToOffset(0), num);
for (int i = 0; i < num; i++) {
if (_global_string_params.HasTypeInformation() && _global_string_params.GetTypeAtOffset(i) == SCC_RAW_STRING_POINTER) {
strings[i] = stredup((const char *)(size_t)_global_string_params.GetParam(i));
dst[i] = (size_t)strings[i];
} else {
strings[i] = nullptr;
}
}
}
static char *StationGetSpecialString(char *buff, int x, const char *last);
static char *GetSpecialTownNameString(char *buff, int ind, uint32 seed, const char *last);
static char *GetSpecialNameString(char *buff, int ind, StringParameters *args, const char *last);
static char *FormatString(char *buff, const char *str, StringParameters *args, const char *last, uint case_index = 0, bool game_script = false, bool dry_run = false);
struct LanguagePack : public LanguagePackHeader {
char data[]; // list of strings
};
struct LanguagePackDeleter {
void operator()(LanguagePack *langpack)
{
/* LanguagePack is in fact reinterpreted char[], we need to reinterpret it back to free it properly. */
delete[] reinterpret_cast<char*>(langpack);
}
};
struct LoadedLanguagePack {
std::unique_ptr<LanguagePack, LanguagePackDeleter> langpack;
std::vector<char *> offsets;
std::array<uint, TEXT_TAB_END> langtab_num; ///< Offset into langpack offs
std::array<uint, TEXT_TAB_END> langtab_start; ///< Offset into langpack offs
};
static LoadedLanguagePack _langpack;
static bool _scan_for_gender_data = false; ///< Are we scanning for the gender of the current string? (instead of formatting it)
const char *GetStringPtr(StringID string)
{
switch (GetStringTab(string)) {
case TEXT_TAB_GAMESCRIPT_START: return GetGameStringPtr(GetStringIndex(string));
/* 0xD0xx and 0xD4xx IDs have been converted earlier. */
case TEXT_TAB_OLD_NEWGRF: NOT_REACHED();
case TEXT_TAB_NEWGRF_START: return GetGRFStringPtr(GetStringIndex(string));
default: return _langpack.offsets[_langpack.langtab_start[GetStringTab(string)] + GetStringIndex(string)];
}
}
/**
* Get a parsed string with most special stringcodes replaced by the string parameters.
* @param buffr Pointer to a string buffer where the formatted string should be written to.
* @param string
* @param args Arguments for the string.
* @param last Pointer just past the end of \a buffr.
* @param case_index The "case index". This will only be set when FormatString wants to print the string in a different case.
* @param game_script The string is coming directly from a game script.
* @return Pointer to the final zero byte of the formatted string.
*/
char *GetStringWithArgs(char *buffr, StringID string, StringParameters *args, const char *last, uint case_index, bool game_script)
{
if (string == 0) return GetStringWithArgs(buffr, STR_UNDEFINED, args, last);
uint index = GetStringIndex(string);
StringTab tab = GetStringTab(string);
switch (tab) {
case TEXT_TAB_TOWN:
if (index >= 0xC0 && !game_script) {
return GetSpecialTownNameString(buffr, index - 0xC0, args->GetInt32(), last);
}
break;
case TEXT_TAB_SPECIAL:
if (index >= 0xE4 && !game_script) {
return GetSpecialNameString(buffr, index - 0xE4, args, last);
}
break;
case TEXT_TAB_OLD_CUSTOM:
/* Old table for custom names. This is no longer used */
if (!game_script) {
error("Incorrect conversion of custom name string.");
}
break;
case TEXT_TAB_GAMESCRIPT_START:
return FormatString(buffr, GetGameStringPtr(index), args, last, case_index, true);
case TEXT_TAB_OLD_NEWGRF:
NOT_REACHED();
case TEXT_TAB_NEWGRF_START:
return FormatString(buffr, GetGRFStringPtr(index), args, last, case_index);
default:
break;
}
if (index >= _langpack.langtab_num[tab]) {
if (game_script) {
return GetStringWithArgs(buffr, STR_UNDEFINED, args, last);
}
error("String 0x%X is invalid. You are probably using an old version of the .lng file.\n", string);
}
return FormatString(buffr, GetStringPtr(string), args, last, case_index);
}
char *GetString(char *buffr, StringID string, const char *last)
{
_global_string_params.ClearTypeInformation();
_global_string_params.offset = 0;
return GetStringWithArgs(buffr, string, &_global_string_params, last);
}
/**
* Resolve the given StringID into a std::string with all the associated
* DParam lookups and formatting.
* @param string The unique identifier of the translatable string.
* @return The std::string of the translated string.
*/
std::string GetString(StringID string)
{
char buffer[DRAW_STRING_BUFFER];
GetString(buffer, string, lastof(buffer));
return buffer;
}
/**
* This function is used to "bind" a C string to a OpenTTD dparam slot.
* @param n slot of the string
* @param str string to bind
*/
void SetDParamStr(uint n, const char *str)
{
SetDParam(n, (uint64)(size_t)str);
}
/**
* This function is used to "bind" the C string of a std::string to a OpenTTD dparam slot.
* The caller has to ensure that the std::string reference remains valid while the string is shown.
* @param n slot of the string
* @param str string to bind
*/
void SetDParamStr(uint n, const std::string &str)
{
SetDParamStr(n, str.c_str());
}
/**
* Format a number into a string.
* @param buff the buffer to write to
* @param number the number to write down
* @param last the last element in the buffer
* @param separator the thousands-separator to use
* @param zerofill minimum number of digits to print for the integer part. The number will be filled with zeros at the front if necessary.
* @param fractional_digits number of fractional digits to display after a decimal separator. The decimal separator is inserted
* in front of the \a fractional_digits last digit of \a number.
* @return till where we wrote
*/
static char *FormatNumber(char *buff, int64 number, const char *last, const char *separator, int zerofill = 1, int fractional_digits = 0)
{
static const int max_digits = 20;
uint64 divisor = 10000000000000000000ULL;
zerofill += fractional_digits;
int thousands_offset = (max_digits - fractional_digits - 1) % 3;
if (number < 0) {
buff += seprintf(buff, last, "-");
number = -number;
}
uint64 num = number;
uint64 tot = 0;
for (int i = 0; i < max_digits; i++) {
if (i == max_digits - fractional_digits) {
const char *decimal_separator = _settings_game.locale.digit_decimal_separator.c_str();
if (StrEmpty(decimal_separator)) decimal_separator = _langpack.langpack->digit_decimal_separator;
buff += seprintf(buff, last, "%s", decimal_separator);
}
uint64 quot = 0;
if (num >= divisor) {
quot = num / divisor;
num = num % divisor;
}
if ((tot |= quot) || i >= max_digits - zerofill) {
buff += seprintf(buff, last, "%i", (int)quot);
if ((i % 3) == thousands_offset && i < max_digits - 1 - fractional_digits) buff = strecpy(buff, separator, last);
}
divisor /= 10;
}
*buff = '\0';
return buff;
}
static char *FormatCommaNumber(char *buff, int64 number, const char *last, int fractional_digits = 0)
{
const char *separator = _settings_game.locale.digit_group_separator.c_str();
if (StrEmpty(separator)) separator = _langpack.langpack->digit_group_separator;
return FormatNumber(buff, number, last, separator, 1, fractional_digits);
}
static char *FormatNoCommaNumber(char *buff, int64 number, const char *last)
{
return FormatNumber(buff, number, last, "");
}
static char *FormatZerofillNumber(char *buff, int64 number, int64 count, const char *last)
{
return FormatNumber(buff, number, last, "", count);
}
static char *FormatHexNumber(char *buff, uint64 number, const char *last)
{
return buff + seprintf(buff, last, "0x" OTTD_PRINTFHEX64, number);
}
/**
* Format a given number as a number of bytes with the SI prefix.
* @param buff the buffer to write to
* @param number the number of bytes to write down
* @param last the last element in the buffer
* @return till where we wrote
*/
static char *FormatBytes(char *buff, int64 number, const char *last)
{
assert(number >= 0);
/* 1 2^10 2^20 2^30 2^40 2^50 2^60 */
const char * const iec_prefixes[] = {"", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei"};
uint id = 1;
while (number >= 1024 * 1024) {
number /= 1024;
id++;
}
const char *decimal_separator = _settings_game.locale.digit_decimal_separator.c_str();
if (StrEmpty(decimal_separator)) decimal_separator = _langpack.langpack->digit_decimal_separator;
if (number < 1024) {
id = 0;
buff += seprintf(buff, last, "%i", (int)number);
} else if (number < 1024 * 10) {
buff += seprintf(buff, last, "%i%s%02i", (int)number / 1024, decimal_separator, (int)(number % 1024) * 100 / 1024);
} else if (number < 1024 * 100) {
buff += seprintf(buff, last, "%i%s%01i", (int)number / 1024, decimal_separator, (int)(number % 1024) * 10 / 1024);
} else {
assert(number < 1024 * 1024);
buff += seprintf(buff, last, "%i", (int)number / 1024);
}
assert(id < lengthof(iec_prefixes));
buff += seprintf(buff, last, NBSP "%sB", iec_prefixes[id]);
return buff;
}
static char *FormatYmdString(char *buff, Date date, const char *last, uint case_index)
{
YearMonthDay ymd;
ConvertDateToYMD(date, &ymd);
int64 args[] = {ymd.day + STR_DAY_NUMBER_1ST - 1, STR_MONTH_ABBREV_JAN + ymd.month, ymd.year};
StringParameters tmp_params(args);
return FormatString(buff, GetStringPtr(STR_FORMAT_DATE_LONG), &tmp_params, last, case_index);
}
static char *FormatMonthAndYear(char *buff, Date date, const char *last, uint case_index)
{
YearMonthDay ymd;
ConvertDateToYMD(date, &ymd);
int64 args[] = {STR_MONTH_JAN + ymd.month, ymd.year};
StringParameters tmp_params(args);
return FormatString(buff, GetStringPtr(STR_FORMAT_DATE_SHORT), &tmp_params, last, case_index);
}
static char *FormatTinyOrISODate(char *buff, Date date, StringID str, const char *last)
{
YearMonthDay ymd;
ConvertDateToYMD(date, &ymd);
char day[3];
char month[3];
/* We want to zero-pad the days and months */
seprintf(day, lastof(day), "%02i", ymd.day);
seprintf(month, lastof(month), "%02i", ymd.month + 1);
int64 args[] = {(int64)(size_t)day, (int64)(size_t)month, ymd.year};
StringParameters tmp_params(args);
return FormatString(buff, GetStringPtr(str), &tmp_params, last);
}
static char *FormatGenericCurrency(char *buff, const CurrencySpec *spec, Money number, bool compact, const char *last)
{
/* We are going to make number absolute for printing, so
* keep this piece of data as we need it later on */
bool negative = number < 0;
const char *multiplier = "";
number *= spec->rate;
/* convert from negative */
if (number < 0) {
if (buff + Utf8CharLen(SCC_PUSH_COLOUR) > last) return buff;
buff += Utf8Encode(buff, SCC_PUSH_COLOUR);
if (buff + Utf8CharLen(SCC_RED) > last) return buff;
buff += Utf8Encode(buff, SCC_RED);
buff = strecpy(buff, "-", last);
number = -number;
}
/* Add prefix part, following symbol_pos specification.
* Here, it can can be either 0 (prefix) or 2 (both prefix and suffix).
* The only remaining value is 1 (suffix), so everything that is not 1 */
if (spec->symbol_pos != 1) buff = strecpy(buff, spec->prefix.c_str(), last);
/* for huge numbers, compact the number into k or M */
if (compact) {
/* Take care of the 'k' rounding. Having 1 000 000 k
* and 1 000 M is inconsistent, so always use 1 000 M. */
if (number >= 1000000000 - 500) {
number = (number + 500000) / 1000000;
multiplier = NBSP "M";
} else if (number >= 1000000) {
number = (number + 500) / 1000;
multiplier = NBSP "k";
}
}
const char *separator = _settings_game.locale.digit_group_separator_currency.c_str();
if (StrEmpty(separator)) separator = _currency->separator.c_str();
if (StrEmpty(separator)) separator = _langpack.langpack->digit_group_separator_currency;
buff = FormatNumber(buff, number, last, separator);
buff = strecpy(buff, multiplier, last);
/* Add suffix part, following symbol_pos specification.
* Here, it can can be either 1 (suffix) or 2 (both prefix and suffix).
* The only remaining value is 1 (prefix), so everything that is not 0 */
if (spec->symbol_pos != 0) buff = strecpy(buff, spec->suffix.c_str(), last);
if (negative) {
if (buff + Utf8CharLen(SCC_POP_COLOUR) > last) return buff;
buff += Utf8Encode(buff, SCC_POP_COLOUR);
*buff = '\0';
}
return buff;
}
/**
* Determine the "plural" index given a plural form and a number.
* @param count The number to get the plural index of.
* @param plural_form The plural form we want an index for.
* @return The plural index for the given form.
*/
static int DeterminePluralForm(int64 count, int plural_form)
{
/* The absolute value determines plurality */
uint64 n = abs(count);
switch (plural_form) {
default:
NOT_REACHED();
/* Two forms: singular used for one only.
* Used in:
* Danish, Dutch, English, German, Norwegian, Swedish, Estonian, Finnish,
* Greek, Hebrew, Italian, Portuguese, Spanish, Esperanto */
case 0:
return n != 1 ? 1 : 0;
/* Only one form.
* Used in:
* Hungarian, Japanese, Turkish */
case 1:
return 0;
/* Two forms: singular used for 0 and 1.
* Used in:
* French, Brazilian Portuguese */
case 2:
return n > 1 ? 1 : 0;
/* Three forms: special cases for 0, and numbers ending in 1 except when ending in 11.
* Note: Cases are out of order for hysterical reasons. '0' is last.
* Used in:
* Latvian */
case 3:
return n % 10 == 1 && n % 100 != 11 ? 0 : n != 0 ? 1 : 2;
/* Five forms: special cases for 1, 2, 3 to 6, and 7 to 10.
* Used in:
* Gaelige (Irish) */
case 4:
return n == 1 ? 0 : n == 2 ? 1 : n < 7 ? 2 : n < 11 ? 3 : 4;
/* Three forms: special cases for numbers ending in 1 except when ending in 11, and 2 to 9 except when ending in 12 to 19.
* Used in:
* Lithuanian */
case 5:
return n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2;
/* Three forms: special cases for numbers ending in 1 except when ending in 11, and 2 to 4 except when ending in 12 to 14.
* Used in:
* Croatian, Russian, Ukrainian */
case 6:
return n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2;
/* Three forms: special cases for 1, and numbers ending in 2 to 4 except when ending in 12 to 14.
* Used in:
* Polish */
case 7:
return n == 1 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2;
/* Four forms: special cases for numbers ending in 01, 02, and 03 to 04.
* Used in:
* Slovenian */
case 8:
return n % 100 == 1 ? 0 : n % 100 == 2 ? 1 : n % 100 == 3 || n % 100 == 4 ? 2 : 3;
/* Two forms: singular used for numbers ending in 1 except when ending in 11.
* Used in:
* Icelandic */
case 9:
return n % 10 == 1 && n % 100 != 11 ? 0 : 1;
/* Three forms: special cases for 1, and 2 to 4
* Used in:
* Czech, Slovak */
case 10:
return n == 1 ? 0 : n >= 2 && n <= 4 ? 1 : 2;
/* Two forms: cases for numbers ending with a consonant, and with a vowel.
* Korean doesn't have the concept of plural, but depending on how a
* number is pronounced it needs another version of a particle.
* As such the plural system is misused to give this distinction.
*/
case 11:
switch (n % 10) {
case 0: // yeong
case 1: // il
case 3: // sam
case 6: // yuk
case 7: // chil
case 8: // pal
return 0;
case 2: // i
case 4: // sa
case 5: // o
case 9: // gu
return 1;
default:
NOT_REACHED();
}
/* Four forms: special cases for 1, 0 and numbers ending in 02 to 10, and numbers ending in 11 to 19.
* Used in:
* Maltese */
case 12:
return (n == 1 ? 0 : n == 0 || (n % 100 > 1 && n % 100 < 11) ? 1 : (n % 100 > 10 && n % 100 < 20) ? 2 : 3);
/* Four forms: special cases for 1 and 11, 2 and 12, 3 .. 10 and 13 .. 19, other
* Used in:
* Scottish Gaelic */
case 13:
return ((n == 1 || n == 11) ? 0 : (n == 2 || n == 12) ? 1 : ((n > 2 && n < 11) || (n > 12 && n < 20)) ? 2 : 3);
/* Three forms: special cases for 1, 0 and numbers ending in 01 to 19.
* Used in:
* Romanian */
case 14:
return n == 1 ? 0 : (n == 0 || (n % 100 > 0 && n % 100 < 20)) ? 1 : 2;
}
}
static const char *ParseStringChoice(const char *b, uint form, char **dst, const char *last)
{
/* <NUM> {Length of each string} {each string} */
uint n = (byte)*b++;
uint pos, i, mypos = 0;
for (i = pos = 0; i != n; i++) {
uint len = (byte)*b++;
if (i == form) mypos = pos;
pos += len;
}
*dst += seprintf(*dst, last, "%s", b + mypos);
return b + pos;
}
/** Helper for unit conversion. */
struct UnitConversion {
int multiplier; ///< Amount to multiply upon conversion.
int shift; ///< Amount to shift upon conversion.
/**
* Convert value from OpenTTD's internal unit into the displayed value.
* @param input The input to convert.
* @param round Whether to round the value or not.
* @return The converted value.
*/
int64 ToDisplay(int64 input, bool round = true) const
{
return ((input * this->multiplier) + (round && this->shift != 0 ? 1 << (this->shift - 1) : 0)) >> this->shift;
}
/**
* Convert the displayed value back into a value of OpenTTD's internal unit.
* @param input The input to convert.
* @param round Whether to round the value up or not.
* @param divider Divide the return value by this.
* @return The converted value.
*/
int64 FromDisplay(int64 input, bool round = true, int64 divider = 1) const
{
return ((input << this->shift) + (round ? (this->multiplier * divider) - 1 : 0)) / (this->multiplier * divider);
}
};
/** Information about a specific unit system. */
struct Units {
UnitConversion c; ///< Conversion
StringID s; ///< String for the unit
unsigned int decimal_places; ///< Number of decimal places embedded in the value. For example, 1 if the value is in tenths, and 3 if the value is in thousandths.
};
/** Information about a specific unit system with a long variant. */
struct UnitsLong {
UnitConversion c; ///< Conversion
StringID s; ///< String for the short variant of the unit
StringID l; ///< String for the long variant of the unit
};
/** Unit conversions for velocity. */
static const Units _units_velocity[] = {
{ { 1, 0}, STR_UNITS_VELOCITY_IMPERIAL, 0 },
{ { 103, 6}, STR_UNITS_VELOCITY_METRIC, 0 },
{ { 1831, 12}, STR_UNITS_VELOCITY_SI, 0 },
{ {37888, 16}, STR_UNITS_VELOCITY_GAMEUNITS, 1 },
};
/** Unit conversions for velocity. */
static const Units _units_power[] = {
{ { 1, 0}, STR_UNITS_POWER_IMPERIAL, 0 },
{ {4153, 12}, STR_UNITS_POWER_METRIC, 0 },
{ {6109, 13}, STR_UNITS_POWER_SI, 0 },
};
/** Unit conversions for weight. */
static const UnitsLong _units_weight[] = {
{ {4515, 12}, STR_UNITS_WEIGHT_SHORT_IMPERIAL, STR_UNITS_WEIGHT_LONG_IMPERIAL },
{ { 1, 0}, STR_UNITS_WEIGHT_SHORT_METRIC, STR_UNITS_WEIGHT_LONG_METRIC },
{ {1000, 0}, STR_UNITS_WEIGHT_SHORT_SI, STR_UNITS_WEIGHT_LONG_SI },
};
/** Unit conversions for volume. */
static const UnitsLong _units_volume[] = {
{ {4227, 4}, STR_UNITS_VOLUME_SHORT_IMPERIAL, STR_UNITS_VOLUME_LONG_IMPERIAL },
{ {1000, 0}, STR_UNITS_VOLUME_SHORT_METRIC, STR_UNITS_VOLUME_LONG_METRIC },
{ { 1, 0}, STR_UNITS_VOLUME_SHORT_SI, STR_UNITS_VOLUME_LONG_SI },
};
/** Unit conversions for force. */
static const Units _units_force[] = {
{ {3597, 4}, STR_UNITS_FORCE_IMPERIAL, 0 },
{ {3263, 5}, STR_UNITS_FORCE_METRIC, 0 },
{ { 1, 0}, STR_UNITS_FORCE_SI, 0 },
};
/** Unit conversions for height. */
static const Units _units_height[] = {
{ { 3, 0}, STR_UNITS_HEIGHT_IMPERIAL, 0 }, // "Wrong" conversion factor for more nicer GUI values
{ { 1, 0}, STR_UNITS_HEIGHT_METRIC, 0 },
{ { 1, 0}, STR_UNITS_HEIGHT_SI, 0 },
};
/**
* Convert the given (internal) speed to the display speed.
* @param speed the speed to convert
* @return the converted speed.
*/
uint ConvertSpeedToDisplaySpeed(uint speed)
{
/* For historical reasons we don't want to mess with the
* conversion for speed. So, don't round it and keep the
* original conversion factors instead of the real ones. */
return _units_velocity[_settings_game.locale.units_velocity].c.ToDisplay(speed, false);
}
/**
* Convert the given display speed to the (internal) speed.
* @param speed the speed to convert
* @return the converted speed.
*/
uint ConvertDisplaySpeedToSpeed(uint speed)
{
return _units_velocity[_settings_game.locale.units_velocity].c.FromDisplay(speed);
}
/**
* Convert the given km/h-ish speed to the display speed.
* @param speed the speed to convert
* @return the converted speed.
*/
uint ConvertKmhishSpeedToDisplaySpeed(uint speed)
{
return _units_velocity[_settings_game.locale.units_velocity].c.ToDisplay(speed * 10, false) / 16;
}
/**
* Convert the given display speed to the km/h-ish speed.
* @param speed the speed to convert
* @return the converted speed.
*/
uint ConvertDisplaySpeedToKmhishSpeed(uint speed)
{
return _units_velocity[_settings_game.locale.units_velocity].c.FromDisplay(speed * 16, true, 10);
}
/**
* Parse most format codes within a string and write the result to a buffer.
* @param buff The buffer to write the final string to.
* @param str_arg The original string with format codes.
* @param args Pointer to extra arguments used by various string codes.
* @param last Pointer to just past the end of the buff array.
* @param dry_run True when the argt array is not yet initialized.
*/
static char *FormatString(char *buff, const char *str_arg, StringParameters *args, const char *last, uint case_index, bool game_script, bool dry_run)
{
uint orig_offset = args->offset;
/* When there is no array with types there is no need to do a dry run. */
if (args->HasTypeInformation() && !dry_run) {
if (UsingNewGRFTextStack()) {
/* Values from the NewGRF text stack are only copied to the normal
* argv array at the time they are encountered. That means that if
* another string command references a value later in the string it
* would fail. We solve that by running FormatString twice. The first
* pass makes sure the argv array is correctly filled and the second
* pass can reference later values without problems. */
struct TextRefStack *backup = CreateTextRefStackBackup();
FormatString(buff, str_arg, args, last, case_index, game_script, true);
RestoreTextRefStackBackup(backup);
} else {
FormatString(buff, str_arg, args, last, case_index, game_script, true);
}
/* We have to restore the original offset here to to read the correct values. */
args->offset = orig_offset;
}
WChar b = '\0';
uint next_substr_case_index = 0;
char *buf_start = buff;
std::stack<const char *, std::vector<const char *>> str_stack;
str_stack.push(str_arg);
for (;;) {
while (!str_stack.empty() && (b = Utf8Consume(&str_stack.top())) == '\0') {
str_stack.pop();
}
if (str_stack.empty()) break;
const char *&str = str_stack.top();
if (SCC_NEWGRF_FIRST <= b && b <= SCC_NEWGRF_LAST) {
/* We need to pass some stuff as it might be modified. */
//todo: should argve be passed here too?
b = RemapNewGRFStringControlCode(b, buf_start, &buff, &str, (int64 *)args->GetDataPointer(), args->GetDataLeft(), dry_run);
if (b == 0) continue;
}
switch (b) {
case SCC_ENCODED: {
uint64 sub_args_data[20];
WChar sub_args_type[20];
bool sub_args_need_free[20];
StringParameters sub_args(sub_args_data, 20, sub_args_type);
sub_args.ClearTypeInformation();
memset(sub_args_need_free, 0, sizeof(sub_args_need_free));
char *p;
uint32 stringid = strtoul(str, &p, 16);
if (*p != ':' && *p != '\0') {
while (*p != '\0') p++;
str = p;
buff = strecat(buff, "(invalid SCC_ENCODED)", last);
break;
}
if (stringid >= TAB_SIZE_GAMESCRIPT) {
while (*p != '\0') p++;
str = p;
buff = strecat(buff, "(invalid StringID)", last);
break;
}
int i = 0;
while (*p != '\0' && i < 20) {
uint64 param;
const char *s = ++p;
/* Find the next value */
bool instring = false;
bool escape = false;
for (;; p++) {
if (*p == '\\') {
escape = true;
continue;
}
if (*p == '"' && escape) {
escape = false;
continue;
}
escape = false;
if (*p == '"') {
instring = !instring;
continue;
}
if (instring) {
continue;
}
if (*p == ':') break;
if (*p == '\0') break;
}
if (*s != '"') {
/* Check if we want to look up another string */
WChar l;
size_t len = Utf8Decode(&l, s);
bool lookup = (l == SCC_ENCODED);
if (lookup) s += len;
param = strtoull(s, &p, 16);
if (lookup) {
if (param >= TAB_SIZE_GAMESCRIPT) {
while (*p != '\0') p++;
str = p;
buff = strecat(buff, "(invalid sub-StringID)", last);
break;
}
param = MakeStringID(TEXT_TAB_GAMESCRIPT_START, param);
}
sub_args.SetParam(i++, param);
} else {
char *g = stredup(s);
g[p - s] = '\0';
sub_args_need_free[i] = true;
sub_args.SetParam(i++, (uint64)(size_t)g);
}
}
/* If we didn't error out, we can actually print the string. */
if (*str != '\0') {
str = p;
buff = GetStringWithArgs(buff, MakeStringID(TEXT_TAB_GAMESCRIPT_START, stringid), &sub_args, last, true);
}
for (int i = 0; i < 20; i++) {
if (sub_args_need_free[i]) free((void *)sub_args.GetParam(i));
}
break;
}
case SCC_NEWGRF_STRINL: {
StringID substr = Utf8Consume(&str);
str_stack.push(GetStringPtr(substr));
break;
}
case SCC_NEWGRF_PRINT_WORD_STRING_ID: {
StringID substr = args->GetInt32(SCC_NEWGRF_PRINT_WORD_STRING_ID);
str_stack.push(GetStringPtr(substr));
case_index = next_substr_case_index;
next_substr_case_index = 0;
break;
}
case SCC_GENDER_LIST: { // {G 0 Der Die Das}
/* First read the meta data from the language file. */
uint offset = orig_offset + (byte)*str++;
int gender = 0;
if (!dry_run && args->GetTypeAtOffset(offset) != 0) {
/* Now we need to figure out what text to resolve, i.e.
* what do we need to draw? So get the actual raw string
* first using the control code to get said string. */
char input[4 + 1];
char *p = input + Utf8Encode(input, args->GetTypeAtOffset(offset));
*p = '\0';
/* Now do the string formatting. */
char buf[256];
bool old_sgd = _scan_for_gender_data;
_scan_for_gender_data = true;
StringParameters tmp_params(args->GetPointerToOffset(offset), args->num_param - offset, nullptr);
p = FormatString(buf, input, &tmp_params, lastof(buf));
_scan_for_gender_data = old_sgd;
*p = '\0';
/* And determine the string. */
const char *s = buf;
WChar c = Utf8Consume(&s);
/* Does this string have a gender, if so, set it */
if (c == SCC_GENDER_INDEX) gender = (byte)s[0];
}
str = ParseStringChoice(str, gender, &buff, last);
break;
}
/* This sets up the gender for the string.
* We just ignore this one. It's used in {G 0 Der Die Das} to determine the case. */
case SCC_GENDER_INDEX: // {GENDER 0}
if (_scan_for_gender_data) {
buff += Utf8Encode(buff, SCC_GENDER_INDEX);
*buff++ = *str++;
} else {
str++;
}
break;
case SCC_PLURAL_LIST: { // {P}
int plural_form = *str++; // contains the plural form for this string
uint offset = orig_offset + (byte)*str++;
int64 v = *args->GetPointerToOffset(offset); // contains the number that determines plural
str = ParseStringChoice(str, DeterminePluralForm(v, plural_form), &buff, last);
break;
}
case SCC_ARG_INDEX: { // Move argument pointer
args->offset = orig_offset + (byte)*str++;