summaryrefslogtreecommitdiff
path: root/tools/msgenc/MessagesDecoder.cpp
blob: f98b28c7afbf9f68a11df172e3f90c434a9842c8 (plain)
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
#include <algorithm>
#include "MessagesDecoder.h"

void MessagesDecoder::CmdmapRegisterCommand(string &command, uint16_t value)
{
    cmdmap[value] = command;
    if (command.rfind("STRVAR_", 0) == 0)
        strvar_codes.insert(value);
}

void MessagesDecoder::CharmapRegisterCharacter(string &code, uint16_t value)
{
    charmap[value] = code;
}

static string ConvertIntToHexStringN(unsigned value, StrConvMode mode, int n) {
    string dest;
    bool printing_zeroes = mode == STR_CONV_MODE_LEADING_ZEROS;
    unsigned shift = 4 * (n - 1);

    for (int i = 0; i < n; i++) {
        unsigned nybble = (value >> shift) & 0xF;
        if (nybble == 0 && !printing_zeroes) {
            if (i == n - 1) printing_zeroes = true;
            else if (mode == STR_CONV_MODE_RIGHT_ALIGN) {
                dest += ' ';
                continue;
            }
        }
        if (nybble != 0 || printing_zeroes) {
            if (nybble < 10) {
                dest += (char)('0' + nybble);
            } else {
                dest += (char)('A' + nybble - 10);
            }
        }
        shift -= 4;
    }

    return dest;
}

void MessagesDecoder::ReadMessagesFromBin(string& filename)
{
    ifstream infile(filename, ios_base::binary);
    if (!infile.good()) {
        throw ifstream::failure("Unable to open file \"" + filename + "\" for reading");
    }
    infile.read((char*)&header, sizeof(header));
    debug_printf("%d lines\n", header.count);
    alloc_table.resize(header.count);
    infile.read((char*)alloc_table.data(), (streamsize)(sizeof(MsgAlloc) * header.count));
    int i = 1;
    for (auto & alloc : alloc_table) {
        alloc.decrypt(header.key, i);
        u16string str;
        str.resize(alloc.length);
        infile.read((char*)str.data(), (2 * alloc.length));
        DecryptU16String(str, i);
        vec_encoded.push_back(str);
        i++;
    }
    infile.close();
}

u16string MessagesDecoder::DecodeTrainerNameMessage(u16string const &message)
{
    int bit = 0;
    u16string out = u"\uf100";
    auto src_p = message.cbegin() + 1;
    char16_t cur_char;
    do {
        cur_char = ((*src_p >> bit) & 0x1FF);
        bit += 9;
        if (bit >= 15) {
            src_p++;
            bit -= 15;
            if (bit != 0 && src_p < message.cend()) {
                cur_char |= (*src_p << (9 - bit)) & 0x1FF;
            }
        }
        out += cur_char;
    } while (src_p < message.cend() && cur_char != 0x1FF);
    return out;
}

string MessagesDecoder::DecodeMessage(u16string &message, int &i) {
    string decoded;
    bool is_trname = false;
    for (size_t j = 0; j < message.size(); j++) {
        uint16_t code = message[j];
        debug_printf("%04X ", code);

        if (charmap.find(code) != charmap.end()) {
            decoded += charmap[code];
        }
        else if (code == (is_trname ? 0x01FF : 0xFFFF)) {
            break;
        }
        else if (code == 0xFFFE) {
            decoded += '{';
            j++;
            code = message[j++];
            debug_printf("%04X ", code);
            string command;
            bool is_strvar = false;
            if (find(strvar_codes.cbegin(), strvar_codes.cend(), code & 0xFF00) != strvar_codes.cend()) {
                is_strvar = true;
                command = "STRVAR_" + ConvertIntToHexStringN((code >> 8), STR_CONV_MODE_LEFT_ALIGN, 2);
            }
            else if (cmdmap.find(code) != cmdmap.end()) {
                command = cmdmap[code];
            } else {
                throw runtime_error("Invalid control code in " + binfilename + ": " + ConvertIntToHexStringN(code, STR_CONV_MODE_LEADING_ZEROS, 4) + " at line " + to_string(i) + ":" + to_string(j));
            }
            decoded += command;
            int nargs = message[j++];
            debug_printf("%04X ", nargs);
            if (is_strvar) {
                decoded += ' ';
                decoded += to_string(code & 0xFF);
                if (nargs != 0)
                    decoded += ',';
            }
            for (int k = 0; k < nargs; k++) {
                decoded += ' ';
                decoded += to_string(message[j + k]);
                debug_printf("%04X ", message[j + k]);
                if (k != nargs - 1)
                    decoded += ',';
            }
            decoded += '}';
            j += nargs - 1;
        }
        else if (code == 0xF100) {
            decoded += "{TRNAME}";
            message = DecodeTrainerNameMessage(message);
            is_trname = true;
        }
        else {
            throw runtime_error("invalid character in " + binfilename + ": " + ConvertIntToHexStringN(code, STR_CONV_MODE_LEADING_ZEROS, 4) + " at " + to_string(i) + ":" + to_string(j));
        }
    }
    MsgAlloc & alloc = alloc_table[i];
    debug_printf("msg %d: at 0x%08X, count %d\n", i + 1, alloc.offset, alloc.length);
    return decoded;
}

template <typename T> void MessagesDecoder::WriteBinaryFile(string& filename, T& data) {
    ofstream outfile(filename, ios_base::binary);
    if (!outfile.good()) {
        throw ofstream::failure("Unable to open file \"" + filename + "\" for writing");
    }
    outfile.write((const char *)&data, sizeof(data));
    outfile.close();
}

void MessagesDecoder::WriteMessagesToText(string& filename) {
    stringstream ss;
    for (string& text : vec_decoded) {
        ss << text << "\r\n";
    }
    WriteTextFile(filename, ss.str());
}

// Public virtual functions

void MessagesDecoder::ReadInput()
{
    ReadMessagesFromBin(binfilename);
}

void MessagesDecoder::Convert()
{
    for (int i = 0; i < (int)vec_encoded.size(); i++) {
        u16string message = vec_encoded[i];
        string decoded = DecodeMessage(message, i);
        vec_decoded.push_back(decoded);
    }
}

void MessagesDecoder::WriteOutput()
{
    WriteMessagesToText(textfilename);
}