summaryrefslogtreecommitdiff
path: root/src/SSVOpenHexagon/Core/Replay.cpp
blob: 809ba47520d35182b2ab261178cc0ac1b9ebce77 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
// Copyright (c) 2013-2020 Vittorio Romeo
// License: Academic Free License ("AFL") v. 3.0
// AFL License page: https://opensource.org/licenses/AFL-3.0

#include "SSVOpenHexagon/Core/Replay.hpp"

#include "SSVOpenHexagon/Global/Assert.hpp"
#include "SSVOpenHexagon/Utils/Concat.hpp"

#include <SSVUtils/Core/Common/LikelyUnlikely.hpp>

#include <SFML/Network/Packet.hpp>

#include <zlib.h>

#include <fstream>
#include <iostream>
#include <sstream>
#include <type_traits>
#include <utility>

namespace hg {

[[gnu::cold]] static void printTryFailure(const char* code)
{
    ::std::cerr << "Failed [de]serialization operation '" << code << "'\n";
}

#define SSVOH_TRY(...)                      \
    do                                      \
    {                                       \
        __VA_ARGS__;                        \
                                            \
        if(SSVU_UNLIKELY(!result._success)) \
        {                                   \
            printTryFailure(#__VA_ARGS__);  \
            return result;                  \
        }                                   \
    }                                       \
    while(false)

static auto make_write(serialization_result& result, std::byte*& buffer,
    const std::byte* const buffer_end)
{
    return [&result, &buffer, buffer_end](const auto& datum)
    {
        if(buffer + sizeof(datum) > buffer_end)
        {
            result._success = false;
            return;
        }

        std::memcpy(buffer, &datum, sizeof(datum));
        buffer += sizeof(datum);
        result._written_bytes += sizeof(datum);
    };
}

static auto make_read(deserialization_result& result, const std::byte*& buffer,
    const std::byte* const buffer_end)
{
    return [&result, &buffer, buffer_end](auto& target)
    {
        if(buffer + sizeof(target) > buffer_end)
        {
            result._success = false;
            return;
        }

        std::memcpy(&target, buffer, sizeof(target));
        buffer += sizeof(target);
        result._read_bytes += sizeof(target);
    };
}

void replay_data::record_input(const bool left, const bool right,
    const bool swap, const bool focus) noexcept
{
    input_bitset& ib = _inputs.emplace_back();
    ib[static_cast<unsigned int>(input_bit::left)] = left;
    ib[static_cast<unsigned int>(input_bit::right)] = right;
    ib[static_cast<unsigned int>(input_bit::swap)] = swap;
    ib[static_cast<unsigned int>(input_bit::focus)] = focus;
}

[[nodiscard]] input_bitset replay_data::at(
    const std::size_t index) const noexcept
{
    SSVOH_ASSERT(index < size());
    return _inputs[index];
}

[[nodiscard]] std::size_t replay_data::size() const noexcept
{
    return _inputs.size();
}

[[nodiscard]] bool replay_data::operator==(
    const replay_data& rhs) const noexcept
{
    return _inputs == rhs._inputs;
}

[[nodiscard]] bool replay_data::operator!=(
    const replay_data& rhs) const noexcept
{
    return !(*this == rhs);
}

[[nodiscard]] serialization_result replay_data::serialize(
    std::byte* buffer, const std::size_t buffer_size) const
{
    return serialize(buffer, buffer + buffer_size);
}

[[nodiscard]] deserialization_result replay_data::deserialize(
    const std::byte* buffer, const std::size_t buffer_size)
{
    return deserialize(buffer, buffer + buffer_size);
}

[[nodiscard]] serialization_result replay_data::serialize(
    std::byte* buffer, const std::byte* const buffer_end) const
{
    serialization_result result;
    const auto write = make_write(result, buffer, buffer_end);

    const std::size_t n_inputs = _inputs.size();
    SSVOH_TRY(write(n_inputs));

    for(const input_bitset& ib : _inputs)
    {
        const std::uint8_t ib_byte = ib.to_ulong();
        SSVOH_TRY(write(ib_byte));
    }

    return result;
}

[[nodiscard]] deserialization_result replay_data::deserialize(
    const std::byte* buffer, const std::byte* const buffer_end)
{
    deserialization_result result;
    const auto read = make_read(result, buffer, buffer_end);

    std::size_t n_inputs;
    SSVOH_TRY(read(n_inputs));

    _inputs.resize(n_inputs);

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
    for(std::size_t i = 0; i < n_inputs; ++i)
#pragma GCC diagnostic pop
    {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
        std::uint8_t ib_byte;
        SSVOH_TRY(read(ib_byte));
#pragma GCC diagnostic pop

        _inputs[i] = input_bitset{static_cast<unsigned long>(ib_byte)};
    }

    return result;
}

replay_player::replay_player(const replay_data& rd) noexcept
    : _replay_data{rd}, _current_index{0}
{}

[[nodiscard]] input_bitset
replay_player::get_current_and_move_forward() noexcept
{
    if(_replay_data.size() <= _current_index)
    {
        return {};
    }

    return _replay_data.at(_current_index++);
}

[[nodiscard]] bool replay_player::done() const noexcept
{
    return _current_index == _replay_data.size();
}

void replay_player::reset() noexcept
{
    _current_index = 0;
}


[[nodiscard]] bool replay_file::operator==(
    const replay_file& rhs) const noexcept
{
    return _version == rhs._version &&                 //
           _player_name == rhs._player_name &&         //
           _seed == rhs._seed &&                       //
           _data == rhs._data &&                       //
           _pack_id == rhs._pack_id &&                 //
           _level_id == rhs._level_id &&               //
           _first_play == rhs._first_play &&           //
           _difficulty_mult == rhs._difficulty_mult && //
           _played_score == rhs._played_score;
}

[[nodiscard]] bool replay_file::operator!=(
    const replay_file& rhs) const noexcept
{
    return !(*this == rhs);
}

[[nodiscard]] serialization_result replay_file::serialize(
    std::byte* buffer, const std::size_t buffer_size) const
{
    return serialize(buffer, buffer + buffer_size);
}

[[nodiscard]] deserialization_result replay_file::deserialize(
    const std::byte* buffer, const std::size_t buffer_size)
{
    return deserialize(buffer, buffer + buffer_size);
}

[[nodiscard]] serialization_result replay_file::serialize(
    std::byte* buffer, const std::byte* const buffer_end) const
{
    serialization_result result;
    const auto write = make_write(result, buffer, buffer_end);

    const auto write_str = [&](const std::string& s)
    {
        SSVOH_TRY(write(static_cast<std::uint32_t>(s.size())));

        for(const char c : s)
        {
            SSVOH_TRY(write(c));
        }

        return result;
    };

    SSVOH_TRY(write(_version));
    SSVOH_TRY(write_str(_player_name));
    SSVOH_TRY(write(_seed));

    const serialization_result data_result =
        _data.serialize(buffer, buffer_end);

    if(!data_result._success)
    {
        result._success = false;
        return result;
    }

    buffer += data_result._written_bytes;
    result._written_bytes += data_result._written_bytes;

    SSVOH_TRY(write_str(_pack_id));
    SSVOH_TRY(write_str(_level_id));
    SSVOH_TRY(write(_first_play));
    SSVOH_TRY(write(_difficulty_mult));
    SSVOH_TRY(write(_played_score));

    return result;
}

[[nodiscard]] deserialization_result replay_file::deserialize(
    const std::byte* buffer, const std::byte* const buffer_end)
{
    deserialization_result result;
    const auto read = make_read(result, buffer, buffer_end);

    const auto read_str = [&](std::string& s)
    {
        std::uint32_t s_size;
        SSVOH_TRY(read(s_size));

        s.resize(s_size);

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
        for(std::uint32_t i = 0; i < s_size; ++i)
        {
            char c;
            SSVOH_TRY(read(c));

            s[i] = c;
        }
#pragma GCC diagnostic pop

        return result;
    };

    SSVOH_TRY(read(_version));
    SSVOH_TRY(read_str(_player_name));
    SSVOH_TRY(read(_seed));

    const deserialization_result data_result =
        _data.deserialize(buffer, buffer_end);

    if(!data_result._success)
    {
        result._success = false;
        return result;
    }

    buffer += data_result._read_bytes;
    result._read_bytes += data_result._read_bytes;

    SSVOH_TRY(read_str(_pack_id));
    SSVOH_TRY(read_str(_level_id));
    SSVOH_TRY(read(_first_play));
    SSVOH_TRY(read(_difficulty_mult));
    SSVOH_TRY(read(_played_score));

    return result;
}

static constexpr std::size_t buf_size{2097152}; // 2MB

[[nodiscard]] static std::byte* get_static_buf()
{
    thread_local std::byte buf[buf_size];
    return buf;
}

[[nodiscard]] bool replay_file::serialize_to_file(
    const std::filesystem::path& p) const
{
    std::byte* buf = get_static_buf();

    const serialization_result sr = serialize(buf, buf_size);
    if(!static_cast<bool>(sr))
    {
        return false;
    }

    std::ofstream os(p, std::ios::binary | std::ios::out);
    os.write(reinterpret_cast<const char*>(buf), sr.written_bytes());
    os.flush();

    return static_cast<bool>(os);
}

[[nodiscard]] bool replay_file::deserialize_from_file(
    const std::filesystem::path& p)
{
    std::ifstream is(p, std::ios::binary | std::ios::in);

    is.seekg(0, std::ios::end);
    const std::size_t bytes_to_read = is.tellg();
    is.seekg(0, std::ios::beg);

    std::byte* buf = get_static_buf();

    is.read(reinterpret_cast<char*>(buf), bytes_to_read);

    if(!static_cast<bool>(is))
    {
        return false;
    }

    const deserialization_result dr = deserialize(buf, bytes_to_read);
    return static_cast<bool>(dr);
}

[[nodiscard]] bool replay_file::serialize_to_packet(sf::Packet& p) const
{
    std::byte* buf = get_static_buf();

    const serialization_result sr = serialize(buf, buf_size);
    if(!static_cast<bool>(sr))
    {
        return false;
    }

    const sf::Uint64 written_bytes = sr.written_bytes();

    p << written_bytes;
    p.append(static_cast<const void*>(buf), written_bytes);
    return true;
}

[[nodiscard]] bool replay_file::deserialize_from_packet(sf::Packet& p)
{
    static_assert(sizeof(sf::Uint8) == sizeof(std::byte));
    static_assert(alignof(sf::Uint8) == alignof(std::byte));

    sf::Uint64 bytes_to_read;
    if(!(p >> bytes_to_read))
    {
        return false;
    }

    std::byte* buf = get_static_buf();

    for(sf::Uint64 i = 0; i < bytes_to_read; ++i)
    {
        if(!(p >> reinterpret_cast<sf::Uint8&>(buf[i])))
        {
            return false;
        }
    }

    const deserialization_result dr = deserialize(buf, bytes_to_read);
    return static_cast<bool>(dr);
}


[[nodiscard]] std::string replay_file::create_filename() const
{
    return Utils::concat(_version, '_', _player_name, '_', _pack_id, '_',
        _level_id, '_', _difficulty_mult, '_', _played_score, ".ohreplay");
}

[[nodiscard]] bool compressed_replay_file::serialize_to_file(
    const std::filesystem::path& p) const
{
    std::ofstream os(p, std::ios::binary | std::ios::out);
    os.write(_data.data(), _data.size());
    os.flush();

    return static_cast<bool>(os);
}

[[nodiscard]] bool compressed_replay_file::deserialize_from_file(
    const std::filesystem::path& p)
{
    std::ifstream is(p, std::ios::binary | std::ios::in);

    is.seekg(0, std::ios::end);
    const std::size_t bytes_to_read = is.tellg();
    is.seekg(0, std::ios::beg);

    _data.resize(bytes_to_read);
    is.read(_data.data(), bytes_to_read);

    return static_cast<bool>(is);
}

[[nodiscard]] bool compressed_replay_file::serialize_to_packet(
    sf::Packet& p) const
{
    p << static_cast<sf::Uint64>(_data.size());
    p.append(static_cast<const void*>(_data.data()), _data.size());
    return true;
}

[[nodiscard]] bool compressed_replay_file::deserialize_from_packet(
    sf::Packet& p)
{
    static_assert(sizeof(sf::Uint8) == sizeof(char));
    static_assert(alignof(sf::Uint8) == alignof(char));

    sf::Uint64 bytes_to_read;
    if(!(p >> bytes_to_read))
    {
        return false;
    }

    _data.resize(bytes_to_read);

    for(sf::Uint64 i = 0; i < bytes_to_read; ++i)
    {
        if(!(p >> reinterpret_cast<sf::Uint8&>(_data[i])))
        {
            return false;
        }
    }

    return true;
}

[[nodiscard]] static std::byte* get_static_compression_buf()
{
    thread_local std::byte buf[buf_size];
    return buf;
}

[[nodiscard]] std::optional<compressed_replay_file> compress_replay_file(
    const replay_file& rf)
{
    std::byte* buf = get_static_buf();

    const serialization_result sr = rf.serialize(buf, buf_size);
    if(!static_cast<bool>(sr))
    {
        return std::nullopt;
    }

    std::byte* compression_buf = get_static_compression_buf();

    uLongf in_out_dest_len = buf_size;
    const int rc = compress2(reinterpret_cast<Bytef*>(compression_buf),
        &in_out_dest_len, reinterpret_cast<const Bytef*>(buf),
        sr.written_bytes(), Z_BEST_COMPRESSION);

    if(rc != Z_OK)
    {
        std::cerr << "Failed compression of replay file, error code: '" << rc
                  << "'\n";

        return std::nullopt;
    }

    compressed_replay_file result;
    result._data.resize(in_out_dest_len);

    std::memcpy(static_cast<void*>(result._data.data()),
        static_cast<const void*>(compression_buf), result._data.size());

    return {std::move(result)};
}

[[nodiscard]] std::optional<replay_file> decompress_replay_file(
    const compressed_replay_file& crf)
{
    std::byte* buf = get_static_buf();

    uLongf in_out_dest_len = buf_size;
    const int rc = uncompress(reinterpret_cast<Bytef*>(buf), &in_out_dest_len,
        reinterpret_cast<const Bytef*>(crf._data.data()), crf._data.size());

    if(rc != Z_OK)
    {
        std::cerr << "Failed compression of replay file, error code: '" << rc
                  << "'\n";

        return std::nullopt;
    }

    replay_file result;

    const deserialization_result dr = result.deserialize(buf, in_out_dest_len);
    if(!static_cast<bool>(dr))
    {
        return std::nullopt;
    }

    return {std::move(result)};
}

} // namespace hg