• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

APN-Pucky / tyrant_optimize / 41359149472

01 Nov 2026 10:50PM UTC coverage: 70.608% (+0.02%) from 70.593%
41359149472

push

github

APN-Pucky
Fix db corruption/crash with concurrent tuo processes

load_db crashed with std::out_of_range when it read database.yml
mid-write by another process, since a truncated line left substr()
calling with pos > size. There was also no synchronization around
database.yml, so concurrent writers could corrupt the file, and each
writer only ever held its own subset of evaluated matchups, so the
last process to finish silently discarded everyone else's results.

- Bounds-check every substr in the db parser and skip malformed/
  truncated lines instead of crashing.
- Serialize write_db across processes with an interprocess file lock.
- Merge with whatever is currently on disk (keeping the higher-count
  result per matchup) instead of overwriting, so parallel runs
  accumulate into the shared db rather than clobbering each other.
- Publish via a temp file + atomic rename so a concurrent reader can
  never observe a half-written file.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

76 of 83 new or added lines in 1 file covered. (91.57%)

636 existing lines in 1 file now uncovered.

4843 of 6859 relevant lines covered (70.61%)

9761209.76 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

55.04
/tyrant_optimize.cpp
1
// This program is free software: you can redistribute it and/or modify
2
// it under the terms of the GNU General Public License as published by
3
// the Free Software Foundation, either version 3 of the License, or
4
// (at your option) any later version.
5

6
// This program is distributed in the hope that it will be useful,
7
// but WITHOUT ANY WARRANTY; without even the implied warranty of
8
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
9
// GNU General Public License for more details.
10

11
// You should have received a copy of the GNU General Public License
12
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
13
//------------------------------------------------------------------------------
14
// #define NDEBUG
15
#define BOOST_THREAD_USE_LIB
16

17
#ifndef _WIN32
18
#include <unistd.h>
19
#else
20
#include <io.h>
21
#define F_OK 0
22
#define access(f, m) _access((f), (m))
23
#endif
24
#include <array>
25
#include <cassert>
26
#include <chrono>
27
#include <cstring>
28
#include <ctime>
29
#include <functional>
30
#include <iostream>
31
#include <map>
32
#include <unordered_map>
33
#include <set>
34
#include <stack>
35
#include <fstream>
36
#include <string>
37
#include <iomanip>
38
#include <tuple>
39
#include <vector>
40
#include <math.h>
41
#include <boost/algorithm/string.hpp>
42
#include <boost/filesystem.hpp>
43
#include <boost/interprocess/sync/file_lock.hpp>
44
#include <boost/interprocess/sync/scoped_lock.hpp>
45
#include <boost/lexical_cast.hpp>
46
#include <boost/math/distributions/binomial.hpp>
47
#include <boost/optional.hpp>
48
#include <boost/range/join.hpp>
49
#include <boost/thread/barrier.hpp>
50
#include <boost/thread/mutex.hpp>
51
#include <boost/thread/thread.hpp>
52
#include <boost/timer/timer.hpp>
53
#include <boost/tokenizer.hpp>
54
#include "card.h"
55
#include "cards.h"
56
#include "deck.h"
57
#include "read.h"
58
#include "sim.h"
59
#include "tyrant.h"
60
#include "xml.h"
61

62
#include "hPMML.h"
63

64
#define DEFINE_GLOBALS
65
#include "algorithms.h"
66

67
// OpenMP Header
68
#ifdef _OPENMP
69
#include <omp.h>
70
#endif
71

72
// Android Headers
73
#if defined(ANDROID) || defined(__ANDROID__)
74
#include <jni.h>
75
#include <android/log.h>
76
#endif
77

78
using namespace tuo;
79
using namespace proc;
80

81
// Confidence bounds are computed in double precision. Boost promotes double to long double by default, which is
82
// slow where long double is a software-emulated 128-bit type (e.g. WebAssembly), and its root finding fails there
83
// near 100% wins ("gamma_p_inv<long double>: Root finding evaluation exceeded 200 iterations").
84
typedef boost::math::binomial_distribution<double, boost::math::policies::policy<boost::math::policies::promote_double<false>>> binomial_distribution;
85

86
// init
87
/*
88
namespace tuo {
89
  unsigned opt_num_threads=4;
90
    gamemode_t gamemode{fight};
91
    OptimizationMode optimization_mode{OptimizationMode::notset};
92
    std::unordered_map<unsigned, unsigned> owned_cards;
93
    const Card* owned_alpha_dominion{nullptr};
94
    bool use_owned_cards{true};
95
    bool opt_skip_unclaimed_decks{false};
96
    //bool opt_trim_unclaimed_decks{false};
97
    unsigned min_deck_len{1};
98
    unsigned max_deck_len{10};
99
    unsigned opt_freezed_cards{0};
100
    unsigned freezed_cards{0};
101
    unsigned fund{0};
102
    long double target_score{100};
103
    long double min_increment_of_score{0};
104
    long double confidence_level{0.99};
105
    bool use_top_level_card{true};
106
    bool use_top_level_commander{true};
107
    bool mode_open_the_deck{false};
108
    bool use_owned_dominions{true};
109
    bool use_maxed_dominions{false};
110
    unsigned use_fused_card_level{0};
111
    unsigned use_fused_commander_level{0};
112
    bool print_upgraded{false};
113
    bool print_values{false};
114
    bool simplify_output{false};
115
    bool show_ci{false};
116
    bool use_harmonic_mean{false};
117
    unsigned iterations_multiplier{10};
118
    unsigned sim_seed{0};
119
    unsigned flexible_iter{20};
120
    unsigned flexible_turn{10};
121
    Requirement requirement;
122
#ifndef NQUEST
123
    Quest quest;
124
#endif
125
    std::unordered_set<unsigned> allowed_candidates;
126
    std::unordered_set<unsigned> disallowed_candidates;
127
    std::chrono::time_point<std::chrono::system_clock> start_time;
128
    long double maximum_time{0};
129
    //anneal
130
    long double temperature = 1000;
131
    long double coolingRate = 0.001;
132
    //genetic
133
    unsigned generations = 50;
134
    unsigned pool_size = 0;
135
    unsigned min_pool_size = 20;
136
    double opt_pool_keep = 1;
137
    double opt_pool_mutate = 1;
138
    double opt_pool_cross = 1;
139
    //fort_climb
140
    unsigned yfpool{0};
141
    unsigned efpool{0};
142
    std::vector<Faction> factions;
143
    bool invert_factions{false};
144
    bool only_recent{false};
145
    bool prefered_recent{false};
146
    unsigned recent_percent{5};
147
    std::vector<Skill::Skill> skills;
148
    bool invert_skills{false};
149
    std::vector<Skill::Skill> prefered_skills;
150
    unsigned prefered_factor{3};
151

152
#if defined(ANDROID) || defined(__ANDROID__)
153
    JNIEnv *envv;
154
    jobject objv;
155
#endif
156
}
157
*/
158

159
static const unsigned int crc32_table[] =
160
    {
161
        0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9,
162
        0x130476dc, 0x17c56b6b, 0x1a864db2, 0x1e475005,
163
        0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61,
164
        0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd,
165
        0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9,
166
        0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75,
167
        0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011,
168
        0x791d4014, 0x7ddc5da3, 0x709f7b7a, 0x745e66cd,
169
        0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039,
170
        0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5,
171
        0xbe2b5b58, 0xbaea46ef, 0xb7a96036, 0xb3687d81,
172
        0xad2f2d84, 0xa9ee3033, 0xa4ad16ea, 0xa06c0b5d,
173
        0xd4326d90, 0xd0f37027, 0xddb056fe, 0xd9714b49,
174
        0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95,
175
        0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1,
176
        0xe13ef6f4, 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d,
177
        0x34867077, 0x30476dc0, 0x3d044b19, 0x39c556ae,
178
        0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072,
179
        0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16,
180
        0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca,
181
        0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde,
182
        0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02,
183
        0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1, 0x53dc6066,
184
        0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba,
185
        0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e,
186
        0xbfa1b04b, 0xbb60adfc, 0xb6238b25, 0xb2e29692,
187
        0x8aad2b2f, 0x8e6c3698, 0x832f1041, 0x87ee0df6,
188
        0x99a95df3, 0x9d684044, 0x902b669d, 0x94ea7b2a,
189
        0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e,
190
        0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2,
191
        0xc6bcf05f, 0xc27dede8, 0xcf3ecb31, 0xcbffd686,
192
        0xd5b88683, 0xd1799b34, 0xdc3abded, 0xd8fba05a,
193
        0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637,
194
        0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb,
195
        0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f,
196
        0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53,
197
        0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47,
198
        0x36194d42, 0x32d850f5, 0x3f9b762c, 0x3b5a6b9b,
199
        0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff,
200
        0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623,
201
        0xf12f560e, 0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7,
202
        0xe22b20d2, 0xe6ea3d65, 0xeba91bbc, 0xef68060b,
203
        0xd727bbb6, 0xd3e6a601, 0xdea580d8, 0xda649d6f,
204
        0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3,
205
        0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7,
206
        0xae3afba2, 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b,
207
        0x9b3660c6, 0x9ff77d71, 0x92b45ba8, 0x9675461f,
208
        0x8832161a, 0x8cf30bad, 0x81b02d74, 0x857130c3,
209
        0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640,
210
        0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c,
211
        0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8,
212
        0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24,
213
        0x119b4be9, 0x155a565e, 0x18197087, 0x1cd86d30,
214
        0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec,
215
        0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088,
216
        0x2497d08d, 0x2056cd3a, 0x2d15ebe3, 0x29d4f654,
217
        0xc5a92679, 0xc1683bce, 0xcc2b1d17, 0xc8ea00a0,
218
        0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, 0xdbee767c,
219
        0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18,
220
        0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4,
221
        0x89b8fd09, 0x8d79e0be, 0x803ac667, 0x84fbdbd0,
222
        0x9abc8bd5, 0x9e7d9662, 0x933eb0bb, 0x97ffad0c,
223
        0xafb010b1, 0xab710d06, 0xa6322bdf, 0xa2f33668,
224
        0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4};
225

226
unsigned int
227
xcrc32(const unsigned char *buf, int len, unsigned int init)
97,280,390 ✔
228
{
229
    unsigned int crc = init;
97,280,390 ✔
230
    while (len--)
2,147,483,647 ✔
231
    {
232
        crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ *buf) & 255];
2,147,483,647 ✔
233
        buf++;
2,147,483,647 ✔
234
    }
UNCOV
235
    return crc;
×
236
}
237

238
unsigned int file_xrcrc32(std::string filename, unsigned int init)
4,580 ✔
239
{
240
    std::ifstream file;
4,580 ✔
241
    file.open(filename);
4,580 ✔
242
    std::string line;
4,580 ✔
243
    unsigned int crc = init;
4,580 ✔
244
    while (getline(file, line))
97,289,550 ✔
245
    {
246
        crc = xcrc32((const unsigned char *)line.c_str(), line.length(), crc);
194,565,360 ✔
247
    }
248
    return crc;
9,160 ✔
249
}
4,580 ✔
250

251
unsigned int checksumcards(std::string prefix)
200 ✔
252
{
253
    unsigned int crc = 0;
200 ✔
254
    // loop cardsections
255
    unsigned int ii = 1;
200 ✔
256

257
    crc = file_xrcrc32(prefix + "data/raids.xml", crc);
200 ✔
258
    crc = file_xrcrc32(prefix + "data/missions.xml", crc);
200 ✔
259
    std::string fname = prefix + "data/cards_section_1.xml";
200 ✔
260
    while (access(fname.c_str(), F_OK) == 0)
4,380 ✔
261
    {
262
        crc = file_xrcrc32(fname, crc);
8,360 ✔
263
        ii += 1;
4,180 ✔
264
        fname = prefix + "data/cards_section_" + std::to_string(ii) + ".xml";
8,360 ✔
265
    }
266
    return crc;
200 ✔
267
}
200 ✔
268

269
void load_ml(std::string prefix)
85 ✔
270
{
271
    if (use_ml)
85 ✔
272
    {
273
        win_model = hpmml::Model(prefix + "data/win.pmml");
2 ✔
274
        stall_model = hpmml::Model(prefix + "data/stall.pmml");
2 ✔
275
        loss_model = hpmml::Model(prefix + "data/loss.pmml");
2 ✔
276
        points_model = hpmml::Model(prefix + "data/points.pmml");
2 ✔
277
    }
278
}
85 ✔
279

280
using Database = std::map<std::string, std::map<std::string, std::map<std::string, Results<uint64_t>>>>;
281

282
// reads the "version: ..." / "xml_check_sum: ..." header lines of a database.yml stream
283
void parse_db_header(std::istream &file, std::string &version, std::string &check)
132 ✔
284
{
285
    std::string line;
132 ✔
286
    // another process may still be in the middle of (re)writing the db file;
287
    // guard every substr so a half-written/truncated line can't throw/crash us
288
    getline(file, line);
132 ✔
289
    {
132 ✔
290
        auto colon = line.find(":");
132 ✔
291
        if (colon != std::string::npos && colon + 2 <= line.size())
132 ✔
292
            version = line.substr(colon + 2);
131 ✔
293
    }
294
    getline(file, line);
132 ✔
295
    {
132 ✔
296
        auto colon = line.find(":");
132 ✔
297
        if (colon != std::string::npos && colon + 2 <= line.size())
132 ✔
298
            check = line.substr(colon + 2);
131 ✔
299
    }
300
}
132 ✔
301

302
// parses the records that follow the header of a database.yml stream into out
303
void parse_db_body(std::istream &file, Database &out)
131 ✔
304
{
305
    std::string line, hfield, hydeck, hedeck;
131 ✔
306
    uint64_t wins, draws, losses, points, count;
131 ✔
307
    while (getline(file, line))
111,203 ✔
308
    {
309
        auto colon = line.find(":");
110,941 ✔
310
        if (line.rfind("\t\t", 0) == 0 && colon != std::string::npos)
110,941 ✔
311
        {
312
            // a concurrent writer may have left this (the last) line truncated
313
            // right after the colon; skip it instead of reading out of bounds
314
            if (colon + 2 > line.size())
95,811 ✔
NEW
315
                continue;
×
316
            hedeck = line.substr(2, colon - 2);
95,811 ✔
317
            std::istringstream reader(line.substr(colon + 2));
95,811 ✔
318
            reader >> wins >> draws >> losses >> points >> count;
95,811 ✔
319
            if (reader.fail())
95,811 ✔
NEW
320
                continue;
×
321
            out[hfield][hydeck][hedeck] = {wins, draws, losses, points, count};
95,811 ✔
322
            // std::cout << "load db: " << hfield << " " << hydeck << " " << hedeck << " " <<wins<< " "<< draws<< " "<< losses<< " " <<points<< " " <<count << std::endl;
323
        }
95,811 ✔
324
        else if (line.rfind("\t", 0) == 0 && colon != std::string::npos)
15,130 ✔
325
        {
326
            hydeck = line.substr(1, colon - 1);
13,643 ✔
327
        }
328
        else if (colon != std::string::npos)
1,487 ✔
329
        {
330
            hfield = line.substr(0, colon);
1,487 ✔
331
        }
332
        else
333
        {
334
            std::cout << "unknown db line: " << line;
111,072 ✔
335
        }
336
    }
337
}
131 ✔
338

339
// load database map from file
340
void load_db(std::string prefix)
85 ✔
341
{
342
    if (use_db_load)
85 ✔
343
    {
344
        _DEBUG_MSG(1, "start loading db\n");
66 ✔
345
        // open file to read from
346
        std::ifstream file;
66 ✔
347
        file.open(prefix + "data/database.yml");
66 ✔
348
        std::string version, check;
66 ✔
349
        parse_db_header(file, version, check);
66 ✔
350
        std::cout << "DB version " << version << std::endl;
66 ✔
351
        std::cout << "DB checksum " << check << std::endl;
66 ✔
352

353
        if (use_strict_db)
66 ✔
354
        {
355
            if (version.compare(TYRANT_OPTIMIZER_VERSION) != 0)
66 ✔
356
            {
357
                std::cout << "DB TUO version outdated" << std::endl;
1 ✔
358
                std::cout << "DB TUO version " << version << " != " << TYRANT_OPTIMIZER_VERSION << std::endl;
1 ✔
359
                std::cout << "DB ignoring database.yml" << std::endl;
1 ✔
360
                use_db_load = false;
1 ✔
361
                return;
1 ✔
362
            }
363
            if (check.compare(std::to_string(checksumcards(prefix))) != 0)
130 ✔
364
            {
UNCOV
365
                std::cout << "DB cards_sections mismatch to db" << std::endl;
×
UNCOV
366
                std::cout << "DB cards_sections checksum " << checksumcards(prefix) << " != " << check << std::endl;
×
367
                std::cout << "DB ignoring database.yml" << std::endl;
×
UNCOV
368
                use_db_load = false;
×
UNCOV
369
                return;
×
370
            }
371
        }
372

373
        parse_db_body(file, database);
65 ✔
374
        // close file
375
        file.close();
65 ✔
376
        _DEBUG_MSG(1, "done loading db\n");
65 ✔
377
    }
66 ✔
378
}
379

380
// write database map to file
381
void write_db(std::string prefix)
85 ✔
382
{
383
    if (use_db_write)
85 ✔
384
    {
385
        _DEBUG_MSG(1, "start writing to db\n");
69 ✔
386
        const std::string db_path = prefix + "data/database.yml";
69 ✔
387

388
        // serialize concurrent writers with an interprocess lock, and merge
389
        // our in-memory results into whatever is currently on disk instead of
390
        // overwriting it outright: each tuo process only ever holds the
391
        // subset of matchups it looked at, so a plain overwrite would make
392
        // the last process to finish the only one whose results survive.
393
        const std::string lock_path = db_path + ".lock";
69 ✔
394
        { std::ofstream ensure_lock(lock_path, std::ios::app); } // file_lock requires the path to already exist
69 ✔
395
        try
69 ✔
396
        {
397
            boost::interprocess::file_lock flock(lock_path.c_str());
69 ✔
398
            boost::interprocess::scoped_lock<boost::interprocess::file_lock> guard(flock);
69 ✔
399

400
            std::ifstream in(db_path);
69 ✔
401
            if (in.is_open())
69 ✔
402
            {
403
                std::string disk_version, disk_check;
66 ✔
404
                parse_db_header(in, disk_version, disk_check);
66 ✔
405
                bool compatible = !use_strict_db || (disk_version == std::string(TYRANT_OPTIMIZER_VERSION) &&
132 ✔
406
                                                      disk_check == std::to_string(checksumcards(prefix)));
198 ✔
407
                if (compatible)
66 ✔
408
                {
409
                    Database on_disk;
66 ✔
410
                    parse_db_body(in, on_disk);
66 ✔
411
                    for (auto &f : on_disk)
810 ✔
412
                        for (auto &d : f.second)
7,566 ✔
413
                            for (auto &e : d.second)
54,728 ✔
414
                            {
415
                                auto &slot = database[f.first][d.first][e.first];
47,906 ✔
416
                                // keep whichever result was computed from more samples
417
                                if (e.second.count > slot.count)
47,906 ✔
418
                                    slot = e.second;
1 ✔
419
                            }
420
                }
66 ✔
421
            }
66 ✔
422
            in.close();
69 ✔
423

424
            // write to a uniquely-named temp file first, then atomically rename it
425
            // onto database.yml, so a concurrent reader never observes a
426
            // half-written (truncated) file
427
            boost::filesystem::path tmp_path = boost::filesystem::unique_path(db_path + ".tmp-%%%%-%%%%");
138 ✔
428
            // open file to write to
429
            std::ofstream file;
69 ✔
430
            file.open(tmp_path.string());
69 ✔
431
            file << "version: " << TYRANT_OPTIMIZER_VERSION << std::endl;
69 ✔
432

433
            file << "xml_check_sum: " << checksumcards(prefix) << std::endl;
138 ✔
434
            auto lines_to_write = db_limit;
69 ✔
435
            // write map to file
436
            for (auto it1 = database.begin(); lines_to_write != 0 && it1 != database.end(); ++it1)
847 ✔
437
            {
438
                file << it1->first << ":" << std::endl;
778 ✔
439
                for (auto it2 = it1->second.begin(); lines_to_write != 0 && it2 != it1->second.end(); ++it2)
7,907 ✔
440
                {
441
                    file << "\t" << it2->first << ":" << std::endl;
7,129 ✔
442
                    for (auto it3 = it2->second.begin(); lines_to_write != 0 && it3 != it2->second.end(); ++it3)
56,995 ✔
443
                    {
444
                        file << "\t\t" << it3->first << ": " << it3->second.wins << " " << it3->second.draws << " " << it3->second.losses << " " << it3->second.points << " " << it3->second.count << std::endl;
49,866 ✔
445
                        if (lines_to_write > 0)
49,866 ✔
NEW
446
                            lines_to_write--;
×
447
                    }
448
                }
449
            }
450
            // close file
451
            file.close();
69 ✔
452
            boost::system::error_code ec;
69 ✔
453
            boost::filesystem::rename(tmp_path, db_path, ec);
138 ✔
454
            if (ec)
69 ✔
455
            {
NEW
456
                std::cout << "DB failed to atomically update database.yml: " << ec.message() << std::endl;
×
NEW
457
                boost::filesystem::remove(tmp_path, ec);
×
458
            }
459
        }
138 ✔
NEW
460
        catch (const boost::interprocess::interprocess_exception &e)
×
461
        {
NEW
462
            std::cout << "DB failed to lock database.yml for writing (" << e.what() << "), skipping write" << std::endl;
×
UNCOV
463
        }
×
464
        _DEBUG_MSG(1, "done writing to db\n");
69 ✔
465
    }
69 ✔
466
}
85 ✔
467

468
void init()
86 ✔
469
{
470
    debug_str.clear();
86 ✔
471
    database.clear();
86 ✔
472
    thread_num_iterations = 0; // written by threads
86 ✔
473
    thread_results = nullptr;  // written by threads
86 ✔
474
    thread_best_results = nullptr;
86 ✔
475
    thread_compare = false;
86 ✔
476
    thread_compare_stop = false; // written by threads
86 ✔
477
    destroy_threads;
86 ✔
478
    opt_num_threads = 4;
86 ✔
479
    gamemode = fight;
86 ✔
480
    optimization_mode = OptimizationMode::notset;
86 ✔
481
    owned_cards.clear();
86 ✔
482
    owned_alpha_dominion = nullptr;
86 ✔
483
    use_owned_cards = true;
86 ✔
484
    opt_skip_unclaimed_decks = false;
86 ✔
485
    // opt_trim_unclaimed_decks=false;
486
    min_deck_len = 1;
86 ✔
487
    max_deck_len = 10;
86 ✔
488
    opt_freezed_cards = 0;
86 ✔
489
    freezed_cards = 0;
86 ✔
490
    fund = 0;
86 ✔
491
    target_score = 100;
86 ✔
492
    min_increment_of_score = 0;
86 ✔
493
    confidence_level = 0.99;
86 ✔
494
    use_top_level_card = true;
86 ✔
495
    use_top_level_commander = true;
86 ✔
496
    mode_open_the_deck = false;
86 ✔
497
    use_owned_dominions = true;
86 ✔
498
    use_maxed_dominions = false;
86 ✔
499
    use_fused_card_level = 0;
86 ✔
500
    use_fused_commander_level = 0;
86 ✔
501
    print_upgraded = false;
86 ✔
502
    print_values = false;
86 ✔
503
    vc_x = 0;
86 ✔
504
    simplify_output = false;
86 ✔
505
    show_ci = false;
86 ✔
506
    use_harmonic_mean = false;
86 ✔
507
    iterations_multiplier = 10;
86 ✔
508
    sim_seed = 0;
86 ✔
509
    flexible_iter = 20;
86 ✔
510
    flexible_turn = 20;
86 ✔
511
    eval_iter = 8;
86 ✔
512
    eval_turn = 8;
86 ✔
513
    requirement.num_cards.clear();
86 ✔
514
    for (unsigned i(0); i < Skill::num_skills; ++i)
4,902 ✔
515
    {
516
        auto s = static_cast<Skill::Skill>(i);
4,816 ✔
517
        x_skill_scale[s] = 1.0;
4,816 ✔
518
        n_skill_scale[s] = 1.0;
4,816 ✔
519
        c_skill_scale[s] = 1.0;
4,816 ✔
520
    }
521
    hp_scale = 1.0;
86 ✔
522
    atk_scale = 1.0;
86 ✔
523
#ifndef NQUEST
524
    // quest = new Quest(); //TODO Quest bugged in Android now here
525
#endif
526
    allowed_candidates.clear();
86 ✔
527
    disallowed_candidates.clear();
86 ✔
528
    disallowed_recipes.clear();
86 ✔
529

530
    // std::chrono::time_point<std::chrono::system_clock> start_time;
531
    maximum_time = 0;
86 ✔
532
    temperature = 1000;
86 ✔
533
    coolingRate = 0.001;
86 ✔
534

535
    generations = 50;
86 ✔
536
    pool_size = 0;
86 ✔
537
    min_pool_size = 20;
86 ✔
538
    opt_pool_keep = 1;
86 ✔
539
    opt_pool_mutate = 1;
86 ✔
540
    opt_pool_cross = 1;
86 ✔
541

542
    min_beam_size = 5;
86 ✔
543

544
    yfpool = 0;
86 ✔
545
    efpool = 0;
86 ✔
546

547
    factions.clear();
86 ✔
548
    invert_factions = false;
86 ✔
549
    only_recent = false;
86 ✔
550
    prefered_recent = false;
86 ✔
551
    recent_percent = 5;
86 ✔
552
    skills.clear();
86 ✔
553
    invert_skills = false;
86 ✔
554
    prefered_skills.clear();
86 ✔
555
    prefered_factor = 3;
86 ✔
556

557
    all_cards.clear();
86 ✔
558

559
    // fix defaults
560
    for (int i = 0; i < Fix::num_fixes; ++i)
1,204 ✔
561
        fixes[i] = false;
1,118 ✔
562

563
    // recommended/default fixes
564
    fixes[Fix::enhance_early] = true;
86 ✔
565
    fixes[Fix::revenge_on_death] = true;
86 ✔
566
    fixes[Fix::death_from_bge] = true;
86 ✔
567
    fixes[Fix::legion_under_mega] = true;
86 ✔
568
    // Sort of a misnomer, but updated skills are also treated as fixes
569
        fixes[Fix::barrier_each_turn] = true;
86 ✔
570
        fixes[Fix::dont_evade_mimic_selection] = true;
86 ✔
571
        fixes[Fix::leech_increase_max_hp] = true;
86 ✔
572
        fixes[Fix::subdue_before_attack] = true;
86 ✔
573
        fixes[Fix::counter_without_damage] = true;
86 ✔
574
        fixes[Fix::poison_after_attacked] = true;
86 ✔
575

576
        fixes[Fix::corrosive_protect_armor] = true;
86 ✔
577
    fixes[Fix::reduce_delay_summoned_by_tower] = true;
86 ✔
578
  
579
    db_limit = -1;
86 ✔
580
    use_strict_db = true;
86 ✔
581
    use_db_write = true;
86 ✔
582
    use_db_load = true;
86 ✔
583

584
    use_ml = false;
86 ✔
585
    use_only_ml = false;
86 ✔
586
    ml_precision = 0.01;
86 ✔
587
}
86 ✔
588

589
#if defined(ANDROID) || defined(__ANDROID__)
590
extern "C" JNIEXPORT void
591

592
    JNICALL
