18
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-12-03 11:15:23 +01:00
Files
maszyna/world/worldlogiccache.cpp
maj00r 4657928af2 feat(world): the statements of the logic tape replayed one by one, in another order than the file's, for the check of D4
Toward loading the logic by regions (docs/world-format-eu07.md, section 13, D4). The statement table keeps the
state of the tape at the start of each statement, the tape reader can move to a statement and read only to its
end (parser_tape::reader::seek, with the names of all the files of the tape), and the logic cache gives the
table back. With EU07_WORLD_REPLAY_ORDER set, a scenery replayed from its cache goes statement by statement,
each from its place on the tape with the transformations it was read with: "file" in the order of the file,
"regions" the statements of the whole package ahead of the regions, "regions-first" the regions first. A check
for the developers; without the variable the tape plays through as before.

The loop of deserialize_continue gives its dispatch to deserialize_statement(), and the transformations go
through transformations_of() and restore_transformations().

Checked in the game (--test 120 s, seed 1, world.binary 1):
- "file": the physics logs of td.scn and Glinojeck.scn the same bit for bit as from the files, so the moves on
  the tape and the restored transformations give the very same scenery;
- "regions-first": the same bit for bit too, for both; the error logs hold the same lines in another order (the
  models load in another order);
- "regions": td.scn ends up without vehicles, its trainsets read before the tracks they stand on. The first
  thing D4 has to settle: the statements of the whole package that refer to the regions go after them.
2026-12-03 00:56:49 +01:00

345 lines
12 KiB
C++

