diff --git a/CMakeLists.txt b/CMakeLists.txt index 38a83779b..9a2530be8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -220,6 +220,7 @@ set(SOURCES "editor/layout/layoutLine.cpp" "editor/layout/layoutNetwork.cpp" "editor/layout/layoutCommands.cpp" +"editor/layout/layoutGenerator.cpp" "editor/editorNormsReport.cpp" "editor/editorProfile.cpp" "editor/editorGauge.cpp" diff --git a/editor/layout/layoutGenerator.cpp b/editor/layout/layoutGenerator.cpp new file mode 100644 index 000000000..cce4b541a --- /dev/null +++ b/editor/layout/layoutGenerator.cpp @@ -0,0 +1,475 @@ +/* +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 "editor/layout/layoutGenerator.hpp" +#include "editor/editorGeometry.hpp" + +#include +#include +#include + +namespace layout +{ + +namespace +{ + +double constexpr kStraightened{0.02}; // m, TTrack::straightened: control vectors this close to the third of the chord are taken for none +double constexpr kShortestPiece{0.1}; // m: the simulation takes a path under 5 cm for one of no length +int constexpr kDeepest{14}; // halvings of a piece, at most + +// a point of the line where a piece ends: at a node with the numbers of the node +struct piece_end +{ + double chainage{0.0}; + glm::dvec3 point{0.0}; + glm::dvec2 heading{0.0, 1.0}; + double grade{0.0}; + double cant{0.0}; +}; + +std::string number_text(double const Value) +{ + return std::format("{}", Value); +} + +std::string number_text(float const Value) +{ + return std::format("{}", Value); +} + +class cutter +{ + public: + cutter(network const &Network, line const &Line, generator_options const &Options) : m_line{Line}, m_solved{Line.solved}, m_options{Options} + { + for (auto const end : {line_end::start, line_end::end}) + { + auto const *at{Network.find(Line.node_at(end))}; + auto const *ref{Network.end_of(Line.id, end)}; + auto &kept{end == line_end::start ? m_start : m_end}; + auto const sense{ref != nullptr ? static_cast(ref->sense) : 1.0}; + auto const chainage{end == line_end::start ? 0.0 : m_solved.length}; + kept.chainage = chainage; + kept.point = at != nullptr ? at->position : m_solved.point(chainage); + kept.heading = at != nullptr ? at->heading * sense : m_solved.tangent(chainage); + kept.cant = at != nullptr ? at->cant * sense : m_solved.cant_at(chainage); + kept.grade = m_solved.grade(chainage); + } + } + + std::vector pieces(std::vector &Errors) + { + auto const cuts{breaks()}; + std::vector result; + auto from{m_start}; + for (std::size_t i = 1; i < cuts.size(); ++i) + { + auto const to{i + 1 == cuts.size() ? m_end : end_at(cuts[i])}; + // no piece longer than a track may be + auto const count{std::max(1, static_cast(std::ceil((to.chainage - from.chainage) / geometry::longest_path - 1e-9)))}; + auto start{from}; + for (int k = 1; k <= count; ++k) + { + auto const finish{k == count ? to : end_at(from.chainage + (to.chainage - from.chainage) * k / count)}; + cut(start, finish, 0, result, Errors); + start = finish; + } + from = to; + } + return result; + } + + private: + line const &m_line; + solved_line const &m_solved; + generator_options const &m_options; + piece_end m_start; + piece_end m_end; + + piece_end end_at(double const Chainage) const + { + piece_end result; + result.chainage = Chainage; + result.point = m_solved.point(Chainage); + result.heading = glm::normalize(m_solved.tangent(Chainage)); + result.grade = m_solved.grade(Chainage); + result.cant = m_solved.cant_at(Chainage); + return result; + } + + // where the pieces have to end: the elements, the vertical curves, the stretches of the cant; none closer than the shortest piece + std::vector breaks() const + { + std::vector result{0.0, m_solved.length}; + for (auto const &e : m_solved.elements) + result.push_back(e.chainage); + for (std::size_t i = 1; i + 1 < m_solved.profile.size(); ++i) + if (auto const &point{m_solved.profile[i]}; point.tangent > 0.0) + { + result.push_back(point.chainage - point.tangent); + result.push_back(point.chainage + point.tangent); + } + for (auto const &stretch : m_solved.cant) + { + result.push_back(stretch.from); + result.push_back(stretch.to); + } + std::ranges::sort(result); + std::erase_if(result, [&](double const Chainage) { return Chainage < 0.0 || Chainage > m_solved.length; }); + auto const last{std::unique(result.begin(), result.end(), [](double const A, double const B) { return std::abs(A - B) < 1e-9; })}; + result.erase(last, result.end()); + result.front() = 0.0; + result.back() = m_solved.length; + for (std::size_t i = 0; i + 1 < result.size() && result.size() > 2;) + { + if (result[i + 1] - result[i] >= kShortestPiece) + { + ++i; + continue; + } + // the short stretch goes to its neighbour: the break after it goes, or the one before it at the end + result.erase(result.begin() + static_cast(i + 1 + 1 < result.size() ? i + 1 : i)); + } + return result; + } + + // the element the chainage lies in, the curve of a span all in one + element const *only_element(double const From, double const To) const + { + auto const &e{m_solved.elements[m_solved.element_at(From + 1e-9)]}; + return e.end_chainage() >= To - 1e-9 ? &e : nullptr; + } + + bool level_grade(double const From, double const To) const + { + for (std::size_t i = 1; i + 1 < m_solved.profile.size(); ++i) + { + auto const &point{m_solved.profile[i]}; + if (point.tangent > 0.0 && point.chainage + point.tangent > From + 1e-9 && point.chainage - point.tangent < To - 1e-9) + return false; + } + return true; + } + + float radius(double const From, double const To) const + { + double sharpest{0.0}; + for (auto const &e : m_solved.elements) + { + if (e.end_chainage() <= From + 1e-9 || e.chainage >= To - 1e-9) + continue; + auto const a{std::max(From, e.chainage) - e.chainage}; + auto const b{std::min(To, e.end_chainage()) - e.chainage}; + sharpest = std::max({sharpest, std::abs(e.curvature(a)), std::abs(e.curvature(b))}); + } + return sharpest > 1e-9 ? static_cast(1.0 / sharpest) : 0.f; + } + + // the cubic parabola of the element as the cubic Bezier curve it is, the part of it between the chainages + bool parabola_controls(element const &E, double const From, double const To, glm::dvec2 &P1, glm::dvec2 &P2, glm::dvec2 const &P0, glm::dvec2 const &P3) const + { + if (E.kind != element_kind::cubic_parabola) + return false; + auto const radius{std::abs(E.parabola_radius)}; + auto const x{E.parabola_x}; + std::array const form{glm::dvec2{0.0, 0.0}, glm::dvec2{x / 3.0, 0.0}, glm::dvec2{x * 2.0 / 3.0, 0.0}, glm::dvec2{x, x * x / (6.0 * radius)}}; + // the abscissae of the ends, along the parabola from its tangent point + auto const abscissa = [&](double const Along) { + double low{0.0}; + double high{x}; + for (int i = 0; i < 60; ++i) + { + auto const middle{0.5 * (low + high)}; + (parabola_length(x, radius, middle) < Along ? low : high) = middle; + } + return 0.5 * (low + high); + }; + auto const a{From - E.chainage}; + auto const b{To - E.chainage}; + glm::dvec2 origin; + glm::dvec2 along; + double side{E.parabola_radius < 0.0 ? -1.0 : 1.0}; + double ta{0.0}; + double tb{0.0}; + if (E.entering) + { + origin = E.origin; + along = E.direction; + ta = abscissa(a) / x; + tb = abscissa(b) / x; + } + else + { + // from the tangent point at its end, looking back into the curve, turning the other way + origin = E.position(E.length); + along = -glm::normalize(E.tangent(E.length)); + side = -side; + ta = abscissa(E.length - a) / x; + tb = abscissa(E.length - b) / x; + } + auto const world = [&](glm::dvec2 const &Point) { return origin + along * Point.x + left_of(along) * (side * Point.y); }; + auto const q0{world(blossom(form, ta, ta, ta))}; + auto const q3{world(blossom(form, tb, tb, tb))}; + P1 = P0 + (world(blossom(form, ta, ta, tb)) - q0); + P2 = P3 + (world(blossom(form, ta, tb, tb)) - q3); + return true; + } + + // the curvature at the chainage from inside the piece: of the element after it at the start of the piece, before it at the end + double curvature_inside(double const Chainage, bool const After) const + { + auto const &e{m_solved.elements[m_solved.element_at(After ? Chainage + 1e-9 : Chainage - 1e-9)]}; + return e.curvature(std::clamp(Chainage - e.chainage, 0.0, e.length)); + } + + // the handles of a cubic Bezier curve between the ends and their headings which give it the curvatures of the line at its ends + // (G2 Hermite interpolation, by Newton's method from those of an arc); the ones of an arc where it finds none near them + static std::pair curvature_handles(glm::dvec2 const &P0, glm::dvec2 const &T0, glm::dvec2 const &P3, glm::dvec2 const &T3, double const K0, double const K3, double const Handle) + { + auto const chord{P3 - P0}; + auto const across0{geometry::cross(T0, chord)}; + auto const across3{geometry::cross(chord, T3)}; + auto const turn{geometry::cross(T0, T3)}; + // 3/2 K0 a^2 = (T0 x D) - b (T0 x T3), 3/2 K3 b^2 = (D x T3) - a (T0 x T3) + double a{Handle}; + double b{Handle}; + for (int i = 0; i < 30; ++i) + { + auto const f{1.5 * K0 * a * a - across0 + b * turn}; + auto const g{1.5 * K3 * b * b - across3 + a * turn}; + auto const fa{3.0 * K0 * a}; + auto const fb{turn}; + auto const ga{turn}; + auto const gb{3.0 * K3 * b}; + auto const determinant{fa * gb - fb * ga}; + if (std::abs(determinant) < 1e-15) + return {Handle, Handle}; + auto const da{(f * gb - fb * g) / determinant}; + auto const db{(fa * g - f * ga) / determinant}; + a -= da; + b -= db; + if (std::abs(da) + std::abs(db) < 1e-12 * Handle) + break; + } + if (false == std::isfinite(a) || false == std::isfinite(b) || a < 0.3 * Handle || b < 0.3 * Handle || a > 2.0 * Handle || b > 2.0 * Handle) + return {Handle, Handle}; + return {a, b}; + } + + double cant_deviation(piece_end const &From, piece_end const &To) const + { + double worst{0.0}; + int constexpr samples{16}; + for (int i = 1; i < samples; ++i) + { + auto const t{static_cast(i) / samples}; + auto const s{From.chainage + (To.chainage - From.chainage) * t}; + worst = std::max(worst, std::abs(m_solved.cant_at(s) - (From.cant + (To.cant - From.cant) * t))); + } + return worst; + } + + segment_data path_of(piece_end const &From, piece_end const &To) const + { + segment_data path; + path.points[segment_data::point::start] = From.point; + path.points[segment_data::point::end] = To.point; + path.rolls = {static_cast(roll_of(From.cant)), static_cast(roll_of(To.cant))}; + path.radius = radius(From.chainage, To.chainage); + auto const p0{geometry::plan_of(From.point)}; + auto const p3{geometry::plan_of(To.point)}; + auto const turn{geometry::signed_angle(From.heading, To.heading)}; + auto const *single{only_element(From.chainage, To.chainage)}; + // a straight of an even grade is drawn by the simulator as a straight of no control vectors + if (single != nullptr && single->kind == element_kind::straight && level_grade(From.chainage, To.chainage)) + return path; + // the handles of an arc of the turn, 4/3 tan(turn / 4) R; for a transition a start, halved until close enough + auto const chord{glm::distance(p0, p3)}; + auto const cosine{std::cos(turn / 4.0)}; + auto const handle{chord / (3.0 * cosine * cosine)}; + auto handles{std::make_pair(handle, handle)}; + if (single == nullptr || single->kind != element_kind::arc) + handles = curvature_handles(p0, From.heading, p3, To.heading, curvature_inside(From.chainage, true), curvature_inside(To.chainage, false), handle); + glm::dvec2 p1{p0 + From.heading * handles.first}; + glm::dvec2 p2{p3 - To.heading * handles.second}; + if (single != nullptr) + parabola_controls(*single, From.chainage, To.chainage, p1, p2, p0, p3); + auto const y1{From.point.y + From.grade * glm::distance(p0, p1)}; + auto const y2{To.point.y - To.grade * glm::distance(p2, p3)}; + path.points[segment_data::point::control1] = glm::dvec3{p1.x, y1, p1.y} - From.point; + path.points[segment_data::point::control2] = glm::dvec3{p2.x, y2, p2.y} - To.point; + return path; + } + + std::string name_of(double const From) + { + auto const &e{m_solved.elements[m_solved.element_at(From + 1e-9)]}; + std::string key; + switch (e.role) + { + case element_role::straight: key = e.vertex != 0 ? std::format("s{}", e.vertex) : "se"; break; + case element_role::transition_in: key = std::format("v{}i", e.vertex); break; + case element_role::arc: key = std::format("v{}a", e.vertex); break; + case element_role::transition_out: key = std::format("v{}o", e.vertex); break; + } + auto const count{++m_counts[key]}; + return std::format("{}{}_{}{}", m_options.prefix, number(m_line.id), key, count); + } + + void cut(piece_end const &From, piece_end const &To, int const Depth, std::vector &Into, std::vector &Errors) + { + auto path{path_of(From, To)}; + if (straightened(path)) + { + // the simulator would draw it straight: so it's a straight, close enough or halved + path.points[segment_data::point::control1] = glm::dvec3{0.0}; + path.points[segment_data::point::control2] = glm::dvec3{0.0}; + } + auto const off{deviation(m_solved, drawn(path), From.chainage, To.chainage)}; + auto const cant_off{cant_deviation(From, To)}; + auto const fits{off <= m_options.tolerance && cant_off <= m_options.cant_tolerance}; + if (false == fits && Depth < kDeepest && To.chainage - From.chainage >= 2.0 * kShortestPiece) + { + auto const middle{end_at(0.5 * (From.chainage + To.chainage))}; + cut(From, middle, Depth + 1, Into, Errors); + cut(middle, To, Depth + 1, Into, Errors); + return; + } + if (false == fits) + Errors.push_back(std::format("{}: the piece at {:.2f} m lies {:.1f} mm from the line", std::format("line {}", number(m_line.id)), From.chainage, off * 1000.0)); + generated_piece piece; + piece.name = name_of(From.chainage); + piece.from = From.chainage; + piece.to = To.chainage; + piece.path = path; + piece.deviation = off; + auto const &p{path.points}; + auto const point = [](glm::dvec3 const &Point) { return std::format("{} {} {}", number_text(Point.x), number_text(Point.y), number_text(Point.z)); }; + piece.text = std::format("node -1 0 {} track normal {:.3f} {} {} {} {} {} {} {} {} velocity {} endtrack\n", piece.name, To.chainage - From.chainage, m_options.surface, point(p[segment_data::point::start]), + number_text(path.rolls[0]), point(p[segment_data::point::control1]), point(p[segment_data::point::control2]), point(p[segment_data::point::end]), number_text(path.rolls[1]), + number_text(path.radius), number_text(m_line.category.vmax)); + Into.push_back(std::move(piece)); + } + + std::map m_counts; +}; + +} // namespace + +glm::dvec3 drawn_curve::point(double const T) const +{ + auto const u{1.0 - T}; + return u * u * u * p0 + 3.0 * u * u * T * p1 + 3.0 * u * T * T * p2 + T * T * T * p3; +} + +bool straightened(segment_data const &Path) +{ + // as TTrack::straightened() takes it, the second of its checks the first control vector again + auto const &p1{Path.points[segment_data::point::start]}; + auto const &cp1{Path.points[segment_data::point::control1]}; + auto const &p2{Path.points[segment_data::point::end]}; + auto const square = [](glm::dvec3 const &V) { return glm::dot(V, V); }; + return square((p1 + p1 + p2) / 3.0 - p1 - cp1) < kStraightened * kStraightened || square((p1 + p2 + p2) / 3.0 - p2 + cp1) < kStraightened * kStraightened; +} + +drawn_curve drawn(segment_data const &Path) +{ + drawn_curve result; + result.p0 = Path.points[segment_data::point::start]; + result.p3 = Path.points[segment_data::point::end]; + auto const &control1{Path.points[segment_data::point::control1]}; + auto const &control2{Path.points[segment_data::point::control2]}; + if ((control1 == glm::dvec3{} && control2 == glm::dvec3{}) || straightened(Path)) + { + result.p1 = glm::mix(result.p0, result.p3, 1.0 / 3.0); + result.p2 = glm::mix(result.p0, result.p3, 2.0 / 3.0); + } + else + { + result.p1 = result.p0 + control1; + result.p2 = result.p3 + control2; + } + return result; +} + +double deviation(solved_line const &Line, drawn_curve const &Curve, double const From, double const To) +{ + auto const length{To - From}; + auto const samples{std::clamp(static_cast(std::ceil(length / 0.5)), 16, 128)}; + double worst{0.0}; + for (int i = 0; i <= samples; ++i) + { + auto const t{static_cast(i) / samples}; + auto const here{Curve.point(t)}; + glm::dvec2 const plan{here.x, here.z}; + auto s{From + length * t}; + for (int step = 0; step < 8; ++step) + { + auto const &e{Line.elements[Line.element_at(s)]}; + auto const local{s - e.chainage}; + auto const shift{glm::dot(plan - e.position(local), glm::normalize(e.tangent(local)))}; + s = std::clamp(s + shift, std::max(0.0, From - 1.0), std::min(Line.length, To + 1.0)); + if (std::abs(shift) < 1e-10) + break; + } + auto const across{glm::distance(plan, Line.position(s))}; + auto const height{here.y - Line.elevation(s)}; + worst = std::max(worst, std::hypot(across, height)); + } + return worst; +} + +std::string generated_line::text() const +{ + std::string result; + for (auto const &piece : pieces) + result += piece.text; + return result; +} + +generated_line generate(network const &Network, line_id const Line, generator_options const &Options) +{ + generated_line result; + result.line = Line; + auto const *owner{Network.find(Line)}; + if (owner == nullptr) + { + result.errors.push_back(std::format("there's no line {}", number(Line))); + return result; + } + if (false == owner->solved.valid()) + { + result.errors.push_back(std::format("line {} isn't laid", number(Line))); + return result; + } + if (auto const hard{Options.hard_splits.find(Line)}; hard != Options.hard_splits.end() && false == hard->second.empty()) + { + result.errors.push_back(std::format("line {}: the joints of old tracks as hard points of the pieces come with stage E6", number(Line))); + return result; + } + cutter pieces{Network, *owner, Options}; + result.pieces = pieces.pieces(result.errors); + return result; +} + +std::string generate_all(network const &Network, generator_options const &Options, std::vector &Errors) +{ + std::string result; + for (auto const &[id, owner] : Network.lines()) + { + auto const made{generate(Network, id, Options)}; + Errors.insert(Errors.end(), made.errors.begin(), made.errors.end()); + result += made.text(); + } + return result; +} + +} // namespace layout diff --git a/editor/layout/layoutGenerator.hpp b/editor/layout/layoutGenerator.hpp new file mode 100644 index 000000000..8d97b84bb --- /dev/null +++ b/editor/layout/layoutGenerator.hpp @@ -0,0 +1,86 @@ +/* +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 "editor/layout/layoutNetwork.hpp" +#include "world/Segment.h" + +#include +#include +#include + +// The generator of the tracks of the simulator (editor-tracks-domain.md §3 and §5): the layer between the domain and the simulator, +// which knows nothing of the domain. A line is cut into cubic Bezier pieces, each one a track entry of the text TTrack::Load reads: +// within the tolerance of the element it follows (half a millimetre by default, the curve measured as the simulator draws it, a straight +// of zero control vectors where it takes the curve for one), the rolls and the heights from the functions of the line, the radius from +// the element. A piece ends at a node with the numbers of the node, the same on both sides of it; the names of the tracks come from the +// identifiers of the line and of its vertices, so they don't change with a change of the shape which keeps its elements. +namespace layout +{ + +// a joint of an old track the pieces are to end at, the name of the old track kept for the piece before it (stage E6) +struct hard_split +{ + double chainage{0.0}; + std::string name; +}; + +struct generator_options +{ + std::string prefix{"l"}; // of the names of the tracks: _ + double tolerance{0.0005}; // m, the farthest a piece may lie from its line, in the plan and in the height + double cant_tolerance{2.0}; // mm the cant may differ from the line between the ends of a piece, where the simulator turns it evenly + // what an entry has between the type and the path: the width, the friction, the sound distance, the quality, the damage, the + // environment and the visibility with the materials + std::string surface{"1.435 0.15 25 20 0 flat vis rail_screw_used1 4 tpbps-new2 0.2 0.5 1.1"}; + // the joints of the old tracks as hard points of the pieces, by line: stage E6 (§10, "stare złącza jako twarde punkty podziału"). + // Not yet: a line given any is refused, so nothing is made which would lose the names and the events of the old tracks + std::map> hard_splits; +}; + +struct generated_piece +{ + std::string name; + double from{0.0}; // chainage along the line + double to{0.0}; + segment_data path; // its control vectors relative to its ends, zero for a straight, as the entry has them + double deviation{0.0}; // m, the farthest the curve as the simulator draws it lies from the line, measured when cut + std::string text; // the entry +}; + +struct generated_line +{ + line_id line{line_id::none}; + std::vector pieces; + std::vector errors; + std::string text() const; +}; + +generated_line generate(network const &Network, line_id const Line, generator_options const &Options = {}); +// all the lines of the network, in the order of their identifiers; the errors of the lines which couldn't be made in Errors +std::string generate_all(network const &Network, generator_options const &Options, std::vector &Errors); + +// the curve the simulator draws of the path: a straight where its control vectors are zero, or so close to the third of the chord that +// TTrack takes it for one (its check of 2 cm, TTrack::straightened) +struct drawn_curve +{ + glm::dvec3 p0; + glm::dvec3 p1; + glm::dvec3 p2; + glm::dvec3 p3; + glm::dvec3 point(double const T) const; +}; +drawn_curve drawn(segment_data const &Path); +bool straightened(segment_data const &Path); +// the farthest the curve drawn lies from the line between the chainages: each point of it set square onto the line, the distance in the +// plan and in the height together +double deviation(solved_line const &Line, drawn_curve const &Curve, double const From, double const To); + +} // namespace layout diff --git a/tests/unit/CMakeLists.txt b/tests/unit/CMakeLists.txt index bb25bf5a3..d56523122 100644 --- a/tests/unit/CMakeLists.txt +++ b/tests/unit/CMakeLists.txt @@ -61,6 +61,7 @@ add_executable(${UNIT_TESTS_NAME} "${CMAKE_SOURCE_DIR}/editor/layout/layoutLine.cpp" "${CMAKE_SOURCE_DIR}/editor/layout/layoutNetwork.cpp" "${CMAKE_SOURCE_DIR}/editor/layout/layoutCommands.cpp" + "${CMAKE_SOURCE_DIR}/editor/layout/layoutGenerator.cpp" ${UNIT_TEST_CASES}) # the core library brings the game's build settings along diff --git a/tests/unit/test_layout_generator.cpp b/tests/unit/test_layout_generator.cpp new file mode 100644 index 000000000..04db8f61a --- /dev/null +++ b/tests/unit/test_layout_generator.cpp @@ -0,0 +1,317 @@ +// the generator of the tracks of the simulator from the lines of the track geometry (editor/layout, editor-tracks-domain.md §5): the +// Bezier pieces within a millimetre of the elements they follow, the clothoid, the Bloss curve, the cubic parabola, the arcs from 190 m to +// 5 km, the vertical curves; the tracks written and read back by the game's own TTrack::Load(): the ends at the nodes the same to the bit +// on both sides, the curve as the simulator draws it within a millimetre of the line, the radius of the element; the names from the ids + +#include "stdafx.h" +#include "doctest.h" +#include "layout_fixture.h" +#include "track_text.h" +#include "editor/layout/layoutGenerator.hpp" + +#include +#include +#include + +namespace { + +using namespace test::layout_fixture; +using layout::line_id; + +double constexpr kMillimetre{0.001}; + +// the farthest the line lies from the curve drawn: each of its points against the nearest point of the curve, searched on its own +// (the other way round from layout::deviation, which sets the points of the curve square onto the line) +double line_from_curve(layout::solved_line const &Line, layout::drawn_curve const &Curve, double const From, double const To) { + double worst{0.0}; + int constexpr samples{40}; + for (int i = 0; i <= samples; ++i) { + auto const s{From + (To - From) * i / samples}; + auto const target{Line.point(s)}; + // coarse, then golden section around the best + int constexpr coarse{400}; + double best{0.0}; + double nearest{1e9}; + for (int k = 0; k <= coarse; ++k) { + auto const t{static_cast(k) / coarse}; + auto const d{glm::distance(Curve.point(t), target)}; + if (d < nearest) { + nearest = d; + best = t; + } + } + double low{std::max(0.0, best - 1.0 / coarse)}; + double high{std::min(1.0, best + 1.0 / coarse)}; + for (int k = 0; k < 60; ++k) { + auto const a{high - (high - low) * 0.618}; + auto const b{low + (high - low) * 0.618}; + if (glm::distance(Curve.point(a), target) < glm::distance(Curve.point(b), target)) { + high = b; + } + else { + low = a; + } + } + worst = std::max(worst, glm::distance(Curve.point(0.5 * (low + high)), target)); + } + return worst; +} + +// the radius of the pieces: of the sharpest curvature of the elements over it +float element_radius(layout::solved_line const &Line, double const From, double const To) { + double sharpest{0.0}; + for (int i = 0; i <= 64; ++i) { + sharpest = std::max(sharpest, std::abs(Line.curvature(std::clamp(From + (To - From) * i / 64.0, From + 1e-9, To - 1e-9)))); + } + return sharpest > 1e-9 ? static_cast(1.0 / sharpest) : 0.f; +} + +layout::model laid(layout::create_line const &Line) { + layout::model model; + auto const made{model.execute(Line)}; + CAPTURE(reasons_of(made)); + REQUIRE(made.done); + return model; +} + +} // namespace + +TEST_CASE("layout generator: the pieces of clothoids, Bloss curves and cubic parabolas, arcs of 190 m to 5 km and vertical curves are within a millimetre") { + struct sample { + char const *name; + layout::create_line line; + }; + std::vector samples; + for (auto const shape : {layout::transition_shape::clothoid, layout::transition_shape::bloss, layout::transition_shape::cubic_parabola}) { + samples.push_back({shape == layout::transition_shape::clothoid ? "clothoid" : shape == layout::transition_shape::bloss ? "bloss" : "cubic parabola", three_curves(shape)}); + } + // tight and wide arcs: a slow siding round R 190 m, a gentle bend of R 5 km, vertical curves on the straights + auto tight{three_curves()}; + tight.category.vmax = 40.0; + tight.category.track = norms::track_kind::side; + tight.end = {420.0, 100.0, 420.0}; + tight.vertices = {curve({300.0, 0.0}, 190.0)}; + tight.vertices.front().cant = 40.0; + tight.vertices.front().transition_in = tight.vertices.front().transition_out = 30.0; + tight.grades.clear(); + samples.push_back({"R 190", tight}); + auto wide{three_curves()}; + wide.end = {3000.0, 100.0, 300.0}; + wide.vertices = {curve({1500.0, 0.0}, 5000.0)}; + wide.grades = {{700.0, 106.0, 5000.0}, {2200.0, 98.0, 8000.0}}; + samples.push_back({"R 5000 and vertical curves", wide}); + for (auto const &[name, line] : samples) { + CAPTURE(name); + auto const model{laid(line)}; + auto const id{model.state().lines().begin()->first}; + auto const &solved{model.state().find(id)->solved}; + auto const made{layout::generate(model.state(), id)}; + CHECK(made.errors.empty()); + REQUIRE_FALSE(made.pieces.empty()); + double worst{0.0}; + double covered{0.0}; + for (auto const &piece : made.pieces) { + CAPTURE(piece.name); + auto const curve{layout::drawn(piece.path)}; + auto const there{layout::deviation(solved, curve, piece.from, piece.to)}; + auto const back{line_from_curve(solved, curve, piece.from, piece.to)}; + CHECK(there < kMillimetre); + CHECK(back < kMillimetre); + CHECK(piece.deviation == doctest::Approx(there)); + worst = std::max({worst, there, back}); + covered += piece.to - piece.from; + CHECK(piece.to - piece.from <= geometry::longest_path + 1e-9); + } + CHECK(covered == doctest::Approx(solved.length).epsilon(1e-12)); + MESSAGE(name << ": " << made.pieces.size() << " pieces, the farthest " << worst * 1000.0 << " mm from the line"); + } +} + +TEST_CASE("layout generator: the tracks read back by TTrack::Load end at the nodes to the bit, within a millimetre of the line, with its radii") { + test::track_reading const reading; + layout::model model; + REQUIRE(model.execute(three_curves()).done); + auto const first{model.state().lines().begin()->first}; + // split on a straight and inside the arc of the second curve: nodes holding two ends, one of them in a curve + REQUIRE(model.execute(layout::split_line{first, 700.0}).done); + auto const second{std::prev(model.state().lines().end())->first}; + double inside{0.0}; + for (auto const &e : model.state().find(second)->solved.elements) { + if (e.role == layout::element_role::arc) { + inside = e.chainage + 0.5 * e.length; + break; + } + } + REQUIRE(model.execute(layout::split_line{second, inside}).done); + auto const &state{model.state()}; + REQUIRE(state.lines().size() == 3); + std::map>> tracks; + std::set names; + for (auto const &[id, line] : state.lines()) { + CAPTURE(layout::number(id)); + auto const made{layout::generate(state, id)}; + REQUIRE(made.errors.empty()); + for (auto const &piece : made.pieces) { + CAPTURE(piece.text); + auto track{test::read_track(piece.text)}; + REQUIRE(track->m_paths.size() == 1); + auto const &path{track->m_paths.front()}; + // as written + CHECK(path.points == piece.path.points); + CHECK(path.rolls == piece.path.rolls); + CHECK(track->name() == piece.name); + CHECK(names.insert(piece.name).second); + // as the simulator draws it, within a millimetre of the line + auto const curve{layout::drawn(path)}; + CHECK(layout::deviation(line.solved, curve, piece.from, piece.to) < kMillimetre); + CHECK(line_from_curve(line.solved, curve, piece.from, piece.to) < kMillimetre); + // the radius of the element, the arcs to the centimetre + auto const expected{element_radius(line.solved, piece.from, piece.to)}; + CHECK(path.radius == doctest::Approx(expected).epsilon(1e-6)); + auto const &e{line.solved.elements[line.solved.element_at(0.5 * (piece.from + piece.to))]}; + if (e.kind == layout::element_kind::arc && e.chainage <= piece.from + 1e-9 && e.end_chainage() >= piece.to - 1e-9) { + CHECK(std::abs(path.radius - 1.0 / std::abs(e.curvature_start)) < 0.01); + } + if (e.kind == layout::element_kind::straight && e.chainage <= piece.from + 1e-9 && e.end_chainage() >= piece.to - 1e-9) { + CHECK(path.radius == 0.f); + } + CHECK(track->VelocityGet() == doctest::Approx(80.0)); + tracks[id].push_back(std::move(track)); + } + // the pieces end where the next ones start, to the bit + auto const &pieces{tracks[id]}; + for (std::size_t i = 1; i < pieces.size(); ++i) { + CHECK(pieces[i - 1]->m_paths.front().points[segment_data::point::end] == pieces[i]->m_paths.front().points[segment_data::point::start]); + CHECK(pieces[i - 1]->m_paths.front().rolls[1] == pieces[i]->m_paths.front().rolls[0]); + } + // and the line starts and ends at its nodes, to the bit + CHECK(pieces.front()->m_paths.front().points[segment_data::point::start] == state.find(line.start)->position); + CHECK(pieces.back()->m_paths.front().points[segment_data::point::end] == state.find(line.end)->position); + } + // at each node holding two ends the tracks on both sides have the same numbers: the place, the roll, the heading of the control + // vectors + for (auto const &[id, node] : state.nodes()) { + if (node.ends.size() != 2) { + continue; + } + CAPTURE(layout::number(id)); + auto const &before{tracks[node.ends[0].line].back()->m_paths.front()}; + auto const &after{tracks[node.ends[1].line].front()->m_paths.front()}; + REQUIRE(node.ends[0].end == layout::line_end::end); + REQUIRE(node.ends[1].end == layout::line_end::start); + CHECK(before.points[segment_data::point::end] == after.points[segment_data::point::start]); + CHECK(before.rolls[1] == after.rolls[0]); + auto const out{glm::normalize(geometry::plan_of(-before.points[segment_data::point::control2]))}; + auto const on{glm::normalize(geometry::plan_of(after.points[segment_data::point::control1]))}; + CHECK(std::abs(geometry::signed_angle(out, on)) < 1e-12); + } + // the node inside the arc has its cant on both sides + auto const curved{std::ranges::find_if(state.nodes(), [](auto const &Each) { return Each.second.curvature != 0.0; })}; + REQUIRE(curved != state.nodes().end()); + CHECK(tracks[curved->second.ends[1].line].front()->m_paths.front().rolls[0] != 0.f); +} + +TEST_CASE("layout generator: a line run the other way through its nodes meets the tracks on both sides with the same numbers") { + test::track_reading const reading; + layout::model model; + REQUIRE(model.execute(three_curves()).done); + auto const first{model.state().lines().begin()->second}; + auto const at = [&](layout::line const &Line, unsigned const Vertex) { + for (auto const &e : Line.solved.elements) { + if (e.role == layout::element_role::straight && e.vertex == Vertex) { + return e.chainage + 0.5 * e.length; + } + } + return 0.0; + }; + // a middle part between two straights taken out and laid again from its end back to its start: the line runs against the + // headings of its nodes + auto const cut{model.execute(layout::split_line{first.id, at(first, layout::number(first.shape.vertices[1].id))})}; + REQUIRE(cut.done); + auto const &middle{*model.state().find(cut.lines.front())}; + auto const tail{model.execute(layout::split_line{middle.id, at(middle, 0)})}; + REQUIRE(tail.done); + auto const from{model.state().find(cut.lines.front())->start}; + auto const to{model.state().find(cut.lines.front())->end}; + REQUIRE(model.execute(layout::delete_line{cut.lines.front()}).done); + auto const back{model.execute(layout::join_ends{to, from})}; + CAPTURE(reasons_of(back)); + REQUIRE(back.done); + auto const &state{model.state()}; + check_invariants(state); + auto const reversed{back.lines.front()}; + auto const made{layout::generate(state, reversed)}; + REQUIRE(made.errors.empty()); + auto const loaded_first{test::read_track(made.pieces.front().text)}; + auto const loaded_last{test::read_track(made.pieces.back().text)}; + for (auto const node : {to, from}) { + CAPTURE(layout::number(node)); + auto const &held{state.find(node)->ends}; + REQUIRE(held.size() == 2); + auto const &other{held[0].line == reversed ? held[1] : held[0]}; + auto const &mine{held[0].line == reversed ? held[0] : held[1]}; + CHECK(mine.sense == -1); + auto const theirs{layout::generate(state, other.line)}; + REQUIRE(theirs.errors.empty()); + auto const their_track{test::read_track(other.end == layout::line_end::start ? theirs.pieces.front().text : theirs.pieces.back().text)}; + auto const &their_path{their_track->m_paths.front()}; + auto const &my_path{(mine.end == layout::line_end::start ? loaded_first : loaded_last)->m_paths.front()}; + auto const their_index{other.end == layout::line_end::start ? segment_data::point::start : segment_data::point::end}; + auto const my_index{mine.end == layout::line_end::start ? segment_data::point::start : segment_data::point::end}; + CHECK(their_path.points[their_index] == my_path.points[my_index]); + CHECK(their_path.points[their_index] == state.find(node)->position); + // the roll of each as it runs: the same cant leaning the same way, of the other sign run the other way + auto const their_roll{their_path.rolls[other.end == layout::line_end::start ? 0 : 1]}; + auto const my_roll{my_path.rolls[mine.end == layout::line_end::start ? 0 : 1]}; + CHECK(my_roll == -their_roll); + } +} + +TEST_CASE("layout generator: the names come from the ids of the line and its vertices, a change of one curve leaves the others' names") { + layout::model model; + REQUIRE(model.execute(three_curves()).done); + auto const &line{model.state().lines().begin()->second}; + auto const id{line.id}; + auto const before{layout::generate(model.state(), id)}; + REQUIRE(before.errors.empty()); + auto const prefix{"l" + std::to_string(layout::number(id)) + "_"}; + for (auto const &piece : before.pieces) { + CHECK(piece.name.starts_with(prefix)); + } + // a new cant and transitions of the last curve: the pieces before its straight keep their names + auto const last{line.shape.vertices.back().id}; + auto const tightened{layout::preferred_curve(norms::profile_id::plk, line_class(), 700.0)}; + REQUIRE(model.execute(layout::set_vertex{id, last, 700.0, tightened.transition, tightened.transition, tightened.cant}).done); + auto const after{layout::generate(model.state(), id)}; + REQUIRE(after.errors.empty()); + auto const key{"s" + std::to_string(layout::number(last))}; + std::vector kept_before; + std::vector kept_after; + for (auto const *made : {&before, &after}) { + auto &kept{made == &before ? kept_before : kept_after}; + for (auto const &piece : made->pieces) { + if (piece.name.find(key) != std::string::npos) { + break; + } + kept.push_back(piece.name); + } + } + CHECK_FALSE(kept_before.empty()); + CHECK(kept_before == kept_after); + // the same network made twice gives the same text + CHECK(layout::generate(model.state(), id).text() == after.text()); +} + +TEST_CASE("layout generator: the joints of old tracks as hard points of the pieces are stage E6, a line given them isn't made") { + auto const model{laid(three_curves())}; + auto const id{model.state().lines().begin()->first}; + layout::generator_options options; + options.hard_splits[id] = {{350.0, "old_track"}}; + auto const made{layout::generate(model.state(), id, options)}; + CHECK(made.pieces.empty()); + REQUIRE(made.errors.size() == 1); + CHECK(made.errors.front().find("E6") != std::string::npos); + std::vector errors; + CHECK(layout::generate_all(model.state(), {}, errors).find("endtrack") != std::string::npos); + CHECK(errors.empty()); +}