593
    Java_de_neuwirthinformatik_alexander_mtuo_TUO_callMain(
594
        JNIEnv *env,
595
        jobject obj /* this */, jobjectArray stringArray)
596
{
597
    envv = env;
598
    objv = obj;
599
    // from: https://stackoverflow.com/questions/8870174/is-stdcout-usable-in-android-ndk and https://gist.github.com/dzhioev/6127982
600
    class androidbuf : public std::streambuf
601
    {
602
    public:
603
        enum
604
        {
605
            bufsize = 512
606
        }; // ... or some other suitable buffer size
607
        androidbuf() { this->setp(buffer, buffer + bufsize - 1); }
608

609
    private:
610
        int overflow(int c)
611
        {
612
            if (c == traits_type::eof())
613
            {
614
                *this->pptr() = traits_type::to_char_type(c);
615
                this->sbumpc();
616
            }
617
            sync_me(c);
618
            return traits_type::not_eof(c);
619
        }
620

621
        void sync_me(int overflow=0) {
622
            if (this->pbase() != this->pptr())
623
            {
624
                char writebuf[bufsize+2];
625
                memcpy(writebuf, this->pbase(), this->pptr() - this->pbase() );
626
                writebuf[this->pptr() - this->pbase() ] = overflow;
627
                writebuf[this->pptr() - this->pbase() + 1 ] = '\0';
628
                //auto sss = std::string(writebuf).c_str();
629
                ///*
630
                __android_log_print(ANDROID_LOG_DEBUG,
631
                                    "TUO_TUO",
632
                                    "%s",
633
                                    writebuf);
634
                //*/
635
                jstring jstr = envv->NewStringUTF(writebuf);
636
                jclass clazz = envv->FindClass("de/neuwirthinformatik/alexander/mtuo/TUO");
637
                jmethodID messageMe = envv->GetMethodID(clazz, "output", "(Ljava/lang/String;)V");
638
                envv->CallVoidMethod(objv, messageMe, jstr);
639
                this->setp(buffer, buffer + bufsize - 1);
640
            }
641
        }
642

643
        int sync()
644
        {
645
            sync_me(0);
646
            return 0;
647
        }
648
        char buffer[bufsize];
649
    };
650
    auto ao = new androidbuf();
651
    auto ae = new androidbuf();
652
    std::cout.rdbuf(ao);
653
    std::cerr.rdbuf(ae);
654
    __android_log_write(ANDROID_LOG_DEBUG, "TUO_TUO", "START");
655
    int stringCount = env->GetArrayLength(stringArray);
656
    char **param = new char *[stringCount];
657
    const char **cparam = new const char *[stringCount];
658
    jstring *strs = new jstring[stringCount];
659
    for (int i = 0; i < stringCount; i++)
660
    {
661
        strs[i] = (jstring)(*env).GetObjectArrayElement(stringArray, i);
662
        cparam[i] = ((*env).GetStringUTFChars(strs[i], NULL));
663
        param[i] = const_cast<char *>(cparam[i]);
664
    }
665

666
    main(stringCount, cparam);
667
    std::cout << std::flush;
668
    __android_log_write(ANDROID_LOG_DEBUG, "TUO_TUO", "END");
669

670
    for (int i = 0; i < stringCount; i++)
671
    {
672
        env->ReleaseStringUTFChars(strs[i], cparam[i]);
673
    }
674
    // std::string text = "return";
675
    // return env->NewStringUTF(text.c_str());
676
    delete[] param;
677
    delete[] cparam;
678
    delete[] strs;
679
    delete ao;
680
    delete ae;
681
}
682

683
extern "C" JNIEXPORT jstring
684

685
    JNICALL
686
    Java_de_neuwirthinformatik_alexander_mtuo_TUO_stringFromJNI(JNIEnv *env,
687
                                                                jobject thiz, jstring s)
688
{
689
    std::string str = env->GetStringUTFChars(s, NULL);
690
    str += "hello.txt";
691
    __android_log_write(ANDROID_LOG_DEBUG, "TUO_TUO", str.c_str());
692
    FILE *file = fopen(str.c_str(), "w+");
693

694
    if (file != NULL)
695
    {
696
        fputs("HELLO WORLD!\n", file);
697
        fflush(file);
698
        fclose(file);
699
    }
700

701
    return env->NewStringUTF("Hello from JNI (with file io)!");
702
}
703
#endif
704
using namespace std::placeholders;
705

706
//------------------------------------------------------------------------------
707

708
//------------------------------------------------------------------------------
709
Deck *find_deck(Decks &decks, const Cards &all_cards, std::string deck_name)
626 ✔
710
{
711
    Deck *deck = decks.find_deck_by_name(deck_name);
626 ✔
712
    if (deck != nullptr)
626 ✔
713
    {
714
        deck->resolve();
566 ✔
715
        return (deck);
566 ✔
716
    }
717
    decks.decks.emplace_back(Deck{all_cards});
120 ✔
718
    deck = &decks.decks.back();
60 ✔
719
    deck->set(deck_name);
60 ✔
720
    deck->resolve();
60 ✔
721
    return (deck);
60 ✔
722
}
723
//---------------------- $80 deck optimization ---------------------------------
724

725
unsigned get_required_cards_before_upgrade(std::unordered_map<unsigned, unsigned> &owned_cards,
86,528 ✔
726
                                           const std::vector<const Card *> &card_list, std::map<const Card *, unsigned> &num_cards)
727
{
728
    unsigned deck_cost = 0;
86,528 ✔
729
    std::set<const Card *> unresolved_cards;
86,528 ✔
730
    for (const Card *card : card_list)
396,458 ✔
731
    {
732
        ++num_cards[card];
309,930 ✔
733
        unresolved_cards.insert(card);
309,930 ✔
734
    }
735
    // un-upgrade according to type/category
736
    // * use fund for normal cards
737
    // * use only top-level cards for initial (basic) dominion (Alpha Dominion) and dominion material (Dominion Shard)
738
    while (!unresolved_cards.empty())
390,497 ✔
739
    {
740
        // pop next unresolved card
741
        auto card_it = unresolved_cards.end();
303,969 ✔
742
        auto card = *(--card_it);
303,969 ✔
743
        unresolved_cards.erase(card_it);
303,969 ✔
744

745
        // assume unlimited common/rare level-1 cards (standard set)
746
        if ((card->m_set == 1000) && (card->m_rarity <= 2) && (card->is_low_level_card()))
303,969 ✔
747
        {
UNCOV
748
            continue;
×
749
        }
750

751
        // keep un-defused (top-level) basic dominion & its material
752
        if ((card->m_id == 50002) || (card->m_category == CardCategory::dominion_material))
303,969 ✔
753
        {
UNCOV
754
            continue;
×
755
        }
756

757
        // defuse if inventory lacks required cards and recipe is not empty
758
        if ((fund || (card->m_category != CardCategory::normal)) && (owned_cards[card->m_id] < num_cards[card]) && !card->m_recipe_cards.empty())
303,969 ✔
759
        {
UNCOV
760
            unsigned num_under = num_cards[card] - owned_cards[card->m_id];
×
UNCOV
761
            num_cards[card] = owned_cards[card->m_id];
×
762

763
            // do count cost (in SP) only for normal cards
UNCOV
764
            if (card->m_category == CardCategory::normal)
×
765
            {
UNCOV
766
                deck_cost += num_under * card->m_recipe_cost;
×
767
            }
768

769
            // enqueue recipe cards as unresolved
UNCOV
770
            for (auto recipe_it : card->m_recipe_cards)
×
771
            {
UNCOV
772
                num_cards[recipe_it.first] += num_under * recipe_it.second;
×
UNCOV
773
                unresolved_cards.insert(recipe_it.first);
×
774
            }
775
        }
776
    }
777
    return deck_cost;
86,528 ✔
778
}
86,528 ✔
779

780
inline unsigned get_required_cards_before_upgrade(const std::vector<const Card *> &card_list, std::map<const Card *, unsigned> &num_cards)
86,528 ✔
781
{
782
    return get_required_cards_before_upgrade(owned_cards, card_list, num_cards);
25,513 ✔
783
}
784

785
unsigned get_deck_cost(const Deck *deck)
28,238 ✔
786
{
787
    if (!use_owned_cards)
28,238 ✔
788
    {
789
        return 0;
790
    }
791
    std::map<const Card *, unsigned> num_in_deck;
28,238 ✔
792
    unsigned deck_cost = 0;
28,238 ✔
793
    if (deck->commander)
28,238 ✔
794
    {
795
        deck_cost += get_required_cards_before_upgrade({deck->commander}, num_in_deck);
51,026 ✔
796
    }
797
    deck_cost += get_required_cards_before_upgrade(deck->cards, num_in_deck);
28,238 ✔
798
    for (auto it : num_in_deck)
193,514 ✔
799
    {
800
        unsigned card_id = it.first->m_id;
166,344 ✔
801
        if (it.second > owned_cards[card_id])
166,344 ✔
802
        {
803
            return UINT_MAX;
1,068 ✔
804
        }
805
    }
806
    return deck_cost;
807
}
28,238 ✔
808

UNCOV
809
bool is_in_recipe(const Card *card, const Card *material)
×
810
{
811
    // is it already material?
UNCOV
812
    if (card == material)
×
813
    {
814
        return true;
815
    }
816

817
    // no recipes
UNCOV
818
    if (card->m_recipe_cards.empty())
×
819
    {
820
        return false;
821
    }
822

823
    // avoid illegal
UNCOV
824
    if (card->m_category == CardCategory::dominion_material)
×
825
    {
826
        return false;
827
    }
828

829
    // check recursively
UNCOV
830
    for (auto recipe_it : card->m_recipe_cards)
×
831
    {
832
        // is material found?
UNCOV
833
        if (recipe_it.first == material)
×
834
        {
835
            return true;
×
836
        }
837

838
        // go deeper ...
UNCOV
839
        if (is_in_recipe(recipe_it.first, material))
×
840
        {
841
            return true;
842
        }
843
    }
844

845
    // found nothing
846
    return false;
847
}
848

849
bool is_owned_or_can_be_fused(const Card *card)
49,441 ✔
850
{
851
    if (owned_cards[card->m_id])
49,441 ✔
852
    {
853
        return true;
854
    }
855
    if (!fund && (card->m_category == CardCategory::normal))
49,217 ✔
856
    {
857
        return false;
858
    }
UNCOV
859
    std::map<const Card *, unsigned> num_in_deck;
×
UNCOV
860
    unsigned deck_cost = get_required_cards_before_upgrade({card}, num_in_deck);
×
UNCOV
861
    if ((card->m_category == CardCategory::normal) && (deck_cost > fund))
×
862
    {
UNCOV
863
        while (!card->is_low_level_card() && (deck_cost > fund))
×
864
        {
UNCOV
865
            card = card->downgraded();
×
UNCOV
866
            num_in_deck.clear();
×
UNCOV
867
            deck_cost = get_required_cards_before_upgrade({card}, num_in_deck);
×
868
        }
UNCOV
869
        if (deck_cost > fund)
×
870
        {
871
            return false;
872
        }
873
    }
UNCOV
874
    std::map<unsigned, unsigned> num_under;
×
UNCOV
875
    for (auto it : num_in_deck)
×
876
    {
UNCOV
877
        if (it.second > owned_cards[it.first->m_id])
×
878
        {
UNCOV
879
            if ((card->m_category == CardCategory::dominion_alpha) && use_maxed_dominions && !is_in_recipe(card, owned_alpha_dominion))
×
880
            {
UNCOV
881
                if (it.first->m_id != 50002)
×
882
                {
UNCOV
883
                    num_under[it.first->m_id] += it.second - owned_cards[it.first->m_id];
×
884
                }
UNCOV
885
                continue;
×
886
            }
UNCOV
887
            return false;
×
888
        }
889
    }
890
    if (!num_under.empty())
×
891
    {
UNCOV
892
        std::map<const Card *, unsigned> &refund = dominion_refund[owned_alpha_dominion->m_fusion_level][owned_alpha_dominion->m_level];
×
893
        for (auto &refund_it : refund)
×
894
        {
UNCOV
895
            unsigned refund_id = refund_it.first->m_id;
×
UNCOV
896
            if (!num_under.count(refund_id))
×
897
            {
UNCOV
898
                continue;
×
899
            }
UNCOV
900
            num_under[refund_id] = safe_minus(num_under[refund_id], refund_it.second);
×
UNCOV
901
            if (!num_under[refund_id])
×
902
            {
UNCOV
903
                num_under.erase(refund_id);
×
904
            }
905
        }
906
    }
UNCOV
907
    return num_under.empty();
×
UNCOV
908
}
×
909

UNCOV
910
std::string alpha_dominion_cost(const Card *dom_card)
×
911
{
UNCOV
912
    assert(dom_card->m_category == CardCategory::dominion_alpha);
×
UNCOV
913
    if (!owned_alpha_dominion)
×
914
    {
UNCOV
915
        return "(no owned alpha dominion)";
×
916
    }
UNCOV
917
    std::unordered_map<unsigned, unsigned> _owned_cards;
×
UNCOV
918
    std::unordered_map<unsigned, unsigned> refund_owned_cards;
×
UNCOV
919
    std::map<const Card *, unsigned> num_cards;
×
920
    std::map<const Card *, unsigned> &refund = dominion_refund[owned_alpha_dominion->m_fusion_level][owned_alpha_dominion->m_level];
×
UNCOV
921
    unsigned own_dom_id = 50002;
×
UNCOV
922
    if (is_in_recipe(dom_card, owned_alpha_dominion))
×
923
    {
UNCOV
924
        own_dom_id = owned_alpha_dominion->m_id;
×
925
    }
UNCOV
926
    else if (owned_alpha_dominion->m_id != 50002)
×
927
    {
UNCOV
928
        for (auto &it : refund)
×
929
        {
UNCOV
930
            if (it.first->m_category != CardCategory::dominion_material)
×
931
            {
UNCOV
932
                continue;
×
933
            }
UNCOV
934
            refund_owned_cards[it.first->m_id] += it.second;
×
935
        }
936
    }
UNCOV
937
    _owned_cards[own_dom_id] = 1;
×
UNCOV
938
    get_required_cards_before_upgrade(_owned_cards, {dom_card}, num_cards);
×
UNCOV
939
    std::string value("");
×
940
    for (auto &it : num_cards)
×
941
    {
942
        if (it.first->m_category != CardCategory::dominion_material)
×
943
        {
944
            continue;
×
945
        }
946
        value += it.first->m_name + " x " + std::to_string(it.second) + ", ";
×
947
    }
948
    if (!is_in_recipe(dom_card, owned_alpha_dominion))
×
949
    {
950
        num_cards.clear();
×
UNCOV
951
        get_required_cards_before_upgrade(_owned_cards, {owned_alpha_dominion}, num_cards);
×
UNCOV
952
        value += "using refund: ";
×
UNCOV
953
        for (auto &it : refund)
×
954
        {
955
            signed num_under(it.second - (signed)num_cards[it.first]);
×
956
            value += it.first->m_name + " x " + std::to_string(it.second) + "/" + std::to_string(num_under) + ", ";
×
957
        }
958
    }
959
    // remove trailing ', ' for non-empty string / replace empty by '(none)'
960
    if (!value.empty())
×
961
    {
962
        value.erase(value.end() - 2, value.end());
×
963
    }
964
    else
965
    {
966
        value += "(none)";
×
967
    }
968
    return value;
×
UNCOV
969
}
×
970

971
// check if claim_cards is necessary => i.e. can the deck be build from the ownedcards
972
bool claim_cards_needed(const std::vector<const Card *> &card_list)
32,763 ✔
973
{
974
    std::map<const Card *, unsigned> num_cards;
32,763 ✔
975
    get_required_cards_before_upgrade(card_list, num_cards);
32,763 ✔
976
    for (const auto &it : num_cards)
150,646 ✔
977
    {
978
        const Card *card = it.first;
120,869 ✔
979
        if (card->m_category == CardCategory::dominion_material && use_maxed_dominions)
120,869 ✔
UNCOV
980
            continue;
×
981
        if (card->m_category == CardCategory::dominion_alpha && use_maxed_dominions)
120,869 ✔
982
            continue;
×
983
        unsigned num_to_claim = safe_minus(it.second, owned_cards[card->m_id]);
120,869 ✔
984
        if (num_to_claim > 0)
985
        {
986
            return true;
32,763 ✔
987
        }
988
    }
989
    return false;
990
}
32,763 ✔
991

992
void claim_cards(const std::vector<const Card *> &card_list)
14 ✔
993
{
994
    std::map<const Card *, unsigned> num_cards;
14 ✔
995
    get_required_cards_before_upgrade(card_list, num_cards);
14 ✔
996
    for (const auto &it : num_cards)
91 ✔
997
    {
998
        const Card *card = it.first;
77 ✔
999
        if (card->m_category == CardCategory::dominion_material)
77 ✔
1000
            continue;
×
1001
        if (card->m_category == CardCategory::dominion_alpha)
77 ✔
1002
            continue;
×
1003
        unsigned num_to_claim = safe_minus(it.second, owned_cards[card->m_id]);
154 ✔
1004
        if (num_to_claim > 0)
77 ✔
1005
        {
1006
            owned_cards[card->m_id] += num_to_claim;
77 ✔
1007
            if (debug_print >= 0)
77 ✔
1008
            {
1009
                std::cerr << "WARNING: Need extra " << num_to_claim << " " << card->m_name << " to build your initial deck: adding to owned card list.\n";
77 ✔
1010
            }
1011
        }
1012
    }
1013
}
14 ✔
1014

1015
bool valid_deck(Deck *your_deck)
11,919 ✔
1016
{
1017
    if (claim_cards_needed({your_deck->commander}))
11,919 ✔
1018
        return false;
1019
    if (claim_cards_needed(your_deck->cards))
11,919 ✔
1020
        return false;
1021
    if (your_deck->alpha_dominion && claim_cards_needed({your_deck->alpha_dominion}))
8,933 ✔
1022
        return false;
1023
    return true; // valid
1024
}
1025
//------------------------------------------------------------------------------
1026
FinalResults<long double> compute_score(const EvaluatedResults &results, std::vector<long double> &factors)
3,367 ✔
1027
{
1028
    FinalResults<long double> final{0, 0, 0, 0, 0, 0, results.second};
3,367 ✔
1029
    long double max_possible = max_possible_score[(size_t)optimization_mode];
3,367 ✔
1030
    for (unsigned index(0); index < results.first.size(); ++index)
10,686 ✔
1031
    {
1032
        // std::cout << results.second << " " << results.first[index].points << " " << results.first[index].count << std::endl;
1033
        final.wins += results.first[index].wins * factors[index] * results.second / results.first[index].count;
7,319 ✔
1034
        final.draws += results.first[index].draws * factors[index] * results.second / results.first[index].count;
7,319 ✔
1035
        final.losses += results.first[index].losses * factors[index] * results.second / results.first[index].count;
7,319 ✔
1036
        // APN
1037
        auto trials = results.second;
7,319 ✔
1038
        auto prob = 1 - confidence_level;
7,319 ✔
1039
        auto successes = results.first[index].points * results.second / results.first[index].count / max_possible;
7,319 ✔
1040
        if (successes > trials)
7,319 ✔
1041
        {
UNCOV
1042
            successes = trials;
×
1043
            // printf("WARNING: biominal successes > trials");
UNCOV
1044
            _DEBUG_MSG(2, "WARNING: biominal successes > trials");
×
1045
        }
1046

1047
        auto lower_bound = binomial_distribution::find_lower_bound_on_p(trials, successes, prob) * max_possible;
7,319 ✔
1048
        auto upper_bound = binomial_distribution::find_upper_bound_on_p(trials, successes, prob) * max_possible;
7,319 ✔
1049
        if (use_harmonic_mean)
7,319 ✔
1050
        {
UNCOV
1051
            final.points += factors[index] / (results.first[index].points * results.second / results.first[index].count);
×
UNCOV
1052
            final.points_lower_bound += factors[index] / lower_bound;
×
UNCOV
1053
            final.points_upper_bound += factors[index] / upper_bound;
×
1054
        }
1055
        else
1056
        {
1057
            final.points += results.first[index].points * factors[index] * results.second / results.first[index].count;
7,319 ✔
1058
            final.points_lower_bound += lower_bound * factors[index];
7,319 ✔
1059
            final.points_upper_bound += upper_bound * factors[index];
7,319 ✔
1060
        }
1061
    }
1062
    long double factor_sum = std::accumulate(factors.begin(), factors.end(), 0.);
3,367 ✔
1063
    final.wins /= factor_sum * (long double)results.second;
3,367 ✔
1064
    final.draws /= factor_sum * (long double)results.second;
3,367 ✔
1065
    final.losses /= factor_sum * (long double)results.second;
3,367 ✔
1066
    if (use_harmonic_mean)
3,367 ✔
1067
    {
UNCOV
1068
        final.points = factor_sum / ((long double)results.second * final.points);
×
UNCOV
1069
        final.points_lower_bound = factor_sum / final.points_lower_bound;
×
UNCOV
1070
        final.points_upper_bound = factor_sum / final.points_upper_bound;
×
1071
    }
1072
    else
1073
    {
1074
        final.points /= factor_sum * (long double)results.second;
3,367 ✔
1075
        final.points_lower_bound /= factor_sum;
3,367 ✔
1076
        final.points_upper_bound /= factor_sum;
3,367 ✔
1077
    }
1078
    return final;
3,367 ✔
1079
}
1080
//------------------------------------------------------------------------------
1081
//------------------------------------------------------------------------------
1082
// Per thread data.
1083
// seed should be unique for each thread.
1084
// d1 and d2 are intended to point to read-only process-wide data.
1085

1086
void SimulationData::set_decks(std::vector<Deck *> const your_decks_, std::vector<Deck *> const &enemy_decks_)
2,935 ✔
1087
{
1088
    for (unsigned i(0); i < your_decks_.size(); ++i)
6,311 ✔
1089
    {
1090
        your_decks[i].reset(your_decks_[i]->clone());
3,376 ✔
1091
        your_hands[i]->deck = your_decks[i].get();
3,376 ✔
1092
    }
1093
    for (unsigned i(0); i < enemy_decks_.size(); ++i)
6,311 ✔
1094
    {
1095
        enemy_decks[i].reset(enemy_decks_[i]->clone());
3,376 ✔
1096
        enemy_hands[i]->deck = enemy_decks[i].get();
3,376 ✔
1097
    }
1098
}
2,935 ✔
1099

1100
std::vector<std::unordered_map<std::string, std::string>> Process::samples()
1 ✔
1101
{
1102
    std::vector<std::unordered_map<std::string, std::string>> samples;
1 ✔
1103

1104
    int i = 0;
1 ✔
1105
    // loop over partial ids and prefix with f add to fmap
1106
    auto ids = partial_ids();
1 ✔
1107
    for (auto const &ydeck : your_decks)
2 ✔
1108
    {
1109
        auto yids = ydeck->sorted_ids();
1 ✔
1110
        for (auto const &edeck : enemy_decks)
2 ✔
1111
        {
1112
            auto eids = edeck->sorted_ids();
1 ✔
1113
            std::unordered_map<std::string, std::string> fmap;
1 ✔
1114
            i = 0;
1 ✔
1115
            for (auto const &id : ids)
92 ✔
1116
            {
1117
                fmap.emplace("f" + std::to_string(i), std::to_string(id));
182 ✔
1118
                i++;
91 ✔
1119
            }
1120
            i = 0;
1 ✔
1121
            for (auto const &id : yids)
13 ✔
1122
            {
1123
                fmap.emplace("y" + std::to_string(i), std::to_string(id->m_id));
24 ✔
1124
                i++;
12 ✔
1125
            }
1126
            // fill up with zeros up to id 12
1127
            while (i < 12)
1 ✔
1128
            {
UNCOV
1129
                fmap.emplace("y" + std::to_string(i), std::to_string(0));
×
UNCOV
1130
                i++;
×
1131
            }
1132
            i = 0;
1 ✔
1133
            for (auto const &id : eids)
13 ✔
1134
            {
1135
                fmap.emplace("e" + std::to_string(i), std::to_string(id->m_id));
24 ✔
1136
                i++;
12 ✔
1137
            }
1138
            // fill up with zeros up to id 12
1139
            while (i < 12)
1 ✔
1140
            {
UNCOV
1141
                fmap.emplace("e" + std::to_string(i), std::to_string(0));
×
UNCOV
1142
                i++;
×
1143
            }
1144
            samples.emplace_back(fmap);
1 ✔
1145
        }
1 ✔
1146
    }
1 ✔
1147
    /*
1148
    auto myMap = samples.at(0);
1149
    for(auto it = myMap.begin(); it != myMap.end(); ++it)
1150
    {
1151
        std::cout << it->first << " " << it->second  <<"\n";
1152
    }
1153
    */
1154

1155
    return samples;
1 ✔
1156
}
1 ✔
1157

1158
std::vector<std::array<std::string, 3>> Process::hashes()
2,856 ✔
1159
{
1160
    std::vector<std::array<std::string, 3>> hashes;
2,856 ✔
1161
    hashes.reserve(your_decks.size() * enemy_decks.size());
2,856 ✔
1162
    std::string hash = partial_hash();
2,856 ✔
1163
    for (auto const &ydeck : your_decks)
5,940 ✔
1164
    {
1165
        for (auto const &edeck : enemy_decks)
7,916 ✔
1166
        {
1167
            hashes.emplace_back(std::array<std::string, 3>{hash, ydeck->hash(), edeck->hash()});
14,496 ✔
1168
        }
1169
    }
1170
    return hashes;
2,856 ✔
1171
}
2,856 ✔
1172

1173
std::vector<unsigned int> Process::partial_ids()
2,857 ✔
1174
{
1175
    std::vector<unsigned int> ids;
2,857 ✔
1176
    ids.emplace_back(gamemode);
2,857 ✔
1177
    ids.emplace_back(optimization_mode);
2,857 ✔
1178
    for (int i = 0; i < Fix::num_fixes; ++i)
39,998 ✔
1179
    {
1180
        ids.emplace_back(fixes[i]);
37,141 ✔
1181
    }
1182
    ids.emplace_back(flexible_iter);
2,857 ✔
1183
    ids.emplace_back(flexible_turn);
2,857 ✔
1184
    ids.emplace_back(eval_iter);
2,857 ✔
1185
    ids.emplace_back(eval_turn);
2,857 ✔
1186
    for (int i = 0; i < PassiveBGE::num_passive_bges; ++i)
79,996 ✔
1187
        ids.emplace_back(your_bg_effects[i]);
77,139 ✔
1188
    for (int i = 0; i < PassiveBGE::num_passive_bges; ++i)
79,996 ✔
1189
        ids.emplace_back(enemy_bg_effects[i]);
77,139 ✔
1190
    if (your_bg_skills.size() > 0)
2,857 ✔
1191
    {
1192
        auto bge = your_bg_skills[0];
1 ✔
1193
        ids.emplace_back(bge.id);
1 ✔
1194
        ids.emplace_back(bge.x);
1 ✔
1195
        ids.emplace_back(bge.y);
1 ✔
1196
        ids.emplace_back(bge.n);
1 ✔
1197
        ids.emplace_back(bge.c);
1 ✔
1198
        ids.emplace_back(bge.s);
1 ✔
1199
        ids.emplace_back(bge.s2);
1 ✔
1200
        ids.emplace_back(bge.all);
1 ✔
1201
        ids.emplace_back(bge.card_id);
1 ✔
1202
    }
1203
    else
1204
    {
1205
        // emplace back 9 zeros
1206
        for (int i = 0; i < 9; ++i)
28,560 ✔
1207
            ids.emplace_back(0);
25,704 ✔
1208
    }
1209
    if (enemy_bg_skills.size() > 0)
2,857 ✔
1210
    {
1211
        auto bge = enemy_bg_skills[0];
1 ✔
1212
        ids.emplace_back(bge.id);
1 ✔
1213
        ids.emplace_back(bge.x);
1 ✔
1214
        ids.emplace_back(bge.y);
1 ✔
1215
        ids.emplace_back(bge.n);
1 ✔
1216
        ids.emplace_back(bge.c);
1 ✔
1217
        ids.emplace_back(bge.s);
1 ✔
1218
        ids.emplace_back(bge.s2);
1 ✔
1219
        ids.emplace_back(bge.all);
1 ✔
1220
        ids.emplace_back(bge.card_id);
1 ✔
1221
    }
1222
    else
1223
    {
1224
        // emplace back 9 zeros
1225
        for (int i = 0; i < 9; ++i)
28,560 ✔
1226
            ids.emplace_back(0);
25,704 ✔
1227
    }
1228

1229
    return ids;
2,857 ✔
UNCOV
1230
}
×
1231

