OpenTTD Source 15.0-beta2
newgrf_text.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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/>.
6 */
7
18#include "stdafx.h"
19
20#include "debug.h"
21#include "newgrf.h"
22#include "strings_internal.h"
23#include "newgrf_storage.h"
24#include "newgrf_text.h"
25#include "newgrf_cargo.h"
26#include "string_func.h"
28#include "debug.h"
29#include "core/alloc_type.hpp"
31#include "language.h"
32
33#include "table/strings.h"
34#include "table/control_codes.h"
35
36#include "safeguards.h"
37
43enum GRFBaseLanguages : uint8_t {
44 GRFLB_AMERICAN = 0x01,
45 GRFLB_ENGLISH = 0x02,
46 GRFLB_GERMAN = 0x04,
47 GRFLB_FRENCH = 0x08,
48 GRFLB_SPANISH = 0x10,
49 GRFLB_GENERIC = 0x80,
50};
51
52enum GRFExtendedLanguages : uint8_t {
53 GRFLX_AMERICAN = 0x00,
54 GRFLX_ENGLISH = 0x01,
55 GRFLX_GERMAN = 0x02,
56 GRFLX_FRENCH = 0x03,
57 GRFLX_SPANISH = 0x04,
58 GRFLX_UNSPECIFIED = 0x7F,
59};
60
61
68 GRFTextList textholder;
69 StringID def_string;
70 uint32_t grfid;
71 GRFStringID stringid;
72};
73
74
76static uint8_t _current_lang_id = GRFLX_ENGLISH;
77
84int LanguageMap::GetMapping(int newgrf_id, bool gender) const
85{
86 const std::vector<Mapping> &map = gender ? this->gender_map : this->case_map;
87 for (const Mapping &m : map) {
88 if (m.newgrf_id == newgrf_id) return m.openttd_id;
89 }
90 return -1;
91}
92
99int LanguageMap::GetReverseMapping(int openttd_id, bool gender) const
100{
101 const std::vector<Mapping> &map = gender ? this->gender_map : this->case_map;
102 for (const Mapping &m : map) {
103 if (m.openttd_id == openttd_id) return m.newgrf_id;
104 }
105 return -1;
106}
107
119
121 int offset;
122
124 std::map<int, std::string> strings;
125
131 void Flush(const LanguageMap *lm, std::string &dest)
132 {
133 if (this->strings.find(0) == this->strings.end()) {
134 /* In case of a (broken) NewGRF without a default,
135 * assume an empty string. */
136 GrfMsg(1, "choice list misses default value");
137 this->strings[0] = std::string();
138 }
139
140 StringBuilder builder(dest);
141
142 if (lm == nullptr) {
143 /* In case there is no mapping, just ignore everything but the default.
144 * A probable cause for this happening is when the language file has
145 * been removed by the user and as such no mapping could be made. */
146 builder += this->strings[0];
147 return;
148 }
149
150 builder.PutUtf8(this->type);
151
152 if (this->type == SCC_SWITCH_CASE) {
153 /*
154 * Format for case switch:
155 * <NUM CASES> <CASE1> <LEN1> <STRING1> <CASE2> <LEN2> <STRING2> <CASE3> <LEN3> <STRING3> <LENDEFAULT> <STRINGDEFAULT>
156 * Each LEN is printed using 2 bytes in big endian order.
157 */
158
159 /* "<NUM CASES>" */
160 int count = 0;
161 for (uint8_t i = 0; i < _current_language->num_cases; i++) {
162 /* Count the ones we have a mapped string for. */
163 if (this->strings.find(lm->GetReverseMapping(i, false)) != this->strings.end()) count++;
164 }
165 builder.PutUint8(count);
166
167 auto add_case = [&](std::string_view str) {
168 /* "<LENn>" */
169 uint16_t len = ClampTo<uint16_t>(str.size());
170 builder.PutUint16LE(len);
171
172 /* "<STRINGn>" */
173 builder += str.substr(0, len);
174 };
175
176 for (uint8_t i = 0; i < _current_language->num_cases; i++) {
177 /* Resolve the string we're looking for. */
178 int idx = lm->GetReverseMapping(i, false);
179 if (this->strings.find(idx) == this->strings.end()) continue;
180 auto &str = this->strings[idx];
181
182 /* "<CASEn>" */
183 builder.PutUint8(i + 1);
184
185 add_case(str);
186 }
187
188 /* "<STRINGDEFAULT>" */
189 add_case(this->strings[0]);
190 } else {
191 if (this->type == SCC_PLURAL_LIST) {
192 builder.PutUint8(lm->plural_form);
193 }
194
195 /*
196 * Format for choice list:
197 * <OFFSET> <NUM CHOICES> <LENs> <STRINGs>
198 */
199
200 /* "<OFFSET>" */
201 builder.PutUint8(this->offset - 0x80);
202
203 /* "<NUM CHOICES>" */
204 int count = (this->type == SCC_GENDER_LIST ? _current_language->num_genders : LANGUAGE_MAX_PLURAL_FORMS);
205 builder.PutUint8(count);
206
207 /* "<LENs>" */
208 for (int i = 0; i < count; i++) {
209 int idx = (this->type == SCC_GENDER_LIST ? lm->GetReverseMapping(i, true) : i + 1);
210 const auto &str = this->strings[this->strings.find(idx) != this->strings.end() ? idx : 0];
211 size_t len = str.size();
212 if (len > UINT8_MAX) GrfMsg(1, "choice list string is too long");
213 builder.PutUint8(ClampTo<uint8_t>(len));
214 }
215
216 /* "<STRINGs>" */
217 for (int i = 0; i < count; i++) {
218 int idx = (this->type == SCC_GENDER_LIST ? lm->GetReverseMapping(i, true) : i + 1);
219 const auto &str = this->strings[this->strings.find(idx) != this->strings.end() ? idx : 0];
220 uint8_t len = ClampTo<uint8_t>(str.size());
221 builder += str.substr(0, len);
222 }
223 }
224 }
225};
226
236std::string TranslateTTDPatchCodes(uint32_t grfid, uint8_t language_id, bool allow_newlines, std::string_view str, StringControlCode byte80)
237{
238 /* Empty input string? Nothing to do here. */
239 if (str.empty()) return {};
240
241 std::string_view::const_iterator src = str.cbegin();
242
243 /* Is this an unicode string? */
244 bool unicode = false;
245 char32_t marker;
246 size_t len = Utf8Decode(&marker, &*src);
247
248 if (marker == NFO_UTF8_IDENTIFIER) {
249 unicode = true;
250 src += len;
251 }
252
253 /* Helper variable for a possible (string) mapping of plural/gender and cases. */
254 std::optional<UnmappedChoiceList> mapping_pg, mapping_c;
255 std::optional<std::reference_wrapper<std::string>> dest_c;
256
257 std::string dest;
258 StringBuilder builder(dest);
259 while (src != str.cend()) {
260 char32_t c;
261
262 if (unicode && Utf8EncodedCharLen(*src) != 0) {
263 c = Utf8Consume(src);
264 /* 'Magic' range of control codes. */
265 if (GB(c, 8, 8) == 0xE0) {
266 c = GB(c, 0, 8);
267 } else if (c >= 0x20) {
268 if (!IsValidChar(c, CS_ALPHANUMERAL)) c = '?';
269 builder.PutUtf8(c);
270 continue;
271 }
272 } else {
273 c = static_cast<uint8_t>(*src++);
274 }
275
276 if (c == '\0') break;
277
278 switch (c) {
279 case 0x01:
280 if (*src == '\0') goto string_end;
281 src++;
282 builder.PutChar(' ');
283 break;
284 case 0x0A: break;
285 case 0x0D:
286 if (allow_newlines) {
287 builder.PutChar(0x0A);
288 } else {
289 GrfMsg(1, "Detected newline in string that does not allow one");
290 }
291 break;
292 case 0x0E: builder.PutUtf8(SCC_TINYFONT); break;
293 case 0x0F: builder.PutUtf8(SCC_BIGFONT); break;
294 case 0x1F:
295 if (src[0] == '\0' || src[1] == '\0') goto string_end;
296 src += 2;
297 builder.PutChar(' ');
298 break;
299 case 0x7B:
300 case 0x7C:
301 case 0x7D:
302 case 0x7E:
303 case 0x7F: builder.PutUtf8(SCC_NEWGRF_PRINT_DWORD_SIGNED + c - 0x7B); break;
304 case 0x80: builder.PutUtf8(byte80); break;
305 case 0x81:
306 {
307 if (src[0] == '\0' || src[1] == '\0') goto string_end;
308 uint16_t string;
309 string = static_cast<uint8_t>(*src++);
310 string |= static_cast<uint8_t>(*src++) << 8;
311 builder.PutUtf8(SCC_NEWGRF_STRINL);
312 builder.PutUtf8(MapGRFStringID(grfid, GRFStringID{string}));
313 break;
314 }
315 case 0x82:
316 case 0x83:
317 case 0x84: builder.PutUtf8(SCC_NEWGRF_PRINT_WORD_DATE_LONG + c - 0x82); break;
318 case 0x85: builder.PutUtf8(SCC_NEWGRF_DISCARD_WORD); break;
319 case 0x86: builder.PutUtf8(SCC_NEWGRF_ROTATE_TOP_4_WORDS); break;
320 case 0x87: builder.PutUtf8(SCC_NEWGRF_PRINT_WORD_VOLUME_LONG); break;
321 case 0x88: builder.PutUtf8(SCC_BLUE); break;
322 case 0x89: builder.PutUtf8(SCC_SILVER); break;
323 case 0x8A: builder.PutUtf8(SCC_GOLD); break;
324 case 0x8B: builder.PutUtf8(SCC_RED); break;
325 case 0x8C: builder.PutUtf8(SCC_PURPLE); break;
326 case 0x8D: builder.PutUtf8(SCC_LTBROWN); break;
327 case 0x8E: builder.PutUtf8(SCC_ORANGE); break;
328 case 0x8F: builder.PutUtf8(SCC_GREEN); break;
329 case 0x90: builder.PutUtf8(SCC_YELLOW); break;
330 case 0x91: builder.PutUtf8(SCC_DKGREEN); break;
331 case 0x92: builder.PutUtf8(SCC_CREAM); break;
332 case 0x93: builder.PutUtf8(SCC_BROWN); break;
333 case 0x94: builder.PutUtf8(SCC_WHITE); break;
334 case 0x95: builder.PutUtf8(SCC_LTBLUE); break;
335 case 0x96: builder.PutUtf8(SCC_GRAY); break;
336 case 0x97: builder.PutUtf8(SCC_DKBLUE); break;
337 case 0x98: builder.PutUtf8(SCC_BLACK); break;
338 case 0x9A:
339 {
340 int code = *src++;
341 switch (code) {
342 case 0x00: goto string_end;
343 case 0x01: builder.PutUtf8(SCC_NEWGRF_PRINT_QWORD_CURRENCY); break;
344 /* 0x02: ignore next colour byte is not supported. It works on the final
345 * string and as such hooks into the string drawing routine. At that
346 * point many things already happened, such as splitting up of strings
347 * when drawn over multiple lines or right-to-left translations, which
348 * make the behaviour peculiar, e.g. only happening at specific width
349 * of windows. Or we need to add another pass over the string to just
350 * support this. As such it is not implemented in OpenTTD. */
351 case 0x03:
352 {
353 if (src[0] == '\0' || src[1] == '\0') goto string_end;
354 uint16_t tmp = static_cast<uint8_t>(*src++);
355 tmp |= static_cast<uint8_t>(*src++) << 8;
357 builder.PutUtf8(tmp);
358 break;
359 }
360 case 0x06: builder.PutUtf8(SCC_NEWGRF_PRINT_BYTE_HEX); break;
361 case 0x07: builder.PutUtf8(SCC_NEWGRF_PRINT_WORD_HEX); break;
362 case 0x08: builder.PutUtf8(SCC_NEWGRF_PRINT_DWORD_HEX); break;
363 /* 0x09, 0x0A are TTDPatch internal use only string codes. */
364 case 0x0B: builder.PutUtf8(SCC_NEWGRF_PRINT_QWORD_HEX); break;
365 case 0x0C: builder.PutUtf8(SCC_NEWGRF_PRINT_WORD_STATION_NAME); break;
366 case 0x0D: builder.PutUtf8(SCC_NEWGRF_PRINT_WORD_WEIGHT_LONG); break;
367 case 0x0E:
368 case 0x0F:
369 {
370 if (str[0] == '\0') goto string_end;
371 const LanguageMap *lm = LanguageMap::GetLanguageMap(grfid, language_id);
372 int index = *src++;
373 int mapped = lm != nullptr ? lm->GetMapping(index, code == 0x0E) : -1;
374 if (mapped >= 0) {
375 builder.PutUtf8(code == 0x0E ? SCC_GENDER_INDEX : SCC_SET_CASE);
376 builder.PutUtf8(code == 0x0E ? mapped : mapped + 1);
377 }
378 break;
379 }
380
381 case 0x10:
382 case 0x11:
383 if (str[0] == '\0') goto string_end;
384 if (!mapping_pg.has_value() && !mapping_c.has_value()) {
385 if (code == 0x10) src++; // Skip the index
386 GrfMsg(1, "choice list {} marker found when not expected", code == 0x10 ? "next" : "default");
387 break;
388 } else {
389 auto &mapping = mapping_pg ? mapping_pg : mapping_c;
390 int index = (code == 0x10 ? *src++ : 0);
391 if (mapping->strings.find(index) != mapping->strings.end()) {
392 GrfMsg(1, "duplicate choice list string, ignoring");
393 } else {
394 builder = StringBuilder(mapping->strings[index]);
395 if (!mapping_pg) dest_c = mapping->strings[index];
396 }
397 }
398 break;
399
400 case 0x12:
401 if (!mapping_pg.has_value() && !mapping_c.has_value()) {
402 GrfMsg(1, "choice list end marker found when not expected");
403 } else {
404 auto &mapping = mapping_pg ? mapping_pg : mapping_c;
405 auto &new_dest = mapping_pg && dest_c ? dest_c->get() : dest;
406 /* Now we can start flushing everything and clean everything up. */
407 mapping->Flush(LanguageMap::GetLanguageMap(grfid, language_id), new_dest);
408 if (!mapping_pg) dest_c.reset();
409 mapping.reset();
410
411 builder = StringBuilder(new_dest);
412 }
413 break;
414
415 case 0x13:
416 case 0x14:
417 case 0x15: {
418 auto &mapping = code == 0x14 ? mapping_c : mapping_pg;
419 if (src[0] == '\0') goto string_end;
420 /* Case mapping can have nested plural/gender mapping. Otherwise nesting is invalid. */
421 if (mapping.has_value() || mapping_pg.has_value()) {
422 GrfMsg(1, "choice lists can't be stacked, it's going to get messy now...");
423 if (code != 0x14) src++;
424 } else {
425 static const StringControlCode mp[] = { SCC_GENDER_LIST, SCC_SWITCH_CASE, SCC_PLURAL_LIST };
426 mapping.emplace(mp[code - 0x13], code == 0x14 ? 0 : *src++);
427 }
428 break;
429 }
430
431 case 0x16:
432 case 0x17:
433 case 0x18:
434 case 0x19:
435 case 0x1A:
436 case 0x1B:
437 case 0x1C:
438 case 0x1D:
439 case 0x1E:
440 builder.PutUtf8(SCC_NEWGRF_PRINT_DWORD_DATE_LONG + code - 0x16);
441 break;
442
443 case 0x1F: builder.PutUtf8(SCC_PUSH_COLOUR); break;
444 case 0x20: builder.PutUtf8(SCC_POP_COLOUR); break;
445
446 case 0x21: builder.PutUtf8(SCC_NEWGRF_PRINT_DWORD_FORCE); break;
447
448 default:
449 GrfMsg(1, "missing handler for extended format code");
450 break;
451 }
452 break;
453 }
454
455 case 0x9E: builder.PutUtf8(0x20AC); break; // Euro
456 case 0x9F: builder.PutUtf8(0x0178); break; // Y with diaeresis
457 case 0xA0: builder.PutUtf8(SCC_UP_ARROW); break;
458 case 0xAA: builder.PutUtf8(SCC_DOWN_ARROW); break;
459 case 0xAC: builder.PutUtf8(SCC_CHECKMARK); break;
460 case 0xAD: builder.PutUtf8(SCC_CROSS); break;
461 case 0xAF: builder.PutUtf8(SCC_RIGHT_ARROW); break;
462 case 0xB4: builder.PutUtf8(SCC_TRAIN); break;
463 case 0xB5: builder.PutUtf8(SCC_LORRY); break;
464 case 0xB6: builder.PutUtf8(SCC_BUS); break;
465 case 0xB7: builder.PutUtf8(SCC_PLANE); break;
466 case 0xB8: builder.PutUtf8(SCC_SHIP); break;
467 case 0xB9: builder.PutUtf8(SCC_SUPERSCRIPT_M1); break;
468 case 0xBC: builder.PutUtf8(SCC_SMALL_UP_ARROW); break;
469 case 0xBD: builder.PutUtf8(SCC_SMALL_DOWN_ARROW); break;
470 default:
471 /* Validate any unhandled character */
472 if (!IsValidChar(c, CS_ALPHANUMERAL)) c = '?';
473 builder.PutUtf8(c);
474 break;
475 }
476 }
477
478string_end:
479 if (mapping_pg.has_value() || mapping_c.has_value()) {
480 GrfMsg(1, "choice list was incomplete, the whole list is ignored");
481 }
482
483 return dest;
484}
485
492static void AddGRFTextToList(GRFTextList &list, uint8_t langid, std::string_view text_to_add)
493{
494 /* Loop through all languages and see if we can replace a string */
495 for (auto &text : list) {
496 if (text.langid == langid) {
497 text.text = text_to_add;
498 return;
499 }
500 }
501
502 /* If a string wasn't replaced, then we must append the new string */
503 list.emplace_back(langid, std::string{text_to_add});
504}
505
515void AddGRFTextToList(GRFTextList &list, uint8_t langid, uint32_t grfid, bool allow_newlines, std::string_view text_to_add)
516{
517 AddGRFTextToList(list, langid, TranslateTTDPatchCodes(grfid, langid, allow_newlines, text_to_add));
518}
519
529void AddGRFTextToList(GRFTextWrapper &list, uint8_t langid, uint32_t grfid, bool allow_newlines, std::string_view text_to_add)
530{
531 if (list == nullptr) list = std::make_shared<GRFTextList>();
532 AddGRFTextToList(*list, langid, grfid, allow_newlines, text_to_add);
533}
534
541void AddGRFTextToList(GRFTextWrapper &list, std::string_view text_to_add)
542{
543 if (list == nullptr) list = std::make_shared<GRFTextList>();
544 AddGRFTextToList(*list, GRFLX_UNSPECIFIED, text_to_add);
545}
546
550StringID AddGRFString(uint32_t grfid, GRFStringID stringid, uint8_t langid_to_add, bool new_scheme, bool allow_newlines, std::string_view text_to_add, StringID def_string)
551{
552 /* When working with the old language scheme (grf_version is less than 7) and
553 * English or American is among the set bits, simply add it as English in
554 * the new scheme, i.e. as langid = 1.
555 * If English is set, it is pretty safe to assume the translations are not
556 * actually translated.
557 */
558 if (!new_scheme) {
559 if (langid_to_add & (GRFLB_AMERICAN | GRFLB_ENGLISH)) {
560 langid_to_add = GRFLX_ENGLISH;
561 } else {
562 StringID ret = STR_EMPTY;
563 if (langid_to_add & GRFLB_GERMAN) ret = AddGRFString(grfid, stringid, GRFLX_GERMAN, true, allow_newlines, text_to_add, def_string);
564 if (langid_to_add & GRFLB_FRENCH) ret = AddGRFString(grfid, stringid, GRFLX_FRENCH, true, allow_newlines, text_to_add, def_string);
565 if (langid_to_add & GRFLB_SPANISH) ret = AddGRFString(grfid, stringid, GRFLX_SPANISH, true, allow_newlines, text_to_add, def_string);
566 return ret;
567 }
568 }
569
570 auto it = std::ranges::find_if(_grf_text, [&grfid, &stringid](const GRFTextEntry &grf_text) { return grf_text.grfid == grfid && grf_text.stringid == stringid; });
571 if (it == std::end(_grf_text)) {
572 /* Too many strings allocated, return empty. */
573 if (_grf_text.size() == TAB_SIZE_NEWGRF) return STR_EMPTY;
574
575 /* We didn't find our stringid and grfid in the list, allocate a new id. */
576 it = _grf_text.emplace(std::end(_grf_text));
577 it->grfid = grfid;
578 it->stringid = stringid;
579 it->def_string = def_string;
580 }
581 StringIndexInTab id(it - std::begin(_grf_text));
582
583 std::string newtext = TranslateTTDPatchCodes(grfid, langid_to_add, allow_newlines, text_to_add);
584 AddGRFTextToList(it->textholder, langid_to_add, newtext);
585
586 GrfMsg(3, "Added 0x{:X} grfid {:08X} string 0x{:X} lang 0x{:X} string '{}' ({:X})", id, grfid, stringid, langid_to_add, newtext, MakeStringID(TEXT_TAB_NEWGRF_START, id));
587
589}
590
594StringID GetGRFStringID(uint32_t grfid, GRFStringID stringid)
595{
596 auto it = std::ranges::find_if(_grf_text, [&grfid, &stringid](const GRFTextEntry &grf_text) { return grf_text.grfid == grfid && grf_text.stringid == stringid; });
597 if (it != std::end(_grf_text)) {
598 StringIndexInTab id(it - std::begin(_grf_text));
600 }
601
602 return STR_UNDEFINED;
603}
604
605
613std::optional<std::string_view> GetGRFStringFromGRFText(const GRFTextList &text_list)
614{
615 std::optional<std::string_view> default_text;
616
617 /* Search the list of lang-strings of this stringid for current lang */
618 for (const auto &text : text_list) {
619 if (text.langid == _current_lang_id) return text.text;
620
621 /* If the current string is English or American, set it as the
622 * fallback language if the specific language isn't available. */
623 if (text.langid == GRFLX_UNSPECIFIED || (!default_text.has_value() && (text.langid == GRFLX_ENGLISH || text.langid == GRFLX_AMERICAN))) {
624 default_text = text.text;
625 }
626 }
627
628 return default_text;
629}
630
638std::optional<std::string_view> GetGRFStringFromGRFText(const GRFTextWrapper &text)
639{
640 return text ? GetGRFStringFromGRFText(*text) : std::nullopt;
641}
642
646std::string_view GetGRFStringPtr(StringIndexInTab stringid)
647{
648 assert(stringid.base() < _grf_text.size());
649 assert(_grf_text[stringid].grfid != 0);
650
651 auto str = GetGRFStringFromGRFText(_grf_text[stringid].textholder);
652 if (str.has_value()) return *str;
653
654 /* Use the default string ID if the fallback string isn't available */
655 return GetStringPtr(_grf_text[stringid].def_string);
656}
657
666void SetCurrentGrfLangID(uint8_t language_id)
667{
668 _current_lang_id = language_id;
669}
670
671bool CheckGrfLangID(uint8_t lang_id, uint8_t grf_version)
672{
673 if (grf_version < 7) {
674 switch (_current_lang_id) {
675 case GRFLX_GERMAN: return (lang_id & GRFLB_GERMAN) != 0;
676 case GRFLX_FRENCH: return (lang_id & GRFLB_FRENCH) != 0;
677 case GRFLX_SPANISH: return (lang_id & GRFLB_SPANISH) != 0;
678 default: return (lang_id & (GRFLB_ENGLISH | GRFLB_AMERICAN)) != 0;
679 }
680 }
681
682 return (lang_id == _current_lang_id || lang_id == GRFLX_UNSPECIFIED);
683}
684
690{
691 _grf_text.clear();
692}
693
695 std::array<uint8_t, 0x30> stack{};
696 uint8_t position = 0;
697 const GRFFile *grffile = nullptr;
698
699 TextRefStack(const GRFFile *grffile, uint8_t num_entries) : grffile(grffile)
700 {
701 extern TemporaryStorageArray<int32_t, 0x110> _temp_store;
702
703 assert(num_entries < sizeof(uint32_t) * std::size(stack));
704
705 auto stack_it = this->stack.begin();
706 for (uint i = 0; i < num_entries; i++) {
707 uint32_t value = _temp_store.GetValue(0x100 + i);
708 for (uint j = 0; j < 32; j += 8) {
709 *stack_it++ = GB(value, j, 8);
710 }
711 }
712 }
713
714 uint8_t PopUnsignedByte() { assert(this->position < this->stack.size()); return this->stack[this->position++]; }
715 int8_t PopSignedByte() { return (int8_t)this->PopUnsignedByte(); }
716
717 uint16_t PopUnsignedWord()
718 {
719 uint16_t val = this->PopUnsignedByte();
720 return val | (this->PopUnsignedByte() << 8);
721 }
722 int16_t PopSignedWord() { return (int32_t)this->PopUnsignedWord(); }
723
724 uint32_t PopUnsignedDWord()
725 {
726 uint32_t val = this->PopUnsignedWord();
727 return val | (this->PopUnsignedWord() << 16);
728 }
729 int32_t PopSignedDWord() { return (int32_t)this->PopUnsignedDWord(); }
730
731 uint64_t PopUnsignedQWord()
732 {
733 uint64_t val = this->PopUnsignedDWord();
734 return val | (((uint64_t)this->PopUnsignedDWord()) << 32);
735 }
736 int64_t PopSignedQWord() { return (int64_t)this->PopUnsignedQWord(); }
737
740 {
741 uint8_t tmp[2];
742 for (int i = 0; i < 2; i++) tmp[i] = this->stack[this->position + i + 6];
743 for (int i = 5; i >= 0; i--) this->stack[this->position + i + 2] = this->stack[this->position + i];
744 for (int i = 0; i < 2; i++) this->stack[this->position + i] = tmp[i];
745 }
746
747 void PushWord(uint16_t word)
748 {
749 if (this->position >= 2) {
750 this->position -= 2;
751 } else {
752 // Rotate right 2 positions
753 std::rotate(this->stack.rbegin(), this->stack.rbegin() + 2, this->stack.rend());
754 }
755 this->stack[this->position] = GB(word, 0, 8);
756 this->stack[this->position + 1] = GB(word, 8, 8);
757 }
758};
759
760static void HandleNewGRFStringControlCodes(std::string_view str, TextRefStack &stack, std::vector<StringParameter> &params);
761
769static void ProcessNewGRFStringControlCode(char32_t scc, const char *&str, TextRefStack &stack, std::vector<StringParameter> &params)
770{
771 /* There is data on the NewGRF text stack, and we want to move them to OpenTTD's string stack.
772 * After this call, a new call is made with `modify_parameters` set to false when the string is finally formatted. */
773 switch (scc) {
774 default: return;
775
776 case SCC_PLURAL_LIST:
777 ++str; // plural form
778 [[fallthrough]];
779 case SCC_GENDER_LIST: {
780 ++str; // offset
781 /* plural and gender choices cannot contain any string commands, so just skip the whole thing */
782 uint num = static_cast<uint8_t>(*str++);
783 uint total_len = 0;
784 for (uint i = 0; i != num; i++) {
785 total_len += static_cast<uint8_t>(*str++);
786 }
787 str += total_len;
788 break;
789 }
790
791 case SCC_SWITCH_CASE: {
792 /* skip all cases and continue with default case */
793 uint num = static_cast<uint8_t>(*str++);
794 for (uint i = 0; i != num; i++) {
795 str += 3 + static_cast<uint8_t>(str[1]) + (static_cast<uint8_t>(str[2]) << 8);
796 }
797 str += 2; // length of default
798 break;
799 }
800
801 case SCC_GENDER_INDEX:
802 case SCC_SET_CASE:
803 ++str;
804 break;
805
806 case SCC_ARG_INDEX:
807 NOT_REACHED();
808 break;
809
810 case SCC_NEWGRF_PRINT_BYTE_SIGNED: params.emplace_back(stack.PopSignedByte()); break;
811 case SCC_NEWGRF_PRINT_QWORD_CURRENCY: params.emplace_back(stack.PopSignedQWord()); break;
812
814 case SCC_NEWGRF_PRINT_DWORD_SIGNED: params.emplace_back(stack.PopSignedDWord()); break;
815
816 case SCC_NEWGRF_PRINT_BYTE_HEX: params.emplace_back(stack.PopUnsignedByte()); break;
817 case SCC_NEWGRF_PRINT_QWORD_HEX: params.emplace_back(stack.PopUnsignedQWord()); break;
818
822 case SCC_NEWGRF_PRINT_WORD_SIGNED: params.emplace_back(stack.PopSignedWord()); break;
823
829 case SCC_NEWGRF_PRINT_WORD_UNSIGNED: params.emplace_back(stack.PopUnsignedWord()); break;
830
834 case SCC_NEWGRF_PRINT_DWORD_HEX: params.emplace_back(stack.PopUnsignedDWord()); break;
835
836 /* Dates from NewGRFs have 1920-01-01 as their zero point, convert it to OpenTTD's epoch. */
838 case SCC_NEWGRF_PRINT_WORD_DATE_SHORT: params.emplace_back(CalendarTime::DAYS_TILL_ORIGINAL_BASE_YEAR + stack.PopUnsignedWord()); break;
839
840 case SCC_NEWGRF_DISCARD_WORD: stack.PopUnsignedWord(); break;
841
843 case SCC_NEWGRF_PUSH_WORD: stack.PushWord(Utf8Consume(&str)); break;
844
848 params.emplace_back(GetCargoTranslation(stack.PopUnsignedWord(), stack.grffile));
849 params.emplace_back(stack.PopUnsignedWord());
850 break;
851
852 case SCC_NEWGRF_STRINL: {
853 StringID stringid = Utf8Consume(str);
854 /* We also need to handle the substring's stack usage. */
855 HandleNewGRFStringControlCodes(GetStringPtr(stringid), stack, params);
856 break;
857 }
858
860 StringID stringid = MapGRFStringID(stack.grffile->grfid, GRFStringID{stack.PopUnsignedWord()});
861 params.emplace_back(stringid);
862 /* We also need to handle the substring's stack usage. */
863 HandleNewGRFStringControlCodes(GetStringPtr(stringid), stack, params);
864 break;
865 }
866
868 CargoType cargo = GetCargoTranslation(stack.PopUnsignedWord(), stack.grffile);
869 params.emplace_back(cargo < NUM_CARGO ? 1ULL << cargo : 0);
870 break;
871 }
872 }
873}
874
881char32_t RemapNewGRFStringControlCode(char32_t scc, const char **str)
882{
883 switch (scc) {
884 default:
885 return scc;
886
891 return SCC_COMMA;
892
897 return SCC_HEX;
898
901 return SCC_CURRENCY_LONG;
902
905 return SCC_DATE_LONG;
906
909 return SCC_DATE_SHORT;
910
912 return SCC_VELOCITY;
913
915 return SCC_VOLUME_LONG;
916
918 return SCC_VOLUME_SHORT;
919
921 return SCC_WEIGHT_LONG;
922
924 return SCC_WEIGHT_SHORT;
925
927 return SCC_POWER;
928
930 return SCC_FORCE;
931
933 return SCC_CARGO_LONG;
934
936 return SCC_CARGO_SHORT;
937
939 return SCC_CARGO_TINY;
940
942 return SCC_CARGO_LIST;
943
945 return SCC_STATION_NAME;
946
947 /* These NewGRF string codes modify the NewGRF stack or otherwise do not map to OpenTTD string codes. */
949 Utf8Consume(str);
950 return 0;
951
954 return 0;
955 }
956}
957
964static void HandleNewGRFStringControlCodes(std::string_view str, TextRefStack &stack, std::vector<StringParameter> &params)
965{
966 for (const char *p = str.data(), *end = str.data() + str.size(); p < end; /* nothing */) {
967 char32_t scc;
968 p += Utf8Decode(&scc, p);
969 ProcessNewGRFStringControlCode(scc, p, stack, params);
970 }
971}
972
980std::vector<StringParameter> GetGRFSringTextStackParameters(const GRFFile *grffile, StringID stringid, uint8_t num_entries)
981{
982 if (stringid == INVALID_STRING_ID) return {};
983
984 auto str = GetStringPtr(stringid);
985
986 std::vector<StringParameter> params;
987 params.reserve(20);
988
989 TextRefStack stack{grffile, num_entries};
990 HandleNewGRFStringControlCodes(str, stack, params);
991
992 return params;
993}
994
1002std::string GetGRFStringWithTextStack(const struct GRFFile *grffile, GRFStringID grfstringid, uint8_t num_entries)
1003{
1004 StringID stringid = GetGRFStringID(grffile->grfid, grfstringid);
1005 auto params = GetGRFSringTextStackParameters(grffile, stringid, num_entries);
1006 return GetStringWithArgs(stringid, params);
1007}
Helper types related to the allocation of memory.
debug_inline static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
uint8_t CargoType
Cargo slots to indicate a cargo type within a game.
Definition cargo_type.h:23
static const CargoType NUM_CARGO
Maximum number of cargo types in a game.
Definition cargo_type.h:75
void PutUtf8(char32_t c)
Append UTF.8 char.
void PutUint16LE(uint16_t value)
Append binary uint16 using little endian.
void PutChar(char c)
Append 8-bit char.
void PutUint8(uint8_t value)
Append binary uint8.
A sort-of mixin that adds 'at(pos)' and 'operator[](pos)' implementations for 'ConvertibleThroughBase...
Compose data into a growing std::string.
static constexpr TimerGame< struct Calendar >::Date DAYS_TILL_ORIGINAL_BASE_YEAR
The date of the first day of the original base year.
Control codes that are embedded in the translation strings.
StringControlCode
List of string control codes used for string formatting, displaying, and by strgen to generate the la...
@ SCC_NEWGRF_PRINT_WORD_VOLUME_SHORT
9A 19: Read 2 bytes from the stack as short signed volume
@ SCC_NEWGRF_PRINT_DWORD_CURRENCY
8F: Read 4 bytes from the stack as currency
@ SCC_NEWGRF_PRINT_WORD_HEX
9A 07: Read 2 bytes from the stack and print it as hex
@ SCC_NEWGRF_PRINT_WORD_WEIGHT_SHORT
9A 1A: Read 2 bytes from the stack as short unsigned weight
@ SCC_NEWGRF_ROTATE_TOP_4_WORDS
86: Rotate the top 4 words of the stack (W4 W1 W2 W3)
@ SCC_TINYFONT
Switch to small font.
@ SCC_NEWGRF_PRINT_DWORD_DATE_LONG
9A 16: Read 4 bytes from the stack as base 0 date
@ SCC_NEWGRF_PRINT_DWORD_HEX
9A 08: Read 4 bytes from the stack and print it as hex
@ SCC_NEWGRF_PRINT_WORD_DATE_SHORT
83: Read 2 bytes from the stack as base 1920 date
@ SCC_BIGFONT
Switch to large font.
@ SCC_NEWGRF_PRINT_BYTE_HEX
9A 06: Read 1 byte from the stack and print it as hex
@ SCC_NEWGRF_PRINT_WORD_UNSIGNED
7E: Read 2 bytes from the stack as unsigned value
@ SCC_NEWGRF_PRINT_BYTE_SIGNED
7D: Read 1 byte from the stack as signed value
@ SCC_NEWGRF_PRINT_WORD_CARGO_NAME
9A 1E: Read 2 bytes from the stack as cargo name
@ SCC_NEWGRF_PRINT_DWORD_SIGNED
7B: Read 4 bytes from the stack
@ SCC_NEWGRF_STRINL
Inline another string at the current position, StringID is encoded in the string.
@ SCC_NEWGRF_PRINT_WORD_CARGO_SHORT
9A 1C: Read 2 + 2 bytes from the stack as cargo type (translated) and unsigned cargo amount
@ SCC_NEWGRF_PRINT_WORD_STATION_NAME
9A 0C: Read 2 bytes from the stack as station name
@ SCC_NEWGRF_PRINT_WORD_DATE_LONG
82: Read 2 bytes from the stack as base 1920 date
@ SCC_NEWGRF_PRINT_WORD_SIGNED
7C: Read 2 bytes from the stack as signed value
@ SCC_NEWGRF_PRINT_WORD_POWER
9A 18: Read 2 bytes from the stack as unsigned power
@ SCC_NEWGRF_PUSH_WORD
9A 03: Pushes 2 bytes onto the stack
@ SCC_NEWGRF_PRINT_WORD_STRING_ID
81: Read 2 bytes from the stack as String ID
@ SCC_NEWGRF_PRINT_WORD_VOLUME_LONG
87: Read 2 bytes from the stack as long signed volume
@ SCC_NEWGRF_DISCARD_WORD
85: Discard the next two bytes
@ SCC_NEWGRF_PRINT_DWORD_FORCE
9A 21: Read 4 bytes from the stack as unsigned force
@ SCC_NEWGRF_PRINT_WORD_CARGO_TINY
9A 1D: Read 2 + 2 bytes from the stack as cargo type (translated) and unsigned cargo amount
@ SCC_NEWGRF_PRINT_QWORD_HEX
9A 0B: Read 8 bytes from the stack and print it as hex
@ SCC_NEWGRF_PRINT_WORD_CARGO_LONG
9A 1B: Read 2 + 2 bytes from the stack as cargo type (translated) and unsigned cargo amount
@ SCC_NEWGRF_PRINT_WORD_SPEED
84: Read 2 bytes from the stack as signed speed
@ SCC_NEWGRF_PRINT_DWORD_DATE_SHORT
9A 17: Read 4 bytes from the stack as base 0 date
@ SCC_NEWGRF_PRINT_WORD_WEIGHT_LONG
9A 0D: Read 2 bytes from the stack as long unsigned weight
@ SCC_NEWGRF_PRINT_QWORD_CURRENCY
9A 01: Read 8 bytes from the stack as currency
Functions related to debugging.
Information about languages and their files.
const LanguageMetadata * _current_language
The currently loaded language.
Definition strings.cpp:55
Base for the NewGRF implementation.
StringID MapGRFStringID(uint32_t grfid, GRFStringID str)
Used when setting an object's property to map to the GRF's strings while taking in consideration the ...
CargoType GetCargoTranslation(uint8_t cargo, const GRFFile *grffile, bool usebit)
Translate a GRF-local cargo slot/bitnum into a CargoType.
Cargo support for NewGRFs.
Functionality related to the temporary and persistent storage arrays for NewGRFs.
void CleanUpStrings()
House cleaning.
static void AddGRFTextToList(GRFTextList &list, uint8_t langid, std::string_view text_to_add)
Add a new text to a GRFText list.
std::string_view GetGRFStringPtr(StringIndexInTab stringid)
Get a C-string from a stringid set by a newgrf.
GRFBaseLanguages
Explains the newgrf shift bit positioning.
static void HandleNewGRFStringControlCodes(std::string_view str, TextRefStack &stack, std::vector< StringParameter > &params)
Handle control codes in a NewGRF string, processing the stack and filling parameters.
std::string TranslateTTDPatchCodes(uint32_t grfid, uint8_t language_id, bool allow_newlines, std::string_view str, StringControlCode byte80)
Translate TTDPatch string codes into something OpenTTD can handle (better).
void SetCurrentGrfLangID(uint8_t language_id)
Equivalence Setter function between game and newgrf langID.
StringID GetGRFStringID(uint32_t grfid, GRFStringID stringid)
Returns the index for this stringid associated with its grfID.
static void ProcessNewGRFStringControlCode(char32_t scc, const char *&str, TextRefStack &stack, std::vector< StringParameter > &params)
Process NewGRF string control code instructions.
std::optional< std::string_view > GetGRFStringFromGRFText(const GRFTextList &text_list)
Get a C-string from a GRFText-list.
std::vector< StringParameter > GetGRFSringTextStackParameters(const GRFFile *grffile, StringID stringid, uint8_t num_entries)
Process the text ref stack for a GRF String and return its parameters.
StringID AddGRFString(uint32_t grfid, GRFStringID stringid, uint8_t langid_to_add, bool new_scheme, bool allow_newlines, std::string_view text_to_add, StringID def_string)
Add the new read string into our structure.
static uint8_t _current_lang_id
by default, english is used.
char32_t RemapNewGRFStringControlCode(char32_t scc, const char **str)
Emit OpenTTD's internal string code for the different NewGRF string codes.
std::string GetGRFStringWithTextStack(const struct GRFFile *grffile, GRFStringID grfstringid, uint8_t num_entries)
Format a GRF string using the text ref stack for parameters.
Header of Action 04 "universal holder" structure and functions.
std::shared_ptr< GRFTextList > GRFTextWrapper
Reference counted wrapper around a GRFText pointer.
std::vector< GRFText > GRFTextList
A GRF text with a list of translations.
static const char32_t NFO_UTF8_IDENTIFIER
This character (thorn) indicates a unicode string to NFO.
A number of safeguards to prevent using unsafe methods.
Definition of base types and functions in a cross-platform compatible way.
bool IsValidChar(char32_t key, CharSetFilter afilter)
Only allow certain keys.
Definition string.cpp:418
size_t Utf8Decode(char32_t *c, const char *s)
Decode and consume the next UTF-8 encoded character.
Definition string.cpp:441
Compose strings from textual and binary data.
Functions related to low-level strings.
int8_t Utf8EncodedCharLen(char c)
Return the length of an UTF-8 encoded value based on a single char.
@ CS_ALPHANUMERAL
Both numeric and alphabetic and spaces and stuff.
Definition string_type.h:25
void GetStringWithArgs(StringBuilder &builder, StringID string, StringParameters &args, uint case_index, bool game_script)
Get a parsed string with most special stringcodes replaced by the string parameters.
Definition strings.cpp:336
StringID MakeStringID(StringTab tab, StringIndexInTab index)
Create a StringID.
uint32_t StringID
Numeric value that represents a string, independent of the selected language.
static const StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames)
static const uint TAB_SIZE_NEWGRF
Number of strings for NewGRFs.
@ TEXT_TAB_NEWGRF_START
Start of NewGRF supplied strings.
Dynamic data of a loaded NewGRF.
Definition newgrf.h:113
Holder of the above structure.
Mapping between NewGRF and OpenTTD IDs.
Mapping of language data between a NewGRF and OpenTTD.
std::vector< Mapping > gender_map
Mapping of NewGRF and OpenTTD IDs for genders.
int GetReverseMapping(int openttd_id, bool gender) const
Get the mapping from OpenTTD's internal ID to the NewGRF supplied ID.
int plural_form
The plural form used for this language.
static const LanguageMap * GetLanguageMap(uint32_t grfid, uint8_t language_id)
Get the language map associated with a given NewGRF and language.
Definition newgrf.cpp:351
std::vector< Mapping > case_map
Mapping of NewGRF and OpenTTD IDs for cases.
int GetMapping(int newgrf_id, bool gender) const
Get the mapping from the NewGRF supplied ID to OpenTTD's internal ID.
uint8_t num_genders
the number of genders of this language
Definition language.h:53
uint8_t num_cases
the number of cases of this language
Definition language.h:54
Class for temporary storage of data.
void RotateTop4Words()
Rotate the top four words down: W1, W2, W3, W4 -> W4, W1, W2, W3.
Helper structure for mapping choice lists.
StringControlCode type
The type of choice list.
int offset
The offset for the plural/gender form.
std::map< int, std::string > strings
Mapping of NewGRF supplied ID to the different strings in the choice list.
UnmappedChoiceList(StringControlCode type, int offset)
Initialise the mapping.
void Flush(const LanguageMap *lm, std::string &dest)
Flush this choice list into the destination string.
Definition of the game-calendar-timer.