/*
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
*/
#include "stdafx.h"
#include "world/worldlogiccache.h"
#include <algorithm>
#include <array>
#include <bit>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include "scene/regionfile.h"
namespace world_logic_cache {
namespace {
// the bytes of a number, little-endian, for the hash
std::array<char, 8> bytes_of(std::uint64_t const Value) {
std::array<char, 8> bytes{};
for (std::size_t k = 0; k < bytes.size(); ++k)
bytes[k] = static_cast<char>((Value >> (8 * k)) & 0xFFu);
return bytes;
}
std::uint64_t mix(std::uint64_t const Hash, std::uint64_t const Value) {
auto const bytes{bytes_of(Value)};
return fnv1a(std::string_view{bytes.data(), bytes.size()}, Hash);
}
// the size and the time of the last change of the file; all ones when it isn't there
std::pair<std::uint64_t, std::uint64_t> file_state(std::string const &Name) {
std::error_code error;
std::filesystem::path const path{Name};
auto const size{std::filesystem::file_size(path, error)};
if (error)
return {~std::uint64_t{0}, ~std::uint64_t{0}};
auto const time{std::filesystem::last_write_time(path, error)};
if (error)
return {size, ~std::uint64_t{0}};
return {size, static_cast<std::uint64_t>(time.time_since_epoch().count())};
}
} // namespace
std::uint64_t statement_region(double const X, double const Z) {
auto const tile{world_geometry::plane_tile_at({world_geometry::micrometres(X), 0, world_geometry::micrometres(Z)}, world_geometry::logic_region_level)};
return tile.raw();
}
namespace {
void put_varint(std::string &Output, std::uint64_t Value) {
while (Value >= 0x80) {
Output.push_back(static_cast<char>((Value & 0x7F) | 0x80));
Value >>= 7;
}
Output.push_back(static_cast<char>(Value));
}
bool get_varint(std::string_view const Bytes, std::size_t &Position, std::uint64_t &Value) {
Value = 0;
for (int shift = 0; shift < 64; shift += 7) {
if (Position >= Bytes.size())
return false;
auto const byte{static_cast<std::uint8_t>(Bytes[Position++])};
Value |= static_cast<std::uint64_t>(byte & 0x7F) << shift;
if ((byte & 0x80) == 0)
return true;
}
return false;
}
void put_bits(std::string &Output, double const Value) {
put_varint(Output, std::bit_cast<std::uint64_t>(Value));
}
void put_bits(std::string &Output, float const Value) {
put_varint(Output, std::bit_cast<std::uint32_t>(Value));
}
bool get_bits(std::string_view const Bytes, std::size_t &Position, double &Value) {
std::uint64_t raw{0};
if (!get_varint(Bytes, Position, raw))
return false;
Value = std::bit_cast<double>(raw);
return true;
}
bool get_bits(std::string_view const Bytes, std::size_t &Position, float &Value) {
std::uint64_t raw{0};
if (!get_varint(Bytes, Position, raw) || raw > 0xFFFF'FFFFULL)
return false;
Value = std::bit_cast<float>(static_cast<std::uint32_t>(raw));
return true;
}
void put_context(std::string &Output, context const &Context) {
Output.push_back(static_cast<char>((Context.has_offset ? 1 : 0) | (Context.has_scale ? 2 : 0)));
put_bits(Output, Context.offset_x);
put_bits(Output, Context.offset_y);
put_bits(Output, Context.offset_z);
put_bits(Output, Context.scale_x);
put_bits(Output, Context.scale_y);
put_bits(Output, Context.scale_z);
put_bits(Output, Context.rotation_x);
put_bits(Output, Context.rotation_y);
put_bits(Output, Context.rotation_z);
}
bool get_context(std::string_view const Bytes, std::size_t &Position, context &Context) {
if (Position >= Bytes.size())
return false;
auto const flags{static_cast<std::uint8_t>(Bytes[Position++])};
if (flags > 3)
return false;
Context.has_offset = (flags & 1) != 0;
Context.has_scale = (flags & 2) != 0;
return get_bits(Bytes, Position, Context.offset_x) && get_bits(Bytes, Position, Context.offset_y) && get_bits(Bytes, Position, Context.offset_z)
&& get_bits(Bytes, Position, Context.scale_x) && get_bits(Bytes, Position, Context.scale_y) && get_bits(Bytes, Position, Context.scale_z)
&& get_bits(Bytes, Position, Context.rotation_x) && get_bits(Bytes, Position, Context.rotation_y) && get_bits(Bytes, Position, Context.rotation_z);
}
std::uint64_t zigzag(std::int64_t const Value) {
return (static_cast<std::uint64_t>(Value) << 1) ^ static_cast<std::uint64_t>(Value >> 63);
}
std::int64_t unzigzag(std::uint64_t const Raw) {
return static_cast<std::int64_t>(Raw >> 1) ^ -static_cast<std::int64_t>(Raw & 1);
}
void put_tape_state(std::string &Output, parser_tape::state const &State) {
put_varint(Output, State.file);
put_varint(Output, State.line);
put_varint(Output, zigzag(State.line_main));
put_varint(Output, zigzag(State.begin));
put_varint(Output, zigzag(State.end));
Output.push_back(State.layer_file ? 1 : 0);
}
bool get_tape_state(std::string_view const Bytes, std::size_t &Position, parser_tape::state &State) {
std::uint64_t file{0};
std::uint64_t line{0};
std::uint64_t main{0};
std::uint64_t begin{0};
std::uint64_t end{0};
if (!get_varint(Bytes, Position, file) || !get_varint(Bytes, Position, line) || !get_varint(Bytes, Position, main) || !get_varint(Bytes, Position, begin)
|| !get_varint(Bytes, Position, end) || Position >= Bytes.size() || file > 0xFFFF'FFFFULL)
return false;
State.file = static_cast<std::uint32_t>(file);
State.line = static_cast<std::size_t>(line);
State.line_main = static_cast<int>(unzigzag(main));
State.begin = static_cast<std::streamoff>(unzigzag(begin));
State.end = static_cast<std::streamoff>(unzigzag(end));
State.layer_file = Bytes[Position++] != 0;
return true;
}
bool get_statement(std::string_view const Bytes, std::size_t &Position, std::uint64_t &Offset, std::size_t const Contexts, statement &Item) {
std::uint64_t delta{0};
std::uint64_t index{0};
if (!get_varint(Bytes, Position, delta) || !get_varint(Bytes, Position, Item.region) || !get_varint(Bytes, Position, index) || index >= Contexts)
return false;
Offset += delta;
Item.offset = Offset;
Item.context = static_cast<std::uint32_t>(index);
return get_tape_state(Bytes, Position, Item.start);
}
} // namespace
std::uint32_t statement_table::context_index(context const &Context) {
if (contexts.empty() || !(contexts.back() == Context))
contexts.push_back(Context);
return static_cast<std::uint32_t>(contexts.size() - 1);
}
std::string encode_statements(statement_table const &Table) {
std::string bytes;
put_varint(bytes, Table.contexts.size());
for (auto const &item : Table.contexts)
put_context(bytes, item);
put_varint(bytes, Table.statements.size());
std::uint64_t previous{0};
for (auto const &item : Table.statements) {
put_varint(bytes, item.offset - previous);
put_varint(bytes, item.region);
put_varint(bytes, item.context);
put_tape_state(bytes, item.start);
previous = item.offset;
}
return bytes;
}
bool decode_statements(std::string_view const Bytes, statement_table &Table) {
std::size_t position{0};
std::uint64_t count{0};
if (!get_varint(Bytes, position, count) || count > Bytes.size())
return false;
statement_table result;
result.contexts.resize(static_cast<std::size_t>(count));
for (auto &item : result.contexts)
if (!get_context(Bytes, position, item))
return false;
if (!get_varint(Bytes, position, count) || count > Bytes.size())
return false;
result.statements.resize(static_cast<std::size_t>(count));
std::uint64_t offset{0};
for (auto &item : result.statements)
if (!get_statement(Bytes, position, offset, result.contexts.size(), item))
return false;
if (position != Bytes.size())
return false;
Table = std::move(result);
return true;
}
std::string file_name(std::string const &Sceneryfolder, std::string const &Scenariofile) {
auto name{Scenariofile};
auto const marks{name.find_first_not_of('$')};
name.erase(0, std::min(marks, name.size()));
if (auto const dot{name.rfind('.')}; dot != std::string::npos && name.find_first_of("/\\", dot) == std::string::npos)
name.erase(dot);
return Sceneryfolder + name + ".logic.eu07";
}
std::uint64_t fnv1a(std::string_view const Bytes, std::uint64_t Hash) {
for (auto const byte : Bytes) {
Hash ^= static_cast<std::uint64_t>(static_cast<unsigned char>(byte));
Hash *= 0x0000'0100'0000'01B3ull;
}
return Hash;
}
std::uint64_t engine_hash(std::string_view const Version) {
return fnv1a(Version);
}
std::uint64_t source_hash(std::vector<std::string> const &Files, load_settings const &Settings) {
auto hash{fnv1a("eu07 logic cache")};
for (auto const &name : Files) {
if (name.empty())
continue;
hash = mix(fnv1a(name, hash), name.size());
auto const [size, time]{file_state(name)};
hash = mix(mix(hash, size), time);
}
hash = mix(hash, Settings.load_traction ? 1 : 0);
hash = mix(hash, Settings.binary_terrain ? 1 : 0);
hash = mix(fnv1a(Settings.prepend, hash), Settings.prepend.size());
hash = mix(fnv1a(Settings.trainset_overrides, hash), Settings.trainset_overrides.size());
return hash;
}
std::string write(std::string const &Filename, std::string const &Tape, std::vector<std::string> const &Files, std::uint64_t const Engine, load_settings const &Settings, statement_table const &Statements) {
auto const &text{Tape};
world_cache::file_contents contents;
contents.header.body = world_geometry::body::plane();
contents.header.layer = world_cache::layer_kind::logic;
contents.header.tile_level = world_geometry::logic_region_level;
contents.header.engine_hash = Engine;
contents.header.source_hash = source_hash(Files, Settings);
for (std::size_t start = 0; start < text.size(); start += tape_part_size) {
auto const length{std::min(tape_part_size, text.size() - start)};
world_cache::package_block block;
block.tag = tape_tag;
block.data.resize(length);
std::memcpy(block.data.data(), text.data() + start, length);
contents.package.push_back(std::move(block));
}
if (!Statements.statements.empty()) {
auto const table{encode_statements(Statements)};
world_cache::package_block block;
block.tag = statements_tag;
block.data.resize(table.size());
std::memcpy(block.data.data(), table.data(), table.size());
contents.package.push_back(std::move(block));
}
// a failure throws, so the temporary file is removed rather than put in place
return scene::region_file::write_through_temporary(Filename, [&contents](std::ostream &Output) {
if (auto const failure{world_cache::write(Output, contents)}; !failure.empty())
throw std::runtime_error{failure};
});
}
std::string read(std::string const &Filename, std::uint64_t const Engine, load_settings const &Settings, std::string &Tape) {
statement_table statements;
std::vector<std::string> files;
return read(Filename, Engine, Settings, Tape, statements, files);
}
std::string read(std::string const &Filename, std::uint64_t const Engine, load_settings const &Settings, std::string &Tape, statement_table &Statements, std::vector<std::string> &Files) {
std::ifstream input{std::filesystem::path{Filename}, std::ios::binary};
if (!input)
return "no cache";
world_cache::reader cache;
if (auto const error{cache.open(input)}; !error.empty())
return error;
if (cache.header().layer != world_cache::layer_kind::logic || cache.header().body.kind != world_geometry::body_kind::plane)
return "not a cache of the logic on the plane";
if (cache.header().engine_hash != Engine)
return "made by another build";
std::string text;
std::size_t total{0};
for (auto const &entry : cache.package())
total += entry.tag == tape_tag ? entry.raw_size : 0;
text.reserve(total);
std::vector<std::byte> part;
statement_table statements;
for (auto const &entry : cache.package()) {
if (entry.tag != tape_tag && entry.tag != statements_tag)
continue;
if (auto const error{cache.read_package_block(input, entry, part)}; !error.empty())
return error;
if (entry.tag == tape_tag) {
text.append(reinterpret_cast<char const *>(part.data()), part.size());
}
else if (!decode_statements(std::string_view{reinterpret_cast<char const *>(part.data()), part.size()}, statements)) {
return "the statement table doesn't read";
}
}
std::vector<std::string> files;
std::size_t entries{0};
if (!parser_tape::check(text, files, entries))
return "the tape doesn't read";
if (cache.header().source_hash != source_hash(files, Settings))
return "the sources or the settings changed";
Tape = std::move(text);
Statements = std::move(statements);
Files = std::move(files);
return {};
}
} // namespace world_logic_cache