1232
// Compute field hash from two decks
1233
std::string Process::partial_hash()
2,856 ✔
1234
{
1235
    // TODO fail if quest enabled since, db caching is incompatible with quest mode
1236
    std::stringstream ios;
2,856 ✔
1237
    for (auto id : partial_ids())
262,752 ✔
1238
        encode_id_ext_b64(ios, id);
262,752 ✔
1239

1240
    return ios.str();
5,712 ✔
1241
}
2,856 ✔
1242

1243
inline std::vector<Results<uint64_t>> SimulationData::evaluate(const std::vector<bool> &deck_mask)
1,172,316 ✔
1244
{
1245
    std::vector<Results<uint64_t>> res;
1,172,316 ✔
1246
    res.reserve(enemy_hands.size() * your_hands.size());
1,172,316 ✔
1247
    assert(deck_mask.size() == your_hands.size() * enemy_hands.size());
1,172,316 ✔
1248
    int i = 0;
1249
    for (Hand *your_hand : your_hands)
2,365,932 ✔
1250
    {
1251
        for (Hand *enemy_hand : enemy_hands)
2,552,432 ✔
1252
        {
1253
            // TUO5 added mask to already computed decks from db
1254
            if (deck_mask[i] != 0)
1,358,816 ✔
1255
            {
1256
                your_hand->reset(re);
1,358,816 ✔
1257
                enemy_hand->reset(re);
1,358,816 ✔
1258
                Field fd(re, cards, *your_hand, *enemy_hand, gamemode, optimization_mode,
1,358,816 ✔
1259
#ifndef NQUEST
1260
                         quest,
1261
#endif
1262
                         your_bg_effects, enemy_bg_effects, your_bg_skills, enemy_bg_skills, fixes, flexible_iter, flexible_turn, eval_iter, eval_turn);
1,358,816 ✔
1263
                Results<uint64_t> result(play(&fd));
1,358,816 ✔
1264
                if (__builtin_expect(mode_open_the_deck, false))
1,358,816 ✔
1265
                {
1266
                    // are there remaining (unopened) cards?
UNCOV
1267
                    if (fd.players[1]->deck->shuffled_cards.size())
×
1268
                    {
1269
                        // apply min score (there are unopened cards, so mission failed)
UNCOV
1270
                        result.points = min_possible_score[(size_t)optimization_mode];
×
1271
                    }
1272
                }
1273
                res.emplace_back(result);
1,358,816 ✔
1274
            }
1,358,816 ✔
1275
            else
1276
            {
UNCOV
1277
                res.emplace_back(Results<uint64_t>()); // no change since masked
×
1278
            }
1279
            i++;
1,358,816 ✔
1280
        }
1281
    }
1282
    // std::cout << std::endl<<  "Deck hash: " << your_hand.deck->hash() << "#"<< std::endl;
1283
    return (res);
1,172,316 ✔
UNCOV
1284
}
×
1285

1286
inline std::vector<Results<uint64_t>> SimulationData::evaluate()
1287
{
1288
    return evaluate(std::vector<bool>(your_hands.size() * enemy_hands.size(), true));
1289
}
1290
//------------------------------------------------------------------------------
1291

1292
//------------------------------------------------------------------------------
1293
// Process
1294
#ifdef _OPENMP
1295
void Process::openmp_evaluate_reduction(EvaluatedResults &evaluated_results)
1296
{
1297

1298
    std::vector<Results<uint64_t>> save_results(evaluated_results.first);
1299
    std::vector<Results<uint64_t>> results(evaluated_results.first);
1300
#pragma omp declare reduction(VecPlus                            \
1301
                              : std::vector <Results <uint64_t>> \
1302
                              : omp_out = merge(omp_out, omp_in))
1303
#pragma omp parallel default(none) shared(evaluated_results, thread_num_iterations, results)
1304
    {
1305
        SimulationData *sim = threads_data.at(omp_get_thread_num());
1306
        sim->set_decks(this->your_decks, this->enemy_decks);
1307
#pragma omp for reduction(VecPlus \
1308
                          : results) schedule(runtime)
1309
        for (unsigned i = 0; i < thread_num_iterations; ++i)
1310
        {
1311
            if (results.size() == 0)
1312
                results = sim->evaluate(mask); // calculate single sim
1313
            else
1314
            {
1315
                results = merge(results, sim->evaluate(mask)); // calculate single sim
1316
            }
1317
        }
1318
#pragma omp for schedule(runtime)
1319
        for (unsigned i = 0; i < results.size(); ++i)
1320
            evaluated_results.first[i] = results[i]; //+?
1321
    }
1322
    evaluated_results.second += thread_num_iterations;
1323
}
1324

1325
void Process::openmp_compare_reduction(EvaluatedResults &evaluated_results)
1326
{
1327

1328
    const unsigned c_num_threads = opt_num_threads;
1329
    std::vector<Results<uint64_t>> save_results(evaluated_results.first);
1330
    std::vector<Results<uint64_t>> results(evaluated_results.first);
1331
    bool compare_stop{false};
1332
    unsigned trials[c_num_threads] = {0};
1333
    long double successes[c_num_threads] = {.0};
1334
    const long double max_possible = max_possible_score[(size_t)optimization_mode];
1335
    const long double prob = 1 - confidence_level;
1336
    omp_lock_t locks[c_num_threads];
1337
    for (unsigned i = 0; i < c_num_threads; ++i)
1338
        omp_init_lock(&locks[i]);
1339
#pragma omp declare reduction(VecPlus                            \
1340
                              : std::vector <Results <uint64_t>> \
1341
                              : omp_out = merge(omp_out, omp_in))
1342
#pragma omp parallel default(none) shared(evaluated_results, trials, successes, locks, compare_stop, thread_num_iterations, results, \
1343
                                          thread_best_results, min_increment_of_score)
1344
    {
1345
        SimulationData *sim = threads_data.at(omp_get_thread_num());
1346
        sim->set_decks(this->your_decks, this->enemy_decks);
1347
        const long double sim_accum = std::accumulate(sim->factors.begin(), sim->factors.end(), .0);
1348
#pragma omp for reduction(VecPlus \
1349
                          : results) schedule(runtime)
1350
        for (unsigned i = 0; i < thread_num_iterations; ++i)
1351
        {
1352
#pragma omp cancellation point for
1353
            if (!compare_stop)
1354
            {
1355
                if (results.size() == 0)
1356
                    results = sim->evaluate(mask); // calculate single sim
1357
                else
1358
                    results = merge(results, sim->evaluate(mask)); // calculate single sim
1359
                long double score_accum_d = 0.0;
1360
                for (unsigned j = 0; j < results.size(); ++j)
1361
                    score_accum_d += results[j].points * sim->factors[j];
1362
                score_accum_d /= sim_accum * max_possible;
1363
                omp_set_lock(&locks[omp_get_thread_num()]);
1364
                trials[omp_get_thread_num()]++;
1365
                successes[omp_get_thread_num()] = score_accum_d;
1366
                omp_unset_lock(&locks[omp_get_thread_num()]);
1367
                // #pragma omp master
1368
                if (omp_get_thread_num() == 0)
1369
                {
1370

1371
                    unsigned ttrials = 0;
1372
                    long double ssuccesses = 0.0;
1373
                    for (unsigned l = 0; l < c_num_threads; ++l)
1374
                    {
1375
                        omp_set_lock(&locks[l]);
1376
                        ttrials += trials[l];
1377
                        ssuccesses += successes[l];
1378
                        omp_unset_lock(&locks[l]);
1379
                    }
1380
                    if (ssuccesses > ttrials)
1381
                    {
1382
                        ssuccesses = ttrials;
1383
                        printf("WARNING: biominal successes {%Le} > trials {%d} in Threads\n", ssuccesses, ttrials);
1384
                        //_DEBUG_MSG(2,"WARNING: biominal successes > trials in Threads");
1385
                    }
1386
                    compare_stop = (binomial_distribution::find_upper_bound_on_p(ttrials, ssuccesses, prob) * max_possible <
1387
                                    thread_best_results->points + min_increment_of_score);
1388
                    if (compare_stop)
1389
                    {
1390
#pragma omp cancel for
1391
                    }
1392
                }
1393
            }
1394
        }
1395
#pragma omp for schedule(runtime)
1396
        for (unsigned i = 0; i < results.size(); ++i)
1397
            evaluated_results.first[i] = results[i]; //+?
1398
    }
1399
    evaluated_results.second += thread_num_iterations;
1400
    for (unsigned i = 0; i < c_num_threads; ++i)
1401
        omp_destroy_lock(&locks[i]);
1402
}
1403

1404
std::vector<Results<uint64_t>> merge(std::vector<Results<uint64_t>> out, std::vector<Results<uint64_t>> in)
1405
{
1406
    // printf("merging out: %d in: %d \n", (int)out[0].wins, (int)in[0].wins);
1407
    // printf("out%p ",(void *)&out );
1408
    for (unsigned i = 0; i < out.size(); ++i)
1409
        out[i] += in[i];
1410
    // printf("merged out: %d \n", (int)out[0].wins);
1411
    return out;
1412
}
1413
#endif
1414

1415
inline bool Process::eval_ml(unsigned num_iterations, EvaluatedResults &evaluated_results)
2,851 ✔
1416
{
1417
    if (!use_ml)
2,851 ✔
1418
        return true;
1419
    bool run = false;
1 ✔
1420
    auto sampls = samples();
1 ✔
1421
    // iterate results from samples()
1422
    for (unsigned i = 0; i < sampls.size(); i++)
2 ✔
1423
    {
1424
        // already found in db?
1425
        if (mask[i])
1 ✔
1426
        {
1427
            auto s = sampls[i];
1 ✔
1428
            auto wins = atof(win_model.predict(s).c_str());
1 ✔
1429
            auto losses = atof(loss_model.predict(s).c_str());
1 ✔
1430
            auto draws = atof(stall_model.predict(s).c_str());
1 ✔
1431
            auto points = atof(points_model.predict(s).c_str());
1 ✔
1432
            if (wins < 0)
1 ✔
1433
                wins = 0;
1434
            if (losses < 0)
1 ✔
1435
                losses = 0;
1436
            if (draws < 0)
1 ✔
1437
                draws = 0;
1438
            if (points < 0)
1 ✔
1439
                points = 0;
1440
            // if((wins + losses + draws) > 1.05 || (wins + losses + draws) < 0.95) {
1441
            //     std::cout << "WARNING: ML model returned invalid sample: " << wins << " "  << draws << " " <<losses << " points " << points << std::endl;
1442
            // }
1443
            if (use_only_ml || ((wins + losses + draws) < 1.00 + ml_precision && (wins + losses + draws) > 1.00 - ml_precision)) // we use the sum of wins, losses and draws to determine if the sample is valid
1 ✔
1444
            {
1445
                // std::cout << "ML model returned: " << wins << " "  << draws << " " <<losses << " points " << points << " " << num_iterations << std::endl;
1446
                mask[i] = false;
1 ✔
1447
                Results<uint64_t> r = {
1 ✔
1448
                    static_cast<uint64_t>(std::round((1.0 * wins * num_iterations / (wins + losses + draws)))),
1 ✔
1449
                    static_cast<uint64_t>(std::round((1.0 * draws * num_iterations / (wins + losses + draws)))),
1 ✔
1450
                    static_cast<uint64_t>(std::round((1.0 * losses * num_iterations / (wins + losses + draws)))),
1 ✔
1451
                    static_cast<uint64_t>(std::round((1.0 * points * num_iterations))),
1 ✔
1452
                    static_cast<uint64_t>(num_iterations)};
1 ✔
1453
                evaluated_results.first[i] = r;
1 ✔
1454
            }
1 ✔
1455
            else
1456
            {
UNCOV
1457
                mask[i] = true;
×
UNCOV
1458
                run = true;
×
1459
            }
1460
        }
1 ✔
1461
    }
1462

1463
    return run;
1 ✔
1464
}
1 ✔
1465

1466
inline bool Process::check_db(std::vector<std::array<std::string, 3>> const &vhashes, unsigned num_iterations, EvaluatedResults &evaluated_results)
2,856 ✔
1467
{
1468
    if (!use_db_load)
2,856 ✔
1469
        return true;
1470
    bool run = false;
1471
    // TODO TUO5 check db for results
1472
    //  TODO TUO5 calculate mask for sim evaluate based on missing results in db
1473
    for (unsigned i = 0; i < vhashes.size(); i++)
2,168 ✔
1474
    {
1475
        bool found = false;
2,072 ✔
1476
        std::string hash = vhashes[i][0];
2,072 ✔
1477
        // TODO TUO5 check db for hash
1478
        auto it1 = database.find(hash);
2,072 ✔
1479
        std::map<std::string, Results<uint64_t>>::iterator it;
2,072 ✔
1480
        if (it1 != database.end())
2,072 ✔
1481
        {
1482
            auto it2 = it1->second.find(vhashes[i][1]);
682 ✔
1483
            if (it2 != it1->second.end())
682 ✔
1484
            {
1485
                auto it3 = it2->second.find(vhashes[i][2]);
117 ✔
1486
                if (it3 != it2->second.end())
117 ✔
1487
                {
1488
                    it = it3;
116 ✔
1489
                    found = true;
116 ✔
1490
                    // std::cout << "hit databse" << std::endl;
1491
                }
1492
            }
1493
        }
1494
        // TODO TUO5 if hash not in db, add to mask
1495
        if (!found)
116 ✔
1496
        {
1497
            mask[i] = true;
1,956 ✔
1498
            run = true;
1,956 ✔
1499
        }
1500
        else
1501
        {
1502
            if (it->second.count >= num_iterations)
116 ✔
1503
            {
1504
                mask[i] = false;
116 ✔
1505
                // TUO5 load results from db
1506
                // renormalized to asked num_iterations
1507
                Results<uint64_t> r = {
116 ✔
1508
                    static_cast<uint64_t>(std::round((1.0 * it->second.wins * num_iterations) / it->second.count)),
116 ✔
1509
                    static_cast<uint64_t>(std::round((1.0 * it->second.draws * num_iterations) / it->second.count)),
116 ✔
1510
                    static_cast<uint64_t>(std::round((1.0 * it->second.losses * num_iterations) / it->second.count)),
116 ✔
1511
                    static_cast<uint64_t>(std::round((1.0 * it->second.points * num_iterations) / it->second.count)),
116 ✔
1512
                    static_cast<uint64_t>(num_iterations)};
116 ✔
1513
                evaluated_results.first[i] = r;
116 ✔
1514
            }
1515
            else
1516
            {
UNCOV
1517
                mask[i] = true;
×
UNCOV
1518
                run = true;
×
1519
            }
1520
        }
1521
    }
2,072 ✔
1522
    return run;
1523
}
1524

1525
inline void Process::save_db(std::vector<std::array<std::string, 3>> const &vhashes, EvaluatedResults &evaluated_results)
2,850 ✔
1526
{
1527
    // TODO TUO5 save results to db
1528
    for (unsigned i = 0; i < vhashes.size(); i++)
7,565 ✔
1529
    {
1530
        if (mask[i])
4,715 ✔
1531
        {
1532
            std::array<std::string, 3> hash = vhashes[i];
4,715 ✔
1533
            // check if map is initialized otherwise initialize
1534
            if (database.find(hash[0]) == database.end())
4,715 ✔
1535
            {
1536
                database[hash[0]] = std::map<std::string, std::map<std::string, Results<uint64_t>>>();
50 ✔
1537
            }
1538
            if (database[hash[0]].find(hash[1]) == database[hash[0]].end())
4,715 ✔
1539
            {
1540
                database[hash[0]][hash[1]] = std::map<std::string, Results<uint64_t>>();
2,455 ✔
1541
            }
1542
            database[hash[0]][hash[1]][hash[2]] = evaluated_results.first[i];
4,715 ✔
1543
        }
4,715 ✔
1544
    }
1545
}
2,850 ✔
1546

1547
EvaluatedResults &Process::evaluate(unsigned num_iterations, EvaluatedResults &evaluated_results)
438 ✔
1548
{
1549
    if (num_iterations <= evaluated_results.second)
438 ✔
1550
    {
1551
        return evaluated_results;
1552
    }
1553
    std::vector<std::array<std::string, 3>> vhashes = hashes();
239 ✔
1554
    // fill mask with true
1555
    mask = std::vector<bool>(vhashes.size(), true);
239 ✔
1556
    if (!check_db(vhashes, num_iterations, evaluated_results))
239 ✔
1557
    {
1558
        // 100% covered by db
1559
        evaluated_results.second = num_iterations;
5 ✔
1560
        return evaluated_results;
5 ✔
1561
    }
1562
    if (!eval_ml(num_iterations, evaluated_results))
234 ✔
1563
    {
1564
        // ml is good
1565
        evaluated_results.second = num_iterations;
1 ✔
1566
        return evaluated_results;
1 ✔
1567
    }
1568

1569
    thread_num_iterations = num_iterations - evaluated_results.second;
233 ✔
1570
    thread_results = &evaluated_results;
233 ✔
1571
    thread_compare = false;
233 ✔
1572
#ifndef _OPENMP
1573
    // unlock all the threads
1574
    main_barrier.wait();
233 ✔
1575
    // wait for the threads
1576
    main_barrier.wait();
233 ✔
1577
#else
1578
    openmp_evaluate_reduction(evaluated_results);
1579
#endif
1580
    save_db(vhashes, evaluated_results);
233 ✔
1581

1582
    return evaluated_results;
1583
}
239 ✔
1584

1585
EvaluatedResults &Process::compare(unsigned num_iterations, EvaluatedResults &evaluated_results, const FinalResults<long double> &best_results)
2,810 ✔
1586
{
1587
    if (num_iterations <= evaluated_results.second)
2,810 ✔
1588
    {
1589
        return evaluated_results;
1590
    }
1591
    std::vector<std::array<std::string, 3>> vhashes = hashes();
2,617 ✔
1592
    // fill mask with true
1593
    mask = std::vector<bool>(vhashes.size(), true);
2,617 ✔
1594
    if (!check_db(vhashes, num_iterations, evaluated_results))
2,617 ✔
1595
    {
1596
        // 100% covered by db
UNCOV
1597
        evaluated_results.second = num_iterations;
×
1598
        return evaluated_results;
×
1599
    }
1600
    if (!eval_ml(num_iterations, evaluated_results))
2,617 ✔
1601
    {
1602
        // ml is good
UNCOV
1603
        evaluated_results.second = num_iterations;
×
UNCOV
1604
        return evaluated_results;
×
1605
    }
1606
    thread_num_iterations = num_iterations - evaluated_results.second;
2,617 ✔
1607
    thread_results = &evaluated_results;
2,617 ✔
1608
    thread_best_results = &best_results;
2,617 ✔
1609
    thread_compare = true;
2,617 ✔
1610
    thread_compare_stop = false;
2,617 ✔
1611
#ifndef _OPENMP
1612
    // unlock all the threads
1613
    main_barrier.wait();
2,617 ✔
1614
    // wait for the threads
1615
    main_barrier.wait();
2,617 ✔
1616
#else
1617
    openmp_compare_reduction(evaluated_results);
1618
#endif
1619
    save_db(vhashes, evaluated_results);
2,617 ✔
1620
    return evaluated_results;
1621
}
2,617 ✔
1622
//------------------------------------------------------------------------------
1623
void thread_evaluate(boost::barrier &main_barrier,
85 ✔
1624
                     boost::mutex &shared_mutex,
1625
                     SimulationData &sim,
1626
                     const Process &p,
1627
                     unsigned thread_id)
1628
{
1629
#ifndef _OPENMP
1630
    while (true)
5,785 ✔
1631
    {
1632
        main_barrier.wait();
2,935 ✔
1633
        sim.set_decks(p.your_decks, p.enemy_decks);
2,935 ✔
1634
        if (destroy_threads)
2,935 ✔
1635
        {
1636
            return;
85 ✔
1637
        }
1638
        while (true)
2,347,482 ✔
1639
        {
1640
            shared_mutex.lock();                                                       //<<<<
1,175,166 ✔
1641
            if (thread_num_iterations == 0 || (thread_compare && thread_compare_stop)) //!
1,175,166 ✔
1642
            {
1643
                shared_mutex.unlock(); //>>>>
2,850 ✔
1644
                main_barrier.wait();
2,850 ✔
1645
                break;
2,850 ✔
1646
            }
1647
            else
1648
            {
1649
                --thread_num_iterations; //!
1,172,316 ✔
1650
                shared_mutex.unlock();   //>>>>
1,172,316 ✔
1651
                std::vector<Results<uint64_t>> result{sim.evaluate(p.mask)};
1,172,316 ✔
1652
                shared_mutex.lock();                                                        //<<<<
1,172,316 ✔
1653
                std::vector<uint64_t> thread_score_local(thread_results->first.size(), 0u); //!
1,172,316 ✔
1654
                unsigned counter = 0;
1,172,316 ✔
1655
                for (unsigned index(0); index < result.size(); ++index)
2,531,132 ✔
1656
                {
1657
                    thread_results->first[index] += result[index]; //!
1,358,816 ✔
1658
                    if (counter == 0 || thread_results->first[index].count < counter)
1,358,816 ✔
1659
                    {
1660
                        counter = thread_results->first[index].count;
1,172,316 ✔
1661
                    }
1662
                }
1663
                for (unsigned index(0); index < result.size(); ++index)
2,531,132 ✔
1664
                {
1665
                    // TUO5 we weight scores by the number of times a deck is used, since the results are no langer same sized in partially cached case
1666
                    thread_score_local[index] = (thread_results->first[index].points * (counter)) / thread_results->first[index].count; //!
1,358,816 ✔
1667
                                                                                                                                        // thread_score_local[index] = static_cast<uint64_t>(std::round((thread_results->first[index].points * (counter))/thread_results->first[index].count)); //!
1668
                }
1669
                ++thread_results->second;                            //!
1,172,316 ✔
1670
                unsigned thread_total_local{thread_results->second}; //!
1,172,316 ✔
1671
                shared_mutex.unlock();                               //>>>>
1,172,316 ✔
1672
                if (thread_compare && thread_id == 0 && thread_total_local > 1)
1,172,316 ✔
1673
                {
1674
                    unsigned score_accum = 0;
801,199 ✔
1675
                    // Multiple defense decks case: scaling by factors and approximation of a "discrete" number of events.
1676
                    if (result.size() > 1)
801,199 ✔
1677
                    {
1678
                        long double score_accum_d = 0.0;
1679
                        for (unsigned i = 0; i < thread_score_local.size(); ++i)
×
1680
                        {
UNCOV
1681
                            score_accum_d += thread_score_local[i] * sim.factors[i];
×
1682
                        }
UNCOV
1683
                        score_accum_d /= std::accumulate(sim.factors.begin(), sim.factors.end(), .0);
×
1684
                        score_accum = score_accum_d;
×
1685
                    }
1686
                    else
1687
                    {
1688
                        score_accum = thread_score_local[0];
801,199 ✔
1689
                    }
1690
                    bool compare_stop(false);
801,199 ✔
1691
                    long double max_possible = max_possible_score[(size_t)optimization_mode];
801,199 ✔
1692

1693
                    // APN
1694
                    auto trials = thread_total_local;
801,199 ✔
1695
                    auto prob = 1 - confidence_level;
801,199 ✔
1696
                    auto successes = score_accum / max_possible;
801,199 ✔
1697
                    if (successes > trials)
801,199 ✔
1698
                    {
UNCOV
1699
                        std::cout << "WARNING: biominal successes > trials in Threads" << successes << " " << trials << " " << counter << std::endl;
×
UNCOV
1700
                        _DEBUG_MSG(2, "WARNING: biominal successes > trials in Threads");
×
1701
                        successes = trials;
1,172,316 ✔
1702
                    }
1703
                    else
1704
                    {
1705

1706
                        // Get a loose (better than no) upper bound. TODO: Improve it.
1707
                        compare_stop = (binomial_distribution::find_upper_bound_on_p(trials, successes, prob) * max_possible <
801,199 ✔
1708
                                        thread_best_results->points + min_increment_of_score);
801,199 ✔
1709
                        if (compare_stop)
801,199 ✔
1710
                        {
1711
                            shared_mutex.lock(); //<<<<
2,129 ✔
1712
                            // std::cout << thread_total_local << "\n";
1713
                            thread_compare_stop = true; //!
2,129 ✔
1714
                            shared_mutex.unlock();      //>>>>
2,129 ✔
1715
                        }
1716
                    }
1717
                }
1718
            }
1,172,316 ✔
1719
        }
1,172,316 ✔
1720
    }
2,850 ✔
1721
#endif
1722
}
1723
//------------------------------------------------------------------------------
1724
void print_score_info(const EvaluatedResults &results, std::vector<long double> &factors)
41 ✔
1725
{
1726
    auto final = compute_score(results, factors);
41 ✔
1727
    std::cout << final.points << " (";
41 ✔
1728
    if (!simplify_output)
41 ✔
1729
    {
1730
        if (show_ci)
41 ✔
1731
        {
UNCOV
1732
            std::cout << final.points_lower_bound << "-" << final.points_upper_bound << ", ";
×
1733
        }
1734
        for (const auto &val : results.first)
82 ✔
1735
        {
1736
            switch (optimization_mode)
41 ✔
1737
            {
UNCOV
1738
            case OptimizationMode::raid:
×
UNCOV
1739
            case OptimizationMode::campaign:
×
UNCOV
1740
            case OptimizationMode::brawl:
×
UNCOV
1741
            case OptimizationMode::brawl_defense:
×
UNCOV
1742
            case OptimizationMode::war:
×
UNCOV
1743
            case OptimizationMode::war_defense:
×
1744
#ifndef NQUEST
1745
            case OptimizationMode::quest:
1746
#endif
UNCOV
1747
                std::cout << val.points << " ";
×
1748
                break;
1749
            default:
41 ✔
1750
                std::cout << val.points / 100 << " ";
41 ✔
1751
                break;
1752
            }
1753
        }
1754
    }
1755
    else
1756
    {
UNCOV
1757
        std::cout << "...";
×
1758
    }
1759
    std::cout << "/ " << results.second << ")" << std::endl;
41 ✔
1760
}
41 ✔
1761
//------------------------------------------------------------------------------
1762
void print_results(const EvaluatedResults &results, std::vector<long double> &factors)
78 ✔
1763
{
1764
    auto final = compute_score(results, factors);
78 ✔
1765
    std::cout << "win%: " << final.wins * 100.0 << " (";
78 ✔
1766
    if (!simplify_output)
78 ✔
1767
    {
1768
        for (const auto &val : results.first)
2,132 ✔
1769
        {
1770
            std::cout << val.wins << " ";
2,054 ✔
1771
        }
1772
    }
1773
    else
1774
    {
UNCOV
1775
        std::cout << "...";
×
1776
    }
1777
    std::cout << "/ " << results.second << ")" << std::endl;
78 ✔
1778

1779
    std::cout << "stall%: " << final.draws * 100.0 << " (";
78 ✔
1780
    if (!simplify_output)
78 ✔
1781
    {
1782
        for (const auto &val : results.first)
2,132 ✔
1783
        {
1784
            std::cout << val.draws << " ";
2,054 ✔
1785
        }
1786
    }
1787
    else
1788
    {
UNCOV
1789
        std::cout << "...";
×
1790
    }
1791
    std::cout << "/ " << results.second << ")" << std::endl;
78 ✔
1792

1793
    std::cout << "loss%: " << final.losses * 100.0 << " (";
78 ✔
1794
    if (!simplify_output)
78 ✔
1795
    {
1796
        for (const auto &val : results.first)
2,132 ✔
1797
        {
1798
            std::cout << val.losses << " ";
2,054 ✔
1799
        }
1800
    }
1801
    else
1802
    {
UNCOV
1803
        std::cout << "...";
×
1804
    }
1805
    std::cout << "/ " << results.second << ")" << std::endl;
78 ✔
1806

1807
#ifndef NQUEST
1808
    if (optimization_mode == OptimizationMode::quest)
1809
    {
1810
        // points = win% * win_score + (must_win ? win% : 100%) * quest% * quest_score
1811
        // quest% = (points - win% * win_score) / (must_win ? win% : 100%) / quest_score
1812
        std::cout << "quest%: " << (final.points - final.wins * tuo::quest.win_score) / (tuo::quest.must_win ? final.wins : 1) / tuo::quest.quest_score * 100 << std::endl;
1813
    }
1814
#endif
1815

1816
    unsigned min_score = min_possible_score[(size_t)optimization_mode];
78 ✔
1817
    unsigned max_score = max_possible_score[(size_t)optimization_mode];
78 ✔
1818
    switch (optimization_mode)
78 ✔
1819
    {
1820
    case OptimizationMode::raid:
×
1821
    case OptimizationMode::campaign:
×
1822
    case OptimizationMode::brawl:
×
1823
    case OptimizationMode::brawl_defense:
×
1824
    case OptimizationMode::war:
×
UNCOV
1825
    case OptimizationMode::war_defense:
×
1826
#ifndef NQUEST
1827
    case OptimizationMode::quest:
1828
#endif
UNCOV
1829
        std::cout << "score: " << final.points;
×
UNCOV
1830
        if (optimization_mode == OptimizationMode::brawl)
×
1831
        {
UNCOV
1832
            auto win_points = final.wins ? ((final.points - min_score * (1.0 - final.wins)) / final.wins) : final.points;
×
UNCOV
1833
            std::cout << " [" << win_points << " per win]";
×
1834
        }
UNCOV
1835
        else if (optimization_mode == OptimizationMode::brawl_defense)
×
1836
        {
UNCOV
1837
            auto opp_win_points = final.losses ? max_score - ((final.points - (max_score - min_score) * (1.0 - final.losses)) / final.losses) : final.points;
×
1838
            std::cout << " [" << opp_win_points << " per opp win]";
×
1839
        }
UNCOV
1840
        else if (optimization_mode == OptimizationMode::war)
×
1841
        {
UNCOV
1842
            auto win_points = final.wins ? ((final.points - min_score * (1.0 - final.wins)) / final.wins) : final.points;
×
UNCOV
1843
            std::cout << " [" << win_points << " per win]";
×
1844
        }
UNCOV
1845
        else if (optimization_mode == OptimizationMode::war_defense)
×
1846
        {
UNCOV
1847
            auto opp_win_points = final.losses ? max_score - ((final.points - (max_score - min_score) * (1.0 - final.losses)) / final.losses) : final.points;
×
UNCOV
1848
            std::cout << " [" << opp_win_points << " per opp win]";
×
1849
        }
UNCOV
1850
        std::cout << " (";
×
UNCOV
1851
        if (!simplify_output)
×
1852
        {
UNCOV
1853
            for (const auto &val : results.first)
×
1854
            {
UNCOV
1855
                std::cout << val.points << " ";
×
1856
            }
1857
        }
1858
        else
1859
        {
UNCOV
1860
            std::cout << "...";
×
1861
        }
UNCOV
1862
        std::cout << "/ " << results.second << ")" << std::endl;
×
UNCOV
1863
        if (show_ci)
×
1864
        {
UNCOV
1865
            std::cout << "ci: " << final.points_lower_bound << " - " << final.points_upper_bound << std::endl;
×
1866
        }
1867
        break;
1868
    default:
1869
        break;
1870
    }
1871
}
78 ✔
1872

