diff --git a/CMakeLists.txt b/CMakeLists.txt index 0e9a8d06f..89a872c87 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -898,6 +898,11 @@ set(CORE_SOURCES ) add_library(eu07_core STATIC ${CORE_SOURCES}) target_link_libraries(eu07_core PUBLIC eu07_settings) +if (CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") + # the floating-point results as MSVC gives them: no multiply and add fused into one where the target has FMA, which GNU C++ + # allows by default (docs/world-format-eu07.md, section 6) + target_compile_options(eu07_settings INTERFACE -ffp-contract=off) +endif() set_target_properties(eu07_core PROPERTIES ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib" FOLDER "libraries") diff --git a/scene/scene.cpp b/scene/scene.cpp index 2c2a5acab..65070246d 100644 --- a/scene/scene.cpp +++ b/scene/scene.cpp @@ -1806,8 +1806,11 @@ bool basic_region::point_inside( glm::dvec3 const &Location ) { if( false == region_bounded() ) { - // as far as the nodes reach; a broken point still stays out - return std::isfinite( Location.x ) && std::isfinite( Location.z ); + // as far as the nodes reach; a broken point still stays out, and so does one far beyond any world (a typo such as 1e13), + // whose section key wouldn't fit in its integers: a million kilometres, past the Moon + constexpr double sanity_bound { 1e9 }; + return std::isfinite( Location.x ) && std::isfinite( Location.z ) + && std::abs( Location.x ) < sanity_bound && std::abs( Location.z ) < sanity_bound; } double const regionboundary = EU07_REGIONSIDESECTIONCOUNT / 2 * EU07_SECTIONSIZE; return Location.x > -regionboundary && Location.x < regionboundary && Location.z > -regionboundary && Location.z < regionboundary; diff --git a/scene/sceneterrain.cpp b/scene/sceneterrain.cpp index 7b47e4281..69bcbe03d 100644 --- a/scene/sceneterrain.cpp +++ b/scene/sceneterrain.cpp @@ -758,7 +758,8 @@ std::uint16_t terrain_file::reference_of(std::string const &File) for (std::size_t index{0}; index < list.size() && index < std::numeric_limits::max(); ++index) { auto const base{Global.asCurrentSceneryPath + list[index].file}; - if (file.ends_with(base + ".txtf") || file.ends_with(base + ".btf")) + // the binary file of the scenery out of the classic square has an extension of its own (scene::binary_terrain_extension()) + if (file.ends_with(base + ".txtf") || file.ends_with(base + ".btf") || file.ends_with(base + scene::binary_terrain_extension())) { return static_cast(index + 1); } diff --git a/simulation/simulationstateserializer.cpp b/simulation/simulationstateserializer.cpp index ec445700d..364829729 100644 --- a/simulation/simulationstateserializer.cpp +++ b/simulation/simulationstateserializer.cpp @@ -103,9 +103,11 @@ restore_transformations( scene::scratch_data::location_data &Location, world_log Location.rotation = { Context.rotation_x, Context.rotation_y, Context.rotation_z }; } -// the order to replay the statements in, asked for by EU07_WORLD_REPLAY_ORDER: "file", the order of the file, by seeks on the tape; -// "regions", the statements of the whole package first, then those of each region; "regions-first", the regions first. none with no variable or no table: then the tape -// plays through as it was recorded +// the order to replay the statements in, asked for by EU07_WORLD_REPLAY_ORDER, a debugging aid for the loading by regions of the next +// steps and not a setting for players: "file", the order of the file, by seeks on the tape; "regions", the statements of the whole +// package first, then those of each region; "regions-first", the regions first. the region orders don't load a real scenery yet: +// the vehicles and the groups are of the whole package, and come before or after the tracks and nodes they need. none with no +// variable or no table: then the tape plays through as it was recorded std::vector replay_order( world_logic_cache::statement_table const &Table ) { @@ -165,6 +167,7 @@ state_serializer::make_deserializer_state( std::string const &Scenariofile, bool world_logic_cache::load_settings settings; settings.load_traction = Global.bLoadTraction; settings.binary_terrain = Binaryterrain; + settings.file_binary_terrain = Global.file_binary_terrain; settings.prepend = Global.prepend_scn; std::vector> overrides { Global.trainset_overrides.begin(), Global.trainset_overrides.end() }; std::ranges::sort( overrides ); @@ -182,9 +185,10 @@ state_serializer::make_deserializer_state( std::string const &Scenariofile, bool state->order = replay_order( table ); if( false == state->order.empty() ) { WriteLog( "Logic cache: " + std::to_string( state->order.size() ) + " statements replayed in the order of EU07_WORLD_REPLAY_ORDER=" + std::getenv( "EU07_WORLD_REPLAY_ORDER" ) ); + // the table and the files are needed only to seek on the tape + state->replaytable = std::move( table ); + state->tapefiles = std::move( files ); } - state->replaytable = std::move( table ); - state->tapefiles = std::move( files ); return state; } else { @@ -343,7 +347,10 @@ state_serializer::deserialize_ordered( deserializer_state &State, std::chrono::s restore_transformations( State.scratchpad.location, State.replaytable.contexts[ item.context ] ); // a repeated name goes to the item of the later statement in the file, whatever the order they load in (D4) table_statement_order() = index; - if( auto const token { State.input.getToken() }; false == token.empty() ) { + // the statement, and what follows it up to the next one, as the loop over the tape plays it: a stray token is a keyword + // there too. the read that ends the part replays what the tape holds after the statement (the closes of the files it + // ends), so the order of the file gives the order of the tape + for( auto token { State.input.getToken() }; false == token.empty(); token = State.input.getToken() ) { deserialize_statement( State, token ); } table_statement_order().reset(); @@ -1489,7 +1496,7 @@ include_binary_terrain( std::string File, scene::scratch_data &Scratchpad ) { // only for the text file of the same name, and has no bearing on how the rest of the scenery is loaded. // a file which is to be read as text is added to Includes, for the caller to pass to the parser void -include_terrain_file( std::string File, std::string &Includes, scene::scratch_data &Scratchpad ) { +include_terrain_file( std::string File, std::string &Includes, scene::scratch_data &Scratchpad, cParser &Input ) { auto &binary { Scratchpad.binary }; @@ -1510,6 +1517,9 @@ include_terrain_file( std::string File, std::string &Includes, scene::scratch_da auto const textfile { Global.asCurrentSceneryPath + File + ".txtf" }; auto const binaryfile { Global.asCurrentSceneryPath + File + scene::binary_terrain_extension() }; + // what the directive gives the parser depends on both files, so a recorded tape follows the changes of both + Input.recordFile( textfile ); + Input.recordFile( binaryfile ); auto const textpresent { FileExists( textfile ) }; // binary file holds the geometry where the text alone puts it, it can't stand in for a file placed with an offset or rotation auto const relocated { @@ -1602,10 +1612,15 @@ state_serializer::deserialize_terrain(cParser &Input, scene::scratch_data &Scrat { if (file.ends_with(".txtf") || file.ends_with(".btf")) { - include_terrain_file(file, includes, Scratchpad); + include_terrain_file(file, includes, Scratchpad, Input); } else if (Global.file_binary_terrain && file.ends_with(".sbt")) { + // whether the file can be used decides which terrain includes the scenery skips, so a recorded tape follows it + auto stem{file}; + replace_slashes(stem); + erase_extension(stem); + Input.recordFile(FileOnDisk(Global.asCurrentSceneryPath + stem + ".sbt")); include_binary_terrain(file, Scratchpad); } } diff --git a/tests/unit/test_parser_tape.cpp b/tests/unit/test_parser_tape.cpp index d15c139bb..49f8ac5fa 100644 --- a/tests/unit/test_parser_tape.cpp +++ b/tests/unit/test_parser_tape.cpp @@ -161,6 +161,47 @@ TEST_CASE("a parser replaying its tape gives the reader the same tokens and the } } +TEST_CASE("the statements of a tape replayed one by one through seek() give what the tape gives played through") { + test::scratch_folder const folder{"parser_tape_seek"}; + folder.write("main.scn", + "node 1000 0 a model 1 2 3 none 7 endmodel\n" + "include part.scm end\n" + "node 500 0 b track 0 0 0 Rail none endtrack\n"); + folder.write("part.scm", "node 10 0 c model 4 5 6 none 8 endmodel\ninclude inner.scm end\n"); + folder.write("inner.scm", "node 20 0 d model 7 8 9 none 9 endmodel\n"); + // each token is a statement here, taken where the loader takes one: the place and the state before its read + parser_tape::writer tape; + std::vector> starts; + std::vector played; + { + cParser input{"main.scn", cParser::buffer_FILE, folder.path()}; + input.startRecording(tape); + while (true) { + starts.emplace_back(tape.position(), tape.last_state()); + auto const token{input.getToken()}; + if (token.empty()) + break; + played.push_back(std::format("{} | {} {}", token, input.Name(), input.Line())); + } + } + starts.pop_back(); + auto const files{tape.files()}; + auto const bytes{tape.finish()}; + std::vector sought; + { + parser_tape::reader reader{bytes}; + cParser input{reader}; + for (std::size_t k = 0; k < starts.size(); ++k) { + auto const end{k + 1 < starts.size() ? starts[k + 1].first : bytes.size() - 1}; + reader.seek(starts[k].first, end, starts[k].second, files); + for (auto token{input.getToken()}; !token.empty(); token = input.getToken()) + sought.push_back(std::format("{} | {} {}", token, input.Name(), input.Line())); + } + } + CHECK(sought == played); + CHECK(played.size() > 30); +} + TEST_CASE("a cut or foreign tape doesn't read") { parser_tape::writer tape; parser_tape::state start; diff --git a/tests/unit/test_world_geometry.cpp b/tests/unit/test_world_geometry.cpp index 547c6c76e..a0dc3b2b8 100644 --- a/tests/unit/test_world_geometry.cpp +++ b/tests/unit/test_world_geometry.cpp @@ -5,6 +5,7 @@ #include #include +#include #include #include #include @@ -317,6 +318,54 @@ TEST_CASE("the tiles of the plane have neighbours within the square, in Hilbert CHECK_FALSE(make_frame(body::earth(), tile).tile.valid()); } +TEST_CASE("the functions refuse what they aren't for, rather than give a quiet wrong answer") { + // the face of a direction on an edge: the later axis on equal components, as S2 does + CHECK(tile_at({1.0, 1.0, 0.5}, 0).face() == 1); + CHECK(tile_at({1.0, 1.0, 1.0}, 0).face() == 2); + CHECK(tile_at({-1.0, 0.5, -1.0}, 0).face() == 5); + CHECK(tile_at({1.0, 0.5, 0.5}, 0).face() == 0); + // a tile of the plane has no direction, a tile of the cube no place on the plane + auto const flat{plane_tile_at({}, surroundings_tile_level)}; + REQUIRE(flat.valid()); + CHECK(centre_direction(flat) == glm::dvec3{0.0}); + CHECK(corner_direction(flat, 2) == glm::dvec3{0.0}); + CHECK(plane_tile_centre(tile_at({0.3, -0.8, 0.5}, surroundings_tile_level)) == position{}); + // geodetic coordinates need a curved body + CHECK(to_cartesian(body::plane(), {0.5, 0.5, 10.0}) == glm::dvec3{0.0}); + CHECK(to_geodetic(body::plane(), {1.0, 2.0, 3.0}).height == 0.0); + // at the very centre no direction is up: the polar axis + CHECK(body::earth().up({0.0, 0.0, 0.0}) == glm::dvec3{0.0, 0.0, 1.0}); + // the Earth is WGS84: other axes are a broken record + std::stringstream other; + write(other, body{body_kind::earth, 6'378'000.0, 6'356'000.0}); + body back; + CHECK_FALSE(read(other, back)); + // a value that doesn't fit in micrometres is no value + CHECK(checked_micrometres(1.5) == 1'500'000); + CHECK(checked_micrometres(-9.1e12).has_value()); + CHECK_FALSE(checked_micrometres(1e13).has_value()); + CHECK_FALSE(checked_micrometres(std::numeric_limits::quiet_NaN()).has_value()); + CHECK_FALSE(checked_micrometres(std::numeric_limits::infinity()).has_value()); + // a frame of the plane with a rotation, or with its anchor outside its tile, doesn't read + auto const plane_frame{make_frame(body::plane(), flat, 12.0)}; + tile_frame read_back; + { + std::stringstream stream; + write(stream, plane_frame); + CHECK(read(stream, read_back)); + } + auto turned{plane_frame}; + turned.orientation = glm::dquat{0.0, 0.0, 1.0, 0.0}; + std::stringstream turned_stream; + write(turned_stream, turned); + CHECK_FALSE(read(turned_stream, read_back)); + auto moved{plane_frame}; + moved.anchor.x += 2'000 * micrometres_per_metre; + std::stringstream moved_stream; + write(moved_stream, moved); + CHECK_FALSE(read(moved_stream, read_back)); +} + TEST_CASE("a frame is written and read back bit for bit, and a broken record doesn't read") { auto const earth{body::earth()}; auto const frame{make_frame(earth, tile_at({0.3, -0.8, 0.5}, surroundings_tile_level), 1234.5)}; diff --git a/tests/unit/test_world_logic_cache.cpp b/tests/unit/test_world_logic_cache.cpp index ceeabb8f6..d7c7ec6aa 100644 --- a/tests/unit/test_world_logic_cache.cpp +++ b/tests/unit/test_world_logic_cache.cpp @@ -4,6 +4,7 @@ #include "utilities/parser.h" #include "world/worldlogiccache.h" +#include #include #include #include @@ -11,9 +12,10 @@ // the cache of the logic of a scenery (world/worldlogiccache.h): the tape of the parser, in package blocks of a cache file, read // back only while the build, the files and the settings are those it was made from -TEST_CASE("the logic cache is named after the scenario file, without the Rainsted marks") { +TEST_CASE("the logic cache is named after the scenario file, with the Rainsted marks") { CHECK(world_logic_cache::file_name("scenery/", "linia053_wrzosy.scn") == "scenery/linia053_wrzosy.logic.eu07"); - CHECK(world_logic_cache::file_name("scenery/", "$$wrzosy.scn") == "scenery/wrzosy.logic.eu07"); + // a scenario written by the starter with other trainsets and time has a cache of its own + CHECK(world_logic_cache::file_name("scenery/", "$$wrzosy.scn") == "scenery/$$wrzosy.logic.eu07"); CHECK(world_logic_cache::file_name("scenery/", "noextension") == "scenery/noextension.logic.eu07"); } @@ -70,6 +72,9 @@ TEST_CASE("the logic cache is read back while it's current, and refused when the other = settings; other.trainset_overrides = "3=trainset x endtrainset;"; CHECK_FALSE(world_logic_cache::read(cachefile, engine, other, back).empty()); + other = settings; + other.file_binary_terrain = true; + CHECK_FALSE(world_logic_cache::read(cachefile, engine, other, back).empty()); // an included file changed folder.write("part.inc", "node 2 0 b model 0 0 0 none 22 endmodel\n"); CHECK_FALSE(world_logic_cache::read(cachefile, engine, settings, back).empty()); @@ -106,3 +111,41 @@ TEST_CASE("the statements of the logic cache: their regions of 8192 m, their tra CHECK_FALSE(world_logic_cache::decode_statements(std::string_view{bytes}.substr(0, length), back)); CHECK_FALSE(world_logic_cache::decode_statements(bytes + "x", back)); } + +TEST_CASE("the files which give no token count for the cache too: an include of includes, an empty one, a missing one") { + test::scratch_folder const folder{"logic_cache_files"}; + folder.write("main.scn", "include outer.scm end\ninclude empty.scm end\ninclude absent.scm end\n"); + folder.write("outer.scm", "include inner.scm end\n"); + folder.write("inner.scm", "node 1 0 a model 0 0 0 none 1 endmodel\n"); + folder.write("empty.scm", "// nothing here yet\n"); + parser_tape::writer recorder; + { + cParser input{"main.scn", cParser::buffer_FILE, folder.path()}; + input.startRecording(recorder); + while (!input.getToken().empty()) { + } + } + auto const files{recorder.files()}; + auto const listed = [&files](std::string_view const Name) { + return std::ranges::any_of(files, [Name](std::string const &File) { return File.ends_with(Name); }); + }; + CHECK(listed("outer.scm")); + CHECK(listed("inner.scm")); + CHECK(listed("empty.scm")); + CHECK(listed("absent.scm")); + auto const tape{recorder.finish()}; + world_logic_cache::load_settings const settings; + auto const cachefile{folder.path("main.logic.eu07")}; + REQUIRE(world_logic_cache::write(cachefile, tape, files, 1, settings).empty()); + std::string back; + CHECK(world_logic_cache::read(cachefile, 1, settings, back).empty()); + // a new include in the file of includes, a line in the empty one, the missing one made: each makes the cache old + folder.write("outer.scm", "include inner.scm end\ninclude more.scm end\n"); + CHECK_FALSE(world_logic_cache::read(cachefile, 1, settings, back).empty()); + REQUIRE(world_logic_cache::write(cachefile, tape, files, 1, settings).empty()); + folder.write("empty.scm", "node 2 0 b model 0 0 0 none 2 endmodel\n"); + CHECK_FALSE(world_logic_cache::read(cachefile, 1, settings, back).empty()); + REQUIRE(world_logic_cache::write(cachefile, tape, files, 1, settings).empty()); + folder.write("absent.scm", "node 3 0 c model 0 0 0 none 3 endmodel\n"); + CHECK_FALSE(world_logic_cache::read(cachefile, 1, settings, back).empty()); +} diff --git a/utilities/parser.cpp b/utilities/parser.cpp index 2d1b15128..b3017aa7f 100644 --- a/utilities/parser.cpp +++ b/utilities/parser.cpp @@ -68,6 +68,15 @@ void record_side_effect(parser_tape::entry_kind const Kind) } } +// a file the scenery depends on, into the list of files of the tape being recorded +void record_file(std::string const &Name) +{ + if (active_recorder != nullptr) + { + active_recorder->tape->file(Name); + } +} + // lends the recorder to the parsers of the included files for the time of one read, and takes it back class recorder_scope { @@ -582,6 +591,8 @@ void cParser::startIncludeFromParser(cParser& srcParser, bool ToLower, std::stri ); mIncludeParser->allowRandomIncludes = allowRandomIncludes; mIncludeParser->autoclear(m_autoclear); + // the file is a part of the scenery whether it gives tokens or not (an include of includes, an empty one, a missing one) + record_file(mIncludeParser->Name()); if (mIncludeParser->mSize <= 0) { ErrorLog("Bad include: can't open file \"" + includefile + "\""); @@ -709,6 +720,14 @@ void cParser::startRecording(parser_tape::writer &Tape) Tape.begin(Name(), parser_state(*this)); } +void cParser::recordFile(std::string const &Name) +{ + if (m_recorder != nullptr) + { + m_recorder->tape->file(Name); + } +} + void cParser::recordToken(std::string const &Token) { if (Token.empty()) diff --git a/utilities/parser.h b/utilities/parser.h index afcae26dc..5a1d38744 100644 --- a/utilities/parser.h +++ b/utilities/parser.h @@ -130,6 +130,9 @@ class cParser //: public std::stringstream // records into the tape everything this parser gives its reader from now on (utilities/parsertape.h). for the outermost parser // of a scenery, not for one that registers scenery layers. the tape has to outlive the parser void startRecording( parser_tape::writer &Tape ); + // puts the file into the list of files of the tape being recorded, if one is: a file the scenery depends on without a token from + // it, as the terrain files of a terrain directive + void recordFile( std::string const &Name ); // the parser records or replays a tape: its readers take every token from it, none straight from the text bool taped() const { return m_recorder != nullptr || m_replay != nullptr; } diff --git a/utilities/parsertape.cpp b/utilities/parsertape.cpp index ef4dc0fbd..0dea0e53b 100644 --- a/utilities/parsertape.cpp +++ b/utilities/parsertape.cpp @@ -223,7 +223,8 @@ reader::reader(std::string_view const Bytes) : m_bytes{Bytes} { std::string const &reader::file_name(std::uint32_t const Index) const { static std::string const none; - return Index < m_files.size() ? m_files[Index] : none; + auto const &table{files()}; + return Index < table.size() ? table[Index] : none; } void reader::decode() { @@ -238,7 +239,7 @@ void reader::decode() { auto const kind{input.byte()}; if (kind == static_cast(entry_kind::file)) { auto const name{input.text()}; - if (!m_fulltable) + if (m_fulltable == nullptr) m_files.emplace_back(name); if (!input.ok()) m_broken = true; @@ -259,8 +260,8 @@ void reader::decode() { if (m_next == entry_kind::token || m_next == entry_kind::text) m_nexttext = input.text(); if (m_next == entry_kind::token) - m_nextstate = get_state(input, m_current, m_nexttext.size(), m_files.size()); - if (!input.ok() || (m_next == entry_kind::token && m_nextstate.file >= m_files.size())) { + m_nextstate = get_state(input, m_current, m_nexttext.size(), files().size()); + if (!input.ok() || (m_next == entry_kind::token && m_nextstate.file >= files().size())) { m_broken = true; m_next = entry_kind::end; } @@ -274,8 +275,7 @@ void reader::seek(std::size_t const Offset, std::size_t const End, state const & m_position = std::min(Offset, m_bytes.size()); m_end = std::min(End, m_bytes.size()); m_current = State; - m_files = Files; - m_fulltable = true; + m_fulltable = &Files; m_broken = false; decode(); } diff --git a/utilities/parsertape.h b/utilities/parsertape.h index 83becbf84..c6152a8d5 100644 --- a/utilities/parsertape.h +++ b/utilities/parsertape.h @@ -65,6 +65,9 @@ public: void token(std::string_view Token, std::string_view File, state State); void side_effect(entry_kind Kind); void text(std::string_view Text); + // a file the scenery depends on whether or not it gives a token: an include of includes, an empty one, one that failed to open, + // a terrain file. it goes into the list of files, so that the cache follows its changes + void file(std::string_view Name) { file_index(Name); } // ends the tape and gives its bytes away std::string finish(); @@ -99,13 +102,14 @@ public: // moves past the next entry; past a token its state becomes the current one void pop(); // moves to the entry at the offset, with the state a reader has there and the names of all the files of the tape (check() gives - // them), and reads only up to the end offset; for replaying the statements of a tape out of their order + // them; they have to outlive the reader, which keeps no copy), and reads only up to the end offset; for replaying the statements + // of a tape out of their order void seek(std::size_t Offset, std::size_t End, state const &State, std::vector const &Files); // the state after the token popped last, or before the first one state const ¤t() const { return m_current; } std::string const &file_name(std::uint32_t Index) const; - // the names of the files met so far, in the order of their indices - std::vector const &files() const { return m_files; } + // the names of the files met so far, in the order of their indices; all of them after seek() + std::vector const &files() const { return m_fulltable != nullptr ? *m_fulltable : m_files; } bool broken() const { return m_broken; } // how far into the bytes the reader got, and their count, for the progress of a load std::size_t consumed() const { return m_position; } @@ -119,8 +123,8 @@ private: std::size_t m_position{0}; // the end of the part being read, the end of the bytes unless seek() set it std::size_t m_end{static_cast(-1)}; - // the table of files was given whole by seek(): the file entries met on the way add nothing to it - bool m_fulltable{false}; + // the table of files given whole by seek(): the file entries met on the way add nothing to it + std::vector const *m_fulltable{nullptr}; std::vector m_files; entry_kind m_next{entry_kind::end}; std::string_view m_nexttext; diff --git a/world/worldgeometry.cpp b/world/worldgeometry.cpp index 728a86b9b..3b5adb970 100644 --- a/world/worldgeometry.cpp +++ b/world/worldgeometry.cpp @@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "world/worldgeometry.h" +#include #include #include #include @@ -36,6 +37,14 @@ std::int64_t micrometres(double const Metres) { return std::llround(Metres * micrometres_in_metre); } +std::optional checked_micrometres(double const Metres) { + // within ±9.2·10¹² m, so that the product and its rounding stay inside an int64 + constexpr double limit{9.2e12}; + if (!std::isfinite(Metres) || std::abs(Metres) > limit) + return std::nullopt; + return micrometres(Metres); +} + double metres(std::int64_t const Micrometres) { // an int64 below 2^53 converts exactly, and the division rounds correctly: the nearest double to the decimal value return static_cast(Micrometres) / micrometres_in_metre; @@ -62,6 +71,7 @@ body body::fictional_planet() { } body body::fictional_planet(double const Radius) { + assert(Radius > 0.0 && std::isfinite(Radius)); return {body_kind::fictional_planet, Radius, Radius}; } @@ -72,6 +82,8 @@ glm::dvec3 body::up(glm::dvec3 const &Point) const { auto const b2{b * b}; glm::dvec3 const normal{Point.x / a2, Point.y / a2, Point.z / b2}; auto const length{std::sqrt(normal.x * normal.x + normal.y * normal.y + normal.z * normal.z)}; + if (!(length > 0.0)) + return {0.0, 0.0, 1.0}; return normal / length; } @@ -103,11 +115,17 @@ bool read(std::istream &Input, body &Body) { else if (kind > static_cast(body_kind::plane) || !(b > 0.0) || b > a || !std::isfinite(a)) { return false; } + else if (kind == static_cast(body_kind::earth) && (a != wgs84_a || b != wgs84_b)) { + // the kind says WGS84, so other axes are a broken record + return false; + } Body = {static_cast(kind), a, b}; return true; } glm::dvec3 to_cartesian(body const &Body, geodetic const &Point) { + if (!Body.curved()) + return {}; auto const e2{Body.eccentricity_squared()}; auto const sine{std::sin(Point.latitude)}; auto const cosine{std::cos(Point.latitude)}; @@ -119,6 +137,8 @@ glm::dvec3 to_cartesian(body const &Body, geodetic const &Point) { } geodetic to_geodetic(body const &Body, glm::dvec3 const &Point) { + if (!Body.curved()) + return {}; auto const e2{Body.eccentricity_squared()}; auto const p{std::hypot(Point.x, Point.y)}; geodetic result; diff --git a/world/worldgeometry.h b/world/worldgeometry.h index a225f8517..221a6a3a7 100644 --- a/world/worldgeometry.h +++ b/world/worldgeometry.h @@ -12,6 +12,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include @@ -44,9 +45,13 @@ struct position { position from_metres(glm::dvec3 const &Metres); // the position in metres, each coordinate correctly rounded to the nearest double glm::dvec3 to_metres(position const &Position); -// a value of metres as micrometres and back, as above +// a value of metres as micrometres and back, as above. micrometres() of NaN, of an infinity or of more than about 9.2·10¹² m has no +// meaningful result: a value read from a file goes through checked_micrometres() std::int64_t micrometres(double Metres); double metres(std::int64_t Micrometres); +// a value of metres as micrometres when it is finite and fits in an int64; none otherwise, for the importers to report with the file +// and the line +std::optional checked_micrometres(double Metres); // the kinds of body a world is set on (section 4) enum class body_kind : std::uint8_t { @@ -70,12 +75,13 @@ struct body { static body plane(); // a fictional planet on the WGS84 ellipsoid, the default static body fictional_planet(); - // a fictional planet as a sphere of the radius, in metres + // a fictional planet as a sphere of the radius, in metres; the radius is positive and finite static body fictional_planet(double Radius); bool curved() const { return kind != body_kind::plane; } // the vertical at the point, in metres in the body's system: the normal of the ellipsoid, (x/a², y/a², z/b²) normalised, with no - // trigonometry; (0, 1, 0) on the plane. the square root is rounded exactly by IEEE, so the result is the same on MSVC and GCC. + // trigonometry; (0, 1, 0) on the plane. at the very centre of a curved body, where no direction is up, the polar axis (0, 0, 1). + // the square root is rounded exactly by IEEE, so the result is the same on MSVC and GCC. // off the surface it is the normal of the ellipsoid scaled through the point, which turns from the geodetic vertical by about // 5e-7 rad per kilometre of height on the Earth: 0.0005 per mille of gradient at 1 km up glm::dvec3 up(glm::dvec3 const &Point) const; @@ -86,8 +92,8 @@ struct body { double eccentricity_squared() const; }; -// the body written as a record of 17 bytes, little-endian: the kind, then a and b; a record of an unknown kind or with axes out of -// order doesn't read +// the body written as a record of 17 bytes, little-endian: the kind, then a and b; a record of an unknown kind, with axes out of +// order, or of the Earth with other axes than WGS84's doesn't read void write(std::ostream &Output, body const &Body); bool read(std::istream &Input, body &Body); @@ -99,7 +105,7 @@ struct geodetic { double height{0.0}; }; -// metres in the body's system; both need a curved body +// metres in the body's system; both need a curved body, and give zero on the plane glm::dvec3 to_cartesian(body const &Body, geodetic const &Point); // iterated to convergence, below a micrometre of height anywhere outside the very centre of the body geodetic to_geodetic(body const &Body, glm::dvec3 const &Point); diff --git a/world/worldlogiccache.cpp b/world/worldlogiccache.cpp index 4aad646ac..6f6981665 100644 --- a/world/worldlogiccache.cpp +++ b/world/worldlogiccache.cpp @@ -20,6 +20,8 @@ http://mozilla.org/MPL/2.0/. #include #include "scene/regionfile.h" +#include "utilities/utilities.h" +#include "utilities/utilities.h" namespace world_logic_cache { @@ -38,10 +40,15 @@ std::uint64_t mix(std::uint64_t const Hash, std::uint64_t const 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 +// the size and the time of the last change of the file; all ones when it isn't there. the parser names the files in lowercase and +// opens them in the case they have on a case-sensitive file system, and so is the file looked at here std::pair file_state(std::string const &Name) { std::error_code error; - std::filesystem::path const path{Name}; + std::filesystem::path path{Name}; + if (!std::filesystem::exists(path, error)) { + if (auto const cased{FileCased(path)}; !cased.empty()) + path = cased; + } auto const size{std::filesystem::file_size(path, error)}; if (error) return {~std::uint64_t{0}, ~std::uint64_t{0}}; @@ -226,9 +233,8 @@ bool decode_statements(std::string_view const Bytes, statement_table &Table) { } std::string file_name(std::string const &Sceneryfolder, std::string const &Scenariofile) { + // the Rainsted marks stay: a scenario written with them holds other trainsets and time than the one without 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"; @@ -257,6 +263,7 @@ std::uint64_t source_hash(std::vector const &Files, load_settings c } hash = mix(hash, Settings.load_traction ? 1 : 0); hash = mix(hash, Settings.binary_terrain ? 1 : 0); + hash = mix(hash, Settings.file_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; diff --git a/world/worldlogiccache.h b/world/worldlogiccache.h index 56bd23d13..ed93b6a4d 100644 --- a/world/worldlogiccache.h +++ b/world/worldlogiccache.h @@ -86,6 +86,9 @@ inline constexpr std::size_t tape_part_size{64u * 1024u * 1024u}; struct load_settings { bool load_traction{true}; bool binary_terrain{false}; + // file.binary.terrain: whether the terrain files of a terrain directive load from their binary files, which decides what the + // directive gives the parser + bool file_binary_terrain{false}; std::string prepend; std::string trainset_overrides; }; diff --git a/world/worldtiles.cpp b/world/worldtiles.cpp index f8ac264d0..0126a20b5 100644 --- a/world/worldtiles.cpp +++ b/world/worldtiles.cpp @@ -71,11 +71,8 @@ int xyz_to_face(glm::dvec3 const &Point) { auto const ax{std::abs(Point.x)}; auto const ay{std::abs(Point.y)}; auto const az{std::abs(Point.z)}; - int axis{0}; - if (ay > ax) - axis = 1; - if (az > std::max(ax, ay)) - axis = 2; + // the largest component, the later axis on equal ones (z over y over x), as S2's LargestAbsComponent + int const axis{ax > ay ? (ax > az ? 0 : 2) : (ay > az ? 1 : 2)}; auto const negative{(axis == 0 && Point.x < 0.0) || (axis == 1 && Point.y < 0.0) || (axis == 2 && Point.z < 0.0)}; return negative ? axis + 3 : axis; } @@ -294,7 +291,7 @@ tile_id tile_at(glm::dvec3 const &Direction, int const Level) { } glm::dvec3 centre_direction(tile_id const Tile) { - if (!Tile.valid()) + if (!Tile.valid() || Tile.planar()) return {}; auto const cell{Tile.to_face_ij()}; auto const side{static_cast(std::uint64_t{1} << Tile.level())}; @@ -302,7 +299,7 @@ glm::dvec3 centre_direction(tile_id const Tile) { } glm::dvec3 corner_direction(tile_id const Tile, int const Corner) { - if (!Tile.valid()) + if (!Tile.valid() || Tile.planar()) return {}; auto const cell{Tile.to_face_ij()}; auto const side{static_cast(std::uint64_t{1} << Tile.level())}; @@ -323,6 +320,8 @@ tile_id plane_tile_at(position const &Position, int const Level) { } position plane_tile_centre(tile_id const Tile) { + if (!Tile.valid() || !Tile.planar()) + return {}; auto const cell{Tile.to_face_ij()}; // the middle of the tile is (2i + 1) halves of its size, and the size is 15625 · 2^(30 - level) / 2 µm auto const quarters{plane_leaf_numerator << (max_tile_level - Tile.level())}; @@ -392,6 +391,10 @@ bool read(std::istream &Input, tile_frame &Frame) { return false; if (auto const norm{glm::length(frame.orientation)}; !(std::abs(norm - 1.0) < 1e-9)) return false; + // a frame of the plane has no rotation, and its anchor lies in its tile: a cache made for another body doesn't read + if (frame.tile.planar() + && (frame.orientation != glm::dquat{1.0, 0.0, 0.0, 0.0} || plane_tile_at(frame.anchor, frame.tile.level()) != frame.tile)) + return false; Frame = frame; return true; } diff --git a/world/worldtiles.h b/world/worldtiles.h index ad25fca63..a392e305e 100644 --- a/world/worldtiles.h +++ b/world/worldtiles.h @@ -22,9 +22,12 @@ http://mozilla.org/MPL/2.0/. // the tiles of the new world format (docs/world-format-eu07.md, section 3): a cube grid of the sphere. the 6 faces of a cube are // projected onto the body, each split by a quadtree. the layout of the faces, the quadratic transform between the face and the cube -// and the Hilbert order follow the documented scheme of S2, so the ids are those S2 gives its cells: neighbouring tiles lie close -// together in the order, across the edges of the faces too. level 13 gives tiles of about 1.2 km on the Earth. the grid is defined -// on the directions from the centre of the body, so it is the same on any ellipsoid. the plane body has no cube: it takes the face +// and the Hilbert order follow the documented scheme of S2, so the ids are those S2 gives its cells for the direction from the centre +// of the body: neighbouring tiles lie close together in the order, across the edges of the faces too. level 13 gives tiles of about +// 1.2 km on the Earth. the grid is defined on the directions from the centre of the body (geocentric), so it is the same on any +// ellipsoid. a geodetic latitude and longitude go through to_cartesian() first, never straight into S2's latitude/longitude, which +// would take the geodetic latitude for the geocentric one: up to about 0.19° apart (21 km) around 45°, another tile and region. +// the records here carry no version of their own: the files that hold them do, in their headers the plane body has no cube: it takes the face // value 6, which the cube leaves free, for a flat square split by the same quadtree in the same order, so the directory, the order in // the files, the regions of the logic and the neighbours are the same code for all bodies namespace world_geometry { @@ -89,15 +92,16 @@ private: // the tile of the cube at the level that holds the direction from the centre of the body (of any non-zero length) tile_id tile_at(glm::dvec3 const &Direction, int Level); -// the direction from the centre of the body to the middle of a tile of the cube, of unit length +// the direction from the centre of the body to the middle of a tile of the cube, of unit length; none (zero) for a tile of the plane glm::dvec3 centre_direction(tile_id Tile); -// the direction to the corner of a tile of the cube, of unit length: 0 at the lowest coordinates of the face, then counter-clockwise +// the direction to the corner of a tile of the cube, of unit length: 0 at the lowest coordinates of the face, then counter-clockwise; +// none (zero) for a tile of the plane glm::dvec3 corner_direction(tile_id Tile, int Corner); // the tile of the plane at the level that holds the position (x and z of .scn; y doesn't count), computed in integers: i along x and // j along z, a leaf of the square 7.8125 mm. no tile outside the square tile_id plane_tile_at(position const &Position, int Level); -// the middle of a tile of the plane, at the height zero; exact down to level 28 +// the middle of a tile of the plane, at the height zero; exact down to level 28. the zero position for a tile of the cube position plane_tile_centre(tile_id Tile); // the local frame of a tile, written in the data so that the game never computes it: the anchor, in micrometres, and the rotation @@ -123,7 +127,8 @@ glm::dvec3 to_local(tile_frame const &Frame, position const &Position); position to_position(tile_frame const &Frame, glm::dvec3 const &Local); // the frame written as a record of 64 bytes, little-endian: the tile, the anchor, then the quaternion as w, x, y, z. a record with -// no valid tile or a quaternion that isn't of unit length doesn't read +// no valid tile or a quaternion that isn't of unit length doesn't read, nor a frame of the plane with a rotation or with its anchor +// outside its tile inline constexpr std::size_t tile_frame_record_size{64}; void write(std::ostream &Output, tile_frame const &Frame); bool read(std::istream &Input, tile_frame &Frame);