diff --git a/.github/workflows/sonar.yml b/.github/workflows/sonar.yml index 58e852370..2e8f83add 100644 --- a/.github/workflows/sonar.yml +++ b/.github/workflows/sonar.yml @@ -13,6 +13,18 @@ on: workflows: [ "Build" ] types: [ requested, completed ] +# One analysis per pull request at a time: a newer commit's Build (its "requested" event already) cancels the +# analysis of the older commit, which would otherwise hold a runner for about an hour for a result nobody reads. +# workflow_run.pull_requests is empty for a pull request from a fork, so the fork and its branch name the group then. +# A push to master gets a group of its own commit and is never cancelled, as in build.yml. +concurrency: + group: >- + ${{ github.workflow }}-${{ github.event.workflow_run.event == 'pull_request' + && format('pr-{0}', github.event.workflow_run.pull_requests[0].number + || format('{0}:{1}', github.event.workflow_run.head_repository.full_name, github.event.workflow_run.head_branch)) + || github.event.workflow_run.head_sha }} + cancel-in-progress: ${{ github.event.workflow_run.event == 'pull_request' }} + # Default to nothing; each job opts in to exactly what it needs. permissions: {} @@ -63,6 +75,9 @@ jobs: name: Analyze if: github.event.action == 'completed' && github.event.workflow_run.conclusion == 'success' runs-on: ubuntu-24.04 + # an analysis takes about an hour; one stuck in the scan or in the wait for the quality gate is stopped + # rather than holding the runner for the default 6 hours + timeout-minutes: 120 permissions: contents: read # fetch trusted config actions: read # download artifact from the Build run @@ -141,14 +156,14 @@ jobs: if [ "$event" != "pull_request" ]; then # A push: the branch comes from the trusted event, not from the artifact. Only - # master and staging are pushed to with a build (build.yml); anything else is refused - # rather than analysed as a branch of its own. + # master is pushed to with a build (build.yml); anything else is refused rather than + # analysed as a branch of its own. if [ "$RUN_EVENT" != "push" ] || [ "$RUN_REPO" != "$REPO" ]; then echo "::error::branch build that isn't a push to this repository ($RUN_EVENT, $RUN_REPO)" exit 1 fi case "$RUN_BRANCH" in - master|staging) echo "branch=$RUN_BRANCH" >> "$GITHUB_OUTPUT" ;; + master) echo "branch=$RUN_BRANCH" >> "$GITHUB_OUTPUT" ;; *) echo "::error::no analysis for a push to $RUN_BRANCH"; exit 1 ;; esac echo "Branch build of $RUN_BRANCH, no PR parameters." @@ -218,25 +233,6 @@ jobs: --define sonar.qualitygate.wait=true --define sonar.scm.revision=${{ github.event.workflow_run.head_sha }} - # staging as a branch of its own next to master, so its issues and its quality gate show - # before staging is merged into master. SonarQube Cloud keeps it as a long-lived branch - # only if its name matches the project's long-lived branch pattern (Administration > - # Branches and Pull Requests); otherwise it is a short-lived one, deleted when inactive. - - name: SonarQube Cloud scan (staging) - if: steps.meta.outputs.event != 'pull_request' && steps.meta.outputs.branch == 'staging' - uses: SonarSource/sonarqube-scan-action@fd88b7d7ccbaefd23d8f36f73b59db7a3d246602 # v6.0.0 - env: - SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} - SONAR_HOST_URL: https://sonarcloud.io - with: - args: > - --define sonar.cfamily.compile-commands=${{ env.BUILD_WRAPPER_OUT_DIR }}/compile_commands.json - --define sonar.cfamily.taintAnalysis=false - --define sonar.exclusions=${{ env.SONAR_EXCLUSIONS }} - --define sonar.qualitygate.wait=true - --define sonar.scm.revision=${{ github.event.workflow_run.head_sha }} - --define sonar.branch.name=staging - - name: Report success if: success() env: @@ -258,3 +254,16 @@ jobs: -f context="SonarQube Cloud" \ -f description="Quality gate failed or analysis errored" \ -f target_url="$RUN_URL" + + # cancelled by a newer commit of the pull request (concurrency above), or stopped by timeout-minutes: + # without this the commit would keep "Analysis in progress" for good + - name: Report cancellation + if: cancelled() + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + gh api -X POST "repos/${{ github.repository }}/statuses/$SHA" \ + -f state=error \ + -f context="SonarQube Cloud" \ + -f description="Analysis cancelled: a newer commit, or over the time limit" \ + -f target_url="$RUN_URL" diff --git a/CMakeLists.txt b/CMakeLists.txt index 25e147fe5..0aa1e34db 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -110,7 +110,14 @@ option(WITH_OPENVR "Compile with OpenVR" OFF) option(WITH_ZMQ "Compile with cppzmq" OFF) option(WITH_CRASHPAD "Compile with crashpad" OFF) option(WITH_DISCORD_RPC "Compile with DISCORD RICH PRESENCE" ON) -option(USE_LTO "Use link-time optimization" OFF) +# link-time optimization of the Release build, on by default with MSVC (/GL, /LTCG): MSVC doesn't inline the small getters +# and the brake valves' virtuals across files without it; the link of the game takes some 3.5 minutes longer +if(MSVC) + set(USE_LTO_DEFAULT ON) +else() + set(USE_LTO_DEFAULT OFF) +endif() +option(USE_LTO "Use link-time optimization (Release)" ${USE_LTO_DEFAULT}) option(WITH_TESTS "Build and run the unit tests with the game, a failing test fails the build" ON) option(WITH_EDITOR_SELFTESTS "Run the scripts of the editor and launcher self-tests named by the EU07_EDITOR_SELFTEST and EU07_LAUNCHER_SELFTEST variables" OFF) option(GENERATE_PDB "Generate executable with program debugging symbols" ON) @@ -226,6 +233,7 @@ set(SOURCES "vehicle/dynamic/visual.cpp" "EU07.cpp" "export_e3d_standalone.cpp" +"model/e4d/e4d_convert.cpp" "export_btf_standalone.cpp" "nodebank_previews_standalone.cpp" "world/Event.cpp" @@ -282,6 +290,9 @@ set(SOURCES "application/application.cpp" "simulation/simulationtime.cpp" "simulation/simulationtest.cpp" +"simulation/simulationsnapshotworld.cpp" +"simulation/simulationsnapshotvehicle.cpp" +"simulation/simulationsnapshotdriver.cpp" "scene/sceneeditor.cpp" "rendering/screenshot.cpp" "input/driverkeyboardinput.cpp" @@ -319,6 +330,7 @@ set(SOURCES "editor/editorGauge.cpp" "editor/editorInfra.cpp" "editor/editorTerrainStreamer.cpp" +"editor/editorScatter.cpp" "editor/editorOrthophoto.cpp" "editor/editorHttp.cpp" "editor/editorNmt.cpp" @@ -359,6 +371,7 @@ set(SOURCES "application/editormodelineside.cpp" "application/editormodevehicle.cpp" "application/editormodeselection.cpp" +"application/editormodebrush.cpp" "application/editormodetracknames.cpp" "application/editormodeviewport.cpp" "application/editormodefields.cpp" @@ -419,7 +432,6 @@ set(SOURCES "${DEPS_DIR}/glad/src/glad.c" "${DEPS_DIR}/dds-ktx/src/dds-ktx.c" -"${DEPS_DIR}/zstd/zstd.c" "gl/shader.cpp" "gl/vao.cpp" @@ -814,6 +826,7 @@ set(CORE_SOURCES "physics/components/fizsections.cpp" "physics/components/pneumatics.cpp" "physics/components/securitysystem.cpp" +"physics/components/snapshot.cpp" "physics/components/setup.cpp" "physics/components/traction.cpp" "physics/couplerphysics.cpp" @@ -823,6 +836,7 @@ set(CORE_SOURCES "vehicle/derailmotion.cpp" "world/TrackCheck.cpp" "world/SleeperPack.cpp" +"world/switchfork.cpp" "physics/oerlikonest.cpp" "utilities/logfiles.cpp" "utilities/parser.cpp" @@ -837,6 +851,8 @@ set(CORE_SOURCES "scripting/scriptscreenkernels.cpp" "scripting/scriptscreendrawing.cpp" "simulation/simulationtestrules.cpp" +"simulation/simulationsnapshot.cpp" +"simulation/simulationsnapshotmover.cpp" "vehicle/aipower.cpp" "vehicle/aiwire.cpp" "vehicle/blackbox.cpp" @@ -865,6 +881,11 @@ set(CORE_SOURCES "world/stationnames.cpp" "world/eventconditions.cpp" "utilities/wholefile.cpp" +# the E4D model format: the files, their checks and the data they carry, which the unit tests read and write too +"model/e4d/e4d_io.cpp" +"model/e4d/e4d_build.cpp" +"model/e4d/e4d_dump.cpp" +"${DEPS_DIR}/zstd/zstd.c" ) add_library(eu07_core STATIC ${CORE_SOURCES}) target_link_libraries(eu07_core PUBLIC eu07_settings) @@ -916,7 +937,8 @@ if (${CMAKE_CXX_COMPILER_ID} STREQUAL MSVC) # /wd4996: disable "deprecation" warnings # /wd4244: disable warnings for conversion with possible loss of data # /wd5033: disable because it is all over Python headers - target_compile_options(eu07_settings INTERFACE /wd4996 /wd4244 /wd5033) + # the sources are UTF-8, and so are the texts the game shows: without it the literals of the files with a BOM came out in the code page of the build machine + target_compile_options(eu07_settings INTERFACE /utf-8 /wd4996 /wd4244 /wd5033) set_target_properties(${PROJECT_NAME} PROPERTIES LINK_FLAGS "/LARGEADDRESSAWARE") endif() @@ -948,7 +970,7 @@ if(NOT ${CMAKE_VERSION} VERSION_LESS "3.16.0") endif() if (USE_LTO) - set_property(TARGET ${PROJECT_NAME} eu07_core PROPERTY INTERPROCEDURAL_OPTIMIZATION TRUE) + set_property(TARGET ${PROJECT_NAME} eu07_core PROPERTY INTERPROCEDURAL_OPTIMIZATION_RELEASE TRUE) endif() if (WITH_OPENVR) @@ -1196,8 +1218,10 @@ if(GENERATE_PDB) add_link_options(/DEBUG /MAP) # Ensure that the PCH is built with the correct runtime library for each configuration - set_target_properties(${PROJECT_NAME} eu07_core PROPERTIES - COMPILE_OPTIONS "$<$:/MDd>$<$:/MD>") + # added to the options the targets have, not put in their place: setting COMPILE_OPTIONS dropped /utf-8 and the rest + foreach(target ${PROJECT_NAME} eu07_core) + target_compile_options(${target} PRIVATE "$<$:/MDd>$<$:/MD>") + endforeach() else() # GCC/Clang (ensure -g is set for all configurations) add_compile_options(-g) diff --git a/EU07.cpp b/EU07.cpp index 6b7ed17b9..9111c8b91 100644 --- a/EU07.cpp +++ b/EU07.cpp @@ -50,6 +50,9 @@ Stele, firleju, szociu, hunter, ZiomalCl, OLI_EU and others int export_e3d_standalone(std::string in, std::string out, int flags, bool dynamic); int export_btf_standalone(std::string in, std::string out); +namespace e4d { +int run_command_line(int Argc, char *Argv[]); +} int generate_nodebank_previews(int Argc, char *Argv[]); #include @@ -146,6 +149,14 @@ int main(int argc, char *argv[]) int dynamic = std::stoi(std::string(argv[5])); exitcode = export_e3d_standalone(in, out, flags, dynamic); } + // standalone conversion, listing and checking of E4D models: -e4d convert|dump|validate ... + else if (argc >= 2 && std::string(argv[1]) == "-e4d") + { + auto const result{e4d::run_command_line(argc, argv)}; + fflush(stdout); + fflush(stderr); + std::_Exit(result); + } // standalone generation of preview images of the node bank models: -generate-nodebank-previews [options] else if (argc >= 2 && std::string(argv[1]) == "-generate-nodebank-previews") { diff --git a/application/application.cpp b/application/application.cpp index fa74c3d7d..36133c53c 100644 --- a/application/application.cpp +++ b/application/application.cpp @@ -37,6 +37,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/dictionary.h" #include "version_info.h" #include "simulation/simulationtest.h" +#include "simulation/simulationsnapshotworld.h" #include "utilities/physicslog.h" #include #include @@ -922,6 +923,9 @@ void eu07_application::exit() auto const step = [closing](char const *What) { WriteLog(std::format("Closing: {} at {} ms", What, std::chrono::duration_cast(std::chrono::steady_clock::now() - closing).count())); }; + // the files found in another case, counted over the whole run: the vehicles, sounds and textures loaded after the scenery + // count as well as those loaded with it + LogFilesInAnotherCase(); step("the sleepers laid in the background"); // the sleepers laid in the background read the scenery, which goes below track_sleepers::stop_background(); @@ -991,7 +995,7 @@ void eu07_application::render_ui() return; } - if (m_modestack.empty()) + if (m_modestack.empty() || Global.test.enabled) { return; } @@ -1002,7 +1006,9 @@ void eu07_application::render_ui() void eu07_application::begin_ui_frame() { - if (m_modestack.empty()) + // in the test mode nobody sees the window (hidden, the null renderer): no ui frames, whose start polled the window, + // the mouse and the gamepads every frame through imgui's glfw backend + if (m_modestack.empty() || Global.test.enabled) { return; } @@ -1398,7 +1404,8 @@ int eu07_application::init_settings(int Argc, char *Argv[]) // a test run is known before the rest of the command line is read (Global.test.enabled, see init()), so a // command line it can't take ends with the error code of the test, not with 0, which would pass it - auto const testcommandline{simulation::parse_test_command_line(std::vector(Argv, Argv + Argc))}; + std::vector const arguments(Argv, Argv + Argc); + auto const testcommandline{simulation::parse_test_command_line(arguments)}; if (false == testcommandline.error.empty()) { simulation::test().conclude(simulation::test_result::error, testcommandline.error); @@ -1415,6 +1422,15 @@ int eu07_application::init_settings(int Argc, char *Argv[]) Global.test.wall_timeout_from_command_line = true; } + // the simulation snapshots to load and to take (--load-snapshot, --snapshot-at) + auto const snapshotcommandline{simulation::snapshot::parse_command_line(arguments)}; + if (false == snapshotcommandline.error.empty()) + { + std::cerr << snapshotcommandline.error << std::endl; + simulation::test().conclude(simulation::test_result::error, snapshotcommandline.error); + return -1; + } + fs::path iniPath = user_config_path("eu07.ini"); // a test reads the settings of the game folder only (and those given with -ini), not the player's own @@ -1435,6 +1451,8 @@ int eu07_application::init_settings(int Argc, char *Argv[]) // process command line arguments bool sceneryfromcommandline{false}; bool editwithoutscenery{false}; + bool seedfromcommandline{false}; + bool vehiclefromcommandline{false}; for (int i = 1; i < Argc; ++i) { @@ -1453,6 +1471,7 @@ int eu07_application::init_settings(int Argc, char *Argv[]) if (i + 1 < Argc) { Global.local_start_vehicle = ToLower(Argv[++i]); + vehiclefromcommandline = true; } } else if (token == "-edit") @@ -1479,6 +1498,7 @@ int eu07_application::init_settings(int Argc, char *Argv[]) { Global.random_seed = *seed; Global.random_seed_given = true; + seedfromcommandline = true; WriteLog(std::format("seed given on the command line: {} -> {}", Argv[i], Global.random_seed)); } } @@ -1493,6 +1513,11 @@ int eu07_application::init_settings(int Argc, char *Argv[]) // taken from the command line above, with its value ++i; } + else if (token == "--load-snapshot" || token == "--snapshot-at" || token == "--load-snapshot-force") + { + // taken from the command line above, with their values + i += simulation::snapshot::option_value_count(token); + } else if (token == "-ini") { // extra settings file read on top of eu07.ini, so a run can override a few keys @@ -1510,7 +1535,8 @@ int eu07_application::init_settings(int Argc, char *Argv[]) << " [-edit [sceneryfilepath]]" << " [-seed number|word]" << " [-ini settingsfile]" - << " [--test [--test-timeout seconds] [--test-wall-timeout seconds]]" << std::endl; + << " [--test [--test-timeout seconds] [--test-wall-timeout seconds]]" + << " [--load-snapshot file [--load-snapshot-force]] [--snapshot-at seconds file]" << std::endl; simulation::test().conclude(simulation::test_result::error, std::format("unknown command line argument {}", token)); return -1; } @@ -1518,6 +1544,18 @@ int eu07_application::init_settings(int Argc, char *Argv[]) if (editwithoutscenery && false == sceneryfromcommandline) Global.SceneryFile.clear(); + simulation::snapshot::request(snapshotcommandline); + // the scenery of a snapshot loads the way it did when the snapshot was taken only with the seed it had then + if (auto const seed{simulation::snapshot::requested_seed()}; seed.has_value() && false == seedfromcommandline) + { + Global.random_seed = *seed; + Global.random_seed_given = true; + WriteLog(std::format("seed taken from the snapshot to load: {}", Global.random_seed)); + } + // and the player goes on in the vehicle they were in + if (auto const vehicle{simulation::snapshot::requested_player_vehicle()}; false == vehicle.empty() && false == vehiclefromcommandline) + Global.local_start_vehicle = vehicle; + if (Global.test.enabled) { if (false == sceneryfromcommandline || Global.SceneryFile.empty()) diff --git a/application/drivermode.cpp b/application/drivermode.cpp index 6a28f2949..6c401a6a7 100644 --- a/application/drivermode.cpp +++ b/application/drivermode.cpp @@ -18,6 +18,7 @@ http://mozilla.org/MPL/2.0/. #include "simulation/simulationtime.h" #include "simulation/simulationenvironment.h" #include "simulation/simulationtest.h" +#include "simulation/simulationsnapshotworld.h" #include "simulation/blackboxrecorder.h" #include "scene/scene.h" #include "rendering/lightarray.h" @@ -365,6 +366,8 @@ bool driver_mode::update() { simulation::test().update(deltatime); } + // the frame is complete: the snapshots asked for at this time are taken (--snapshot-at) + simulation::snapshot::update(); } // render time routines follow: @@ -487,17 +490,24 @@ bool driver_mode::update() Timer::subsystem.switching.update(); Timer::subsystem.loop_audio.start(); - simulation::Region->update_sounds(); - if (Global.RailSinging) + // the test mode has no sound: the sounds of the scenery and of the vehicles aren't gone through. they draw from the local + // engine of Random() only (LocalRandom()), and clear the sound flags of the vehicles, which nothing else reads. nor do the rails sing + if (false == Global.test.enabled) { - m_railsinging.update(deltarealtime); + simulation::Region->update_sounds(); + if (Global.RailSinging) + { + m_railsinging.update(deltarealtime); + } } audio::renderer.update(Global.iPause ? 0.0 : deltarealtime); Timer::subsystem.loop_audio.stop(); // NOTE: particle system runs on simulation time, but needs actual camera position to determine how to update each particle source + // nor smoke in the test mode, which draws nothing: the particles draw from the local engine of Random() only Timer::subsystem.loop_particles.start(); - simulation::Particles.update(); + if (false == Global.test.enabled) + simulation::Particles.update(); Timer::subsystem.loop_particles.stop(); Timer::subsystem.loop_renderer_update.start(); @@ -565,6 +575,9 @@ void driver_mode::enter() Timer::ResetTimers(); + // the scenery is loaded and nothing runs yet: the state saved in a snapshot goes over it (--load-snapshot) + simulation::snapshot::start(); + if (Global.test.enabled) { // the test runs as fast as it can compute, in steps of fixed length, so that runs on different machines agree diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index ede3f887e..5747b8934 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -639,12 +639,13 @@ debug_panel::render() { render_section_developer(); // Developer tools #ifdef WITH_UART if(true == render_section( "UART", m_uartlines)) { - auto ports_num = static_cast(UartStatus.available_ports.size()); - auto avlports = new char*[ports_num]; - for (int i=0; i < ports_num; i++) { - avlports[i] = (char *) UartStatus.available_ports[i].c_str(); + // the names of the ports for the list, kept by the vector for the call only (they were leaked every frame) + std::vector avlports; + avlports.reserve(UartStatus.available_ports.size()); + for (auto const &port : UartStatus.available_ports) { + avlports.push_back(port.c_str()); } - ImGui::Combo("Port", &UartStatus.selected_port_index, avlports, ports_num); + ImGui::Combo("Port", &UartStatus.selected_port_index, avlports.data(), static_cast(avlports.size())); ImGui::Combo("Baud", &UartStatus.selected_baud_index, uart_baudrates_list, static_cast(uart_baudrates_list_num)); ImGui::Checkbox("Enabled", &UartStatus.enabled); } diff --git a/application/editormode.cpp b/application/editormode.cpp index 7c9231d2b..56c49521a 100644 --- a/application/editormode.cpp +++ b/application/editormode.cpp @@ -817,51 +817,6 @@ void editor_mode::snap_to_ground(scene::basic_node *node, bool const Alone, bool m_editor.translate(node, target, true); // true == apply the computed Y (free vertical move) } -void editor_mode::handle_brush_mouse_hold(int Action, int Button) -{ - auto const mode = ui()->mode(); - auto const rotation_mode = ui()->rot_mode(); - auto const fixed_rotation_value = ui()->rot_val(); - - if(mode != nodebank_panel::BRUSH) - return; - - GfxRenderer->Pick_Node_Callback( - [this, mode, rotation_mode, fixed_rotation_value, Action, Button](scene::basic_node * /*node*/) { - // picks are resolved a few frames later; drop the ones queued before the button went up, - // or for a press that turned out to belong to the UI - if (!mouseHold || !viewport_click()) - return; - - // spacing is measured in world space: the mouse offset is camera-relative and the camera may move mid-stroke - glm::dvec3 const newPos = Camera.Pos + clamp_mouse_offset_to_max(GfxRenderer->Mouse_Position()); - if (m_brush_has_last && glm::distance(newPos, oldPos) < ui()->getSpacing()) - return; - - // picked only when a placement is due, so a random pick from a set isn't drawn every tick - const std::string *src = ui()->get_active_node_template(); - if (!src || src->starts_with(editor_includes::directive_mark)) // scenery templates are placed one at a time - return; - - // NOTE: no name for what the brush puts in, as with thousands of nodes the names take their share of the time - // the scenery needs to load. a node which needs one, to be referred to by an event, gets it in the node properties - TAnimModel *cloned = simulation::State.create_model(*src, std::string{}, placement_on_ground(newPos)); - oldPos = newPos; - m_brush_has_last = true; - if (!cloned) - return; - - apply_rotation_for_new_node(cloned, rotation_mode, fixed_rotation_value); - - std::string as_text; - cloned->export_as_text(as_text); - push_snapshot(cloned, EditorSnapshot::Action::Add, as_text); - - m_node = cloned; - ui()->set_node(m_node); - }); -} - void editor_mode::add_to_hierarchy(scene::basic_node *node) { if (!node) return; @@ -1034,6 +989,8 @@ void editor_mode::restore_terrain(EditorSnapshot &Snapshot) void editor_mode::undo_last() { + // Ctrl+Z with the brush still held: the stroke so far is a step of its own, the one taken back, and the dabs stop there + end_brush_stroke(); first_step_done(first_step::undo); // the warning by the cursor told of the step taken back now: "Ctrl+Z takes it back" is done ui()->drop_refusal(); @@ -1237,6 +1194,8 @@ void editor_mode::redo_last() m_history_busy = true; terrain_history_step(); m_history_busy = false; + // Ctrl+Y with the brush still held: the stroke is over and the dabs stop, its step stays as it is + end_brush_stroke(); // the first of the changes made together is on the top, the others follow it std::vector touched; do @@ -1520,6 +1479,11 @@ bool editor_mode::update() if(ui()->mode() == nodebank_panel::BRUSH) handle_brush_mouse_hold(GLFW_REPEAT, GLFW_MOUSE_BUTTON_LEFT); } + else + { + // the button let go: the stroke's models make one step of the history + end_brush_stroke(); + } // decelerate camera velocity with thresholding Camera.Velocity *= 0.65f; @@ -1741,6 +1705,9 @@ bool editor_mode::update() // --- area fill: outline overlay while the mode is active (its settings are drawn in the node bank window) --- if (ui()->mode() == nodebank_panel::FILL) draw_area_fill_outline(); + // --- the brush of models: the cross on the ground under the cursor, the circle of the brush of many --- + if (ui()->mode() == nodebank_panel::BRUSH && false == ImGui::GetIO().WantCaptureMouse) + draw_brush_cursor(); background->PopClipRect(); draw_ortho_compass(); @@ -8055,6 +8022,12 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in area_finish(false); break; } + // the line of the brush being clicked given up + if (is_press(Action) && brush_on_line() && false == m_brush_line.empty()) + { + m_brush_line.clear(); + break; + } // area fill: the outline dropped, an area picked up for a change left as it was if (is_press(Action) && ui()->mode() == nodebank_panel::FILL && false == ImGui::GetIO().WantTextInput && (false == m_fill_points.empty() || false == m_fill_editing.empty())) { @@ -8154,6 +8127,9 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in // area fill: remove the last outline point if (is_press(Action) && ui()->mode() == nodebank_panel::FILL && !m_fill_points.empty()) m_fill_points.pop_back(); + // the line of the brush: the last point taken back + if (is_press(Action) && brush_on_line() && false == m_brush_line.empty()) + m_brush_line.pop_back(); if (is_press(Action) && ui()->mode() == nodebank_panel::TRACK && m_lay.active && !m_lay.points.empty()) lay_back(); if (is_press(Action) && m_route.trace.active && route_active() && !m_route.trace.points.empty()) @@ -8180,6 +8156,9 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in } if (is_press(Action) && ui()->mode() == nodebank_panel::TRACK && m_lay.active) lay_enter(); + // the models of the brush put along the line clicked + if (is_press(Action) && brush_on_line() && false == m_brush_line.empty()) + brush_line_finish(); if (is_press(Action) && m_route.trace.active && route_active()) route_trace_end(true); break; @@ -8338,6 +8317,14 @@ void editor_mode::on_mouse_button(int const Button, int const Action, int const mouseHold = true; m_brush_has_last = false; // every brush stroke starts with a placement + // the brush puts models, it doesn't select + if (mode == nodebank_panel::BRUSH) + { + brush_press(); + m_input.mouse.button(Button, Action); + return; + } + // in area fill mode the left button only adds outline points, it doesn't touch the selection if (mode == nodebank_panel::FILL) { @@ -8684,7 +8671,8 @@ void editor_mode::starter_trainset(std::vector &Trailing) auto const &layer{scene::Layers.layer(static_cast(handle))}; if (layer.created) continue; - std::ifstream input{Global.asCurrentSceneryPath + layer.name, std::ios_base::binary}; + // the file as it's named on the disk, as node_layers::path() reads it + std::ifstream input{FileOnDisk(Global.asCurrentSceneryPath + layer.name), std::ios_base::binary}; std::string const content{std::istreambuf_iterator(input), std::istreambuf_iterator()}; if (std::regex_search(content, trainset)) return; diff --git a/application/editormode.h b/application/editormode.h index ad09e9d5e..1a4e59186 100644 --- a/application/editormode.h +++ b/application/editormode.h @@ -9,6 +9,8 @@ http://mozilla.org/MPL/2.0/. #pragma once +#include + #include "application/applicationmode.h" #include "application/editoruipanels.h" #include "input/editormouseinput.h" @@ -44,6 +46,7 @@ http://mozilla.org/MPL/2.0/. #include "editor/editorKilometrage.hpp" #include "editor/editorSpeed.hpp" #include "editor/editorRoad.hpp" +#include "editor/editorScatter.hpp" #include "editor/editorProfile.hpp" #include "editor/editorGroundFollow.hpp" #include "editor/editorInfra.hpp" @@ -215,6 +218,27 @@ class editor_mode : public application_mode, private editor_track::observer, pri void restore_kilometrage(EditorSnapshot &Snapshot); bool m_history_busy{false}; // undo or redo under way void handle_brush_mouse_hold(int Action, int Button); + // the brush of models (editormodebrush.cpp): the press starts a stroke of many, or puts one model; the point on the ground under + // the cursor, the height of the ground near a height, a model of the template the brush paints, turned and scaled as it says + void brush_press(); + void end_brush_stroke(); + void draw_brush_cursor(); + bool brush_ground(glm::dvec3 &Point); + double brush_height(glm::dvec2 const &Point, double Around); + // one dab of the stroke of many models, at the cursor on the ground + void brush_dab(); + // the step of the history of the stroke going on, looked up by its serial; Make: made if the stroke has none yet, with its + // first model. nullptr: the stroke has no step (yet, or any more) + EditorSnapshot *brush_step(bool Make); + // the places (x, z) of the models of the scene within Reach of Centre + std::vector brush_standing(glm::dvec2 const &Centre, double Reach) const; + // the many along a line: a point of it at the cursor, the models put along it, the line and its band drawn on the ground + // the brush is the one of many models along a line: the keys of the line (Enter, Backspace, Esc) are its + bool brush_on_line() const; + void brush_line_point(); + void brush_line_finish(); + void draw_brush_line(glm::dvec3 const *Cursor); + TAnimModel *place_brush_model(glm::dvec3 const &At, float Scale = 1.0f); void apply_rotation_for_new_node(scene::basic_node *node, int rotation_mode, float fixed_rotation_value); // members state_backup m_statebackup; // helper, cached variables to be restored on mode exit @@ -243,8 +267,13 @@ class editor_mode : public application_mode, private editor_track::observer, pri std::vector> m_retired; // models replaced after changes of includes, with the frames left until they're destroyed bool m_takesnapshot{true}; // helper, hints whether snapshot of selected node(s) should be taken before modification bool m_dragging = false; - glm::dvec3 oldPos; // world position of the last brush placement - bool m_brush_has_last{false}; // false at the start of a brush stroke, so the first placement ignores spacing + glm::dvec3 oldPos; // world position of the last dab of the brush + bool m_brush_has_last{false}; // false at the start of a brush stroke, so the first dab ignores the step + bool m_brush_stroke{false}; // a stroke of the brush of many models is on + std::uint64_t m_brush_step{0}; // the serial of the step of the history the stroke puts its models into, 0 before its first model + scatter::stroke m_brush_done; // what the stroke has done so far: the places of its models and the circles of its dabs + std::vector m_brush_line; // the points of the line the brush of many puts models along, in the order clicked + std::mt19937 m_brush_random{std::random_device{}()}; // NOSONAR(cpp:S2245) where the brush puts models, not security bool m_draw_cursor{false}; // the cursor drawn into the picture (View menu), on only while the editor is bool mouseHold{false}; float kMaxPlacementDistance = 200.0f; diff --git a/application/editormodebrush.cpp b/application/editormodebrush.cpp new file mode 100644 index 000000000..0558ce4e7 --- /dev/null +++ b/application/editormodebrush.cpp @@ -0,0 +1,355 @@ +/* +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/. +*/ + +// the brush of models of the Surroundings: one model where clicked, or many in a circle along the path of the cursor + +#include "stdafx.h" + +#include "application/editormode.h" +#include "application/editorprojection.h" +#include "application/editoruilayer.h" +#include "editor/editorFormat.hpp" +#include "editor/editorIncludeInfo.hpp" +#include "model/AnimModel.h" +#include "simulation/simulation.h" +#include "utilities/translation.h" + +#include +#include +#include +#include +#include +#include + +namespace +{ + +ImU32 constexpr kCrossColour{IM_COL32(255, 220, 70, 255)}; +ImU32 constexpr kCircleColour{IM_COL32(255, 220, 70, 170)}; +ImU32 constexpr kShadowColour{IM_COL32(0, 0, 0, 140)}; + +// the last press of the left button landed in the viewport, not on a window (see editormode.cpp) +bool viewport_click() +{ + return false == ImGui::GetIO().MouseDownOwned[0]; +} + +} // namespace + +bool editor_mode::brush_ground(glm::dvec3 &Point) +{ + if (false == cursor_on_ground(Point)) + return false; + // no further than things are placed at all + auto const offset{Point - glm::dvec3{Camera.Pos}}; + Point = placement_on_ground(glm::dvec3{Camera.Pos} + clamp_mouse_offset_to_max(offset)); + return std::isfinite(Point.x) && std::isfinite(Point.y) && std::isfinite(Point.z); +} + +double editor_mode::brush_height(glm::dvec2 const &Point, double const Around) +{ + if (double height{Around}; m_streamer.active() && m_streamer.height_at(Point.x, Point.y, height)) + return height; + return placement_on_ground({Point.x, Around, Point.y}).y; +} + +TAnimModel *editor_mode::place_brush_model(glm::dvec3 const &At, float const Scale) +{ + auto const *source{ui()->get_active_node_template()}; + // the scenery templates are put one at a time with the insert mode + if (source == nullptr || source->starts_with(editor_includes::directive_mark)) + return nullptr; + // NOTE: no name, as with thousands of nodes the names take their share of the time the scenery needs to load. a node which + // needs one, to be referred to by an event, gets it in the node properties + auto *model{simulation::State.create_model(*source, std::string{}, At)}; + if (model == nullptr) + return nullptr; + auto const look{scatter::pick(ui()->brush().look, m_brush_random)}; + m_editor.rotate(model, look.angles, 0.0f); + model->Scale(model->Scale() * look.scale * Scale); + add_to_hierarchy(model); + return model; +} + +void editor_mode::brush_press() +{ + mouseHold = true; + m_brush_has_last = false; + m_brush_done = {}; + auto const &settings{ui()->brush()}; + if (settings.way != brush_object_list::kind::single && settings.stroke == brush_object_list::shape::along_line) + { + // a point of the line, read once the renderer has the depth under the cursor + GfxRenderer->Pick_Node_Callback([this](scene::basic_node * /*node*/) { brush_line_point(); }); + return; + } + if (settings.way != brush_object_list::kind::single) + { + // one step of the history for the whole stroke, made when its first model is put (brush_step()): a press which puts + // nothing, on the sky or with no model chosen, leaves the history and the steps to redo as they were + m_brush_stroke = true; + m_brush_step = 0; + return; + } + // the point is read once the renderer has the depth under the cursor of the press + GfxRenderer->Pick_Node_Callback([this](scene::basic_node * /*node*/) { + if (false == viewport_click()) + return; + glm::dvec3 at; + if (false == brush_ground(at)) + return; + auto *model{place_brush_model(at)}; + if (model == nullptr) + return; + std::string text; + model->export_as_text(text); + push_snapshot(model, EditorSnapshot::Action::Add, text); + m_node = model; + ui()->set_node(m_node); + }); +} + +void editor_mode::handle_brush_mouse_hold(int /*Action*/, int /*Button*/) +{ + if (ui()->mode() != nodebank_panel::BRUSH || false == m_brush_stroke) + return; + GfxRenderer->Pick_Node_Callback([this](scene::basic_node * /*node*/) { brush_dab(); }); +} + +void editor_mode::brush_dab() +{ + // picks are resolved a few frames later; drop the ones queued before the button went up, or for a press that turned out + // to belong to the UI + if (false == mouseHold || false == m_brush_stroke || false == viewport_click()) + return; + // the step the stroke fills is gone from the history (taken back, or pushed out by the steps made since): the stroke is over + if (m_brush_step != 0 && brush_step(false) == nullptr) + { + m_brush_stroke = false; + m_brush_step = 0; + return; + } + glm::dvec3 centre; + if (false == brush_ground(centre)) + return; + auto const &settings{ui()->brush().dab}; + // the next dab once the cursor went far enough, measured on the ground, whatever the camera does meanwhile + if (m_brush_has_last && glm::distance(glm::dvec2{centre.x, centre.z}, glm::dvec2{oldPos.x, oldPos.z}) < scatter::dab_step(settings)) + return; + oldPos = centre; + m_brush_has_last = true; + // the dab goes to what the stroke has done: its circle isn't filled again, and its places are taken whether a model stands + // there or failed, so it isn't tried there on every move. the uniform fill is also told of the models which stand there + // already: its grid is fixed to the world, and a second stroke over the same ground would put every model again + std::vector standing; + if (settings.mode == scatter::fill::uniform) + standing = brush_standing({centre.x, centre.z}, std::max(0.1, settings.radius) + std::max(0.05, settings.spacing)); + auto const points{scatter::dab({centre.x, centre.z}, settings, m_brush_done, m_brush_random, standing)}; + if (auto const cut_short{settings.mode != scatter::fill::uniform && scatter::dab_wanted(settings) > scatter::dab_most}; cut_short || static_cast(points.size()) >= scatter::dab_most) + ui()->set_status(format(STR_C("Brush: a dab puts %d models at most; widen the spacing or narrow the circle for the rest"), scatter::dab_most)); + for (auto const &point : points) + { + auto *model{place_brush_model({point.x, brush_height(point, centre.y), point.y})}; + if (model == nullptr) + continue; + // the step of the stroke is looked up by its serial for each model, never taken for the last one of the history: a + // step another key pushed while the button is held (Del) doesn't get the models of the stroke + auto *stroke{brush_step(true)}; + // there is one: a stroke whose step is gone ended before the dab, and a step is made with the first model otherwise + if (stroke == nullptr) + continue; + EditorSnapshot::array_copy copy; + copy.model = model; + copy.uuid = model->uuid; + stroke->layer = model->layer(); + stroke->copies.push_back(std::move(copy)); + } +} + +editor_mode::EditorSnapshot *editor_mode::brush_step(bool const Make) +{ + if (m_brush_step != 0) + { + // from the end: the step of the stroke is the last one, or among the last + auto const found{std::ranges::find_if(m_history.rbegin(), m_history.rend(), [this](EditorSnapshot const &Step) { return Step.serial == m_brush_step; })}; + // none when the step is gone from the history (taken back, or pushed out by the steps made since): brush_dab() ends the + // stroke then, before the models of the dab + return found != m_history.rend() ? std::to_address(found) : nullptr; + } + if (false == Make) + return nullptr; + trim_history(); + EditorSnapshot stroke; + stroke.action = EditorSnapshot::Action::Array; + m_brush_step = stroke.serial; + m_history.push_back(std::move(stroke)); + g_redo.clear(); + return &m_history.back(); +} + +std::vector editor_mode::brush_standing(glm::dvec2 const &Centre, double const Reach) const +{ + std::vector standing; + for (auto const *model : simulation::Instances.sequence()) + { + if (model == nullptr) + continue; + auto const &at{model->location()}; + if (glm::dvec2 const place{at.x, at.z}; glm::distance(place, Centre) <= Reach) + standing.push_back(place); + } + return standing; +} + +void editor_mode::end_brush_stroke() +{ + if (false == m_brush_stroke) + return; + m_brush_stroke = false; + // nothing put: the stroke made no step; or its step is gone from the history already + auto const *step{brush_step(false)}; + m_brush_step = 0; + if (step == nullptr) + return; + ui()->set_status(format(STR_C("Brush: %zu models put; Ctrl+Z takes the whole stroke back"), step->copies.size())); +} + +bool editor_mode::brush_on_line() const +{ + auto const &settings{ui()->brush()}; + return ui()->mode() == nodebank_panel::BRUSH && settings.way == brush_object_list::kind::multi && settings.stroke == brush_object_list::shape::along_line; +} + +void editor_mode::brush_line_point() +{ + if (false == viewport_click()) + return; + glm::dvec3 at; + if (false == brush_ground(at)) + return; + // a double-click on the last point gives it twice: one is enough + if (false == m_brush_line.empty() && glm::distance(glm::dvec2{at.x, at.z}, glm::dvec2{m_brush_line.back().x, m_brush_line.back().z}) < 0.1) + return; + m_brush_line.push_back(at); +} + +void editor_mode::brush_line_finish() +{ + if (m_brush_line.size() < 2) + { + ui()->set_status(STR_C("Brush: a line needs two points at least")); + return; + } + auto const &settings{ui()->brush()}; + auto const places{scatter::along(m_brush_line, settings.line, m_brush_random)}; + // the whole line one step of the history, as a stroke is + EditorSnapshot step; + step.action = EditorSnapshot::Action::Array; + for (auto const &place : places) + { + auto *model{place_brush_model({place.point.x, brush_height(place.point, place.height), place.point.y}, scatter::side_scale(settings.line, place.side))}; + if (model == nullptr) + continue; + EditorSnapshot::array_copy copy; + copy.model = model; + copy.uuid = model->uuid; + step.layer = model->layer(); + step.copies.push_back(std::move(copy)); + } + m_brush_line.clear(); + auto const count{step.copies.size()}; + if (count == 0) + { + ui()->set_status(STR_C("Brush: no models put along the line")); + return; + } + trim_history(); + m_history.push_back(std::move(step)); + g_redo.clear(); + if (static_cast(places.size()) >= scatter::line_most) + ui()->set_status(format(STR_C("Brush: %zu models put along the line, the most one line puts; Ctrl+Z takes them back"), count)); + else + ui()->set_status(format(STR_C("Brush: %zu models put along the line; Ctrl+Z takes them back"), count)); +} + +void editor_mode::draw_brush_line(glm::dvec3 const *Cursor) +{ + if (m_brush_line.empty()) + return; + screen_projection const view; + auto *drawlist{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())}; + auto const width{std::max(0.0, ui()->brush().line.width)}; + auto const lifted = [](glm::dvec3 const &Point) { return Point + glm::dvec3{0.0, 0.05, 0.0}; }; + auto const side = [this, &lifted](glm::dvec3 const &Point, glm::dvec2 const &Offset) { + glm::dvec2 const at{Point.x + Offset.x, Point.z + Offset.y}; + return lifted({at.x, brush_height(at, Point.y), at.y}); + }; + for (std::size_t i = 1; i < m_brush_line.size(); ++i) + { + auto const &a{m_brush_line[i - 1]}; + auto const &b{m_brush_line[i]}; + view.line(drawlist, lifted(a), lifted(b), kShadowColour, 4.0f); + view.line(drawlist, lifted(a), lifted(b), kCrossColour, 2.0f); + // the edges of the band, piece by piece + glm::dvec2 const run{b.x - a.x, b.z - a.z}; + auto const length{glm::length(run)}; + if (width <= 0.0 || length <= 0.0) + continue; + auto const normal{glm::dvec2{-run.y, run.x} * (width / length)}; + view.line(drawlist, side(a, normal), side(b, normal), kCircleColour, 1.5f); + view.line(drawlist, side(a, -normal), side(b, -normal), kCircleColour, 1.5f); + } + // the piece the next click would add + if (Cursor != nullptr) + view.line(drawlist, lifted(m_brush_line.back()), lifted(*Cursor), kCircleColour, 1.5f); + for (auto const &point : m_brush_line) + { + if (ImVec2 screen; view.project(lifted(point), screen)) + drawlist->AddCircleFilled(screen, 4.0f, kCrossColour); + } +} + +void editor_mode::draw_brush_cursor() +{ + auto const &settings{ui()->brush()}; + auto const many{settings.way == brush_object_list::kind::multi}; + auto const on_line{many && settings.stroke == brush_object_list::shape::along_line}; + glm::dvec3 centre; + auto const on_ground{brush_ground(centre)}; + if (on_line) + draw_brush_line(on_ground ? ¢re : nullptr); + if (false == on_ground) + return; + screen_projection const view; + auto *drawlist{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())}; + // the cross on the ground, as large as a tenth of the circle (a metre for the single model), between 0.5 and 3 m + auto const arm{std::clamp(many && false == on_line ? 0.1 * settings.dab.radius : 1.0, 0.5, 3.0)}; + auto const ground = [&](double const X, double const Z) { return glm::dvec3{X, brush_height({X, Z}, centre.y) + 0.05, Z}; }; + std::array, 2> const arms{std::make_pair(ground(centre.x - arm, centre.z), ground(centre.x + arm, centre.z)), + std::make_pair(ground(centre.x, centre.z - arm), ground(centre.x, centre.z + arm))}; + for (auto const &[a, b] : arms) + { + view.line(drawlist, a, b, kShadowColour, 4.0f); + view.line(drawlist, a, b, kCrossColour, 2.0f); + } + if (false == many || on_line) + return; + // the circle, laid on the ground + int constexpr pieces{64}; + auto const radius{std::max(0.1, settings.dab.radius)}; + auto previous{ground(centre.x + radius, centre.z)}; + for (int i = 1; i <= pieces; ++i) + { + auto const angle{2.0 * std::numbers::pi * i / pieces}; + auto const next{ground(centre.x + radius * std::cos(angle), centre.z + radius * std::sin(angle))}; + view.line(drawlist, previous, next, kShadowColour, 3.5f); + view.line(drawlist, previous, next, kCircleColour, 1.8f); + previous = next; + } +} diff --git a/application/editoruilayer.cpp b/application/editoruilayer.cpp index 42a3d6289..b1a808f56 100644 --- a/application/editoruilayer.cpp +++ b/application/editoruilayer.cpp @@ -712,9 +712,8 @@ void editor_ui::render_mode_options(nodebank_panel::edit_mode const Mode) break; } case nodebank_panel::BRUSH: - ImGui::TextDisabled(STR_C("Hold LMB: paint models along the cursor path")); + // the brush turns the models itself (Turn), the rotation settings of the insert mode don't apply to it m_brushobjects.render_options(m_nodebankpanel); - m_functionspanel.render_controls(); break; case nodebank_panel::FILL: if (m_filloptions) @@ -1162,9 +1161,9 @@ void editor_ui::set_mode(nodebank_panel::edit_mode const Mode) m_nodebankpanel.mode = Mode; m_nodebankpanel.is_open = true; } -float editor_ui::getSpacing() +brush_object_list const &editor_ui::brush() const { - return m_brushobjects.spacing; + return m_brushobjects; } functions_panel::rotation_mode editor_ui::rot_mode() diff --git a/application/editoruilayer.h b/application/editoruilayer.h index d7fc890e1..aedd34552 100644 --- a/application/editoruilayer.h +++ b/application/editoruilayer.h @@ -45,7 +45,8 @@ class editor_ui : public ui_layer const std::string *get_active_node_template(bool bypassRandom = false); nodebank_panel::edit_mode mode(); void set_mode(nodebank_panel::edit_mode const Mode); - float getSpacing(); + // the settings of the brush of models + brush_object_list const &brush() const; // node bank and model set access (set selection widgets, set contents) nodebank_panel &nodebank() { diff --git a/application/editoruipanels.cpp b/application/editoruipanels.cpp index 305508f4b..8e34d5126 100644 --- a/application/editoruipanels.cpp +++ b/application/editoruipanels.cpp @@ -27,6 +27,7 @@ http://mozilla.org/MPL/2.0/. #include "editor/editorSettings.hpp" #include "imgui/imgui_internal.h" +#include #include #include #include @@ -591,7 +592,19 @@ std::string *brush_object_list::GetRandomObject() void brush_object_list::render_options(nodebank_panel &Bank) { - ImGui::SliderFloat(STR_C("Spacing"), &spacing, 0.1f, 20.0f, "%.1f m"); + // one model at a click, or many in the circle while the button is held + auto many{way == kind::multi}; + if (ImGui::RadioButton(STR_C("Single model##brush"), false == many)) + way = kind::single; + ImGui::SameLine(); + if (ImGui::RadioButton(STR_C("Many models##brush"), many)) + way = kind::multi; + if (way == kind::single) + ImGui::TextDisabled("%s", STR_C("LMB: one model at the cross on the ground")); + else + render_dab(); + render_look(); + ImGui::Separator(); ImGui::Checkbox(STR_C("Random model from set"), &useRandom); if (false == useRandom) { @@ -610,6 +623,113 @@ void brush_object_list::render_options(nodebank_panel &Bank) } } +void brush_object_list::render_dab() +{ + auto on_line{stroke == shape::along_line}; + if (ImGui::RadioButton(STR_C("In a circle##brushshape"), false == on_line)) + stroke = shape::circle; + ImGui::SameLine(); + if (ImGui::RadioButton(STR_C("Along a line##brushshape"), on_line)) + stroke = shape::along_line; + if (stroke == shape::along_line) + { + render_line(); + return; + } + ImGui::TextDisabled("%s", STR_C("Hold LMB: models in the circle along the cursor's path; one Ctrl+Z takes the whole stroke back")); + if (auto radius{static_cast(dab.radius)}; ImGui::SliderFloat(STR_C("Radius##brush"), &radius, 0.5f, 100.0f, "%.1f m", ImGuiSliderFlags_Logarithmic | ImGuiSliderFlags_AlwaysClamp)) + dab.radius = radius; + std::array const fills{STR_C("Random, anywhere in the circle"), STR_C("Uniform (grid)"), STR_C("Feathered to the edge")}; + ImGui::SetNextItemWidth(220.0f); + if (int fillmode{static_cast(dab.mode)}; ImGui::Combo(STR_C("Fill##brush"), &fillmode, fills.data(), static_cast(fills.size()))) + dab.mode = static_cast(fillmode); + if (auto spacing{static_cast(dab.spacing)}; ImGui::SliderFloat(STR_C("Spacing##brush"), &spacing, 0.1f, 50.0f, "%.1f m", ImGuiSliderFlags_Logarithmic | ImGuiSliderFlags_AlwaysClamp)) + dab.spacing = spacing; + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", dab.mode == scatter::fill::uniform ? STR_C("The step of the grid the models stand on") : STR_C("The least distance between two models")); + if (dab.mode == scatter::fill::uniform) + return; + if (auto density{static_cast(dab.density)}; ImGui::SliderFloat(STR_C("Density##brush"), &density, 0.1f, 200.0f, STR_C("%.1f per 100 m²"), ImGuiSliderFlags_Logarithmic | ImGuiSliderFlags_AlwaysClamp)) + dab.density = density; + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", dab.mode == scatter::fill::feathered ? STR_C("How many models a 100 m² the middle of the stroke gets, fewer and fewer towards its edge, as many as the spacing lets in.\nGround the stroke has gone over gets no more when the cursor comes back over it") : + STR_C("How many models a 100 m² the ground under the stroke gets, as many as the spacing lets in.\nGround the stroke has gone over gets no more when the cursor comes back over it")); +} + +void brush_object_list::render_line() +{ + ImGui::TextDisabled("%s", STR_C("LMB: the points of the line; Enter puts the models, Backspace takes the last point back, Esc drops the line")); + if (auto width{static_cast(line.width)}; ImGui::SliderFloat(STR_C("Width each side##brushline"), &width, 0.0f, 100.0f, "%.1f m", ImGuiSliderFlags_AlwaysClamp)) + line.width = width; + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("How far to each side of the line the models go; 0: one row on the line itself")); + std::array const fills{STR_C("Regular, in rows"), STR_C("Irregular, anywhere in the band")}; + ImGui::SetNextItemWidth(220.0f); + if (int fillmode{static_cast(line.mode)}; ImGui::Combo(STR_C("Fill##brushline"), &fillmode, fills.data(), static_cast(fills.size()))) + line.mode = static_cast(fillmode); + auto const regular{line.mode == scatter::line_fill::regular}; + if (auto spacing{static_cast(line.spacing)}; ImGui::SliderFloat(STR_C("Spacing##brushline"), &spacing, 0.1f, 50.0f, "%.1f m", ImGuiSliderFlags_Logarithmic | ImGuiSliderFlags_AlwaysClamp)) + line.spacing = spacing; + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", regular ? STR_C("The step along the line and between the rows") : STR_C("The least distance between two models")); + if (regular) + { + if (auto jitter{static_cast(line.jitter * 100.0)}; ImGui::SliderFloat(STR_C("Irregularity##brushline"), &jitter, 0.0f, 50.0f, "%.0f%%", ImGuiSliderFlags_AlwaysClamp)) + line.jitter = jitter / 100.0; + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Each model moved off its place in the rows by up to this share of the spacing each way; 0: exactly in rows")); + } + else + { + if (auto density{static_cast(line.density)}; ImGui::SliderFloat(STR_C("Density##brushline"), &density, 0.1f, 200.0f, STR_C("%.1f per 100 m²"), ImGuiSliderFlags_Logarithmic | ImGuiSliderFlags_AlwaysClamp)) + line.density = density; + ImGui::Checkbox(STR_C("Fewer towards the edges##brushline"), &line.thin_out); + } + if (auto edge{static_cast(line.edge_scale)}; ImGui::SliderFloat(STR_C("Size at the edges##brushline"), &edge, 1.0f, 200.0f, "%.0f%%", ImGuiSliderFlags_AlwaysClamp)) + line.edge_scale = edge; + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("The size of the models at the edges of the band, as a share of their size on the line; between, it goes evenly from one to the other")); +} + +void brush_object_list::render_look() +{ + using enum scatter::vary; + ImGui::SeparatorText(STR_C("Turn##brush")); + auto turn_random{look.turn == random}; + if (ImGui::RadioButton(STR_C("Fixed##brushturn"), false == turn_random)) + look.turn = fixed; + ImGui::SameLine(); + if (ImGui::RadioButton(STR_C("Random##brushturn"), turn_random)) + look.turn = random; + if (look.turn == fixed) + ImGui::DragFloat3(STR_C("Angles x y z##brush"), &look.angles.x, 0.5f, -180.0f, 180.0f, "%.1f°", ImGuiSliderFlags_AlwaysClamp); + else + { + ImGui::DragFloat3(STR_C("Each way x y z##brushturn"), &look.angle_range.x, 0.5f, 0.0f, 180.0f, "±%.1f°", ImGuiSliderFlags_AlwaysClamp); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Each model turned by a random angle up to this much each way: x and z tilt it, y turns it round (180: any way)")); + } + ImGui::SeparatorText(STR_C("Scale##brush")); + auto size_random{look.size == random}; + if (ImGui::RadioButton(STR_C("Fixed##brushscale"), false == size_random)) + look.size = fixed; + ImGui::SameLine(); + if (ImGui::RadioButton(STR_C("Random##brushscale"), size_random)) + look.size = random; + if (look.size == fixed) + ImGui::DragFloat3(STR_C("Percent x y z##brush"), &look.scale.x, 0.5f, 1.0f, 1000.0f, "%.0f%%", ImGuiSliderFlags_AlwaysClamp); + else + { + ImGui::Checkbox(STR_C("The same on every axis##brush"), &look.same_scale); + if (look.same_scale) + ImGui::DragFloat(STR_C("Each way##brushscale"), &look.scale_range.x, 0.5f, 0.0f, 99.0f, "±%.0f%%", ImGuiSliderFlags_AlwaysClamp); + else + ImGui::DragFloat3(STR_C("Each way x y z##brushscale"), &look.scale_range.x, 0.5f, 0.0f, 99.0f, "±%.0f%%", ImGuiSliderFlags_AlwaysClamp); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Each model scaled by a random share up to this much each way from its own size")); + } +} + nodebank_panel::nodebank_panel(std::string const &Name, bool const Isopen) : ui_panel(Name, Isopen) { size_min = {100, 50}; diff --git a/application/editoruipanels.h b/application/editoruipanels.h index 4e6c4b493..a07d512ea 100644 --- a/application/editoruipanels.h +++ b/application/editoruipanels.h @@ -13,6 +13,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Classes.h" #include "editor/editorIncludeInfo.hpp" #include "editor/editorPreviews.hpp" +#include "editor/editorScatter.hpp" #include /* @@ -111,12 +112,37 @@ class brush_object_list public: void render_options(nodebank_panel &Bank); + // one model where clicked, or many in the circle of the brush while the button is held + enum class kind + { + single, + multi, + }; + // class use std::vector Objects; // manual list, used when source is set to manual std::string *GetRandomObject(); bool useRandom = {false}; model_set_ref source; - float spacing{1.0f}; + // the many put in the circle along the path of the cursor, or along a line clicked on the ground point by point + enum class shape + { + circle, + along_line, + }; + + kind way{kind::multi}; + shape stroke{shape::circle}; + scatter::dab_settings dab; // the circle of the many and how they fill it + scatter::line_settings line; // the band along the line and how it's filled + scatter::look_settings look; // the turn and the scale of each model + + private: + void render_look(); + // the settings of the stroke of many models + void render_dab(); + // the settings of the many along a line + void render_line(); }; class nodebank_panel : public ui_panel diff --git a/application/uilayer.cpp b/application/uilayer.cpp index c24291047..d74513205 100644 --- a/application/uilayer.cpp +++ b/application/uilayer.cpp @@ -440,7 +440,9 @@ bool ui_layer::init(GLFWwindow *Window) void ui_layer::shutdown() { - ImGui::EndFrame(); + // the frame begun last, if there was one: the test mode begins none (eu07_application::begin_ui_frame()) + if (GImGui != nullptr && GImGui->WithinFrameScope) + ImGui::EndFrame(); // the vulkan renderer is gone by now (its backend of imgui went with it) if (auto *renderer{GfxRenderer->GetImguiRenderer()}) diff --git a/audio/audio.cpp b/audio/audio.cpp index 04a61ee77..81fbdd011 100644 --- a/audio/audio.cpp +++ b/audio/audio.cpp @@ -382,7 +382,17 @@ audio::buffer_handle buffer_manager::emplace( std::string Filename ) { buffer_handle const handle { m_buffers.size() }; - if( true == Global.AudioAsyncLoad ) { + if( nullptr == ::alcGetCurrentContext() ) { + // no audio device (the sound off, as in a test run): the decoded samples would have nowhere to go, upload_sound() makes + // no buffer without a context. the file is found and its caption read, as with the device, but it isn't decoded: + // the decoding took a fifth of the loading of a scenery in a test run + WriteLog( "sound: loading file: " + Filename ); + openal_buffer buffer; + buffer.name = Filename; + buffer.fetch_caption(); + m_buffers.emplace_back( std::move( buffer ) ); + } + else if( true == Global.AudioAsyncLoad ) { // the file is decoded in the background, the AL buffer is made once the data is ready or when the buffer is needed WriteLog( "sound: loading file: " + Filename ); openal_buffer buffer; diff --git a/docs/behaviour-changes.md b/docs/behaviour-changes.md index 9877fb50e..6debedcab 100644 --- a/docs/behaviour-changes.md +++ b/docs/behaviour-changes.md @@ -112,6 +112,19 @@ existing data. `couplerphysics` (slack, hysteresis and breaking of the coupler; commits c85aab4f to 226155d4, no PR number) are off by default. - **Welded track buckles in the heat** (#378) when the scenery or an event sets it; no effect otherwise. +- **A vehicle off the track (`physics.derailment new`) slides less far and no longer falls through the ground** + (GH#556, #560). The friction on the ground goes from 0.3 to 0.45 on its wheels and from 0.5 to 0.7 on its side: an + EU07 overturning at 130 km/h stops some 140 m on instead of 170 m. Where the terrain of the scenery has no ground + under it (a hole, past what was gathered around it), the slope of the track bed ends 3 m under the ballast and the + vehicle keeps its height beyond it, rather than sinking under the terrain. Needs: nothing; `old` and `monitor` are + not affected. +- **The coupling of a vehicle off the track (`physics.derailment new`) pulls hook to hook** (GH#579). It drew the two + ends together along the line between the faces of their buffers, which for ends side by side, almost touching along + the track and 0.4 m apart across it, ran at 80-90 degrees to the vehicles: a coach derailing next to its neighbours + pulled them off across the rails. Now it pulls along the line between the headstocks behind the buffers, some 1.2 m + apart along, at about 18 degrees in that case. Notices: fewer neighbours pulled off by a coupling, more of the force + of the coupling along the vehicles, a derailed train folding a little less (19 of 32 scattered trains of the unit + test fold where 23 did). Needs: nothing; `old` and `monitor` are not affected. - **The cab shake is taken at the frame's moment** (#403, #414) and no longer moves in steps. - **Station names keep their Polish letters** in the interface and timetables, a W4 finds its station by one key (#418). A station of departure written in capitals is still a stop (#343). diff --git a/docs/e4d-format.md b/docs/e4d-format.md new file mode 100644 index 000000000..21c41a303 --- /dev/null +++ b/docs/e4d-format.md @@ -0,0 +1,229 @@ +# Format modeli E4D (`.e4d`) + +Następca E3D: w pełni binarny format modeli. Plik czyta się prawie bez przetwarzania, prosto do buforów OpenGL 4.6 i +Vulkana 1.4. Niesie węzły TRS, skinning, typowane komponenty i metadane węzłów oraz grup wierzchołków. Rozszerza się bez +podnoszenia wersji. Rekordy, rozmiary i offsety są w `model/e4d/e4d_format.h`, a `static_assert` pilnują, żeby kod i ten +opis się nie rozjechały. + +Stan: wersja 1.0, etap 1 (format, czytnik, pisarz, konwersja z E3D/T3D). Gra jeszcze nie wczytuje `.e4d`; to etap 2. + +## Zasady + +- **Little-endian.** Rekordy leżą w pliku tak, jak w pamięci, i tak trafiają do GPU. +- **Spis sekcji (TOC).** Każdą sekcję znajduje się przez spis, a nie przez przejście po kolejnych kawałkach. Czytnik może + wziąć tylko te sekcje, których potrzebuje. +- **Tablice z `stride`.** Sekcja z rekordami zaczyna się od `count` i `stride`. Nowa wersja dopisuje pola na końcu + rekordu: stary czytnik bierze znany prefiks, a nowy daje brakującym polom wartości domyślne. +- **Sekcje wymagane i opcjonalne.** Nieznaną sekcję opcjonalną czytnik pomija, a narzędzia przenoszą ją bez zmian. + Nieznana sekcja wymagana sprawia, że plik jest odrzucany z czytelnym komunikatem. +- **Wersja.** Wersja główna zmienia się tylko przy zmianie niezgodnej; czytnik odrzuca plik o wyższej wersji głównej. + Wersja poboczna oznacza nowe pola i sekcje, które starszy czytnik pomija. +- **Plik to dane niezaufane.** Czytnik sprawdza każdy offset, rozmiar, indeks, rodzica, joint i odwołanie, zanim + cokolwiek zostanie użyte (`e4d::validate`). +- **Semantyka w danych, nie w nazwach.** Role, strony pojazdu, warianty i sloty świateł są polami komponentów. Nazwy + zostają, żeby dzisiejsze `.mmd` i eventy działały bez zmian. + +## Nagłówek (64 B) + +| Offset | Typ | Pole | +|---|---|---| +| 0 | char × 4 | magic `E4D\0` | +| 4 | u16 × 2 | wersja główna (1), poboczna (0) | +| 8 | u32 | flagi: bit 0 = kolejność indeksów zoptymalizowana | +| 12 | u32 | liczba sekcji | +| 16 | u64 | offset spisu sekcji | +| 24 | u64 | rozmiar pliku | +| 32 | u64 | FNV-1a 64 bajtów od offsetu 64 do końca pliku | +| 40 | u64 | hash pliku źródłowego (eksporter i konwerter wiedzą, kiedy budować od nowa) | +| 48 | 16 B | zarezerwowane, zera | + +## Wpis spisu sekcji (32 B) + +| Typ | Pole | +|---|---| +| u32 | FourCC | +| u32 | flagi: bit 0 = wymagana, bit 1 = zstd | +| u64 | offset w pliku | +| u64 | rozmiar w pliku | +| u64 | rozmiar po rozpakowaniu | + +Sekcje są wyrównane do 16 B, a strumienie wierzchołków i indeksów do 64 B. Sekcja może być skompresowana zstd. Każda +sekcja występuje najwyżej raz. + +## Sekcje + +`[T]` oznacza tablicę: `u32 count`, `u32 stride`, potem `count` rekordów co `stride` bajtów. `[S]` oznacza surowy +strumień bez nagłówka: liczba elementów to rozmiar sekcji podzielony przez rozmiar elementu. + +| FourCC | Wym. | Postać | Zawartość | +|---|---|---|---| +| `STRS` | tak | — | `u32 count`, `u32 blob_size`, `count + 1` offsetów `u32`, blob UTF-8. String `i` to bajty `[offset[i], offset[i+1])`. | +| `NIDX` | nie | [T] 16 B | indeks nazw: `u64` FNV-1a 64 nazwy w ASCII małymi literami, `u32` węzeł, `u32` 0; posortowane po hashu, potem po węźle | +| `NODE` | tak | [T] 80 B | węzły | +| `XFRM` | nie | [T] 80 B | `u32` węzeł, 12 B zera, macierz 4×4 `f32` kolumnami: przekształcenie węzła, którego TRS nie opisze (ścinanie) | +| `MESH` | tak | [T] 16 B | `u32` pierwszy prymityw, `u32` liczba, `i32` skóra (−1), `u32` flagi (0x1: siatka używa `VUSR`) | +| `PRIM` | tak | [T] 48 B | prymitywy (rekordy rysowania) | +| `VPOS` | tak | [S] 12 B | pozycja `f32 × 3` | +| `VATT` | tak | [S] 16 B | QTangent `snorm16 × 4`, UV0 `f32 × 2` | +| `VSKN` | nie | [S] 8 B | jointy `u8 × 4`, wagi `unorm8 × 4` (suma 255) | +| `VSKW` | nie | [S] 16 B | jointy `u16 × 4`, wagi `unorm16 × 4` (suma 65535); zamiast `VSKN`, gdy skóra ma ponad 256 jointów | +| `VUSR` | nie | [S] 16 B | dane użytkownika `f32 × 4` (dzisiejsze `userdata`) | +| `VBND` | tak, gdy jest | [S] 4 B | przypisanie wierzchołka scalonego prymitywu: `u8` joint skóry prymitywu, `u8` slot światła, `u8` rola w slocie (0 brak, 1 zapalony, 2 zgaszony), `u8` 0. Pisarz oznacza go jako wymagany, bo bez niego scalone prymitywy rysują się źle | +| `IDX2` | nie | [S] 2 B | indeksy `u16`, lokalne względem `base_vertex` prymitywu | +| `IDX4` | nie | [S] 4 B | indeksy `u32`, jw. | +| `MATL` | tak | [T] 80 B | sloty materiałów | +| `SKIN` | nie | [T] 16 B | `u32` pierwszy joint w `SKJT`, `u32` liczba, `i32` węzeł korzenia, `u32` 0 | +| `SKJT` | nie | [T] 64 B | `u32` węzeł, 12 B zera, odwrotna macierz bindu 3×4 `f32` (cztery kolumny po trzy) | +| `VGRP` | nie | [T] 32 B | grupy wierzchołków | +| `VGIT` | nie | [S] 4 B | elementy grup: wierzchołki albo pary (pierwszy, liczba) | +| `VGWT` | nie | [S] 1 B | wagi `unorm8` elementów grup, które je mają | +| `CMPT` | nie | [T] 20 B | komponenty | +| `CDAT` | nie | — | dane komponentów | +| `BNDS` | nie | [T] 40 B | granice: `f32 × 3` min, `f32 × 3` max, sfera `f32 × 4`; jeden rekord na węzeł (geometria węzła w jego przestrzeni), ostatni dla całego modelu | +| `EDIT` | nie | [T] 16 B | `u32` ścieżka pliku źródłowego (string), `u32` narzędzie (string), 8 B zera | + +Wszystkie strumienie wierzchołków (`VPOS`, `VATT`, `VSKN`/`VSKW`, `VUSR`, `VBND`) mają tyle samo elementów: jeden na wierzchołek +pliku. Strumień skóry obejmuje więc też wierzchołki siatek sztywnych (z zerami; zstd je zjada). Do GPU trafiają tylko +zakresy siatek skinowanych. + +### Węzeł (80 B) + +| Offset | Typ | Pole | +|---|---|---| +| 0 | u32 | nazwa (string) | +| 4 | i32 | rodzic, −1 dla korzenia | +| 8 | u32 | koniec poddrzewa: indeks za ostatnim węzłem poddrzewa | +| 12 | u32 | flagi: bit 0 animowany, bit 1 ukryty, bit 2 przekształcenie w `XFRM` | +| 16 | f32 × 3 | translacja | +| 28 | f32 × 4 | obrót, kwaternion x y z w | +| 44 | f32 × 3 | skala | +| 56 | i32 | siatka, −1 bez siatki | +| 60 | u32 × 2 | komponenty węzła: pierwszy, liczba | +| 68 | f32 × 2 | kwadrat odległości od kamery: od, do (0 = bez ograniczenia) | +| 76 | u32 | `iFlags` submodelu E3D, z którego węzeł powstał; 0 w modelu nowym | + +Węzły leżą w porządku DFS: rodzic przed dziećmi, a poddrzewo zajmuje ciągły zakres `[węzeł, koniec poddrzewa)`. Dzieci +jednego rodzica są w kolejności rysowania. Macierze świata liczy się więc jedną pętlą od początku tablicy. Przekształcenie +węzła to T · R · S, chyba że ma flagę `XFRM`. + +### Prymityw (48 B) + +| Offset | Typ | Pole | +|---|---|---| +| 0 | u32 | pierwszy indeks w `IDX2`/`IDX4`; bez indeksów: pierwszy wierzchołek liczony od `base_vertex` | +| 4 | u32 | liczba indeksów; bez indeksów: liczba rysowanych wierzchołków | +| 8 | u32 | `base_vertex` w strumieniach | +| 12 | u32 | liczba wierzchołków prymitywu | +| 16 | u32 | materiał (slot `MATL`) | +| 20 | u32 | węzeł | +| 24 | i32 | skóra, −1 dla sztywnego | +| 28 | u32 | flagi: bity 0-3 topologia (wartości GL: 0 punkty, 1 linie, 2 pętla, 3 łamana, 4 trójkąty, 5 pas, 6 wachlarz); 0x10 indeksowany; 0x20 indeksy w `IDX4`; 0x40 przebieg nieprzezroczysty; 0x80 przebieg przezroczysty; 0x100 bez cienia; 0x200 sztywne jointy z `VBND`; 0x400 sloty świateł z `VBND`; bity 16-23 LOD | +| 32 | f32 × 4 | sfera w przestrzeni węzła | + +### Prymitywy scalone + +Dziś każda ruchoma część i każda lampa (`Light_On##` / `Light_Off##`) to osobny submodel, a więc osobny draw call w +każdym przebiegu. Model scenerii ze światłem albo animacją nie jest przy tym instancjonowany. E4D pozwala złożyć części +kilku węzłów o tym samym materiale w jeden prymityw: + +- **Sztywne jointy (0x200).** Każdy wierzchołek wskazuje w `VBND` joint skóry prymitywu (`skin` ≥ 0), z wagą 1. + Wierzchołki leżą w pozie bindu, tak jak w skinningu, a macierz to `świat(joint) · odwrotny bind(joint)`. Vertex shader + bierze ją z bufora póz instancji sam, bez przebiegu compute. Prymityw nie potrzebuje `VSKN`. Skóra ma najwyżej 256 + jointów; większą grupę narzędzie dzieli na kilka prymitywów. +- **Sloty świateł (0x400).** Wierzchołek wskazuje slot (`u8`, pole `slot` komponentu `LSLT`) i rolę: zapalony (świeci i + jest widoczny, gdy slot się świeci) albo zgaszony (widoczny, gdy slot jest zgaszony). Stan slotu leży w buforze stanów + instancji, więc model ze światłami da się instancjonować. Slotu, którego model nie ma, shader nie zapala. +- **Węzły zostają.** Scalenie przenosi tylko geometrię; węzły i ich nazwy zostają w `NODE`, więc `GetFromName`, `.mmd` i + eventy działają dalej. Ukrycie węzła (`visible`) to zerowa macierz jego jointu w buforze póz. +- Sfera prymitywu obejmuje pozę bindu. Runtime dla prymitywu z ruchomymi jointami bierze granice instancji. + +Łączy narzędzie (`optimize`), nie konwerter: łączy węzły nieanimowane i bez komponentów, a węzły, do których coś odwołuje +się po nazwie, zostawia jako jointy. Części przezroczyste, ze skórkami wymiennymi innymi niż reszta oraz z innym zakresem +widoczności nie są łączone. + +### Wierzchołek + +- Pozycja `f32 × 3` względem originu modelu. +- QTangent: kwaternion obrotu układu (T, B, N), w którym B = N × T. Kwaternion ma w ≥ 1/32767. Gdy bitangent jest + odwrócony (lustrzane UV, `tangent.w < 0` w `basic_vertex`), cały kwaternion jest zanegowany, więc w < 0. Dekodowanie: + N = trzecia kolumna, T = pierwsza, B = N × T · znak(w). +- UV0 `f32 × 2`; half traci precyzję przy teksturach powtarzanych setki razy. + +Rozmiar: 28 B (sztywny), 32 B (w prymitywie scalonym, z `VBND`), 36 B (skinowany), wobec 48 B `basic_vertex`. Przebieg +cieni czyta tylko `VPOS` (i `VBND` w prymitywach scalonych). + +### Materiał (80 B) + +| Offset | Typ | Pole | +|---|---|---| +| 0 | u32 | nazwa `.mat` albo tekstury (string); brak = tylko kolory | +| 4 | i32 | skórka wymienna −1..−4, 0 = stała | +| 8 | u32 | flagi | +| 12 | f32 | próg selfillum (`fLight` z E3D) | +| 16 | f32 × 4 × 4 | ambient, diffuse, specular, emission | + +### Grupa wierzchołków (32 B) + +`u32` nazwa, `u32` siatka, `u32` pierwszy element w `VGIT`, `u32` liczba elementów, `u32` flagi (0x1 elementy to +pary (pierwszy, liczba), 0x2 wagi w `VGWT`), `u32 × 2` komponenty grupy (pierwszy, liczba), `u32` 0. Indeksy wierzchołków +są w strumieniach pliku (bezwzględne). + +## Komponenty + +Rekord w `CMPT` (20 B): + +| Offset | Typ | Pole | +|---|---|---| +| 0 | u32 | typ (FourCC) | +| 4 | u16 | wersja danych | +| 6 | u8 | rodzaj celu: 0 model, 1 węzeł, 2 siatka, 3 grupa wierzchołków | +| 7 | u8 | flagi | +| 8 | u32 | indeks celu | +| 12 | u32 | offset danych w `CDAT` (wyrównany do 4) | +| 16 | u32 | rozmiar danych | + +Komponenty jednego węzła leżą obok siebie, a węzeł wskazuje swój zakres; tak samo grupa wierzchołków. Nieznany typ gra +pomija, a narzędzia przenoszą go bez zmian. Nowa wersja typu dopisuje pola na samym końcu danych, za listami, więc +starszy czytnik czyta swoją część od początku i pomija resztę. +Odwołania wewnątrz danych to indeksy: string, węzeł albo komponent; `0xFFFFFFFF` = brak. + +| Typ | Dane (wersja 1) | +|---|---| +| `PROP` | `u32 count`, potem rekordy 24 B: `u32` klucz (string), `u8` typ (0 bool, 1 int, 2 float, 3-5 vec2-4, 6 string, 7 węzeł, 8 komponent), 3 B zera, 16 B wartości | +| `SOCK` | gniazdo, 36 B: `u32` rola (string), `u8` strona (0 brak, 1 przód, 2 tył), `u8` 0, `u16` indeks, pozycja `f32 × 3`, obrót `f32 × 4` (w przestrzeni węzła) | +| `JOIN` | joint, 36 B: `u8` rodzaj (0 stały, 1 zawias, 2 kulisty, 3 przesuw, 4 śruba), `u8` czy ograniczony, `u16` 0, `u32` rola, oś `f32 × 3`, min, max, spoczynek, skok śruby (m na obrót) | +| `SPRG` | sprężyna, 52 B: `u8` tryb (0 follow, 1 stretch, 2 aim, 3 wahadło), `u8` ruch boczny, `u16` 0, kotwica A (węzeł, gniazdo), kotwica B (węzeł, gniazdo), oś `f32 × 3`, długość swobodna, skok min, max, długość wahadła, tłumienie wahadła | +| `CHAN` | łańcuch (wąż, kabel, miech), 32 B: `u8` rodzaj (0 wąż hamulcowy, 1 zasilający, 2 kabel, 3 miech, 4 inny), `u8` 0, `u16` liczba jointów, `i32` skóra, min. promień gięcia, sztywność, masa głowicy, długość sztywnej głowicy, gniazda końców A i B; potem węzły jointów `u32 × n` i długości segmentów `f32 × (n − 1)` | +| `VARI` | grupa wariantów: `u32` nazwa, `u16` liczba stanów, `u16` stan domyślny; stany po 12 B (`u32` nazwa, `u32` pierwszy, `u32` liczba węzłów), potem lista węzłów `u32` | +| `CHNL` | kanał sterowania: `u32` nazwa, `f32` min, max, wartość początkowa, `u16` liczba powiązań, `u16` 0; powiązania po 16 B: `u8` rodzaj (0 joint, 1 klip, 2 warianty, 3 slot światła), 3 B zera, `u32` komponent celu, `f32` skala, `f32` przesunięcie (wartość celu = kanał · skala + przesunięcie) | +| `LSLT` | slot światła: `u16` slot, `u16` 0, `f32` stan początkowy (kodowanie z eventu `lights`), kolor `f32 × 3` (ujemny: kolor źródeł), `u16` liczba węzłów zapalonych, zgaszonych, źródeł `LGHT`, `u16` 0; potem te trzy listy `u32` | +| `LGHT` | źródło światła, 52 B: `u8` rodzaj (0 punkt, 1 reflektor), `u8` flagi (0x1 shadeself, 0x2 bez cieni, 0x4 soft falloff, 0x8 tylko oświetlenie, 0x10 aureola), `u16` 0, kolor `f32 × 4`, natężenie, promień, aureola od, do, `i32` typ zaniku, promień zaniku, cos stożka, cos plamy | +| `EMIT` | emiter, 16 B: `u8` rodzaj (0 dym, 1 para, 2 iskry), 3 B zera, kierunek `f32 × 3` | +| `MREF` | model wpięty w węzeł, 12 B: ścieżka (string), gniazdo (komponent), skórka (string) | +| `COLL` | bryła, 48 B: `u8` kształt (0 prostopadłościan, 1 kula, 2 kapsuła), 3 B zera, `u32` rola, środek `f32 × 3`, obrót `f32 × 4`, półwymiary `f32 × 3` | +| `LANM` | animacja E3D (`TAnimType`): `u32` | +| `LTXT` | wyświetlacz tekstu E3D (`TP_TEXT`); dzieci węzła to znaki nazwane swoim znakiem. Bez danych. | +| `STAR` | gwiazdy E3D (`TP_STARS`): `u32 count`, potem kolory RGB `u32` (jak w E3D), po jednym na wierzchołek siatki węzła | + +## Konwersja z E3D i T3D + +`eu07 -e4d convert [dynamic]` wczytuje model istniejącym loaderem (jak `-e3d`) i zapisuje +go w E4D: + +- Submodel staje się węzłem. Kolejność dzieci i nazwy zostają, więc `GetFromName`, `.mmd` i eventy działają po staremu. +- Macierz submodelu jest rozkładana na TRS. Gdy TRS jej nie odtwarza (ścinanie), pełna macierz idzie do `XFRM`. +- `iFlags`, zakres widoczności i kolory zostają w węźle i w slocie materiału. +- `TP_FREESPOTLIGHT` → `LGHT`; `Light_On##` / `Light_Off##` → `LSLT`; `smokesource_*` → `EMIT`; animacja `anim:` → `LANM`; + `TP_TEXT` → `LTXT`; `TP_STARS` → `STAR`. +- Indeksy są zapisywane jako `u16`, gdy prymityw ma co najwyżej 65 536 wierzchołków (indeksy 0–65 535). +- Bity fazy rysowania (0x30) zgadnięte przy wczytaniu E3D z materiału nie trafiają do `legacy_flags` ani do flag prymitywu: + zgaduje je na nowo gra, z prawdziwym materiałem. Model pojazdu konwertuje się z `.e3d`, który robi z niego gra, nie z `.t3d`. +- Wymienna skóra `-k` w przebiegu przezroczystym (bit k−1 flag E3D) ma w `MATL` flagę `translucent`. + +Pozostałe polecenia: `eu07 -e4d dump ` (zawartość jako tekst) i `eu07 -e4d validate ` (sprawdzenie +pliku wraz z hashem zawartości). + +## Zgodność wstecz + +E3D i T3D są czytane jak dotąd. Gra zacznie wczytywać `.e4d` w etapie 2, i tylko wtedy, gdy plik istnieje, za +przełącznikiem w `eu07.ini`. Obecne wydanie nie czyta `.e4d`. diff --git a/editor/editorScatter.cpp b/editor/editorScatter.cpp new file mode 100644 index 000000000..d05149f7f --- /dev/null +++ b/editor/editorScatter.cpp @@ -0,0 +1,473 @@ +#include "stdafx.h" + +#include "editor/editorScatter.hpp" + +#include +#include +#include +#include +#include + +namespace scatter +{ + +namespace +{ + +// a setting typed into a field of the panel may be anything a float can hold, "inf" and "nan" too, and what the fields +// don't stop reaches here. one which isn't a finite number is the Fallback, a finite one is kept between Least and Most: far +// more than the panel offers, so within its ranges nothing changes, and no place or transform of a model comes out of a +// number which isn't one +double bounded(double const Value, double const Least, double const Most, double const Fallback) +{ + return std::isfinite(Value) ? std::clamp(Value, Least, Most) : Fallback; +} + +glm::vec3 bounded(glm::vec3 const &Value, float const Least, float const Most, float const Fallback) +{ + return {static_cast(bounded(Value.x, Least, Most, Fallback)), static_cast(bounded(Value.y, Least, Most, Fallback)), static_cast(bounded(Value.z, Least, Most, Fallback))}; +} + +double constexpr most_metres{1000.0}; // of a radius, a spacing or a width +double constexpr most_density{1.0e6}; + +dab_settings sane(dab_settings Settings) +{ + Settings.radius = bounded(Settings.radius, 0.0, most_metres, 0.0); + Settings.spacing = bounded(Settings.spacing, 0.0, most_metres, 0.0); + Settings.density = bounded(Settings.density, 0.0, most_density, 0.0); + return Settings; +} + +line_settings sane(line_settings Settings) +{ + Settings.width = bounded(Settings.width, 0.0, most_metres, 0.0); + Settings.spacing = bounded(Settings.spacing, 0.0, most_metres, 0.0); + Settings.jitter = bounded(Settings.jitter, 0.0, 0.5, 0.0); + Settings.density = bounded(Settings.density, 0.0, most_density, 0.0); + Settings.edge_scale = bounded(Settings.edge_scale, 1.0, 10000.0, 100.0); + return Settings; +} + +look_settings sane(look_settings Settings) +{ + Settings.angles = bounded(Settings.angles, -36000.0f, 36000.0f, 0.0f); + Settings.angle_range = bounded(Settings.angle_range, 0.0f, 36000.0f, 0.0f); + Settings.scale = bounded(Settings.scale, 1.0f, 100000.0f, 100.0f); + Settings.scale_range = bounded(Settings.scale_range, 0.0f, 10000.0f, 0.0f); + return Settings; +} + +bool clear_of(glm::dvec2 const &Point, double const Spacing, std::vector const &Points) +{ + auto const least{Spacing * Spacing}; + return std::ranges::all_of(Points, [&](glm::dvec2 const &Other) { + auto const d{Point - Other}; + return glm::dot(d, d) >= least; + }); +} + +bool clear_of(glm::dvec2 const &Point, double const Spacing, std::vector const &Taken, std::vector const &Made) +{ + return clear_of(Point, Spacing, Taken) && clear_of(Point, Spacing, Made); +} + +// one row of the grid of triangles in the circle, added to Made until it holds dab_most points +void grid_row(long long const Row, glm::dvec2 const &Centre, double const Radius, double const Spacing, std::vector const &Taken, std::vector &Made) +{ + auto const row{Spacing * std::sqrt(3.0) * 0.5}; + auto const shift{(Row % 2 == 0) ? 0.0 : 0.5 * Spacing}; + auto const z{static_cast(Row) * row}; + auto const first{static_cast(std::floor((Centre.x - Radius - shift) / Spacing))}; + auto const last{static_cast(std::ceil((Centre.x + Radius - shift) / Spacing))}; + for (auto c = first; c <= last; ++c) + { + if (static_cast(Made.size()) >= dab_most) + break; + glm::dvec2 const point{static_cast(c) * Spacing + shift, z}; + // the points of one dab are Spacing apart by the grid itself; only a point an earlier dab put is there already, the same + // point again, a hair away at most + if (glm::distance(point, Centre) <= Radius && clear_of(point, 0.5 * Spacing, Taken)) + Made.push_back(point); + } +} + +// the points of the grid of triangles of the world (rows Spacing·√3/2 apart, every other one shifted by half) in the circle, +// dab_most at most +std::vector grid_points(glm::dvec2 const &Centre, double const Radius, double const Spacing, std::vector const &Taken) +{ + std::vector made; + auto const row{Spacing * std::sqrt(3.0) * 0.5}; + auto const first_row{static_cast(std::floor((Centre.y - Radius) / row))}; + auto const last_row{static_cast(std::ceil((Centre.y + Radius) / row))}; + for (auto r = first_row; r <= last_row; ++r) + { + if (static_cast(made.size()) >= dab_most) + break; + grid_row(r, Centre, Radius, Spacing, Taken, made); + } + return made; +} + +// the line drawn, measured along its length: a point at a distance along it and an offset to its side +class polyline +{ + public: + explicit polyline(std::vector const &Points) + { + m_points.reserve(Points.size()); + m_lengths.reserve(Points.size()); + auto total{0.0}; + for (auto const &point : Points) + { + // a point given twice (a double-click) makes a piece of no length, with no direction to put the rows to the side of + if (false == m_points.empty()) + { + auto const step{glm::distance(flat(m_points.back()), flat(point))}; + if (step < 1e-6) + continue; + total += step; + } + m_points.push_back(point); + m_lengths.push_back(total); + } + } + + double length() const + { + return m_lengths.back(); + } + + // the place At metres along the line, Offset metres to its left (negative: to the right) + line_place at(double const At, double const Offset, double const Width) const + { + auto const piece{segment(At)}; + auto const &a{m_points[piece]}; + auto const &b{m_points[piece + 1]}; + auto const span{m_lengths[piece + 1] - m_lengths[piece]}; + auto const t{span > 0.0 ? std::clamp((At - m_lengths[piece]) / span, 0.0, 1.0) : 0.0}; + auto const direction{span > 0.0 ? (flat(b) - flat(a)) / span : glm::dvec2{1.0, 0.0}}; + glm::dvec2 const normal{-direction.y, direction.x}; + line_place place; + place.point = glm::mix(flat(a), flat(b), t) + normal * Offset; + place.height = std::lerp(a.y, b.y, t); + place.side = Width > 0.0 ? std::min(1.0, std::abs(Offset) / Width) : 0.0; + return place; + } + + private: + static glm::dvec2 flat(glm::dvec3 const &Point) + { + return {Point.x, Point.z}; + } + + // the piece of the line At metres along it lies on + std::size_t segment(double const At) const + { + auto const next{std::ranges::upper_bound(m_lengths, At)}; + auto const index{static_cast(std::distance(m_lengths.begin(), next))}; + return std::clamp(index, 1, m_points.size() - 1) - 1; + } + + std::vector m_points; + std::vector m_lengths; +}; + +// the places taken by a line, sorted into square cells as wide as the spacing: a long line with thousands of models isn't gone +// through whole for every new one +class spaced_places +{ + public: + explicit spaced_places(double const Spacing) : m_spacing{Spacing} + { + } + + bool clear(glm::dvec2 const &Point, double const Least) const + { + auto const [cx, cz]{cell(Point)}; + for (auto x = cx - 1; x <= cx + 1; ++x) + { + for (auto z = cz - 1; z <= cz + 1; ++z) + { + if (auto const found{m_cells.find(key(x, z))}; found != m_cells.end() && false == clear_of(Point, Least, found->second)) + return false; + } + } + return true; + } + + void add(glm::dvec2 const &Point) + { + auto const [cx, cz]{cell(Point)}; + m_cells[key(cx, cz)].push_back(Point); + } + + private: + std::pair cell(glm::dvec2 const &Point) const + { + return {static_cast(std::floor(Point.x / m_spacing)), static_cast(std::floor(Point.y / m_spacing))}; + } + + static long long key(long long const X, long long const Z) + { + // the cells of a scenery, tens of kilometres across at most, fit the 32 bits of each half + return (X << 32) ^ (Z & 0xffffffffLL); + } + + double m_spacing; + std::unordered_map> m_cells; +}; + +// the regular fill: rows along the line, each a list of places a spacing apart +struct regular_line +{ + polyline const &line; + line_settings const &settings; + double spacing; + std::mt19937 &random; // NOSONAR(cpp:S2245) placement of scenery models, not security + + void row(long long const Row, spaced_places &Taken, std::vector &Made) const + { + auto const offset{static_cast(Row) * spacing}; + auto const shift{(Row % 2 == 0) ? 0.0 : 0.5 * spacing}; + auto const jitter{std::clamp(settings.jitter, 0.0, 0.5) * spacing}; + std::uniform_real_distribution each_way{-1.0, 1.0}; + // the places of the row counted in whole steps: no error added up along a long line + auto const steps{static_cast(std::floor((line.length() + 1e-9 - shift) / spacing))}; + for (long long step = 0; step <= steps; ++step) + { + if (static_cast(Made.size()) >= line_most) + break; + auto const at{shift + static_cast(step) * spacing}; + auto const along_off{jitter > 0.0 ? jitter * each_way(random) : 0.0}; + auto const side_off{jitter > 0.0 ? jitter * each_way(random) : 0.0}; + auto place{line.at(std::clamp(at + along_off, 0.0, line.length()), offset + side_off, settings.width)}; + // where the line bends, the rows on the inner side of the bend run into each other: one model of the two + if (false == Taken.clear(place.point, 0.5 * spacing)) + continue; + Taken.add(place.point); + Made.push_back(place); + } + } + + std::vector make() const + { + std::vector made; + spaced_places taken{spacing}; + auto const rows{static_cast(std::floor(std::max(0.0, settings.width) / spacing + 1e-9))}; + // the row on the line first, then the pairs of rows outwards: cut short by the limit, the band stays even + row(0, taken, made); + for (long long r = 1; r <= rows; ++r) + { + if (static_cast(made.size()) >= line_most) + break; + row(r, taken, made); + row(-r, taken, made); + } + return made; + } +}; + +// the irregular fill: random places in the band, the spacing kept +std::vector irregular_line(polyline const &Line, line_settings const &Settings, double const Spacing, std::mt19937 &Random) // NOSONAR(cpp:S2245) placement of scenery models, not security +{ + auto const width{std::max(0.0, Settings.width)}; + auto const density{std::max(0.0, Settings.density)}; + // over the area of the band; a line of no width gets the density per spacing of its length + auto const amount{width > 0.0 ? density * Line.length() * 2.0 * width / 100.0 : density * Line.length() / Spacing}; + auto const wanted{static_cast(std::min(static_cast(line_most), std::round(amount)))}; + std::uniform_real_distribution unit{0.0, 1.0}; + std::vector made; + spaced_places taken{Spacing}; + int constexpr tries_each{30}; + auto attempts{static_cast(wanted) * tries_each}; + while (attempts > 0 && static_cast(made.size()) < wanted) + { + --attempts; + auto const across{2.0 * unit(Random) - 1.0}; + // fewer towards the edges: kept with the chance falling from 1 on the line to 0 at the edge + if (Settings.thin_out && unit(Random) > (1.0 - across * across) * (1.0 - across * across)) + continue; + auto const place{Line.at(Line.length() * unit(Random), width * across, width)}; + if (false == taken.clear(place.point, Spacing)) + continue; + taken.add(place.point); + made.push_back(place); + } + return made; +} + +// the share of the full density a dab leaves at a place, Share of its radius from its middle: all of it anywhere in the circle +// for the random fill, falling from all in the middle to none at the edge for the feathered one +double dab_weight(fill const Mode, double const Share) +{ + if (Share >= 1.0) + return 0.0; + if (Mode != fill::feathered) + return 1.0; + auto const inner{1.0 - Share * Share}; + return inner * inner; +} + +// a number of tries with the Expected count on average: its whole part, and one more with the chance of its fraction. rounded +// instead, a small circle or a low density would get nothing from any of the dabs +int tries_for(double const Expected, std::mt19937 &Random) // NOSONAR(cpp:S2245) placement of scenery models, not security +{ + auto const whole{std::floor(Expected)}; + std::uniform_real_distribution unit{0.0, 1.0}; + auto const more{unit(Random) < Expected - whole ? 1.0 : 0.0}; + return static_cast(std::min(static_cast(dab_most), whole + more)); +} + +// the ground of a dab the stroke hasn't filled yet: the dab adds only what its circle is short of +class fresh_ground +{ + public: + fresh_ground(glm::dvec2 const &Centre, double const Radius, fill const Mode, std::vector const &Dabs) : m_centre{Centre}, m_radius{Radius}, m_mode{Mode} + { + // only the circles which reach into this one + std::ranges::copy_if(Dabs, std::back_inserter(m_before), [&](dab_circle const &Dab) { return glm::distance(Dab.centre, Centre) < Radius + Dab.radius; }); + } + + // the places of the models, Spacing from each other and from the Nearby ones at least. Count of them are drawn evenly over + // the whole circle (as many as the density asks for in it), each kept with the chance of what the ground there is short of: + // the density comes out the same wherever the circles of the stroke overlap, however many of them do + std::vector places(int const Count, double const Spacing, std::vector const &Nearby, std::mt19937 &Random) const // NOSONAR(cpp:S2245) placement of scenery models, not security + { + std::vector made; + for (int i = 0; i < Count; ++i) + { + if (auto const place{spaced_place(Spacing, Nearby, made, Random)}; place.has_value()) + made.push_back(*place); + } + return made; + } + + private: + // what the earlier dabs left at the Point already, as a share of the full density + double filled(glm::dvec2 const &Point) const + { + auto most{0.0}; + for (auto const &dab : m_before) + most = std::max(most, dab_weight(m_mode, glm::distance(Point, dab.centre) / dab.radius)); + return most; + } + + // one place drawn in the circle and kept with the chance of what the ground there is short of; one too close to the + // others is drawn again, a number of times before it's given up for the spacing + std::optional spaced_place(double const Spacing, std::vector const &Nearby, std::vector const &Made, std::mt19937 &Random) const // NOSONAR(cpp:S2245) placement of scenery models, not security + { + std::uniform_real_distribution unit{0.0, 1.0}; + int constexpr tries_each{30}; + for (int attempt = 0; attempt < tries_each; ++attempt) + { + // even over the area: the square root of the share of the radius + auto const share{std::sqrt(unit(Random))}; + auto const angle{2.0 * std::numbers::pi * unit(Random)}; + glm::dvec2 const point{m_centre.x + m_radius * share * std::cos(angle), m_centre.y + m_radius * share * std::sin(angle)}; + if (unit(Random) >= dab_weight(m_mode, share) - filled(point)) + return std::nullopt; + if (clear_of(point, Spacing, Nearby, Made)) + return point; + } + return std::nullopt; + } + + glm::dvec2 m_centre; + double m_radius; + fill m_mode; + std::vector m_before; +}; + +} // namespace + +std::vector along(std::vector const &Points, line_settings const &Asked, std::mt19937 &Random) // NOSONAR(cpp:S2245) placement of scenery models, not security +{ + if (Points.size() < 2) + return {}; + polyline const line{Points}; + if (line.length() <= 0.0) + return {}; + auto const Settings{sane(Asked)}; + auto const spacing{std::max(0.1, Settings.spacing)}; + if (Settings.mode == line_fill::irregular) + return irregular_line(line, Settings, spacing, Random); + return regular_line{line, Settings, spacing, Random}.make(); +} + +float side_scale(line_settings const &Settings, double const Side) +{ + auto const edge{std::max(1.0, sane(Settings).edge_scale) / 100.0}; + return static_cast(std::lerp(1.0, edge, bounded(Side, 0.0, 1.0, 0.0))); +} + +std::vector dab(glm::dvec2 const &Centre, dab_settings const &Asked, stroke &Stroke, std::mt19937 &Random, std::vector const &Standing) // NOSONAR(cpp:S2245) placement of scenery models, not security +{ + if (false == std::isfinite(Centre.x) || false == std::isfinite(Centre.y)) + return {}; + auto const Settings{sane(Asked)}; + auto const radius{std::max(0.1, Settings.radius)}; + auto const spacing{std::max(0.05, Settings.spacing)}; + // only what the stroke put near this circle matters: a long stroke isn't gone through whole for every point + std::vector nearby; + auto const reach{radius + spacing}; + auto const within{[&Centre, reach](glm::dvec2 const &Point) { return glm::distance(Point, Centre) <= reach; }}; + std::ranges::copy_if(Stroke.taken, std::back_inserter(nearby), within); + std::vector made; + if (Settings.mode == fill::uniform) + { + // the grid is fixed to the world, so a stroke over the ground of an earlier one comes to the very same points: those + // where a model stands already are left alone + std::ranges::copy_if(Standing, std::back_inserter(nearby), within); + made = grid_points(Centre, radius, spacing, nearby); + } + else + made = fresh_ground{Centre, radius, Settings.mode, Stroke.dabs}.places(tries_for(dab_wanted(Settings), Random), spacing, nearby, Random); + Stroke.taken.insert(Stroke.taken.end(), made.begin(), made.end()); + Stroke.dabs.emplace_back(Centre, radius); + return made; +} + +double dab_wanted(dab_settings const &Asked) +{ + auto const Settings{sane(Asked)}; + auto const radius{std::max(0.1, Settings.radius)}; + return std::max(0.0, Settings.density) * std::numbers::pi * radius * radius / 100.0; +} + +double dab_step(dab_settings const &Asked) +{ + auto const Settings{sane(Asked)}; + return std::max({0.05, Settings.spacing, 0.5 * Settings.radius}); +} + +look pick(look_settings const &Asked, std::mt19937 &Random) // NOSONAR(cpp:S2245) placement of scenery models, not security +{ + auto const Settings{sane(Asked)}; + look out; + auto const spread = [&](float const Range) { + if (Range <= 0.0f) + return 0.0f; + std::uniform_real_distribution each_way{-Range, Range}; + return each_way(Random); + }; + if (Settings.turn == vary::fixed) + out.angles = Settings.angles; + else + out.angles = {spread(Settings.angle_range.x), spread(Settings.angle_range.y), spread(Settings.angle_range.z)}; + glm::vec3 percent{Settings.scale}; + if (Settings.size == vary::random) + { + if (Settings.same_scale) + { + auto const common{spread(Settings.scale_range.x)}; + percent = glm::vec3{100.0f + common}; + } + else + percent = glm::vec3{100.0f + spread(Settings.scale_range.x), 100.0f + spread(Settings.scale_range.y), 100.0f + spread(Settings.scale_range.z)}; + } + out.scale = glm::max(percent, glm::vec3{1.0f}) / 100.0f; + return out; +} + +} // namespace scatter diff --git a/editor/editorScatter.hpp b/editor/editorScatter.hpp new file mode 100644 index 000000000..ebb9a7c47 --- /dev/null +++ b/editor/editorScatter.hpp @@ -0,0 +1,131 @@ +#pragma once + +// where the brush of models puts them, and how it turns and scales each: engine-free, so it can be tested on its own + +#include +#include +#include + +#include + +namespace scatter +{ + +// how the models fill the circle of the brush +enum class fill +{ + random, // anywhere in the circle, no closer to each other than the spacing + // on a grid of triangles as wide as the spacing, fixed to the world: strokes over one another come to the same points, and a + // point where a model stands already (the Standing ones given to dab()) gets no second one + uniform, + feathered, // anywhere, fewer and fewer towards the edge of the circle +}; + +struct dab_settings +{ + double radius{5.0}; // m + fill mode{fill::random}; + double spacing{2.0}; // m: the least distance between two models; the step of the grid of the uniform fill + // models a 100 m² of the ground the stroke goes over, as much as the spacing lets: for the random fill everywhere under the + // circle, for the feathered one in the middle of the stroke, fewer and fewer towards its edge + double density{4.0}; +}; + +// the circle a dab of the stroke has filled already +struct dab_circle +{ + glm::dvec2 centre; + double radius; +}; + +// what a stroke of the brush has done so far. the circles of its dabs overlap, and the cursor may come back over them: the +// ground a dab has filled gets no more from the next ones, so it holds as many models as the density says, not that many +// from each dab that went over it +struct stroke +{ + std::vector taken; // the places of the models put (x, z) + std::vector dabs; // the circles filled +}; + +// the most models one dab puts, whatever the fill: a dab wider or denser than that is cut short +int constexpr dab_most{2000}; + +// the places of the models of one dab of the brush round Centre (x, z): inside the circle, Spacing from each other and from those +// the Stroke put so far at least, on the ground the stroke hasn't filled yet. the dab is added to the Stroke: its circle, and its +// places, whether a model ends up standing there or not. +// Standing: the places (x, z) of the models which stand near the circle already, whoever put them. the uniform fill leaves the +// points of its grid alone where one of them stands within half the spacing, so a second stroke over the same ground adds +// nothing to the first; the other fills don't look at them. +// settings which aren't finite numbers are taken for the least ones, far too large ones are cut (see sane() in the .cpp) +std::vector dab(glm::dvec2 const &Centre, dab_settings const &Settings, stroke &Stroke, std::mt19937 &Random, std::vector const &Standing = {}); // NOSONAR(cpp:S2245) placement of scenery models, not security + +// how many models the density asks for in the whole circle of a dab of the random or the feathered fill; more than dab_most +// of them and the dab is cut short +double dab_wanted(dab_settings const &Settings); + +// the distance the cursor goes before the next dab: the circles of two dabs overlap by half +double dab_step(dab_settings const &Settings); + +// how the models stand along a line drawn on the ground +enum class line_fill +{ + regular, // in rows along the line, Spacing apart along it and across it, every other row shifted by half + irregular, // anywhere in the band, no closer to each other than the spacing +}; + +struct line_settings +{ + double width{0.0}; // m each side of the line: 0 is one row on the line itself + line_fill mode{line_fill::regular}; + double spacing{4.0}; // m: the step along the line and between the rows; the least distance for the irregular fill + double jitter{0.0}; // the regular fill moved off its places by up to this share of the spacing each way, 0 to 0.5 + double density{4.0}; // models a 100 m² of the band for the irregular fill (on a line of no width: per spacing of it) + bool thin_out{false}; // the irregular fill fewer and fewer towards the edges of the band + double edge_scale{100.0}; // percent of their size the models at the edges of the band get, down from the full size on the line +}; + +// a place along the line: where (x, z), the height of the line there, and how far out in the band it is (0 on the line, 1 at the edge) +struct line_place +{ + glm::dvec2 point; + double height; + double side; +}; + +// the most models one line puts +int constexpr line_most{20000}; + +// the places of the models along the line through Points (x, height, z), two points at least +std::vector along(std::vector const &Points, line_settings const &Settings, std::mt19937 &Random); // NOSONAR(cpp:S2245) placement of scenery models, not security + +// the share of its size a model gets at the place Side of the band (0 on the line, 1 at the edge) +float side_scale(line_settings const &Settings, double Side); + +// a setting the same for every model, or drawn for each from a range +enum class vary +{ + fixed, + random, +}; + +struct look_settings +{ + vary turn{vary::random}; + glm::vec3 angles{0.0f}; // degrees about x, y, z, for the fixed turn + glm::vec3 angle_range{0.0f, 180.0f, 0.0f}; // degrees each way about x, y, z, for the random turn + vary size{vary::fixed}; + glm::vec3 scale{100.0f}; // percent along x, y, z, for the fixed scale + glm::vec3 scale_range{0.0f}; // percent each way along x, y, z, for the random scale + bool same_scale{true}; // the random scale one for all the axes (the x range), the model keeps its shape +}; + +struct look +{ + glm::vec3 angles{0.0f}; // degrees about x, y, z + glm::vec3 scale{1.0f}; // factors along x, y, z, never under 1% +}; + +// the turn and the scale of one model +look pick(look_settings const &Settings, std::mt19937 &Random); // NOSONAR(cpp:S2245) placement of scenery models, not security + +} // namespace scatter diff --git a/editor/editorTerrainStreamer.cpp b/editor/editorTerrainStreamer.cpp index a8f569aaa..d887b14b9 100644 --- a/editor/editorTerrainStreamer.cpp +++ b/editor/editorTerrainStreamer.cpp @@ -16,6 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "simulation/simulation.h" #include "utilities/Globals.h" #include "utilities/Logs.h" +#include "utilities/utilities.h" #include #include @@ -99,17 +100,19 @@ terrain_streamer::~terrain_streamer() std::string terrain_streamer::pack_path(heightmap::pack_key const &Key) const { - return m_directory + heightmap::pack_file_name(Key); + // read and written as it's named on the disk + return FileOnDisk(m_directory + heightmap::pack_file_name(Key)); } bool terrain_streamer::open(std::string const &Name) { close(); m_name = Name; - m_directory = "terrain/" + Name + "/"; + // the folder as it's named on the disk, the editor writes the files of the terrain into it + m_directory = FileOnDiskToWrite("terrain/" + Name) + "/"; m_manifest = heightmap::manifest(); m_manifestchanged = false; - auto const manifestpath{m_directory + "terrain.yaml"}; + auto const manifestpath{FileOnDisk(m_directory + "terrain.yaml")}; std::error_code ec; if (std::filesystem::exists(manifestpath, ec)) { @@ -2306,7 +2309,8 @@ bool terrain_streamer::save(std::string *Error) return false; }; std::error_code ec; - auto const manifestpath{m_directory + "terrain.yaml"}; + // written over as it's named on the disk, not joined by a second one next to it + auto const manifestpath{FileOnDisk(m_directory + "terrain.yaml")}; if (m_manifestchanged || modified() || false == std::filesystem::exists(manifestpath, ec)) { std::string error; diff --git a/input/command.cpp b/input/command.cpp index 35d7f546e..8b52d8ad6 100644 --- a/input/command.cpp +++ b/input/command.cpp @@ -459,6 +459,9 @@ commanddescription_sequence Commands_descriptions = { {"gensettoggle", command_target::vehicle, command_mode::oneoff}, {"gensetenable", command_target::vehicle, command_mode::oneoff}, {"gensetdisable", command_target::vehicle, command_mode::oneoff}, + // the flashlight is the player's own: an entity command, which stays on the machine it was given on (command_queue::is_network_target()) + {"flashlighttoggle", command_target::entity, command_mode::oneoff}, + {"snapshotsave", command_target::simulation, command_mode::oneoff}, }; // Maps of command and coresponding strings @@ -897,6 +900,8 @@ std::unordered_map const commandMap = { {"gensettoggle", user_command::gensettoggle}, {"gensetenable", user_command::gensetenable}, {"gensetdisable", user_command::gensetdisable}, + {"flashlighttoggle", user_command::flashlighttoggle}, + {"snapshotsave", user_command::snapshotsave}, {"none", user_command::none}}; } // namespace simulation diff --git a/input/command.h b/input/command.h index 7571a8638..daa46d908 100644 --- a/input/command.h +++ b/input/command.h @@ -459,6 +459,10 @@ enum class user_command gensettoggle, gensetenable, gensetdisable, + // the flashlight of the player (Global.flashlight), at the end so the numbers of the commands before it stay as they were. + // an entity command, taken by the camera of the player (TCamera::OnCommand()): it isn't sent to the other machines of a network game + flashlighttoggle, + snapshotsave, // writes a snapshot of the simulation to the snapshots folder (simulation/simulationsnapshotworld.h) none = -1 }; diff --git a/input/driverkeyboardinput.cpp b/input/driverkeyboardinput.cpp index 566a07192..5aa8635d7 100644 --- a/input/driverkeyboardinput.cpp +++ b/input/driverkeyboardinput.cpp @@ -15,6 +15,8 @@ driverkeyboard_input::init() { default_bindings(); recall_bindings(); + // the flashlight came after the players wrote their bindings: it takes no key from a command of their file + yield_default( user_command::flashlighttoggle ); bind(); return true; @@ -269,6 +271,8 @@ driverkeyboard_input::default_bindings() { // interiorlightenable, // interiorlightdisable, { interiorlightdimtoggle, {GLFW_KEY_APOSTROPHE | keymodifier::control, ""} }, + // Ctrl+Shift+F: no command has it in the eu07_input-keyboard.ini the game ships with (Ctrl+Shift+L there is motorconnectorsclose) + { flashlighttoggle, {GLFW_KEY_F | keymodifier::control | keymodifier::shift, ""} }, // interiorlightdimenable, // interiorlightdimdisable, // compartmentlightstoggle, @@ -334,7 +338,8 @@ driverkeyboard_input::default_bindings() { { vehiclemovebackwards, {GLFW_KEY_RIGHT_BRACKET | keymodifier::control, "Move the train backwards (Debug Mode only)"} }, { vehicleboost, {GLFW_KEY_TAB | keymodifier::control, "Boost the train (Debug Mode only)"} }, { debugtoggle, {GLFW_KEY_F12 | keymodifier::control | keymodifier::shift, "Toggle Debug Mode"} }, - { pausetoggle, {GLFW_KEY_ESCAPE, "Pause the game"} } + { pausetoggle, {GLFW_KEY_ESCAPE, "Pause the game"} }, + { snapshotsave, {GLFW_KEY_F9 | keymodifier::control | keymodifier::shift, "Save a snapshot of the simulation"} } }; } diff --git a/input/keyboardinput.cpp b/input/keyboardinput.cpp index 4c2fdf8f0..9a5696cf0 100644 --- a/input/keyboardinput.cpp +++ b/input/keyboardinput.cpp @@ -8,6 +8,7 @@ http://mozilla.org/MPL/2.0/. */ #include "stdafx.h" +#include #include "input/keyboardinput.h" #include "utilities/Globals.h" #include "utilities/Logs.h" @@ -217,6 +218,7 @@ keyboard_input::recall_bindings() { std::tuple binding{keycode, description}; m_bindingsetups.insert_or_assign(lookup->second, binding); + m_recalled.insert( lookup->second ); } } } @@ -225,6 +227,28 @@ keyboard_input::recall_bindings() { return true; } +void keyboard_input::yield_default( user_command const Command ) { + + auto const own { m_bindingsetups.find( Command ) }; + if( own == m_bindingsetups.end() || m_recalled.contains( Command ) ) { + // no default to yield, or the file binds the command itself: the choice of the player + return; + } + auto const key { std::get( own->second ) }; + if( key == 0 ) { + return; + } + auto const taken { std::ranges::find_if( m_bindingsetups, [this, Command, key]( auto const &Setup ) { + return Setup.first != Command && std::get( Setup.second ) == key && m_recalled.contains( Setup.first ); } ) }; + if( taken == m_bindingsetups.end() ) { + return; + } + WriteLog( + "Keyboard binding: \"" + simulation::Commands_descriptions[ static_cast( Command ) ].name + "\" is left without a key, its default one is bound to \"" + + simulation::Commands_descriptions[ static_cast( taken->first ) ].name + "\" in eu07_input-keyboard.ini" ); + std::get( own->second ) = 0; +} + void keyboard_input::dump_bindings() const { std::fstream stream("eu07_input-keyboard.ini", diff --git a/input/keyboardinput.h b/input/keyboardinput.h index 1611c9a3c..eb2886152 100644 --- a/input/keyboardinput.h +++ b/input/keyboardinput.h @@ -9,6 +9,8 @@ http://mozilla.org/MPL/2.0/. #pragma once +#include +#include #include #include #include "input/command.h" @@ -79,11 +81,17 @@ protected: default_bindings() = 0; bool recall_bindings(); + // a command added after the players wrote their bindings: where their file doesn't list it and gives the key of its default + // to another command, the command is left without a key, so that the one of the file goes on working. bind() gives a key + // two commands share to the one later in user_command, which a new command always is + void + yield_default( user_command const Command ); void bind(); // members bindingsetup_sequence m_bindingsetups; + std::set m_recalled; // the commands the file of the bindings lists private: // types diff --git a/lang/editor_pl.po b/lang/editor_pl.po index 2abe0652d..4f1a76c79 100644 --- a/lang/editor_pl.po +++ b/lang/editor_pl.po @@ -14313,6 +14313,162 @@ msgstr "Kursor rysowany w obrazie (stream)" msgid "The pointer drawn by the editor into the frame instead of the one of the system: seen by those watching a stream\nor a recording of the window (Discord, OBS, the capture of the system), which leave the system pointer out" msgstr "Wskaźnik rysowany przez edytor w klatce zamiast systemowego: widać go w streamie\ni w nagraniu okna (Discord, OBS, przechwytywanie systemowe), które pomijają wskaźnik systemu" +msgid "Single model##brush" +msgstr "Pojedynczy model##brush" + +msgid "Many models##brush" +msgstr "Wiele modeli##brush" + +msgid "LMB: one model at the cross on the ground" +msgstr "LPM: jeden model w miejscu krzyżyka na gruncie" + +msgid "Hold LMB: models in the circle along the cursor's path; one Ctrl+Z takes the whole stroke back" +msgstr "Przytrzymaj LPM: modele w okręgu wzdłuż drogi kursora; jedno Ctrl+Z cofa całe pociągnięcie" + +msgid "Radius##brush" +msgstr "Promień##brush" + +msgid "Random, anywhere in the circle" +msgstr "Losowe" + +msgid "Uniform (grid)" +msgstr "Równomierne (siatka)" + +msgid "Feathered to the edge" +msgstr "Rozmyte do krawędzi" + +msgid "Fill##brush" +msgstr "Wypełnienie##brush" + +msgid "Spacing##brush" +msgstr "Odstęp##brush" + +msgid "The step of the grid the models stand on" +msgstr "Krok siatki, na której stoją modele" + +msgid "The least distance between two models" +msgstr "Najmniejsza odległość między dwoma modelami" + +msgid "Density##brush" +msgstr "Gęstość##brush" + +msgid "%.1f per 100 m²" +msgstr "%.1f na 100 m²" + +msgid "How many models a 100 m² the ground under the stroke gets, as many as the spacing lets in.\nGround the stroke has gone over gets no more when the cursor comes back over it" +msgstr "Ile modeli na 100 m² dostaje teren pod pociągnięciem, o ile pozwala na to odstęp.\nTeren, po którym pociągnięcie już przeszło, nie dostaje więcej, gdy kursor na niego wraca" + +msgid "How many models a 100 m² the middle of the stroke gets, fewer and fewer towards its edge, as many as the spacing lets in.\nGround the stroke has gone over gets no more when the cursor comes back over it" +msgstr "Ile modeli na 100 m² dostaje środek pociągnięcia, coraz mniej ku jego brzegowi, o ile pozwala na to odstęp.\nTeren, po którym pociągnięcie już przeszło, nie dostaje więcej, gdy kursor na niego wraca" + +msgid "Turn##brush" +msgstr "Obrót##brush" + +msgid "Fixed##brushturn" +msgstr "Stały##brushturn" + +msgid "Random##brushturn" +msgstr "Losowy##brushturn" + +msgid "Angles x y z##brush" +msgstr "Kąty x y z##brush" + +msgid "Each way x y z##brushturn" +msgstr "W obie strony x y z##brushturn" + +msgid "Each model turned by a random angle up to this much each way: x and z tilt it, y turns it round (180: any way)" +msgstr "Każdy model obrócony o losowy kąt do tylu stopni w obie strony: x i z go przechylają, y obraca wokół pionu (180: dowolnie)" + +msgid "Scale##brush" +msgstr "Skala##brush" + +msgid "Fixed##brushscale" +msgstr "Stała##brushscale" + +msgid "Random##brushscale" +msgstr "Losowa##brushscale" + +msgid "Percent x y z##brush" +msgstr "Procent x y z##brush" + +msgid "The same on every axis##brush" +msgstr "Jednakowa na wszystkich osiach##brush" + +msgid "Each way##brushscale" +msgstr "W obie strony##brushscale" + +msgid "Each way x y z##brushscale" +msgstr "W obie strony x y z##brushscale" + +msgid "Each model scaled by a random share up to this much each way from its own size" +msgstr "Każdy model przeskalowany losowo o tyle procent w obie strony od własnego rozmiaru" + +msgid "Brush: %zu models put; Ctrl+Z takes the whole stroke back" +msgstr "Pędzel: postawiono %zu modeli; Ctrl+Z cofa całe pociągnięcie" + +msgid "Brush: a dab puts %d models at most; widen the spacing or narrow the circle for the rest" +msgstr "Pędzel: jedno dotknięcie stawia najwyżej %d modeli; zwiększ odstęp albo zmniejsz koło, by objąć resztę" + +msgid "In a circle##brushshape" +msgstr "W kole##brushshape" + +msgid "Along a line##brushshape" +msgstr "Wzdłuż linii##brushshape" + +msgid "LMB: the points of the line; Enter puts the models, Backspace takes the last point back, Esc drops the line" +msgstr "LPM: punkty linii; Enter stawia modele, Backspace cofa ostatni punkt, Esc porzuca linię" + +msgid "Width each side##brushline" +msgstr "Szerokość w każdą stronę##brushline" + +msgid "How far to each side of the line the models go; 0: one row on the line itself" +msgstr "Jak daleko w każdą stronę od linii sięgają modele; 0: jeden rząd na samej linii" + +msgid "Regular, in rows" +msgstr "Regularnie, w rzędach" + +msgid "Irregular, anywhere in the band" +msgstr "Nieregularnie, gdziekolwiek w pasie" + +msgid "Fill##brushline" +msgstr "Wypełnienie##brushline" + +msgid "Spacing##brushline" +msgstr "Odstęp##brushline" + +msgid "The step along the line and between the rows" +msgstr "Krok wzdłuż linii i odstęp między rzędami" + +msgid "Irregularity##brushline" +msgstr "Nieregularność##brushline" + +msgid "Each model moved off its place in the rows by up to this share of the spacing each way; 0: exactly in rows" +msgstr "Każdy model przesunięty ze swojego miejsca w rzędzie o najwyżej taką część odstępu w każdą stronę; 0: dokładnie w rzędach" + +msgid "Density##brushline" +msgstr "Gęstość##brushline" + +msgid "Fewer towards the edges##brushline" +msgstr "Rzadziej ku krawędziom##brushline" + +msgid "Size at the edges##brushline" +msgstr "Rozmiar na krawędziach##brushline" + +msgid "The size of the models at the edges of the band, as a share of their size on the line; between, it goes evenly from one to the other" +msgstr "Rozmiar modeli na krawędziach pasa jako część ich rozmiaru na linii; pomiędzy zmienia się równomiernie od jednego do drugiego" + +msgid "Brush: a line needs two points at least" +msgstr "Pędzel: linia potrzebuje co najmniej dwóch punktów" + +msgid "Brush: no models put along the line" +msgstr "Pędzel: wzdłuż linii nie postawiono żadnego modelu" + +msgid "Brush: %zu models put along the line, the most one line puts; Ctrl+Z takes them back" +msgstr "Pędzel: postawiono %zu modeli wzdłuż linii, najwięcej, ile stawia jedna linia; Ctrl+Z je cofa" + +msgid "Brush: %zu models put along the line; Ctrl+Z takes them back" +msgstr "Pędzel: postawiono %zu modeli wzdłuż linii; Ctrl+Z je cofa" + msgid "Track names outside of ASCII..." msgstr "Nazwy torów spoza ASCII..." diff --git a/model/Model3d.cpp b/model/Model3d.cpp index 61899cca3..b9937a77c 100644 --- a/model/Model3d.cpp +++ b/model/Model3d.cpp @@ -1876,6 +1876,11 @@ bool TModel3d::LoadFromFile(std::string const &FileName, bool dynamic) // the files as they're named on the disk, the name given is in lowercase auto const textfile{FileCased(name + ".t3d")}; auto const binaryfile{FileCased(asBinary)}; + // the binary file made of the text one: written over where it's there in another case, made next to the text otherwise + if (false == binaryfile.empty()) + asBinary = binaryfile; + else if (false == textfile.empty()) + asBinary = textfile.substr(0, textfile.size() - 4) + ".e3d"; // Hirek: Jesli mamy ustawione priorityLoadText3D na yes to wpierw ladujemy t3d if (Global.priorityLoadText3D && (false == textfile.empty())) @@ -2747,6 +2752,7 @@ void TSubModel::BinInit(TSubModel *s, float4x4 *m, std::vector *t, float opacity = mat->get_or_guess_opacity(); // set phase flag based on material opacity + m_passguessed = true; if (opacity == 0.0f) iFlags |= 0x20; // translucent else diff --git a/model/Model3d.h b/model/Model3d.h index 67486802e..2a6db5476 100644 --- a/model/Model3d.h +++ b/model/Model3d.h @@ -101,6 +101,9 @@ public: // bit 13: =1 wystarczy przesunięcie zamiast mnożenia macierzy (trzy jedynki) // bit 14: =1 wymagane przechowanie macierzy (animacje) // bit 15: =1 wymagane przechowanie macierzy (transform niejedynkowy) + // the pass bits (0x30) weren't in the file but guessed on load from the material (BinInit); a converter keeps them out, + // so the guess is made again with the real material where the model is drawn + bool m_passguessed{false}; union { // transform, nie każdy submodel musi mieć float4x4 *fMatrix = nullptr; // pojedyncza precyzja wystarcza diff --git a/model/e4d/e4d_build.cpp b/model/e4d/e4d_build.cpp new file mode 100644 index 000000000..11122354a --- /dev/null +++ b/model/e4d/e4d_build.cpp @@ -0,0 +1,256 @@ +/* +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 "model/e4d/e4d_build.h" + +#include +#include + +#include +#include + +namespace e4d { + +namespace { + +constexpr float snorm16_scale{32767.f}; +constexpr float minimum_length{1e-12f}; + +glm::vec3 perpendicular(glm::vec3 const &Normal) { + // the axis least along the normal gives the steadiest cross product + auto const absolute{glm::abs(Normal)}; + glm::vec3 axis{1.f, 0.f, 0.f}; + if (absolute.y < absolute.x && absolute.y <= absolute.z) + axis = {0.f, 1.f, 0.f}; + else if (absolute.z < absolute.x && absolute.z < absolute.y) + axis = {0.f, 0.f, 1.f}; + return glm::normalize(glm::cross(axis, Normal)); +} + +std::int16_t pack_snorm16(float const Value) { + return static_cast(std::lround(std::clamp(Value, -1.f, 1.f) * snorm16_scale)); +} + +glm::mat4 compose(node_record const &Node) { + glm::quat const rotation{Node.rotation[3], Node.rotation[0], Node.rotation[1], Node.rotation[2]}; + auto transform{glm::mat4_cast(glm::normalize(rotation))}; + transform[0] *= Node.scale[0]; + transform[1] *= Node.scale[1]; + transform[2] *= Node.scale[2]; + transform[3] = glm::vec4{Node.translation[0], Node.translation[1], Node.translation[2], 1.f}; + return transform; +} + +std::unordered_map matrix_lookup(model const &Model) { + std::unordered_map lookup; + for (std::size_t idx = 0; idx < Model.transforms.size(); ++idx) + lookup.try_emplace(Model.transforms[idx].node, idx); + return lookup; +} + +glm::mat4 node_transform(model const &Model, std::uint32_t const Node, std::unordered_map const &Matrices) { + auto const &node{Model.nodes[Node]}; + if ((node.flags & node_flags::matrix) != 0) { + if (auto const lookup{Matrices.find(Node)}; lookup != Matrices.end()) + return glm::make_mat4(Model.transforms[lookup->second].matrix.data()); + } + return compose(node); +} + +std::string lowercase(std::string_view const Text) { + std::string result{Text}; + for (auto &character : result) { + if (character >= 'A' && character <= 'Z') + character = static_cast(character - 'A' + 'a'); + } + return result; +} + +struct box { + glm::vec3 min{std::numeric_limits::max()}; + glm::vec3 max{std::numeric_limits::lowest()}; + bool empty() const { + return min.x > max.x; + } + void add(glm::vec3 const &Point) { + min = glm::min(min, Point); + max = glm::max(max, Point); + } + glm::vec3 centre() const { + return empty() ? glm::vec3{0.f} : (min + max) * 0.5f; + } +}; + +glm::vec3 to_vec3(position const &Position) { + return {Position[0], Position[1], Position[2]}; +} + +// the sphere around the centre of the box of the vertices, reaching the farthest of them +std::array sphere_of(model const &Model, std::size_t const First, std::size_t const Count, box &Box) { + for (auto idx = First; idx < First + Count; ++idx) + Box.add(to_vec3(Model.positions[idx])); + auto const centre{Box.centre()}; + float radius{0.f}; + for (auto idx = First; idx < First + Count; ++idx) + radius = std::max(radius, glm::length(to_vec3(Model.positions[idx]) - centre)); + return {centre.x, centre.y, centre.z, radius}; +} + +bounds_record to_bounds(box const &Box, float const Radius) { + bounds_record bounds; + if (Box.empty()) + return bounds; + auto const centre{Box.centre()}; + bounds.min = {Box.min.x, Box.min.y, Box.min.z}; + bounds.max = {Box.max.x, Box.max.y, Box.max.z}; + bounds.sphere = {centre.x, centre.y, centre.z, Radius}; + return bounds; +} + +} // namespace + +std::array encode_qtangent(tangent_frame const &Frame) { + auto const normal{glm::dot(Frame.normal, Frame.normal) > minimum_length ? glm::normalize(Frame.normal) : glm::vec3{0.f, 0.f, 1.f}}; + auto tangent{Frame.tangent - normal * glm::dot(normal, Frame.tangent)}; + tangent = glm::dot(tangent, tangent) > minimum_length ? glm::normalize(tangent) : perpendicular(normal); + auto const bitangent{glm::cross(normal, tangent)}; + auto rotation{glm::normalize(glm::quat_cast(glm::mat3{tangent, bitangent, normal}))}; + if (rotation.w < 0.f) + rotation = -rotation; + // w keeps its sign through the packing, the sign of the bitangent rides on it + constexpr float bias{1.f / snorm16_scale}; + if (rotation.w < bias) { + auto const scale{std::sqrt(1.f - bias * bias) / std::max(glm::length(glm::vec3{rotation.x, rotation.y, rotation.z}), minimum_length)}; + rotation = glm::quat{bias, rotation.x * scale, rotation.y * scale, rotation.z * scale}; + } + if (Frame.handedness < 0.f) + rotation = -rotation; + return {pack_snorm16(rotation.x), pack_snorm16(rotation.y), pack_snorm16(rotation.z), pack_snorm16(rotation.w)}; +} + +tangent_frame decode_qtangent(std::array const &Packed) { + glm::quat rotation{Packed[3] / snorm16_scale, Packed[0] / snorm16_scale, Packed[1] / snorm16_scale, Packed[2] / snorm16_scale}; + tangent_frame frame; + frame.handedness = rotation.w < 0.f ? -1.f : 1.f; + auto const matrix{glm::mat3_cast(glm::normalize(rotation))}; + frame.tangent = matrix[0]; + frame.normal = matrix[2]; + return frame; +} + +glm::mat4 local_transform(model const &Model, std::uint32_t const Node) { + return node_transform(Model, Node, matrix_lookup(Model)); +} + +std::vector model_transforms(model const &Model) { + auto const matrices{matrix_lookup(Model)}; + std::vector transforms(Model.nodes.size()); + for (std::uint32_t idx = 0; idx < Model.nodes.size(); ++idx) { + auto const local{node_transform(Model, idx, matrices)}; + auto const parent{Model.nodes[idx].parent}; + transforms[idx] = (parent >= 0 && parent < static_cast(idx)) ? transforms[parent] * local : local; + } + return transforms; +} + +bool set_transform(node_record &Node, glm::mat4 const &Matrix, float const Tolerance) { + glm::vec3 scale{glm::length(glm::vec3{Matrix[0]}), glm::length(glm::vec3{Matrix[1]}), glm::length(glm::vec3{Matrix[2]})}; + glm::mat3 rotation{1.f}; + if (scale.x > minimum_length && scale.y > minimum_length && scale.z > minimum_length) { + rotation = glm::mat3{glm::vec3{Matrix[0]} / scale.x, glm::vec3{Matrix[1]} / scale.y, glm::vec3{Matrix[2]} / scale.z}; + // a mirror goes into the scale, the rotation stays proper + if (glm::determinant(rotation) < 0.f) { + scale.x = -scale.x; + rotation[0] = -rotation[0]; + } + } + auto const quaternion{glm::normalize(glm::quat_cast(rotation))}; + Node.translation = {Matrix[3].x, Matrix[3].y, Matrix[3].z}; + Node.rotation = {quaternion.x, quaternion.y, quaternion.z, quaternion.w}; + Node.scale = {scale.x, scale.y, scale.z}; + auto const composed{compose(Node)}; + for (int column = 0; column < 4; ++column) { + for (int row = 0; row < 4; ++row) { + auto const original{Matrix[column][row]}; + if (std::abs(composed[column][row] - original) > Tolerance * std::max(1.f, std::abs(original))) + return false; + } + } + return true; +} + +void build_name_index(model &Model) { + Model.name_index.clear(); + for (std::uint32_t idx = 0; idx < Model.nodes.size(); ++idx) { + if (auto const name{Model.nodes[idx].name}; name != no_index && name < Model.strings.size()) + Model.name_index.push_back({hash_name(Model.strings[name]), idx, 0}); + } + std::ranges::sort(Model.name_index, [](name_index_record const &Left, name_index_record const &Right) { return Left.hash != Right.hash ? Left.hash < Right.hash : Left.node < Right.node; }); +} + +std::vector find_nodes(model const &Model, std::string_view const Name) { + auto const key{lowercase(Name)}; + std::vector found; + auto const matches{[&Model, &key](std::uint32_t const Node) { return lowercase(Model.string(Model.nodes[Node].name)) == key; }}; + if (Model.name_index.empty()) { + for (std::uint32_t idx = 0; idx < Model.nodes.size(); ++idx) { + if (Model.nodes[idx].name != no_index && matches(idx)) + found.push_back(idx); + } + return found; + } + auto const hash{hash_name(Name)}; + auto const range{std::ranges::equal_range(Model.name_index, hash, {}, &name_index_record::hash)}; + for (auto const &entry : range) { + if (matches(entry.node)) + found.push_back(entry.node); + } + return found; +} + +void compute_bounds(model &Model) { + std::vector boxes(Model.nodes.size()); + std::vector radii(Model.nodes.size(), 0.f); + for (auto &primitive : Model.primitives) { + if (primitive.node >= Model.nodes.size() || primitive.vertex_count == 0) + continue; + box own; + primitive.sphere = sphere_of(Model, primitive.base_vertex, primitive.vertex_count, own); + auto &nodebox{boxes[primitive.node]}; + nodebox.add(own.min); + nodebox.add(own.max); + } + // the radius of the node around the centre of its box, from all its vertices + for (auto const &primitive : Model.primitives) { + if (primitive.node >= Model.nodes.size() || primitive.vertex_count == 0) + continue; + auto const centre{boxes[primitive.node].centre()}; + auto &radius{radii[primitive.node]}; + for (auto idx = std::size_t{primitive.base_vertex}; idx < std::size_t{primitive.base_vertex} + primitive.vertex_count; ++idx) + radius = std::max(radius, glm::length(to_vec3(Model.positions[idx]) - centre)); + } + Model.bounds.clear(); + Model.bounds.reserve(Model.nodes.size() + 1); + auto const transforms{model_transforms(Model)}; + box whole; + for (std::size_t idx = 0; idx < Model.nodes.size(); ++idx) { + Model.bounds.push_back(to_bounds(boxes[idx], radii[idx])); + if (boxes[idx].empty()) + continue; + for (int corner = 0; corner < 8; ++corner) { + glm::vec3 const point{(corner & 1) ? boxes[idx].max.x : boxes[idx].min.x, (corner & 2) ? boxes[idx].max.y : boxes[idx].min.y, (corner & 4) ? boxes[idx].max.z : boxes[idx].min.z}; + whole.add(glm::vec3{transforms[idx] * glm::vec4{point, 1.f}}); + } + } + Model.bounds.push_back(to_bounds(whole, whole.empty() ? 0.f : glm::length(whole.max - whole.centre()))); +} + +} // namespace e4d diff --git a/model/e4d/e4d_build.h b/model/e4d/e4d_build.h new file mode 100644 index 000000000..491425e6f --- /dev/null +++ b/model/e4d/e4d_build.h @@ -0,0 +1,48 @@ +/* +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/. +*/ + +#pragma once + +// the helpers which make and read the data of an E4D model: the tangent frames, the transforms of the nodes, the index of +// the names and the bounds + +#include "model/e4d/e4d_model.h" + +#include + +namespace e4d { + +struct tangent_frame { + glm::vec3 normal{0.f, 0.f, 1.f}; + glm::vec3 tangent{1.f, 0.f, 0.f}; + float handedness{1.f}; // -1 where the bitangent is flipped (mirrored texture) +}; + +// the snorm16 quaternion of the frame. a degenerate normal or tangent gets an arbitrary perpendicular one +std::array encode_qtangent(tangent_frame const &Frame); +tangent_frame decode_qtangent(std::array const &Packed); + +// the transform of the node within its parent: the matrix of XFRM, or T * R * S +glm::mat4 local_transform(model const &Model, std::uint32_t Node); +// the transforms of all nodes within the model, in one pass (the parents come first) +std::vector model_transforms(model const &Model); + +// fills the TRS fields of the node from the matrix. returns false when T * R * S doesn't give the matrix back (shear), +// and the matrix has to be kept in XFRM +bool set_transform(node_record &Node, glm::mat4 const &Matrix, float Tolerance = 1e-5f); + +// the sorted index of the names of the nodes +void build_name_index(model &Model); +// the nodes with the name, case-insensitive, in the order of the nodes +std::vector find_nodes(model const &Model, std::string_view Name); + +// the bounds of every node (its own geometry, in its space) and of the whole model, and the spheres of the primitives +void compute_bounds(model &Model); + +} // namespace e4d diff --git a/model/e4d/e4d_convert.cpp b/model/e4d/e4d_convert.cpp new file mode 100644 index 000000000..2fa6fe76e --- /dev/null +++ b/model/e4d/e4d_convert.cpp @@ -0,0 +1,397 @@ +/* +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 "model/e4d/e4d_convert.h" + +#include "model/e4d/e4d_build.h" +#include "model/e4d/e4d_dump.h" +#include "model/e4d/e4d_io.h" +#include "model/Model3d.h" +#include "rendering/renderer.h" +#include "utilities/Globals.h" +#include "utilities/Logs.h" +#include "utilities/utilities.h" +#include "utilities/wholefile.h" + +#include +#include +#include +#include +#include + +namespace e4d { + +namespace { + +// the E3D kinds of geometry are the primitive types of OpenGL, which the topologies of E4D take over +constexpr int gl_primitive_last{6}; + +std::uint32_t pack_colour(glm::vec3 const &Colour) { + auto const channel{[](float const Value) { return static_cast(std::lround(std::clamp(Value, 0.f, 1.f) * 255.f)); }}; + return channel(Colour.r) | (channel(Colour.g) << 8) | (channel(Colour.b) << 16); +} + +std::array to_array(glm::vec4 const &Value) { + return {Value.x, Value.y, Value.z, Value.w}; +} + +class converter { + public: + converter(TModel3d &Source, std::vector &Faults) : m_source(Source), m_faults(Faults) {} + model run(); + + private: + void siblings(TSubModel *First, std::int32_t Parent); + void node(TSubModel &Submodel, std::int32_t Parent); + void transform(TSubModel const &Submodel, std::uint32_t Node); + void components(TSubModel const &Submodel, std::uint32_t Node); + void geometry(TSubModel const &Submodel, std::uint32_t Node); + void vertices(TSubModel const &Submodel, gfx::vertex_array const &Vertices, gfx::userdata_array const &Userdata); + void indices(TSubModel const &Submodel, gfx::index_array const &Indices, primitive_record &Primitive); + void stars(gfx::vertex_array const &Vertices, std::uint32_t Node); + std::uint32_t material(TSubModel const &Submodel); + void light_slots(); + bool any_userdata(TSubModel const *First) const; + + TModel3d &m_source; + std::vector &m_faults; + model m_model; + bool m_userdata{false}; + std::vector m_stars; // the nodes whose STAR components wait for their meshes + std::unordered_map m_nodeof; // the node made of each submodel +}; + +// the pass bits of the submodel as they come from the model file: the ones BinInit guessed from a material are left out, so +// where the model is drawn the guess is made again with the real material (the converter loads through the null renderer, +// whose materials all guess opaque) +std::uint32_t file_flags(TSubModel const &Submodel) { + return Submodel.m_passguessed ? Submodel.iFlags & ~0x30u : Submodel.iFlags; +} + +bool converter::any_userdata(TSubModel const *First) const { + for (auto const *submodel{First}; submodel != nullptr; submodel = submodel->Next) { + if (submodel->m_geometry.handle != null_handle && false == GfxRenderer->UserData(submodel->m_geometry.handle).empty()) + return true; + if (any_userdata(submodel->Child)) + return true; + } + return false; +} + +model converter::run() { + m_userdata = any_userdata(m_source.GetSMRoot()); + siblings(m_source.GetSMRoot(), -1); + build_name_index(m_model); + light_slots(); + compute_bounds(m_model); + return std::move(m_model); +} + +void converter::siblings(TSubModel *const First, std::int32_t const Parent) { + for (auto *submodel{First}; submodel != nullptr; submodel = submodel->Next) + node(*submodel, Parent); +} + +void converter::node(TSubModel &Submodel, std::int32_t const Parent) { + auto const index{static_cast(m_model.nodes.size())}; + m_model.nodes.emplace_back(); + auto &record{m_model.nodes.back()}; + record.name = Submodel.pName.empty() ? no_index : m_model.intern(Submodel.pName); + record.parent = Parent; + record.legacy_flags = file_flags(Submodel); + m_nodeof.try_emplace(&Submodel, index); + record.range_min_sq = Submodel.fSquareMinDist; + record.range_max_sq = Submodel.fSquareMaxDist; + if ((Submodel.iFlags & 0x4000) != 0) + record.flags |= node_flags::animated; + if (Submodel.iVisible == 0) + record.flags |= node_flags::hidden; + transform(Submodel, index); + // the components of a node lie together, before those of its children + m_model.nodes[index].component_first = static_cast(m_model.components.size()); + components(Submodel, index); + geometry(Submodel, index); + m_model.nodes[index].component_count = static_cast(m_model.components.size()) - m_model.nodes[index].component_first; + siblings(Submodel.Child, static_cast(index)); + m_model.nodes[index].subtree_end = static_cast(m_model.nodes.size()); +} + +void converter::transform(TSubModel const &Submodel, std::uint32_t const Node) { + auto const *matrix{Submodel.GetMatrix()}; + if (matrix == nullptr) + return; + auto const transform{glm::make_mat4(matrix->readArray())}; + if (set_transform(m_model.nodes[Node], transform)) + return; + m_model.nodes[Node].flags |= node_flags::matrix; + transform_record record; + record.node = Node; + std::memcpy(record.matrix.data(), glm::value_ptr(transform), sizeof(float) * 16); + m_model.transforms.push_back(record); +} + +void converter::components(TSubModel const &Submodel, std::uint32_t const Node) { + if (Submodel.eType == TP_FREESPOTLIGHT) { + payload::light light; + light.kind = Submodel.fCosFalloffAngle <= -0.999f ? payload::light_kind::point : payload::light_kind::spot; + light.flags = static_cast((Submodel.bShadeSelf ? payload::light_flags::shade_self : 0) | (Submodel.bCastShadows ? 0 : payload::light_flags::no_shadows) | + (Submodel.bSoftFalloff ? payload::light_flags::soft_falloff : 0) | (Submodel.bLightOnly ? payload::light_flags::light_only : 0) | + (Submodel.bUseNearAtten ? payload::light_flags::near_attenuation : 0)); + light.color = to_array(Submodel.f4Diffuse); + light.hotspot_power = Submodel.fHotspotPower; + light.radius = Submodel.fLightRadius; + light.near_start = Submodel.fNearAttenStart; + light.near_end = Submodel.fNearAttenEnd; + light.far_decay = Submodel.iFarAttenDecay; + light.far_radius = Submodel.fFarDecayRadius; + light.cos_falloff = Submodel.fCosFalloffAngle; + light.cos_hotspot = Submodel.fCosHotspotAngle; + m_model.add_component(component::light, target_kind::node, Node, payload_writer{}.put(light).data()); + } + if (Submodel.is_emitter()) + m_model.add_component(component::emitter, target_kind::node, Node, payload_writer{}.put(payload::emitter{}).data()); + if (Submodel.b_Anim != TAnimType::at_None) + m_model.add_component(component::legacy_animation, target_kind::node, Node, payload_writer{}.put(payload::legacy_animation{static_cast(Submodel.b_Anim)}).data()); + if (Submodel.eType == TP_TEXT) + m_model.add_component(component::legacy_text, target_kind::node, Node, {}); +} + +std::uint32_t converter::material(TSubModel const &Submodel) { + material_record record; + if (Submodel.m_material < 0) { + record.replaceable = std::max(Submodel.m_material, -4); + // the pass of a replaceable skin: bit k-1 of the E3D flags for the skin -k + if ((Submodel.iFlags & (1u << (-record.replaceable - 1))) != 0) + record.flags |= material_flags::translucent; + } + else if (false == Submodel.m_materialname.empty()) + record.name = m_model.intern(Submodel.m_materialname); + record.selfillum = Submodel.fLight; + record.ambient = to_array(Submodel.f4Ambient); + record.diffuse = to_array(Submodel.f4Diffuse); + record.specular = to_array(Submodel.f4Specular); + record.emission = to_array(Submodel.f4Emision); + auto const same{[&record](material_record const &Other) { return std::memcmp(&record, &Other, sizeof(material_record)) == 0; }}; + if (auto const found{std::ranges::find_if(m_model.materials, same)}; found != m_model.materials.end()) + return static_cast(std::distance(m_model.materials.begin(), found)); + m_model.materials.push_back(record); + return static_cast(m_model.materials.size() - 1); +} + +void converter::vertices(TSubModel const &Submodel, gfx::vertex_array const &Vertices, gfx::userdata_array const &Userdata) { + auto const stars{Submodel.eType == TP_STARS}; + for (std::size_t idx = 0; idx < Vertices.size(); ++idx) { + auto const &vertex{Vertices[idx]}; + m_model.positions.push_back({vertex.position.x, vertex.position.y, vertex.position.z}); + attributes attribute; + // the normal of a star is its colour, which goes to the STAR component + if (false == stars) + attribute.qtangent = encode_qtangent({vertex.normal, glm::vec3{vertex.tangent}, vertex.tangent.w}); + attribute.uv = {vertex.texture.x, vertex.texture.y}; + m_model.vertex_attributes.push_back(attribute); + if (m_userdata) { + auto const data{idx < Userdata.size() ? Userdata[idx].data : glm::vec4{0.f, 0.f, 0.f, 1.f}}; + m_model.vertex_userdata.push_back({data.x, data.y, data.z, data.w}); + } + } +} + +void converter::indices(TSubModel const &Submodel, gfx::index_array const &Indices, primitive_record &Primitive) { + if (auto const last{std::ranges::max(Indices)}; last >= Primitive.vertex_count) + m_faults.push_back(std::format("submodel \"{}\" has index {} past its {} vertices", Submodel.pName, last, Primitive.vertex_count)); + Primitive.flags |= primitive_flags::indexed; + if (Primitive.vertex_count <= 65536) { + Primitive.first_index = static_cast(m_model.indices16.size()); + for (auto const index : Indices) + m_model.indices16.push_back(static_cast(index)); + } + else { + Primitive.flags |= primitive_flags::index32; + Primitive.first_index = static_cast(m_model.indices32.size()); + m_model.indices32.insert(m_model.indices32.end(), Indices.begin(), Indices.end()); + } + Primitive.index_count = static_cast(Indices.size()); +} + +void converter::stars(gfx::vertex_array const &Vertices, std::uint32_t const Node) { + payload_writer writer; + writer.put(payload::legacy_stars{static_cast(Vertices.size())}); + for (auto const &vertex : Vertices) + writer.put(pack_colour(vertex.normal)); + m_model.add_component(component::legacy_stars, target_kind::node, Node, writer.data()); +} + +void converter::geometry(TSubModel const &Submodel, std::uint32_t const Node) { + auto const drawable{(Submodel.eType >= 0 && Submodel.eType <= gl_primitive_last) || Submodel.eType == TP_STARS}; + if (false == drawable || Submodel.m_geometry.handle == null_handle || Submodel.m_geometry.vertex_count <= 0) + return; + auto const &vertexdata{GfxRenderer->Vertices(Submodel.m_geometry.handle)}; + if (vertexdata.empty()) + return; + primitive_record primitive; + primitive.base_vertex = static_cast(m_model.positions.size()); + primitive.vertex_count = static_cast(vertexdata.size()); + primitive.node = Node; + primitive.material = material(Submodel); + auto const kind{Submodel.eType == TP_STARS ? 0u : static_cast(Submodel.eType)}; + auto const flags{file_flags(Submodel)}; + primitive.flags = kind | ((flags & 0x10) != 0 ? primitive_flags::opaque : 0u) | ((flags & 0x20) != 0 ? primitive_flags::translucent : 0u); + vertices(Submodel, vertexdata, GfxRenderer->UserData(Submodel.m_geometry.handle)); + if (auto const &indexdata{GfxRenderer->Indices(Submodel.m_geometry.handle)}; false == indexdata.empty()) + indices(Submodel, indexdata, primitive); + else + primitive.index_count = primitive.vertex_count; + mesh_record mesh; + mesh.primitive_first = static_cast(m_model.primitives.size()); + mesh.primitive_count = 1; + if (m_userdata) + mesh.flags |= mesh_flags::userdata; + m_model.primitives.push_back(primitive); + m_model.nodes[Node].mesh = static_cast(m_model.meshes.size()); + m_model.meshes.push_back(mesh); + if (Submodel.eType == TP_STARS) + stars(vertexdata, Node); +} + +void converter::light_slots() { + // the numbered lights the lights event of the scenery switches (TModel3d::instance_parts) + // the submodel the game finds by the name (GetFromName, which looks at the following submodels before the children), so + // with two of one name the same one counts + auto const found{[this](std::string const &Name) -> std::optional { + auto const *submodel{m_source.GetFromName(Name)}; + if (submodel == nullptr) + return std::nullopt; + auto const lookup{m_nodeof.find(submodel)}; + return lookup == m_nodeof.end() ? std::nullopt : std::optional{lookup->second}; + }}; + for (int slot = 0; slot < 8; ++slot) { + auto const on{found(std::format("Light_On{:02}", slot))}; + auto const off{found(std::format("Light_Off{:02}", slot))}; + if (false == on.has_value() && false == off.has_value()) + continue; + payload::light_slot record; + record.slot = static_cast(slot); + record.on_count = on.has_value() ? 1 : 0; + record.off_count = off.has_value() ? 1 : 0; + payload_writer writer; + writer.put(record); + if (on.has_value()) + writer.put(*on); + if (off.has_value()) + writer.put(*off); + m_model.add_component(component::light_slot, target_kind::model, 0, writer.data()); + } +} + +std::string extension_of(std::string const &Path) { + auto const dot{Path.rfind('.')}; + return dot == std::string::npos ? std::string{} : ToLower(Path.substr(dot)); +} + +int command_convert(int const Argc, char *Argv[]) { + if (Argc < 5) { + std::cerr << "usage: -e4d convert [dynamic 0|1] [convertmodels flags]\n"; + return 2; + } + std::string const input{Argv[3]}; + std::string const output{Argv[4]}; + auto const dynamic{Argc > 5 && std::string_view{Argv[5]} == "1"}; + if (dynamic && extension_of(input) != ".e3d") { + // the game prepares a vehicle's text model only after the vehicle marked its animated parts (WillBeAnimated); made here + // at once, their vertices would be turned into the frame of the model instead of keeping their matrices + std::cerr << "a vehicle's model is converted from the .e3d the game makes of it (convertmodels), not from its .t3d\n"; + return 2; + } + Global.iConvertModels = 0; + if (Argc > 6) { + auto const flags{std::string_view{Argv[6]}}; + if (auto const [end, error]{std::from_chars(flags.data(), flags.data() + flags.size(), Global.iConvertModels)}; error != std::errc{} || end != flags.data() + flags.size()) { + std::cerr << std::format("the convertmodels flags \"{}\" aren't a number\n", flags); + return 2; + } + } + Global.iWriteLogEnabled = 2; + GfxRenderer = gfx_renderer_factory::get_instance()->create("null"); + TModel3d source; + if (extension_of(input) == ".e3d") + source.LoadFromBinFile(input, dynamic); + else + source.LoadFromTextFile(input, dynamic); + source.Init(); + if (source.GetSMRoot() == nullptr) { + std::cerr << std::format("can't load model \"{}\"\n", input); + return 1; + } + std::vector faults; + auto converted{convert(source, faults)}; + for (auto const &fault : faults) + std::cerr << std::format("{}: {}\n", input, fault); + auto const file{read_whole_file(input)}; + converted.source_hash = hash_bytes(std::as_bytes(std::span{file.data.get(), file.size})); + converted.edit.push_back({converted.intern(input), converted.intern("eu07 -e4d convert"), {}}); + if (auto const problems{validate(converted)}; false == problems.empty()) { + for (auto const &problem : problems) + std::cerr << std::format("the converted model is invalid: {}\n", problem); + return 1; + } + auto const bytes{write(converted)}; + std::ofstream stream{output, std::ios::binary | std::ios::trunc}; + stream.write(reinterpret_cast(bytes.data()), static_cast(bytes.size())); + if (false == stream.good()) { + std::cerr << std::format("can't write \"{}\"\n", output); + return 1; + } + std::cout << std::format("{} -> {}: {} nodes, {} vertices, {} bytes\n", input, output, converted.nodes.size(), converted.vertex_count(), bytes.size()); + return 0; +} + +int command_read(int const Argc, char *Argv[], bool const Dump) { + if (Argc < 4) { + std::cerr << std::format("usage: -e4d {} \n", Dump ? "dump" : "validate"); + return 2; + } + auto const file{read_whole_file(Argv[3])}; + if (file.data == nullptr) { + std::cerr << std::format("can't read \"{}\"\n", Argv[3]); + return 1; + } + model loaded; + auto const result{read(std::as_bytes(std::span{file.data.get(), file.size}), loaded, {true, true})}; + if (false == result.ok) { + std::cerr << std::format("{}: {}\n", Argv[3], result.error); + return 1; + } + if (Dump) + std::cout << dump(loaded); + else + std::cout << std::format("{}: valid, {} nodes, {} vertices\n", Argv[3], loaded.nodes.size(), loaded.vertex_count()); + return 0; +} + +} // namespace + +model convert(TModel3d &Source, std::vector &Faults) { + return converter{Source, Faults}.run(); +} + +int run_command_line(int const Argc, char *Argv[]) { + std::string_view const command{Argc > 2 ? Argv[2] : ""}; + if (command == "convert") + return command_convert(Argc, Argv); + if (command == "dump") + return command_read(Argc, Argv, true); + if (command == "validate") + return command_read(Argc, Argv, false); + std::cerr << "usage: -e4d convert|dump|validate ...\n"; + return 2; +} + +} // namespace e4d diff --git a/model/e4d/e4d_convert.h b/model/e4d/e4d_convert.h new file mode 100644 index 000000000..9dc8499fc --- /dev/null +++ b/model/e4d/e4d_convert.h @@ -0,0 +1,31 @@ +/* +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/. +*/ + +#pragma once + +// the conversion of a model loaded from E3D or T3D into E4D, and the -e4d commands of the program + +#include "model/e4d/e4d_model.h" + +#include +#include + +class TModel3d; + +namespace e4d { + +// the E4D form of the loaded model, its geometry taken from the renderer's banks (as SaveToBinFile does). the name index +// and the bounds are filled in; the source hash is left to the caller. the faults of the source found on the way, which +// leave the result invalid, are added to Faults, each naming its submodel +model convert(TModel3d &Source, std::vector &Faults); + +// the -e4d commands: convert, dump, validate. returns the exit code of the program +int run_command_line(int Argc, char *Argv[]); + +} // namespace e4d diff --git a/model/e4d/e4d_dump.cpp b/model/e4d/e4d_dump.cpp new file mode 100644 index 000000000..8dcd0925e --- /dev/null +++ b/model/e4d/e4d_dump.cpp @@ -0,0 +1,116 @@ +/* +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 "model/e4d/e4d_dump.h" + +#include + +namespace e4d { + +std::string fourcc_name(std::uint32_t const Id) { + std::string text(4, ' '); + for (std::size_t idx = 0; idx < 4; ++idx) { + auto const character{static_cast((Id >> (idx * 8)) & 0xFF)}; + text[idx] = (character >= 32 && character < 127) ? character : '?'; + } + return text; +} + +namespace { + +std::string_view topology_name(std::uint32_t const Flags) { + switch (static_cast(Flags & primitive_flags::topology_mask)) { + case topology::points: return "points"; + case topology::lines: return "lines"; + case topology::line_loop: return "line loop"; + case topology::line_strip: return "line strip"; + case topology::triangles: return "triangles"; + case topology::triangle_strip: return "triangle strip"; + case topology::triangle_fan: return "triangle fan"; + default: return "?"; + } +} + +std::string quoted(model const &Model, std::uint32_t const Id) { + return Id == no_index ? std::string{"-"} : std::format("\"{}\"", Model.string(Id)); +} + +void dump_counts(model const &Model, std::string &Output) { + Output += std::format("flags: {:#x}, source hash: {:#018x}\n", Model.flags, Model.source_hash); + Output += std::format("strings: {}, nodes: {} (matrices {}), meshes: {}, primitives: {}, materials: {}\n", Model.strings.size(), Model.nodes.size(), Model.transforms.size(), + Model.meshes.size(), Model.primitives.size(), Model.materials.size()); + Output += std::format("vertices: {}, indices: {} x u16 + {} x u32, weights: {} + {} wide, userdata: {}, bindings: {}\n", Model.vertex_count(), Model.indices16.size(), + Model.indices32.size(), Model.weights.size(), Model.weights_wide.size(), Model.vertex_userdata.size(), Model.bindings.size()); + Output += std::format("skins: {} ({} joints), vertex groups: {}, components: {} ({} bytes), bounds: {}, name index: {}\n", Model.skins.size(), Model.skin_joints.size(), + Model.vertex_groups.size(), Model.components.size(), Model.component_data.size(), Model.bounds.size(), Model.name_index.size()); + for (auto const §ion : Model.unknown) + Output += std::format("unknown section {}: {} bytes\n", fourcc_name(section.id), section.data.size()); +} + +void dump_primitives(model const &Model, mesh_record const &Mesh, std::string_view const Indent, std::string &Output) { + for (auto idx = Mesh.primitive_first; idx < Mesh.primitive_first + Mesh.primitive_count && idx < Model.primitives.size(); ++idx) { + auto const &primitive{Model.primitives[idx]}; + auto const material{primitive.material < Model.materials.size() ? Model.materials[primitive.material] : material_record{}}; + auto const materialname{material.replaceable != 0 ? std::format("skin {}", material.replaceable) : quoted(Model, material.name)}; + Output += std::format("{} {} {}{}, vertices {}+{}, indices {}+{}, material {}, flags {:#x}\n", Indent, topology_name(primitive.flags), + (primitive.flags & primitive_flags::indexed) != 0 ? "indexed" : "plain", (primitive.flags & primitive_flags::index32) != 0 ? " u32" : "", primitive.base_vertex, + primitive.vertex_count, primitive.first_index, primitive.index_count, materialname, primitive.flags); + } +} + +void dump_components(model const &Model, std::uint32_t const First, std::uint32_t const Count, std::string_view const Indent, std::string &Output) { + for (auto idx = First; idx < First + Count && idx < Model.components.size(); ++idx) { + auto const &component{Model.components[idx]}; + Output += std::format("{} [{}] {} v{}, {} bytes\n", Indent, idx, fourcc_name(component.type), component.version, component.data_size); + } +} + +void dump_nodes(model const &Model, std::string &Output) { + std::vector depth(Model.nodes.size(), 0); + for (std::uint32_t idx = 0; idx < Model.nodes.size(); ++idx) { + auto const &node{Model.nodes[idx]}; + if (node.parent >= 0 && node.parent < static_cast(idx)) + depth[idx] = depth[node.parent] + 1; + std::string const indent(static_cast(depth[idx]) * 2, ' '); + Output += std::format("{}{} {} t({:.4f} {:.4f} {:.4f}) r({:.4f} {:.4f} {:.4f} {:.4f}) s({:.4f} {:.4f} {:.4f}){}{} range {:.1f}-{:.1f} legacy {:#x}\n", indent, idx, + quoted(Model, node.name), node.translation[0], node.translation[1], node.translation[2], node.rotation[0], node.rotation[1], node.rotation[2], node.rotation[3], + node.scale[0], node.scale[1], node.scale[2], (node.flags & node_flags::matrix) != 0 ? " matrix" : "", (node.flags & node_flags::animated) != 0 ? " animated" : "", + std::sqrt(node.range_min_sq), std::sqrt(node.range_max_sq), node.legacy_flags); + if (node.mesh >= 0 && node.mesh < static_cast(Model.meshes.size())) + dump_primitives(Model, Model.meshes[node.mesh], indent, Output); + dump_components(Model, node.component_first, node.component_count, indent, Output); + } +} + +void dump_model_components(model const &Model, std::string &Output) { + for (std::uint32_t idx = 0; idx < Model.components.size(); ++idx) { + auto const &component{Model.components[idx]}; + if (component.kind == target_kind::model) + Output += std::format("model component [{}] {} v{}, {} bytes\n", idx, fourcc_name(component.type), component.version, component.data_size); + } +} + +} // namespace + +std::string dump(model const &Model) { + std::string output; + dump_counts(Model, output); + dump_nodes(Model, output); + dump_model_components(Model, output); + if (false == Model.bounds.empty()) { + auto const &whole{Model.bounds.back()}; + output += std::format("bounds: ({:.3f} {:.3f} {:.3f}) - ({:.3f} {:.3f} {:.3f}), radius {:.3f}\n", whole.min[0], whole.min[1], whole.min[2], whole.max[0], whole.max[1], whole.max[2], + whole.sphere[3]); + } + return output; +} + +} // namespace e4d diff --git a/model/e4d/e4d_dump.h b/model/e4d/e4d_dump.h new file mode 100644 index 000000000..73acab2ab --- /dev/null +++ b/model/e4d/e4d_dump.h @@ -0,0 +1,24 @@ +/* +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/. +*/ + +#pragma once + +// the content of an E4D model as text, for people and for comparing two files + +#include "model/e4d/e4d_model.h" + +#include + +namespace e4d { + +std::string dump(model const &Model); + +std::string fourcc_name(std::uint32_t Id); + +} // namespace e4d diff --git a/model/e4d/e4d_format.h b/model/e4d/e4d_format.h new file mode 100644 index 000000000..9f67d7ffc --- /dev/null +++ b/model/e4d/e4d_format.h @@ -0,0 +1,566 @@ +/* +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/. +*/ + +#pragma once + +// the records of the E4D model format, as they lie in the file. docs/e4d-format.md describes them; the sizes and offsets +// below are the format, and the static_asserts keep the two the same + +#include +#include +#include +#include +#include + +namespace e4d { + +static_assert(std::endian::native == std::endian::little, "the E4D records are read and uploaded to the gpu as they lie in the file, little-endian"); + +constexpr std::uint32_t fourcc(std::string_view const Code) { + return static_cast(static_cast(Code[0])) | (static_cast(static_cast(Code[1])) << 8) | + (static_cast(static_cast(Code[2])) << 16) | (static_cast(static_cast(Code[3])) << 24); +} + +constexpr std::uint16_t version_major{1}; +constexpr std::uint16_t version_minor{0}; +constexpr std::uint32_t no_index{0xFFFFFFFFu}; // no string, node, component and the like +constexpr std::size_t gpu_alignment{64}; // the vertex and index streams +constexpr std::size_t section_alignment{16}; // every other section + +// the sections +namespace section { +constexpr std::uint32_t strings{fourcc("STRS")}; +constexpr std::uint32_t name_index{fourcc("NIDX")}; +constexpr std::uint32_t nodes{fourcc("NODE")}; +constexpr std::uint32_t transforms{fourcc("XFRM")}; +constexpr std::uint32_t meshes{fourcc("MESH")}; +constexpr std::uint32_t primitives{fourcc("PRIM")}; +constexpr std::uint32_t positions{fourcc("VPOS")}; +constexpr std::uint32_t attributes{fourcc("VATT")}; +constexpr std::uint32_t skin_weights{fourcc("VSKN")}; +constexpr std::uint32_t skin_weights_wide{fourcc("VSKW")}; +constexpr std::uint32_t userdata{fourcc("VUSR")}; +constexpr std::uint32_t bindings{fourcc("VBND")}; +constexpr std::uint32_t indices16{fourcc("IDX2")}; +constexpr std::uint32_t indices32{fourcc("IDX4")}; +constexpr std::uint32_t materials{fourcc("MATL")}; +constexpr std::uint32_t skins{fourcc("SKIN")}; +constexpr std::uint32_t skin_joints{fourcc("SKJT")}; +constexpr std::uint32_t vertex_groups{fourcc("VGRP")}; +constexpr std::uint32_t vertex_group_items{fourcc("VGIT")}; +constexpr std::uint32_t vertex_group_weights{fourcc("VGWT")}; +constexpr std::uint32_t components{fourcc("CMPT")}; +constexpr std::uint32_t component_data{fourcc("CDAT")}; +constexpr std::uint32_t bounds{fourcc("BNDS")}; +constexpr std::uint32_t edit{fourcc("EDIT")}; +} // namespace section + +// the components +namespace component { +constexpr std::uint32_t properties{fourcc("PROP")}; +constexpr std::uint32_t socket{fourcc("SOCK")}; +constexpr std::uint32_t joint{fourcc("JOIN")}; +constexpr std::uint32_t spring{fourcc("SPRG")}; +constexpr std::uint32_t chain{fourcc("CHAN")}; +constexpr std::uint32_t variants{fourcc("VARI")}; +constexpr std::uint32_t channel{fourcc("CHNL")}; +constexpr std::uint32_t light_slot{fourcc("LSLT")}; +constexpr std::uint32_t light{fourcc("LGHT")}; +constexpr std::uint32_t emitter{fourcc("EMIT")}; +constexpr std::uint32_t model_reference{fourcc("MREF")}; +constexpr std::uint32_t collision{fourcc("COLL")}; +constexpr std::uint32_t legacy_animation{fourcc("LANM")}; +constexpr std::uint32_t legacy_text{fourcc("LTXT")}; +constexpr std::uint32_t legacy_stars{fourcc("STAR")}; +} // namespace component + +struct file_header { + std::array magic{'E', '4', 'D', '\0'}; + std::uint16_t major{version_major}; + std::uint16_t minor{version_minor}; + std::uint32_t flags{0}; + std::uint32_t section_count{0}; + std::uint64_t toc_offset{0}; + std::uint64_t file_size{0}; + std::uint64_t content_hash{0}; // FNV-1a 64 of the bytes after the header + std::uint64_t source_hash{0}; // of the file the model was made from, so the tools know when to make it again + std::array reserved{}; +}; +static_assert(sizeof(file_header) == 64); +static_assert(offsetof(file_header, toc_offset) == 16); + +namespace file_flags { +constexpr std::uint32_t optimized{0x1}; // the index order was optimised; a file straight from the exporter has it clear +} + +struct section_entry { + std::uint32_t id{0}; + std::uint32_t flags{0}; + std::uint64_t offset{0}; + std::uint64_t stored_size{0}; // in the file + std::uint64_t size{0}; // unpacked +}; +static_assert(sizeof(section_entry) == 32); + +namespace section_flags { +constexpr std::uint32_t required{0x1}; // a reader which doesn't know the section refuses the file +constexpr std::uint32_t zstd{0x2}; +} + +// the head of a section holding a table of records. the stride lets a later version add fields at the end of a record +struct table_header { + std::uint32_t count{0}; + std::uint32_t stride{0}; +}; +static_assert(sizeof(table_header) == 8); + +struct name_index_record { + std::uint64_t hash{0}; // FNV-1a 64 of the name in ASCII lowercase + std::uint32_t node{0}; + std::uint32_t reserved{0}; +}; +static_assert(sizeof(name_index_record) == 16); + +namespace node_flags { +constexpr std::uint32_t animated{0x1}; // moved at run time, keeps its own transform +constexpr std::uint32_t hidden{0x2}; // not drawn until something shows it +constexpr std::uint32_t matrix{0x4}; // the transform is the matrix in XFRM, the TRS fields are only an approximation +} + +struct node_record { + std::uint32_t name{no_index}; + std::int32_t parent{-1}; + std::uint32_t subtree_end{0}; // one past the last node of the subtree (nodes are in depth-first order) + std::uint32_t flags{0}; + std::array translation{0.f, 0.f, 0.f}; + std::array rotation{0.f, 0.f, 0.f, 1.f}; // quaternion x, y, z, w + std::array scale{1.f, 1.f, 1.f}; + std::int32_t mesh{-1}; + std::uint32_t component_first{0}; + std::uint32_t component_count{0}; + float range_min_sq{0.f}; // squared distance from the camera from which it is drawn + float range_max_sq{0.f}; // squared distance up to which it is drawn; 0 means no limit + std::uint32_t legacy_flags{0}; // iFlags of the E3D submodel it came from, 0 for a model made anew +}; +static_assert(sizeof(node_record) == 80); +static_assert(offsetof(node_record, translation) == 16); +static_assert(offsetof(node_record, mesh) == 56); + +struct transform_record { + std::uint32_t node{0}; + std::array reserved{}; + std::array matrix{}; // column-major +}; +static_assert(sizeof(transform_record) == 80); + +namespace mesh_flags { +constexpr std::uint32_t userdata{0x1}; // the model of E3D had user data for the vertices of this mesh (or of another) +} + +struct mesh_record { + std::uint32_t primitive_first{0}; + std::uint32_t primitive_count{0}; + std::int32_t skin{-1}; + std::uint32_t flags{0}; +}; +static_assert(sizeof(mesh_record) == 16); + +enum class topology : std::uint8_t { + points = 0, + lines = 1, + line_loop = 2, + line_strip = 3, + triangles = 4, + triangle_strip = 5, + triangle_fan = 6 +}; + +namespace primitive_flags { +constexpr std::uint32_t topology_mask{0xF}; +constexpr std::uint32_t indexed{0x10}; +constexpr std::uint32_t index32{0x20}; // the indices are in IDX4, else in IDX2 +constexpr std::uint32_t opaque{0x40}; // drawn in the opaque pass +constexpr std::uint32_t translucent{0x80}; // drawn in the translucent pass +constexpr std::uint32_t no_shadow{0x100}; +// the vertices of the primitive follow the joints named in VBND, each with a weight of 1: parts of several nodes merged +// into one draw. the joints are those of the skin of the primitive; the vertex shader takes the matrix, without skinning +constexpr std::uint32_t rigid_joints{0x200}; +// the vertices of the primitive are lit, dimmed or hidden by the light slots named in VBND +constexpr std::uint32_t light_slots{0x400}; +constexpr std::uint32_t lod_shift{16}; // bits 16-23: level of detail, 0 is the most detailed +constexpr std::uint32_t lod_mask{0xFF0000}; +} // namespace primitive_flags + +struct primitive_record { + std::uint32_t first_index{0}; // in IDX2 or IDX4, in elements; for a primitive without indices, the first vertex past base_vertex + std::uint32_t index_count{0}; // for a primitive without indices, the count of vertices drawn + std::uint32_t base_vertex{0}; // into the vertex streams + std::uint32_t vertex_count{0}; + std::uint32_t material{no_index}; + std::uint32_t node{0}; + std::int32_t skin{-1}; + std::uint32_t flags{0}; + std::array sphere{0.f, 0.f, 0.f, 0.f}; // centre and radius, in the space of the node +}; +static_assert(sizeof(primitive_record) == 48); + +// the vertex streams. every stream present has one element per vertex of the file +using position = std::array; +static_assert(sizeof(position) == 12); + +struct attributes { + std::array qtangent{0, 0, 0, 32767}; // snorm16 quaternion of the tangent frame; w < 0 flips the bitangent + std::array uv{0.f, 0.f}; +}; +static_assert(sizeof(attributes) == 16); + +struct skin_weights { + std::array joints{}; // into the joints of the skin of the mesh + std::array weights{}; // unorm8, summing to 255 +}; +static_assert(sizeof(skin_weights) == 8); + +struct skin_weights_wide { + std::array joints{}; + std::array weights{}; // unorm16, summing to 65535 +}; +static_assert(sizeof(skin_weights_wide) == 16); + +using userdata = std::array; +static_assert(sizeof(userdata) == 16); + +// what a vertex of a merged primitive belongs to +enum class slot_role : std::uint8_t { + none = 0, // not tied to a light slot + lit = 1, // shown, and glowing, while the slot is lit (the Light_On## of E3D) + dark = 2 // shown while the slot is dark (the Light_Off## of E3D) +}; + +struct vertex_binding { + std::uint8_t joint{0}; // with primitive_flags::rigid_joints: into the joints of the skin of the primitive + std::uint8_t slot{0}; // with primitive_flags::light_slots: the light slot (the slot of an LSLT) + slot_role role{slot_role::none}; + std::uint8_t reserved{0}; // 0; a later version may use it, a reader ignores it +}; +static_assert(sizeof(vertex_binding) == 4); + +namespace material_flags { +constexpr std::uint32_t translucent{0x1}; // the replaceable skin decides the pass (bits 0-3 of the E3D flags) +} + +struct material_record { + std::uint32_t name{no_index}; // the .mat file or texture; no_index draws in the colours below only + std::int32_t replaceable{0}; // 0, or the replaceable skin -1..-4 used instead of the name + std::uint32_t flags{0}; + float selfillum{-1.f}; // the light level below which the material glows (fLight of E3D) + std::array ambient{1.f, 1.f, 1.f, 1.f}; + std::array diffuse{1.f, 1.f, 1.f, 1.f}; + std::array specular{0.f, 0.f, 0.f, 1.f}; + std::array emission{1.f, 1.f, 1.f, 1.f}; +}; +static_assert(sizeof(material_record) == 80); + +struct skin_record { + std::uint32_t joint_first{0}; // in SKJT + std::uint32_t joint_count{0}; + std::int32_t root{-1}; // the node the skin hangs from + std::uint32_t reserved{0}; +}; +static_assert(sizeof(skin_record) == 16); + +struct skin_joint_record { + std::uint32_t node{0}; + std::array reserved{}; + std::array inverse_bind{}; // 3x4, column-major: four columns of three +}; +static_assert(sizeof(skin_joint_record) == 64); + +namespace vertex_group_flags { +constexpr std::uint32_t ranges{0x1}; // the items are pairs (first vertex, count), else single vertices +constexpr std::uint32_t weighted{0x2}; // VGWT holds an unorm8 weight for each item +} // namespace vertex_group_flags + +struct vertex_group_record { + std::uint32_t name{no_index}; + std::uint32_t mesh{0}; + std::uint32_t item_first{0}; // in VGIT (and VGWT) + std::uint32_t item_count{0}; + std::uint32_t flags{0}; + std::uint32_t component_first{0}; + std::uint32_t component_count{0}; + std::uint32_t reserved{0}; +}; +static_assert(sizeof(vertex_group_record) == 32); + +enum class target_kind : std::uint8_t { + model = 0, + node = 1, + mesh = 2, + vertex_group = 3 +}; + +struct component_record { + std::uint32_t type{0}; + std::uint16_t version{1}; + target_kind kind{target_kind::node}; + std::uint8_t flags{0}; + std::uint32_t target{0}; + std::uint32_t data_offset{0}; // in CDAT, 4-byte aligned + std::uint32_t data_size{0}; +}; +static_assert(sizeof(component_record) == 20); + +struct bounds_record { + std::array min{0.f, 0.f, 0.f}; + std::array max{0.f, 0.f, 0.f}; + std::array sphere{0.f, 0.f, 0.f, 0.f}; +}; +static_assert(sizeof(bounds_record) == 40); + +// the payloads of the components, version 1. a payload may be longer than the struct, the rest is read by the +// variable-length parts described with each type +namespace payload { + +enum class value_type : std::uint8_t { + boolean = 0, + integer = 1, + real = 2, + vec2 = 3, + vec3 = 4, + vec4 = 5, + string = 6, // string id in value[0] + node = 7, // node index in value[0] + component = 8 // component index in value[0] +}; + +struct property { + std::uint32_t key{no_index}; + value_type type{value_type::real}; + std::array reserved{}; + std::array value{}; // the bits of the value; a real is a float, an integer an int32 +}; +static_assert(sizeof(property) == 24); +// PROP: std::uint32_t count, then count property records + +enum class side : std::uint8_t { + none = 0, + front = 1, + rear = 2 +}; + +struct socket { + std::uint32_t role{no_index}; + side end{side::none}; + std::uint8_t reserved{0}; + std::uint16_t index{0}; + std::array position{0.f, 0.f, 0.f}; // in the space of the node + std::array rotation{0.f, 0.f, 0.f, 1.f}; +}; +static_assert(sizeof(socket) == 36); + +enum class joint_kind : std::uint8_t { + fixed = 0, + hinge = 1, + ball = 2, + slider = 3, + screw = 4 +}; + +struct joint { + joint_kind kind{joint_kind::hinge}; + std::uint8_t limited{0}; + std::uint16_t reserved{0}; + std::uint32_t role{no_index}; + std::array axis{1.f, 0.f, 0.f}; // in the space of the node + float minimum{0.f}; // radians or metres + float maximum{0.f}; + float rest{0.f}; + float pitch{0.f}; // metres per turn of a screw +}; +static_assert(sizeof(joint) == 36); + +enum class spring_mode : std::uint8_t { + follow = 0, + stretch = 1, + aim = 2, + pendulum = 3 +}; + +struct spring { + spring_mode mode{spring_mode::follow}; + std::uint8_t sideways{0}; // a pendulum may swing sideways too + std::uint16_t reserved{0}; + std::uint32_t anchor_a{no_index}; // node + std::uint32_t socket_a{no_index}; // component, or no_index for the origin of the node + std::uint32_t anchor_b{no_index}; + std::uint32_t socket_b{no_index}; + std::array axis{0.f, 1.f, 0.f}; + float rest_length{0.f}; + float travel_min{0.f}; + float travel_max{0.f}; + float pendulum_length{0.f}; + float pendulum_damping{0.f}; +}; +static_assert(sizeof(spring) == 52); + +enum class chain_kind : std::uint8_t { + hose_brake = 0, + hose_main = 1, + cable = 2, + bellows = 3, + other = 4 +}; + +struct chain { + chain_kind kind{chain_kind::other}; + std::uint8_t reserved{0}; + std::uint16_t joint_count{0}; + std::int32_t skin{-1}; + float min_bend_radius{0.f}; + float stiffness{0.f}; + float head_mass{0.f}; + float head_length{0.f}; + std::uint32_t end_a{no_index}; // socket components + std::uint32_t end_b{no_index}; +}; +static_assert(sizeof(chain) == 32); +// CHAN: the chain, then joint_count node indices (std::uint32_t), then joint_count - 1 rest lengths of the segments (float) + +struct variants { + std::uint32_t name{no_index}; + std::uint16_t state_count{0}; + std::uint16_t default_state{0}; +}; +static_assert(sizeof(variants) == 8); +struct variant_state { + std::uint32_t name{no_index}; + std::uint32_t node_first{0}; // in the node list after the states + std::uint32_t node_count{0}; +}; +static_assert(sizeof(variant_state) == 12); +// VARI: the variants, then state_count variant_state records, then the node list (std::uint32_t) + +enum class binding_kind : std::uint8_t { + joint = 0, + clip = 1, + variants = 2, + light_slot = 3 +}; + +struct channel { + std::uint32_t name{no_index}; + float minimum{0.f}; + float maximum{1.f}; + float initial{0.f}; + std::uint16_t binding_count{0}; + std::uint16_t reserved{0}; +}; +static_assert(sizeof(channel) == 20); +struct channel_binding { + binding_kind kind{binding_kind::joint}; + std::array reserved{}; + std::uint32_t target{no_index}; // component + float scale{1.f}; // target value = channel value * scale + offset + float offset{0.f}; +}; +static_assert(sizeof(channel_binding) == 16); +// CHNL: the channel, then binding_count channel_binding records + +struct light_slot { + std::uint16_t slot{0}; + std::uint16_t reserved{0}; + float initial{0.f}; // the state, coded as the values of the lights event + std::array color{-1.f, -1.f, -1.f}; // negative: the colour of the light sources + std::uint16_t on_count{0}; + std::uint16_t off_count{0}; + std::uint16_t light_count{0}; + std::uint16_t reserved2{0}; +}; +static_assert(sizeof(light_slot) == 28); +// LSLT: the slot, then on_count nodes shown when lit, off_count nodes shown when dark, light_count LGHT components (all std::uint32_t) + +enum class light_kind : std::uint8_t { + point = 0, + spot = 1 +}; + +namespace light_flags { +constexpr std::uint8_t shade_self{0x1}; +constexpr std::uint8_t no_shadows{0x2}; +constexpr std::uint8_t soft_falloff{0x4}; +constexpr std::uint8_t light_only{0x8}; +constexpr std::uint8_t near_attenuation{0x10}; +} // namespace light_flags + +struct light { + light_kind kind{light_kind::spot}; + std::uint8_t flags{0}; + std::uint16_t reserved{0}; + std::array color{1.f, 1.f, 1.f, 1.f}; + float hotspot_power{1.f}; + float radius{0.f}; + float near_start{40.f}; + float near_end{80.f}; + std::int32_t far_decay{0}; + float far_radius{100.f}; + float cos_falloff{0.5f}; + float cos_hotspot{0.3f}; +}; +static_assert(sizeof(light) == 52); + +enum class emitter_kind : std::uint8_t { + smoke = 0, + steam = 1, + sparks = 2 +}; + +struct emitter { + emitter_kind kind{emitter_kind::smoke}; + std::array reserved{}; + std::array direction{0.f, 1.f, 0.f}; +}; +static_assert(sizeof(emitter) == 16); + +struct model_reference { + std::uint32_t path{no_index}; + std::uint32_t socket{no_index}; // component; no_index for the origin of the node + std::uint32_t skin{no_index}; // string, the skin of the model put in +}; +static_assert(sizeof(model_reference) == 12); + +enum class shape : std::uint8_t { + box = 0, + sphere = 1, + capsule = 2 +}; + +struct collision { + shape kind{shape::box}; + std::array reserved{}; + std::uint32_t role{no_index}; + std::array centre{0.f, 0.f, 0.f}; + std::array rotation{0.f, 0.f, 0.f, 1.f}; + std::array size{0.f, 0.f, 0.f}; // half extents; a sphere uses x, a capsule x (radius) and y (half length) +}; +static_assert(sizeof(collision) == 48); + +struct legacy_animation { + std::uint32_t type{0}; // the TAnimType of E3D +}; +static_assert(sizeof(legacy_animation) == 4); + +struct legacy_stars { + std::uint32_t count{0}; +}; +static_assert(sizeof(legacy_stars) == 4); +// STAR: the count, then count packed RGB colours (std::uint32_t), one for each vertex of the mesh of the node + +} // namespace payload + +} // namespace e4d diff --git a/model/e4d/e4d_io.cpp b/model/e4d/e4d_io.cpp new file mode 100644 index 000000000..6fb0fe449 --- /dev/null +++ b/model/e4d/e4d_io.cpp @@ -0,0 +1,966 @@ +/* +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 "model/e4d/e4d_io.h" +#include "model/e4d/e4d_dump.h" + +#include "zstd.h" + +#include +#include +#include +#include + +namespace e4d { + +std::uint32_t model::intern(std::string_view const Text) { + if (m_stringids.size() != strings.size()) { + // the strings were filled from outside (the reader), the lookup is made anew + m_stringids.clear(); + for (std::uint32_t idx = 0; idx < strings.size(); ++idx) + m_stringids.try_emplace(strings[idx], idx); + } + if (auto const lookup{m_stringids.find(std::string{Text})}; lookup != m_stringids.end()) + return lookup->second; + auto const id{static_cast(strings.size())}; + strings.emplace_back(Text); + m_stringids.try_emplace(strings.back(), id); + return id; +} + +std::string_view model::string(std::uint32_t const Id) const { + return Id < strings.size() ? std::string_view{strings[Id]} : std::string_view{}; +} + +std::uint32_t model::add_component(std::uint32_t const Type, target_kind const Kind, std::uint32_t const Target, std::span const Data, std::uint16_t const Version) { + // the payloads start at multiples of 4, so their fields can be read in place + while (component_data.size() % 4 != 0) + component_data.push_back(std::byte{0}); + component_record record; + record.type = Type; + record.version = Version; + record.kind = Kind; + record.target = Target; + record.data_offset = static_cast(component_data.size()); + record.data_size = static_cast(Data.size()); + component_data.insert(component_data.end(), Data.begin(), Data.end()); + components.push_back(record); + return static_cast(components.size() - 1); +} + +std::span model::component_payload(std::uint32_t const Component) const { + if (Component >= components.size()) + return {}; + auto const &record{components[Component]}; + if (std::uint64_t{record.data_offset} + record.data_size > component_data.size()) + return {}; + return std::span{component_data}.subspan(record.data_offset, record.data_size); +} + +std::uint64_t hash_bytes(std::span const Data, std::uint64_t const Seed) { + auto hash{Seed}; + for (auto const byte : Data) { + hash ^= std::to_integer(byte); + hash *= 0x100000001b3ull; + } + return hash; +} + +std::uint64_t hash_name(std::string_view const Name) { + std::uint64_t hash{0xcbf29ce484222325ull}; + for (auto const character : Name) { + auto byte{static_cast(character)}; + if (byte >= 'A' && byte <= 'Z') + byte = static_cast(byte - 'A' + 'a'); + hash ^= byte; + hash *= 0x100000001b3ull; + } + return hash; +} + +namespace { + +// --------------------------------------------------------------------------------------------------------------------- +// writing + +template void append_bytes(std::vector &Output, Type_ const &Value) { + auto const offset{Output.size()}; + Output.resize(offset + sizeof(Type_)); + std::memcpy(Output.data() + offset, &Value, sizeof(Type_)); +} + +template void append_array(std::vector &Output, std::vector const &Values) { + if (Values.empty()) + return; + auto const offset{Output.size()}; + Output.resize(offset + Values.size() * sizeof(Type_)); + std::memcpy(Output.data() + offset, Values.data(), Values.size() * sizeof(Type_)); +} + +struct pending_section { + std::uint32_t id{0}; + std::uint32_t flags{0}; + std::size_t alignment{section_alignment}; + std::vector data; +}; + +class file_builder { + public: + template void table(std::uint32_t const Id, std::vector const &Records, bool const Required) { + if (Records.empty() && false == Required) + return; + std::vector data; + append_bytes(data, table_header{static_cast(Records.size()), static_cast(sizeof(Type_))}); + append_array(data, Records); + add(Id, Required, section_alignment, std::move(data)); + } + template void stream(std::uint32_t const Id, std::vector const &Values, bool const Required) { + if (Values.empty() && false == Required) + return; + std::vector data; + append_array(data, Values); + add(Id, Required, gpu_alignment, std::move(data)); + } + void raw(std::uint32_t const Id, std::uint32_t const Flags, std::vector Data) { + m_sections.push_back({Id, Flags & section_flags::required, section_alignment, std::move(Data)}); + } + void add(std::uint32_t const Id, bool const Required, std::size_t const Alignment, std::vector Data) { + m_sections.push_back({Id, Required ? section_flags::required : 0u, Alignment, std::move(Data)}); + } + std::vector finish(model const &Model, write_options const &Options); + + private: + static void pad_to(std::vector &Output, std::size_t const Alignment) { + while (Output.size() % Alignment != 0) + Output.push_back(std::byte{0}); + } + static bool compress(pending_section const &Section, std::vector &Packed, int const Level); + + std::vector m_sections; +}; + +bool file_builder::compress(pending_section const &Section, std::vector &Packed, int const Level) { + // small sections stay as they are, unpacking them costs more than reading them + if (Section.data.size() < 512) + return false; + Packed.resize(ZSTD_compressBound(Section.data.size())); + auto const size{ZSTD_compress(Packed.data(), Packed.size(), Section.data.data(), Section.data.size(), Level)}; + if (ZSTD_isError(size) || size > Section.data.size() - Section.data.size() / 8) + return false; + Packed.resize(size); + return true; +} + +std::vector file_builder::finish(model const &Model, write_options const &Options) { + std::vector output(sizeof(file_header) + m_sections.size() * sizeof(section_entry)); + std::vector entries; + entries.reserve(m_sections.size()); + std::vector packed; + for (auto const §ion : m_sections) { + pad_to(output, section.alignment); + section_entry entry; + entry.id = section.id; + entry.flags = section.flags; + entry.offset = output.size(); + entry.size = section.data.size(); + if (Options.compress && compress(section, packed, Options.level)) { + entry.flags |= section_flags::zstd; + output.insert(output.end(), packed.begin(), packed.end()); + } + else { + output.insert(output.end(), section.data.begin(), section.data.end()); + } + entry.stored_size = output.size() - entry.offset; + entries.push_back(entry); + } + std::memcpy(output.data() + sizeof(file_header), entries.data(), entries.size() * sizeof(section_entry)); + + file_header header; + header.flags = Model.flags; + header.section_count = static_cast(entries.size()); + header.toc_offset = sizeof(file_header); + header.file_size = output.size(); + header.source_hash = Model.source_hash; + header.content_hash = hash_bytes(std::span{output}.subspan(sizeof(file_header))); + std::memcpy(output.data(), &header, sizeof(file_header)); + return output; +} + +std::vector encode_strings(std::vector const &Strings) { + std::vector offsets; + offsets.reserve(Strings.size() + 1); + std::uint32_t offset{0}; + for (auto const &text : Strings) { + offsets.push_back(offset); + offset += static_cast(text.size()); + } + offsets.push_back(offset); + std::vector data; + append_bytes(data, static_cast(Strings.size())); + append_bytes(data, offset); + append_array(data, offsets); + for (auto const &text : Strings) { + auto const *bytes{reinterpret_cast(text.data())}; + data.insert(data.end(), bytes, bytes + text.size()); + } + return data; +} + +// --------------------------------------------------------------------------------------------------------------------- +// reading + +// a section of the file, unpacked +class section_bytes { + public: + section_bytes(std::uint32_t const Id, std::span const Bytes) : m_id(Id), m_bytes(Bytes) {} + + template bool table(std::vector &Output, std::string &Error) const { + table_header header; + if (m_bytes.size() < sizeof(header)) + return fail(Error, "is shorter than its table header"); + std::memcpy(&header, m_bytes.data(), sizeof(header)); + if (header.stride < sizeof(Type_)) + return fail(Error, std::format("has records of {} bytes, {} expected at least", header.stride, sizeof(Type_))); + if (std::uint64_t{header.count} * header.stride > m_bytes.size() - sizeof(header)) + return fail(Error, std::format("holds {} records of {} bytes in {} bytes", header.count, header.stride, m_bytes.size() - sizeof(header))); + Output.resize(header.count); + for (std::size_t idx = 0; idx < header.count; ++idx) + std::memcpy(&Output[idx], m_bytes.data() + sizeof(header) + idx * header.stride, sizeof(Type_)); + return true; + } + + template bool stream(std::vector &Output, std::string &Error) const { + if (m_bytes.size() % sizeof(Type_) != 0) + return fail(Error, std::format("of {} bytes isn't a whole number of elements of {} bytes", m_bytes.size(), sizeof(Type_))); + Output.resize(m_bytes.size() / sizeof(Type_)); + if (false == Output.empty()) + std::memcpy(Output.data(), m_bytes.data(), m_bytes.size()); + return true; + } + + bool strings(std::vector &Output, std::string &Error) const; + + std::span bytes() const { + return m_bytes; + } + + private: + bool fail(std::string &Error, std::string_view const What) const { + Error = std::format("section {} {}", fourcc_name(m_id), What); + return false; + } + + std::uint32_t m_id; + std::span m_bytes; +}; + +bool section_bytes::strings(std::vector &Output, std::string &Error) const { + std::array head{}; + if (m_bytes.size() < sizeof(head)) + return fail(Error, "is shorter than its head"); + std::memcpy(head.data(), m_bytes.data(), sizeof(head)); + auto const count{std::uint64_t{head[0]}}; + auto const offsetsend{sizeof(head) + (count + 1) * sizeof(std::uint32_t)}; + if (offsetsend > m_bytes.size() || offsetsend + head[1] > m_bytes.size()) + return fail(Error, std::format("can't hold {} strings of {} bytes", count, head[1])); + std::vector offsets(count + 1); + std::memcpy(offsets.data(), m_bytes.data() + sizeof(head), offsets.size() * sizeof(std::uint32_t)); + if (offsets.front() != 0 || offsets.back() != head[1] || false == std::ranges::is_sorted(offsets)) + return fail(Error, "has the bounds of its strings out of order"); + auto const *blob{reinterpret_cast(m_bytes.data() + offsetsend)}; + Output.clear(); + Output.reserve(count); + for (std::size_t idx = 0; idx < count; ++idx) + Output.emplace_back(blob + offsets[idx], offsets[idx + 1] - offsets[idx]); + return true; +} + +// the largest section unpacked, so a broken file can't make the reader take all the memory +constexpr std::uint64_t section_size_limit{std::uint64_t{1} << 30}; +// and the most all the sections of a model may unpack to together +constexpr std::uint64_t model_size_limit{std::uint64_t{2} << 30}; + +class file_reader { + public: + file_reader(std::span const File, read_options const &Options) : m_file(File), m_options(Options) {} + read_result run(model &Model); + + private: + bool read_header(file_header &Header); + bool read_entries(file_header const &Header, std::vector &Entries); + bool unpack(section_entry const &Entry, std::vector &Storage, std::span &Bytes); + bool dispatch(section_entry const &Entry, section_bytes const &Section, model &Model); + bool fail(std::string Error) { + m_error = std::move(Error); + return false; + } + + std::span m_file; + read_options m_options; + std::string m_error; +}; + +bool file_reader::read_header(file_header &Header) { + if (m_file.size() < sizeof(file_header)) + return fail("the file is shorter than the header"); + std::memcpy(&Header, m_file.data(), sizeof(file_header)); + if (Header.magic != file_header{}.magic) + return fail("the file isn't an E4D model"); + if (Header.major != version_major) + return fail(std::format("the model has version {}.{}, this program reads version {}", Header.major, Header.minor, version_major)); + if (Header.file_size > m_file.size()) + return fail(std::format("the file is cut short: {} bytes of {}", m_file.size(), Header.file_size)); + if (Header.file_size < sizeof(file_header)) + return fail(std::format("the file claims {} bytes, less than its header", Header.file_size)); + m_file = m_file.first(Header.file_size); + if (m_options.verify_hash && hash_bytes(m_file.subspan(sizeof(file_header))) != Header.content_hash) + return fail("the content of the file doesn't match its hash"); + return true; +} + +bool file_reader::read_entries(file_header const &Header, std::vector &Entries) { + auto const tablesize{std::uint64_t{Header.section_count} * sizeof(section_entry)}; + if (Header.toc_offset > m_file.size() || tablesize > m_file.size() - Header.toc_offset) + return fail("the list of the sections lies outside the file"); + Entries.resize(Header.section_count); + if (false == Entries.empty()) + std::memcpy(Entries.data(), m_file.data() + Header.toc_offset, tablesize); + std::unordered_set seen; + seen.reserve(Entries.size()); + std::uint64_t total{0}; + for (auto const &entry : Entries) { + if (entry.offset > m_file.size() || entry.stored_size > m_file.size() - entry.offset) + return fail(std::format("section {} lies outside the file", fourcc_name(entry.id))); + if (entry.size > section_size_limit) + return fail(std::format("section {} claims {} bytes", fourcc_name(entry.id), entry.size)); + if (false == seen.insert(entry.id).second) + return fail(std::format("section {} appears twice", fourcc_name(entry.id))); + total += entry.size; + if (total > model_size_limit) + return fail(std::format("the sections claim more than {} bytes together", model_size_limit)); + } + return true; +} + +bool file_reader::unpack(section_entry const &Entry, std::vector &Storage, std::span &Bytes) { + auto const stored{m_file.subspan(Entry.offset, Entry.stored_size)}; + if ((Entry.flags & section_flags::zstd) == 0) { + if (Entry.stored_size != Entry.size) + return fail(std::format("section {} has {} bytes stored and {} declared", fourcc_name(Entry.id), Entry.stored_size, Entry.size)); + Bytes = stored; + return true; + } + // the size the frame declares has to be the one of the section before any memory is taken for it + if (ZSTD_getFrameContentSize(stored.data(), stored.size()) != Entry.size) + return fail(std::format("section {} doesn't unpack to its {} bytes", fourcc_name(Entry.id), Entry.size)); + Storage.resize(Entry.size); + auto const size{ZSTD_decompress(Storage.data(), Storage.size(), stored.data(), stored.size())}; + if (ZSTD_isError(size) || size != Entry.size) + return fail(std::format("section {} doesn't unpack to its {} bytes", fourcc_name(Entry.id), Entry.size)); + Bytes = Storage; + return true; +} + +// the sections this reader reads (dispatch() below) +constexpr std::array known_sections{section::strings, section::name_index, section::nodes, section::transforms, + section::meshes, section::primitives, section::positions, section::attributes, + section::skin_weights, section::skin_weights_wide, section::userdata, section::bindings, + section::indices16, section::indices32, section::materials, section::skins, + section::skin_joints, section::vertex_groups, section::vertex_group_items, section::vertex_group_weights, + section::components, section::component_data, section::bounds, section::edit}; + +bool known_section(std::uint32_t const Id) { + return std::ranges::find(known_sections, Id) != known_sections.end(); +} + +bool file_reader::dispatch(section_entry const &Entry, section_bytes const &Section, model &Model) { + std::string error; + bool known{true}; + bool result{true}; + switch (Entry.id) { + case section::strings: result = Section.strings(Model.strings, error); break; + case section::name_index: result = Section.table(Model.name_index, error); break; + case section::nodes: result = Section.table(Model.nodes, error); break; + case section::transforms: result = Section.table(Model.transforms, error); break; + case section::meshes: result = Section.table(Model.meshes, error); break; + case section::primitives: result = Section.table(Model.primitives, error); break; + case section::positions: result = Section.stream(Model.positions, error); break; + case section::attributes: result = Section.stream(Model.vertex_attributes, error); break; + case section::skin_weights: result = Section.stream(Model.weights, error); break; + case section::skin_weights_wide: result = Section.stream(Model.weights_wide, error); break; + case section::userdata: result = Section.stream(Model.vertex_userdata, error); break; + case section::bindings: result = Section.stream(Model.bindings, error); break; + case section::indices16: result = Section.stream(Model.indices16, error); break; + case section::indices32: result = Section.stream(Model.indices32, error); break; + case section::materials: result = Section.table(Model.materials, error); break; + case section::skins: result = Section.table(Model.skins, error); break; + case section::skin_joints: result = Section.table(Model.skin_joints, error); break; + case section::vertex_groups: result = Section.table(Model.vertex_groups, error); break; + case section::vertex_group_items: result = Section.stream(Model.vertex_group_items, error); break; + case section::vertex_group_weights: result = Section.stream(Model.vertex_group_weights, error); break; + case section::components: result = Section.table(Model.components, error); break; + case section::component_data: result = Section.stream(Model.component_data, error); break; + case section::bounds: result = Section.table(Model.bounds, error); break; + case section::edit: result = Section.table(Model.edit, error); break; + default: known = false; break; + } + if (false == result) + return fail(error); + if (known) + return true; + if ((Entry.flags & section_flags::required) != 0) + return fail(std::format("the model needs section {}, which this program doesn't know", fourcc_name(Entry.id))); + if (m_options.keep_unknown) { + auto const bytes{Section.bytes()}; + Model.unknown.push_back({Entry.id, Entry.flags & section_flags::required, std::vector(bytes.begin(), bytes.end())}); + } + return true; +} + +read_result file_reader::run(model &Model) { + Model = model{}; + file_header header; + std::vector sections; + if (false == read_header(header) || false == read_entries(header, sections)) + return {false, m_error}; + Model.flags = header.flags; + Model.source_hash = header.source_hash; + std::vector storage; + for (auto const &entry : sections) { + // a section this reader doesn't know and the model can do without is passed over before it is unpacked, unless the + // tools keep it to write it back + if (false == known_section(entry.id) && (entry.flags & section_flags::required) == 0 && false == m_options.keep_unknown) + continue; + std::span bytes; + if (false == unpack(entry, storage, bytes) || false == dispatch(entry, section_bytes{entry.id, bytes}, Model)) { + Model = model{}; + return {false, m_error}; + } + } + for (auto const required : {section::strings, section::nodes, section::meshes, section::primitives, section::positions, section::attributes, section::materials}) { + if (std::ranges::none_of(sections, [required](section_entry const &Entry) { return Entry.id == required; })) { + Model = model{}; + return {false, std::format("the model has no section {}", fourcc_name(required))}; + } + } + if (auto const faults{validate(Model, 1)}; false == faults.empty()) { + Model = model{}; + return {false, faults.front()}; + } + return {true, {}}; +} + +// --------------------------------------------------------------------------------------------------------------------- +// checking + +bool valid_string(model const &Model, std::uint32_t const Id) { + return Id == no_index || Id < Model.strings.size(); +} + +bool valid_node(model const &Model, std::uint32_t const Id) { + return Id < Model.nodes.size(); +} + +bool valid_optional_node(model const &Model, std::uint32_t const Id) { + return Id == no_index || valid_node(Model, Id); +} + +bool valid_optional_component(model const &Model, std::uint32_t const Id) { + return Id == no_index || Id < Model.components.size(); +} + +bool all_nodes(model const &Model, payload_reader &Reader, std::size_t const Count) { + for (std::size_t idx = 0; idx < Count; ++idx) { + std::uint32_t node{0}; + if (false == Reader.get(node) || false == valid_node(Model, node)) + return false; + } + return true; +} + +bool valid_properties(model const &Model, payload_reader &Reader) { + std::uint32_t count{0}; + if (false == Reader.get(count)) + return false; + for (std::uint32_t idx = 0; idx < count; ++idx) { + payload::property property; + if (false == Reader.get(property) || false == valid_string(Model, property.key)) + return false; + auto const reference{property.value[0]}; + using enum payload::value_type; + if ((property.type == string && false == valid_string(Model, reference)) || (property.type == node && false == valid_optional_node(Model, reference)) || + (property.type == component && false == valid_optional_component(Model, reference)) || property.type > component) + return false; + } + return true; +} + +bool valid_spring(model const &Model, payload_reader &Reader) { + payload::spring spring; + return Reader.get(spring) && valid_optional_node(Model, spring.anchor_a) && valid_optional_node(Model, spring.anchor_b) && valid_optional_component(Model, spring.socket_a) && + valid_optional_component(Model, spring.socket_b); +} + +bool valid_chain(model const &Model, payload_reader &Reader) { + payload::chain chain; + if (false == Reader.get(chain) || false == valid_optional_component(Model, chain.end_a) || false == valid_optional_component(Model, chain.end_b)) + return false; + if (chain.skin >= static_cast(Model.skins.size())) + return false; + if (false == all_nodes(Model, Reader, chain.joint_count)) + return false; + auto const segments{chain.joint_count > 0 ? chain.joint_count - 1u : 0u}; + return Reader.remaining() >= segments * sizeof(float); +} + +bool valid_variants(model const &Model, payload_reader &Reader) { + payload::variants variants; + if (false == Reader.get(variants) || false == valid_string(Model, variants.name)) + return false; + if (variants.state_count > 0 && variants.default_state >= variants.state_count) + return false; + std::uint64_t listsize{0}; + for (std::uint32_t idx = 0; idx < variants.state_count; ++idx) { + payload::variant_state state; + if (false == Reader.get(state) || false == valid_string(Model, state.name)) + return false; + listsize = std::max(listsize, std::uint64_t{state.node_first} + state.node_count); + } + return all_nodes(Model, Reader, listsize); +} + +bool valid_channel(model const &Model, payload_reader &Reader) { + payload::channel channel; + if (false == Reader.get(channel) || false == valid_string(Model, channel.name)) + return false; + for (std::uint32_t idx = 0; idx < channel.binding_count; ++idx) { + payload::channel_binding binding; + if (false == Reader.get(binding) || binding.kind > payload::binding_kind::light_slot || false == valid_optional_component(Model, binding.target)) + return false; + } + return true; +} + +bool valid_light_slot(model const &Model, payload_reader &Reader) { + payload::light_slot slot; + if (false == Reader.get(slot) || false == all_nodes(Model, Reader, std::size_t{slot.on_count} + slot.off_count)) + return false; + for (std::uint32_t idx = 0; idx < slot.light_count; ++idx) { + std::uint32_t light{0}; + if (false == Reader.get(light) || light >= Model.components.size() || Model.components[light].type != component::light) + return false; + } + return true; +} + +bool valid_stars(model const &Model, component_record const &Record, payload_reader &Reader) { + payload::legacy_stars stars; + if (false == Reader.get(stars) || Reader.remaining() < std::uint64_t{stars.count} * sizeof(std::uint32_t)) + return false; + // the colours go with the vertices of the mesh of the node + if (Record.kind != target_kind::node || Record.target >= Model.nodes.size()) + return false; + auto const mesh{Model.nodes[Record.target].mesh}; + if (mesh < 0 || mesh >= static_cast(Model.meshes.size())) + return false; + std::uint64_t vertices{0}; + auto const &record{Model.meshes[mesh]}; + for (auto idx = record.primitive_first; idx < record.primitive_first + record.primitive_count && idx < Model.primitives.size(); ++idx) + vertices += Model.primitives[idx].vertex_count; + return vertices == stars.count; +} + +template bool valid_fixed(payload_reader &Reader) { + Type_ value; + return Reader.get(value); +} + +// whether the payload of the component holds what its type says, with references in range. unknown types pass +bool valid_payload(model const &Model, component_record const &Record, std::span const Data) { + payload_reader reader{Data}; + switch (Record.type) { + case component::properties: return valid_properties(Model, reader); + case component::socket: { + payload::socket socket; + return reader.get(socket) && valid_string(Model, socket.role); + } + case component::joint: { + payload::joint joint; + return reader.get(joint) && joint.kind <= payload::joint_kind::screw && valid_string(Model, joint.role); + } + case component::spring: return valid_spring(Model, reader); + case component::chain: return valid_chain(Model, reader); + case component::variants: return valid_variants(Model, reader); + case component::channel: return valid_channel(Model, reader); + case component::light_slot: return valid_light_slot(Model, reader); + case component::light: return valid_fixed(reader); + case component::emitter: return valid_fixed(reader); + case component::model_reference: { + payload::model_reference reference; + return reader.get(reference) && valid_string(Model, reference.path) && valid_string(Model, reference.skin) && valid_optional_component(Model, reference.socket); + } + case component::collision: { + payload::collision collision; + return reader.get(collision) && valid_string(Model, collision.role); + } + case component::legacy_animation: return valid_fixed(reader); + case component::legacy_stars: return valid_stars(Model, Record, reader); + default: return true; // a type of a later version, or a marker without data (LTXT) + } +} + +class validator { + public: + validator(model const &Model, std::size_t const Limit) : m_model(Model), m_limit(Limit) {} + std::vector run(); + + private: + bool full() const { + return m_faults.size() >= m_limit; + } + void fault(std::string Text) { + if (false == full()) + m_faults.push_back(std::move(Text)); + } + void nodes(); + void node(std::uint32_t Index, node_record const &Node); + void transforms(); + void meshes(); + void primitives(); + void primitive(std::uint32_t Index, primitive_record const &Primitive); + void indices(std::uint32_t Index, primitive_record const &Primitive); + void skinned(std::uint32_t Index, primitive_record const &Primitive); + void bound(std::uint32_t Index, primitive_record const &Primitive); + void slotted(std::uint32_t Index, primitive_record const &Primitive); + void streams(); + void materials(); + void skins(); + void vertex_groups(); + void components(); + void component_ranges(std::uint32_t First, std::uint32_t Count, target_kind Kind, std::uint32_t Target, std::string_view Owner); + void tables(); + + model const &m_model; + std::size_t m_limit; + std::vector m_faults; +}; + +void validator::node(std::uint32_t const Index, node_record const &Node) { + auto const count{m_model.nodes.size()}; + if (false == valid_string(m_model, Node.name)) + fault(std::format("node {} has a name out of range", Index)); + auto const parent{Node.parent >= 0 && Node.parent < static_cast(Index)}; + if (Node.parent != -1 && false == parent) + fault(std::format("node {} has parent {}, which isn't before it", Index, Node.parent)); + if (Node.subtree_end <= Index || Node.subtree_end > count) + fault(std::format("node {} ends its subtree at {}", Index, Node.subtree_end)); + if (parent && Node.subtree_end > m_model.nodes[Node.parent].subtree_end) + fault(std::format("node {} reaches past the subtree of its parent", Index)); + if (Node.mesh < -1 || Node.mesh >= static_cast(m_model.meshes.size())) + fault(std::format("node {} has mesh {} out of range", Index, Node.mesh)); + if ((Node.flags & node_flags::matrix) != 0 && std::ranges::none_of(m_model.transforms, [Index](transform_record const &Transform) { return Transform.node == Index; })) + fault(std::format("node {} has no matrix in XFRM", Index)); + component_ranges(Node.component_first, Node.component_count, target_kind::node, Index, std::format("node {}", Index)); +} + +void validator::nodes() { + for (std::uint32_t idx = 0; idx < m_model.nodes.size() && false == full(); ++idx) + node(idx, m_model.nodes[idx]); + // the subtrees nest, and the parent of each node is the innermost node whose subtree holds it, so the tree the ranges + // give is the one the parents give + std::vector open; + for (std::uint32_t idx = 0; idx < m_model.nodes.size() && false == full(); ++idx) { + while (false == open.empty() && m_model.nodes[open.back()].subtree_end <= idx) + open.pop_back(); + auto const holder{open.empty() ? std::int64_t{-1} : std::int64_t{open.back()}}; + if (m_model.nodes[idx].parent != holder) + fault(std::format("node {} has parent {}, but lies in the subtree of node {}", idx, m_model.nodes[idx].parent, holder)); + open.push_back(idx); + } +} + +void validator::transforms() { + for (auto const &transform : m_model.transforms) { + if (false == valid_node(m_model, transform.node)) + fault(std::format("a matrix in XFRM belongs to node {}, which isn't there", transform.node)); + } +} + +void validator::meshes() { + for (std::uint32_t idx = 0; idx < m_model.meshes.size() && false == full(); ++idx) { + auto const &mesh{m_model.meshes[idx]}; + if (std::uint64_t{mesh.primitive_first} + mesh.primitive_count > m_model.primitives.size()) + fault(std::format("mesh {} has primitives out of range", idx)); + if (mesh.skin < -1 || mesh.skin >= static_cast(m_model.skins.size())) + fault(std::format("mesh {} has skin {} out of range", idx, mesh.skin)); + } +} + +void validator::indices(std::uint32_t const Index, primitive_record const &Primitive) { + auto const wide{(Primitive.flags & primitive_flags::index32) != 0}; + auto const available{wide ? m_model.indices32.size() : m_model.indices16.size()}; + if (std::uint64_t{Primitive.first_index} + Primitive.index_count > available) { + fault(std::format("primitive {} has indices out of range", Index)); + return; + } + for (std::size_t idx = Primitive.first_index; idx < std::size_t{Primitive.first_index} + Primitive.index_count; ++idx) { + auto const value{wide ? m_model.indices32[idx] : std::uint32_t{m_model.indices16[idx]}}; + if (value >= Primitive.vertex_count) { + fault(std::format("primitive {} has index {} past its {} vertices", Index, value, Primitive.vertex_count)); + return; + } + } +} + +void validator::skinned(std::uint32_t const Index, primitive_record const &Primitive) { + auto const &skin{m_model.skins[Primitive.skin]}; + auto const end{std::size_t{Primitive.base_vertex} + Primitive.vertex_count}; + auto const wide{m_model.weights_wide.size() == m_model.vertex_count()}; + for (auto idx = std::size_t{Primitive.base_vertex}; idx < end; ++idx) { + auto const exceeds{[&skin](auto const &Joints) { return std::ranges::any_of(Joints, [&skin](auto const Joint) { return Joint >= skin.joint_count; }); }}; + auto const bad{wide ? exceeds(m_model.weights_wide[idx].joints) : exceeds(m_model.weights[idx].joints)}; + if (bad) { + fault(std::format("primitive {} has vertex {} bound to a joint its skin doesn't have", Index, idx)); + return; + } + } +} + +void validator::primitive(std::uint32_t const Index, primitive_record const &Primitive) { + if (std::uint64_t{Primitive.base_vertex} + Primitive.vertex_count > m_model.vertex_count()) { + fault(std::format("primitive {} has vertices out of range", Index)); + return; + } + if ((Primitive.flags & primitive_flags::topology_mask) > static_cast(topology::triangle_fan)) + fault(std::format("primitive {} has an unknown topology", Index)); + if (false == valid_node(m_model, Primitive.node)) + fault(std::format("primitive {} belongs to node {}, which isn't there", Index, Primitive.node)); + if (Primitive.material != no_index && Primitive.material >= m_model.materials.size()) + fault(std::format("primitive {} has material {} out of range", Index, Primitive.material)); + if ((Primitive.flags & primitive_flags::indexed) != 0) + indices(Index, Primitive); + else if (std::uint64_t{Primitive.first_index} + Primitive.index_count > Primitive.vertex_count) + fault(std::format("primitive {} draws vertices past its own", Index)); + if (Primitive.skin < -1 || Primitive.skin >= static_cast(m_model.skins.size())) + fault(std::format("primitive {} has skin {} out of range", Index, Primitive.skin)); + else if ((Primitive.flags & primitive_flags::rigid_joints) != 0) + bound(Index, Primitive); + else if (Primitive.skin >= 0 && m_model.weights.size() != m_model.vertex_count() && m_model.weights_wide.size() != m_model.vertex_count()) + fault(std::format("primitive {} is skinned, and the model has no weights for its vertices", Index)); + else if (Primitive.skin >= 0) + skinned(Index, Primitive); + if ((Primitive.flags & primitive_flags::light_slots) != 0) + slotted(Index, Primitive); +} + +// a primitive of parts merged from several nodes: every vertex names a joint of the skin +void validator::bound(std::uint32_t const Index, primitive_record const &Primitive) { + if (Primitive.skin < 0) { + fault(std::format("primitive {} follows joints, and has no skin naming them", Index)); + return; + } + if (m_model.bindings.size() != m_model.vertex_count()) { + fault(std::format("primitive {} follows joints, and the model has no VBND for its vertices", Index)); + return; + } + auto const &skin{m_model.skins[Primitive.skin]}; + auto const vertices{std::span{m_model.bindings}.subspan(Primitive.base_vertex, Primitive.vertex_count)}; + if (std::ranges::any_of(vertices, [&skin](vertex_binding const &Binding) { return Binding.joint >= skin.joint_count; })) + fault(std::format("primitive {} has a vertex bound to a joint its skin doesn't have", Index)); +} + +void validator::slotted(std::uint32_t const Index, primitive_record const &Primitive) { + if (m_model.bindings.size() != m_model.vertex_count()) { + fault(std::format("primitive {} uses light slots, and the model has no VBND for its vertices", Index)); + return; + } + auto const vertices{std::span{m_model.bindings}.subspan(Primitive.base_vertex, Primitive.vertex_count)}; + if (std::ranges::any_of(vertices, [](vertex_binding const &Binding) { return Binding.role > slot_role::dark; })) + fault(std::format("primitive {} has a vertex with an unknown light slot role", Index)); +} + +void validator::primitives() { + for (std::uint32_t idx = 0; idx < m_model.primitives.size() && false == full(); ++idx) + primitive(idx, m_model.primitives[idx]); +} + +void validator::streams() { + auto const count{m_model.vertex_count()}; + if (m_model.vertex_attributes.size() != count) + fault(std::format("VATT has {} vertices, VPOS {}", m_model.vertex_attributes.size(), count)); + if (false == m_model.weights.empty() && m_model.weights.size() != count) + fault(std::format("VSKN has {} vertices, VPOS {}", m_model.weights.size(), count)); + if (false == m_model.weights_wide.empty() && m_model.weights_wide.size() != count) + fault(std::format("VSKW has {} vertices, VPOS {}", m_model.weights_wide.size(), count)); + if (false == m_model.weights.empty() && false == m_model.weights_wide.empty()) + fault("the model has both VSKN and VSKW"); + if (false == m_model.vertex_userdata.empty() && m_model.vertex_userdata.size() != count) + fault(std::format("VUSR has {} vertices, VPOS {}", m_model.vertex_userdata.size(), count)); + if (false == m_model.bindings.empty() && m_model.bindings.size() != count) + fault(std::format("VBND has {} vertices, VPOS {}", m_model.bindings.size(), count)); +} + +void validator::materials() { + for (std::uint32_t idx = 0; idx < m_model.materials.size(); ++idx) { + auto const &material{m_model.materials[idx]}; + if (false == valid_string(m_model, material.name) || material.replaceable < -4 || material.replaceable > 0) + fault(std::format("material {} has a name or a skin out of range", idx)); + } +} + +void validator::skins() { + for (std::uint32_t idx = 0; idx < m_model.skins.size(); ++idx) { + auto const &skin{m_model.skins[idx]}; + if (std::uint64_t{skin.joint_first} + skin.joint_count > m_model.skin_joints.size()) + fault(std::format("skin {} has joints out of range", idx)); + if (skin.root < -1 || skin.root >= static_cast(m_model.nodes.size())) + fault(std::format("skin {} has root {} out of range", idx, skin.root)); + if (false == m_model.weights.empty() && skin.joint_count > 256) + fault(std::format("skin {} has {} joints, VSKN can address 256", idx, skin.joint_count)); + } + for (auto const &joint : m_model.skin_joints) { + if (false == valid_node(m_model, joint.node)) + fault(std::format("a joint is node {}, which isn't there", joint.node)); + } +} + +void validator::vertex_groups() { + for (std::uint32_t idx = 0; idx < m_model.vertex_groups.size() && false == full(); ++idx) { + auto const &group{m_model.vertex_groups[idx]}; + auto const ranges{(group.flags & vertex_group_flags::ranges) != 0}; + auto const itemsize{ranges ? 2u : 1u}; + auto const end{std::uint64_t{group.item_first} + std::uint64_t{group.item_count} * itemsize}; + if (group.mesh >= m_model.meshes.size() || false == valid_string(m_model, group.name) || end > m_model.vertex_group_items.size()) { + fault(std::format("vertex group {} has its mesh, name or items out of range", idx)); + continue; + } + if ((group.flags & vertex_group_flags::weighted) != 0 && end > m_model.vertex_group_weights.size()) + fault(std::format("vertex group {} has weights out of range", idx)); + for (auto item = std::size_t{group.item_first}; item < end; item += itemsize) { + auto const last{ranges ? std::uint64_t{m_model.vertex_group_items[item]} + m_model.vertex_group_items[item + 1] : std::uint64_t{m_model.vertex_group_items[item]} + 1}; + if (last > m_model.vertex_count()) { + fault(std::format("vertex group {} has vertices out of range", idx)); + break; + } + } + component_ranges(group.component_first, group.component_count, target_kind::vertex_group, idx, std::format("vertex group {}", idx)); + } +} + +void validator::component_ranges(std::uint32_t const First, std::uint32_t const Count, target_kind const Kind, std::uint32_t const Target, std::string_view const Owner) { + if (std::uint64_t{First} + Count > m_model.components.size()) { + fault(std::format("{} has components out of range", Owner)); + return; + } + for (auto idx = First; idx < First + Count; ++idx) { + if (m_model.components[idx].kind != Kind || m_model.components[idx].target != Target) { + fault(std::format("{} lists component {}, which belongs to something else", Owner, idx)); + return; + } + } +} + +void validator::components() { + for (std::uint32_t idx = 0; idx < m_model.components.size() && false == full(); ++idx) { + auto const &record{m_model.components[idx]}; + if (std::uint64_t{record.data_offset} + record.data_size > m_model.component_data.size() || record.data_offset % 4 != 0) { + fault(std::format("component {} has its data out of range", idx)); + continue; + } + bool target{true}; + switch (record.kind) { + case target_kind::model: target = record.target == 0; break; + case target_kind::node: target = record.target < m_model.nodes.size(); break; + case target_kind::mesh: target = record.target < m_model.meshes.size(); break; + case target_kind::vertex_group: target = record.target < m_model.vertex_groups.size(); break; + default: target = false; break; + } + if (false == target) + fault(std::format("component {} ({}) belongs to something which isn't there", idx, fourcc_name(record.type))); + else if (record.version == 1 && false == valid_payload(m_model, record, m_model.component_payload(idx))) + fault(std::format("component {} ({}) has data which don't hold together", idx, fourcc_name(record.type))); + } +} + +void validator::tables() { + if (false == m_model.bounds.empty() && m_model.bounds.size() != m_model.nodes.size() + 1) + fault(std::format("BNDS has {} records for {} nodes", m_model.bounds.size(), m_model.nodes.size())); + for (std::size_t idx = 0; idx < m_model.name_index.size(); ++idx) { + auto const &entry{m_model.name_index[idx]}; + if (false == valid_node(m_model, entry.node) || (idx > 0 && entry.hash < m_model.name_index[idx - 1].hash)) { + fault("the name index is out of order or out of range"); + break; + } + } + for (auto const &edit : m_model.edit) { + if (false == valid_string(m_model, edit.source) || false == valid_string(m_model, edit.tool)) + fault("EDIT has a string out of range"); + } +} + +std::vector validator::run() { + nodes(); + transforms(); + streams(); + meshes(); + materials(); + skins(); + primitives(); + vertex_groups(); + components(); + tables(); + return m_faults; +} + +} // namespace + +std::vector write(model const &Model, write_options const &Options) { + file_builder builder; + builder.add(section::strings, true, section_alignment, encode_strings(Model.strings)); + builder.table(section::name_index, Model.name_index, false); + builder.table(section::nodes, Model.nodes, true); + builder.table(section::transforms, Model.transforms, false); + builder.table(section::meshes, Model.meshes, true); + builder.table(section::primitives, Model.primitives, true); + builder.table(section::materials, Model.materials, true); + builder.table(section::skins, Model.skins, false); + builder.table(section::skin_joints, Model.skin_joints, false); + builder.table(section::vertex_groups, Model.vertex_groups, false); + builder.stream(section::vertex_group_items, Model.vertex_group_items, false); + builder.stream(section::vertex_group_weights, Model.vertex_group_weights, false); + builder.table(section::components, Model.components, false); + if (false == Model.component_data.empty()) + builder.add(section::component_data, false, section_alignment, Model.component_data); + builder.table(section::bounds, Model.bounds, false); + builder.table(section::edit, Model.edit, false); + builder.stream(section::positions, Model.positions, true); + builder.stream(section::attributes, Model.vertex_attributes, true); + builder.stream(section::skin_weights, Model.weights, false); + builder.stream(section::skin_weights_wide, Model.weights_wide, false); + builder.stream(section::userdata, Model.vertex_userdata, false); + // required once present: the primitives which follow it draw wrong without it + builder.stream(section::bindings, Model.bindings, false == Model.bindings.empty()); + builder.stream(section::indices16, Model.indices16, false); + builder.stream(section::indices32, Model.indices32, false); + for (auto const §ion : Model.unknown) + builder.raw(section.id, section.flags, section.data); + return builder.finish(Model, Options); +} + +read_result read(std::span const File, model &Model, read_options const &Options) { + return file_reader{File, Options}.run(Model); +} + +std::vector validate(model const &Model, std::size_t const Limit) { + return validator{Model, Limit}.run(); +} + +} // namespace e4d diff --git a/model/e4d/e4d_io.h b/model/e4d/e4d_io.h new file mode 100644 index 000000000..0bf7846d3 --- /dev/null +++ b/model/e4d/e4d_io.h @@ -0,0 +1,45 @@ +/* +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/. +*/ + +#pragma once + +// writing, reading and checking of E4D files + +#include "model/e4d/e4d_model.h" + +#include +#include + +namespace e4d { + +struct write_options { + bool compress{true}; // zstd for the sections where it saves at least an eighth + int level{9}; +}; + +// the file of the model. the model is written as it is; validate() it first +std::vector write(model const &Model, write_options const &Options = {}); + +struct read_options { + bool verify_hash{false}; // the hash of the content, which costs a pass over the whole file + bool keep_unknown{true}; // the sections the reader doesn't know, for the tools to write back +}; + +struct read_result { + bool ok{false}; + std::string error; // what is wrong with the file, when not ok +}; + +// reads the file into the model and checks it with validate(). a file which fails leaves the model empty +read_result read(std::span File, model &Model, read_options const &Options = {}); + +// the faults of the model, each a line of text; empty when it can be used. stops after Limit faults +std::vector validate(model const &Model, std::size_t Limit = 16); + +} // namespace e4d diff --git a/model/e4d/e4d_model.h b/model/e4d/e4d_model.h new file mode 100644 index 000000000..da3228e87 --- /dev/null +++ b/model/e4d/e4d_model.h @@ -0,0 +1,142 @@ +/* +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/. +*/ + +#pragma once + +// an E4D model in memory: the tables of the file, as the writer takes them and the reader gives them back + +#include "model/e4d/e4d_format.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace e4d { + +// a section the reader didn't know, kept so the tools write it back unchanged +struct unknown_section { + std::uint32_t id{0}; + std::uint32_t flags{0}; + std::vector data; +}; + +struct edit_record { + std::uint32_t source{no_index}; + std::uint32_t tool{no_index}; + std::array reserved{}; +}; +static_assert(sizeof(edit_record) == 16); + +struct model { + std::uint32_t flags{0}; + std::uint64_t source_hash{0}; + + std::vector strings; + std::vector name_index; + std::vector nodes; + std::vector transforms; + std::vector meshes; + std::vector primitives; + std::vector positions; + std::vector vertex_attributes; + std::vector weights; + std::vector weights_wide; + std::vector vertex_userdata; + std::vector bindings; + std::vector indices16; + std::vector indices32; + std::vector materials; + std::vector skins; + std::vector skin_joints; + std::vector vertex_groups; + std::vector vertex_group_items; + std::vector vertex_group_weights; + std::vector components; + std::vector component_data; + std::vector bounds; + std::vector edit; + std::vector unknown; + + // the id of the string, adding it when it isn't there yet + std::uint32_t intern(std::string_view Text); + // the string of the id, empty for no_index or an id out of range + std::string_view string(std::uint32_t Id) const; + // adds a component with the given payload and returns its index + std::uint32_t add_component(std::uint32_t Type, target_kind Kind, std::uint32_t Target, std::span Data, std::uint16_t Version = 1); + // the payload of the component + std::span component_payload(std::uint32_t Component) const; + std::size_t vertex_count() const { + return positions.size(); + } + + private: + std::unordered_map m_stringids; // filled by intern() on first use +}; + +// builds the payload of a component: the fixed part, then the variable lists +class payload_writer { + public: + template payload_writer &put(Type_ const &Value) { + static_assert(std::is_trivially_copyable_v); + auto const offset{m_data.size()}; + m_data.resize(offset + sizeof(Type_)); + std::memcpy(m_data.data() + offset, &Value, sizeof(Type_)); + return *this; + } + template payload_writer &put_all(std::span Values) { + for (auto const &value : Values) + put(value); + return *this; + } + std::span data() const { + return m_data; + } + + private: + std::vector m_data; +}; + +// reads the payload of a component. a read past the end leaves the value as it was and marks the reader failed +class payload_reader { + public: + explicit payload_reader(std::span Data) : m_data(Data) {} + template bool get(Type_ &Value) { + static_assert(std::is_trivially_copyable_v); + if (m_failed || m_data.size() - m_offset < sizeof(Type_)) { + m_failed = true; + return false; + } + std::memcpy(&Value, m_data.data() + m_offset, sizeof(Type_)); + m_offset += sizeof(Type_); + return true; + } + bool failed() const { + return m_failed; + } + std::size_t remaining() const { + return m_failed ? 0 : m_data.size() - std::min(m_offset, m_data.size()); + } + + private: + std::span m_data; + std::size_t m_offset{0}; + bool m_failed{false}; +}; + +// FNV-1a 64 +std::uint64_t hash_bytes(std::span Data, std::uint64_t Seed = 0xcbf29ce484222325ull); +// FNV-1a 64 of the name in ASCII lowercase, the key of the name index +std::uint64_t hash_name(std::string_view Name); + +} // namespace e4d diff --git a/physics/brakes.cpp b/physics/brakes.cpp index 7cd66b1d5..7a33c01b4 100644 --- a/physics/brakes.cpp +++ b/physics/brakes.cpp @@ -479,6 +479,229 @@ double TBrake::GetCRP() return GetBRP(); } +/// +/// The reservoirs every valve has. The kinds of valve with more reservoirs add theirs after these. +/// +std::vector TBrake::reservoirs() const +{ + return {BrakeCyl.get(), BrakeRes.get(), ValveRes.get()}; +} + +/// +/// What every valve keeps: whether the double check valve is over to the auxiliary brake, the anti-slip pressure. +/// +std::vector TBrake::latches() const +{ + return {DCV ? 1.0 : 0.0, ASBP}; +} + +void TBrake::latches(std::vector const &State) +{ + if (State.size() < 2) + return; + DCV = State[0] != 0.0; + ASBP = State[1]; +} + +std::vector TWest::latches() const +{ + auto state{TBrake::latches()}; + state.emplace_back(LBP); + state.emplace_back(dVP); + state.emplace_back(EPS); + state.emplace_back(LoadC); + return state; +} + +void TWest::latches(std::vector const &State) +{ + auto const first{TBrake::latches().size()}; + if (State.size() < first + 4) + return; + TBrake::latches(State); + LBP = State[first + 0]; + dVP = State[first + 1]; + EPS = State[first + 2]; + LoadC = State[first + 3]; +} + +std::vector TESt3AL2::latches() const +{ + auto state{TESt3::latches()}; + state.emplace_back(LoadC); + return state; +} + +void TESt3AL2::latches(std::vector const &State) +{ + auto const first{TESt3::latches().size()}; + if (State.size() < first + 1) + return; + TESt3::latches(State); + LoadC = State[first + 0]; +} + +std::vector TESt4R::latches() const +{ + auto state{TESt::latches()}; + state.emplace_back(RapidStatus ? 1.0 : 0.0); + state.emplace_back(RapidTemp); + return state; +} + +void TESt4R::latches(std::vector const &State) +{ + auto const first{TESt::latches().size()}; + if (State.size() < first + 2) + return; + TESt::latches(State); + RapidStatus = State[first + 0] != 0.0; + RapidTemp = State[first + 1]; +} + +std::vector TLSt::latches() const +{ + auto state{TESt4R::latches()}; + state.emplace_back(LBP); + state.emplace_back(EDFlag); + return state; +} + +void TLSt::latches(std::vector const &State) +{ + auto const first{TESt4R::latches().size()}; + if (State.size() < first + 2) + return; + TESt4R::latches(State); + LBP = State[first + 0]; + EDFlag = State[first + 1]; +} + +std::vector TEStED::latches() const +{ + auto state{TLSt::latches()}; + state.emplace_back(Zamykajacy ? 1.0 : 0.0); + state.emplace_back(Przys_blok ? 1.0 : 0.0); + state.emplace_back(LoadC); + return state; +} + +void TEStED::latches(std::vector const &State) +{ + auto const first{TLSt::latches().size()}; + if (State.size() < first + 3) + return; + TLSt::latches(State); + Zamykajacy = State[first + 0] != 0.0; + Przys_blok = State[first + 1] != 0.0; + LoadC = State[first + 2]; +} + +std::vector TEStEP2::latches() const +{ + auto state{TLSt::latches()}; + state.emplace_back(LoadC); + state.emplace_back(EPS); + return state; +} + +void TEStEP2::latches(std::vector const &State) +{ + auto const first{TLSt::latches().size()}; + if (State.size() < first + 2) + return; + TLSt::latches(State); + LoadC = State[first + 0]; + EPS = State[first + 1]; +} + +std::vector TCV1L_TR::latches() const +{ + auto state{TCV1::latches()}; + state.emplace_back(LBP); + return state; +} + +void TCV1L_TR::latches(std::vector const &State) +{ + auto const first{TCV1::latches().size()}; + if (State.size() < first + 1) + return; + TCV1::latches(State); + LBP = State[first + 0]; +} + +std::vector TKE::latches() const +{ + auto state{TBrake::latches()}; + state.emplace_back(RapidStatus ? 1.0 : 0.0); + state.emplace_back(LoadC); + state.emplace_back(LBP); + return state; +} + +void TKE::latches(std::vector const &State) +{ + auto const first{TBrake::latches().size()}; + if (State.size() < first + 3) + return; + TBrake::latches(State); + RapidStatus = State[first + 0] != 0.0; + LoadC = State[first + 1]; + LBP = State[first + 2]; +} + +std::vector TESt::reservoirs() const +{ + auto list{TBrake::reservoirs()}; + list.emplace_back(CntrlRes.get()); + return list; +} + +std::vector TESt3AL2::reservoirs() const +{ + auto list{TESt::reservoirs()}; + list.emplace_back(ImplsRes.get()); + return list; +} + +std::vector TESt4R::reservoirs() const +{ + auto list{TESt::reservoirs()}; + list.emplace_back(ImplsRes.get()); + return list; +} + +std::vector TEStED::reservoirs() const +{ + auto list{TLSt::reservoirs()}; + list.emplace_back(Miedzypoj.get()); + return list; +} + +std::vector TCV1::reservoirs() const +{ + auto list{TBrake::reservoirs()}; + list.emplace_back(CntrlRes.get()); + return list; +} + +std::vector TCV1L_TR::reservoirs() const +{ + auto list{TCV1::reservoirs()}; + list.emplace_back(ImplsRes.get()); + return list; +} + +std::vector TKE::reservoirs() const +{ + auto list{TBrake::reservoirs()}; + list.emplace_back(CntrlRes.get()); + list.emplace_back(ImplsRes.get()); + list.emplace_back(Brak2Res.get()); + return list; +} + /// /// Default per-step distributor advance — commits any pending flows on the /// reservoirs and reports zero brake-pipe exchange. Concrete distributors override. @@ -2941,6 +3164,79 @@ double TDriverHandle::GetCP() return 0; } +/// A valve with no pressures of its own. +std::vector TDriverHandle::pressures() +{ + return {}; +} + +std::vector TFV4a::pressures() +{ + return {&CP, &TP, &RP}; +} + +std::vector TFV4aM::pressures() +{ + return {&CP, &TP, &RP, &XP, &RedAdj}; +} + +std::vector TMHZ_EN57::pressures() +{ + return {&CP, &TP, &RP, &RedAdj, &UnbrakeOverPressure}; +} + +std::vector TMHZ_K5P::pressures() +{ + return {&CP, &TP, &RedAdj, &UnbrakeOverPressure}; +} + +std::vector TMHZ_6P::pressures() +{ + return {&CP, &TP, &RedAdj, &UnbrakeOverPressure}; +} + +std::vector TM394::pressures() +{ + return {&CP, &RedAdj}; +} + +std::vector TH14K1::pressures() +{ + return {&CP, &RedAdj}; +} + +std::vector TSt113::pressures() +{ + auto list{TH14K1::pressures()}; // the control chamber and the reductor are inherited + list.emplace_back(&EPS); + return list; +} + +std::vector Ttest::pressures() +{ + return {&CP}; +} + +std::vector TFD1::pressures() +{ + return {&BP}; +} + +std::vector TH1405::pressures() +{ + return {&BP}; +} + +std::vector TFVel6::pressures() +{ + return {&CP, &EPS}; +} + +std::vector TFVE408::pressures() +{ + return {&CP, &EPS}; +} + /// Default EP intensity — 0. double TDriverHandle::GetEP() { diff --git a/physics/brakes.h b/physics/brakes.h index 4fb4b7f9f..f719d3216 100644 --- a/physics/brakes.h +++ b/physics/brakes.h @@ -35,6 +35,9 @@ Knorr/West EP - żeby był #include "physics/friction.h" // Pascal unit +#include +#include + /// Number of positions of the local (auxiliary/manual) brake handle. static int const LocalBrakePosNo = 10; /*ilosc nastaw hamulca recznego lub pomocniczego*/ /// Maximum number of positions of the main (train) brake handle. @@ -251,6 +254,16 @@ class TReservoir void CreatePress(double Press); /// Returns reservoir capacity in liters. double GetCap() const { return Cap; } + /// Returns the air volume contained; with the capacity it gives the pressure. + double GetVol() const { return Vol; } + /// Returns the flow accumulated since the last , which isn't in the volume yet. + double GetPendingFlow() const { return dVol; } + /// Sets the air volume contained and the flow still to be applied to it, for a restored state. + void SetVol(double const Volume, double const Pendingflow = 0.0) + { + Vol = Volume; + dVol = Pendingflow; + } /// /// Returns absolute (atmospheric) pressure inside the reservoir. /// @@ -438,6 +451,18 @@ class TBrake double GetVRP() const; // cisnienie komory wstepnej rozdzielacza /// Returns control reservoir (ZS) pressure [bar]; defaults to the auxiliary reservoir for valves without a dedicated ZS. virtual double GetCRP(); // cisnienie zbiornika sterujacego + /// + /// The reservoirs of the valve: brake cylinder, auxiliary reservoir, pre-chamber, then the ones the kind of valve adds, + /// always in the same order for a kind. For a snapshot of the simulation, which keeps the air in them. + /// + virtual std::vector reservoirs() const; + /// + /// What the valve keeps from one step to the next beside the air in its reservoirs: the latches of its inner valves, the + /// step of its rapid relay, the pressures it was last told. Always in the same order for a kind of valve. For a snapshot of + /// the simulation, which puts them back with the other overload; a list too short for the kind of valve is left alone. + /// + virtual std::vector latches() const; + virtual void latches(std::vector const &State); /// Share of the full cylinder pressure the distributor settles at for the given share /// of the full service pipe drop. Used only to predict the brake force; the default is proportional. /// Share of the full service brake pipe drop. @@ -559,6 +584,9 @@ class TWest : public TBrake double LoadC = 0.0; // wspolczynnik przystawki wazacej public: + /// What the valve keeps from one step to the next beside the air in its reservoirs (see TBrake::latches()). + std::vector latches() const override; + void latches(std::vector const &State) override; /// Initialises pressures: PP into ValveRes, BP into BrakeCyl, average of PP/HPP into BrakeRes. /// Brake pipe pressure. /// High pressure. @@ -604,6 +632,7 @@ class TESt : public TBrake public: /// Initialises the ESt distributor; sizes the control reservoir (15 l) and computes BVM. void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; + std::vector reservoirs() const override; /// One-step distributor advance for the ESt baseline. /// Net flow exchanged with the brake pipe. double GetPF(double const PP, double const dt, double const Vel) override; // przeplyw miedzy komora wstepna i PG @@ -696,8 +725,12 @@ class TESt3AL2 : public TESt3 double LoadC = 0.0; public: + /// What the valve keeps from one step to the next beside the air in its reservoirs (see TBrake::latches()). + std::vector latches() const override; + void latches(std::vector const &State) override; /// Initialises the impulse chamber on top of the ESt initialisation. void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; + std::vector reservoirs() const override; /// One-step distributor advance for ESt3/AL2 with load-weighing relay. double GetPF(double const PP, double const dt, double const Vel) override; // przeplyw miedzy komora wstepna i PG /// Recomputes LoadC for the current vehicle mass. @@ -731,8 +764,12 @@ class TESt4R : public TESt double RapidTemp = 0.0; // aktualne, zmienne przelozenie public: + /// What the valve keeps from one step to the next beside the air in its reservoirs (see TBrake::latches()). + std::vector latches() const override; + void latches(std::vector const &State) override; /// Initialises the ESt4R; sizes the impulse chamber and selects the R delay. void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; + std::vector reservoirs() const override; /// One-step distributor advance for ESt4R (rapid step active above velocity threshold). double GetPF(double const PP, double const dt, double const Vel) override; // przeplyw miedzy komora wstepna i PG @@ -761,6 +798,9 @@ class TLSt : public TESt4R double EDFlag = 0.0; // luzowanie hamulca z powodu zalaczonego ED public: + /// What the valve keeps from one step to the next beside the air in its reservoirs (see TBrake::latches()). + std::vector latches() const override; + void latches(std::vector const &State) override; /// Initialises the LSt; resizes the valve and impulse reservoirs and presets pressures. void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; /// Sets the auxiliary brake target pressure for the DCV. @@ -815,8 +855,12 @@ class TEStED : public TLSt double LoadC = 0.0; public: + /// What the valve keeps from one step to the next beside the air in its reservoirs (see TBrake::latches()). + std::vector latches() const override; + void latches(std::vector const &State) override; /// Initialises the EStED — sets up Miedzypoj, ImplsRes and the nozzle characteristics. void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; + std::vector reservoirs() const override; /// One-step distributor advance for EStED (full EP09 logic with intermediate reservoir). double GetPF(double const PP, double const dt, double const Vel) override; // przeplyw miedzy komora wstepna i PG /// Returns ED-brake reference pressure (ImplsRes pressure scaled by load coefficient). @@ -864,6 +908,9 @@ class TEStEP2 : public TLSt void UpdateStatusEP2(double BCP, double VVP, double CVP); public: + /// What the valve keeps from one step to the next beside the air in its reservoirs (see TBrake::latches()). + std::vector latches() const override; + void latches(std::vector const &State) override; /// Initialises the EP2-equipped distributor (impulse chamber, P delay). void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; // inicjalizacja /// One-step distributor advance with EP2 EP brake logic. @@ -919,6 +966,7 @@ class TCV1 : public TBrake public: /// Initialises the CV1 distributor (sizes ZS, sets pressures, computes BVM). void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; + std::vector reservoirs() const override; /// One-step distributor advance for the CV1 baseline. double GetPF(double const PP, double const dt, double const Vel) override; // przeplyw miedzy komora wstepna i PG /// Returns the control reservoir (ZS) pressure. @@ -972,8 +1020,12 @@ class TCV1L_TR : public TCV1 double LBP = 0.0; // cisnienie hamulca pomocniczego public: + /// What the valve keeps from one step to the next beside the air in its reservoirs (see TBrake::latches()). + std::vector latches() const override; + void latches(std::vector const &State) override; /// Initialises the CV1-L-TR (sizes the impulse chamber on top of CV1::Init). void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; + std::vector reservoirs() const override; /// One-step distributor advance for CV1-L-TR (impulse chamber + DCV). double GetPF(double const PP, double const dt, double const Vel) override; // przeplyw miedzy komora wstepna i PG /// Sets the auxiliary brake target pressure for the DCV. @@ -1025,8 +1077,12 @@ class TKE : public TBrake void CheckStateHeld(double BCP, double VVP, double CVP); public: + /// What the valve keeps from one step to the next beside the air in its reservoirs (see TBrake::latches()). + std::vector latches() const override; + void latches(std::vector const &State) override; /// Initialises the KE distributor (control / impulse / auxiliary reservoirs and BVM). void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; + std::vector reservoirs() const override; /// Sets the rapid step ratio (RM = 1 - RMR). void SetRM(double const RMR) override; // ustalenie przelozenia rapida /// One-step distributor advance for the KE distributor. @@ -1104,6 +1160,11 @@ class TDriverHandle /// Initialises internal pressures from the supplied reference. /// Initial pressure [bar]. virtual void Init(double Press); + /// + /// The pressures the valve keeps from one step to the next, in an order of its own kind. + /// For a snapshot of the simulation, which reads them and puts them back. + /// + virtual std::vector pressures(); /// Returns the control-reservoir / equalising pressure displayed on the cab gauge. virtual double GetCP(); /// Returns the EP brake intensity reported by the handle (0 by default). @@ -1166,6 +1227,7 @@ class TFV4a : public TDriverHandle double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Initialises CP and RP to the supplied pressure. void Init(double Press) override; + std::vector pressures() override; /// Default constructor. using TDriverHandle::TDriverHandle; @@ -1212,6 +1274,7 @@ class TFV4aM : public TDriverHandle double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Initialises CP and RP. void Init(double Press) override; + std::vector pressures() override; /// Sets the reductor adjustment offset. void SetReductor(double nAdj) override; /// Returns Sounds[i] (or 0 if i > 4). @@ -1266,6 +1329,7 @@ class TMHZ_EN57 : public TDriverHandle double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Initialises CP. void Init(double Press) override; + std::vector pressures() override; /// Sets the reductor adjustment offset. void SetReductor(double nAdj) override; /// Returns Sounds[i] (or 0 if i > 4). @@ -1318,6 +1382,7 @@ class TMHZ_K5P : public TDriverHandle double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Initialises CP and enables the time chambers. void Init(double Press) override; + std::vector pressures() override; /// Sets the reductor adjustment offset. void SetReductor(double nAdj) override; /// Returns Sounds[i] (or 0 if i > 4). @@ -1369,6 +1434,7 @@ class TMHZ_6P : public TDriverHandle double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Initialises CP and enables the time chambers. void Init(double Press) override; + std::vector pressures() override; /// Sets the reductor adjustment offset. void SetReductor(double nAdj) override; /// Returns Sounds[i] (or 0 if i > 4). @@ -1434,6 +1500,7 @@ class TM394 : public TDriverHandle double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Initialises CP and enables the time chamber. void Init(double Press) override; + std::vector pressures() override; /// Sets the reductor adjustment offset. void SetReductor(double nAdj) override; /// Returns CP. @@ -1473,6 +1540,7 @@ class TH14K1 : public TDriverHandle double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Initialises CP and enables the time chambers. void Init(double Press) override; + std::vector pressures() override; /// Sets the reductor adjustment offset. void SetReductor(double nAdj) override; /// Returns CP. @@ -1518,6 +1586,7 @@ class TSt113 : public TH14K1 double GetPos(int i) override; /// Enables the time chambers (no pressure init). void Init(double Press) override; + std::vector pressures() override; /// Default constructor. using TH14K1::TH14K1;}; @@ -1538,6 +1607,7 @@ class Ttest : public TDriverHandle double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Initialises CP. void Init(double Press) override; + std::vector pressures() override; /// Default constructor. using TDriverHandle::TDriverHandle;}; @@ -1563,6 +1633,7 @@ class TFD1 : public TDriverHandle double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Initialises MaxBP and the action speed. void Init(double Press) override; + std::vector pressures() override; /// Returns the currently commanded cylinder pressure (BP). double GetCP() override; /// Sets the action speed multiplier. @@ -1589,6 +1660,7 @@ class TH1405 : public TDriverHandle double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Initialises MaxBP and enables the time chamber. void Init(double Press) override; + std::vector pressures() override; /// Returns the currently commanded cylinder pressure (BP). double GetCP() override; // procedure Init(press: real; MaxBP: real); overload; @@ -1625,6 +1697,7 @@ class TFVel6 : public TDriverHandle double GetSound(int i) override; /// Enables the time chambers. void Init(double Press) override; + std::vector pressures() override; /// Default constructor. using TDriverHandle::TDriverHandle;}; @@ -1659,6 +1732,7 @@ class TFVE408 : public TDriverHandle double GetSound(int i) override; /// Enables the time chamber, disables the EP-time chamber. void Init(double Press) override; + std::vector pressures() override; /// Default constructor. using TDriverHandle::TDriverHandle;}; diff --git a/physics/components/airsupply.h b/physics/components/airsupply.h index b5a04460b..acf237ee8 100644 --- a/physics/components/airsupply.h +++ b/physics/components/airsupply.h @@ -254,6 +254,30 @@ class AirCompressor return step; } + // what a snapshot of the simulation keeps of it (physics/components/snapshot.cpp), put back as it was + struct Snapshot + { + bool running{false}; + bool allow{false}; + bool allowLocal{true}; + bool governorLock{false}; + double powerTime{0.0}; + int listPosition{0}; + }; + Snapshot TakeSnapshot() const + { + return {running, allow, allowLocal, governorLock, powerTime, listPosition}; + } + void RestoreSnapshot(Snapshot const &State) + { + running = State.running; + allow = State.allow; + allowLocal = State.allowLocal; + governorLock = State.governorLock; + powerTime = State.powerTime; + listPosition = State.listPosition; + } + private: bool running{false}; bool allow{false}; @@ -318,6 +342,22 @@ class AirSupply // for the tests: the pressure in the reservoir as given, whatever its air void SetPressureForTest(double const Value) { mainReservoirPressure = Value; } + // what a snapshot of the simulation keeps of it (physics/components/snapshot.cpp), put back as it was + struct Snapshot + { + double mainReservoirPressure{0.0}; + double compressedVolume{0.0}; + }; + Snapshot TakeSnapshot() const + { + return {mainReservoirPressure, compressedVolume}; + } + void RestoreSnapshot(Snapshot const &State) + { + mainReservoirPressure = State.mainReservoirPressure; + compressedVolume = State.compressedVolume; + } + private: double mainReservoirPressure{0.0}; double compressedVolume{0.0}; diff --git a/physics/components/cab.cpp b/physics/components/cab.cpp index b17bd8624..99025c534 100644 --- a/physics/components/cab.cpp +++ b/physics/components/cab.cpp @@ -180,6 +180,11 @@ bool physics::Vehicle::CabDeactivisationAuto(bool const Enforce) return OK; } +bool physics::Vehicle::MirrorsFold() const +{ + return (Vel > MirrorVelClose) || (CabActive == 0 && (InactiveCabFlag & activation::mirrors) != 0) || mirrorForbidden; +} + // ************************************************************************************************* // pullee mode ("jazda ciągniona", MaSzyna-EU07/maszyna#64): prepares the vehicle for being hauled dead in a // train, or puts it back in service. while in the mode the vehicle: diff --git a/physics/components/collisions.cpp b/physics/components/collisions.cpp index 5ce2a5a89..8204361d5 100644 --- a/physics/components/collisions.cpp +++ b/physics/components/collisions.cpp @@ -323,6 +323,32 @@ void physics::Vehicle::derail_in_collision(DerailReason const Reason, std::strin pushed_off_monitor.reset(); ErrorLog(std::format("Bad driving: {} derailed in a collision, {}: {}", Name, Reason == COLLISION_OVERRIDE ? "overriding" : "pushed off the track", Why)); } + +void physics::Vehicle::derail_forked(int const Side, std::string const &Why) +{ + if (false == DamageFlag.Set(VehicleDamage::derailed)) + { + return; + } + // upright, the flange climbed the rail: it slides on the sleepers as one derailed by the criteria of derailment.h + derailOutcome = derailment::outcome::off_rails; + // physics.derailment new: it leaves the track to the side the other way of the switch lies on + derailCause = derail_motion::cause::off_rails; + derailAcceleration = 0.0; + derailSide = Side; + eventFlag = true; + MainSwitch(false, range_t::local); + if (Vel < 5.0) + { + // HACK: prevent permanent axle spin in static vehicle after a collision + nrotValue = 0.0; + slippingWheels = false; + } + // the brake hoses tear: the brake pipe vents and the rest of the train brakes in emergency + tear_brake_hoses(*this); + derailment_monitor.reset(); + ErrorLog(std::format("Bad driving: {} derailed running forked, {}", Name, Why)); +} namespace { diff --git a/physics/components/fizsections.cpp b/physics/components/fizsections.cpp index 08643375c..c1d1b8e8a 100644 --- a/physics/components/fizsections.cpp +++ b/physics/components/fizsections.cpp @@ -193,6 +193,7 @@ void physics::Vehicle::LoadFIZ_Wheels(std::string const &line) extract_value(aDist, "Ad", line, ""); extract_value(bDist, "Bd", line, ""); + extract_value(rMin, "Rmin", line, ""); if (AxleInertialMoment <= 0.0) { diff --git a/physics/components/hosetrains.h b/physics/components/hosetrains.h new file mode 100644 index 000000000..1eafce24e --- /dev/null +++ b/physics/components/hosetrains.h @@ -0,0 +1,56 @@ +/* +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/. +*/ + +// the trains of the air exchange through the hoses (physics::Vehicle::UpdatePipeCouplers()) kept from one step to the next + +#pragma once + +#include +#include +#include + +namespace physics +{ + +class Vehicle; + +// the trains of the hose exchange of the brake and the main reservoir pipe, worked out from the list of vehicles given, +// which of them stepped the pipe and which neighbours their hoses join them to. they change only with a coupling or an +// uncoupling, a vehicle going to sleep or waking up, or one added or taken away, so they're kept while all of that +// stays as it was in the step before, which is checked on every step: kept or worked out again, they're the same +class hose_trains_cache +{ + public: + // what the trains of a pipe were worked out from, for one vehicle of the list + struct input + { + Vehicle const *vehicle{nullptr}; + std::array joined{nullptr, nullptr}; // the neighbour the hose of each end joins it to, or none + bool pending{false}; // the vehicle stepped the pipe + bool operator==(input const &) const = default; + }; + // the trains of a pipe + struct pipe + { + std::vector inputs; + std::vector scratch; // the inputs of the step, read in to be compared with those, kept for the memory + std::vector trains; // the train of each vehicle of the list, none for one which didn't step the pipe + std::vector firsts; // train t is members[firsts[t]] up to members[firsts[t + 1]], not included + std::vector members; // the indices in the list of the vehicles of each train, in the order of the list + bool valid{false}; + }; + pipe brake; + pipe main; +}; + +// physics::Vehicle::UpdatePipeCouplers(), with the trains kept in Cache from one call to the next. for one list of +// vehicles which comes back in every step (all of the scenery's, vehicle_table::update_brake_pipes()) +void UpdatePipeCouplers(std::vector const &Vehicles, double dt, hose_trains_cache &Cache); + +} // namespace physics diff --git a/physics/components/lowvoltage.h b/physics/components/lowvoltage.h index a3c4b1332..50a01fc73 100644 --- a/physics/components/lowvoltage.h +++ b/physics/components/lowvoltage.h @@ -95,6 +95,28 @@ class LowVoltageSupply void Set24vAvailableForTest(bool const State) { power24vAvailable = State; } void Set110vAvailableForTest(bool const State) { power110vAvailable = State; } + // what a snapshot of the simulation keeps of it (physics/components/snapshot.cpp), put back as it was + struct Snapshot + { + bool batteryOn{false}; + double batteryVoltage{0.0}; + bool power110vAvailable{false}; + bool power24vAvailable{false}; + double power24vVoltage{0.0}; + }; + Snapshot TakeSnapshot() const + { + return {batteryOn, batteryVoltage, power110vAvailable, power24vAvailable, power24vVoltage}; + } + void RestoreSnapshot(Snapshot const &State) + { + batteryOn = State.batteryOn; + batteryVoltage = State.batteryVoltage; + power110vAvailable = State.power110vAvailable; + power24vAvailable = State.power24vAvailable; + power24vVoltage = State.power24vVoltage; + } + private: bool batteryOn{false}; double batteryVoltage{0.0}; diff --git a/physics/components/maincircuit.h b/physics/components/maincircuit.h index 39f083687..d96a957f6 100644 --- a/physics/components/maincircuit.h +++ b/physics/components/maincircuit.h @@ -75,6 +75,22 @@ class LineBreaker return true; } + // what a snapshot of the simulation keeps of it (physics/components/snapshot.cpp), put back as it was + struct Snapshot + { + bool closed{false}; + double initCountdown{0.0}; + }; + Snapshot TakeSnapshot() const + { + return {closed, initCountdown}; + } + void RestoreSnapshot(Snapshot const &State) + { + closed = State.closed; + initCountdown = State.initCountdown; + } + private: bool closed{false}; double initCountdown{0.0}; // how long it still initialises [s] @@ -104,6 +120,24 @@ class LineContactors void RestartSwitchTimer() { lastSwitchTime = 0.0; } void AdvanceSwitchTimer(double const dt) { lastSwitchTime += dt; } + // what a snapshot of the simulation keeps of it (physics/components/snapshot.cpp), put back as it was + struct Snapshot + { + bool closed{false}; + bool forcedOpen{false}; + double lastSwitchTime{0.0}; + }; + Snapshot TakeSnapshot() const + { + return {closed, forcedOpen, lastSwitchTime}; + } + void RestoreSnapshot(Snapshot const &State) + { + closed = State.closed; + forcedOpen = State.forcedOpen; + lastSwitchTime = State.lastSwitchTime; + } + private: bool closed{false}; bool forcedOpen{false}; @@ -169,6 +203,26 @@ class ProtectionRelays pressureSwitch = config.hasPressureSwitch && ((config.pressureSwitchWatchesCylinders && cylinderPressure > 2.0) || pipePressure < 3.6); } + // what a snapshot of the simulation keeps of it (physics/components/snapshot.cpp), put back as it was + struct Snapshot + { + bool noVoltage{true}; + bool overvoltage{true}; + bool ground{true}; + bool pressureSwitch{false}; + }; + Snapshot TakeSnapshot() const + { + return {noVoltage, overvoltage, ground, pressureSwitch}; + } + void RestoreSnapshot(Snapshot const &State) + { + noVoltage = State.noVoltage; + overvoltage = State.overvoltage; + ground = State.ground; + pressureSwitch = State.pressureSwitch; + } + private: bool noVoltage{true}; bool overvoltage{true}; @@ -278,6 +332,28 @@ class PowerConverter // for the tests of the parts it feeds: the converter running, or not, whatever its conditions void SetRunningForTest(bool const State) { running = State; } + // what a snapshot of the simulation keeps of it (physics/components/snapshot.cpp), put back as it was + struct Snapshot + { + bool allow{false}; + bool allowLocal{true}; + bool running{false}; + bool overloaded{false}; + double startDelayTimer{0.0}; + }; + Snapshot TakeSnapshot() const + { + return {allow, allowLocal, running, overloaded, startDelayTimer}; + } + void RestoreSnapshot(Snapshot const &State) + { + allow = State.allow; + allowLocal = State.allowLocal; + running = State.running; + overloaded = State.overloaded; + startDelayTimer = State.startDelayTimer; + } + private: bool allow{false}; bool allowLocal{true}; diff --git a/physics/components/pantographs.h b/physics/components/pantographs.h index be7ab5688..7783d8c90 100644 --- a/physics/components/pantographs.h +++ b/physics/components/pantographs.h @@ -201,6 +201,30 @@ class PantographAir pressureSwitchActive = PressureSwitchPrimed; } + // what a snapshot of the simulation keeps of it (physics/components/snapshot.cpp), put back as it was + struct Snapshot + { + double volume{0.48}; + double pressure{0.0}; + bool compressorRunning{false}; + bool connectedToMainReservoir{true}; + bool pressureSwitchActive{false}; + bool pressureLockActive{false}; + }; + Snapshot TakeSnapshot() const + { + return {volume, pressure, compressorRunning, connectedToMainReservoir, pressureSwitchActive, pressureLockActive}; + } + void RestoreSnapshot(Snapshot const &State) + { + volume = State.volume; + pressure = State.pressure; + compressorRunning = State.compressorRunning; + connectedToMainReservoir = State.connectedToMainReservoir; + pressureSwitchActive = State.pressureSwitchActive; + pressureLockActive = State.pressureLockActive; + } + private: double volume{0.48}; // so that the raised pantographs drop soon with the compressor off double pressure{0.0}; diff --git a/physics/components/pneumatics.cpp b/physics/components/pneumatics.cpp index 335616420..cd85345ae 100644 --- a/physics/components/pneumatics.cpp +++ b/physics/components/pneumatics.cpp @@ -28,6 +28,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include "physics/components/internal.h" +#include "physics/components/hosetrains.h" // Nastawianie hamulców @@ -1425,25 +1426,96 @@ std::vector hose_trains(std::vector const &Vehi return trains; } +// the trains of the pipe laid out: the vehicles of each train, in the order of the list, for going through a train alone. a +// sub-step of a train then costs its own vehicles, not a look at every vehicle of the list (all of the scenery's, in +// update_brake_pipes()), and takes them in the same order as that did +void lay_out_trains(physics::hose_trains_cache::pipe &Layout, std::vector Trains) +{ + Layout.trains = std::move(Trains); + std::size_t count{0}; + for (auto const train : Layout.trains) + { + if (train != std::numeric_limits::max()) + { + count = std::max(count, train + 1); + } + } + Layout.firsts.assign(count + 1, 0); + for (auto const train : Layout.trains) + { + if (train < count) + { + ++Layout.firsts[train + 1]; + } + } + for (std::size_t train = 0; train < count; ++train) + { + Layout.firsts[train + 1] += Layout.firsts[train]; + } + Layout.members.resize(Layout.firsts.back()); + auto next{Layout.firsts}; + for (std::size_t index = 0; index < Layout.trains.size(); ++index) + { + if (Layout.trains[index] < count) + { + Layout.members[next[Layout.trains[index]]++] = index; + } + } +} + +// what hose_trains() goes by, of each vehicle of the list: whether it stepped the pipe and the neighbours its hoses join it to +void hose_inputs(std::vector &Inputs, std::vector const &Vehicles, train_pipe const &trainPipe) +{ + Inputs.resize(Vehicles.size()); + for (std::size_t index = 0; index < Vehicles.size(); ++index) + { + auto const &vehicle{*Vehicles[index]}; + auto &input{Inputs[index]}; + input.vehicle = &vehicle; + input.pending = (vehicle.*trainPipe.pipe).CouplersPending(); + std::size_t end{0}; + for (auto const &hose : vehicle.Couplers) + { + input.joined[end++] = (hose.Connected != nullptr && hose.CouplingFlag.HasAll(trainPipe.hose)) ? hose.Connected : nullptr; + } + } +} + // the air exchange through the hoses of the pipe, for the vehicles which stepped it since the last call, in the order // they stepped: each train in as many sub-steps of dt as its vehicle needing the most of them takes, each going through // its vehicles one after another, as the step of the vehicles does. the air of a train stays in it, so a train comes out // the same whichever other vehicles are exchanged in the same call: all of them, or the ones of a group of -// vehicle_table::update_steps_parallel() -void exchange_through_hoses(std::vector const &Vehicles, train_pipe const &trainPipe, double const dt) +// vehicle_table::update_steps_parallel(). with a Cache, the trains of the call before are taken again when what they +// were worked out from is the same +void exchange_through_hoses(std::vector const &Vehicles, train_pipe const &trainPipe, double const dt, physics::hose_trains_cache::pipe *Cache = nullptr) { - auto const trains{hose_trains(Vehicles, trainPipe)}; - std::vector substeps; + physics::hose_trains_cache::pipe fresh; + auto *layout{&fresh}; + if (Cache != nullptr) + { + hose_inputs(Cache->scratch, Vehicles, trainPipe); + if (false == Cache->valid || Cache->scratch != Cache->inputs) + { + lay_out_trains(*Cache, hose_trains(Vehicles, trainPipe)); + std::swap(Cache->inputs, Cache->scratch); + Cache->valid = true; + } + layout = Cache; + } + else + { + lay_out_trains(fresh, hose_trains(Vehicles, trainPipe)); + } + auto const &trains{layout->trains}; + auto const &firsts{layout->firsts}; + auto const &members{layout->members}; + std::vector substeps(firsts.size() - 1, 1); for (std::size_t index = 0; index < Vehicles.size(); ++index) { if (false == (Vehicles[index]->*trainPipe.pipe).CouplersPending()) { continue; } - if (substeps.size() <= trains[index]) - { - substeps.resize(trains[index] + 1, 1); - } substeps[trains[index]] = std::max(substeps[trains[index]], hose_substeps(*Vehicles[index], trainPipe, dt)); } for (std::size_t train = 0; train < substeps.size(); ++train) @@ -1451,13 +1523,9 @@ void exchange_through_hoses(std::vector const &Vehicles, tra auto const substep{dt / substeps[train]}; for (auto i = 0; i < substeps[train]; ++i) { - for (std::size_t index = 0; index < Vehicles.size(); ++index) + for (auto member = firsts[train]; member < firsts[train + 1]; ++member) { - if (false == (Vehicles[index]->*trainPipe.pipe).CouplersPending() || trains[index] != train) - { - continue; - } - auto *vehicle{Vehicles[index]}; + auto *vehicle{Vehicles[members[member]]}; auto &pipe{*(vehicle->*trainPipe.pipe).reservoir}; pipe.Act(); // what the neighbours have sent in the meantime (vehicle->*trainPipe.pipe).SetPressure(pipe.P()); @@ -1507,6 +1575,12 @@ void physics::Vehicle::UpdatePipeCouplers(std::vector const exchange_through_hoses(Vehicles, main_reservoir_pipe, dt); } +void physics::UpdatePipeCouplers(std::vector const &Vehicles, double const dt, hose_trains_cache &Cache) +{ + exchange_through_hoses(Vehicles, brake_pipe, dt, &Cache.brake); + exchange_through_hoses(Vehicles, main_reservoir_pipe, dt, &Cache.main); +} + bool physics::Vehicle::UpdateStopBrakeRelease(double const Demand, double const Dt) { if (Demand <= 0.0) diff --git a/physics/components/securitysystem.cpp b/physics/components/securitysystem.cpp index 3605d6810..45e415a2a 100644 --- a/physics/components/securitysystem.cpp +++ b/physics/components/securitysystem.cpp @@ -30,6 +30,39 @@ http://mozilla.org/MPL/2.0/. #include "physics/components/internal.h" +std::vector TSecuritySystem::state() const +{ + return {vigilance_timer, + alert_timer, + press_timer, + velocity, + cabsignal_active ? 1.0 : 0.0, + pressed ? 1.0 : 0.0, + enabled ? 1.0 : 0.0, + cabsignal_lock ? 1.0 : 0.0, + vigilance_suspended ? 1.0 : 0.0, + power ? 1.0 : 0.0, + static_cast(cabactive)}; +} + +void TSecuritySystem::state(std::vector const &State) +{ + // a list of another length comes from a build which keeps other things + if (State.size() != 11) + return; + vigilance_timer = State[0]; + alert_timer = State[1]; + press_timer = State[2]; + velocity = State[3]; + cabsignal_active = State[4] != 0.0; + pressed = State[5] != 0.0; + enabled = State[6] != 0.0; + cabsignal_lock = State[7] != 0.0; + vigilance_suspended = State[8] != 0.0; + power = State[9] != 0.0; + cabactive = static_cast(State[10]); +} + void TSecuritySystem::set_enabled(bool e) { if (vigilance_enabled || cabsignal_enabled || radiostop_enabled) diff --git a/physics/components/snapshot.cpp b/physics/components/snapshot.cpp new file mode 100644 index 000000000..ed0b85430 --- /dev/null +++ b/physics/components/snapshot.cpp @@ -0,0 +1,1130 @@ +/* +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/. +*/ + +// the state of a running vehicle in a snapshot of the simulation (simulation/simulationsnapshot.h): what it carries, how it +// moves, what its machinery is set to and the air in its brakes. the list of what's kept is here; it's what a train needs +// to carry on as it was, not every variable of the physics. the keys and their order are those of the snapshots written +// before the state of the vehicle went private, so those still load + +#include "stdafx.h" +#include "physics/vehicle.h" +#include "physics/brakes.h" +#include "simulation/simulationsnapshot.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace snap = simulation::snapshot; + +namespace +{ + +// keys of the parts a vehicle has two of, or a few: "pant0valve", "door1open" +std::string indexed(std::string_view const Part, int const Index, std::string_view const Key) +{ + return std::format("{}{}{}", Part, Index, Key); +} + +// the pressures a valve of the driver keeps, under the keys "0", "1"... +void capture_handle(snap::record &Entry, std::string_view const Name, TDriverHandle &Handle) +{ + std::vector values; + for (auto const *pressure : Handle.pressures()) + values.emplace_back(*pressure); + Entry.set(Name, snap::numbers_text(values)); + Entry.set(std::format("{}time", Name), (Handle.Time ? 1 : 0) | (Handle.TimeEP ? 2 : 0)); +} + +void apply_handle(snap::record const &Entry, std::string_view const Name, TDriverHandle &Handle) +{ + auto const pressures{Handle.pressures()}; + // the pressures of another kind of valve mean nothing to this one + if (auto const values{snap::text_numbers(Entry.text(Name))}; values.size() == pressures.size()) + { + for (std::size_t index{0}; index < values.size(); ++index) + *pressures[index] = values[index]; + } + if (auto time{0}; Entry.get(std::format("{}time", Name), time)) + { + Handle.Time = (time & 1) != 0; + Handle.TimeEP = (time & 2) != 0; + } +} + +// the three states of a device as one number: 1 allowed to run, 2 told to stop, 4 running +template int device_state(Device_ const &Device) +{ + return (Device.is_enabled ? 1 : 0) | (Device.is_disabled ? 2 : 0) | (Device.is_active ? 4 : 0); +} + +template void device_state(Device_ &Device, int const State) +{ + Device.is_enabled = (State & 1) != 0; + Device.is_disabled = (State & 2) != 0; + Device.is_active = (State & 4) != 0; +} + +template void capture_device(snap::record &Entry, std::string_view const Key, Device_ const &Device) +{ + Entry.set(Key, device_state(Device)); +} + +template void apply_device(snap::record const &Entry, std::string_view const Key, Device_ &Device) +{ + if (auto state{0}; Entry.get(Key, state)) + device_state(Device, state); +} + +// what a door is told to do, as one number: 1 permit, 2 local open, 4 local close, 8 remote open, 16 remote close +int door_inputs(physics::basic_door const &Door) +{ + return (Door.open_permit ? 1 : 0) | (Door.local_open ? 2 : 0) | (Door.local_close ? 4 : 0) | (Door.remote_open ? 8 : 0) | (Door.remote_close ? 16 : 0); +} + +// what a door does, as one number: 1 closed with its step, 2 the door itself closed, 4 closing, 8 opening, 16 open, +// 32 step folding, 64 step unfolding +int door_outputs(physics::basic_door const &Door) +{ + return (Door.is_closed ? 1 : 0) | (Door.is_door_closed ? 2 : 0) | (Door.is_closing ? 4 : 0) | (Door.is_opening ? 8 : 0) | (Door.is_open ? 16 : 0) | + (Door.step_folding ? 32 : 0) | (Door.step_unfolding ? 64 : 0); +} + +void apply_door(physics::basic_door &Door, snap::record const &Entry, int const Index) +{ + if (auto inputs{0}; Entry.get(indexed("door", Index, "in"), inputs)) + { + Door.open_permit = (inputs & 1) != 0; + Door.local_open = (inputs & 2) != 0; + Door.local_close = (inputs & 4) != 0; + Door.remote_open = (inputs & 8) != 0; + Door.remote_close = (inputs & 16) != 0; + } + if (auto outputs{0}; Entry.get(indexed("door", Index, "out"), outputs)) + { + Door.is_closed = (outputs & 1) != 0; + Door.is_door_closed = (outputs & 2) != 0; + Door.is_closing = (outputs & 4) != 0; + Door.is_opening = (outputs & 8) != 0; + Door.is_open = (outputs & 16) != 0; + Door.step_folding = (outputs & 32) != 0; + Door.step_unfolding = (outputs & 64) != 0; + } + Entry.get(indexed("door", Index, "position"), Door.position); + Entry.get(indexed("door", Index, "step"), Door.step_position); + Entry.get(indexed("door", Index, "timer"), Door.auto_timer); + Entry.get(indexed("door", Index, "closedelay"), Door.close_delay); + Entry.get(indexed("door", Index, "opendelay"), Door.open_delay); +} + +// the air of a reservoir: what it holds and, when there's any, the flow it has taken since it last acted. a flow +// added late in a step (the feed of the brake reservoir from the main pipe) waits there for the next one +void capture_reservoir(snap::record &Entry, std::string const &Key, TReservoir const &Reservoir) +{ + Entry.set(Key, Reservoir.GetVol()); + if (Reservoir.GetPendingFlow() != 0.0) + Entry.set(Key + "flow", Reservoir.GetPendingFlow()); +} + +bool apply_reservoir(TReservoir &Reservoir, snap::record const &Entry, std::string const &Key) +{ + auto volume{0.0}; + if (false == Entry.get(Key, volume)) + return false; + Reservoir.SetVol(volume, Entry.value(Key + "flow", 0.0)); + return true; +} + +// the figures of an induction motor drive, which each step goes on from, in the order of the eimv table they were kept +// in before (eimv_FMAXMAX .. eimv_Fful), which is the order of the snapshot +template auto induction_motor_figures(State_ &State) +{ + return std::array{&State.absoluteMaxForce, &State.maxForce, &State.slipShare, &State.slipFrequency, &State.supplyFrequency, &State.voltage, + &State.flux, &State.torqueCurrent, &State.fieldCurrent, &State.torque, &State.force, &State.lineCurrent, + &State.mechanicalPower, &State.electricalPower, &State.efficiency, &State.criticalFrequency, &State.linkVoltage, + &State.powerLimit, &State.forceDemand, &State.currentLimit, &State.fullForce}; +} + +} // namespace + +struct physics::Vehicle::snapshot_members +{ + // the state of the parts of the vehicle the snapshot keeps, as plain values: taken from the parts for a save and + // for a load, and put back into them once the load has set what the entry has + struct parts + { + LowVoltageSupply::Snapshot lowVoltage; + bool heating{false}; + bool heatingAllow{false}; + LineBreaker::Snapshot lineBreaker; + LineContactors::Snapshot lineContactors; + ProtectionRelays::Snapshot protection; + PowerConverter::Snapshot converter; + double pantographFrontVoltage{0.0}; + double pantographRearVoltage{0.0}; + double pantographSupplyVoltage{0.0}; + bool pantographsAllDown{false}; + PantographAir::Snapshot pantographAir; + AirCompressor::Snapshot compressor; + AirSupply::Snapshot air; + double brakePipePressure{0.0}; + double mainPipePressure{0.0}; + int handlePosition{0}; + double handlePositionReal{0.0}; + double handleCapPosition{0.0}; + double handlePositionSmooth{0.0}; + double independentPosition{0.0}; + double independentPositionEim{0.0}; + int handBrakePosition{0}; + // the sets of flags, by their numbers + int damage{0}; + int equipmentFaults{0}; + }; + + static parts take(Vehicle const &V) + { + parts P; + P.lowVoltage = V.lowVoltage.TakeSnapshot(); + P.heating = V.trainHeating.IsOn(); + P.heatingAllow = V.trainHeating.IsAllowed(); + P.lineBreaker = V.lineBreaker.TakeSnapshot(); + P.lineContactors = V.lineContactors.TakeSnapshot(); + P.protection = V.protection.TakeSnapshot(); + P.converter = V.converter.TakeSnapshot(); + P.pantographFrontVoltage = V.pantographCircuit.FrontVoltage(); + P.pantographRearVoltage = V.pantographCircuit.RearVoltage(); + P.pantographSupplyVoltage = V.pantographCircuit.SupplyVoltage(); + P.pantographsAllDown = V.pantographCircuit.AllDown(); + P.pantographAir = V.pantographAir.TakeSnapshot(); + P.compressor = V.air.compressor.TakeSnapshot(); + P.air = V.air.TakeSnapshot(); + P.brakePipePressure = V.brakePipe.Pressure(); + P.mainPipePressure = V.mainPipe.Pressure(); + P.handlePosition = V.brakes.HandlePosition(); + P.handlePositionReal = V.brakes.HandlePositionReal(); + P.handleCapPosition = V.brakes.HandleCapPosition(); + P.handlePositionSmooth = V.brakes.HandlePositionSmooth(); + P.independentPosition = V.brakes.IndependentPosition(); + P.independentPositionEim = V.brakes.IndependentPositionEim(); + P.handBrakePosition = V.brakes.HandBrakePosition(); + P.damage = V.DamageFlag.Bits(); + P.equipmentFaults = V.equipmentFaults.Bits(); + return P; + } + + static void put(Vehicle &V, parts const &P) + { + V.lowVoltage.RestoreSnapshot(P.lowVoltage); + V.trainHeating.SetOn(P.heating); + V.trainHeating.Allow(P.heatingAllow); + V.lineBreaker.RestoreSnapshot(P.lineBreaker); + V.lineContactors.RestoreSnapshot(P.lineContactors); + V.protection.RestoreSnapshot(P.protection); + V.converter.RestoreSnapshot(P.converter); + V.pantographCircuit.SetFrontVoltage(P.pantographFrontVoltage); + V.pantographCircuit.SetRearVoltage(P.pantographRearVoltage); + V.pantographCircuit.SetSupplyVoltage(P.pantographSupplyVoltage); + V.pantographCircuit.SetAllDown(P.pantographsAllDown); + V.pantographAir.RestoreSnapshot(P.pantographAir); + V.air.compressor.RestoreSnapshot(P.compressor); + V.air.RestoreSnapshot(P.air); + V.brakePipe.SetPressure(P.brakePipePressure); + V.mainPipe.SetPressure(P.mainPipePressure); + V.brakes.SetHandlePosition(P.handlePosition); + V.brakes.SetHandlePositionReal(P.handlePositionReal); + V.brakes.SetHandleCapPosition(P.handleCapPosition); + V.brakes.SetHandlePositionSmooth(P.handlePositionSmooth); + V.brakes.SetIndependentPosition(P.independentPosition); + V.brakes.SetIndependentPositionEim(P.independentPositionEim); + V.brakes.SetHandBrakePosition(P.handBrakePosition); + // as the snapshot had them, without what setting them anew sets going (SetEquipmentFaults()) + V.DamageFlag = DamageSet::FromBits(P.damage); + V.equipmentFaults = EquipmentFaultSet::FromBits(P.equipmentFaults); + } + + // the plain values the snapshot keeps under a key each, by groups in the order of the entry. Vehicle_ and Parts_ are + // const for a save; Visit takes the key and the variable + + // what the vehicle does: its movement, as the physics left it at the end of the step + template static void motion(Vehicle_ &V, Parts_ &, Visit_ const &Visit) + { + Visit("v", V.travelSpeed); + Visit("vel", V.Vel); + Visit("acc", V.accS); + Visit("accv", V.accSVBased); + Visit("nrot", V.nrotValue); + Visit("distance", V.distCounter); + Visit("movelen", V.moveLength); + } + + // forces, moments and powers a step reads before it works them out anew, as it left them + template static void forces(Vehicle_ &V, Parts_ &, Visit_ const &Visit) + { + Visit("enginepower", V.EnginePower); + Visit("ft", V.ft); + Visit("fw", V.Fw); + Visit("mm", V.motorMoment); + Visit("mw", V.Mw); + Visit("fb", V.brakingForce); + Visit("ff", V.Ff); + Visit("ftrain", V.FTrain); + Visit("fstand", V.FStand); + Visit("ftotal", V.FTotal); + Visit("unitbrakeforce", V.brakes.unitForce); + Visit("ntotal", V.Ntotal); + Visit("totalcurrent", V.TotalCurrent); + Visit("dl", V.dL); + Visit("nroteps", V.nrot_eps); + Visit("accn", V.accN); + Visit("accvert", V.accVert); + Visit("dizeltorque", V.diesel.torque); + Visit("dizelpower", V.diesel.power); + Visit("dizeldeltaomega", V.diesel.clutchSlip); + Visit("dizelnold", V.diesel.previousRevolutions); + Visit("dizelnregmin", V.diesel.governorMinRevolutions); + Visit("dizelnregmax", V.diesel.governorMaxRevolutions); + Visit("hydrotorquein", V.torqueConverter.torqueIn); + Visit("hydrotorqueout", V.torqueConverter.torqueOut); + Visit("hydrotmratio", V.torqueConverter.torqueRatio); + Visit("hydrorequest", V.torqueConverter.request); + Visit("retarderfill", V.retarder.fill); + Visit("retardertorque", V.retarder.torque); + Visit("retarderrequest", V.retarder.request); + Visit("retardern", V.retarder.revolutions); + Visit("eimvpr", V.inductionMotor.forceShare); + Visit("eimicstep", V.eimic_step_progress); + Visit("eimicspeedctrl", V.eimicSpeedCtrlValue); + Visit("eimicspeedctrlintegral", V.eimicSpeedCtrlIntegral); + Visit("newspeed", V.newSpeed); + Visit("speedctrltimer", V.SpeedCtrlTimer); + Visit("vadd", V.Vadd); + Visit("medepvctime", V.brakes.blending.epCorrectionTimer); + Visit("mededdelay", V.brakes.blending.edDelayTimer); + // how long power has been asked for, which lets the holding brake of a unit go after its delay + Visit("stopbrakereleasetimer", V.brakes.holding.releaseTimer); + } + + // positions of the controllers + template static void positions(Vehicle_ &V, Parts_ &P, Visit_ const &Visit) + { + Visit("mainctrl", V.mainCtrlPos); + Visit("scndctrl", V.scndCtrlPos); + Visit("mainctrlactual", V.MainCtrlActualPos); + Visit("scndctrlactual", V.ScndCtrlActualPos); + Visit("diractive", V.DirActive); + Visit("dirabsolute", V.DirAbsolute); + Visit("cabactive", V.CabActive); + Visit("caboccupied", V.cabOccupied); + Visit("lightspos", V.lightsPos); + Visit("compressorlistpos", P.compressor.listPosition); + Visit("wiperswitchpos", V.wiperSwitchPos); + Visit("pulseforcecount", V.PulseForceCount); + Visit("loadstatus", V.loadStatus); + Visit("brakectrl", P.handlePosition); + Visit("manualbrake", P.handBrakePosition); + Visit("brakedelay", V.brakes.delaySetting); + Visit("brakeopmode", V.brakes.operatingMode); + Visit("doubletr", V.DoubleTr); + Visit("damage", P.damage); + Visit("enginedamage", P.equipmentFaults); + Visit("warningsignal", V.warningSignal); + Visit("dimmer", V.modernDimmerPosition); + Visit("tuhexstage", V.TUHEX_StageActual); + } + + // continuous settings, timers of the devices and the state of the engine + template static void levels(Vehicle_ &V, Parts_ &P, Visit_ const &Visit) + { + Visit("brakectrlr", P.handlePositionReal); + Visit("brakectrl2", P.handleCapPosition); + Visit("brakectrlf", P.handlePositionSmooth); + Visit("localbrake", P.independentPosition); + Visit("localbrakeeim", P.independentPositionEim); + Visit("dynamicbrakectrl", V.brakes.electrodynamic.controllerPosition); + Visit("eimic", V.eimic); + Visit("eimicanalog", V.eimicAnalog); + Visit("eimicreal", V.eimicReal); + Visit("eimlocalbrake", V.eim_localbrake); + Visit("anpos", V.anPos); + Visit("speedctrl", V.SpeedCtrlValue); + Visit("mainsinit", P.lineBreaker.initCountdown); + Visit("converterdelay", P.converter.startDelayTimer); + Visit("compressorpowertime", P.compressor.powerTime); + Visit("wheelflat", V.wheelFlat); + Visit("brakeslippingtimer", V.brakes.antiSlipTimer); + Visit("pulseforce", V.PulseForce); + Visit("pulseforcetimer", V.PulseForceTimer); + Visit("lastloadchangetime", V.LastLoadChangeTime); + Visit("brvtimer", V.brakes.electrodynamic.resistorFansTimer); + Visit("epforce", V.EpForce); + Visit("lastrelaytime", P.lineContactors.lastSwitchTime); + Visit("lastswitchingtime", V.LastSwitchingTime); + Visit("batteryvoltage", P.lowVoltage.batteryVoltage); + Visit("power24vvoltage", P.lowVoltage.power24vVoltage); + Visit("enginevoltage", V.EngineVoltage); + Visit("enrot", V.enrot); + Visit("im", V.Im); + Visit("itot", V.Itot); + Visit("rventrot", V.RventRot); + Visit("sand", V.Sand); + Visit("dizelfill", V.diesel.fill); + Visit("dizelengage", V.diesel.clutchPressure); + Visit("dizelengagestate", V.diesel.clutchState); + Visit("dizelgear", V.diesel.automaticGearShift); + Visit("dizelfiring", V.diesel.firingCountdown); + Visit("hydrofill", V.torqueConverter.fill); + Visit("hydronin", V.torqueConverter.revolutionsIn); + Visit("hydronout", V.torqueConverter.revolutionsOut); + Visit("hydrolockuprate", V.torqueConverter.lockupRate); + Visit("eangle", V.eAngleValue); + Visit("fuelrate", V.diesel.fuelConsumptionActual); + Visit("fuelused", V.diesel.fuelConsumedTotal); + } + + // switches, levers and what they've set going + template static void switches(Vehicle_ &V, Parts_ &P, Visit_ const &Visit) + { + Visit("battery", P.lowVoltage.batteryOn); + Visit("mains", P.lineBreaker.closed); + Visit("converterallow", P.converter.allow); + Visit("converterallowlocal", P.converter.allowLocal); + Visit("converter", P.converter.running); + Visit("compressorallow", P.compressor.allow); + Visit("compressorallowlocal", P.compressor.allowLocal); + Visit("compressor", P.compressor.running); + Visit("compressorlock", P.compressor.governorLock); + Visit("pantcompressor", P.pantographAir.compressorRunning); + Visit("heatingallow", P.heatingAllow); + Visit("heating", P.heating); + Visit("cabmaster", V.cabMaster); + Visit("alarmchain", V.brakes.alarmChain); + Visit("radiostop", V.radioStopFlag); + Visit("radio", V.radio); + Visit("radiofuse", V.radioFuse); + Visit("signalling", V.signalling); + Visit("emergencyvalveopen", V.brakes.emergencyValve.open); + Visit("lockpipe", V.brakes.pipeLock.locked); + Visit("unlockpipe", V.brakes.pipeLock.unlockPressed); + Visit("departuresignal", V.departureSignalOn); + Visit("sanddoseauto", V.SandDoseAuto); + Visit("sanddoseautoallow", V.SandDoseAutoAllow); + Visit("inspectorcutout", V.brakes.cutOutByInspector); + Visit("physicactivation", V.physicActivation); + Visit("epfuse", V.epFuse); + Visit("shuntmode", V.ShuntMode); + Visit("pantkurek3", P.pantographAir.connectedToMainReservoir); + Visit("pantswitch", P.pantographAir.pressureSwitchActive); + Visit("pantlock", P.pantographAir.pressureLockActive); + Visit("pantalldown", P.pantographsAllDown); + Visit("sanddose", V.sandDose); + Visit("sanddosemanual", V.SandDoseManual); + Visit("dynamicbrake", V.brakes.electrodynamic.on); + Visit("stlinswitchoff", P.lineContactors.forcedOpen); + Visit("power110v", P.lowVoltage.power110vAvailable); + Visit("power24v", P.lowVoltage.power24vAvailable); + // prepared for being hauled dead: the scenery sets it, a switch of the physics can change it + Visit("pulleemode", V.pulleeMode); + } + + // relays and contactors + template static void relays(Vehicle_ &V, Parts_ &P, Visit_ const &Visit) + { + Visit("fuse", V.FuseFlag); + Visit("convovld", P.converter.overloaded); + Visit("groundrelay", P.protection.ground); + Visit("stlin", P.lineContactors.closed); + Visit("resistors", V.ResistorsFlag); + Visit("novoltrelay", P.protection.noVoltage); + Visit("overvoltrelay", P.protection.overvoltage); + Visit("pressureswitch", P.protection.pressureSwitch); + Visit("delayctrl", V.delayCtrlFlag); + Visit("autorelay", V.autoRelayFlag); + Visit("slipping", V.slippingWheels); + Visit("dizelstartup", V.diesel.startupRequested); + Visit("dizelignition", V.diesel.ignitionRequested); + Visit("dizelspinup", V.diesel.spinningUp); + Visit("hydrolockup", V.torqueConverter.lockedUp); + Visit("retarderclutch", V.retarder.clutchActive); + Visit("dynamicbrakeemu", V.brakes.electrodynamic.emuWorking); + Visit("tuhexreschange", V.TUHEX_ResChange); + Visit("tuhexactive", V.TUHEX_Active); + } + + // the air: pressures and volumes the physics keeps itself. the reservoirs of the brake valve come apart from these + template static void air(Vehicle_ &V, Parts_ &P, Visit_ const &Visit) + { + Visit("pipe", P.brakePipePressure); + Visit("pipeeqvt", V.brakes.equivalentPipePressure); + Visit("cntrlpipe", V.brakes.controlReservoirPressure); + Visit("scndpipe", P.mainPipePressure); + Visit("brakepress", V.brakes.cylinderPressure); + Visit("locbrakepress", V.brakes.independentCylinderPressure); + Visit("pipebrakepress", V.brakes.pipeCylinderPressure); + Visit("volume", V.brakes.reservoirAir); + Visit("compressedvolume", P.air.compressedVolume); + Visit("compressorpress", P.air.mainReservoirPressure); + Visit("limpipe", V.brakes.pipeLimiterPressure); + Visit("actflowspeed", V.actFlowSpeed); + Visit("pantvolume", P.pantographAir.volume); + Visit("pantpress", P.pantographAir.pressure); + } + + // the positions a controller or a switch of the vehicle can take. they index tables of the vehicle (the resistors of + // the start by the master controller, the settings of the compressor, the lights, the wipers), so a position of the + // file past them is brought within them: a file edited by hand, or a vehicle definition with fewer positions since + static std::pair position_range(Vehicle const &V, std::string_view const Key) + { + if (Key == "mainctrl") + return {0, std::clamp(V.MainCtrlPosNo, 0, ResArraySize)}; + if (Key == "mainctrlactual") + return {0, std::clamp(std::max(V.MainCtrlPosNo, V.RlistSize), 0, ResArraySize - 1)}; + if (Key == "scndctrl" || Key == "scndctrlactual") + return {0, std::max(V.scndCtrlPosNo, 0)}; + if (Key == "diractive" || Key == "dirabsolute" || Key == "cabactive" || Key == "caboccupied") + return {-1, 1}; + if (Key == "lightspos") + return {0, std::clamp(V.LightsPosNo, 0, static_cast(std::size(V.Lights[0])))}; + if (Key == "compressorlistpos") + return {0, std::clamp(V.air.compressor.config.listPositions, 0, static_cast(std::size(V.air.compressor.config.list[0])) - 1)}; + if (Key == "wiperswitchpos") + return {0, static_cast(std::size(V.WiperList)) - 1}; + if (Key == "brakectrl") + return {-2, std::max(V.brakes.config.handlePositions, 0)}; + if (Key == "manualbrake") + return {0, ManualBrakePosNo}; + if (Key == "dimmer") + return {0, std::max(static_cast(V.dimPositions.size()) - 1, 0)}; + return {std::numeric_limits::min(), std::numeric_limits::max()}; + } + + // the electric circuits of the vehicle, and what it gives and takes through its power couplings: each step starts + // from what the one before left there + static void capture_power(snap::record &Entry, Vehicle const &V) + { + std::vector circuits; + for (auto const &[voltage, current] : V.PowerCircuits) + { + circuits.emplace_back(voltage); + circuits.emplace_back(current); + } + Entry.set("circuits", snap::numbers_text(circuits)); + for (auto side{0}; side < 2; ++side) + { + auto const &joint{V.Couplers[side]}; + std::vector values; + for (auto const *power : {&joint.power_high, &joint.power_110v, &joint.power_24v}) + { + values.emplace_back(power->current); + values.emplace_back(power->voltage); + values.emplace_back(power->is_local ? 1.0 : 0.0); + values.emplace_back(power->is_live ? 1.0 : 0.0); + } + Entry.set(indexed("couplerpower", side, ""), snap::numbers_text(values)); + } + Entry.set("security", snap::numbers_text(V.SecuritySystem.state())); + // the figures of an induction motor drive, which each step goes on from + std::vector drive; + for (auto const *figure : induction_motor_figures(V.inductionMotor.state)) + drive.emplace_back(*figure); + Entry.set("eimv", snap::numbers_text(drive)); + // the speed control: 1 active, 2 starting, 4 set by hand, 8 braking in, 16 braking, 32 releasing, 64 standby, 128 parking + auto const &speedctrl{V.SpeedCtrlUnit}; + Entry.set("speedctrlstate", (speedctrl.IsActive ? 1 : 0) | (speedctrl.Start ? 2 : 0) | (speedctrl.ManualStateOverride ? 4 : 0) | + (speedctrl.BrakeIntervention ? 8 : 0) | (speedctrl.BrakeInterventionBraking ? 16 : 0) | + (speedctrl.BrakeInterventionUnbraking ? 32 : 0) | (speedctrl.Standby ? 64 : 0) | (speedctrl.Parking ? 128 : 0)); + Entry.set("speedctrlvelocity", speedctrl.DesiredVelocity).set("speedctrlpower", speedctrl.DesiredPower); + } + + static void apply_power(Vehicle &V, snap::record const &Entry) + { + if (auto const circuits{snap::text_numbers(Entry.text("circuits"))}; circuits.size() == 2 * V.PowerCircuits.size()) + { + for (std::size_t index{0}; index < V.PowerCircuits.size(); ++index) + V.PowerCircuits[index] = {circuits[2 * index], circuits[2 * index + 1]}; + } + for (auto side{0}; side < 2; ++side) + { + auto &joint{V.Couplers[side]}; + auto const values{snap::text_numbers(Entry.text(indexed("couplerpower", side, "")))}; + if (values.size() != 12) + continue; + std::size_t index{0}; + for (auto *power : {&joint.power_high, &joint.power_110v, &joint.power_24v}) + { + power->current = values[index]; + power->voltage = values[index + 1]; + power->is_local = values[index + 2] != 0.0; + power->is_live = values[index + 3] != 0.0; + index += 4; + } + } + if (Entry.has("security")) + { + // the last one is the cab it watches + if (auto const state{snap::text_numbers(Entry.text("security"))}; false == state.empty() && snap::whole_number(state.back(), -1, 1).has_value()) + V.SecuritySystem.state(state); + else + Entry.refuse("security", "its cab isn't -1, 0 or 1"); + } + if (auto const drive{snap::text_numbers(Entry.text("eimv"))}; drive.size() == induction_motor_figures(V.inductionMotor.state).size()) + { + auto const figures{induction_motor_figures(V.inductionMotor.state)}; + for (std::size_t index{0}; index < figures.size(); ++index) + *figures[index] = drive[index]; + } + auto &speedctrl{V.SpeedCtrlUnit}; + if (auto state{0}; Entry.get("speedctrlstate", state)) + { + speedctrl.IsActive = (state & 1) != 0; + speedctrl.Start = (state & 2) != 0; + speedctrl.ManualStateOverride = (state & 4) != 0; + speedctrl.BrakeIntervention = (state & 8) != 0; + speedctrl.BrakeInterventionBraking = (state & 16) != 0; + speedctrl.BrakeInterventionUnbraking = (state & 32) != 0; + speedctrl.Standby = (state & 64) != 0; + speedctrl.Parking = (state & 128) != 0; + } + Entry.get("speedctrlvelocity", speedctrl.DesiredVelocity); + Entry.get("speedctrlpower", speedctrl.DesiredPower); + } + + static void capture_devices(snap::record &Entry, Vehicle const &V, parts const &P) + { + capture_device(Entry, "pantsvalve", V.pantographAir.valve); + for (auto index{0}; index < static_cast(V.pantographs.size()); ++index) + { + auto const &pantograph{V.pantographs[index]}; + capture_device(Entry, indexed("pant", index, "valve"), pantograph.valve); + Entry.set(indexed("pant", index, "up"), pantograph.is_active); + Entry.set(indexed("pant", index, "voltage"), pantograph.voltage); + } + Entry.set("pantfrontvolt", P.pantographFrontVoltage); + Entry.set("pantrearvolt", P.pantographRearVoltage); + Entry.set("pantvoltage", P.pantographSupplyVoltage); + capture_device(Entry, "fuelpump", V.FuelPump); + capture_device(Entry, "oilpump", V.OilPump); + Entry.set("oilpressure", V.OilPump.pressure); + capture_device(Entry, "waterpump", V.WaterPump); + Entry.set("waterpumpbreaker", V.WaterPump.breaker); + Entry.set("waterheater", (V.WaterHeater.is_enabled ? 1 : 0) | (V.WaterHeater.is_active ? 4 : 0)); + Entry.set("waterheaterbreaker", V.WaterHeater.breaker); + for (auto index{0}; index < static_cast(V.MotorBlowers.size()); ++index) + { + capture_device(Entry, indexed("blower", index, ""), V.MotorBlowers[index]); + Entry.set(indexed("blower", index, "rpm"), V.MotorBlowers[index].revolutions); + } + capture_device(Entry, "compartmentlights", V.CompartmentLights); + Entry.set("lights0", V.litLights[VehicleEnd::front]); + Entry.set("lights1", V.litLights[VehicleEnd::rear]); + } + + static void apply_devices(Vehicle &V, parts &P, snap::record const &Entry) + { + apply_device(Entry, "pantsvalve", V.pantographAir.valve); + for (auto index{0}; index < static_cast(V.pantographs.size()); ++index) + { + auto &pantograph{V.pantographs[index]}; + apply_device(Entry, indexed("pant", index, "valve"), pantograph.valve); + Entry.get(indexed("pant", index, "up"), pantograph.is_active); + Entry.get(indexed("pant", index, "voltage"), pantograph.voltage); + } + Entry.get("pantfrontvolt", P.pantographFrontVoltage); + Entry.get("pantrearvolt", P.pantographRearVoltage); + Entry.get("pantvoltage", P.pantographSupplyVoltage); + apply_device(Entry, "fuelpump", V.FuelPump); + apply_device(Entry, "oilpump", V.OilPump); + Entry.get("oilpressure", V.OilPump.pressure); + apply_device(Entry, "waterpump", V.WaterPump); + Entry.get("waterpumpbreaker", V.WaterPump.breaker); + if (auto state{0}; Entry.get("waterheater", state)) + { + V.WaterHeater.is_enabled = (state & 1) != 0; + V.WaterHeater.is_active = (state & 4) != 0; + } + Entry.get("waterheaterbreaker", V.WaterHeater.breaker); + for (auto index{0}; index < static_cast(V.MotorBlowers.size()); ++index) + { + apply_device(Entry, indexed("blower", index, ""), V.MotorBlowers[index]); + Entry.get(indexed("blower", index, "rpm"), V.MotorBlowers[index].revolutions); + } + apply_device(Entry, "compartmentlights", V.CompartmentLights); + Entry.get("lights0", V.litLights[VehicleEnd::front]); + Entry.get("lights1", V.litLights[VehicleEnd::rear]); + } + + static void capture_doors(snap::record &Entry, Vehicle const &V) + { + Entry.set("doorlock", V.Doors.lock_enabled); + Entry.set("doorlocked", V.Doors.is_locked); + Entry.set("doorstep", V.Doors.step_enabled); + Entry.set("doorremoteonly", V.Doors.remote_only); + Entry.set("doorpreset", V.Doors.permit_preset); + for (auto index{0}; index < static_cast(V.Doors.instances.size()); ++index) + { + auto const &door{V.Doors.instances[index]}; + Entry.set(indexed("door", index, "in"), door_inputs(door)); + Entry.set(indexed("door", index, "out"), door_outputs(door)); + Entry.set(indexed("door", index, "position"), door.position); + Entry.set(indexed("door", index, "step"), door.step_position); + Entry.set(indexed("door", index, "timer"), door.auto_timer); + Entry.set(indexed("door", index, "closedelay"), door.close_delay); + Entry.set(indexed("door", index, "opendelay"), door.open_delay); + } + } + + static void apply_doors(Vehicle &V, snap::record const &Entry) + { + Entry.get("doorlock", V.Doors.lock_enabled); + Entry.get("doorlocked", V.Doors.is_locked); + Entry.get("doorstep", V.Doors.step_enabled); + Entry.get("doorremoteonly", V.Doors.remote_only); + Entry.get("doorpreset", V.Doors.permit_preset); + for (auto index{0}; index < static_cast(V.Doors.instances.size()); ++index) + apply_door(V.Doors.instances[index], Entry, index); + } + + // the temperatures of a combustion engine and what its cooling is doing + static void capture_heat(snap::record &Entry, Vehicle const &V) + { + auto const &heat{V.diesel.heat}; + Entry.set("heatts", heat.Ts).set("heatto", heat.To).set("heattsr", heat.Tsr).set("heattwy", heat.Twy).set("heattsr2", heat.Tsr2).set("heattwy2", heat.Twy2); + Entry.set("heatt1", heat.temperatura1).set("heatt2", heat.temperatura2).set("heatrpmw", heat.rpmw).set("heatrpmw2", heat.rpmw2); + Entry.set("heatshutters1", heat.zaluzje1).set("heatshutters2", heat.zaluzje2).set("heatfault", heat.PA); + Entry.set("heatrpmwz", heat.rpmwz).set("heatrpmwz2", heat.rpmwz2).set("heatenginehot", heat.engine_is_hot); + // what each circuit of the cooling tells of its fluid: 1 too cold, 2 too hot, 4 past the cooling point, 8 flowing + auto index{0}; + for (auto const *circuit : {&heat.water, &heat.water_aux, &heat.oil, &heat.engine}) + { + Entry.set(indexed("heatcircuit", index++, ""), + (circuit->is_cold ? 1 : 0) | (circuit->is_warm ? 2 : 0) | (circuit->is_hot ? 4 : 0) | (circuit->is_flowing ? 8 : 0)); + } + } + + static void apply_heat(Vehicle &V, snap::record const &Entry) + { + auto &heat{V.diesel.heat}; + Entry.get("heatts", heat.Ts); + Entry.get("heatto", heat.To); + Entry.get("heattsr", heat.Tsr); + Entry.get("heattwy", heat.Twy); + Entry.get("heattsr2", heat.Tsr2); + Entry.get("heattwy2", heat.Twy2); + Entry.get("heatt1", heat.temperatura1); + Entry.get("heatt2", heat.temperatura2); + Entry.get("heatrpmw", heat.rpmw); + Entry.get("heatrpmw2", heat.rpmw2); + Entry.get("heatshutters1", heat.zaluzje1); + Entry.get("heatshutters2", heat.zaluzje2); + Entry.get("heatfault", heat.PA); + Entry.get("heatrpmwz", heat.rpmwz); + Entry.get("heatrpmwz2", heat.rpmwz2); + Entry.get("heatenginehot", heat.engine_is_hot); + auto index{0}; + for (auto *circuit : {&heat.water, &heat.water_aux, &heat.oil, &heat.engine}) + { + if (auto state{0}; Entry.get(indexed("heatcircuit", index++, ""), state)) + { + circuit->is_cold = (state & 1) != 0; + circuit->is_warm = (state & 2) != 0; + circuit->is_hot = (state & 4) != 0; + circuit->is_flowing = (state & 8) != 0; + } + } + } + + // the air of the brake: the pipes of the vehicle, the reservoirs of its valve, the valve of the driver, the spring brake + static void capture_brake(snap::record &Entry, Vehicle const &V) + { + if (V.brakePipe.reservoir != nullptr) + capture_reservoir(Entry, "pipeair", *V.brakePipe.reservoir); + if (V.mainPipe.reservoir != nullptr) + capture_reservoir(Entry, "scndpipeair", *V.mainPipe.reservoir); + // the brake set for an empty, a part loaded or a loaded vehicle + Entry.set("brakeload", V.brakes.loadSetting); + if (auto const *valve{V.brakes.distributor.get()}; valve != nullptr) + { + Entry.set("brakestatus", valve->GetBrakeStatus()); + Entry.set("releaser", valve->Releaser()); + // the latches of its inner valves, the step of its rapid relay + Entry.set("brakelatches", snap::numbers_text(valve->latches())); + auto index{0}; + for (auto const *reservoir : valve->reservoirs()) + { + if (reservoir != nullptr) + capture_reservoir(Entry, indexed("res", index, ""), *reservoir); + else + Entry.set(indexed("res", index, ""), 0.0); + ++index; + } + } + if (V.brakes.driverValve != nullptr) + capture_handle(Entry, "handle", *V.brakes.driverValve); + if (V.brakes.independentValve != nullptr) + capture_handle(Entry, "lochandle", *V.brakes.independentValve); + auto const &spring{V.brakes.spring}; + Entry.set("springbrake", spring.activate); + Entry.set("springbrakeshutoff", spring.shutOff); + Entry.set("springbrakerelease", spring.release); + Entry.set("springbrakeactive", spring.isActive); + Entry.set("springbrakeready", spring.isReady); + Entry.set("springbrakepress", spring.pressure); + if (spring.cylinder != nullptr) + capture_reservoir(Entry, "springbrakevolume", *spring.cylinder); + } + + static void apply_brake_valve(TBrake &Valve, Vehicle const &V, snap::record const &Entry) + { + auto const reservoirs{Valve.reservoirs()}; + // the air of each reservoir, when the entry has it for the reservoirs this kind of valve has; otherwise the valve + // is set as the scenery sets it at the start, to the pressures of the pipe and of the cylinders + if (auto const complete{false == reservoirs.empty() && Entry.has(indexed("res", static_cast(reservoirs.size()) - 1, "")) && + false == Entry.has(indexed("res", static_cast(reservoirs.size()), ""))}; + false == complete) + { + if (Entry.has("pipe")) + Valve.Init(V.brakePipe.Pressure(), V.brakes.config.pipeHighPressure, V.brakes.config.pipeLowPressure, V.brakes.cylinderPressure, V.brakes.delaySetting); + } + else + { + auto index{0}; + for (auto *reservoir : reservoirs) + { + if (reservoir != nullptr) + apply_reservoir(*reservoir, Entry, indexed("res", index, "")); + ++index; + } + } + if (Entry.has("brakedelay")) + Valve.SetBDF(V.brakes.delaySetting); + if (auto status{0}; Entry.get("brakestatus", status)) + Valve.SetBrakeStatus(status); + // of the same kind of valve only: another kind has other latches + if (auto const latches{snap::text_numbers(Entry.text("brakelatches"))}; latches.size() == Valve.latches().size()) + Valve.latches(latches); + if (auto releaser{false}; Entry.get("releaser", releaser) && releaser != Valve.Releaser()) + Valve.Releaser(releaser ? 1 : 0); + } + + static void apply_brake(Vehicle &V, snap::record const &Entry) + { + // the pipes of the vehicle hold the pressures the physics reads them from: by their air, or, for an entry which + // only gives the pressures, filled to those + if (V.brakePipe.reservoir != nullptr && false == apply_reservoir(*V.brakePipe.reservoir, Entry, "pipeair") && Entry.has("pipe")) + { + V.brakePipe.reservoir->CreatePress(V.brakePipe.Pressure()); + V.brakePipe.reservoir->Act(); + } + if (V.mainPipe.reservoir != nullptr && false == apply_reservoir(*V.mainPipe.reservoir, Entry, "scndpipeair") && Entry.has("scndpipe")) + { + V.mainPipe.reservoir->CreatePress(V.mainPipe.Pressure()); + V.mainPipe.reservoir->Act(); + } + if (auto setting{V.brakes.loadSetting}; Entry.get("brakeload", setting, 0, 3)) + { + // by the steps of the lever, which change the ratio of the rigging with it + auto moved{true}; + while (moved && V.brakes.loadSetting != setting) + moved = V.brakes.loadSetting < setting ? V.IncBrakeMult() : V.DecBrakeMult(); + } + if (V.brakes.distributor != nullptr) + apply_brake_valve(*V.brakes.distributor, V, Entry); + if (V.brakes.driverValve != nullptr) + apply_handle(Entry, "handle", *V.brakes.driverValve); + if (V.brakes.independentValve != nullptr) + apply_handle(Entry, "lochandle", *V.brakes.independentValve); + auto &spring{V.brakes.spring}; + Entry.get("springbrake", spring.activate); + Entry.get("springbrakeshutoff", spring.shutOff); + Entry.get("springbrakerelease", spring.release); + Entry.get("springbrakeactive", spring.isActive); + Entry.get("springbrakeready", spring.isReady); + Entry.get("springbrakepress", spring.pressure); + if (spring.cylinder != nullptr) + apply_reservoir(*spring.cylinder, Entry, "springbrakevolume"); + } + + // the load changes the mass, and with it what the brakes are set for + static void apply_load(Vehicle &V, snap::record const &Entry) + { + auto amount{V.loadAmount}; + auto name{V.LoadType.name}; + // the share of the load shown is worked out from it: what can be read as a load, up to a thousand times what the + // vehicle is rated for + auto const most{1000.f * std::max(V.maxLoad, 1.f)}; + auto const given{Entry.get("load", amount, 0.f, most)}; + if (Entry.has("load") && false == given) + return; + // the name of the load is that of its model, looked up in the folder of the vehicle + if (auto const *text{Entry.find("loadtype")}; + text != nullptr && (text->find_first_of("/\\:") != std::string::npos || text->find("..") != std::string::npos)) + { + Entry.refuse("loadtype", "a load is named by a name, not by a path"); + return; + } + if (false == Entry.get("loadtype", name) && false == given) + return; + if (amount == V.loadAmount && name == V.LoadType.name) + return; + if (name == V.LoadType.name) + { + // more or less of what it carries + V.loadAmount = amount; + V.ComputeMass(); + return; + } + // the vehicle is emptied first: it doesn't take a load of another kind on top of the one it has + V.AssignLoad(""); + if (false == name.empty()) + { + V.AssignLoad(name, amount); + // a load the vehicle isn't made for, as the scenery can give it one all the same, or one with nothing left of it + if (V.LoadType.name != name) + V.LoadType.name = name; + // AssignLoad() keeps the amount within what the vehicle is rated for, a vehicle loaded over that keeps what it had + V.loadAmount = amount; + } + V.ComputeMass(); + } + + // the track under the vehicle as the last step was given it. the next step works its constants out from this one + // (the resistance of a curve in ComputeConstans()) before it's given the track anew + static void capture_running(snap::record &Entry, Vehicle const &V) + { + auto const &shape{V.RunningShape}; + Entry.set("runningshape", snap::numbers_text(std::array{shape.R, shape.Len, shape.dHtrack, shape.dHrail, shape.uneven_curvature, shape.uneven_cross, + shape.buckle_curvature})); + auto const &track{V.RunningTrack}; + Entry.set("runningtrack", snap::numbers_text(std::array{track.Width, track.friction, static_cast(track.CategoryFlag), + static_cast(track.QualityFlag), static_cast(track.DamageFlag), + std::isfinite(track.Velmax) ? track.Velmax : 0.0})); + auto const &traction{V.RunningTraction}; + Entry.set("runningtraction", + snap::numbers_text(std::array{traction.TractionVoltage, traction.TractionFreq, traction.TractionMaxCurrent, traction.TractionResistivity})); + // where the physics has the vehicle: at the place it started the last step from, a frame behind its body. the gaps + // between the couplers are measured between these + auto const &location{V.location}; + if (std::isfinite(location.X) && std::isfinite(location.Y) && std::isfinite(location.Z)) + Entry.set("loc", snap::numbers_text(std::array{location.X, location.Y, location.Z})); + } + + static void apply_running(Vehicle &V, snap::record const &Entry) + { + if (auto const numbers{snap::text_numbers(Entry.text("runningshape"))}; numbers.size() == 7) + { + auto &shape{V.RunningShape}; + shape.R = numbers[0]; + shape.Len = numbers[1]; + shape.dHtrack = numbers[2]; + shape.dHrail = numbers[3]; + shape.uneven_curvature = numbers[4]; + shape.uneven_cross = numbers[5]; + shape.buckle_curvature = numbers[6]; + } + if (auto const numbers{snap::text_numbers(Entry.text("runningtrack"))}; numbers.size() == 6) + { + constexpr auto lowest{std::numeric_limits::min()}; + constexpr auto highest{std::numeric_limits::max()}; + auto const category{snap::whole_number(numbers[2], lowest, highest)}; + auto const quality{snap::whole_number(numbers[3], lowest, highest)}; + auto const damage{snap::whole_number(numbers[4], lowest, highest)}; + if (category.has_value() && quality.has_value() && damage.has_value()) + { + auto &track{V.RunningTrack}; + track.Width = numbers[0]; + track.friction = numbers[1]; + track.CategoryFlag = *category; + track.QualityFlag = *quality; + track.DamageFlag = *damage; + track.Velmax = numbers[5]; + } + else + Entry.refuse("runningtrack", "its flags aren't whole numbers"); + } + if (auto const numbers{snap::text_numbers(Entry.text("loc"))}; numbers.size() == 3) + V.location = {numbers[0], numbers[1], numbers[2]}; + if (auto const numbers{snap::text_numbers(Entry.text("runningtraction"))}; numbers.size() == 4) + { + auto &traction{V.RunningTraction}; + traction.TractionVoltage = numbers[0]; + traction.TractionFreq = numbers[1]; + traction.TractionMaxCurrent = numbers[2]; + traction.TractionResistivity = numbers[3]; + } + } + + // how the vehicle left the rails, by any model of the derailment, written for a vehicle that did; and for every vehicle + // the distance its criteria of derailment were last checked over. an entry without them, written before they were + // kept, leaves the vehicle on the rails as the scenery put it + static void capture_derailment(snap::record &Entry, Vehicle const &V) + { + Entry.set("derailmentdistance", V.derailmentDistance); + if (V.derailOutcome == derailment::outcome::none && V.derailedBy == derailment::reason::none && V.collisionDerail == NONE) + return; + Entry.set("derailed", static_cast(V.derailOutcome)); + Entry.set("derailedby", static_cast(V.derailedBy)); + Entry.set("derailvelocity", V.derailVelocity); + Entry.set("derailcause", static_cast(V.derailCause)); + Entry.set("derailacceleration", V.derailAcceleration); + Entry.set("derailside", V.derailSide); + Entry.set("collisionderail", static_cast(V.collisionDerail)); + } + + static void apply_derailment(Vehicle &V, snap::record const &Entry) + { + Entry.get("derailmentdistance", V.derailmentDistance); + if (auto outcome{0}; Entry.get("derailed", outcome, 0, static_cast(derailment::outcome::overturned))) + V.derailOutcome = static_cast(outcome); + if (auto reason{0}; Entry.get("derailedby", reason, 0, static_cast(derailment::reason::other))) + V.derailedBy = static_cast(reason); + Entry.get("derailvelocity", V.derailVelocity); + if (auto cause{0}; Entry.get("derailcause", cause, 0, static_cast(derail_motion::cause::collision))) + V.derailCause = static_cast(cause); + Entry.get("derailacceleration", V.derailAcceleration); + Entry.get("derailside", V.derailSide, -1, 1); + if (auto reason{0}; Entry.get("collisionderail", reason, 0, static_cast(COLLISION_PUSHED_OFF))) + V.collisionDerail = static_cast(reason); + } + + // what the brake force came from when the physics fell asleep (physics.sleepheld): a change of it wakes the vehicle + static void capture_asleep(snap::record &Entry, Vehicle const &V) + { + auto const &brakes{V.sleep_brakes}; + Entry.set("sleepbrakes", snap::numbers_text(std::array{brakes.cylinder, brakes.spring, static_cast(brakes.manual), brakes.local})); + } + + static void apply_asleep(Vehicle &V, snap::record const &Entry) + { + auto const numbers{snap::text_numbers(Entry.text("sleepbrakes"))}; + if (numbers.size() != 4) + return; + auto const manual{snap::whole_number(numbers[2], 0, ManualBrakePosNo)}; + if (false == manual.has_value()) + { + Entry.refuse("sleepbrakes", "its hand brake position isn't one the vehicle has"); + return; + } + auto &brakes{V.sleep_brakes}; + brakes.cylinder = numbers[0]; + brakes.spring = numbers[1]; + brakes.manual = *manual; + brakes.local = numbers[3]; + } + + // what each coupler keeps from the step before: its force and the deflection of the buffers, how long it has been + // overstretched, the collision it's in, and the springs of the physical model of the pair, which give by where they were + static void capture_couplers(snap::record &Entry, Vehicle const &V) + { + for (auto side{0}; side < 2; ++side) + { + auto const &joint{V.Couplers[side]}; + auto const &pair{joint.physics_state}; + Entry.set(indexed("couplerstate", side, ""), + snap::numbers_text(std::array{joint.CForce, joint.Dist, static_cast(joint.stretch_duration), joint.CheckCollision ? 1.0 : 0.0, + joint.crush, joint.closing, joint.hit_handled ? 1.0 : 0.0, joint.hit_force, joint.hit_duration, + pair.draw_gear.force, pair.draw_gear.deflection, pair.buffers.force, pair.buffers.deflection, + pair.elongation, pair.gap, static_cast(pair.stop), pair.stop_force})); + } + } + + static void apply_couplers(Vehicle &V, snap::record const &Entry) + { + for (auto side{0}; side < 2; ++side) + { + auto const values{snap::text_numbers(Entry.text(indexed("couplerstate", side, "")))}; + if (values.size() != 17) + continue; + auto const stop{snap::whole_number(values[15], std::numeric_limits::min(), std::numeric_limits::max())}; + if (false == stop.has_value()) + { + Entry.refuse(indexed("couplerstate", side, ""), "the stop of the pair isn't a whole number"); + continue; + } + auto &joint{V.Couplers[side]}; + auto &pair{joint.physics_state}; + joint.CForce = values[0]; + joint.Dist = values[1]; + joint.stretch_duration = static_cast(values[2]); + joint.CheckCollision = values[3] != 0.0; + joint.crush = values[4]; + joint.closing = values[5]; + joint.hit_handled = values[6] != 0.0; + joint.hit_force = values[7]; + joint.hit_duration = values[8]; + pair.draw_gear.force = values[9]; + pair.draw_gear.deflection = values[10]; + pair.buffers.force = values[11]; + pair.buffers.deflection = values[12]; + pair.elongation = values[13]; + pair.gap = values[14]; + pair.stop = *stop; + pair.stop_force = values[16]; + } + } +}; + +void physics::Vehicle::SnapshotSave(simulation::snapshot::record &Entry) const +{ + using members = snapshot_members; + auto const parts{members::take(*this)}; + auto const save{[&Entry](std::string_view const Key, auto const &Value) { Entry.set(Key, Value); }}; + Entry.set("load", loadAmount); + Entry.set("loadtype", LoadType.name); + members::motion(*this, parts, save); + members::forces(*this, parts, save); + members::positions(*this, parts, save); + members::levels(*this, parts, save); + members::switches(*this, parts, save); + members::relays(*this, parts, save); + members::capture_devices(Entry, *this, parts); + members::capture_doors(Entry, *this); + members::capture_heat(Entry, *this); + members::air(*this, parts, save); + members::capture_brake(Entry, *this); + members::capture_power(Entry, *this); + members::capture_running(Entry, *this); + members::capture_couplers(Entry, *this); + members::capture_derailment(Entry, *this); + members::capture_asleep(Entry, *this); +} + +void physics::Vehicle::SnapshotLoad(simulation::snapshot::record const &Entry) +{ + using members = snapshot_members; + members::apply_load(*this, Entry); + // the parts as they are; what the entry has goes over it, and they get it back before the brake, which reads the pipes + auto parts{members::take(*this)}; + auto const load{[&Entry](std::string_view const Key, auto &Value) { Entry.get(Key, Value); }}; + members::motion(*this, parts, load); + members::forces(*this, parts, load); + members::positions(*this, parts, [this, &Entry](std::string_view const Key, int &Value) { + auto const [lowest, highest]{members::position_range(*this, Key)}; + Entry.get_clamped(Key, Value, lowest, highest); + }); + members::levels(*this, parts, load); + members::switches(*this, parts, load); + members::relays(*this, parts, load); + members::apply_devices(*this, parts, Entry); + members::apply_doors(*this, Entry); + members::apply_heat(*this, Entry); + members::air(*this, parts, load); + members::put(*this, parts); + members::apply_brake(*this, Entry); + members::apply_power(*this, Entry); + members::apply_running(*this, Entry); + members::apply_couplers(*this, Entry); + members::apply_derailment(*this, Entry); + members::apply_asleep(*this, Entry); +} diff --git a/physics/consistbraking.cpp b/physics/consistbraking.cpp index 2f86603cb..4e68f932f 100644 --- a/physics/consistbraking.cpp +++ b/physics/consistbraking.cpp @@ -193,11 +193,17 @@ void physics::ConsistBrakeBlending::ComputeDemand(Step &state, Vehicle &Lead, do // the log of the braking of the consist opened, once it brakes while moving void physics::ConsistBrakeBlending::OpenLog(Step const &state, Vehicle const &Lead) { - if (state.Fzad > 1 && !log.is_open() && Lead.Vel > 1) + if (state.Fzad > 1 && !log.is_open() && false == logUnavailable && Lead.Vel > 1) { log.open( "MEDLOGS/" + Lead.Name + "_" + std::to_string( ++logCount ) + ".csv", std::ios::in | std::ios::out | std::ios::trunc ); + if( false == log.is_open() ) { + // no MEDLOGS folder (the usual case, the game doesn't come with one): not tried again for this vehicle. + // an attempt costs a file system call, and it used to be made on every step of the braking + logUnavailable = true; + return; + } log << "t\tVel\tMasa\tOsie\tFmaxPN\tFmaxED\tFfulED\tFrED\tFzad\tFzadED\tFzadPN"; for(int k=1;k<=state.np;k++) { diff --git a/physics/consistbraking.h b/physics/consistbraking.h index bef61ff4c..c7e9a3109 100644 --- a/physics/consistbraking.h +++ b/physics/consistbraking.h @@ -42,6 +42,10 @@ class ConsistBrakeBlending // the figures of the last step for the debug screen, in the order of Labels static constexpr std::array Labels{"masa: ", "amax: ", "Fzad: ", "FmPN: ", "FmED: ", "FrED: ", "FzPN: ", "nPrF: "}; std::array const &Figures() const { return figures; } + // the demand of the ED brake of the step before [N], which the next one is held to: read and put back by a snapshot of the + // simulation + double LastElectrodynamicDemand() const { return lastEdDemand; } + void RestoreLastElectrodynamicDemand(double const Demand) { lastEdDemand = Demand; } private: struct Step; @@ -63,6 +67,7 @@ class ConsistBrakeBlending double logTime{0.0}; double logInactiveTime{0.0}; int logCount{0}; + bool logUnavailable{false}; // the log couldn't be opened (no MEDLOGS folder): it isn't tried again }; } // namespace physics diff --git a/physics/derailment.h b/physics/derailment.h index d8937754e..f57a51fb5 100644 --- a/physics/derailment.h +++ b/physics/derailment.h @@ -212,9 +212,11 @@ private: stretch m_climbing; }; -// the friction of a derailed vehicle sliding along [-]: on its wheels on the sleepers and the ballast, or on its side -inline constexpr double off_rails_friction{0.3}; -inline constexpr double overturned_friction{0.5}; +// the friction of a derailed vehicle sliding along [-]: on its wheels ploughing the sleepers and the ballast, or on its +// side digging into the ground (GH#556: with 0.3 and 0.5 a train off the track at 130-150 km/h slid some 250 m, more than +// a derailment on soil gives) +inline constexpr double off_rails_friction{0.45}; +inline constexpr double overturned_friction{0.7}; double sliding_friction(outcome Outcome); // the lowest speed [m/s] from the one the cant balances at which the flange of the leading axle climbs the rail (Y / Q diff --git a/physics/oerlikonest.cpp b/physics/oerlikonest.cpp index 70c3d4f8e..c5dad80b9 100644 --- a/physics/oerlikonest.cpp +++ b/physics/oerlikonest.cpp @@ -66,12 +66,12 @@ void TPrzekladnik::Update(double dt) double BCP{ Next->P() }; double BVP{ BrakeRes->P() }; - - if ( BCP > P() ) - dV = -PFVd(BCP, 0, d2A(10), P()) * dt; + // the pressure of the relay itself, read once: nothing changes it before the flows are applied (Act()) + if ( double const ownP{ P() }; BCP > ownP ) + dV = -PFVd(BCP, 0, d2A(10), ownP) * dt; else { - if( BCP < P() ) - dV = PFVa( BVP, BCP, d2A( 10 ), P() ) * dt; + if( BCP < ownP ) + dV = PFVa( BVP, BCP, d2A( 10 ), ownP ) * dt; else dV = 0; } @@ -120,10 +120,10 @@ void TRapid::Update(double dt) ActMult = 1.0; } - if (BCP * RapidMult > P() * ActMult) - dV = -PFVd(BCP, 0, DL, P() * ActMult / RapidMult) * dt; - else if (BCP * RapidMult < P() * ActMult) - dV = PFVa(BVP, BCP, DN, P() * ActMult / RapidMult) * dt; + if (double const ownP{ P() }; BCP * RapidMult > ownP * ActMult) + dV = -PFVd(BCP, 0, DL, ownP * ActMult / RapidMult) * dt; + else if (BCP * RapidMult < ownP * ActMult) + dV = PFVa(BVP, BCP, DN, ownP * ActMult / RapidMult) * dt; else dV = 0.0; @@ -145,10 +145,10 @@ void TPrzekCiagly::Update(double dt) double const BCP{ Next->P() }; double dV; - if ( BCP > P() * Mult) - dV = -PFVd(BCP, 0, d2A(8.0), P() * Mult) * dt; - else if (BCP < P() * Mult) - dV = PFVa(BVP, BCP, d2A(8.0), P() * Mult) * dt; + if ( double const ownP{ P() }; BCP > ownP * Mult) + dV = -PFVd(BCP, 0, d2A(8.0), ownP * Mult) * dt; + else if (BCP < ownP * Mult) + dV = PFVa(BVP, BCP, d2A(8.0), ownP * Mult) * dt; else dV = 0.0; @@ -193,10 +193,11 @@ void TPrzekED::SetP(double P) void TPrzekED::Update(double dt) { - if (Next->P() > MaxP) + // the pressure after the relay, read once: the flows change it only once applied (Act()) + if (double const nextP{ Next->P() }; nextP > MaxP) { BrakeRes->Flow(dVol); - Next->Flow(PFVd(Next->P(), 0, d2A(10.0) * dt, MaxP)); + Next->Flow(PFVd(nextP, 0, d2A(10.0) * dt, MaxP)); } else Next->Flow(dVol); @@ -232,7 +233,8 @@ double TNESt3::GetPF( double const PP, double const dt, double const Vel ) // pr dV = 0.0; // BrakeCyl.Flow(-dV); Przekladniki[1]->Flow(-dV); - if ( (BrakeStatus & b_on) == b_on && Przekladniki[1]->P() * HBG300 < MaxBP ) + // the flows above change the pressure of the cylinder only once applied (Act()), it's still BCP + if ( (BrakeStatus & b_on) == b_on && BCP * HBG300 < MaxBP ) dV = PF( BVP, BCP, Nozzles[dTN] * (nastG + 2.0 * (BCP < Podskok ? 1.0 : 0.0)) + Nozzles[dON] * (1.0 - nastG) ) * dt * (0.1 + 4.9 * std::min( 0.2, cel - BCP ) ); @@ -262,8 +264,11 @@ double TNESt3::GetPF( double const PP, double const dt, double const Vel ) // pr if( PrzekPZZ != nullptr ) PrzekPZZ->SetLBP(LBP); + // the nozzle of the control reservoir's filler, the same for both flows below: the flows change the pressures it + // goes by only once applied (Act()) + double const temp = CVs(BCP); // przeplyw testowy miedzypojemnosci - dV = PF(MPP, VVP, BVs(BCP)) + PF(MPP, CVP, CVs(BCP)); + dV = PF(MPP, VVP, BVs(BCP)) + PF(MPP, CVP, temp); if (MPP - 0.05 > BVP) dV += PF(MPP - 0.05, BVP, Nozzles[dPT] * nastG + (1.0 - nastG) * Nozzles[dPO]); if (MPP > VVP) @@ -271,7 +276,6 @@ double TNESt3::GetPF( double const PP, double const dt, double const Vel ) // pr Miedzypoj->Flow(dV * dt * 0.15); // przeplyw ZS <-> PG - double const temp = CVs(BCP); dV = PF(CVP, MPP, temp) * dt; CntrlRes->Flow(dV); ValveRes->Flow(-0.02 * dV); @@ -305,6 +309,42 @@ void TNESt3::EStParams( double const /*i_crc*/ ) const // parametry charakteryst // no effect for this device type } +std::vector TNESt3::latches() const +{ + auto state{TBrake::latches()}; + state.emplace_back(Zamykajacy ? 1.0 : 0.0); + state.emplace_back(Przys_blok ? 1.0 : 0.0); + state.emplace_back(RapidStatus ? 1.0 : 0.0); + state.emplace_back(LBP); + state.emplace_back(LoadC); + return state; +} + +void TNESt3::latches(std::vector const &State) +{ + auto const first{TBrake::latches().size()}; + if (State.size() < first + 5) + return; + TBrake::latches(State); + Zamykajacy = State[first + 0] != 0.0; + Przys_blok = State[first + 1] != 0.0; + RapidStatus = State[first + 2] != 0.0; + LBP = State[first + 3]; + LoadC = State[first + 4]; +} + +std::vector TNESt3::reservoirs() const +{ + auto list { TBrake::reservoirs() }; + list.emplace_back( CntrlRes.get() ); + list.emplace_back( Miedzypoj.get() ); + // the relays hold air of their own; a slot without a relay keeps its place in the list + for( auto const &relay : Przekladniki ) { + list.emplace_back( relay.get() ); + } + return list; +} + void TNESt3::Init( double const PP, double const HPP, double const LPP, double const BP, int const BDF ) { TBrake::Init(PP, HPP, LPP, BP, BDF); diff --git a/physics/oerlikonest.h b/physics/oerlikonest.h index eedf80dc9..6ff49cbd6 100644 --- a/physics/oerlikonest.h +++ b/physics/oerlikonest.h @@ -192,6 +192,9 @@ class TNESt3 : public TBrake { public: using TBrake::TBrake; void Init( double const PP, double const HPP, double const LPP, double const BP, int const BDF ) override; + std::vector reservoirs() const override; // with the control reservoir, the intermediate volume and the relays + std::vector latches() const override; // the closing valve, the lock of the accelerator, the rapid step, the pressures last told + void latches( std::vector const &State ) override; double GetPF( double const PP, double const dt, double const Vel ) override; // przeplyw miedzy komora wstepna i PG void EStParams(double i_crc) const; // parametry charakterystyczne dla ESt double GetCRP() override; diff --git a/physics/vehicle.h b/physics/vehicle.h index 705f7cd4b..269a13add 100644 --- a/physics/vehicle.h +++ b/physics/vehicle.h @@ -34,6 +34,10 @@ http://mozilla.org/MPL/2.0/. class TractionDrive; class cParser; +namespace simulation::snapshot +{ +class record; // simulation/simulationsnapshot.h +} namespace physics { class Vehicle; @@ -450,6 +454,9 @@ class TSecuritySystem bool radiostop_available() const; bool has_separate_acknowledge() const; void load(std::string const &line, double vmax); + // what the device keeps from one step to the next, its timers and latches: read and put back by a snapshot of the simulation + std::vector state() const; + void state(std::vector const &State); double MagnetLocation = 0.0; }; @@ -667,6 +674,7 @@ class Vehicle int BearingType = 1; /*lozyska: 0 - slizgowe, 1 - toczne*/ double const &ADist() const { return aDist; } double const &BDist() const { return bDist; } /*odlegosc osi oraz czopow skretu*/ + double const &Rmin() const { return rMin; } // the tightest curve the vehicle runs through [m] (Wheels: Rmin), 0 when the definition gives none int SandCapacity = 0; /*zasobnik piasku [kg]*/ int const &WiperSwitchPos() const { return wiperSwitchPos; } // pozycja przelacznika wycieraczek @@ -1226,6 +1234,10 @@ class Vehicle // the vehicle leaves the rails in a collision, the reason told in the log, and slides on as the criteria of // derailment.h have it void derail_in_collision(DerailReason Reason, std::string const &Why); + // physics.derailment new: running forked (world/switchfork.h) the vehicle came past what it takes, the flange climbs + // the rail: it leaves the rails upright, the reason told in the log. Side is the side of its front the way the + // switch was thrown to lies on (1 the left, -1 the right, 0 unknown), the way it goes off the track to + void derail_forked(int Side, std::string const &Why); bool DirectionForward(); bool DirectionBackward(void); /*! kierunek ruchu*/ bool EIMDirectionChangeAllow(void) const; @@ -1309,6 +1321,8 @@ class Vehicle bool CabDeactivisation(bool const Enforce = false); bool CabActivisationAuto(bool const Enforce = false); bool CabDeactivisationAuto(bool const Enforce = false); + // whether the cab mirrors fold (or stay folded): above MirrorVelClose, in an inactive cab when InactiveCabFlag says so, or switched off + bool MirrorsFold() const; /*! funkcje zwiekszajace/zmniejszajace nastawniki*/ /*! glowny nastawnik:*/ @@ -1796,8 +1810,15 @@ class Vehicle // the cab interior light the light preset at given position (1-based, as lightsPos) sets, if it sets one std::optional LightsPresetCabLight(int Position) const; + // the state of the running vehicle in an entry of a snapshot of the simulation (physics/components/snapshot.cpp): what it + // carries, how it moves, what its machinery is set to and the air in its brakes. Load sets what the entry has and leaves + // the rest as the vehicle has it; the couplings belong to the pair of vehicles and aren't touched + void SnapshotSave(simulation::snapshot::record &Entry) const; + void SnapshotLoad(simulation::snapshot::record const &Entry); + private: // the state and the definition no code outside the vehicle uses + struct snapshot_members; // what a snapshot keeps of the vehicle and of its parts, physics/components/snapshot.cpp // the vehicle derails now, by the Reason, at the speed it has (DerailedBy(), DerailVelocity()) void noteDerailment(derailment::reason Reason); double eimicReal = 0; @@ -1892,6 +1913,7 @@ class Vehicle DerailReason collisionDerail{NONE}; bool autoRelayFlag = false; double bDist = 0.0; + double rMin = 0.0; bool physicActivation = true; bool waterCircuitsLink{false}; bool enableModernDimmerValue{false}; diff --git a/rendering/common/locallights.cpp b/rendering/common/locallights.cpp index 3a7349209..869ad015c 100644 --- a/rendering/common/locallights.cpp +++ b/rendering/common/locallights.cpp @@ -212,6 +212,12 @@ void gfx::local_lights::gather(glm::dvec3 const &Camera, scene::basic_region &Re gather_cab_lights(Geometry); } + // the flashlight of the player, by day as well. the lights are put in order below, so it may be added before the others + if (Global.flashlight) + { + add_flashlight(); + } + // lamps are lost in the daylight; this also spares the work of gathering them in the middle of the day auto const darkness{1.f - glm::smoothstep(LIGHT_DUSK_LUMINANCE, LIGHT_DAY_LUMINANCE, static_cast(Global.fLuminance))}; auto const range{gather_range()}; @@ -274,6 +280,35 @@ void gfx::local_lights::gather(glm::dvec3 const &Camera, scene::basic_region &Re m_gathertime = (m_gathertime == 0.0 ? elapsed : m_gathertime * 0.95 + elapsed * 0.05); } +// the flashlight of the player (Global.flashlight): a cone of neutral white light where the camera looks, from the right hand, by +// day as well. it casts shadows as the lamps of the scenery do (a cube map, made anew as it moves), so it doesn't +// light the snow or the ground through the walls of the vehicles and the houses; Global.flashlight names it to the shadow maps +void gfx::local_lights::add_flashlight() +{ + auto const &camera{Global.pCamera}; + glm::dmat4 view{1.0}; + camera.SetMatrix(view); + // the line of sight: the -z axis of the view, in the world + auto const forward{glm::normalize(-glm::dvec3{view[0][2], view[1][2], view[2][2]})}; + auto const up{glm::normalize(glm::dvec3{view[0][1], view[1][1], view[2][1]})}; + auto const right{glm::normalize(glm::dvec3{view[0][0], view[1][0], view[2][0]})}; + light flashlight; + // held in the right hand, low by the hip: off the eye, so the shadows of what it lights are seen beside the things (a light + // at the eye hides every shadow right behind the thing which casts it) + flashlight.position = camera.Pos - up * 0.35 + right * 0.25; + flashlight.direction = glm::vec3{forward}; + flashlight.color = to_linear(glm::vec3{1.f, 0.98f, 0.95f}) * 4.f; + flashlight.cos_outer = std::cos(glm::radians(16.f)); + flashlight.cos_inner = std::cos(glm::radians(8.f)); + flashlight.range = light_range(flashlight.color); + flashlight.radius = 0.02f; + flashlight.cast_shadows = true; + flashlight.shade_self = true; + flashlight.owner = &Global.flashlight; + flashlight.part = &Global.flashlight; + m_lights.emplace_back(flashlight); +} + void gfx::local_lights::reset() { m_lights.clear(); diff --git a/rendering/common/locallights.h b/rendering/common/locallights.h index 95808c079..6a7cb27d1 100644 --- a/rendering/common/locallights.h +++ b/rendering/common/locallights.h @@ -146,6 +146,8 @@ class local_lights void gather_instance(TAnimModel *Instance, glm::dvec3 const &Camera, float const Brightness, unsigned int const Framestamp); void gather_vehicle(TDynamicObject *Vehicle, glm::dvec3 const &Camera, gfx::geometrybank_manager const &Geometry, float const Freespotbrightness, float const Compartmentbrightness); void gather_cab_lights(gfx::geometrybank_manager const &Geometry); + // the flashlight of the player, when it's on (Global.flashlight), added by gather() + void add_flashlight(); bool has_light_points(TModel3d *Model); cell_data const &cell_instances(scene::basic_cell &Cell, bool const Rebuild); // the instances of the list with light points not yet in Added, appended to Lit diff --git a/rendering/common/localshadows.cpp b/rendering/common/localshadows.cpp index 867473ed1..c454d382a 100644 --- a/rendering/common/localshadows.cpp +++ b/rendering/common/localshadows.cpp @@ -48,6 +48,12 @@ float const CAB_RANGE_MIN{0.25f}; // walls are where they are for both float const CAB_SHARE_DISTANCE{1.0f}; +// the light is the flashlight of the player (gfx::local_lights::add_flashlight()) +bool is_flashlight(gfx::local_lights::light const &Light) +{ + return Light.owner == &Global.flashlight; +} + } // namespace local_shadows::level_setup local_shadows::setup(int const Level) @@ -346,7 +352,12 @@ void local_shadows::update_lamps(std::vector const &Li m_frame = Framestamp; m_wanted.clear(); auto const level{std::clamp(Global.gfx_lights_shadows, 0, 3)}; - auto const count{level > 0 ? Global.gfx_lights_shadows_lamps : 0}; + auto const lamps{level > 0 ? Global.gfx_lights_shadows_lamps : 0}; + // the flashlight of the player gets a map of its own, past those of the lamps, from when it is first switched on (the maps + // are made anew then, once). it goes with the player, so its map is drawn anew in nearly every frame: among the maps of the + // lamps it would take the first of them for itself, and with it the few drawings of their scenery a frame allows + m_flashlightslot = m_flashlightslot || (Global.flashlight && (lamps > 0)); + auto const count{((lamps > 0) && m_flashlightslot) ? lamps + 1 : lamps}; auto const size{count > 0 ? Global.gfx_lights_shadows_lamps_size : 0}; if ((static_cast(count) != m_slots.size()) || (size != m_lampssize)) { @@ -358,15 +369,17 @@ void local_shadows::update_lamps(std::vector const &Li } m_sceneryleft = setup(level).sceneryperframe; auto const reach{static_cast(Global.gfx_lights_shadows_lamps_range)}; + // the slots of the lamps: all of them but the last, when that is the flashlight's + auto const lampslots{m_slots.size() - (m_flashlightslot ? 1 : 0)}; // the lights come the most important first: the first ones within reach get the slots std::vector picked; for (auto const &light : Lights) { - if (picked.size() >= m_slots.size()) + if (picked.size() >= lampslots) { break; } - if ((light.owner == nullptr) || (false == light.cast_shadows) || (light.range < LAMP_RANGE_MIN) || (glm::length(light.position - Camera) > reach)) + if ((light.owner == nullptr) || is_flashlight(light) || (false == light.cast_shadows) || (light.range < LAMP_RANGE_MIN) || (glm::length(light.position - Camera) > reach)) { continue; } @@ -377,7 +390,7 @@ void local_shadows::update_lamps(std::vector const &Li for (auto const *light : picked) { auto placed{false}; - for (std::size_t idx = 0; idx < m_slots.size(); ++idx) + for (std::size_t idx = 0; idx < lampslots; ++idx) { auto &slot{m_slots[idx]}; if ((slot.owner == light->owner) && (slot.part == light->part) && (slot.wantedframe != Framestamp)) @@ -405,7 +418,7 @@ void local_shadows::update_lamps(std::vector const &Li // the others take the slots of lamps no longer picked for (auto const *light : unplaced) { - for (std::size_t idx = 0; idx < m_slots.size(); ++idx) + for (std::size_t idx = 0; idx < lampslots; ++idx) { auto &slot{m_slots[idx]}; if (slot.wantedframe == Framestamp) @@ -424,6 +437,10 @@ void local_shadows::update_lamps(std::vector const &Li break; } } + if (auto const flashlight{std::ranges::find_if(Lights, is_flashlight)}; m_flashlightslot && (flashlight != Lights.end()) && flashlight->cast_shadows) + { + place_flashlight(*flashlight, Framestamp); + } // the scene changed (events, the editor): the scenery parts are out of date for (auto &slot : m_slots) { @@ -435,6 +452,25 @@ void local_shadows::update_lamps(std::vector const &Li } } +void local_shadows::place_flashlight(gfx::local_lights::light const &Light, unsigned int const Framestamp) +{ + auto const idx{m_slots.size() - 1}; + auto &slot{m_slots[idx]}; + if ((slot.owner != Light.owner) || (glm::length(slot.position - Light.position) > LAMP_MOVED)) + { + // switched on, or carried on: its map is drawn anew + slot = lamp_slot{}; + slot.owner = Light.owner; + slot.part = Light.part; + } + slot.position = Light.position; + slot.range = Light.range; + slot.nearplane = lamp_near(Light); + slot.shade_self = Light.shade_self; + slot.wantedframe = Framestamp; + m_wanted.emplace_back(idx); +} + void local_shadows::reset_lamps() { for (auto &slot : m_slots) @@ -446,7 +482,16 @@ void local_shadows::reset_lamps() bool local_shadows::scenery_wanted(std::size_t const Slot) { - if (m_slots[Slot].scenery || (m_sceneryleft <= 0)) + if (m_slots[Slot].scenery) + { + return false; + } + // the map of the flashlight is drawn when it needs it, and not out of what the frame allows the lamps + if (m_flashlightslot && (Slot + 1 == m_slots.size())) + { + return true; + } + if (m_sceneryleft <= 0) { return false; } diff --git a/rendering/common/localshadows.h b/rendering/common/localshadows.h index b04f4501a..a52716751 100644 --- a/rendering/common/localshadows.h +++ b/rendering/common/localshadows.h @@ -34,6 +34,7 @@ namespace gfx // every few frames (for the moving parts of the cab: levers, doors, wipers; a few maps per frame) or when the light, the cab or the // level change. a light keeps its map (slot) while it's among those picked; the other lights of the cab take the map of the // closest light with one. the near plane of these maps is a few centimetres: the desk right under its lights holds their light back; +// - the flashlight of the player (Global.flashlight), in a map kept as those of the lamps are, in a slot of its own past theirs // - the lamps of scenery models closest to the camera (Global.gfx_lights_shadows_lamps of them, within // Global.gfx_lights_shadows_lamps_range). the map of such a lamp is kept in world axes, centred on the lamp, and has two parts: // the scenery (drawn once, when the lamp gets its slot or the scene changes) and a working copy of it, with the vehicles near @@ -134,7 +135,8 @@ class local_shadows { return m_slots[Slot]; } - // whether the scenery part of the map of the slot is to be drawn in this frame. a few per frame at most, by the level + // whether the scenery part of the map of the slot is to be drawn in this frame. a few per frame at most, by the level; the + // map of the flashlight of the player whenever it needs it, beside those bool scenery_wanted(std::size_t const Slot); // whether the working copy of the slot, with vehicles, is to be drawn in this frame (every few frames, by the level) bool vehicles_wanted(std::size_t const Slot, unsigned int const Framestamp) const; @@ -287,6 +289,11 @@ class local_shadows std::vector m_wanted; unsigned int m_frame{0}; // framestamp of the last update_lamps() int m_sceneryleft{0}; // scenery parts which may still be drawn in this frame + // the flashlight of the player (Global.flashlight) has a slot of its own, the last one, beside the + // Global.gfx_lights_shadows_lamps slots of the lamps: from when it is first switched on + bool m_flashlightslot{false}; + // gives the flashlight its slot for the frame; its map is drawn anew when it was switched on or moved + void place_flashlight(gfx::local_lights::light const &Light, unsigned int const Framestamp); bool m_lampstiming{false}; std::vector m_lampvehicles; std::vector m_slotvehicles; diff --git a/rendering/vulkan14/vulkan14memory.cpp b/rendering/vulkan14/vulkan14memory.cpp index ed0cad182..6d0a4dbc1 100644 --- a/rendering/vulkan14/vulkan14memory.cpp +++ b/rendering/vulkan14/vulkan14memory.cpp @@ -13,8 +13,10 @@ http://mozilla.org/MPL/2.0/. #include "rendering/vulkan14/vulkan14instance.h" #include "rendering/vulkan14/vulkan14device.h" +#include #include #include +#include namespace vk14 { @@ -287,6 +289,29 @@ VkDeviceAddress image_address(VmaAllocator const Allocator, VkDevice const Devic } // namespace address_registry +// the uses of the memory + +std::string_view MemoryUseOf(std::string_view const Name, std::string_view const Group) +{ + if (false == Group.empty()) + { + return Group; + } + auto const end{Name.find_last_not_of("0123456789 ")}; + return (end == std::string_view::npos ? std::string_view{"unnamed"} : Name.substr(0, end + 1)); +} + +void MemoryCount::Release() noexcept +{ + if (tally != nullptr) + { + tally->bytes -= bytes; + --tally->count; + } + tally = nullptr; + bytes = 0; +} + // allocator allocator::~allocator() @@ -337,6 +362,11 @@ bool allocator::create(instance const &Instance, device const &Device, std::stri { m_deviceheaps[i] = ((memory.memoryHeaps[i].flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) != 0); } + deviceTypes.assign(memory.memoryTypeCount, false); + for (std::uint32_t i = 0; i < memory.memoryTypeCount; ++i) + { + deviceTypes[i] = ((memory.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != 0); + } return true; } @@ -370,22 +400,70 @@ VkSharingMode allocator::sharing(bool const Shared, std::uint32_t &Count, std::u void allocator::budget(VkDeviceSize &Usage, VkDeviceSize &Budget) const { - Usage = 0; - Budget = 0; + auto const summed{Heaps()}; + Usage = summed.usage; + Budget = summed.budget; +} + +MemoryHeaps allocator::Heaps() const +{ + MemoryHeaps result; if (m_allocator == VK_NULL_HANDLE) { - return; + return result; } std::vector budgets(m_heapcount); vmaGetHeapBudgets(m_allocator, budgets.data()); for (std::uint32_t i = 0; i < m_heapcount; ++i) { - if (m_deviceheaps[i]) + if (false == m_deviceheaps[i]) { - Usage += budgets[i].usage; - Budget += budgets[i].budget; + continue; + } + result.usage += budgets[i].usage; + result.budget += budgets[i].budget; + result.blocks += budgets[i].statistics.blockBytes; + result.allocations += budgets[i].statistics.allocationBytes; + } + return result; +} + +std::vector allocator::Uses() const +{ + std::vector result; + { + std::scoped_lock lock(tallyMutex); + result.reserve(tallies.size()); + for (auto const &tally : tallies) + { + if (auto const count{tally.count.load()}; count > 0) + { + result.emplace_back(tally.group, tally.bytes.load(), count); + } } } + std::ranges::sort(result, std::ranges::greater{}, &MemoryUse::bytes); + return result; +} + +MemoryCount allocator::Count(std::string_view const Group, std::uint32_t const Memorytype, VkDeviceSize const Bytes) const +{ + if ((Memorytype >= deviceTypes.size()) || (false == deviceTypes[Memorytype])) + { + return {}; + } + std::string group{Group}; + std::scoped_lock lock(tallyMutex); + auto lookup{tallyGroups.find(group)}; + if (lookup == tallyGroups.end()) + { + auto &made{tallies.emplace_back(group)}; + lookup = tallyGroups.emplace(std::move(group), &made).first; + } + auto *tally{lookup->second}; + tally->bytes += Bytes; + ++tally->count; + return {tally, Bytes}; } // buffer @@ -406,6 +484,7 @@ buffer &buffer::operator=(buffer &&Other) noexcept std::swap(m_size, Other.m_size); std::swap(m_mapped, Other.m_mapped); std::swap(m_address, Other.m_address); + std::swap(counted, Other.counted); } return *this; } @@ -464,6 +543,7 @@ bool buffer::create(allocator const &Allocator, VkDeviceSize Size, VkBufferUsage m_allocator = Allocator.handle(); m_size = Size; m_mapped = static_cast(allocated.pMappedData); + counted = Allocator.Count(MemoryUseOf(Name, {}), allocated.memoryType, allocated.size); name_object(Allocator.device_handle(), VK_OBJECT_TYPE_BUFFER, handle_value(m_buffer), Name); return true; } @@ -478,6 +558,7 @@ void buffer::destroy() } vmaDestroyBuffer(m_allocator, m_buffer, m_allocation); } + counted.Release(); m_buffer = VK_NULL_HANDLE; m_allocation = VK_NULL_HANDLE; m_size = 0; @@ -542,7 +623,7 @@ VkImageAspectFlags image::aspect() const return VK_IMAGE_ASPECT_COLOR_BIT; } -bool image::create(allocator const &Allocator, image_desc const &Desc, std::string const &Name) +bool image::create(allocator const &Allocator, image_desc const &Desc, std::string const &Name, std::string_view const Group) { destroy(); m_desc = Desc; @@ -573,6 +654,7 @@ bool image::create(allocator const &Allocator, image_desc const &Desc, std::stri m_allocator = Allocator.handle(); m_device = Allocator.device_handle(); m_bytes = allocated.size; + counted = Allocator.Count(MemoryUseOf(Name, Group), allocated.memoryType, allocated.size); if (address_registry::enabled()) { // an image in a block of the allocator (the memory has device addresses there) is placed exactly; one in memory of its own isn't @@ -616,6 +698,7 @@ void image::destroy() } vmaDestroyImage(m_allocator, m_image, m_allocation); } + counted.Release(); m_view = VK_NULL_HANDLE; m_image = VK_NULL_HANDLE; m_allocation = VK_NULL_HANDLE; diff --git a/rendering/vulkan14/vulkan14memory.h b/rendering/vulkan14/vulkan14memory.h index 7b6b6ec48..3ce4b21b1 100644 --- a/rendering/vulkan14/vulkan14memory.h +++ b/rendering/vulkan14/vulkan14memory.h @@ -15,9 +15,14 @@ http://mozilla.org/MPL/2.0/. #include "rendering/vulkan14/vulkan14common.h" +#include #include #include #include +#include +#include +#include +#include #include namespace vk14 @@ -26,6 +31,45 @@ namespace vk14 class instance; class device; +// the device local memory the buffers and the images of one use hold: those made with the same name (without the number at its +// end) or in the same group. the allocator keeps these, the buffers and the images count themselves to them +struct MemoryTally +{ + explicit MemoryTally(std::string_view Group) : group{Group} {} + std::string const group; + std::atomic bytes{0}; + std::atomic count{0}; +}; + +// what a buffer or an image counted to the tally of its use, given back when it goes +struct MemoryCount +{ + MemoryTally *tally{nullptr}; // null where the memory isn't device local + VkDeviceSize bytes{0}; + void Release() noexcept; +}; + +// a use of the device local memory as allocator::Uses() gives it +struct MemoryUse +{ + std::string group; + VkDeviceSize bytes{0}; + std::uint32_t count{0}; +}; + +// the heaps which are local to the device, summed up, bytes +struct MemoryHeaps +{ + VkDeviceSize usage{0}; // used by the process, as the driver tells it (the allocator's blocks, the swapchain, the driver's own) + VkDeviceSize budget{0}; // what the driver gives the process + VkDeviceSize blocks{0}; // the blocks of memory the allocator holds + VkDeviceSize allocations{0}; // what its buffers and images take of these +}; + +// the use a buffer or an image named Name counts to: Group, or where none is given, Name without the number at its end ("shadow +// cascade 2" counts to "shadow cascade") +std::string_view MemoryUseOf(std::string_view Name, std::string_view Group); + // the allocator of the device memory class allocator { @@ -48,6 +92,12 @@ class allocator } // device memory used and the budget of the heaps which are local to the device, bytes void budget(VkDeviceSize &Usage, VkDeviceSize &Budget) const; + // the same with what the allocator holds of the memory + MemoryHeaps Heaps() const; + // the device local memory held by the buffers and the images by their uses, the largest first + std::vector Uses() const; + // counts an allocation of Bytes in memory of the type Memorytype to the use Group, where that memory is device local. any thread + MemoryCount Count(std::string_view Group, std::uint32_t Memorytype, VkDeviceSize Bytes) const; // the buffers and images made shared from now on are used by the queues of both families without transfers of their ownership // (VK_SHARING_MODE_CONCURRENT, the async compute of M6); nothing changes when the families are the same void share_between(std::uint32_t First, std::uint32_t Second); @@ -60,6 +110,12 @@ class allocator std::array m_shared{VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED}; std::uint32_t m_heapcount{0}; std::vector m_deviceheaps; + std::vector deviceTypes; // the memory types which are device local + // the tallies of the uses, in a deque where they stay in place as it grows (the buffers and the images point at them). counting + // doesn't change what the allocator does, so it's done by the const allocator the buffers and the images are made with + mutable std::mutex tallyMutex; + mutable std::deque tallies; + mutable std::unordered_map tallyGroups; }; // what the memory of the gpu holds by its device addresses, for the report of a lost device (device::fault_report()): the buffers, all @@ -127,6 +183,7 @@ class buffer VkDeviceSize m_size{0}; std::uint8_t *m_mapped{nullptr}; mutable VkDeviceAddress m_address{0}; // asked for the first time it's needed + MemoryCount counted; }; // the state of an image the barriers start from: its layout and the last stage and access which used it @@ -162,8 +219,9 @@ class image image &operator=(image const &) = delete; ~image(); - // a device local image with a view of all its levels and layers - bool create(allocator const &Allocator, image_desc const &Desc, std::string const &Name = {}); + // a device local image with a view of all its levels and layers. Group: the use its memory counts to, where its name doesn't tell + // it (the textures, named after their files) + bool create(allocator const &Allocator, image_desc const &Desc, std::string const &Name = {}, std::string_view Group = {}); void destroy(); VkImage handle() const @@ -198,6 +256,7 @@ class image VmaAllocation m_allocation{VK_NULL_HANDLE}; VkDeviceSize m_bytes{0}; image_desc m_desc; + MemoryCount counted; }; // a barrier of an image from its state to the given one, the state of the image updated. nothing when the image already is diff --git a/rendering/vulkan14/vulkan14renderer.cpp b/rendering/vulkan14/vulkan14renderer.cpp index 5d07dd832..d11ac55fd 100644 --- a/rendering/vulkan14/vulkan14renderer.cpp +++ b/rendering/vulkan14/vulkan14renderer.cpp @@ -19,6 +19,9 @@ http://mozilla.org/MPL/2.0/. #include "utilities/utilities.h" #include "imgui/imgui.h" +#include +#include + namespace { @@ -81,6 +84,35 @@ std::size_t render_threads() return (cores > 3 ? cores - 2 : 1); } +// the device local memory by its uses: those which hold the most of it, then the free space in the blocks of the allocator and what the +// process holds outside of it (the swapchain, the driver's own, dlss) +std::string memoryUsesInfo(vk14::allocator const &Memory) +{ + constexpr std::size_t listed{10}; + auto const heaps{Memory.Heaps()}; + auto const uses{Memory.Uses()}; + std::string text{"device memory by use:\n"}; + for (auto const &use : uses | std::views::take(listed)) + { + text += std::format(" {}: {} in {}\n", use.group, vk14::memory_size_string(use.bytes), use.count); + } + VkDeviceSize otherBytes{0}; + std::uint32_t otherCount{0}; + for (auto const &use : uses | std::views::drop(listed)) + { + otherBytes += use.bytes; + otherCount += use.count; + } + if (otherCount > 0) + { + text += std::format(" the others: {} in {}\n", vk14::memory_size_string(otherBytes), otherCount); + } + auto const freeInBlocks{heaps.blocks > heaps.allocations ? heaps.blocks - heaps.allocations : 0}; + auto const outside{heaps.usage > heaps.blocks ? heaps.usage - heaps.blocks : 0}; + text += std::format(" free in the blocks of the allocator: {}\n outside the allocator (swapchain, driver, dlss): {}\n", vk14::memory_size_string(freeInBlocks), vk14::memory_size_string(outside)); + return text; +} + } // namespace bool vulkan14_renderer::context::create_frames(std::uint32_t const Count, std::string &Reason) @@ -1273,7 +1305,7 @@ void vulkan14_renderer::update_info() (ctx.render_threaded() ? ", on the render thread; waited for it: " + to_string(ctx.render_wait, 2) + " ms\n" : "\n") + "gpu frame parts:\n" + ctx.passes.info(); VkDeviceSize usage{0}, budget{0}; ctx.memory.budget(usage, budget); - m_infostats = "device memory: " + vk14::memory_size_string(usage) + " of " + vk14::memory_size_string(budget) + (ctx.device.memory_budget_enabled() ? "" : " (no budget from the driver)") + "\n" + "images: " + std::to_string(ctx.images.size()) + + m_infostats = "device memory: " + vk14::memory_size_string(usage) + " of " + vk14::memory_size_string(budget) + (ctx.device.memory_budget_enabled() ? "" : " (no budget from the driver)") + "\n" + memoryUsesInfo(ctx.memory) + "images: " + std::to_string(ctx.images.size()) + ", uploaded " + vk14::memory_size_string(ctx.uploads.uploaded()) + ", waiting for the gpu to be deleted: " + std::to_string(ctx.deletions.size()) + "\n" + (ctx.textures ? ctx.textures->info() + "\n" : std::string{}) + ctx.shaders.info() + "\n" + ctx.pipelines.info() + "\n" + background_info() + "frame ring: " + vk14::memory_size_string(ctx.ring.used()) + " of " + vk14::memory_size_string(ctx.ring.capacity()) + ", of the draws: " + vk14::memory_size_string(ctx.scene.draws.ring.used()) + " of " + vk14::memory_size_string(ctx.scene.draws.ring.capacity()) + ", of the instances: " + diff --git a/rendering/vulkan14/vulkan14scene.cpp b/rendering/vulkan14/vulkan14scene.cpp index 9598f7f9f..53246252f 100644 --- a/rendering/vulkan14/vulkan14scene.cpp +++ b/rendering/vulkan14/vulkan14scene.cpp @@ -1761,6 +1761,11 @@ void vulkan14_renderer::walk_shadow_material(material_handle const Material) m_indirectsubmodel = nullptr; return; } + if (false == bool(m_context)) + { + // no device yet (own_shadow_program() checks it too): nothing to bind + return; + } auto &draw{*m_draw}; auto &scene{m_context->scene}; if (own != nullptr) diff --git a/rendering/vulkan14/vulkan14swapchain.cpp b/rendering/vulkan14/vulkan14swapchain.cpp index 7ceb07941..c38e5f45b 100644 --- a/rendering/vulkan14/vulkan14swapchain.cpp +++ b/rendering/vulkan14/vulkan14swapchain.cpp @@ -633,13 +633,31 @@ void swapchain::destroy_retired(bool const Now) m_retiredsemaphores.clear(); } -void swapchain::destroy() +void swapchain::destroy() noexcept { + // everything goes at once here, so the present semaphores aren't kept for later like in release_images(): nothing to allocate, + // which the destructor can't afford auto const device{m_device != nullptr ? m_device->handle() : VK_NULL_HANDLE}; if (device != VK_NULL_HANDLE) { - release_images(); - destroy_retired(true); + for (auto const view : m_views) + { + if (view != VK_NULL_HANDLE) + { + vkDestroyImageView(device, view, nullptr); + } + } + for (auto const semaphore : m_presentsemaphores) + { + if (semaphore != VK_NULL_HANDLE) + { + vkDestroySemaphore(device, semaphore, nullptr); + } + } + for (auto const semaphore : m_retiredsemaphores) + { + vkDestroySemaphore(device, semaphore, nullptr); + } if (m_swapchain != VK_NULL_HANDLE) { vkDestroySwapchainKHR(device, m_swapchain, nullptr); @@ -652,6 +670,12 @@ void swapchain::destroy() } } } + m_acquired = 0; + m_views.clear(); + m_presentsemaphores.clear(); + m_retiredsemaphores.clear(); + m_images.clear(); + m_states.clear(); m_swapchain = VK_NULL_HANDLE; m_acquiresemaphores.clear(); m_generated.clear(); diff --git a/rendering/vulkan14/vulkan14swapchain.h b/rendering/vulkan14/vulkan14swapchain.h index 2079ec0c8..40bd28469 100644 --- a/rendering/vulkan14/vulkan14swapchain.h +++ b/rendering/vulkan14/vulkan14swapchain.h @@ -61,7 +61,7 @@ class swapchain bool latency_sleep(VkSemaphore Semaphore, std::uint64_t Value) const; // reflex: the point Marker of the frame with the id PresentId reached void latency_marker(std::uint64_t PresentId, VkLatencyMarkerNV Marker) const; - void destroy(); + void destroy() noexcept; // the image of the frame Frame (index of the frame in flight), and Generated more for the frames generated from it, which are // shown before it (as many of them as there is room for, generated_count()) diff --git a/rendering/vulkan14/vulkan14terrain.cpp b/rendering/vulkan14/vulkan14terrain.cpp index feb7b777e..d8512d253 100644 --- a/rendering/vulkan14/vulkan14terrain.cpp +++ b/rendering/vulkan14/vulkan14terrain.cpp @@ -13,12 +13,17 @@ http://mozilla.org/MPL/2.0/. #include "rendering/vulkan14/vulkan14device.h" #include "utilities/Logs.h" +#include + namespace vk14 { namespace { +// the use the memory of the maps of the terrain counts to: they are named after the textures they're made for +constexpr std::string_view terrainMemoryUse{"terrain maps"}; + std::uint32_t mip_count(std::uint32_t const Size) { return static_cast(std::floor(std::log2(std::max(Size, 1u)))) + 1; @@ -73,7 +78,7 @@ std::shared_ptr terrain_materials::make_image(VkFormat const Format, std: desc.mips = Mips; desc.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT; auto result{std::make_shared()}; - if (false == result->create(*m_resources->memory, desc, Name)) + if (false == result->create(*m_resources->memory, desc, Name, terrainMemoryUse)) { ErrorLog(std::string("heightmap terrain: no gpu image for ") + Name); return nullptr; @@ -127,7 +132,7 @@ void terrain_materials::gpu_storage(texture_array const &Array, int const Layers desc.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; auto &target{texture(Array.handle)}; auto map{std::make_shared()}; - if (false == map->create(*m_resources->memory, desc, target.name)) + if (false == map->create(*m_resources->memory, desc, target.name, terrainMemoryUse)) { ErrorLog("heightmap terrain: no gpu image for the layers of \"" + target.name + "\""); return; diff --git a/rendering/vulkan14/vulkan14texture.cpp b/rendering/vulkan14/vulkan14texture.cpp index ff6951298..2f7d77dc9 100644 --- a/rendering/vulkan14/vulkan14texture.cpp +++ b/rendering/vulkan14/vulkan14texture.cpp @@ -16,11 +16,14 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Globals.h" #include "utilities/Logs.h" +#include #include #include +#include #include #include #include +#include namespace vk14 { @@ -28,6 +31,9 @@ namespace vk14 namespace { +// the use the memory of the images of the textures counts to: they are named after their files +constexpr std::string_view textureMemoryUse{"textures"}; + // the data a texture is made of, for the alpha test of the shadow maps struct alpha_source { @@ -104,6 +110,30 @@ struct job_ticket std::atomic taken{false}; }; +// the image of a texture. one to be filled by the host (HostCopy) which can't be made is tried again to be filled through a staging +// buffer, HostCopy cleared. only when that one can be made is it the host transfer the driver can't do, and the next images of the +// format are filled through staging buffers too; when it can't either, it's something else (the memory ran out) and the format keeps +// the host copy +bool createTextureImage(image &Target, allocator const &Memory, uploader &Uploads, image_desc &Desc, std::string const &Name, bool &HostCopy) +{ + if (Target.create(Memory, Desc, Name, textureMemoryUse)) + { + return true; + } + if (false == HostCopy) + { + return false; + } + Desc.usage &= ~VkImageUsageFlags{VK_IMAGE_USAGE_HOST_TRANSFER_BIT}; + if (false == Target.create(Memory, Desc, Name, textureMemoryUse)) + { + return false; + } + HostCopy = false; + Uploads.RefuseHostCopy(Desc.format); + return true; +} + } // namespace // uploader @@ -148,17 +178,53 @@ bool uploader::can_blit(VkFormat Format) const return result; } -bool uploader::can_host_copy(VkFormat Format) const +bool uploader::can_host_copy(VkFormat Format, VkExtent3D const &Extent, std::uint32_t const Mips) const { if (false == m_hostcopy) { return false; } - std::lock_guard lock(m_mutex); - auto const lookup{m_hostcopyable.find(Format)}; - if (lookup != m_hostcopyable.end()) + auto const limits{hostCopyLimits(Format)}; + return limits.usable && (Extent.width <= limits.maxExtent.width) && (Extent.height <= limits.maxExtent.height) && (Extent.depth <= limits.maxExtent.depth) && + (Mips <= limits.maxMips); +} + +void uploader::RefuseHostCopy(VkFormat Format) +{ + auto refused{false}; { - return lookup->second; + std::scoped_lock lock(m_mutex); + auto &limits{m_hostcopyable[Format]}; + refused = limits.usable; + limits.usable = false; + } + if (refused) + { + log_warning(std::format("the textures of format {} are filled through staging buffers: the driver can't make their images to be filled by the host, although it says it can (the error above, recovered from)", static_cast(Format))); + } +} + +uploader::HostCopyLimits uploader::hostCopyLimits(VkFormat Format) const +{ + { + std::scoped_lock lock(m_mutex); + if (auto const lookup{m_hostcopyable.find(Format)}; lookup != m_hostcopyable.end()) + { + return lookup->second; + } + } + // asked outside of the lock (the allocator makes a trial image); two threads asking at once find the same, the first one kept + auto const limits{probeHostCopy(Format)}; + std::scoped_lock lock(m_mutex); + return m_hostcopyable.try_emplace(Format, limits).first->second; +} + +uploader::HostCopyLimits uploader::probeHostCopy(VkFormat Format) const +{ + HostCopyLimits limits; + if (m_allocator == nullptr) + { + return limits; } // the format filled by the host, and an image which can be is as fast for the gpu as one which can't VkFormatProperties3 properties3{}; @@ -167,24 +233,67 @@ bool uploader::can_host_copy(VkFormat Format) const properties.sType = VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2; properties.pNext = &properties3; vkGetPhysicalDeviceFormatProperties2(m_physical, Format, &properties); - auto result{(properties3.optimalTilingFeatures & VK_FORMAT_FEATURE_2_HOST_IMAGE_TRANSFER_BIT) != 0}; - if (result) + if ((properties3.optimalTilingFeatures & VK_FORMAT_FEATURE_2_HOST_IMAGE_TRANSFER_BIT) == 0) { - VkHostImageCopyDevicePerformanceQuery performance{}; - performance.sType = VK_STRUCTURE_TYPE_HOST_IMAGE_COPY_DEVICE_PERFORMANCE_QUERY; - VkImageFormatProperties2 imageproperties{}; - imageproperties.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2; - imageproperties.pNext = &performance; - VkPhysicalDeviceImageFormatInfo2 info{}; - info.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2; - info.format = Format; - info.type = VK_IMAGE_TYPE_2D; - info.tiling = VK_IMAGE_TILING_OPTIMAL; - info.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_HOST_TRANSFER_BIT; - result = (vkGetPhysicalDeviceImageFormatProperties2(m_physical, &info, &imageproperties) == VK_SUCCESS) && (performance.optimalDeviceAccess == VK_TRUE); + return limits; } - m_hostcopyable.emplace(Format, result); - return result; + auto const usage{VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_HOST_TRANSFER_BIT}; + VkHostImageCopyDevicePerformanceQuery performance{}; + performance.sType = VK_STRUCTURE_TYPE_HOST_IMAGE_COPY_DEVICE_PERFORMANCE_QUERY; + VkImageFormatProperties2 imageproperties{}; + imageproperties.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2; + imageproperties.pNext = &performance; + VkPhysicalDeviceImageFormatInfo2 formatinfo{}; + formatinfo.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2; + formatinfo.format = Format; + formatinfo.type = VK_IMAGE_TYPE_2D; + formatinfo.tiling = VK_IMAGE_TILING_OPTIMAL; + formatinfo.usage = usage; + if ((vkGetPhysicalDeviceImageFormatProperties2(m_physical, &formatinfo, &imageproperties) != VK_SUCCESS) || (performance.optimalDeviceAccess != VK_TRUE)) + { + return limits; + } + auto const &formatlimits{imageproperties.imageFormatProperties}; + if ((formatlimits.maxExtent.width == 0) || (formatlimits.maxExtent.height == 0) || (formatlimits.maxMipLevels == 0)) + { + return limits; + } + // the memory: the host transfer usage is among what decides the memory types an image can be in (its size and levels aren't), and + // a driver can have none for it although the format allows the usage (a geforce gtx 1050 with the driver 582.28 did). the allocator + // makes a trial image of the textures' kind and finds the memory it would go to + VkImageCreateInfo imageinfo{}; + imageinfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; + imageinfo.imageType = VK_IMAGE_TYPE_2D; + imageinfo.format = Format; + imageinfo.extent = {std::min(64u, formatlimits.maxExtent.width), std::min(64u, formatlimits.maxExtent.height), 1}; + imageinfo.mipLevels = 1; + imageinfo.arrayLayers = 1; + imageinfo.samples = VK_SAMPLE_COUNT_1_BIT; + imageinfo.tiling = VK_IMAGE_TILING_OPTIMAL; + imageinfo.usage = usage; + imageinfo.sharingMode = m_allocator->sharing(false, imageinfo.queueFamilyIndexCount, imageinfo.pQueueFamilyIndices); + imageinfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + VmaAllocationCreateInfo allocation{}; + allocation.usage = VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE; + std::uint32_t memorytype{0}; + if (auto const result{vmaFindMemoryTypeIndexForImageInfo(m_allocator->handle(), &imageinfo, &allocation, &memorytype)}; result != VK_SUCCESS) + { + log_info(std::format("the textures of format {} are filled through staging buffers: no memory for images filled by the host (vkresult {})", static_cast(Format), static_cast(result))); + return limits; + } + VkMemoryPropertyFlags memoryflags{0}; + vmaGetMemoryTypeProperties(m_allocator->handle(), memorytype, &memoryflags); + if ((memoryflags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) == 0) + { + // in the memory of the host the gpu would read them slower than the copies of staging buffers + log_info(std::format("the textures of format {} are filled through staging buffers: images filled by the host go to the memory of the host", static_cast(Format))); + return limits; + } + log_info(std::format("the textures of format {} are filled by the host (memory type {})", static_cast(Format), memorytype)); + limits.usable = true; + limits.maxExtent = formatlimits.maxExtent; + limits.maxMips = formatlimits.maxMipLevels; + return limits; } void uploader::begin_frame(command_stream *Commands, std::uint64_t Value) @@ -238,7 +347,7 @@ bool uploader::upload_buffer(std::shared_ptr const &Target, void const * upload.parts.emplace_back(0, Size); } upload.staging = std::make_shared(); - if ((false == upload.staging->create(*m_allocator, Size, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, memory_kind::upload)) || (upload.staging->mapped() == nullptr)) + if ((false == upload.staging->create(*m_allocator, Size, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, memory_kind::upload, "upload staging")) || (upload.staging->mapped() == nullptr)) { log_error("no staging buffer of " + memory_size_string(Size) + " for an upload"); return false; @@ -275,7 +384,7 @@ bool uploader::prepare(std::shared_ptr const &Image, void const *Data, Vk Upload.levels = Levels; Upload.mipmaps = Mipmaps; Upload.staging = std::make_shared(); - if ((false == Upload.staging->create(*m_allocator, Size, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, memory_kind::upload)) || (Upload.staging->mapped() == nullptr)) + if ((false == Upload.staging->create(*m_allocator, Size, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, memory_kind::upload, "upload staging")) || (Upload.staging->mapped() == nullptr)) { log_error("no staging buffer of " + memory_size_string(Size) + " for an upload"); Upload = prepared{}; @@ -932,15 +1041,15 @@ vulkan14_texture::make_result vulkan14_texture::make(bool const Background) auto const generate{(levels.size() == 1) && (false == format.compressed) && m_resources.uploads->can_blit(format.format)}; // the levels the file gives are filled by the host where it can, by a background thread (what the gpu makes goes through the // commands of a frame) - auto const hostcopy{Background && (false == generate) && m_resources.uploads->can_host_copy(format.format)}; image_desc desc; desc.format = format.format; desc.extent = {data_width, data_height, 1}; desc.mips = (generate ? static_cast(std::floor(std::log2(std::max(data_width, data_height)))) + 1 : static_cast(levels.size())); + auto hostcopy{Background && (false == generate) && m_resources.uploads->can_host_copy(format.format, desc.extent, desc.mips)}; desc.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | (generate ? VK_IMAGE_USAGE_TRANSFER_SRC_BIT : 0) | (hostcopy ? VK_IMAGE_USAGE_HOST_TRANSFER_BIT : 0); desc.components = format.components; auto image{std::make_shared()}; - if (false == image->create(*m_resources.memory, desc, name)) + if (false == createTextureImage(*image, *m_resources.memory, *m_resources.uploads, desc, name, hostcopy)) { ErrorLog("Bad texture: no gpu image for \"" + name + "\"", logtype::texture); return failed(); @@ -1180,7 +1289,7 @@ void vulkan14_texture::upload_rgba(std::uint8_t const *Data, std::size_t Width, desc.mips = (generate ? static_cast(std::floor(std::log2(std::max(width, height)))) + 1 : 1); desc.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | (generate ? VK_IMAGE_USAGE_TRANSFER_SRC_BIT : 0); target = std::make_shared(); - if (false == target->create(*m_resources.memory, desc, name)) + if (false == target->create(*m_resources.memory, desc, name, textureMemoryUse)) { return; } diff --git a/rendering/vulkan14/vulkan14texture.h b/rendering/vulkan14/vulkan14texture.h index b15846b33..ec1144ce1 100644 --- a/rendering/vulkan14/vulkan14texture.h +++ b/rendering/vulkan14/vulkan14texture.h @@ -87,13 +87,18 @@ class uploader } // whether the format can be filtered by blits (the mipmaps made on the gpu) bool can_blit(VkFormat Format) const; - // whether images of the format are filled by the host (hostImageCopy) straight to the layout they're sampled in, without a loss of - // speed for the gpu. Copyable: the device does that for the layout (decided when the device is made) + // whether images are filled by the host (hostImageCopy) straight to the layout they're sampled in, without a loss of speed for the + // gpu. Copyable: the device does that for the layout (decided when the device is made) void enable_host_copy(bool Copyable) { m_hostcopy = Copyable; } - bool can_host_copy(VkFormat Format) const; + // whether an image of the format, of Extent and Mips levels is: the format allows it, the device has memory of its own for such + // images (asked once a format) and the image is within the limits of the format for that use + bool can_host_copy(VkFormat Format, VkExtent3D const &Extent, std::uint32_t Mips) const; + // an image of the format which can_host_copy() allowed couldn't be made, and the same one without the host transfer could: the + // images of the format are filled through staging buffers from now on + void RefuseHostCopy(VkFormat Format); private: struct job @@ -106,7 +111,16 @@ class uploader std::shared_ptr buffertarget; std::vector> parts; }; + // what hostImageCopy can do with the images of a format + struct HostCopyLimits + { + bool usable{false}; + VkExtent3D maxExtent{0, 0, 0}; + std::uint32_t maxMips{0}; + }; void record(job &Job); + HostCopyLimits hostCopyLimits(VkFormat Format) const; + HostCopyLimits probeHostCopy(VkFormat Format) const; mutable std::mutex m_mutex; allocator const *m_allocator{nullptr}; @@ -121,7 +135,7 @@ class uploader std::atomic m_uploaded{0}; mutable std::unordered_map m_blittable; bool m_hostcopy{false}; - mutable std::unordered_map m_hostcopyable; + mutable std::unordered_map m_hostcopyable; }; // the images the shaders can be given by an id. added to by any thread drawing (a texture made when a draw needs it), removed from diff --git a/scene/scene.cpp b/scene/scene.cpp index 03b10d8f1..f997e9762 100644 --- a/scene/scene.cpp +++ b/scene/scene.cpp @@ -18,6 +18,7 @@ http://mozilla.org/MPL/2.0/. #include "world/EvLaunch.h" #include "utilities/Timer.h" #include "utilities/Logs.h" +#include "utilities/utilities.h" #include "scene/sn_utils.h" #include "scene/regionfile.h" #include "scene/sceneterrain.h" @@ -1302,7 +1303,8 @@ basic_region::wire_over( glm::dvec3 const &Point, glm::dvec3 const &Front, doubl bool basic_region::is_scene( std::string const &Scenariofile ) const { - auto const filename { region_file_name( Scenariofile ) }; + // the file as it's named on the disk, the names the scenery includes come in lowercase + auto const filename { FileOnDisk( region_file_name( Scenariofile ) ) }; if( false == FileExists( filename ) ) { return false; @@ -1323,7 +1325,8 @@ basic_region::is_scene( std::string const &Scenariofile ) const { void basic_region::serialize( std::string const &Scenariofile ) const { - auto const filename { region_file_name( Scenariofile ) }; + // a file there in another case is written over, not joined by a second one next to it + auto const filename { FileOnDiskToWrite( region_file_name( Scenariofile ) ) }; // the file is written under a temporary name and takes the final one only when complete, so a write cut short // (a crash, the process killed) leaves no partial file to be read on the next start @@ -1359,7 +1362,8 @@ basic_region::serialize( std::string const &Scenariofile ) const { bool basic_region::deserialize( std::string const &Scenariofile ) { - auto const filename { region_file_name( Scenariofile ) }; + // the file as it's named on the disk, the names the scenery includes come in lowercase + auto const filename { FileOnDisk( region_file_name( Scenariofile ) ) }; if( false == FileExists( filename ) ) { Global.file_binary_terrain_state = false; diff --git a/scene/scenelayers.cpp b/scene/scenelayers.cpp index e729fac7b..e7a72f3a9 100644 --- a/scene/scenelayers.cpp +++ b/scene/scenelayers.cpp @@ -559,9 +559,8 @@ bool node_layers::is_descendant(layer_handle Layer, layer_handle const Ancestor) std::string node_layers::path(layer_handle const Layer) const { - auto const named{Global.asCurrentSceneryPath + layer(Layer).name}; - auto const cased{FileCased(named)}; - return cased.empty() ? named : cased; + // read and written as it's named on the disk; a new file is made in the folders as they're named there + return FileOnDiskToWrite(Global.asCurrentSceneryPath + layer(Layer).name); } // stores current state of the layer file, to detect later whether it was changed behind our back @@ -619,7 +618,8 @@ layer_handle node_layers::create(std::string Name, layer_handle Parent, std::str return null_handle; } auto const taken{std::any_of(std::begin(m_layers), std::end(m_layers), [&](basic_layer const &Layer) { return Layer.name == Name && false == Layer.dead; })}; - if (taken || FileExists(Global.asCurrentSceneryPath + Name)) + // a file there in another case counts as well, path() would write over it + if (taken || false == FileCased(Global.asCurrentSceneryPath + Name).empty()) { Reason = format(STR_C("the file \"%s\" already exists"), Name.c_str()); return null_handle; diff --git a/scene/scenelayerssave.cpp b/scene/scenelayerssave.cpp index 5d52689e9..06fb75423 100644 --- a/scene/scenelayerssave.cpp +++ b/scene/scenelayerssave.cpp @@ -1986,7 +1986,7 @@ save_result node_layers::save(std::vector const &Rootstatements, st terrainfile.erase(0, 1); } erase_extension(terrainfile); - if (std::filesystem::remove(Global.asCurrentSceneryPath + terrainfile + ".sbt", error)) + if (std::filesystem::remove(FileOnDisk(Global.asCurrentSceneryPath + terrainfile + ".sbt"), error)) { WriteLog("Scenery save: binary terrain file removed, it'll be generated again on the next load"); } diff --git a/script_screens_doc.md b/script_screens_doc.md index 3e9248d11..793cc1233 100644 --- a/script_screens_doc.md +++ b/script_screens_doc.md @@ -308,6 +308,6 @@ again: Only `eu07.ini` turns it on: a `config` block of a scenery doesn't (the log says the key was ignored). Nor does it set the other keys that would take a scenery out of its sandbox or reach the computer: `execonexit`, `extcam.cmd`, -`extcam.rec`, `screenshotsdir`, `network.server`, `network.client`, `zmq.address`, `motiontelemetry`, `uart`, +`extcam.rec`, `screenshotsdir`, `snapshotsdir`, `network.server`, `network.client`, `zmq.address`, `motiontelemetry`, `uart`, `feedbackmode`, `feedbackport`, nor does it switch on `python.enabled`, `luascreens.enabled` or `wasm.enabled` when `eu07.ini` has them off. A scenery may still switch those three off, or `lua.fulllibraries` off, as it always could. diff --git a/scripting/luasandbox.cpp b/scripting/luasandbox.cpp index 16e7f70ba..13b1c1bc5 100644 --- a/scripting/luasandbox.cpp +++ b/scripting/luasandbox.cpp @@ -11,6 +11,7 @@ http://mozilla.org/MPL/2.0/. #include "scripting/luasandbox.h" #include "scripting/scriptscreenrules.h" +#include "utilities/utilities.h" #include #include @@ -134,7 +135,12 @@ std::optional read_file(std::filesystem::path const &Folder, std::s } // a folder or a device (CON, NUL, COM1...) isn't a regular file. in the code page of the system, as the game opens // its files - auto const path{Folder / with_forward_slashes(Path)}; + auto path{Folder / with_forward_slashes(Path)}; +#ifndef _WIN32 + // named in another case on the disk, as the game finds its other files (on Windows the name is found as it is, and + // the folder of the player's files may be named outside of the code page) + path = FileOnDisk(path.string()); +#endif std::error_code error; if (false == std::filesystem::is_regular_file(path, error)) { diff --git a/scripting/scriptscreens.cpp b/scripting/scriptscreens.cpp index 224a2f27e..47c35bc4b 100644 --- a/scripting/scriptscreens.cpp +++ b/scripting/scriptscreens.cpp @@ -108,8 +108,8 @@ std::optional read_regular_file(std::string const &Path) { // a folder or a device (CON, NUL, COM1...) isn't a regular file std::error_code error; - // in the code page of the system, as the game opens its files - std::filesystem::path const path{Path}; + // in the code page of the system, as the game opens its files; named in another case on the disk on Linux + std::filesystem::path const path{FileOnDisk(Path)}; if (false == std::filesystem::is_regular_file(path, error)) { return std::nullopt; diff --git a/shaders/README.md b/shaders/README.md index 34c7122f9..6cb8963f1 100644 --- a/shaders/README.md +++ b/shaders/README.md @@ -18,7 +18,7 @@ even with the binaries: the directives of the materials (`#pragma texture`, `#pr python shaders/compile_spirv.py compiles every shader of `ogl46/` (with the variant `MODEL_DRAWS` of the vertex and fragment shaders) and of `vk14/` with -`glslc` (Vulkan SDK, `VULKAN_SDK`, or `--glslc `). A single file compiles the same way by hand: +`glslc` (Vulkan SDK, `VULKAN_SDK`, or on `PATH`). A single file compiles the same way by hand: glslc --target-env=opengl4.5 ogl46/mat_default.frag -o ogl46bin/mat_default.frag.spv glslc --target-env=opengl4.5 -DMODEL_DRAWS=1 ogl46/vertex.vert -o ogl46bin/vertex.vert.MODEL_DRAWS.spv diff --git a/shaders/compile_spirv.py b/shaders/compile_spirv.py index da0aa3053..02745e2d3 100644 --- a/shaders/compile_spirv.py +++ b/shaders/compile_spirv.py @@ -4,9 +4,11 @@ # manifest.txt: the source files each binary was compiled from, with their hashes, so the game doesn't take a binary older # than its sources. # -# python shaders/compile_spirv.py [--glslc ] [--only ogl46|vk14] [] +# python shaders/compile_spirv.py [--only ogl46|vk14] # -# glslc comes with the Vulkan SDK (VULKAN_SDK is looked at) or with the shaderc package. the shaders of opengl are compiled +# the shaders are those of the directory of this script, and glslc is the one of the Vulkan SDK (VULKAN_SDK is looked at) or +# the one on PATH (the shaderc package); nothing on the command line names a file. the includes read stay inside the directory +# of the sources. the shaders of opengl are compiled # for --target-env=opengl4.5 (SPIR-V 1.0, which opengl 4.6 takes), with the variant of the multi draws (MODEL_DRAWS) of the # vertex and fragment shaders; those of vulkan for --target-env=vulkan1.4. a single file can be compiled by hand the same way: # glslc --target-env=opengl4.5 shaders/ogl46/mat_default.frag -o shaders/ogl46bin/mat_default.frag.spv @@ -29,11 +31,23 @@ TREES = { 'vk14': ('vk14', 'vk14bin', 'vulkan1.4', ['NO_MOTION_OUTPUT'], True), } INCLUDE = re.compile(r'^[ \t]*#include[ \t]*[<"]([^>"]+)[>"]', re.M) +GLSLC_NAMES = ('glslc.exe', 'glslc') + + +def inside(base, path): + # the path without links and .., when it is the directory base or a path under it; None when it leaves base + base = os.path.realpath(base) + path = os.path.realpath(path) + try: + common = os.path.commonpath([base, path]) + except ValueError: # another drive + return None + return path if os.path.normcase(common) == os.path.normcase(base) else None def file_hash(path): # fnv-1a 64 of the text with the line ends made \n, the same as gfx::shader_file_hash() - with open(path, 'rb') as f: # NOSONAR: a developer tool reading the shader files of the directory it is given + with open(path, 'rb') as f: data = f.read().replace(b'\r\n', b'\n') h = 14695981039346656037 for b in data: @@ -48,8 +62,11 @@ def dependencies(directory, name, found=None): found = [] if name in found: return found + path = inside(directory, os.path.join(directory, name)) + if path is None: + raise OSError('%s is outside %s' % (name, directory)) found.append(name) - with open(os.path.join(directory, name), 'r', encoding='utf-8', errors='replace') as f: # NOSONAR: a developer tool reading the shader files of the directory it is given + with open(path, 'r', encoding='utf-8', errors='replace') as f: text = f.read() for include in INCLUDE.findall(text): if include == 'common': @@ -58,76 +75,81 @@ def dependencies(directory, name, found=None): return found -def find_glslc(explicit): - if explicit: - return explicit +def find_glslc(): + # glslc of the Vulkan SDK (VULKAN_SDK), else the one on PATH; never a path given on the command line sdk = os.environ.get('VULKAN_SDK') if sdk: for sub in ('Bin', 'bin'): - for exe in ('glslc.exe', 'glslc'): + for exe in GLSLC_NAMES: path = os.path.join(sdk, sub, exe) if os.path.isfile(path): return path return shutil.which('glslc') +def variant_jobs(sources, name, deps, variants, onlyused): + # the plain binary, and for the vertex and fragment shaders one per variant (only the variants the file uses, if onlyused) + jobs = [('', [])] + if os.path.splitext(name)[1] not in ('.vert', '.frag'): + return jobs + text = '' + for dep in deps: + with open(os.path.join(sources, dep), 'r', encoding='utf-8', errors='replace') as f: + text += f.read() + return jobs + [(v, ['-D%s=1' % v]) for v in variants if (not onlyused) or (v in text)] + + +def compile_tree(glslc, shaders, tree, failed): + # compiles one tree of TREES into its directory of binaries with its manifest.txt; returns how many binaries were made + sourcedir, binarydir, env, variants, onlyused = tree + sources = os.path.join(shaders, sourcedir) + binaries = os.path.join(shaders, binarydir) + if not os.path.isdir(sources): + return 0 + os.makedirs(binaries, exist_ok=True) + manifest = ['# made by compile_spirv.py: binary, source file it was compiled from, fnv-1a 64 of the source (line ends as \\n)'] + count = 0 + for name in sorted(n for n in os.listdir(sources) if os.path.splitext(n)[1] in STAGES): + try: + deps = dependencies(sources, name) + except OSError as e: + failed.append('%s/%s (%s)' % (sourcedir, name, e)) + continue + for variant, defines in variant_jobs(sources, name, deps, variants, onlyused): + binary = name + ('.' + variant if variant else '') + '.spv' + command = [glslc, '--target-env=' + env] + defines + [os.path.join(sources, name), '-o', os.path.join(binaries, binary)] + result = subprocess.run(command, capture_output=True, text=True) + if result.stderr.strip(): + sys.stderr.write(result.stderr) + if result.returncode != 0: + failed.append('%s/%s' % (binarydir, binary)) + # the binary of an earlier run would stay beside a source it no longer matches + stale = os.path.join(binaries, binary) + if os.path.isfile(stale): + os.remove(stale) + print('removed the stale %s/%s' % (binarydir, binary), file=sys.stderr) + continue + count += 1 + manifest += ['%s %s %s' % (binary, dep, file_hash(os.path.join(sources, dep))) for dep in deps] + with open(os.path.join(binaries, 'manifest.txt'), 'w', newline='\n') as f: + f.write('\n'.join(manifest) + '\n') + return count + + def main(): - parser = argparse.ArgumentParser(description='compiles the shaders of MaSzyna to SPIR-V with glslc') - parser.add_argument('shaders', nargs='?', default=os.path.dirname(os.path.abspath(__file__)), help='the shaders directory (the one of this script by default)') - parser.add_argument('--glslc', help='path of glslc') + parser = argparse.ArgumentParser(description='compiles the shaders of MaSzyna (the directory of this script) to SPIR-V with glslc') parser.add_argument('--only', choices=sorted(TREES), help='only the shaders of one renderer') args = parser.parse_args() - glslc = find_glslc(args.glslc) + glslc = find_glslc() if not glslc or not os.path.isfile(glslc): - print('glslc not found: install the Vulkan SDK (VULKAN_SDK) or shaderc, or give --glslc', file=sys.stderr) + print('glslc not found: install the Vulkan SDK (VULKAN_SDK) or shaderc, or put glslc on PATH', file=sys.stderr) return 1 + # the shaders directory is the one of this script: nothing on the command line names a file or a directory + shaders = os.path.dirname(os.path.realpath(__file__)) failed = [] - count = 0 - for key, (sourcedir, binarydir, env, variants, onlyused) in TREES.items(): - if args.only and args.only != key: - continue - sources = os.path.join(args.shaders, sourcedir) - binaries = os.path.join(args.shaders, binarydir) - if not os.path.isdir(sources): - continue - os.makedirs(binaries, exist_ok=True) # NOSONAR: a developer tool writing the binaries beside the shaders it is given - manifest = ['# made by compile_spirv.py: binary, source file it was compiled from, fnv-1a 64 of the source (line ends as \\n)'] - names = sorted(n for n in os.listdir(sources) if os.path.splitext(n)[1] in STAGES) - for name in names: - jobs = [('', [])] - try: - deps = dependencies(sources, name) - except OSError as e: - failed.append('%s/%s (%s)' % (sourcedir, name, e)) - continue - if os.path.splitext(name)[1] in ('.vert', '.frag'): - text = '' - for dep in deps: - with open(os.path.join(sources, dep), 'r', encoding='utf-8', errors='replace') as f: # NOSONAR: a developer tool reading the shader files of the directory it is given - text += f.read() - jobs += [(v, ['-D%s=1' % v]) for v in variants if (not onlyused) or (v in text)] - for variant, defines in jobs: - binary = name + ('.' + variant if variant else '') + '.spv' - command = [glslc, '--target-env=' + env] + defines + [os.path.join(sources, name), '-o', os.path.join(binaries, binary)] - result = subprocess.run(command, capture_output=True, text=True) # NOSONAR: runs the glslc named by --glslc or found in the Vulkan SDK, without a shell - if result.returncode != 0: - failed.append('%s/%s' % (binarydir, binary)) - sys.stderr.write(result.stderr) - # the binary of an earlier run would stay beside a source it no longer matches - stale = os.path.join(binaries, binary) - if os.path.isfile(stale): - os.remove(stale) # NOSONAR: a developer tool removing its own output beside the shaders it is given - print('removed the stale %s/%s' % (binarydir, binary), file=sys.stderr) - continue - if result.stderr.strip(): - sys.stderr.write(result.stderr) - count += 1 - for dep in deps: - manifest.append('%s %s %s' % (binary, dep, file_hash(os.path.join(sources, dep)))) - with open(os.path.join(binaries, 'manifest.txt'), 'w', newline='\n') as f: # NOSONAR: a developer tool writing the binaries beside the shaders it is given - f.write('\n'.join(manifest) + '\n') + count = sum(compile_tree(glslc, shaders, tree, failed) for key, tree in TREES.items() if args.only in (None, key)) print('%d binaries compiled' % count) if failed: diff --git a/simulation/simulation.cpp b/simulation/simulation.cpp index 25aa8d9b5..5fba90743 100644 --- a/simulation/simulation.cpp +++ b/simulation/simulation.cpp @@ -12,6 +12,7 @@ http://mozilla.org/MPL/2.0/. #include "simulation/simulationtime.h" #include "simulation/simulationenvironment.h" #include "simulation/simulationtest.h" +#include "simulation/simulationsnapshotworld.h" #include "simulation/blackboxrecorder.h" #include "utilities/Globals.h" @@ -552,6 +553,10 @@ void state_manager::process_commands() { vehicle->Mechanik->PutCommand(command, commanddata.param1, commanddata.param2, &location); } + if (commanddata.command == user_command::snapshotsave && commanddata.action == GLFW_PRESS) { + snapshot::save_now(); + } + if (commanddata.command == user_command::quitsimulation) { // TBD: allow clients to go into offline mode? Application.queue_quit(true); diff --git a/simulation/simulationenvironment.cpp b/simulation/simulationenvironment.cpp index ba12ee4f7..2b3a9f399 100644 --- a/simulation/simulationenvironment.cpp +++ b/simulation/simulationenvironment.cpp @@ -255,6 +255,23 @@ world_environment::update_moon() { m_moon.update( true ); } +std::array +world_environment::wind_state() const { + + return { m_wind.azimuth, m_wind.azimuth_change, m_wind.velocity, m_wind.velocity_change, m_wind.change_time, m_wind.vector.x, m_wind.vector.y, m_wind.vector.z }; +} + +void +world_environment::wind_state( std::array const &State ) { + + m_wind.azimuth = State[ 0 ]; + m_wind.azimuth_change = State[ 1 ]; + m_wind.velocity = State[ 2 ]; + m_wind.velocity_change = State[ 3 ]; + m_wind.change_time = State[ 4 ]; + m_wind.vector = { State[ 5 ], State[ 6 ], State[ 7 ] }; +} + void world_environment::update_wind() { diff --git a/simulation/simulationenvironment.h b/simulation/simulationenvironment.h index 249d706e7..8d67e94ca 100644 --- a/simulation/simulationenvironment.h +++ b/simulation/simulationenvironment.h @@ -18,6 +18,8 @@ http://mozilla.org/MPL/2.0/. #include "rendering/precipitation.h" #include "audio/sound.h" +#include + class opengl46_renderer; // wrapper for environment elements -- sky, sun, stars, clouds etc @@ -63,6 +65,12 @@ public: inline auto const & wind_azimuth() const { return m_wind.azimuth; } + // the wind as it blows and as it is about to change, for a snapshot of the simulation, which puts it back: + // azimuth and its change, velocity and its change, the time to the next change, the vector + std::array + wind_state() const; + void + wind_state( std::array const &State ); // clouds, fog and precipitation of the scenery, see environment/weather.h inline auto const & weather() const { diff --git a/simulation/simulationsnapshot.cpp b/simulation/simulationsnapshot.cpp new file mode 100644 index 000000000..e5ac33f60 --- /dev/null +++ b/simulation/simulationsnapshot.cpp @@ -0,0 +1,758 @@ +/* +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 "simulation/simulationsnapshot.h" + +#include "utilities/parser.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace simulation::snapshot { + +namespace { + +// a value which is no text at all is written as this, there's no way to write an empty token +constexpr std::string_view empty_mark{"<>"}; +// lines of the file are kept shorter than this, where the tokens allow +constexpr std::size_t line_width{110}; + +// characters a token can hold without quotes around it: nothing which ends a token, starts a comment or a quoted text +bool is_plain(std::string_view const Text) +{ + if (Text.find("//") != std::string_view::npos || Text.find("/*") != std::string_view::npos) + return false; + return std::ranges::none_of(Text, [](char const Character) { + auto const code{static_cast(Character)}; + return code <= ' ' || Character == ';' || Character == '"' || Character == '\\' || code == 127; + }); +} + +// the value as a token of the file; Terminator is the word which ends the entry the value is written in +std::string encode(std::string_view const Value, std::string_view const Terminator) +{ + if (Value.empty()) + return std::string(empty_mark); + std::string text; + if (Value.front() == '<' || Value == Terminator) + { + // one more '<' in front keeps the value apart from the mark of an empty one, and from the end of its entry + text += '<'; + } + text += Value; + if (is_plain(text)) + return text; + std::string quoted{"\""}; + for (auto const character : text) + { + if (character == '"' || character == '\\') + quoted += '\\'; + quoted += character; + } + quoted += '"'; + return quoted; +} + +// the value a token of the file stands for; the parser has taken the quotes off already +std::string decode(std::string const &Token) +{ + if (Token == empty_mark) + return {}; + if (Token.starts_with('<')) + return Token.substr(1); + return Token; +} + +std::string next_token(cParser &Input) +{ + return Input.getToken(false); +} + +// the headings put before the entries of a type, for a reader of the file +std::string_view heading(std::string_view const Type) +{ + using entry = std::pair; + static constexpr std::array headings{ + entry{"time", "date and time of the simulation"}, + entry{"weather", "weather"}, + entry{"random", "random number engine"}, + entry{"memcell", "memory cells: text, value 1, value 2"}, + entry{"switch", "switches: the path set"}, + entry{"track", "tracks changed by events: speed limit, damage"}, + entry{"crossing", "road crossings: the way through which was taken last"}, + entry{"madetrack", "tracks made on the run where a track of the scenery ends: turning loops, derailing tracks"}, + entry{"powersource", "traction power sources: voltage, current, admittance now and before, output, fuses, their timer and count"}, + entry{"isolated", "isolated sections: axles counted in"}, + entry{"event", "queued events: seconds left, the vehicle which set them off"}, + entry{"launcher", "event launchers: their timers"}, + entry{"model", "lights of the models which events switch: the signals"}, + entry{"vehicle", "vehicles: place, speed, couplings, load, machinery"}, + entry{"driver", "drivers: orders, timetable"}, + entry{"player", "the vehicle of the player"}, + }; + auto const lookup{std::ranges::find(headings, Type, &entry::first)}; + return lookup != headings.end() ? lookup->second : std::string_view{}; +} + +void write_record(std::ostream &Output, record const &Record) +{ + auto const terminator{"end" + Record.type}; + std::string line{Record.type + ' ' + encode(Record.name, terminator)}; + for (auto const &[key, value] : Record.fields) + { + auto const token{key + ' ' + encode(value, terminator)}; + if (line.size() + 1 + token.size() > line_width) + { + Output << line << '\n'; + line = " "; + } + line += ' '; + line += token; + } + if (line.size() + 1 + terminator.size() > line_width) + { + Output << line << '\n'; + line = " "; + } + Output << line << ' ' << terminator << '\n'; +} + +// reads the keys and values of an entry, up to its end. returns: what went wrong, if anything +std::string read_fields(cParser &Input, record &Record) +{ + auto const terminator{"end" + Record.type}; + while (true) + { + auto key{next_token(Input)}; + if (key == terminator) + return {}; + if (key.empty()) + return std::format("entry \"{} {}\" isn't closed with {}", Record.type, Record.name, terminator); + auto const value{next_token(Input)}; + if (value.empty() || value == terminator) + return std::format("entry \"{} {}\" has key {} without a value", Record.type, Record.name, key); + Record.fields.emplace_back(std::move(key), decode(value)); + } +} + +using coupler_key = std::pair; + +struct coupler_link { + std::string other; + int otherend{0}; + int flags{0}; +}; + +using coupler_map = std::map>; + +// the links by each of their ends; a link to nothing is the vehicle's end standing free +coupler_map by_coupler(std::vector const &Links) +{ + coupler_map map; + for (auto const &link : Links) + { + auto const linked{false == link.other.empty() && link.flags != 0}; + map[coupler_key{link.vehicle, link.end}] = linked ? coupler_link{link.other, link.otherend, link.flags} : coupler_link{}; + if (linked) + map[coupler_key{link.other, link.otherend}] = coupler_link{link.vehicle, link.end, link.flags}; + } + return map; +} + +bool same_partner(coupler_link const &Left, coupler_link const &Right) +{ + return Left.other == Right.other && Left.otherend == Right.otherend; +} + +// each link once: the end it's listed by first is the one which comes first in the list +std::vector unique_links(std::vector const &Links) +{ + std::vector unique; + std::set> seen; + for (auto const &link : Links) + { + if (link.other.empty() || link.flags == 0) + continue; + if (seen.contains(coupler_key{link.vehicle, link.end}) || seen.contains(coupler_key{link.other, link.otherend})) + continue; + seen.emplace(link.vehicle, link.end); + seen.emplace(link.other, link.otherend); + unique.emplace_back(link); + } + return unique; +} + +// what the snapshot wants of a coupler, if it says anything of it +coupler_link const *wanted_link(coupler_map const &Wanted, std::string const &Vehicle, int const End) +{ + auto const lookup{Wanted.find(coupler_key{Vehicle, End})}; + return lookup != Wanted.end() ? &lookup->second : nullptr; +} + +// the consists the links make, as sets of vehicles: two vehicles are of one consist if a chain of links joins them +class consists { + +public: + // joins the consists of the two vehicles. returns: false if they're of one consist already, which the link would + // make into a ring + bool join(std::string const &Left, std::string const &Right) + { + auto const left{root(Left)}; + auto const right{root(Right)}; + if (left == right) + return false; + m_parents[left] = right; + return true; + } + +private: + std::string root(std::string const &Vehicle) const + { + auto current{Vehicle}; + for (auto lookup{m_parents.find(current)}; lookup != m_parents.end(); lookup = m_parents.find(current)) + current = lookup->second; + return current; + } + + std::map> m_parents; +}; + +// what's refused is kept in the order it came, up to this many lines +constexpr std::size_t refusals_kept{100}; + +struct refusal_list { + std::vector lines; + std::size_t more{0}; +}; + +refusal_list &refusals() +{ + static refusal_list list; + return list; +} + +// a value of the file in what's told of it: a damaged file can have anything in a value, a whole other file too +std::string shortened(std::string_view const Text) +{ + constexpr std::size_t length{40}; + return Text.size() <= length ? std::string(Text) : std::string(Text.substr(0, length)) + "..."; +} + +} // namespace + +std::string number_text(double const Value) +{ + if (std::isnan(Value)) + return "nan"; + if (std::isinf(Value)) + return Value > 0.0 ? "inf" : "-inf"; + // the shortest text which reads back as the same value + return std::format("{}", Value); +} + +std::string number_text(float const Value) +{ + if (std::isnan(Value) || std::isinf(Value)) + return number_text(static_cast(Value)); + return std::format("{}", Value); +} + +std::optional text_number(std::string_view Text) +{ + if (Text.empty()) + return std::nullopt; + if (Text == "nan") + return std::nan(""); + if (Text == "inf") + return HUGE_VAL; + if (Text == "-inf") + return -HUGE_VAL; + if (Text.front() == '+') + Text.remove_prefix(1); + double value{0.0}; + auto const *const end{Text.data() + Text.size()}; + if (auto const [parsed, error]{std::from_chars(Text.data(), end, value)}; error == std::errc{} && parsed == end) + return value; + return std::nullopt; +} + +std::string numbers_text(std::span const Numbers) +{ + std::string text; + for (auto const number : Numbers) + { + if (false == text.empty()) + text += ','; + text += number_text(number); + } + return text; +} + +std::optional whole_number(double const Value, int const Min, int const Max) +{ + if (false == detail::fits_integer(Value) || Value < Min || Value > Max) + return std::nullopt; + return static_cast(Value); +} + +void refuse(std::string Text) +{ + auto &list{refusals()}; + if (list.lines.size() < refusals_kept) + list.lines.emplace_back(std::move(Text)); + else + ++list.more; +} + +std::vector take_refusals() +{ + auto list{std::move(refusals())}; + refusals() = {}; + if (list.more != 0) + list.lines.emplace_back(std::format("and {} more values refused", list.more)); + return std::move(list.lines); +} + +std::vector text_numbers(std::string_view Text) +{ + std::vector numbers; + while (false == Text.empty()) + { + auto const comma{Text.find(',')}; + if (auto const number{text_number(Text.substr(0, comma))}; number.has_value()) + numbers.emplace_back(*number); + Text.remove_prefix(comma == std::string_view::npos ? Text.size() : comma + 1); + } + return numbers; +} + +std::string const *record::find(std::string_view const Key) const +{ + auto const lookup{std::ranges::find(fields, Key, &std::pair::first)}; + return lookup != fields.end() ? &lookup->second : nullptr; +} + +std::string record::text(std::string_view const Key, std::string_view const Fallback) const +{ + auto const *value{find(Key)}; + return value != nullptr ? *value : std::string(Fallback); +} + +void record::refuse(std::string_view const Key, std::string_view const Why) const +{ + snapshot::refuse(std::format("{} {}: {} \"{}\" refused, {}", type, shortened(name), Key, shortened(text(Key)), Why)); +} + +void record::set_text(std::string_view const Key, std::string Value) +{ + if (auto const lookup{std::ranges::find(fields, Key, &std::pair::first)}; lookup != fields.end()) + { + lookup->second = std::move(Value); + return; + } + fields.emplace_back(std::string(Key), std::move(Value)); +} + +std::optional read_count(record const &Entry, std::string_view const Key) +{ + if (std::size_t count{0}; Entry.get(Key, count, std::size_t{0}, Entry.fields.size())) + return count; + return std::nullopt; +} + +std::optional read_index(record const &Entry, std::string_view const Key, std::size_t const Size) +{ + std::size_t index{0}; + if (false == Entry.get(Key, index)) + return std::nullopt; + if (index >= Size) + { + Entry.refuse(Key, std::format("it's past the end of a table of {}", Size)); + return std::nullopt; + } + return index; +} + +record &document::add(std::string_view const Type, std::string_view const Name) +{ + return records.emplace_back(Type, Name); +} + +std::vector document::of(std::string_view const Type) const +{ + std::vector found; + for (auto const &entry : records) + { + if (entry.type == Type) + found.emplace_back(&entry); + } + return found; +} + +record const *document::find(std::string_view const Type, std::string_view const Name) const +{ + auto const lookup{std::ranges::find_if(records, [&](record const &Entry) { return Entry.type == Type && Entry.name == Name; })}; + return lookup != records.end() ? std::to_address(lookup) : nullptr; +} + +record *document::find(std::string_view const Type, std::string_view const Name) +{ + auto const lookup{std::ranges::find_if(records, [&](record const &Entry) { return Entry.type == Type && Entry.name == Name; })}; + return lookup != records.end() ? std::to_address(lookup) : nullptr; +} + +record const *document::header() const +{ + return false == records.empty() && records.front().type == "snapshot" ? &records.front() : nullptr; +} + +int document::version() const +{ + auto const *first{header()}; + if (first == nullptr) + return 0; + // a version which isn't a whole number is no version this build knows + return whole_number(text_number(first->name).value_or(0.0), 0, std::numeric_limits::max()).value_or(0); +} + +void write(std::ostream &Output, document const &Document) +{ + Output << "// MaSzyna simulation snapshot: the state of a running scenery, loaded over it with --load-snapshot\n"; + std::string lasttype; + for (auto const &entry : Document.records) + { + if (entry.type != lasttype) + { + lasttype = entry.type; + if (auto const text{heading(entry.type)}; false == text.empty()) + Output << "\n// " << text << '\n'; + } + write_record(Output, entry); + } +} + +std::string to_text(document const &Document) +{ + std::ostringstream output; + write(output, Document); + return output.str(); +} + +document read(cParser &Input) +{ + // a value can be any word, "include" among them + Input.expandIncludes = false; + document result; + auto type{next_token(Input)}; + while (false == type.empty()) + { + auto name{next_token(Input)}; + if (name.empty()) + { + result.problems.emplace_back(std::format("the file ends after \"{}\"", type)); + break; + } + auto &entry{result.records.emplace_back(type, decode(name))}; + if (auto problem{read_fields(Input, entry)}; false == problem.empty()) + result.problems.emplace_back(std::move(problem)); + type = next_token(Input); + } + auto const *header{result.header()}; + if (header == nullptr) + { + result.problems.emplace_back("the file doesn't start with a \"snapshot\" entry"); + return result; + } + if (result.version() > format_version) + result.warnings.emplace_back(std::format("the file is of version {}, newer than {} which this build writes", result.version(), format_version)); + // the header counts the entries of the file: a file cut short between two entries reads without a fault otherwise + if (auto const *entries{header->find("entries")}; entries != nullptr) + { + if (auto const count{text_number(*entries)}; false == count.has_value() || *count != static_cast(result.records.size())) + { + result.problems.emplace_back(std::format("the header says the file has {} entries, it has {}: it's cut short, or it was put together from pieces", + shortened(*entries), result.records.size())); + } + } + return result; +} + +document parse(std::string const &Text) +{ + cParser parser(Text, cParser::buffer_TEXT); + return read(parser); +} + +bool accepted(document const &Document, bool const Force) +{ + return Document.header() != nullptr && (Document.problems.empty() || Force); +} + +namespace { + +std::filesystem::path temporary_file(std::string const &File) +{ + std::filesystem::path temporary{File}; + temporary += ".tmp"; + return temporary; +} + +} // namespace + +std::string open_temporary(std::string const &File, std::ofstream &Output) +{ + Output.open(temporary_file(File), std::ios::binary | std::ios::trunc); + if (false == Output.is_open()) + return std::format("file \"{}.tmp\" can't be written", File); + return {}; +} + +std::string put_in_place(std::string const &File, std::ofstream &Output) +{ + auto const temporary{temporary_file(File)}; + std::error_code error; + Output.flush(); + Output.close(); + if (Output.fail()) + { + std::filesystem::remove(temporary, error); + return std::format("writing file \"{}.tmp\" failed", File); + } + // the whole text is there: it takes the place of the file at once + std::filesystem::rename(temporary, File, error); + if (error) + { + std::filesystem::remove(temporary, error); + return std::format(R"(file "{0}.tmp" can't be put in place of "{0}")", File); + } + return {}; +} + +std::string write_file(std::string const &File, document const &Document) +{ + return write_file(File, [&Document](std::ostream &Output) { write(Output, Document); }); +} + +document load(std::string const &File) +{ + std::ifstream input(File, std::ios::binary); + if (false == input.is_open()) + { + document result; + result.problems.emplace_back(std::format("file \"{}\" can't be opened", File)); + return result; + } + std::ostringstream text; + text << input.rdbuf(); + return parse(text.str()); +} + +std::string reference(std::string_view const Name, std::size_t const Index, bool const Foundbyname) +{ + if (Foundbyname && false == Name.empty() && Name.front() != '#') + return std::string(Name); + return std::format("#{}", Index); +} + +std::optional reference_index(std::string_view const Reference) +{ + if (Reference.size() < 2 || Reference.front() != '#') + return std::nullopt; + std::size_t index{0}; + auto const *const begin{Reference.data() + 1}; + auto const *const end{Reference.data() + Reference.size()}; + if (auto const [parsed, error]{std::from_chars(begin, end, index)}; error == std::errc{} && parsed == end) + return index; + return std::nullopt; +} + +void name_hash::add(std::string_view const Name) +{ + constexpr std::uint64_t prime{1099511628211ULL}; + for (auto const character : Name) + { + m_hash ^= static_cast(character); + m_hash *= prime; + } + // the end of the name counts too: "ab", "c" isn't "a", "bc" + m_hash ^= 0xffU; + m_hash *= prime; +} + +std::string name_hash::text() const +{ + return std::format("{:016x}", m_hash); +} + +int option_value_count(std::string_view const Option) +{ + if (Option == "--snapshot-at") + return 2; + if (Option == "-s" || Option == "-v" || Option == "-seed" || Option == "-ini" || Option == "--test-timeout" || Option == "--test-wall-timeout" || + Option == "--load-snapshot") + return 1; + return 0; +} + +command_line parse_command_line(std::span const Arguments) +{ + command_line result; + std::size_t index{1}; + while (index < Arguments.size()) + { + std::string_view const option{Arguments[index]}; + auto const values{static_cast(option_value_count(option))}; + auto const complete{index + values < Arguments.size()}; + if (option == "--load-snapshot-force") + { + result.force = true; + } + else if (option == "--load-snapshot") + { + if (complete) + result.load = Arguments[index + 1]; + else if (result.error.empty()) + result.error = "--load-snapshot needs the name of a snapshot file"; + } + else if (option == "--snapshot-at") + { + auto const seconds{complete ? text_number(Arguments[index + 1]) : std::nullopt}; + if (seconds.has_value() && std::isfinite(*seconds) && *seconds >= 0.0) + result.saves.emplace_back(*seconds, Arguments[index + 2]); + else if (result.error.empty()) + result.error = "--snapshot-at needs a number of seconds and the name of a file"; + } + index += 1 + values; + } + return result; +} + +coupling_plan plan_couplings(std::vector const &Current, std::vector const &Wanted, std::vector const &Present) +{ + coupling_plan plan; + auto const current{by_coupler(Current)}; + auto const wanted{by_coupler(Wanted)}; + std::set> const present(Present.begin(), Present.end()); + + // what's coupled and shouldn't be, or should be another way + for (auto const &link : unique_links(Current)) + { + auto const *here{wanted_link(wanted, link.vehicle, link.end)}; + if (auto const *there{wanted_link(wanted, link.other, link.otherend)}; here == nullptr && there == nullptr) + continue; + // a vehicle which stays where the scenery put it isn't coupled to one put where the snapshot has it + if (auto const kept{here != nullptr && present.contains(link.vehicle) && present.contains(link.other) && + same_partner(*here, coupler_link{link.other, link.otherend, link.flags})}; + false == kept) + { + plan.part.emplace_back(link); + continue; + } + if (here->flags != link.flags) + plan.change.emplace_back(link.vehicle, link.end, link.other, link.otherend, here->flags); + } + // what should be coupled and isn't + for (auto const &link : unique_links(Wanted)) + { + if (false == present.contains(link.vehicle) || false == present.contains(link.other)) + { + plan.missing.emplace_back(link); + continue; + } + if (auto const lookup{current.find(coupler_key{link.vehicle, link.end})}; lookup != current.end() && same_partner(lookup->second, coupler_link{link.other, link.otherend, link.flags})) + continue; + plan.join.emplace_back(link); + } + // the links which stay and the ones to make mustn't close a ring of vehicles + consists joined; + for (auto const &link : unique_links(Current)) + { + if (std::ranges::find(plan.part, link) == plan.part.end()) + joined.join(link.vehicle, link.other); + } + std::erase_if(plan.join, [&joined, &plan](coupling_link const &Link) { + if (Link.vehicle != Link.other && joined.join(Link.vehicle, Link.other)) + return false; + plan.refused.emplace_back(Link); + return true; + }); + return plan; +} + +std::vector read_couplings(std::vector const &Entries) +{ + std::vector links; + for (auto const *entry : Entries) + { + for (auto const side : {0, 1}) + { + auto const key{std::format("coupler{}", side)}; + if (false == entry->has(key + "flags")) + continue; + // the end of the coupler on the other side is the index of one of the two couplers of a vehicle + auto otherend{0}; + auto flags{0}; + if (false == entry->get(key + "end", otherend, 0, 1) || false == entry->get(key + "flags", flags, 0, coupling_flags_mask)) + continue; + links.emplace_back(entry->name, side, entry->text(key), otherend, flags); + } + } + return links; +} + +bool placed_where_saved(record const &Entry, double const X, double const Y, double const Z) +{ + auto const x{text_number(Entry.text("x"))}; + auto const y{text_number(Entry.text("y"))}; + auto const z{text_number(Entry.text("z"))}; + if (false == x.has_value() || false == y.has_value() || false == z.has_value() || false == std::isfinite(*x + *y + *z)) + return true; + // written so that a vehicle put at a place which isn't a number is off + return std::hypot(X - *x, Y - *y, Z - *z) <= misplaced_distance; +} + +std::string fingerprint_changes(record const &Saved, record const &Now) +{ + std::string changed; + for (auto const &[key, value] : Now.fields) + { + if (auto const saved{Saved.text(key, value)}; saved != value) + changed += std::format("{}{} {} (snapshot {})", changed.empty() ? "" : ", ", key, value, shortened(saved)); + } + return changed; +} + +std::string free_file(std::string const &File) +{ + std::error_code error; + if (false == std::filesystem::exists(File, error)) + return File; + // the number goes before the extension of the name, the folder is written as it was given + auto const extension{std::filesystem::path{File}.extension().string()}; + auto const stem{File.substr(0, File.size() - extension.size())}; + auto number{2}; + auto file{std::format("{}_{}{}", stem, number, extension)}; + while (std::filesystem::exists(file, error)) + { + ++number; + file = std::format("{}_{}{}", stem, number, extension); + } + return file; +} + +} // namespace simulation::snapshot diff --git a/simulation/simulationsnapshot.h b/simulation/simulationsnapshot.h new file mode 100644 index 000000000..d5dbcc709 --- /dev/null +++ b/simulation/simulationsnapshot.h @@ -0,0 +1,402 @@ +/* +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/. +*/ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class cParser; + +// snapshot of a running simulation (stage A of the saved game): a text file in the syntax of the scenery files, which +// names the scenery it was taken in and holds what changed since that scenery was loaded. loading one means loading the +// scenery the usual way and then putting the saved state over it. +// this file is the text itself: the entries, how they're written and read. what goes into them is in +// simulationsnapshotmover.cpp (the state of a vehicle's machinery) and simulationsnapshotworld.cpp (the rest) +namespace simulation::snapshot { + +// version of the format, the name of the "snapshot" entry which starts the file. a reader takes the files of its own +// version and older ones, and of a newer file what it knows: unknown entries and keys are skipped +inline constexpr int format_version{1}; + +// writes a number so that reading it back gives the very same value +std::string number_text(double Value); +// a single precision value takes fewer digits to come back the same +std::string number_text(float Value); +// reads a number written by number_text(), or any other the standard reads. returns: empty if the text isn't a number +std::optional text_number(std::string_view Text); +// a few numbers as one value, with commas between them, and back; what isn't a number is left out +std::string numbers_text(std::span Numbers); +std::vector text_numbers(std::string_view Text); +// a number of the file as a whole number between Min and Max. returns: empty if it isn't one (not finite, a fraction, +// out of the range) +std::optional whole_number(double Value, int Min, int Max); + +// the values of the file the reader doesn't take: a number out of the range of what it's put into, a count past what +// the entry can hold, a text where a number is needed. a snapshot from a damaged or edited file mustn't put an index +// past the end of a table nor a count which takes forever, so each such value is left out (or brought into its range, +// where that's said) and told of here; the simulation collects them while a snapshot is put back, for the log +void refuse(std::string Text); +// the refusals told of since the last call, in their order. a damaged file can give a great many: past the first +// hundred only their number is kept, given as the last line +std::vector take_refusals(); + +// one entry of a snapshot: " ... end". the values are single tokens, +// kept as text in the order of the file, so an entry read and written back comes out the same, whatever it holds +class record { + +public: + record() = default; + record(std::string_view Type, std::string_view Name) : type(Type), name(Name) {} + + // adds the value, or replaces the one the key has + template record &set(std::string_view Key, Type_ const &Value); + // the value of the key, or nullptr + std::string const *find(std::string_view Key) const; + bool has(std::string_view Key) const { return find(Key) != nullptr; } + // the value of the key in the type of Target, which stays as it is when the entry has no such key or the value + // can't be read as that type (a whole number for a whole one, within the range of the type). a value which can't + // be read is refused (refuse()). returns: true if Target was set + template bool get(std::string_view Key, Type_ &Target) const; + // the same, for a value which has to be between Min and Max: one past them is refused + template bool get(std::string_view Key, Type_ &Target, Type_ Min, Type_ Max) const; + // the same, but a value past Min or Max is brought to it, and that's told of (refuse()) + template bool get_clamped(std::string_view Key, Type_ &Target, Type_ Min, Type_ Max) const; + // the value of the key, or Fallback + template Type_ value(std::string_view Key, Type_ Fallback) const; + // the value of the key between Min and Max, or Fallback + template Type_ value(std::string_view Key, Type_ Fallback, Type_ Min, Type_ Max) const; + std::string text(std::string_view Key, std::string_view Fallback = {}) const; + // tells of a value of the entry the reader didn't take, and why (refuse()) + void refuse(std::string_view Key, std::string_view Why) const; + + bool operator==(record const &) const = default; + + std::string type; + std::string name; + std::vector> fields; + +private: + void set_text(std::string_view Key, std::string Value); +}; + +// a count the entry gives of things it lists, each under a key of its own (the points of a table of a driver: "table" +// and "p0", "p1"...): a count past the number of keys of the entry can't be the count of what it lists, and is refused, +// as is one which isn't a whole number. returns: empty if the entry hasn't the key or its value is refused +std::optional read_count(record const &Entry, std::string_view Key); +// an index the entry gives into a table of Size things: one past the end of the table is refused. +// returns: empty if the entry hasn't the key or its value is refused +std::optional read_index(record const &Entry, std::string_view Key, std::size_t Size); + +// the whole file: the entries in their order. the first one is the header, "snapshot ... endsnapshot" +struct document { + std::vector records; + // what the reader couldn't make sense of: the file is damaged or cut short. a document with problems isn't put + // over a scenery unless that's forced (accepted()) + std::vector problems; + // what a reader should know, but which doesn't keep the document from being used: a file of a newer version + std::vector warnings; + + record &add(std::string_view Type, std::string_view Name); + // the entries of the type, in the order of the file + std::vector of(std::string_view Type) const; + // the first entry of the type with the name, or nullptr + record const *find(std::string_view Type, std::string_view Name) const; + record *find(std::string_view Type, std::string_view Name); + // the header, or nullptr if the document doesn't start with one + record const *header() const; + // the version the header gives, 0 without a header + int version() const; +}; + +// the document as text +void write(std::ostream &Output, document const &Document); +std::string to_text(document const &Document); +// reads the entries until the input ends +document read(cParser &Input); +document parse(std::string const &Text); +// reads the file; a file which can't be opened gives a document with that as its problem +document load(std::string const &File); +// whether the document is to be put over the scenery: it has to start with a header, and to have no problems unless +// Force says to use what could be read of it all the same (--load-snapshot-force) +bool accepted(document const &Document, bool Force); +// the steps of write_file(): opens ".tmp" for Output, and puts it in place of the file once it's written. +// returns: what went wrong, empty if nothing did +std::string open_temporary(std::string const &File, std::ofstream &Output); +std::string put_in_place(std::string const &File, std::ofstream &Output); +// writes the text Writer gives to the file, whole or not at all: to ".tmp" first, which takes the place of the +// file only once it's all written. a write which fails leaves the file as it was, and no .tmp behind. +// returns: what went wrong, empty if nothing did +template std::string write_file(std::string const &File, Writer_ const &Writer) +{ + std::ofstream output; + if (auto error{open_temporary(File, output)}; false == error.empty()) + return error; + Writer(output); + return put_in_place(File, output); +} +std::string write_file(std::string const &File, document const &Document); + +// a thing of the scenery is named in a snapshot by its name where it has one of its own, which is the one the tables +// of the simulation find it by, and by its place in the table otherwise ("#12"): the tables are filled in the order +// of the scenery files, so the same scenery gives the same places +std::string reference(std::string_view Name, std::size_t Index, bool Foundbyname); +// the place in the table a reference gives, if it's of the "#12" kind +std::optional reference_index(std::string_view Reference); + +// a hash of names (FNV-1a, 64 bits), for the fingerprint of the scenery in the header: the snapshot remembers how many +// tracks, memory cells, events and vehicles the scenery had and a hash of their names, and a scenery which gives +// other numbers when the snapshot is loaded isn't the one it was taken in +class name_hash { + +public: + void add(std::string_view Name); + std::uint64_t value() const { return m_hash; } + // as text, 16 hexadecimal digits + std::string text() const; + +private: + std::uint64_t m_hash{14695981039346656037ULL}; +}; + +// the flags of a coupling a snapshot can give: every bit of the Coupling enum of the physics (physics/vehicletypes.h), from coupler +// (0x1) to power3x400v (0x400) +inline constexpr int coupling_flags_mask{0x7ff}; + +// what the vehicles of a snapshot are coupled to: for a vehicle and its end (0 front, 1 rear) the vehicle and the end +// on the other side, and the Coupling flags of what's joined +struct coupling_link { + std::string vehicle; + int end{0}; + std::string other; + int otherend{0}; + int flags{0}; + + bool operator==(coupling_link const &) const = default; +}; + +// what has to be done to the couplings of the scenery to get the ones of the snapshot: the links to part first, then +// the links to make. a link is listed once, by the vehicle and end which come first in the given lists +struct coupling_plan { + std::vector part; + std::vector join; + // the links to set other flags on: joined to the same vehicle and end already, but by other means + std::vector change; + // the links of the snapshot to vehicles which aren't in Present + std::vector missing; + // the links of the snapshot which would close a ring of vehicles (a vehicle coupled to itself, or the last vehicle + // of a consist to its first): a consist is a line, and the code which walks along one would never get to its end + std::vector refused; +}; +// Current: the links as they are, each given from both of its ends or from one. Wanted: the same for the snapshot. +// Present: the names of the vehicles of the scenery which can be coupled as the snapshot has them. links of vehicles the +// snapshot says nothing of stay as they are, unless a vehicle of the snapshot needs the coupler at their other end. a +// vehicle left out of Present (one which stays where the scenery put it) is parted from the vehicles of the snapshot, +// and the links of the snapshot to it are missing +coupling_plan plan_couplings(std::vector const &Current, std::vector const &Wanted, std::vector const &Present); +// the couplings of the vehicle entries ("coupler0", "coupler0end", "coupler0flags" and the same for 1), for +// plan_couplings(). an end other than 0 or 1, or flags which aren't those of a coupling, are refused (refuse()): that +// coupler is left out, as if the entry said nothing of it +std::vector read_couplings(std::vector const &Entries); + +// how far a vehicle may be put from the place in the world its entry gives ("x", "y", "z") to be where the snapshot has +// it. further off, the track the entry names is another one now: the scenery changed since the snapshot was taken +inline constexpr double misplaced_distance{1.0}; +// whether the vehicle, put at X Y Z, is where the entry has it. an entry without its place in the world can't tell, and +// is taken at its word +bool placed_where_saved(record const &Entry, double X, double Y, double Z); +// what differs between the fingerprint of the scenery in the header of a snapshot (Saved) and the one of the scenery +// it's put over (Now): "tracks 812 (snapshot 811), names ...". returns: empty if they're the same +std::string fingerprint_changes(record const &Saved, record const &Now); +// the file to write in place of File, which is taken already: "_2", "_3"... the first +// one which isn't. returns: File itself if it isn't taken +std::string free_file(std::string const &File); + +// the snapshots asked for on the command line of the simulator +struct command_line { + struct save_request { + double time{0.0}; // of the simulation, seconds since the scenery started (Timer::GetTime()) + std::string file; + }; + std::string load; // --load-snapshot : put over the scenery once it's loaded + bool force{false}; // --load-snapshot-force: a damaged file is put over the scenery as far as it could be read + std::vector saves; // --snapshot-at , any number of them: written when the time comes + std::string error; // what's wrong with the options; empty if nothing +}; +// picks the snapshot options out of a command line (the first argument is the program), skipping the values of the +// other options the simulator takes +command_line parse_command_line(std::span Arguments); +// how many values follow an option of the simulator on its command line, for the parsers which pick out their own +int option_value_count(std::string_view Option); + +// implementation of the templates + +namespace detail { + +template std::string value_text(Type_ const &Value) +{ + using type = std::remove_cvref_t; + if constexpr (std::is_same_v) + return Value ? "1" : "0"; + else if constexpr (std::is_enum_v) + return std::to_string(static_cast(Value)); + else if constexpr (std::is_integral_v) + return std::to_string(Value); + else if constexpr (std::is_same_v) + return number_text(Value); + else if constexpr (std::is_floating_point_v) + return number_text(static_cast(Value)); + else + return std::string(std::string_view(Value)); +} + +// whether the number fits a variable of the integer type: whole, and within its range +template bool fits_integer(double const Number) +{ + using limits = std::numeric_limits; + // the bounds as exact doubles: -2^63 .. 2^63 for a 64 bit signed type, 0 .. 2^64 for an unsigned one; the upper one + // is past the range + auto const lowest{limits::is_signed ? -std::ldexp(1.0, limits::digits) : 0.0}; + auto const past{std::ldexp(1.0, limits::digits)}; + return std::isfinite(Number) && std::trunc(Number) == Number && Number >= lowest && Number < past; +} + +template bool text_value(std::string const &Text, Type_ &Target) +{ + using type = std::remove_cvref_t; + if constexpr (std::is_same_v) + { + Target = Text; + return true; + } + else + { + auto const number{text_number(Text)}; + if (false == number.has_value()) + return false; + if constexpr (std::is_same_v) + { + if (std::isnan(*number)) + return false; + Target = *number != 0.0; + } + else if constexpr (std::is_enum_v || std::is_integral_v) + { + // an integer out of the range of its type is undefined, a fraction isn't what was written + using integer = typename std::conditional_t, std::underlying_type, std::type_identity>::type; + if (false == fits_integer(*number)) + return false; + Target = static_cast(static_cast(*number)); + } + else + { + // not a number and the infinities are values like any other, a finite number too big for the type isn't: one + // which rounds past its largest value + auto const top{static_cast(std::numeric_limits::max())}; + if (auto const step{top - static_cast(std::nextafter(std::numeric_limits::max(), type{0}))}; + std::isfinite(*number) && std::abs(*number) >= top + step / 2) + return false; + Target = static_cast(*number); + } + return true; + } +} + +// the text of a bound, for what's told of a value out of its range +template std::string bound_text(Type_ const Value) +{ + if constexpr (std::is_enum_v) + return std::to_string(static_cast(Value)); + else + return value_text(Value); +} + +} // namespace detail + +template record &record::set(std::string_view const Key, Type_ const &Value) +{ + set_text(Key, detail::value_text(Value)); + return *this; +} + +template bool record::get(std::string_view const Key, Type_ &Target) const +{ + auto const *text{find(Key)}; + if (text == nullptr) + return false; + if (detail::text_value(*text, Target)) + return true; + refuse(Key, "it can't be read as a value of its kind"); + return false; +} + +template bool record::get(std::string_view const Key, Type_ &Target, Type_ const Min, Type_ const Max) const +{ + auto value{Target}; + if (false == get(Key, value)) + return false; + // written so that not a number fails too + if (false == (value >= Min && value <= Max)) + { + refuse(Key, std::format("it's out of the range {} .. {}", detail::bound_text(Min), detail::bound_text(Max))); + return false; + } + Target = value; + return true; +} + +template bool record::get_clamped(std::string_view const Key, Type_ &Target, Type_ const Min, Type_ const Max) const +{ + auto value{Target}; + if (false == get(Key, value)) + return false; + if constexpr (std::is_floating_point_v) + { + if (std::isnan(value)) + { + refuse(Key, "it's not a number"); + return false; + } + } + if (value < Min || value > Max) + { + auto const clamped{value < Min ? Min : Max}; + refuse(Key, std::format("it's out of the range {} .. {}, {} is taken", detail::bound_text(Min), detail::bound_text(Max), detail::bound_text(clamped))); + value = clamped; + } + Target = value; + return true; +} + +template Type_ record::value(std::string_view const Key, Type_ Fallback) const +{ + get(Key, Fallback); + return Fallback; +} + +template Type_ record::value(std::string_view const Key, Type_ Fallback, Type_ const Min, Type_ const Max) const +{ + get(Key, Fallback, Min, Max); + return Fallback; +} + +} // namespace simulation::snapshot diff --git a/simulation/simulationsnapshotdriver.cpp b/simulation/simulationsnapshotdriver.cpp new file mode 100644 index 000000000..e2c7fefa7 --- /dev/null +++ b/simulation/simulationsnapshotdriver.cpp @@ -0,0 +1,622 @@ +/* +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 "vehicle/Driver.h" + +#include "simulation/simulation.h" +#include "simulation/simulationsnapshotworld.h" +#include "utilities/Globals.h" +#include "utilities/Logs.h" +#include "world/Event.h" + +#include +#include +#include +#include + +// the part of a simulation snapshot kept by the driver of a train (TController): the orders it has and which one it's +// on, where it is in its timetable, the consist it drives, and what it has made up its mind about: the speeds it +// holds to, why it stands, what it waits for, and its table of what's ahead on the track with the limits it latched + +namespace { + +namespace snapshot = simulation::snapshot; + +// the most events sharing a name a snapshot looks among +constexpr int most_siblings{100000}; +// every order the driver knows, as bits (DriverOrders) +constexpr int every_order{(static_cast(DriverOrder::jumpToFirstOrder) << 1) - 1}; + +// the orders as their numbers joined with commas: "1,128,16,32" +std::string join(std::span const Orders) +{ + std::string text; + for (auto const order : Orders) + { + if (false == text.empty()) + text += ','; + text += std::to_string(order.Bits()); + } + return text; +} + +// the whole numbers of a list between Min and Max. returns: empty if one of them isn't such a number +std::optional> split(std::string_view Text, int const Min, int const Max) +{ + std::vector numbers; + while (false == Text.empty()) + { + auto const comma{Text.find(',')}; + auto const number{snapshot::text_number(Text.substr(0, comma))}; + auto const whole{number.has_value() ? snapshot::whole_number(*number, Min, Max) : std::nullopt}; + if (false == whole.has_value()) + return std::nullopt; + numbers.emplace_back(*whole); + Text.remove_prefix(comma == std::string_view::npos ? Text.size() : comma + 1); + } + return numbers; +} + +// an event under the keys "" (its name) and "sibling" (its place among the events sharing the name) +void save_event(snapshot::record &Entry, std::string const &Key, basic_event const *Event) +{ + if (Event == nullptr) + return; + Entry.set(Key, Event->m_name); + if (auto const sibling{snapshot::event_sibling(Event)}; sibling != 0) + Entry.set(Key + "sibling", sibling); +} + +basic_event *load_event(snapshot::record const &Entry, std::string const &Key) +{ + auto const name{Entry.text(Key)}; + auto sibling{0}; + if (name.empty() || (false == Entry.get(Key + "sibling", sibling, 0, most_siblings) && Entry.has(Key + "sibling"))) + return nullptr; + return snapshot::find_event(name, sibling); +} + +// a point of the table of what's ahead: its numbers under "", its track and its event beside them +void save_point(snapshot::record &Entry, std::string const &Key, TSpeedPos const &Point) +{ + std::array const numbers{Point.fDist, Point.fVelNext, Point.fSectionVelocityDist, Point.fPointDist, static_cast(Point.LegacyFlagsValue()), + Point.bMoved ? 1.0 : 0.0, Point.fMoved, Point.vPos.x, Point.vPos.y, Point.vPos.z}; + Entry.set(Key, snapshot::numbers_text(numbers)); + if (Point.trTrack != nullptr) + Entry.set(Key + "track", snapshot::track_reference(Point.trTrack)); + save_event(Entry, Key + "event", Point.evEvent); +} + +// returns: false if the entry has no such point, or it's of another make +bool load_point(snapshot::record const &Entry, std::string const &Key, TSpeedPos &Point) +{ + auto const numbers{snapshot::text_numbers(Entry.text(Key))}; + if (numbers.size() != 10) + return false; + // the flags of a point are bits of a whole number + auto const flags{snapshot::whole_number(numbers[4], std::numeric_limits::min(), std::numeric_limits::max())}; + if (false == flags.has_value()) + { + Entry.refuse(Key, "its flags aren't a whole number"); + return false; + } + Point.fDist = numbers[0]; + Point.fVelNext = numbers[1]; + Point.fSectionVelocityDist = numbers[2]; + Point.fPointDist = numbers[3]; + // the flags and, in their top 4 bits, the route through a crossing, -8..7 + Point.flags = SpeedPointFlags::FromBits(static_cast(static_cast(*flags) & 0x0fffffffu)); + Point.crossRoute = *flags >> 28; + Point.bMoved = numbers[5] != 0.0; + Point.fMoved = numbers[6]; + Point.vPos = {numbers[7], numbers[8], numbers[9]}; + Point.trTrack = snapshot::find_track(Entry.text(Key + "track")); + Point.evEvent = load_event(Entry, Key + "event"); + // a point whose track or event the scenery no longer has can't be told from one which had none + return (Point.trTrack != nullptr) == Entry.has(Key + "track") && (Point.evEvent != nullptr) == Entry.has(Key + "event"); +} + +} // namespace + +// the variables kept one for one, by groups in the order of the entry. they're members so that they can name the private +// ones. Driver_ and Converted_ are const for a save; Visit takes the key, the variable and, for a whole number which has +// to be in a range, the range +struct TController::snapshot_members { + // what the driver keeps in another form than the snapshot has it, as the numbers of the snapshot: taken for a save and + // for a load, put back once the load has set what the entry has + struct converted { + int flags{0}; // the driving flags, as the bits of iDrivigFlags they were (TMovementStatus) + int brakeTest{0}; // the stage of the running brake test, as the number of DynamicBrakeTest it was + int staticBrakeTest{0}; // StaticBrakeTest, which nothing read or wrote and which is gone: 0, read and left + int coupler{0}; // the couplings to make when the driver couples next (iCoupler), as the bits of the set + bool uphillStart{false}; // starting uphill: the train brake holds the train until the power does, or is being released + }; + + // the driving flags in the order of their bits in iDrivigFlags (moveStopCloser 0x1 .. moveDepartureWarned 0x400000) + template static auto driving_flags(Flags_ &Flags) + { + return std::array{&Flags.stopCloser, &Flags.stopPoint, &Flags.active, &Flags.press, &Flags.connect, &Flags.primary, + &Flags.late, &Flags.stopHere, &Flags.startHorn, &Flags.startHornNow, &Flags.startHornDone, &Flags.oerlikons, + &Flags.incSpeed, &Flags.trackEnd, &Flags.switchFound, &Flags.guardSignal, &Flags.visibility, &Flags.doorOpened, + &Flags.pushPull, &Flags.signalFound, &Flags.stopPointFound, &Flags.guardOpenDoor, &Flags.departureWarned}; + } + + static converted take(TController const &Driver) + { + converted values; + auto bits{0u}; + auto bit{1u}; + for (auto const *flag : driving_flags(Driver.drivingFlags)) + { + bits |= *flag ? bit : 0u; + bit <<= 1; + } + // the signals the map asked to show were bits Signal_Pc6 and Signal_A1 of the same number + bits |= Driver.drivingFlags.signalPc6 ? 1u << Signal_Pc6 : 0u; + bits |= Driver.drivingFlags.signalA1 ? 1u << Signal_A1 : 0u; + values.flags = static_cast(bits); + values.brakeTest = static_cast(Driver.brakeTest.stage); + values.coupler = Driver.iCoupler.Bits(); + values.uphillStart = Driver.uphillStart.IsActive(); + return values; + } + + static void put(TController &Driver, converted const &Values) + { + auto const bits{static_cast(Values.flags)}; + auto bit{1u}; + for (auto *flag : driving_flags(Driver.drivingFlags)) + { + *flag = (bits & bit) != 0; + bit <<= 1; + } + Driver.drivingFlags.signalPc6 = (bits & (1u << Signal_Pc6)) != 0; + Driver.drivingFlags.signalA1 = (bits & (1u << Signal_A1)) != 0; + Driver.brakeTest.stage = static_cast(Values.brakeTest); + Driver.iCoupler = CouplingSet::FromBits(Values.coupler); + // a start uphill was kept as starting or not: one going on goes on, one given in the entry starts holding + if (false == Values.uphillStart) + Driver.uphillStart.phase = uphill_start::Phase::none; + else if (false == Driver.uphillStart.IsActive()) + Driver.uphillStart.phase = uphill_start::Phase::holding; + } + + template static void speeds(Driver_ &D, Converted_ &, Visit_ const &Visit) + { + Visit("accpreferred", D.AccPreferred); + Visit("accdesired", D.AccDesired); + Visit("veldesired", D.VelDesired); + Visit("accdesiredav", D.fAccDesiredAv); + Visit("accdesiredgravity", D.fAccDesiredGravity); + Visit("velfordriver", D.VelforDriver); + Visit("velsignal", D.VelSignal); + Visit("vellimit", D.VelLimit); + Visit("velsignallast", D.VelSignalLast); + Visit("velsignalnext", D.VelSignalNext); + Visit("vellimitlast", D.VelLimitLast); + Visit("velroad", D.VelRoad); + Visit("velnext", D.VelNext); + Visit("velrestricted", D.VelRestricted); + Visit("shuntvelocity", D.fShuntVelocity); + Visit("velmax", D.fVelMax); + Visit("velplus", D.fVelPlus); + Visit("velminus", D.fVelMinus); + } + + template static void distances(Driver_ &D, Converted_ &, Visit_ const &Visit) + { + Visit("firstsemaphordist", D.FirstSemaphorDist); + Visit("actualproximitydist", D.ActualProximityDist); + Visit("switchcleardist", D.SwitchClearDist); + Visit("signalareaenddist", D.SignalAreaEndDist); + Visit("minproximitydist", D.fMinProximityDist); + Visit("maxproximitydist", D.fMaxProximityDist); + Visit("laststopexpdist", D.fLastStopExpDist); + Visit("driverdist", D.fDriverDist); + Visit("brakedist", D.fBrakeDist); + Visit("movelen", D.dMoveLen); + Visit("length", D.fLength); + Visit("mass", D.fMass); + } + + template static void timers(Driver_ &D, Converted_ &, Visit_ const &Visit) + { + Visit("brakeheldtime", D.fBrakeHeldTime); + Visit("shortfall", D.brakingShortfall.value); + Visit("shortfalltime", D.brakingShortfall.time); + Visit("uphillstarttime", D.uphillStart.startTime); + Visit("warningduration", D.fWarningDuration); + Visit("waitingtime", D.WaitingTime); + Visit("waitingexpiretime", D.WaitingExpireTime); + Visit("idletime", D.IdleTime); + Visit("stoptime", D.fStopTime); + Visit("reactiontime", D.ReactionTime); + Visit("lastreactiontime", D.LastReactionTime); + Visit("braketime", D.fBrakeTime); + Visit("actiontime", D.fActionTime); + Visit("radiocontroltime", D.m_radiocontroltime); + Visit("brakechargingcooldown", D.BrakeChargingCooldown); + Visit("brakechargingstart", D.BrakeChargingStart); + Visit("departblockedstart", D.DepartBlockedStart); + Visit("dbtvelocitybrake", D.brakeTest.velocityBrake); + Visit("dbtvelocityrelease", D.brakeTest.velocityRelease); + Visit("dbtvelocityfinish", D.brakeTest.velocityFinish); + Visit("dbtbrakingtime", D.brakeTest.brakingTime); + Visit("dbtreleasingtime", D.brakeTest.releasingTime); + Visit("dbtmidpointacc", D.brakeTest.midPointAcc); + Visit("lastupdatedtime", D.LastUpdatedTime); + Visit("elapsedtime", D.ElapsedTime); + // when the power was last taken down a step for a slip while starting (#494) + Visit("sandedstarttime", D.sandedStart.decreaseTime); + } + + template static void levels(Driver_ &D, Converted_ &, Visit_ const &Visit) + { + Visit("brakectrlposition", D.BrakeCtrlPosition); + Visit("overhead1", D.fOverhead1); + Visit("overhead2", D.fOverhead2); + Visit("voltage", D.fVoltage); + Visit("driverbraking", D.fDriverBraking); + Visit("brakereaction", D.fBrakeReaction); + Visit("nominalaccthreshold", D.fNominalAccThreshold); + Visit("accthreshold", D.fAccThreshold); + Visit("absaccs", D.AbsAccS); + Visit("brakinginitiallevel", D.BrakingInitialLevel); + Visit("brakinglevelincrease", D.BrakingLevelIncrease); + Visit("accgravity", D.fAccGravity); + Visit("ready", D.fReady); + Visit("consistshade", D.ConsistShade); + Visit("medamax", D.fMedAmax); + } + + template static void numbers(Driver_ &D, Converted_ &C, Visit_ const &Visit) + { + Visit("flags", C.flags); + Visit("direction", D.iDirection, -1, 1); + Visit("directionorder", D.iDirectionOrder, -1, 1); + Visit("vehiclecount", D.iVehicleCount); + Visit("coupler", C.coupler); + Visit("failcount", D.iDriverFailCount); + Visit("overheadzero", D.iOverheadZero); + Visit("overheaddown", D.iOverheadDown); + Visit("universalbrakebuttons", D.UniversalBrakeButtons); + Visit("dizelpercentage", D.DizelPercentage); + Visit("dizelpercentagespeed", D.DizelPercentage_Speed); + Visit("helperstate", D.HelperState); + Visit("shortfallgrowth", D.brakingShortfall.growth); + Visit("dynamicbraketest", C.brakeTest, static_cast(RunningBrakeTest::Stage::waiting), static_cast(RunningBrakeTest::Stage::done)); + Visit("staticbraketest", C.staticBrakeTest); + Visit("radiochannel", D.iRadioChannel); + Visit("guardradio", D.iGuardRadio); + Visit("vehicles", D.iVehicles); + Visit("engines", D.ControlledEnginesCount); + Visit("lastexchangeplatforms", D.m_lastexchangeplatforms); + Visit("lastexchangedirection", D.m_lastexchangedirection); + } + + template static void flags(Driver_ &D, Converted_ &C, Visit_ const &Visit) + { + Visit("stoptargetispassengerstop", D.bStopTargetIsPassengerStop); + Visit("uphillstart", C.uphillStart); + Visit("needtryagain", D.Need_TryAgain); + Visit("heatingtemperatureok", D.IsHeatingTemperatureOK); + Visit("heatingtemperaturetoolow", D.IsHeatingTemperatureTooLow); + Visit("atpassengerstop", D.IsAtPassengerStop); + Visit("scheduledstopvisible", D.IsScheduledPassengerStopVisible); + Visit("forcepnbrake", D.ForcePNBrake); + Visit("brakereinspection", D.BrakeReinspectionPending); + Visit("engineactive", D.iEngineActive); + Visit("passengertrain", D.IsPassengerTrain); + Visit("cargotrain", D.IsCargoTrain); + Visit("heavycargotrain", D.IsHeavyCargoTrain); + Visit("isready", D.Ready); + Visit("consistbraked", D.IsConsistBraked); + Visit("nextstopannouncement", D.m_makenextstopannouncement); + Visit("doorneedsopening", D.DoesAnyDoorNeedOpening); + // a start that slipped: sanding under power until the train is under way (#494) + Visit("sandedstart", D.sandedStart.active); + } + + template static void texts(Driver_ &D, Converted_ &, Visit_ const &Visit) + { + Visit("nextstop", D.asNextStop); + Visit("lastexchangestop", D.m_lastexchangestop); + Visit("assignment", D.m_assignment); + } +}; + +namespace { + +// writes a variable of the driver to the entry +struct save_visit { + snapshot::record &entry; + template void operator()(std::string_view const Key, Type_ const &Value, Range_...) const { entry.set(Key, Value); } +}; + +// sets a variable of the driver from the entry: a whole number given a range only within it +struct load_visit { + snapshot::record const &entry; + template void operator()(std::string_view const Key, Type_ &Target, Range_... Range) const + { + if constexpr (sizeof...(Range) == 2) + entry.get(Key, Target, static_cast(Range)...); + else + entry.get(Key, Target); + } +}; + +} // namespace + +void TController::snapshot_save(simulation::snapshot::record &Entry) const +{ + using members = snapshot_members; + auto const converted{members::take(*this)}; + save_visit const save{Entry}; + // who drives, and what + Entry.set("ai", aiControlled); + Entry.set("front", snapshot::vehicle_reference(pVehicles[VehicleEnd::front])); + Entry.set("rear", snapshot::vehicle_reference(pVehicles[VehicleEnd::rear])); + // the orders: the one it's on, in words for the reader of the file, then all of them + Entry.set("order", Order2Str(OrderCurrentGet())); + Entry.set("orderpos", OrderPos); + Entry.set("orders", join(std::span{OrderList}.first(static_cast(std::clamp(OrderTop, 0, maxorders))))); + // the timetable + Entry.set("train", TrainParams.TrainName); + Entry.set("station", TrainParams.StationIndex); + Entry.set("stationstart", TrainParams.StationStart); + Entry.set("nextstation", TrainParams.NextStationName); + Entry.set("latency", TrainParams.LastStationLatency); + Entry.set("timetabledirection", TrainParams.Direction); + Entry.set("ttvmax", TrainParams.TTVmax); + // the service flags of the stop the train is at or left last: central doors, doorstep, conductor, brake test + Entry.set("stopflags", std::format("{},{},{},{}", static_cast(m_stopflags.central_doors), static_cast(m_stopflags.doorstep), + static_cast(m_stopflags.conductor), static_cast(m_stopflags.brake_test))); + members::texts(*this, converted, save); + // what it does and why + Entry.set("action", eAction); + Entry.set("stopreason", eStopReason); + members::numbers(*this, converted, save); + members::flags(*this, converted, save); + members::speeds(*this, converted, save); + members::distances(*this, converted, save); + members::timers(*this, converted, save); + members::levels(*this, converted, save); + Entry.set("exchangetime", ExchangeTime); + // what the brake of the consist gives at each speed, as worked out when the consist was last looked over + Entry.set("brakea0", snapshot::numbers_text(fBrake_a0)); + Entry.set("brakea1", snapshot::numbers_text(fBrake_a1)); + Entry.set("brakesystem", BrakeSystem); + Entry.set("doorclosure", DoorClosure); + Entry.set("lastannouncement", m_lastannouncement); + Entry.set("vellimitlastdist0", VelLimitLastDist.first).set("vellimitlastdist1", VelLimitLastDist.second); + Entry.set("lighthint0", m_lighthints[VehicleEnd::front]).set("lighthint1", m_lighthints[VehicleEnd::rear]); + if (iDirectionBackup.has_value()) + Entry.set("directionbackup", *iDirectionBackup); + if (iCouplingVehicle.has_value() && iCouplingVehicle->first != nullptr) + Entry.set("couplingvehicle", snapshot::vehicle_reference(iCouplingVehicle->first)).set("couplingend", iCouplingVehicle->second); + save_event(Entry, "signskip", eSignSkip); + save_event(Entry, "signnext", eSignNext); + snapshot_save_table(Entry); +} + +// what the driver sees ahead: the table of the tracks and signs on its way, and the speed limits of points it has +// passed the signs of +void TController::snapshot_save_table(simulation::snapshot::record &Entry) const +{ + Entry.set("table", sSpeedTable.size()); + Entry.set("tablelast", iLast).set("tabledirection", iTableDirection).set("tablelastvel", fLastVel); + if (tLast != nullptr) + Entry.set("tablelasttrack", snapshot::track_reference(tLast)); + if (SemNextIndex != npos) + Entry.set("semnext", SemNextIndex); + if (SemNextStopIndex != npos) + Entry.set("semnextstop", SemNextStopIndex); + for (std::size_t index{0}; index < sSpeedTable.size(); ++index) + save_point(Entry, std::format("p{}", index), sSpeedTable[index]); + + Entry.set("limits", m_pointlimits.size()); + for (std::size_t index{0}; index < m_pointlimits.size(); ++index) + { + auto const &limit{m_pointlimits[index]}; + auto const key{std::format("l{}", index)}; + std::array const numbers{limit.velocity, limit.distance, limit.celldistance, limit.heading.x, limit.heading.y, limit.heading.z, limit.end, limit.endknown ? 1.0 : 0.0}; + Entry.set(key, snapshot::numbers_text(numbers)); + save_event(Entry, key + "event", limit.source); + } + if (m_pointlimitsvehicle != nullptr) + { + std::array const position{m_pointlimitsposition.x, m_pointlimitsposition.y, m_pointlimitsposition.z, m_pointlimitslength}; + Entry.set("limitsvehicle", snapshot::vehicle_reference(m_pointlimitsvehicle)).set("limitsposition", snapshot::numbers_text(position)); + Entry.set("limitsend0", snapshot::vehicle_reference(m_pointlimitsends[0])).set("limitsend1", snapshot::vehicle_reference(m_pointlimitsends[1])); + } +} + +// returns: false if the table of the entry can't be put back whole; the driver then looks at the track again +bool TController::snapshot_load_table(simulation::snapshot::record const &Entry) +{ + TableClear(); + m_pointlimits.clear(); + m_pointlimitsvehicle = nullptr; + // each point of the table has a key of its own: a count past the keys of the entry can't be the count of its points + auto const points{snapshot::read_count(Entry, "table")}; + if (false == points.has_value()) + return false; + auto const count{*points}; + std::vector table(count); + for (std::size_t index{0}; index < count; ++index) + { + if (false == load_point(Entry, std::format("p{}", index), table[index])) + return false; + } + // the indices into the table point at one of its points, or at none (-1 and npos, which the entry doesn't write) + auto last{-1}; + auto const next{snapshot::read_index(Entry, "semnext", count)}; + auto const nextstop{snapshot::read_index(Entry, "semnextstop", count)}; + if ((false == Entry.get("tablelast", last, -1, static_cast(count) - 1) && Entry.has("tablelast")) || (false == next.has_value() && Entry.has("semnext")) || + (false == nextstop.has_value() && Entry.has("semnextstop"))) + return false; + sSpeedTable = std::move(table); + iLast = last; + Entry.get("tabledirection", iTableDirection, -1, 1); + Entry.get("tablelastvel", fLastVel); + tLast = snapshot::find_track(Entry.text("tablelasttrack")); + SemNextIndex = next.value_or(npos); + SemNextStopIndex = nextstop.value_or(npos); + eSignNext = load_event(Entry, "signnext"); + + auto const limits{snapshot::read_count(Entry, "limits").value_or(0)}; + for (std::size_t index{0}; index < limits; ++index) + { + auto const key{std::format("l{}", index)}; + auto const numbers{snapshot::text_numbers(Entry.text(key))}; + auto const *source{load_event(Entry, key + "event")}; + if (numbers.size() != 8 || source == nullptr) + continue; + auto &limit{m_pointlimits.emplace_back()}; + limit.source = source; + limit.velocity = numbers[0]; + limit.distance = numbers[1]; + limit.celldistance = numbers[2]; + limit.heading = {numbers[3], numbers[4], numbers[5]}; + limit.end = numbers[6]; + limit.endknown = numbers[7] != 0.0; + } + if (auto const position{snapshot::text_numbers(Entry.text("limitsposition"))}; position.size() == 4) + { + m_pointlimitsvehicle = snapshot::find_vehicle(Entry.text("limitsvehicle")); + m_pointlimitsposition = {position[0], position[1], position[2]}; + m_pointlimitslength = position[3]; + m_pointlimitsends[0] = snapshot::find_vehicle(Entry.text("limitsend0")); + m_pointlimitsends[1] = snapshot::find_vehicle(Entry.text("limitsend1")); + } + return true; +} + +void TController::snapshot_load(simulation::snapshot::record const &Entry, std::function const &Left) +{ + using members = snapshot_members; + auto converted{members::take(*this)}; + load_visit const load{Entry}; + // the timetable: the scenery gave the train the one it started with, which another may have replaced since + if (auto const train{Entry.text("train", TrainParams.TrainName)}; train != TrainParams.TrainName) + { + TrainParams = TTrainParameters(train); + if (train != "none" && false == TrainParams.LoadTTfile(Global.asCurrentSceneryPath, 0, Entry.value("ttvmax", 0.0))) + ErrorLog(std::format("snapshot: timetable \"{}\" of {} can't be loaded", train, OwnerName())); + } + // the stations are entries of the table of the timetable, 1..StationCount, and the one after the last + auto const laststation{std::clamp(TrainParams.StationCount + 1, 0, MaxTTableSize)}; + Entry.get("station", TrainParams.StationIndex, 0, laststation); + Entry.get("stationstart", TrainParams.StationStart, 0, laststation); + Entry.get("nextstation", TrainParams.NextStationName); + Entry.get("latency", TrainParams.LastStationLatency); + Entry.get("timetabledirection", TrainParams.Direction, -1, 1); + Entry.get("ttvmax", TrainParams.TTVmax); + m_stopflags = TrainParams.stop_flags(); + if (auto const stopflags{split(Entry.text("stopflags"), 0, static_cast(timetable::tristate::no)).value_or(std::vector{})}; stopflags.size() == 4) + { + using timetable::tristate; + m_stopflags.central_doors = static_cast(stopflags[0]); + m_stopflags.doorstep = static_cast(stopflags[1]); + m_stopflags.conductor = static_cast(stopflags[2]); + m_stopflags.brake_test = static_cast(stopflags[3]); + } + members::texts(*this, converted, load); + + // the orders + if (Entry.has("orders")) + { + // the orders are bits, and the stack holds so many of them + if (auto const orders{split(Entry.text("orders"), 0, every_order)}; orders.has_value() && orders->size() <= static_cast(maxorders)) + { + OrdersClear(); + OrderTop = static_cast(orders->size()); + for (auto index{0}; index < OrderTop; ++index) + OrderList[index] = DriverOrders::FromBits((*orders)[index]); + } + else + Entry.refuse("orders", std::format("they aren't up to {} numbers of orders", maxorders)); + } + // the order the driver is on is an index into the stack + Entry.get("orderpos", OrderPos, 0, maxorders - 1); + + Entry.get("action", eAction, TAction::actUnknown, TAction::actTrial); + Entry.get("stopreason", eStopReason, stopNone, stopError); + members::numbers(*this, converted, load); + members::flags(*this, converted, load); + members::speeds(*this, converted, load); + members::distances(*this, converted, load); + members::timers(*this, converted, load); + members::levels(*this, converted, load); + members::put(*this, converted); + Entry.get("exchangetime", ExchangeTime); + if (auto const numbers{snapshot::text_numbers(Entry.text("brakea0"))}; numbers.size() == std::size(fBrake_a0)) + std::ranges::copy(numbers, fBrake_a0); + if (auto const numbers{snapshot::text_numbers(Entry.text("brakea1"))}; numbers.size() == std::size(fBrake_a1)) + std::ranges::copy(numbers, fBrake_a1); + Entry.get("brakesystem", BrakeSystem, TBrakeSystem::Individual, TBrakeSystem::ElectroPneumatic); + Entry.get("doorclosure", DoorClosure, door_closure_t::none, door_closure_t::open); + Entry.get("lastannouncement", m_lastannouncement, announcement_t::idle, announcement_t::end); + Entry.get("vellimitlastdist0", VelLimitLastDist.first); + Entry.get("vellimitlastdist1", VelLimitLastDist.second); + Entry.get("lighthint0", m_lighthints[VehicleEnd::front]); + Entry.get("lighthint1", m_lighthints[VehicleEnd::rear]); + iDirectionBackup.reset(); + if (auto direction{0}; Entry.get("directionbackup", direction, -1, 1)) + iDirectionBackup = direction; + iCouplingVehicle.reset(); + // the end of the vehicle to couple to is one of its two couplers + if (auto *vehicle{snapshot::find_vehicle(Entry.text("couplingvehicle"))}; vehicle != nullptr) + { + if (auto end{0}; Entry.get("couplingend", end, 0, 1) || false == Entry.has("couplingend")) + iCouplingVehicle = std::make_pair(vehicle, end); + } + + // the consist: its ends as they were, the vehicles driven and braked found anew among what's coupled now. an end left + // where the scenery put it isn't coupled to the consist any more: the ends are then those of what's coupled now + auto *first{snapshot::find_vehicle(Entry.text("front"))}; + auto *last{snapshot::find_vehicle(Entry.text("rear"))}; + if ((first != nullptr && Left(first)) || (last != nullptr && Left(last))) + { + // as CheckVehicles() finds them, from the end the consist goes to + auto end{CheckDirection() >= 0 ? 0 : 1}; + first = pVehicle->FirstFind(end); + if (first == nullptr) + first = pVehicle; + // from the head to the back, the coupler to go on through turned with each vehicle coupled the other way round; + // no further than FirstFind() looks, should the couplings close a ring + last = first; + auto side{1 - end}; + for (auto count{0}; count < 300; ++count) + { + auto *next{last->Neighbour(side)}; + if (next == nullptr) + break; + last = next; + } + } + if (first != nullptr) + pVehicles[VehicleEnd::front] = first; + if (last != nullptr) + pVehicles[VehicleEnd::rear] = last; + ControllingSet(); + if (auto ai{aiControlled}; Entry.get("ai", ai)) + { + aiControlled = ai; + pVehicle->Controller = ai; + } + // what's ahead on the track as the driver had it; without it the table is filled anew from where the train is now + if (false == snapshot_load_table(Entry)) + TableClear(); + eSignSkip = load_event(Entry, "signskip"); + // the hints of what the driver is about to do are for the player, and made again as the driver goes on + m_hints.clear(); + BrakeChargingPipeOverchargeStart.clear(); +} diff --git a/simulation/simulationsnapshotmover.cpp b/simulation/simulationsnapshotmover.cpp new file mode 100644 index 000000000..acdcaaab6 --- /dev/null +++ b/simulation/simulationsnapshotmover.cpp @@ -0,0 +1,27 @@ +/* +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 "simulation/simulationsnapshotmover.h" + +#include "physics/vehicle.h" + +namespace simulation::snapshot { + +void capture_mover(record &Entry, physics::Vehicle const &Mover) +{ + Mover.SnapshotSave(Entry); +} + +void apply_mover(physics::Vehicle &Mover, record const &Entry) +{ + Mover.SnapshotLoad(Entry); +} + +} // namespace simulation::snapshot diff --git a/simulation/simulationsnapshotmover.h b/simulation/simulationsnapshotmover.h new file mode 100644 index 000000000..c621d3788 --- /dev/null +++ b/simulation/simulationsnapshotmover.h @@ -0,0 +1,26 @@ +/* +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/. +*/ + +#pragma once + +#include "simulation/simulationsnapshot.h" +#include "utilities/Classes.h" + +// the part of a simulation snapshot held by the physics of a vehicle (physics::Vehicle): what it carries, how it moves, +// what its machinery is set to and the air in its brakes. the vehicle reads and writes its own state +// (physics::Vehicle::SnapshotSave(), SnapshotLoad(), physics/components/snapshot.cpp); these hand it the entry +namespace simulation::snapshot { + +// adds the state of the vehicle to its entry +void capture_mover(record &Entry, physics::Vehicle const &Mover); +// sets the vehicle to the state of the entry; what the entry doesn't have stays as the vehicle has it. +// the couplings aren't touched, they belong to the pair of vehicles (see plan_couplings()) +void apply_mover(physics::Vehicle &Mover, record const &Entry); + +} // namespace simulation::snapshot diff --git a/simulation/simulationsnapshotvehicle.cpp b/simulation/simulationsnapshotvehicle.cpp new file mode 100644 index 000000000..24d5ad8f6 --- /dev/null +++ b/simulation/simulationsnapshotvehicle.cpp @@ -0,0 +1,443 @@ +/* +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 "vehicle/DynObj.h" + +#include "physics/vehicle.h" +#include "simulation/simulation.h" +#include "simulation/simulationsnapshotmover.h" +#include "simulation/simulationsnapshotworld.h" +#include "vehicle/Driver.h" +#include "world/Track.h" + +#include +#include +#include + +// the part of a simulation snapshot kept by a vehicle of the scenery: where its axles are on the tracks, which way it +// faces, what it's coupled to, where it's bound for, and through its physics (simulationsnapshotmover.cpp) how fast +// it goes, what it carries and what its machinery is doing + +namespace { + +namespace snapshot = simulation::snapshot; + +// keys of the two axles and the two couplers: "track0", "coupler1flags" +std::string indexed(std::string_view const Part, int const Index, std::string_view const Key = {}) +{ + return std::format("{}{}{}", Part, Index, Key); +} + +void save_axle(snapshot::record &Entry, int const Index, TTrackFollower const &Axle) +{ + Entry.set(indexed("track", Index), snapshot::track_reference(Axle.GetTrack())); + Entry.set(indexed("at", Index), Axle.GetTranslation()); + Entry.set(indexed("dir", Index), Axle.GetDirection()); + if (auto const path{Axle.Path()}; path != 0) + Entry.set(indexed("path", Index), path); + // which events of the track the axle has yet to set off: of the trains with a driver, and of any vehicle + Entry.set(indexed("events", Index), Axle.EventFlags() | (Axle.EventallFlags() << 2)); + // the ways of the switches the axle ran over last, the oldest first: the axle behind it coming onto one of them + // after a throw is checked against them for running forked (world/switchfork.h) + auto const paths{Axle.Paths().entries()}; + for (std::size_t index{0}; index < paths.size(); ++index) + { + Entry.set(indexed("axle", Index, std::format("switch{}", index)), snapshot::track_reference(static_cast(paths[index].first))); + Entry.set(indexed("axle", Index, std::format("way{}", index)), paths[index].second); + } +} + +// the ways of the switches the axle ran over last as the entry has them; an entry without them leaves none +void load_paths(snapshot::record const &Entry, int const Index, TTrackFollower &Axle) +{ + switch_fork::path_memory paths; + for (std::size_t index{0}; index < switch_fork::path_memory::size; ++index) + { + auto const key{indexed("axle", Index, std::format("switch{}", index))}; + if (false == Entry.has(key)) + break; + auto const *track{snapshot::find_track(Entry.text(key))}; + if (track == nullptr || track->eType != tt_Switch) + { + Entry.refuse(key, "it isn't a switch of the scenery"); + continue; + } + if (auto way{0}; Entry.get(indexed("axle", Index, std::format("way{}", index)), way, 0, 1)) + paths.record(track, way); + } + Axle.SetPaths(paths); +} + +// where an entry has an axle +struct axle_place { + TTrack *track{nullptr}; + int path{0}; + double distance{0.0}; + double direction{1.0}; + int events{15}; + + bool put(TTrackFollower &Axle, double const Inset) const + { + // Inset keeps the axle off the very ends of the track + auto const length{track->Length()}; + auto const place{Inset > 0.0 && length > 2.0 * Inset ? std::clamp(distance, Inset, length - Inset) : distance}; + return Axle.Place(track, path, place, direction, events & 3, (events >> 2) & 3); + } +}; + +// returns: the place, without its track if the entry doesn't give one which can be used +axle_place read_axle(snapshot::record const &Entry, int const Index) +{ + axle_place place; + place.track = snapshot::find_track(Entry.text(indexed("track", Index))); + // the path is a segment of a switch (0, 1) or of a crossing (1..6, the sign the way through it), the events two + // pairs of flags. the axle is put at a distance along its track, which has to be a number + if (auto const usable{(Entry.get(indexed("path", Index), place.path, -6, 6) || false == Entry.has(indexed("path", Index))) && + (Entry.get(indexed("at", Index), place.distance, -1e7, 1e7) || false == Entry.has(indexed("at", Index))) && + (Entry.get(indexed("dir", Index), place.direction, -1e7, 1e7) || false == Entry.has(indexed("dir", Index))) && + (Entry.get(indexed("events", Index), place.events, 0, 15) || false == Entry.has(indexed("events", Index)))}; + false == usable) + place.track = nullptr; + return place; +} + +// where the axle is now +axle_place axle_at(TTrackFollower const &Axle) +{ + return {Axle.GetTrack(), Axle.Path(), Axle.GetTranslation(), Axle.GetDirection(), Axle.EventFlags() | (Axle.EventallFlags() << 2)}; +} + +// takes the vehicle off the list of the track it's on, if it's on it +void leave_track(TDynamicObject &Vehicle) +{ + if (Vehicle.MyTrack != nullptr && Vehicle.MyTrack->CheckDynamicObject(&Vehicle)) + Vehicle.MyTrack->RemoveDynamicObject(&Vehicle); + Vehicle.MyTrack = nullptr; +} + +// puts the axles of the vehicle at the places, and its body after them. returns: false if an axle can't be put there +bool put_axles(TDynamicObject &Vehicle, std::array const &Places) +{ + // the axles a hair off the ends of their tracks first, for the body of the vehicle to be worked out from them: + // Move() does that, and takes an axle standing at the very end of a track over to the next one + if (constexpr double inset{1e-6}; false == Places[0].put(Vehicle.Axle0, inset) || false == Places[1].put(Vehicle.Axle1, inset)) + return false; + // too short a way for the axles to move at all + Vehicle.Move(1e-300); + // then exactly where they were + Places[0].put(Vehicle.Axle0, 0.0); + Places[1].put(Vehicle.Axle1, 0.0); + return true; +} + +// the vehicle is on the list of the track its leading axle is on, and its physics where its body is +void settle(TDynamicObject &Vehicle) +{ + if (auto *track{Vehicle.iAxleFirst != 0 ? Vehicle.Axle1.GetTrack() : Vehicle.Axle0.GetTrack()}; track != nullptr && track != Vehicle.MyTrack) + { + leave_track(Vehicle); + track->AddDynamicObject(&Vehicle); + } + Vehicle.physics->SetLoc({-Vehicle.vPosition.x, Vehicle.vPosition.z, Vehicle.vPosition.y}); +} + +// the vehicle whose physics a coupler is joined to: the neighbour at that end as a rule, otherwise looked up +TDynamicObject const *coupled_vehicle(TCoupling const &Coupler, TDynamicObject const *Neighbour) +{ + if (Coupler.Connected == nullptr || Coupler.CouplingFlag.Empty()) + return nullptr; + if (Neighbour != nullptr && Neighbour->physics == Coupler.Connected) + return Neighbour; + auto const &vehicles{simulation::Vehicles.sequence()}; + auto const lookup{std::ranges::find_if(vehicles, [&](TDynamicObject const *Vehicle) { return Vehicle != nullptr && Vehicle->physics == Coupler.Connected; })}; + return lookup != vehicles.end() ? *lookup : nullptr; +} + +void save_coupler(snapshot::record &Entry, int const Index, TCoupling const &Coupler, TDynamicObject const *Neighbour) +{ + Neighbour = coupled_vehicle(Coupler, Neighbour); + auto const coupled{Neighbour != nullptr}; + // an end with nothing coupled says so too: the snapshot knows the vehicle stands free there + Entry.set(indexed("coupler", Index), coupled ? snapshot::vehicle_reference(Neighbour) : std::string{}); + Entry.set(indexed("coupler", Index, "end"), coupled ? Coupler.ConnectedNr : 0); + Entry.set(indexed("coupler", Index, "flags"), coupled ? Coupler.CouplingFlag.Bits() : 0); +} + +} // namespace + +// what the vehicle keeps of its machinery beside its physics: the pantographs as they stand, the passengers getting on and off +void TDynamicObject::snapshot_save_machinery(simulation::snapshot::record &Entry) const +{ + Entry.set("overheadmask", iOverheadMask); + Entry.set("novolttime", NoVoltTime); + for (auto index{0}; index < iAnimType[ANIM_PANTS] && pants != nullptr; ++index) + { + auto const *pantograph{pants[index].fParamPants}; + if (pantograph == nullptr) + continue; + Entry.set(indexed("pant", index, "anglel"), pantograph->fAngleL); + Entry.set(indexed("pant", index, "angleu"), pantograph->fAngleU); + Entry.set(indexed("pant", index, "height"), pantograph->PantWys); + Entry.set(indexed("pant", index, "wire"), pantograph->PantTraction); + Entry.set(indexed("pant", index, "novolttime"), pantograph->NoVoltTime); + } + if (auto const &exchange{m_exchange}; exchange.unload_count != 0.f || exchange.load_count != 0.f) + { + Entry.set("exchangeunload", exchange.unload_count).set("exchangeload", exchange.load_count); + Entry.set("exchangeplatforms", exchange.platforms).set("exchangetime", exchange.time); + } + // the rails under the wheel sets: the length of a rail, and for each wheel set how far along its rail it is and + // whether that's by the joints of the track. a joint of a worn track jolts the vehicle + Entry.set("raillength", dRailLength); + if (false == m_axlesounds.empty()) + { + std::vector joints; + for (auto const &axle : m_axlesounds) + { + joints.emplace_back(axle.distance); + joints.emplace_back(axle.atjoints ? 1.0 : 0.0); + } + Entry.set("railjoints", snapshot::numbers_text(joints)); + } + // the lighting of the compartments: which of them are lit is drawn at random when it comes on + Entry.set("sectionlights", SectionLightsActive); + if (false == Sections.empty()) + { + std::vector levels; + for (auto const §ion : Sections) + levels.emplace_back(section.light_level); + Entry.set("sectionlightlevels", snapshot::numbers_text(levels)); + } + Entry.set("dimheadlights", DimHeadlights).set("highbeamlights", HighBeamLights); + Entry.set("headlightsaoff", HeadlightsAoff).set("headlightsboff", HeadlightsBoff); + // the force the electrodynamic brake of a unit was asked for in the step before, which the next one is held to + if (brakeBlending.LastElectrodynamicDemand() != 0.0) + Entry.set("medoldfed", brakeBlending.LastElectrodynamicDemand()); + // the derailment the scenery and the test mode were told of (new_derailment()): told once, it isn't told again + if (m_derailment.has_value()) + { + Entry.set("derailtold", static_cast(m_derailment->why)).set("derailtoldtrack", m_derailment->track); + Entry.set("derailtoldvelocity", m_derailment->velocity); + } + // off the track: how long, when it's told of in the log next, the move along the track its axles haven't made yet and + // where its body was when they last did + if (physics->OffTrack.active()) + { + Entry.set("offtracktime", m_offtracktotal).set("offtracklog", m_offtracklogdue).set("offtrackaxles", m_offtrackaxles); + Entry.set("offtrackfrom", snapshot::numbers_text(std::array{m_offtrackfrom.x, m_offtrackfrom.y, m_offtrackfrom.z})); + } + // a switch thrown under the train (world/switchfork.h): the switch the bogies of the vehicle, or an end of it and + // the vehicle coupled there, run forked on, and whether that came past what the vehicle takes and was told of + auto const save_fork = [&Entry](std::string const &Key, fork_watch const &Watch) { + if (Watch.Switch != nullptr) + Entry.set(Key, snapshot::track_reference(Watch.Switch)).set(Key + "told", Watch.told); + }; + save_fork("forkbogies", m_forkbogies); + for (auto const end : VehicleEnds) + save_fork(indexed("fork", NumberOf(end)), m_forkends[end]); +} + +void TDynamicObject::snapshot_load_machinery(simulation::snapshot::record const &Entry) +{ + Entry.get("overheadmask", iOverheadMask); + Entry.get("novolttime", NoVoltTime); + for (auto index{0}; index < iAnimType[ANIM_PANTS] && pants != nullptr; ++index) + { + auto *pantograph{pants[index].fParamPants}; + if (pantograph == nullptr) + continue; + Entry.get(indexed("pant", index, "anglel"), pantograph->fAngleL); + Entry.get(indexed("pant", index, "angleu"), pantograph->fAngleU); + Entry.get(indexed("pant", index, "height"), pantograph->PantWys); + Entry.get(indexed("pant", index, "wire"), pantograph->PantTraction); + Entry.get(indexed("pant", index, "novolttime"), pantograph->NoVoltTime); + } + auto &exchange{m_exchange}; + exchange = {}; + // the counts of the passengers getting off and on are counted down step by step + constexpr auto most_passengers{1e6f}; + Entry.get("exchangeunload", exchange.unload_count, -most_passengers, most_passengers); + Entry.get("exchangeload", exchange.load_count, -most_passengers, most_passengers); + Entry.get("exchangeplatforms", exchange.platforms); + Entry.get("exchangetime", exchange.time); + Entry.get("raillength", dRailLength, -1.0, 1e6); + if (auto const joints{snapshot::text_numbers(Entry.text("railjoints"))}; joints.size() == 2 * m_axlesounds.size()) + { + for (std::size_t index{0}; index < m_axlesounds.size(); ++index) + { + m_axlesounds[index].distance = joints[2 * index]; + m_axlesounds[index].atjoints = joints[2 * index + 1] != 0.0; + } + } + Entry.get("sectionlights", SectionLightsActive); + if (auto const levels{snapshot::text_numbers(Entry.text("sectionlightlevels"))}; levels.size() == Sections.size()) + { + for (std::size_t index{0}; index < levels.size(); ++index) + Sections[index].light_level = static_cast(levels[index]); + } + Entry.get("dimheadlights", DimHeadlights); + Entry.get("highbeamlights", HighBeamLights); + Entry.get("headlightsaoff", HeadlightsAoff); + Entry.get("headlightsboff", HeadlightsBoff); + brakeBlending.RestoreLastElectrodynamicDemand(Entry.value("medoldfed", 0.0, -1e9, 1e9)); + m_derailment.reset(); + if (auto why{0}; Entry.get("derailtold", why, 1, static_cast(derailment::reason::other))) + { + std::string track; + Entry.get("derailtoldtrack", track); + m_derailment = derailment::notice{asName, static_cast(why), track, Entry.value("derailtoldvelocity", 0.0)}; + } + else if (false == Entry.has("derailtold") && physics->DamageFlag.HasAll(VehicleDamage::derailed)) + { + // a snapshot written before this was kept: a vehicle derailed then isn't told of again + new_derailment(); + } + if (physics->OffTrack.active()) + { + Entry.get("offtracktime", m_offtracktotal); + Entry.get("offtracklog", m_offtracklogdue); + Entry.get("offtrackaxles", m_offtrackaxles); + if (auto const from{snapshot::text_numbers(Entry.text("offtrackfrom"))}; from.size() == 3) + m_offtrackfrom = {from[0], from[1], from[2]}; + else + m_offtrackfrom = physics->OffTrack.current().position; + // the terrain it slides over, gathered anew around where it is, as when it left the rails + gather_off_track_terrain(); + m_offtracksite = derail_motion::site{m_offtrackterrain.get(), track_bed()}; + if (physics->OffTrack.at_rest()) + crop_off_track_terrain(); + } + auto const load_fork = [&Entry](std::string const &Key, fork_watch &Watch) { + Watch = {}; + if (false == Entry.has(Key)) + return; + auto const *track{snapshot::find_track(Entry.text(Key))}; + if (track == nullptr || track->eType != tt_Switch) + { + Entry.refuse(Key, "it isn't a switch of the scenery"); + return; + } + Watch.Switch = track; + Entry.get(Key + "told", Watch.told); + }; + load_fork("forkbogies", m_forkbogies); + for (auto const end : VehicleEnds) + load_fork(indexed("fork", NumberOf(end)), m_forkends[end]); +} + +void TDynamicObject::snapshot_save(simulation::snapshot::record &Entry) const +{ + if (false == bEnabled) + { + // gone from the simulation, through a portal say + Entry.set("removed", true); + return; + } + // place + save_axle(Entry, 0, Axle0); + save_axle(Entry, 1, Axle1); + Entry.set("first", iAxleFirst); + Entry.set("facing", iDirection); + // where that is in the world: the reader of the file sees it, and a loaded snapshot is checked against it + Entry.set("x", vPosition.x).set("y", vPosition.y).set("z", vPosition.z); + // physics.derailment new, off the track: its body on the ground, which the place above is the place of + if (physics->OffTrack.active()) + Entry.set("offtrack", snapshot::numbers_text(physics->OffTrack.state())); + // consist + for (auto const side : VehicleEnds) + save_coupler(Entry, NumberOf(side), physics->Couplers[side], physics->Neighbours[side].vehicle); + if (ctOwner != nullptr && ctOwner->Vehicle() != nullptr) + Entry.set("owner", snapshot::vehicle_reference(ctOwner->Vehicle())); + Entry.set("destination", asDestination); + // the physics + snapshot::capture_mover(Entry, *physics); + snapshot_save_machinery(Entry); +} + +bool TDynamicObject::snapshot_place(simulation::snapshot::record const &Entry) +{ + if (Entry.value("removed", false)) + { + if (false == bEnabled) + return true; + // the vehicle left the simulation before the snapshot was taken: off the track, and off the list at the next update + leave_track(*this); + // the scenery counted its axles in the isolated sections of the tracks it put it on, the run the snapshot comes + // from counted them out as the train drove off. the events are held while a snapshot is put back, and the saved + // cells and queue carry what followed from it + for (auto const *axle : {&Axle0, &Axle1}) + { + if (auto *track{axle->GetTrack()}; track != nullptr) + track->AxleCounter(-1, this); + } + // nobody's in charge of it: its driver, if it had one, doesn't go on (apply_drivers()) + ctOwner = nullptr; + bEnabled = false; + bDynamicRemove = true; + return true; + } + auto const places{std::array{read_axle(Entry, 0), read_axle(Entry, 1)}}; + if (places[0].track == nullptr || places[1].track == nullptr) + return false; + + // where the scenery put the vehicle, for it to stay there if it can't be put where the snapshot has it + auto const scenery{std::array{axle_at(Axle0), axle_at(Axle1)}}; + auto const facing{iDirection}; + auto const first{iAxleFirst}; + // which of the ends of the vehicle leads in its consist, which of its axles is the first: 0 or 1 + Entry.get("facing", iDirection, 0, 1); + if (put_axles(*this, places)) + { + Entry.get("first", iAxleFirst, 0, 1); + // a vehicle off the track: its axles go along the track beside it, its body is where its motion on the ground has it + if (Entry.has("offtrack")) + { + if (physics->OffTrack.state(snapshot::text_numbers(Entry.text("offtrack"))) && physics->OffTrack.active()) + place_off_track(); + else + Entry.refuse("offtrack", "it isn't the motion of a vehicle off the track"); + } + // a track named by its place in the scenery ("#12") is another one after a track was added before it: the + // place in the world the entry gives tells + if (snapshot::placed_where_saved(Entry, vPosition.x, vPosition.y, vPosition.z)) + { + load_paths(Entry, 0, Axle0); + load_paths(Entry, 1, Axle1); + settle(*this); + return true; + } + Entry.refuse("x", std::format("the vehicle put on track {} is more than {} m from there", Entry.text("track0"), snapshot::misplaced_distance)); + } + // back where the scenery put it, on the rails + physics->OffTrack.reset(); + m_offtrackplaced = false; + iDirection = facing; + iAxleFirst = first; + if (scenery[0].track != nullptr && scenery[1].track != nullptr) + put_axles(*this, scenery); + settle(*this); + return false; +} + +void TDynamicObject::snapshot_load(simulation::snapshot::record const &Entry) +{ + if (false == bEnabled) + return; + Entry.get("destination", asDestination); + + snapshot::apply_mover(*physics, Entry); + // a load of another kind than the scenery gave comes with its model. it's loaded here and not by the first frame: + // laying the load out in the vehicle draws at random, which doesn't count while a snapshot is put back + if (physics->LoadTypeChange()) + LoadUpdate(); + update_load_visibility(); + + snapshot_load_machinery(Entry); +} diff --git a/simulation/simulationsnapshotworld.cpp b/simulation/simulationsnapshotworld.cpp new file mode 100644 index 000000000..d17ebadda --- /dev/null +++ b/simulation/simulationsnapshotworld.cpp @@ -0,0 +1,1416 @@ +/* +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 "simulation/simulationsnapshotworld.h" + +#include "physics/vehicle.h" +#include "application/uitranscripts.h" +#include "model/AnimModel.h" +#include "simulation/simulation.h" +#include "simulation/simulationenvironment.h" +#include "simulation/simulationtest.h" +#include "simulation/simulationtime.h" +#include "utilities/Globals.h" +#include "utilities/Logs.h" +#include "utilities/Timer.h" +#include "utilities/utilities.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/EvLaunch.h" +#include "world/Event.h" +#include "world/MemCell.h" +#include "world/Track.h" +#include "world/TractionPower.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace simulation::snapshot { + +namespace { + +// the cells the simulation itself writes each frame: the weather, the time and the date for the scripts +constexpr std::string_view scripting_cells{"__simulation."}; +// a speed limit beyond any a track has: a value of the file past it is refused +constexpr double big_velocity{1e6}; +// the most events sharing a name a snapshot looks among, the most seconds an event waits in the queue +constexpr int most_siblings{100000}; +constexpr double longest_wait{1e9}; + +// the place of each thing of a table, to name the ones without a name of their own +template class table_index { + +public: + // the place of the item in the sequence, or the size of the sequence for an item which isn't there + template std::size_t of(Sequence_ const &Sequence, Item_ const *Item) + { + if (auto const place{known(Sequence, Item)}; place < Sequence.size()) + return place; + // the table has grown, or it's the table of another scenery now + m_places.clear(); + std::size_t place{0}; + for (auto const *item : Sequence) + m_places.emplace(item, place++); + return known(Sequence, Item); + } + +private: + template std::size_t known(Sequence_ const &Sequence, Item_ const *Item) const + { + auto const lookup{m_places.find(Item)}; + return lookup != m_places.end() && lookup->second < Sequence.size() && Sequence[lookup->second] == Item ? lookup->second : Sequence.size(); + } + + std::unordered_map m_places; +}; + +// a thing of a table by its reference: its name, or its place +template auto find_in(Table_ const &Table, std::string const &Reference) -> decltype(Table.find(Reference)) +{ + if (auto const index{reference_index(Reference)}; index.has_value()) + return *index < Table.sequence().size() ? Table.sequence()[*index] : nullptr; + return Table.find(Reference); +} + +template std::string reference_in(Table_ const &Table, table_index &Index, Item_ const *Item) +{ + if (Item == nullptr) + return {}; + auto const place{Index.of(Table.sequence(), Item)}; + if (place >= Table.sequence().size()) + return {}; + return reference(Item->name(), place, Table.find(Item->name()) == Item); +} + +table_index &track_index() +{ + static table_index index; + return index; +} + +table_index &vehicle_index() +{ + static table_index index; + return index; +} + +table_index &powersource_index() +{ + static table_index index; + return index; +} + +table_index &model_index() +{ + static table_index index; + return index; +} + +// a track the simulation made on the run, where a track of the scenery ends: the loop a road vehicle turns back on, +// the track a train runs off the rails along (TTrack::NullCreate()) +bool made_on_the_run(TTrack const &Track) +{ + return (Track.iCategoryFlag & 0x80) != 0; +} + +// what the scenery is made of, by which a snapshot tells whether it's put over the scenery it was taken in +void capture_fingerprint(record &Header) +{ + name_hash names; + auto switches{0}; + auto tracks{0}; + for (auto const *track : Paths.sequence()) + { + // the tracks made on the run aren't the scenery's + if (track == nullptr || made_on_the_run(*track)) + continue; + ++tracks; + names.add(track->name()); + if (track->eType == tt_Switch) + ++switches; + } + for (auto const *cell : Memory.sequence()) + names.add(cell != nullptr ? cell->name() : std::string{}); + for (auto const *scenery_event : Events.sequence()) + names.add(scenery_event != nullptr ? scenery_event->m_name : std::string{}); + for (auto const *vehicle : Vehicles.sequence()) + names.add(vehicle != nullptr ? vehicle->name() : std::string{}); + Header.set("tracks", tracks); + Header.set("switches", switches); + Header.set("memcells", Memory.sequence().size()); + Header.set("events", Events.sequence().size()); + Header.set("launchers", Events.launchers().size()); + Header.set("vehicles", Vehicles.sequence().size()); + Header.set("names", names.text()); +} + +void capture_header(document &Document) +{ + auto &header{Document.add("snapshot", std::to_string(format_version))}; + header.set("scenery", Global.SceneryFile); + header.set("seed", Global.random_seed); + header.set("timer", Timer::GetTime()); + capture_fingerprint(header); +} + +void capture_time(document &Document) +{ + auto const &time{Time.data()}; + auto &entry{Document.add("time", "now")}; + entry.set("year", time.wYear).set("month", time.wMonth).set("day", time.wDay).set("weekday", time.wDayOfWeek); + entry.set("hour", time.wHour).set("minute", time.wMinute).set("second", time.wSecond).set("milliseconds", Time.milliseconds()); +} + +bool apply_time(record const &Entry) +{ + // the month and the day pick entries of the tables of the clock: a date which isn't one is refused whole + auto time{Time.data()}; + if (false == Entry.get("year", time.wYear, WORD{1}, WORD{9999}) && Entry.has("year")) + return false; + if (false == Entry.get("month", time.wMonth, WORD{1}, WORD{12}) && Entry.has("month")) + return false; + if (constexpr std::array days{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + false == Entry.get("day", time.wDay, WORD{1}, days[time.wMonth]) && Entry.has("day")) + return false; + if (time.wMonth == 2 && time.wDay == 29 && false == ((time.wYear % 4 == 0 && time.wYear % 100 != 0) || time.wYear % 400 == 0)) + { + Entry.refuse("day", "the year isn't a leap one"); + return false; + } + auto milliseconds{Time.milliseconds()}; + if ((false == Entry.get("weekday", time.wDayOfWeek, WORD{0}, WORD{6}) && Entry.has("weekday")) || + (false == Entry.get("hour", time.wHour, WORD{0}, WORD{23}) && Entry.has("hour")) || + (false == Entry.get("minute", time.wMinute, WORD{0}, WORD{59}) && Entry.has("minute")) || + (false == Entry.get("second", time.wSecond, WORD{0}, WORD{59}) && Entry.has("second")) || + (false == Entry.get("milliseconds", milliseconds, 0.0, 999.999999) && Entry.has("milliseconds"))) + return false; + Time.restore(time, milliseconds); + // the season goes by the date, and the weather by the season + Environment.compute_season(Time.year_day()); + return true; +} + +void capture_weather(document &Document) +{ + auto &entry{Document.add("weather", "now")}; + entry.set("overcast", Global.Overcast).set("fog", Global.fFogEnd).set("temperature", Global.AirTemperature); + // the wind: it changes now and then, by numbers drawn at random + std::vector wind; + for (auto const value : Environment.wind_state()) + wind.emplace_back(value); + entry.set("wind", numbers_text(wind)); +} + +void apply_weather(record const &Entry) +{ + // the weather is drawn from these: a number which isn't one has no place in it + constexpr auto big{1e9f}; + Entry.get("overcast", Global.Overcast, 0.f, 10.f); + Entry.get("fog", Global.fFogEnd, 0.f, big); + Entry.get("temperature", Global.AirTemperature, -100.f, 100.f); + Environment.compute_weather(); + auto state{Environment.wind_state()}; + if (auto const wind{text_numbers(Entry.text("wind"))}; wind.size() == state.size()) + { + if (std::ranges::all_of(wind, [](double const Value) { return std::isfinite(Value) && std::abs(Value) < 1e9; })) + { + std::ranges::transform(wind, state.begin(), [](double const Value) { return static_cast(Value); }); + Environment.wind_state(state); + } + else + Entry.refuse("wind", "a number of it isn't finite"); + } +} + +// the sources of the traction power: the voltage an event may have set, the load of the step before, the fuses +void capture_power(document &Document) +{ + // what a source which has fed nothing yet says of itself, but for its voltage + std::vector const idle{0.0, 1e-10, 1e-10, 0.0, 0.0, 0.0, 0.0, 0.0}; + for (auto const *source : Powergrid.sequence()) + { + if (source == nullptr) + continue; + auto const state{source->state()}; + // the sources made for single wires are many, and most of them idle + if (source->IsAutogenerated && std::ranges::equal(state.begin() + 1, state.end(), idle.begin(), idle.end())) + continue; + if (auto const name{reference_in(Powergrid, powersource_index(), source)}; false == name.empty()) + Document.add("powersource", name).set("state", numbers_text(state)); + } +} + +bool apply_power(record const &Entry) +{ + auto *source{find_in(Powergrid, Entry.name)}; + if (source == nullptr) + return false; + auto const state{text_numbers(Entry.text("state"))}; + // the last one counts the times the fuse blew + if (false == state.empty() && false == whole_number(state.back(), 0, std::numeric_limits::max()).has_value()) + { + Entry.refuse("state", "the count of its fuse isn't a whole number"); + return true; + } + source->state(state); + return true; +} + +// the engine the simulation draws its random numbers from, as the numbers of its state, eight to a line +void capture_random(document &Document) +{ + std::ostringstream state; + state << Global.random_engine; + std::istringstream numbers{state.str()}; + std::string text; + std::string number; + auto count{0}; + while (numbers >> number) + { + if (false == text.empty()) + text += (count % 8 == 0 ? "\n " : " "); + text += number; + ++count; + } + Document.add("random", "engine").set("state", text); +} + +bool apply_random(record const &Entry) +{ + std::istringstream state{Entry.text("state")}; + auto engine{Global.random_engine}; // NOSONAR: a copy of the simulation's reproducible engine, which nothing secure uses + state >> engine; + if (state.fail()) + return false; + Global.random_engine = engine; + return true; +} + +void capture_memcells(document &Document) +{ + auto const &cells{Memory.sequence()}; + for (std::size_t index{0}; index < cells.size(); ++index) + { + auto const *cell{cells[index]}; + if (cell == nullptr || cell->name().starts_with(scripting_cells)) + continue; + auto &entry{Document.add("memcell", reference(cell->name(), index, Memory.find(cell->name()) == cell))}; + entry.set("text", cell->Text()).set("value1", cell->Value1()).set("value2", cell->Value2()); + if (false == cell->StopCommand()) + { + // the command of the cell isn't waiting to be sent to a train: it's not a command, or it was sent already + entry.set("sent", true); + } + } +} + +bool apply_memcell(record const &Entry) +{ + auto *cell{find_in(Memory, Entry.name)}; + if (cell == nullptr) + return false; + cell->UpdateValues(Entry.text("text", cell->Text()), Entry.value("value1", cell->Value1()), Entry.value("value2", cell->Value2()), + basic_event::flags::text | basic_event::flags::value1 | basic_event::flags::value2); + if (Entry.value("sent", false)) + cell->StopCommandSent(); + return true; +} + +void capture_tracks(document &Document) +{ + // what an event can change of a track: bit 0x100 of iAction marks the damage, 0x200 the speed limit + constexpr int changedbyevents{0x100 | 0x200}; + for (auto *track : Paths.sequence()) + { + if (track != nullptr && track->eType == tt_Switch) + Document.add("switch", track_reference(track)).set("state", track->GetSwitchState()).set("velocity", track->velocity_limit()); + } + for (auto const *track : Paths.sequence()) + { + if (track != nullptr && track->eType != tt_Switch && (track->iAction & changedbyevents) != 0) + Document.add("track", track_reference(track)).set("velocity", track->velocity_limit()).set("damage", track->iDamageFlag); + } +} + +// the crossings of roads: which of the ways through was taken last. the crossing has it as its current segment, by +// which a driver looking ahead measures it +void capture_crossings(document &Document) +{ + for (auto const *track : Paths.sequence()) + { + if (track == nullptr || track->eType != tt_Cross || track->SwitchExtension == nullptr) + continue; + auto const &segments{track->SwitchExtension->Segments}; + for (auto index{0}; index < 6; ++index) + { + if (segments[index] != nullptr && segments[index] == track->Segment) + { + Document.add("crossing", track_reference(track)).set("segment", index); + break; + } + } + } +} + +bool apply_crossing(record const &Entry) +{ + auto *track{find_track(Entry.name)}; + if (track == nullptr || track->eType != tt_Cross || track->SwitchExtension == nullptr) + return false; + auto const index{Entry.value("segment", -1, 0, 5)}; + if (index < 0 || track->SwitchExtension->Segments[index] == nullptr) + return false; + track->Segment = track->SwitchExtension->Segments[index]; + return true; +} + +// the tracks made on the run, each by the track of the scenery it was made at and the end of it. they come back in +// the order they were made in, which gives them their places in the table again +void capture_made_tracks(document &Document) +{ + for (auto const *made : Paths.sequence()) + { + if (made == nullptr || false == made_on_the_run(*made)) + continue; + for (auto const *track : Paths.sequence()) + { + if (track == nullptr || made_on_the_run(*track) || (track->trPrev != made && track->trNext != made)) + continue; + Document.add("madetrack", track_reference(track)).set("end", track->trPrev == made ? 0 : 1); + break; + } + } +} + +bool apply_made_track(record const &Entry) +{ + auto *track{find_track(Entry.name)}; + if (track == nullptr) + return false; + auto end{0}; + if (false == Entry.get("end", end, 0, 1) && Entry.has("end")) + return false; + // made anew unless the scenery has something there by now + if ((end == 0 ? track->trPrev : track->trNext) == nullptr) + track->NullCreate(end); + return true; +} + +bool apply_switch(record const &Entry) +{ + auto *track{find_track(Entry.name)}; + if (track == nullptr || track->eType != tt_Switch) + return false; + if (auto state{0}; Entry.get("state", state, 0, 1) && state != track->GetSwitchState()) + track->Switch(state); + if (auto velocity{0.0}; Entry.get("velocity", velocity, -big_velocity, big_velocity)) + track->velocity_limit(velocity); + return true; +} + +bool apply_track(record const &Entry) +{ + auto *track{find_track(Entry.name)}; + if (track == nullptr) + return false; + if (auto velocity{0.0}; Entry.get("velocity", velocity, -big_velocity, big_velocity)) + track->velocity_limit(velocity); + Entry.get("damage", track->iDamageFlag); + return true; +} + +void capture_events(document &Document) +{ + auto const now{Timer::GetTime()}; + for (auto const *queued{Events.begin()}; queued != nullptr; queued = queued->m_next) + { + auto &entry{Document.add("event", queued->m_name)}; + if (auto const sibling{event_sibling(queued)}; sibling != 0) + entry.set("sibling", sibling); + // when it runs, by the clock of the simulation; the seconds left are for the reader of the file + entry.set("at", queued->m_launchtime).set("left", queued->m_launchtime - now); + if (queued->m_activator != nullptr) + entry.set("activator", vehicle_reference(queued->m_activator)); + } +} + +bool apply_event(record const &Entry) +{ + auto sibling{0}; + if (false == Entry.get("sibling", sibling, 0, most_siblings) && Entry.has("sibling")) + return false; + auto *found{find_event(Entry.name, sibling)}; + if (found == nullptr) + return false; + // without the time it ran at, the seconds it had left count from now. the queue is kept in the order of the times, + // which a time that isn't a number has none in + auto const now{Timer::GetTime()}; + auto launchtime{now + Entry.value("left", 0.0, -longest_wait, longest_wait)}; + if (false == Entry.get("at", launchtime, now - longest_wait, now + longest_wait) && Entry.has("at")) + return false; + auto const *activator{Entry.has("activator") ? find_vehicle(Entry.text("activator")) : nullptr}; + return Events.restore_queued(found, activator, launchtime); +} + +void capture_launchers(document &Document) +{ + auto const launchers{Events.launchers()}; + std::map> named; + for (auto const *launcher : launchers) + { + if (launcher != nullptr) + ++named[launcher->name()]; + } + for (std::size_t index{0}; index < launchers.size(); ++index) + { + auto const *launcher{launchers[index]}; + // a launcher which hasn't counted any time yet is as the scenery makes it + if (launcher == nullptr || launcher->timer() == 0.0) + continue; + Document.add("launcher", reference(launcher->name(), index, named[launcher->name()] == 1 && launcher->name() != "none")).set("timer", launcher->timer()); + } +} + +bool apply_launcher(record const &Entry, std::vector const &Launchers) +{ + TEventLauncher *launcher{nullptr}; + if (auto const index{reference_index(Entry.name)}; index.has_value()) + launcher = (*index < Launchers.size() ? Launchers[*index] : nullptr); + else if (auto const lookup{std::ranges::find_if(Launchers, [&](TEventLauncher const *Item) { return Item != nullptr && Item->name() == Entry.name; })}; + lookup != Launchers.end()) + launcher = *lookup; + if (launcher == nullptr) + return false; + launcher->timer(Entry.value("timer", launcher->timer(), 0.0, longest_wait)); + return true; +} + +// the models whose lights the events of the scenery switch: the signals, mostly +std::vector switched_models() +{ + std::vector models; + std::unordered_set seen; + for (auto const *scenery_event : Events.sequence()) + { + if (dynamic_cast(scenery_event) == nullptr) + continue; + for (auto *node : scenery_event->target_nodes()) + { + if (seen.emplace(node).second) + models.emplace_back(static_cast(node)); + } + } + return models; +} + +void capture_lights(document &Document) +{ + for (auto *model : switched_models()) + { + auto const name{reference_in(Instances, model_index(), static_cast(model))}; + if (name.empty()) + continue; + record entry{"model", name}; + for (auto light{0}; light < iMaxNumLights; ++light) + { + if (auto const state{model->LightGet(light)}; state.has_value()) + entry.set(std::format("light{}", light), std::get<0>(*state)); + } + if (false == entry.fields.empty()) + Document.records.emplace_back(std::move(entry)); + } +} + +bool apply_lights(record const &Entry) +{ + auto *model{find_in(Instances, Entry.name)}; + if (model == nullptr) + return false; + for (auto light{0}; light < iMaxNumLights; ++light) + { + if (auto state{0.f}; Entry.get(std::format("light{}", light), state, -1e6f, 1e6f)) + model->LightSet(light, state); + } + return true; +} + +void capture_vehicles(document &Document) +{ + for (auto const *vehicle : Vehicles.sequence()) + { + if (vehicle == nullptr || vehicle->physics == nullptr) + continue; + vehicle->snapshot_save(Document.add("vehicle", vehicle_reference(vehicle))); + } +} + +// the couplings as the vehicles have them now +std::vector current_couplings(std::unordered_map const &Owners) +{ + std::vector links; + for (auto const *vehicle : Vehicles.sequence()) + { + if (vehicle == nullptr || vehicle->physics == nullptr) + continue; + for (auto const side : VehicleEnds) + { + auto const &joint{vehicle->physics->Couplers[side]}; + auto const owner{joint.Connected != nullptr ? Owners.find(joint.Connected) : Owners.end()}; + if (owner == Owners.end() || joint.CouplingFlag.Empty()) + continue; + links.emplace_back(vehicle_reference(vehicle), NumberOf(side), vehicle_reference(owner->second), joint.ConnectedNr, joint.CouplingFlag.Bits()); + } + } + return links; +} + +static_assert(coupling_flags_mask == (static_cast(Coupling::power3x400v) << 1) - 1, "the flags a snapshot takes are every bit of the coupling enum"); + +void part(TDynamicObject &Vehicle, int const End) +{ + auto &joint{Vehicle.physics->Couplers[End]}; + if (joint.Connected != nullptr && joint.ConnectedNr >= 0 && joint.ConnectedNr < 2) + { + auto &other{joint.Connected->Couplers[joint.ConnectedNr]}; + other.Connected = nullptr; + other.ConnectedNr = -1; + other.CouplingFlag = CouplingSet{}; + } + joint.Connected = nullptr; + joint.ConnectedNr = -1; + joint.CouplingFlag = CouplingSet{}; +} + +// whether the vehicle is there, with its physics +bool with_physics(TDynamicObject const *Vehicle) +{ + return Vehicle != nullptr && Vehicle->physics != nullptr; +} + +// the flags of the link as the two vehicles can have them now: no control between an electric and a diesel locomotive +// (eu07/maszyna#520), whatever an edited file or a vehicle definition changed since the snapshot says +int compatible_flags(TDynamicObject const &Vehicle, TDynamicObject const &Other, coupling_link const &Link) +{ + return Vehicle.physics->CompatibleCoupling(EndOf(Link.end), *Other.physics, EndOf(Link.otherend), CouplingSet::FromBits(Link.flags)).Bits(); +} + +// the links of the plan which change the kind of a coupling the vehicles keep +void change_couplings(std::vector const &Links) +{ + for (auto const &link : Links) + { + auto const *vehicle{find_vehicle(link.vehicle)}; + auto const *other{find_vehicle(link.other)}; + if (false == with_physics(vehicle) || false == with_physics(other)) + continue; + auto const flags{compatible_flags(*vehicle, *other, link)}; + if (flags == 0) + continue; + vehicle->physics->Couplers[link.end].CouplingFlag = CouplingSet::FromBits(flags); + other->physics->Couplers[link.otherend].CouplingFlag = CouplingSet::FromBits(flags); + } +} + +// the links of the plan to make. returns: how many couldn't be made +int join_couplings(std::vector const &Links) +{ + auto failed{0}; + for (auto const &link : Links) + { + auto *vehicle{find_vehicle(link.vehicle)}; + auto *other{find_vehicle(link.other)}; + if (false == with_physics(vehicle) || false == with_physics(other) || + false == vehicle->physics->Attach(link.end, link.otherend, other->physics, CouplingSet::FromBits(link.flags), true, false)) + { + ++failed; + continue; + } + // the vehicles joined in the snapshot, whatever the scenery made of their couplers, as far as they can be + auto const flags{compatible_flags(*vehicle, *other, link)}; + vehicle->physics->Couplers[link.end].CouplingFlag = CouplingSet::FromBits(flags); + other->physics->Couplers[link.otherend].CouplingFlag = CouplingSet::FromBits(flags); + } + return failed; +} + +void report_couplings(coupling_plan const &Plan, int const Failed, apply_summary &Summary) +{ + if (false == Plan.part.empty() || false == Plan.join.empty() || false == Plan.change.empty()) + Summary.remarks.emplace_back(std::format("couplings: {} parted, {} joined, {} changed", Plan.part.size(), static_cast(Plan.join.size()) - Failed, Plan.change.size())); + if (Failed != 0 || false == Plan.missing.empty()) + Summary.notes.emplace_back(std::format("couplings: {} of the snapshot couldn't be made, {} are to vehicles the scenery doesn't have or which stay where it put them", + Failed, Plan.missing.size())); + if (false == Plan.refused.empty()) + { + Summary.notes.emplace_back(std::format("couplings: {} of the snapshot refused, they'd close a ring of vehicles; the first one {} {} to {} {}", Plan.refused.size(), + Plan.refused.front().vehicle, Plan.refused.front().end, Plan.refused.front().other, Plan.refused.front().otherend)); + } +} + +// each vehicle knows the one coupled to it as its neighbour at that end +void find_neighbours(std::unordered_map const &Owners) +{ + for (auto *vehicle : Vehicles.sequence()) + { + if (vehicle == nullptr || vehicle->physics == nullptr) + continue; + for (auto const side : VehicleEnds) + { + auto const &joint{vehicle->physics->Couplers[side]}; + auto &neighbour{vehicle->physics->Neighbours[side]}; + neighbour = neighbour_data(); + if (auto const owner{joint.Connected != nullptr ? Owners.find(joint.Connected) : Owners.end()}; owner != Owners.end()) + { + neighbour.vehicle = owner->second; + neighbour.vehicle_end = joint.ConnectedNr; + } + } + } + for (auto *vehicle : Vehicles.sequence()) + { + if (vehicle != nullptr && vehicle->physics != nullptr && vehicle->bEnabled) + vehicle->update_neighbours(); + } +} + +// the vehicles of the snapshot which stay as the scenery made them: the ones it couldn't put where the snapshot has +// them, and the road traffic waiting at its spawn point +using vehicle_set = std::unordered_set; + +// parts and joins the vehicles of the scenery until they're coupled the way the snapshot has them. the vehicles Left +// aren't coupled to the ones put where the snapshot has them: the links to them are missing +void apply_couplings(std::vector const &Entries, vehicle_set const &Left, apply_summary &Summary) +{ + std::unordered_map owners; + std::vector present; + for (auto *vehicle : Vehicles.sequence()) + { + if (vehicle == nullptr || vehicle->physics == nullptr) + continue; + owners.emplace(vehicle->physics, vehicle); + if (false == Left.contains(vehicle)) + present.emplace_back(vehicle_reference(vehicle)); + } + std::vector entries; + std::ranges::copy_if(Entries, std::back_inserter(entries), [&Left](record const *Entry) { return false == Left.contains(find_vehicle(Entry->name)); }); + auto const plan{plan_couplings(current_couplings(owners), read_couplings(entries), present)}; + + // the vehicles of the links are of the scenery (Present), with their physics + for (auto const &link : plan.part) + { + if (auto *vehicle{find_vehicle(link.vehicle)}; with_physics(vehicle)) + part(*vehicle, link.end); + } + change_couplings(plan.change); + auto const failed{join_couplings(plan.join)}; + report_couplings(plan, failed, Summary); + find_neighbours(owners); +} + +// a vehicle the scenery keeps out of the simulation until its time comes: a car a road spawn point (roadpoint_node) made +// as the scenery loaded, which waits off the road to be put on it. the snapshot doesn't bring one which was on the +// road back: the spawn point puts its cars on the road and takes them back to its set, and a car put there by the +// snapshot would be one the point doesn't know is out +bool waits_off_the_road(TDynamicObject const &Vehicle) +{ + return false == Vehicle.bEnabled && Vehicle.MyTrack == nullptr; +} + +// the vehicles of the snapshot's entries +struct vehicle_entries { + std::vector> known; // to put where the snapshot has them + vehicle_set listed; // every vehicle of the scenery the snapshot has + vehicle_set left; // the ones of them left as the scenery made them +}; + +vehicle_entries read_vehicles(std::vector const &Entries, apply_summary &Summary) +{ + vehicle_entries result; + auto traffic{0}; + for (auto const *entry : Entries) + { + auto *vehicle{find_vehicle(entry->name)}; + if (vehicle == nullptr || vehicle->physics == nullptr) + { + ++Summary.skipped; + Summary.notes.emplace_back(std::format("vehicle {} of the snapshot isn't in the scenery", entry->name)); + continue; + } + // a vehicle placed twice would have its axles counted out of their sections twice + if (false == result.listed.emplace(vehicle).second) + { + ++Summary.skipped; + Summary.notes.emplace_back(std::format("vehicle {} has more than one entry in the snapshot, the first one is taken", entry->name)); + continue; + } + if (false == waits_off_the_road(*vehicle)) + { + result.known.emplace_back(vehicle, entry); + continue; + } + // off the road in the snapshot too, or a car of the road traffic which isn't brought back + result.left.emplace(vehicle); + if (entry->value("removed", false)) + { + ++Summary.entries; + continue; + } + ++Summary.skipped; + ++traffic; + } + if (traffic != 0) + Summary.notes.emplace_back(std::format("{} cars of the road traffic of the snapshot aren't put back, their spawn points send cars anew", traffic)); + return result; +} + +// puts the vehicles of the snapshot in place. returns: the vehicles of the snapshot left as the scenery made them +vehicle_set apply_vehicles(document const &Document, apply_summary &Summary) +{ + auto const entries{Document.of("vehicle")}; + auto vehicles{read_vehicles(entries, Summary)}; + auto const &known{vehicles.known}; + auto const &listed{vehicles.listed}; + auto &left{vehicles.left}; + // where the vehicles are, then what they're coupled to, then what they're doing. a vehicle which can't be put where + // the snapshot has it is left out of the rest: coupled to vehicles put elsewhere, it'd be torn off them + auto misplaced{0}; + for (auto const &[vehicle, entry] : known) + { + if (false == vehicle->snapshot_place(*entry)) + { + ++misplaced; + left.emplace(vehicle); + } + } + if (misplaced != 0) + Summary.notes.emplace_back(std::format("{} vehicles of the snapshot couldn't be put where it has them, they stay as the scenery made them", misplaced)); + apply_couplings(entries, left, Summary); + for (auto const &[vehicle, entry] : known) + { + if (left.contains(vehicle)) + { + ++Summary.skipped; + continue; + } + vehicle->snapshot_load(*entry); + ++Summary.entries; + } + // the vehicles the snapshot doesn't know stay as the scenery made them + if (auto const unknown{std::ranges::count_if(Vehicles.sequence(), [&](TDynamicObject const *Vehicle) { return Vehicle != nullptr && false == listed.contains(Vehicle); })}; + unknown != 0) + Summary.notes.emplace_back(std::format("{} vehicles of the scenery aren't in the snapshot, they stay as the scenery made them", unknown)); + return std::move(left); +} + +// a hash of the text of a name, which finds a string key by any kind of string +struct name_hash { + using is_transparent = void; + std::size_t operator()(std::string_view const Name) const noexcept { return std::hash{}(Name); } +}; + +using isolated_map = std::unordered_map>; + +// the isolated sections, by their names: the scenery makes one for each name (TIsolated::Find()) +isolated_map isolated_sections() +{ + isolated_map sections; + for (auto *section{TIsolated::Root()}; section != nullptr; section = section->Next()) + sections.try_emplace(section->asName, section); + return sections; +} + +// how many axles each isolated section counts. in a running simulation it's the vehicles on its tracks, but not only: +// the vehicles of a consist which follow its first one out through a portal leave the simulation where they are, and +// stay counted there. a snapshot keeps the counts as they are +void capture_isolated(document &Document) +{ + for (auto *section{TIsolated::Root()}; section != nullptr; section = section->Next()) + Document.add("isolated", section->asName).set("axles", section->axles()); +} + +// how many axles more or fewer each isolated section counts than the snapshot has, for the axles of the vehicles left as +// the scenery made them: they stand where the scenery put them, not where the snapshot has them +using section_counts = std::unordered_map; + +// counts Axles in every section of the Track and in the sections those pass their counts to (TIsolated::Modify()) +void count_axles(TTrack const *Track, int const Axles, section_counts &Counts) +{ + if (Track == nullptr) + return; + for (auto *section : Track->Isolated) + { + for (; section != nullptr; section = section->parent()) + Counts[section] += Axles; + } +} + +// the axles of the Left vehicles: counted in the sections they stand in now, and out of the ones the snapshot has them in +section_counts left_axles(document const &Document, vehicle_set const &Left) +{ + section_counts counts; + if (Left.empty()) + return counts; + vehicle_set seen; + for (auto const *entry : Document.of("vehicle")) + { + // the first entry of a vehicle is the one taken (read_vehicles()) + auto const *vehicle{find_vehicle(entry->name)}; + if (vehicle == nullptr || false == Left.contains(vehicle) || false == seen.emplace(vehicle).second) + continue; + // a car off the road waits in its spawn point's set, on no track + if (vehicle->MyTrack != nullptr) + { + count_axles(vehicle->Axle0.GetTrack(), 1, counts); + count_axles(vehicle->Axle1.GetTrack(), 1, counts); + } + if (false == entry->value("removed", false)) + { + count_axles(find_track(entry->text("track0")), -1, counts); + count_axles(find_track(entry->text("track1")), -1, counts); + } + } + std::erase_if(counts, [](auto const &Count) { return Count.second == 0; }); + return counts; +} + +// sets the counts of the isolated sections to those of the snapshot, after the vehicles are put on their tracks: which +// counts them anew. a section whose count comes out other than the snapshot has is told of. the axles of the vehicles +// left as the scenery made them (Left) are counted where they stand instead of where the snapshot has them. returns: +// the sections whose counts that changed +std::vector apply_isolated(document const &Document, section_counts const &Left, apply_summary &Summary) +{ + std::vector moved; + auto const entries{Document.of("isolated")}; + if (entries.empty()) + return moved; + auto const sections{isolated_sections()}; + auto missing{0}; + auto differing{0}; + std::string example; + for (auto const *entry : entries) + { + auto const lookup{sections.find(entry->name)}; + if (lookup == sections.end()) + { + ++Summary.skipped; + ++missing; + continue; + } + // a count beyond any the vehicles of a scenery make + auto axles{0}; + if (false == entry->get("axles", axles, -1000000, 1000000)) + { + ++Summary.skipped; + continue; + } + auto *section{lookup->second}; + if (auto const left{Left.find(section)}; left != Left.end()) + { + // no fewer than none: a snapshot taken in another scenery can name a track the vehicle wasn't on + axles = std::max(axles + left->second, 0); + moved.emplace_back(section); + } + if (section->axles() != axles) + { + if (differing++ == 0) + example = std::format("{}: {} axles, the snapshot has {}", section->asName, section->axles(), axles); + section->axles(axles); + } + ++Summary.entries; + } + if (missing != 0) + Summary.notes.emplace_back(std::format("{} isolated sections of the snapshot aren't in the scenery", missing)); + if (false == moved.empty()) + Summary.notes.emplace_back(std::format("{} isolated sections count the axles of vehicles left where the scenery put them instead of where the snapshot has them; the first one {}", + moved.size(), moved.front()->asName)); + // not a fault as such: the vehicles a consist leaves behind as it goes through a portal stay counted where they were + if (differing != 0) + Summary.remarks.emplace_back(std::format("{} isolated sections counted other axles with the vehicles placed than the snapshot has, set to its counts; the first one {}", + differing, example)); + return moved; +} + +// the cells of the sections whose counts the left vehicles changed say whether they're taken by the count, not by the +// snapshot: as TIsolated::Modify() writes them, the lowest bits of the second value +void apply_isolated_cells(std::vector const &Sections) +{ + for (auto const *section : Sections) + { + if (section->pMemCell == nullptr) + continue; + auto const value{static_cast(section->pMemCell->Value2())}; + auto const busy{section->axles() > 0}; + if (busy != ((value & 1) != 0)) + section->pMemCell->UpdateValues("", 0, busy ? value | 1 : value & ~0xFF, basic_event::flags::value2); + } +} + +void capture_drivers(document &Document) +{ + for (auto const *vehicle : Vehicles.sequence()) + { + if (vehicle != nullptr && vehicle->bEnabled && vehicle->Mechanik != nullptr) + vehicle->Mechanik->snapshot_save(Document.add("driver", vehicle_reference(vehicle))); + } +} + +// a driver of the consist of the vehicle whom the snapshot doesn't have where the scenery put them: the one to move +// to the vehicle, where the snapshot has a driver and the scenery none (a driver changes ends of a train) +TController *spare_driver(TDynamicObject *Vehicle, std::unordered_set const &Taken) +{ + TController *found{nullptr}; + Vehicle->for_each(Coupling::coupler, [&found, &Taken](TDynamicObject const *Coupled) { + if (found == nullptr && Coupled->Mechanik != nullptr && false == Taken.contains(Coupled)) + found = Coupled->Mechanik; + }); + return found; +} + +// the drivers of the snapshot, in the vehicles it has them in. the vehicles Left keep the drivers the scenery gave them +void apply_drivers(document const &Document, vehicle_set const &Left, apply_summary &Summary) +{ + auto const entries{Document.of("driver")}; + if (entries.empty()) + return; + // the vehicles the snapshot has drivers in + std::unordered_set taken; + for (auto const *entry : entries) + taken.emplace(find_vehicle(entry->name)); + auto missing{0}; + for (auto const *entry : entries) + { + auto *vehicle{find_vehicle(entry->name)}; + if (Left.contains(vehicle)) + { + ++Summary.skipped; + continue; + } + if (vehicle == nullptr) + { + ++Summary.skipped; + ++missing; + continue; + } + if (vehicle->Mechanik == nullptr) + { + if (auto *spare{spare_driver(vehicle, taken)}; spare != nullptr) + spare->MoveTo(vehicle); + } + if (vehicle->Mechanik == nullptr) + { + ++Summary.skipped; + ++missing; + continue; + } + vehicle->Mechanik->snapshot_load(*entry, [&Left](TDynamicObject const *Vehicle) { return Left.contains(Vehicle); }); + ++Summary.entries; + } + if (missing != 0) + Summary.notes.emplace_back(std::format("{} drivers of the snapshot have no driver in the scenery to become", missing)); + // the drivers of the scenery the snapshot has no word of, in vehicles it does know, were gone when it was taken + std::unordered_set known; + for (auto const *entry : Document.of("vehicle")) + known.emplace(find_vehicle(entry->name)); + std::unordered_set deleted; + for (auto *vehicle : Vehicles.sequence()) + { + if (vehicle == nullptr || vehicle->Mechanik == nullptr || taken.contains(vehicle) || false == known.contains(vehicle) || Left.contains(vehicle)) + continue; + if (vehicle->Mechanik->AIControllFlag()) + { + deleted.emplace(vehicle->Mechanik); + SafeDelete(vehicle->Mechanik); + } + } + // the other vehicles of their consists had them in charge: those the snapshot has get their owners anew + // (apply_owners()), but no vehicle is left pointing at a driver who's no more + for (auto *vehicle : Vehicles.sequence()) + { + if (vehicle != nullptr && deleted.contains(vehicle->ctOwner)) + vehicle->ctOwner = nullptr; + } +} + +// the driver in charge of each vehicle; after the drivers are where the snapshot has them. the vehicles Left keep +// theirs +void apply_owners(document const &Document, vehicle_set const &Left) +{ + for (auto const *entry : Document.of("vehicle")) + { + auto *vehicle{find_vehicle(entry->name)}; + if (vehicle == nullptr || Left.contains(vehicle)) + continue; + // a vehicle gone from the simulation has nobody in charge + if (entry->value("removed", false)) + { + vehicle->ctOwner = nullptr; + continue; + } + if (false == entry->has("first")) + continue; + auto const *owner{find_vehicle(entry->text("owner"))}; + vehicle->ctOwner = (owner != nullptr ? owner->Mechanik : nullptr); + } +} + +void capture_player(document &Document) +{ + if (Train == nullptr || Train->Dynamic() == nullptr) + return; + auto const *vehicle{Train->Dynamic()}; + // by its name, which is what the simulator is started in a vehicle with. the cab the player is in is the one the + // vehicle has occupied, which its entry keeps (caboccupied); a file written before has it here too, as cab, unread + Document.add("player", vehicle->name()); +} + +// tells whether the snapshot was taken in the scenery it's being put over. returns: false if the scenery isn't what it +// was then, which the snapshot isn't put over unless that's forced +bool check_scenery(record const &Header, bool const Force, apply_summary &Summary) +{ + if (auto const scenery{Header.text("scenery")}; scenery != Global.SceneryFile) + Summary.notes.emplace_back(std::format(R"(the snapshot was taken in scenery "{}", this one is "{}")", scenery, Global.SceneryFile)); + if (auto const seed{Header.value("seed", Global.random_seed)}; seed != Global.random_seed) + { + Summary.notes.emplace_back( + std::format("the snapshot was taken with random seed {}, the scenery was loaded with {}: what it draws at random while it loads may differ", seed, + Global.random_seed)); + } + record now; + capture_fingerprint(now); + auto const changed{fingerprint_changes(Header, now)}; + if (changed.empty()) + return true; + // most tracks have no name and are named by their place: a track added early in a file of the scenery moves the + // places of all after it, and the vehicles would be put on other tracks than they were on + Summary.notes.emplace_back(std::format("the scenery isn't what it was when the snapshot was taken: {}. things named by their place in the scenery " + "(\"#12\") may be other ones now", + changed)); + if (Force) + return true; + Summary.notes.emplace_back("the snapshot isn't loaded (--load-snapshot-force loads it all the same)"); + return false; +} + +// applies the entries of a type, each by the function given, and counts how it went +template void apply_each(document const &Document, std::string_view const Type, apply_summary &Summary, Function_ const Function) +{ + auto missing{0}; + std::string example; + for (auto const *entry : Document.of(Type)) + { + if (Function(*entry)) + { + ++Summary.entries; + continue; + } + ++Summary.skipped; + if (missing++ == 0) + example = entry->name; + } + if (missing != 0) + Summary.notes.emplace_back(std::format("{} {} entries of the snapshot have nothing in the scenery to go to, the first one is {}", missing, Type, example)); +} + +// the snapshots asked for on the command line +struct schedule { + command_line requests; + std::optional pending; // the one to load, read ahead for its header + std::size_t written{0}; // how many of the saves are done +}; + +schedule &requested() +{ + static schedule instance; + return instance; +} + +} // namespace + +std::string track_reference(TTrack const *Track) +{ + return reference_in(Paths, track_index(), Track); +} + +TTrack *find_track(std::string const &Reference) +{ + return Reference.empty() ? nullptr : find_in(Paths, Reference); +} + +std::string vehicle_reference(TDynamicObject const *Vehicle) +{ + return reference_in(Vehicles, vehicle_index(), Vehicle); +} + +TDynamicObject *find_vehicle(std::string const &Reference) +{ + return Reference.empty() ? nullptr : find_in(Vehicles, Reference); +} + +int event_sibling(basic_event const *Event) +{ + auto index{0}; + for (auto const *sibling{Events.FindEvent(Event->m_name)}; sibling != nullptr && sibling != Event; sibling = sibling->m_sibling) + ++index; + return index; +} + +basic_event *find_event(std::string const &Name, int const Sibling) +{ + auto *found{Events.FindEvent(Name)}; + auto index{0}; + while (index < Sibling && found != nullptr) + { + found = found->m_sibling; + ++index; + } + return found; +} + +document capture() +{ + document result; + capture_header(result); + capture_time(result); + capture_weather(result); + capture_memcells(result); + capture_tracks(result); + capture_crossings(result); + capture_made_tracks(result); + capture_power(result); + capture_events(result); + capture_launchers(result); + capture_lights(result); + capture_vehicles(result); + capture_isolated(result); + capture_drivers(result); + capture_player(result); + // the long one last, out of the way of whoever reads the file + capture_random(result); + // a file cut short between two entries is told by this + result.records.front().set("entries", result.records.size()); + return result; +} + +apply_summary apply(document const &Document, bool const Force) +{ + apply_summary summary; + auto const *header{Document.header()}; + if (header == nullptr) + { + summary.refused = true; + summary.notes.emplace_back("not a snapshot, nothing was loaded from it"); + return summary; + } + if (false == check_scenery(*header, Force, summary)) + { + summary.refused = true; + return summary; + } + + // nothing in the scenery reacts to the saved state being put back: the vehicles moved to their places don't + // set off the events of the tracks, the sections they free and take don't change their signals + Events.suspend(true); + + if (auto timer{0.0}; header->get("timer", timer, 0.0, longest_wait)) + Timer::set_time(timer); + apply_each(Document, "time", summary, apply_time); + apply_each(Document, "weather", summary, [](record const &Entry) { + apply_weather(Entry); + return true; + }); + // the switches first: a vehicle is put on the path a switch is set to + apply_each(Document, "switch", summary, apply_switch); + apply_each(Document, "track", summary, apply_track); + apply_each(Document, "crossing", summary, apply_crossing); + apply_each(Document, "madetrack", summary, apply_made_track); + apply_each(Document, "powersource", summary, apply_power); + auto const left{apply_vehicles(Document, summary)}; + // the sections the vehicles were counted in and out of as they were put on their tracks + auto const moved{apply_isolated(Document, left_axles(Document, left), summary)}; + apply_drivers(Document, left, summary); + apply_owners(Document, left); + // the cells after the vehicles, whose sections write to their cells as they're taken and freed + apply_each(Document, "memcell", summary, apply_memcell); + apply_isolated_cells(moved); + auto const launchers{Events.launchers()}; + apply_each(Document, "launcher", summary, [&launchers](record const &Entry) { return apply_launcher(Entry, launchers); }); + apply_each(Document, "model", summary, apply_lights); + + Events.suspend(false); + // the queue of the scenery just loaded gives way to the saved one + if (false == Document.of("event").empty() || header->has("timer")) + { + Events.clear_queue(); + apply_each(Document, "event", summary, apply_event); + } + // last, whatever was drawn at random on the way here doesn't count + apply_each(Document, "random", summary, apply_random); + // the values of the file which weren't taken + for (auto &refusal : take_refusals()) + summary.notes.emplace_back(std::move(refusal)); + return summary; +} + +bool save(std::string const &File) +{ + auto const document{capture()}; + // to a file of its own first, which takes the place of the one asked for once it's whole + if (auto const error{write_file(File, document)}; false == error.empty()) + { + ErrorLog(std::format("snapshot: {}", error)); + return false; + } + WriteLog(std::format("snapshot: the simulation at {:.2f} s saved to \"{}\", {} entries", Timer::GetTime(), File, document.records.size())); + return true; +} + +std::string save_now() +{ + auto const &time{Time.data()}; + auto scenery{Global.SceneryFile}; + if (auto const extension{scenery.rfind('.')}; extension != std::string::npos) + scenery.erase(extension); + std::ranges::replace_if(scenery, [](char const Character) { return Character == '/' || Character == '\\' || Character == ':'; }, '_'); + // the folder eu07.ini names; the game folder may be one the game can't write to + auto const folder{Global.snapshot_dir.empty() ? std::string{"snapshots"} : Global.snapshot_dir}; + std::error_code error; + std::filesystem::create_directories(folder, error); + // two saves in the same second of the simulation (while it's paused, say) don't write over each other + auto const file{free_file(std::format("{}/{}_{:04}-{:02}-{:02}_{:02}-{:02}-{:02}.snapshot", folder, scenery, time.wYear, time.wMonth, time.wDay, time.wHour, + time.wMinute, time.wSecond))}; + auto const saved{save(file)}; + ui::Transcripts.AddLine(saved ? std::format("Snapshot saved: {}", file) : std::format("Snapshot not saved, {} can't be written (see errors.txt)", file), 0.f, 10.f, + false); + return saved ? file : std::string{}; +} + +void request(command_line const &Requests) +{ + auto &schedule{requested()}; + schedule.requests = Requests; + // the earliest first + std::ranges::stable_sort(schedule.requests.saves, {}, &command_line::save_request::time); + schedule.written = 0; + schedule.pending.reset(); + if (false == Requests.load.empty()) + schedule.pending = load(Requests.load); +} + +// the snapshot to load, if it's to be used +document const *accepted_pending() +{ + auto const &schedule{requested()}; + return schedule.pending.has_value() && accepted(*schedule.pending, schedule.requests.force) ? &*schedule.pending : nullptr; +} + +std::optional requested_seed() +{ + auto const *pending{accepted_pending()}; + auto const *header{pending != nullptr ? pending->header() : nullptr}; + if (std::uint32_t seed{0}; header != nullptr && header->get("seed", seed)) + return seed; + return std::nullopt; +} + +std::string requested_player_vehicle() +{ + auto const *pending{accepted_pending()}; + if (pending == nullptr) + return {}; + auto const players{pending->of("player")}; + return players.empty() ? std::string{} : players.front()->name; +} + +void start() +{ + auto &schedule{requested()}; + auto loaded{false}; + if (schedule.pending.has_value()) + { + auto const document{std::move(*schedule.pending)}; + schedule.pending.reset(); + for (auto const &problem : document.problems) + ErrorLog(std::format("snapshot: \"{}\": {}", schedule.requests.load, problem)); + for (auto const &warning : document.warnings) + ErrorLog(std::format("snapshot: \"{}\": {}", schedule.requests.load, warning)); + // a damaged file would put back part of the world, and leave the rest as the scenery makes it + apply_summary summary; + if (accepted(document, schedule.requests.force)) + { + if (false == document.problems.empty()) + ErrorLog(std::format("snapshot: \"{}\" is loaded as far as it could be read, --load-snapshot-force says so", schedule.requests.load)); + summary = apply(document, schedule.requests.force); + } + else + { + summary.refused = true; + summary.notes.emplace_back(std::format("\"{}\" isn't loaded: it's damaged (--load-snapshot-force loads what can be read of it)", schedule.requests.load)); + } + for (auto const ¬e : summary.notes) + ErrorLog(std::format("snapshot: {}", note)); + for (auto const &remark : summary.remarks) + WriteLog(std::format("snapshot: {}", remark)); + loaded = (false == summary.refused); + if (false == loaded && Global.test.enabled) + { + // a test run from a snapshot is no test without it + test().finish(test_result::error, "the snapshot to load is damaged, missing or of another scenery"); + } + if (loaded) + { + // the simulation goes on, it doesn't start: with nobody to wait for in a cab the drivers and the scenery + // take the first frame as any other, the way they took it in the run the snapshot comes from + if (Global.local_start_vehicle == "ghostview") + { + // the cells the scripts read the weather and the time from are made by the first, not yet ready, pass. + // the run the snapshot comes from made them in its first frame; made here, the numbers their making + // draws at random don't count + auto const engine{Global.random_engine}; // NOSONAR: a copy of the simulation's reproducible engine, which nothing secure uses + State.update_scripting_interface(); + Global.random_engine = engine; + is_ready = true; + } + WriteLog(std::format("snapshot: \"{}\" loaded, the simulation goes on from {:.2f} s: {} entries put in place, {} left out", schedule.requests.load, + Timer::GetTime(), summary.entries, summary.skipped)); + } + } + // a snapshot asked for at the very time the simulation starts from + update(); + if (loaded && Timer::GetDeltaTime() == 0.0) + { + // the main loop draws a number after every frame of the simulation (eu07_application::generate_sync()), but + // not after this start. the snapshot was taken at the end of a frame, before that draw: it's made up for here + Random(1.0, 100.0); + } +} + +void update() +{ + auto &schedule{requested()}; + auto const &saves{schedule.requests.saves}; + // a frame is never short of the time asked for by the rounding of its steps alone + constexpr double margin{1e-6}; + while (schedule.written < saves.size() && Timer::GetTime() >= saves[schedule.written].time - margin) + { + save(saves[schedule.written].file); + ++schedule.written; + } +} + +} // namespace simulation::snapshot diff --git a/simulation/simulationsnapshotworld.h b/simulation/simulationsnapshotworld.h new file mode 100644 index 000000000..d2df9ecbd --- /dev/null +++ b/simulation/simulationsnapshotworld.h @@ -0,0 +1,73 @@ +/* +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/. +*/ + +#pragma once + +#include "simulation/simulationsnapshot.h" + +#include +#include + +class TDynamicObject; +class TTrack; +class basic_event; + +// the simulation snapshot of the running game: taken from the scenery as it is, and put over a scenery just loaded. +// the text of the file is in simulationsnapshot.h; the parts kept by a vehicle and by its driver are with those classes +// (TDynamicObject::snapshot_save() and the like, defined in simulationsnapshotvehicle.cpp and simulationsnapshotdriver.cpp) +namespace simulation::snapshot { + +// the state of the simulation as a document +document capture(); + +// how putting a snapshot over the scenery went +struct apply_summary { + int entries{0}; // put in place + int skipped{0}; // of the snapshot, with nothing in the scenery to put them on + std::vector notes; // what went other than the snapshot has it, for the user to know of + std::vector remarks; // what was done on the way, for the log + bool refused{false}; // the snapshot wasn't used at all +}; + +// puts the state of the document over the scenery, which is expected to be loaded and initialized, with the simulation +// not yet running. what the snapshot doesn't hold stays as the scenery made it. a snapshot taken in a scenery which +// isn't the same as this one (its fingerprint differs) is refused, unless Force says to put it over it all the same +apply_summary apply(document const &Document, bool Force = false); + +// writes a snapshot of the simulation to the file. returns: true on success +bool save(std::string const &File); +// writes one to the folder of the snapshots (snapshotsdir of eu07.ini, "snapshots" by default), named after the scenery +// and the time of the simulation, with a number added if that file is there already; for the player, who asks for it +// with a key (the snapshotsave command), and is told on the screen where it went. returns: the file written, empty if +// it couldn't be +std::string save_now(); + +// the snapshots asked for on the command line (parse_command_line()): one to load when the simulation starts, and the +// ones to write when its time comes +void request(command_line const &Requests); +// the seed the snapshot to be loaded was taken with, if there's one to load and it tells: the scenery loads the same +// way again only with the seed it was loaded with then +std::optional requested_seed(); +// the vehicle the player was in when the snapshot to be loaded was taken, if it tells +std::string requested_player_vehicle(); +// called when the simulation is about to start: loads the snapshot asked for +void start(); +// called at the end of each frame of the simulation: writes the snapshots due +void update(); + +// names of the things of the scenery, as the entries of a snapshot give them (reference()) +std::string track_reference(TTrack const *Track); +TTrack *find_track(std::string const &Reference); +std::string vehicle_reference(TDynamicObject const *Vehicle); +TDynamicObject *find_vehicle(std::string const &Reference); +// an event is named by its name and, among the events sharing that name, its place +int event_sibling(basic_event const *Event); +basic_event *find_event(std::string const &Name, int Sibling); + +} // namespace simulation::snapshot diff --git a/simulation/simulationtestrules.cpp b/simulation/simulationtestrules.cpp index 6635d0808..f5d39071e 100644 --- a/simulation/simulationtestrules.cpp +++ b/simulation/simulationtestrules.cpp @@ -10,6 +10,8 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "simulation/simulationtestrules.h" +#include "simulation/simulationsnapshot.h" + #include #include #include @@ -28,11 +30,6 @@ std::string reason_suffix(std::string_view const Reason) return Reason.empty() ? std::string() : std::format(" ({})", Reason); } -// options of the simulator which take a value, see eu07_application::init_settings() -bool takes_value(std::string_view const Option) -{ - return Option == "-s" || Option == "-v" || Option == "-seed" || Option == "-ini"; -} // a number of seconds given to Option, at Index of Arguments; the index is moved past the value std::optional option_seconds(std::span const Arguments, std::size_t &Index) @@ -97,9 +94,10 @@ test_command_line parse_test_command_line(std::span const Arg else result.wall_timeout = seconds; } - else if (takes_value(option)) + else { - ++i; + // the values of the other options, see eu07_application::init_settings() + i += static_cast(snapshot::option_value_count(option)); } } return result; diff --git a/simulation/simulationtime.cpp b/simulation/simulationtime.cpp index 6f9f87a5f..14099b714 100644 --- a/simulation/simulationtime.cpp +++ b/simulation/simulationtime.cpp @@ -193,6 +193,13 @@ void scenario_time::set_time(int yearday, int minute) { m_time.wMinute = minute % 60; } +void scenario_time::restore( SYSTEMTIME const &Time, double const Milliseconds ) { + m_time = Time; + m_milliseconds = Milliseconds; + m_time.wMilliseconds = static_cast( std::floor( m_milliseconds ) ); + m_yearday = year_day( m_time.wDay, m_time.wMonth, m_time.wYear ); +} + // calculates day of week for provided date int scenario_time::day_of_week( int const Day, int const Month, int const Year ) const { diff --git a/simulation/simulationtime.h b/simulation/simulationtime.h index aae98ee82..eec227e99 100644 --- a/simulation/simulationtime.h +++ b/simulation/simulationtime.h @@ -47,6 +47,14 @@ public: return m_timezonebias; } void set_time(int yearday, int minute); + // the part of the running second gone by [ms], with its fraction + inline + double + milliseconds() const { + return m_milliseconds; } + // sets the clock to a saved moment: the date and time of Time, Milliseconds into its second (simulation snapshot) + void + restore( SYSTEMTIME const &Time, double const Milliseconds ); /** Returns std::string in format: `"mm:ss"`. */ operator std::string(); diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index a62ca84c8..a98cc6a35 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -174,10 +174,72 @@ a driver isn't watched, and neither is a signal the driver never scanned (a trai 100 km/h 150 m before a signal at stop got past it before its AI first looked ahead; at 60 km/h it was caught). Outside the test mode the same is written to the log, nothing more. +## Simulation snapshots + +A snapshot is a text file with the state of a running simulation: the clock, the weather, the memory cells, +the switches, the queued events, where every vehicle is, how it is coupled and what its machinery and brakes +are doing, what the drivers are up to. Loading one means loading its scenery the usual way and putting that +state over it before the first frame, so a run can go on from the middle of a scenario: + +``` +eu07 -s [--snapshot-at ]... [--load-snapshot [--load-snapshot-force]] +``` + +- `--snapshot-at ` writes a snapshot once the simulation has run that long and goes on. The + time is the simulation time since the scenery started, which a run loaded from a snapshot carries on with + (a snapshot taken at 600 s and loaded starts at 600 s, so `--snapshot-at 900` is written 300 s later). The + switch can be given several times. +- `--load-snapshot ` puts the snapshot over the scenery given with `-s` once it has loaded. Without + `-seed` the random seed is taken from the snapshot, so the scenery loads the way it did then; without + `-v` the player starts in the vehicle they were in. A file the reader finds damaged (an entry cut short, or + fewer entries than its header counts), or one taken in a scenery which isn't the same as this one (see + below), isn't loaded: the scenery starts as it is, the log says why, and a test run ends with the error code. + `--load-snapshot-force` loads what can be read of it all the same. +- Both work with and without `--test`. In the game the `snapshotsave` command ([Ctrl]+[Shift]+[F9], or + whatever `eu07_input-keyboard.ini` binds it to) writes one to `__