1873
//------------------------------------------------------------------------------
1874
// Prints which cards have been upgraded
1875
void print_upgraded_cards(Deck *deck)
7 ✔
1876
{
1877
    if (!print_upgraded)
7 ✔
1878
        return;
7 ✔
UNCOV
1879
    auto owned_cards_c = owned_cards;
×
UNCOV
1880
    std::cout << "Upgraded Cards: ";
×
UNCOV
1881
    auto cards = deck->cards;
×
UNCOV
1882
    cards.insert(cards.begin(), deck->commander);
×
UNCOV
1883
    for (const Card *card : cards)
×
1884
    {
1885

UNCOV
1886
        if ((card->m_set == 1000) && (card->m_rarity <= 2) && (card->is_low_level_card()))
×
1887
        {
UNCOV
1888
            continue;
×
1889
        }
1890

UNCOV
1891
        if ((card->m_id == 50002) || (card->m_category == CardCategory::dominion_material))
×
1892
        {
UNCOV
1893
            continue;
×
1894
        }
1895

UNCOV
1896
        if ((fund || (card->m_category != CardCategory::normal)) && (owned_cards_c[card->m_id] == 0))
×
1897
        {
1898
            // print card
UNCOV
1899
            std::cout << card->m_name << ", ";
×
1900
        }
1901
        if (owned_cards_c[card->m_id] > 0)
×
1902
            owned_cards_c[card->m_id]--;
×
1903
    }
1904
    std::cout << std::endl;
×
1905
}
×
1906
//------------------------------------------------------------------------------
1907
void print_cards_inline(std::vector<const Card *> cards, std::ostream &os, Deck *deck)
1,349 ✔
1908
{
1909
    std::string last_name = "";
1,349 ✔
1910
    unsigned num_repeat(0);
1,349 ✔
1911
    bool first = true;
1,349 ✔
1912

1913
    // for (const Card* card: cards)
1914
    //{
1915
    for (unsigned i = 0; i < cards.size(); ++i)
14,384 ✔
1916
    {
1917
        auto card = cards[i];
13,035 ✔
1918

1919
        if (deck == nullptr && card->m_name == last_name)
13,035 ✔
1920
        {
1921
            ++num_repeat;
×
1922
        }
1923
        else
1924
        {
1925
            if (num_repeat > 1)
13,035 ✔
1926
            {
UNCOV
1927
                os << " #" << num_repeat;
×
1928
            }
1929
            if (deck != nullptr)
13,035 ✔
1930
                os << (first ? "" : ", ") << (deck->card_marks[i] == '!' ? "!" : "") << card->m_name;
1,833 ✔
1931
            else
1932
                os << (first ? "" : ", ") << card->m_name;
23,532 ✔
1933
            first = false;
13,035 ✔
1934
            last_name = card->m_name;
26,070 ✔
1935
            num_repeat = 1;
1936
        }
1937
    }
1938
    if (num_repeat > 1)
1,349 ✔
1939
    {
UNCOV
1940
        os << " #" << num_repeat;
×
1941
    }
1942
    os << "\n";
1,349 ✔
1943
}
1,349 ✔
1944
void print_score_inline(const FinalResults<long double> score)
1,264 ✔
1945
{
1946
    // print optimization result details
1947
    switch (optimization_mode)
1,264 ✔
1948
    {
UNCOV
1949
    case OptimizationMode::raid:
×
UNCOV
1950
    case OptimizationMode::campaign:
×
UNCOV
1951
    case OptimizationMode::brawl:
×
UNCOV
1952
    case OptimizationMode::brawl_defense:
×
UNCOV
1953
    case OptimizationMode::war:
×
UNCOV
1954
    case OptimizationMode::war_defense:
×
1955
#ifndef NQUEST
1956
    case OptimizationMode::quest:
1957
#endif
UNCOV
1958
        std::cout << "(" << score.wins * 100 << "% win";
×
1959
#ifndef NQUEST
1960
        if (optimization_mode == OptimizationMode::quest)
1961
        {
1962
            std::cout << ", " << (score.points - score.wins * tuo::quest.win_score) / (tuo::quest.must_win ? score.wins : 1) / tuo::quest.quest_score * 100 << "% quest";
1963
        }
1964
#endif
UNCOV
1965
        if (show_ci)
×
1966
        {
1967
            std::cout << ", " << score.points_lower_bound << "-" << score.points_upper_bound;
×
1968
        }
1969
        std::cout << ") ";
×
UNCOV
1970
        break;
×
UNCOV
1971
    case OptimizationMode::defense:
×
1972
        std::cout << "(" << score.draws * 100.0 << "% stall) ";
×
UNCOV
1973
        break;
×
1974
    default:
1975
        break;
1976
    }
1977
    std::cout << score.points;
1,264 ✔
1978
    unsigned min_score = min_possible_score[(size_t)optimization_mode];
1,264 ✔
1979
    unsigned max_score = max_possible_score[(size_t)optimization_mode];
1,264 ✔
1980
    if (optimization_mode == OptimizationMode::brawl)
1,264 ✔
1981
    {
1982
        auto win_points = score.wins ? ((score.points - min_score * (1.0 - score.wins)) / score.wins) : score.points;
×
1983
        std::cout << " [" << win_points << " per win]";
×
1984
    }
1985
    else if (optimization_mode == OptimizationMode::brawl_defense)
1,264 ✔
1986
    {
UNCOV
1987
        auto opp_win_points = score.losses ? max_score - ((score.points - (max_score - min_score) * (1.0 - score.losses)) / score.losses) : score.points;
×
UNCOV
1988
        std::cout << " [" << opp_win_points << " per opp win]";
×
1989
    }
1990
    else if (optimization_mode == OptimizationMode::war)
1,264 ✔
1991
    {
UNCOV
1992
        auto win_points = score.wins ? ((score.points - min_score * (1.0 - score.wins)) / score.wins) : score.points;
×
UNCOV
1993
        std::cout << " [" << win_points << " per win]";
×
1994
    }
1995
    else if (optimization_mode == OptimizationMode::war_defense)
1,264 ✔
1996
    {
UNCOV
1997
        auto opp_win_points = score.losses ? max_score - ((score.points - (max_score - min_score) * (1.0 - score.losses)) / score.losses) : score.points;
×
UNCOV
1998
        std::cout << " [" << opp_win_points << " per opp win]";
×
1999
    }
2000
}
1,264 ✔
2001
//------------------------------------------------------------------------------
2002
// Calculates and prints individual card value in this deck
2003
void print_sim_card_values(Deck *original_deck, Process &p, unsigned iter) // run_deck == p.your_decks[0]
85 ✔
2004
{
2005
    if (!print_values && vc_x == 0)
85 ✔
2006
        return;
85 ✔
UNCOV
2007
    if (p.your_decks.size() != 1)
×
2008
        return; // only for single deck
2009
    // auto deck = original_deck;
UNCOV
2010
    if (original_deck->strategy == DeckStrategy::random || original_deck->strategy == DeckStrategy::flexible || original_deck->strategy == DeckStrategy::evaluate || original_deck->strategy == DeckStrategy::evaluate_twice)
×
2011
    {
UNCOV
2012
        std::sort(original_deck->cards.begin(), original_deck->cards.end(), [](const Card *a, const Card *b)
×
UNCOV
2013
                  { return a->m_id < b->m_id; });
×
2014
    }
UNCOV
2015
    std::string last_name;
×
UNCOV
2016
    long double score;
×
UNCOV
2017
    Deck *sim_deck = p.your_decks[0];
×
UNCOV
2018
    Deck *your_deck = original_deck->clone(); // save the original deck
×
UNCOV
2019
    auto cards = your_deck->cards;
×
2020
    // sim original/base result
2021
    sim_deck->commander = your_deck->commander;
×
UNCOV
2022
    sim_deck->cards = your_deck->cards;
×
UNCOV
2023
    sim_deck->alpha_dominion = your_deck->alpha_dominion;
×
UNCOV
2024
    EvaluatedResults results = {EvaluatedResults::first_type(p.enemy_decks.size() * p.your_decks.size()), 0};
×
UNCOV
2025
    results = p.evaluate(iter, results);
×
UNCOV
2026
    const FinalResults<long double> fr_base = compute_score(results, p.factors);
×
UNCOV
2027
    long double base = fr_base.points;
×
UNCOV
2028
    std::multimap<long double, std::string> msn;
×
UNCOV
2029
    std::multimap<std::string, long double> mns;
×
2030
    for (unsigned i = 0; i < cards.size(); ++i)
×
2031
    {
2032
        auto card = cards[i];
×
2033
        // if (card->m_name == last_name)
2034
        //{
2035
        // }
2036
        // else
2037
        //{
UNCOV
2038
        last_name = card->m_name;
×
2039
        // sim it
UNCOV
2040
        sim_deck->cards = your_deck->cards;                 // reset cards
×
UNCOV
2041
        sim_deck->cards.erase(sim_deck->cards.begin() + i); // remove to test card
×
UNCOV
2042
        EvaluatedResults results = {EvaluatedResults::first_type(p.enemy_decks.size() * p.your_decks.size()), 0};
×
UNCOV
2043
        results = p.evaluate(iter, results);
×
UNCOV
2044
        const FinalResults<long double> fr = compute_score(results, p.factors);
×
UNCOV
2045
        score = base - fr.points; // subtract from result to get value
×
2046
        // std::cout << card->m_name << " (" << score << "), ";
UNCOV
2047
        msn.insert(std::make_pair(score, card->m_name));
×
2048
        mns.insert(std::make_pair(card->m_name, score));
×
2049
        //}
2050
    }
×
2051
    sim_deck->cards = your_deck->cards; // reset cards
×
2052
    if (vc_x > 0)
×
2053
    {
2054
        // std::cout << "Locked Deck: ";
2055
        ////std::cout << original_deck->cards.size() << " units: ";
2056
        ////print_score_inline(fr_base);
2057
        ////std::cout <<  ": ";
2058
        // std::cout << original_deck->commander->m_name;
2059
        //  print dominions
2060
        // if (original_deck->alpha_dominion)
2061
        //{ std::cout << ", " << original_deck->alpha_dominion->m_name; }
2062

2063
        for (unsigned i = 0; i < cards.size(); ++i)
×
2064
        {
UNCOV
2065
            original_deck->card_marks.erase(i);
×
UNCOV
2066
            if (vc_x >= std::distance(msn.find(mns.find(cards[i]->m_name)->second), msn.end())) // or mns.start()
×
2067
            {
2068
                original_deck->card_marks[i] = '!';
×
2069
            }
2070
        }
2071
    }
UNCOV
2072
    if (print_values)
×
2073
    {
2074
        std::cout << "Value of Cards: ";
×
UNCOV
2075
        for (unsigned i = 0; i < cards.size(); ++i)
×
2076
        {
UNCOV
2077
            std::cout << cards[i]->m_name << " (" << mns.find(cards[i]->m_name)->second << "), ";
×
2078
        }
2079
        std::cout << std::endl;
×
2080
    }
UNCOV
2081
}
×
2082
//------------------------------------------------------------------------------
2083
void print_deck_inline(const unsigned deck_cost, const FinalResults<long double> score, Deck *deck, bool print_locked)
1,264 ✔
2084
{
2085
    // print units count
2086
    std::cout << deck->cards.size() << " units: ";
1,264 ✔
2087

2088
    // print deck cost (if fund is enabled)
2089
    if (fund > 0)
1,264 ✔
2090
    {
2091
        std::cout << "$" << deck_cost << " ";
×
2092
    }
2093
    print_score_inline(score);
1,264 ✔
2094
    /*
2095
    // print optimization result details
2096
    switch(optimization_mode)
2097
    {
2098
    case OptimizationMode::raid:
2099
    case OptimizationMode::campaign:
2100
    case OptimizationMode::brawl:
2101
    case OptimizationMode::brawl_defense:
2102
    case OptimizationMode::war:
2103
    case OptimizationMode::war_defense:
2104
#ifndef NQUEST
2105
case OptimizationMode::quest:
2106
#endif
2107
std::cout << "(" << score.wins * 100 << "% win";
2108
#ifndef NQUEST
2109
if (optimization_mode == OptimizationMode::quest)
2110
{
2111
std::cout << ", " << (score.points - score.wins * quest.win_score) / (quest.must_win ? score.wins : 1) / quest.quest_score * 100 << "% quest";
2112
}
2113
#endif
2114
if (show_ci)
2115
{
2116
std::cout << ", " << score.points_lower_bound << "-" << score.points_upper_bound;
2117
}
2118
std::cout << ") ";
2119
break;
2120
case OptimizationMode::defense:
2121
std::cout << "(" << score.draws * 100.0 << "% stall) ";
2122
break;
2123
default:
2124
break;
2125
}
2126
std::cout << score.points;
2127
unsigned min_score = min_possible_score[(size_t)optimization_mode];
2128
unsigned max_score = max_possible_score[(size_t)optimization_mode];
2129
if (optimization_mode == OptimizationMode::brawl)
2130
{
2131
auto win_points = score.wins ? ((score.points - min_score * (1.0 - score.wins)) / score.wins) : score.points;
2132
std::cout << " [" << win_points << " per win]";
2133
}
2134
else if (optimization_mode == OptimizationMode::brawl_defense)
2135
{
2136
auto opp_win_points = score.losses ? max_score - ((score.points - (max_score - min_score) * (1.0 - score.losses)) / score.losses) : score.points;
2137
std::cout << " [" << opp_win_points << " per opp win]";
2138
}
2139
else if (optimization_mode == OptimizationMode::war)
2140
{
2141
auto win_points = score.wins ? ((score.points - min_score * (1.0 - score.wins)) / score.wins) : score.points;
2142
std::cout << " [" << win_points << " per win]";
2143
}
2144
else if (optimization_mode == OptimizationMode::war_defense)
2145
{
2146
auto opp_win_points = score.losses ? max_score - ((score.points - (max_score - min_score) * (1.0 - score.losses)) / score.losses) : score.points;
2147
std::cout << " [" << opp_win_points << " per opp win]";
2148
}
2149
*/
2150

2151
    // print commander
2152
    std::cout << ": " << deck->commander->m_name;
1,264 ✔
2153

2154
    // print dominions
2155
    if (deck->alpha_dominion)
1,264 ✔
2156
    {
2157
        std::cout << ", " << deck->alpha_dominion->m_name;
1,195 ✔
2158
    }
2159

2160
    // print deck cards
2161
    if (deck->strategy == DeckStrategy::random || deck->strategy == DeckStrategy::flexible || deck->strategy == DeckStrategy::evaluate || deck->strategy == DeckStrategy::evaluate_twice)
1,264 ✔
2162
    {
2163
        std::sort(deck->cards.begin(), deck->cards.end(), [](const Card *a, const Card *b)
1,264 ✔
2164
                  { return a->m_id < b->m_id; });
24,504 ✔
2165
    }
2166
    std::cout << ", ";
1,264 ✔
2167
    if (print_locked)
1,264 ✔
2168
        print_cards_inline(deck->cards, std::cout, deck);
14 ✔
2169
    else
2170
        print_cards_inline(deck->cards, std::cout);
1,250 ✔
2171
}
1,264 ✔
2172
//------------------------------------------------------------------------------
2173
bool is_timeout_reached()
367 ✔
2174
{
2175
    if (__builtin_expect(maximum_time > 0, false))
367 ✔
2176
    {
UNCOV
2177
        if ((std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now() - start_time)).count() > maximum_time * 60 * 60)
×
2178
        {
UNCOV
2179
            std::cout << "Time expired! Current result:" << std::endl;
×
UNCOV
2180
            return true;
×
2181
        }
2182
    }
2183
    return false;
2184
}
2185
std::vector<std::vector<const Card *>> get_candidate_lists(Process &proc)
7 ✔
2186
{
2187
    std::vector<std::vector<const Card *>> ret_candidates;
7 ✔
2188
    std::vector<const Card *> commander_candidates;
7 ✔
2189
    std::vector<const Card *> alpha_dominion_candidates;
7 ✔
2190
    std::vector<const Card *> card_candidates;
7 ✔
2191

2192
    // resolve available to player cards
2193
    auto player_assaults_and_structures = proc.cards.player_commanders;
7 ✔
2194
    player_assaults_and_structures.insert(player_assaults_and_structures.end(), proc.cards.player_structures.begin(), proc.cards.player_structures.end());
7 ✔
2195
    player_assaults_and_structures.insert(player_assaults_and_structures.end(), proc.cards.player_assaults.begin(), proc.cards.player_assaults.end());
7 ✔
2196
    for (auto it = player_assaults_and_structures.begin(); it != player_assaults_and_structures.end(); ++it)
294,770 ✔
2197
    {
2198
        const Card *card = *it;
294,763 ✔
2199
        // skip illegal
2200
        if ((card->m_category != CardCategory::dominion_alpha) && (card->m_category != CardCategory::normal))
294,763 ✔
2201
        {
2202
            continue;
294,518 ✔
2203
        }
2204

2205
        // skip dominions when their climbing is disabled
2206
        if ((card->m_category == CardCategory::dominion_alpha) && (!use_owned_dominions))
294,763 ✔
2207
        {
UNCOV
2208
            continue;
×
2209
        }
2210

2211
        // try to skip a card unless it's allowed
2212
        if (!allowed_candidates.count(card->m_id))
294,763 ✔
2213
        {
2214
            // skip disallowed always
2215
            if (disallowed_candidates.count(card->m_id))
294,763 ✔
2216
            {
UNCOV
2217
                continue;
×
2218
            }
2219

2220
            // handle dominions
2221
            if (card->m_category == CardCategory::dominion_alpha)
294,763 ✔
2222
            {
2223
                // skip non-top-level dominions anyway
2224
                // (will check it later and downgrade if necessary according to amount of material (shards))
2225
                /*if (!card->is_top_level_card())
2226
                  { continue; }
2227

2228
                // skip basic dominions
2229
                if ((card->m_id == 50001) || (card->m_id == 50002))
2230
                { continue; }*/
2231
            }
2232

2233
            // handle normal cards
2234
            else
2235
            {
2236
                // skip non-top-level cards (adjust_deck() will try to downgrade them if necessary)
2237
                bool use_top_level = (card->m_type == CardType::commander) ? use_top_level_commander : use_top_level_card;
292,257 ✔
2238
                if (!card->is_top_level_card() and (fund || use_top_level || !owned_cards[card->m_id]))
292,257 ✔
2239
                {
2240
                    continue;
242,816 ✔
2241
                }
2242

2243
                // skip lowest fusion levels
2244
                unsigned use_fused_level = (card->m_type == CardType::commander) ? use_fused_commander_level : use_fused_card_level;
49,441 ✔
2245
                if (card->m_fusion_level < use_fused_level)
49,441 ✔
2246
                {
UNCOV
2247
                    continue;
×
2248
                }
2249
            }
2250
        }
2251

2252
        if (use_owned_cards && card->m_category == CardCategory::dominion_alpha && !owned_cards[card->m_id])
51,947 ✔
2253
        {
2254
            if (use_maxed_dominions && card->m_used_for_cards.size() == 0)
2,485 ✔
2255
            {
2256
            }
2257
            else
2258
            {
2259
                continue;
2,485 ✔
2260
            }
2261
        }
2262
        // skip unavailable cards anyway when ownedcards is used
2263
        if (use_owned_cards && !(card->m_category == CardCategory::dominion_alpha) && !is_owned_or_can_be_fused(card))
49,462 ✔
2264
        {
2265
            continue;
49,217 ✔
2266
        }
2267
        // mono
2268
        if (!factions.empty() && (std::find(factions.begin(), factions.end(), card->m_faction) == factions.end()) != invert_factions) // XOR
245 ✔
2269
        {
UNCOV
2270
            continue;
×
2271
        }
2272

2273
        // enqueue candidate according to category & type
2274
        if (card->m_type == CardType::commander)
245 ✔
2275
        {
2276
            commander_candidates.emplace_back(card);
63 ✔
2277
        }
2278
        else if (card->m_category == CardCategory::dominion_alpha)
182 ✔
2279
        {
2280
            alpha_dominion_candidates.emplace_back(card);
21 ✔
2281
        }
2282
        else if (card->m_category == CardCategory::normal)
161 ✔
2283
        {
2284
            bool contains{false};
161 ✔
2285
            if (!skills.empty())
161 ✔
2286
            {
UNCOV
2287
                for (Skill::Skill skill_id : skills)
×
2288
                {
2289
                    if (card->m_skill_value[skill_id])
×
2290
                    {
2291
                        contains = true;
2292
                        break;
2293
                    }
2294
                }
UNCOV
2295
                if (!contains != invert_skills)
×
UNCOV
2296
                    continue; // XOR
×
2297
            }
2298
            if (only_recent && !((it + (player_assaults_and_structures.size() * recent_percent / 100)) > player_assaults_and_structures.end()))
161 ✔
UNCOV
2299
                continue;                                                                                                                      // latest %
×
2300
            if (prefered_recent && it + (player_assaults_and_structures.size() * recent_percent) / 100 > player_assaults_and_structures.end()) // latest %
161 ✔
2301
            {
UNCOV
2302
                for (unsigned k = 0; k < prefered_factor; ++k)
×
UNCOV
2303
                    card_candidates.emplace_back(card);
×
2304
            }
2305
            for (Skill::Skill skill_id : prefered_skills)
161 ✔
2306
            {
UNCOV
2307
                if (card->m_skill_value[skill_id])
×
2308
                {
UNCOV
2309
                    for (unsigned k = 0; k < prefered_factor; ++k)
×
UNCOV
2310
                        card_candidates.emplace_back(card);
×
2311
                }
2312
            }
2313

2314
            card_candidates.emplace_back(card);
161 ✔
2315
        }
2316
    }
2317
    card_candidates.emplace_back(nullptr);
7 ✔
2318

2319
    ret_candidates.emplace_back(commander_candidates);
7 ✔
2320
    ret_candidates.emplace_back(alpha_dominion_candidates);
7 ✔
2321
    ret_candidates.emplace_back(card_candidates);
7 ✔
2322
    return ret_candidates;
7 ✔
2323
}
7 ✔
2324
//------------------------------------------------------------------------------
2325
enum Operation
2326
{
2327
    noop,
2328
    simulate,
2329
    climb,
2330
    climb_forts,
2331
    anneal,
2332
    genetic,
2333
    beam,
2334
    reorder,
2335
    debug,
2336
    debuguntil,
2337
};
2338
//------------------------------------------------------------------------------
2339
extern void (*skill_table[Skill::num_skills])(Field *, CardStatus *src_status, const SkillSpec &);
UNCOV
2340
void print_available_effects()
×
2341
{
UNCOV
2342
    std::cout << "Available effects besides activation skills:\n"
×
2343
                 "  Bloodlust X\n"
2344
                 "  Brigade\n"
2345
                 "  Counterflux\n"
2346
                 "  Divert\n"
2347
                 "  Enduring-Rage\n"
2348
                 "  Fortification\n"
2349
                 "  Heroism\n"
2350
                 "  Zealots-Preservation\n"
2351
                 "  Metamorphosis\n"
2352
                 "  Megamorphosis\n"
2353
                 "  Revenge X\n"
2354
                 "  Turning-Tides\n"
2355
                 "  Virulence\n"
2356
                 "  Halted-Orders\n"
2357
                 "  Devour X\n"
2358
                 "  Critical-Reach\n"
2359
                 "  Temporal-Backlash\n"
2360
                 "  Furiosity\n"
2361
                 "  Oath-Of-Loyalty\n"
2362
                 "  Blood-Vengeance\n"
2363
                 "  Cold-Sleep\n"
2364
                 "  Iron-Will\n"
2365
                 "  Unity\n"
2366
                 "  Devotion\n"
2367
                 "  Crackdown\n"
2368
                 "  SuperHeroism\n";
×
UNCOV
2369
}
×
2370
bool check_input_amount(int argc, const char **argv, int argIndex, int number)
402 ✔
2371
{
2372
    if (argc <= argIndex + number)
402 ✔
2373
    {
UNCOV
2374
        std::cerr << argv[argIndex] << " needs " << number << " paramters" << std::endl;
×
UNCOV
2375
        return true;
×
2376
    }
2377
    return false;
2378
}
UNCOV
2379
void input_error(std::string msg)
×
2380
{
UNCOV
2381
    std::cerr << msg << std::endl;
×
UNCOV
2382
    exit(EXIT_FAILURE);
×
2383
}
2384
void usage(int argc, const char **argv)
×
2385
{
UNCOV
2386
    std::cout << "Tyrant Unleashed Optimizer (TUO) " << TYRANT_OPTIMIZER_VERSION << "\n"
×
2387
                                                                                    "usage: "
2388
              << argv[0] << " Your_Deck Enemy_Deck [Flags] [Operations]\n"
2389
                            "\n"
2390
                            "Your_Deck:\n"
2391
                            "  the name/hash/cards of a custom deck.\n"
2392
                            "\n"
2393
                            "Enemy_Deck:\n"
2394
                            "  semicolon separated list of defense decks, syntax:\n"
2395
                            "  deck1[:factor1];deck2[:factor2];...\n"
2396
                            "  where deck is the name/hash/cards of a mission, raid, quest or custom deck, and factor is optional. The default factor is 1.\n"
2397
                            "  example: \'fear:0.2;slowroll:0.8\' means fear is the defense deck 20% of the time, while slowroll is the defense deck 80% of the time.\n"
2398
                            "\n"
2399
                            "Flags:\n"
2400
                            "  -e \"<effect>\": set the battleground effect; you may use -e multiple times.\n"
2401
                            "  -r: the attack deck is played in order instead of randomly (respects the 3 cards drawn limit).\n"
2402
                            "  -s: use surge (default is fight).\n"
2403
                            "  -t <num>: set the number of threads, default is 4.\n"
2404
                            "  win:     simulate/optimize for win rate. default for non-raids.\n"
2405
                            "  defense: simulate/optimize for win rate + stall rate. can be used for defending deck or win rate oriented raid simulations.\n"
2406
                            "  raid:    simulate/optimize for average raid damage (ARD). default for raids.\n"
2407
                            "Flags for climb:\n"
2408
                            "  -c: don't try to optimize the commander.\n"
2409
                            "  -L <min> <max>: restrict deck size between <min> and <max>.\n"
2410
                            "  -o: restrict to the owned cards listed in \"data/ownedcards.txt\".\n"
2411
                            "  -o=<filename>: restrict to the owned cards listed in <filename>.\n"
2412
                            "  fund <num>: invest <num> SP to upgrade cards.\n"
2413
                            "  target <num>: stop as soon as the score reaches <num>.\n"
2414
                            "\n"
2415
                            "Operations:\n"
2416
                            "  sim <num>: simulate <num> battles to evaluate a deck.\n"
2417
                            "  climb <num>: perform hill-climbing starting from the given attack deck, using up to <num> battles to evaluate a deck.\n"
2418
                            "  reorder <num>: optimize the order for given attack deck, using up to <num> battles to evaluate an order.\n"
2419
#ifndef NDEBUG
2420
                            "  debug: testing purpose only. very verbose output. only one battle.\n"
2421
                            "  debuguntil <min> <max>: testing purpose only. fight until the last fight results in range [<min>, <max>]. recommend to redirect std::coutput.\n"
×
2422
#endif
2423
        ;
UNCOV
2424
}
×
2425

