18
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-11-19 23:55:00 +01:00
Files
maszyna/application/editormodesrk.cpp
maj00r e6fa206e47 Split stack 3-5c into master (switch blades, 3D sleepers, editor core, SRK stations, tutorial) (#289)
* feat(track): the rail code split by concern, the blades of the switches with the key frogs shaped from their templates

The rails are laid by code of their own instead of inside Track.cpp: gauge lines (GaugeLine), knot lines (Knots.h), crossings and check rails (RailCrossings), rail materials (RailMaterials), measuring the rail profile (RailProfile), planning the cuts (RailPlan), the carving scan (RailCarve) and laying the geometry (RailLayer).

A switch with the key frogs draws its blades from the tip where their planed nose ends to the heel, bent as they're thrown, and the rail behind them from the heel on, where they were laid from the start of the switch before; on a switch of the catalogue they start at the cut tip of the tables, 1.248 m from the joint at R 190, 1.5 m at R 300 (track_features::blades). The frogs cut from the rails, the wing and the check rails are built but switched off (track_features::crossings), the rails laid whole as before. The switches without the key keep the blades they had.

A switch path can be a chain of pieces: pieces1 and pieces2 keep the parts of each path after the classic bezier, which stays as the approximation older versions read. A path with its radius given is a curve however gently it bends, a plain track a straight only where both of its control vectors lie along it. A vehicle trailing through a switch with a movable nose set the other way runs off the rails at it (TRAILED_SWITCH).

* feat(render): the shared treads of the rails and their cut faces drawn, the cut faces in the matte variants of the rail materials

Both renderers draw the treads a track shares with the rails it crosses, in the pick pass too, and a pass of their own for the faces where the rails are cut, the ends of the blades among them, in the matte variants of the rail materials, so the cut faces don't shine like the head the wheels polish.

* feat(vehicle): an axle on a switch keeps to the path it came on, and coming from the frog end trails the switch through where the wheels reach the blades

The switch thrown under an axle no longer moves it over onto the other path; it runs on along the one it entered. Coming from the frog end, where the blades are shaped or the frog has a movable nose, the switch set the other way is trailed through (rozprucie) only where the wheels get to the blades or to the nose, not as the axle enters the track; the other switches are trailed through as it enters, as before.

* fix(track): the tracks drawn straight before, which their second control vector bends now, written to the log

The simulator told a straight by the first control vector of a path alone, so a track whose second control vector bent it was drawn straight; now it's a curve. Such a track is named in the log as it loads, so a scenery made counting on the straight can be found: 25 tracks of lk357. Paths with both control vectors along them bend a centimetre or so at most and aren't named.

* feat(track): 3D sleepers and switch timbers laid where the simulator makes the ballast, switched off in the build

The sleepers of a track running alone are laid square to it, the timbers of the switches and crossings across the tracks running over them, shared by them, of the models set with sleepers3d and sleepers3dplain in eu07.ini; sleepers3dbed tells whether the ballast is laid under them too, lowered so they stick out of it. The layout of a cluster of tracks is worked out once and kept till a track of it changes, in a thread of its own while the simulation runs. timbermodel of a track, read and written back before, takes the place of the model of sleepers3d there. All of it is off whatever eu07.ini sets (track_features::sleepers), the tracks keeping their ballast and their sleeper models.

* feat(render): the 3D sleepers and switch timbers drawn in instanced batches

Render_Timbers lays the beams of the tracks in range where they're out of date and draws those of a run of tracks of a cell gathered by the model and its part or its level of detail, in as few instanced batches as they fit in; in the shadow pass only those near the camera. A track with them leaves its old sleeper model out. OpenGL 3.3 renderer only.

* fix(track): the counts of what's wrong with the sleepers kept safe from the thread laying them, and that thread stopped before what it works with goes

The counts of the beams clipped, dropped and off the plane, of the slowest and the biggest cluster, are counted by the thread working out the layouts in the background as well as by the simulation laying a cluster itself, and were plain values written by both; they're atomic now. What the thread keeps the clusters in, their version and the counts were made after the worker, as it first asked for them, and so destroyed before it at the exit while its thread could still be laying a cluster; they're made first now, the worker stopping and joining its thread before they go. The tracks go with the paths of the simulation, made before the worker.

* revert(track): a tributary and a track of an unknown type load as before

They came in with the rail code from the guards of the editor against crashing, and don't belong with the blades: a track of an unknown type loaded as a normal track of the railway could be joined to it and run on, and a tributary loaded as a river with its first path lost the second one when the editor saved the scenery. Both load as on master again; the place where the editor crashed on them is to be guarded where it is.

* fix(track): the tracks drawn straight before named in the log once, as they load, and the paths of the switches with no radius told a straight as before in one term

The log of the tracks the second control vector bends now was written each time the segments of a track were made again, as a track with its unevenness loads and as the editor changes or drags a track; it's written only the first time, as the track loads. The paths of a switch or a crossing with no radius keep the rule of master, a straight told by the first control vector alone, its two terms being the same length; they're one term now, with the comment saying so.

* fix(track): the thread laying the sleepers stopped as the application exits, and loading no models itself

The thread reads the scenery, which the application deletes as it exits well before the statics go: it's stopped and joined first thing in exit() now, the worker destroyed with the statics only where the application exits some other way, and not started again after. The models the beams are made of were loaded by the thread where it didn't find them, through the renderer, out of the thread of the renderer, into a map read by the simulation meanwhile: they're found under a lock now and loaded only by the threads other than it, again for all the tracks whenever a track changed since, before a layout is asked of it. With the 3D sleepers off in the build their settings aren't exported, and a track changed doesn't look for the tracks around to lay their beams again.

* feat(track): the 3D sleepers turned on with sleepers3d in eu07.ini, no longer switched off in the build

track_features::sleepers is gone: sleepers3d <model> in eu07.ini lays them, none (the default) lays nothing and the
tracks keep their ballast, as before. The sleepers3d settings are written back with the others.

The editor changes the tracks, so while it's open their sleepers are worked out on the main thread as they're needed,
not in the background.

* fix(render): only the part of a timber model drawn, not what else the model holds

A timber model of parts may hold more than its begin, main and end, as the kits with the fastenings of the rails do. Those
were drawn with each part of each timber, in the middle of the track; they aren't laid, so they're skipped now.

* fix(track): the 3D sleepers laid only for a renderer which draws them

Only the OpenGL 3.3 renderer draws the beams. With another one a track set to them lost its ballast to them, lowered or
not laid at all with sleepers3dbed no, and nothing was drawn in its place. Draws_Timbers() of the renderer tells now,
and where it's false the tracks keep their ballast, as with sleepers3d none.

* fix(render): the submodels of a timber model left as they were after its parts are drawn

They were all made visible after a part was drawn, the ones the model hides itself too, like Light_On, while the same
model may stand in the scenery. The submodels of the top level besides the parts are listed as the model is loaded,
hidden while a part is drawn and given back their own visibility after. The parts have to be at the top level of the
model for that; a model with them deeper is logged and drawn whole.

Render_Timbers no longer looks the model up under the lock for every run of tracks, the name set is enough there.

* fix(render): a vertex whose faces give its texture no direction gets a tangent across its normal, not a NaN one

The cut ends of the rails have one spot of the texture on all their corners, so their tangent came out of normalize() as NaN. The normal-mapped shaders then shaded them with a NaN normal: about half of the vertices of the cuts and frogs, and the end faces of the rails.

* feat(track): the frogs cut from the rails turned on with frogs in eu07.ini, no longer switched off in the build

frogs yes cuts the rails of the plain tracks and of the switches with the key frogs where they cross other rails, into frogs, wing rails and check rails. It's off by default: the rails are laid whole as before, the blades of the switches with the key are shaped still.

* refactor(editor): the track mode file split into the files of its tools, the code as it was

A pure move, so that the commits after it show what changes in each tool rather than a 4800-line file rewritten.
The member functions of editor_mode go to the file the editor of this branch has them in: route, straights, lay,
switchplace, switchdrive, switchtool, trackgizmo, and the rest stays in editormodetrack.cpp. The helpers of its
anonymous namespace go to editormodetrackshared.h, as they were but inline, in namespace track_mode, which the files
use. No line of code changes; the files add only their license, includes and the using line.

* feat(editor): the groundwork the tools of the editor share

- The tool interface (editortool.h), the gestures of the mouse (editorgestures.h) and what the modes share
  (editormodeshared.h); the projection, viewport, selection and texture picking taking them up.
- Scripted input (scriptedinput): the input of a selftest script fed to the editor as if typed and clicked, the real
  mouse and keyboard ignored meanwhile; EU07_EDITOR_SELFTEST_HIDDEN draws into a window never shown nor focused.
- The ui layers and panels of the editor, its settings, icons and the info of the includes; the layers of the scenery
  and their saving; the launcher mode.
- utilities: user_cache_path (the cache folder of the system for the user) and the helpers of the translations.
- stb_image: the gif loader takes the frame two back from the frames it decoded, not from before its buffer.
- tools/editor: the scripts making the headers of the drives, the turntables, the editor and its usage.
- Unit tests: test_area and the stubs of the editor the tests link.

Not built on its own: the tree builds again with the selftests commit, the one before the translation.

* feat(editor): the tracks laid along an alignment, to the PKP PLK norms, with their grade line and the ground

- The alignment of the laying (editorAlignment, editorAlignmentStore): straights, transition curves and arcs with the
  cant of the norms for the speed, the radius below the minimum for it a warning; the lay, route and straights tools
  build on it, the route plan reading the curves going on from the tracks adjoining.
- The grade line (editorProfile, the profile and gradeline tools): fitted to the terrain model or edited by hand, the
  tracks fitted marked in the scenery (//$f), the shared grade lines of nearly parallel tracks (//$n).
- The ground under the tracks (editorGroundFollow, trackbed): the terrain drawn to the tracks and restored, the tracks
  put onto the terrain.
- Connections between tracks (editorConnections, the connection and connection curve tools), the track presets, the
  shape of a track (editorTrackShape), digitizing tracks from the orthophoto, the properties sheet of the tracks
  (trackprops) and the track ux.
- Unit tests: alignment, ground fit, heights, with the data of two fits.

Not built on its own: the tree builds again with the selftests commit, the one before the translation.

* feat(editor): the switches placed, slid and designed from their templates

- The switch templates (editorSwitchStore, the template tool): the catalogue switches and the user's own, kept with
  the settings; the designer (editorSwitchDesign) with a drawing of the dimensions, a and b typed in with the shape
  making up the rest, a switch clicked off the orthophoto.
- The curve of a switch laid into a curve (editorSwitchCurve), placement on a straight or into a curve, slide along
  it, crossovers and double slips (switchplace, switchslide), the drives of the switches (switchdrive) and the records
  of the switches placed (records).
- Unit tests: test_switch_curve.

Not built on its own: the tree builds again with the selftests commit, the one before the translation.

* feat(editor): the tools of the infrastructure beside the tracks

The gauge, speed, joints, lineside, parallel tracks, vehicles, signals, turntables, sweep and road tools with headers
of their own; the kilometrage of the lines (editorKilometrage, the km tool); the infrastructure, roads and speeds
behind them (editorInfra, editorRoad, editorSpeed).

Not built on its own: the tree builds again with the selftests commit, the one before the translation.

* feat(editor): the terrain model of geoportal.gov.pl and the orthophoto downloaded for the editor

- editorNmt: the squares of the terrain model at 1 m (NMT GRID1, the WCS service of geoportal.gov.pl) fetched by two
  workers, kept in editor/cache/nmt/grid1 of the game folder, the heights of the scenery taken from them; the nmt
  mode loads it along the tracks or around the camera.
- editorHttp: the HTTP client of both, WinHTTP on Windows, libcurl elsewhere where it's built with it; without it the
  caches only.
- The orthophoto: its cache moved to the cache folder of the system for the user, the download area a polygon on the
  topo map (//$a) filled in the background, the 4K imagery, the tiles waiting outlined on the ground.
- editorGeoMap: the topo map of the top view; heightmapterrain and the terrain streamer grow the terrain made from the
  model around the camera.

Not built on its own: the tree builds again with the selftests commit, the one before the translation.

* feat(launcher): the scenery wizard picks the place of a new scenery on the topo map the editor shares

The wizard drops its own map download and decoding for the topo map widget of the editor (editorGeoMap). The place
clicked becomes the geographic reference of the new scenery (//$g PUWG1992), and the scenery starts with the
orthophoto of the editor on (//$o), lying under it in place.

Not built on its own: the tree builds again with the selftests commit, the one before the translation.

* feat(editor): the tools wired into the editor mode and the build

editor_mode takes the tools of the commits before: its header declares them, editormode.cpp and the track mode drive
them, and the renderers draw their overlays (opengl33 and legacy). CMakeLists lists the new sources and adds
WITH_EDITOR_SELFTESTS (off by default); the unit tests build the new test files.

Not built on its own: the tree builds again with the selftests commit, the one before the translation.

* feat(editor): the selftests of the editor split by what they test

The scripts of EU07_EDITOR_SELFTEST run the commands of editormodeselftest*.cpp: scene, track, rails, join, switch,
signal, sleepers, sweep, terrain, monkey. The code is in every build; only with WITH_EDITOR_SELFTESTS=ON does the
editor read the variables and run a script. The selftests of master now need the option too.

The tree builds again with this commit.

* feat(editor): the Polish texts of the editor, all of them in one update of editor_pl.po

* fix(editor): the marks of the editor moved off the letters the starters read, and its lines told by their words

The starters read some letters in a scenery file: the Starter the title //$n, the attachments //$f and the old scenery //$a,
StarterNG and the launcher of the game the attachments //$f and the title //$n. The editor wrote its download area,
shared grade lines and fitted tracks under them, and took every line of those marks as its own: saved, a scenery lost
its title and attachments, and the starters showed the lines of the editor as them.

- The download area is //$z, the shared grade lines //$w, the fitted tracks //$t.
- Their lines and those of //$o are told by their first words, as //$h, //$r and //$k were: //$o only as "on 0" or
  "on 1", the origin or the settings of older builds after it, so a trainset described as "on ..." isn't taken.
- The lines older builds wrote under //$a, //$n and //$f are read only by the words the editor wrote in them, or by
  its own comment line before them, under the new mark. Each save writes them again with it, also when the editor
  didn't change them; the lines of the starters stay.

* fix(editor): a square of the terrain model cut short isn't read, and the squares are kept in the user's cache

The service puts the directory of its GeoTIFF before the pixels, so a file cut short by a write or a fetch broken off
was read whole, the pixels missing coming out as heights of 0 m, for good.

- The reader (editorGeoTiff.hpp, with unit tests) wants all the strips the rows need, each within the file.
- A square is written under a name of its own and renamed.
- The squares are kept in the user's cache folder (nmt/grid1), as the orthophoto, since the game folder may not be
  writable; without one, in the game folder as before. The ones older builds kept there are moved over as each is
  asked for, a damaged one deleted.
- Capabilities that didn't come aren't kept as the fallback name for the session: the next square asks again.

* chore(editor): the http client said to serve the terrain model and the topo map too, the gif fix of stb_image marked local

- CMake names the orthophoto, the terrain model and the topo map as what goes without libcurl.
- The fix of the gif frame two back in stb_image is ours, not upstream's (v2.30 still has the old line): a comment at
  the line says so, for an update of stb_image to keep it.

* fix(editor): the lines moved off the letters of the starters in a merged layer written once, not again with each save

A merged layer's text goes into the file of its target on save, and the target is read again; the marked lines of the
merged layer were dropped only for the marks the editor had changed. The lines moved to the new letters stayed with
their old places, and the next save of the session wrote them into the target once more.

- After a save, the marked lines of every merged layer are dropped; those of its target are read again from its file.
- The lines of a dead layer aren't written again.
- The selftest layermerge merges the layer of one file into another's, as the layers panel does.

* feat(editor): the station as the signalling sees it, found from a switch of it, and its schematic

editorStation: the switches joined by plain track no longer than 1.5 km, the tracks between them and the lines leading
out, 400 m of each beyond the outermost switch; laid out as a schematic along the main track through the station. The
track circuits, the signals and their lights, the lengths of the station tracks and the lines to the next stations are
worked out from it for the signalling tool.

Nothing uses it yet: the signalling tool, wired in the next commit, does. It builds on its own.

* feat(editor): the signalling of a station in the Signalling tab, laid out from a switch of it as on the lines of PKP PLK

LMB on a switch in the Signalling tab opens its station: the schematic in a window of its own, the name, the code, the
line and the km of the station, and the steps of its signalling, each one step of undo:

- the switches numbered along the station after its code, bpd_1, the parts of a slip bpd_15a..d; the drives and the
  objects naming a switch follow it, events written by hand keep the old names;
- the tracks cut at the joints of the track circuits, Ie-4, and the circuits named, bpd_iz1, bpd_it1;
- the entry, exit and shunting signals placed and named, A, F1, Tm1, from the templates chosen;
- the signals of the lines out: the automatic block of three or four aspects, the block sections no shorter than the
  braking distance, or the semi-automatic one with a warning disc; block boundaries drawn by hand;
- the lights each signal needs for its routes, Ie-1 and Ie-4 § 8, its template fitted to them;
- the SHP track resonators the signals lack, rezonator.inc;
- the lengths of the station tracks as a table, and what the station and its lines still lack, with Repair.

The stations described are kept as //$s lines in the files of their layers.

* fix(editor): the signals of a station and of its lines not placed with no template for a kind, no track cut for them first

- Set the signals and Set the line signals cut the tracks first, and only then found no template for a kind. They
  stopped there, but the cuts stayed as a step of undo. Now they ask for the templates first, by the lookup
  signal_batch() uses (signal_template_for(), behind editor_signals::signal_templates_missing()). Without one
  nothing is cut.
- Set the signals and Set the track circuits again under Track lengths had the ids of the buttons of the steps
  above them. ImGui flagged them when hovered. Each now has an id of its own.

* fix(utilities): win1250_to_utf8 turns the polish letters into utf-8, not into themselves

utilities.cpp starts with a byte order mark, so the compiler reads it as utf-8. The game's targets don't get
/utf-8, though: set_target_properties(... COMPILE_OPTIONS ...) in the MSVC block of CMakeLists.txt replaces the
options add_compile_options gave them. So the string literals went into the program in the code page of the
system, windows-1250 on a polish one, and the map of win1250_to_utf8 turned each letter into itself.

What read windows-1250 through it got no utf-8: the names, descriptions and categories of the sceneries and the
names of the textures in the launcher, and the descriptions of the templates in the editor. The editor writes
such a description back through utf8_to_win1250, which makes a question mark of each byte that doesn't start
a utf-8 sequence, so the letters it had read unchanged didn't come back.

The utf-8 sequences are written as bytes now, the way utf8_to_win1250 has them, so they don't depend on the
options. The options stay as they are: with /utf-8 other literals of the files with a byte order mark would
change, the "±" of the table of Bezogonkow would take two bytes and move the letters after it.

The unit tests check the letters and that the text given is valid utf-8.

(cherry picked from commit 9ffed96ec1)

* fix(editor): the switches renamed only after the events by their old names are shown, the station records in windows-1250 and in the file the scenery had

Number the switches renames the switches and what the editor writes along with them, but not the events written
by hand: a switch event aiming at a switch, or <name>:event0 and the others named after it, would keep the old
name and lose its switch. Now the first click lists them in the status, up to six and how many more, and renames
nothing. A second click with the same renames goes ahead.

The name of a station is written in windows-1250, like the rest of the scenery file. A name read that isn't
valid utf-8 is taken for windows-1250; the utf-8 the earlier builds wrote is read as it is. utf8_to_win1250
moves from editorIncludeInfo.cpp to the utilities, beside win1250_to_utf8, and the unit tests check both ways.

The record of a station that had none goes beside the records of the other stations, in the file marked with
them, so a scenery saved under another name keeps them in one file. output_layer takes, after
<scenery>_<part>.scm, an included file of the part of another name, the one of the scenery it was copied from,
before it makes a new one.

The comments: the joints of the track circuits stand 4.2 m beyond the fouling points, where the axes are 3.5 m
apart, as joints() counts them; the regulation of the lengths is cited with its date and title.

* fix(editor): a scenery saved under another name keeps one file of the keys by the movable noses, not the old one beside its own

The editor writes the keys by the movable noses on each save to <scenery>_dzioby.scm and includes it. A copy of
a scenery, saved under another name, still included the file of the scenery it came from, and its save wrote a
file of its own and included it too, so each key stood twice.

Now the save leaves out of the scenery the other files of such keys it includes, told by the line the editor
writes at their start. Their files stay on the disk, for the scenery they were made for. A file made by hand,
without that line, stays included. The turntable controls had the same, fixed the same way on their own.

* fix(editor): a file of the scenery named like a part of a tool isn't taken for the one the tool made

output_layer took, after <scenery>_<part>.scm, any included file named *_<part>.scm, so that a scenery saved under
another name goes on with the file of the scenery it was copied from. A file of the scenery named alike, written by
hand, such as rejon_teren.scm, got the terrain directive, the hectometre posts or the new signals too.

The files output_layer makes start with a line of their own now, "// scenery layer created in the editor for its
<part> part", and a file of another name is taken only with that line. A layer gets it through the new parameter
of scene::node_layers::create(); the others start with the general line as before. <scenery>_<part>.scm of the
scenery itself is taken without the line, as it was. A file made for a part by an earlier build has only the
general line, so a copy saved from it gets a file of its own.

* feat(editor): a player of GIF clips for the windows of the editor

editor_clips::clip plays a GIF in an ImGui window, looped, from the time given. stb_image decodes the whole
file on a thread of its own, so the window isn't held up; until then the clip says it's loading. The frames are
kept as stb_image decoded them, and the one shown is a texture of the ImGui renderer (Create_Image), made again
only when the frame changes. A file that isn't there is told missing at once, with no thread started.

Nothing uses it yet; the tutorial of the next commit shows its clips with it.

* feat(editor): Help > Tutorial, fifteen short lessons of the editor

The lessons: looking around, laying track, curves, the radius of the curves at the bends, correcting a curve,
joining tracks, switches, switch templates, signals and posts, selecting and fixing, editing with the gizmo, the
grade line, terrain from the terrain model, sceneries made before, saving and driving.

Each lesson has:
- in eight lessons, a looping clip from lang/editor_tutorial/<lesson>.gif, played from the start on a click;
  in six others, a moving drawing (the radius at a bend, a switch template clicked, the signals, the grade
  line, the terrain, a trainset);
- the mouse buttons and keys drawn as pictures beside what they do;
- ticks that fill in as the user does it, told by the tools through editor_guide::first_step_done();
- a button that turns the tool of the lesson on;
- Back / Next and a dot per lesson, green when the lesson is done.

The window follows the work: when the tool in use changes, it turns to the first lesson of that tool not done
yet, and a page turned by hand stays until then. In a lesson of laying it warns when there's no ground under
the cursor.

Where it opens:
- by itself when an editor session starts, until "Show when the editor opens" is unticked (first_steps in the
  editor's settings);
- from the Help menu;
- from a Tutorial button beside Lay a track in the hint of an empty scenery, which isn't drawn while the
  tutorial is open;
- at its lesson, from a "?" by the radius at the bends in the lay panel.

A lesson whose clip isn't there is shown without it; the clips aren't in this commit.

editor_guide is a new role of the editor, given to the hekto-post and trainset tools. Selftest command
tutorial <page>: opens the tutorial at a lesson, from 0; -1 closes it.

* fix(editor): the lessons of the tutorial say what the editor does

The lesson texts checked one by one against the tools; the ones that told otherwise:
- Switches: a connection isn't chosen at the top of the panel, its kind comes from where the drag is let go (a
  crossover onto the other track, over a crossover the other way a double one, or scissors where they overlap).
- Switches: a ladder leads onto the parallel tracks it's dragged across, let go on the farthest, with the
  straights up to where they start; it lays no missing tracks.
- Terrain: there is no step 3. Step 1 is Location, step 2 is Load around the camera while there are no tracks
  and Tracks and terrain with its three ways once there are. The rows had the step numbers in the keys column,
  and 1, 2 and 3 switch the edit modes in the Terrain field. Now the steps show the mouse, the terrain under
  some tracks only is a row of F3 (the line the terrain panel shows), and the rows that only tell what the
  fit does have no key.
- Sceneries made before: a plain include can be changed; the row lists what can't: an include template (.inc),
  the binary terrain cache, a file included twice or with parameters, a locked or hidden layer.
- Laying: the second Esc drops the points only within 3 s.
- The radius at the bends: two transition curves from 6000 m down to 2000 m while they're long enough for the
  speed, then an arc; a label turns orange where the curve breaks the norms, not because it came out smaller;
  two transitions meeting read 2xL and R; the labels of each transition curve are on laid tracks, close up.
- Signals and posts: the W17 markers go by the selected switch, around the camera or the whole scenery, not
  along a line.
- Selecting and fixing: E lengthens the track, the control vectors bend it.
- The gizmo: at a point Q moves the point alone, W turns the whole track about it.

The tooltip of Help > Tutorial no longer speaks of clips: the tutorial goes without them. lang/editor_pl.po
has the new texts.

* fix(editor): the lessons of the tutorial in plain words

Every row, goal and warning of the tutorial is said again for someone
who has never laid a track, in English and in Polish:
- the words of the railway and of the editor are said in everyday ones,
  or explained where they come: the radius (how big the curve is), the
  transition curve (the easing into it), the cant (the outer rail
  raised), the gizmo (handles on the track), the control vectors (points
  that bend it), the grade line (how the line goes up and down), the
  terrain model (the real ground), the orthophoto (the aerial photo),
  the hectometre posts (every 100 m), W17 (how far a wagon may stand);
- what only a designer needs is left out: the 6000 and 2000 m of the
  radius ladder, the compound curve, the hump, the kinds of include that
  can't be changed;
- the buttons are named as the panels name them: Apply to the scenery,
  Template editor..., the tiles of the switch tool;
- the Polish names of three lessons say what they are about ("Uchwyty na
  torze (gizmo)", "Wzniesienia i spadki", "Prawdziwy teren"). Their
  English titles stay, the lessons are found by them;
- the warning of no ground under the cursor tells what happens to the
  track;
- two captions of the drawings say what they show (the tracks inside a
  box, posts every 100 m), and in Polish the button of the top view is
  "Widok z góry (O)", without "ortogonalny".

What each row tells of is the same as before. The msgid of the length
typed while laying stays, the window of the keys (F1) uses it.

* feat(editor): the semaphores and the warning discs chosen by what their descriptions say they show

The descriptions of the signal templates can now say what a semaphore shows and what a disc
repeats, and the editor reads it:

- signal: {arms: 2, aspects: {Sr1: ..., Sr2: ..., Sr3: ..., Sz: ...}, repeats: {stop: ...,
  vmax: ..., "40": ...}} is kept with the template, the events named for each aspect
- the palette shows a template with arms as a semaphore of its arms, with 1 arm / 2 arms and
  Sz picking the template of the same tile that has them
- the signals of SRK take a semaphore whose aspects cover what the signal needs (Sr3 where a
  speed is reduced, Sz on the main signals), the fewest arms that do it, and say which one
  does when the placed one hasn't them or has more than it needs
- the warning disc before a semaphore is one whose repeats cover stop, the highest speed and
  40 km/h when the semaphore shows Sr3; SRK writes no events of the routes, so this only
  chooses and checks the disc
- the linked signal (parameter 7) is read for the role link as well as text
- signal_headers.py keeps the keys written by hand in a description (arms, aspects, repeats,
  the description and the parameters from 6 on) when it writes the guessed ones again
- signaltemplates of the self test lists what the templates say and the heads made of them

* feat(editor): the shaped discs swapped and set by hand, the warning discs checked by what they repeat

The shaped shunting and stop discs (mk1, tzm, z1) are known to the signalling, but it doesn't
place them by itself:

- a shaped disc chosen in the palette for the shunting or the stop signals is placed by hand
  only; the signalling of a station takes the light template of the kind there, and says so
  when there is none
- the template of a shunting or a stop signal standing can be swapped for a light or a shaped
  one of another mount as well (dwarf and mast, not gantry)
- a signal whose description lists its aspects shows a button for each under its card: it sets
  the signal to that aspect in the editor, by the animations, the lights and the submodels its
  event sets off, the time standing still; nothing of it is saved. TAnimContainer::Finish takes
  an animation to its end at once, giving the submodel its angles, multi_event::branches tells
  the events set off when the condition isn't met

From the review of the descriptions:

- a shaped warning disc standing before a semaphore described is checked by the events it
  repeats: stop, the highest speed and 40 km/h of a second arm told apart; one which doesn't is
  offered the disc which does, and Fit swaps it
- the disc offered is of the mount of the disc chosen, taken from the template even when it
  isn't described
- 1 arm / 2 arms / Sz of the palette pick the template leaning as the chosen one and most like
  it by its name
- a semaphore described with its arms but not its aspects has Sr1, Sr2 and with a second arm
  Sr3
- Fit leaves a semaphore having what it needs with its arms, for the events written by hand to
  the aspects of a second one; the messages of the fitting speak of what the signals need, not
  of their lights
- signal_headers.py warns of a signal map written as a block, whose keys it can't keep

* fix(editor): an aspect shown by hand doesn't name a vehicle that may be gone

The Show button runs the events of the aspect outside the queue. run() writes
the vehicle that set the event off last into the log, and nothing clears that
pointer, so a train deleted since would have been read after it was freed. The
queue sets the activator anew each time, so it is cleared before the run.

* fix(editor): a disc not described is only offered the one that tells, a light stand-in of the mount of the shaped one

- A shaped warning disc whose template doesn't say what it repeats may tell
  all its semaphore shows as well. It is no longer marked as not fitting:
  the disc described is offered as a hint, and Fit leaves it be. A disc whose
  template isn't among the scanned, its mount not known, is offered nothing
  rather than discs of any mount.
- A shaped disc chosen for shunting or stop is stood in for by a light
  template of its own mount first, a dwarf for a dwarf.
- The tooltip of the aspect buttons says the trains read the signal as its
  events set it last, in a run started from the editor too.
- The Polish texts of the fitting speak of signals, not semaphores, since it
  takes the discs too.

* refactor: the Sonar remarks on the switch blades taken care of

- the big functions of the rails split into helpers with one job each:
  the carving, the laying and the planning of the rails, their
  crossings, the blades, the lofted spans of a segment, the profile of
  a rail measured piece by piece, the joining of the switches
- the floating-point loop counters are while loops doing the same
  additions, so the samples come out where they did
- C arrays are std::array, the two sides of the paths path_sides; the
  ends of a cut are two parts of one struct, ending and starting
- the rail laid by a course of its own, not eleven parameters
- the globals kept in functions, the nested ternaries taken apart, one
  declaration per statement, explicit captures, ranges algorithms,
  std::format, std::numbers, emplace_back, structured bindings
- the region finds the sections around a point into a list the caller
  gives, so the search for the rails around a track shares no list with
  another thread
- check_rails and create_track_rail_profile are const, the pool of the
  reused chunks can't be copied

The geometry of every chunk of lk357 and td_fog, with the frogs on and
off, comes out the same as before.

* refactor: the Sonar remarks on the 3D sleepers taken care of

- the big functions of the sleepers split into helpers with one job
  each: the clusters and the lines of timbers, the gaps under the rails,
  the models and their parts, the check of the layout, the drawing of
  the timbers in instanced batches
- the tracks near a track found into a list of their own, the region
  searched into a list the caller keeps, not the one the region shares
  with the main thread; the callbacks are templates, not std::function
- the layout of a cluster takes a span of its tracks
- the globals kept in functions, the parts of a beam int constants,
  beam_overhang no longer hidden by a field of the same name
- scoped_lock, jthread, contains, ranges algorithms, std::format,
  emplace_back, structured bindings, explicit captures, upper-case
  literal suffixes, one declaration per statement
- the uniform buffer takes a span of bytes

* fix(editor): the editor core builds with GCC again

- kCrossoverStraights is constexpr, so the connection curve can take it into
  a constant expression; GCC refused a double that was only const there.
- the track_hover alias inside editor_mode dropped: declared after
  hovered_track had already used the name, it changed what the name meant in
  the class (-Wchanges-meaning); the definitions name the shared track_hover.
- <cstring> included where the rail self-test uses std::memcpy, which MSVC
  reached through other headers.

* refactor: the second round of Sonar remarks on the switch blades

- the carve of a throwable part takes the cut before it only where there
  is one, as only that cut makes it throwable
- the splitting of a grooved profile by the floor of its groove moved out
  of the rail layer into a class of its own, which is given the profile,
  the size of the rail, the texture of the plates and the side
- the rail drawing is made by a const function
- the triangles of an ear-clipped outline go in as the arrays they are,
  the search for a corner within an ear is an any_of, the loop pruning
  thin corners keeps the count it started with, as it stops at the first
- the bytes of the blocks of a texture are taken off the file through
  its buffer, with no cast of their storage
- the log of a carved part takes the tracks around it as a span
- the joint length of a switch, a constant, isn't captured, and the
  directions at the ends of a crossroads are tested in one condition each

* refactor: the Sonar remarks on the tutorial

- the window of the tutorial in smaller pieces: the steps reached, the
  lesson followed and its clip, the clip or the sketch of a lesson, its
  keys and steps, the button under it and the buttons of the pages; the
  lessons are a table of their own, the button of each kind of lesson
  picked from a switch
- a clip whose delays add up to nothing shows no frame instead of
  dividing by them
- the frames of a clip are decoded by a function of their own, on a
  thread kept with them and joined once it's done, or as the editor
  closes, instead of a detached one
- the sleepers of the signal sketch counted by a whole number, the texts
  of the sketches made by std::format, their points kept in std::array,
  the whole numbers turned into floats where it's meant

* fix: the bugs and vulnerabilities Sonar found in the editor core

- the loops stepping along a track, a curve or the view count their
  steps by a whole number and take the station as so many steps from
  the first, instead of adding a fraction up, which drifts
- the self-test of the guard rails keeps the plan of the rails of the
  track against while it goes through them: the range of the loop was
  in a plan made for it and gone before the loop began
- the generators of the self-tests and of a unit test are seeded on
  purpose, so a run can be repeated: marked for Sonar as such
- the tool writing the descriptions of the templates takes the names
  out of its tables only where they stay in the data folder

* fix: the loops of the signalling stepping by a whole number

the places of the block signals along a line and the marks of the
chainage under the plan of a station are counted by a whole number and
taken as so many steps from the first, instead of adding a fraction up,
which drifts; Sonar took the counters of floats for bugs

* refactor: the checks of the signal heads and the signal sheet in smaller pieces

the remarks Sonar made on the signal descriptions: the warning about
a disc on the mount of a signal is worked out by a function of its own,
the fit and the aspects of a head, the swap of a template and its
aspects in the sheet of a signal are drawn by members of their own, the
walk over the events of a signal is a free function instead of a
std::function held by a lambda, and the description of an include is
read a part at a time; the names of the kinds are kept in a std::array
and looked up by the algorithms of ranges, a name is taken as a
std::string_view where it is only compared, and the locals named event,
which hid the enumerator, are renamed

* style: a space after a comma in the join self-test

* style: a space after the question mark in the terrain sketch

* style: a space after the question mark in the status of the fitting

* refactor: the last Sonar remarks on the small fixes

the opening of a scenario catches the exception the scenery throws when
it can't be read, not any runtime error; the vehicle moved between
trainsets keeps its source by a reference to const; the messages of a
track of an unknown type and of a tributary are raw string literals;
the parser opens a file by a std::filesystem::path, and the log of a
file it can't open still names its folder and its name

* refactor: the crossings of a track found without casting its const away

the radius of a node can be read off a const one: radius_() is const
across the nodes, the ones of the tracks and the models marked override,
and a const radius() gives the radius worked out already, or works it
out anew without keeping it; the helpers finding the crossings of a
track only read it and take it const, its own run of rails typed apart
from the ones of the tracks it crosses, which the crossings found name;
the triangles of a filled outline are pushed as named corners

* refactor: the paths around a track sampled without casting its const away

the sampling of the paths and the clusters of tracks laid together only
read the tracks, so they take and keep them const: the path sampled
points at a const track, the tracks near one are found from a const one
by its const radius, and a cluster holds const tracks; the shared zones
of the timbers no longer cast the const of their track away

* fix(editor): the Sonar blocker remarks on the stack, no side effects in the operands of && and ||, no local named final (S912, S1669)

Counting the leftover signals, the pieces of a station walk, the places with nothing beside a run and the joints and fouling points
logged by the self-tests no longer counts inside a condition; the last span of a straight is named tail. The counts and what they
log are the same.

* revert(vehicle): an axle on a switch follows the switch as it is set, as before the stack

The axle kept to the path it came on, so a switch thrown under a moving train no longer sent the rest of it onto the other
branch, and coming from the frog end it trailed shaped blades only where the wheels reached them. That changed the running of
every switch in every scenery, and the AI still scans its route by the switch as set. TrkFoll is as on master again, and the
trailing point of the blades it used is gone.

* revert(track): a path is told a straight by its first control vector alone again, as the sceneries are made for

A plain track was drawn bent where its second control vector was off the chord though the first lay along it, and a path with a
radius given was never straightened. Tracks of existing sceneries drawn straight before would have been drawn bent, with their
length, cant and the models along them. TTrack::straightened is the rule of master, for plain tracks and the paths of switches.

The editor keeps a bend dragged with the second control vector, or set by joining the tangents, by moving the first one 2.5 cm
off the chord to the side of the bend, past the tolerance, so the track is drawn, saved and read back bent, by older builds too;
the second one dragged back along the chord takes the first one back onto it.

* feat(track): the switches joined directly to other switches at load told in the log

A switch right after another one is joined to it as the sceneries load, where its end was left open before and vehicles came off
the track there. Each switch joined so is logged with its place and the number of ends, and the whole number once, so a scenery
can be checked for places that run differently now.

* fix(editor): a bend kept by lengthening the first control vector, not turning it

keep_bent moved the first control vector 2.5 cm sideways, which turned the
start tangent: a kink of 0.29 deg on a 15 m track, flagged by the joints
check, and against the fixed direction at a switch or a locked track.

Now the vector keeps its direction and gets 2.5 cm longer than a third of
the chord, which the simulator no longer takes for a straight. It is also
applied after an end is moved or snapped, since a new chord or a snap onto
a neighbour could bring the vector back within the tolerance. With the
second vector back on the chord, the first goes back to a third of it.

* fix(track): each switch joined directly to another one logged with both names

join_switches counted ends, while one join links both switches, and only
the first switch of a pair was named. It now returns the switches joined
to, and the log names both of each joint and gives the number of joints.

* fix(editor): a path drawn bent is kept bent through every edit, one drawn straight is left as it is

The first control vector is made longer past the 2 cm tolerance only where the path was drawn bent before the edit, or where
the edit itself sets the second vector: the end of the path moved, its first vector, its second one, a neighbour followed or
its grade taken, the controls aligned at a joint, an end snapped. A path drawn straight keeps being straight when its ends
move, and the paths of a track that the edit doesn't bend aren't changed. Moving the second vector back along the chord takes
the first one back to a third of the chord where it was made longer here.

* fix(app): a scenery that can't be opened takes the game back to the launcher whatever the file system throws

Catches std::runtime_error again, as master did: invalid_scenery_exception is one of them, and so is what the file system
throws while the scenery is opened.

* fix(track): the beams worked out in the background don't read the ends a switch is set to

The ballast a switch trackbed takes is asked of the tracks joined to its main path, as the trackbed is made at the load,
not of the ends the switch is set to now, which change as it's thrown while the thread runs. What the thread reads with no
lock against the main thread is written down where it runs, with the two things driving can change: a switch thrown and a
turntable turned.

* perf(render): the cut faces of a track drawn with nothing put on the heap, a track with none passed over at once

* chore(track): the switch drawing the cut faces in the unrolled material read only in the builds with the self-tests

* docs(track): the blades flag said to be switched on, and what frogs in eu07.ini changes of it

* fix(editor): a response over 64 MB is refused, curl kept to http and https, the address read as UTF-8

The body of a map or of a service the user typed is read into memory up to 64 MB and fails above that, with WinHTTP and
with curl. curl follows at most 10 redirects and only to http or https. WinHTTP gets the address widened from UTF-8, so a
pasted one with letters past ASCII isn't turned into garbage.

* fix(editor): only the orthophoto an older editor kept is deleted from the settings folder, not all its cache

The geoportal folder of the old cache is removed, and the cache folder itself only where nothing else is left in it.

* fix(editor): the square metre of the outlined area written as its UTF-8 bytes, shown right where /utf-8 doesn't reach

* docs(track): why the velocity read for a switch is put back after its segments are made

* fix(track): the blade tips and the open ends of a track take the dark of the rail, not the colour of a worn tread

No wheel runs over them, so their cut faces aren't drawn as worn: the beige the matte material gives a worn face is left
to the cut faces of the frogs.

* fix(editor): a neighbour followed or given its grade is bent only where its second vector really changed

follow() and follow_grade() write the second vector of a track joined at its end back as it was when the joint didn't
turn or keep its grade; a track the simulator draws straight with that vector off the chord was made bent then, though
the edit never touched it. Its first vector is lengthened now only where the path was drawn bent or the second vector
took another direction or grade.

* fix(track): the open ends of a track laid with cuts take the dark of the rail too

The rails a frog or a crossing cuts are laid piece by piece; the caps of their pieces at the open ends of the track were
drawn worn with the cuts of the frogs. They aren't worn now, as the open ends of the other tracks.

* fix(editor): a neighbour drawn straight is bent only where the edit took its second vector off the chord

follow_grade() sets the height of the second vector anew on every graded joint, a fraction of a millimetre off the height
the scenery has, so a change of the vector bent a track whose second vector stood off the chord sideways already, though
the simulator draws it straight. follow() and follow_grade() keep a path drawn straight bent now only where its second
vector lay along the chord before the edit and stands off it after; a path drawn bent is kept bent as before. How far the
vector stands off the chord is measured in one place, keep_bent() uses it too.

* docs(editor): the comment of keep_bent above keep_bent again, not above the measure of the chord

* Editor: signal reads kept by the signal, level crossing discs, signals out of the gauge, indicators, the signalling tools split (#307)

* fix(editor): the read of a signal stays by it as its track is split, on a switch and when it is moved, and a level crossing disc is placed

The trains find a signal by its read, a passive event in a list of the track, and measure the way to the cell it reads along three
tracks further at most. The editor let the read drift away from the signal, or put it where trains of another path read it.

- A track split in two: a read the trains scan for (a passive event) goes to the piece by the point it reads, whatever its list;
  before, those of the runs towards the end stayed on the first piece. Five splits left the reads of A, B, C and J on the first
  piece while the signals stood on the sixth, out of the reach of the trains. The reads of signals placed since the scenery was
  opened, not bound to an event yet, go to the piece by their signal the same way.
- A signal moved off its track jumped back to that track's end once the track was changed: the track had taken it up as its
  object and measured it again along itself. A moved signal is let go by the track it stood by, and an object of a single point
  moved off the side of its track no longer follows it.
- A switch reads its events to the trains of both its paths. A signal past the frog of a path, where the axes are a gauge apart,
  is passed by the trains of that path only, so its read goes to the track joined to the far end of the path, in the list of
  the trains running from the switch onto it or the other way. Before the frog it stays on the switch. Moving the signal across
  the frog takes the read between the two.
- A signal by a switch on the side of its other path stood on that path, in the way of its trains (0.45 m from its axis); it
  is refused there, placed or moved, with the reason.
- The kind crossing of the descriptions (tsosp, tsospn) is known: the level crossing disc is listed in the palette and placed
  with its read.

Checked in the editor on a hidden desktop: five splits of a track with bound and fresh reads, a signal moved to another track
and the old one raised, signals placed before and past the frog of a switch on both paths, turned and moved across the frog,
saved and opened again with the reads bound, the tracks raised, shifted and bent with the signals following. Unit tests pass.

* fix(editor): a split keeps reads far off the path and bound objects up to 30 m by their pieces

A read the trains scan for moves to the piece by the point it reads only from event1 and event2, only
when it isn't ignored and only when that point is within 50 m of one of the pieces; a read at the
station building stays in its list. An object bound by hand keeps its binding as its path moves up to
30 m from it, an adopted one up to 12 m as before.

* feat(editor): the tracks that read a signal are drawn and can be picked, flipped or dropped

The selected signal shows each read of its _sem_info as a thick band over the reading track, arrows
in the way the read is scanned, a line from the foot of the signal and a plate with the list and the
track; the hovered one shows them thinner and placing or moving a signal shows where it will be read.
The panel lists the reads: each can be turned the other way or removed, "Pick the path" takes a
click on a track (with Shift one read more or less) and "By the path it stands by" puts back the
read the signal gets when it is placed. Each change is one step of the undo.

The self-test gets signalread, signalreadflip, signalreaddrop and signalreaddefault, and the probe
lists every read of a signal.

* fix(editor): a moved or turned signal keeps the reads picked by hand, and a read set again isn't an undo step

Moving a signal, taking it across the track or turning it put back only the read by the track it
stands by and dropped the others: those stay on their tracks now, on the other list when the signal
is turned. Setting the reads the signal has already says so and adds no step to the undo. Picking a
reading track disarms the template, so a click after Esc doesn't place a signal, and the signals
are listed again after any change of the history, also once it is full.

* feat(editor): a signal is placed out of the gauge of the tracks around it

As a signal is placed, moved, taken across or turned, its models are measured against the gauge
chosen in the Gauge window along every path near it. One that enters it is taken sideways, away
from the axis of the track whose gauge it enters, as deep as it went in and 3 cm more, in the same
step of the undo; between two tracks too close for it, it stays where it was put and the status
tells which gauge it enters and how deep. A gantry is only measured.

The panel of the selected signal tells when it stands in the gauge, with a button to move it out,
and the view marks the deepest place. The gauge tool measures any models against the paths around
them for it. The self-test places a signal at a given offset and its probe tells the gauge.

* fix(editor): a moved signal leaves only the read of the track it stood by, and the gauge is checked on its level

The reads a moved signal keeps were all but the first one listed, which is the first track of the
scenery having it, not the one the signal stood by: a read picked by hand could go and the track
it left could keep it. It is the read of the track it stood by that goes with it now, and turned,
eventall1 and eventall2 swap as well. A track more than 2 m above or below the foot doesn't push
the signal aside, the status tells the real distance it went, the gauge is measured again when the
signal follows a dragged track, and the marker in the view shows only what is up to date.

* feat(editor): indicators put on a signal from the panel, they move and go with it

The indicators of scenery/pkp/wskazniki described as "category: indicator"
are offered under the selected signal, grouped by their sign. One is put
in as an include named after the signal, on the srk layer:

- a lit one (place: head) under the lowest lamp of the signal, 0.73 m
  below it and 5 cm ahead of the mast, each next one 0.45 m lower; a dwarf
  signal is refused, it has no mast for one;
- a plate (place: foot) at the foot of the signal, its model has its place
  by the mast built in.

The panel lists the indicators standing by the signal with a Remove
button. They are found as the includes whose first parameter is the
signal's name, within 1 m of it in plan. When the signal is flipped,
turned or moved, they keep their place in its frame, in the same undo
step; deleting the signal deletes them too. If the signal and the
indicator both define an event, the status says so, since the scenery
keeps only one of them.

The self-test gets signalindicator and signalindicatordrop, and its
signalprobe gives each indicator's height and the height of the lowest
lamp.

* feat(tools): indicator descriptions and the indicators taken out of the signal templates

indicator_headers.py writes //$e descriptions into the LED indicators of
scenery/pkp/wskazniki (W19, W20, W21, W24, W26) with the events each
shows. It also makes the indicators that were so far only built into the
signal templates:

- W1 of the warning discs, new, old and with the light strip;
- W1 and W18 (new and old) of the block signals;
- the I, II and III plates of the repeaters.

The plates fixed flat to the mast are moved 4 cm ahead. Their back is
5 cm from the mast's axis, while the mast is 6.1 cm thick and its clamp
under them 8.3 cm, so the mast went through the plate, in the templates
too.

* fix(editor): a signal turned or moved by the gizmo is read and kept out of the gauge, its indicators go with it everywhere

The gizmo of an include only rewrote the numbers of a signal. Its read stayed on the event it had, even when the signal was turned
to the trains of the other direction. Its indicators stayed behind, its height could be dragged off the ground, and the gauge
wasn't checked. Now:

- the gizmo moves a signal in the plan only, at the height it has;
- while it is dragged, its indicators keep their place by it;
- once it is let go, the drag is made again as a move of the signal tool, one step of the history: the read goes to the event of
  the trains it faces on the path it stands by, and it is taken out of the gauge;
- dropped away from every track, it goes back where it stood.

The indicators of a signal are found in the scenery now, not in the list the signal tool keeps up only while it is open:

- deleted from another tab, the signal takes them with it;
- a signal renamed in the node properties gives its new name to them in the same step of the history;
- in the station and line batches, a renamed signal renames them, and a removed one removes them;
- the binding of objects to tracks puts them on the path reading their signal, not on the one nearest to them, and a signal moved
  by hand lets go of them too.

Also:

- a signal on a gantry takes no indicator from the list;
- an indicator a signal has already isn't put on it twice;
- the signals and their indicators are found in one pass over the includes, the indicators by the name of their signal;
- a step of the history with tracks is always one of their edit, so they are taken back with the includes.

The self-test gets signalgizmo, which turns and moves a signal as the gizmo does.

* fix(tools): indicator_headers.py keeps the files it replaces, writes beside the data on request

- An indicator it made, found changed, is put into a tar in editor_backup before it's written again.
- --sidecar writes the descriptions of the lit indicators into editor/templates, as the other header scripts do, the files of
  the game left alone.
- The indicators it makes are copies: the signal templates keep their own, and the docstring and the files say so.

* fix(editor): a signal moved by the gizmo by another track is read by it, the templates known without the signal tool

- At the end of a gizmo move the nearest track takes the signal when it is nearer than its own by more than 0.5 m; a track it
  was dropped onto, within 1.2 m of its axis, doesn't, so a signal only turned between two tracks or dropped onto one in a
  switch keeps its own.
- The signal templates and indicators are looked for when a signal is renamed or its gizmo shown, so its indicators follow
  without the signal tool opened first.
- A drop refused puts the gizmo and the node properties back where the signal stands.
- The indicators follow only once the gizmo made its step, and the ones not changed are left alone: grabbed and let go it
  changes nothing.

* fix(editor): a signal dropped by the gizmo onto a track keeps its own, the gizmo doesn't wait for the template scan

- When the nearest path to the drop is within 1.2 m of its axis, the signal keeps its own track, instead of only that path
  being left out: dropped onto a middle track it no longer goes to the track beyond it.
- The gizmo starts the signal template scan without waiting for it, so a rescan with a signal selected doesn't stop the
  editor; renaming a signal still waits.

* feat(editor): the signalling split into Signals, Station, Station signals and Line block

The one Signalling tool held the signals placed by hand, the whole wizard of a station and its checks; each is now a tool of its
own in the toolbar:
- Signals (I): the palette, a signal placed by a track, dragged along it, selected; a click on a switch no longer opens a station.
- Station: LMB on a switch lays the station out; its name, code, line, km, speed and braking distance, the numbers of the
  switches, the track circuits, the number of the selected track, the list of the switches.
- Station signals: the signals of the whole station placed at once, the template of each of their kinds (main, shunt) chosen in
  a table, and below what the signalling lacks: the repairs, the SHP resonators, the track lengths, the signal heads.
- Line block: the block of each line, the block boundaries drawn by hand, the line signals, the templates of the block signals
  and warning discs.
The station tools share the open station and its schematic; Station signals and Line block show what the Station tool set for
it, the line and the km in red where the line block needs them. The template table replaces the palette in the station
tools, so choosing a template there no longer arms placing. Two icons drawn for the new tools, in editor_icons.py too; the
png is drawn by the same shapes, Pillow wasn't at hand. The tracktab self-test takes a tool by its name, and srkopen shows the
Station tool.

* feat(editor): a signal shows its distance from the track axis and to the switch ahead, and goes to 50, 100 m... from it

- editor/editorTrackTrace: the track followed the way a train runs, shared by the W17 markers and the signals. The fouling
  point of a switch (where the axes of its tracks are 3.5 m apart) moved here from the lineside tool, and danger_ahead
  finds where a train first comes to a switch: the start of one it runs onto from its start, or the fouling point of one it
  runs onto from behind, which may lie behind the point (a signal in the fouling zone).
- The card of the selected signal: its distance from the axis of its track, and along it to the start or the fouling
  point of the switch ahead, in red when it stands inside the fouling zone. The overlay draws the same as a dimension line
  beside the track on the side of the signal, with the distance at the place.
- Placed, dragged along or moved with the gizmo, a signal goes to a round distance to the switch ahead (50 m steps) when
  within 2.5 m of one; Alt keeps it where it is. The drag of a new one is measured from where it was pressed.
- The fixes of the review of the split: the click label of the station tools in their own branch and a plain select in
  Signals, the card of a signal picked from the check lists shown in Station signals, and the help texts naming the
  Templates table and the Signals tool.
- Self-tests: signalprobe logs the distance from the axis and to the switch ahead, signal snap=1 snaps as placing does.

* feat(editor): the fouling point widened in the curves under 250 m, as the standard of the gauge says

Standardy techniczne PKP PLK, tom II (from 2025-07-17), 6.5-6.6: the W17 marker stands where the axes of the tracks are
nominally 3.50 m apart; where one of the tracks lies there in a curve under 250 m that spacing grows by the widening of the
gauge from its radius (annex 1, table 1), the widenings of both summed when both lie in curves.

- editor/editorFouling: the fouling point found along the axes of the main track and the branch, standing on its own: at
  each point of the branch the spacing wanted is the nominal one plus, for each track, the widening on the side of the
  other track from its radius there (taken over 5 m each way): 50000/R - 185 mm towards the centre of the curve,
  60000/R - 225 mm away from it, none from 250 m up.
- gauge::curve_widening gives table 1 of the gauge the editor checks already.
- The W17 tool and the distance of a signal to the switch ahead both use it; the card of a signal shows how far apart the
  axes are at the fouling point, the help of the W17 tool says where the figures come from.
- Unit tests: a straight branch at 1:9, a branch in a curve of 300 m (no widening) and of 200 m (outer widening), both
  tracks in curves (both widenings summed) and a straight branch off a curving track.

* feat(editor): the cant leans the cars into the fouling point, and the fixes of the review of the metre

- The fouling point takes the cant in, as Ie-1 wants it placed "with the gauge, the cant and the widening in the curves":
  the cars of a track on a cant lean towards the inside of its curve by D Hi / 1500 (bD of table 1 of the standard of the
  gauge), so when the other track lies on that side the spacing wanted grows by it, taken at 3.05 m over the rail top, the
  top of the widest part of GPL-1. The cant of each point comes from the roll of its path as the gauge tool takes it. At any
  radius, as the table has it; the track leaning away adds nothing.
- Below 150 m, where table 1 ends, the widening from the radius is that of 150 m rather than the formula run on.
- A switch run onto from behind has its fouling point looked for once its own path is walked too, so one lying on that
  path is found rather than skipped for a farther switch.
- A point behind a signal lies on the track of the farther end of its segment, so a signal snapped back over a joint lands
  at the round distance rather than at the joint.
- Alt keeping a signal off the round distances reads the key from ImGui, which Global.altState misses while ImGui holds the
  keyboard. The gizmo doesn't snap a signal: a1d10bb0 says it does, it's placing and dragging with the tool only.
- The help of the distance on the card stays on the distance, the spacing of the axes under it. The unused
  track_trace::nearest_on is gone.
- Unit tests: the cant leaning towards the other track in a curve and at 300 m, nothing when leaning away, and the table
  ending at 150 m.

* fix(editor): the cars lean the way the cant of their track tips them, taken 3.25 m up

- The cant along the trace keeps its sign: a roll above 0 lowers the left rail of the path (as the editor lifts its
  terrain by it), turned to the way the track is walked. A track adds the leaning of its cars to the spacing wanted at the
  fouling point when the other track lies on the side its lower rail is, whichever way it curves: a branch on a cant
  against its own curve leans towards the main track on its outer side, which d70f189c missed, and a cant on the straight
  counts too.
- The leaning is taken 3.25 m over the rail top, the top of the widest part of the cars, rather than 3.05 m of GPL-1.
- Unit tests: a cant against the curve, a cant on the straight, and the leaning away still adding nothing.

* fix(editor): the station tools tell by the mouse what a button came to, and the fields of a station read as empty

What a button of the Station, Station signals and Line block tools came to was written at the foot of the panel, under the
lists, scrolled away: a click which refused for want of the code of the station looked as if nothing happened. It's told now by
the mouse which clicked, a refusal in red as the other tools do, and in the status bar. The fields of a station still empty
show their examples as such, "e.g. BPd", not as values typed in; the Station tool says above its steps that the code is to be
typed first, Station signals that the code and the track circuits are wanted, the code marked there as needed.

The check of a warning disc and of a block section went by the braking distance of the station, while Set the line signals
places them by the one of their line: on lk357 a disc placed 700 m before Z, the line run at 100 km/h, was marked as standing
nearer than the 1000 m of the station. A signal of a line out is checked by the braking distance of its line now.

* feat(editor): the joints of the track circuits put, moved and taken away by hand, kept by the station

The Station tool gets Edit the joints by hand: LMB on a plain track of the
station puts a joint there, LMB on a joint takes it, then on a track moves
it, on it again takes it away. The circuits are set again at once, one step
of undo each. The joints so changed are kept in the //$s record of the
station (joints +x/y/z for one put, -x/y/z for a planned one taken away),
so Set the track circuits keeps them; As planned forgets them. The undo
step carries the hand joints of the station with the tracks.

srkjoint drives it in the self-tests.

* feat(editor): the indicators under the lights reordered, a signal set from the axis and raised, standing on the ground by default

The indicators under the lights of the selected signal get arrows up and
down: one changes places with the indicator above or below it, a plate at
the foot keeps its own. One step of undo each.

The distance of the selected signal from the axis of its track is typed in
the panel, it moves across as far along the track as it stands, the gauge
pushing it out again where it comes too near. Its height is set the same
way, raised over where it stands by default, over the rail heads on a
gantry.

A signal is put on the ground by default, the zero of its model 0.38 m
under the rail heads: the ground lies 0.35 m under them as Ie-102 draws it
(Lx), the foot of the mast stands on the foundation 3 cm over it in the
models of pctga, and the sceneries made by hand (Wrzosy, Baltyk) stand
their signals 0.20 m under the rail foot so. It stood on the rail heads.

signalindicatorswap and signalacross drive it in the self-tests.

* fix(editor): the hand joints of a station without a record, of its ends and of another station; a dragged signal keeps its place across and its height

- Edit the joints by hand on a station not described yet read the record
  of index -1: the hand joints are shown only for a station with one.
- The joint between the station and a line out of it can't be taken: taken
  away, the circuit of the switch ran on over the tracks of the line.
- A joint held is let go when another station opens, a move by less than
  half a metre lets it go, and a change no step of the history takes is
  undone, so the undo knows every change of the joints.
- A signal dragged or snapped along its track keeps its distance from the
  axis and its height over the default, set by hand or standing so before.

* fix(editor): a dragged signal carries what it had by its own track; As planned forgets the hand joints that change nothing

The distance from the axis and the height of a dragged signal were taken
against the track it was dropped onto: dropped on the next piece of its
line, on a grade or by a parallel track it came out too far, in the gauge
or off the ground. They are taken as it stood by its own track at the
start of the drag. As planned clears the hand joints even where the
circuits come out the same.

* fix(editor): a signal stands as high over the rail heads as its include gives, lowered only where its bottom would hang over the ground

The default height of a signal was 0.38 m under the rail heads for every model. It is now read from the
description of its include, `//$e signal: {..., height: <m>, depth: <m>}`: height is where the zero of the
model stands over the rail heads (by Ie-117 § 15 the top of the foundation of a mast 0.10 m under them, of
a dwarf 0.20 m), depth how far the model reaches under its zero. With a depth, a signal whose bottom would
hang over the ground, down an embankment, goes down onto it, by at most 3 m (more is taken for a bridge).
Without a height the zero stands at the rail heads.

"Raised" in the panel, a signal moved across or dragged, all count from that default height.

* fix(editor): a signal flipped, given another template or its variant for the other side stays as raised as it was

The default height now depends on the template and on the ground under the signal, so keeping the height
as it was no longer keeps the raise. Flipped to the other side of the track, the signal is raised over the
default there as it was over the default on its own side. Given another template (Swap), or the variant of
its template for the other side when moved or placed, it goes up or down by how much the default height of
the new template differs from the old one.

* fix(editor): As planned forgetting hand joints that change nothing is a step of undo of its own

With nothing in the circuits to change no step of the history took the forgotten joints, so they went with no undo for it: Ctrl+Z took back the step before. The anchor of the station as it is now carries them in a step of their own. The signalmove selftest gets its carry indented with the block it is in.

* feat(editor): an indicator under the lights goes in its place by Ie-117, from the top W21, W24, W20, W19, W26

Put on a signal, an indicator under its lights was put below the ones there. It now goes in its place by Ie-117 section 12.1 among them, under the last one it doesn't go above, the others (W18 and the rest) below these; the ones under it move a place down, in the same step of undo.

* fix(editor): the signal card and the move of a signal keep no pointer across a refresh of the signals

- The card of the selected signal went on after "To the other side" or
  "Turn around" with found pointing into the list of the signals
  standing, which their refresh had just replaced: the indicators and
  the gauge of the card read freed memory. It now ends that frame there.
- signal_move_to read the mount of the template after the refresh,
  which may scan the templates again; it is taken before it.
  signal_place takes a copy of the template given for the same reason.
- The fouling test counts its metres with an int, and the search of the
  middle point of the radius is a while loop (no floating loop counter).

* fix(editor): the dimension line to the danger point counts its metres with an int (Sonar S2193)

The line drawn by the track from a signal to the switch or fouling point
ahead stepped a double by 1 m. It now counts the whole metres with an
int from the same first one: the points are the same, since adding 1 to
a whole double and adding a whole int to it give the same values.

---------

Co-authored-by: maj00r <maj00r@host>

* feat(editor): ride the camera along the tracks, and a minimap with stations by their W4 (#317)

* feat(editor): the camera rides along the tracks, over the joints and switches and over to the tracks alongside

Y puts the camera onto the track under the cursor (or the nearest one), looking along it 3 m over the rails.
W/S drive it ahead and back the way the camera looks, Shift and Ctrl faster (20, 60, 250 m/s); A/D take
it over to the track alongside, a click to any track; E/Q and the wheel raise and lower it; the mouse looks
around as when flying. At a switch entered from its blades it goes straight on, Z picks the turnout for the
camera alone: no switch is thrown, no track learns of the ride. The bar over the view shows the track, the
km, the speed, the height and the switch ahead. Y or Esc ends it. Self-test commands ride, ridewalk,
ridejump, rideahead, rideprobe and rideleave.

* feat(editor): a minimap of the tracks with the camera on them, and the stations found by the names of their W4

View / Minimap and stations (W4), Ctrl+M: a window with the rail tracks seen from above, the camera as
a triangle the way it looks, the track ridden along in orange and the stops of passenger trains as dots
with the names of their stations. It follows the camera, or is dragged and zoomed apart from it; a
click takes the camera there, riding along the track onto the track there. Above it the stations the
PassengerStopPoint memory cells and events name, searched by a part of the name with or without the
polish letters; a click (or Enter for the first found) flies the camera over to the stop looking along
the track, riding it rides on from there, each click to the next W4 of the station. Self-test commands
minimap, stations, station and minimapclick.

* fix(editor): the ride and the minimap after the review, with fewer words on the screen

- Ctrl+S, Ctrl+Z and the other shortcuts reach the editor while riding; Esc closes
  an open popup first
- no key stays held when a window takes the keyboard, the place is kept within
  a path that got shorter, a release of the mouse goes where its press went
- the minimap keeps under the vertex limit of a draw list, Enter in the search
  goes round the stops of the station, the marked station stays marked
- the bar of the ride is one line: the track, km, speed and height; the switch
  ahead under it, the keys only while standing
- the minimap in the Map menu, opening over the view, with short texts; the
  context menu of a track rides along it

* feat(editor): the ride drives with the right button held, as the camera flies, and the editor works on along it

- W/S, A/D and Q/E drive the ride only with the right button held; without it
  they're the editor's keys again (Q/W/E the gizmo)
- the left button and Esc go to the tools while riding: tracks and objects are
  laid and selected from where the ride took the camera; Y leaves, a flight of
  the camera to a framing leaves too
- after the review: the help names Ctrl+W/Ctrl+Down as the much faster drive,
  the stops of the minimap stay within the vertex limit, the search field lets
  the keys go after Enter

* fix(editor): the tools keep their wheel and the menu of a track its click while riding, a pan or the view from above ends the ride

---------

Co-authored-by: maj00r <maj00r@host>

* feat(editor): signals placed by the editor get a name plate drawn by python (#316)

* feat: Elf emergency brake position in the master controller (eu07/maszyna#413)

The Elf's master controller (EIMCtrlType 2) gets an optional emergency
brake position below its position 0, turned on by the new .fiz key
EIMCtrlMainEmergency=Yes in Cntrl (default No, no change without it).
With it the old positions move up by one (MCPN 5, neutral at 4): the
emergency position brakes fully at once and vents the brake pipe, like
the alarm chain or the Impuls's EIMCtrlEmergency. The loader raises a
too small MCPN to 5 and logs it. The Elf code with hard-coded positions
(CheckEIMIC, the MED full braking, the AI) takes the shift into account.

SVN data to change afterwards (dynamic/pkp/elf_v1, needs this exe):
- every .fiz with EIMCtrlType=2: EIMCtrlMainEmergency=Yes, MCPN=5,
  DirChangeMaxPos=4 where present;
- the cab .mmd mainctrl entries: offset one notch lower (-0.06 -> -0.09),
  sounds shifted one index up, new sound0 with
  26284_elf_nastawnik_nagle_*.wav.

Issue: (eu07/maszyna#413)

* fix: Elf emergency brake position vents the pipe only from the driven vehicle, coupled units agree on the controller position

The emergency position of the master controller vented the brake pipe from
every vehicle whose controller stood there, and "MainCtrl" reached the coupled
vehicles raw, so an Elf with EIMCtrlMainEmergency and one without it disagreed
by one notch (the full braking of one was the emergency brake of the other,
neutral of one a power position of the other). The pipe is now vented only
from the vehicle driven from (IsCabMaster()), and the position goes to the
coupled vehicles in the positions without the key (MainCtrlPosForCoupled(),
the emergency one as the full braking), each adding its own shift on receiving
it (MainCtrlPosFromCoupled()).

The loader's fix-up for the old MCPN=4 raises DirChangeMaxPos by the same
shift, so the reverser keeps working at the new neutral.

* feat(editor): the signals the editor places get a plate with their name, drawn by python

A signal placed with the signal tool used to get the plate texture of
textures/tabl named like it, or none at all. Now, unless a texture is
picked, its plate is made by python/local/signal_plate.py:
"make:signal_plate?name=<name>", a light plate with a dark edge, four
screws and the name in black, the way the plates of textures/tabl look.
Renaming the signal in its properties renames a drawn plate with it; a
picked texture stays.

The templates put the plate after a folder, "tabl/(p6)", so
material_data::assign() takes the folder off a skin which names a
texture made by a script.

* fix(editor): a drawn signal plate keeps following a cleared name, and isn't made for a name it can't carry

Clearing the name of a signal in its properties made its plate the drawn
plate of no name, which then never followed the name again. A drawn
plate now follows any rename to a name, and keeps the last one while the
name is cleared.

A name with '|', '&' or '?', or one longer than 64 characters, gets no
plate (0_nothing) instead of a broken one: '|' splits the skin, '&' and
'?' the query of the script, and a very long name made a path too long
for the file system when the skin was looked for on the disk.

* fix(editor): a signal plate keeps its last name through a name it can't carry, and a plate named by hand stays

Renaming a signal to a name its plate can't carry turned the drawn plate
into 0_nothing, and it stopped following the name for good. Such a name
now leaves the plate with the last usable one, like a cleared name does,
and the plate follows again once a usable name is typed.

A drawn plate whose name was given by hand, different from the name of
the signal, is no longer replaced on a rename: only the drawn plate of
the signal's own name follows it.

* feat(editor): the drawn signal plates come in three looks, plain, toned and aged

The plate drawn by python/local/signal_plate.py looked too clean. It now
takes a look in its query, "make:signal_plate?look=toned&name=Tm12":
plain is the bright plate it was, toned a greyish field with a little
grain and dust towards the bottom and the sides, a thinner edge, smaller
screws and graphite letters, aged a darker, grainier and dustier one.
Toned is drawn when no look is given.

The signal tool picks the look under the plate, kept in the settings of
the editor. A rename of the signal in its properties keeps the look of
its plate.

* perf(editor): the grain and the dust of a drawn signal plate are made on whole images

The toned and aged plates shaded their field a pixel at a time in
python, about 34 ms a plate with the interpreter held, so a station of
a hundred signals in view kept the python queue, and the screens of the
cabs, waiting for seconds. The dust is now made once per look, and the
grain from random bytes of the name, both put on the field with
ImageChops: about 2 ms a plate. The mean colour of the plates stays the
same; only the grain falls differently.

* fix(editor): the station signalling draws the plates of its signals as their schematic names them

The plates the station signalling places and renames say what its
schematic shows (Tm3, F1, ToA, a block signal without the stem), and a
template swapped in for a signal without a plate draws that text too
rather than the small letters of the name. A signal left for removal
gets a plate of no text again, not one saying "_old".

No plate, 0_nothing, or the texture named like the signal, what the
editor gave before the plates were drawn, become the drawn plate when
the signal is renamed, in the properties panel as by the station
signalling, in the look set in the editor.

* fix(editor): a plate of a scenery named like the end of the name of its signal stays through a rename in the properties

A texture pzs_a was given by its scenery as a, its real plate: a rename in the properties panel keeps it. Only the station signalling, which looked its plates up that way, takes such a one for its own.

* feat(editor): the drawn signal plates are 256 pixels across, sharp up close

The edge, the screws and the blur are drawn bigger by as much as the plate is, and the grain is as coarse as before, so the three looks stay as they were. The smallest letters tried grow with the plate too.

* feat(editor): a drawn signal plate takes a speed index and the m of shunting signals, typed in the signal tool

signal_plate.py draws the speed index after the name, one digit up at
its right or two as a fraction across the height of the letters (index=4,
index=12 for 1/2), and with m=1 an "m" on a strip of its own under the
name, as Ie-1 marks a semaphore giving shunting signals and as the
textures/tabl a-12m plates show it.

The signal tool has a field for the index and a box for the m under the
look of the plate; the hint of the plate names them (B 1/2 m). The
style of a drawn plate, its look with the index and the m, stays with
it through a rename, in the properties panel and by the station
signalling, which sets neither. The signal selftest takes index= and m=.

* fix(editor): the speed index of a plate takes only digits as they are typed

The decimal field let in signs and dots, which stayed shown while the index held only the digits, and filled the two places before a second digit could go in.

* fix(sonar): the remarks on the drawn signal plates, to pass the quality gate

The new code of the plates was 5.2% technical debt against the 5% of the
gate. Fixed the small remarks; the big functions stay as they are:
- the speed index field and the plate looks are std::arrays, the index is
  copied without snprintf, the combo of the looks has a function of its own
- ranges algorithms, a string_view for signal_plate_drawn, emplace_back
- signal_plate.py: dict literals, a cache of fonts not named like FONTS,
  no unused local, the name and the m drawn by methods of their own; the
  plates drawn are byte for byte the same as before

---------

Co-authored-by: jerrrrycho <jurek.pakula@gmail.com>
Co-authored-by: maj00r <maj00r@host>

* fix(editor): the tutorial and the hints tell of the kilometrage, and the first lesson takes O either way

The kilometrage (X) was in no hint, no shortcut list and no lesson, though the hectometre posts and the block signals are numbered after it. The row of the track tools now reads L T G N U I X B P V J, the turntable with it, and F1 lists I / X / B. The lesson of the signals and the posts says what X does and where the posts take their numbers from, the km of the line or the km typed in their panel for the place clicked, and it opens with the kilometrage tool too. The first lesson asked to switch to the view from above, which a scenery made in the wizard opens in already: O either way does it now.

* fix(editor): master's road lifting texts translated, and the panning by the wheel told of in 3D too

The merge of master left the status and the label of the lifting of the road points in English: both go through the translations now. Master pans the 3D view by the wheel as well, so the lesson, the hint row and its line say it works in both views. <cstring>, dropped from the road tool before, came back in the merge and is gone again.

* fix(editor): the tools of a plain line in sight, the km of a line set once, a lesson of a whole line and of the ride along a track

What a layman building a line with signals and posts couldn't find:
- The Signals, Kilometrage and Posts tools are in the main row of Tracks, after the tools of laying; the stations, their signals, the line block, the turntable, the trainset and the checks stay behind More.
- "Objects" was where the hectometre posts are: the tool is Posts now (Słupki), its hints say the line the posts go along.
- The km of a line could be typed in three places that didn't lead to each other. The panel of the posts and the one of a station, where the line has no km set, say the typed km is theirs alone and have Set the km of the line (X), opening the Kilometrage tool; that tool says first that one known point serves the posts, the stations and the block signals.
- The hint of the Signals tool says to pick a signal in the list, then click beside a track; with no templates the panel says so in plain words.
- A new lesson, A whole line, step by step: the tracks and switches, the km, the station, its signals, the line block, the posts and the drive, with a button to the station tool, and opened with the station tools.
- The first lesson shows the ride of the camera along a track (Y, then W S A D and Z) and has it as a step to try.
- lang/editor_pl.po: "Restore the terrain" and "Drag an end" were there twice, the second copies are gone.

Checked: MSVC build, unit tests 459/459; editor run on a small scenery, screenshots of the toolbar, the new lesson, the first lesson with the ride ticked after Y, the panels of the posts, the kilometrage and the signals. The station panel with no km of the line wasn't seen, the scenery had no station.

* fix(editor): the posts open expanded from the trainset, and the Polish of the whole-line lesson reads right

B or the Posts button pressed while the trainset tab is shown opens the hectometre posts with their panel expanded.
The Tracks area tooltip names the kilometrage and the posts.
The station step names the shunting signals, the station button says Narzędzie Stacja, and the ride rows and the lesson list read smoother in Polish.

* fix(editor): a bent model is lengthened along the tracks joined to its own, laid along another track after the bending, and set by fewer settings

The ends of a bent model have handles in the view: dragged, the model goes on along the tracks joined there, at a switch the way it's dragged to.
Its length, a drag of the whole model and a drag of an end all follow the joined tracks; before, they went on straight past the end of the track under the model.
The panel of a bent model picks its track: another one picked, the model stays where it stands, a platform turns its edge to the new track and keeps its length.
On top stay the track, the length, the offset and the height, bent or repeated, and the platform edge; the reference point, the position along, turned, mirrored, the cant and the gauge widening went under More settings.
The buttons of the model's own length and of the whole track are gone: the length field and the handles do it.
The links of a model to its tracks are counted anew when its pieces change, undo and redo included.

* fix(editor): the bends of straights laid from the end of a curve begin with a straight, not a compound curve

In the mode of straights the curve of a plain track's free end no longer goes on into the curve of the first bend as a compound curve.
The line comes out of the end's curve by a transition onto a straight, and each bend gets a curve of its own.
Only a curve traced in the mode of a curve goes on from the curve of the end, as it already did at a switch.

* fix(editor): the bent model keeps its links and its line to what it reaches, and drags without rebuilding at each track

- the links of a bent model are matched anew whenever any of its pieces change, not only the first
- the line is lengthened by the plan lengths of the joined tracks and built once a round; a drag reuses the line made at its start while it doesn't grow
- the tracks of one name are told apart in the track lists, and a deleted track leaves them
- the tracks at the ends the copies no longer reach are left out of the line after an edit or a drag

* fix(editor): a click on a bent model's handles changes nothing, and the track picked stays picked

- the line is trimmed on a drag's release only when the drag changed the model, and an edit that trimming undoes makes no undo step
- the track picked for the bending is kept by the track, not its place in the list, when the list is gathered anew

* fix(lang): a stray line taken out of editor_pl.po

A single "r" between two entries, left by an edit of the switch texts: msgfmt refuses the file with it.

* feat(launcher): the range of the aerial photos of a new real scenery given on the map, changed later in the editor (#328)

* feat(launcher): the new real scenery gets the range of its aerial photos on the map, changed later in the editor

The wizard of a new scenery asked only for the centre; the editor then
downloaded the photos around the camera wherever it went, and a scenery
had no range of them until one was drawn in the orthophoto settings.

The realistic scenery is made in three steps: the name, the place (a
click on the map or the place typed, degrees or PUWG 1992), and the
range of the aerial photos: a square of 1, 2, 5 or 10 km around the
centre, or an area of the user's, its corners clicked on the map. The
range is drawn on the map with its size and the number of the tiles,
and it's written to the scenery as the download area (//$z), so the
editor downloads the photos and the terrain model inside it only.

What a beginner gets wrong is told before the scenery is made: the
button stays off with the reason under it (no name, the name taken, no
centre, the centre outside Poland, an area being drawn or crossing
itself), and a warning comes with the centre outside the area, a large
area and a centre clicked on the map of the whole country (the map
zooms to the place after the first click).

In the editor the download area says in plain words what it does, a
square around the camera replaces it in one click, and with the camera
outside it a note at the bottom of the view says there are no photos
there, with the way to the range.

* fix(launcher): the range of the photos asked for after the centre, the drawing given up as with Cancel, the square named by its sides

The review of the range of the aerial photos found:
- with My own area chosen before the centre, the clicks meant for the
  centre went to the corners of the area: step 3 waits for the centre;
- switching to Fictional while drawing dropped the area there was
  before, and an unfinished one of three corners counted as done: it's
  given up as with Cancel now, also with Esc; Enter ends it, Backspace
  takes the last corner back, as in the editor;
- the error of a place mistyped stayed after a click on the map;
- the largest square was told to be large or not by the rounding: the
  warning comes from 50 sq km on;
- "2 km" read as a radius: the squares say "2 x 2 km", the tooltip how
  far each edge is;
- a place typed with an area of the user's fitted the map to the area,
  not to the place.

In the editor the note of the camera outside the range says the terrain
model isn't there either, its button says it opens the settings, it
stands above the strip of the profile and the keys of the tools, and it
can be closed until the camera is back inside. The squares around the
camera want the place of the scenery on the map, and replace an area
there is, or start one of 10 x 10 km, only with a yes.

* fix(editor): one note of the empty scenery in the middle of the view, the warnings of an area told once it's drawn

A new scenery opened in the editor showed two notes of the same over
each other in the middle of the view: the panel of the track tools
("The scenery has no tracks yet") and the line of the terrain ("This
scenery is still empty"). The line gives way to the panel now.

In the wizard the centre outside the area and the crossing edges were
told while the area was still being drawn; they're told once it's done.

* fix(editor): the note of the camera outside the range of the photos hidden while the camera rides a track

Its lines at the bottom of the view are where the camera riding a track writes the next switch and its keys.

---------

Co-authored-by: maj00r <maj00r@host>

---------

Co-authored-by: maj00r <maj00r@host>
Co-authored-by: Hirek193 <polomarket73@gmail.com>
Co-authored-by: jerrrrycho <jurek.pakula@gmail.com>
2026-11-11 21:34:39 +01:00

6054 lines
262 KiB
C++

/*
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
*/
#include "stdafx.h"
#include "application/editormodesrk.h"
#include "application/editorgestures.h"
#include "application/editormodeshared.h"
#include "application/editorprojection.h"
#include "application/editoruilayer.h"
#include "editor/editorAlignmentStore.hpp"
#include "editor/editorFormat.hpp"
#include "editor/editorGeometry.hpp"
#include "editor/editorIncludeInfo.hpp"
#include "editor/editorKilometrage.hpp"
#include "editor/editorSwitchStore.hpp"
#include "editor/editorTrack.hpp"
#include "simulation/simulation.h"
#include "utilities/Globals.h"
#include "utilities/Logs.h"
#include "utilities/utilities.h"
#include "world/Track.h"
#include "imgui/imgui.h"
#include "utilities/translation.h"
#include <algorithm>
#include <array>
#include <cctype>
#include <cmath>
#include <limits>
#include <map>
#include <tuple>
#include <functional>
#include <unordered_map>
#include <unordered_set>
namespace
{
// the hint of an empty field, which mustn't read as a value typed in
std::string example(char const *Text)
{
return format(STR_C("e.g. %s"), Text);
}
char const *const kMark{"//$s"};
double constexpr kOverlayRange{4000.0};
double constexpr kJointRange{1500.0}; // m, of the joints shown in the scenery
double constexpr kLabelRange{700.0}; // m, of the names shown there, farther ones crowd the horizon
double constexpr kRailHead{0.18}; // m, above the axis of a path
double constexpr kLineLimit{30000.0}; // m, of a line followed out to the next station
double constexpr kGapReach{1500.0}; // m, the tracks going on beyond the end of a line found within it
double constexpr kBlockShare{1.1}; // of the braking distance, the block sections towards the end of the tracks
double constexpr kPredicted{305.0}; // m, out from the next station to its entry signal, while it has none
// the events of a block section, switching the block signal guarding it
char const *const kControl{"sbl_odstep.inc"};
// the SHP track resonator: its model on the axis, 0.2 m below it, turned as a signal facing the trains, and its event
char const *const kResonator{"rezonator.inc"};
double constexpr kShpBefore{200.0}; // m, of the resonator before an entry signal, a block signal and a warning disc
double constexpr kShpTolerance{5.0}; // m, either way
double constexpr kShpWindow{100.0}; // m, either way of its place, a resonator standing is taken for the one of the signal
double constexpr kResonatorDrop{0.2}; // m, of its origin below the axis
double constexpr kBoundaryReach{30.0}; // m, either way of a block signal, a click while drawing the boundaries takes it away
double constexpr kBoundaryEnd{50.0}; // m, of a block boundary drawn from the entry signals at the ends of the line
double constexpr kWrongTrack{30.0}; // m, a standing wrong-track block signal counts for the one of a boundary within it of its place
// m, of a train at the speed, as Ie-4 § 8 takes it: the least block section of the automatic block, a warning disc that far before
// its signal
double braking_distance(double const Speed)
{
return Speed <= 60.0 ? 400.0 : Speed <= 100.0 ? 700.0 : Speed <= 140.0 ? 1000.0 : 1300.0;
}
ImU32 constexpr kPlain{IM_COL32(170, 176, 188, 255)};
ImU32 constexpr kSwitch{IM_COL32(240, 200, 90, 255)};
ImU32 constexpr kApproach{IM_COL32(95, 100, 112, 255)};
ImU32 constexpr kHovered{IM_COL32(255, 255, 255, 255)};
ImU32 constexpr kSignal{IM_COL32(240, 95, 85, 255)};
ImU32 constexpr kJoint{IM_COL32(255, 255, 255, 235)};
ImU32 constexpr kUseful{IM_COL32(120, 230, 255, 255)};
double constexpr kTrainMargin{25.0}; // m, of a useful length the train leaves: 10 to stop, 10 to see the signal, 5 to the joint, ST-T1-A6
double constexpr kJointPick{2.5}; // m, of the mouse to a track or a joint picked while the joints are edited
double constexpr kJointSnap{0.5}; // m, a joint put this near the end of a track goes to the end, near one taken away is it
double constexpr kUnequal{20.0}; // m, the useful lengths of the two ways differing more are shown: ST-T1-A6 wants them the same
ImU32 constexpr kUnfit{IM_COL32(255, 190, 40, 255)};
double constexpr kFastest{250.0}; // km/h, a track set faster is taken for one without a limit
ImVec4 constexpr kWrong{1.0f, 0.42f, 0.36f, 1.0f};
ImVec4 constexpr kDoubtful{1.0f, 0.75f, 0.3f, 1.0f};
ImVec4 constexpr kRight{0.45f, 0.85f, 0.45f, 1.0f};
bool is_switch(TTrack const &Track)
{
return Track.eType != tt_Normal;
}
// a word of the record line: blanks taken out, - for none
std::string word_of(std::string const &Text)
{
std::string result;
for (auto const c : Text)
if (false == std::isspace(static_cast<unsigned char>(c)))
result += c;
return result.empty() ? std::string{"-"} : result;
}
std::string shown(std::string const &Word)
{
return Word == "-" ? std::string{} : Word;
}
// the number of the switch of a unit: of its name once named after the station, of its record, else of its place
std::string unit_number(station::unit const &Unit, std::string const &Stem, std::size_t const Index)
{
auto const &name{Unit.parts.front()->name()};
if (name.size() > Stem.size() && name.compare(0, Stem.size(), Stem) == 0)
{
auto digits{name.substr(Stem.size())};
while (false == digits.empty() && std::isalpha(static_cast<unsigned char>(digits.back())))
digits.pop_back();
if (false == digits.empty() && std::all_of(digits.begin(), digits.end(), [](char const Digit) { return std::isdigit(static_cast<unsigned char>(Digit)) != 0; }))
return digits;
}
if (auto const record{switch_store::named(*Unit.parts.front())}; record && record->number != "-")
return record->number;
return std::to_string(Index + 1);
}
// the number of the station track a circuit is named after: bpd_it5b of track 5; empty for the other names, bpd_ita of the
// circuit before the entry signal A among them
std::string track_of(std::string const &Name, std::string const &Stem)
{
auto const head{Stem + "it"};
if (Stem.empty() || Name.size() <= head.size() || Name.compare(0, head.size(), head) != 0)
return {};
auto number{Name.substr(head.size())};
if (std::none_of(number.begin(), number.end(), [](char const Letter) { return std::isdigit(static_cast<unsigned char>(Letter)) != 0; }))
return {};
if (number.size() > 1 && std::isalpha(static_cast<unsigned char>(number.back())) && std::isdigit(static_cast<unsigned char>(number[number.size() - 2])))
number.pop_back();
return number;
}
// the circuit between an entry signal and the station: bpd_ita
bool entry_circuit(std::string const &Name, std::string const &Stem)
{
auto const head{Stem + "it"};
return false == Stem.empty() && Name.size() > head.size() && Name.compare(0, head.size(), head) == 0 &&
std::all_of(Name.begin() + head.size(), Name.end(), [](char const Letter) { return std::isalpha(static_cast<unsigned char>(Letter)) != 0; });
}
// the name of a signal as its plate and the schematic show it: bpd_tm3 as Tm3, bpd_f1 as F1
std::string signal_shown(std::string const &Name, std::string const &Stem)
{
auto text{false == Stem.empty() && Name.size() > Stem.size() && ToLower(Name).compare(0, Stem.size(), Stem) == 0 ? Name.substr(Stem.size()) : Name};
std::transform(text.begin(), text.end(), text.begin(), [](char const Letter) { return static_cast<char>(std::toupper(static_cast<unsigned char>(Letter))); });
if (text.size() > 2 && text[0] == 'T' && (text[1] == 'M' || text[1] == 'O'))
text[1] = static_cast<char>(std::tolower(static_cast<unsigned char>(text[1])));
return text;
}
// a signal in the names of the block sections: a block signal by its number, a station one by its letter, with the number of the
// track: 2411, A2
std::string section_tag(std::string const &Name, int const Track)
{
auto const cut{Name.rfind('_')};
auto tag{cut == std::string::npos ? Name : Name.substr(cut + 1)};
std::transform(tag.begin(), tag.end(), tag.begin(), [](char const Letter) { return static_cast<char>(std::toupper(static_cast<unsigned char>(Letter))); });
return tag + std::to_string(Track);
}
// the way the trains a signal faces run, in the plan: it stands turned to them
glm::dvec2 travel_of(double const Yaw)
{
auto const yaw{glm::radians(Yaw + 180.0)};
return {std::sin(yaw), std::cos(yaw)};
}
// how far the point lies from the tracks of the station, in the plan
double gap_to(station::layout const &Layout, glm::dvec3 const &Point)
{
auto best{std::numeric_limits<double>::max()};
for (auto const &path : Layout.paths)
for (auto const &point : path.points)
best = std::min(best, glm::distance(glm::dvec2{point.x, point.z}, glm::dvec2{Point.x, Point.z}));
return best;
}
ImU32 circuit_colour(std::string const &Name)
{
static std::array<ImU32, 6> const palette{IM_COL32(110, 200, 250, 255), IM_COL32(250, 150, 90, 255), IM_COL32(150, 220, 120, 255), IM_COL32(230, 120, 200, 255), IM_COL32(240, 220, 100, 255), IM_COL32(150, 140, 250, 255)};
return palette[std::hash<std::string>{}(Name) % palette.size()];
}
template <typename Record_> std::string anchor_of(Record_ const &Entry)
{
return Entry.track != nullptr && false == Entry.track->m_editorremoved ? Entry.track->name() : Entry.anchor;
}
// the name without the code of the station: bpd_4 as 4
std::string without_stem(std::string const &Name, std::string const &Stem)
{
return false == Stem.empty() && Name.size() > Stem.size() && Name.compare(0, Stem.size(), Stem) == 0 ? Name.substr(Stem.size()) : Name;
}
// a limit of a useful length in words, as "from" and "to" take it
std::string limit_text(station::limit const &Limit, std::string const &Stem)
{
auto const name{without_stem(Limit.name, Stem)};
switch (Limit.what)
{
case station::limit::kind::signal:
return format(STR_C("signal %s"), name.c_str());
case station::limit::kind::fouling:
return format(STR_C("the fouling point of switch %s"), name.c_str());
case station::limit::kind::start:
return format(STR_C("the start of switch %s"), name.c_str());
case station::limit::kind::buffer:
return STR_C("the buffer stop");
case station::limit::kind::crossing:
return STR_C("the level crossing");
default:
return name.empty() ? std::string{STR_C("the joint")} : format(STR_C("the joint by switch %s"), name.c_str());
}
}
// the points of the track from one distance along it to the other
std::vector<glm::dvec3> stretch_of(station::lengths const &Track, double const From, double const To)
{
auto const at = [&](double const Along) {
auto const after{std::min<std::size_t>(std::upper_bound(Track.distances.begin(), Track.distances.end(), Along) - Track.distances.begin(), Track.distances.size() - 1)};
auto const before{after > 0 ? after - 1 : 0};
auto const span{Track.distances[after] - Track.distances[before]};
return glm::mix(Track.points[before], Track.points[after], span > 1e-9 ? std::clamp((Along - Track.distances[before]) / span, 0.0, 1.0) : 0.0);
};
std::vector<glm::dvec3> result{at(std::min(From, To))};
for (std::size_t i = 0; i < Track.distances.size(); ++i)
if (Track.distances[i] > std::min(From, To) + 0.05 && Track.distances[i] < std::max(From, To) - 0.05)
result.push_back(Track.points[i]);
result.push_back(at(std::max(From, To)));
if (From > To)
std::reverse(result.begin(), result.end());
return result;
}
glm::dvec3 axis_point(station::layout const &Layout, double const Chainage)
{
auto const after{std::lower_bound(Layout.chainage.begin(), Layout.chainage.end(), Chainage)};
if (after == Layout.chainage.begin())
return Layout.axis.front();
if (after == Layout.chainage.end())
return Layout.axis.back();
auto const i{static_cast<std::size_t>(after - Layout.chainage.begin())};
auto const step{Layout.chainage[i] - Layout.chainage[i - 1]};
return glm::mix(Layout.axis[i - 1], Layout.axis[i], step > 1e-9 ? (Chainage - Layout.chainage[i - 1]) / step : 0.0);
}
// km/h, a signal shows for the route at the speed: 40, 60 or 100 with a light strip, Ie-1; 0 for the highest the line allows
int shown_speed(double const Speed, double const Line)
{
if (Speed <= 0.0 || Speed >= Line - 1.0)
return 0;
auto const shown{Speed >= 98.0 ? 100 : Speed >= 58.0 ? 60 : 40};
return shown >= Line ? 0 : shown;
}
// km/h, a signal slows the trains to with the next one at stop standing that far on, Ie-4 § 8 ust. 5; 140 with a W21 indicator
int shortened_speed(double const Length)
{
return Length < 400.0 ? 40 : Length < 700.0 ? 60 : Length < 1000.0 ? 100 : 140;
}
// what the lights of a signal must show for the routes of its trains
struct head_need
{
std::vector<int> speeds; // km/h, the lower ones
bool informs{false};
bool white{false};
int shortened{0};
bool indicator{false};
};
head_need need_of(std::vector<station::route> const &Routes, bool const Main, double const Line, double const Braking)
{
head_need need;
need.white = Main;
auto const add = [&](int const Speed) {
if (Speed > 0 && std::find(need.speeds.begin(), need.speeds.end(), Speed) == need.speeds.end())
need.speeds.push_back(Speed);
};
for (auto const &route : Routes)
{
auto const shown{Main ? shown_speed(route.speed, Line) : 0};
add(shown);
auto const told{route.next >= 0 && route.warning < 0};
need.informs = need.informs || told;
if (false == Main || false == told || route.length >= Braking)
continue;
auto const slower{shortened_speed(route.length)};
if (slower >= (shown > 0 ? shown : Line))
continue;
if (slower > 100)
need.indicator = true;
else
{
add(slower);
need.shortened = need.shortened == 0 ? slower : std::min(need.shortened, slower);
}
}
std::sort(need.speeds.begin(), need.speeds.end());
return need;
}
bool has_speed(std::vector<int> const &Speeds, int const Speed)
{
return std::find(Speeds.begin(), Speeds.end(), Speed) != Speeds.end();
}
// the template has the lights the need takes, by its chambers: an orange one to tell the next signal shows stop, a lower orange one
// for a lower speed, a strip for 60 and 100 by the speeds its events set, Ie-1 § 7, two orange ones to show a lower speed with the
// next signal at stop
bool has_aspect(signal_head const &Head, char const *Name)
{
return std::ranges::find(Head.aspect_names, std::string_view{Name}) != Head.aspect_names.end();
}
// a semaphore, by the aspects of its description: Sr1 and Sr2, Sr3 of the second arm for any lower speed, 40 km/h being the one it
// gives, Sz on a main signal. It tells nothing of the next signal, a warning disc does that
bool shows_arms(signal_head const &Head, head_need const &Need)
{
if (false == has_aspect(Head, "Sr1") || false == has_aspect(Head, "Sr2") || (Need.white && false == has_aspect(Head, "Sz")))
return false;
return Need.speeds.empty() || has_aspect(Head, "Sr3");
}
bool shows(signal_head const &Head, head_need const &Need)
{
if (Head.arms > 0)
return shows_arms(Head, Need);
auto const &lamps{Head.lamps};
auto const count = [&](char const Lamp) { return std::count(lamps.begin(), lamps.end(), Lamp); };
if (count('z') == 0 || count('c') == 0 || (Need.white && count('b') == 0))
return false;
if (Need.informs && count('p') == 0)
return false;
if (Need.speeds.empty())
return true;
if (lamps.find('p', lamps.find('c')) == std::string::npos || (Need.informs && count('p') < 2))
return false;
return std::all_of(Need.speeds.begin(), Need.speeds.end(), [&](int const Speed) { return has_speed(Head.speeds, Speed); });
}
// the more lights and strips beyond the need, the more
int surplus(signal_head const &Head, head_need const &Need)
{
if (Head.arms > 0)
return Head.arms * 4 + (has_aspect(Head, "Sz") && false == Need.white ? 1 : 0);
auto result{static_cast<int>(Head.lamps.size()) * 4};
for (auto const speed : {60, 100})
if (has_speed(Head.speeds, speed) && false == has_speed(Need.speeds, speed))
++result;
return result;
}
// of the templates of the kind and the mount that fit the need, the one with the least beyond it, the most like the one named;
// -1 for none. A semaphore is swapped for a semaphore only, a signal with lights for one with lights
int best_head(std::vector<signal_head> const &Heads, std::string_view const Kind, std::string_view const Mount, std::string_view const Like, int const Aspects, head_need const &Need, bool const Arms)
{
auto best{-1};
std::tuple<int, int, std::size_t> score;
for (int index = 0; index < static_cast<int>(Heads.size()); ++index)
{
auto const &head{Heads[index]};
if (head.kind != Kind || head.mount != Mount || head.aspects != Aspects || (head.arms > 0) != Arms || false == shows(head, Need))
continue;
std::size_t common{0};
while (common < head.name.size() && common < Like.size() && head.name[common] == Like[common])
++common;
std::tuple<int, int, std::size_t> const candidate{surplus(head, Need), -static_cast<int>(common), head.name.size()};
if (best < 0 || candidate < score)
{
best = index;
score = candidate;
}
}
return best;
}
// the aspects a semaphore needs for it: Sr1, Sr2, Sr3 for a lower speed, Sz on a main signal
std::string need_arms_text(head_need const &Need)
{
std::string text{"Sr1, Sr2"};
if (false == Need.speeds.empty())
text += ", Sr3 (" + format(STR_C("%s km/h"), "40") + ")";
if (Need.white)
text += ", Sz";
return text;
}
// the lights of the need in words: green, two orange, red, white; 40, 60 km/h with an orange strip
std::string need_text(head_need const &Need)
{
std::string text{STR("green")};
if (Need.informs && false == Need.speeds.empty())
text += ", " + STR("two orange");
else if (Need.informs || false == Need.speeds.empty())
text += ", " + STR("orange");
text += ", " + STR("red");
if (Need.white)
text += ", " + STR("white");
if (Need.speeds.empty())
return text;
std::string speeds;
for (auto const speed : Need.speeds)
speeds += (speeds.empty() ? "" : ", ") + std::to_string(speed);
text += "; " + format(STR_C("%s km/h"), speeds.c_str());
if (has_speed(Need.speeds, 60))
text += ", " + STR("an orange strip");
if (has_speed(Need.speeds, 100))
text += ", " + STR("a green strip");
return text;
}
ImU32 lamp_colour(char const Lamp)
{
switch (Lamp)
{
case 'z': return IM_COL32(40, 210, 80, 255);
case 'c': return IM_COL32(230, 40, 40, 255);
case 'p': return IM_COL32(255, 160, 30, 255);
case 'b': return IM_COL32(235, 235, 235, 255);
case 'n': return IM_COL32(60, 110, 255, 255);
default: return IM_COL32(70, 70, 70, 255);
}
}
// the lights of a template in a row, from its top on the left, its strips after them
void lamp_row(std::string const &Lamps, std::vector<int> const &Speeds)
{
auto const height{ImGui::GetTextLineHeight()};
auto const radius{height * 0.3f};
auto const origin{ImGui::GetCursorScreenPos()};
auto *draw{ImGui::GetWindowDrawList()};
auto x{origin.x + radius};
for (auto const lamp : Lamps)
{
draw->AddCircleFilled(ImVec2(x, origin.y + height * 0.5f), radius, lamp_colour(lamp));
x += radius * 2.6f;
}
for (auto const &[speed, colour] : {std::make_pair(60, lamp_colour('p')), std::make_pair(100, lamp_colour('z'))})
if (has_speed(Speeds, speed))
{
draw->AddRectFilled(ImVec2(x, origin.y + height * 0.38f), ImVec2(x + radius * 3.0f, origin.y + height * 0.62f), colour, 1.0f);
x += radius * 3.6f;
}
ImGui::Dummy(ImVec2(std::max(1.0f, x - origin.x), height));
}
// m, the routes of the trains are followed from a signal at most, beyond it the next one needs no telling of
double route_reach(double const Braking)
{
return std::max(3000.0, 3.0 * Braking);
}
// how far the point lies from the path in the plan, Parameter: of the nearest point of it, found among points 8 m or so apart and
// narrowed down between the two by them
double nearest_of(TTrack const &Track, int const Path, glm::dvec3 const &Point, double &Parameter)
{
geometry::bezier const curve{Track.m_paths[Path]};
auto const gap = [&](double const At) { return geometry::plan_distance(curve.point(At), Point); };
auto const count{std::clamp(static_cast<int>(curve.plan_length(16) / 8.0), 16, 512)};
auto best{std::numeric_limits<double>::max()};
for (int k = 0; k <= count; ++k)
if (auto const distance{gap(static_cast<double>(k) / count)}; distance < best)
{
best = distance;
Parameter = static_cast<double>(k) / count;
}
auto low{std::max(0.0, Parameter - 1.0 / count)};
auto high{std::min(1.0, Parameter + 1.0 / count)};
for (int step = 0; step < 40; ++step)
{
auto const first{low + (high - low) / 3.0};
auto const second{high - (high - low) / 3.0};
if (gap(first) < gap(second))
high = second;
else
low = first;
}
if (auto const narrowed{(low + high) * 0.5}; gap(narrowed) < best)
{
best = gap(narrowed);
Parameter = narrowed;
}
return best;
}
// a standing signal by the track its trains read it on, no track for a signal of another kind or by none
station::post post_of(standing_signal const &Signal)
{
using role = station::signal::role;
station::post post;
if (Signal.kind == "main")
post.kind = role::entry;
else if (Signal.kind == "block")
post.kind = role::block;
else if (Signal.kind == "warning")
post.kind = role::warning;
else if (Signal.kind == "shunt")
post.kind = role::shunting;
else
return post;
post.point = Signal.position;
// the track it's read on, where it stands by it: an event put on a track before the signal leaves the track it stands by
if (Signal.track != nullptr && Signal.facing != 0 && false == Signal.track->m_editorremoved)
for (int candidate = 0; candidate < static_cast<int>(Signal.track->m_paths.size()); ++candidate)
if (double parameter{0.0}; nearest_of(*Signal.track, candidate, Signal.position, parameter) < 4.5)
{
post.track = Signal.track;
post.facing = Signal.facing;
return post;
}
int path{0};
post.track = kilometrage::track_near(Signal.position, 4.5, path);
if (post.track == nullptr)
return post;
geometry::bezier const curve{post.track->m_paths[path]};
auto parameter{0.0};
nearest_of(*post.track, path, Signal.position, parameter);
auto const tangent{curve.first(parameter)};
auto const travel{travel_of(Signal.yaw)};
post.facing = travel.x * tangent.x + travel.y * tangent.z >= 0.0 ? 1 : -1;
return post;
}
// the entry signal of the next station along the line: the first main signal 100 m out or more facing out, of the standing ones,
// -1 for none; Distance: out to it, else to where the signals of the line end
int next_entry(station::line const &Line, std::vector<standing_signal> const &Standing, double &Distance)
{
auto found{-1};
for (std::size_t k = 0; k < Standing.size(); ++k)
{
if (Standing[k].kind != "main")
continue;
double gap{0.0};
auto const distance{station::distance_on(Line, Standing[k].position, gap)};
if (gap > 4.5 || distance < 100.0 || distance > Line.length() - 1.0)
continue;
auto const way{station::point_on(Line, distance).way};
if (glm::dot(travel_of(Standing[k].yaw), glm::dvec2{way.x, way.z}) < 0.87)
continue;
if (found < 0 || distance < Distance)
{
found = static_cast<int>(k);
Distance = distance;
}
}
if (found < 0)
Distance = Line.station ? Line.length() - kPredicted : Line.length();
return found;
}
// where the trains run into the event of an SHP track resonator: the end of the track it's put on, the way they run
struct shp_trigger
{
glm::dvec3 point{0.0};
glm::dvec3 way{0.0, 0.0, 1.0};
};
bool shp_event(std::string const &Name)
{
return Name.size() > 4 && ToLower(Name.substr(Name.size() - 4)) == "_shp";
}
std::vector<shp_trigger> shp_triggers()
{
std::vector<shp_trigger> result;
for (auto *track : simulation::Paths.sequence())
{
if (track == nullptr || track->m_editorremoved || track->m_paths.empty())
continue;
for (auto const list : {1, 2, 4, 5})
for (auto const &event : editor_track::events(*track, list))
if (shp_event(event.first))
{
auto const towards_end{list % 3 == 2};
geometry::bezier const curve{track->m_paths.front()};
auto const tangent{curve.first(towards_end ? 0.0 : 1.0)};
glm::dvec3 way{tangent.x, 0.0, tangent.z};
way = glm::length(way) > 1e-9 ? glm::normalize(way) * (towards_end ? 1.0 : -1.0) : glm::dvec3{0.0, 0.0, 1.0};
result.push_back({curve.point(towards_end ? 0.0 : 1.0), way});
}
}
return result;
}
// m before the signal the trains run into the event of an SHP resonator, the one nearest the place wanted within kShpWindow of it;
// -1 for none
double shp_before(std::vector<station::approach_point> const &Way, glm::dvec3 const &Signal, glm::dvec3 const &Travel, std::vector<shp_trigger> const &Triggers, double const Wanted)
{
auto best{-1.0};
auto miss{std::numeric_limits<double>::max()};
for (auto const &trigger : Triggers)
{
if (geometry::plan_distance(trigger.point, Signal) > Wanted + kShpWindow + 10.0 || glm::dot(trigger.way, Travel) < 0.7)
continue;
auto before{std::numeric_limits<double>::lowest()};
if (geometry::plan_distance(trigger.point, Signal) < 12.0)
before = glm::dot(glm::dvec3{Signal.x - trigger.point.x, 0.0, Signal.z - trigger.point.z}, Travel);
else
{
auto nearest{2.5};
for (auto const &point : Way)
if (auto const gap{geometry::plan_distance(point.point, trigger.point)}; gap < nearest && glm::dot(point.way, trigger.way) > 0.7)
{
nearest = gap;
before = point.distance;
}
}
if (before < -10.0 || std::abs(before - Wanted) > kShpWindow)
continue;
if (std::abs(before - Wanted) < miss)
{
miss = std::abs(before - Wanted);
best = std::max(0.0, before);
}
}
return best;
}
// m from the point to the nearer end of the track
double end_gap(TTrack const &Track, glm::dvec3 const &Point)
{
auto const &ends{Track.m_paths.front().points};
return std::min(glm::distance(Point, ends[segment_data::point::start]), glm::distance(Point, ends[segment_data::point::end]));
}
// of the way of the trains, the point the SHP resonator wanted m before the signal goes at, within kShpTolerance: a joint of the
// tracks, Joint, its event put on the plain track the trains run into there, else a point of a plain track away from its ends, the
// track cut at it; -1 for none
int resonator_at(std::vector<station::approach_point> const &Way, double const Wanted, bool &Joint)
{
auto best{-1};
auto miss{kShpTolerance + 1e-6};
Joint = false;
for (std::size_t k = 0; k + 1 < Way.size(); ++k)
if (Way[k + 1].track != Way[k].track && Way[k].track->eType == tt_Normal && std::abs(Way[k].distance - Wanted) < miss)
{
miss = std::abs(Way[k].distance - Wanted);
best = static_cast<int>(k);
Joint = true;
}
if (best >= 0)
return best;
for (std::size_t k = 0; k < Way.size(); ++k)
if (Way[k].track->eType == tt_Normal && end_gap(*Way[k].track, Way[k].point) > 0.5 && std::abs(Way[k].distance - Wanted) < miss)
{
miss = std::abs(Way[k].distance - Wanted);
best = static_cast<int>(k);
}
return best;
}
// the template of a block signal of the aspects wanted, Like: the one standing, empty for the one chosen in the Templates of the tool, taken
// where it has them, else the one of their mount with them, its counterpart by the name first, then of its lights; not the first of
// a line, whose events tell a station signal; Wrong: of a wrong-track one, standing on the left, its head leaning right where one
// does, a head leaning so only for it; empty for none
std::string block_template(std::vector<signal_head> const &Heads, std::string const &Like, int const Aspects, bool const Wrong = false)
{
auto const leans = [&](signal_head const &Head) { return (Head.lean == "right") == Wrong; };
auto const any_leans{std::any_of(Heads.begin(), Heads.end(), [&](signal_head const &Head) { return Head.kind == "block" && Head.aspects == Aspects && leans(Head); })};
signal_head const *like{nullptr};
for (auto const &head : Heads)
if (head.kind == "block" && (Like.empty() ? head.chosen : head.file == Like))
like = &head;
if (like != nullptr && like->aspects == Aspects && (leans(*like) || false == any_leans))
return like->file;
auto counterpart{like != nullptr ? like->name : std::string{}};
if (auto const digit{counterpart.find_first_of("34")}; digit != std::string::npos)
counterpart[digit] = counterpart[digit] == '3' ? '4' : '3';
signal_head const *best{nullptr};
auto rank{std::make_pair(std::numeric_limits<int>::max(), std::size_t{0})};
for (auto const &head : Heads)
{
if (head.kind != "block" || head.aspects != Aspects || ToLower(head.name).find("pierwszy") != std::string::npos || (any_leans && false == leans(head)))
continue;
auto const score{std::make_pair(like == nullptr ? 0 : (head.mount != like->mount ? 4 : 0) + (head.name != counterpart ? 2 : 0) + (head.lamps != like->lamps ? 1 : 0), head.file.size())};
if (score < rank)
{
rank = score;
best = &head;
}
}
return best != nullptr ? best->file : std::string{};
}
// what a warning disc tells of the semaphore after it: stop, the highest speed and, with a second arm, 40 km/h
std::vector<std::string> disc_classes(signal_head const &Main)
{
std::vector<std::string> classes{"stop", "vmax"};
if (has_aspect(Main, "Sr3"))
classes.emplace_back("40");
return classes;
}
// of the events a disc repeats, how many apart for the classes given; -1 when it has no event for one of them
int disc_apart(signal_head const &Disc, std::vector<std::string> const &Classes)
{
std::vector<std::string> events;
for (auto const &type : Classes)
{
auto const found{std::ranges::find_if(Disc.repeats, [&](auto const &Repeat) { return Repeat.first == type; })};
if (found == Disc.repeats.end() || found->second.empty())
return -1;
events.push_back(found->second);
}
std::ranges::sort(events);
return static_cast<int>(std::ranges::unique(events).begin() - events.begin());
}
// the disc tells apart all the semaphore after it shows
bool disc_tells(signal_head const &Disc, signal_head const &Main)
{
auto const classes{disc_classes(Main)};
return disc_apart(Disc, classes) == static_cast<int>(classes.size());
}
// the warning disc of a semaphore, of the discs described with the events they repeat: one telling apart what the semaphore does,
// stop, the highest speed and, with a second arm, 40 km/h, with the fewest aspects, of the mount given, any for none. Empty for the
// chosen disc: before a signal with lights, before a semaphore not described, with no disc described so
std::string disc_template(std::vector<signal_head> const &Heads, signal_head const *Main, std::string_view const Mount)
{
if (Main == nullptr || Main->arms == 0)
return {};
auto const classes{disc_classes(*Main)};
signal_head const *chosen{nullptr};
for (auto const &head : Heads)
if (head.kind == "warning" && head.chosen)
chosen = &head;
signal_head const *best{nullptr};
std::tuple<int, std::size_t, int, std::size_t> rank;
for (auto const &head : Heads)
{
if (head.kind != "warning" || head.repeats.empty() || (false == Mount.empty() && head.mount != Mount))
continue;
auto const apart{disc_apart(head, classes)};
if (apart < 0)
continue;
std::tuple<int, std::size_t, int, std::size_t> const score{-apart, head.aspect_names.size(), &head == chosen ? 0 : 1, head.file.size()};
if (best == nullptr || score < rank)
{
best = &head;
rank = score;
}
}
return best != nullptr ? best->file : std::string{};
}
// a shaped warning disc checked by the events it repeats: of the semaphores described after it, whether it tells apart all they
// show, and the template which would
struct disc_check
{
bool told{false}; // there's a semaphore described after it
bool unsaid{false}; // its template doesn't say what it repeats: the one described offered, the fitting leaves it be
bool fits{true};
std::string fit; // the template which tells all apart, empty for none
};
// Mains: for each route of the disc the semaphore described with its arms it leads to, none for the other routes. File: the template
// of the disc, Template: its head, none when it isn't among the scanned
disc_check check_disc(std::vector<signal_head> const &Heads, std::unordered_map<std::string, std::size_t> const &By_file, std::vector<signal_head const *> const &Mains, signal_head const *Template, std::string const &File, std::string const &Mount)
{
disc_check result;
auto const described{Template != nullptr && false == Template->repeats.empty()};
for (auto const *main : Mains)
{
if (main == nullptr)
continue;
auto fit{disc_template(Heads, main, Mount)};
if (auto const offered{By_file.find(fit)}; fit == File || offered == By_file.end() || false == disc_tells(Heads[offered->second], *main))
fit.clear();
if (false == described)
{
// one not described tells nothing to check: the one described is offered as a hint
if (fit.empty())
continue;
result.told = true;
result.unsaid = true;
if (result.fit.empty())
result.fit = fit;
continue;
}
result.told = true;
if (disc_tells(*Template, *main))
continue;
result.fits = false;
if (result.fit.empty())
result.fit = fit;
}
return result;
}
// the block signals switched by the block sections of the editor, lower case
std::unordered_set<std::string> guarded(std::vector<standing_template> const &Controls)
{
std::unordered_set<std::string> result;
for (auto const &control : Controls)
for (std::size_t index = 5; index < control.values.size() && index < 7; ++index)
result.insert(ToLower(control.values[index]));
return result;
}
// a block signal standing by the track of the line facing its trains, or Wrong: its wrong-track ones, Distance: how far out along it
bool faces_along(station::line const &Line, standing_signal const &Signal, double &Distance, bool const Wrong = false)
{
double gap{0.0};
Distance = station::distance_on(Line, Signal.position, gap);
if (gap > 4.5 || Distance < 50.0 || Distance > Line.length() - 1.0)
return false;
auto const way{station::point_on(Line, Distance).way};
return (Line.inbound != Wrong ? -1.0 : 1.0) * glm::dot(travel_of(Signal.yaw), glm::dvec2{way.x, way.z}) >= 0.87;
}
bool block_along(station::line const &Line, standing_signal const &Signal, double &Distance, bool const Wrong = false)
{
auto const along{faces_along(Line, Signal, Distance, Wrong)};
return Signal.kind == "block" && along;
}
// a warning disc by the line facing its wrong-track trains, on no other line out of the station: of the semi-automatic block they
// run on, the automatic one of the track the other way
bool wrong_disc(std::vector<station::line> const &Lines, std::size_t const Index, standing_signal const &Signal)
{
double distance{0.0};
if (Signal.kind != "warning" || false == faces_along(Lines[Index], Signal, distance, true))
return false;
for (std::size_t other = 0; other < Lines.size(); ++other)
{
double gap{0.0};
auto const at{station::distance_on(Lines[other], Signal.position, gap)};
if (other != Index && gap < 4.5 && at > 50.0 && at < Lines[other].length() - 1.0)
return false;
}
return true;
}
// the way the trains of the line run out along it, 1 out, -1 in
double out_of(station::line const &Line)
{
return Line.inbound ? -1.0 : 1.0;
}
} // namespace
srk_tool::shp_state srk_tool::head_check::shp_of() const
{
if (shp < 0.0)
return shp_state::needless;
if (shp_found < 0.0)
return shp_short ? shp_state::beyond : shp_state::missing;
return std::abs(shp_found - shp) > kShpTolerance ? shp_state::off : shp_state::placed;
}
void srk_tool::load()
{
if (m_loaded)
return;
m_loaded = true;
m_records.clear();
if (scene::Layers.empty())
return;
for (auto const layer : scene::Layers.marked_layers(kMark))
for (auto const &text : scene::Layers.marked(layer, kMark))
{
std::istringstream words{text};
std::string word;
if ((words >> word).fail() || word != "station")
continue;
record entry;
entry.layer = layer;
words >> entry.code;
while (words >> word)
{
if (word == "line")
words >> entry.line;
else if (word == "km")
words >> entry.km;
else if (word == "from")
entry.reversed = (words >> word) && word == "right";
else if (word == "braking")
words >> entry.braking;
else if (word == "blocks" && words >> word)
for (std::size_t from = 0; from < word.size();)
{
auto const comma{std::min(word.find(',', from), word.size())};
auto const item{word.substr(from, comma - from)};
if (auto const equals{item.find('=')}; equals != std::string::npos && equals > 0)
{
auto const kind{item.substr(equals + 1)};
entry.blocks[item.substr(0, equals)] = kind == "sbl4" ? block_kind::four : kind == "sbl" || kind == "sbl3" ? block_kind::three : block_kind::semi;
}
from = comma + 1;
}
else if (word == "ways" && words >> word)
for (std::size_t from = 0; from < word.size();)
{
auto const comma{std::min(word.find(',', from), word.size())};
auto const item{word.substr(from, comma - from)};
if (auto const equals{item.find('=')}; equals != std::string::npos && equals > 0)
entry.ways[item.substr(0, equals)] = item.substr(equals + 1) == "2";
from = comma + 1;
}
else if (word == "joints" && words >> word)
// +x/y/z for one put by hand, -x/y/z for a planned one taken away
for (std::size_t from = 0; from < word.size();)
{
auto const comma{std::min(word.find(',', from), word.size())};
auto const item{word.substr(from, comma - from)};
glm::dvec3 point{0.0};
if (item.size() > 1 && (item.front() == '+' || item.front() == '-') && std::sscanf(item.c_str() + 1, "%lf/%lf/%lf", &point.x, &point.y, &point.z) == 3)
(item.front() == '+' ? entry.joints_added : entry.joints_removed).push_back(point);
from = comma + 1;
}
else if (word == "anchor")
words >> entry.anchor;
else if (word == "name")
{
std::getline(words, entry.name);
entry.name.erase(0, entry.name.find_first_not_of(' '));
// windows-1250 like the rest of the scenery file; earlier builds wrote it in utf-8, which stays as it is
if (std::u32string decoded; false == utf8_to_utf32(entry.name, decoded))
entry.name = win1250_to_utf8(entry.name);
break;
}
}
entry.code = shown(entry.code);
entry.line = shown(entry.line);
entry.km = shown(entry.km);
entry.track = simulation::Paths.find(entry.anchor);
if (false == entry.anchor.empty())
m_records.push_back(std::move(entry));
}
}
void srk_tool::store()
{
if (false == m_changed || scene::Layers.empty())
return;
m_changed = false;
std::vector<scene::layer_handle> layers{scene::Layers.marked_layers(kMark)};
for (auto const &entry : m_records)
if (std::find(layers.begin(), layers.end(), entry.layer) == layers.end())
layers.push_back(entry.layer);
for (auto const layer : layers)
{
std::vector<std::string> lines;
for (auto const &entry : m_records)
{
if (entry.layer != layer)
continue;
if (lines.empty())
lines.emplace_back("# stations described in the track editor, the simulation skips these lines");
auto const braking{entry.braking > 0 ? format(" braking %d", entry.braking) : std::string{}};
std::string blocks;
for (auto const &[signal, kind] : entry.blocks)
if (false == signal.empty() && signal.find_first_of(" ,=\t") == std::string::npos)
blocks += (blocks.empty() ? " blocks " : ",") + signal + (kind == block_kind::four ? "=sbl4" : kind == block_kind::three ? "=sbl" : "=semi");
std::string ways;
for (auto const &[signal, both] : entry.ways)
if (false == signal.empty() && signal.find_first_of(" ,=\t") == std::string::npos)
ways += (ways.empty() ? " ways " : ",") + signal + (both ? "=2" : "=1");
std::string joints;
for (auto const *list : {&entry.joints_added, &entry.joints_removed})
for (auto const &point : *list)
joints += (joints.empty() ? " joints " : ",") + format("%c%.3f/%.3f/%.3f", list == &entry.joints_added ? '+' : '-', point.x, point.y, point.z);
lines.push_back(format("station %s line %s km %s from %s anchor %s%s%s%s%s name %s", word_of(entry.code).c_str(), word_of(entry.line).c_str(), word_of(entry.km).c_str(), entry.reversed ? "right" : "left", anchor_of(entry).c_str(), braking.c_str(), blocks.c_str(), ways.c_str(), joints.c_str(), utf8_to_win1250(entry.name).c_str()));
}
scene::Layers.mark(layer, kMark, std::move(lines));
}
}
void srk_tool::open(TTrack &Track)
{
m_status.clear();
m_status_refused = false;
m_joint_held.reset();
m_joint_target = {};
auto found{station::find(Track)};
if (false == found.has_value())
{
refuse(STR_C("No switch near this track: it isn't a part of a station"));
return;
}
m_layout = std::move(found);
m_plot = station::generalize(*m_layout);
m_hover = -1;
m_view_state.exaggeration = 0.0f;
m_history_revision = m_history.history_revision();
// the record of the station, by any of its switches
m_record = -1;
for (int index = 0; index < static_cast<int>(m_records.size()) && m_record < 0; ++index)
{
auto &entry{m_records[index]};
if (entry.track == nullptr)
entry.track = simulation::Paths.find(entry.anchor);
if (std::find(m_layout->switches.begin(), m_layout->switches.end(), entry.track) != m_layout->switches.end())
m_record = index;
}
m_anchor = m_record >= 0 ? m_records[m_record].track : m_layout->switches.front();
m_reversed = m_record >= 0 && m_records[m_record].reversed;
survey();
}
void srk_tool::refresh()
{
m_history_revision = m_history.history_revision();
if (m_anchor == nullptr || m_anchor->m_editorremoved)
{
m_layout.reset();
return;
}
auto const view{m_view_state};
auto const status{m_status};
open(*m_anchor);
if (m_layout.has_value())
{
m_view_state = view;
m_status = status;
}
}
bool srk_tool::circuits_set()
{
auto const stem{stem_of_open()};
if (m_history.history_revision() != m_circuits_revision || stem != m_circuits_stem)
{
m_circuits_revision = m_history.history_revision();
m_circuits_stem = stem;
std::vector<station::numbered> tracks;
std::unordered_set<TTrack const *> inside;
m_circuits_known = station_tracks(tracks, inside);
}
return m_circuits_known;
}
bool srk_tool::told(std::string &Status, bool &Refused)
{
if (m_status_count == m_told_count && m_status == m_told)
return false;
m_told_count = m_status_count;
m_told = m_status;
if (m_status.empty())
return false;
Status = m_status;
Refused = m_status_refused;
return true;
}
srk_tool::record &srk_tool::record_of_open()
{
if (m_record < 0)
{
record entry;
auto *first{m_layout->switches.front()};
entry.anchor = first->name();
entry.track = first;
// beside the records of the other stations, in the file of the scenery they were written in under another name too
for (auto const layer : scene::Layers.marked_layers(kMark))
if (scene::Layers.accepts(layer))
{
entry.layer = layer;
break;
}
if (entry.layer == null_handle)
entry.layer = m_templates.output_layer("srk");
if (entry.layer == null_handle)
entry.layer = alignment_store::layer_of(*first);
m_records.push_back(std::move(entry));
m_record = static_cast<int>(m_records.size()) - 1;
m_anchor = first;
}
return m_records[m_record];
}
std::string srk_tool::title() const
{
if (m_record >= 0)
{
auto const &entry{m_records[m_record]};
if (false == entry.name.empty())
return entry.code.empty() ? entry.name : entry.name + " (" + entry.code + ")";
if (false == entry.code.empty())
return entry.code;
}
return format(STR_C("Station of %s"), m_anchor != nullptr ? m_anchor->name().c_str() : "");
}
void srk_tool::find_all()
{
m_found.clear();
for (auto *track : station::stations())
m_found.emplace_back(track->name(), station::switches_of(*track).size());
std::sort(m_found.begin(), m_found.end(), [](auto const &A, auto const &B) { return A.second > B.second; });
}
void srk_tool::update()
{
if (false == m_open)
return;
load();
// the stations follow their anchors renamed
for (auto &entry : m_records)
if (auto const name{anchor_of(entry)}; name != entry.anchor)
{
entry.anchor = name;
m_changed = true;
}
if ((m_layout.has_value() || m_anchor != nullptr) && m_history.history_revision() != m_history_revision)
refresh();
else if (m_layout.has_value() && false == m_signals_known)
survey_signals();
m_length_shown = m_length_hover >= 0 ? m_length_hover : m_length_canvas >= 0 ? m_length_canvas : length_of(m_selection.selected_track());
if (m_length_shown >= static_cast<int>(m_lengths.size()))
m_length_shown = -1;
// a track of another station selected opens it
auto *track{m_selection.selected_track()};
if (track == nullptr || track == m_picked)
return;
m_picked = track;
if (m_layout.has_value() && std::any_of(m_layout->paths.begin(), m_layout->paths.end(), [&](station::path const &Path) { return Path.track == track && false == Path.approach; }))
return;
open(*track);
}
void srk_tool::forget(scene::basic_node const *Node)
{
if (Node == m_picked)
m_picked = nullptr;
for (auto &entry : m_records)
if (entry.track == Node)
entry.track = nullptr;
if (Node == m_anchor)
{
m_anchor = nullptr;
if (m_layout.has_value())
for (auto *track : m_layout->switches)
if (track != Node)
{
m_anchor = track;
break;
}
}
if (m_layout.has_value() && std::any_of(m_layout->paths.begin(), m_layout->paths.end(), [&](station::path const &Path) { return Path.track == Node; }))
{
// laid out again from its anchor at the next update
m_layout.reset();
m_hover = -1;
m_history_revision = static_cast<std::size_t>(-1);
}
}
void srk_tool::draw_overlay() const
{
if (false == m_open || false == m_layout.has_value())
return;
screen_projection const projection;
auto *drawlist{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())};
glm::dvec3 const camera{Global.pCamera.Pos};
auto const near_enough = [&](glm::dvec3 const &Point, double const Range) { return Global.EditorOrtho || glm::distance(Point, camera) < Range; };
glm::dvec3 const lift{0.0, kRailHead, 0.0};
// the track circuits: the tracks in their colours, a bar across them at each joint with a post, the station tracks named
for (std::size_t index = 0; index < m_layout->paths.size() && index < m_circuit_of.size(); ++index)
{
if (m_circuit_of[index] < 0)
continue;
auto const colour{(m_circuits[m_circuit_of[index]].colour & ~IM_COL32_A_MASK) | IM_COL32(0, 0, 0, 200)};
auto const &points{m_layout->paths[index].points};
for (std::size_t i = 1; i < points.size(); ++i)
if (near_enough(points[i], kOverlayRange))
projection.line(drawlist, points[i - 1] + lift, points[i] + lift, colour, Global.EditorOrtho ? 6.0f : 3.0f);
}
for (auto const &joint : m_joints)
{
if (false == near_enough(joint.at, kJointRange))
continue;
auto const centre{joint.at + lift};
projection.line(drawlist, centre - joint.across * 1.7, centre + joint.across * 1.7, kJoint, 4.0f);
projection.line(drawlist, centre + joint.across * 1.7, centre + joint.across * 1.7 + glm::dvec3{0.0, 1.2, 0.0}, kJoint, 2.0f);
ImVec2 top;
if (projection.project(centre + joint.across * 1.7 + glm::dvec3{0.0, 1.2, 0.0}, top))
drawlist->AddCircleFilled(top, 3.0f, kJoint);
}
for (auto const &mark : m_circuits)
{
ImVec2 screen;
if (false == mark.labelled || false == near_enough(mark.world, kLabelRange) || false == projection.project(mark.world + glm::dvec3{0.0, 0.8, 0.0}, screen))
continue;
auto const size{ImGui::CalcTextSize(mark.text.c_str())};
drawlist->AddRectFilled(ImVec2(screen.x - size.x * 0.5f - 3.0f, screen.y - size.y - 2.0f), ImVec2(screen.x + size.x * 0.5f + 3.0f, screen.y + 2.0f), IM_COL32(0, 0, 0, 160), 3.0f);
drawlist->AddText(ImVec2(screen.x - size.x * 0.5f, screen.y - size.y), mark.colour, mark.text.c_str());
}
if (m_hover >= 0 && m_hover < static_cast<int>(m_layout->paths.size()))
{
auto const &points{m_layout->paths[m_hover].points};
for (std::size_t i = 1; i < points.size(); ++i)
projection.line(drawlist, points[i - 1], points[i], kHovered, 4.0f);
}
for (auto const *track : m_layout->switches)
{
auto const start{track->m_paths.front().points[segment_data::point::start] + glm::dvec3{0.0, 1.0, 0.0}};
ImVec2 screen;
if (false == near_enough(start, kLabelRange) || false == projection.project(start, screen))
continue;
auto const text{track->name()};
auto const size{ImGui::CalcTextSize(text.c_str())};
drawlist->AddRectFilled(ImVec2(screen.x - 3.0f, screen.y - size.y - 4.0f), ImVec2(screen.x + size.x + 3.0f, screen.y), IM_COL32(0, 0, 0, 160), 3.0f);
drawlist->AddText(ImVec2(screen.x, screen.y - size.y - 2.0f), kSwitch, text.c_str());
}
// the useful lengths of the station track shown, beside it on the right of the trains, a post where they stop
if (m_length_shown >= 0 && m_length_shown < static_cast<int>(m_lengths.size()))
{
auto const &track{m_lengths[m_length_shown]};
for (auto const &part : track.ways)
{
if (part.length <= 0.0)
continue;
auto const points{stretch_of(track, part.rear.along, part.head.along)};
std::vector<glm::dvec3> beside;
for (std::size_t i = 0; i < points.size(); ++i)
{
auto const way{points[std::min(i + 1, points.size() - 1)] - points[i > 0 && i + 1 == points.size() ? i - 1 : i]};
glm::dvec2 const along{glm::normalize(glm::dvec2{way.x, way.z} + glm::dvec2{1e-12, 0.0})};
beside.push_back(points[i] + lift + glm::dvec3{-along.y, 0.1, along.x} * 0.9);
}
for (std::size_t i = 1; i < beside.size(); ++i)
if (near_enough(beside[i], kOverlayRange))
projection.line(drawlist, beside[i - 1], beside[i], kUseful, 3.0f);
auto const top{beside.back() + glm::dvec3{0.0, 2.5, 0.0}};
projection.line(drawlist, beside.front(), beside.front() + glm::dvec3{0.0, 1.0, 0.0}, kUseful, 2.0f);
projection.line(drawlist, beside.back(), top, kUseful, 2.0f);
ImVec2 screen;
if (false == near_enough(top, kLabelRange) || false == projection.project(top, screen))
continue;
auto const text{format(STR_C("track %s: %.0f m"), track.number.c_str(), part.length)};
auto const size{ImGui::CalcTextSize(text.c_str())};
drawlist->AddRectFilled(ImVec2(screen.x - size.x * 0.5f - 4.0f, screen.y - size.y - 4.0f), ImVec2(screen.x + size.x * 0.5f + 4.0f, screen.y), IM_COL32(0, 0, 0, 180), 3.0f);
drawlist->AddText(ImVec2(screen.x - size.x * 0.5f, screen.y - size.y - 2.0f), kUseful, text.c_str());
}
}
// the block boundary under the mouse while they are drawn: a bar across each track at the joint and a post where each signal goes
if (drawing() && m_boundary.valid)
{
auto const colour{m_boundary.remove ? IM_COL32(255, 90, 80, 255) : IM_COL32(110, 230, 120, 255)};
for (auto const &[point, way] : m_boundary.joints)
{
glm::dvec3 const across{-way.z, 0.0, way.x};
projection.line(drawlist, point + lift - across * 2.0, point + lift + across * 2.0, colour, 4.0f);
}
for (auto const &post : m_boundary.posts)
{
auto const base{post.point + lift + post.side * 2.4};
projection.line(drawlist, post.point + lift, base, colour, 2.0f);
projection.line(drawlist, base, base + glm::dvec3{0.0, 6.0, 0.0}, colour, 3.0f);
ImVec2 screen;
if (false == projection.project(base + glm::dvec3{0.0, 6.5, 0.0}, screen))
continue;
auto const &text{post.name};
auto const size{ImGui::CalcTextSize(text.c_str())};
drawlist->AddRectFilled(ImVec2(screen.x - size.x * 0.5f - 4.0f, screen.y - size.y - 4.0f), ImVec2(screen.x + size.x * 0.5f + 4.0f, screen.y), colour, 3.0f);
drawlist->AddText(ImVec2(screen.x - size.x * 0.5f, screen.y - size.y - 2.0f), IM_COL32(0, 0, 0, 255), text.c_str());
}
}
// the joint taken while the joints are edited, and where a click puts one or takes it away
if (editing_joints())
{
auto const bar = [&](glm::dvec3 const &Point, ImU32 const Colour, float const Width) {
// across the track at the point, the way of the nearest joint or path
glm::dvec3 across{1.0, 0.0, 0.0};
auto nearest{std::numeric_limits<double>::max()};
for (auto const &path : m_layout->paths)
for (std::size_t i = 1; i < path.points.size(); ++i)
if (auto const gap{glm::distance(path.points[i], Point)}; gap < nearest)
{
nearest = gap;
glm::dvec2 const way{glm::normalize(glm::dvec2{path.points[i].x - path.points[i - 1].x, path.points[i].z - path.points[i - 1].z} + glm::dvec2{1e-12, 0.0})};
across = glm::dvec3{-way.y, 0.0, way.x};
}
projection.line(drawlist, Point + lift - across * 2.2, Point + lift + across * 2.2, Colour, Width);
};
if (m_joint_held.has_value())
bar(*m_joint_held, IM_COL32(255, 200, 60, 255), 6.0f);
switch (m_joint_target.what)
{
case joint_target::kind::add:
case joint_target::kind::move: bar(m_joint_target.point, IM_COL32(110, 230, 120, 255), 5.0f); break;
case joint_target::kind::remove: bar(m_joint_target.point, IM_COL32(255, 90, 80, 255), 7.0f); break;
case joint_target::kind::pick: bar(m_joint_target.point, IM_COL32(255, 200, 60, 255), 5.0f); break;
default: break;
}
}
for (auto const &mark : m_signal_marks)
{
ImVec2 screen;
if (false == near_enough(mark.head, kLabelRange) || false == projection.project(mark.head, screen))
continue;
auto const text{mark.unfit ? mark.text + " !" : mark.text};
auto const size{ImGui::CalcTextSize(text.c_str())};
drawlist->AddRectFilled(ImVec2(screen.x - size.x * 0.5f - 4.0f, screen.y - size.y - 4.0f), ImVec2(screen.x + size.x * 0.5f + 4.0f, screen.y), mark.unfit ? kUnfit : kSignal, 3.0f);
drawlist->AddText(ImVec2(screen.x - size.x * 0.5f, screen.y - size.y - 2.0f), mark.unfit ? IM_COL32(0, 0, 0, 255) : IM_COL32(255, 255, 255, 255), text.c_str());
}
if (m_head_hover >= 0 && m_head_hover < static_cast<int>(m_heads.size()))
{
auto const &head{m_heads[m_head_hover]};
ImVec2 label;
if (projection.project(head.position + glm::dvec3{0.0, 7.0, 0.0}, label))
{
ImVec2 const foot{label.x, label.y - ImGui::GetTextLineHeight() - 8.0f};
ImVec2 const top{label.x, foot.y - 30.0f};
drawlist->AddLine(foot, top, kHovered, 3.0f);
drawlist->AddCircle(ImVec2(top.x, top.y - 9.0f), 9.0f, kHovered, 0, 3.0f);
}
}
}
void srk_tool::render_found()
{
if (main_button(STR_C("Find the stations of the scenery"), ImVec2(-1.0f, tall_button_height())))
find_all();
item_tooltip("Each group of switches joined by tracks shorter than 1.5 km is a station");
if (m_found.empty())
return;
ImGui::TextDisabled("%s", format(STR_P("%zu station", "%zu stations", m_found.size()), m_found.size()).c_str());
if (false == ImGui::BeginChild("##srkfound", ImVec2(0.0f, std::min(300.0f, ImGui::GetTextLineHeightWithSpacing() * (m_found.size() + 1.0f))), true))
{
ImGui::EndChild();
return;
}
for (std::size_t index = 0; index < m_found.size(); ++index)
{
auto const &[name, count]{m_found[index]};
auto const described{std::find_if(m_records.begin(), m_records.end(), [&](record const &Entry) { return anchor_of(Entry) == name; })};
auto label{format(STR_P("%s: %zu switch", "%s: %zu switches", count), name.c_str(), count)};
if (described != m_records.end() && false == described->name.empty())
label = described->name + " - " + label;
if (ImGui::Selectable((label + "##srkfound" + std::to_string(index)).c_str(), false))
if (auto *track{simulation::Paths.find(name)}; track != nullptr)
{
open(*track);
m_selection.set_current_node(track);
m_picked = track;
m_view.focus_track(*track, 0, track->m_paths.front().points[segment_data::point::start]);
}
}
ImGui::EndChild();
}
void srk_tool::render_options()
{
m_length_hover = -1;
m_head_hover = -1;
if (false == m_layout.has_value())
{
static char const *const intro[]{
"The station: LMB on a switch lays it out as a schematic. Its name and code, the numbers of its switches and tracks, its track circuits",
"The signals of a whole station placed at once, named after its code, and what its signalling lacks: the lights of its signals, the SHP resonators, the lengths of its tracks. LMB on a switch opens the station",
"The block of the lines out of a station, its block signals and warning discs: LMB on a switch opens the station"};
ImGui::TextDisabled("%s", STR_C(intro[static_cast<int>(m_part)]));
if (false == m_status.empty())
ImGui::TextColored(kDoubtful, "%s", m_status.c_str());
ImGui::Spacing();
render_found();
return;
}
auto const &layout{*m_layout};
ImGui::TextUnformatted(title().c_str());
std::unordered_set<TTrack const *> tracks;
for (auto const &path : layout.paths)
if (false == path.approach)
tracks.insert(path.track);
metric_tiles({{format("%zu", layout.switches.size()), STR_C("switches"), kSwitch},
{format("%zu", tracks.size() - layout.switches.size()), STR_C("tracks"), kPlain},
{format("%.0f m", layout.to - layout.from), STR_C("length"), ImGui::GetColorU32(ImGuiCol_Text)}});
switch (m_part)
{
case part::station: render_station(); break;
case part::signals: render_station_signals(); break;
case part::lines: render_line_block(); break;
}
if (false == m_status.empty())
ImGui::TextColored(kDoubtful, "%s", m_status.c_str());
ImGui::Spacing();
if (ImGui::Button(STR_C("Another station"), ImVec2(-1.0f, 0.0f)))
{
m_layout.reset();
m_anchor = nullptr;
m_record = -1;
m_hover = -1;
}
item_tooltip("Leaves this station; LMB on a switch opens another one");
}
void srk_tool::render_summary(bool const Line)
{
// what the Station tool set for it, which this one goes by
auto const *entry{m_record >= 0 ? &m_records[m_record] : nullptr};
auto const code{entry != nullptr ? entry->code : std::string{}};
auto const line{line_of_open()};
double km{0.0};
auto const known{km_of_open((m_layout->from + m_layout->to) * 0.5, km)};
auto const value = [](bool const Set, std::string const &Text, bool const Needed) {
if (Set)
ImGui::TextUnformatted(Text.c_str());
else if (Needed)
ImGui::TextColored(kWrong, "%s", STR_C("not set"));
else
ImGui::TextDisabled("%s", STR_C("not set"));
};
if (begin_fields("##srksummary"))
{
field_row("Code");
value(false == code.empty(), code, true);
field_row("Line");
value(false == line.empty(), line, Line);
field_row("Km");
value(known, format("%.3f", km), Line);
field_row("Braking distance");
ImGui::Text("%.0f m", braking_of_open());
ImGui::EndTable();
}
if (ImGui::SmallButton(STR_C("Change in the Station tool")))
m_view.show_track_tab(editor_track_tab::station);
item_tooltip("The name, the code, the line, the km and the braking distance of the station are set in the Station tool");
}
void srk_tool::render_station()
{
auto const &layout{*m_layout};
if (begin_fields("##srkstation"))
{
auto const text = [&](char const *Label, char const *Id, std::string const &Value, char const *Hint, auto const &Set) {
field_row(Label);
std::array<char, 128> buffer{};
Value.copy(buffer.data(), buffer.size() - 1);
if (ImGui::InputTextWithHint(Id, Hint, buffer.data(), buffer.size()))
{
Set(std::string{buffer.data()});
m_changed = true;
}
};
auto const *entry{m_record >= 0 ? &m_records[m_record] : nullptr};
text("Name", "##srkname", entry != nullptr ? entry->name : std::string{}, example("Biała Podlaska").c_str(), [&](std::string const &Value) { record_of_open().name = Value; });
text("Code", "##srkcode", entry != nullptr ? entry->code : std::string{}, example("BPd").c_str(), [&](std::string const &Value) { record_of_open().code = word_of(Value) == "-" ? std::string{} : word_of(Value); });
item_tooltip("The abbreviation of the station: the names of its switches, track circuits and signals begin with it");
auto const line_hint{line_of_open()};
text("Line", "##srkline", entry != nullptr ? entry->line : std::string{}, line_hint.empty() ? example("2").c_str() : line_hint.c_str(), [&](std::string const &Value) { record_of_open().line = word_of(Value) == "-" ? std::string{} : word_of(Value); });
item_tooltip("The number of the railway line the station lies on, as the block sections between the stations are named after it");
double known{0.0};
if (km_of_line((layout.from + layout.to) * 0.5, known))
{
field_row("Km");
ImGui::TextDisabled("%s", format(STR_C("%s, of the kilometrage of line %s"), kilometrage::text(known).c_str(), line_of_open().c_str()).c_str());
item_tooltip("The km of the middle of the station, as the Kilometrage tool sets them for the line, the jumps too: the block signals of the lines are numbered after them");
}
else
{
auto const hint{layout.kilometrage && km_of_open((layout.from + layout.to) * 0.5, known) ? format("%.3f", known) : example("189.563")};
text("Km", "##srkkm", entry != nullptr ? entry->km : std::string{}, hint.c_str(), [&](std::string const &Value) {
auto km{word_of(Value)};
std::replace(km.begin(), km.end(), ',', '.');
record_of_open().km = km == "-" ? std::string{} : km;
});
item_tooltip("The km of the middle of the station along the line, rising the way the switches are numbered: the block signals of the lines are numbered after the km");
// a km typed here is the station's alone: the one of the line serves the posts and the next stations too
ImGui::TableNextRow();
ImGui::TableSetColumnIndex(1);
if (ImGui::SmallButton(STR_C("Set the km of the line (X)")))
m_guide.open_kilometrage();
item_tooltip("The km typed above is this station's alone. Set with the Kilometrage tool, the km of the line serves this station, the next ones and the hectometre posts, typed once");
}
auto changed{false};
field_row("Line speed");
auto const set{set_speed_of_open()};
if (set > 0.0)
ImGui::TextWrapped("%s", format(STR_C("%.0f km/h, the highest set on its main tracks"), set).c_str());
else
ImGui::TextColored(kWrong, "%s", format(STR_C("%.0f km/h taken: no track of the station has a speed set"), speed_of_open()).c_str());
item_tooltip("The speed of the trains through the station, the highest one its main tracks and the lines out of it are set to in the Track tool, up to 250 km/h: the braking distance and the lights of the signals go by it. Without one 160 km/h is taken, or the speed of the braking distance set by hand");
field_row("Braking distance");
auto const by_hand{m_record >= 0 ? m_records[m_record].braking : 0};
auto const after{format(STR_C("%.0f m, after the speed"), braking_distance(set > 0.0 ? set : 160.0))};
ImGui::SetNextItemWidth(-1.0f);
if (ImGui::BeginCombo("##srkbrakingset", by_hand > 0 ? format(STR_C("%d m, set by hand"), by_hand).c_str() : after.c_str()))
{
if (ImGui::Selectable(after.c_str(), by_hand == 0))
{
record_of_open().braking = 0;
changed = true;
}
for (auto const distance : {400, 700, 1000, 1300})
if (ImGui::Selectable(format(STR_C("%d m, set by hand"), distance).c_str(), by_hand == distance))
{
record_of_open().braking = distance;
changed = true;
}
ImGui::EndCombo();
}
item_tooltip("The braking distance of the trains on the line, Ie-4 § 8: 400 m up to 60 km/h, 700 m up to 100, 1000 m up to 140, 1300 m above. The block sections and the warning discs stand no nearer, a signal telling of the next one standing nearer slows the trains. Set it by hand where the line has another one");
ImGui::EndTable();
if (changed)
{
m_changed = true;
survey_signals();
}
}
auto const coded{false == stem_of_open().empty()};
if (false == coded)
ImGui::TextColored(kWrong, "%s", STR_C("Type the code of the station first: its switches, track circuits and signals are named after it"));
step_heading(1, STR_C("Switch numbers"));
int from{m_reversed ? 1 : 0};
if (segmented("##srkfrom", from,
{{0, STR_C("From the left"), layout.kilometrage ? "From the lower km, as PKP PLK numbers them" : "From the west end of the station"},
{1, STR_C("From the right"), layout.kilometrage ? "From the higher km" : "From the east end of the station"}}))
{
m_reversed = from == 1;
record_of_open().reversed = m_reversed;
m_changed = true;
}
if (ImGui::Button(STR_C("Number the switches"), ImVec2(-1.0f, 0.0f)))
number_switches();
item_tooltip("Numbers the switches 1, 2, 3... along the station and names them after its code, as on the lines of PKP PLK: bpd_1, "
"the parts of a slip bpd_15a to bpd_15d. The drives and the objects naming a switch follow it, events written by hand keep the old names. One step of undo");
step_heading(2, STR_C("Track circuits"));
if (main_button(STR_C("Set the track circuits"), ImVec2(-1.0f, tall_button_height())))
set_circuits();
item_tooltip("Cuts the tracks of the station at the joints of the track circuits and names the circuits, as on the lines of PKP PLK: a "
"joint 1.5 m before the start of a switch, 4.2 m beyond the fouling point of each branch, where the axes are 3.5 m apart, as "
"Ie-4 gives it, in the middle of a link too short for both. Each switch gets bpd_iz<number>, each station track "
"bpd_it<number>: 1 and 2 the main tracks, track 1 on the right along the km, the odd ones beyond it, the even ones on the "
"other side. Run again after changes, it keeps the numbers the tracks have. One step of undo");
if (ImGui::Checkbox(STR_C("Edit the joints by hand"), &m_joint_editing) && false == m_joint_editing)
m_joint_held.reset();
item_tooltip("LMB on a plain track of the station: a new joint of the track circuits there. LMB on a joint: it is taken; then LMB on a "
"track moves it there, LMB on it again takes it away. The circuits are set again at once, and Set the track circuits "
"keeps the joints so changed. One step of undo each");
if (m_joint_editing && m_record >= 0)
{
auto const &hand{m_records[m_record]};
ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled));
ImGui::TextWrapped("%s", m_joint_held.has_value() ? STR_C("A joint taken: LMB on a track puts it there, LMB on it again takes it away, elsewhere lets it go") :
STR_C("LMB on a track: a new joint there; on a joint: take it, to move it or take it away"));
ImGui::PopStyleColor();
if (false == hand.joints_added.empty() || false == hand.joints_removed.empty())
{
ImGui::TextUnformatted(format(STR_C("By hand: %zu put, %zu taken away"), hand.joints_added.size(), hand.joints_removed.size()).c_str());
ImGui::SameLine();
if (ImGui::SmallButton(STR_C("As planned")))
{
auto &entry{record_of_open()};
srk_hand_joints const before{entry.track, entry.joints_added, entry.joints_removed};
entry.joints_added.clear();
entry.joints_removed.clear();
joints_changed(before, true);
}
item_tooltip("The joints put and taken away by hand forgotten, the circuits set again as planned. One step of undo");
}
}
if (auto const *selected{m_selection.selected_track()}; selected != nullptr && false == selected->Isolated.empty())
if (auto const number{track_of(selected->Isolated.front()->asName, stem_of_open())}; false == number.empty() && begin_fields("##srktrack"))
{
field_row("Track number");
std::array<char, 16> buffer{};
number.copy(buffer.data(), buffer.size() - 1);
if (ImGui::InputText("##srktracknumber", buffer.data(), buffer.size(), ImGuiInputTextFlags_EnterReturnsTrue) || ImGui::IsItemDeactivatedAfterEdit())
renumber_track(*selected, buffer.data());
item_tooltip("The number of the selected station track: type another one and its track circuits are renamed, bpd_it7a, bpd_it7b. One step of undo");
ImGui::EndTable();
}
ImGui::Spacing();
if (ImGui::CollapsingHeader(format("%s (%zu)###srkswitches", STR_C("Switches"), layout.switches.size()).c_str(), ImGuiTreeNodeFlags_DefaultOpen))
render_switches();
}
void srk_tool::render_switches()
{
auto const &layout{*m_layout};
if (false == ImGui::BeginTable("##srkswitchlist", 3, ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_ScrollY, ImVec2(0.0f, std::min(320.0f, ImGui::GetTextLineHeightWithSpacing() * (layout.switches.size() + 1.5f)))))
return;
ImGui::TableSetupScrollFreeze(0, 1);
ImGui::TableSetupColumn(STR_C("Switch"), ImGuiTableColumnFlags_WidthStretch, 0.35f);
ImGui::TableSetupColumn(STR_C("Type"), ImGuiTableColumnFlags_WidthStretch, 0.45f);
ImGui::TableSetupColumn(STR_C("km"), ImGuiTableColumnFlags_WidthStretch, 0.2f);
ImGui::TableHeadersRow();
auto *selected{m_selection.selected_track()};
for (std::size_t index = 0; index < layout.switches.size(); ++index)
{
auto *track{layout.switches[index]};
auto const start{track->m_paths.front().points[segment_data::point::start]};
ImGui::TableNextRow();
ImGui::TableNextColumn();
if (ImGui::Selectable((track->name() + "##srksw" + std::to_string(index)).c_str(), track == selected, ImGuiSelectableFlags_SpanAllColumns))
{
m_selection.set_current_node(track);
m_picked = track;
m_view.focus_track(*track, 0, start);
}
ImGui::TableNextColumn();
auto const record{switch_store::named(*track)};
ImGui::TextUnformatted(record ? switch_store::label(*record).c_str() : track->eType == tt_Switch ? STR_C("switch") : track->eType == tt_Cross ? STR_C("crossing") : STR_C("turntable"));
ImGui::TableNextColumn();
auto const along{station::project(layout, start).x};
if (layout.kilometrage)
ImGui::Text("%.3f", station::km_of(layout, along));
else
ImGui::Text("%.0f m", along);
}
ImGui::EndTable();
}
void srk_tool::render_station_signals()
{
render_summary(false);
auto const coded{false == stem_of_open().empty()};
auto const ready{coded && circuits_set()};
if (false == ready)
ImGui::TextColored(kWrong, "%s", coded ? STR_C("Set the track circuits of the station first, in the Station tool: the signals stand at their joints") : STR_C("Type the code of the station first, in the Station tool: the signals are named after it"));
if (main_button(STR_C("Set the signals"), ImVec2(-1.0f, tall_button_height())))
set_signals();
item_tooltip("Places the signals of the station, as on the lines of PKP PLK, and names them after its code: an entry signal 300 m out on "
"each line, A, B... from the start of the km, Z, Y... from the end, the circuit from 15 m beyond it to the station bpd_ita; "
"an exit signal 15 m before the joint at the end of each station track a train is sent out of, F1, G2 towards the start, R1, "
"P2 towards the end; a shunting signal Tm1, Tm2... at the end of a shorter track. A signal standing by the place of one gets "
"its name, none is doubled. Each kind with the template chosen for it below. One step of undo");
m_signals.render_signal_templates({"main", "shunt"});
// what the signals placed lack, checked again after each change
ImGui::Spacing();
if (ImGui::CollapsingHeader(format("%s###srkcheck", STR_C("Signalling check")).c_str(), ImGuiTreeNodeFlags_DefaultOpen))
render_check();
}
void srk_tool::render_line_block()
{
render_summary(true);
render_lines();
if (main_button(STR_C("Set the line signals"), ImVec2(-1.0f, tall_button_height())))
set_lines();
item_tooltip("Places the signals of the lines out of the station, from its entry signals on, by the block chosen for each line above. "
"The automatic block: block signals evenly to the entry signals of the next station, a section no shorter than the braking "
"distance, numbered after the hectometre ahead of them, odd on track 1, even on track 2, and the block sections from 15 m "
"beyond them named as on the lines of PKP PLK, 2411-2571@LK2.1. The semi-automatic block: a warning disc ToA the braking "
"distance before the entry signal. The braking distance after the speed of the line, as Ie-4 gives it: 400 m up to 60 km/h, "
"700 m up to 100, 1000 m up to 140, 1300 m above. Needs the line and the km of the station. Run it at the next station too, it "
"keeps what stands. One step of undo");
m_signals.render_signal_templates({"block", "warning"});
}
void srk_tool::render_check()
{
render_problems();
ImGui::SeparatorText(STR_C("SHP"));
std::array<std::size_t, 5> states{};
for (auto const &head : m_heads)
++states[static_cast<std::size_t>(head.shp_of())];
auto const of = [&](shp_state const State) { return states[static_cast<std::size_t>(State)]; };
auto const needed{m_heads.size() - of(shp_state::needless)};
auto const found{of(shp_state::off) + of(shp_state::placed)};
auto const off{of(shp_state::off)};
auto const nowhere{of(shp_state::beyond)};
ImGui::BeginDisabled(of(shp_state::missing) == 0);
if (ImGui::Button(format("%s (%zu)###srkshp", STR_C("Place the SHP resonators"), of(shp_state::missing)).c_str(), ImVec2(-1.0f, 0.0f)))
set_shp();
ImGui::EndDisabled();
item_tooltip("Places the SHP track resonators the signals checked lack, rezonator.inc, as PKP PLK places them: 200 m before an entry "
"signal, a block signal and a warning disc, at an exit signal telling of the next one, as one onto a line of the automatic "
"block, 5 m either way. Its event goes on the track the trains run into there, at a joint of the tracks within 5 m, else the "
"track is cut. A resonator standing is one whose event ends with _shp, put on a track the trains run into within 100 m of its "
"place, so the ones of the old sceneries count too. One step of undo");
if (m_heads_known && needed > 0)
{
ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled));
ImGui::TextWrapped("%s", (format(STR_P("%zu of %zu signal has its SHP resonator", "%zu of %zu signals have their SHP resonators", needed), found, needed) + (off > 0 ? ", " + format(STR_P("%zu farther than 5 m from its place", "%zu farther than 5 m from their places", off), off) : std::string{}) +
(nowhere > 0 ? ", " + format(STR_P("%zu with the tracks ending short of the place of its resonator", "%zu with the tracks ending short of the places of their resonators", nowhere), nowhere) : std::string{})).c_str());
ImGui::PopStyleColor();
}
ImGui::Spacing();
if (ImGui::CollapsingHeader(format("%s (%zu)###srklengths", STR_C("Track lengths"), m_lengths.size()).c_str(), ImGuiTreeNodeFlags_DefaultOpen))
render_lengths();
ImGui::Spacing();
if (ImGui::CollapsingHeader(format("%s (%zu)###srkheads", STR_C("Signal heads"), static_cast<std::size_t>(std::count_if(m_heads.begin(), m_heads.end(), [](head_check const &Head) { return Head.station; }))).c_str(), ImGuiTreeNodeFlags_DefaultOpen))
render_heads();
}
void srk_tool::render_lines()
{
if (m_lines.empty())
{
ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled));
ImGui::TextWrapped("%s", m_lines_problem.empty() ? STR_C("No line leads out of the station beyond its entry signals") : m_lines_problem.c_str());
ImGui::PopStyleColor();
return;
}
auto const reason = [](block_reason const Why) {
switch (Why)
{
case block_reason::hand: return STR_C("set by hand");
case block_reason::standing: return STR_C("block signals stand along it");
case block_reason::double_track: return STR_C("a double-track line");
default: return STR_C("a single-track line");
}
};
auto const kind = [](block_kind const Kind) {
switch (Kind)
{
case block_kind::three: return STR_C("SBL, 3 aspects");
case block_kind::four: return STR_C("SBL, 4 aspects");
default: return STR_C("semi-automatic");
}
};
auto const set = [&](line_row const &Row, std::optional<block_kind> const Kind) {
auto &entry{record_of_open()};
for (auto const *row : std::initializer_list<line_row const *>{&Row, Row.partner >= 0 && Row.partner < static_cast<int>(m_lines.size()) ? &m_lines[Row.partner] : nullptr})
if (row != nullptr)
{
if (Kind.has_value())
entry.blocks[row->entry] = *Kind;
else
entry.blocks.erase(row->entry);
}
m_changed = true;
};
auto const set_ways = [&](line_row const &Row, std::optional<bool> const Both) {
auto &entry{record_of_open()};
if (Both.has_value())
entry.ways[Row.entry] = *Both;
else
entry.ways.erase(Row.entry);
m_changed = true;
};
auto changed{false};
if (ImGui::BeginTable("##srklinelist", 3, ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingStretchProp))
{
ImGui::TableSetupColumn(STR_C("Line"), ImGuiTableColumnFlags_WidthStretch, 0.26f);
ImGui::TableSetupColumn(STR_C("To"), ImGuiTableColumnFlags_WidthStretch, 0.29f);
ImGui::TableSetupColumn(STR_C("Block"), ImGuiTableColumnFlags_WidthStretch, 0.45f);
ImGui::TableHeadersRow();
for (std::size_t index = 0; index < m_lines.size() && false == changed; ++index)
{
auto const &row{m_lines[index]};
ImGui::PushID(static_cast<int>(index));
ImGui::TableNextRow();
ImGui::TableNextColumn();
auto const track{row.number == 0 ? std::string{STR_C("single track")} : format(STR_C("track %d"), row.number)};
if (row.leftovers > 0)
ImGui::PushStyleColor(ImGuiCol_Text, kDoubtful);
auto const clicked{ImGui::Selectable(format("%s, %s##srkline", row.entry.c_str(), track.c_str()).c_str(), false, ImGuiSelectableFlags_SpanAllColumns | ImGuiSelectableFlags_AllowOverlap)};
if (row.leftovers > 0)
ImGui::PopStyleColor();
if (clicked)
{
auto const &position{row.leftovers > 0 ? row.leftover : row.position};
auto const &travel{row.leftovers > 0 ? row.leftover_travel : row.travel};
m_view.fly_to(position + glm::dvec3{0.0, 4.0, 0.0}, glm::normalize(glm::dvec3{travel.x, -0.3, travel.y}), 30.0);
}
if (ImGui::IsItemHovered())
{
ImGui::BeginTooltip();
ImGui::PushTextWrapPos(ImGui::GetFontSize() * 30.0f);
ImGui::TextUnformatted(format(STR_C("The line out beyond the entry signal %s"), row.entry.c_str()).c_str());
if (row.number > 0)
ImGui::TextUnformatted((format(STR_C("Track %d of a double-track line"), row.number) + ", " + (row.inbound ? STR("its trains run in to the station") : STR("its trains run out of the station"))).c_str());
else
ImGui::TextUnformatted(STR_C("A single-track line"));
ImGui::TextUnformatted(format(STR_P("%zu block signal stands along it", "%zu block signals stand along it", row.blocks), row.blocks).c_str());
ImGui::TextUnformatted(format(STR_C("Block: %s, %s"), kind(row.block), reason(row.why)).c_str());
if (row.number > 0 && row.block != block_kind::semi)
ImGui::TextUnformatted(row.both ? STR_C("Wrong-track running: SBL both ways, the block signals with N") : STR_C("Wrong-track running: the mixed block, a warning disc before the entry signal"));
if (row.legacy)
ImGui::TextColored(kDoubtful, "%s", STR_C("No block section of the editor switches its block signals: it keeps the block of the scenery as it stands"));
if (row.leftovers > 0)
{
ImGui::TextColored(kDoubtful, "%s", (row.block != block_kind::semi ? format(STR_P("%zu warning disc stands along it, of the semi-automatic block: Set the line signals takes it away", "%zu warning discs stand along it, of the semi-automatic block: Set the line signals takes them away", row.leftovers), row.leftovers)
: format(STR_P("%zu block signal stands along it, of the automatic block: Set the line signals takes it away", "%zu block signals stand along it, of the automatic block: Set the line signals takes them away", row.leftovers), row.leftovers)).c_str());
ImGui::TextDisabled("%s", STR_C("LMB: fly to the first of them"));
}
else
ImGui::TextDisabled("%s", STR_C("LMB: fly to the entry signal"));
ImGui::PopTextWrapPos();
ImGui::EndTooltip();
}
ImGui::TableNextColumn();
auto const where{false == row.next.empty() ? row.next : row.station ? std::string{STR_C("station")} : std::string{STR_C("track end")}};
ImGui::TextUnformatted(format("%s %.1f km", where.c_str(), row.length / 1000.0).c_str());
if (ImGui::IsItemHovered())
ImGui::SetTooltip("%s", (false == row.next.empty() ? format(STR_C("To the entry signal %s of the next station"), row.next.c_str()) : row.station ? std::string{STR_C("To the next station, its entry signal not standing yet")} : std::string{STR_C("To the end of the tracks")}).c_str());
ImGui::TableNextColumn();
ImGui::SetNextItemWidth(-1.0f);
auto const preview{row.legacy ? std::string{STR_C("of the scenery")} : row.why == block_reason::hand ? std::string{kind(row.block)} : format(STR_C("%s, auto"), kind(row.block))};
ImGui::BeginDisabled(row.legacy);
if (ImGui::BeginCombo("##srkblock", preview.c_str()))
{
if (ImGui::Selectable(format(STR_C("Auto: %s, %s"), kind(row.own), reason(row.own_why)).c_str(), row.why != block_reason::hand))
{
set(row, std::nullopt);
changed = true;
}
for (auto const automatic : {block_kind::three, block_kind::four})
{
ImGui::BeginDisabled(row.number == 0);
if (ImGui::Selectable(automatic == block_kind::three ? STR_C("Automatic block, 3 aspects (SBL)") : STR_C("Automatic block, 4 aspects (SBL)"), row.why == block_reason::hand && row.block == automatic))
{
set(row, automatic);
changed = true;
}
ImGui::EndDisabled();
if (row.number == 0)
item_tooltip("Placed on a double-track line only: on a single track the block signals would face both ways, the editor leaves those standing as they are");
else
item_tooltip(automatic == block_kind::three ? "A block signal tells of the next one, Ie-1: red, orange for the next at stop, green. The block sections no shorter than the braking distance" :
"A block signal tells of the next two, Ie-1: red, orange for the next at stop, green flashing for the one after it at stop, green. The block sections no shorter than half the braking distance, two of them no shorter than it");
}
if (ImGui::Selectable(STR_C("Semi-automatic block"), row.why == block_reason::hand && row.block == block_kind::semi))
{
set(row, block_kind::semi);
changed = true;
}
ImGui::EndCombo();
}
ImGui::EndDisabled();
item_tooltip(row.legacy ? "Block signals stand along the line, none of them switched by a block section of the editor: the line keeps the block of the scenery as it stands" :
"The block of the line, both tracks of a double-track one alike. Automatic (SBL): block signals with block sections, no "
"warning disc, of 3 or 4 aspects, the templates of the block signals standing swapped for those of the aspects. "
"Semi-automatic: a warning disc ToA the braking distance before the entry signal. By itself: the automatic one where "
"block signals stand along the line, of their aspects, or it's double-track, of the aspects of the block signal "
"chosen in Templates below, else the semi-automatic one");
ImGui::PopID();
}
ImGui::EndTable();
}
// the wrong-track trains on the automatic block too, or on the semi-automatic one: the mixed block, the double-track lines of the
// automatic block of the station alike
std::vector<line_row const *> two_track;
for (auto const &row : m_lines)
if (row.number > 0 && row.block != block_kind::semi && false == row.legacy)
two_track.push_back(&row);
if (false == two_track.empty())
{
auto const all = [&](bool const Both) { return std::all_of(two_track.begin(), two_track.end(), [&](line_row const *Row) { return Row->both == Both; }); };
int ways{all(true) ? 2 : all(false) ? 1 : 0};
ImGui::TextDisabled("%s", STR_C("Wrong-track running"));
ImGui::BeginDisabled(changed);
if (segmented("##srkways", ways,
{{2, STR_C("SBL both ways"), "At each block boundary the block signals of both tracks either way: of the trains of the track 15 m "
"before the joint, for the wrong-track ones 15 m beyond it, with N (523N), on the outside of the line, as "
"on the lines of PKP PLK"},
{1, STR_C("Mixed"), "The automatic block for the trains of the track, the semi-automatic one for the wrong-track ones: no N "
"signals, a warning disc ToB the braking distance before the entry signal of the wrong-track trains, on the "
"outside of the line. Set the line signals places it and takes the N signals away"}}))
{
for (auto const *row : two_track)
set_ways(*row, (ways == 2) == row->own_both ? std::nullopt : std::optional<bool>{ways == 2});
changed = true;
}
ImGui::EndDisabled();
if (ways == 0)
ImGui::TextDisabled("%s", STR_C("Each line as it stands: a choice sets all of them"));
}
if (changed)
survey_signals();
ImGui::Checkbox(STR_C("Draw the block boundaries"), &m_drawing);
item_tooltip("LMB on a track of a line of the automatic block, beyond the entry signal: a block boundary there, the tracks cut "
"across the line, block signals 15 m before the joint, numbered after the hectometre ahead of them, on a line both ways "
"the wrong-track ones 15 m beyond it, with N, and the new block sections named; LMB on a block boundary standing takes its "
"signals away, the sections either side joined. A line whose block signals stand keeps them: Set the line signals places "
"them evenly only on a line without any. One step of undo each");
if (m_drawing)
{
ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled));
ImGui::TextWrapped("%s", STR_C("LMB on a track of a line beyond the entry signal: a block boundary there; on one standing: taken away"));
ImGui::PopStyleColor();
}
}
std::string srk_tool::boundary_hover(glm::dvec3 const &Point, bool &Valid)
{
m_boundary = {};
Valid = false;
if (false == drawing())
return {};
auto best{-1};
auto nearest{3.0};
double at{0.0};
for (std::size_t index = 0; index < m_lines.size() && index < m_line_ways.size(); ++index)
{
double gap{0.0};
auto const distance{station::distance_on(m_line_ways[index], Point, gap)};
if (gap < nearest && distance > 0.0 && distance < m_line_ways[index].length())
{
nearest = gap;
best = static_cast<int>(index);
at = distance;
}
}
if (best < 0)
return STR("Drawing the block boundaries: LMB on a track of a line out of the station, beyond its entry signal");
auto const &row{m_lines[best]};
auto const &line{m_line_ways[best]};
if (row.legacy)
return format(STR_C("No block section of the editor switches the block signals beyond %s: the line keeps them as they stand"), row.entry.c_str());
if (row.block == block_kind::semi)
return format(STR_C("The line beyond %s has the semi-automatic block: choose the automatic one for it in the table of the lines"), row.entry.c_str());
if (row.number == 0)
return format(STR_C("The line beyond %s is single-track: the editor draws the block boundaries of double-track lines only"), row.entry.c_str());
if (at < kBoundaryEnd || at > row.length - kBoundaryEnd)
return format(STR_C("A block boundary stands %.0f m or more from the entry signals"), kBoundaryEnd);
m_boundary.entry = row.entry;
m_boundary.point = station::point_on(line, at).point;
// the other track across, the block signals standing within reach on both
std::vector<std::pair<std::size_t, double>> tracks{{static_cast<std::size_t>(best), at}};
if (row.partner >= 0 && row.partner < static_cast<int>(std::min(m_lines.size(), m_line_ways.size())) && false == m_lines[row.partner].legacy && m_lines[row.partner].block != block_kind::semi)
if (double gap{0.0}; true)
if (auto const across{station::distance_on(m_line_ways[row.partner], m_boundary.point, gap)}; gap < 12.0)
tracks.emplace_back(static_cast<std::size_t>(row.partner), across);
auto const near_stop = [&](line_row const &Row, double const Distance) {
auto const found{std::min_element(Row.stops.begin(), Row.stops.end(), [&](auto const &A, auto const &B) { return std::abs(A.first - Distance) < std::abs(B.first - Distance); })};
return found != Row.stops.end() && std::abs(found->first - Distance) < kBoundaryReach ? found : Row.stops.end();
};
m_boundary.remove = near_stop(row, at) != row.stops.end();
auto previous{0.0};
auto next{row.length};
for (auto const &stop : row.stops)
{
if (m_boundary.remove && std::abs(stop.first - at) < kBoundaryReach)
continue;
if (stop.first < at)
previous = std::max(previous, stop.first);
else
next = std::min(next, stop.first);
}
// the joint across each track, the block signal of its trains before it, the wrong-track one beyond it, both on the outside
auto const post_at = [&](station::line const &Way, double const Distance, std::string const &Name) {
auto const on{station::point_on(Way, Distance)};
glm::dvec3 const travel{on.way * out_of(Way)};
m_boundary.posts.push_back({on.point, glm::dvec3{-travel.z, 0.0, travel.x}, Name});
};
for (auto const &[index, distance] : tracks)
{
auto const &other{m_lines[index]};
auto const &way{m_line_ways[index]};
auto const drop{station::signal_drop * out_of(way)};
auto joint{distance};
if (m_boundary.remove)
{
auto const stop{near_stop(other, distance)};
if (stop == other.stops.end())
continue;
joint = stop->first;
post_at(way, joint - drop, stop->second);
auto const wrong{std::min_element(other.wrong.begin(), other.wrong.end(), [&](auto const &A, auto const &B) { return std::abs(A.first - joint - drop) < std::abs(B.first - joint - drop); })};
if (wrong != other.wrong.end() && std::abs(wrong->first - joint - drop) < kWrongTrack)
post_at(way, wrong->first, wrong->second);
}
else
{
// a number standing already gets a letter, as Set the line signals gives it
auto const free = [&](std::string const &Base) {
auto name{Base};
for (char letter = 'a'; m_signal_names.count(ToLower(name)) > 0 && letter <= 'z'; ++letter)
name = Base + letter;
return name;
};
auto const name{free(station::block_number(km_along(way, other.km_number, joint - drop), way.number, other.rising))};
post_at(way, joint - drop, signal_shown(name, {}));
if (other.both)
post_at(way, joint + drop, signal_shown(free(name + "N"), {}));
}
auto const on{station::point_on(way, joint)};
m_boundary.joints.emplace_back(on.point, on.way);
}
std::string names;
for (auto const &post : m_boundary.posts)
names += (names.empty() ? "" : ", ") + post.name;
m_boundary.valid = true;
Valid = true;
if (m_boundary.remove)
return format(STR_C("Click: take the block signals %s away, the block sections either side joined: %.2f km"), names.c_str(), (next - previous) / 1000.0);
auto const least{row.block == block_kind::four ? row.braking * 0.5 : row.braking};
auto label{format(STR_C("Click: block signals %s here: the block sections %.2f km and %.2f km"), names.c_str(), (at - previous) / 1000.0, (next - at) / 1000.0)};
if (std::min(at - previous, next - at) < least)
label += "\n" + format(row.block == block_kind::four ? STR_C("The block section of %.2f km is shorter than half the braking distance, %.0f m, of the 4-aspect block") : STR_C("The block section of %.2f km is shorter than the braking distance, %.0f m"), std::min(at - previous, next - at) / 1000.0, least);
return label;
}
void srk_tool::boundary_click()
{
if (false == drawing() || false == m_boundary.valid)
return;
block_edit const edit{m_boundary.entry, m_boundary.point, m_boundary.remove};
m_boundary = {};
set_lines(&edit);
}
std::optional<station::joint> srk_tool::hand_joint(glm::dvec3 const &Point, std::string &Why) const
{
Why.clear();
if (false == m_layout.has_value())
return std::nullopt;
// the path of the station nearest the point, along its polyline
auto nearest{kJointPick};
station::path const *on{nullptr};
for (auto const &path : m_layout->paths)
for (std::size_t i = 1; i < path.points.size(); ++i)
{
auto const a{path.points[i - 1]};
auto const step{path.points[i] - a};
auto const span{glm::dot(step, step)};
auto const t{span > 1e-9 ? std::clamp(glm::dot(Point - a, step) / span, 0.0, 1.0) : 0.0};
if (auto const gap{glm::distance(Point, a + step * t)}; gap < nearest)
{
nearest = gap;
on = &path;
}
}
if (on == nullptr)
{
Why = STR("LMB on a track of the station: a joint of the track circuits there");
return std::nullopt;
}
if (is_switch(*on->track))
{
Why = STR("A joint stands on a plain track, not in a switch: its circuit is the switch's own");
return std::nullopt;
}
if (on->approach)
{
Why = STR("Out on the line, beyond the station: its circuits go by its block, drawn in the Line block tool");
return std::nullopt;
}
station::joint result;
result.point = editor_track::point_at(*on->track, editor_track::nearest_parameter(*on->track, Point));
// at an end of the track: the tracks meeting there part, no cut
for (auto const &end : {on->points.front(), on->points.back()})
if (glm::distance(end, result.point) < kJointSnap)
return station::joint{nullptr, end};
result.track = on->track;
return result;
}
bool srk_tool::joint_outer(glm::dvec3 const &Joint) const
{
if (false == m_layout.has_value())
return false;
for (auto const &path : m_layout->paths)
if (path.approach && false == path.points.empty() && (glm::distance(path.points.front(), Joint) < 0.05 || glm::distance(path.points.back(), Joint) < 0.05))
return true;
return false;
}
std::optional<glm::dvec3> srk_tool::joint_near(glm::dvec3 const &Point) const
{
std::optional<glm::dvec3> result;
auto nearest{kJointPick};
for (auto const &joint : m_joints)
if (auto const gap{glm::distance(joint.at, Point)}; gap < nearest)
{
nearest = gap;
result = joint.at;
}
return result;
}
std::string srk_tool::joint_hover(glm::dvec3 const &Point, bool &Valid)
{
m_joint_target = {};
Valid = false;
if (false == editing_joints())
{
m_joint_held.reset();
return {};
}
if (stem_of_open().empty())
return STR("Type the code of the station first: its track circuits are named after it");
auto const standing{joint_near(Point)};
if (standing.has_value() && joint_outer(*standing))
return STR("This joint parts the station from the line out of it: it stays where the station ends");
std::string why;
auto const joint{hand_joint(Point, why)};
if (m_joint_held.has_value())
{
if (standing.has_value() && glm::distance(*standing, *m_joint_held) < 0.05)
{
m_joint_target = {joint_target::kind::remove, *standing};
Valid = true;
return STR("Click: take this joint away, the track circuits either side joined");
}
if (standing.has_value())
{
m_joint_target = {joint_target::kind::pick, *standing};
Valid = true;
return STR("Click: take this joint instead");
}
if (joint.has_value() && glm::distance(joint->point, *m_joint_held) < kJointSnap)
{
m_joint_target = {joint_target::kind::drop, *m_joint_held};
Valid = true;
return STR("Click: let the joint go, it stays where it stands");
}
if (joint.has_value())
{
m_joint_target = {joint_target::kind::move, joint->point};
Valid = true;
return format(STR_C("Click: the joint moved here, %.1f m from where it stood"), glm::distance(joint->point, *m_joint_held));
}
m_joint_target = {joint_target::kind::drop, *m_joint_held};
Valid = true;
return STR("Click: let the joint go, it stays where it stands");
}
if (standing.has_value())
{
m_joint_target = {joint_target::kind::pick, *standing};
Valid = true;
return STR("Click: take this joint, then click a track to move it there, or it again to take it away");
}
if (false == joint.has_value())
return why;
m_joint_target = {joint_target::kind::add, joint->point};
Valid = true;
return STR("Click: a new joint here, the track circuit parted");
}
void srk_tool::joint_click()
{
if (false == editing_joints())
return;
auto const target{m_joint_target};
m_joint_target = {};
switch (target.what)
{
case joint_target::kind::add:
change_joints(std::nullopt, target.point);
break;
case joint_target::kind::pick:
m_joint_held = target.point;
break;
case joint_target::kind::move:
{
auto const from{*m_joint_held};
m_joint_held.reset();
if (glm::distance(from, target.point) >= kJointSnap)
change_joints(from, target.point);
break;
}
case joint_target::kind::remove:
m_joint_held.reset();
change_joints(target.point, std::nullopt);
break;
case joint_target::kind::drop:
m_joint_held.reset();
break;
case joint_target::kind::none:
break;
}
}
void srk_tool::change_joints(std::optional<glm::dvec3> const &Remove, std::optional<glm::dvec3> const &Add)
{
if (m_record < 0)
return;
auto &entry{record_of_open()};
srk_hand_joints const before{entry.track, entry.joints_added, entry.joints_removed};
auto const within = [](std::vector<glm::dvec3> &List, glm::dvec3 const &Point, double const Reach) {
auto const found{std::find_if(List.begin(), List.end(), [&](glm::dvec3 const &Other) { return glm::distance(Other, Point) < Reach; })};
if (found == List.end())
return false;
List.erase(found);
return true;
};
// one put by hand goes away, a planned one is kept away; a joint put back where a planned one was taken away is the planned one
if (Remove.has_value() && false == within(entry.joints_added, *Remove, kJointSnap))
entry.joints_removed.push_back(*Remove);
if (Add.has_value() && false == within(entry.joints_removed, *Add, kJointSnap))
entry.joints_added.push_back(*Add);
joints_changed(before);
}
void srk_tool::joints_changed(srk_hand_joints const &Before, bool const Forget)
{
auto &entry{record_of_open()};
m_changed = true;
m_joint_change = Before;
set_circuits();
if (false == m_joint_change.has_value())
return;
// forgotten, the ones that changed nothing go anyway, in a step of their own: the anchor as it is carries them
if (Forget && false == m_status_refused && entry.track != nullptr && (Before.added != entry.joints_added || Before.removed != entry.joints_removed))
{
m_history.push_track_snapshot({{entry.track, editor_track::capture(*entry.track)}});
if (false == m_joint_change.has_value())
return;
}
// no step of the history took it, refused or with nothing to change: the joints as they were, the undo knowing of no other
if (m_status_refused || false == Forget)
{
entry.joints_added = Before.added;
entry.joints_removed = Before.removed;
}
m_joint_change.reset();
}
std::optional<srk_hand_joints> srk_tool::take_joint_change()
{
auto result{std::move(m_joint_change)};
m_joint_change.reset();
return result;
}
srk_hand_joints srk_tool::restore_joints(srk_hand_joints const &Joints)
{
load();
for (auto &entry : m_records)
if (entry.track == Joints.anchor && Joints.anchor != nullptr)
{
srk_hand_joints current{entry.track, entry.joints_added, entry.joints_removed};
entry.joints_added = Joints.added;
entry.joints_removed = Joints.removed;
m_changed = true;
m_joint_held.reset();
return current;
}
return Joints;
}
void srk_tool::render_lengths()
{
auto const dimmed = [](char const *Text) {
ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled));
ImGui::TextWrapped("%s", Text);
ImGui::PopStyleColor();
};
if (m_lengths.empty())
{
if (stem_of_open().empty())
dimmed(STR_C("Give the station its code first: its tracks are numbered and measured after it"));
else if (m_numbered)
dimmed(STR_C("The station tracks have no ends to be measured between"));
else
{
dimmed(STR_C("Set the track circuits first: the station tracks are measured by their numbers, from their joints, the fouling points and the signals"));
if (ImGui::Button((std::string{STR_C("Set the track circuits")} + "##srklengthcircuits").c_str(), ImVec2(-1.0f, 0.0f)))
set_circuits();
}
return;
}
auto const stem{stem_of_open()};
char const *const ways[] = {STR_C("To the right"), STR_C("To the left")};
if (ImGui::BeginTable("##srklengthlist", 4, ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_ScrollY, ImVec2(0.0f, std::min(320.0f, ImGui::GetTextLineHeightWithSpacing() * (m_lengths.size() + 1.5f)))))
{
ImGui::TableSetupScrollFreeze(0, 1);
ImGui::TableSetupColumn(STR_C("Track"), ImGuiTableColumnFlags_WidthStretch, 0.16f);
ImGui::TableSetupColumn(ways[0], ImGuiTableColumnFlags_WidthStretch, 0.28f);
ImGui::TableSetupColumn(ways[1], ImGuiTableColumnFlags_WidthStretch, 0.28f);
ImGui::TableSetupColumn(STR_C("Train up to"), ImGuiTableColumnFlags_WidthStretch, 0.28f);
ImGui::TableHeadersRow();
for (std::size_t index = 0; index < m_lengths.size(); ++index)
{
auto const &track{m_lengths[index]};
ImGui::TableNextRow();
ImGui::TableNextColumn();
if (ImGui::Selectable((track.number + "##srklength" + std::to_string(index)).c_str(), static_cast<int>(index) == m_length_shown, ImGuiSelectableFlags_SpanAllColumns))
{
// the track at the middle of its useful length selected, the camera over it
auto const &way{track.ways[0]};
auto const middle{stretch_of(track, way.rear.along, way.head.along)};
auto const at{middle[middle.size() / 2]};
station::path const *nearest{nullptr};
auto best{std::numeric_limits<double>::max()};
for (auto const &path : m_layout->paths)
for (auto const &point : path.points)
if (auto const distance{glm::distance(glm::dvec2{point.x, point.z}, glm::dvec2{at.x, at.z})}; false == path.approach && distance < best)
{
best = distance;
nearest = &path;
}
if (nearest != nullptr)
{
m_selection.set_current_node(nearest->track);
m_picked = nearest->track;
m_view.focus_track(*nearest->track, nearest->index, at);
}
}
if (ImGui::IsItemHovered())
{
m_length_hover = static_cast<int>(index);
ImGui::BeginTooltip();
ImGui::TextUnformatted(format(STR_C("Track %s"), track.number.c_str()).c_str());
for (int way = 0; way < 2; ++way)
{
auto const &part{track.ways[way]};
ImGui::TextUnformatted(format(STR_C("%s: %.0f m, from %s to %s"), ways[way], part.length, limit_text(part.rear, stem).c_str(), limit_text(part.head, stem).c_str()).c_str());
}
ImGui::TextDisabled(STR_C("Construction length %.0f m: between the switches at its ends, the switches within it left out"), track.construction);
if (std::abs(track.ways[0].length - track.ways[1].length) > kUnequal)
ImGui::TextColored(kDoubtful, "%s", STR_C("The two ways differ: their trains stop on other stretches of the track, between other switches or signals"));
ImGui::TextDisabled("%s", STR_C("LMB: show it"));
ImGui::EndTooltip();
}
auto const unequal{std::abs(track.ways[0].length - track.ways[1].length) > kUnequal};
for (int way = 0; way < 2; ++way)
{
ImGui::TableNextColumn();
auto const &part{track.ways[way]};
if (unequal)
ImGui::TextColored(ImVec4(1.0f, 0.75f, 0.3f, part.head.what == station::limit::kind::signal ? 1.0f : 0.6f), "%.0f m", part.length);
else if (part.head.what == station::limit::kind::signal)
ImGui::Text("%.0f m", part.length);
else
ImGui::TextDisabled("%.0f m", part.length);
}
ImGui::TableNextColumn();
ImGui::Text("%.0f m", std::max(0.0, std::min(track.ways[0].length, track.ways[1].length) - kTrainMargin));
}
ImGui::EndTable();
}
if (std::none_of(m_lengths.begin(), m_lengths.end(), [](station::lengths const &Track) { return Track.ways[0].head.what == station::limit::kind::signal || Track.ways[1].head.what == station::limit::kind::signal; }))
{
dimmed(STR_C("No signal stands by the station tracks yet, the lengths run between the fouling points: set the signals for the useful ones"));
if (ImGui::Button((std::string{STR_C("Set the signals")} + "##srklengthsignals").c_str(), ImVec2(-1.0f, 0.0f)))
set_signals();
}
if (ImGui::Button(STR_C("Copy the list of tracks"), ImVec2(-1.0f, 0.0f)))
{
ImGui::SetClipboardText(lengths_table().c_str());
begin_status();
m_status = format(STR_P("The lengths of %zu track copied", "The lengths of %zu tracks copied", m_lengths.size()), m_lengths.size());
}
item_tooltip("The lengths of the station tracks as a table to paste into a spreadsheet: the construction length and the useful one each way with its limits, as the list of the tracks of a station gives them");
dimmed(STR_C("The useful length: where a train stands, from the signal it stops by back to the joint, the fouling point or the level crossing behind it, between those where no signal stands (dimmed). The longest train leaves 25 m of it: 10 m to stop, 10 m to see the signal, 5 m to the joint"));
}
void srk_tool::render_head_fit(head_check const &Head)
{
if (Head.arms > 0)
{
// a semaphore described with its arms and its aspects
if (false == Head.fits && Head.fit.empty())
ImGui::TextColored(kWrong, "%s", STR_C("No semaphore of its mount has these aspects"));
else if (false == Head.fits)
ImGui::TextColored(kDoubtful, "%s", format(STR_C("Its arms don't show all of it: %s does"), Head.fit.c_str()).c_str());
else if (Head.more)
ImGui::TextDisabled("%s", format(STR_C("It has more than it needs: %s would do. The fitting leaves it be: events written by hand may use its aspects"), Head.fit.c_str()).c_str());
}
else if (Head.told)
{
// a shaped warning disc before a semaphore described, by the events it repeats; one not described only offered the one
if (Head.unsaid)
ImGui::TextDisabled("%s", format(STR_C("Its template doesn't say what it tells, so it isn't checked: %s says so and tells all its semaphore shows. The fitting leaves it be, swap it by hand if you like"), Head.fit.c_str()).c_str());
else if (false == Head.fits && Head.fit.empty())
ImGui::TextColored(kWrong, "%s", STR_C("No disc of its mount tells all its semaphore shows"));
else if (false == Head.fits)
ImGui::TextColored(kDoubtful, "%s", format(STR_C("It doesn't tell apart all its semaphore shows: %s does"), Head.fit.c_str()).c_str());
}
else if (Head.lamps.empty() && Head.kind != "warning")
ImGui::TextDisabled("%s", STR_C("A semaphore with arms: its lights aren't checked"));
else if (false == Head.fits && Head.fit.empty())
ImGui::TextColored(kWrong, "%s", STR_C("No template of its kind and mount has these lights"));
else if (false == Head.fits)
ImGui::TextColored(kDoubtful, "%s", format(STR_C("Its lights don't show all of it: %s does"), Head.fit.c_str()).c_str());
else if (Head.more)
ImGui::TextDisabled("%s", format(STR_C("It has more lights than it needs: %s will do"), Head.fit.c_str()).c_str());
}
void srk_tool::render_head_aspects(head_check const &Head)
{
if (Head.arms > 0 || (Head.lamps.empty() && false == Head.aspect_names.empty()))
{
// a semaphore or a disc described: its aspects by name
std::string names;
for (auto const &name : Head.aspect_names)
names += (names.empty() ? "" : " ") + name;
ImGui::TextUnformatted(names.c_str());
}
else if (Head.lamps.empty())
ImGui::TextDisabled("%s", Head.kind == "warning" ? STR_C("disc") : STR_C("arms"));
else
lamp_row(Head.lamps, Head.own);
}
void srk_tool::render_heads()
{
auto const dimmed = [](char const *Text) {
ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled));
ImGui::TextWrapped("%s", Text);
ImGui::PopStyleColor();
};
if (false == m_heads_known)
{
dimmed(STR_C("Looking for the signal templates..."));
return;
}
if (std::none_of(m_heads.begin(), m_heads.end(), [](head_check const &Head) { return Head.station; }))
{
dimmed(STR_C("No main signal stands by the station yet: its lights are checked once one does"));
if (ImGui::Button((std::string{STR_C("Set the signals")} + "##srkheads").c_str(), ImVec2(-1.0f, 0.0f)))
set_signals();
return;
}
auto const line{speed_of_open()};
std::vector<std::size_t> rows;
std::size_t fine{0};
for (std::size_t index = 0; index < m_heads.size(); ++index)
{
auto const &head{m_heads[index]};
if (head.station || false == head.fits || false == head.problems.empty() || (head.shp_of() != shp_state::needless && head.shp_of() != shp_state::placed))
rows.push_back(index);
else
++fine;
}
if (ImGui::BeginTable("##srkheadlist", 5, ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_ScrollY, ImVec2(0.0f, std::min(320.0f, ImGui::GetTextLineHeightWithSpacing() * (rows.size() + 1.5f)))))
{
ImGui::TableSetupScrollFreeze(0, 1);
ImGui::TableSetupColumn(STR_C("Signal"), ImGuiTableColumnFlags_WidthStretch, 0.2f);
ImGui::TableSetupColumn(STR_C("Speeds"), ImGuiTableColumnFlags_WidthStretch, 0.2f);
ImGui::TableSetupColumn(STR_C("Lights"), ImGuiTableColumnFlags_WidthStretch, 0.21f);
ImGui::TableSetupColumn(STR_C("State"), ImGuiTableColumnFlags_WidthStretch, 0.24f);
ImGui::TableSetupColumn(STR_C("SHP"), ImGuiTableColumnFlags_WidthStretch, 0.15f);
ImGui::TableHeadersRow();
for (auto const index : rows)
{
auto const &head{m_heads[index]};
ImGui::TableNextRow();
ImGui::TableNextColumn();
if (ImGui::Selectable((head.name + "##srkhead" + std::to_string(index)).c_str(), static_cast<int>(index) == m_head_hover, ImGuiSelectableFlags_SpanAllColumns))
{
m_view.fly_to(head.position + glm::dvec3{0.0, 4.0, 0.0}, glm::normalize(glm::dvec3{head.travel.x, -0.3, head.travel.y}), 30.0);
m_signals.select_signal(head.instance);
}
if (ImGui::IsItemHovered())
{
m_head_hover = static_cast<int>(index);
ImGui::BeginTooltip();
ImGui::PushTextWrapPos(ImGui::GetFontSize() * 32.0f);
auto const *kind{head.kind == "main" ? STR_C("Main signal %s") : head.kind == "block" ? STR_C("Block signal %s") : STR_C("Warning disc %s")};
ImGui::TextUnformatted(format(kind, head.name.c_str()).c_str());
ImGui::TextDisabled("%s", head.file.c_str());
for (std::size_t k = 0; k < head.routes.size(); ++k)
{
auto const &route{head.routes[k]};
std::string text;
if (route.next >= 0)
text = format(STR_C("To %s: %.0f m"), head.nexts[k].c_str(), route.length);
else if (route.ended)
text = format(STR_C("To the end of the tracks: %.0f m"), route.length);
else
text = format(STR_C("No signal within %.0f m"), route.length);
if (head.kind == "main")
text += ", " + (route.speed > 0.0 && shown_speed(route.speed, line) > 0 ? format(STR_C("%d km/h through the switches"), shown_speed(route.speed, line)) : format(STR_C("%.0f km/h"), line));
std::string turnouts;
for (auto const *turnout : route.turnouts)
turnouts += (turnouts.empty() ? "" : ", ") + without_stem(turnout->name(), stem_of_open());
if (false == turnouts.empty())
text += ", " + format(STR_P("off the straight at switch %s", "off the straight at switches %s", route.turnouts.size()), turnouts.c_str());
if (route.warning >= 0)
text += ", " + STR("past a warning disc");
ImGui::BulletText("%s", text.c_str());
}
if (head.kind != "warning")
{
head_need need;
need.speeds = head.speeds;
need.informs = head.informs;
need.white = head.white;
ImGui::TextUnformatted(format(STR_C("Needs: %s"), (head.arms > 0 ? need_arms_text(need) : need_text(need)).c_str()).c_str());
}
if (head.shortened > 0)
ImGui::TextColored(kDoubtful, "%s", format(STR_C("The next signal stands nearer than the braking distance: with it at stop this one slows the trains to %d km/h, Ie-4 § 8 ust. 5"), head.shortened).c_str());
if (head.indicator)
ImGui::TextColored(kDoubtful, "%s", STR_C("Give it a W21 indicator \"14\": 140 km/h with the next signal at stop, Ie-4 § 8 ust. 5"));
render_head_fit(head);
for (auto const &problem : head.problems)
ImGui::TextColored(kWrong, "%s", problem.c_str());
if (auto const state{head.shp_of()}; state != shp_state::needless)
{
auto const wanted{head.shp > 0.0 ? format(STR_C("its SHP resonator belongs %.0f m before it"), head.shp) : std::string{STR_C("its SHP resonator belongs at it, it tells of the next signal")}};
if (state == shp_state::missing || state == shp_state::beyond)
ImGui::TextColored(kWrong, "%s", (wanted + ", " + (state == shp_state::beyond ? STR("the tracks before it end short of it") : STR("none stands"))).c_str());
else
ImGui::TextColored(state == shp_state::off ? kDoubtful : kRight, "%s", (wanted + ", " + format(STR_C("its event %.0f m before it"), head.shp_found)).c_str());
}
ImGui::TextDisabled("%s", STR_C("LMB: fly to it"));
ImGui::PopTextWrapPos();
ImGui::EndTooltip();
}
ImGui::TableNextColumn();
if (head.kind == "main")
{
auto text{format("%.0f", line)};
for (auto speed{head.speeds.rbegin()}; speed != head.speeds.rend(); ++speed)
text += ", " + std::to_string(*speed);
ImGui::TextUnformatted(text.c_str());
}
else
ImGui::TextDisabled("-");
ImGui::TableNextColumn();
render_head_aspects(head);
ImGui::TableNextColumn();
if (head.lamps.empty() && head.arms == 0 && false == head.told)
ImGui::TextDisabled("-");
else if (head.unsaid)
ImGui::TextDisabled("%s", STR_C("not described"));
else if (false == head.fits)
{
auto const *missing{head.arms > 0 || head.told ? STR_C("aspects missing") : STR_C("lights missing")};
ImGui::TextColored(head.fit.empty() ? kWrong : kDoubtful, "%s", head.fit.empty() ? STR_C("no template") : missing);
}
else if (head.more)
ImGui::TextDisabled("%s", STR_C("more than needed"));
else
ImGui::TextColored(kRight, "%s", STR_C("fits"));
if (false == head.problems.empty())
{
ImGui::SameLine();
ImGui::TextColored(kWrong, "%s", STR_C("too near"));
}
ImGui::TableNextColumn();
switch (head.shp_of())
{
case shp_state::needless: ImGui::TextDisabled("-"); break;
case shp_state::missing: ImGui::TextColored(kWrong, "%s", STR_C("none")); break;
case shp_state::beyond: ImGui::TextColored(kWrong, "%s", STR_C("no track")); break;
case shp_state::off: ImGui::TextColored(kDoubtful, "%.0f m", head.shp_found); break;
default: ImGui::TextColored(kRight, "%s", head.shp > 0.0 ? format("%.0f m", head.shp_found).c_str() : STR_C("at it")); break;
}
}
ImGui::EndTable();
}
if (fine > 0)
ImGui::TextDisabled("%s", format(STR_P("%zu signal of the lines fits, its SHP too", "%zu signals of the lines fit, their SHP too", fine), fine).c_str());
auto const fitting{static_cast<std::size_t>(std::count_if(m_heads.begin(), m_heads.end(), [](head_check const &Head) { return false == Head.fit.empty() && Head.fit != Head.file && (false == Head.fits || Head.more); }))};
ImGui::BeginDisabled(fitting == 0);
if (main_button(format("%s (%zu)###srkfitheads", STR_C("Fit the lights"), fitting).c_str(), ImVec2(-1.0f, 0.0f)))
fit_heads();
ImGui::EndDisabled();
item_tooltip("Gives each signal marked the template of its kind and mount with the lights its routes need and the least beyond them, the name, the plate and the place kept, the trains reading it as before. One step of undo");
dimmed(STR_C("The lights go by the routes of the trains: 40 km/h through the switches 1:9, 60 through 1:12 and 1:14, 100 through 1:18.5, by their radii, for these a lower orange light, with an orange strip for 60, a green one for 100, Ie-1; an upper orange one where the next signal can show stop; the white one of the substitute signal. A signal telling of the next one standing nearer than the braking distance slows the trains with it at stop, Ie-4 § 8 ust. 5"));
}
std::string srk_tool::lengths_table() const
{
auto const stem{stem_of_open()};
std::string result{STR_C("Track\tConstruction length [m]\tUseful to the right [m]\tfrom\tto\tUseful to the left [m]\tfrom\tto")};
result += '\n';
for (auto const &track : m_lengths)
{
result += format("%s\t%.0f", track.number.c_str(), track.construction);
for (auto const &part : track.ways)
result += format("\t%.0f\t%s\t%s", part.length, limit_text(part.rear, stem).c_str(), limit_text(part.head, stem).c_str());
result += '\n';
}
return result;
}
int srk_tool::length_of(TTrack const *Track) const
{
if (Track == nullptr || Track->Isolated.empty())
return -1;
auto const number{track_of(Track->Isolated.front()->asName, stem_of_open())};
for (std::size_t index = 0; index < m_lengths.size() && false == number.empty(); ++index)
if (m_lengths[index].number == number)
return static_cast<int>(index);
return -1;
}
void srk_tool::number_switches()
{
begin_status();
auto const code{m_record >= 0 ? m_records[m_record].code : std::string{}};
if (code.empty())
{
refuse(STR_C("Give the station its code first: the switches are named after it"));
return;
}
if (m_records[m_record].reversed != m_reversed)
{
m_records[m_record].reversed = m_reversed;
m_changed = true;
}
auto const units{station::numbering(*m_layout, m_reversed)};
std::vector<std::pair<TTrack *, std::string>> names;
std::unordered_set<TTrack const *> own;
for (std::size_t index = 0; index < units.size(); ++index)
for (std::size_t part = 0; part < units[index].parts.size(); ++part)
{
names.emplace_back(units[index].parts[part], station::switch_name(code, static_cast<int>(index) + 1, part, units[index].parts.size()));
own.insert(units[index].parts[part]);
}
for (auto &[track, name] : names)
{
std::string reason;
TTrack *owner{nullptr};
if (false == scene::Layers.editable(track, &reason))
{
refuse(format(STR_C("%s can't be renamed: %s"), track->name().c_str(), reason.c_str()));
return;
}
if (false == editor_track::name_valid(*track, name, reason, &owner) && (owner == nullptr || own.count(owner) == 0))
{
refuse(format(STR_C("%s can't be named %s: %s"), track->name().c_str(), name.c_str(), reason.c_str()));
return;
}
}
// the events aiming at a switch by its old name or named after it, <name>:event0, the editor doesn't write: renamed, the
// switch would lose them. they're listed first, the same renames clicked again go ahead
{
std::vector<std::string> unwritten;
std::string key{code};
for (auto const &[track, name] : names)
{
if (track->name() == name)
continue;
key += ' ' + track->name() + '>' + name;
auto const uses{editor_track::uses_of_name(*track)};
for (auto const *events : {&uses.events, &uses.loose})
for (auto const &event : *events)
unwritten.push_back(track->name() + ": " + event);
}
if (unwritten.empty() || m_numbering_confirm == key)
m_numbering_confirm.clear();
else
{
m_numbering_confirm = key;
std::string listed;
for (std::size_t i = 0; i < unwritten.size() && i < 6; ++i)
listed += (i > 0 ? ", " : "") + unwritten[i];
if (unwritten.size() > 6)
listed += format(" (+%zu)", unwritten.size() - 6);
refuse(format(STR_C("These events aim at the switches by their old names, the editor doesn't write them and they'd lose them: %s. Number the switches again to rename them anyway"), listed.c_str()));
return;
}
}
std::vector<std::pair<TTrack *, editor_track::state>> before;
std::map<std::string, std::string> parts;
std::map<std::string, std::string> bases;
for (auto const &[track, name] : names)
if (track->name() != name)
{
before.emplace_back(track, editor_track::capture(*track));
parts[track->name()] = name;
}
for (std::size_t index = 0; index < units.size(); ++index)
if (false == units[index].record.empty())
bases[units[index].record] = station::switch_name(code, static_cast<int>(index) + 1, 0, 1);
switch_store::rename(parts, bases);
// the objects of the scenery naming a switch, as the lanterns of rainsted/lwzm.inc, follow it
std::map<std::string, std::string> renamed;
for (auto const &[track, name] : names)
if (track->name() != name)
renamed[ToLower(track->name())] = name;
std::vector<std::pair<scene::instance_handle, std::vector<std::string>>> following;
for (auto &standing : m_templates.standing_templates([](std::string const &) { return true; }))
{
auto changed{false};
for (auto &value : standing.values)
if (auto const found{renamed.find(ToLower(value))}; found != renamed.end())
{
value = found->second;
changed = true;
}
if (changed)
following.emplace_back(standing.instance, std::move(standing.values));
}
// the names go round among the switches: a switch whose name another one gets gives it up first
for (auto const &entry : names)
if (entry.first->name() != entry.second && std::any_of(names.begin(), names.end(), [&](auto const &Other) { return Other.first != entry.first && Other.second == entry.first->name(); }))
editor_track::rename(*entry.first, entry.first->name() + "~");
for (auto const &[track, name] : names)
editor_track::rename(*track, name);
std::size_t numbered{0};
for (std::size_t index = 0; index < units.size(); ++index)
if (auto const record{switch_store::named(*units[index].parts.front())}; record && record->number != std::to_string(index + 1))
{
switch_store::number(record->name, std::to_string(index + 1));
++numbered;
}
if (before.empty() && numbered == 0)
{
m_status = STR_C("The switches have these numbers already");
return;
}
if (before.empty())
before.emplace_back(units.front().parts.front(), editor_track::capture(*units.front().parts.front()));
auto const followed{following.size()};
if (following.empty())
m_history.push_track_snapshot(std::move(before));
else
{
std::string error;
m_signals.signal_batch({{}, {}, {}, std::move(following)}, std::move(before), {}, error);
}
m_status = format(STR_P("%zu switch numbered", "%zu switches numbered", units.size()), units.size());
if (followed > 0)
m_status += ", " + format(STR_P("%zu object of the scenery follows them", "%zu objects of the scenery follow them", followed), followed);
}
void srk_tool::set_circuits()
{
begin_status();
auto const code{m_record >= 0 ? m_records[m_record].code : std::string{}};
if (code.empty())
{
refuse(STR_C("Give the station its code first: the track circuits are named after it"));
return;
}
auto const units{station::numbering(*m_layout, m_reversed)};
auto planned{station::joints(*m_layout, units)};
// the joints changed by hand: the planned ones taken away left out, the ones put by hand on the plain tracks they stand on
{
auto const &hand{m_records[m_record]};
planned.erase(std::remove_if(planned.begin(), planned.end(),
[&](station::joint const &Joint) {
return std::any_of(hand.joints_removed.begin(), hand.joints_removed.end(), [&](glm::dvec3 const &Point) { return glm::distance(Point, Joint.point) < kJointSnap; });
}),
planned.end());
for (auto const &point : hand.joints_added)
{
std::string why;
if (auto const joint{hand_joint(point, why)}; joint.has_value() && std::none_of(planned.begin(), planned.end(), [&](station::joint const &Other) { return glm::distance(Other.point, joint->point) < 0.05; }))
planned.push_back(*joint);
}
}
for (auto const &entry : planned)
if (std::string reason; entry.track != nullptr && false == editor_track::can_edit_geometry(*entry.track, reason))
{
refuse(format(STR_C("%s can't be cut: %s"), name_of(*entry.track).c_str(), reason.c_str()));
return;
}
for (auto const &path : m_layout->paths)
if (std::string reason; false == path.approach && false == scene::Layers.editable(path.track, &reason))
{
refuse(format(STR_C("%s can't be changed: %s"), name_of(*path.track).c_str(), reason.c_str()));
return;
}
// the cuts: each track from its end back, so the pieces left to cut stay in the track
std::vector<std::pair<TTrack *, editor_track::state>> before;
std::vector<TTrack *> created;
std::vector<glm::dvec3> points;
std::vector<std::pair<TTrack *, std::vector<glm::dvec3>>> cuts;
for (auto const &entry : planned)
{
points.push_back(entry.point);
if (entry.track == nullptr)
continue;
auto found{std::find_if(cuts.begin(), cuts.end(), [&](auto const &Cut) { return Cut.first == entry.track; })};
if (found == cuts.end())
found = cuts.insert(cuts.end(), {entry.track, {}});
found->second.push_back(entry.point);
}
for (auto &[track, at] : cuts)
{
before.emplace_back(track, editor_track::capture(*track));
auto *const piece{track};
std::sort(at.begin(), at.end(), [&](glm::dvec3 const &A, glm::dvec3 const &B) { return editor_track::nearest_parameter(*piece, A) > editor_track::nearest_parameter(*piece, B); });
for (auto const &point : at)
if (auto *cut{editor_track::split_path(*track, editor_track::nearest_parameter(*track, point))})
created.push_back(cut);
}
// the circuits of the station as cut
std::size_t count{0};
if (auto const found{station::find(*m_anchor)})
{
auto const circuits{station::circuits(*found, units, points)};
auto const numbers{station::track_numbers(*found, circuits)};
auto const stem{station::prefix(code)};
std::unordered_set<TTrack const *> captured(created.begin(), created.end());
for (auto const &[track, state] : before)
captured.insert(track);
// a station track keeps the name most of it has, given by hand or so far, unless another one has it too; the others take
// the numbers left on their side
std::vector<std::string> names(circuits.size());
std::map<std::string, std::size_t> held;
for (std::size_t index = 0; index < circuits.size(); ++index)
{
auto const &circuit{circuits[index]};
if (circuit.unit >= 0)
continue;
std::map<std::string, std::size_t> counts;
for (auto const *track : circuit.tracks)
if (track->Isolated.size() == 1 && false == track_of(track->Isolated.front()->asName, stem).empty())
++counts[track->Isolated.front()->asName];
if (auto const most{std::max_element(counts.begin(), counts.end(), [](auto const &A, auto const &B) { return A.second < B.second; })}; most != counts.end())
++held[names[index] = most->first];
}
std::unordered_set<std::string> taken;
for (auto &name : names)
if (false == name.empty() && held[name] > 1)
name.clear();
else if (false == name.empty())
taken.insert(name);
for (std::size_t index = 0; index < circuits.size(); ++index)
{
auto const &circuit{circuits[index]};
auto &name{names[index]};
if (circuit.unit >= 0)
name = stem + "iz" + unit_number(units[circuit.unit], stem, circuit.unit);
else if (name.empty())
{
auto number{numbers[index]};
while (taken.count(stem + "it" + number) > 0)
{
std::size_t digits{0};
while (digits < number.size() && std::isdigit(static_cast<unsigned char>(number[digits])))
++digits;
if (digits == 0)
break;
number = std::to_string(std::stoi(number.substr(0, digits)) + 2) + number.substr(digits);
}
taken.insert(name = stem + "it" + number);
}
for (auto *track : circuit.tracks)
{
if (track->Isolated.size() == 1 && track->Isolated.front()->asName == name)
continue;
if (captured.insert(track).second)
before.emplace_back(track, editor_track::capture(*track));
editor_track::isolated(*track, {name});
}
}
count = circuits.size();
}
if (before.empty() && created.empty())
{
m_status = STR_C("The track circuits are set already");
return;
}
m_history.push_track_snapshot(std::move(before), created);
m_status = format(STR_P("%zu track circuit", "%zu track circuits", count), count) + ", " + format(STR_P("%zu cut", "%zu cuts", created.size()), created.size());
}
std::string srk_tool::stem_of_open() const
{
return m_record >= 0 && false == m_records[m_record].code.empty() ? station::prefix(m_records[m_record].code) : std::string{};
}
std::string srk_tool::line_of_open() const
{
if (m_record >= 0 && false == m_records[m_record].line.empty())
return m_records[m_record].line;
if (false == m_layout.has_value())
return {};
return kilometrage::line_at(axis_point(*m_layout, (m_layout->from + m_layout->to) * 0.5));
}
bool srk_tool::km_of_line(double const Chainage, double &Km) const
{
auto const line{line_of_open()};
if (false == m_layout.has_value() || line.empty())
return false;
// along the axis of the station, on beyond its switches the way the km go through it
auto const &layout{*m_layout};
auto const within{std::clamp(Chainage, layout.from, layout.to)};
double low{0.0};
double high{0.0};
if (false == kilometrage::km_at(line, axis_point(layout, within), Km) || false == kilometrage::km_at(line, axis_point(layout, layout.from), low) || false == kilometrage::km_at(line, axis_point(layout, layout.to), high))
return false;
Km += (Chainage - within) / 1000.0 * (high >= low ? 1.0 : -1.0);
return true;
}
bool srk_tool::km_of_open(double const Chainage, double &Km) const
{
if (false == m_layout.has_value())
return false;
if (km_of_line(Chainage, Km))
return true;
if (m_record >= 0 && false == m_records[m_record].km.empty())
{
char *end{nullptr};
auto const &text{m_records[m_record].km};
auto const middle{std::strtod(text.c_str(), &end)};
if (end != text.c_str())
{
Km = middle + (Chainage - (m_layout->from + m_layout->to) * 0.5) / 1000.0 * (m_reversed ? -1.0 : 1.0);
return true;
}
}
if (false == m_layout->kilometrage)
return false;
Km = station::km_of(*m_layout, Chainage);
return true;
}
bool srk_tool::station_tracks(std::vector<station::numbered> &Tracks, std::unordered_set<TTrack const *> &Inside) const
{
Tracks.clear();
Inside.clear();
auto const stem{stem_of_open()};
if (false == m_layout.has_value() || stem.empty())
return false;
std::map<std::string, std::map<std::string, std::vector<TTrack *>>> numbers;
for (auto const &path : m_layout->paths)
{
if (path.track->m_editorremoved || path.track->Isolated.empty() || Inside.count(path.track) > 0)
continue;
auto const &name{path.track->Isolated.front()->asName};
if (name.size() <= stem.size() || name.compare(0, stem.size(), stem) != 0 || entry_circuit(name, stem))
continue;
Inside.insert(path.track);
if (auto const number{track_of(name, stem)}; false == number.empty())
numbers[number][name].push_back(path.track);
}
for (auto &[number, circuits] : numbers)
{
station::numbered entry;
entry.number = number;
for (auto &[name, members] : circuits)
entry.circuits.push_back(std::move(members));
Tracks.push_back(std::move(entry));
}
return false == Tracks.empty();
}
void srk_tool::renumber_track(TTrack const &Track, std::string const &Number)
{
begin_status();
auto const stem{stem_of_open()};
auto const from{Track.Isolated.empty() ? std::string{} : track_of(Track.Isolated.front()->asName, stem)};
std::string to;
for (auto const letter : Number)
if (std::isalnum(static_cast<unsigned char>(letter)))
to += static_cast<char>(std::tolower(static_cast<unsigned char>(letter)));
if (from.empty() || to.empty() || to == from)
return;
std::vector<std::pair<TTrack *, editor_track::state>> before;
std::unordered_set<TTrack const *> seen;
for (auto const &path : m_layout->paths)
{
if (path.track->Isolated.empty() || false == seen.insert(path.track).second)
continue;
auto const number{track_of(path.track->Isolated.front()->asName, stem)};
if (number == to)
{
refuse(format(STR_C("The station has a track %s already"), to.c_str()));
return;
}
if (number == from)
before.emplace_back(path.track, editor_track::capture(*path.track));
}
for (auto &[track, state] : before)
{
auto const &name{track->Isolated.front()->asName};
editor_track::isolated(*track, {stem + "it" + to + name.substr(stem.size() + 2 + from.size())});
}
if (before.empty())
return;
m_history.push_track_snapshot(std::move(before));
m_status = format(STR_C("Track %s is track %s now"), from.c_str(), to.c_str());
}
void srk_tool::set_signals()
{
begin_status();
auto const stem{stem_of_open()};
if (stem.empty())
{
refuse(STR_C("Give the station its code first: the signals are named after it"));
return;
}
auto const &layout{*m_layout};
std::vector<station::numbered> tracks;
std::unordered_set<TTrack const *> inside;
if (false == station_tracks(tracks, inside))
{
refuse(STR_C("Set the track circuits first: the signals stand at their joints"));
return;
}
auto plan{station::signals(layout, tracks, [&](TTrack const &Track) { return inside.count(&Track) > 0; })};
std::vector<standing_signal> standing;
m_signals.standing_signals(standing, true);
standing.erase(std::remove_if(standing.begin(), standing.end(), [&](standing_signal const &Signal) { return gap_to(layout, Signal.position) > 8.0; }), standing.end());
auto const full = [&](station::signal const &Signal) { return stem + ToLower(Signal.name); };
// the standing ones by their places, then by their names the ones moved away
std::vector<int> match(plan.size(), -1);
std::vector<char> used(standing.size(), 0);
std::vector<std::tuple<double, std::size_t, std::size_t>> candidates;
for (std::size_t i = 0; i < plan.size(); ++i)
{
auto const &planned{plan[i]};
glm::dvec2 const travel{glm::normalize(glm::dvec2{planned.travel.x, planned.travel.z} + glm::dvec2{1e-12, 0.0})};
auto const reach{planned.kind == station::signal::role::entry ? 400.0 : planned.kind == station::signal::role::exit ? 60.0 : 40.0};
for (std::size_t k = 0; k < standing.size(); ++k)
{
auto const &signal{standing[k]};
if ((signal.kind == "shunt") != (planned.kind == station::signal::role::shunting) || (signal.kind != "shunt" && signal.kind != "main") || glm::dot(travel_of(signal.yaw), travel) < 0.87)
continue;
glm::dvec2 const offset{signal.position.x - planned.point.x, signal.position.z - planned.point.z};
auto const along{glm::dot(offset, travel)};
auto const across{std::abs(offset.x * travel.y - offset.y * travel.x)};
if (std::abs(along) < reach && across < 3.0)
candidates.emplace_back(std::abs(along) + across * 10.0, i, k);
}
}
std::sort(candidates.begin(), candidates.end());
for (auto const &[score, i, k] : candidates)
if (match[i] < 0 && 0 == used[k])
{
match[i] = static_cast<int>(k);
used[k] = 1;
}
for (std::size_t i = 0; i < plan.size(); ++i)
for (std::size_t k = 0; k < standing.size() && match[i] < 0; ++k)
if (0 == used[k] && ToLower(standing[k].name) == full(plan[i]))
{
match[i] = static_cast<int>(k);
used[k] = 1;
}
// the circuits from the entry signals to the station: the line cut by each one, all of it checked before any is
struct cut
{
std::size_t signal{0};
TTrack *track{nullptr};
double parameter{0.0};
glm::dvec3 point{0.0};
bool outward{false};
std::vector<TTrack *> named; // between the station and the cut
std::vector<TTrack *> beyond; // out from the cut to the signal and on
};
std::vector<cut> cuts;
for (std::size_t i = 0; i < plan.size(); ++i)
{
auto const &planned{plan[i]};
if (planned.kind != station::signal::role::entry || planned.run.empty())
continue;
// the joint the trains pass the signal to, in from it towards the station
auto const run{station::run_line(planned)};
double gap{0.0};
auto const signal_at{station::distance_on(run, match[i] >= 0 ? standing[match[i]].position : planned.point, gap)};
auto const at{station::point_on(run, std::max(0.0, signal_at - station::signal_drop)).point};
cut entry;
entry.signal = i;
auto best{std::numeric_limits<double>::max()};
std::size_t nearest{0};
for (std::size_t k = 0; k < planned.run.size(); ++k)
{
auto const t{editor_track::nearest_parameter(*planned.run[k].first, at)};
auto const point{editor_track::point_at(*planned.run[k].first, t)};
if (auto const distance{glm::distance(glm::dvec2{point.x, point.z}, glm::dvec2{at.x, at.z})}; distance < best)
{
best = distance;
nearest = k;
entry.parameter = t;
entry.point = point;
}
}
for (std::size_t k = 0; k < nearest; ++k)
entry.named.push_back(planned.run[k].first);
for (std::size_t k = nearest + 1; k < planned.run.size(); ++k)
entry.beyond.push_back(planned.run[k].first);
entry.track = planned.run[nearest].first;
entry.outward = planned.run[nearest].second;
auto const &ends{entry.track->m_paths.front().points};
auto const to_start{glm::distance(entry.point, ends[segment_data::point::start])};
auto const to_end{glm::distance(entry.point, ends[segment_data::point::end])};
std::string reason;
if (std::min(to_start, to_end) <= 0.3)
{
// at an end already
((to_end < to_start) == entry.outward ? entry.named : entry.beyond).push_back(entry.track);
entry.track = nullptr;
}
else if (false == editor_track::can_edit_geometry(*entry.track, reason))
{
refuse(format(STR_C("%s can't be cut: %s"), name_of(*entry.track).c_str(), reason.c_str()));
return;
}
for (auto *part : entry.named)
if (false == scene::Layers.editable(part, &reason))
{
refuse(format(STR_C("%s can't be changed: %s"), name_of(*part).c_str(), reason.c_str()));
return;
}
cuts.push_back(std::move(entry));
}
// a template for each signal placed, before any track is cut for them
{
std::vector<signal_order> wanted;
for (std::size_t i = 0; i < plan.size(); ++i)
if (match[i] < 0)
{
wanted.emplace_back();
wanted.back().kind = plan[i].kind == station::signal::role::shunting ? "shunt" : "main";
}
if (auto const missing{m_signals.signal_templates_missing(wanted)}; false == missing.empty())
{
refuse(format(STR_C("The signals couldn't be placed: %s"), missing.c_str()));
return;
}
}
std::vector<std::pair<TTrack *, editor_track::state>> before;
std::vector<TTrack *> created;
std::unordered_set<TTrack const *> captured;
for (auto &entry : cuts)
{
auto &planned{plan[entry.signal]};
if (entry.track != nullptr)
{
captured.insert(entry.track);
before.emplace_back(entry.track, editor_track::capture(*entry.track));
if (auto *piece{editor_track::split_path(*entry.track, entry.parameter)})
{
created.push_back(piece);
captured.insert(piece);
entry.named.push_back(entry.outward ? entry.track : piece);
entry.beyond.push_back(entry.outward ? piece : entry.track);
if (planned.track == entry.track)
planned.track = entry.outward ? piece : entry.track;
}
}
auto const name{stem + "it" + ToLower(planned.name)};
for (auto *part : entry.named)
{
if (part->Isolated.size() == 1 && part->Isolated.front()->asName == name)
continue;
if (captured.insert(part).second)
before.emplace_back(part, editor_track::capture(*part));
editor_track::isolated(*part, {name});
}
// out of the circuit beyond its joint, where an earlier one ended at the signal
for (auto *part : entry.beyond)
{
if (part->Isolated.size() != 1 || ToLower(part->Isolated.front()->asName) != name)
continue;
if (captured.insert(part).second)
before.emplace_back(part, editor_track::capture(*part));
editor_track::isolated(*part, {});
}
}
std::vector<signal_order> placed;
std::vector<signal_rename> renamed;
for (std::size_t i = 0; i < plan.size(); ++i)
{
auto const &planned{plan[i]};
auto const plate{signal_shown(planned.name, {})}; // the text of its drawn plate
if (match[i] >= 0)
{
if (ToLower(standing[match[i]].name) != full(planned))
renamed.push_back({standing[match[i]].instance, full(planned), plate});
continue;
}
signal_order order;
order.track = planned.track;
order.point = planned.point;
order.facing = planned.facing;
order.side = planned.side;
order.kind = planned.kind == station::signal::role::shunting ? "shunt" : "main";
order.name = full(planned);
order.plate = plate;
placed.emplace_back(std::move(order));
}
// the others keep their names, unless one of these takes it
for (std::size_t k = 0; k < standing.size(); ++k)
if (0 == used[k] && std::any_of(plan.begin(), plan.end(), [&](station::signal const &Signal) { return full(Signal) == ToLower(standing[k].name); }))
renamed.push_back({standing[k].instance, ToLower(standing[k].name) + "_old", std::string{"0_nothing"}}); // a plate of no text: one left for removal
if (placed.empty() && renamed.empty() && before.empty() && created.empty())
{
m_status = STR_C("The signals are set already");
return;
}
// the lights of the main signals placed after the routes of their trains, to the signals standing and to these
std::vector<std::string> unfit;
std::vector<signal_head> heads;
m_signals.signal_heads(heads, true);
auto const chosen{std::find_if(heads.begin(), heads.end(), [](signal_head const &Head) { return Head.kind == "main" && Head.chosen; })};
if (chosen != heads.end())
{
std::vector<standing_signal> everywhere;
m_signals.standing_signals(everywhere, true);
std::vector<station::post> posts;
for (auto const &signal : everywhere)
if (auto const post{post_of(signal)}; post.track != nullptr)
posts.push_back(post);
std::vector<std::size_t> from;
for (auto const &order : placed)
{
if (order.kind == "main")
from.push_back(posts.size());
posts.push_back({order.track, order.facing, order.point, order.kind == "shunt" ? station::signal::role::shunting : station::signal::role::entry});
}
auto const found{station::routes(posts, from, route_reach(braking_of_open()))};
auto const line{speed_of_open()};
std::size_t next{0};
for (auto &order : placed)
{
if (order.kind != "main")
continue;
auto const need{need_of(found[next++], true, line, braking_of_open())};
if (auto const best{best_head(heads, "main", chosen->mount, chosen->name, 0, need, chosen->arms > 0)}; best >= 0)
order.file = heads[best].file;
else
unfit.push_back(signal_shown(order.name, stem));
}
}
std::string error;
auto const touched{false == before.empty() || false == created.empty()};
auto const count{m_signals.signal_batch({placed, renamed, {}, {}, {}}, std::move(before), std::move(created), error)};
if (false == error.empty())
refuse(format(STR_C("The signals couldn't be placed: %s"), error.c_str()) + (touched ? ". " + STR("Ctrl+Z takes back the tracks cut") : std::string{}));
else
m_status = format(STR_P("%zu signal placed", "%zu signals placed", count), count) + ", " + format(STR_P("%zu renamed", "%zu renamed", renamed.size()), renamed.size());
if (false == unfit.empty())
{
std::string names;
for (auto const &name : unfit)
names += (names.empty() ? "" : ", ") + name;
m_status += "\n" + format(STR_C("No template has what %s need, they got the one chosen in Templates: see Signal heads"), names.c_str());
}
}
bool srk_tool::lines_of_open(std::vector<standing_signal> const &Standing, std::vector<station::line> &Lines, std::vector<station::signal> &Entries, std::vector<std::size_t> &Owners, std::string &Problem) const
{
Lines.clear();
Entries.clear();
Owners.clear();
auto const stem{stem_of_open()};
if (false == m_layout.has_value())
return false;
if (stem.empty())
{
Problem = STR_C("Give the station its code first: the signals are named after it");
return false;
}
std::vector<station::numbered> tracks;
std::unordered_set<TTrack const *> inside;
if (false == station_tracks(tracks, inside))
{
Problem = STR_C("Set the track circuits first: the signals stand at their joints");
return false;
}
auto const plan{station::signals(*m_layout, tracks, [&](TTrack const &Track) { return inside.count(&Track) > 0; })};
// the lines begin at the entry signals standing
for (auto const &planned : plan)
{
if (planned.kind != station::signal::role::entry)
continue;
auto const found{std::find_if(Standing.begin(), Standing.end(), [&](standing_signal const &Signal) { return Signal.kind == "main" && ToLower(Signal.name) == stem + ToLower(planned.name); })};
if (found == Standing.end())
continue;
Entries.push_back(planned);
Owners.push_back(static_cast<std::size_t>(found - Standing.begin()));
}
if (Entries.empty())
{
Problem = STR_C("Set the signals first: the lines begin at the entry signals");
return false;
}
Lines = station::lines_out(*m_layout, Entries, kLineLimit);
if (Lines.empty())
{
Problem = STR_C("No line leads out of the station beyond its entry signals");
return false;
}
// the distances from the entry signals as they stand
for (auto &line : Lines)
{
double gap{0.0};
auto const at{station::distance_on(line, Standing[Owners[line.entry]].position, gap)};
if (gap < 4.5)
for (auto &distance : line.distances)
distance -= at;
}
return true;
}
srk_tool::block_kind srk_tool::block_of(station::line const &Line, std::string const &Entry, std::vector<standing_signal> const &Standing, std::vector<signal_head> const &Heads, block_reason &Why, block_kind &Own, block_reason &Own_why, std::size_t &Blocks) const
{
Blocks = 0;
auto four{false};
for (auto const &signal : Standing)
{
if (signal.kind != "block")
continue;
double gap{0.0};
auto const distance{station::distance_on(Line, signal.position, gap)};
if (gap > 4.5 || distance < 50.0 || distance > Line.length() - 1.0)
continue;
++Blocks;
four = four || std::any_of(Heads.begin(), Heads.end(), [&](signal_head const &Head) { return Head.file == signal.file && Head.aspects == 4; });
}
if (Blocks > 0)
{
Own = four ? block_kind::four : block_kind::three;
Own_why = block_reason::standing;
}
else if (Line.number > 0)
{
auto const chosen{std::find_if(Heads.begin(), Heads.end(), [](signal_head const &Head) { return Head.kind == "block" && Head.chosen; })};
Own = chosen != Heads.end() && chosen->aspects == 4 ? block_kind::four : block_kind::three;
Own_why = block_reason::double_track;
}
else
{
Own = block_kind::semi;
Own_why = block_reason::single;
}
Why = Own_why;
if (m_record >= 0)
if (auto const set{m_records[m_record].blocks.find(Entry)}; set != m_records[m_record].blocks.end())
{
Why = block_reason::hand;
return set->second;
}
return Own;
}
bool srk_tool::both_ways(std::vector<station::line> const &Lines, std::size_t const Index, std::string const &Entry, std::vector<standing_signal> const &Standing, bool &Hand, bool &Own) const
{
auto const &Line{Lines[Index]};
auto along{false};
auto wrong{false};
auto mixed{false};
for (auto const &signal : Standing)
{
double distance{0.0};
along = along || block_along(Line, signal, distance);
wrong = wrong || block_along(Line, signal, distance, true);
mixed = mixed || wrong_disc(Lines, Index, signal);
}
// block signals for the wrong-track trains, or none of either but a warning disc for them: the mixed block
Own = Line.number > 0 && (wrong || (false == along && false == mixed));
Hand = false;
if (m_record >= 0)
if (auto const set{m_records[m_record].ways.find(Entry)}; set != m_records[m_record].ways.end())
{
Hand = true;
return Line.number > 0 && set->second;
}
return Own;
}
std::string srk_tool::km_line(station::line const &Line) const
{
auto const described{line_of_open()};
auto const out{station::point_on(Line, std::min(2000.0, Line.length() * 0.5)).point};
double km{0.0};
if (false == kilometrage::km_at(described, out, km))
if (auto const found{kilometrage::line_at(out)}; false == found.empty())
return found;
return described;
}
double srk_tool::km_along(station::line const &Line, std::string const &Number, double const Distance) const
{
double km{0.0};
if (kilometrage::km_at(Number, station::point_on(Line, Distance).point, km) || false == m_layout.has_value())
return km;
auto const middle{(m_layout->from + m_layout->to) * 0.5};
auto const chainage{station::project(*m_layout, station::point_on(Line, 0.0).point).x};
km_of_open(chainage < middle ? chainage - Distance : chainage + Distance, km);
return km;
}
bool srk_tool::km_rising(station::line const &Line, std::string const &Number) const
{
auto const at{station::point_on(Line, 100.0)};
if (auto const growth{kilometrage::growth_at(Number, at.point, {at.way.x, at.way.z})}; growth != 0)
return (growth > 0) != Line.inbound;
return (km_along(Line, Number, 1000.0) > km_along(Line, Number, 0.0)) != Line.inbound;
}
double srk_tool::line_braking(station::line const &Line) const
{
if (m_record >= 0 && m_records[m_record].braking > 0)
return static_cast<double>(m_records[m_record].braking);
auto speed{0.0};
for (std::size_t k = 0; k < Line.points.size() && k < Line.owners.size(); ++k)
if (auto const set{Line.tracks[Line.owners[k]]->VelocityGet()}; Line.distances[k] >= 0.0 && set <= kFastest)
speed = std::max(speed, set);
return braking_distance(speed > 0.0 ? speed : 160.0);
}
void srk_tool::survey_lines(std::vector<standing_signal> const &Standing)
{
m_lines.clear();
m_line_ways.clear();
m_lines_problem.clear();
std::vector<station::line> lines;
std::vector<station::signal> entries;
std::vector<std::size_t> owners;
if (false == lines_of_open(Standing, lines, entries, owners, m_lines_problem))
return;
std::vector<signal_head> heads;
m_signals.signal_heads(heads, false);
auto const guards{guarded(m_templates.standing_templates([](std::string const &File) { return File == kControl; }))};
auto const stem{stem_of_open()};
auto const on_line = [](station::line const &Line, glm::dvec3 const &Point) {
double gap{0.0};
auto const distance{station::distance_on(Line, Point, gap)};
return gap < 4.5 && distance > 50.0 && distance < Line.length() - 1.0;
};
for (auto const &line : lines)
{
line_row row;
row.entry = entries[line.entry].name;
row.number = line.number;
row.inbound = line.inbound;
row.partner = line.partner;
row.station = line.station;
row.position = Standing[owners[line.entry]].position;
row.travel = travel_of(Standing[owners[line.entry]].yaw);
row.block = block_of(line, row.entry, Standing, heads, row.why, row.own, row.own_why, row.blocks);
row.braking = line_braking(line);
row.km_number = km_line(line);
row.rising = km_rising(line, row.km_number);
row.both = both_ways(lines, static_cast<std::size_t>(&line - lines.data()), row.entry, Standing, row.both_hand, row.own_both);
auto switched{false};
for (auto const &signal : Standing)
{
double distance{0.0};
if (block_along(line, signal, distance, true))
{
row.wrong.emplace_back(distance, signal_shown(signal.name, stem));
row.posts.push_back({distance, signal_shown(signal.name, stem), true, km_along(line, row.km_number, distance)});
}
if (false == block_along(line, signal, distance))
continue;
row.stops.emplace_back(distance + station::signal_drop * out_of(line), signal_shown(signal.name, stem));
row.posts.push_back({distance, signal_shown(signal.name, stem), false, km_along(line, row.km_number, distance)});
switched = switched || guards.count(ToLower(signal.name)) > 0;
}
// the warning discs: of the semi-automatic block, of the wrong-track trains of the mixed one
for (auto const &signal : Standing)
{
double distance{0.0};
auto const mixed{row.block != block_kind::semi && wrong_disc(lines, static_cast<std::size_t>(&line - lines.data()), signal)};
if (signal.kind == "warning" && (mixed || (row.block == block_kind::semi && faces_along(line, signal, distance))))
{
faces_along(line, signal, distance, mixed);
row.posts.push_back({distance, signal_shown(signal.name, stem), mixed, km_along(line, row.km_number, distance)});
}
}
std::sort(row.stops.begin(), row.stops.end());
std::sort(row.wrong.begin(), row.wrong.end());
// the schematic: straight out of the entry signal along the chainage, the track circuits along it in the colours of their names
auto const entry_at{station::project(*m_layout, station::point_on(line, 0.0).point)};
row.chainage = entry_at.x;
row.offset = entry_at.y;
row.outward = station::project(*m_layout, station::point_on(line, std::min(50.0, line.length())).point).x >= entry_at.x ? 1.0 : -1.0;
double probe{0.0};
row.km_known = kilometrage::km_at(row.km_number, station::point_on(line, 0.0).point, probe) || km_of_open(row.chainage, probe);
for (std::size_t k = 0; k < line.points.size() && k < line.distances.size() && k < line.owners.size(); ++k)
{
auto const *track{line.owners[k] < line.tracks.size() ? line.tracks[line.owners[k]] : nullptr};
auto const name{track == nullptr || track->Isolated.empty() ? std::string{} : track->Isolated.front()->asName};
if (row.sections.empty() || row.sections.back().name != name)
row.sections.push_back({line.distances[k], line.distances[k], name});
row.sections.back().to = line.distances[k];
if (k > 0 && row.sections.size() > 1 && row.sections.back().from == line.distances[k])
row.sections[row.sections.size() - 2].to = line.distances[k];
}
std::vector<std::pair<double, double>> bare;
for (std::size_t k = 1; k + 1 < row.sections.size(); ++k)
if (row.sections[k].name.empty() && row.sections[k].from >= 0.0 && row.sections[k].to - row.sections[k].from >= 1.0)
bare.emplace_back(row.sections[k].from, row.sections[k].to);
row.sections.erase(std::remove_if(row.sections.begin(), row.sections.end(), [](line_row::run const &Run) { return Run.name.empty() || Run.to - std::max(0.0, Run.from) < 1.0; }), row.sections.end());
for (auto &run : row.sections)
{
run.km_from = km_along(line, row.km_number, run.from);
run.km_to = km_along(line, row.km_number, run.to);
}
row.legacy = false == row.stops.empty() && false == switched;
if (false == row.legacy && row.block != block_kind::semi)
row.bare = std::move(bare);
auto const next{next_entry(line, Standing, row.length)};
row.next = next >= 0 ? signal_shown(Standing[next].name, stem) : std::string{};
m_lines.push_back(std::move(row));
m_line_ways.push_back(line);
}
// the signals of the other block along a line, but where it shares its track with a line of that block
for (std::size_t index = 0; index < m_lines.size(); ++index)
{
auto &row{m_lines[index]};
if (row.legacy || (row.number == 0 && row.block != block_kind::semi))
continue;
auto const automatic{row.block != block_kind::semi};
for (auto const &signal : Standing)
{
if (signal.kind != (automatic ? "warning" : "block") || false == on_line(m_line_ways[index], signal.position))
continue;
if (automatic && false == row.both && wrong_disc(m_line_ways, index, signal))
continue;
auto shared{false};
for (std::size_t other = 0; other < m_lines.size() && false == shared; ++other)
shared = (m_lines[other].block != block_kind::semi) != automatic && on_line(m_line_ways[other], signal.position);
if (shared)
continue;
++row.leftovers;
if (row.leftovers > 1)
continue;
row.leftover = signal.position;
row.leftover_travel = travel_of(signal.yaw);
}
}
}
void srk_tool::survey_problems(std::vector<standing_signal> const &Standing)
{
m_problems.clear();
if (false == m_layout.has_value())
return;
auto const stem{stem_of_open()};
auto const plan = [](glm::dvec3 const &Point) { return glm::dvec2{Point.x, Point.z}; };
auto const by_open = [&](glm::dvec3 const &Point) {
if (gap_to(*m_layout, Point) <= 8.0)
return true;
return std::any_of(m_line_ways.begin(), m_line_ways.end(), [&](station::line const &Line) {
double gap{0.0};
auto const distance{station::distance_on(Line, Point, gap)};
return gap <= 8.0 && distance > -50.0 && distance < Line.length() + 1.0;
});
};
for (auto const &signal : Standing)
if (false == signal.read.empty() && signal.track == nullptr && by_open(signal.position))
m_problems.push_back({format(STR_C("Signal %s: no track reads it"), signal_shown(signal.name, stem).c_str()), signal.position, signal.instance});
for (std::size_t index = 0; index < m_lines.size() && index < m_line_ways.size(); ++index)
{
auto const &row{m_lines[index]};
auto const &line{m_line_ways[index]};
if (false == row.station && line.points.size() > 1 && line.length() < kLineLimit - 50.0)
{
// the tracks go on beyond a gap: one missing, deleted maybe
auto const end{line.points.back()};
auto const step{plan(line.points.back() - line.points[line.points.size() - 2])};
if (glm::length(step) > 1e-9)
{
auto const way{glm::normalize(step)};
std::vector<TTrack const *> own(line.tracks.begin(), line.tracks.end());
for (auto const &target : editor_track::free_ends(nullptr, 1, end, kGapReach, own))
{
auto const ahead{plan(target.position - end)};
auto const along{glm::dot(ahead, way)};
auto const direction{plan(target.direction)};
if (along < 5.0 || along < glm::length(ahead) * 0.8 || glm::length(direction) < 1e-9 || std::abs(glm::dot(glm::normalize(direction), way)) < 0.7)
continue;
m_problems.push_back({format(STR_C("The line out of %s breaks off %.0f m beyond it, the tracks go on %.0f m farther"), row.entry.c_str(), line.length(), glm::length(ahead)), end});
break;
}
}
}
for (auto const &bare : row.bare)
m_problems.push_back({format(STR_C("The line out of %s: %.0f m of tracks %.0f m beyond the signal are in no block section"), row.entry.c_str(), bare.second - bare.first, bare.first), station::point_on(line, (bare.first + bare.second) * 0.5).point, 0, true});
}
// the block sections their controls switch, the tracks gone
std::unordered_set<std::string> circuits;
for (auto *track : simulation::Paths.sequence())
if (track != nullptr && false == track->m_editorremoved)
for (auto const *isolated : track->Isolated)
if (isolated != nullptr)
circuits.insert(ToLower(isolated->asName));
for (auto const &control : m_templates.standing_templates([](std::string const &File) { return File == kControl; }))
if (false == control.values.empty() && circuits.count(ToLower(control.values[0])) == 0 && by_open(control.location))
m_problems.push_back({format(STR_C("Block section %s has no track"), control.values[0].c_str()), control.location});
}
void srk_tool::render_problems()
{
if (m_problems.empty())
return;
ImGui::Spacing();
ImGui::PushStyleColor(ImGuiCol_Text, kWrong);
auto const open{ImGui::CollapsingHeader(format("%s (%zu)###srkproblems", STR_C("To repair"), m_problems.size()).c_str(), ImGuiTreeNodeFlags_DefaultOpen)};
ImGui::PopStyleColor();
item_tooltip("What the station and its lines need yet: signals no track reads, lines broken off where a track is missing, tracks of a line of the automatic block in no block section, block sections whose tracks are gone. Click a row to see the place");
if (false == open)
return;
for (std::size_t index = 0; index < m_problems.size(); ++index)
{
auto const &problem{m_problems[index]};
ImGui::PushStyleColor(ImGuiCol_Text, problem.signal != 0 || problem.lines ? kDoubtful : kWrong);
if (ImGui::Selectable((problem.text + "##srkproblem" + std::to_string(index)).c_str()))
m_view.fly_to(problem.at + glm::dvec3{0.0, 4.0, 0.0}, glm::normalize(glm::dvec3{0.3, -0.5, 0.8}), 60.0);
ImGui::PopStyleColor();
}
auto const fixable{static_cast<std::size_t>(std::count_if(m_problems.begin(), m_problems.end(), [](problem const &Problem) { return Problem.signal != 0 || Problem.lines; }))};
if (fixable == 0)
{
ImGui::TextDisabled("%s", STR_C("A track missing is laid in the Track tool: laid in the place of a deleted one it takes over its events and its track circuit"));
return;
}
if (main_button(format("%s (%zu)###srkfix", STR_C("Repair"), fixable).c_str(), ImVec2(-1.0f, 0.0f)))
fix_problems();
item_tooltip("The signals no track reads are read by the track they stand by again, as moving them does, the lines with tracks in no block section get their line signals set again. A track missing is laid in the Track tool. A step of undo each");
}
void srk_tool::fix_problems()
{
begin_status();
std::vector<scene::instance_handle> signals;
auto lines{false};
for (auto const &problem : m_problems)
{
if (problem.signal != 0)
signals.push_back(problem.signal);
lines = lines || problem.lines;
}
std::vector<std::string> done;
if (false == signals.empty())
{
auto const read{m_signals.signal_reattach(signals)};
done.push_back(format(STR_P("%zu of %zu signal read again", "%zu of %zu signals read again", static_cast<long long>(signals.size())), read, signals.size()));
if (read < signals.size())
done.back() += STR(": the rest stand farther than 10 m from a track, by vehicles or their events are gone");
}
auto const status{done.empty() ? std::string{} : done.front()};
if (lines)
{
m_status.clear();
set_lines();
if (false == status.empty())
m_status = status + (m_status.empty() ? "" : "\n" + m_status);
}
else
m_status = status;
}
void srk_tool::set_lines(block_edit const *Edit)
{
begin_status();
auto const stem{stem_of_open()};
std::vector<standing_signal> standing;
m_signals.standing_signals(standing, true);
std::vector<station::line> lines;
std::vector<station::signal> entries;
std::vector<std::size_t> entry_standing;
if (false == lines_of_open(standing, lines, entries, entry_standing, m_status))
return;
std::vector<signal_head> heads;
m_signals.signal_heads(heads, true);
auto const controls{m_templates.standing_templates([](std::string const &File) { return File == kControl; })};
auto const guards{guarded(controls)};
auto const facing_out = [&](station::line const &Line, standing_signal const &Signal, double const Distance) {
auto const way{station::point_on(Line, Distance).way};
return glm::dot(travel_of(Signal.yaw), glm::dvec2{way.x, way.z});
};
// of each line, 1: the automatic block, placed on a double-track line only, 2: the automatic block left as it stands, on a
// single-track line its signals facing both ways on a track, or with block signals the block sections of the editor don't switch,
// 0: the semi-automatic one
std::vector<char> automatic(lines.size(), 0);
std::vector<int> aspects(lines.size(), 3);
std::vector<char> both(lines.size(), 0); // the automatic block both ways
std::vector<std::vector<std::size_t>> along(lines.size()); // the block signals standing along each line facing its trains
std::vector<std::vector<std::size_t>> wrong(lines.size()); // and facing its wrong-track trains
for (std::size_t index = 0; index < lines.size(); ++index)
{
auto const &line{lines[index]};
auto why{block_reason::single};
auto own{block_kind::semi};
auto own_why{block_reason::single};
std::size_t blocks{0};
auto const kind{block_of(line, entries[line.entry].name, standing, heads, why, own, own_why, blocks)};
aspects[index] = kind == block_kind::four ? 4 : 3;
auto hand{false};
auto own_both{false};
both[index] = both_ways(lines, index, entries[line.entry].name, standing, hand, own_both) ? 1 : 0;
auto switched{false};
for (std::size_t k = 0; k < standing.size(); ++k)
{
double distance{0.0};
if (block_along(line, standing[k], distance, true))
wrong[index].push_back(k);
else if (block_along(line, standing[k], distance))
along[index].push_back(k);
else
continue;
switched = switched || guards.count(ToLower(standing[k].name)) > 0;
}
if (kind != block_kind::semi)
automatic[index] = line.number > 0 && (along[index].empty() || switched) ? 1 : 2;
}
// the lines set: all of them, or the one a block boundary is drawn on with the other track of a double-track one
std::vector<char> processed(lines.size(), Edit == nullptr ? 1 : 0);
int edited{-1};
double drawn{0.0};
if (Edit != nullptr)
{
for (std::size_t index = 0; index < lines.size(); ++index)
if (entries[lines[index].entry].name == Edit->entry)
edited = static_cast<int>(index);
double gap{0.0};
if (edited >= 0)
drawn = station::distance_on(lines[edited], Edit->point, gap);
if (edited < 0 || gap > 5.0)
{
refuse(STR_C("The line drawn on isn't there any more"));
return;
}
if (automatic[edited] != 1)
{
refuse(format(STR_C("The line beyond %s has no automatic block the editor sets: choose one for it in the table of the lines"), Edit->entry.c_str()));
return;
}
processed[edited] = 1;
if (auto const partner{lines[edited].partner}; partner >= 0 && automatic[partner] == 1)
{
station::distance_on(lines[partner], station::point_on(lines[edited], drawn).point, gap);
processed[partner] = gap < 12.0 ? 1 : 0;
}
}
auto const described{line_of_open()};
double known{0.0};
auto const blocked{[&] {
for (std::size_t index = 0; index < lines.size(); ++index)
if (processed[index] && automatic[index] == 1)
return true;
return false;
}()};
if (blocked && (false == km_of_open(0.0, known) || described.empty()))
{
refuse(STR_C("Give the station its line and its km first: the block signals and the block sections are named after them"));
return;
}
struct planned_signal
{
station::signal::role kind{station::signal::role::block};
std::string name;
std::string plate;
std::size_t line{0};
double distance{0.0}; // out along the line
std::string linked{"none"};
int match{-1}; // of the standing signals
bool kept{false}; // standing as it is, its name and its plate kept
bool wrong{false}; // facing the wrong-track trains
int twin{-1}; // the block signal of the other way at its boundary, of the planned ones
};
struct far_end
{
int signal{-1}; // the entry signal of the next station standing, of the standing signals
double distance{0.0}; // out to it, or to where the signals of the line end
};
std::vector<planned_signal> planned;
std::vector<far_end> ends(lines.size());
// the lines of the kilometrage the lines out run along, at a junction another one than the line of the station
std::vector<std::string> numbers;
for (auto const &line : lines)
numbers.push_back(km_line(line));
auto const km_on = [&](std::size_t const Index, double const Distance) { return km_along(lines[Index], numbers[Index], Distance); };
auto const rising = [&](std::size_t const Index) { return km_rising(lines[Index], numbers[Index]); };
auto const braking = [&](std::size_t const Index) { return line_braking(lines[Index]); };
for (std::size_t index = 0; index < lines.size(); ++index)
ends[index].signal = next_entry(lines[index], standing, ends[index].distance);
// the standing signals taken away: of a boundary drawn away, of the other block left along a line
std::vector<char> gone(standing.size(), 0);
for (std::size_t index = 0; index < lines.size(); ++index)
{
if (false == processed[index])
continue;
auto const &line{lines[index]};
auto const &end{ends[index]};
auto const &entry{entries[line.entry]};
auto const least{braking(index) * (aspects[index] == 4 ? 0.5 : 1.0)};
// the block signal of a boundary facing its trains before the joint, the wrong-track one beyond it
auto const drop{station::signal_drop * out_of(line)};
auto const plan = [&](double const Distance, std::string const &Name, int const Match, bool const Wrong) {
planned_signal signal;
signal.name = Name;
signal.plate = Match >= 0 ? std::string{} : signal_shown(Name, stem);
signal.line = index;
signal.distance = Distance;
signal.match = Match;
signal.kept = Match >= 0;
signal.wrong = Wrong;
planned.push_back(std::move(signal));
return static_cast<int>(planned.size() - 1);
};
std::unordered_set<std::size_t> paired;
auto const nearest_wrong = [&](double const Wanted, double &At) {
int found{-1};
auto nearest{kWrongTrack};
for (auto const k : wrong[index])
{
double distance{0.0};
block_along(line, standing[k], distance, true);
if (0 == gone[k] && 0 == paired.count(k) && std::abs(distance - Wanted) < nearest)
{
nearest = std::abs(distance - Wanted);
found = static_cast<int>(k);
At = distance;
}
}
return found;
};
// the wrong-track one: the one standing beyond the joint, else a new one there; none of one way only
auto const add_wrong = [&](int const Normal) {
auto at{planned[Normal].distance + 2.0 * drop};
auto const match{nearest_wrong(at, at)};
if (match >= 0)
paired.insert(static_cast<std::size_t>(match));
if (false == both[index])
{
if (match >= 0)
gone[match] = 1;
return;
}
auto const twin{plan(at, match >= 0 ? standing[match].name : planned[Normal].name + "N", match, true)};
planned[twin].twin = Normal;
planned[Normal].twin = twin;
};
if (automatic[index] == 1)
{
// the boundary drawn, the joint on the line drawn on and across on its other track
std::optional<double> boundary;
if (static_cast<int>(index) == edited)
boundary = drawn;
else if (edited >= 0)
if (double gap{0.0}; true)
if (auto const across{station::distance_on(line, station::point_on(lines[edited], drawn).point, gap)}; gap < 12.0)
boundary = across;
if (false == along[index].empty() || boundary.has_value())
{
// the block signals standing kept as they stand, the boundary drawn added or the ones standing at it taken away
for (auto const k : along[index])
{
double distance{0.0};
block_along(line, standing[k], distance);
if (boundary.has_value() && Edit->remove && std::abs(distance + drop - *boundary) < kBoundaryReach)
{
gone[k] = 1;
auto at{distance + 2.0 * drop};
if (auto const twin{nearest_wrong(at, at)}; twin >= 0)
gone[twin] = 1;
continue;
}
add_wrong(plan(distance, standing[k].name, static_cast<int>(k), false));
}
if (boundary.has_value() && false == Edit->remove)
add_wrong(plan(*boundary - drop, station::block_number(km_on(index, *boundary - drop), line.number, rising(index)), -1, false));
}
else
{
// the block signals, Ie-4 § 51: the sections no shorter than the braking distance, half of it with four aspects, and no
// longer than twice it, the line to the next station parted evenly, towards the end of the tracks a little over the
// least each
std::vector<double> places;
if (line.station || end.signal >= 0)
{
// as many on both tracks of the line, where both have the automatic block
auto const paired{line.partner >= 0 && line.partner < static_cast<int>(lines.size()) && automatic[line.partner] == 1};
auto const reach{paired ? (end.distance + ends[line.partner].distance) * 0.5 : end.distance};
auto const other{paired ? braking(line.partner) * (aspects[line.partner] == 4 ? 0.5 : 1.0) : least};
auto const sections{std::max(1.0, std::floor(reach / std::max(least, other)))};
for (int k = 1; k < sections; ++k)
places.push_back(end.distance * k / sections);
}
else
for (int k = 1; least * kBlockShare * k <= end.distance - 100.0; ++k)
places.push_back(least * kBlockShare * k);
for (auto const distance : places)
add_wrong(plan(distance, station::block_number(km_on(index, distance), line.number, rising(index)), -1, false));
}
// the wrong-track ones of no boundary taken away
for (auto const k : wrong[index])
if (0 == paired.count(k))
gone[k] = 1;
}
// the warning disc of the entry signal, the braking distance before it: of the semi-automatic block, or of the mixed one where
// it's the entry signal of the wrong-track trains, on the outside of the line facing them
auto const mixed{automatic[index] == 1 && line.number > 0 && false == line.inbound && false == both[index] && Edit == nullptr};
if (automatic[index] == 0 || mixed)
{
auto const distance{std::min(braking(index), end.distance - 100.0)};
if (distance >= 400.0)
{
planned_signal signal;
signal.kind = station::signal::role::warning;
signal.name = stem + "to" + ToLower(entry.name);
signal.plate = signal_shown("to" + entry.name, {});
signal.line = index;
signal.distance = distance;
signal.wrong = mixed;
planned.push_back(std::move(signal));
}
}
// the signals of the other block left along the line: the warning discs of a line of the automatic block, the block signals of
// one of the semi-automatic one
if (Edit != nullptr || automatic[index] == 2)
continue;
for (std::size_t k = 0; k < standing.size(); ++k)
{
if (automatic[index] == 1 ? standing[k].kind != "warning" : std::find(along[index].begin(), along[index].end(), k) == along[index].end())
continue;
// the one of the wrong-track trains of the mixed block kept
if (automatic[index] == 1 && false == both[index] && wrong_disc(lines, index, standing[k]))
continue;
// not where the line shares its track with one of the other block
auto shared{false};
for (std::size_t other = 0; other < lines.size() && false == shared; ++other)
{
if ((automatic[other] == 0) == (automatic[index] == 0))
continue;
double gap{0.0};
auto const distance{station::distance_on(lines[other], standing[k].position, gap)};
shared = gap < 4.5 && distance > 50.0 && distance < lines[other].length() - 1.0;
}
double gap{0.0};
auto const distance{station::distance_on(line, standing[k].position, gap)};
if (false == shared && gap < 4.5 && distance > 50.0 && distance < line.length() - 1.0)
gone[k] = 1;
}
}
// the standing ones by their places, then by their names
std::vector<char> used(gone);
for (auto const &signal : planned)
if (signal.match >= 0)
used[signal.match] = 1;
for (auto const index : entry_standing)
used[index] = 1;
for (auto const &end : ends)
if (end.signal >= 0)
used[end.signal] = 1;
std::vector<std::tuple<double, std::size_t, std::size_t>> candidates;
for (std::size_t i = 0; i < planned.size(); ++i)
{
auto const &signal{planned[i]};
if (signal.match >= 0)
continue;
auto const &line{lines[signal.line]};
auto const kind{signal.kind == station::signal::role::block ? "block" : "warning"};
auto const reach{signal.kind == station::signal::role::block ? 300.0 : 400.0};
for (std::size_t k = 0; k < standing.size(); ++k)
{
if (standing[k].kind != kind)
continue;
double gap{0.0};
auto const distance{station::distance_on(line, standing[k].position, gap)};
auto const facing{facing_out(line, standing[k], distance)};
if (gap < 4.5 && std::abs(distance - signal.distance) < reach && (line.inbound != signal.wrong ? -facing : facing) > 0.87)
candidates.emplace_back(std::abs(distance - signal.distance) + gap * 10.0, i, k);
}
}
std::sort(candidates.begin(), candidates.end());
for (auto const &[score, i, k] : candidates)
if (planned[i].match < 0 && 0 == used[k])
{
planned[i].match = static_cast<int>(k);
used[k] = 1;
double gap{0.0};
planned[i].distance = station::distance_on(lines[planned[i].line], standing[k].position, gap);
}
for (auto &signal : planned)
for (std::size_t k = 0; k < standing.size() && signal.match < 0; ++k)
if (0 == used[k] && ToLower(standing[k].name) == ToLower(signal.name))
{
signal.match = static_cast<int>(k);
used[k] = 1;
}
// a number another signal of the scenery has already gets a letter
std::unordered_set<std::string> taken;
for (std::size_t k = 0; k < standing.size(); ++k)
if (0 == used[k])
taken.insert(ToLower(standing[k].name));
for (auto const &signal : planned)
if (signal.kept)
taken.insert(ToLower(signal.name));
// the wrong-track ones after their twins: 523N beside 523
for (auto const wrong_track : {false, true})
for (auto &signal : planned)
{
if (signal.kind != station::signal::role::block || signal.kept || signal.wrong != wrong_track)
continue;
auto const base{wrong_track && signal.twin >= 0 ? planned[signal.twin].name + "N" : signal.name};
signal.name = base;
for (char letter = 'a'; taken.count(ToLower(signal.name)) > 0 && letter <= 'z'; ++letter)
signal.name = base + letter;
taken.insert(ToLower(signal.name));
signal.plate = signal_shown(signal.name, stem);
}
// the block sections of each track of a double-track line, between the signals in the order the trains pass them
struct section
{
std::string name;
std::size_t line{0};
double from{0.0};
double to{0.0};
std::string guard; // the block signal at its start, empty for a station one
std::string wrong_guard; // the one at its end facing the wrong-track trains, empty for none
glm::dvec3 start{0.0};
};
std::vector<section> sections;
std::vector<std::pair<std::size_t, std::string>> relinked; // standing station signals, the block signal before each
for (std::size_t index = 0; index < lines.size(); ++index)
{
auto const &line{lines[index]};
if (automatic[index] != 1 || false == processed[index])
continue;
struct stop
{
double distance{0.0};
std::string name;
int signal{-1}; // of the planned ones, -1 for a station signal
int standing{-1};
};
std::vector<stop> order{{0.0, standing[entry_standing[line.entry]].name, -1, static_cast<int>(entry_standing[line.entry])}};
for (std::size_t i = 0; i < planned.size(); ++i)
if (planned[i].line == index && false == planned[i].wrong)
order.push_back({planned[i].distance, planned[i].name, static_cast<int>(i), planned[i].match});
if (ends[index].signal >= 0)
order.push_back({ends[index].distance, standing[ends[index].signal].name, -1, ends[index].signal});
std::sort(order.begin(), order.end(), [](stop const &A, stop const &B) { return A.distance < B.distance; });
if (line.inbound)
std::reverse(order.begin(), order.end());
// the joints the trains pass the signals to: on beyond a block signal, in towards the station from an entry one
auto const joint_of = [&](stop const &Stop) {
if (Stop.signal >= 0)
return Stop.distance + (line.inbound ? -station::signal_drop : station::signal_drop);
return Stop.distance + (Stop.distance > 0.0 ? station::signal_drop : -station::signal_drop);
};
// the wrong-track one of a stop, the wrong-track trains pass them the other way
auto const twin_of = [&](std::size_t const At) { return At < order.size() && order[At].signal >= 0 ? planned[order[At].signal].twin : -1; };
for (std::size_t i = 0; i < order.size(); ++i)
{
auto const &here{order[i]};
auto const block_before{i > 0 && order[i - 1].signal >= 0};
auto const linked{block_before ? order[i - 1].name : std::string{"none"}};
if (here.signal >= 0)
planned[here.signal].linked = linked;
else if (block_before && here.standing >= 0 && false == standing[here.standing].linked.empty() && ToLower(standing[here.standing].linked) != ToLower(linked))
relinked.emplace_back(here.standing, linked);
auto const wrong_before{twin_of(i + 1)};
auto const wrong_linked{wrong_before >= 0 ? planned[wrong_before].name : std::string{"none"}};
if (auto const twin{twin_of(i)}; twin >= 0)
planned[twin].linked = wrong_linked;
else if (i == 0 && here.signal < 0 && here.standing >= 0 && false == standing[here.standing].linked.empty())
{
// the station signal the wrong-track trains come to: after the last wrong-track block signal, after none once it's gone
auto const &had{standing[here.standing].linked};
auto dropped{false};
for (std::size_t k = 0; k < standing.size() && false == dropped; ++k)
dropped = gone[k] && ToLower(standing[k].name) == ToLower(had);
if (ToLower(had) != ToLower(wrong_linked) && (wrong_before >= 0 || dropped))
relinked.emplace_back(here.standing, wrong_linked);
}
if (i == 0)
continue;
auto const &before{order[i - 1]};
// the lower km first, as on the lines of PKP PLK: 2411-2571@LK2.1
auto const ascending{rising(index)};
auto const &low{ascending ? before : here};
auto const &high{ascending ? here : before};
section found;
found.name = ToLower(section_tag(low.name, line.number) + "-" + section_tag(high.name, line.number) + "@lk" + numbers[index] + "." + std::to_string(line.number));
found.line = index;
found.from = std::min(joint_of(before), joint_of(here));
found.to = std::max(joint_of(before), joint_of(here));
found.guard = before.signal >= 0 ? before.name : std::string{};
if (auto const twin{twin_of(i)}; twin >= 0)
found.wrong_guard = planned[twin].name;
found.start = station::point_on(line, before.distance).point;
sections.push_back(std::move(found));
}
}
// the template of a signal placed: of a block signal by the aspects of its line, of the warning disc by the entry signal it tells
// of, of the mount of the disc chosen
auto const disc_mount{m_signals.signal_mount("warning", {})};
auto const template_of = [&](planned_signal const &Signal) {
if (Signal.kind == station::signal::role::block)
return block_template(heads, {}, aspects[Signal.line], Signal.wrong);
auto const &entry{standing[entry_standing[lines[Signal.line].entry]]};
auto const main{std::ranges::find_if(heads, [&entry](signal_head const &Head) { return Head.file == entry.file; })};
return disc_template(heads, main != heads.end() ? std::to_address(main) : nullptr, disc_mount);
};
// a template for each signal placed, before any track is cut for them
{
std::vector<signal_order> wanted;
for (auto const &signal : planned)
if (signal.match < 0)
{
auto const block{signal.kind == station::signal::role::block};
wanted.emplace_back();
wanted.back().kind = block ? "block" : "warning";
wanted.back().file = template_of(signal);
}
if (auto const missing{m_signals.signal_templates_missing(wanted)}; false == missing.empty())
{
refuse(format(STR_C("The signals couldn't be placed: %s"), missing.c_str()));
return;
}
}
// the tracks cut where the sections meet, all of it checked before any is
struct cut
{
TTrack *track{nullptr};
glm::dvec3 point{0.0};
};
std::vector<cut> cuts;
auto const add_cut = [&](station::line const &Line, double const Distance) -> bool {
auto const at{station::point_on(Line, Distance)};
if (at.track == nullptr || std::any_of(cuts.begin(), cuts.end(), [&](cut const &Cut) { return glm::distance(Cut.point, at.point) < 0.5; }))
return true;
auto const &ends_of{at.track->m_paths.front().points};
if (std::min(glm::distance(at.point, ends_of[segment_data::point::start]), glm::distance(at.point, ends_of[segment_data::point::end])) <= 0.3)
return true;
std::string reason;
if (false == editor_track::can_edit_geometry(*at.track, reason))
{
refuse(format(STR_C("%s can't be cut: %s"), name_of(*at.track).c_str(), reason.c_str()));
return false;
}
cuts.push_back({at.track, at.point});
return true;
};
for (auto const &found : sections)
if (false == add_cut(lines[found.line], found.from) || false == add_cut(lines[found.line], found.to))
return;
for (auto const &line : lines)
for (auto *part : line.tracks)
if (std::string reason; false == scene::Layers.editable(part, &reason) && std::any_of(sections.begin(), sections.end(), [&](section const &Found) { return &lines[Found.line] == &line; }))
{
refuse(format(STR_C("%s can't be changed: %s"), name_of(*part).c_str(), reason.c_str()));
return;
}
std::vector<std::pair<TTrack *, editor_track::state>> before;
std::vector<TTrack *> created;
std::unordered_set<TTrack const *> captured;
std::unordered_map<TTrack const *, std::vector<TTrack *>> pieces; // of each track cut, itself and the pieces cut off it
auto const piece_at = [&](TTrack *Track, glm::dvec3 const &Point) {
auto found{pieces.find(Track)};
if (found == pieces.end())
return Track;
TTrack *best{Track};
auto nearest{std::numeric_limits<double>::max()};
for (auto *piece : found->second)
{
auto const point{editor_track::point_at(*piece, editor_track::nearest_parameter(*piece, Point))};
if (auto const distance{glm::distance(point, Point)}; distance < nearest)
{
nearest = distance;
best = piece;
}
}
return best;
};
for (auto const &entry : cuts)
{
auto *track{piece_at(entry.track, entry.point)};
auto const parameter{editor_track::nearest_parameter(*track, entry.point)};
auto const &ends_of{track->m_paths.front().points};
if (std::min(glm::distance(entry.point, ends_of[segment_data::point::start]), glm::distance(entry.point, ends_of[segment_data::point::end])) <= 0.3)
continue;
if (captured.insert(track).second)
before.emplace_back(track, editor_track::capture(*track));
if (auto *piece{editor_track::split_path(*track, parameter)})
{
created.push_back(piece);
captured.insert(piece);
auto &list{pieces[entry.track]};
if (list.empty())
list.push_back(entry.track);
list.push_back(piece);
}
}
// the sections named, each track by its middle
for (std::size_t index = 0; index < lines.size(); ++index)
{
if (false == processed[index])
continue;
std::vector<TTrack *> parts;
for (auto *track : lines[index].tracks)
{
auto const found{pieces.find(track)};
if (found == pieces.end())
parts.push_back(track);
else
parts.insert(parts.end(), found->second.begin(), found->second.end());
}
for (auto *part : parts)
{
double gap{0.0};
auto const distance{station::distance_on(lines[index], editor_track::point_at(*part, 0.5), gap)};
if (gap > 1.0)
continue;
auto const found{std::find_if(sections.begin(), sections.end(), [&](section const &Section) { return Section.line == index && distance > Section.from && distance < Section.to; })};
if (found == sections.end() || (part->Isolated.size() == 1 && ToLower(part->Isolated.front()->asName) == found->name))
continue;
if (captured.insert(part).second)
before.emplace_back(part, editor_track::capture(*part));
editor_track::isolated(*part, {found->name});
}
}
// the signals placed on the track the trains run on up to them
signal_changes changes;
std::size_t blocks{0};
std::size_t discs{0};
std::size_t swapped{0};
std::size_t renamed{0};
for (auto const &signal : planned)
{
auto const block{signal.kind == station::signal::role::block};
if (signal.match >= 0)
{
auto const &found{standing[signal.match]};
auto const relink{block && false == found.linked.empty() && ToLower(found.linked) != ToLower(signal.linked)};
if (ToLower(found.name) != ToLower(signal.name) || relink)
changes.renamed.push_back({found.instance, signal.name, signal.plate, relink ? signal.linked : std::string{}});
if (ToLower(found.name) != ToLower(signal.name))
++renamed;
// of the aspects of its line
auto const head{std::find_if(heads.begin(), heads.end(), [&](signal_head const &Head) { return Head.file == found.file; })};
if (block && head != heads.end() && head->aspects != 0 && (head->aspects != aspects[signal.line] || (head->lean == "right") != signal.wrong))
if (auto const other{block_template(heads, found.file, aspects[signal.line], signal.wrong)}; false == other.empty() && other != found.file)
{
changes.files.emplace_back(found.instance, other);
++swapped;
}
continue;
}
auto const &line{lines[signal.line]};
// its trains run in, the wrong-track ones of an outbound track too; a wrong-track one stands on the outside, on their left
auto const inbound{line.inbound != signal.wrong};
auto const at{station::point_on(line, signal.distance)};
auto const approach{station::point_on(line, signal.distance + (inbound ? 1.0 : -1.0))};
signal_order order;
order.track = piece_at(approach.track, approach.point);
order.point = at.point;
order.facing = inbound == approach.outward ? -1 : 1;
order.side = signal.wrong ? -order.facing : order.facing;
order.kind = block ? "block" : "warning";
order.file = template_of(signal);
order.name = signal.name;
order.plate = signal.plate;
order.linked = signal.linked;
changes.placed.push_back(std::move(order));
++(block ? blocks : discs);
}
for (auto const &[index, linked] : relinked)
changes.renamed.push_back({standing[index].instance, standing[index].name, std::string{}, linked});
for (std::size_t k = 0; k < standing.size(); ++k)
if (gone[k])
changes.removed.push_back(standing[k].instance);
auto const removed{changes.removed.size()};
// the block signals switched by the sections they guard, the wrong-track one the 7th, or the one guard twice
include_info control;
std::string missing;
auto const controlled{editor_includes::load(kControl, control, missing)};
if (controlled)
{
for (auto const &found : sections)
{
auto const already{std::find_if(controls.begin(), controls.end(), [&](standing_template const &Control) { return false == Control.values.empty() && ToLower(Control.values[0]) == found.name; })};
if (found.guard.empty() && found.wrong_guard.empty())
{
// guarded by station signals only, once its wrong-track signal is gone
if (already != controls.end())
changes.removed.push_back(already->instance);
continue;
}
std::array<std::string, 2> const guards_of{found.guard.empty() ? found.wrong_guard : found.guard, found.wrong_guard.empty() ? found.guard : found.wrong_guard};
if (already != controls.end())
{
auto values{already->values};
values.resize(std::max<std::size_t>(values.size(), 7));
auto differ{false};
for (std::size_t k = 0; k < guards_of.size(); ++k)
if (ToLower(values[5 + k]) != ToLower(guards_of[k]))
{
values[5 + k] = guards_of[k];
differ = true;
}
if (differ)
changes.values.emplace_back(already->instance, std::move(values));
continue;
}
template_item item;
item.file = kControl;
item.location = found.start;
item.described = true;
item.values["name"] = found.name;
item.values["#6"] = guards_of[0];
item.values["#7"] = guards_of[1];
changes.others.push_back(std::move(item));
}
// those of the sections gone from the lines set taken away with them
std::unordered_set<std::string> named;
for (auto const &found : sections)
named.insert(found.name);
for (auto const &standing_control : controls)
{
if (standing_control.values.empty() || named.count(ToLower(standing_control.values[0])) > 0)
continue;
for (std::size_t index = 0; index < lines.size(); ++index)
{
double gap{0.0};
auto const distance{station::distance_on(lines[index], standing_control.location, gap)};
if (processed[index] && automatic[index] != 2 && gap < 4.5 && distance > 0.0 && distance < lines[index].length())
{
changes.removed.push_back(standing_control.instance);
break;
}
}
}
}
if (changes.placed.empty() && changes.renamed.empty() && changes.others.empty() && changes.values.empty() && changes.files.empty() && changes.removed.empty() && before.empty() && created.empty())
{
m_status = STR_C("The lines are set already");
return;
}
std::string error;
auto const touched{false == before.empty() || false == created.empty()};
m_signals.signal_batch(changes, std::move(before), std::move(created), error);
if (false == error.empty())
{
refuse(format(STR_C("The signals couldn't be placed: %s"), error.c_str()) + (touched ? ". " + STR("Ctrl+Z takes back the tracks cut") : std::string{}));
return;
}
m_status = format(STR_P("%zu block signal placed", "%zu block signals placed", blocks), blocks) + ", " + format(STR_P("%zu warning disc", "%zu warning discs", discs), discs) + ", " +
format(STR_P("%zu renamed", "%zu renamed", renamed), renamed) + ", " + format(STR_P("%zu block section", "%zu block sections", sections.size()), sections.size());
if (removed > 0)
m_status += ", " + format(STR_P("%zu signal taken away", "%zu signals taken away", removed), removed);
if (swapped > 0)
m_status += ", " + format(STR_P("%zu given the template of the aspects of its line", "%zu given the templates of the aspects of their lines", swapped), swapped);
m_status += ". " + STR("Ctrl+Z takes it back");
if (false == controlled && std::any_of(sections.begin(), sections.end(), [](section const &Found) { return false == Found.guard.empty(); }))
m_status += "\n" + format(STR_C("%s isn't in the scenery folder: the block signals won't change their lights"), kControl);
}
void srk_tool::survey_signals()
{
m_signal_marks.clear();
m_signal_names.clear();
std::vector<standing_signal> standing;
m_signals_known = m_layout.has_value() && m_signals.standing_signals(standing, false);
for (auto const &signal : standing)
m_signal_names.insert(ToLower(signal.name));
if (false == m_signals_known)
{
m_heads.clear();
m_heads_known = false;
m_lines.clear();
m_line_ways.clear();
m_problems.clear();
m_lines_problem = STR("Looking for the signal templates...");
if (false == m_measured)
measure({});
return;
}
check_heads(standing);
survey_lines(standing);
survey_problems(standing);
auto const stem{stem_of_open()};
std::vector<station::signal> stops;
for (auto const &signal : standing)
{
if (gap_to(*m_layout, signal.position) > 8.0)
continue;
auto const travel{travel_of(signal.yaw)};
auto const at{station::project(*m_layout, signal.position)};
auto const ahead{station::project(*m_layout, signal.position + glm::dvec3{travel.x, 0.0, travel.y} * 5.0)};
auto const unfit{std::any_of(m_heads.begin(), m_heads.end(), [&](head_check const &Head) { return Head.instance == signal.instance && (false == Head.fits || false == Head.problems.empty()); })};
m_signal_marks.push_back({at, ahead.x > at.x, signal_shown(signal.name, stem), signal.position + glm::dvec3{0.0, signal.kind == "shunt" ? 3.0 : 7.0, 0.0}, unfit});
// in the plot on the track it stands by, to its side
auto &mark{m_signal_marks.back()};
mark.drawn = m_plot.at(at);
auto nearest{6.0};
for (std::size_t path = 0; path < m_layout->paths.size(); ++path)
for (std::size_t k = 0; k < m_layout->paths[path].schematic.size(); ++k)
if (auto const &point{m_layout->paths[path].schematic[k]}; glm::distance(point, at) < nearest)
{
nearest = glm::distance(point, at);
mark.drawn = m_plot.paths[path][k];
mark.side = at.y > point.y ? 1.0f : -1.0f;
}
if (signal.kind != "main" && signal.kind != "shunt")
continue;
station::signal stop;
stop.name = signal_shown(signal.name, stem);
stop.point = signal.position;
stop.travel = glm::dvec3{travel.x, 0.0, travel.y};
stops.push_back(std::move(stop));
}
measure(stops);
}
void srk_tool::measure(std::vector<station::signal> const &Signals)
{
m_measured = true;
m_lengths.clear();
std::vector<station::numbered> tracks;
std::unordered_set<TTrack const *> inside;
m_numbered = m_layout.has_value() && station_tracks(tracks, inside);
if (false == m_numbered)
return;
m_lengths = station::track_lengths(*m_layout, tracks, Signals);
std::sort(m_lengths.begin(), m_lengths.end(), [](station::lengths const &A, station::lengths const &B) {
return std::make_pair(std::atoi(A.number.c_str()), A.number) < std::make_pair(std::atoi(B.number.c_str()), B.number);
});
}
double srk_tool::set_speed_of_open() const
{
if (false == m_layout.has_value())
return 0.0;
auto const highest = [](auto const &Tracks) {
auto speed{0.0};
for (auto *track : Tracks)
if (auto const set{track->VelocityGet()}; track->eType == tt_Normal && set <= kFastest)
speed = std::max(speed, set);
return speed;
};
std::vector<TTrack *> through{m_layout->main};
through.insert(through.end(), m_layout->second.begin(), m_layout->second.end());
for (auto const &path : m_layout->paths)
if (path.approach)
through.push_back(path.track);
if (auto const speed{highest(through)}; speed > 0.0)
return speed;
std::vector<TTrack *> all;
for (auto const &path : m_layout->paths)
all.push_back(path.track);
return highest(all);
}
double srk_tool::speed_of_open() const
{
if (auto const speed{set_speed_of_open()}; speed > 0.0)
return speed;
auto const set{m_record >= 0 ? m_records[m_record].braking : 0};
return set <= 0 ? 160.0 : set <= 400 ? 60.0 : set <= 700 ? 100.0 : set <= 1000 ? 140.0 : 160.0;
}
double srk_tool::braking_of_open() const
{
auto const set{m_record >= 0 ? m_records[m_record].braking : 0};
return set > 0 ? static_cast<double>(set) : braking_distance(speed_of_open());
}
void srk_tool::check_heads(std::vector<standing_signal> const &Standing)
{
using role = station::signal::role;
m_heads.clear();
std::vector<signal_head> heads;
m_heads_known = m_layout.has_value() && m_signals.signal_heads(heads, false);
if (false == m_heads_known)
return;
auto const &layout{*m_layout};
auto const stem{stem_of_open()};
auto const line{speed_of_open()};
auto const braking{braking_of_open()};
auto const middle{axis_point(layout, (layout.from + layout.to) * 0.5)};
std::vector<station::post> posts;
std::vector<std::size_t> owners;
for (std::size_t k = 0; k < Standing.size(); ++k)
if (geometry::plan_distance(Standing[k].position, middle) <= kLineLimit)
if (auto const post{post_of(Standing[k])}; post.track != nullptr)
{
posts.push_back(post);
owners.push_back(k);
}
// the main signals of the station, the block signals and the warning discs of the lines in and out of it
std::vector<std::size_t> from;
std::vector<char> own(posts.size(), 0);
for (std::size_t index = 0; index < posts.size(); ++index)
{
if (posts[index].kind == role::entry && gap_to(layout, posts[index].point) <= 8.0)
own[index] = 1;
if (own[index] || posts[index].kind == role::block || posts[index].kind == role::warning)
from.push_back(index);
}
auto const found{station::routes(posts, from, route_reach(braking))};
std::vector<int> routes_of(posts.size(), -1);
for (std::size_t k = 0; k < from.size(); ++k)
routes_of[from[k]] = static_cast<int>(k);
std::vector<char> checked(own);
std::vector<std::size_t> order;
for (std::size_t index = 0; index < posts.size(); ++index)
if (own[index])
order.push_back(index);
for (std::size_t at = 0; at < order.size(); ++at)
for (auto const &route : found[routes_of[order[at]]])
for (auto const index : {route.warning, route.next})
if (index >= 0 && 0 == checked[index] && posts[index].kind != role::entry && routes_of[index] >= 0)
{
checked[index] = 1;
order.push_back(static_cast<std::size_t>(index));
}
for (auto grown{true}; grown;)
{
grown = false;
for (std::size_t index = 0; index < posts.size(); ++index)
{
if (checked[index] || routes_of[index] < 0 || posts[index].kind == role::entry)
continue;
auto const &routes{found[routes_of[index]]};
if (std::none_of(routes.begin(), routes.end(), [&](station::route const &Route) { return Route.next >= 0 && checked[Route.next]; }))
continue;
checked[index] = 1;
order.push_back(index);
grown = true;
}
}
std::unordered_map<std::string, std::size_t> by_file;
for (std::size_t index = 0; index < heads.size(); ++index)
by_file.emplace(heads[index].file, index);
// the semaphore described with its arms a route leads to, none for a route to another signal or to none
auto const semaphore_at = [&heads, &by_file, &Standing, &owners](station::route const &Route) {
auto const ahead{Route.next >= 0 ? by_file.find(Standing[owners[Route.next]].file) : by_file.end()};
return ahead != by_file.end() && heads[ahead->second].arms > 0 ? &heads[ahead->second] : nullptr;
};
auto const triggers{shp_triggers()};
// the braking distance of the line out a signal stands along, beyond its entry signal, as Set the line signals goes by it; the one of
// the station elsewhere
std::vector<station::line> lines;
{
std::vector<station::signal> entries;
std::vector<std::size_t> line_owners;
std::string problem;
if (false == lines_of_open(Standing, lines, entries, line_owners, problem))
lines.clear();
}
auto const braking_on = [&](glm::dvec3 const &Position) {
auto nearest{4.5};
auto found{braking};
for (auto const &line : lines)
{
double gap{0.0};
auto const distance{station::distance_on(line, Position, gap)};
if (gap <= nearest && distance >= 0.0 && distance <= line.length())
{
nearest = gap;
found = line_braking(line);
}
}
return found;
};
for (auto const index : order)
{
auto const &signal{Standing[owners[index]]};
auto const &post{posts[index]};
head_check check;
check.instance = signal.instance;
check.name = signal_shown(signal.name, stem);
check.kind = signal.kind;
check.position = signal.position;
check.travel = travel_of(signal.yaw);
check.file = signal.file;
check.station = own[index] != 0;
check.routes = found[routes_of[index]];
for (auto const &route : check.routes)
check.nexts.push_back(route.next >= 0 ? signal_shown(Standing[owners[route.next]].name, stem) : std::string{});
auto const known{by_file.find(signal.file)};
auto const *template_of{known != by_file.end() ? &heads[known->second] : nullptr};
if (template_of != nullptr)
{
check.lamps = template_of->lamps;
check.arms = template_of->arms;
check.aspect_names = template_of->aspect_names;
check.own = template_of->speeds;
}
glm::dvec3 const travel{check.travel.x, 0.0, check.travel.y};
if (post.kind != role::entry)
check.shp = kShpBefore;
else if (own[index])
{
auto const along{station::project(layout, signal.position).x};
auto const ahead{station::project(layout, signal.position + travel * 10.0).x};
if ((along < layout.from && ahead > along) || (along > layout.to && ahead < along))
check.shp = kShpBefore;
else if (std::any_of(check.routes.begin(), check.routes.end(), [](station::route const &Route) { return Route.next >= 0 && Route.warning < 0; }))
check.shp = 0.0;
}
if (check.shp >= 0.0)
{
auto const way{station::approach(*post.track, post.point, post.facing, check.shp + kShpWindow)};
check.shp_found = shp_before(way, signal.position, travel, triggers, check.shp);
check.shp_short = way.empty() || way.back().distance < check.shp - kShpTolerance;
}
// a signal of a line goes by the braking distance of its line, as Set the line signals placed it, the ones of the station by its
// own
auto const local{post.kind == role::warning || post.kind == role::block ? braking_on(signal.position) : braking};
if (post.kind == role::warning)
{
for (std::size_t k = 0; k < check.routes.size(); ++k)
{
auto const &route{check.routes[k]};
if (route.next < 0)
check.problems.push_back(format(STR_C("No main signal within %.0f m ahead of it to tell of"), route.length));
else if (route.length < local - 1.0)
check.problems.push_back(format(STR_C("It stands %.0f m before %s, less than the braking distance of %.0f m: the trains don't stop by the signal in time"), route.length, check.nexts[k].c_str(), local));
}
// a shaped disc before a semaphore described with its arms: the events it repeats tell apart all the semaphore shows. One not
// described so may as well, it is offered the one described as a hint and the fitting leaves it be. A disc with lights isn't
// checked, nor one whose template isn't among the scanned, its mount not known
auto const described{template_of != nullptr && false == template_of->repeats.empty()};
if (auto const mount{m_signals.signal_mount("warning", signal.file)}; false == mount.empty() && (described || template_of == nullptr || template_of->lamps.empty()))
{
std::vector<signal_head const *> mains;
std::ranges::transform(check.routes, std::back_inserter(mains), semaphore_at);
auto disc{check_disc(heads, by_file, mains, template_of, signal.file, mount)};
check.told = disc.told;
check.unsaid = disc.unsaid;
check.fits = disc.fits;
check.fit = std::move(disc.fit);
}
m_heads.push_back(std::move(check));
continue;
}
auto const main{post.kind == role::entry};
auto const need{need_of(check.routes, main, line, local)};
check.speeds = need.speeds;
check.informs = need.informs;
check.white = need.white;
check.shortened = need.shortened;
check.indicator = need.indicator;
if (false == main)
for (std::size_t k = 0; k < check.routes.size(); ++k)
{
auto const &route{check.routes[k]};
if (route.next < 0 || route.warning >= 0)
continue;
if (template_of != nullptr && template_of->aspects == 4)
{
if (route.length < local * 0.5 - 1.0)
check.problems.push_back(format(STR_C("The block section to %s is %.0f m long, shorter than half the braking distance of %.0f m, of the 4-aspect block"), check.nexts[k].c_str(), route.length, local));
}
else if (route.length < local - 1.0)
check.problems.push_back(format(STR_C("The block section to %s is %.0f m long, shorter than the braking distance of %.0f m, Ie-4 § 8 ust. 1"), check.nexts[k].c_str(), route.length, local));
}
if (template_of != nullptr)
{
check.fits = shows(*template_of, need);
auto const best{best_head(heads, signal.kind, template_of->mount, template_of->name, template_of->aspects, need, template_of->arms > 0)};
if (best >= 0)
{
check.fit = heads[best].file;
check.more = check.fits && surplus(heads[best], need) < surplus(*template_of, need);
}
}
m_heads.push_back(std::move(check));
}
std::stable_sort(m_heads.begin(), m_heads.end(), [&](head_check const &A, head_check const &B) {
if (A.station != B.station)
return A.station;
if (A.station)
return station::project(layout, A.position).x < station::project(layout, B.position).x;
return geometry::plan_distance(A.position, middle) < geometry::plan_distance(B.position, middle);
});
}
void srk_tool::fit_heads()
{
begin_status();
signal_changes changes;
// a semaphore described having what it needs keeps its arms, for the events written by hand to the aspects of a second one
for (auto const &head : m_heads)
if (false == head.fit.empty() && head.fit != head.file && (false == head.fits || (head.more && head.arms == 0)))
changes.files.emplace_back(head.instance, head.fit);
if (changes.files.empty())
{
m_status = std::ranges::any_of(m_heads, [](head_check const &Head) { return false == Head.fits; }) ? STR_C("No template has what the signals marked need") : STR_C("The signals have what they need already");
return;
}
std::string error;
m_signals.signal_batch(changes, {}, {}, error);
if (false == error.empty())
{
refuse(format(STR_C("The signals couldn't be changed: %s"), error.c_str()));
return;
}
std::vector<standing_signal> standing;
m_signals.standing_signals(standing, true);
std::size_t changed{0};
for (auto const &head : m_heads)
changed += static_cast<std::size_t>(std::count_if(standing.begin(), standing.end(), [&](standing_signal const &Signal) { return Signal.instance == head.instance && Signal.file != head.file; }));
if (changed == 0)
m_status = STR_C("The signals have what they need already");
else
m_status = format(STR_P("%zu signal got what it needs, Ctrl+Z takes it back", "%zu signals got what they need, Ctrl+Z takes it back", changed), changed);
}
void srk_tool::set_shp()
{
begin_status();
if (false == m_layout.has_value())
return;
include_info resonator;
std::string unreadable;
if (false == editor_includes::load(kResonator, resonator, unreadable))
{
refuse(format(STR_C("%s isn't in the scenery folder: the SHP resonators can't be placed"), kResonator));
return;
}
std::vector<standing_signal> standing;
m_signals.standing_signals(standing, true);
check_heads(standing);
std::unordered_set<std::string> taken;
for (auto *track : simulation::Paths.sequence())
if (track != nullptr && false == track->m_editorremoved)
for (int list = 0; list < 6; ++list)
for (auto const &event : editor_track::events(*track, list))
taken.insert(ToLower(event.first));
struct placing
{
std::string signal; // shown
std::string name; // of the resonator, its event is <name>_shp
TTrack *track{nullptr}; // the trains run into its event on, where a joint of the tracks lies
TTrack *cut{nullptr}; // the track cut at the point, else
int facing{1}; // the trains run on the track, 1: towards the end of its path
glm::dvec3 point{0.0};
glm::dvec3 way{0.0, 0.0, 1.0};
glm::dvec3 inside{0.0}; // of the track the trains run into, a metre on from the point
};
std::vector<placing> places;
std::vector<std::string> problems;
for (auto const &head : m_heads)
{
if (head.shp_of() != shp_state::missing && head.shp_of() != shp_state::beyond)
continue;
if (head.shp_of() == shp_state::beyond)
{
problems.push_back(format(STR_C("%s: the tracks before it end short of %.0f m"), head.name.c_str(), head.shp));
continue;
}
auto const found{std::find_if(standing.begin(), standing.end(), [&](standing_signal const &Signal) { return Signal.instance == head.instance; })};
if (found == standing.end())
continue;
auto const post{post_of(*found)};
if (post.track == nullptr)
{
problems.push_back(format(STR_C("%s stands by no track"), head.name.c_str()));
continue;
}
auto const way{station::approach(*post.track, post.point, post.facing, head.shp + kShpTolerance + 1.0)};
if (way.empty() || way.back().distance < head.shp - kShpTolerance)
{
problems.push_back(format(STR_C("%s: the tracks before it end short of %.0f m"), head.name.c_str(), head.shp));
continue;
}
auto joint{false};
auto const best{resonator_at(way, head.shp, joint)};
if (best < 0)
{
problems.push_back(format(STR_C("%s: no plain track within %.0f m of the place of its SHP resonator"), head.name.c_str(), kShpTolerance));
continue;
}
auto const &at{way[best]};
std::string reason;
if (false == scene::Layers.editable(at.track, &reason) || (false == joint && false == editor_track::can_edit_geometry(*at.track, reason)))
{
problems.push_back(format(STR_C("%s can't be changed: %s"), name_of(*at.track).c_str(), reason.c_str()));
continue;
}
if (false == at.track->Dynamics.empty())
{
problems.push_back(format(STR_C("%s: vehicles stand on %s"), head.name.c_str(), name_of(*at.track).c_str()));
continue;
}
placing entry;
auto name{found->name + "_rez"};
for (int number = 2; taken.count(ToLower(name) + "_shp") > 0 && number < 100; ++number)
name = found->name + "_rez" + std::to_string(number);
taken.insert(ToLower(name) + "_shp");
entry.signal = head.name;
entry.name = name;
entry.facing = at.facing;
entry.point = at.point;
entry.way = at.way;
if (joint)
entry.track = at.track;
else
{
entry.cut = at.track;
entry.inside = best > 0 ? way[best - 1].point : at.point + at.way;
}
places.push_back(std::move(entry));
}
if (places.empty())
{
m_status = problems.empty() ? STR_C("The signals have their SHP resonators already") : problems.front();
return;
}
std::vector<std::pair<TTrack *, editor_track::state>> before;
std::vector<TTrack *> created;
std::unordered_set<TTrack const *> captured;
std::unordered_map<TTrack const *, std::vector<TTrack *>> pieces; // of each track cut, itself and the pieces cut off it
auto const piece_at = [&](TTrack *Track, glm::dvec3 const &Point) {
auto found{pieces.find(Track)};
if (found == pieces.end())
return Track;
TTrack *nearest{Track};
auto gap{std::numeric_limits<double>::max()};
for (auto *piece : found->second)
if (auto const distance{glm::distance(editor_track::point_at(*piece, editor_track::nearest_parameter(*piece, Point)), Point)}; distance < gap)
{
gap = distance;
nearest = piece;
}
return nearest;
};
std::size_t cuts{0};
for (auto const &entry : places)
{
if (entry.cut == nullptr)
continue;
auto *track{piece_at(entry.cut, entry.point)};
if (end_gap(*track, entry.point) <= 0.3)
continue;
if (captured.insert(track).second)
before.emplace_back(track, editor_track::capture(*track));
if (auto *piece{editor_track::split_path(*track, editor_track::nearest_parameter(*track, entry.point))})
{
created.push_back(piece);
captured.insert(piece);
auto &list{pieces[entry.cut]};
if (list.empty())
list.push_back(entry.cut);
list.push_back(piece);
++cuts;
}
}
signal_changes changes;
for (auto const &entry : places)
{
auto *track{entry.track != nullptr ? piece_at(entry.track, entry.point) : piece_at(entry.cut, entry.inside)};
// the trains run into the track at the point: at the start of its path running towards its end
if (glm::distance(track->m_paths.front().points[entry.facing > 0 ? segment_data::point::start : segment_data::point::end], entry.point) > 1.0)
{
problems.push_back(format(STR_C("%s: the track couldn't be cut at the place of its SHP resonator"), entry.signal.c_str()));
continue;
}
if (captured.insert(track).second)
before.emplace_back(track, editor_track::capture(*track));
editor_track::events(*track, entry.facing > 0 ? 2 : 1).emplace_back(ToLower(entry.name) + "_shp", nullptr);
std::string missing;
editor_track::bind_events(*track, missing);
track->mark_dirty();
template_item item;
item.file = kResonator;
item.location = entry.point - glm::dvec3{0.0, kResonatorDrop, 0.0};
auto const yaw{geometry::heading_of({entry.way.x, entry.way.z}) + 180.0};
item.yaw = yaw >= 360.0 ? yaw - 360.0 : yaw;
item.values["name"] = entry.name;
changes.others.push_back(std::move(item));
}
std::string error;
auto const placed{changes.others.size()};
m_signals.signal_batch(changes, std::move(before), std::move(created), error);
if (false == error.empty())
{
refuse(format(STR_C("The SHP resonators couldn't be placed: %s. Ctrl+Z takes back the tracks cut"), error.c_str()));
return;
}
m_status = format(STR_P("%zu SHP resonator placed", "%zu SHP resonators placed", placed), placed) + ", " + format(STR_P("%zu track cut", "%zu tracks cut", cuts), cuts) + ". " + STR("Ctrl+Z takes it back, the resonators work after the scenery is saved and opened again");
for (auto const &problem : problems)
m_status += "\n" + problem;
}
void srk_tool::survey()
{
m_circuit_of.assign(m_layout.has_value() ? m_layout->paths.size() : 0, -1);
m_circuits.clear();
m_ticks.clear();
m_ticks_drawn.clear();
m_lengths.clear();
m_measured = false;
m_numbered = false;
if (false == m_layout.has_value())
return;
auto const &layout{*m_layout};
auto const stem{stem_of_open()};
std::vector<double> weights;
for (std::size_t index = 0; index < layout.paths.size(); ++index)
{
auto const &path{layout.paths[index]};
if (path.track->Isolated.empty())
continue;
// of the lines leading out only the stretches up to the joints of the station
auto const &name{path.track->Isolated.front()->asName};
if (path.approach && (stem.empty() || name.compare(0, stem.size(), stem) != 0))
continue;
auto found{std::find_if(m_circuits.begin(), m_circuits.end(), [&](circuit_mark const &Mark) { return Mark.text == name; })};
if (found == m_circuits.end())
{
found = m_circuits.insert(m_circuits.end(), {glm::dvec2{0.0}, glm::dvec3{0.0}, name, circuit_colour(name)});
found->labelled = stem.empty() || name.compare(0, stem.size() + 2, stem + "iz") != 0;
weights.push_back(0.0);
}
auto const circuit{static_cast<std::size_t>(found - m_circuits.begin())};
m_circuit_of[index] = static_cast<int>(circuit);
for (auto const &point : path.schematic)
{
found->at += point;
weights[circuit] += 1.0;
}
found->length += path.length;
}
for (std::size_t index = 0; index < m_circuits.size(); ++index)
{
auto &mark{m_circuits[index]};
mark.at /= std::max(1.0, weights[index]);
// on its track, nearest the middle of its points
auto nearest{std::numeric_limits<double>::max()};
glm::dvec2 on{mark.at};
for (std::size_t path = 0; path < layout.paths.size(); ++path)
if (m_circuit_of[path] == static_cast<int>(index))
for (std::size_t k = 0; k < layout.paths[path].schematic.size(); ++k)
if (auto const distance{glm::distance(layout.paths[path].schematic[k], mark.at)}; distance < nearest)
{
nearest = distance;
on = layout.paths[path].schematic[k];
mark.world = layout.paths[path].points[k];
mark.drawn = m_plot.paths[path][k];
}
mark.at = on;
auto const entry{entry_circuit(mark.text, stem)};
// bpd_it3 shown as It3
if (false == stem.empty() && mark.text.compare(0, stem.size(), stem) == 0)
mark.text.erase(0, stem.size());
if (false == mark.text.empty())
mark.text.front() = static_cast<char>(std::toupper(static_cast<unsigned char>(mark.text.front())));
// bpd_ita, before the entry signal A, as ItA
if (entry && mark.text.size() > 2)
std::transform(mark.text.begin() + 2, mark.text.end(), mark.text.begin() + 2, [](char const Letter) { return static_cast<char>(std::toupper(static_cast<unsigned char>(Letter))); });
}
// the joints: the ends where paths of different circuits meet
struct end
{
glm::dvec3 point;
glm::dvec3 way;
int circuit;
glm::dvec2 drawn;
};
std::vector<end> ends;
for (std::size_t index = 0; index < layout.paths.size(); ++index)
{
auto const &points{layout.paths[index].points};
if (points.size() < 2)
continue;
auto const circuit{m_circuit_of[index]};
ends.push_back({points.front(), points[1] - points.front(), circuit, m_plot.paths[index].front()});
ends.push_back({points.back(), points.back() - points[points.size() - 2], circuit, m_plot.paths[index].back()});
}
m_joints.clear();
for (std::size_t i = 0; i < ends.size(); ++i)
for (std::size_t j = i + 1; j < ends.size(); ++j)
if (ends[i].circuit != ends[j].circuit && (ends[i].circuit >= 0 || ends[j].circuit >= 0) && glm::distance(ends[i].point, ends[j].point) < 0.05 &&
std::none_of(m_joints.begin(), m_joints.end(), [&](joint_mark const &Joint) { return glm::distance(Joint.at, ends[i].point) < 0.05; }))
{
m_ticks.push_back(station::project(layout, ends[i].point));
m_ticks_drawn.push_back(ends[i].drawn);
glm::dvec2 const way{glm::normalize(glm::dvec2{ends[i].way.x, ends[i].way.z} + glm::dvec2{1e-12, 0.0})};
m_joints.push_back({ends[i].point, glm::dvec3{-way.y, 0.0, way.x}});
}
survey_signals();
}
void srk_tool::fit_view(float const Width, float const Height)
{
auto const &layout{*m_layout};
auto &view{m_view_state};
// the switches and the signals out on the lines
auto from{layout.from};
auto to{layout.to};
for (auto const &mark : m_signal_marks)
{
from = std::min(from, mark.at.x);
to = std::max(to, mark.at.x);
}
if (m_fit_lines)
for (auto const &row : m_lines)
{
from = std::min(from, row.chainage + row.outward * row.length);
to = std::max(to, row.chainage + row.outward * row.length);
}
from = m_plot.x(from);
to = m_plot.x(to);
auto const span{std::max(50.0, to - from)};
view.from = from - span * 0.04 - 30.0;
view.to = to + span * 0.04 + 30.0;
auto low{std::numeric_limits<double>::max()};
auto high{std::numeric_limits<double>::lowest()};
for (std::size_t index = 0; index < layout.paths.size() && index < m_plot.paths.size(); ++index)
if (false == layout.paths[index].approach)
for (auto const &point : m_plot.paths[index])
{
low = std::min(low, point.y);
high = std::max(high, point.y);
}
if (low > high)
low = high = 0.0;
view.centre = (low + high) * 0.5;
auto const across{(view.to - view.from) / std::max(1.0f, Width)};
auto const vertical{(high - low + 2.0 * station::row_height) / std::max(1.0f, Height * 0.85f)};
view.exaggeration = static_cast<float>(std::clamp(across / vertical, 1.0, 500.0));
}
void srk_tool::render_canvas(float const Height)
{
auto const &layout{*m_layout};
auto &view{m_view_state};
auto const &io{ImGui::GetIO()};
ImVec2 const size{std::max(200.0f, ImGui::GetContentRegionAvail().x), std::max(80.0f, Height)};
ImVec2 const corner{ImGui::GetCursorScreenPos()};
ImGui::InvisibleButton("##srkcanvas", size, ImGuiButtonFlags_MouseButtonLeft | ImGuiButtonFlags_MouseButtonMiddle);
bool const hovered{ImGui::IsItemHovered()};
if (view.exaggeration <= 0.0f)
fit_view(size.x, size.y);
// the wheel zooms about the mouse, with Ctrl it exaggerates the offsets; a drag moves the plot
if (hovered && io.MouseWheel != 0.0f)
{
if (io.KeyCtrl)
view.exaggeration = std::clamp(view.exaggeration * std::pow(1.2f, io.MouseWheel), 1.0f, 500.0f);
else
{
auto const at{view.from + (io.MousePos.x - corner.x) / size.x * (view.to - view.from)};
auto const factor{std::pow(0.8, static_cast<double>(io.MouseWheel))};
view.from = at - (at - view.from) * factor;
view.to = at + (view.to - at) * factor;
}
}
auto const across{(view.to - view.from) / size.x};
auto const vertical{across / view.exaggeration};
if (ImGui::IsItemActive() && (ImGui::IsMouseDragging(ImGuiMouseButton_Left, kDragPixels) || ImGui::IsMouseDragging(ImGuiMouseButton_Middle, kDragPixels)))
{
m_dragging = true;
view.from -= io.MouseDelta.x * across;
view.to -= io.MouseDelta.x * across;
view.centre += io.MouseDelta.y * vertical;
}
// the plot draws the generalized schematic: its x shortens the chainage between the switches, its height puts the tracks on rows
auto const plot_x = [&](double const X) { return corner.x + static_cast<float>((X - view.from) / across); };
auto const plot_y = [&](double const Height) { return corner.y + size.y * 0.5f - static_cast<float>((Height - view.centre) / vertical); };
auto const x_of = [&](double const Chainage) { return plot_x(m_plot.x(Chainage)); };
auto const screen_of = [&](glm::dvec2 const &Point) { return ImVec2(plot_x(Point.x), plot_y(Point.y)); };
auto const chainage_at = [&](float const Mouse) { return m_plot.chainage(view.from + (Mouse - corner.x) * across); };
auto const drawn_of = [&](std::size_t const Index) -> std::vector<glm::dvec2> const & {
static std::vector<glm::dvec2> const none;
return Index < m_plot.paths.size() ? m_plot.paths[Index] : none;
};
// the path under the mouse
if (hovered && false == m_dragging)
{
m_hover = -1;
auto nearest{7.0f * 7.0f};
auto const &mouse{io.MousePos};
for (int index = 0; index < static_cast<int>(layout.paths.size()); ++index)
{
auto const &points{drawn_of(index)};
for (std::size_t i = 1; i < points.size(); ++i)
{
auto const a{screen_of(points[i - 1])};
auto const b{screen_of(points[i])};
auto const dx{b.x - a.x};
auto const dy{b.y - a.y};
auto const length2{dx * dx + dy * dy};
auto const t{length2 > 0.0f ? std::clamp(((mouse.x - a.x) * dx + (mouse.y - a.y) * dy) / length2, 0.0f, 1.0f) : 0.0f};
auto const ex{a.x + t * dx - mouse.x};
auto const ey{a.y + t * dy - mouse.y};
if (ex * ex + ey * ey < nearest)
{
nearest = ex * ex + ey * ey;
m_hover = index;
}
}
}
}
else if (false == hovered && false == ImGui::IsItemActive())
m_hover = -1;
// a line out of the station under the mouse, how far out along it
auto const line_x = [&](line_row const &Row, double const Distance) { return x_of(Row.chainage + Row.outward * Distance); };
int line_hover{-1};
double line_at{0.0};
if (hovered && false == m_dragging && m_hover < 0)
for (std::size_t index = 0; index < m_lines.size() && index < m_line_ways.size() && line_hover < 0; ++index)
{
auto const &row{m_lines[index]};
auto const distance{(chainage_at(io.MousePos.x) - row.chainage) * row.outward};
if (std::abs(io.MousePos.y - plot_y(m_plot.at({row.chainage, row.offset}).y)) < 6.0f && distance >= 0.0 && distance <= row.length)
{
line_hover = static_cast<int>(index);
line_at = distance;
}
}
m_length_canvas = m_hover >= 0 && false == m_dragging ? length_of(layout.paths[m_hover].track) : -1;
if (ImGui::IsItemDeactivated())
{
if (false == m_dragging && m_hover >= 0)
{
auto const &path{layout.paths[m_hover]};
m_selection.set_current_node(path.track);
m_picked = path.track;
m_view.focus_track(*path.track, path.index, path.points[path.points.size() / 2]);
}
else if (false == m_dragging && line_hover >= 0)
{
auto const on{station::point_on(m_line_ways[line_hover], line_at)};
auto const out{m_lines[line_hover].inbound ? -1.0 : 1.0};
m_view.fly_to(on.point + glm::dvec3{0.0, 4.0, 0.0}, glm::normalize(glm::dvec3{on.way.x * out, -0.3, on.way.z * out}), 30.0);
}
m_dragging = false;
}
auto *draw{ImGui::GetWindowDrawList()};
ImVec2 const corner_end{corner.x + size.x, corner.y + size.y};
draw->AddRectFilled(corner, corner_end, IM_COL32(22, 24, 28, 255));
draw->PushClipRect(corner, corner_end, true);
// the km, or the chainage, along the top
{
auto const first{chainage_at(corner.x)};
auto const last{chainage_at(corner_end.x)};
auto const metres{(last - first) / size.x * 90.0};
double step{10.0};
for (auto const candidate : {10.0, 20.0, 50.0, 100.0, 200.0, 500.0, 1000.0, 2000.0, 5000.0})
if ((step = candidate) >= metres)
break;
// the km of the station where it has them, else the chainage; the shortened stretches skip the marks too near
double km_from{0.0};
double km_to{0.0};
auto const kilometrage{km_of_open(first, km_from) && km_of_open(last, km_to) && std::abs(km_to - km_from) > 1e-6};
auto const low{kilometrage ? std::min(km_from, km_to) * 1000.0 : first};
auto const high{kilometrage ? std::max(km_from, km_to) * 1000.0 : last};
auto shown{std::numeric_limits<float>::lowest()};
auto const lowest_mark{std::ceil(low / step) * step};
for (int k = 0; lowest_mark + k * step <= high; ++k)
{
auto const mark{lowest_mark + k * step};
auto const x{x_of(kilometrage ? first + (mark / 1000.0 - km_from) / (km_to - km_from) * (last - first) : mark)};
auto const label{kilometrage ? format("km %.3f", mark / 1000.0) : format("%.0f m", mark)};
if (std::abs(x - shown) < ImGui::CalcTextSize(label.c_str()).x + 12.0f)
continue;
shown = x;
draw->AddLine(ImVec2(x, corner.y), ImVec2(x, corner_end.y), IM_COL32(255, 255, 255, 16));
draw->AddText(ImVec2(x + 3.0f, corner.y + 2.0f), IM_COL32(150, 155, 165, 255), label.c_str());
}
}
auto const *selected{m_selection.selected_track()};
auto const draw_path = [&](std::size_t const Index, ImU32 const Colour, float const Width) {
auto const &points{drawn_of(Index)};
for (std::size_t i = 1; i < points.size(); ++i)
draw->AddLine(screen_of(points[i - 1]), screen_of(points[i]), Colour, Width);
};
for (std::size_t index = 0; index < layout.paths.size(); ++index)
if (layout.paths[index].approach)
draw_path(index, kApproach, 2.0f);
for (std::size_t index = 0; index < layout.paths.size(); ++index)
if (auto const &path{layout.paths[index]}; false == path.approach || m_circuit_of[index] >= 0)
draw_path(index, m_circuit_of[index] >= 0 ? m_circuits[m_circuit_of[index]].colour : is_switch(*path.track) ? kSwitch : kPlain, 2.5f);
for (auto const &tick : m_ticks_drawn)
{
auto const at{screen_of(tick)};
draw->AddLine(ImVec2(at.x, at.y - 5.0f), ImVec2(at.x, at.y + 5.0f), IM_COL32(255, 255, 255, 220), 2.0f);
}
// the lines out straightened beyond the entry signals: the block sections in the colours of their names, the joints between
// them, the block signals each a flag pointing the way of its trains
for (std::size_t index = 0; index < m_lines.size(); ++index)
{
auto const &row{m_lines[index]};
auto const y{plot_y(m_plot.at({row.chainage, row.offset}).y)};
draw->AddLine(ImVec2(line_x(row, 0.0), y), ImVec2(line_x(row, row.length), y), kApproach, 2.0f);
for (std::size_t k = 0; k < row.sections.size(); ++k)
{
auto const &run{row.sections[k]};
auto const lit{static_cast<int>(index) == line_hover && line_at >= run.from && line_at <= run.to};
draw->AddLine(ImVec2(line_x(row, std::max(0.0, run.from)), y), ImVec2(line_x(row, run.to), y), lit ? kHovered : circuit_colour(run.name), lit ? 4.0f : 2.5f);
for (auto const end : {run.from, run.to})
if (end > 1.0 && end < row.length - 1.0)
draw->AddLine(ImVec2(line_x(row, end), y - 5.0f), ImVec2(line_x(row, end), y + 5.0f), kJoint, 2.0f);
}
for (auto const &post : row.posts)
{
auto const x{line_x(row, post.distance)};
auto const way{static_cast<float>(row.outward * (row.inbound ? -1.0 : 1.0) * (post.wrong ? -1.0 : 1.0))};
draw->AddTriangleFilled(ImVec2(x - 4.0f * way, y - 4.0f), ImVec2(x - 4.0f * way, y + 4.0f), ImVec2(x + 4.0f * way, y), kSignal);
}
}
for (std::size_t index = 0; index < layout.paths.size(); ++index)
if (layout.paths[index].track == selected)
draw_path(index, overlay_color::selected, 4.0f);
if (m_hover >= 0)
draw_path(static_cast<std::size_t>(m_hover), kHovered, 4.0f);
// the useful lengths of the station track shown: of the trains to the right over it, to the left under it, an arrowhead where
// they stop
std::vector<std::pair<std::string, ImVec2>> useful;
if (m_length_shown >= 0 && m_length_shown < static_cast<int>(m_lengths.size()))
{
auto const &track{m_lengths[m_length_shown]};
for (int way = 0; way < 2; ++way)
{
auto const &part{track.ways[way]};
if (part.length <= 0.0)
continue;
auto const shift{way == 0 ? -7.0f : 7.0f};
std::vector<ImVec2> line;
for (auto const &point : stretch_of(track, part.rear.along, part.head.along))
{
auto at{screen_of(m_plot.at(station::project(layout, point)))};
at.y += shift;
line.push_back(at);
}
draw->AddPolyline(line.data(), static_cast<int>(line.size()), kUseful, ImDrawFlags_None, 2.0f);
auto const &rear{line.front()};
auto const &head{line.back()};
draw->AddLine(ImVec2(rear.x, rear.y - 4.0f), ImVec2(rear.x, rear.y + 4.0f), kUseful, 2.0f);
auto const way_x{head.x >= line[line.size() > 1 ? line.size() - 2 : 0].x ? 1.0f : -1.0f};
draw->AddTriangleFilled(ImVec2(head.x - 7.0f * way_x, head.y - 4.5f), ImVec2(head.x - 7.0f * way_x, head.y + 4.5f), ImVec2(head.x + 1.0f * way_x, head.y), kUseful);
auto const &middle{line[line.size() / 2]};
useful.emplace_back(format("%.0f m", part.length), ImVec2(middle.x, way == 0 ? middle.y - ImGui::GetTextLineHeight() - 3.0f : middle.y + 3.0f));
}
}
// the labels, none over another: the switches first, a dot at the start and the name over or under it in turn, the number
// alone once named after the station; then the station tracks under or over them, the longest first
std::vector<ImVec4> placed;
auto const label = [&](std::string const &Text, ImU32 const Colour, std::initializer_list<ImVec2> Places) {
auto const extent{ImGui::CalcTextSize(Text.c_str())};
for (auto const &place : Places)
{
ImVec4 const box{place.x - extent.x * 0.5f - 2.0f, place.y - 1.0f, place.x + extent.x * 0.5f + 2.0f, place.y + extent.y + 1.0f};
if (std::any_of(placed.begin(), placed.end(), [&](ImVec4 const &Other) { return box.x < Other.z && Other.x < box.z && box.y < Other.w && Other.y < box.w; }))
continue;
placed.push_back(box);
draw->AddRectFilled(ImVec2(box.x, box.y), ImVec2(box.z, box.w), IM_COL32(22, 24, 28, 200), 2.0f);
draw->AddText(ImVec2(place.x - extent.x * 0.5f, place.y), Colour, Text.c_str());
return;
}
};
for (auto const &[text, at] : useful)
label(text, kUseful, {at});
auto const stem{stem_of_open()};
auto const height{ImGui::GetTextLineHeight()};
for (std::size_t index = 0; index < layout.switches.size(); ++index)
{
auto const *track{layout.switches[index]};
auto at{screen_of(m_plot.at(station::project(layout, track->m_paths.front().points[segment_data::point::start])))};
for (std::size_t path = 0; path < layout.paths.size(); ++path)
if (layout.paths[path].track == track && layout.paths[path].index == 0 && false == drawn_of(path).empty())
at = screen_of(drawn_of(path).front());
draw->AddCircleFilled(at, 3.5f, kSwitch);
auto text{track->name()};
if (false == stem.empty() && text.size() > stem.size() && text.compare(0, stem.size(), stem) == 0)
text.erase(0, stem.size());
ImVec2 const over{at.x, at.y - height - 6.0f};
ImVec2 const under{at.x, at.y + 6.0f};
if (index % 2 == 0)
label(text, kSwitch, {over, under});
else
label(text, kSwitch, {under, over});
}
// the signals: a flag pointing the way of the trains they face
for (auto const &mark : m_signal_marks)
{
auto at{screen_of(mark.drawn)};
at.y -= mark.side * 6.0f;
auto const way{mark.ahead ? 1.0f : -1.0f};
auto const colour{mark.unfit ? kUnfit : kSignal};
draw->AddTriangleFilled(ImVec2(at.x - 4.0f * way, at.y - 4.0f), ImVec2(at.x - 4.0f * way, at.y + 4.0f), ImVec2(at.x + 4.0f * way, at.y), colour);
label(mark.unfit ? mark.text + " !" : mark.text, colour, {ImVec2(at.x, at.y - height - 5.0f), ImVec2(at.x, at.y + 5.0f)});
}
// the block signals of the lines with their km, the lengths of the block sections, on the outside of the line: over the upper
// track of a double-track one, under the lower
for (auto const &row : m_lines)
{
auto const y{plot_y(m_plot.at({row.chainage, row.offset}).y)};
auto const up{row.partner < 0 || row.partner >= static_cast<int>(m_lines.size()) || row.offset >= m_lines[row.partner].offset};
auto const outside = [&](float const Tall, float const Level) { return up ? y - 5.0f - (Tall + 3.0f) * Level + 3.0f : y + 5.0f + (Tall + 3.0f) * (Level - 1.0f); };
auto const tall{height * (row.km_known ? 2.0f : 1.0f)};
for (auto const wrong_track : {false, true})
for (auto const &post : row.posts)
if (post.wrong == wrong_track)
{
auto const x{line_x(row, post.distance)};
label(row.km_known ? post.name + "\n" + format("%.3f", post.km) : post.name, kSignal, {ImVec2(x, outside(tall, 1.0f)), ImVec2(x, outside(tall, 2.0f))});
}
for (auto const &run : row.sections)
{
auto const x{line_x(row, (std::max(0.0, run.from) + run.to) * 0.5)};
label(format("%.2f km", (run.to - std::max(0.0, run.from)) / 1000.0), circuit_colour(run.name), {ImVec2(x, outside(height, 1.0f)), ImVec2(x, outside(height, 2.0f))});
}
}
std::vector<std::size_t> order;
for (std::size_t index = 0; index < m_circuits.size(); ++index)
if (m_circuits[index].labelled)
order.push_back(index);
std::sort(order.begin(), order.end(), [&](std::size_t A, std::size_t B) { return m_circuits[A].length > m_circuits[B].length; });
for (auto const index : order)
{
auto const &mark{m_circuits[index]};
auto const at{screen_of(mark.drawn)};
label(mark.text, mark.colour, {ImVec2(at.x, at.y + 4.0f), ImVec2(at.x, at.y - height - 4.0f)});
}
draw->PopClipRect();
if (hovered && m_hover >= 0 && false == m_dragging)
{
auto const &path{layout.paths[m_hover]};
auto const along{chainage_at(io.MousePos.x)};
ImGui::BeginTooltip();
ImGui::TextUnformatted(path.track->name().empty() ? STR_C("(no name)") : path.track->name().c_str());
ImGui::TextDisabled("%s, %.1f m", is_switch(*path.track) ? STR_C("switch") : path.approach ? STR_C("line out of the station") : STR_C("track"), path.length);
if (layout.kilometrage)
ImGui::TextDisabled("km %.3f", station::km_of(layout, along));
if (false == path.track->Isolated.empty())
ImGui::TextDisabled(STR_C("track circuit %s"), path.track->Isolated.front()->asName.c_str());
if (m_length_canvas >= 0 && m_length_canvas < static_cast<int>(m_lengths.size()))
{
auto const &track{m_lengths[m_length_canvas]};
ImGui::TextColored(ImGui::ColorConvertU32ToFloat4(kUseful), STR_C("Track %s, useful length %.0f m to the right, %.0f m to the left"), track.number.c_str(), track.ways[0].length, track.ways[1].length);
}
ImGui::TextDisabled("%s", STR_C("LMB: select it"));
ImGui::EndTooltip();
}
else if (line_hover >= 0)
{
auto const &row{m_lines[line_hover]};
ImGui::BeginTooltip();
ImGui::TextUnformatted((format(STR_C("The line out beyond the entry signal %s"), row.entry.c_str()) + ", " + (row.number == 0 ? std::string{STR_C("single track")} : format(STR_C("track %d"), row.number))).c_str());
auto const run{std::find_if(row.sections.begin(), row.sections.end(), [&](line_row::run const &Run) { return line_at >= Run.from && line_at <= Run.to; })};
if (run != row.sections.end())
{
ImGui::TextColored(ImGui::ColorConvertU32ToFloat4(circuit_colour(run->name)), STR_C("Block section %s, %.2f km"), run->name.c_str(), (run->to - std::max(0.0, run->from)) / 1000.0);
if (row.km_known)
ImGui::TextDisabled(STR_C("km %.3f to %.3f"), std::min(run->km_from, run->km_to), std::max(run->km_from, run->km_to));
}
else
ImGui::TextDisabled("%s", STR_C("No track circuit here"));
if (row.km_known && line_hover < static_cast<int>(m_line_ways.size()))
ImGui::TextDisabled("km %.3f", km_along(m_line_ways[line_hover], row.km_number, line_at));
ImGui::TextDisabled("%s", STR_C("LMB: show it in the 3d view"));
ImGui::EndTooltip();
}
}
void srk_tool::render_windows()
{
m_length_canvas = -1;
if (false == m_open || false == m_strip || false == m_layout.has_value())
return;
auto const &io{ImGui::GetIO()};
// along the bottom of the 3d view, as the vertical profile
auto const low{editor_ui::view_min()};
auto const high{editor_ui::view_max()};
auto const width{std::max(480.0f, high.x - low.x)};
auto const height{std::clamp((high.y - low.y) * 0.4f, 220.0f, std::max(220.0f, high.y - low.y - 80.0f))};
ImGui::SetNextWindowPos(ImVec2(low.x, high.y - height), ImGuiCond_Appearing);
ImGui::SetNextWindowSize(ImVec2(width, height), ImGuiCond_Appearing);
auto const name{std::string{STR_C("Station schematic")} + " " + title() + "###srkstrip"};
if (ImGui::Begin(name.c_str(), nullptr, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse))
{
auto const position{ImGui::GetWindowPos()};
auto const size{ImGui::GetWindowSize()};
if (false == ImGui::IsWindowDocked() && (position.y + size.y > io.DisplaySize.y + 1.0f || position.x + 80.0f > io.DisplaySize.x || position.x + size.x < 80.0f))
ImGui::SetWindowPos(ImVec2(std::clamp(position.x, 0.0f, std::max(0.0f, io.DisplaySize.x - size.x)), std::max(0.0f, std::min(position.y, io.DisplaySize.y - size.y))));
if (ImGui::Button(STR_C("Fit")))
{
m_fit_lines = false;
m_view_state.exaggeration = 0.0f;
}
item_tooltip("Shows the whole station");
ImGui::SameLine();
ImGui::BeginDisabled(m_lines.empty());
if (ImGui::Button(STR_C("Lines")))
{
m_fit_lines = true;
m_view_state.exaggeration = 0.0f;
}
ImGui::EndDisabled();
item_tooltip("Shows the station with its lines out to the next stations: their block sections, the block signals with their km");
ImGui::SameLine();
ImGui::SetNextItemWidth(140.0f);
ImGui::SliderFloat("##srkexaggeration", &m_view_state.exaggeration, 1.0f, 500.0f, STR_C("offsets x%.0f"), ImGuiSliderFlags_Logarithmic);
item_tooltip("How much the offsets of the tracks are stretched against the lengths, also Ctrl+wheel over the plot");
ImGui::SameLine();
ImGui::TextDisabled("%s", STR_C("Wheel: zoom, drag: move, LMB on a track: select it"));
render_canvas(ImGui::GetContentRegionAvail().y);
}
ImGui::End();
}
editor_selftest_result srk_tool::selftest(std::string const &Command, std::istringstream &Words)
{
if (Command == "srkopen")
{
// srkopen track=<name>: the station of the track, as a click on it opens it
auto const values{selftest_values(Words)};
auto const found{values.find("track")};
auto *track{found != values.end() ? simulation::Paths.find(found->second) : nullptr};
m_open = true;
// a tool of the station shown, so it stays open
if (auto const tab{m_view.current_track_tab()}; tab != editor_track_tab::station && tab != editor_track_tab::station_signals && tab != editor_track_tab::line_block)
m_view.show_track_tab(editor_track_tab::station);
load();
if (track == nullptr)
{
WriteLog("SELFTEST srkopen: no such track");
return editor_selftest_result::handled;
}
open(*track);
if (false == m_layout.has_value())
{
WriteLog("SELFTEST srkopen: " + m_status);
return editor_selftest_result::handled;
}
auto const &layout{*m_layout};
std::unordered_set<TTrack const *> tracks;
std::size_t approach{0};
for (auto const &path : layout.paths)
if (path.approach)
++approach;
else
tracks.insert(path.track);
WriteLog(format("SELFTEST srkopen %s: %zu switches, %zu tracks, %zu paths out, axis %.0f m, switches over %.0f..%.0f, offsets %.1f..%.1f, km %s, record %d", m_anchor->name().c_str(), layout.switches.size(), tracks.size(), approach,
layout.chainage.back(), layout.from, layout.to, layout.low, layout.high, layout.kilometrage ? format("%.3f", layout.km).c_str() : "-", m_record));
WriteLog(format("SELFTEST srkopen lines %zu, main %zu tracks, second %zu tracks", layout.lines.size(), layout.main.size(), layout.second.size()));
for (auto const *track : layout.switches)
{
auto const at{station::project(layout, track->m_paths.front().points[segment_data::point::start])};
WriteLog(format("SELFTEST srkopen switch %s at %.1f offset %.1f", track->name().c_str(), at.x, at.y));
}
return editor_selftest_result::handled;
}
if (Command == "srknumber")
{
// srknumber [from=right]: the switches of the open station numbered
if (false == m_layout.has_value())
{
WriteLog("SELFTEST srknumber: no station open");
return editor_selftest_result::handled;
}
auto const values{selftest_values(Words)};
auto const from{values.find("from")};
m_reversed = from != values.end() && from->second == "right";
number_switches();
std::string list;
for (auto const &unit : station::numbering(*m_layout, m_reversed))
for (auto const *part : unit.parts)
{
auto const record{switch_store::named(*part)};
list += ' ' + part->name() + '/' + (record ? record->number : std::string{"?"});
}
WriteLog("SELFTEST srknumber: " + m_status);
WriteLog("SELFTEST srknumber names:" + list);
return editor_selftest_result::handled;
}
if (Command == "srkcircuits")
{
// srkcircuits: the open station cut into its track circuits
if (false == m_layout.has_value())
{
WriteLog("SELFTEST srkcircuits: no station open");
return editor_selftest_result::handled;
}
set_circuits();
WriteLog("SELFTEST srkcircuits: " + m_status);
refresh();
std::map<std::string, std::pair<std::size_t, double>> found;
for (auto const &path : m_layout->paths)
if (false == path.track->Isolated.empty())
{
auto &entry{found[path.track->Isolated.front()->asName]};
++entry.first;
entry.second += path.length;
}
std::string list;
for (auto const &[name, entry] : found)
list += format(" %s:%zu/%.0f", name.c_str(), entry.first, entry.second);
WriteLog(format("SELFTEST srkcircuits %zu named, %zu joints:", found.size(), m_ticks.size()) + list);
return editor_selftest_result::handled;
}
if (Command == "srktrack")
{
// srktrack circuit=<name> number=<number>: the station track of the circuit renumbered
auto const values{selftest_values(Words)};
auto const circuit{values.find("circuit")};
auto const number{values.find("number")};
TTrack const *found{nullptr};
if (m_layout.has_value() && circuit != values.end())
for (auto const &path : m_layout->paths)
if (false == path.track->Isolated.empty() && path.track->Isolated.front()->asName == circuit->second)
found = path.track;
if (found == nullptr || number == values.end())
{
WriteLog("SELFTEST srktrack: no station open, or no such circuit");
return editor_selftest_result::handled;
}
renumber_track(*found, number->second);
WriteLog("SELFTEST srktrack: " + m_status);
return editor_selftest_result::handled;
}
if (Command == "srksignals")
{
// srksignals: the signals of the open station set
if (false == m_layout.has_value())
{
WriteLog("SELFTEST srksignals: no station open");
return editor_selftest_result::handled;
}
set_signals();
WriteLog("SELFTEST srksignals: " + m_status);
refresh();
std::string list;
for (auto const &mark : m_signal_marks)
{
// and the joint nearest to it, in the plan
auto nearest{std::numeric_limits<double>::max()};
for (auto const &joint : m_joints)
nearest = std::min(nearest, glm::distance(glm::dvec2{joint.at.x, joint.at.z}, glm::dvec2{mark.head.x, mark.head.z}));
list += format(" %s@%.0f/%.1f%s~%.1f", mark.text.c_str(), mark.at.x, mark.at.y, mark.ahead ? ">" : "<", nearest);
}
WriteLog(format("SELFTEST srksignals %zu:", m_signal_marks.size()) + list);
return editor_selftest_result::handled;
}
if (Command == "srklines")
{
// srklines: the signals of the lines out of the open station set
if (false == m_layout.has_value())
{
WriteLog("SELFTEST srklines: no station open");
return editor_selftest_result::handled;
}
set_lines();
WriteLog("SELFTEST srklines: " + m_status);
refresh();
std::vector<station::numbered> tracks;
std::unordered_set<TTrack const *> inside;
if (false == station_tracks(tracks, inside))
return editor_selftest_result::handled;
auto const plan{station::signals(*m_layout, tracks, [&](TTrack const &Track) { return inside.count(&Track) > 0; })};
std::vector<standing_signal> standing;
m_signals.standing_signals(standing, true);
for (auto const &line : station::lines_out(*m_layout, plan, kLineLimit))
{
std::vector<std::pair<double, std::string>> along;
for (auto const &signal : standing)
{
double gap{0.0};
auto const distance{station::distance_on(line, signal.position, gap)};
if (gap < 4.5 && distance < line.length())
along.emplace_back(distance, format("%s(%s,%s)", signal.name.c_str(), signal.kind.c_str(), signal.linked.c_str()));
}
std::string last;
for (std::size_t i = 1; i < line.points.size(); ++i)
{
auto const *track{line.tracks[line.owners[i]]};
auto const name{track->Isolated.empty() ? std::string{"-"} : track->Isolated.front()->asName};
if (name != last)
along.emplace_back(line.distances[i], "[" + name + "]");
last = name;
}
std::sort(along.begin(), along.end());
std::string list;
for (auto const &[distance, text] : along)
list += format(" %.0f:%s", distance, text.c_str());
WriteLog(format("SELFTEST srklines %s track %d %s %.0f m%s:", plan[line.entry].name.c_str(), line.number, line.inbound ? "in" : "out", line.length(), line.station ? " to a station" : "") + list);
}
return editor_selftest_result::handled;
}
if (Command == "srklengths")
{
// srklengths [show=<number>]: the lengths of the station tracks of the open station, the one shown drawn
if (false == m_layout.has_value())
{
WriteLog("SELFTEST srklengths: no station open");
return editor_selftest_result::handled;
}
std::vector<standing_signal> standing;
m_signals.standing_signals(standing, true);
refresh();
if (false == m_layout.has_value())
{
WriteLog("SELFTEST srklengths: the station is gone");
return editor_selftest_result::handled;
}
auto const values{selftest_values(Words)};
auto const show{values.find("show")};
auto const code = [](station::limit const &Limit) {
char const *const kinds[] = {"S", "J", "F", "St", "B", "X"};
return std::string{kinds[static_cast<int>(Limit.what)]} + ":" + Limit.name + format("@%.1f", Limit.along);
};
for (std::size_t index = 0; index < m_lengths.size(); ++index)
{
auto const &track{m_lengths[index]};
WriteLog(format("SELFTEST srklengths %s: right %.1f (%s .. %s), left %.1f (%s .. %s), construction %.1f", track.number.c_str(), track.ways[0].length, code(track.ways[0].rear).c_str(), code(track.ways[0].head).c_str(), track.ways[1].length,
code(track.ways[1].rear).c_str(), code(track.ways[1].head).c_str(), track.construction));
}
WriteLog(format("SELFTEST srklengths: %zu tracks", m_lengths.size()));
if (auto const copy{values.find("copy")}; copy != values.end() && copy->second == "1")
WriteLog("SELFTEST srklengths table:\n" + lengths_table());
// the track shown selected
for (auto const &path : m_layout->paths)
if (show != values.end() && false == path.track->Isolated.empty() && track_of(path.track->Isolated.front()->asName, stem_of_open()) == show->second)
{
m_selection.set_current_node(path.track);
m_picked = path.track;
break;
}
return editor_selftest_result::handled;
}
if (Command == "srkheads")
{
// srkheads [braking=<m>] [fit=1]: the lights of the signals of the open station checked, fitted
if (false == m_layout.has_value())
{
WriteLog("SELFTEST srkheads: no station open");
return editor_selftest_result::handled;
}
auto const values{selftest_values(Words)};
if (auto const braking{values.find("braking")}; braking != values.end())
{
record_of_open().braking = std::atoi(braking->second.c_str());
m_changed = true;
}
std::vector<standing_signal> standing;
m_signals.standing_signals(standing, true);
std::vector<signal_head> heads;
m_signals.signal_heads(heads, true);
refresh();
if (auto const fit{values.find("fit")}; fit != values.end() && fit->second == "1" && m_layout.has_value())
{
fit_heads();
WriteLog("SELFTEST srkheads fit: " + m_status);
refresh();
}
if (false == m_layout.has_value())
{
WriteLog("SELFTEST srkheads: the station is gone");
return editor_selftest_result::handled;
}
WriteLog(format("SELFTEST srkheads: speed %.0f (set %.0f), braking %.0f, %zu checked, templates %zu", speed_of_open(), set_speed_of_open(), braking_of_open(), m_heads.size(), heads.size()));
auto const list = [](std::vector<int> const &Speeds) {
std::string text;
for (auto const speed : Speeds)
text += (text.empty() ? "" : "/") + std::to_string(speed);
return text.empty() ? std::string{"-"} : text;
};
for (auto const &head : m_heads)
{
std::string routes;
for (std::size_t k = 0; k < head.routes.size(); ++k)
{
auto const &route{head.routes[k]};
routes += format(" %s:%.0f:%.0f%s%s", route.next >= 0 ? head.nexts[k].c_str() : route.ended ? "end" : "none", route.length, route.speed, route.warning >= 0 ? ":to" : "", route.turnouts.empty() ? "" : format(":%zut", route.turnouts.size()).c_str());
}
WriteLog(format("SELFTEST srkheads %s %s%s %s lamps=%s own=%s need=%s%s%s short=%d%s fits=%d more=%d told=%d%s fit=%s shp=%.0f/%.0f routes%s problems=%zu", head.name.c_str(), head.kind.c_str(), head.station ? "" : "(line)", head.file.c_str(), head.lamps.c_str(), list(head.own).c_str(), list(head.speeds).c_str(), head.informs ? "+inform" : "",
head.white ? "+white" : "", head.shortened, head.indicator ? " w21" : "", head.fits ? 1 : 0, head.more ? 1 : 0, head.told ? 1 : 0, head.unsaid ? "(unsaid)" : "", head.fit.empty() ? "-" : head.fit.c_str(), head.shp, head.shp_found, routes.c_str(), head.problems.size()));
for (auto const &problem : head.problems)
WriteLog("SELFTEST srkheads " + problem);
}
return editor_selftest_result::handled;
}
if (Command == "srkshp")
{
// srkshp: the SHP resonators of the open station placed, the signals listed with them
if (false == m_layout.has_value())
{
WriteLog("SELFTEST srkshp: no station open");
return editor_selftest_result::handled;
}
set_shp();
WriteLog("SELFTEST srkshp: " + m_status);
refresh();
if (false == m_layout.has_value())
return editor_selftest_result::handled;
std::vector<standing_signal> standing;
m_signals.standing_signals(standing, true);
check_heads(standing);
for (auto const &head : m_heads)
if (head.shp >= 0.0)
WriteLog(format("SELFTEST srkshp %s %s wanted %.0f found %.0f", head.name.c_str(), head.kind.c_str(), head.shp, head.shp_found));
for (auto const &include : m_templates.standing_templates([](std::string const &File) { return File == kResonator; }))
WriteLog(format("SELFTEST srkshp resonator %s at %.2f %.2f %.2f yaw %.1f", include.values.empty() ? "-" : include.values.front().c_str(), include.location.x, include.location.y, include.location.z, include.yaw));
return editor_selftest_result::handled;
}
if (Command == "srkblock")
{
// srkblock entry=<A> [kind=sbl|sbl4|semi|auto] [ways=1|2|auto]: the block of the line out beyond the entry signal, both ways or
// not with the other track of the line, the lines listed
if (m_history.history_revision() != m_history_revision)
refresh();
if (false == m_layout.has_value())
{
WriteLog("SELFTEST srkblock: no station open");
return editor_selftest_result::handled;
}
auto const values{selftest_values(Words)};
auto const entry{values.find("entry")};
auto const kind{values.find("kind")};
if (entry != values.end() && kind != values.end())
{
if (kind->second == "auto")
record_of_open().blocks.erase(entry->second);
else
record_of_open().blocks[entry->second] = kind->second == "sbl4" ? block_kind::four : kind->second == "sbl" ? block_kind::three : block_kind::semi;
m_changed = true;
}
if (auto const ways{values.find("ways")}; entry != values.end() && ways != values.end())
{
auto const row{std::find_if(m_lines.begin(), m_lines.end(), [&](line_row const &Row) { return Row.entry == entry->second; })};
std::vector<std::string> entries{entry->second};
if (row != m_lines.end() && row->partner >= 0 && row->partner < static_cast<int>(m_lines.size()))
entries.push_back(m_lines[row->partner].entry);
for (auto const &name : entries)
if (ways->second == "auto")
record_of_open().ways.erase(name);
else
record_of_open().ways[name] = ways->second == "2";
m_changed = true;
}
survey_signals();
if (false == m_lines_problem.empty())
WriteLog("SELFTEST srkblock: " + m_lines_problem);
auto const listed = [](std::vector<std::pair<double, std::string>> const &Stops) {
std::string text;
for (auto const &[distance, name] : Stops)
text += format(" %s@%.0f", name.c_str(), distance);
return text;
};
for (auto const &row : m_lines)
WriteLog(format("SELFTEST srkblock %s track %d %s to %s %.0f m blocks %zu: %s why %d own %d ways %d%s leftovers %zu legacy %d stops%s wrong%s", row.entry.c_str(), row.number, row.inbound ? "in" : "out", row.next.empty() ? "-" : row.next.c_str(), row.length, row.blocks,
row.block == block_kind::four ? "sbl4" : row.block == block_kind::three ? "sbl" : "semi", static_cast<int>(row.why), static_cast<int>(row.own), row.both ? 2 : 1, row.both_hand ? " hand" : "", row.leftovers, row.legacy ? 1 : 0, listed(row.stops).c_str(), listed(row.wrong).c_str()));
return editor_selftest_result::handled;
}
if (Command == "srkjoint")
{
// srkjoint [edit=0|1] [track=<name>|#<path> at=<0..1>|joint=<n>|hand=<n>|aside=<m>] [click=0] [plan=1]: a click while the joints are edited, on
// the track at the share of its length, on the n-th joint standing, on the n-th one put by hand, or that far aside of the track; the hover alone with
// click=0; plan=1 the joints by hand forgotten
if (m_history.history_revision() != m_history_revision)
refresh();
if (false == m_layout.has_value())
{
WriteLog("SELFTEST srkjoint: no station open");
return editor_selftest_result::handled;
}
auto const values{selftest_values(Words)};
if (values.count("edit") > 0)
m_joint_editing = values.at("edit") != "0";
auto const log = [&](std::string const &Label, bool const Valid) {
if (m_history.history_revision() != m_history_revision)
refresh();
auto const added{m_record >= 0 ? m_records[m_record].joints_added.size() : 0};
auto const removed{m_record >= 0 ? m_records[m_record].joints_removed.size() : 0};
WriteLog(format("SELFTEST srkjoint: %s valid %d held %d joints %zu circuits %zu added %zu removed %zu status %s", Label.c_str(), Valid ? 1 : 0, m_joint_held.has_value() ? 1 : 0, m_joints.size(), m_circuits.size(), added, removed, m_status.c_str()));
};
if (values.count("list") > 0)
for (std::size_t index = 0; index < m_layout->paths.size(); ++index)
{
auto const &path{m_layout->paths[index]};
WriteLog(format("SELFTEST srkjoint path #%zu %s%s%s %.1f m %s", index, path.track->name().c_str(), is_switch(*path.track) ? " switch" : "", path.approach ? " approach" : "", path.length, path.track->Isolated.empty() ? "-" : path.track->Isolated.front()->asName.c_str()));
}
if (values.count("plan") > 0 && m_record >= 0)
{
auto &entry{record_of_open()};
srk_hand_joints const before{entry.track, entry.joints_added, entry.joints_removed};
entry.joints_added.clear();
entry.joints_removed.clear();
joints_changed(before, true);
log("plan", true);
return editor_selftest_result::handled;
}
std::optional<glm::dvec3> point;
if (values.count("joint") > 0)
{
auto const index{static_cast<std::size_t>(std::atoi(values.at("joint").c_str()))};
if (index < m_joints.size())
point = m_joints[index].at;
}
else if (values.count("hand") > 0 && m_record >= 0)
{
auto const &added{m_records[m_record].joints_added};
if (auto const index{static_cast<std::size_t>(std::atoi(values.at("hand").c_str()))}; index < added.size())
point = added[index];
}
else if (values.count("track") > 0)
{
auto const share{values.count("at") > 0 ? std::atof(values.at("at").c_str()) : 0.5};
for (auto const &path : m_layout->paths)
if ((path.track->name() == values.at("track") || (values.at("track").front() == '#' && &path == &m_layout->paths[std::min<std::size_t>(std::atoi(values.at("track").c_str() + 1), m_layout->paths.size() - 1)])) && path.points.size() > 1 && false == point.has_value())
{
double length{0.0};
for (std::size_t i = 1; i < path.points.size(); ++i)
length += glm::distance(path.points[i - 1], path.points[i]);
auto left{length * share};
for (std::size_t i = 1; i < path.points.size() && false == point.has_value(); ++i)
{
auto const step{glm::distance(path.points[i - 1], path.points[i])};
if (left <= step || i + 1 == path.points.size())
point = glm::mix(path.points[i - 1], path.points[i], step > 0.0 ? std::min(1.0, left / step) : 0.0);
left -= step;
}
}
}
else if (values.count("aside") > 0 && false == m_layout->paths.empty())
point = m_layout->paths.front().points.front() + glm::dvec3{std::atof(values.at("aside").c_str()), 0.0, 0.0};
if (false == point.has_value())
{
log("no point", false);
return editor_selftest_result::handled;
}
bool valid{false};
auto const label{joint_hover(*point, valid)};
if (values.count("click") == 0 || values.at("click") != "0")
{
begin_status();
joint_click();
}
log(label, valid);
return editor_selftest_result::handled;
}
if (Command == "srkboundary")
{
// srkboundary entry=<A> at=<m>|stop=<n> [nudge=<m>]: a click while drawing the block boundaries, on the line beyond the entry
// signal at the distance out or at a block signal standing along it, nudge metres aside
if (m_history.history_revision() != m_history_revision)
refresh();
auto const values{selftest_values(Words)};
auto const entry{values.count("entry") > 0 ? values.at("entry") : std::string{}};
auto at{values.count("at") > 0 ? std::atof(values.at("at").c_str()) : 0.0};
auto const nudge{values.count("nudge") > 0 ? std::atof(values.at("nudge").c_str()) : 0.0};
auto const found{std::find_if(m_lines.begin(), m_lines.end(), [&](line_row const &Row) { return Row.entry == entry; })};
if (false == m_layout.has_value() || found == m_lines.end())
{
WriteLog("SELFTEST srkboundary: no line beyond " + entry);
return editor_selftest_result::handled;
}
if (values.count("stop") > 0 && false == found->stops.empty())
at = found->stops[static_cast<std::size_t>(std::abs(std::atoi(values.at("stop").c_str()))) % found->stops.size()].first;
auto const place{station::point_on(m_line_ways[found - m_lines.begin()], at)};
m_drawing = true;
bool valid{false};
auto const label{boundary_hover(place.point + glm::dvec3{-place.way.z, 0.0, place.way.x} * nudge, valid)};
WriteLog(format("SELFTEST srkboundary %s at %.0f: %s%s", entry.c_str(), at, valid ? "" : "(refused) ", label.c_str()));
if (valid)
{
boundary_click();
WriteLog("SELFTEST srkboundary: " + m_status);
}
m_drawing = false;
return editor_selftest_result::handled;
}
if (Command == "srkfit")
{
// srkfit lines|station|from=<m> to=<m>: the schematic fitting the lines out, the station, or the chainage between
std::string word;
std::string mode;
std::map<std::string, std::string> range;
while (Words >> word)
if (auto const equals{word.find('=')}; equals != std::string::npos)
range[word.substr(0, equals)] = word.substr(equals + 1);
else
mode = word;
m_fit_lines = mode == "lines";
m_view_state.exaggeration = 0.0f;
if (range.count("from") > 0 && range.count("to") > 0 && m_layout.has_value())
{
fit_view(1000.0f, 400.0f);
m_view_state.from = std::atof(range.at("from").c_str());
m_view_state.to = std::atof(range.at("to").c_str());
}
WriteLog("SELFTEST srkfit " + mode);
return editor_selftest_result::handled;
}
if (Command == "srkdraw")
{
// srkdraw on|off: the block boundaries drawn by hand, or not
std::string word;
Words >> word;
m_drawing = word != "off";
WriteLog(std::string{"SELFTEST srkdraw "} + (m_drawing ? "on" : "off"));
return editor_selftest_result::handled;
}
if (Command == "srkcheck")
{
// srkcheck: the block sections of the scenery checked: each switched by a block signal standing, none twice, no two signals of
// one name
std::vector<standing_signal> standing;
m_signals.standing_signals(standing, true);
std::unordered_map<std::string, int> names;
for (auto const &signal : standing)
++names[ToLower(signal.name)];
std::size_t bad{0};
for (auto const &[name, count] : names)
if (count > 1)
{
++bad;
WriteLog(format("SELFTEST srkcheck: %d signals named %s", count, name.c_str()));
}
std::unordered_map<std::string, int> sections;
auto const controls{m_templates.standing_templates([](std::string const &File) { return File == kControl; })};
for (auto const &control : controls)
{
if (control.values.size() < 6)
{
++bad;
WriteLog("SELFTEST srkcheck: a block section without its signal");
continue;
}
if (++sections[ToLower(control.values[0])] > 1)
{
++bad;
WriteLog("SELFTEST srkcheck: block section " + control.values[0] + " twice");
}
for (std::size_t index = 5; index < control.values.size() && index < 7; ++index)
if (names.count(ToLower(control.values[index])) == 0)
{
++bad;
WriteLog("SELFTEST srkcheck: block section " + control.values[0] + " switched by " + control.values[index] + ", which doesn't stand");
}
}
std::size_t unread{0};
for (auto const &signal : standing)
if (false == signal.read.empty() && signal.track == nullptr)
{
++unread;
WriteLog("SELFTEST srkcheck: signal " + signal.name + " read by no track, its event " + signal.read);
}
std::unordered_set<std::string> circuits;
for (auto *track : simulation::Paths.sequence())
if (track != nullptr && false == track->m_editorremoved)
for (auto const *isolated : track->Isolated)
if (isolated != nullptr)
circuits.insert(ToLower(isolated->asName));
std::size_t bare{0};
for (auto const &control : controls)
if (false == control.values.empty() && circuits.count(ToLower(control.values[0])) == 0)
{
++bare;
WriteLog("SELFTEST srkcheck: block section " + control.values[0] + " without a track");
}
bad += unread + bare;
if (m_layout.has_value())
{
survey_signals();
for (auto const &problem : m_problems)
WriteLog(format("SELFTEST srkcheck: open station: %s at %.1f %.1f%s%s", problem.text.c_str(), problem.at.x, problem.at.z, problem.signal != 0 ? " (signal)" : "", problem.lines ? " (lines)" : ""));
}
WriteLog(format("SELFTEST srkcheck: %zu signals, %zu block sections, %zu unread, %zu without a track, %zu problems of the open station, %zu bad", standing.size(), controls.size(), unread, bare, m_problems.size(), bad));
return editor_selftest_result::handled;
}
if (Command == "srkfix")
{
// srkfix: the Repair of the check of the open station
if (false == m_layout.has_value())
{
WriteLog("SELFTEST srkfix: no station open");
return editor_selftest_result::handled;
}
survey_signals();
auto const before{m_problems.size()};
fix_problems();
WriteLog(format("SELFTEST srkfix: %zu problems before, status %s", before, m_status.c_str()));
return editor_selftest_result::handled;
}
if (Command == "srkdrawing")
{
// srkdrawing [track=<circuit>]: the schematic as the plot draws it: the rows of the tracks, the shortened chainage, the points
// on the rows, on slants, the corners; the points of the paths of the circuit, offset > row
if (false == m_layout.has_value())
{
WriteLog("SELFTEST srkdrawing: no station open");
return editor_selftest_result::handled;
}
auto const &layout{*m_layout};
std::map<int, std::string> rows;
for (auto const &run : m_plot.runs)
if (false == run.paths.empty())
rows[run.row] += format(" %s@%.1f", layout.paths[run.paths.front()].track->name().c_str(), run.offset);
std::string list;
for (auto const &[row, names] : rows)
list += format(" |%d:", row) + names;
WriteLog(format("SELFTEST srkdrawing tracks %zu, rows %zu, spacing %.2f", m_plot.runs.size(), rows.size(), m_plot.spacing));
WriteLog("SELFTEST srkdrawing rows" + list);
WriteLog(format("SELFTEST srkdrawing switches over %.0f..%.0f m drawn %.0f..%.0f, back %.1f..%.1f", layout.from, layout.to, m_plot.x(layout.from), m_plot.x(layout.to), m_plot.chainage(m_plot.x(layout.from)), m_plot.chainage(m_plot.x(layout.to))));
std::size_t on_rows{0};
std::size_t between{0};
std::size_t bends{0};
std::size_t backwards{0};
for (std::size_t index = 0; index < layout.paths.size(); ++index)
{
if (layout.paths[index].approach)
continue;
auto const &points{m_plot.paths[index]};
for (auto const &point : points)
{
auto const rows{point.y / station::row_height};
if (std::abs(rows - std::round(rows)) < 1e-6)
++on_rows;
else
++between;
}
for (std::size_t k = 2; k < points.size(); ++k)
{
auto const a{points[k - 1] - points[k - 2]};
auto const b{points[k] - points[k - 1]};
if (std::abs(a.x) > 1e-6 && std::abs(b.x) > 1e-6 && (std::abs(a.y) > 1e-6 || std::abs(b.y) > 1e-6) && std::abs(a.y / a.x - b.y / b.x) > 1e-3)
++bends;
}
for (std::size_t k = 1; k < points.size(); ++k)
if ((points[k].x - points[k - 1].x) * (layout.paths[index].schematic[k].x - layout.paths[index].schematic[k - 1].x) < 0.0)
++backwards;
}
WriteLog(format("SELFTEST srkdrawing points on rows %zu, between %zu, bends %zu, x backwards %zu", on_rows, between, bends, backwards));
if (auto const values{selftest_values(Words)}; values.count("track"))
for (std::size_t index = 0; index < layout.paths.size(); ++index)
if (auto const &path{layout.paths[index]}; false == path.track->Isolated.empty() && path.track->Isolated.front()->asName == values.at("track"))
{
std::string list;
for (std::size_t k = 0; k < path.schematic.size(); k += 4)
list += format(" %.0f/%.2f>%.2f", path.schematic[k].x, path.schematic[k].y, m_plot.paths[index][k].y / station::row_height);
WriteLog(format("SELFTEST srkdrawing %s/%d:", path.track->name().c_str(), path.index) + list);
}
return editor_selftest_result::handled;
}
if (Command == "srkstrip")
{
// srkstrip shown=0: the schematic hidden, the 3d view whole for a screenshot
auto const values{selftest_values(Words)};
auto const shown{values.find("shown")};
m_strip = shown == values.end() || shown->second != "0";
return editor_selftest_result::handled;
}
if (Command == "srkstations")
{
load();
find_all();
WriteLog(format("SELFTEST srkstations: %zu", m_found.size()));
for (auto const &[name, count] : m_found)
WriteLog(format("SELFTEST srkstations %s: %zu switches", name.c_str(), count));
return editor_selftest_result::handled;
}
if (Command == "srkset")
{
// srkset code=<code> line=<line> name=<words joined by _>
if (false == m_layout.has_value())
{
WriteLog("SELFTEST srkset: no station open");
return editor_selftest_result::handled;
}
auto const values{selftest_values(Words)};
auto &entry{record_of_open()};
if (auto const code{values.find("code")}; code != values.end())
entry.code = code->second;
if (auto const line{values.find("line")}; line != values.end())
entry.line = line->second;
if (auto const name{values.find("name")}; name != values.end())
{
entry.name = name->second;
std::replace(entry.name.begin(), entry.name.end(), '_', ' ');
}
if (auto const km{values.find("km")}; km != values.end())
entry.km = km->second;
m_changed = true;
WriteLog("SELFTEST srkset: " + title());
return editor_selftest_result::handled;
}
return editor_selftest_result::unhandled;
}