2426
bool parse_bge(
63 ✔
2427
    std::string bge_name,
2428
    unsigned player,
2429
    const std::unordered_map<std::string, std::string> &bge_aliases,
2430
    std::array<signed short, PassiveBGE::num_passive_bges> &your_bg_effects,
2431
    std::array<signed short, PassiveBGE::num_passive_bges> &enemy_bg_effects,
2432
    std::vector<SkillSpec> &your_bg_skills,
2433
    std::vector<SkillSpec> &enemy_bg_skills,
2434
    std::unordered_set<std::string> used_bge_aliases)
2435
{
2436
    // skip empty
2437
    tuo::trim(bge_name);
63 ✔
2438
    if (bge_name.empty())
63 ✔
2439
    {
2440
        return true;
2441
    }
2442

2443
    // is effect combined?
2444
    if (bge_name.find_first_of(";|") != std::string::npos)
37 ✔
2445
    {
UNCOV
2446
        std::vector<std::string> bges;
×
UNCOV
2447
        boost::split(bges, bge_name, boost::is_any_of(";|"));
×
UNCOV
2448
        for (auto &&next_bge : bges)
×
2449
        {
2450
            if (!parse_bge(next_bge, player, bge_aliases, your_bg_effects, enemy_bg_effects, your_bg_skills, enemy_bg_skills, used_bge_aliases))
×
2451
            {
UNCOV
2452
                return false;
×
2453
            }
2454
        }
2455
        return true;
2456
    }
×
2457

2458
    // try to resolve bge name as alias
2459
    std::string simple_bge_name = simplify_name(bge_name);
37 ✔
2460
    const auto bge_alias_itr = bge_aliases.find(simple_bge_name);
37 ✔
2461
    if (bge_alias_itr != bge_aliases.end())
37 ✔
2462
    {
2463
        if (!used_bge_aliases.insert(simple_bge_name).second)
1 ✔
2464
        {
2465
            throw std::runtime_error("BGE alias: " + bge_name + ": Circular reference");
×
2466
        }
2467
        return parse_bge(bge_alias_itr->second, player, bge_aliases, your_bg_effects, enemy_bg_effects, your_bg_skills, enemy_bg_skills, used_bge_aliases);
3 ✔
2468
    }
2469

2470
    // parse as passive or skill based BGE
2471
    std::vector<std::string> tokens, skill_name_list;
36 ✔
2472
    boost::split(tokens, bge_name, boost::is_any_of(" "));
36 ✔
2473
    boost::split(skill_name_list, tokens[0], boost::is_any_of("+"));
36 ✔
2474
    try
36 ✔
2475
    {
2476
        for (auto &&skill_name : skill_name_list)
72 ✔
2477
        {
2478
            PassiveBGE::PassiveBGE passive_bge_id = passive_bge_name_to_id(skill_name);
36 ✔
2479
            Skill::Skill skill_id = skill_name_to_id(skill_name);
36 ✔
2480
            if (passive_bge_id != PassiveBGE::no_bge)
36 ✔
2481
            {
2482
                // map bge id to its value (if present otherwise zero)
2483
                signed short bge_value = (tokens.size() > 1) ? boost::lexical_cast<signed short>(tokens[1]) : 1;
35 ✔
2484
                if (!bge_value)
6 ✔
UNCOV
2485
                    throw std::runtime_error("BGE " + skill_name + ": zero value means no BGE");
×
2486
                if ((player == 0) or (player == 2))
35 ✔
2487
                    your_bg_effects[passive_bge_id] = bge_value;
35 ✔
2488
                if ((player == 1) or (player == 2))
35 ✔
2489
                    enemy_bg_effects[passive_bge_id] = bge_value;
35 ✔
2490
            }
2491
            else if (skill_table[skill_id] != nullptr)
1 ✔
2492
            {
2493
                unsigned skill_index = 1;
1 ✔
2494
                // activation BG skill
2495
                SkillSpec bg_skill{
1 ✔
2496
                    skill_id,
2497
                    0,
2498
                    allfactions,
2499
                    0,
2500
                    0,
2501
                    Skill::no_skill,
2502
                    Skill::no_skill,
2503
                    false,
2504
                    0,
2505
                };
1 ✔
2506

2507
                // skill [ ALL | N ] ...
2508
                if (skill_index < tokens.size() && boost::to_lower_copy(tokens[skill_index]) == "all")
2 ✔
2509
                {
2510
                    bg_skill.all = true;
1 ✔
2511
                    skill_index += 1;
1 ✔
2512
                }
UNCOV
2513
                else if (skill_index + 1 < tokens.size() && isdigit(*tokens[skill_index].c_str()))
×
2514
                {
UNCOV
2515
                    bg_skill.n = boost::lexical_cast<unsigned>(tokens[skill_index]);
×
UNCOV
2516
                    skill_index += 1;
×
2517
                }
2518

2519
                // skill n [ FACTION ] ...
2520
                if ((skill_index + 1) < tokens.size())
1 ✔
2521
                {
2522
                    for (auto f = allfactions + 1; f < num_factions; ++f)
7 ✔
2523
                    {
2524
                        if (boost::to_lower_copy(tokens[skill_index]) == faction_names[f])
6 ✔
2525
                        {
UNCOV
2526
                            bg_skill.y = static_cast<Faction>(f);
×
2527
                            skill_index += 1;
×
2528
                            break;
×
2529
                        }
2530
                    }
2531
                }
2532

2533
                if (skill_index < tokens.size())
1 ✔
2534
                {
2535
                    bg_skill.s = skill_name_to_id(tokens[skill_index]);
1 ✔
2536
                    if (bg_skill.s != Skill::no_skill)
1 ✔
2537
                    {
2538
                        skill_index += 1;
1 ✔
2539
                        if (skill_index < tokens.size() && (boost::to_lower_copy(tokens[skill_index]) == "to" || boost::to_lower_copy(tokens[skill_index]) == "into"))
3 ✔
2540
                        {
UNCOV
2541
                            skill_index += 1;
×
2542
                        }
2543
                        if (skill_index < tokens.size())
1 ✔
2544
                        {
2545
                            bg_skill.s2 = skill_name_to_id(tokens[skill_index]);
1 ✔
2546
                            if (bg_skill.s2 != Skill::no_skill)
1 ✔
2547
                            {
UNCOV
2548
                                skill_index += 1;
×
2549
                            }
2550
                        }
2551
                    }
2552
                }
2553
                if (skill_index < tokens.size())
1 ✔
2554
                {
2555
                    if (bg_skill.id == Skill::jam || bg_skill.id == Skill::overload)
1 ✔
2556
                    {
UNCOV
2557
                        bg_skill.n = boost::lexical_cast<unsigned>(tokens[skill_index]);
×
2558
                    }
2559
                    else
2560
                    {
2561
                        bg_skill.x = boost::lexical_cast<unsigned>(tokens[skill_index]);
1 ✔
2562
                    }
2563
                }
2564
                switch (player)
1 ✔
2565
                {
2566
                case 0:
×
UNCOV
2567
                    your_bg_skills.push_back(bg_skill);
×
2568
                    break;
UNCOV
2569
                case 1:
×
UNCOV
2570
                    enemy_bg_skills.push_back(bg_skill);
×
2571
                    break;
2572
                case 2:
1 ✔
2573
                    your_bg_skills.push_back(bg_skill);
1 ✔
2574
                    enemy_bg_skills.push_back(bg_skill);
1 ✔
2575
                    break;
UNCOV
2576
                default:
×
UNCOV
2577
                    throw std::runtime_error("Bad player number: " + boost::lexical_cast<std::string>(player));
×
2578
                }
2579
            }
2580
            else
2581
            {
UNCOV
2582
                std::cerr << "Error: unrecognized effect \"" << bge_name << "\".\n";
×
UNCOV
2583
                std::cout << "Unrecognized effect \"" << bge_name << "\".\n";
×
UNCOV
2584
                print_available_effects();
×
2585
                return false;
36 ✔
2586
            }
2587
        }
2588
    }
UNCOV
2589
    catch (const boost::bad_lexical_cast &e)
×
2590
    {
UNCOV
2591
        throw std::runtime_error("Expect a number in effect \"" + bge_name + "\"");
×
UNCOV
2592
    }
×
2593
    return true;
2594
}
73 ✔
2595

2596
DeckResults run(int argc, const char **argv)
85 ✔
2597
{
2598
    start_time = std::chrono::system_clock::now();
85 ✔
2599
    DeckResults fr;
85 ✔
2600
    opt_num_threads = 4;
85 ✔
2601
    DeckStrategy::DeckStrategy opt_your_strategy(DeckStrategy::random);
85 ✔
2602
    DeckStrategy::DeckStrategy opt_enemy_strategy(DeckStrategy::random);
85 ✔
2603
    std::string opt_forts, opt_enemy_forts;
85 ✔
2604
    std::string opt_doms, opt_enemy_doms;
85 ✔
2605
    std::string opt_hand, opt_enemy_hand;
85 ✔
2606
    std::string opt_vip;
85 ✔
2607
    std::string opt_allow_candidates;
85 ✔
2608
    std::string opt_disallow_candidates;
85 ✔
2609
    std::string opt_disallow_recipes;
85 ✔
2610
#ifndef NQUEST
2611
    std::string opt_quest;
2612
#endif
2613
    std::string opt_target_score;
85 ✔
2614
    std::vector<std::string> fn_suffix_list{
85 ✔
2615
        "",
2616
    };
170 ✔
2617
    std::string prefix = "";
170 ✔
2618
    std::vector<std::string> opt_owned_cards_str_list;
85 ✔
2619
    bool opt_do_optimization(false);
85 ✔
2620
    bool opt_multi_optimization(false);
85 ✔
2621
    bool opt_do_reorder(false);
85 ✔
2622
    bool opt_keep_commander{false};
85 ✔
2623
    std::vector<std::tuple<unsigned, unsigned, Operation>> opt_todo;
85 ✔
2624
    std::vector<std::string> opt_effects[3]; // 0-you; 1-enemy; 2-global
595 ✔
2625
    std::array<signed short, PassiveBGE::num_passive_bges> opt_bg_effects[2];
2626
    std::vector<SkillSpec> opt_bg_skills[2];
425 ✔
2627

2628
    std::string your_deck_list{argv[1]};
85 ✔
2629
    std::string enemy_deck_list{argv[2]};
85 ✔
2630

2631
    for (int argIndex = 3; argIndex < argc; ++argIndex)
513 ✔
2632
    {
2633
        //bypass MSVS issue: Nesting of code blocks exceeds the limit of 128 nesting levels
2634
        bool tokenParsed = true;
428 ✔
2635
        if (strcmp(argv[argIndex], "deck") == 0)
428 ✔
2636
        {
UNCOV
2637
            your_deck_list = std::string(argv[argIndex + 1]);
×
2638
            argIndex += 1;
×
2639
        }
2640
        else if (strcmp(argv[argIndex], "enemy:deck") == 0)
428 ✔
2641
        {
UNCOV
2642
            enemy_deck_list = std::string(argv[argIndex + 1]);
×
UNCOV
2643
            argIndex += 1;
×
2644
        }
2645
        // Codec
2646
        else if (strcmp(argv[argIndex], "ext_b64") == 0)
428 ✔
2647
        {
2648
            hash_to_ids = hash_to_ids_ext_b64;
×
UNCOV
2649
            encode_deck = encode_deck_ext_b64;
×
2650
        }
2651
        else if (strcmp(argv[argIndex], "wmt_b64") == 0)
428 ✔
2652
        {
UNCOV
2653
            hash_to_ids = hash_to_ids_wmt_b64;
×
UNCOV
2654
            encode_deck = encode_deck_wmt_b64;
×
2655
        }
2656
        else if (strcmp(argv[argIndex], "ddd_b64") == 0)
428 ✔
2657
        {
2658
            hash_to_ids = hash_to_ids_ddd_b64;
×
UNCOV
2659
            encode_deck = encode_deck_ddd_b64;
×
2660
        }
2661
        else if (strcmp(argv[argIndex], "ml") == 0)
428 ✔
2662
        {
2663
            use_ml = true;
1 ✔
2664
            use_db_write = false;
1 ✔
2665
        }
2666
        else if (strcmp(argv[argIndex], "noop") == 0)
427 ✔
2667
        {
2668
        }
2669
        else if (strcmp(argv[argIndex], "no-ml") == 0)
427 ✔
2670
        {
UNCOV
2671
            use_ml = false;
×
2672
        }
2673
        else if (strcmp(argv[argIndex], "only-ml") == 0)
427 ✔
2674
        {
UNCOV
2675
            use_ml = true;
×
UNCOV
2676
            use_only_ml = true;
×
UNCOV
2677
            use_db_write = false;
×
2678
        }
2679
        else if (strcmp(argv[argIndex], "ml-precision") == 0)
427 ✔
2680
        {
UNCOV
2681
            if (check_input_amount(argc, argv, argIndex, 1))
×
UNCOV
2682
                exit(1);
×
UNCOV
2683
            ml_precision = std::stof(argv[argIndex + 1]);
×
UNCOV
2684
            argIndex += 1;
×
2685
        }
2686
        else if (strcmp(argv[argIndex], "no-db-write") == 0)
427 ✔
2687
        {
UNCOV
2688
            use_db_write = false;
×
2689
        }
2690
        else if (strcmp(argv[argIndex], "no-db-load") == 0)
427 ✔
2691
        {
2692
            use_db_load = false;
3 ✔
2693
        }
2694
        else if (strcmp(argv[argIndex], "no-db") == 0)
424 ✔
2695
        {
2696
            use_db_load = false;
16 ✔
2697
            use_db_write = false;
16 ✔
2698
        }
2699
        else if (strcmp(argv[argIndex], "db") == 0)
408 ✔
2700
        {
2701
            use_db_load = true;
4 ✔
2702
            use_db_write = true;
4 ✔
2703
        }
2704
        else if (strcmp(argv[argIndex], "strict-db") == 0)
404 ✔
2705
        {
UNCOV
2706
            use_strict_db = true;
×
UNCOV
2707
            use_db_load = true;
×
UNCOV
2708
            use_db_write = true;
×
2709
        }
2710
        else if (strcmp(argv[argIndex], "no-strict-db") == 0)
404 ✔
2711
        {
UNCOV
2712
            use_strict_db = false;
×
2713
        }
2714
        else if (strcmp(argv[argIndex], "db-limit") == 0)
404 ✔
2715
        {
UNCOV
2716
            if (check_input_amount(argc, argv, argIndex, 1))
×
UNCOV
2717
                exit(1);
×
2718
            db_limit = std::stoi(argv[argIndex + 1]);
×
2719
            argIndex += 1;
×
2720
        }
2721

2722
        // Base Game Mode
2723
        else if (strcmp(argv[argIndex], "fight") == 0)
404 ✔
2724
        {
UNCOV
2725
            gamemode = fight;
×
2726
        }
2727
        else if (strcmp(argv[argIndex], "-s") == 0 || strcmp(argv[argIndex], "surge") == 0)
404 ✔
2728
        {
2729
            gamemode = surge;
×
2730
        }
2731
        // Base Scoring Mode
2732
        else if (strcmp(argv[argIndex], "win") == 0)
404 ✔
2733
        {
2734
            optimization_mode = OptimizationMode::winrate;
×
2735
        }
2736
        else if (strcmp(argv[argIndex], "defense") == 0)
404 ✔
2737
        {
UNCOV
2738
            optimization_mode = OptimizationMode::defense;
×
2739
        }
2740
        else if (strcmp(argv[argIndex], "raid") == 0)
404 ✔
2741
        {
UNCOV
2742
            optimization_mode = OptimizationMode::raid;
×
2743
        }
2744
        // Mode Package
2745
        else if (strcmp(argv[argIndex], "campaign") == 0)
404 ✔
2746
        {
UNCOV
2747
            gamemode = surge;
×
UNCOV
2748
            optimization_mode = OptimizationMode::campaign;
×
2749
        }
2750
        else if (strcmp(argv[argIndex], "pvp") == 0)
404 ✔
2751
        {
2752
            gamemode = fight;
×
UNCOV
2753
            optimization_mode = OptimizationMode::winrate;
×
2754
        }
2755
        else if (strcmp(argv[argIndex], "pvp-defense") == 0)
404 ✔
2756
        {
2757
            gamemode = surge;
×
2758
            optimization_mode = OptimizationMode::defense;
×
2759
        }
2760
        else if (strcmp(argv[argIndex], "brawl") == 0)
404 ✔
2761
        {
2762
            gamemode = surge;
×
2763
            optimization_mode = OptimizationMode::brawl;
×
2764
        }
2765
        else if (strcmp(argv[argIndex], "brawl-defense") == 0)
404 ✔
2766
        {
UNCOV
2767
            gamemode = fight;
×
UNCOV
2768
            optimization_mode = OptimizationMode::brawl_defense;
×
2769
        }
2770
        else if (strcmp(argv[argIndex], "gw") == 0)
404 ✔
2771
        {
UNCOV
2772
            gamemode = surge;
×
UNCOV
2773
            optimization_mode = OptimizationMode::war;
×
2774
        }
2775
        else if (strcmp(argv[argIndex], "gw-defense") == 0)
404 ✔
2776
        {
UNCOV
2777
            gamemode = fight;
×
UNCOV
2778
            optimization_mode = OptimizationMode::war_defense;
×
2779
        }
2780
        // Others
2781
        else if (strcmp(argv[argIndex], "keep-commander") == 0 || strcmp(argv[argIndex], "-c") == 0)
404 ✔
2782
        {
2783
            opt_keep_commander = true;
2784
        }
2785
        else if (strcmp(argv[argIndex], "mono") == 0 || strcmp(argv[argIndex], "-m") == 0 || strcmp(argv[argIndex], "factions") == 0 || strcmp(argv[argIndex], "-f") == 0)
404 ✔
2786
        {
2787
            if (check_input_amount(argc, argv, argIndex, 1))
×
2788
                exit(1);
×
2789
            if (strcmp(argv[argIndex + 1], "") != 0)
×
2790
            {
UNCOV
2791
                factions.push_back(faction_name_to_id(argv[argIndex + 1]));
×
2792
            }
2793
            argIndex += 1;
×
2794
        }
2795
        else if (strcmp(argv[argIndex], "no-mono") == 0 || strcmp(argv[argIndex], "no-factions") == 0)
404 ✔
2796
        {
2797
            if (check_input_amount(argc, argv, argIndex, 1))
×
2798
                exit(1);
×
2799
            factions.push_back(faction_name_to_id(argv[argIndex + 1]));
×
2800
            invert_factions = true;
×
UNCOV
2801
            argIndex += 1;
×
2802
        }
2803
        else if (strcmp(argv[argIndex], "strategy") == 0 || strcmp(argv[argIndex], "skill") == 0)
404 ✔
2804
        {
UNCOV
2805
            if (check_input_amount(argc, argv, argIndex, 1))
×
2806
                exit(1);
×
UNCOV
2807
            if (strcmp(argv[argIndex + 1], "") != 0)
×
2808
            {
UNCOV
2809
                if (strcmp(argv[argIndex + 1], "recent") == 0)
×
2810
                {
UNCOV
2811
                    only_recent = true;
×
2812
                }
2813
                else
2814
                {
2815
                    skills.push_back(skill_name_to_id(argv[argIndex + 1]));
×
2816
                }
2817
            }
UNCOV
2818
            argIndex += 1;
×
2819
        }
2820
        else if (strcmp(argv[argIndex], "no-strategy") == 0 || strcmp(argv[argIndex], "no-skill") == 0)
404 ✔
2821
        {
UNCOV
2822
            if (check_input_amount(argc, argv, argIndex, 1))
×
2823
                exit(1);
×
UNCOV
2824
            if (strcmp(argv[argIndex + 1], "") != 0)
×
2825
            {
UNCOV
2826
                skills.push_back(skill_name_to_id(argv[argIndex + 1]));
×
UNCOV
2827
                invert_skills = true;
×
2828
            }
2829
            argIndex += 1;
×
2830
        }
2831
        else if (strcmp(argv[argIndex], "prefered-strategy") == 0 || strcmp(argv[argIndex], "prefered-skill") == 0)
404 ✔
2832
        {
2833
            if (check_input_amount(argc, argv, argIndex, 1))
×
2834
                exit(1);
×
UNCOV
2835
            if (strcmp(argv[argIndex + 1], "") != 0)
×
2836
            {
UNCOV
2837
                if (strcmp(argv[argIndex + 1], "recent") == 0)
×
2838
                {
2839
                    prefered_recent = true;
×
2840
                }
2841
                else
2842
                {
2843
                    prefered_skills.push_back(skill_name_to_id(argv[argIndex + 1]));
×
2844
                }
2845
            }
UNCOV
2846
            argIndex += 1;
×
2847
        }
2848
        else if (strcmp(argv[argIndex], "prefered-factor") == 0)
404 ✔
2849
        {
UNCOV
2850
            if (check_input_amount(argc, argv, argIndex, 1))
×
UNCOV
2851
                exit(1);
×
UNCOV
2852
            prefered_factor = std::stoi(argv[argIndex + 1]);
×
2853
            argIndex += 1;
×
2854
        }
2855
        else if (strcmp(argv[argIndex], "recent-percent") == 0)
404 ✔
2856
        {
UNCOV
2857
            if (check_input_amount(argc, argv, argIndex, 1))
×
2858
                exit(1);
×
2859
            recent_percent = std::stoi(argv[argIndex + 1]);
×
UNCOV
2860
            argIndex += 1;
×
2861
        }
2862
        else if (strcmp(argv[argIndex], "effect") == 0 || strcmp(argv[argIndex], "-e") == 0)
404 ✔
2863
        {
2864
            if (check_input_amount(argc, argv, argIndex, 1))
62 ✔
UNCOV
2865
                exit(1);
×
2866
            opt_effects[2].push_back(argv[argIndex + 1]);
124 ✔
2867
            argIndex += 1;
62 ✔
2868
        }
2869
        else if (strcmp(argv[argIndex], "ye") == 0 || strcmp(argv[argIndex], "yeffect") == 0)
342 ✔
2870
        {
UNCOV
2871
            if (check_input_amount(argc, argv, argIndex, 1))
×
2872
                exit(1);
×
UNCOV
2873
            opt_effects[0].push_back(argv[argIndex + 1]);
×
2874
            argIndex += 1;
×
2875
        }
2876
        else if (strcmp(argv[argIndex], "ee") == 0 || strcmp(argv[argIndex], "eeffect") == 0)
342 ✔
2877
        {
2878
            if (check_input_amount(argc, argv, argIndex, 1))
×
2879
                exit(1);
×
2880
            opt_effects[1].push_back(argv[argIndex + 1]);
×
2881
            argIndex += 1;
×
2882
        }
2883
        else if (strcmp(argv[argIndex], "freeze") == 0 || strcmp(argv[argIndex], "-F") == 0)
342 ✔
2884
        {
UNCOV
2885
            if (check_input_amount(argc, argv, argIndex, 1))
×
2886
                exit(1);
×
2887
            opt_freezed_cards = atoi(argv[argIndex + 1]);
×
2888
            argIndex += 1;
×
2889
        }
2890
        else if (strcmp(argv[argIndex], "-L") == 0)
342 ✔
2891
        {
2892
            if (check_input_amount(argc, argv, argIndex, 2))
×
UNCOV
2893
                exit(1);
×
UNCOV
2894
            min_deck_len = atoi(argv[argIndex + 1]);
×
UNCOV
2895
            max_deck_len = atoi(argv[argIndex + 2]);
×
2896
            argIndex += 2;
×
2897
        }
2898
        else if (strcmp(argv[argIndex], "-o-") == 0)
342 ✔
2899
        {
UNCOV
2900
            use_owned_cards = false;
×
2901
        }
2902
        else if (strcmp(argv[argIndex], "-o") == 0)
342 ✔
2903
        {
2904
            opt_owned_cards_str_list.push_back(prefix + "data/ownedcards.txt");
×
2905
            use_owned_cards = true;
×
2906
        }
2907
        else if (strncmp(argv[argIndex], "-o=", 3) == 0)
342 ✔
2908
        {
UNCOV
2909
            std::string fname{prefix};
×
2910
            fname += (argv[argIndex] + 3);
×
UNCOV
2911
            opt_owned_cards_str_list.push_back(fname);
×
UNCOV
2912
            use_owned_cards = true;
×
UNCOV
2913
        }
×
2914
        else if (strncmp(argv[argIndex], "_", 1) == 0)
342 ✔
2915
        {
2916
            fn_suffix_list.push_back(argv[argIndex]);
×
2917
        }
2918
        else if (strcmp(argv[argIndex], "prefix") == 0)
342 ✔
2919
        {
2920
            if (check_input_amount(argc, argv, argIndex, 1))
85 ✔
UNCOV
2921
                exit(1);
×
2922
            prefix = argv[argIndex + 1];
85 ✔
2923
            argIndex += 1;
85 ✔
2924
        }
2925
        else if (strcmp(argv[argIndex], "fund") == 0)
257 ✔
2926
        {
2927
            if (check_input_amount(argc, argv, argIndex, 1))
×
UNCOV
2928
                exit(1);
×
UNCOV
2929
            fund = atoi(argv[argIndex + 1]);
×
UNCOV
2930
            argIndex += 1;
×
2931
        }
2932
        else if (strcmp(argv[argIndex], "dom-none") == 0)
257 ✔
2933
        {
2934
            use_owned_dominions = false;
×
UNCOV
2935
            use_maxed_dominions = false;
×
2936
        }
2937
        else if (strcmp(argv[argIndex], "dom+") == 0 || strcmp(argv[argIndex], "dominion+") == 0 || strcmp(argv[argIndex], "dom-owned") == 0)
257 ✔
2938
        {
2939
            use_owned_dominions = true;
×
2940
            use_maxed_dominions = false;
×
2941
        }
2942
        else if (strcmp(argv[argIndex], "dom-") == 0 || strcmp(argv[argIndex], "dominion-") == 0 || strcmp(argv[argIndex], "dom-maxed") == 0)
257 ✔
2943
        {
UNCOV
2944
            use_owned_dominions = true;
×
UNCOV
2945
            use_maxed_dominions = true;
×
2946
        }
2947
        else if (strcmp(argv[argIndex], "random") == 0)
257 ✔
2948
        {
2949
            opt_your_strategy = DeckStrategy::random;
2950
        }
2951
        else if (strcmp(argv[argIndex], "-r") == 0 || strcmp(argv[argIndex], "ordered") == 0)
257 ✔
2952
        {
2953
            opt_your_strategy = DeckStrategy::ordered;
2954
        }
2955
        else if (strcmp(argv[argIndex], "flexible") == 0 || strcmp(argv[argIndex], "flex") == 0)
257 ✔
2956
        {
2957
            opt_your_strategy = DeckStrategy::flexible;
2958
        }
2959
        else if (strcmp(argv[argIndex], "flexible-iter") == 0)
257 ✔
2960
        {
2961
            if (check_input_amount(argc, argv, argIndex, 1))
×
2962
                exit(1);
×
UNCOV
2963
            flexible_iter = atoi(argv[argIndex + 1]);
×
UNCOV
2964
            argIndex += 1;
×
2965
        }
2966
        else if (strcmp(argv[argIndex], "flexible-turn") == 0)
257 ✔
2967
        {
2968
            if (check_input_amount(argc, argv, argIndex, 1))
×
2969
                exit(1);
×
UNCOV
2970
            flexible_turn = atoi(argv[argIndex + 1]);
×
UNCOV
2971
            argIndex += 1;
×
2972
        }
2973
        else if (strcmp(argv[argIndex], "evaluate") == 0 || strcmp(argv[argIndex], "eval") == 0)
257 ✔
2974
        {
2975
            opt_your_strategy = DeckStrategy::evaluate;
2976
        }
2977
        else if (strcmp(argv[argIndex], "evaluate2") == 0 || strcmp(argv[argIndex], "eval2") == 0)
257 ✔
2978
        {
2979
            opt_your_strategy = DeckStrategy::evaluate_twice;
2980
        }
2981
        else if (strcmp(argv[argIndex], "eval-iter") == 0)
257 ✔
2982
        {
UNCOV
2983
            if (check_input_amount(argc, argv, argIndex, 1))
×
UNCOV
2984
                exit(1);
×
2985
            eval_iter = atoi(argv[argIndex + 1]);
×
2986
            argIndex += 1;
×
2987
        }
2988
        else if (strcmp(argv[argIndex], "eval-turn") == 0)
257 ✔
2989
        {
2990
            if (check_input_amount(argc, argv, argIndex, 1))
×
2991
                exit(1);
×
2992
            eval_turn = atoi(argv[argIndex + 1]);
×
2993
            argIndex += 1;
×
2994
        }
2995
        else if (strcmp(argv[argIndex], "exact-ordered") == 0)
257 ✔
2996
        {
2997
            opt_your_strategy = DeckStrategy::exact_ordered;
2998
        }
2999
        else if (strcmp(argv[argIndex], "enemy:evaluate") == 0)
257 ✔
3000
        {
3001
            opt_enemy_strategy = DeckStrategy::evaluate;
3002
        }
3003
        else if (strcmp(argv[argIndex], "enemy:evaluate2") == 0)
257 ✔
3004
        {
3005
            opt_enemy_strategy = DeckStrategy::evaluate_twice;
3006
        }
3007
        else if (strcmp(argv[argIndex], "enemy:flexible") == 0)
257 ✔
3008
        {
3009
            opt_enemy_strategy = DeckStrategy::flexible;
3010
        }
3011
        else if (strcmp(argv[argIndex], "enemy:ordered") == 0)
257 ✔
3012
        {
3013
            opt_enemy_strategy = DeckStrategy::ordered;
3014
        }
3015
        else if (strcmp(argv[argIndex], "enemy:flexible") == 0)
257 ✔
3016
        {
3017
            opt_enemy_strategy = DeckStrategy::flexible;
3018
        }
3019
        else if (strcmp(argv[argIndex], "enemy:exact-ordered") == 0)
257 ✔
3020
        {
3021
            opt_enemy_strategy = DeckStrategy::exact_ordered;
3022
        }
3023
        else if (strcmp(argv[argIndex], "endgame") == 0)
257 ✔
3024
        {
3025
            if (check_input_amount(argc, argv, argIndex, 1))
×
3026
                exit(1);
×
UNCOV
3027
            use_fused_card_level = atoi(argv[argIndex + 1]);
×
UNCOV
3028
            argIndex += 1;
×
3029
        }
3030
#ifndef NQUEST
3031
        else if (strcmp(argv[argIndex], "quest") == 0)
3032
        {
3033
            if (check_input_amount(argc, argv, argIndex, 1))
3034
                exit(1);
3035
            opt_quest = argv[argIndex + 1];
3036
            argIndex += 1;
3037
        }
3038
#endif
3039
        else if (strcmp(argv[argIndex], "threads") == 0 || strcmp(argv[argIndex], "-t") == 0)
257 ✔
3040
        {
3041
            if (check_input_amount(argc, argv, argIndex, 1))
85 ✔
3042
                exit(1);
×
3043
            opt_num_threads = atoi(argv[argIndex + 1]);
85 ✔
3044
#ifdef _OPENMP
3045
            omp_set_num_threads(opt_num_threads);
3046
#endif
3047
            argIndex += 1;
85 ✔
3048
        }
3049
        else if (strcmp(argv[argIndex], "target") == 0)
172 ✔
3050
        {
3051
            if (check_input_amount(argc, argv, argIndex, 1))
×
3052
                exit(1);
×
UNCOV
3053
            opt_target_score = argv[argIndex + 1];
×
UNCOV
3054
            argIndex += 1;
×
3055
        }
3056
        else if (strcmp(argv[argIndex], "turnlimit") == 0)
172 ✔
3057
        {
UNCOV
3058
            if (check_input_amount(argc, argv, argIndex, 1))
×
UNCOV
3059
                exit(1);
×
UNCOV
3060
            turn_limit = atoi(argv[argIndex + 1]);
×
UNCOV
3061
            argIndex += 1;
×
3062
        }
3063
        else if (strcmp(argv[argIndex], "mis") == 0)
172 ✔
3064
        {
3065
            if (check_input_amount(argc, argv, argIndex, 1))
×
3066
                exit(1);
×
3067
            min_increment_of_score = atof(argv[argIndex + 1]);
×
UNCOV
3068
            argIndex += 1;
×
3069
        }
3070
        else if (strcmp(argv[argIndex], "timeout") == 0) // set timeout in hours. tuo will stop approx. at the given time.
172 ✔
3071
        {
3072
            if (check_input_amount(argc, argv, argIndex, 1))
×
3073
                exit(1);
×
3074
            maximum_time = atof(argv[argIndex + 1]);
×
UNCOV
3075
            argIndex += 1;
×
3076
        }
3077
        else if (strcmp(argv[argIndex], "strict-ownedcards") == 0) // won't add missing cards, instead skips faulty decks
172 ✔
3078
        {
UNCOV
3079
            opt_skip_unclaimed_decks = true;
×
3080
        }
3081
        /*else if (strcmp(argv[argIndex], "trim-ownedcards") == 0) //won't add missing cards, instead removes missing cards from decks
3082
          {
3083
          opt_trim_unclaimed_decks = true;
3084
          }*/
3085
        else if (strcmp(argv[argIndex], "cl") == 0)
172 ✔
3086
        {
UNCOV
3087
            if (check_input_amount(argc, argv, argIndex, 1))
×
UNCOV
3088
                exit(1);
×
UNCOV
3089
            confidence_level = atof(argv[argIndex + 1]);
×
UNCOV
3090
            argIndex += 1;
×
3091
        }
3092
        else if (strcmp(argv[argIndex], "+so") == 0)
172 ✔
3093
        {
UNCOV
3094
            simplify_output = true;
×
3095
        }
3096
        else if (strcmp(argv[argIndex], "+uc") == 0)
172 ✔
3097
        {
UNCOV
3098
            print_upgraded = true;
×
3099
        }
3100
        else if (strcmp(argv[argIndex], "+vc") == 0)
172 ✔
3101
        {
UNCOV
3102
            print_values = true;
×
3103
        }
3104
        else if (strcmp(argv[argIndex], "+vc-x") == 0)
172 ✔
3105
        {
3106
            if (check_input_amount(argc, argv, argIndex, 1))
×
3107
                exit(1);
×
3108
            vc_x = atoi(argv[argIndex + 1]);
×
3109
            // print_values = true;
UNCOV
3110
            argIndex += 1;
×
3111
        }
3112
        else if (strcmp(argv[argIndex], "+ci") == 0)
172 ✔
3113
        {
UNCOV
3114
            show_ci = true;
×
3115
        }
3116
        else if (strcmp(argv[argIndex], "+hm") == 0)
172 ✔
3117
        {
UNCOV
3118
            use_harmonic_mean = true;
×
3119
        }
3120
        else if (strcmp(argv[argIndex], "no-fix") == 0)
172 ✔
3121
        {
UNCOV
3122
            for (int i = 0; i < Fix::num_fixes; ++i)
×
3123
                fixes[i] = false;
×
3124
        }
3125
        else if (strcmp(argv[argIndex], "fix-enhance-early") == 0)
172 ✔
3126
        {
UNCOV
3127
            fixes[Fix::enhance_early] = true;
×
3128
        }
3129
        else if (strcmp(argv[argIndex], "no-fix-enhance-early") == 0)
172 ✔
3130
        {
UNCOV
3131
            fixes[Fix::enhance_early] = false;
×
3132
        }
3133
        else if (strcmp(argv[argIndex], "fix-revenge-on-death") == 0)
172 ✔
3134
        {
3135
            fixes[Fix::revenge_on_death] = true;
×
3136
        }
3137
        else if (strcmp(argv[argIndex], "no-fix-revenge-on-death") == 0)
172 ✔
3138
        {
3139
            fixes[Fix::revenge_on_death] = false;
×
3140
        }
3141
        else if (strcmp(argv[argIndex], "fix-death-from-bge") == 0)
172 ✔
3142
        {
UNCOV
3143
            fixes[Fix::death_from_bge] = true;
×
3144
        }
3145
        else if (strcmp(argv[argIndex], "no-fix-death-from-bge") == 0)
172 ✔
3146
        {
3147
            fixes[Fix::death_from_bge] = false;
×
3148
        }
3149
        else if (strcmp(argv[argIndex], "fix-legion-under-megamorphosis") == 0)
172 ✔
3150
        {
UNCOV
3151
            fixes[Fix::legion_under_mega] = true;
×
3152
        }
3153
        else if (strcmp(argv[argIndex], "no-fix-legion-under-megamorphosis") == 0)
172 ✔
3154
        {
3155
            fixes[Fix::legion_under_mega] = false;
×
3156
        }
3157
        else if (strcmp(argv[argIndex], "update-barrier-each-turn") == 0)
172 ✔
3158
                {
UNCOV
3159
                        fixes[Fix::barrier_each_turn] = true;
×
3160
                }
3161
        else if (strcmp(argv[argIndex], "no-update-barrier-each-turn") == 0)
172 ✔
3162
                {
UNCOV
3163
                        fixes[Fix::barrier_each_turn] = false;
×
3164
                }
3165
        else if (strcmp(argv[argIndex], "update-dont-evade-mimic-selection") == 0)
172 ✔
3166
                {
UNCOV
3167
                        fixes[Fix::dont_evade_mimic_selection] = true;
×
3168
                }
3169
        else if (strcmp(argv[argIndex], "no-update-dont-evade-mimic-selection") == 0)
172 ✔
3170
                {
3171
                        fixes[Fix::dont_evade_mimic_selection] = false;
×
3172
                }
3173
        else if (strcmp(argv[argIndex], "update-leech-increase-max-hp") == 0)
172 ✔
3174
                {
3175
                        fixes[Fix::leech_increase_max_hp] = true;
×
3176
                }
3177
        else if (strcmp(argv[argIndex], "no-update-leech-increase-max-hp") == 0)
172 ✔
3178
                {
3179
                        fixes[Fix::leech_increase_max_hp] = false;
×
3180
                }
3181
        else if (strcmp(argv[argIndex], "update-counter-without-damage") == 0)
172 ✔
3182
                {
3183
                        fixes[Fix::counter_without_damage] = true;
×
3184
                }
3185
        else if (strcmp(argv[argIndex], "no-update-counter-without-damage") == 0)
172 ✔
3186
                {
3187
                        fixes[Fix::counter_without_damage] = false;
×
3188
                }
3189
        else if (strcmp(argv[argIndex], "update-corrosive-protect-armor") == 0)
172 ✔
3190
                {
3191
                        fixes[Fix::corrosive_protect_armor] = true;
×
3192
                }
3193
        else if (strcmp(argv[argIndex], "no-update-corrosive-protect-armor") == 0)
172 ✔
3194
                {
3195
                        fixes[Fix::corrosive_protect_armor] = false;
×
3196
                }
3197
        else if (strcmp(argv[argIndex], "update-poison-after-attacked") == 0)
172 ✔
3198
                {
3199
                        fixes[Fix::poison_after_attacked] = true;
×
3200
                }
3201
        else if (strcmp(argv[argIndex], "no-update-poison-after-attacked") == 0)
172 ✔
3202
                {
3203
                        fixes[Fix::poison_after_attacked] = false;
×
3204
                }
3205
        else if (strcmp(argv[argIndex], "update-subdue-before-attack") == 0)
172 ✔
3206
                {
UNCOV
3207
                        fixes[Fix::subdue_before_attack] = true;
×
3208
                }
3209
        else if (strcmp(argv[argIndex], "no-update-subdue-before-attack") == 0)
172 ✔
3210
                {
UNCOV
3211
                        fixes[Fix::subdue_before_attack] = false;
×
3212
                }
3213
        else if (strcmp(argv[argIndex], "update-reduce-delay-summoned-by-tower") == 0)
172 ✔
3214
        {
3215
            fixes[Fix::reduce_delay_summoned_by_tower] = true;
1 ✔
3216
        }
3217
        else if (strcmp(argv[argIndex], "no-update-reduce-delay-summoned-by-tower") == 0)
171 ✔
3218
        {
3219
            fixes[Fix::reduce_delay_summoned_by_tower] = false;
1 ✔
3220
        }
3221
        else if (strcmp(argv[argIndex], "seed") == 0)
170 ✔
3222
        {
3223
            if (check_input_amount(argc, argv, argIndex, 1))
85 ✔
3224
                exit(1);
×
3225
            sim_seed = atoi(argv[argIndex + 1]);
85 ✔
3226
            argIndex += 1;
85 ✔
3227
        }
3228
        else if (strcmp(argv[argIndex], "-v") == 0)
85 ✔
3229
        {
UNCOV
3230
            --debug_print;
×
3231
        }
3232
        else if (strcmp(argv[argIndex], "+v") == 0)
85 ✔
3233
        {
UNCOV
3234
            ++debug_print;
×
3235
        }
3236
        else if (strcmp(argv[argIndex], "vip") == 0)
85 ✔
3237
        {
UNCOV
3238
            if (check_input_amount(argc, argv, argIndex, 1))
×
UNCOV
3239
                exit(1);
×
3240
            opt_vip = argv[argIndex + 1];
×
UNCOV
3241
            argIndex += 1;
×
3242
        }
3243
        else if (strcmp(argv[argIndex], "allow-candidates") == 0)
85 ✔
3244
        {
UNCOV
3245
            if (check_input_amount(argc, argv, argIndex, 1))
×
UNCOV
3246
                exit(1);
×
UNCOV
3247
            opt_allow_candidates = argv[argIndex + 1];
×
3248
            argIndex += 1;
×
3249
        }
3250
        else if (strcmp(argv[argIndex], "disallow-candidates") == 0)
85 ✔
3251
        {
3252
            if (check_input_amount(argc, argv, argIndex, 1))
×
UNCOV
3253
                exit(1);
×
UNCOV
3254
            opt_disallow_candidates = argv[argIndex + 1];
×
UNCOV
3255
            argIndex += 1;
×
3256
        }
3257
        else if (strcmp(argv[argIndex], "disallow-recipes") == 0)
85 ✔
3258
        {
UNCOV
3259
            if (check_input_amount(argc, argv, argIndex, 1))
×
3260
                exit(1);
×
UNCOV
3261
            opt_disallow_recipes = argv[argIndex + 1];
×
UNCOV
3262
            argIndex += 1;
×
3263
        }
3264
        else if (strcmp(argv[argIndex], "hand") == 0) // set initial hand for test
85 ✔
3265
        {
UNCOV
3266
            if (check_input_amount(argc, argv, argIndex, 1))
×
UNCOV
3267
                exit(1);
×
3268
            opt_hand = argv[argIndex + 1];
×
UNCOV
3269
            argIndex += 1;
×
3270
        }
3271
        else if (strcmp(argv[argIndex], "enemy:hand") == 0) // set enemies' initial hand for test
85 ✔
3272
        {
UNCOV
3273
            if (check_input_amount(argc, argv, argIndex, 1))
×
UNCOV
3274
                exit(1);
×
UNCOV
3275
            opt_enemy_hand = argv[argIndex + 1];
×
3276
            argIndex += 1;
×
3277
        }
3278
        else if (strcmp(argv[argIndex], "yf") == 0 || strcmp(argv[argIndex], "yfort") == 0) // set forts
85 ✔
3279
        {
3280
            if (check_input_amount(argc, argv, argIndex, 1))
×
UNCOV
3281
                exit(1);
×
UNCOV
3282
            opt_forts = std::string(argv[argIndex + 1]);
×
UNCOV
3283
            argIndex += 1;
×
3284
        }
3285
        else if (strcmp(argv[argIndex], "yfpool") == 0 || strcmp(argv[argIndex], "yfortpool") == 0) // set forts
85 ✔
3286
        {
UNCOV
3287
            if (check_input_amount(argc, argv, argIndex, 1))
×
3288
                exit(1);
×
UNCOV
3289
            yfpool = std::stoi(argv[argIndex + 1]);
×
UNCOV
3290
            argIndex += 1;
×
3291
        }
3292
        else if (strcmp(argv[argIndex], "ef") == 0 || strcmp(argv[argIndex], "efort") == 0) // set enemies' forts
85 ✔
3293
        {
UNCOV
3294
            if (check_input_amount(argc, argv, argIndex, 1))
×
UNCOV
3295
                exit(1);
×
UNCOV
3296
            opt_enemy_forts = std::string(argv[argIndex + 1]);
×
UNCOV
3297
            argIndex += 1;
×
3298
        }
3299
        else if (strcmp(argv[argIndex], "efpool") == 0 || strcmp(argv[argIndex], "efortpool") == 0) // set forts
85 ✔
3300
        {
UNCOV
3301
            if (check_input_amount(argc, argv, argIndex, 1))
×
UNCOV
3302
                exit(1);
×
UNCOV
3303
            efpool = std::stoi(argv[argIndex + 1]);
×
UNCOV
3304
            argIndex += 1;
×
3305
        }
3306
        else if (strcmp(argv[argIndex], "yd") == 0 || strcmp(argv[argIndex], "ydom") == 0) // set dominions
85 ✔
3307
        {
UNCOV
3308
            if (check_input_amount(argc, argv, argIndex, 1))
×
UNCOV
3309
                exit(1);
×
UNCOV
3310
            opt_doms = std::string(argv[argIndex + 1]);
×
3311
            argIndex += 1;
×
3312
        }
3313
        else if (strcmp(argv[argIndex], "ed") == 0 || strcmp(argv[argIndex], "edom") == 0) // set enemies' dominions
85 ✔
3314
        {
3315
            if (check_input_amount(argc, argv, argIndex, 1))
×
UNCOV
3316
                exit(1);
×
UNCOV
3317
            opt_enemy_doms = std::string(argv[argIndex + 1]);
×
UNCOV
3318
            argIndex += 1;
×
3319
        }
3320
        else if (strcmp(argv[argIndex], "sim") == 0)
85 ✔
3321
        {
3322
            if (check_input_amount(argc, argv, argIndex, 1))
78 ✔
UNCOV
3323
                exit(1);
×
3324
            opt_todo.push_back(std::make_tuple((unsigned)atoi(argv[argIndex + 1]), 0u, simulate));
78 ✔
3325
            if (std::get<0>(opt_todo.back()) < 10)
78 ✔
3326
            {
3327
                opt_num_threads = 1;
×
3328
            }
3329
            argIndex += 1;
78 ✔
3330
        }
3331
        // climbing tasks
3332
        else if (strcmp(argv[argIndex], "climbex") == 0)
7 ✔
3333
        {
3334
            if (check_input_amount(argc, argv, argIndex, 2))
1 ✔
3335
                exit(1);
×
3336
            opt_todo.push_back(std::make_tuple((unsigned)atoi(argv[argIndex + 1]), (unsigned)atoi(argv[argIndex + 2]), climb));
1 ✔
3337
            if (std::get<1>(opt_todo.back()) < 10)
1 ✔
3338
            {
UNCOV
3339
                opt_num_threads = 1;
×
3340
            }
3341
            opt_do_optimization = true;
1 ✔
3342
            opt_multi_optimization = true;
1 ✔
3343
            argIndex += 2;
1 ✔
3344
        }
3345
        else if (strcmp(argv[argIndex], "climb") == 0)
6 ✔
3346
        {
3347
            if (check_input_amount(argc, argv, argIndex, 1))
2 ✔
3348
                exit(1);
×
3349
            opt_todo.push_back(std::make_tuple((unsigned)atoi(argv[argIndex + 1]), (unsigned)atoi(argv[argIndex + 1]), climb));
2 ✔
3350
            if (std::get<1>(opt_todo.back()) < 10)
2 ✔
3351
            {
3352
                opt_num_threads = 1;
1 ✔
3353
            }
3354
            opt_do_optimization = true;
2 ✔
3355
            opt_multi_optimization = true;
2 ✔
3356
            argIndex += 1;
2 ✔
3357
        }
3358
        else if (strcmp(argv[argIndex], "climb_forts") == 0)
4 ✔
3359
        {
UNCOV
3360
            if (check_input_amount(argc, argv, argIndex, 1))
×
3361
                exit(1);
×
3362
            opt_todo.push_back(std::make_tuple((unsigned)atoi(argv[argIndex + 1]), (unsigned)atoi(argv[argIndex + 1]), climb_forts));
×
3363
            if (std::get<1>(opt_todo.back()) < 10)
×
3364
            {
UNCOV
3365
                opt_num_threads = 1;
×
3366
            }
UNCOV
3367
            argIndex += 1;
×
3368
        }
3369
        else if (strcmp(argv[argIndex], "anneal") == 0)
4 ✔
3370
        {
3371
            if (check_input_amount(argc, argv, argIndex, 3))
1 ✔
UNCOV
3372
                exit(1);
×
3373
            opt_todo.push_back(std::make_tuple((unsigned)atoi(argv[argIndex + 1]), (unsigned)atoi(argv[argIndex + 1]), anneal));
1 ✔
3374
            temperature = std::stod(argv[argIndex + 2]);
2 ✔
3375
            coolingRate = std::stod(argv[argIndex + 3]);
2 ✔
3376
            if (std::get<1>(opt_todo.back()) < 10)
1 ✔
3377
            {
3378
                opt_num_threads = 1;
×
3379
            }
3380
            opt_do_optimization = true;
1 ✔
3381
            opt_multi_optimization = true;
1 ✔
3382
            argIndex += 3;
1 ✔
3383
        }
3384
        else {
3385
            tokenParsed = false;
3386
        }
3387
        
3388
        if (!tokenParsed)
428 ✔
3389
        {
3390
        //no indent: keep two parts of a nested if at the same level
3391
        if (strcmp(argv[argIndex], "genetic") == 0)
3 ✔
3392
        {
3393
            if (check_input_amount(argc, argv, argIndex, 1))
1 ✔
UNCOV
3394
                exit(1);
×
3395
            opt_todo.push_back(std::make_tuple((unsigned)atoi(argv[argIndex + 1]), (unsigned)atoi(argv[argIndex + 1]), genetic));
1 ✔
3396
            if (std::get<1>(opt_todo.back()) < 10)
1 ✔
3397
            {
3398
                opt_num_threads = 1;
×
3399
            }
3400
            opt_do_optimization = true;
1 ✔
3401
            opt_multi_optimization = true;
1 ✔
3402
            argIndex += 1;
1 ✔
3403
        }
3404
        else if (strcmp(argv[argIndex], "genetic-pool") == 0 || strcmp(argv[argIndex], "beam-size") == 0 || strcmp(argv[argIndex], "size") == 0)
2 ✔
3405
        {
UNCOV
3406
            if (check_input_amount(argc, argv, argIndex, 1))
×
UNCOV
3407
                exit(1);
×
3408
            pool_size = std::stod(argv[argIndex + 1]);
×
UNCOV
3409
            argIndex += 1;
×
3410
        }
3411
        else if (strcmp(argv[argIndex], "genetic-gen") == 0)
2 ✔
3412
        {
UNCOV
3413
            if (check_input_amount(argc, argv, argIndex, 1))
×
UNCOV
3414
                exit(1);
×
UNCOV
3415
            generations = std::stod(argv[argIndex + 1]);
×
3416
            argIndex += 1;
×
3417
        }
3418
        else if (strcmp(argv[argIndex], "genetic-opts") == 0)
2 ✔
3419
        {
3420
            if (check_input_amount(argc, argv, argIndex, 3))
×
UNCOV
3421
                exit(1);
×
UNCOV
3422
            opt_pool_keep = std::stod(argv[argIndex + 1]);
×
UNCOV
3423
            opt_pool_cross = std::stod(argv[argIndex + 2]);
×
UNCOV
3424
            opt_pool_mutate = std::stod(argv[argIndex + 3]);
×
UNCOV
3425
            argIndex += 3;
×
3426
        }
3427
        else if (strcmp(argv[argIndex], "beam") == 0)
2 ✔
3428
        {
3429
            if (check_input_amount(argc, argv, argIndex, 1))
2 ✔
UNCOV
3430
                exit(1);
×
3431
            opt_todo.push_back(std::make_tuple((unsigned)atoi(argv[argIndex + 1]), (unsigned)atoi(argv[argIndex + 1]), beam));
2 ✔
3432
            if (std::get<1>(opt_todo.back()) < 10)
2 ✔
3433
            {
3434
                opt_num_threads = 1;
1 ✔
3435
            }
3436
            opt_do_optimization = true;
2 ✔
3437
            opt_multi_optimization = true;
2 ✔
3438
            argIndex += 1;
2 ✔
3439
        }
UNCOV
3440
        else if (strcmp(argv[argIndex], "reorder") == 0)
×
3441
        {
3442
            if (check_input_amount(argc, argv, argIndex, 1))
×
3443
                exit(1);
×
3444
            opt_todo.push_back(std::make_tuple((unsigned)atoi(argv[argIndex + 1]), (unsigned)atoi(argv[argIndex + 1]), reorder));
×
UNCOV
3445
            if (std::get<1>(opt_todo.back()) < 10)
×
3446
            {
UNCOV
3447
                opt_num_threads = 1;
×
3448
            }
UNCOV
3449
            opt_do_reorder = true;
×
UNCOV
3450
            argIndex += 1;
×
3451
        }
UNCOV
3452
        else if (strncmp(argv[argIndex], "scale-opts:", 11) == 0)
×
3453
        {
UNCOV
3454
            std::string climb_opts_str(argv[argIndex] + 11);
×
UNCOV
3455
            boost::tokenizer<boost::char_delimiters_separator<char>> climb_opts{climb_opts_str, boost::char_delimiters_separator<char>{false, ",", ""}};
×
UNCOV
3456
            for (const auto &opt : climb_opts)
×
3457
            {
UNCOV
3458
                const auto dot_pos = opt.find(".");
×
3459
                const auto slash_pos = opt.find("/");
×
UNCOV
3460
                const bool has_value = (dot_pos != std::string::npos);
×
UNCOV
3461
                if (slash_pos == std::string::npos)
×
UNCOV
3462
                    throw std::runtime_error("scale-opts:" + opt + " requires an argument");
×
UNCOV
3463
                const std::string &opt_type = has_value ? opt.substr(0, dot_pos) : "";
×
UNCOV
3464
                const std::string opt_name{has_value ? opt.substr(dot_pos + 1, slash_pos - dot_pos - 1) : opt.substr(0, slash_pos)};
×
UNCOV
3465
                const std::string opt_value{opt.substr(slash_pos + 1)};
×
UNCOV
3466
                if ((opt_name == "hp"))
×
3467
                {
UNCOV
3468
                    hp_scale = atof(opt_value.c_str());
×
3469
                }
UNCOV
3470
                else if ((opt_name == "atk"))
×
3471
                {
UNCOV
3472
                    atk_scale = atof(opt_value.c_str());
×
3473
                }
UNCOV
3474
                else if (opt_name == "x")
×
3475
                {
UNCOV
3476
                    x_skill_scale[skill_name_to_id(opt_type)] = atof(opt_value.c_str());
×
3477
                }
UNCOV
3478
                else if (opt_name == "n")
×
3479
                {
UNCOV
3480
                    n_skill_scale[skill_name_to_id(opt_type)] = atof(opt_value.c_str());
×
3481
                }
UNCOV
3482
                else if (opt_name == "c")
×
3483
                {
UNCOV
3484
                    c_skill_scale[skill_name_to_id(opt_type)] = atof(opt_value.c_str());
×
3485
                }
3486
                else
3487
                {
3488
                    std::cerr << "Error: Unknown scale option " << opt_name << " of " << opt_type;
×
3489
                    if (has_value)
×
3490
                    {
UNCOV
3491
                        std::cerr << " (value is: " << opt_value << ")";
×
3492
                    }
UNCOV
3493
                    std::cerr << std::endl;
×
3494
                    exit(1);
×
3495
                }
3496
            }
×
3497
        }
×
3498
        // climbing options
UNCOV
3499
        else if (strncmp(argv[argIndex], "climb-opts:", 11) == 0)
×
3500
        {
3501
            std::string climb_opts_str(argv[argIndex] + 11);
×
3502
            boost::tokenizer<boost::char_delimiters_separator<char>> climb_opts{climb_opts_str, boost::char_delimiters_separator<char>{false, ",", ""}};
×
3503
            for (const auto &opt : climb_opts)
×
3504
            {
3505
                const auto delim_pos = opt.find("=");
×
3506
                const bool has_value = (delim_pos != std::string::npos);
×
UNCOV
3507
                const std::string &opt_name = has_value ? opt.substr(0, delim_pos) : opt;
×
UNCOV
3508
                const std::string opt_value{has_value ? opt.substr(delim_pos + 1) : opt};
×
UNCOV
3509
                auto ensure_opt_value = [](const bool has_value, const std::string &opt_name)
×
3510
                {
3511
                    if (!has_value)
×
3512
                    {
UNCOV
3513
                        throw std::runtime_error("climb-opts:" + opt_name + " requires an argument");
×
3514
                    }
UNCOV
3515
                };
×
UNCOV
3516
                if ((opt_name == "iter-mul") or (opt_name == "iterations-multiplier"))
×
3517
                {
UNCOV
3518
                    ensure_opt_value(has_value, opt_name);
×
UNCOV
3519
                    iterations_multiplier = std::stoi(opt_value);
×
3520
                }
3521
                else if ((opt_name == "egc") or (opt_name == "endgame-commander") or (opt_name == "min-commander-fusion-level"))
×
3522
                {
3523
                    ensure_opt_value(has_value, opt_name);
×
3524
                    use_fused_commander_level = std::stoi(opt_value);
×
3525
                }
3526
                else if (opt_name == "use-all-commander-levels")
×
3527
                {
3528
                    use_top_level_commander = false;
×
3529
                }
3530
                else if (opt_name == "use-all-card-levels")
×
3531
                {
UNCOV
3532
                    use_top_level_card = false;
×
3533
                }
UNCOV
3534
                else if ((opt_name == "recent-boost") or (opt_name == "rb")) // prefer new cards in hill climb and break climb loop faster
×
3535
                {
3536
                    prefered_recent = true;
×
3537
                }
UNCOV
3538
                else if ((opt_name == "recent-boost-times") or (opt_name == "rbt")) // prefer new cards in hill climb and break climb loop faster
×
3539
                {
3540
                    ensure_opt_value(has_value, opt_name);
×
3541
                    prefered_factor = std::stoi(opt_value);
×
3542
                }
3543
                else if ((opt_name == "recent-boost-percent") or (opt_name == "rbp")) // prefer new cards in hill climb and break climb loop faster
×
3544
                {
3545
                    ensure_opt_value(has_value, opt_name);
×
3546
                    recent_percent = std::stoi(opt_value);
×
3547
                }
UNCOV
3548
                else if ((opt_name == "otd") or (opt_name == "open-the-deck"))
×
3549
                {
UNCOV
3550
                    mode_open_the_deck = true;
×
3551
                }
3552
                else
3553
                {
UNCOV
3554
                    std::cerr << "Error: Unknown climb option " << opt_name;
×
3555
                    if (has_value)
×
3556
                    {
3557
                        std::cerr << " (value is: " << opt_value << ")";
×
3558
                    }
3559
                    std::cerr << std::endl;
×
UNCOV
3560
                    exit(1);
×
3561
                }
UNCOV
3562
            }
×
3563
        }
×
UNCOV
3564
        else if (strcmp(argv[argIndex], "debug") == 0)
×
3565
        {
UNCOV
3566
            opt_todo.push_back(std::make_tuple(0u, 0u, debug));
×
UNCOV
3567
            opt_num_threads = 1;
×
3568
            // disable saving to db
3569
            use_db_write= false;
×
3570
            use_db_load = false;
×
3571
        }
3572
        else if (strcmp(argv[argIndex], "debuguntil") == 0)
×
3573
        {
3574
            // output the debug info for the first battle that min_score <= score <= max_score.
3575
            // E.g., 0 0: lose; 100 100: win (non-raid); 20 100: at least 20 damage (raid).
UNCOV
3576
            if (check_input_amount(argc, argv, argIndex, 2))
×
3577
                exit(1);
×
3578
            opt_todo.push_back(std::make_tuple((unsigned)atoi(argv[argIndex + 1]), (unsigned)atoi(argv[argIndex + 2]), debuguntil));
×
UNCOV
3579
            opt_num_threads = 1;
×
3580
            argIndex += 2;
×
3581
            // disable saving to db
3582
            use_db_write= false;
×
3583
            use_db_load = false;
×
3584
        }
3585
        else
3586
        {
3587
            std::cerr << "Error: Unknown option " << argv[argIndex] << std::endl;
×
3588
            exit(1);
×
3589
        }
3590
        } // if (tokenParsed)
3591
    }
3592
    load_db(prefix);
170 ✔
3593
    load_ml(prefix);
170 ✔
3594

3595
#ifdef _OPENMP
3596
    opt_num_threads = omp_get_max_threads();
3597
#endif
3598
    // delete, since prefix/suffix might change we reload all cards.
3599
    // redundant to calling init() before run()
3600
    all_cards.clear();
85 ✔
3601
    owned_alpha_dominion = nullptr;
85 ✔
3602

3603
    all_cards = Cards();
85 ✔
3604
    Decks decks;
85 ✔
3605
    std::unordered_map<std::string, std::string> bge_aliases;
85 ✔
3606
    load_skills_set_xml(all_cards, prefix + "data/skills_set.xml", true);
85 ✔
3607
    for (unsigned section = 1;
1,828 ✔
3608
         load_cards_xml(all_cards, prefix + "data/cards_section_" + std::to_string(section) + ".xml", false);
3,656 ✔
3609
         ++section)
3610
        ;
3611
    all_cards.organize();
85 ✔
3612
    load_levels_xml(all_cards, prefix + "data/levels.xml", true);
85 ✔
3613
    all_cards.fix_dominion_recipes();
85 ✔
3614
    for (const auto &suffix : fn_suffix_list)
170 ✔
3615
    {
3616
        load_decks_xml(decks, all_cards, prefix + "data/missions" + suffix + ".xml", prefix + "data/raids" + suffix + ".xml", suffix.empty());
510 ✔
3617
        load_recipes_xml(all_cards, prefix + "data/fusion_recipes_cj2" + suffix + ".xml", suffix.empty());
340 ✔
3618
        read_card_abbrs(all_cards, prefix + "data/cardabbrs" + suffix + ".txt");
340 ✔
3619
    }
3620
    for (const auto &suffix : fn_suffix_list)
170 ✔
3621
    {
3622
        load_custom_decks(decks, all_cards, prefix + "data/customdecks" + suffix + ".txt");
340 ✔
3623
        map_keys_to_set(read_custom_cards(all_cards, prefix + "data/allowed_candidates" + suffix + ".txt", false), allowed_candidates);
340 ✔
3624
        map_keys_to_set(read_custom_cards(all_cards, prefix + "data/disallowed_candidates" + suffix + ".txt", false), disallowed_candidates);
340 ✔
3625
        map_keys_to_set(read_custom_cards(all_cards, prefix + "data/disallowed_recipes" + suffix + ".txt", false), disallowed_recipes);
340 ✔
3626
    }
3627

3628
    read_bge_aliases(bge_aliases, prefix + "data/bges.txt");
85 ✔
3629

3630
    fill_skill_table();
85 ✔
3631

3632
    if (opt_do_optimization and use_owned_cards)
85 ✔
3633
    {
3634
        if (opt_owned_cards_str_list.empty())
7 ✔
3635
        { // load default files only if specify no -o=
3636
            for (const auto &suffix : fn_suffix_list)
14 ✔
3637
            {
3638
                std::string filename = prefix + "data/ownedcards" + suffix + ".txt";
21 ✔
3639
                if (boost::filesystem::exists(filename))
21 ✔
3640
                {
3641
                    opt_owned_cards_str_list.push_back(filename);
7 ✔
3642
                }
3643
            }
7 ✔
3644
        }
3645
        std::map<unsigned, unsigned> _owned_cards;
7 ✔
3646
        for (const auto &oc_str : opt_owned_cards_str_list)
14 ✔
3647
        {
3648
            read_owned_cards(all_cards, _owned_cards, oc_str);
7 ✔
3649
        }
3650

3651
        // keep only one copy of alpha dominion
3652
        for (auto owned_it = _owned_cards.begin(); owned_it != _owned_cards.end();)
175 ✔
3653
        {
3654
            const Card *owned_card = all_cards.by_id(owned_it->first);
168 ✔
3655
            bool need_remove = (!owned_it->second);
168 ✔
3656
            if (!need_remove && (owned_card->m_category == CardCategory::dominion_alpha))
168 ✔
3657
            {
3658
                if (!owned_alpha_dominion)
21 ✔
3659
                {
3660
                    owned_alpha_dominion = owned_card;
7 ✔
3661
                }
3662
                else
3663
                {
3664
                    /*std::cerr << "Warning: ownedcards already contains alpha dominion (" << owned_alpha_dominion->m_name
3665
                      << "): removing additional " << owned_card->m_name << std::endl;
3666
                      need_remove = true;*/
3667
                }
3668
            }
3669
            if (need_remove)
168 ✔
3670
            {
UNCOV
3671
                owned_it = _owned_cards.erase(owned_it);
×
3672
            }
3673
            else
3674
            {
3675
                ++owned_it;
168 ✔
3676
            }
3677
        }
3678
        if (!owned_alpha_dominion && use_owned_dominions)
7 ✔
3679
        {
3680
            // owned_alpha_dominion = all_cards.by_id(50002);
3681
            // std::cerr << "Warning: dominion climbing enabled and no alpha dominion found in owned cards, adding default "
3682
            //     << owned_alpha_dominion->m_name << std::endl;
3683
        }
3684
        if (owned_alpha_dominion)
7 ✔
3685
        {
3686
            _owned_cards[owned_alpha_dominion->m_id] = 1;
7 ✔
3687
        }
3688

3689
        // remap owned cards to unordered map (should be quicker for searching)
3690
        owned_cards.reserve(_owned_cards.size());
7 ✔
3691
        for (auto owned_it = _owned_cards.begin(); owned_it != _owned_cards.end(); ++owned_it)
175 ✔
3692
        {
3693
            owned_cards[owned_it->first] = owned_it->second;
168 ✔
3694
        }
3695
    }
7 ✔
3696

3697
    // parse BGEs
3698
    opt_bg_effects[0].fill(0);
2,380 ✔
3699
    opt_bg_effects[1].fill(0);
340 ✔
3700
    for (int player = 2; player >= 0; --player)
340 ✔
3701
    {
3702
        for (auto &&opt_effect : opt_effects[player])
317 ✔
3703
        {
3704
            std::unordered_set<std::string> used_bge_aliases;
62 ✔
3705
            if (!parse_bge(opt_effect, player, bge_aliases, opt_bg_effects[0], opt_bg_effects[1], opt_bg_skills[0], opt_bg_skills[1], used_bge_aliases))
186 ✔
3706
            {
UNCOV
3707
                exit(1);
×
3708
            }
3709
        }
62 ✔
3710
    }
3711

3712
    // parse allowed candidates from options
3713
    try
85 ✔
3714
    {
3715
        auto &&id_marks = string_to_ids(all_cards, opt_allow_candidates, "allowed-candidates");
85 ✔
3716
        for (const auto &cid : id_marks.first)
85 ✔
3717
        {
UNCOV
3718
            allowed_candidates.insert(cid);
×
3719
        }
UNCOV
3720
    }
×
UNCOV
3721
    catch (const std::runtime_error &e)
×
3722
    {
UNCOV
3723
        std::cerr << "Error: allow-candidates " << opt_allow_candidates << ": " << e.what() << std::endl;
×
UNCOV
3724
        exit(1);
×
UNCOV
3725
    }
×
3726

3727
    // parse disallowed candidates from options
3728
    try
85 ✔
3729
    {
3730
        auto &&id_marks = string_to_ids(all_cards, opt_disallow_candidates, "disallowed-candidates");
85 ✔
3731
        for (const auto &cid : id_marks.first)
85 ✔
3732
        {
UNCOV
3733
            disallowed_candidates.insert(cid);
×
3734
        }
UNCOV
3735
    }
×
UNCOV
3736
    catch (const std::runtime_error &e)
×
3737
    {
UNCOV
3738
        std::cerr << "Error: disallow-candidates " << opt_disallow_candidates << ": " << e.what() << std::endl;
×
UNCOV
3739
        exit(1);
×
UNCOV
3740
    }
×
3741

3742
    // parse & drop disallowed recipes
3743
    try
85 ✔
3744
    {
3745
        auto &&id_dis_recipes = string_to_ids(all_cards, opt_disallow_recipes, "disallowed-recipes");
85 ✔
3746
        for (auto &cid : id_dis_recipes.first)
85 ✔
3747
        {
UNCOV
3748
            all_cards.erase_fusion_recipe(cid);
×
3749
        }
UNCOV
3750
    }
×
UNCOV
3751
    catch (const std::runtime_error &e)
×
3752
    {
UNCOV
3753
        std::cerr << "Error: disallow-recipes " << opt_disallow_recipes << ": " << e.what() << std::endl;
×
UNCOV
3754
        exit(1);
×
UNCOV
3755
    }
×
3756
    for (auto cid : disallowed_recipes)
85 ✔
3757
    {
UNCOV
3758
        all_cards.erase_fusion_recipe(cid);
×
3759
    }
3760

3761
#ifndef NQUEST
3762
    if (!opt_quest.empty())
3763
    {
3764
        try
3765
        {
3766
            optimization_mode = OptimizationMode::quest;
3767
            std::vector<std::string> tokens;
3768
            boost::split(tokens, opt_quest, boost::is_any_of(" -"));
3769
            if (tokens.size() < 3)
3770
            {
3771
                throw std::runtime_error("Expect one of: su n skill; sd n skill; cu n faction/strcture; ck n structure");
3772
            }
3773
            auto type_str = boost::to_lower_copy(tokens[0]);
3774
            tuo::quest.quest_value = boost::lexical_cast<unsigned>(tokens[1]);
3775
            auto key_str = boost::to_lower_copy(tokens[2]);
3776
            unsigned quest_index = 3;
3777
            if (type_str == "su" || type_str == "sd")
3778
            {
3779
                Skill::Skill skill_id = skill_name_to_id(key_str);
3780
                if (skill_id == Skill::no_skill)
3781
                {
3782
                    std::cerr << "Error: Expect skill in quest \"" << opt_quest << "\".\n";
3783
                    exit(1);
3784
                }
3785
                tuo::quest.quest_type = type_str == "su" ? QuestType::skill_use : QuestType::skill_damage;
3786
                tuo::quest.quest_key = skill_id;
3787
            }
3788
            else if (type_str == "cu" || type_str == "ck")
3789
            {
3790
                if (key_str == "assault")
3791
                {
3792
                    tuo::quest.quest_type = type_str == "cu" ? QuestType::type_card_use : QuestType::type_card_kill;
3793
                    tuo::quest.quest_key = CardType::assault;
3794
                }
3795
                else if (key_str == "structure")
3796
                {
3797
                    tuo::quest.quest_type = type_str == "cu" ? QuestType::type_card_use : QuestType::type_card_kill;
3798
                    tuo::quest.quest_key = CardType::structure;
3799
                }
3800
                else
3801
                {
3802
                    for (unsigned i = 1; i < Faction::num_factions; ++i)
3803
                    {
3804
                        if (key_str == boost::to_lower_copy(faction_names[i]))
3805
                        {
3806
                            tuo::quest.quest_type = type_str == "cu" ? QuestType::faction_assault_card_use : QuestType::faction_assault_card_kill;
3807
                            tuo::quest.quest_key = i;
3808
                            break;
3809
                        }
3810
                    }
3811
                    if (tuo::quest.quest_key == 0)
3812
                    {
3813
                        std::cerr << "Error: Expect assault, structure or faction in quest \"" << opt_quest << "\".\n";
3814
                        exit(1);
3815
                    }
3816
                }
3817
            }
3818
            else if (type_str == "cs")
3819
            {
3820
                unsigned card_id;
3821
                unsigned card_num;
3822
                char num_sign;
3823
                char mark;
3824
                try
3825
                {
3826
                    parse_card_spec(all_cards, key_str, card_id, card_num, num_sign, mark);
3827
                    tuo::quest.quest_type = QuestType::card_survival;
3828
                    tuo::quest.quest_key = card_id;
3829
                }
3830
                catch (const std::runtime_error &e)
3831
                {
3832
                    std::cerr << "Error: Expect a card in quest \"" << opt_quest << "\".\n";
3833
                    exit(1);
3834
                }
3835
            }
3836
            else if (type_str == "suoc" && tokens.size() >= 4)
3837
            {
3838
                Skill::Skill skill_id = skill_name_to_id(key_str);
3839
                if (skill_id == Skill::no_skill)
3840
                {
3841
                    std::cerr << "Error: Expect skill in quest \"" << opt_quest << "\".\n";
3842
                    exit(1);
3843
                }
3844
                unsigned card_id;
3845
                unsigned card_num;
3846
                char num_sign;
3847
                char mark;
3848
                try
3849
                {
3850
                    parse_card_spec(all_cards, boost::to_lower_copy(tokens[3]), card_id, card_num, num_sign, mark);
3851
                    quest_index += 1;
3852
                    tuo::quest.quest_type = QuestType::skill_use;
3853
                    tuo::quest.quest_key = skill_id;
3854
                    tuo::quest.quest_2nd_key = card_id;
3855
                }
3856
                catch (const std::runtime_error &e)
3857
                {
3858
                    std::cerr << "Error: Expect a card in quest \"" << opt_quest << "\".\n";
3859
                    exit(1);
3860
                }
3861
            }
3862
            else
3863
            {
3864
                throw std::runtime_error("Expect one of: su n skill; sd n skill; cu n faction/strcture; ck n structure");
3865
            }
3866
            tuo::quest.quest_score = tuo::quest.quest_value;
3867
            for (unsigned i = quest_index; i < tokens.size(); ++i)
3868
            {
3869
                const auto &token = tokens[i];
3870
                if (token == "each")
3871
                {
3872
                    tuo::quest.must_fulfill = true;
3873
                    tuo::quest.quest_score = 100;
3874
                }
3875
                else if (token == "win")
3876
                {
3877
                    tuo::quest.must_win = true;
3878
                }
3879
                else if (token.substr(0, 2) == "q=")
3880
                {
3881
                    tuo::quest.quest_score = boost::lexical_cast<unsigned>(token.substr(2));
3882
                }
3883
                else if (token.substr(0, 2) == "w=")
3884
                {
3885
                    tuo::quest.win_score = boost::lexical_cast<unsigned>(token.substr(2));
3886
                }
3887
                else
3888
                {
3889
                    throw std::runtime_error("Cannot recognize " + token);
3890
                }
3891
            }
3892
            max_possible_score[(size_t)optimization_mode] = tuo::quest.quest_score + tuo::quest.win_score;
3893
        }
3894
        catch (const boost::bad_lexical_cast &e)
3895
        {
3896
            std::cerr << "Error: Expect a number in quest \"" << opt_quest << "\".\n";
3897
            exit(1);
3898
        }
3899
        catch (const std::runtime_error &e)
3900
        {
3901
            std::cerr << "Error: quest " << opt_quest << ": " << e.what() << std::endl;
3902
            exit(1);
3903
        }
3904
    }
3905
#endif
3906

3907
    // std::string your_deck_name{argv[1]};
3908
    auto &&your_deck_list_parsed = parse_deck_list(your_deck_list, decks);
170 ✔
3909
    auto &&enemy_deck_list_parsed = parse_deck_list(enemy_deck_list, decks);
170 ✔
3910

3911
    // Deck* your_deck{nullptr};
3912
    std::vector<Deck *> your_decks;
85 ✔
3913
    std::vector<Deck *> enemy_decks;
85 ✔
3914
    std::vector<long double> your_decks_factors;
85 ✔
3915
    std::vector<long double> enemy_decks_factors;
85 ✔
3916
    for (auto deck_parsed : your_deck_list_parsed)
398 ✔
3917
    {
3918
        Deck *your_deck{nullptr};
313 ✔
3919
        try
313 ✔
3920
        {
3921
            your_deck = find_deck(decks, all_cards, deck_parsed.first)->clone();
626 ✔
3922
        }
UNCOV
3923
        catch (const std::runtime_error &e)
×
3924
        {
UNCOV
3925
            std::cerr << "Error: Deck " << deck_parsed.first << ": " << e.what() << std::endl;
×
UNCOV
3926
            exit(1);
×
UNCOV
3927
        }
×
3928
        if (your_deck == nullptr)
313 ✔
3929
        {
UNCOV
3930
            std::cerr << "Error: Invalid attack deck name/hash " << deck_parsed.first << ".\n";
×
UNCOV
3931
            exit(1);
×
3932
        }
3933
        else if (!your_deck->variable_cards.empty())
313 ✔
3934
        {
UNCOV
3935
            std::cerr << "Error: Invalid attack deck " << deck_parsed.first << ": has optional cards.\n";
×
UNCOV
3936
            your_deck = nullptr;
×
3937
        }
3938
        else if (!your_deck->variable_forts.empty())
313 ✔
3939
        {
UNCOV
3940
            std::cerr << "Error: Invalid attack deck " << deck_parsed.first << ": has optional cards.\n";
×
UNCOV
3941
            your_deck = nullptr;
×
3942
        }
3943
        if (your_deck == nullptr)
313 ✔
3944
        {
UNCOV
3945
            usage(argc, argv);
×
UNCOV
3946
            exit(1);
×
3947
            // return 255;
3948
        }
3949

3950
        your_deck->strategy = opt_your_strategy;
313 ✔
3951
        if (!opt_forts.empty())
313 ✔
3952
        {
UNCOV
3953
            try
×
3954
            {
UNCOV
3955
                if (!yfpool)
×
UNCOV
3956
                    your_deck->add_forts(opt_forts + ",");
×
3957
                else
UNCOV
3958
                    your_deck->add_pool_forts(opt_forts + ",", yfpool);
×
3959
            }
UNCOV
3960
            catch (const std::runtime_error &e)
×
3961
            {
UNCOV
3962
                std::cerr << "Error: yfort " << opt_forts << ": " << e.what() << std::endl;
×
UNCOV
3963
                exit(1);
×
UNCOV
3964
            }
×
3965
        }
3966
        if (!opt_doms.empty())
313 ✔
3967
        {
UNCOV
3968
            try
×
3969
            {
UNCOV
3970
                your_deck->add_dominions(opt_doms + ",", true);
×
3971
            }
UNCOV
3972
            catch (const std::runtime_error &e)
×
3973
            {
UNCOV
3974
                std::cerr << "Error: ydom " << opt_doms << ": " << e.what() << std::endl;
×
UNCOV
3975
                exit(1);
×
UNCOV
3976
            }
×
3977
        }
3978

3979
        try
313 ✔
3980
        {
3981
            your_deck->set_vip_cards(opt_vip);
313 ✔
3982
        }
UNCOV
3983
        catch (const std::runtime_error &e)
×
3984
        {
UNCOV
3985
            std::cerr << "Error: vip " << opt_vip << ": " << e.what() << std::endl;
×
UNCOV
3986
            exit(1);
×
UNCOV
3987
        }
×
3988

3989
        try
313 ✔
3990
        {
3991
            your_deck->set_given_hand(opt_hand);
313 ✔
3992
        }
UNCOV
3993
        catch (const std::runtime_error &e)
×
3994
        {
UNCOV
3995
            std::cerr << "Error: hand " << opt_hand << ": " << e.what() << std::endl;
×
UNCOV
3996
            exit(1);
×
UNCOV
3997
        }
×
3998

3999
        // add cards from the decks to requirement/inventory
4000
        if (opt_do_optimization || opt_do_reorder)
313 ✔
4001
        {
4002
            if (opt_keep_commander) // TODO this does not work with multi deck mode
7 ✔
4003
            {
4004
                requirement.num_cards[your_deck->commander] = 1;
×
4005
            }
4006
            for (auto &&card_mark : your_deck->card_marks)
7 ✔
4007
            {
4008
                auto &&card = card_mark.first < 0 ? your_deck->commander : your_deck->cards[card_mark.first];
×
UNCOV
4009
                auto mark = card_mark.second;
×
UNCOV
4010
                if ((mark == '!') && ((card_mark.first >= 0) || !opt_keep_commander))
×
4011
                {
4012
                    requirement.num_cards[card] += 1;
×
4013
                }
4014
            }
4015
            if (opt_skip_unclaimed_decks)
7 ✔
4016
            {
4017
                // skip decks that can not be build
UNCOV
4018
                if (claim_cards_needed({your_deck->commander}))
×
UNCOV
4019
                    continue;
×
UNCOV
4020
                if (claim_cards_needed(your_deck->cards))
×
4021
                    continue;
×
4022
                if (your_deck->alpha_dominion && claim_cards_needed({your_deck->alpha_dominion}))
×
UNCOV
4023
                    continue;
×
4024
            }
4025
            else if (opt_do_optimization and use_owned_cards)
7 ✔
4026
            {
4027
                // Force to claim cards in your initial deck.
4028
                claim_cards({your_deck->commander});
7 ✔
4029
                claim_cards(your_deck->cards);
7 ✔
4030
                if (your_deck->alpha_dominion)
7 ✔
UNCOV
4031
                    claim_cards({your_deck->alpha_dominion});
×
4032
            }
4033

4034
            // shrink any oversized deck to maximum of 10 cards + commander
4035
            // NOTE: do this AFTER the call to claim_cards so that passing an initial deck of >10 cards
4036
            //       can be used as a "shortcut" for adding them to owned cards. Also this allows climb
4037
            //       to figure out which are the best 10, rather than restricting climb to the first 10.
4038
            if (your_deck->cards.size() > max_deck_len)
7 ✔
4039
            {
UNCOV
4040
                your_deck->shrink(max_deck_len);
×
4041
                if (debug_print >= 0)
×
4042
                {
4043
                    std::cerr << "WARNING: Too many cards in your deck. Trimmed.\n";
×
4044
                }
4045
            }
4046
        }
4047

4048
        your_decks.push_back(your_deck);
313 ✔
4049
        your_decks_factors.push_back(deck_parsed.second);
313 ✔
4050
    }
313 ✔
4051
    if (your_decks.size() == 0)
85 ✔
4052
    {
4053
        std::cerr << "No deck set. Probably due to 'strict-ownedcards' and a deck that is incompatible to the set 'ownedcards'." << std::endl;
×
UNCOV
4054
        exit(1);
×
4055
    }
4056
    target_score = opt_target_score.empty() ? max_possible_score[(size_t)optimization_mode] : boost::lexical_cast<long double>(opt_target_score);
85 ✔
4057

4058
    for (auto deck_parsed : enemy_deck_list_parsed)
398 ✔
4059
    {
4060
        Deck *enemy_deck{nullptr};
313 ✔
4061
        try
313 ✔
4062
        {
4063
            enemy_deck = find_deck(decks, all_cards, deck_parsed.first);
626 ✔
4064
        }
UNCOV
4065
        catch (const std::runtime_error &e)
×
4066
        {
4067
            std::cerr << "Error: Deck " << deck_parsed.first << ": " << e.what() << std::endl;
×
4068
            exit(1);
×
UNCOV
4069
        }
×
4070
        if (enemy_deck == nullptr)
313 ✔
4071
        {
UNCOV
4072
            std::cerr << "Error: Invalid defense deck name/hash " << deck_parsed.first << ".\n";
×
UNCOV
4073
            usage(argc, argv);
×
4074
            exit(1);
×
4075
        }
4076
        if (optimization_mode == OptimizationMode::notset)
313 ✔
4077
        {
4078
            if (enemy_deck->decktype == DeckType::raid)
85 ✔
4079
            {
UNCOV
4080
                optimization_mode = OptimizationMode::raid;
×
4081
            }
4082
            else if (enemy_deck->decktype == DeckType::campaign)
85 ✔
4083
            {
UNCOV
4084
                gamemode = surge;
×
4085
                optimization_mode = OptimizationMode::campaign;
×
4086
            }
4087
            else
4088
            {
4089
                optimization_mode = OptimizationMode::winrate;
85 ✔
4090
            }
4091
        }
4092
        enemy_deck->strategy = opt_enemy_strategy;
313 ✔
4093
        if (!opt_enemy_doms.empty())
313 ✔
4094
        {
UNCOV
4095
            try
×
4096
            {
UNCOV
4097
                enemy_deck->add_dominions(opt_enemy_doms + ",", true);
×
4098
            }
4099
            catch (const std::runtime_error &e)
×
4100
            {
4101
                std::cerr << "Error: edom " << opt_enemy_doms << ": " << e.what() << std::endl;
×
4102
                exit(1);
×
4103
            }
×
4104
        }
4105
        if (!opt_enemy_forts.empty())
313 ✔
4106
        {
UNCOV
4107
            try
×
4108
            {
UNCOV
4109
                if (!efpool)
×
UNCOV
4110
                    enemy_deck->add_forts(opt_enemy_forts + ",");
×
4111
                else
4112
                    enemy_deck->add_pool_forts(opt_enemy_forts + ",", efpool);
×
4113
            }
UNCOV
4114
            catch (const std::runtime_error &e)
×
4115
            {
UNCOV
4116
                std::cerr << "Error: efort " << opt_enemy_forts << ": " << e.what() << std::endl;
×
UNCOV
4117
                exit(1);
×
UNCOV
4118
            }
×
4119
        }
4120
        try
313 ✔
4121
        {
4122
            enemy_deck->set_given_hand(opt_enemy_hand);
313 ✔
4123
        }
4124
        catch (const std::runtime_error &e)
×
4125
        {
UNCOV
4126
            std::cerr << "Error: enemy:hand " << opt_enemy_hand << ": " << e.what() << std::endl;
×
UNCOV
4127
            exit(1);
×
UNCOV
4128
        }
×
4129
        enemy_decks.push_back(enemy_deck);
313 ✔
4130
        enemy_decks_factors.push_back(deck_parsed.second);
313 ✔
4131
    }
313 ✔
4132

4133
    std::vector<long double> factors((opt_multi_optimization ? 1 : your_decks_factors.size()) * enemy_decks_factors.size());
85 ✔
4134
    for (unsigned i = 0; i < factors.size(); ++i)
2,146 ✔
4135
    {
4136
        factors[i] = your_decks_factors[i / enemy_decks_factors.size()] * enemy_decks_factors[i % enemy_decks_factors.size()];
2,061 ✔
4137
    }
4138

4139
    if ((opt_do_optimization || opt_do_reorder) && (your_decks.size() != 1 && !opt_multi_optimization))
85 ✔
4140
    {
UNCOV
4141
        std::cerr << "Optimization only works with a single deck" << std::endl;
×
UNCOV
4142
        exit(1);
×
4143
    }
4144

4145
    if (debug_print >= 0)
85 ✔
4146
    {
4147
        for (unsigned i(0); i < your_decks.size(); ++i)
398 ✔
4148
        {
4149
            auto your_deck = your_decks[i];
313 ✔
4150
            std::cout << "Your Deck:" << your_decks_factors[i] << ": " << (debug_print > 0 ? your_deck->long_description() : your_deck->medium_description()) << std::endl;
626 ✔
4151
        }
4152
        for (unsigned bg_effect = PassiveBGE::no_bge; bg_effect < PassiveBGE::num_passive_bges; ++bg_effect)
2,380 ✔
4153
        {
4154
            auto bge_value = opt_bg_effects[0][bg_effect];
2,295 ✔
4155
            if (!bge_value)
2,295 ✔
4156
                continue;
2,260 ✔
4157
            std::cout << "Your BG Effect: " << passive_bge_names[bg_effect];
35 ✔
4158
            if (bge_value != -1)
35 ✔
4159
                std::cout << " " << bge_value;
35 ✔
4160
            std::cout << std::endl;
2,295 ✔
4161
        }
4162
        for (const auto &bg_skill : opt_bg_skills[0])
86 ✔
4163
        {
4164
            std::cout << "Your BG Skill: " << skill_description(all_cards, bg_skill) << std::endl;
1 ✔
4165
        }
4166

4167
        for (unsigned i(0); i < enemy_decks.size(); ++i)
398 ✔
4168
        {
4169
            auto enemy_deck = enemy_decks[i];
313 ✔
4170
            std::cout << "Enemy's Deck:" << enemy_decks_factors[i] << ": "
313 ✔
4171
                      << (debug_print > 0 ? enemy_deck->long_description() : enemy_deck->medium_description()) << std::endl;
626 ✔
4172
        }
4173
        for (unsigned bg_effect = PassiveBGE::no_bge; bg_effect < PassiveBGE::num_passive_bges; ++bg_effect)
2,380 ✔
4174
        {
4175
            auto bge_value = opt_bg_effects[1][bg_effect];
2,295 ✔
4176
            if (!bge_value)
2,295 ✔
4177
                continue;
2,260 ✔
4178
            std::cout << "Enemy's BG Effect: " << passive_bge_names[bg_effect];
35 ✔
4179
            if (bge_value != -1)
35 ✔
4180
                std::cout << " " << bge_value;
35 ✔
4181
            std::cout << std::endl;
2,295 ✔
4182
        }
4183
        for (const auto &bg_skill : opt_bg_skills[1])
86 ✔
4184
        {
4185
            std::cout << "Enemy's BG Skill: " << skill_description(all_cards, bg_skill) << std::endl;
1 ✔
4186
        }
4187
    }
4188
    if (enemy_decks.size() == 1)
85 ✔
4189
    {
4190
        auto enemy_deck = enemy_decks[0];
47 ✔
4191
        for (auto x_mult_ss : enemy_deck->effects)
47 ✔
4192
        {
4193
            if (debug_print >= 0)
×
4194
            {
4195
                std::cout << "Enemy's X-Mult BG Skill (effective X = round_up[X * " << enemy_deck->level << "]): "
×
UNCOV
4196
                          << skill_description(all_cards, x_mult_ss);
×
4197
                if (x_mult_ss.x)
×
4198
                {
4199
                    std::cout << " (eff. X = " << ceil(x_mult_ss.x * enemy_deck->level) << ")";
×
4200
                }
UNCOV
4201
                std::cout << std::endl;
×
4202
            }
UNCOV
4203
            opt_bg_skills[1].push_back({x_mult_ss.id,
×
UNCOV
4204
                                        (unsigned)ceil(x_mult_ss.x * enemy_deck->level),
×
4205
                                        x_mult_ss.y, x_mult_ss.n, x_mult_ss.c,
×
UNCOV
4206
                                        x_mult_ss.s, x_mult_ss.s2, x_mult_ss.all});
×
4207
        }
4208
    }
4209
    auto proc_decks = your_decks;
85 ✔
4210
    if (opt_multi_optimization)
85 ✔
4211
    { // only one deck at a time
4212
        proc_decks.erase(proc_decks.begin() + 1, proc_decks.end());
7 ✔
4213
    }
4214
    Process p(opt_num_threads, all_cards, decks, proc_decks, enemy_decks, factors, gamemode,
85 ✔
4215
#ifndef NQUEST
4216
              tuo::quest,
4217
#endif
4218
              opt_bg_effects[0], opt_bg_effects[1], opt_bg_skills[0], opt_bg_skills[1]);
85 ✔
4219

4220
    auto your_deck = your_decks[0];
85 ✔
4221

4222
    if (!opt_todo.empty())
85 ✔
4223
    {
4224
    auto op = opt_todo.back();
85 ✔
4225
    // for (auto op: opt_todo)
4226
    {
85 ✔
4227
        switch (std::get<2>(op))
85 ✔
4228
        {
4229
        case noop:
4230
            break;
4231
        case simulate:
78 ✔
4232
        {
78 ✔
4233
            EvaluatedResults results = {EvaluatedResults::first_type(enemy_decks.size() * your_decks.size()), 0};
78 ✔
4234
            results = p.evaluate(std::get<0>(op), results);
78 ✔
4235
            print_results(results, p.factors);
78 ✔
4236
            fr = std::make_pair(your_deck->clone(), compute_score(results, p.factors));
78 ✔
4237
            print_sim_card_values(fr.first, p, std::get<0>(op));
78 ✔
4238
            break;
78 ✔
4239
        }
78 ✔
UNCOV
4240
        case climb_forts:
×
UNCOV
4241
        {
×
UNCOV
4242
            fr = forts_climbing(std::get<0>(op), p);
×
UNCOV
4243
            break;
×
4244
        }
4245
        case climb:
3 ✔
4246
        {
3 ✔
4247
            // TODO check for your_decks.size()==1
4248
            fr = hill_climbing(std::get<0>(op), std::get<1>(op), your_decks, p, requirement
3 ✔
4249
#ifndef NQUEST
4250
                               ,
4251
                               tuo::quest
4252
#endif
4253
            );
3 ✔
4254
            break;
3 ✔
4255
        }
4256
        case anneal:
1 ✔
4257
        {
1 ✔
4258
            // TODO check for your_decks.size()==1
4259
            fr = simulated_annealing(std::get<0>(op), std::get<1>(op), your_decks, p, requirement
1 ✔
4260
#ifndef NQUEST
4261
                                     ,
4262
                                     tuo::quest
4263
#endif
4264
            );
1 ✔
4265
            break;
1 ✔
4266
        }
4267
        case genetic:
1 ✔
4268
        {
1 ✔
4269
            fr = genetic_algorithm(std::get<0>(op), std::get<1>(op), your_decks, p, requirement
1 ✔
4270
#ifndef NQUEST
4271
                                   ,
4272
                                   tuo::quest
4273
#endif
4274
            );
1 ✔
4275
            break;
1 ✔
4276
        }
4277

4278
        case beam:
2 ✔
4279
        {
2 ✔
4280
            fr = beam_climb(std::get<0>(op), std::get<1>(op), your_decks, p, requirement
2 ✔
4281
#ifndef NQUEST
4282
                            ,
4283
                            tuo::quest
4284
#endif
4285
            );
2 ✔
4286
            break;
2 ✔
4287
        }
UNCOV
4288
        case reorder:
×
UNCOV
4289
        {
×
4290
            // TODO multi deck mode for reorder
UNCOV
4291
            your_deck->strategy = DeckStrategy::ordered;
×
UNCOV
4292
            use_owned_cards = true;
×
UNCOV
4293
            use_top_level_card = false;
×
UNCOV
4294
            use_top_level_commander = false;
×
UNCOV
4295
            use_owned_dominions = false;
×
UNCOV
4296
            if (min_deck_len == 1 && max_deck_len == 10)
×
4297
            {
UNCOV
4298
                min_deck_len = max_deck_len = your_deck->cards.size();
×
4299
            }
UNCOV
4300
            fund = 0;
×
UNCOV
4301
            debug_print = -1;
×
UNCOV
4302
            owned_cards.clear();
×
UNCOV
4303
            claim_cards({your_deck->commander});
×
UNCOV
4304
            claim_cards(your_deck->cards);
×
UNCOV
4305
            std::vector<Deck *> single_deck = {your_deck};
×
UNCOV
4306
            fr = hill_climbing(std::get<0>(op), std::get<1>(op), single_deck, p, requirement
×
4307
#ifndef NQUEST
4308
                               ,
4309
                               tuo::quest
4310
#endif
UNCOV
4311
            );
×
UNCOV
4312
            break;
×
UNCOV
4313
        }
×
4314
            // fr=nllptr no return
UNCOV
4315
        case debug:
×
UNCOV
4316
        {
×
UNCOV
4317
            ++debug_print;
×
UNCOV
4318
            debug_str.clear();
×
UNCOV
4319
            EvaluatedResults results{EvaluatedResults::first_type(enemy_decks.size()), 0};
×
UNCOV
4320
            results = p.evaluate(1, results);
×
4321
            print_results(results, p.factors);
×
4322
            --debug_print;
×
4323
            break;
×
4324
        }
×
4325
            // fr=nllptr no return
UNCOV
4326
        case debuguntil:
×
UNCOV
4327
        {
×
UNCOV
4328
            ++debug_print;
×
UNCOV
4329
            ++debug_cached;
×
UNCOV
4330
            while (true)
×
4331
            {
UNCOV
4332
                debug_str.clear();
×
UNCOV
4333
                EvaluatedResults results{EvaluatedResults::first_type(enemy_decks.size()), 0};
×
UNCOV
4334
                results = p.evaluate(1, results);
×
UNCOV
4335
                auto score = compute_score(results, p.factors);
×
UNCOV
4336
                if (score.points >= std::get<0>(op) && score.points <= std::get<1>(op))
×
4337
                {
UNCOV
4338
                    std::cout << debug_str << std::flush;
×
UNCOV
4339
                    print_results(results, p.factors);
×
UNCOV
4340
                    break;
×
4341
                }
UNCOV
4342
            }
×
UNCOV
4343
            --debug_cached;
×
UNCOV
4344
            --debug_print;
×
UNCOV
4345
            break;
×
4346
        }
4347
        }
4348
    }
4349
    write_db(prefix);
255 ✔
4350
    }
4351
    else {
UNCOV
4352
        std::cout << "No operation specified" << std::endl;
×
4353
    }
4354
    return fr;
170 ✔
4355
}
935 ✔
4356

UNCOV
4357
std::vector<const char *> strlist(std::vector<std::string> &input)
×
4358
{
UNCOV
4359
    std::vector<const char *> result;
×
4360

4361
    // remember the nullptr terminator
UNCOV
4362
    result.reserve(input.size() + 1);
×
4363

UNCOV
4364
    for (auto &i : input)
×
UNCOV
4365
        result.push_back(i.data());
×
UNCOV
4366
    result.push_back(nullptr);
×
UNCOV
4367
    return result;
×
UNCOV
4368
}
×
4369

4370
DeckResults start(int argc, const char **argv)
×
4371
{
4372
    std::vector<std::string> result_decks;
×
4373
    DeckResults drc;
×
4374
    bool first = true;
×
4375
    result_decks.push_back(argv[1]);
×
4376
    for (int j = 0; j < argc; ++j)
×
4377
    {
UNCOV
4378
        int add_j_inc = 0;
×
4379
        bool do_it = false;
×
UNCOV
4380
        std::stringstream param_file;
×
4381
        if (strcmp(argv[j], "boost-ml") == 0)
×
4382
        {
4383
            do_it = true;
×
4384
            add_j_inc = -1;
×
4385
            param_file << "noop" << std::endl
×
4386
                       << "only-ml" << std::endl
×
4387
                       << "deck @1@ no-ml" << std::endl;
×
4388
        }
UNCOV
4389
        if (strcmp(argv[j], "-p") == 0 || strcmp(argv[j], "params") == 0)
×
4390
        {
UNCOV
4391
            if (j + 1 < argc)
×
4392
            {
4393
                std::ifstream in_param_file(argv[j + 1]);
×
4394
                if (in_param_file.good())
×
4395
                {
4396
                    param_file << in_param_file.rdbuf();
×
4397
                    in_param_file.close();
×
4398
                    do_it = true;
4399
                }
4400
                else
4401
                {
4402
                    std::cout << "Error loading params file " << argv[j + 1] << std::endl;
×
4403
                }
4404
            }
×
4405
            else
4406
            {
4407
                std::cout << "-p/params needs a file as parameter" << std::endl;
×
4408
            }
4409
        }
4410
        if (do_it)
×
4411
        {
UNCOV
4412
            {
×
4413
                param_file.clear();
×
4414
                param_file.seekg(0, std::ios::beg);
×
4415
                // param_file to istream
4416
                std::cout << "Loading params file " << argv[j + 1] << std::endl;
×
4417
                std::string line, tmp, first_line = "";
×
UNCOV
4418
                std::vector<std::string> first_split, cur_split;
×
4419
                // first count parameters in file
4420
                while (param_file && !param_file.eof())
×
4421
                {
UNCOV
4422
                    std::getline(param_file, line);
×
4423
                    if (is_line_empty_or_commented(line))
×
4424
                        continue;
×
4425
                    for (int z = 0; z < argc - j - 1; ++z)
×
4426
                    {
UNCOV
4427
                        std::string rep("$" + std::to_string(z) + "$");
×
UNCOV
4428
                        if (line.find(rep) != std::string::npos && z > add_j_inc)
×
UNCOV
4429
                            add_j_inc = z;
×
UNCOV
4430
                    }
×
4431
                }
UNCOV
4432
                param_file.clear();
×
4433
                param_file.seekg(0, std::ios::beg);
×
UNCOV
4434
                while (param_file && !param_file.eof())
×
4435
                {
UNCOV
4436
                    std::getline(param_file, line);
×
UNCOV
4437
                    if (is_line_empty_or_commented(line))
×
4438
                        continue;
×
4439
                    // std::cout << line << std::endl;
4440
                    if (first_line == "")
×
4441
                    {
UNCOV
4442
                        first_line = line;
×
4443
                        std::istringstream ss(first_line);
×
UNCOV
4444
                        while (ss >> boost::io::quoted(tmp))
×
4445
                        {
4446
                            for (unsigned z = 0; z < result_decks.size(); ++z)
×
4447
                            {
4448
                                boost::replace_all(tmp, "@" + std::to_string(z) + "@", result_decks[z]);
×
4449
                            }
UNCOV
4450
                            for (int z = 0; z < argc - j - 1; ++z)
×
4451
                            {
UNCOV
4452
                                std::string rep("$" + std::to_string(z) + "$");
×
4453
                                boost::replace_all(tmp, rep, std::string(argv[j + 1 + z]));
×
4454
                            }
×
4455
                            first_split.push_back(tmp);
×
4456
                        }
4457
                    }
×
4458
                    else
4459
                    {
4460
                        cur_split = first_split;
×
4461
                        std::istringstream ss(line);
×
4462
                        while (ss >> boost::io::quoted(tmp))
×
4463
                        {
4464
                            for (unsigned z = 0; z < result_decks.size(); ++z)
×
4465
                            {
4466
                                boost::replace_all(tmp, "@" + std::to_string(z) + "@", result_decks[z]);
×
4467
                            }
4468
                            for (int z = 0; z < argc - j - 1; ++z)
×
4469
                            {
4470
                                std::string rep("$" + std::to_string(z) + "$");
×
UNCOV
4471
                                boost::replace_all(tmp, rep, std::string(argv[j + 1 + z]));
×
4472
                            }
×
UNCOV
4473
                            cur_split.push_back(tmp);
×
4474
                        }
4475
                        for (int i = 0; i < argc; ++i)
×
4476
                        {
4477
                            if (i < j)
×
4478
                                cur_split.insert(cur_split.begin() + i, std::string(argv[i]));
×
UNCOV
4479
                            if (i > j + 1 + add_j_inc)
×
UNCOV
4480
                                cur_split.push_back(std::string(argv[i]));
×
4481
                        }
UNCOV
4482
                        if (!first)
×
4483
                        {
4484
                            // replace passed deck with most recent deck
4485
                            cur_split.erase(cur_split.begin() + 1);
×
UNCOV
4486
                            cur_split.insert(cur_split.begin() + 1, result_decks[result_decks.size() - 1]);
×
4487
                        }
4488
                        first = false;
×
4489

UNCOV
4490
                        std::cout << std::endl
×
4491
                                  << "///////////////" << std::endl;
×
4492
                        // std::cout << result_decks[result_decks.size()-1] <<std::endl;
4493
                        int k = 0;
×
4494
                        for (auto &str : cur_split)
×
4495
                        {
UNCOV
4496
                            if (k > 0)
×
4497
                                std::cout << "\"";
×
4498
                            std::cout << str;
×
4499
                            if (k > 0)
×
UNCOV
4500
                                std::cout << "\"";
×
4501
                            std::cout << ' ';
×
UNCOV
4502
                            k++;
×
4503
                        }
4504
                        std::cout << std::endl;
×
4505
                        std::cout << "///////////////" << std::endl
×
4506
                                  << std::endl;
×
4507

4508
                        drc = start(cur_split.size(), strlist(cur_split).data());
×
4509

4510
                        // result to string
4511
                        std::stringstream oss;
×
UNCOV
4512
                        if (drc.first->commander)
×
4513
                            oss << drc.first->commander->m_name << ", ";
×
4514
                        if (drc.first->alpha_dominion)
×
4515
                            oss << drc.first->alpha_dominion->m_name << ", ";
×
UNCOV
4516
                        print_cards_inline(drc.first->cards, oss, drc.first);
×
4517
                        std::string decks(oss.str());
×
4518
                        std::replace(decks.begin(), decks.end(), '\n', ' ');
×
4519
                        result_decks.push_back(decks);
×
4520

4521
                        // print_cards_inline(drc.first->cards,std::cout);
UNCOV
4522
                    }
×
4523
                }
4524
                return drc;
×
4525
            }
×
4526
        }
4527
        else
4528
        {
4529
            // return run(argc,argv);
4530
        }
4531
    }
×
UNCOV
4532
    init();
×
4533
    auto rtrn = run(argc, argv);
×
4534
    return rtrn;
×
4535
}
×
4536

4537
#if !defined(TEST)
4538
int main(int argc, const char **argv)
4539
{
4540
#ifndef NTIMER
4541
    boost::timer::auto_cpu_timer t;
4542
#endif
4543
    if (argc == 2 && strcmp(argv[1], "-version") == 0)
4544
    {
4545
        std::cout << "Tyrant Unleashed Optimizer " << TYRANT_OPTIMIZER_VERSION << std::endl;
4546
        return 0;
4547
    }
4548
    if (argc < 2)
4549
    {
4550
        usage(argc, argv);
4551
        return 255;
4552
    }
4553
    start(argc, argv);
4554
    return 0;
4555
}
4556
#endif
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc