18
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-11-19 23:55:00 +01:00
Files
maszyna/world/Track.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

4370 lines
183 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/.
*/
/*
MaSzyna EU07 locomotive simulator
Copyright (C) 2001-2004 Marcin Wozniak and others
*/
#include "stdafx.h"
#include "world/Track.h"
#include "world/TrackRails.h"
#include "simulation/simulation.h"
#include "scene/scene.h"
#include "utilities/Globals.h"
#include "world/Event.h"
#include "world/MemCell.h"
#include "input/messaging.h"
#include "vehicle/DynObj.h"
#include "vehicle/Driver.h"
#include "model/AnimModel.h"
#include "model/MdlMngr.h"
#include "model/Model3d.h"
#include "utilities/Timer.h"
#include "utilities/Logs.h"
#include "rendering/renderer.h"
#include <format>
// 101206 Ra: trapezoidalne drogi i tory
// 110720 Ra: rozprucie zwrotnicy i odcinki izolowane
static float const fMaxOffset = 0.1f; // double(0.1f)==0.100000001490116
// const int NextMask[4]={0,1,0,1}; //tor następny dla stanów 0, 1, 2, 3
// const int PrevMask[4]={0,0,1,1}; //tor poprzedni dla stanów 0, 1, 2, 3
const int iLewo4[4] = {5, 3, 4, 6}; // segmenty (1..6) do skręcania w lewo
const int iPrawo4[4] = {-4, -6, -3, -5}; // segmenty (1..6) do skręcania w prawo
const int iProsto4[4] = {1, -1, 2, -2}; // segmenty (1..6) do jazdy prosto
const int iEnds4[13] = {3, 0, 2, 1, 2, 0, -1, 1, 3, 2, 0, 3, 1}; // numer sąsiedniego toru na końcu segmentu "-1"
const int iLewo3[4] = {1, 3, 2, 1}; // segmenty do skręcania w lewo
const int iPrawo3[4] = {-2, -1, -3, -2}; // segmenty do skręcania w prawo
const int iProsto3[4] = {1, -1, 2, 1}; // segmenty do jazdy prosto
const int iEnds3[13] = {3, 0, 2, 1, 2, 0, -1, 1, 0, 2, 0, 3, 1}; // numer sąsiedniego toru na końcu segmentu "-1"
TIsolated *TIsolated::pRoot = nullptr;
namespace {
// a part of a switch path, shaped like the path itself: heights on the rail heads, straights made of their own points
void init_switch_piece( TSegment &Segment, segment_data const &Piece, bool const Rail ) {
auto p1 { Piece.points[ segment_data::point::start ] };
auto cp1 { Piece.points[ segment_data::point::control1 ] };
auto cp2 { Piece.points[ segment_data::point::control2 ] };
auto p2 { Piece.points[ segment_data::point::end ] };
if( Rail ) {
p1.y += 0.18;
p2.y += 0.18;
}
// one with its radius given is a curve however gently it bends, as a short path bent with the curve it's laid into
if( Piece.radius == 0.f
&& ( glm::length2( ( p1 + p1 + p2 ) / 3.0 - p1 - cp1 ) < sq( 0.02 )
|| glm::length2( ( p1 + p2 + p2 ) / 3.0 - p2 - cp2 ) < sq( 0.02 ) ) ) {
cp1 = cp2 = glm::dvec3( 0, 0, 0 );
}
auto const straight { cp1 == glm::dvec3() && cp2 == glm::dvec3() };
auto segsize { 10.0 };
if( Piece.radius != 0.f ) {
segsize = std::clamp( std::abs( Piece.radius ) * ( 0.02 / Global.SplineFidelity ), 2.0 / Global.SplineFidelity, 10.0 / Global.SplineFidelity );
}
else if( false == straight ) {
segsize = std::clamp( glm::length( p1 - p2 ) * 0.1, 2.0 / Global.SplineFidelity, 10.0 / Global.SplineFidelity );
}
if( straight ) {
Segment.Init( p1, p2, segsize, Piece.rolls[ 0 ], Piece.rolls[ 1 ] );
}
else {
Segment.Init( p1, p1 + cp1, p2 + cp2, p2, segsize, Piece.rolls[ 0 ], Piece.rolls[ 1 ] );
}
}
// a path of the switch made of the pieces given for it, where they join its ends and one another; the path as given where they don't
void chain_switch_pieces( TTrack &Track, std::size_t const Index ) {
auto const &pieces { Track.m_paths[ Index ].pieces };
if( pieces.empty() ) {
return;
}
auto joined {
glm::distance( pieces.front().points[ segment_data::point::start ], Track.m_paths[ Index ].points[ segment_data::point::start ] ) < 0.02
&& glm::distance( pieces.back().points[ segment_data::point::end ], Track.m_paths[ Index ].points[ segment_data::point::end ] ) < 0.02 };
for( std::size_t piece = 1; piece < pieces.size(); ++piece ) {
joined = joined && glm::distance( pieces[ piece - 1 ].points[ segment_data::point::end ], pieces[ piece ].points[ segment_data::point::start ] ) < 0.02;
}
if( false == joined ) {
ErrorLog( std::format( "Bad track: pieces of path {} of switch \"{}\" don't join its ends, the path is used instead", Index + 1, Track.m_name ) );
return;
}
auto const texheight { Track.fTexHeight1 };
auto const texheightoffset { Track.fTexHeightOffset };
std::vector<std::shared_ptr<TSegment>> chain;
for( auto const &piece : pieces ) {
chain.emplace_back( std::make_shared<TSegment>( &Track ) );
init_switch_piece( *chain.back(), piece, ( Track.iCategoryFlag & 1 ) != 0 );
}
Track.fTexHeight1 = texheight;
Track.fTexHeightOffset = texheightoffset;
Track.SwitchExtension->Segments[ Index ]->InitChain( std::move( chain ) );
}
} // namespace
TTrack::profiles_array TTrack::m_profiles;
TTrack::profiles_map TTrack::m_profilesmap;
int TTrack::s_layoutstamp { 0 };
TSwitchExtension::TSwitchExtension(TTrack *owner, int const what)
{ // na początku wszystko puste
pNexts[0] = nullptr; // wskaźniki do kolejnych odcinków ruchu
pNexts[1] = nullptr;
pPrevs[0] = nullptr;
pPrevs[1] = nullptr;
fOffset1 = fOffset = fDesiredOffset = -fOffsetDelay; // położenie zasadnicze
fOffset2 = 0.f; // w zasadniczym wewnętrzna iglica dolega
Segments[0] = std::make_shared<TSegment>(owner); // z punktu 1 do 2
Segments[1] = std::make_shared<TSegment>(owner); // z punktu 3 do 4 (1=3 dla zwrotnic; odwrócony dla skrzyżowań, ewentualnie 1=4)
Segments[2] = what >= 3 ?
std::make_shared<TSegment>(owner) :
nullptr; // z punktu 2 do 4 skrzyżowanie od góry: wersja "-1":
Segments[3] = what >= 4 ?
std::make_shared<TSegment>(owner) :
nullptr; // z punktu 4 do 1 1 1=4 0 0=3
Segments[4] = what >= 5 ?
std::make_shared<TSegment>(owner) :
nullptr; // z punktu 1 do 3 4 x 3 3 3 x 2 2
Segments[5] = what >= 6 ?
std::make_shared<TSegment>(owner) :
nullptr; // z punktu 3 do 2 2 2 1 1
}
TSwitchExtension::~TSwitchExtension()
{ // nie ma nic do usuwania
}
/*
TIsolated::TIsolated()
{ // utworznie pustego
TIsolated("none", NULL);
};
*/
TIsolated::TIsolated(std::string const &n, TIsolated *i) :
asName( n ), pNext( i )
{
// utworznie obwodu izolowanego. nothing to do here.
};
void TIsolated::DeleteAll() {
while( pRoot ) {
auto *next = pRoot->Next();
delete pRoot;
pRoot = next;
}
}
TIsolated * TIsolated::Find(std::string const &n)
{ // znalezienie obiektu albo utworzenie nowego
TIsolated *p = pRoot;
while (p)
{ // jeśli się znajdzie, to podać wskaźnik
if (p->asName == n)
return p;
p = p->pNext;
}
pRoot = new TIsolated(n, pRoot); // BUG: source of a memory leak
return pRoot;
};
void
TIsolated::AssignEvents() {
evBusy = simulation::Events.FindEvent( asName + ":busy" );
evFree = simulation::Events.FindEvent( asName + ":free" );
evInc = simulation::Events.FindEvent( asName + ":inc" );
evDec = simulation::Events.FindEvent( asName + ":dec" );
}
void TIsolated::Modify(int i, TDynamicObject *o)
{ // dodanie lub odjęcie osi
if (iAxles)
{ // grupa zajęta
iAxles += i;
if (!iAxles)
{ // jeśli po zmianie nie ma żadnej osi na odcinku izolowanym
if (evFree)
simulation::Events.AddToQuery(evFree, o); // dodanie zwolnienia do kolejki
if (Global.iMultiplayer) // jeśli multiplayer
multiplayer::WyslijString(asName, 10); // wysłanie pakietu o zwolnieniu
if (pMemCell) // w powiązanej komórce
pMemCell->UpdateValues( "", 0, int( pMemCell->Value2() ) & ~0xFF,
basic_event::flags::value2 ); //"zerujemy" ostatnią wartość
}
}
else
{ // grupa była wolna
iAxles += i;
if (iAxles)
{
if (evBusy)
simulation::Events.AddToQuery(evBusy, o); // dodanie zajętości do kolejki
if (Global.iMultiplayer) // jeśli multiplayer
{
auto const *owner = o->Mechanik != nullptr && o->Mechanik->primary() ? o->Mechanik : o->ctOwner;
auto textline = owner != nullptr ? Bezogonkow(owner->TrainName(), true) : "none";
if ("none" != textline && Global.bIsolatedTrainName) {
textline = ":" + Bezogonkow(owner->TrainName(), true);
}
else {
textline = "";
}
multiplayer::WyslijString(asName+textline, 11); // wysłanie pakietu o zajęciu
}
if (pMemCell) // w powiązanej komórce
pMemCell->UpdateValues( "", 0, int( pMemCell->Value2() ) | 1, basic_event::flags::value2 ); // zmieniamy ostatnią wartość na nieparzystą
}
}
if (i > 0 && evInc)
simulation::Events.AddToQuery(evInc, o);
if (i < 0 && evDec)
simulation::Events.AddToQuery(evDec, o);
// pass the event to the parent
if( pParent != nullptr ) {
pParent->Modify( i, o );
}
};
// tworzenie nowego odcinka ruchu
TTrack::TTrack( scene::node_data const &Nodedata ) : basic_node( Nodedata ) {
track_rails::forget();
}
TTrack::~TTrack()
{ // likwidacja odcinka
track_rails::forget();
if( eType == tt_Cross ) {
delete SwitchExtension->vPoints; // skrzyżowanie może mieć punkty
}
}
void TTrack::Init()
{ // tworzenie pomocniczych danych
switch (eType)
{
case tt_Switch:
SwitchExtension = std::make_shared<TSwitchExtension>( this, 2 ); // na wprost i na bok
break;
case tt_Cross: // tylko dla skrzyżowania dróg
SwitchExtension = std::make_shared<TSwitchExtension>( this, 6 ); // 6 po³¹czeñ
SwitchExtension->vPoints = nullptr; // brak tablicy punktów
SwitchExtension->bPoints = false; // tablica punktów nie wypełniona
SwitchExtension->iRoads = 4; // domyślnie 4
break;
case tt_Normal:
Segment = std::make_shared<TSegment>( this );
break;
case tt_Table: // oba potrzebne
SwitchExtension = std::make_shared<TSwitchExtension>( this, 1 ); // kopia oryginalnego toru
Segment = std::make_shared<TSegment>(this);
break;
}
}
bool
TTrack::sort_by_material( TTrack const *Left, TTrack const *Right ) {
return std::tie( Left->m_material1, Left->m_material2 ) < std::tie( Right->m_material1, Right->m_material2 );
}
TTrack * TTrack::Create400m(int what, double dx)
{ // tworzenie toru do wstawiania taboru podczas konwersji na E3D
scene::node_data nodedata;
nodedata.name = "auto_400m"; // track isn't visible so only name is needed
auto *trk = new TTrack( nodedata );
trk->m_visible = false; // nie potrzeba pokazywać, zresztą i tak nie ma tekstur
trk->iCategoryFlag = what; // taki sam typ plus informacja, że dodatkowy
trk->Init(); // utworzenie segmentu
trk->Segment->Init(glm::dvec3(-dx, 0, 0), glm::dvec3(-dx, 0, 400), 10.0, 0, 0); // prosty
trk->location( glm::dvec3{ -dx, 0, 200 } ); //środek, aby się mogło wyświetlić
simulation::Paths.insert( trk );
simulation::Region->insert( trk );
return trk;
};
TTrack * TTrack::NullCreate(int dir)
{ // tworzenie toru wykolejającego od strony (dir), albo pętli dla samochodów
TTrack
*trk { nullptr },
*trk2 { nullptr };
scene::node_data nodedata;
nodedata.name = "auto_null"; // track isn't visible so only name is needed
trk = new TTrack( nodedata );
trk->m_visible = false; // nie potrzeba pokazywać, zresztą i tak nie ma tekstur
trk->iCategoryFlag = iCategoryFlag & 15 | 0x80; // taki sam typ plus informacja, że dodatkowy
float r1, r2;
Segment->GetRolls(r1, r2); // pobranie przechyłek na początku toru
glm::dvec3 p1, cv1, cv2, p2; // będziem tworzyć trajektorię lotu
if (iCategoryFlag & 1)
{ // tylko dla kolei
trk->iDamageFlag = 128; // wykolejenie
trk->fVelocity = 0.0; // koniec jazdy
trk->Init(); // utworzenie segmentu
switch (dir)
{ //łączenie z nowym torem
case 0:
p1 = Segment->FastGetPoint_0();
p2 = p1 - 450.0 * glm::normalize(Segment->GetDirection1());
// bo prosty, kontrolne wyliczane przy zmiennej przechyłce
trk->Segment->Init(p1, p2, 5, -glm::degrees(r1), 70.0);
ConnectPrevPrev(trk, 0);
break;
case 1:
p1 = Segment->FastGetPoint_1();
p2 = p1 - 450.0 * glm::normalize(Segment->GetDirection2());
// bo prosty, kontrolne wyliczane przy zmiennej przechyłce
trk->Segment->Init(p1, p2, 5, glm::degrees(r2), 70.0);
ConnectNextPrev(trk, 0);
break;
case 3: // na razie nie możliwe
p1 = SwitchExtension->Segments[1]->FastGetPoint_1(); // koniec toru drugiego zwrotnicy
p2 = p1 - 450.0 * glm::normalize(SwitchExtension->Segments[1]->GetDirection2()); // przedłużenie na wprost
trk->Segment->Init(p1, p2, 5, glm::degrees(r2), 70.0); // bo prosty, kontrolne wyliczane przy zmiennej przechyłce
ConnectNextPrev(trk, 0);
// trk->ConnectPrevNext(trk,dir);
SetConnections(1); // skopiowanie połączeń
Switch(1); // bo się przełączy na 0, a to coś chce się przecież wykoleić na bok
break; // do drugiego zwrotnicy... nie zadziała?
}
}
else
{ // tworznie pętelki dla samochodów
trk->fVelocity = 20.0; // zawracanie powoli
trk->fRadius = 20.0; // promień, aby się dodawało do tabelki prędkości i liczyło narastająco
trk->Init(); // utworzenie segmentu
trk2 = new TTrack( nodedata );
trk2->iCategoryFlag =
iCategoryFlag & 15 | 0x80; // taki sam typ plus informacja, że dodatkowy
trk2->m_visible = false;
trk2->fVelocity = 20.0; // zawracanie powoli
trk2->fRadius = 20.0; // promień, aby się dodawało do tabelki prędkości i liczyło narastająco
trk2->Init(); // utworzenie segmentu
trk->m_name = m_name + ":loopstart";
trk2->m_name = m_name + ":loopfinish";
switch (dir)
{ //łączenie z nowym torem
case 0:
p1 = Segment->FastGetPoint_0();
cv1 = -20.0 * glm::normalize(Segment->GetDirection1()); // pierwszy wektor kontrolny
p2 = p1 + cv1 + cv1; // 40m
// bo prosty, kontrolne wyliczane przy zmiennej przechyłce
trk->Segment->Init(p1, p1 + cv1, p2 + glm::dvec3(-cv1.z, cv1.y, cv1.x), p2, 2, -glm::degrees(r1), 0.0);
ConnectPrevPrev(trk, 0);
// bo prosty, kontrolne wyliczane przy zmiennej przechyłce
trk2->Segment->Init(p1, p1 + cv1, p2 + glm::dvec3(cv1.z, cv1.y, -cv1.x), p2, 2, -glm::degrees(r1), 0.0);
trk2->iPrevDirection = 0; // zwrotnie do tego samego odcinka
break;
case 1:
p1 = Segment->FastGetPoint_1();
cv1 = -20.0 * glm::normalize(Segment->GetDirection2()); // pierwszy wektor kontrolny
p2 = p1 + cv1 + cv1;
// bo prosty, kontrolne wyliczane przy zmiennej przechyłce
trk->Segment->Init(p1, p1 + cv1, p2 + glm::dvec3(-cv1.z, cv1.y, cv1.x), p2, 2, glm::degrees(r2), 0.0);
ConnectNextPrev(trk, 0);
// bo prosty, kontrolne wyliczane przy zmiennej przechyłce
trk2->Segment->Init(p1, p1 + cv1, p2 + glm::dvec3(cv1.z, cv1.y, -cv1.x), p2, 2, glm::degrees(r2), 0.0);
trk2->iPrevDirection = 1; // zwrotnie do tego samego odcinka
break;
}
trk2->trPrev = this;
trk->ConnectNextNext(trk2, 1); // połączenie dwóch dodatkowych odcinków punktami 2
}
// trzeba jeszcze dodać do odpowiedniego segmentu, aby się renderowały z niego pojazdy
trk->location( glm::dvec3{ 0.5 * ( p1 + p2 ) } ); //środek, aby się mogło wyświetlić
simulation::Paths.insert( trk );
simulation::Region->insert( trk );
if( trk2 ) {
trk2->location( trk->location() ); // ten sam środek jest
simulation::Paths.insert( trk2 );
simulation::Region->insert( trk2 );
}
return trk;
};
void TTrack::ConnectPrevPrev(TTrack *pTrack, int typ)
{ //łączenie torów - Point1 własny do Point1 cudzego
if (pTrack)
{ //(pTrack) może być zwrotnicą, a (this) tylko zwykłym odcinkiem
++s_layoutstamp;
trPrev = pTrack;
iPrevDirection = pTrack->eType == tt_Switch ? 0 : typ & 2;
pTrack->trPrev = this;
pTrack->iPrevDirection = 0;
}
}
void TTrack::ConnectPrevNext(TTrack *pTrack, int typ)
{ //łaczenie torów - Point1 własny do Point2 cudzego
if (pTrack)
{
++s_layoutstamp;
trPrev = pTrack;
iPrevDirection = typ | 1; // 1:zwykły lub pierwszy zwrotnicy, 3:drugi zwrotnicy
pTrack->trNext = this;
pTrack->iNextDirection = 0;
if (m_visible)
if (pTrack->m_visible)
if (eType == tt_Normal) // jeśli łączone są dwa normalne
if (pTrack->eType == tt_Normal)
if (fTrackWidth != pTrack->fTrackWidth // Ra: jeśli kolejny ma inne wymiary
||
fTexHeight1 != pTrack->fTexHeight1 ||
fTexWidth != pTrack->fTexWidth || fTexSlope != pTrack->fTexSlope)
pTrack->iTrapezoid |= 2; // to rysujemy potworka
}
}
void TTrack::ConnectNextPrev(TTrack *pTrack, int typ)
{ //łaczenie torów - Point2 własny do Point1 cudzego
if (pTrack)
{
++s_layoutstamp;
trNext = pTrack;
iNextDirection = pTrack->eType == tt_Switch ? 0 : typ & 2;
pTrack->trPrev = this;
pTrack->iPrevDirection = 1;
if (m_visible)
if (pTrack->m_visible)
if (eType == tt_Normal) // jeśli łączone są dwa normalne
if (pTrack->eType == tt_Normal)
if (fTrackWidth != pTrack->fTrackWidth // Ra: jeśli kolejny ma inne wymiary
||
fTexHeight1 != pTrack->fTexHeight1 ||
fTexWidth != pTrack->fTexWidth || fTexSlope != pTrack->fTexSlope)
iTrapezoid |= 2; // to rysujemy potworka
}
}
void TTrack::ConnectNextNext(TTrack *pTrack, int typ)
{ //łaczenie torów - Point2 własny do Point2 cudzego
if (pTrack)
{
++s_layoutstamp;
trNext = pTrack;
iNextDirection = typ | 1; // 1:zwykły lub pierwszy zwrotnicy, 3:drugi zwrotnicy
pTrack->trNext = this;
pTrack->iNextDirection = 1;
}
}
void TTrack::Load(cParser *parser, glm::dvec3 const &pOrigin)
{ // pobranie obiektu trajektorii ruchu
double a1, a2;
std::string str;
size_t i; //,state; //Ra: teraz już nie ma początkowego stanu zwrotnicy we wpisie
std::string token;
parser->getTokens();
*parser >> str; // typ toru
if (str == "normal")
{
eType = tt_Normal;
iCategoryFlag = 1;
}
else if (str == "switch")
{
eType = tt_Switch;
iCategoryFlag = 1;
}
else if (str == "turn")
{ // Ra: to jest obrotnica
eType = tt_Table;
iCategoryFlag = 1;
}
else if (str == "table")
{ // Ra: obrotnica, przesuwnica albo wywrotnica
eType = tt_Table;
iCategoryFlag = 1;
}
else if (str == "road")
{
eType = tt_Normal;
iCategoryFlag = 2;
}
else if (str == "cross")
{ // Ra: to będzie skrzyżowanie dróg
eType = tt_Cross;
iCategoryFlag = 2;
}
else if (str == "river")
{
eType = tt_Normal;
iCategoryFlag = 4;
}
else if (str == "tributary")
{
// dopływ: no path of it was ever made, the simulator falling over it as it loaded. a river of its first path now, the
// second one kept and written back
ErrorLog(std::format(R"(Bad track: tributary "{}" in file "{}" (line {}) is drawn and run on as a river of its first path)", m_name, parser->Name(), parser->Line()));
eType = tt_Normal;
iCategoryFlag = 4;
m_tributary = true;
}
else
eType = tt_Unknown; // left out by the loader
if (Global.iWriteLogEnabled & 4)
WriteLog(str);
parser->getTokens(4);
float discard {};
*parser
>> discard
>> fTrackWidth
>> fFriction
>> fSoundDistance;
if (eType == tt_Switch)
{
fSoundDistance = 10.0f;
}
fTrackWidth2 = fTrackWidth; // rozstaw/szerokość w punkcie 2, na razie taka sama
parser->getTokens(2);
*parser
>> iQualityFlag
>> iDamageFlag;
if (iDamageFlag & 128)
iAction |= 0x80; // flaga wykolejania z powodu uszkodzenia
parser->getTokens();
*parser >> str; // environment
if (str == "flat")
eEnvironment = e_flat;
else if (str == "mountains" || str == "mountain")
eEnvironment = e_mountains;
else if (str == "canyon")
eEnvironment = e_canyon;
else if (str == "tunnel")
eEnvironment = e_tunnel;
else if (str == "bridge")
eEnvironment = e_bridge;
else if (str == "bank")
eEnvironment = e_bank;
else
{
eEnvironment = e_unknown;
Error( "Unknown track environment: \"" + str + "\"" );
}
parser->getTokens();
*parser >> token;
m_visible = token.compare("vis") == 0; // visible
if (m_visible)
{
parser->getTokens();
*parser >> str; // railtex
replace_slashes(str);
m_material1 = str == "none" ? null_handle : GfxRenderer->Fetch_Material(str);
parser->getTokens();
*parser >> fTexLength; // tex tile length
if (fTexLength < 0.01)
fTexLength = 4; // Ra: zabezpiecznie przed zawieszeniem
parser->getTokens();
*parser >> str; // sub || railtex
replace_slashes(str);
m_material2 = str == "none" ? null_handle : GfxRenderer->Fetch_Material(str);
parser->getTokens(3);
*parser
>> fTexHeight1
>> fTexWidth
>> fTexSlope;
if (iCategoryFlag & 4)
fTexHeight1 = -fTexHeight1; // rzeki mają wysokość odwrotnie niż drogi
}
else if (Global.iWriteLogEnabled & 4)
WriteLog("unvis");
Init(); // ustawia SwitchExtension
// path data
// all subtypes contain at least one path
m_paths.emplace_back();
m_paths.back().deserialize( *parser, pOrigin );
switch( eType ) {
case tt_Switch:
case tt_Cross:
case tt_Tributary: {
// these subtypes contain additional path
m_paths.emplace_back();
m_paths.back().deserialize( *parser, pOrigin );
break;
}
default: {
break;
}
}
if( m_tributary ) {
// the second path of a tributary, kept to be written back
m_paths.emplace_back();
m_paths.back().deserialize( *parser, pOrigin );
}
// optional attributes
parser->getTokens();
*parser >> token;
str = token;
while (str != "endtrack")
{
if (str == "event0")
{
parser->getTokens();
*parser >> token;
m_events0.emplace_back( token, nullptr );
}
else if (str == "event1")
{
parser->getTokens();
*parser >> token;
m_events1.emplace_back( token, nullptr );
}
else if (str == "event2")
{
parser->getTokens();
*parser >> token;
m_events2.emplace_back( token, nullptr );
}
else if (str == "eventall0")
{
parser->getTokens();
*parser >> token;
m_events0all.emplace_back( token, nullptr );
}
else if (str == "eventall1")
{
parser->getTokens();
*parser >> token;
m_events1all.emplace_back( token, nullptr );
}
else if (str == "eventall2")
{
parser->getTokens();
*parser >> token;
m_events2all.emplace_back( token, nullptr );
}
else if (str == "velocity")
{
parser->getTokens();
*parser >> fVelocity; //*0.28; McZapkie-010602
if (SwitchExtension) // jeśli tor ruchomy
if (std::abs(fVelocity) >= 1.0) //żeby zero nie ograniczało dożywotnio
// zapamiętanie głównego ograniczenia; a np. -40 ogranicza tylko na bok
SwitchExtension->fVelocity = static_cast<float>(fVelocity);
}
else if (str == "isolated")
{ // obwód izolowany, do którego tor należy
parser->getTokens();
*parser >> token;
Isolated.push_back(TIsolated::Find(token));
}
else if (str == "angle1")
{ // kąt ścięcia końca od strony 1
// NOTE: not used/implemented
parser->getTokens();
*parser >> a1;
//Segment->AngleSet(0, a1);
}
else if (str == "angle2")
{ // kąt ścięcia końca od strony 2
// NOTE: not used/implemented
parser->getTokens();
*parser >> a2;
//Segment->AngleSet(1, a2);
}
else if (str == "fouling1")
{ // wskazanie modelu ukresu w kierunku 1
// NOTE: not used/implemented
parser->getTokens();
*parser >> token;
// nFouling[0]=
}
else if (str == "fouling2")
{ // wskazanie modelu ukresu w kierunku 2
// NOTE: not used/implemented
parser->getTokens();
*parser >> token;
// nFouling[1]=
}
else if (str == "overhead")
{ // informacja o stanie sieci: 0-jazda bezprądowa, >0-z opuszczonym i ograniczeniem prędkości
parser->getTokens();
*parser >> fOverhead;
if (fOverhead > 0.0)
iAction |= 0x40; // flaga opuszczenia pantografu (tor uwzględniany w skanowaniu jako
// ograniczenie dla pantografujących)
}
else if( str == "vradius" ) {
// y-axis track radius
// NOTE: not used/implemented
parser->getTokens();
*parser >> fVerticalRadius;
}
else if( str == "trackbed" ) {
// switch trackbed texture
auto const trackbedtexture { parser->getToken<std::string>() };
if( eType == tt_Switch ) {
SwitchExtension->m_material3 = GfxRenderer->Fetch_Material( trackbedtexture );
}
}
else if( str == "railprofile" ) {
// rail profile
auto const railprofile { parser->getToken<std::string>() };
if( iCategoryFlag == 1 ) {
m_profile1 = fetch_track_rail_profile( railprofile );
}
}
else if( str == "frogs" ) {
// frog and check rails made from the rails of the switch
if( eType == tt_Switch ) {
SwitchExtension->m_frogs = true;
}
}
else if( str == "movablenose" ) {
// the frog of the switch with a movable nose
if( eType == tt_Switch ) {
SwitchExtension->m_movablenose = true;
}
}
else if( str == "blades" ) {
// blades <heel> <throw>: where the moving blades of the switch end and how far their tips move over, 0: from the shape of the switch
auto const heel { parser->getToken<double>() };
auto const bladethrow { parser->getToken<double>() };
if( eType == tt_Switch ) {
SwitchExtension->m_bladeheel = std::max( 0.0, heel );
SwitchExtension->m_bladethrow = std::max( 0.0, bladethrow );
}
}
else if( str == "timbermodel" ) {
// timbermodel <model> <skin>: the model of the timbers under the switch or the crossing the track is part of, put together
// from its submodels begin, main and end, or drawn whole; skin none: the textures of the model
auto modelpath { parser->getToken<std::string>( false ) };
auto skinpath { parser->getToken<std::string>( false ) };
replace_slashes( modelpath );
m_timber_model_name = modelpath;
m_timber_skin_name = ( skinpath == "none" ? std::string{} : skinpath );
}
else if( str == "uneven" ) {
// uneven <mm>[;<mm>...]: see TrackUneven.h. The semicolons stay in the token
auto const values { parser->getToken<std::string>( false, "\n\r\t " ) };
if( ( eType == tt_Normal || eType == tt_Switch ) && iCategoryFlag == 1 ) {
m_uneven = track_uneven::read_attribute( values, eType == tt_Switch );
}
}
else if( str == "friction" ) {
// memory cell holding friction value modifiers
m_friction.first = parser->getToken<std::string>();
}
else if( str == "sleepermodel" ) {
// sleepermodel <frequency> <model> <skin> <offsetX> <offsetY> <offsetZ> <ballastZ>
// - frequency: meters between consecutive sleeper instances (must be > 0)
// - model: path to the .e3d sleeper model
// - skin: replacable skin path, or "none" for the model's defaults
// - offset: local-space offset applied per-instance (x=left/right, y=forward/back, z=up/down)
// - ballastZ: vertical shift applied to the auto-generated trackbed (ballast). negative pushes ballast down.
float frequency { 0.f };
float offsetx { 0.f }, offsety { 0.f }, offsetz { 0.f };
float ballastz { 0.f };
parser->getTokens( 1, false ); *parser >> frequency;
auto modelpath { parser->getToken<std::string>( false ) };
auto skinpath { parser->getToken<std::string>( false ) };
parser->getTokens( 3, false ); *parser >> offsetx >> offsety >> offsetz;
parser->getTokens( 1, false ); *parser >> ballastz;
if( frequency <= 0.01f ) {
ErrorLog( "Bad track: invalid sleepermodel frequency (" + std::to_string( frequency ) + ") for track \"" + m_name + "\"" );
}
else {
replace_slashes( modelpath );
m_sleeper_enabled = true;
m_sleeper_frequency = frequency;
m_sleeper_model_name = modelpath;
m_sleeper_skin_name = skinpath;
m_sleeper_offset = glm::vec3( offsetx, offsety, offsetz );
m_sleeper_ballast_z = ballastz;
// model and skin are resolved (and instance transforms baked) in build_sleeper_transforms,
// called after segment initialisation so the path geometry is final.
}
}
else if( str == "pieces1" || str == "pieces2" ) {
// consecutive parts of a path, kept after the path itself for versions which know only the path
auto const index { static_cast<std::size_t>( str.back() - '1' ) };
auto const count { parser->getToken<int>() };
std::vector<segment_data> pieces;
for( int piece = 0; piece < count; ++piece ) {
pieces.emplace_back();
pieces.back().deserialize( *parser, pOrigin );
}
if( index < m_paths.size() ) {
m_paths[ index ].pieces = std::move( pieces );
}
else {
ErrorLog( "Bad track: \"" + str + "\" defined for track \"" + m_name + "\" which has no such path" );
}
}
else
ErrorLog("Bad track: unknown property: \"" + str + "\" defined for track \"" + m_name + "\"");
parser->getTokens();
*parser >> token;
str = token;
}
// a switch made sets itself straight with Switch(0), which overwrites fVelocity from SwitchExtension->fVelocity; the velocity read
// from the scenery is put back after it
auto const velocity { fVelocity };
init_segments( true );
// made with no unevenness, which is read with the attributes and goes onto them by making them again
if( is_uneven() ) {
init_segments( false );
}
if( SwitchExtension ) {
fVelocity = velocity;
}
// alternatywny zapis nazwy odcinka izolowanego - po znaku "@" w nazwie toru
if ((i = m_name.find("@")) != std::string::npos && i < m_name.length())
{
Isolated.push_back(TIsolated::Find(m_name.substr(i + 1, m_name.length())));
m_name = m_name.substr(0, i - 1); // usunięcie z nazwy
}
if( CurrentSegment() == nullptr ) {
// of an unknown type, no path of it is made
return;
}
update_location();
// sleeper transforms are baked later in create_geometry(), once the owning cell has
// assigned this track its m_origin (otherwise the local-space matrices would be relative
// to a stale origin and the renderer would draw sleepers in the wrong place).
}
void TTrack::update_location() {
location( (
CurrentSegment()->FastGetPoint_0()
+ CurrentSegment()->FastGetPoint( 0.5 )
+ CurrentSegment()->FastGetPoint_1() )
/ 3.0 );
}
// "prostowanie" prostych z kontrolnymi, dokładność 2cm: a path is a straight where its first control vector lies along the chord, whatever
// the second one does, as the sceneries are made for. Length2 is better than length for comparing because it does not require sqrt
bool TTrack::straightened( glm::dvec3 const &P1, glm::dvec3 const &Cp1, glm::dvec3 const &P2 ) {
return glm::length2( ( P1 + P1 + P2 ) / 3.0 - P1 - Cp1 ) < sq( 0.02 )
|| glm::length2( ( P1 + P2 + P2 ) / 3.0 - P2 + Cp1 ) < sq( 0.02 );
}
void TTrack::init_segments( bool const Initial ) {
glm::dvec3 p1, p2, cp1, cp2, p3, p4, cp3, cp4; // dodatkowe punkty potrzebne do skrzyżowań
double r1, r2, r3, r4;
double segsize = 5.0; // długość odcinka segmentowania
fTexHeight1 -= fTexHeightOffset;
fTexHeightOffset = 0.f;
iTrapezoid = 0;
++s_layoutstamp;
if( eType == tt_Switch && SwitchExtension ) {
SwitchExtension->Segments[ 0 ]->set_uneven( is_uneven() );
SwitchExtension->Segments[ 1 ]->set_uneven( is_uneven(), 1 );
}
else if( Segment ) {
Segment->set_uneven( is_uneven() );
}
switch (eType) {
// Ra: łuki segmentowane co 5m albo 314-kątem foremnym
case tt_Table: {
// obrotnica jest prawie jak zwykły tor
iAction |= 2; // flaga zmiany położenia typu obrotnica
}
case tt_Normal: {
// pobranie współrzędnych P1
auto const &path { m_paths[ 0 ] };
p1 = path.points[ segment_data::point::start ];
// pobranie współrzędnych punktów kontrolnych
cp1 = path.points[ segment_data::point::control1 ];
cp2 = path.points[ segment_data::point::control2 ];
// pobranie współrzędnych P2
p2 = path.points[ segment_data::point::end ];
r1 = path.rolls[ 0 ];
r2 = path.rolls[ 1 ];
fRadius = std::abs( path.radius ); // we wpisie może być ujemny
if (iCategoryFlag & 1)
{ // zero na główce szyny
// TODO: delay these calculations unti rail profile and thus height is known
auto const railheight { 0.18 };
p1.y += railheight;
p2.y += railheight;
// na przechyłce doliczyć jeszcze pół przechyłki
}
if( straightened( p1, cp1, p2 ) ) {
// "prostowanie" prostych z kontrolnymi, dokładność 2cm
cp1 = cp2 = glm::dvec3(0, 0, 0);
}
if( fRadius != 0 ) {
// gdy podany promień
segsize =
std::clamp(
std::abs( fRadius ) * ( 0.02 / Global.SplineFidelity ),
2.0 / Global.SplineFidelity,
10.0 / Global.SplineFidelity );
}
else {
// HACK: crude check whether claimed straight is an actual straight piece
if (cp1 == glm::dvec3() && cp2 == glm::dvec3())
{
segsize = 10.0; // for straights, 10m per segment works good enough
}
else {
// HACK: divide roughly in 10 segments.
segsize =
std::clamp(
glm::length( p1 - p2 ) * 0.1,
2.0 / Global.SplineFidelity,
10.0 / Global.SplineFidelity );
}
}
if (cp1 == glm::dvec3() && cp2 == glm::dvec3())
{
// Ra: hm, czasem dla prostego są podane...
// gdy prosty, kontrolne wyliczane przy zmiennej przechyłce
Segment->Init( p1, p2, segsize, r1, r2 );
}
else {
// gdy łuk (ustawia bCurve=true)
Segment->Init( p1, cp1 + p1, cp2 + p2, p2, segsize, r1, r2 );
}
if (r1 != 0 || r2 != 0)
iTrapezoid = 1; // są przechyłki do uwzględniania w rysowaniu
if (eType == tt_Table) // obrotnica ma doklejkę
{ // SwitchExtension=new TSwitchExtension(this,1); //dodatkowe zmienne dla obrotnicy
SwitchExtension->Segments[0]->Init(p1, p2, segsize, r1, r2 ); // kopia oryginalnego toru
}
else if (iCategoryFlag & 2)
if (m_material1 && fTexLength)
{ // dla drogi trzeba ustalić proporcje boków nawierzchni
auto const &texture1 { GfxRenderer->Texture( GfxRenderer->Material( m_material1 )->GetTexture(0) ) };
if( texture1.get_height() > 0 ) {
fTexRatio1 = static_cast<float>( texture1.get_width() ) / static_cast<float>( texture1.get_height() ); // proporcja boków
}
auto const &texture2 { GfxRenderer->Texture( GfxRenderer->Material( m_material2 )->GetTexture(0) ) };
if( texture2.get_height() > 0 ) {
fTexRatio2 = static_cast<float>( texture2.get_width() ) / static_cast<float>( texture2.get_height() ); // proporcja boków
}
}
break;
}
case tt_Cross: {
// skrzyżowanie dróg - 4 punkty z wektorami kontrolnymi
// segsize = 1.0; // specjalne segmentowanie ze względu na małe promienie
}
case tt_Tributary: // dopływ
case tt_Switch: { // zwrotnica
iAction |= 1; // flaga zmiany położenia typu zwrotnica lub skrzyżowanie dróg
// problemy z animacją iglic powstaje, gdzy odcinek prosty ma zmienną przechyłkę
// wtedy dzieli się na dodatkowe odcinki (po 0.2m, bo R=0) i animację diabli biorą
// Ra: na razie nie podejmuję się przerabiania iglic
// SwitchExtension=new TSwitchExtension(this,eType==tt_Cross?6:2); //zwrotnica ma doklejkę
auto const &path { m_paths[ 0 ] };
p1 = path.points[ segment_data::point::start ];
// pobranie współrzędnych punktów kontrolnych
cp1 = path.points[ segment_data::point::control1 ];
cp2 = path.points[ segment_data::point::control2 ];
// pobranie współrzędnych P2
p2 = path.points[ segment_data::point::end ];
r1 = path.rolls[ 0 ];
r2 = path.rolls[ 1 ];
fRadiusTable[0] = std::abs( path.radius ); // we wpisie może być ujemny
if (iCategoryFlag & 1)
{ // zero na główce szyny
// TODO: delay these calculations unti rail profile and thus height is known
auto const railheight { 0.18 };
p1.y += railheight;
p2.y += railheight;
// na przechyłce doliczyć jeszcze pół przechyłki?
}
if( eType != tt_Cross ) {
// dla skrzyżowań muszą być podane kontrolne
// length2 is better than length for comparing because it does not require sqrt function
if( straightened( p1, cp1, p2 ) ) {
// "prostowanie" prostych z kontrolnymi, dokładność 2cm
cp1 = cp2 = glm::dvec3(0, 0, 0);
}
}
if( fRadiusTable[ 0 ] != 0 ) {
// gdy podany promień
segsize =
std::clamp(
std::abs( fRadiusTable[ 0 ] ) * ( 0.02 / Global.SplineFidelity ),
2.0 / Global.SplineFidelity,
10.0 / Global.SplineFidelity );
}
else {
// HACK: crude check whether claimed straight is an actual straight piece
if (cp1 == glm::dvec3() && cp2 == glm::dvec3())
{
segsize = 10.0; // for straights, 10m per segment works good enough
}
else {
// HACK: divide roughly in 10 segments.
segsize =
std::clamp(
glm::length( p1 - p2 ) * 0.1,
2.0 / Global.SplineFidelity,
10.0 / Global.SplineFidelity );
}
}
if (cp1 == glm::dvec3() && cp2 == glm::dvec3())
{
// Ra: hm, czasem dla prostego są podane...
// gdy prosty, kontrolne wyliczane przy zmiennej przechyłce
SwitchExtension->Segments[ 0 ]->Init( p1, p2, segsize, r1, r2 );
}
else {
// gdy łuk (ustawia bCurve=true)
SwitchExtension->Segments[ 0 ]->Init( p1, cp1 + p1, cp2 + p2, p2, segsize, r1, r2 );
}
auto const &path2 { m_paths[ 1 ] };
p3 = path2.points[ segment_data::point::start ];
// pobranie współrzędnych punktów kontrolnych
cp3 = path2.points[ segment_data::point::control1 ];
cp4 = path2.points[ segment_data::point::control2 ];
// pobranie współrzędnych P2
p4 = path2.points[ segment_data::point::end ];
r3 = path2.rolls[ 0 ];
r4 = path2.rolls[ 1 ];
fRadiusTable[1] = std::abs( path2.radius ); // we wpisie może być ujemny
if (iCategoryFlag & 1)
{ // zero na główce szyny
// TODO: delay these calculations unti rail profile and thus height is known
auto const railheight{ 0.18 };
p3.y += railheight;
p4.y += railheight;
// na przechyłce doliczyć jeszcze pół przechyłki?
}
if( eType != tt_Cross ) {
// dla skrzyżowań muszą być podane kontrolne
// length2 is better than length for comparing because it does not require sqrt function
if( straightened( p3, cp3, p4 ) ) {
// "prostowanie" prostych z kontrolnymi, dokładność 2cm
cp3 = cp4 = glm::dvec3(0, 0, 0);
}
}
if( fRadiusTable[ 1 ] != 0 ) {
// gdy podany promień
segsize =
std::clamp(
std::abs( fRadiusTable[ 1 ] ) * ( 0.02 / Global.SplineFidelity ),
2.0 / Global.SplineFidelity,
10.0 / Global.SplineFidelity );
}
else {
// HACK: crude check whether claimed straight is an actual straight piece
if (cp3 == glm::dvec3() && cp4 == glm::dvec3())
{
segsize = 10.0; // for straights, 10m per segment works good enough
}
else {
// HACK: divide roughly in 10 segments.
segsize =
std::clamp(
glm::length( p3 - p4 ) * 0.1,
2.0 / Global.SplineFidelity,
10.0 / Global.SplineFidelity );
}
}
if (cp3 == glm::dvec3() && cp4 == glm::dvec3())
{
// Ra: hm, czasem dla prostego są podane...
// gdy prosty, kontrolne wyliczane przy zmiennej przechyłce
SwitchExtension->Segments[ 1 ]->Init( p3, p4, segsize, r3, r4 );
}
else {
if( eType != tt_Cross ) {
SwitchExtension->Segments[ 1 ]->Init( p3, p3 + cp3, p4 + cp4, p4, segsize, r3, r4 );
}
else {
// dla skrzyżowania dróg dać odwrotnie końce, żeby brzegi generować lewym
SwitchExtension->Segments[ 1 ]->Init( p4, p4 + cp4, p3 + cp3, p3, segsize, r4, r3 ); // odwrócony
}
}
if (eType == tt_Cross)
{ // Ra 2014-07: dla skrzyżowań będą dodatkowe segmenty
SwitchExtension->Segments[2]->Init(p2, cp2 + p2, cp4 + p4, p4, segsize, r2, r4); // z punktu 2 do 4
auto p1p3 = p3 - p1;
if (glm::length2(p1p3) < 0.01) // gdy mniej niż 10cm, to mamy skrzyżowanie trzech dróg
SwitchExtension->iRoads = 3;
else // dla 4 dróg będą dodatkowe 3 segmenty
{
SwitchExtension->Segments[3]->Init(p4, p4 + cp4, p1 + cp1, p1, segsize, r4, r1); // z punktu 4 do 1
SwitchExtension->Segments[4]->Init(p1, p1 + cp1, p3 + cp3, p3, segsize, r1, r3); // z punktu 1 do 3
SwitchExtension->Segments[5]->Init(p3, p3 + cp3, p2 + cp2, p2, segsize, r3, r2); // z punktu 3 do 2
}
}
if( eType == tt_Switch ) {
for( std::size_t index = 0; index < 2; ++index ) {
chain_switch_pieces( *this, index );
}
// the profiles of the switch are made at the mean of the rolls of its paths; lofted, they're turned from it to the roll of
// each path along it, so a switch on a cant ramp follows the ramp to its ends
float mean1 { 0.f };
float mean2 { 0.f };
profile_rolls( mean1, mean2 );
for( std::size_t index = 0; index < 2; ++index ) {
SwitchExtension->Segments[ index ]->set_baked_roll( mean1 );
}
}
if( Initial ) {
Switch(0);
} // na stałe w położeniu 0 - nie ma początkowego stanu zwrotnicy we wpisie
if( eType == tt_Switch )
// Ra: zamienić później na iloczyn wektorowy
{
glm::dvec3 v1, v2;
double a1, a2;
v1 = SwitchExtension->Segments[0]->FastGetPoint_1()
- SwitchExtension->Segments[0]->FastGetPoint_0();
v2 = SwitchExtension->Segments[1]->FastGetPoint_1()
- SwitchExtension->Segments[1]->FastGetPoint_0();
a1 = atan2(v1.x, v1.z);
a2 = atan2(v2.x, v2.z);
a2 = a2 - a1;
while (a2 > M_PI)
a2 = a2 - 2 * M_PI;
while (a2 < -M_PI)
a2 = a2 + 2 * M_PI;
SwitchExtension->RightSwitch = a2 < 0; // lustrzany układ OXY...
}
break;
}
}
}
bool TTrack::AssignEvents() {
bool lookupfail { false };
std::vector< std::pair< std::string, event_sequence * > > const eventsequences {
{ "event0", &m_events0 }, { "eventall0", &m_events0all },
{ "event1", &m_events1 }, { "eventall1", &m_events1all },
{ "event2", &m_events2 }, { "eventall2", &m_events2all } };
for( auto &eventsequence : eventsequences ) {
for( auto &event : *eventsequence.second ) {
event.second = simulation::Events.FindEvent( event.first );
if( event.second != nullptr ) {
m_events = true;
}
else {
ErrorLog( "Bad track: " + ( m_name.empty() ? "unnamed track" : "\"" + m_name + "\"" ) + " can't find assigned event \"" + event.first + "\"" );
lookupfail = true;
}
}
}
auto const trackname { name() };
if (Global.iHiddenEvents & 1
&& false == trackname.empty() ) {
// jeśli podana jest nazwa torów, można szukać eventów skojarzonych przez nazwę
for( auto &eventsequence : eventsequences ) {
auto *event = simulation::Events.FindEvent( trackname + ':' + eventsequence.first );
if( event != nullptr ) {
// HACK: auto-associated events come with empty lookup string, to avoid including them in the text format export
eventsequence.second->emplace_back( "", event );
m_events = true;
}
}
}
return lookupfail == false;
}
bool TTrack::AssignForcedEvents(basic_event *NewEventPlus, basic_event *NewEventMinus)
{ // ustawienie eventów sygnalizacji rozprucia
if (SwitchExtension)
{
if (NewEventPlus)
SwitchExtension->evPlus = NewEventPlus;
if (NewEventMinus)
SwitchExtension->evMinus = NewEventMinus;
return true;
}
return false;
};
void TTrack::QueueEvents( event_sequence const &Events, TDynamicObject const *Owner ) {
for( auto const &event : Events ) {
if( event.second != nullptr ) {
simulation::Events.AddToQuery( event.second, Owner );
}
}
}
void TTrack::QueueEvents( event_sequence const &Events, TDynamicObject const *Owner, double const Delaylimit ) {
for( auto const &event : Events ) {
if( event.second != nullptr
&& event.second->m_delay <= Delaylimit ) {
simulation::Events.AddToQuery( event.second, Owner );
}
}
}
std::string TTrack::RemoteIsolatedName()
{ // podaje nazwę odcinka izolowanego, jesli nie ma on jeszcze przypisanych zdarzeń
for (const TIsolated *iso : Isolated)
if (!iso->evBusy && !iso->evFree)
return iso->asName;
return "";
};
// ABu: przeniesione z Path.h i poprawione!!!
bool TTrack::AddDynamicObject(TDynamicObject *Dynamic)
{ // dodanie pojazdu do trajektorii
// Ra: tymczasowo wysyłanie informacji o zajętości konkretnego toru
// Ra: usunąć po upowszechnieniu się odcinków izolowanych
if (iCategoryFlag & 0x100) // jeśli usuwaczek
{
Dynamic->MyTrack = nullptr; // trzeba by to uzależnić od kierunku ruchu...
return true;
}
if( Global.iMultiplayer ) {
// jeśli multiplayer
if( true == Dynamics.empty() ) {
// pierwszy zajmujący
if( m_name != "none" ) {
// przekazanie informacji o zajętości toru
multiplayer::WyslijString( m_name, 8 );
}
}
}
Dynamics.emplace_back( Dynamic );
Dynamic->MyTrack = this; // ABu: na ktorym torze jesteśmy
if( Dynamic->iOverheadMask ) {
// jeśli ma pantografy
Dynamic->OverheadTrack( fOverhead ); // przekazanie informacji o jeździe bezprądowej na tym odcinku toru
}
return true;
};
const int numPts = 4;
bool TTrack::CheckDynamicObject(TDynamicObject *Dynamic)
{ // sprawdzenie, czy pojazd jest przypisany do toru
for( auto dynamic : Dynamics ) {
if( dynamic == Dynamic ) {
return true;
}
}
return false;
};
bool TTrack::RemoveDynamicObject(TDynamicObject *Dynamic)
{ // usunięcie pojazdu z listy przypisanych do toru
bool result = false;
if( *Dynamics.begin() == Dynamic ) {
// most likely the object getting removed is at the front...
Dynamics.pop_front();
result = true;
}
else if( *--Dynamics.end() == Dynamic ) {
// ...or the back of the queue...
Dynamics.pop_back();
result = true;
}
else {
// ... if these fail, check all objects one by one
for( auto idx = Dynamics.begin(); idx != Dynamics.end(); /*iterator advancement is inside the loop*/ ) {
if( *idx == Dynamic ) {
idx = Dynamics.erase( idx );
result = true;
break; // object are unique, so we can bail out here.
}
else {
++idx;
}
}
}
if( Global.iMultiplayer ) {
// jeśli multiplayer
if( true == Dynamics.empty() ) {
// jeśli już nie ma żadnego
if( m_name != "none" ) {
// przekazanie informacji o zwolnieniu toru
multiplayer::WyslijString( m_name, 9 );
}
}
}
return result;
}
bool TTrack::InMovement()
{ // tory animowane (zwrotnica, obrotnica) mają SwitchExtension
if (SwitchExtension)
{
if (eType == tt_Switch)
return SwitchExtension->bMovement; // ze zwrotnicą łatwiej
if (eType == tt_Table)
if (SwitchExtension->pModel)
{
if (!SwitchExtension->CurrentIndex)
return false; // 0=zablokowana się nie animuje
// trzeba każdorazowo porównywać z kątem modelu
auto ac = SwitchExtension->pModel ? SwitchExtension->pModel->GetContainer() : nullptr;
return ac ?
ac->AngleGet() != SwitchExtension->fOffset ||
!(ac->TransGet() == SwitchExtension->vTrans) :
false;
// return true; //jeśli jest taki obiekt
}
}
return false;
};
void TTrack::RaAssign( TAnimModel *am, basic_event *done, basic_event *joined )
{ // Ra: wiązanie toru z modelem obrotnicy
if (eType == tt_Table)
{
SwitchExtension->pModel = am;
SwitchExtension->evMinus = done; // event zakończenia animacji (zadanie nowej przedłuża)
SwitchExtension->evPlus = joined; // event potwierdzenia połączenia (gdy nie znajdzie, to się nie połączy)
if( am != nullptr && am->GetContainer() ) {// może nie być?
am->GetContainer()->EventAssign( done ); // zdarzenie zakończenia animacji
}
}
};
void TTrack::create_map_geometry(std::vector<gfx::basic_vertex> &Bank, const gfx::geometrybank_handle Extra)
{
if (iCategoryFlag != 1)
return; // only tracks for now
gfx::userdata_array empty_userdata{};
switch (eType)
{
case tt_Normal: {
std::vector<gfx::basic_vertex> vertices;
Segment->render_lines(vertices, 0.5f);
std::copy(vertices.begin(), vertices.end(), std::back_inserter(Bank));
extra_map_geometry = GfxRenderer->Insert(vertices, empty_userdata, Extra, GL_LINES);
break;
}
case tt_Switch: {
std::vector<gfx::basic_vertex> vertices;
SwitchExtension->Segments[0]->render_lines(vertices, 0.5f);
std::copy(vertices.begin(), vertices.end(), std::back_inserter(Bank));
SwitchExtension->map_geometry[0] = GfxRenderer->Insert(vertices, empty_userdata, Extra, GL_LINES);
vertices.clear();
SwitchExtension->Segments[1]->render_lines(vertices, 0.5f);
std::copy(vertices.begin(), vertices.end(), std::back_inserter(Bank));
SwitchExtension->map_geometry[1] = GfxRenderer->Insert(vertices, empty_userdata, Extra, GL_LINES);
break;
}
default:
break;
}
}
TTrack *TTrack::Next(TTrack *visitor) {
if (eType == tt_Normal) {
if (trNext != visitor)
return trNext;
else
return trPrev;
} else if (eType == tt_Switch) {
int state = GetSwitchState();
if (SwitchExtension->pPrevs[0] == visitor
|| SwitchExtension->pPrevs[1] == visitor)
{
// we came from 'previous' side
return SwitchExtension->pNexts[state];
}
if (SwitchExtension->pNexts[0] == visitor
|| SwitchExtension->pNexts[1] == visitor)
{
// we came from 'next' side
return SwitchExtension->pPrevs[state];
}
}
return nullptr;
}
double TTrack::ActiveLength() {
if (eType == tt_Normal) {
return Segment->GetLength();
} else if (eType == tt_Switch) {
if (GetSwitchState() == 0)
return SwitchExtension->Segments[0]->GetLength();
else
return SwitchExtension->Segments[1]->GetLength();
}
return 1.0f;
}
void TTrack::get_map_active_paths(map_colored_paths &handles)
{
if (iCategoryFlag != 1)
return;
if (eType == tt_Switch) {
if (GetSwitchState() == 0)
handles.switches.push_back(SwitchExtension->map_geometry[0]);
else
handles.switches.push_back(SwitchExtension->map_geometry[1]);
}
}
void TTrack::get_map_paths_for_state(map_colored_paths &handles, int state)
{
if (iCategoryFlag != 1 || eType != tt_Switch)
return;
handles.highlighted.push_back(SwitchExtension->map_geometry[state]);
}
void TTrack::get_map_future_paths(map_colored_paths &handles) {
if (iCategoryFlag != 1)
return;
if (!Dynamics.empty()) {
if (eType == tt_Switch) {
if (GetSwitchState() == 0)
handles.occupied.push_back(SwitchExtension->map_geometry[0]);
else
handles.occupied.push_back(SwitchExtension->map_geometry[1]);
} else if (eType == tt_Normal) {
handles.occupied.push_back(extra_map_geometry);
}
static int stamp = 0;
stamp++;
float distance = Global.map_highlight_distance;
TTrack *track = trPrev;
TTrack *visitor = this;
while (distance > 0.0f && track && track->iterate_stamp != stamp) {
handles.future.push_back(track->extra_map_geometry);
track->iterate_stamp = stamp;
distance -= track->ActiveLength();
TTrack *tmp = track;
track = track->Next(visitor);
visitor = tmp;
}
distance = Global.map_highlight_distance;
stamp++;
track = trNext;
visitor = this;
while (distance > 0.0f && track && track->iterate_stamp != stamp) {
handles.future.push_back(track->extra_map_geometry);
track->iterate_stamp = stamp;
distance -= track->ActiveLength();
TTrack *tmp = track;
track = track->Next(visitor);
visitor = tmp;
}
}
}
glm::vec3 TTrack::get_nearest_point(const glm::dvec3 &point) const
{
if (eType == tt_Normal) {
return Segment->get_nearest_point(point);
}
else if (eType == tt_Switch) {
glm::vec3 nearest;
float min = std::numeric_limits<float>::max();
for (size_t i = 0; i < 2; i++) {
glm::dvec3 p = SwitchExtension->Segments[i]->get_nearest_point(point);
float dist2 = glm::distance2(p, point);
if (dist2 < min) {
nearest = p;
min = dist2;
}
}
return nearest;
}
return glm::vec3(NAN);
}
namespace {
// each path of the switch with a material of its own, the first one first, handed on with its material
template <typename Lay_>
void for_each_railed_path( TTrack const &Track, Lay_ const &Lay ) {
for( int path = 0; path < 2; ++path ) {
auto const material { path ? Track.m_material2 : Track.m_material1 };
if( material == 0 ) {
continue;
}
Lay( path, material );
}
}
} // namespace
// wypełnianie tablic VBO
void TTrack::rebuild_geometry( gfx::geometrybank_handle const &Bank ) {
m_drawnrun = {};
track_rails::forget();
auto const erase = [ this ]( gfx::geometry_handle const &Chunk ) {
if( SwitchExtension
&& std::ranges::any_of( SwitchExtension->m_nosechunks, [ &Chunk ]( auto const &Pooled ) { return Pooled.handle == Chunk; } ) ) {
return;
}
GfxRenderer->Erase( Chunk );
};
for( auto const *geometry : { &Geometry1, &Geometry2, &GeometryCut1, &GeometryCut2 } ) {
std::ranges::for_each( *geometry, erase );
}
for( auto const &tread : GeometryTreads ) {
std::ranges::for_each( tread.geometry, erase );
std::ranges::for_each( tread.cuts, erase );
}
Geometry1.clear();
Geometry2.clear();
GeometryCut1.clear();
GeometryCut2.clear();
GeometryTreads.clear();
if( SwitchExtension ) {
erase( SwitchExtension->Geometry3 );
SwitchExtension->Geometry3 = gfx::geometry_handle{};
}
m_sleeper_local_transforms.clear();
// the sleepers of this track and of the tracks around depend on where it runs
m_sleepers3d.dirty = true;
track_sleepers::unsettle_around( *this );
if( Bank == null_handle ) { return; }
create_geometry( Bank );
}
void TTrack::create_geometry( gfx::geometrybank_handle const &Bank ) {
gfx::userdata_array empty_userdata;
// the rails of a frog with a movable nose are laid again as it moves over, in the same chunks
auto const movable { eType == tt_Switch && SwitchExtension && SwitchExtension->m_movablenose };
track_rails::reused_chunks const reuse { movable ? &SwitchExtension->m_nosechunks : nullptr };
if( eType == tt_Switch && SwitchExtension ) {
SwitchExtension->m_nosethrow = ( Bank != null_handle ? nose_throw() : -1.0 );
}
share_joints();
m_sleepers3d.active = track_sleepers::lays( *this );
if( rail_phase( 0.0 ) >= 0.0 ) {
m_drawnrun = m_railrun;
}
// bake per-instance sleeper transforms now that the owning cell has assigned m_origin.
// safe to call here even if the track has no sleepermodel (early-outs internally).
if( m_sleeper_enabled && m_sleeper_local_transforms.empty() ) {
build_sleeper_transforms();
}
switch (iCategoryFlag & 15)
{
case 1: // tor
{
// zwykla szyna: //Ra: czemu główki są asymetryczne na wysokości 0.140?
gfx::vertex_array rpts1, rpts2;
create_track_rail_profile( rpts1, rpts2 );
auto const drawing { make_rail_drawing( Bank ) };
// the open ends of a track and the blade tips: no wheel runs over them, they aren't worn
auto const cut_faces = [&]( gfx::vertex_array const &Strip, std::size_t const Ring, bool const Start, bool const End, geometryhandle_sequence &Geometry ) {
track_rails::cut_faces( Strip, Ring, Start, End, Bank, Geometry, false ); };
m_materialcut1 = track_rails::cut_material( m_material1 );
auto const layout { plan_rails( Bank != 0 ) };
if( Bank != 0 ) {
m_crossings = layout.crossed;
}
switch (eType) // dalej zależnie od typu
{
case tt_Table: // obrotnica jak zwykły tor, tylko animacja dochodzi
case tt_Normal:
if (m_material2 && ( Global.Sleepers3DBed || false == m_sleepers3d.active ) )
{ // podsypka z podkładami jest tylko dla zwykłego toru
gfx::vertex_array bpts1;
create_track_bed_profile( bpts1, trPrev, trNext );
// optional vertical shift of the auto-generated ballast (sleepermodel ballastZ).
// positive value raises the trackbed, negative pushes it down so a custom
// sleeper model placed on top can sit flush with the ballast surface.
if( m_sleeper_enabled && m_sleeper_ballast_z != 0.f ) {
for( auto &v : bpts1 ) {
v.position.y += m_sleeper_ballast_z;
}
}
auto const texturelength { texture_length( m_material2 ) };
gfx::vertex_array vertices;
Segment->RenderLoft(vertices, m_origin, bpts1, iTrapezoid > 0, texturelength);
if( Bank != 0 && true == Geometry2.empty() ) {
Geometry2.emplace_back(track_rails::insert_chunk(vertices, empty_userdata, Bank, GL_TRIANGLE_STRIP));
}
if( Bank == 0 && false == Geometry2.empty() ) {
// special variant, replace existing data for a turntable track
GfxRenderer->Replace(vertices, empty_userdata, Geometry2[0], GL_TRIANGLE_STRIP);
}
}
if (m_material1)
{ // szyny - generujemy dwie, najwyżej rysować się będzie jedną
auto const nnumPts { track_rail_profile( m_profile1.second ).size() / 2 };
auto const texturelength { texture_length( m_material1 ) };
gfx::vertex_array vertices;
auto const open { eType == tt_Normal && ( trPrev == nullptr || trNext == nullptr ) };
if( Bank != 0 && true == Geometry1.empty() ) {
for( auto const side : { 1, -1 } ) {
auto const &profile { side > 0 ? rpts1 : rpts2 };
if( eType == tt_Normal && iTrapezoid == 0 && lay_rail( layout, drawing, profile, { .path = 0, .side = side, .texturelength = texturelength, .from = track_rails::blade_runon( *this, side ), .openstart = ( trPrev == nullptr ), .openend = ( trNext == nullptr ) }, Geometry1, GeometryCut1 ) ) {
continue;
}
vertices.clear(); // reuse the scratchpad
// the rail starts behind the heel of a blade running on into the track from the switch before it
if( auto const runon { eType == tt_Normal && iTrapezoid == 0 ? track_rails::blade_runon( *this, side ) : 0.0 }; runon > 0.0 ) {
Segment->RenderLoftSpan( vertices, m_origin, profile, { .side = side, .halfwidth = 0.5f * std::abs( fTrackWidth ), .texturelength = texturelength, .from = runon, .to = Segment->GetLength() } );
}
else {
Segment->RenderLoft( vertices, m_origin, profile, iTrapezoid > 0, texturelength );
}
if( open ) {
cut_faces( vertices, nnumPts, trPrev == nullptr, trNext == nullptr, GeometryCut1 );
}
Geometry1.emplace_back(track_rails::insert_chunk(vertices, empty_userdata, Bank, GL_TRIANGLE_STRIP));
}
}
if( Bank == 0 && false == Geometry1.empty() ) {
// special variant, replace existing data for a turntable track
Segment->RenderLoft( vertices, m_origin, rpts1, iTrapezoid > 0, texturelength );
GfxRenderer->Replace(vertices, empty_userdata, Geometry1[0], GL_TRIANGLE_STRIP);
vertices.clear(); // reuse the scratchpad
Segment->RenderLoft( vertices, m_origin, rpts2, iTrapezoid > 0, texturelength );
GfxRenderer->Replace(vertices, empty_userdata, Geometry1[1], GL_TRIANGLE_STRIP);
}
}
break;
case tt_Switch: { // dla zwrotnicy dwa razy szyny
// positive jointlength: the switch is typically used along the main track, negative: along the diverging track
// TODO: determine this from names of textures assigned to the tracks
// auto const jointlength { static_cast<int>( std::ceil( SwitchExtension->Segments[ 0 ]->RaSegCount() * 0.15 ) ) };
auto const jointlength { 0 }; // temporary until implementation of the above
// rail behind the blade
auto const fixed_rail = [ this, &layout, &drawing, &empty_userdata, &Bank ]( int const Path, gfx::vertex_array const &Profile, int const Side, float const Texturelength, geometryhandle_sequence &Geometry, geometryhandle_sequence &Cuts ) {
if( lay_rail( layout, drawing, Profile, { .path = Path, .side = Side, .texturelength = Texturelength, .from = track_rails::blade_length( *this, Path ) }, Geometry, Cuts ) ) {
return;
}
gfx::vertex_array vertices;
if( auto const &shape { blade( Path ) }; shape.valid ) {
SwitchExtension->Segments[ Path ]->RenderLoftSpan( vertices, m_origin, Profile, { .side = Side, .halfwidth = 0.5f * std::abs( fTrackWidth ), .texturelength = Texturelength, .from = shape.heel, .to = SwitchExtension->Segments[ Path ]->GetLength() } );
}
else {
SwitchExtension->Segments[ Path ]->RenderLoft( vertices, m_origin, Profile, false, Texturelength, 1.0, track_rails::blade_steps( *this, Path ) );
}
Geometry.emplace_back( track_rails::insert_chunk( vertices, empty_userdata, Bank, GL_TRIANGLE_STRIP ) );
};
// rail along the whole path
auto const whole_rail = [ this, &layout, &drawing, &empty_userdata, &Bank ]( int const Path, gfx::vertex_array const &Profile, int const Side, float const Texturelength, geometryhandle_sequence &Geometry, geometryhandle_sequence &Cuts ) {
if( false == lay_rail( layout, drawing, Profile, { .path = Path, .side = Side, .texturelength = Texturelength, .from = 0.0 }, Geometry, Cuts ) ) {
gfx::vertex_array vertices;
SwitchExtension->Segments[ Path ]->RenderLoft( vertices, m_origin, Profile, false, Texturelength, 1.0, jointlength );
Geometry.emplace_back( track_rails::insert_chunk( vertices, empty_userdata, Bank, GL_TRIANGLE_STRIP ) );
}
};
// part of the diverging rail touched by wheels of vehicle going straight, laid with the first path
auto const joint_rail = [ this, &empty_userdata, &Bank ]( int const Path, gfx::vertex_array const &Rail, float const Texturelength, geometryhandle_sequence &Geometry, gfx::vertex_array &Vertices ) {
if( Path == 0 && jointlength > 0 ) {
SwitchExtension->Segments[ 1 ]->RenderLoft( Vertices, m_origin, Rail, false, Texturelength, 1.0, 0, jointlength );
Geometry.emplace_back( track_rails::insert_chunk( Vertices, empty_userdata, Bank, GL_TRIANGLE_STRIP ) );
Vertices.clear();
}
};
if( m_material1 || m_material2 ) {
// iglice liczone tylko dla zwrotnic
gfx::vertex_array rpts3, rpts4;
create_track_blade_profile( rpts3, rpts4 );
// TODO, TBD: change all track geometry to triangles, to allow packing data in less, larger buffers
auto const nnumPts { track_rail_profile( m_profile1.second ).size() / 2 };
auto const dense { std::max( blade( 0 ).valid ? blade( 0 ).heel : 0.0, blade( 1 ).valid ? blade( 1 ).heel : 0.0 ) };
SwitchExtension->Segments[ 0 ]->set_dense( dense );
SwitchExtension->Segments[ 1 ]->set_dense( dense );
m_materialcut2 = track_rails::cut_material( m_material2 );
gfx::vertex_array vertices;
// the blades
for_each_railed_path( *this, [ this, &rpts1, &rpts2, &rpts3, &rpts4, &vertices, &cut_faces, nnumPts, &empty_userdata, &Bank ]( int const Path, material_handle const Material ) {
auto const side { blade_side( Path ) };
loft_blade( Path, side > 0 ? rpts1 : rpts2, side > 0 ? rpts3 : rpts4, texture_length( Material ), vertices );
cut_faces( vertices, nnumPts, true, false, Path ? GeometryCut2 : GeometryCut1 );
( Path ? Geometry2 : Geometry1 ).emplace_back( track_rails::insert_chunk( vertices, empty_userdata, Bank, GL_TRIANGLE_STRIP ) );
vertices.clear(); } );
for_each_railed_path( *this, [ this, &rpts1, &rpts2, &vertices, &fixed_rail, &joint_rail, &whole_rail ]( int const Path, material_handle const Material ) {
auto &geometry { Path ? Geometry2 : Geometry1 };
auto &cuts { Path ? GeometryCut2 : GeometryCut1 };
auto const texturelength { texture_length( Material ) };
auto const side { blade_side( Path ) };
auto const &rail { side > 0 ? rpts1 : rpts2 };
// fixed parts
// szyna za iglicą
fixed_rail( Path, rail, side, texturelength, geometry, cuts );
joint_rail( Path, rail, texturelength, geometry, vertices );
// other rail, full length; on the diverging path potentially minus part touched by wheels of vehicle going straight
whole_rail( Path, side > 0 ? rpts2 : rpts1, -side, texturelength, geometry, cuts ); } );
}
// auto-generated switch trackbed
if( true == Global.CreateSwitchTrackbeds ) {
gfx::vertex_array vertices;
create_switch_trackbed( vertices );
SwitchExtension->Geometry3 = track_rails::insert_chunk(vertices, empty_userdata, Bank, GL_TRIANGLE_STRIP);
vertices.clear();
}
break;
}
}
} // koniec obsługi torów
break;
case 2: // McZapkie-260302 - droga - rendering
switch (eType) // dalej zależnie od typu
{
case tt_Normal: // drogi proste, bo skrzyżowania osobno
{
gfx::vertex_array bpts1; // punkty głównej płaszczyzny przydają się do robienia boków
if (m_material1 || m_material2) {
// punkty się przydadzą, nawet jeśli nawierzchni nie ma
create_road_profile( bpts1 );
}
if (m_material1) // jeśli podana była tekstura, generujemy trójkąty
{ // tworzenie trójkątów nawierzchni szosy
auto const texturelength { texture_length( m_material1 ) };
gfx::vertex_array vertices;
Segment->RenderLoft(vertices, m_origin, bpts1, iTrapezoid > 0, texturelength);
Geometry1.emplace_back(GfxRenderer->Insert(vertices, empty_userdata, Bank, GL_TRIANGLE_STRIP));
}
if (m_material2)
{ // pobocze drogi - poziome przy przechyłce (a może krawężnik i chodnik zrobić jak w Midtown Madness 2?)
auto const side{ std::abs( fTexWidth ) }; // szerokść podsypki na zewnątrz szyny albo pobocza
auto const slop{ std::abs( fTexSlope ) }; // brzeg zewnętrzny
auto const texturelength { texture_length( m_material2 ) };
gfx::vertex_array rpts1, rpts2; // współrzędne przekroju i mapowania dla prawej i lewej strony
create_road_side_profile( rpts1, rpts2, bpts1 );
gfx::vertex_array vertices;
if( fTexHeight1 >= 0.0 || slop != 0.0 ) {
// tylko jeśli jest z prawej
Segment->RenderLoft( vertices, m_origin, rpts1, iTrapezoid > 0, texturelength );
Geometry2.emplace_back(GfxRenderer->Insert(vertices, empty_userdata, Bank, GL_TRIANGLE_STRIP));
vertices.clear();
}
if( fTexHeight1 >= 0.0 || side != 0.0 ) {
// tylko jeśli jest z lewej
Segment->RenderLoft( vertices, m_origin, rpts2, iTrapezoid > 0, texturelength );
Geometry2.emplace_back(GfxRenderer->Insert(vertices, empty_userdata, Bank, GL_TRIANGLE_STRIP));
vertices.clear();
}
}
break;
}
case tt_Cross: // skrzyżowanie dróg rysujemy inaczej
{ // ustalenie współrzędnych środka - przecięcie Point1-Point2 z CV4-Point4
double a[4]; // kąty osi ulic wchodzących
glm::dvec3 p[4]; // punkty się przydadzą do obliczeń
// na razie połowa odległości pomiędzy Point1 i Point2, potem się dopracuje
a[0] = a[1] = 0.5; // parametr do poszukiwania przecięcia łuków
// modyfikować a[0] i a[1] tak, aby trafić na przecięcie odcinka 34
p[0] = SwitchExtension->Segments[0]->FastGetPoint(a[0]); // współrzędne środka pierwszego odcinka
p[1] = SwitchExtension->Segments[1]->FastGetPoint(a[1]); //-//- drugiego
// p[2]=p[1]-p[0]; //jeśli różne od zera, przeliczyć a[0] i a[1] i wyznaczyć nowe punkty
glm::dvec3 oxz = p[0]; // punkt mapowania środka tekstury skrzyżowania
p[0] = SwitchExtension->Segments[0]->GetDirection1(); // Point1 - pobranie wektorów kontrolnych
p[1] = SwitchExtension->Segments[1]->GetDirection2(); // Point3 (bo zamienione)
p[2] = SwitchExtension->Segments[0]->GetDirection2(); // Point2
p[3] = SwitchExtension->Segments[1]->GetDirection1(); // Point4 (bo zamienione)
a[0] = atan2(-p[0].x, p[0].z); // kąty stycznych osi dróg
a[1] = atan2(-p[1].x, p[1].z);
a[2] = atan2(-p[2].x, p[2].z);
a[3] = atan2(-p[3].x, p[3].z);
p[0] = SwitchExtension->Segments[0]->FastGetPoint_0(); // Point1 - pobranie współrzędnych końców
p[1] = SwitchExtension->Segments[1]->FastGetPoint_1(); // Point3
p[2] = SwitchExtension->Segments[0]->FastGetPoint_1(); // Point2
p[3] = SwitchExtension->Segments[1]->FastGetPoint_0(); // Point4 - przy trzech drogach pokrywa się z Point1
// 2014-07: na początek rysować brzegi jak dla łuków
// punkty brzegu nawierzchni uzyskujemy podczas renderowania boków (bez sensu, ale najszybciej było zrobić)
int pointcount;
if( SwitchExtension->iRoads == 3 ) {
// mogą być tylko 3 drogi zamiast 4
pointcount =
SwitchExtension->Segments[ 0 ]->RaSegCount()
+ SwitchExtension->Segments[ 1 ]->RaSegCount()
+ SwitchExtension->Segments[ 2 ]->RaSegCount();
}
else {
pointcount =
SwitchExtension->Segments[ 2 ]->RaSegCount()
+ SwitchExtension->Segments[ 3 ]->RaSegCount()
+ SwitchExtension->Segments[ 4 ]->RaSegCount()
+ SwitchExtension->Segments[ 5 ]->RaSegCount();
}
if (!SwitchExtension->vPoints)
{ // jeśli tablica punktów nie jest jeszcze utworzona, zliczamy punkty i tworzymy ją
// we'll need to add couple extra points for the complete fan we'll build
SwitchExtension->vPoints = new glm::vec3[pointcount + SwitchExtension->iRoads];
}
glm::vec3 *b =
SwitchExtension->bPoints ?
nullptr :
SwitchExtension->vPoints; // zmienna robocza, NULL gdy tablica punktów już jest wypełniona
gfx::vertex_array bpts1; // punkty głównej płaszczyzny przydają się do robienia boków
if (m_material1 || m_material2) { // punkty się przydadzą, nawet jeśli nawierzchni nie ma
create_road_profile( bpts1, true );
}
// najpierw renderowanie poboczy i zapamiętywanie punktów
// problem ze skrzyżowaniami jest taki, że teren chce się pogrupować wg tekstur, ale zaczyna od nawierzchni
// sama nawierzchnia nie wypełni tablicy punktów, bo potrzebne są pobocza
// ale pobocza renderują się później, więc nawierzchnia nie załapuje się na renderowanie w swoim czasie
if( m_material2 )
{ // pobocze drogi - poziome przy przechyłce (a może krawężnik i chodnik zrobić jak w Midtown Madness 2?)
gfx::vertex_array rpts1, rpts2; // współrzędne przekroju i mapowania dla prawej i lewej strony
create_road_side_profile( rpts1, rpts2, bpts1, true );
// Ra 2014-07: trzeba to przerobić na pętlę i pobierać profile (przynajmniej 2..4) z sąsiednich dróg
bool render = m_material2 != 0; // renderować nie trzeba, ale trzeba wyznaczyć punkty brzegowe nawierzchni
auto const side{ std::abs( fTexWidth ) }; // szerokść podsypki na zewnątrz szyny albo pobocza
auto const texturelength{ texture_length( m_material2 ) };
gfx::vertex_array vertices;
if (SwitchExtension->iRoads == 4)
{ // pobocza do trapezowatej nawierzchni - dodatkowe punkty z drugiej strony odcinka
if( fTexHeight1 >= 0.0 || side != 0.0 ) {
SwitchExtension->Segments[ 2 ]->RenderLoft( vertices, m_origin, rpts2, true, texturelength, 1.0, 0, 0, {}, &b, render );
if( true == render ) {
Geometry2.emplace_back(GfxRenderer->Insert(vertices, empty_userdata, Bank, GL_TRIANGLE_STRIP));
vertices.clear();
}
SwitchExtension->Segments[ 3 ]->RenderLoft( vertices, m_origin, rpts2, true, texturelength, 1.0, 0, 0, {}, &b, render );
if( true == render ) {
Geometry2.emplace_back(GfxRenderer->Insert(vertices, empty_userdata, Bank, GL_TRIANGLE_STRIP));
vertices.clear();
}
SwitchExtension->Segments[ 4 ]->RenderLoft( vertices, m_origin, rpts2, true, texturelength, 1.0, 0, 0, {}, &b, render );
if( true == render ) {
Geometry2.emplace_back(GfxRenderer->Insert(vertices, empty_userdata, Bank, GL_TRIANGLE_STRIP));
vertices.clear();
}
SwitchExtension->Segments[ 5 ]->RenderLoft( vertices, m_origin, rpts2, true, texturelength, 1.0, 0, 0, {}, &b, render );
if( true == render ) {
Geometry2.emplace_back(GfxRenderer->Insert(vertices, empty_userdata, Bank, GL_TRIANGLE_STRIP));
vertices.clear();
}
}
}
else {
// punkt 3 pokrywa się z punktem 1, jak w zwrotnicy; połączenie 1->2 nie musi być prostoliniowe
if( fTexHeight1 >= 0.0 || side != 0.0 ) {
SwitchExtension->Segments[ 2 ]->RenderLoft( vertices, m_origin, rpts2, true, texturelength, 1.0, 0, 0, {}, &b, render ); // z P2 do P4
if( true == render ) {
Geometry2.emplace_back(GfxRenderer->Insert(vertices, empty_userdata, Bank, GL_TRIANGLE_STRIP));
vertices.clear();
}
SwitchExtension->Segments[ 1 ]->RenderLoft( vertices, m_origin, rpts2, true, texturelength, 1.0, 0, 0, {}, &b, render ); // z P4 do P3=P1 (odwrócony)
if( true == render ) {
Geometry2.emplace_back(GfxRenderer->Insert(vertices, empty_userdata, Bank, GL_TRIANGLE_STRIP));
vertices.clear();
}
SwitchExtension->Segments[ 0 ]->RenderLoft( vertices, m_origin, rpts2, true, texturelength, 1.0, 0, 0, {}, &b, render ); // z P1 do P2
if( true == render ) {
Geometry2.emplace_back(GfxRenderer->Insert(vertices, empty_userdata, Bank, GL_TRIANGLE_STRIP));
vertices.clear();
}
}
}
}
// renderowanie nawierzchni na końcu
double sina0 = sin(a[0]), cosa0 = cos(a[0]);
double u, v;
if( false == SwitchExtension->bPoints // jeśli tablica nie wypełniona
&& b != nullptr ) {
SwitchExtension->bPoints = true; // tablica punktów została wypełniona
}
if( m_material1 ) {
auto const texturelength { texture_length( m_material1 ) };
gfx::vertex_array vertices;
// jeśli podana tekstura nawierzchni
// we start with a vertex in the middle...
vertices.emplace_back(
glm::vec3{
oxz.x - m_origin.x,
oxz.y - m_origin.y,
oxz.z - m_origin.z },
glm::vec3{ 0.0f, 1.0f, 0.0f },
glm::vec2{ 0.5f, 0.5f } );
// ...and add one extra vertex to close the fan...
u = ( SwitchExtension->vPoints[ 0 ].x - oxz.x + m_origin.x ) / texturelength;
v = ( SwitchExtension->vPoints[ 0 ].z - oxz.z + m_origin.z ) / ( fTexRatio1 * texturelength );
vertices.emplace_back(
glm::vec3 {
SwitchExtension->vPoints[ 0 ].x,
SwitchExtension->vPoints[ 0 ].y,
SwitchExtension->vPoints[ 0 ].z },
glm::vec3{ 0.0f, 1.0f, 0.0f },
// mapowanie we współrzędnych scenerii
glm::vec2{
cosa0 * u + sina0 * v + 0.5,
-sina0 * u + cosa0 * v + 0.5 } );
// ...then draw the precalculated rest
for (int i = pointcount + SwitchExtension->iRoads - 1; i >= 0; --i) {
// mapowanie we współrzędnych scenerii
u = ( SwitchExtension->vPoints[ i ].x - oxz.x + m_origin.x ) / texturelength;
v = ( SwitchExtension->vPoints[ i ].z - oxz.z + m_origin.z ) / ( fTexRatio1 * texturelength );
vertices.emplace_back(
glm::vec3 {
SwitchExtension->vPoints[ i ].x,
SwitchExtension->vPoints[ i ].y,
SwitchExtension->vPoints[ i ].z },
glm::vec3{ 0.0f, 1.0f, 0.0f },
// mapowanie we współrzędnych scenerii
glm::vec2{
cosa0 * u + sina0 * v + 0.5,
-sina0 * u + cosa0 * v + 0.5 } );
}
Geometry1.emplace_back(GfxRenderer->Insert(vertices, empty_userdata, Bank, GL_TRIANGLE_FAN));
}
break;
} // tt_cross
} // road
break;
case 4: // Ra: rzeki na razie jak drogi, przechyłki na pewno nie mają
switch (eType) // dalej zależnie od typu
{
case tt_Normal: // drogi proste, bo skrzyżowania osobno
{
gfx::vertex_array bpts1; // punkty głównej płaszczyzny przydają się do robienia boków
if (m_material1 || m_material2) { // punkty się przydadzą, nawet jeśli nawierzchni nie ma
create_road_profile( bpts1 );
}
if (m_material1) // jeśli podana była tekstura, generujemy trójkąty
{ // tworzenie trójkątów nawierzchni szosy
gfx::vertex_array vertices;
Segment->RenderLoft(vertices, m_origin, bpts1, iTrapezoid > 0, fTexLength);
Geometry1.emplace_back(GfxRenderer->Insert(vertices, empty_userdata, Bank, GL_TRIANGLE_STRIP));
}
if (m_material2)
{ // pobocze drogi - poziome przy przechyłce (a może krawężnik i chodnik zrobić jak w Midtown Madness 2?)
gfx::vertex_array rpts1, rpts2; // współrzędne przekroju i mapowania dla prawej i lewej strony
create_road_side_profile( rpts1, rpts2, bpts1 );
gfx::vertex_array vertices;
Segment->RenderLoft( vertices, m_origin, rpts1, iTrapezoid > 0, fTexLength );
Geometry2.emplace_back(GfxRenderer->Insert(vertices, empty_userdata, Bank, GL_TRIANGLE_STRIP));
vertices.clear();
Segment->RenderLoft( vertices, m_origin, rpts2, iTrapezoid > 0, fTexLength );
Geometry2.emplace_back(GfxRenderer->Insert(vertices, empty_userdata, Bank, GL_TRIANGLE_STRIP));
vertices.clear();
}
}
}
break;
}
return;
};
void TTrack::RenderDynSounds()
{ // odtwarzanie dźwięków pojazdów jest niezależne od ich wyświetlania
for( auto dynamic : Dynamics ) {
dynamic->RenderSounds();
}
};
//---------------------------------------------------------------------------
bool TTrack::SetConnections(int i)
{ // przepisanie aktualnych połączeń toru do odpowiedniego segmentu
if (SwitchExtension)
{
SwitchExtension->pNexts[i] = trNext;
SwitchExtension->pPrevs[i] = trPrev;
SwitchExtension->iNextDirection[i] = iNextDirection;
SwitchExtension->iPrevDirection[i] = iPrevDirection;
if (eType == tt_Switch)
{ // zwrotnica jest wyłącznie w punkcie 1, więc tor od strony Prev jest zawsze ten sam
SwitchExtension->pPrevs[i ^ 1] = trPrev;
SwitchExtension->iPrevDirection[i ^ 1] = iPrevDirection;
}
else if (eType == tt_Cross)
if (SwitchExtension->iRoads == 3)
{
}
if (i)
Switch(0); // po przypisaniu w punkcie 4 włączyć stan zasadniczy
return true;
}
Error("Cannot set connections");
return false;
}
namespace {
// the ends of the paths as the codes of the track joined to them have them: 0 the start of a switch, where both paths begin, 1 the end of
// its first path, 3 the end of its second one; a vehicle going on onto a start keeps its direction, onto an end it turns
int joined_end_code( int const Endpoint ) {
if( Endpoint == 3 ) {
return 1;
}
if( Endpoint == 5 ) {
return 3;
}
return 0;
}
// the code of an end of a path of the switch, as the switch joined there has it: 0 the start, 1 the end of the first path, 3 of the second one
int own_end_code( int const Path, int const End ) {
if( End == 0 ) {
return 0;
}
return ( Path ? 3 : 1 );
}
// the paths of the switch joined to its neighbours as it's set, as Switch() takes them
void bind_switch( TTrack &Switch ) {
auto const &extension { *Switch.SwitchExtension };
auto const state { extension.CurrentIndex & 1 };
Switch.trNext = extension.pNexts[ state ];
Switch.trPrev = extension.pPrevs[ state ];
Switch.iNextDirection = extension.iNextDirection[ state ];
Switch.iPrevDirection = extension.iPrevDirection[ state ];
}
// the free end of a path of the switch joined to the end of another switch in the same point, and that one joined back to it; the
// other switch, none: not joined
TTrack const *join_switch_end( TTrack &Switch, int const Path, int const End ) {
auto &own { *Switch.SwitchExtension };
if( ( End ? own.pNexts[ Path ] : own.pPrevs[ Path ] ) != nullptr || own.Segments[ Path ] == nullptr ) {
return nullptr;
}
auto const point { End ? own.Segments[ Path ]->FastGetPoint_1() : own.Segments[ Path ]->FastGetPoint_0() };
auto const [ other, endpoint ] { simulation::Region->find_path( point, &Switch ) };
if( other == nullptr || other == &Switch || other->eType != tt_Switch || other->SwitchExtension == nullptr || endpoint < 2 || endpoint > 5 ) {
return nullptr;
}
auto &theirs { *other->SwitchExtension };
if( End == 0 ) {
own.pPrevs[ 0 ] = other;
own.pPrevs[ 1 ] = other;
own.iPrevDirection[ 0 ] = joined_end_code( endpoint );
own.iPrevDirection[ 1 ] = own.iPrevDirection[ 0 ];
}
else {
own.pNexts[ Path ] = other;
own.iNextDirection[ Path ] = joined_end_code( endpoint );
}
auto const ours { own_end_code( Path, End ) };
if( endpoint == 2 || endpoint == 4 ) {
theirs.pPrevs[ 0 ] = &Switch;
theirs.pPrevs[ 1 ] = &Switch;
theirs.iPrevDirection[ 0 ] = ours;
theirs.iPrevDirection[ 1 ] = ours;
}
else {
auto const theirpath { endpoint == 5 ? 1 : 0 };
theirs.pNexts[ theirpath ] = &Switch;
theirs.iNextDirection[ theirpath ] = ours;
}
bind_switch( *other );
return other;
}
} // namespace
std::vector<TTrack const *> TTrack::join_switches()
{
std::vector<TTrack const *> joined;
if( eType != tt_Switch || SwitchExtension == nullptr || simulation::Region == nullptr ) {
return joined;
}
for( int path = 0; path < 2; ++path ) {
for( int end = 0; end < 2; ++end ) {
if( auto const *other { join_switch_end( *this, path, end ) }; other != nullptr ) {
joined.push_back( other );
}
}
}
bind_switch( *this );
return joined;
}
bool TTrack::Switch(int i, float const t, float const d)
{ // przełączenie torów z uruchomieniem animacji
if (SwitchExtension) // tory przełączalne mają doklejkę
if (eType == tt_Switch)
{ // przekładanie zwrotnicy jak zwykle
if (t > 0.f) // prędkość liniowa ruchu iglic
SwitchExtension->fOffsetSpeed = t; // prędkość łatwiej zgrać z animacją modelu
if (d >= 0.f) // dodatkowy ruch drugiej iglicy (zamknięcie nastawnicze)
SwitchExtension->fOffsetDelay = d;
i &= 1; // ograniczenie błędów !!!!
SwitchExtension->fDesiredOffset =
i ? fMaxOffset + SwitchExtension->fOffsetDelay : -SwitchExtension->fOffsetDelay;
SwitchExtension->CurrentIndex = i;
Segment = SwitchExtension->Segments[i]; // wybranie aktywnej drogi - potrzebne to?
trNext = SwitchExtension->pNexts[i]; // przełączenie końców
trPrev = SwitchExtension->pPrevs[i];
iNextDirection = SwitchExtension->iNextDirection[i];
iPrevDirection = SwitchExtension->iPrevDirection[i];
fRadius = fRadiusTable[i]; // McZapkie: wybor promienia toru
if( SwitchExtension->fVelocity <= -2 ) {
//-1 oznacza maksymalną prędkość, a dalsze ujemne to ograniczenie na bok
fVelocity = i ? -SwitchExtension->fVelocity : -1;
}
else {
fVelocity = SwitchExtension->fVelocity;
}
if (SwitchExtension->pOwner ? SwitchExtension->pOwner->RaTrackAnimAdd(this) :
true) // jeśli nie dodane do animacji
{ // nie ma się co bawić
SwitchExtension->fOffset = SwitchExtension->fDesiredOffset;
// przeliczenie położenia iglic; czy zadziała na niewyświetlanym sektorze w VBO?
RaAnimate();
}
return true;
}
else if (eType == tt_Table)
{ // blokowanie (0, szukanie torów) lub odblokowanie (1, rozłączenie) obrotnicy
if (i) // NOTE: this condition seems opposite to intention/comment? TODO: investigate this
{ // 0: rozłączenie sąsiednich torów od obrotnicy
if (trPrev) // jeśli jest tor od Point1 obrotnicy
if (iPrevDirection) // 0:dołączony Point1, 1:dołączony Point2
trPrev->trNext = nullptr; // rozłączamy od Point2
else
trPrev->trPrev = nullptr; // rozłączamy od Point1
if (trNext) // jeśli jest tor od Point2 obrotnicy
if (iNextDirection) // 0:dołączony Point1, 1:dołączony Point2
trNext->trNext = nullptr; // rozłączamy od Point2
else
trNext->trPrev = nullptr; // rozłączamy od Point1
trNext = trPrev = nullptr; // na końcu rozłączamy obrotnicę (wkaźniki do sąsiadów już niepotrzebne)
fVelocity = 0.0; // AI, nie ruszaj się!
if (SwitchExtension->pOwner)
SwitchExtension->pOwner->RaTrackAnimAdd(this); // dodanie do listy animacyjnej
// TODO: unregister path ends in the owner cell
}
else
{ // 1: ustalenie finalnego położenia (gdy nie było animacji)
RaAnimate(); // ostatni etap animowania
// zablokowanie pozycji i połączenie do sąsiednich torów
// TODO: register new position of the path endpoints with the region
simulation::Region->TrackJoin( this );
if (trNext || trPrev)
{
fVelocity = 6.0; // jazda dozwolona
if( trPrev
&& trPrev->fVelocity == 0.0 ) {
// ustawienie 0 da możliwość zatrzymania AI na obrotnicy
trPrev->VelocitySet( 6.0 ); // odblokowanie dołączonego toru do jazdy
}
if( trNext
&& trNext->fVelocity == 0.0 ) {
trNext->VelocitySet( 6.0 );
}
if( SwitchExtension->evPlus ) { // w starych sceneriach może nie być
// potwierdzenie wykonania (np. odpala WZ)
simulation::Events.AddToQuery( SwitchExtension->evPlus, nullptr );
}
}
}
SwitchExtension->CurrentIndex = i; // zapamiętanie stanu zablokowania
return true;
}
else if (eType == tt_Cross)
{ // to jest przydatne tylko do łączenia odcinków
i &= 1;
SwitchExtension->CurrentIndex = i;
Segment = SwitchExtension->Segments[i]; // wybranie aktywnej drogi - potrzebne to?
trNext = SwitchExtension->pNexts[i]; // przełączenie końców
trPrev = SwitchExtension->pPrevs[i];
iNextDirection = SwitchExtension->iNextDirection[i];
iPrevDirection = SwitchExtension->iPrevDirection[i];
return true;
}
if (iCategoryFlag == 1)
iDamageFlag = (iDamageFlag & 127) + 128 * (i & 1); // przełączanie wykolejenia
else
Error("Cannot switch normal track");
return false;
};
int TTrack::nose_set() const {
return ( SwitchExtension->fOffset > 0.5f * fMaxOffset ? 1 : 0 );
}
double TTrack::nose_throw() const {
return ( fMaxOffset > 0.f ? std::clamp( static_cast<double>( SwitchExtension->fOffset / fMaxOffset ), 0.0, 1.0 ) : nose_set() );
}
namespace {
// the switch run through against the way it's set: the event of that queued, the blades pushed over, a vehicle derailed at a movable nose
void trail_switch( TTrack &Track, int const i, TDynamicObject const *o ) {
if( i == Track.SwitchExtension->CurrentIndex ) {
return;
}
switch (i)
{
case 0:
if (Track.SwitchExtension->evPlus)
simulation::Events.AddToQuery(Track.SwitchExtension->evPlus, o); // dodanie do kolejki
break;
case 1:
if (Track.SwitchExtension->evMinus)
simulation::Events.AddToQuery(Track.SwitchExtension->evMinus, o); // dodanie do kolejki
break;
default:
// a switch has no other paths
break;
}
Track.Switch(i); // jeśli się tu nie przełączy, to każdy pojazd powtórzy event rozrprucia
if( Track.SwitchExtension->m_movablenose && o != nullptr ) {
// the wheels can't push the nose of the frog over, the vehicle runs off the rails at it
o->MoverParameters->Derail( TRAILED_SWITCH );
}
}
} // namespace
bool TTrack::SwitchForced(int i, TDynamicObject *o)
{ // rozprucie rozjazdu
if (SwitchExtension)
if (eType == tt_Switch)
{ //
trail_switch( *this, i, o );
}
else if (eType == tt_Cross)
{ // ustawienie wskaźnika na wskazany segment
Segment = SwitchExtension->Segments[i];
}
return true;
};
// picks one of the routes through a crossroads for a driver heading for it
int TTrack::RouteDraw() const {
auto const count { std::min( RouteCount(), static_cast<int>( m_routeweights.size() ) ) };
auto total { 0.0 };
for( int route = 0; route < count; ++route ) {
total += std::max( 0.f, m_routeweights[ route ] );
}
if( total <= 0.0 ) {
// even odds, the way it's always been for the crossroads of the scenery
return 1 + static_cast<int>( std::floor( Random( static_cast<double>( RouteCount() ) - 0.001 ) ) );
}
auto draw { Random( total ) };
auto last { 1 };
for( int route = 0; route < count; ++route ) {
if( m_routeweights[ route ] <= 0.f ) { continue; }
last = route + 1;
draw -= m_routeweights[ route ];
if( draw < 0.0 ) { break; }
}
return last;
}
int TTrack::CrossSegment(int from, int into)
{ // ustawienie wskaźnika na segement w pożądanym kierunku (into) od strony (from)
// zwraca kod segmentu, z kierunkiem jazdy jako znakiem ±
int i = 0;
switch (into)
{
case 0: // stop
// WriteLog( "Stopping in P" + to_string( from + 1 ) + " on " + name() );
break;
case 1: // left
// WriteLog( "Turning left from P" + to_string( from + 1 ) + " on " + name() );
i = SwitchExtension->iRoads == 4 ? iLewo4[from] : iLewo3[from];
break;
case 2: // right
// WriteLog( "Turning right from P" + to_string( from + 1 ) + " on " + name() );
i = SwitchExtension->iRoads == 4 ? iPrawo4[from] : iPrawo3[from];
break;
case 3: // stright
// WriteLog( "Going straight from P" + to_string( from + 1 ) + " on " + name() );
i = SwitchExtension->iRoads == 4 ? iProsto4[from] : iProsto3[from];
break;
}
if (i)
{
Segment = SwitchExtension->Segments[abs(i) - 1];
// WriteLog("Selected segment: "+AnsiString(abs(i)-1));
}
return i;
};
void TTrack::RaAnimListAdd(TTrack *t)
{ // dodanie toru do listy animacyjnej
if (t != nullptr && SwitchExtension != nullptr)
{
if (t == this)
return; // siebie nie dodajemy drugi raz do listy
if (!t->SwitchExtension)
return; // nie podlega animacji
if (SwitchExtension->pNextAnim)
{
if (SwitchExtension->pNextAnim == t)
return; // gdy już taki jest
else
SwitchExtension->pNextAnim->RaAnimListAdd(t);
}
else
{
SwitchExtension->pNextAnim = t;
t->SwitchExtension->pNextAnim = nullptr; // nowo dodawany nie może mieć ogona
}
}
};
int TTrack::blade_side( int const Path ) const {
return ( SwitchExtension->RightSwitch == ( Path == 0 ) ? 1 : -1 );
}
void TTrack::loft_blade( int const Path, gfx::vertex_array const &Rail, gfx::vertex_array const &Blade, float const Texturelength, gfx::vertex_array &Vertices ) const {
auto const opening { Path == 0 ? SwitchExtension->fOffset2 : fMaxOffset - SwitchExtension->fOffset1 };
auto const offset { blade_side( Path ) * opening };
if( auto const &shape { blade( Path ) }; shape.valid ) {
auto const thrown { blades_throw() * std::clamp( static_cast<double>( opening ) / ( fMaxOffset + SwitchExtension->fOffsetDelay ), 0.0, 1.0 ) };
std::vector<glm::dvec2> offsets;
for( auto const &bend : shape.bends ) {
offsets.emplace_back( bend.x, -thrown * bend.y );
}
auto const size { rail_dimensions() };
auto const length { SwitchExtension->Segments[ Path ]->GetLength() };
SwitchExtension->Segments[ Path ]->RenderLoftSpan( Vertices, m_origin, Rail, { .side = blade_side( Path ), .halfwidth = 0.5f * std::abs( fTrackWidth ), .texturelength = Texturelength, .from = shape.tip, .to = std::min( shape.heel, length ), .offsets = offsets, .extents = shape.extents, .walls = true, .drops = shape.drops, .head = { size.neck, size.crest } } );
// the blade running on past the end of the path goes on along the plain track joined there, whose rail starts behind the heel
if( auto const *next { track_rails::runon_track( *this, Path ) }; next != nullptr && shape.heel > length + 1e-3 ) {
auto const along = [&]( std::vector<glm::dvec2> const &Knots ) {
std::vector<glm::dvec2> result;
for( auto const &knot : Knots ) {
result.emplace_back( knot.x - length, knot.y );
}
return result; };
next->Segment->RenderLoftSpan( Vertices, m_origin, Rail, { .side = blade_side( Path ), .halfwidth = 0.5f * std::abs( fTrackWidth ), .texturelength = Texturelength, .from = 0.0, .to = shape.heel - length, .offsets = along( offsets ), .extents = along( shape.extents ), .walls = true, .drops = along( shape.drops ), .head = { size.neck, size.crest } } );
}
return;
}
auto const bladelength { track_rails::blade_steps( *this, Path ) };
// composed from two parts: transition from blade to regular rail, and regular rail
SwitchExtension->Segments[ Path ]->RenderLoft( Vertices, m_origin, Blade, true, Texturelength, 1.0, 0, bladelength / 2, { offset, offset / 2 } );
SwitchExtension->Segments[ Path ]->RenderLoft( Vertices, m_origin, Rail, false, Texturelength, 1.0, bladelength / 2, bladelength, { offset / 2, 0.f } );
}
TTrack * TTrack::RaAnimate()
{ // wykonanie rekurencyjne animacji, wywoływane przed wyświetleniem sektora
// zwraca wskaźnik toru wymagającego dalszej animacji
gfx::userdata_array empty_userdata;
if( SwitchExtension->pNextAnim )
SwitchExtension->pNextAnim = SwitchExtension->pNextAnim->RaAnimate();
bool m = true; // animacja trwa
if (eType == tt_Switch) // dla zwrotnicy tylko szyny
{
auto const v = SwitchExtension->fDesiredOffset - SwitchExtension->fOffset; // kierunek
SwitchExtension->fOffset += sign(v) * Timer::GetDeltaTime() * SwitchExtension->fOffsetSpeed;
// Ra: trzeba dać to do klasy...
SwitchExtension->fOffset1 = SwitchExtension->fOffset;
SwitchExtension->fOffset2 = SwitchExtension->fOffset;
if (SwitchExtension->fOffset1 > fMaxOffset)
SwitchExtension->fOffset1 = fMaxOffset; // ograniczenie animacji zewnętrznej iglicy
if (SwitchExtension->fOffset2 < 0.f)
SwitchExtension->fOffset2 = 0.f; // ograniczenie animacji wewnętrznej iglicy
if (v < 0.f)
{ // jak na pierwszy z torów
if (SwitchExtension->fOffset <= SwitchExtension->fDesiredOffset)
{
SwitchExtension->fOffset = SwitchExtension->fDesiredOffset;
m = false; // koniec animacji
}
}
else
{ // jak na drugi z torów
if (SwitchExtension->fOffset >= SwitchExtension->fDesiredOffset)
{
SwitchExtension->fOffset = SwitchExtension->fDesiredOffset;
m = false; // koniec animacji
}
}
if( auto const nosethrow { SwitchExtension->m_movablenose ? nose_throw() : 0.0 };
SwitchExtension->m_movablenose
&& SwitchExtension->m_nosethrow >= 0.0
&& ( std::abs( nosethrow - SwitchExtension->m_nosethrow ) >= 0.05
|| ( false == m && nosethrow != SwitchExtension->m_nosethrow ) )
&& false == Geometry1.empty() ) {
// the nose of the frog goes over to the wing rail of the other track along with the blades, laid again in steps
gfx::geometrybank_handle const bank { Geometry1.front().bank, 0 };
Geometry1.clear();
Geometry2.clear();
GeometryCut1.clear();
GeometryCut2.clear();
GeometryTreads.clear();
SwitchExtension->Geometry3 = gfx::geometry_handle{};
create_geometry( bank );
}
// skip the geometry update if no geometry for this track was generated yet
if( ( m_material1 != 0
|| m_material2 != 0 )
&& ( false == Geometry1.empty()
|| false == Geometry2.empty() ) ) {
// iglice liczone tylko dla zwrotnic
gfx::vertex_array rpts1, rpts2;
create_track_rail_profile( rpts1, rpts2 );
gfx::vertex_array rpts3, rpts4;
create_track_blade_profile( rpts3, rpts4 );
gfx::vertex_array vertices;
auto const nnumPts { track_rail_profile( m_profile1.second ).size() / 2 };
auto const replace_blade = [&]( geometryhandle_sequence const &Geometry, geometryhandle_sequence const &Cuts ) {
if( false == Cuts.empty() ) {
gfx::vertex_array triangles;
track_rails::cap_loft( vertices, nnumPts, true, false, triangles );
auto userdata { track_rails::worn_userdata( triangles.size(), false ) };
GfxRenderer->Replace( triangles, userdata, Cuts[ 0 ], GL_TRIANGLES );
}
GfxRenderer->Replace( vertices, empty_userdata, Geometry[ 0 ], GL_TRIANGLE_STRIP );
vertices.clear(); };
for_each_railed_path( *this, [ this, &rpts1, &rpts2, &rpts3, &rpts4, &vertices, &replace_blade ]( int const Path, material_handle const Material ) {
auto const side { blade_side( Path ) };
loft_blade( Path, side > 0 ? rpts1 : rpts2, side > 0 ? rpts3 : rpts4, texture_length( Material ), vertices );
replace_blade( Path ? Geometry2 : Geometry1, Path ? GeometryCut2 : GeometryCut1 ); } );
}
}
else if (eType == tt_Table) {
// dla obrotnicy - szyny i podsypka
if (SwitchExtension->pModel &&
SwitchExtension->CurrentIndex) // 0=zablokowana się nie animuje
{ // trzeba każdorazowo porównywać z kątem modelu
// //pobranie kąta z modelu
auto ac = SwitchExtension->pModel ? SwitchExtension->pModel->GetContainer() : // pobranie głównego submodelu
nullptr;
if( ac ) {
if( ac->AngleGet() != SwitchExtension->fOffset
|| !( ac->TransGet() == SwitchExtension->vTrans ) ) { // czy przemieściło się od ostatniego sprawdzania
double hlen = 0.5 * SwitchExtension->Segments[ 0 ]->GetLength(); // połowa długości
SwitchExtension->fOffset =
SwitchExtension->pModel->Angles().y // take into account orientation of the model
+ ac->AngleGet(); // pobranie kąta z submodelu
double
sina = -hlen * std::sin( glm::radians( SwitchExtension->fOffset ) ),
cosa = -hlen * std::cos( glm::radians( SwitchExtension->fOffset ) );
SwitchExtension->vTrans = ac->TransGet();
auto middle = location() + SwitchExtension->vTrans; // SwitchExtension->Segments[0]->FastGetPoint(0.5);
Segment->Init(middle + glm::dvec3(sina, 0.0, cosa), middle - glm::dvec3(sina, 0.0, cosa),
10.0 ); // nowy odcinek
for( auto dynamic : Dynamics ) {
// minimalny ruch, aby przeliczyć pozycję
dynamic->Move( 0.000001 );
}
// NOTE: passing empty handle is a bit of a hack here. could be refactored into something more elegant
create_geometry( {} );
} // animacja trwa nadal
}
}
else
m = false; // koniec animacji albo w ogóle nie połączone z modelem
}
return m ? this : SwitchExtension->pNextAnim; // zwraca obiekt do dalszej animacji
};
//---------------------------------------------------------------------------
void TTrack::RadioStop()
{ // przekazanie pojazdom rozkazu zatrzymania
for( auto dynamic : Dynamics ) {
dynamic->RadioStop();
}
};
double TTrack::WidthTotal()
{ // szerokość z poboczem
if (iCategoryFlag & 2) // jesli droga
if (fTexHeight1 >= 0.0) // i ma boki zagięte w dół (chodnik jest w górę)
return 2.0 * fabs(fTexWidth) +
0.5 * fabs(fTrackWidth + fTrackWidth2); // dodajemy pobocze
return 0.5 * fabs(fTrackWidth + fTrackWidth2); // a tak tylko zwykła średnia szerokość
};
bool TTrack::IsGroupable()
{ // czy wyświetlanie toru może być zgrupwane z innymi
if (eType == tt_Switch || eType == tt_Table)
return false; // tory ruchome nie są grupowane
if (eEnvironment == e_canyon || eEnvironment == e_tunnel)
return false; // tory ze zmianą światła
return true;
};
bool Equal(const glm::dvec3 v1, const glm::dvec3 *v2)
{ // sprawdzenie odległości punktów
// Ra: powinno być do 100cm wzdłuż toru i ze 2cm w poprzek (na prostej może nie być długiego
// kawałka)
// Ra: z automatycznie dodawanym stukiem, jeśli dziura jest większa niż 2mm.
if (fabs(v1.x - v2->x) > 0.02)
return false; // sześcian zamiast kuli
if (fabs(v1.z - v2->z) > 0.02)
return false;
if (fabs(v1.y - v2->y) > 0.02)
return false;
return true;
// return (SquareMagnitude(v1-*v2)<0.00012); //0.011^2=0.00012
};
int TTrack::TestPoint(const glm::dvec3 *Point)
{ // sprawdzanie, czy tory można połączyć
switch (eType)
{
case tt_Normal: // zwykły odcinek
if (trPrev == nullptr)
if (Equal(Segment->FastGetPoint_0(), Point))
return 0;
if (trNext == nullptr)
if (Equal(Segment->FastGetPoint_1(), Point))
return 1;
break;
case tt_Switch: // zwrotnica
{
int state = GetSwitchState(); // po co?
// Ra: TODO: jak się zmieni na bezpośrednie odwołania do segmentow zwrotnicy,
// to się wykoleja, ponieważ trNext zależy od przełożenia
Switch(0);
if (trPrev == nullptr)
// if (Equal(SwitchExtension->Segments[0]->FastGetPoint_0(),Point))
if (Equal(Segment->FastGetPoint_0(), Point))
{
Switch(state);
return 2;
}
if (trNext == nullptr)
// if (Equal(SwitchExtension->Segments[0]->FastGetPoint_1(),Point))
if (Equal(Segment->FastGetPoint_1(), Point))
{
Switch(state);
return 3;
}
Switch(1); // można by się pozbyć tego przełączania
if (trPrev == nullptr) // Ra: z tym chyba nie potrzeba łączyć
// if (Equal(SwitchExtension->Segments[1]->FastGetPoint_0(),Point))
if (Equal(Segment->FastGetPoint_0(), Point))
{
Switch(state); // Switch(0);
return 4;
}
if (trNext == nullptr) // TODO: to zależy od przełożenia zwrotnicy
// if (Equal(SwitchExtension->Segments[1]->FastGetPoint_1(),Point))
if (Equal(Segment->FastGetPoint_1(), Point))
{
Switch(state); // Switch(0);
return 5;
}
Switch(state);
}
break;
case tt_Cross: // skrzyżowanie dróg
// if (trPrev==NULL)
if (Equal(SwitchExtension->Segments[0]->FastGetPoint_0(), Point))
return 2;
// if (trNext==NULL)
if (Equal(SwitchExtension->Segments[0]->FastGetPoint_1(), Point))
return 3;
// if (trPrev==NULL)
if (Equal(SwitchExtension->Segments[1]->FastGetPoint_0(), Point))
return 4;
// if (trNext==NULL)
if (Equal(SwitchExtension->Segments[1]->FastGetPoint_1(), Point))
return 5;
break;
}
return -1;
};
// retrieves list of the track's end points
std::vector<glm::dvec3>
TTrack::endpoints() const {
switch( eType ) {
case tt_Normal:
case tt_Table: {
return {
glm::dvec3{ Segment->FastGetPoint_0() },
glm::dvec3{ Segment->FastGetPoint_1() } };
}
case tt_Switch:
case tt_Cross: {
return {
glm::dvec3{ SwitchExtension->Segments[ 0 ]->FastGetPoint_0() },
glm::dvec3{ SwitchExtension->Segments[ 0 ]->FastGetPoint_1() },
glm::dvec3{ SwitchExtension->Segments[ 1 ]->FastGetPoint_0() },
glm::dvec3{ SwitchExtension->Segments[ 1 ]->FastGetPoint_1() } };
}
default: {
return{};
}
}
}
// radius() subclass details, calculates node's bounding radius
float
TTrack::radius_() const {
auto const points { endpoints() };
auto radius { 0.f };
for( auto &point : points ) {
radius = std::max(
radius,
static_cast<float>( glm::length( m_area.center - point ) ) ); // extra margin to prevent driven vehicle from flicking
}
return radius;
}
// serialize() subclass details, sends content of the subclass to provided stream
void
TTrack::serialize_( std::ostream &Output ) const {
// TODO: implement
}
// deserialize() subclass details, restores content of the subclass from provided stream
void
TTrack::deserialize_( std::istream &Input ) {
// TODO: implement
}
// the keyword the track is written with, by its type and for a plain one by what runs on it
char const *
TTrack::type_keyword() const {
if( eType == tt_Normal && m_tributary ) {
return "tributary";
}
if( eType == tt_Normal ) {
switch( iCategoryFlag & 15 ) {
case 1: { return "normal"; }
case 2: { return "road"; }
case 4: { return "river"; }
default: { return "none"; }
}
}
switch( eType ) {
case tt_Switch: { return "switch"; }
case tt_Cross: { return "cross"; }
case tt_Table: { return "turn"; }
case tt_Tributary: { return "tributary"; }
default: { return "none"; }
}
}
namespace {
// a piece of a path as the scenery file has it: its points, the roll at its start after the first one, the roll at its end and its radius
void export_piece_as_text( std::ostream &Output, segment_data const &Piece ) {
for( auto const point : { segment_data::point::start, segment_data::point::control1, segment_data::point::control2, segment_data::point::end } ) {
Output
<< Piece.points[ point ].x << ' '
<< Piece.points[ point ].y << ' '
<< Piece.points[ point ].z << ' ';
if( point == segment_data::point::start ) {
Output << Piece.rolls[ 0 ] << ' ';
}
}
Output
<< Piece.rolls[ 1 ] << ' '
<< Piece.radius << ' ';
}
} // namespace
// export() subclass details, sends basic content of the class in legacy (text) format to provided stream
void
TTrack::export_as_text_( std::ostream &Output ) const {
// header
Output << "track ";
// type
Output << type_keyword() << ' ';
// basic attributes
Output
<< Length() << ' '
<< fTrackWidth << ' '
<< fFriction << ' '
<< fSoundDistance << ' '
<< iQualityFlag << ' '
<< iDamageFlag << ' ';
// environment
Output << (
eEnvironment == e_flat ? "flat" :
eEnvironment == e_bridge ? "bridge" :
eEnvironment == e_tunnel ? "tunnel" :
eEnvironment == e_bank ? "bank" :
eEnvironment == e_canyon ? "canyon" :
eEnvironment == e_mountains ? "mountains" :
"none" )
<< ' ';
// visibility
// NOTE: 'invis' would be less wrong than 'unvis', but potentially incompatible with old 3rd party tools
Output << ( m_visible ? "vis" : "unvis" ) << ' ';
if( m_visible ) {
// texture parameters are supplied only if the path is set as visible
auto texturefile { (
m_material1 != null_handle ?
GfxRenderer->Material( m_material1 )->GetName() :
"none" ) };
if( texturefile.find( paths::textures ) == 0 ) {
// don't include 'textures/' in the path
texturefile.erase( 0, std::string{ paths::textures }.size() );
}
Output
<< texturefile << ' '
<< fTexLength << ' ';
texturefile = m_material2 != null_handle ? GfxRenderer->Material(m_material2)->GetName() : "none";
if( texturefile.find( paths::textures ) == 0 ) {
// don't include 'textures/' in the path
texturefile.erase( 0, std::string{ paths::textures }.size() );
}
Output << texturefile << ' ';
Output
<< (fTexHeight1 - fTexHeightOffset ) * ( iCategoryFlag & 4 ? -1 : 1 ) << ' '
<< fTexWidth << ' '
<< fTexSlope << ' ';
}
// path data
auto const precision { Output.precision( std::numeric_limits<double>::digits10 ) };
for( auto const &path : m_paths ) {
Output
<< path.points[ segment_data::point::start ].x << ' '
<< path.points[ segment_data::point::start ].y << ' '
<< path.points[ segment_data::point::start ].z << ' '
<< path.rolls[ 0 ] << ' '
<< path.points[ segment_data::point::control1 ].x << ' '
<< path.points[ segment_data::point::control1 ].y << ' '
<< path.points[ segment_data::point::control1 ].z << ' '
<< path.points[ segment_data::point::control2 ].x << ' '
<< path.points[ segment_data::point::control2 ].y << ' '
<< path.points[ segment_data::point::control2 ].z << ' '
<< path.points[ segment_data::point::end ].x << ' '
<< path.points[ segment_data::point::end ].y << ' '
<< path.points[ segment_data::point::end ].z << ' '
<< path.rolls[ 1 ] << ' '
<< path.radius << ' ';
}
Output.precision( precision );
// optional attributes
std::vector< std::pair< std::string, event_sequence const * > > const eventsequences {
{ "event0", &m_events0 }, { "eventall0", &m_events0all },
{ "event1", &m_events1 }, { "eventall1", &m_events1all },
{ "event2", &m_events2 }, { "eventall2", &m_events2all } };
for( auto &eventsequence : eventsequences ) {
for( auto &event : *eventsequence.second ) {
// NOTE: actual event name can be potentially different from its cached name, if it was renamed in the editor
// therefore on export we pull the name from the event itself, if the binding isn't broken
Output
<< eventsequence.first << ' '
<< ( event.second != nullptr ?
event.second->m_name :
event.first )
<< ' ';
}
}
if( SwitchExtension
&& SwitchExtension->fVelocity != -1.0 ) {
Output << "velocity " << SwitchExtension->fVelocity << ' ';
}
else {
if( fVelocity != -1.0 ) {
Output << "velocity " << fVelocity << ' ';
}
}
for( const TIsolated *iso : Isolated ) {
Output << "isolated " << iso->asName << ' ';
}
if( fOverhead != -1.0 ) {
Output << "overhead " << fOverhead << ' ';
}
if( fVerticalRadius != 0.f ) {
Output << "vradius " << fVerticalRadius << ' ';
}
for( std::size_t index = 0; index < m_paths.size(); ++index ) {
auto const &pieces { m_paths[ index ].pieces };
if( pieces.empty() ) {
continue;
}
auto const piecesprecision { Output.precision( std::numeric_limits<double>::digits10 ) };
Output << "pieces" << index + 1 << ' ' << pieces.size() << ' ';
for( auto const &piece : pieces ) {
export_piece_as_text( Output, piece );
}
Output.precision( piecesprecision );
}
if( eType == tt_Switch
&& SwitchExtension->m_material3 != null_handle) {
auto texturefile { GfxRenderer->Material( SwitchExtension->m_material3 )->GetName() };
if( texturefile.find( paths::textures ) == 0 ) {
// don't include 'textures/' in the path
texturefile.erase( 0, std::string{ paths::textures }.size() );
}
Output << "trackbed " << texturefile << ' ';
}
if( eType == tt_Switch
&& SwitchExtension->m_frogs ) {
Output << "frogs ";
}
if( eType == tt_Switch
&& SwitchExtension->m_movablenose ) {
Output << "movablenose ";
}
if( eType == tt_Switch
&& ( SwitchExtension->m_bladeheel > 0.0 || SwitchExtension->m_bladethrow > 0.0 ) ) {
Output << "blades " << SwitchExtension->m_bladeheel << ' ' << SwitchExtension->m_bladethrow << ' ';
}
if( iCategoryFlag == 1
&& false == m_profile1.first.empty() ) {
Output << "railprofile " << m_profile1.first << ' ';
}
Output << track_uneven::write_attribute( m_uneven, eType == tt_Switch );
if( false == m_friction.first.empty() ) {
Output << "friction " << m_friction.first << ' ';
}
if( m_sleeper_enabled && false == m_sleeper_model_name.empty() ) {
Output
<< "sleepermodel "
<< m_sleeper_frequency << ' '
<< m_sleeper_model_name << ' '
<< ( m_sleeper_skin_name.empty() ? std::string{ "none" } : m_sleeper_skin_name ) << ' '
<< m_sleeper_offset.x << ' '
<< m_sleeper_offset.y << ' '
<< m_sleeper_offset.z << ' '
<< m_sleeper_ballast_z << ' ';
}
if( false == m_timber_model_name.empty() ) {
Output
<< "timbermodel "
<< m_timber_model_name << ' '
<< ( m_timber_skin_name.empty() ? std::string{ "none" } : m_timber_skin_name ) << ' ';
}
// footer
Output
<< "endtrack"
<< "\n";
}
// Returns the tooltip of this Track, which may contain a list of isolations if the track belongs to any.
std::string TTrack::tooltip() const
{
std::string tooltip = this->name();
if (!Isolated.empty())
{
tooltip += "\nIsolated:";
for (const auto isolation : Isolated)
tooltip += " " + isolation->asName;
}
return tooltip;
}
// locates specified profile in the profile database, potentially loading it from a file
// returns: pair <profile name, profile handle>
void
TTrack::rail_profile( std::string const &Name ) {
m_profile1 = ( Name.empty() ? std::pair<std::string, int>{} : fetch_track_rail_profile( Name ) );
}
std::pair<std::string, int>
TTrack::fetch_track_rail_profile( std::string const &Profile ) {
auto const railprofilepath { std::string( paths::models ) + "tory/railprofile_" };
auto const railkeyprefix { std::string( "rail_" ) };
if( m_profiles.empty() ) {
// ensure the default profile is always first in the database
fetch_default_profiles();
}
// try to locate specified rail profile...
auto const lookup { m_profilesmap.find( railkeyprefix + Profile ) };
if( lookup != m_profilesmap.end() ) {
// ...if it works, we're done...
return { Profile, lookup->second };
}
// ... and if it fails try to add the profile to the database from a data file
auto profilehandle { 0 }; // fallback link to default profile if loading it fails
auto profiledata { deserialize_profile( railprofilepath + Profile ) };
if( false == profiledata.empty() ) {
// if we get the profile data add it to the database and calculate a link to it
profilehandle = static_cast<int>( m_profiles.size() );
m_profiles.emplace_back( profiledata );
}
m_profilesmap.emplace( railkeyprefix + Profile, profilehandle );
return { Profile, profilehandle };
}
void
TTrack::fetch_default_profiles() {
if( false == m_profiles.empty() ) { return; }
auto const railprofilepath { std::string( paths::models ) + "tory/railprofile_" };
auto const railkeyprefix { std::string( "rail_" ) };
m_profiles.emplace_back( deserialize_profile( railprofilepath + "default" ) );
if( m_profiles.back().empty() ) {
// fallback to prevent utter start failure, supply legacy track profile
m_profiles.back() = {
// szyna - vextor6(x,y,mapowanie tekstury,xn,yn,zn)
// tę wersję opracował Tolein (bez pochylenia)
{{ 0.111f, -0.180f, 0.f}, { 1.000f, 0.000f, 0.f}, {0.00f, 0.f}},
{{ 0.046f, -0.150f, 0.f}, { 0.707f, 0.707f, 0.f}, {0.15f, 0.f}},
{{ 0.044f, -0.050f, 0.f}, { 0.707f, -0.707f, 0.f}, {0.25f, 0.f}},
{{ 0.073f, -0.038f, 0.f}, { 0.707f, -0.707f, 0.f}, {0.35f, 0.f}},
{{ 0.072f, -0.010f, 0.f}, { 0.707f, 0.707f, 0.f}, {0.40f, 0.f}},
{{ 0.052f, -0.000f, 0.f}, { 0.000f, 1.000f, 0.f}, {0.45f, 0.f}},
{{ 0.020f, -0.000f, 0.f}, { 0.000f, 1.000f, 0.f}, {0.55f, 0.f}},
{{ 0.000f, -0.010f, 0.f}, {-0.707f, 0.707f, 0.f}, {0.60f, 0.f}},
{{-0.001f, -0.038f, 0.f}, {-0.707f, -0.707f, 0.f}, {0.65f, 0.f}},
{{ 0.028f, -0.050f, 0.f}, {-0.707f, -0.707f, 0.f}, {0.75f, 0.f}},
{{ 0.026f, -0.150f, 0.f}, {-0.707f, 0.707f, 0.f}, {0.85f, 0.f}},
{{-0.039f, -0.180f, 0.f}, {-1.000f, 0.000f, 0.f}, {1.00f, 0.f}},
// iglica - vextor3(x,y,mapowanie tekstury)
// 1 mm więcej, żeby nie nachodziły tekstury?
{{ 0.010f, -0.180f, 0.f}, { 1.000f, 0.000f, 0.f}, {0.00f, 0.f}},
{{ 0.010f, -0.155f, 0.f}, { 1.000f, 0.000f, 0.f}, {0.15f, 0.f}},
{{ 0.010f, -0.070f, 0.f}, { 1.000f, 0.000f, 0.f}, {0.25f, 0.f}},
{{ 0.010f, -0.040f, 0.f}, { 1.000f, 0.000f, 0.f}, {0.35f, 0.f}},
{{ 0.010f, -0.010f, 0.f}, { 1.000f, 0.000f, 0.f}, {0.40f, 0.f}},
{{ 0.010f, -0.000f, 0.f}, { 0.707f, 0.707f, 0.f}, {0.45f, 0.f}},
{{ 0.000f, -0.000f, 0.f}, { 0.707f, 0.707f, 0.f}, {0.55f, 0.f}},
{{ 0.000f, -0.010f, 0.f}, {-1.000f, 0.000f, 0.f}, {0.60f, 0.f}},
{{ 0.000f, -0.040f, 0.f}, {-1.000f, 0.000f, 0.f}, {0.65f, 0.f}},
{{ 0.000f, -0.070f, 0.f}, {-1.000f, 0.000f, 0.f}, {0.75f, 0.f}},
{{ 0.000f, -0.155f, 0.f}, {-0.707f, 0.707f, 0.f}, {0.85f, 0.f}},
{{-0.040f, -0.180f, 0.f}, {-1.000f, 0.000f, 0.f}, {1.00f, 0.f}} };
}
m_profilesmap.emplace( railkeyprefix + "default", 0 );
}
gfx::vertex_array
TTrack::deserialize_profile( std::string const &Profile ) {
gfx::vertex_array profiledata;
cParser input { Profile + ".txt", cParser::buffer_FILE };
while( input.getTokens( 5, true, "\n\r\t ;,{}" ) ) {
gfx::basic_vertex vertex;
input
>> vertex.position.x
>> vertex.position.y
>> vertex.normal.x
>> vertex.normal.y
>> vertex.texture.s;
profiledata.emplace_back( vertex );
}
return profiledata;
}
gfx::vertex_array const &
TTrack::track_rail_profile( int const Profile ) {
return m_profiles[ Profile ];
}
track_rails::rail_size
TTrack::rail_dimensions() const {
if( m_profiles.empty() ) {
return {};
}
return track_rails::measure_rail( track_rail_profile( m_profile1.second ) );
}
float
TTrack::texture_length( material_handle const Material ) {
if( Material == null_handle ) {
return fTexLength;
}
auto const texturelength { GfxRenderer->Material( Material )->GetSize().y };
return texturelength < 0.f ? fTexLength : texturelength;
}
float
TTrack::rail_height() const {
// the same height the ballast is laid at, under the rail profile
return std::abs( track_rail_profile( m_profile1.second ).front().position.y );
}
void TTrack::MovedUp1(float const dh)
{ // poprawienie przechyłki wymaga wydłużenia podsypki
fTexHeight1 += dh;
fTexHeightOffset += dh;
};
// ustawienie prędkości z ograniczeniem do pierwotnej wartości (zapisanej w scenerii)
void TTrack::VelocitySet(float v) {
// TBD, TODO: add a variable to preserve potential speed limit set by the track configuration on basic track pieces
if( SwitchExtension
&& SwitchExtension->fVelocity != -1 ) {
// zwrotnica może mieć odgórne ograniczenie, nieprzeskakiwalne eventem
fVelocity =
min_speed<float>(
v,
SwitchExtension->fVelocity > 0 ?
SwitchExtension->fVelocity : // positive limit applies to both switch tracks
SwitchExtension->CurrentIndex == 0 ?
-1 : // negative limit applies only to the diverging track
-SwitchExtension->fVelocity );
}
else {
fVelocity = v; // nie ma ograniczenia
}
};
double TTrack::VelocityGet()
{ // pobranie dozwolonej prędkości podczas skanowania
return iDamageFlag & 128 ? 0.0 : fVelocity; // tor uszkodzony = prędkość zerowa
};
float TTrack::Friction() const {
if( m_friction.second == nullptr ) {
return fFriction;
}
else {
return std::clamp( fFriction * m_friction.second->Value1() + m_friction.second->Value2(), 0.0, 1.0 );
}
}
void TTrack::ConnectionsLog()
{ // wypisanie informacji o połączeniach
int i;
WriteLog("--> tt_Cross named " + m_name);
if (eType == tt_Cross)
for (i = 0; i < 2; ++i)
{
if (SwitchExtension->pPrevs[i])
WriteLog("Point " + std::to_string(i + i + 1) + " -> track " +
SwitchExtension->pPrevs[i]->m_name + ":" +
std::to_string(int(SwitchExtension->iPrevDirection[i])));
if (SwitchExtension->pNexts[i])
WriteLog("Point " + std::to_string(i + i + 2) + " -> track " +
SwitchExtension->pNexts[i]->m_name + ":" +
std::to_string(int(SwitchExtension->iNextDirection[i])));
}
};
bool
TTrack::DoubleSlip() const {
// crude way to discern part of double slip switch:
// a switch with name ending in _a or _b or _c or _d
return iCategoryFlag == 1 && eType == tt_Switch && m_name.size() > 2 && m_name.back() >= 'a' && m_name.back() <= 'd' &&
(m_name[m_name.size() - 2] == '_' || m_name.rfind('_') != std::string::npos);
}
namespace {
// the track joined at the end of a path of the switch in the direction (s) gives, turning (d) where it runs the other way
TTrack *switch_path_neighbour( TSwitchExtension const &Extension, int const s, double &d, int const Path ) {
auto *const t { s > 0 ? Extension.pNexts[ Path ] : Extension.pPrevs[ Path ] };
if( t != nullptr && t->eType != tt_Cross && ( s > 0 ? Extension.iNextDirection[ Path ] : !Extension.iPrevDirection[ Path ] ) ) {
d = -d;
}
return t;
}
// the track joined at the end of the crossroads left in the direction (s) gives, turning (d) where it runs the other way
TTrack *crossroads_neighbour( TSwitchExtension const &Extension, int const s, double &d ) {
switch (Extension.iRoads == 4 ? iEnds4[s + 6] :
iEnds3[s + 6]) // numer końca 0..3, -1 to błąd
{ // zjazd ze skrzyżowania
case 0:
if (Extension.pPrevs[0] && (s > 0) == Extension.iPrevDirection[0])
d = -d;
return Extension.pPrevs[0];
case 1:
if (Extension.pNexts[0] && (s > 0) == Extension.iNextDirection[0])
d = -d;
return Extension.pNexts[0];
case 2:
if (Extension.pPrevs[1] && (s > 0) == Extension.iPrevDirection[1])
d = -d;
return Extension.pPrevs[1];
case 3:
if (Extension.pNexts[1] && (s > 0) == Extension.iNextDirection[1])
d = -d;
return Extension.pNexts[1];
default:
// no such end
break;
}
return nullptr;
}
} // namespace
TTrack * TTrack::Connected(int s, double &d, int const Path) const
{ // zwraca wskaźnik na sąsiedni tor, w kierunku określonym znakiem (s), odwraca (d) w razie
// niezgodności kierunku torów
TTrack *t; // nie zmieniamy kierunku (d), jeśli nie ma toru dalej
if( eType == tt_Switch && Path >= 0 && Path < 2 ) {
// the neighbour of the path given, not of the one the switch is set to
return switch_path_neighbour( *SwitchExtension, s, d, Path );
}
if (eType != tt_Cross)
{ // jeszcze trzeba sprawdzić zgodność
t = s > 0 ? trNext : trPrev;
if (t) // o ile jest na co przejść, zmieniamy znak kierunku na nowym torze
if (t->eType == tt_Cross)
{ // jeśli wjazd na skrzyżowanie, trzeba ustalić segment, bo od tego zależy zmiana
// kierunku (d)
// if (r) //gdy nie podano (r), to nie zmieniać (d)
// if (s*t->CrossSegment(((s>0)?iNextDirection:iPrevDirection),r)<0)
// d=-d;
}
else
{
if (s > 0 ? iNextDirection : !iPrevDirection)
d = -d; // następuje zmiana kierunku wózka albo kierunku skanowania
// s=((s>0)?iNextDirection:iPrevDirection)?-1:1; //kierunek toru po zmianie
}
return t; // zwrotnica ma odpowiednio ustawione (trNext)
}
return crossroads_neighbour( *SwitchExtension, s, d );
};
// creates rail profile data for current track
void
TTrack::create_track_rail_profile( gfx::vertex_array &Right, gfx::vertex_array &Left, gfx::vertex_array const *Shape ) const {
auto const fHTW { 0.5f * std::abs( fTrackWidth ) };
float const fHTW2{((iTrapezoid & 2) != 0 ? // ten bit oznacza, że istnieje odpowiednie pNext
0.5f * std::fabs(trNext->fTrackWidth) : // połowa rozstawu/nawierzchni
fHTW)};
float
roll1{ 0.f },
roll2{ 0.f };
profile_rolls( roll1, roll2 );
float const
sin1 { std::sin( roll1 ) },
cos1 { std::cos( roll1 ) },
sin2 { std::sin( roll2 ) },
cos2 { std::cos( roll2 ) };
auto const &railprofile { Shape != nullptr ? *Shape : track_rail_profile( m_profile1.second ) };
// NOTE: rail profile defines both regular rail and switch blade profiles, so we halve total point count
auto const pointcount { Shape != nullptr ? railprofile.size() : railprofile.size() / 2 };
Right.resize( pointcount * ( iTrapezoid == 0 ? 1 : 2 ) );
Left.resize( pointcount * ( iTrapezoid == 0 ? 1 : 2 ) );
auto const *szyna { railprofile.data() };
for( int i = 0; i < pointcount; ++i ) {
Right[ i ] = {
// position
{( fHTW + szyna[ i ].position.x ) * cos1 + szyna[ i ].position.y * sin1,
-( fHTW + szyna[ i ].position.x ) * sin1 + szyna[ i ].position.y * cos1,
szyna[ i ].position.z},
// normal
{ szyna[ i ].normal.x * cos1 + szyna[ i ].normal.y * sin1,
-szyna[ i ].normal.x * sin1 + szyna[ i ].normal.y * cos1,
szyna[ i ].normal.z },
// texture
{ szyna[ i ].texture.s,
szyna[ i ].texture.t } };
Left[ pointcount - 1 - i ] = {
// position
{(-fHTW - szyna[ i ].position.x ) * cos1 + szyna[ i ].position.y * sin1,
-(-fHTW - szyna[ i ].position.x ) * sin1 + szyna[ i ].position.y * cos1,
szyna[ i ].position.z},
// normal
{-szyna[ i ].normal.x * cos1 + szyna[ i ].normal.y * sin1,
szyna[ i ].normal.x * sin1 + szyna[ i ].normal.y * cos1,
szyna[ i ].normal.z },
// texture
{ szyna[ i ].texture.s,
szyna[ i ].texture.t } };
if( iTrapezoid == 0 ) { continue; }
// trapez albo przechyłki, to oddzielne punkty na końcu
Right[ pointcount + i ] = {
// position
{( fHTW2 + szyna[ i ].position.x ) * cos2 + szyna[ i ].position.y * sin2,
-( fHTW2 + szyna[ i ].position.x ) * sin2 + szyna[ i ].position.y * cos2,
szyna[ i ].position.z},
// normal
{ szyna[ i ].normal.x * cos2 + szyna[ i ].normal.y * sin2,
-szyna[ i ].normal.x * sin2 + szyna[ i ].normal.y * cos2,
szyna[ i ].normal.z },
// texture
{ szyna[ i ].texture.s,
szyna[ i ].texture.t } };
Left[ pointcount * 2 - 1 - i ] = {
// position
{(-fHTW2 - szyna[ i ].position.x ) * cos2 + szyna[ i ].position.y * sin2,
-(-fHTW2 - szyna[ i ].position.x ) * sin2 + szyna[ i ].position.y * cos2,
szyna[ i ].position.z},
// normal
{-szyna[ i ].normal.x * cos2 + szyna[ i ].normal.y * sin2,
szyna[ i ].normal.x * sin2 + szyna[ i ].normal.y * cos2,
szyna[ i ].normal.z },
// texture
{ szyna[ i ].texture.s,
szyna[ i ].texture.t } };
}
}
void
TTrack::profile_rolls( float &Roll1, float &Roll2 ) const {
Roll1 = 0.f;
Roll2 = 0.f;
if( eType == tt_Switch && SwitchExtension ) {
auto sum { 0.f };
for( int path = 0; path < 2; ++path ) {
float roll1 { 0.f };
float roll2 { 0.f };
SwitchExtension->Segments[ path ]->GetRolls( roll1, roll2 );
sum += roll1 + roll2;
}
Roll1 = 0.25f * sum;
Roll2 = Roll1;
return;
}
if( Segment ) {
Segment->GetRolls( Roll1, Roll2 );
}
}
// creates switch blades profile data for current track
void
TTrack::create_track_blade_profile( gfx::vertex_array &Right, gfx::vertex_array &Left ) {
auto const fHTW { 0.5f * std::abs( fTrackWidth ) };
float const fHTW2 { (
( iTrapezoid & 2 ) != 0 ? // ten bit oznacza, że istnieje odpowiednie pNext
0.5f * std::fabs( trNext->fTrackWidth ) : // połowa rozstawu/nawierzchni
fHTW ) };
float
roll1 { 0.f },
roll2 { 0.f };
profile_rolls( roll1, roll2 );
float const
sin1 { std::sin( roll1 ) },
cos1 { std::cos( roll1 ) },
sin2 { std::sin( roll2 ) },
cos2 { std::cos( roll2 ) };
auto const &railprofile { track_rail_profile( m_profile1.second ) };
// NOTE: rail profile defines both regular rail and switch blade profiles, so we halve total point count
auto const pointcount { railprofile.size() / 2 };
Right.resize( pointcount * 2 );
Left.resize( pointcount * 2 );
auto const *szyna { railprofile.data() };
auto const *iglica { szyna + pointcount };
glm::vec3 const flipxvalue { -1, 1, 1 };
for( int i = 0; i < pointcount; ++i ) {
Right[ i ] = {
{+( fHTW + iglica[ i ].position.x ) * cos1 + iglica[ i ].position.y * sin1,
-( fHTW + iglica[ i ].position.x ) * sin1 + iglica[ i ].position.y * cos1,
0.f},
{iglica[ i ].normal},
{iglica[ i ].texture.s, 0.f} };
Right[ i + pointcount ] = {
{+( fHTW2 + szyna[ i ].position.x ) * cos2 + szyna[ i ].position.y * sin2,
-( fHTW2 + szyna[ i ].position.x ) * sin2 + szyna[ i ].position.y * cos2,
0.f},
{szyna[ i ].normal},
{szyna[ i ].texture.s, 0.f} };
Left[ pointcount - 1 - i ] = {
{ ( -fHTW - iglica[ i ].position.x ) * cos1 + iglica[ i ].position.y * sin1,
-( -fHTW - iglica[ i ].position.x ) * sin1 + iglica[ i ].position.y * cos1,
0.f},
{iglica[ i ].normal * flipxvalue},
{iglica[ i ].texture.s, 0.f} };
Left[ pointcount * 2 - 1 - i ] = {
{ ( -fHTW2 - szyna[ i ].position.x ) * cos2 + szyna[ i ].position.y * sin2,
-( -fHTW2 - szyna[ i ].position.x ) * sin2 + szyna[ i ].position.y * cos2,
0.f},
{szyna[ i ].normal * flipxvalue},
{szyna[ i ].texture.s, 0.f} };
}
}
// creates trackbed profile data for current track
void
TTrack::create_track_bed_profile( gfx::vertex_array &Output, TTrack const *Previous, TTrack const *Next ) {
// geometry parameters
auto * profilesource = eType != tt_Switch ? this : Previous && Previous->eType != tt_Switch ? Previous : Next && Next->eType != tt_Switch ? Next : this;
auto const texheight1 { profilesource->fTexHeight1 };
auto const texwidth { profilesource->fTexWidth };
auto const texslope { profilesource->fTexSlope };
auto const fHTW { 0.5f * std::abs( fTrackWidth ) };
auto const side { std::abs( texwidth ) }; // szerokść podsypki na zewnątrz szyny albo pobocza
auto const slop { std::abs( texslope ) }; // brzeg zewnętrzny
auto const rozp { fHTW + side + slop }; // brzeg zewnętrzny
auto hypot1 { std::hypot( slop, texheight1 ) }; // rozmiar pochylenia do liczenia normalnych
if( hypot1 == 0.f )
hypot1 = 1.f;
glm::vec3 normal1 { texheight1 / hypot1, texslope / hypot1, 0.f }; // wektor normalny
if( glm::length( normal1 ) == 0.f ) {
// fix normal for vertical surfaces
normal1 = glm::vec3 { 1.f, 0.f, 0.f };
}
glm::vec3 normal2;
float fHTW2, side2, slop2, rozp2, fTexHeight2, hypot2;
if( Next != nullptr
&& Next->eType != tt_Switch
&& ( iTrapezoid & 2 // ten bit oznacza, że istnieje odpowiednie pNext
|| eType == tt_Switch ) ) {
fHTW2 = 0.5f * std::abs(Next->fTrackWidth); // połowa rozstawu/nawierzchni
side2 = std::abs(Next->fTexWidth);
slop2 = std::abs(Next->fTexSlope); // nie jest używane później
rozp2 = fHTW2 + side2 + slop2;
fTexHeight2 = Next->fTexHeight1;
hypot2 = std::hypot(slop2, fTexHeight2);
if( hypot2 == 0.f )
hypot2 = 1.f;
normal2 = { fTexHeight2 / hypot2, Next->fTexSlope / hypot2, 0.f };
if( glm::length( normal2 ) == 0.f ) {
// fix normal for vertical surfaces
normal2 = glm::vec3 { 1.f, 0.f, 0.f };
}
}
else {
// gdy nie ma następnego albo jest nieodpowiednim końcem podpięty
fHTW2 = fHTW;
side2 = side;
slop2 = slop;
rozp2 = rozp;
fTexHeight2 = texheight1;
hypot2 = hypot1;
normal2 = normal1;
}
float
roll1{ 0.f },
roll2{ 0.f };
profile_rolls( roll1, roll2 );
float const
sin1 { std::sin( roll1 ) },
cos1 { std::cos( roll1 ) },
sin2 { std::sin( roll2 ) },
cos2 { std::cos( roll2 ) };
// profile
auto const transition { iTrapezoid != 0 || eType == tt_Switch };
auto const pointcount { transition ? 10 : 5 };
Output.resize( pointcount );
// potentially retrieve texture length override from the assigned material
auto const texturelength { texture_length( copy_adjacent_trackbed_material() ) };
auto const railheight { std::abs( track_rail_profile( m_profile1.second ).front().position.y ) };
if( texturelength == 4.f ) {
// stare mapowanie z różną gęstością pikseli i oddzielnymi teksturami na każdy profil
auto const normalx = std::cos( glm::radians( 75.f ) );
auto const normaly = std::sin( glm::radians( 75.f ) );
if( transition ) {
// trapez albo przechyłki
// ewentualnie poprawić mapowanie, żeby środek mapował się na 1.435/4.671 ((0.3464,0.6536)
// bo się tekstury podsypki rozjeżdżają po zmianie proporcji profilu
Output[ 0 ] = {
{rozp, -texheight1 - railheight, 0.f},
{normalx, normaly, 0.f},
{0.00f, 0.f} }; // lewy brzeg
Output[ 1 ] = {
{( fHTW + side ) * cos1, -( fHTW + side ) * sin1 - railheight, 0.f},
{normalx, normaly, 0.f},
{0.33f, 0.f} }; // krawędź załamania
Output[ 2 ] = {
{0.f, -railheight + 0.01f, 0.f},
{0.f, 1.f, 0.f},
{0.5f, 0.f} }; // middle
Output[ 3 ] = {
{-Output[ 1 ].position.x, +( fHTW + side ) * sin1 - railheight, 0.f},
{-normalx, normaly, 0.f},
{0.67f, 0.f} }; // prawy brzeg początku symetrycznie
Output[ 4 ] = {
{-rozp, -texheight1 - railheight, 0.f},
{-normalx, normaly, 0.f},
{1.f, 0.f} }; // prawy skos
// końcowy przekrój
Output[ 5 ] = {
{rozp2, -fTexHeight2 - railheight, 0.f},
{normalx, normaly, 0.f},
{0.00f, 0.f} }; // lewy brzeg
Output[ 6 ] = {
{( fHTW2 + side2 ) * cos2, -( fHTW2 + side2 ) * sin2 - railheight, 0.f},
{normalx, normaly, 0.f},
{0.33f, 0.f} }; // krawędź załamania
Output[ 7 ] = {
{0.f, -railheight + 0.01f, 0.f},
{0.f, 1.f, 0.f},
{0.5f, 0.f} }; // middle
Output[ 8 ] = {
{-Output[ 6 ].position.x, +( fHTW2 + side2 ) * sin2 - railheight, 0.f},
{-normalx, normaly, 0.f},
{0.67f, 0.f} }; // prawy brzeg początku symetrycznie
Output[ 9 ] = {
{-rozp2, -fTexHeight2 - railheight, 0.f},
{-normalx, normaly, 0.f},
{1.00f, 0.f} }; // prawy skos
}
else {
Output[ 0 ] = {
{rozp, -texheight1 - railheight, 0.f},
{normalx, normaly, 0.f},
{0.00f, 0.f} }; // lewy brzeg
Output[ 1 ] = {
{fHTW + side, -railheight, 0.f},
{normalx, normaly, 0.f},
{0.33f, 0.f} }; // krawędź załamania
Output[ 2 ] = {
{0.f, -railheight + 0.01f, 0.f},
{0.f, 1.f, 0.f},
{0.5f, 0.f} }; // middle
Output[ 3 ] = {
{-fHTW - side, -railheight, 0.f},
{-normalx, normaly, 0.f},
{0.67f, 0.f} }; // druga
Output[ 4 ] = {
{-rozp, -texheight1 - railheight, 0.f},
{-normalx, normaly, 0.f},
{1.00f, 0.f} }; // prawy skos
}
}
else {
// mapowanie proporcjonalne do powierzchni, rozmiar w poprzek określa fTexLength
auto const max = fTexRatio2 * texturelength; // szerokość proporcjonalna do długości
auto const map11 = max > 0.f ? (fHTW + side) / max : 0.25f; // załamanie od strony 1
auto const map12 = max > 0.f ? (fHTW + side + hypot1) / max : 0.5f; // brzeg od strony 1
if (transition) {
// trapez albo przechyłki
auto const map21 = max > 0.f ? (fHTW2 + side2) / max : 0.25f; // załamanie od strony 2
auto const map22 = max > 0.f ? (fHTW2 + side2 + hypot2) / max : 0.5f; // brzeg od strony 2
// ewentualnie poprawić mapowanie, żeby środek mapował się na 1.435/4.671
// ((0.3464,0.6536)
// bo się tekstury podsypki rozjeżdżają po zmianie proporcji profilu
Output[ 0 ] = {
{rozp, -texheight1 - railheight, 0.f},
{normal1.x, normal1.y, 0.f},
{0.5f - map12, 0.f} }; // lewy brzeg
Output[ 1 ] = {
{( fHTW + side ) * cos1, -( fHTW + side ) * sin1 - railheight, 0.f},
{normal1.x, normal1.y, 0.f},
{0.5f - map11 , 0.f} }; // krawędź załamania
Output[ 2 ] = {
{0.f, -railheight + 0.01f, 0.f},
{0.f, 1.f, 0.f},
{0.5f, 0.f} }; // middle
Output[ 3 ] = {
{-Output[ 1 ].position.x, +( fHTW + side ) * sin1 - railheight, 0.f},
{-normal1.x, normal1.y, 0.f},
{0.5 + map11, 0.f} }; // prawy brzeg początku symetrycznie
Output[ 4 ] = {
{-rozp, -texheight1 - railheight, 0.f},
{-normal1.x, normal1.y, 0.f},
{0.5f + map12, 0.f} }; // prawy skos
// przekrój końcowy
Output[ 5 ] = {
{rozp2, -fTexHeight2 - railheight, 0.f},
{normal2.x, normal2.y, 0.f},
{0.5f - map22, 0.f} }; // lewy brzeg
Output[ 6 ] = {
{( fHTW2 + side2 ) * cos2, -( fHTW2 + side2 ) * sin2 - railheight, 0.f},
{normal2.x, normal2.y, 0.f},
{0.5f - map21 , 0.f} }; // krawędź załamania
Output[ 7 ] = {
{0.f, -railheight + 0.01f, 0.f},
{0.f, 1.f, 0.f},
{0.5f, 0.f} }; // middle
Output[ 8 ] = {
{-Output[ 6 ].position.x, +( fHTW2 + side2 ) * sin2 - railheight, 0.f},
{-normal2.x, normal2.y, 0.f},
{0.5f + map21, 0.f} }; // prawy brzeg początku symetrycznie
Output[ 9 ] = {
{-rozp2, -fTexHeight2 - railheight, 0.f},
{-normal2.x, normal2.y, 0.f},
{0.5f + map22, 0.f} }; // prawy skos
}
else
{
Output[ 0 ] = {
{rozp, -texheight1 - railheight, 0.f},
{+normal1.x, normal1.y, 0.f},
{0.5f - map12, 0.f} }; // lewy brzeg
Output[ 1 ] = {
{fHTW + side, - railheight, 0.f},
{+normal1.x, normal1.y, 0.f},
{0.5f - map11, 0.f} }; // krawędź załamania
Output[ 2 ] = {
{0.f, -railheight + 0.01f, 0.f},
{0.f, 1.f, 0.f},
{0.5f, 0.f} }; // middle
Output[ 3 ] = {
{-fHTW - side, - railheight, 0.f},
{-normal1.x, normal1.y, 0.f},
{0.5f + map11, 0.f} }; // druga
Output[ 4 ] = {
{-rozp, -texheight1 - railheight, 0.f},
{-normal1.x, normal1.y, 0.f},
{0.5f + map12, 0.f} }; // prawy skos
}
}
if( m_sleepers3d.active ) {
// the ballast lowered under the sleepers laid on it, so they stick out of it
for( auto &point : Output ) {
point.position.y -= static_cast<float>( track_sleepers::bed_drop );
}
}
}
// creates road profile data for current path
void
TTrack::create_road_profile( gfx::vertex_array &Output, bool const Forcetransition ) {
auto const fHTW { 0.5f * std::abs( fTrackWidth ) };
float const fHTW2 { (
( iTrapezoid & 2 ) != 0 ? // ten bit oznacza, że istnieje odpowiednie pNext
0.5f * std::fabs( trNext->fTrackWidth ) : // połowa rozstawu/nawierzchni
fHTW ) };
glm::vec3 const normalup { 0.f, 1.f, 0.f };
auto const texturelength { texture_length( m_material1 ) };
auto const max = fTexRatio1 * texturelength; // test: szerokość proporcjonalna do długości
auto const map1 = max > 0.f ? fHTW / max : 0.5f; // obcięcie tekstury od strony 1
auto const map2 = max > 0.f ? fHTW2 / max : 0.5f; // obcięcie tekstury od strony 2
auto const transition { true == Forcetransition || iTrapezoid != 0 };
auto const pointcount{ transition ? 4 : 2 };
Output.resize( pointcount );
if( transition ) {
// trapez albo przechyłki
float
roll1 { 0.f },
roll2 { 0.f };
if( Segment ) {
Segment->GetRolls( roll1, roll2 );
}
Output[ 0 ] = {
{fHTW * std::cos( roll1 ), -fHTW * std::sin( roll1 ), 0.f},
normalup,
{0.5f - map1, 0.f} }; // lewy brzeg początku
Output[ 1 ] = {
{-Output[ 0 ].position.x, -Output[ 0 ].position.y, 0.f},
normalup,
{0.5f + map1, 0.f} }; // prawy brzeg początku symetrycznie
Output[ 2 ] = {
{fHTW2 * std::cos( roll2 ), -fHTW2 * std::sin( roll2 ), 0.f},
normalup,
{0.5f - map2, 0.f} }; // lewy brzeg końca
Output[ 3 ] = {
{-Output[ 2 ].position.x, -Output[ 2 ].position.y, 0.f},
normalup,
{0.5f + map2, 0.f} }; // prawy brzeg początku symetrycznie
}
else {
Output[ 0 ] = {
{fHTW, 0.f, 0.f},
normalup,
{0.5f - map1, 0.f} };
Output[ 1 ] = {
{-fHTW, 0.f, 0.f},
normalup,
{0.5f + map1, 0.f} };
}
}
void
TTrack::create_road_side_profile( gfx::vertex_array &Right, gfx::vertex_array &Left, gfx::vertex_array const &Road, bool const Forcetransition ) {
auto const fHTW{ 0.5f * std::abs( fTrackWidth ) };
auto const side{ std::abs( fTexWidth ) }; // szerokść podsypki na zewnątrz szyny albo pobocza
auto const slop{ std::abs( fTexSlope ) }; // brzeg zewnętrzny
auto const rozp{ fHTW + side + slop }; // brzeg zewnętrzny
float fHTW2, side2, slop2, rozp2, fTexHeight2;
if( iTrapezoid & 2 ) {
// ten bit oznacza, że istnieje odpowiednie pNext
// Ra: jest OK
fHTW2 = 0.5f * std::fabs( trNext->fTrackWidth ); // połowa rozstawu/nawierzchni
side2 = std::fabs( trNext->fTexWidth );
slop2 = std::fabs( trNext->fTexSlope ); // nie jest używane później
rozp2 = fHTW2 + side2 + slop2;
fTexHeight2 = trNext->fTexHeight1;
}
else {
// gdy nie ma następnego albo jest nieodpowiednim końcem podpięty
fHTW2 = fHTW;
side2 = side;
slop2 = slop;
rozp2 = rozp;
fTexHeight2 = fTexHeight1;
}
glm::vec3 const normalup{ 0.f, 1.f, 0.f };
auto const texturelength{ texture_length( m_material2 ) };
auto const transition { true == Forcetransition || iTrapezoid != 0 };
auto const pointcount{ transition ? 6 : 3 };
Right.resize( pointcount );
Left.resize( pointcount );
if( fTexHeight1 >= 0.f ) { // standardowo: od zewnątrz pochylenie, a od wewnątrz poziomo
Right[ 0 ] = {
{rozp, -fTexHeight1, 0.f},
{ 1.f, 0.f, 0.f },
{0.f, 0.f} }; // lewy brzeg podstawy
Right[ 1 ] = {
{Road[ 0 ].position.x + side, Road[ 0 ].position.y, 0.f},
normalup,
{0.5, 0.f} }; // lewa krawędź załamania
Right[ 2 ] = {
{Road[ 0 ].position.x, Road[ 0 ].position.y, 0.f},
normalup,
{1.f, 0.f} }; // lewy brzeg pobocza (mapowanie może być inne
Left[ 0 ] = {
{Road[ 1 ].position.x, Road[ 1 ].position.y, 0.f},
normalup,
{1.f, 0.f} }; // prawy brzeg pobocza
Left[ 1 ] = {
{Road[ 1 ].position.x - side, Road[ 1 ].position.y, 0.f},
normalup,
{0.5f, 0.f} }; // prawa krawędź załamania
Left[ 2 ] = {
{-rozp, -fTexHeight1, 0.f},
{ -1.f, 0.f, 0.f },
{0.f, 0.f} }; // prawy brzeg podstawy
if( transition ) {
// pobocza do trapezowatej nawierzchni - dodatkowe punkty z drugiej strony odcinka
Right[ 3 ] = {
{rozp2, -fTexHeight2, 0.f},
{ 1.f, 0.f, 0.f },
{0.f, 0.f} }; // lewy brzeg lewego pobocza
Right[ 4 ] = {
{Road[ 2 ].position.x + side2, Road[ 2 ].position.y, 0.f},
normalup,
{0.5f, 0.f} }; // krawędź załamania
Right[ 5 ] = {
{Road[ 2 ].position.x, Road[ 2 ].position.y, 0.f},
normalup,
{1.f, 0.f} }; // brzeg pobocza
Left[ 3 ] = {
{Road[ 3 ].position.x, Road[ 3 ].position.y, 0.f},
normalup,
{1.f, 0.f} };
Left[ 4 ] = {
{Road[ 3 ].position.x - side2, Road[ 3 ].position.y, 0.f},
normalup,
{0.5f, 0.f} };
Left[ 5 ] = {
{-rozp2, -fTexHeight2, 0.f},
{ -1.f, 0.f, 0.f },
{0.f, 0.f} }; // prawy brzeg prawego pobocza
}
}
else { // wersja dla chodnika: skos 1:3.75, każdy chodnik innej szerokości
// mapowanie propocjonalne do szerokości chodnika
// krawężnik jest mapowany od 31/64 do 32/64 lewy i od 32/64 do 33/64 prawy
auto const d = -fTexHeight1 / 3.75f; // krawężnik o wysokości 150mm jest pochylony 40mm
auto const max = fTexRatio2 * texturelength; // test: szerokość proporcjonalna do długości
auto const map1l = max > 0.f ? side / max : 0.484375f; // obcięcie tekstury od lewej strony punktu 1
auto const map1r = max > 0.f ? slop / max : 0.484375f; // obcięcie tekstury od prawej strony punktu 1
auto const h1r = slop > d ? -fTexHeight1 : 0.f;
auto const h1l = side > d ? -fTexHeight1 : 0.f;
Right[ 0 ] = {
{Road[ 0 ].position.x + slop, Road[ 0 ].position.y + h1r, 0.f},
normalup,
{0.515625f + map1r, 0.f} }; // prawy brzeg prawego chodnika
Right[ 1 ] = {
{Road[ 0 ].position.x + d, Road[ 0 ].position.y + h1r, 0.f},
normalup,
{0.515625f, 0.f} }; // prawy krawężnik u góry
Right[ 2 ] = {
{Road[ 0 ].position.x, Road[ 0 ].position.y, 0.f},
{ -1.f, 0.f, 0.f },
{0.515625f - d / 2.56f, 0.f} }; // prawy krawężnik u dołu
Left[ 0 ] = {
{Road[ 1 ].position.x, Road[ 1 ].position.y, 0.f},
{ 1.f, 0.f, 0.f },
{0.484375f + d / 2.56f, 0.f} }; // lewy krawężnik u dołu
Left[ 1 ] = {
{Road[ 1 ].position.x - d, Road[ 1 ].position.y + h1l, 0.f},
normalup,
{0.484375f, 0.f} }; // lewy krawężnik u góry
Left[ 2 ] = {
{Road[ 1 ].position.x - side, Road[ 1 ].position.y + h1l, 0.f},
normalup,
{0.484375f - map1l, 0.f} }; // lewy brzeg lewego chodnika
if( transition ) {
// pobocza do trapezowatej nawierzchni - dodatkowe punkty z drugiej strony odcinka
slop2 = std::fabs(iTrapezoid & 2 ? slop2 : slop); // szerokość chodnika po prawej
auto const map2l = max > 0.f ? side2 / max : 0.484375f; // obcięcie tekstury od lewej strony punktu 2
auto const map2r = max > 0.f ? slop2 / max : 0.484375f; // obcięcie tekstury od prawej strony punktu 2
auto const h2r = slop2 > d ? -fTexHeight2 : 0.f;
auto const h2l = side2 > d ? -fTexHeight2 : 0.f;
Right[ 3 ] = {
{Road[ 2 ].position.x + slop2, Road[ 2 ].position.y + h2r, 0.f},
normalup,
{0.515625f + map2r, 0.f} }; // prawy brzeg prawego chodnika
Right[ 4 ] = {
{Road[ 2 ].position.x + d, Road[ 2 ].position.y + h2r, 0.f},
normalup,
{0.515625f, 0.f} }; // prawy krawężnik u góry
Right[ 5 ] = {
{Road[ 2 ].position.x, Road[ 2 ].position.y, 0.f},
{ -1.f, 0.f, 0.f },
{0.515625f - d / 2.56f, 0.f} }; // prawy krawężnik u dołu
Left[ 3 ] = {
{Road[ 3 ].position.x, Road[ 3 ].position.y, 0.f},
{ 1.f, 0.f, 0.f },
{0.484375f + d / 2.56f, 0.f} }; // lewy krawężnik u dołu
Left[ 4 ] = {
{Road[ 3 ].position.x - d, Road[ 3 ].position.y + h2l, 0.f},
normalup,
{0.484375f, 0.f} }; // lewy krawężnik u góry
Left[ 5 ] = {
{Road[ 3 ].position.x - side2, Road[ 3 ].position.y + h2l, 0.f},
normalup,
{0.484375f - map2l, 0.f} }; // lewy brzeg lewego chodnika
}
}
}
void
TTrack::create_switch_trackbed( gfx::vertex_array &Output ) {
// try to get trackbed material from a regular track connected to the primary path
if( SwitchExtension->m_material3 == null_handle && trPrev != nullptr
&& trPrev->eType == tt_Normal ) {
SwitchExtension->m_material3 = trPrev->m_material2;
}
if( SwitchExtension->m_material3 == null_handle && trNext != nullptr
&& trNext->eType == tt_Normal ) {
SwitchExtension->m_material3 = trNext->m_material2;
}
// without material don't bother, nor when the ballast isn't laid under the 3D sleepers
if( SwitchExtension->m_material3 == null_handle || ( m_sleepers3d.active && false == Global.Sleepers3DBed ) ) { return; }
// generate trackbed for each path of the switch...
auto const texturelength { texture_length( SwitchExtension->m_material3 ) };
gfx::vertex_array trackbedprofile;
gfx::vertex_array trackbedvertices1, trackbedvertices2;
// main trackbed
create_track_bed_profile( trackbedprofile, SwitchExtension->pPrevs[ 0 ], SwitchExtension->pNexts[ 0 ] );
SwitchExtension->Segments[ 0 ]->RenderLoft( trackbedvertices1, m_origin, trackbedprofile, true, texturelength );
// side trackbed
create_track_bed_profile( trackbedprofile, SwitchExtension->pPrevs[ 1 ], SwitchExtension->pNexts[ 1 ] );
SwitchExtension->Segments[ 1 ]->RenderLoft( trackbedvertices2, m_origin, trackbedprofile, true, texturelength );
if( trackbedvertices1.size() != trackbedvertices2.size() ) {
// a path made of several curves has more pieces than the other one, and the two are combined piece by piece,
// so both are lofted again in the same number of equal pieces, else the trackbed would end where the shorter count does
auto const steps { std::max( SwitchExtension->Segments[ 0 ]->RaSegCount(), SwitchExtension->Segments[ 1 ]->RaSegCount() ) };
trackbedvertices1.clear();
trackbedvertices2.clear();
create_track_bed_profile( trackbedprofile, SwitchExtension->pPrevs[ 0 ], SwitchExtension->pNexts[ 0 ] );
SwitchExtension->Segments[ 0 ]->RenderLoftSteps( trackbedvertices1, m_origin, trackbedprofile, texturelength, steps );
create_track_bed_profile( trackbedprofile, SwitchExtension->pPrevs[ 1 ], SwitchExtension->pNexts[ 1 ] );
SwitchExtension->Segments[ 1 ]->RenderLoftSteps( trackbedvertices2, m_origin, trackbedprofile, texturelength, steps );
}
// ...then combine them into a single geometry sequence
auto const segmentsize { 10 };
auto const segmentcount { std::min( trackbedvertices1.size(), trackbedvertices2.size() ) / segmentsize };
auto *sampler1 { trackbedvertices1.data() };
auto *sampler2 { trackbedvertices2.data() };
auto const isright { SwitchExtension->RightSwitch };
auto const isleft { false == isright };
auto const samplersoffset { isright ? 2 : 0 };
auto const geometryoffset { 0.025f };
for( int segment = 0; segment < segmentcount; ++segment ) {
// main trackbed
// lower outer edge to avoid z-fighting
if( isright ) {
( sampler1 + samplersoffset + 0 )->position.y -= geometryoffset;
( sampler1 + samplersoffset + 1 )->position.y -= geometryoffset;
}
if( isleft ) {
( sampler1 + samplersoffset + 6 )->position.y -= geometryoffset;
( sampler1 + samplersoffset + 7 )->position.y -= geometryoffset;
}
// copy the data
for( auto pointidx = 0; pointidx < segmentsize; ++pointidx ) {
Output.emplace_back( *( sampler1 + pointidx ) );
}
// side trackbed
// lower outer edge to avoid z-fighting
if( isleft ) {
( sampler2 - samplersoffset + 2 )->position.y -= geometryoffset;
( sampler2 - samplersoffset + 3 )->position.y -= geometryoffset;
}
if( isright ) {
( sampler2 - samplersoffset + 8 )->position.y -= geometryoffset;
( sampler2 - samplersoffset + 9 )->position.y -= geometryoffset;
}
// copy the data
for( auto pointidx = 0; pointidx < segmentsize; ++pointidx ) {
Output.emplace_back( *( sampler2 + pointidx ) );
}
// switch to next segment data
sampler1 += segmentsize;
sampler2 += segmentsize;
}
}
material_handle
TTrack::copy_adjacent_trackbed_material( TTrack const *Exclude ) {
if( iCategoryFlag != 1 ) { return null_handle; } // tracks only
auto &material { eType == tt_Switch ? SwitchExtension->m_material3 : m_material2 };
if( material != null_handle ) { return material; } // already has material
std::vector<TTrack *> adjacents;
switch( eType ) {
case tt_Normal: {
// for regular tracks don't set the trackbed texture if we aren't sitting next to a part of a double slip
/*
auto const hasadjacentdoubleslip {
( trPrev ? trPrev->DoubleSlip() : false )
|| ( trNext ? trNext->DoubleSlip() : false ) };
if( true == hasadjacentdoubleslip ) {
adjacents.emplace_back( trPrev );
adjacents.emplace_back( trNext );
}
*/
auto const hasadjacentswitch {
( trPrev && trPrev->eType == tt_Switch )
|| ( trNext && trNext->eType == tt_Switch ) };
// if( true == hasadjacentdoubleslip ) {
if( true == hasadjacentswitch ) {
adjacents.emplace_back( trPrev );
adjacents.emplace_back( trNext );
}
break;
}
case tt_Switch: {
// only check the neighbours of the main track
adjacents.emplace_back( SwitchExtension->pPrevs[ 0 ] );
adjacents.emplace_back( SwitchExtension->pNexts[ 0 ] );
break;
}
default: {
break;
}
}
for( auto *adjacent : adjacents ) {
if( adjacent != nullptr && adjacent != Exclude ) {
material = adjacent->copy_adjacent_trackbed_material( this );
if( material != null_handle ) { break; } // got what we wanted
}
}
return material;
}
path_table::~path_table() {
TIsolated::DeleteAll();
}
// legacy method, initializes tracks after deserialization from scenario file
void
path_table::InitTracks() {
int connection { -1 };
TTrack *matchingtrack { nullptr };
#ifdef EU07_IGNORE_LEGACYPROCESSINGORDER
for( auto *track : m_items ) {
#else
// NOTE: legacy code peformed item operations last-to-first due to way the items were added to the list
// this had impact in situations like two possible connection candidates, where only the first one would be used
for( auto first = std::rbegin(m_items); first != std::rend(m_items); ++first ) {
auto *track = *first;
#endif
track->AssignEvents();
auto const trackname { track->name() };
switch (track->eType) {
case tt_Table: {
// obrotnicę też łączymy na starcie z innymi torami
// szukamy modelu o tej samej nazwie
auto *instance = simulation::Instances.find( trackname );
// wiązanie toru z modelem obrotnicy
track->RaAssign(
instance,
simulation::Events.FindEvent( trackname + ":done" ),
simulation::Events.FindEvent( trackname + ":joined" ) );
if( instance == nullptr ) {
// jak nie ma modelu to pewnie jest wykolejnica, a ta jest domyślnie zamknięta i wykoleja
break;
}
// no break on purpose:
// "jak coś pójdzie źle, to robimy z tego normalny tor"
}
case tt_Normal: {
// tylko proste są podłączane do rozjazdów, stąd dwa rozjazdy się nie połączą ze sobą
if( track->CurrentPrev() == nullptr ) {
// tylko jeśli jeszcze nie podłączony
std::tie( matchingtrack, connection ) = simulation::Region->find_path( track->CurrentSegment()->FastGetPoint_0(), track );
switch( connection ) {
case -1: // Ra: pierwsza koncepcja zawijania samochodów i statków
// if ((Track->iCategoryFlag&1)==0) //jeśli nie jest torem szynowym
// Track->ConnectPrevPrev(Track,0); //łączenie końca odcinka do samego siebie
break;
case 0:
track->ConnectPrevPrev( matchingtrack, 0 );
break;
case 1:
track->ConnectPrevNext( matchingtrack, 1 );
break;
case 2:
track->ConnectPrevPrev( matchingtrack, 0 ); // do Point1 pierwszego
matchingtrack->SetConnections( 0 ); // zapamiętanie ustawień w Segmencie
break;
case 3:
track->ConnectPrevNext( matchingtrack, 1 ); // do Point2 pierwszego
matchingtrack->SetConnections( 0 ); // zapamiętanie ustawień w Segmencie
break;
case 4:
matchingtrack->Switch( 1 );
track->ConnectPrevPrev( matchingtrack, 2 ); // do Point1 drugiego
matchingtrack->SetConnections( 1 ); // robi też Switch(0)
matchingtrack->Switch( 0 );
break;
case 5:
matchingtrack->Switch( 1 );
track->ConnectPrevNext( matchingtrack, 3 ); // do Point2 drugiego
matchingtrack->SetConnections( 1 ); // robi też Switch(0)
matchingtrack->Switch( 0 );
break;
default:
break;
}
}
if( track->CurrentNext() == nullptr ) {
// tylko jeśli jeszcze nie podłączony
std::tie( matchingtrack, connection ) = simulation::Region->find_path( track->CurrentSegment()->FastGetPoint_1(), track );
switch( connection ) {
case -1: // Ra: pierwsza koncepcja zawijania samochodów i statków
// if ((Track->iCategoryFlag&1)==0) //jeśli nie jest torem szynowym
// Track->ConnectNextNext(Track,1); //łączenie końca odcinka do samego siebie
break;
case 0:
track->ConnectNextPrev( matchingtrack, 0 );
break;
case 1:
track->ConnectNextNext( matchingtrack, 1 );
break;
case 2:
track->ConnectNextPrev( matchingtrack, 0 );
matchingtrack->SetConnections( 0 ); // zapamiętanie ustawień w Segmencie
break;
case 3:
track->ConnectNextNext( matchingtrack, 1 );
matchingtrack->SetConnections( 0 ); // zapamiętanie ustawień w Segmencie
break;
case 4:
matchingtrack->Switch( 1 );
track->ConnectNextPrev( matchingtrack, 2 );
matchingtrack->SetConnections( 1 ); // robi też Switch(0)
// tmp->Switch(0);
break;
case 5:
matchingtrack->Switch( 1 );
track->ConnectNextNext( matchingtrack, 3 );
matchingtrack->SetConnections( 1 ); // robi też Switch(0)
// tmp->Switch(0);
break;
default:
break;
}
}
break;
}
case tt_Switch: {
// dla rozjazdów szukamy eventów sygnalizacji rozprucia
track->AssignForcedEvents(
simulation::Events.FindEvent( trackname + ":forced+" ),
simulation::Events.FindEvent( trackname + ":forced-" ) );
break;
}
default: {
break;
}
} // switch
if( trackname[0] == '*'
&& !track->CurrentPrev() && track->CurrentNext() ) {
// możliwy portal, jeśli nie podłączony od strony 1
// ustawienie flagi portalu
track->iCategoryFlag |= 0x100;
}
{
auto const inputcellname { track->m_friction.first };
if( false == inputcellname.empty() ) {
track->m_friction.second = simulation::Memory.find( inputcellname );
if( track->m_friction.second == nullptr ) {
ErrorLog( "Bad track: " + ( trackname.empty() ? "unnamed track" : "\"" + trackname + "\"" ) + " can't find assigned memory cell \"" + inputcellname + "\"" );
}
}
}
}
// the plain tracks are joined to the switches above, a switch right after another one only here, once they are. Such joints were
// left open before, so each one is told in the log, with both switches
auto switchjoints { 0 };
for( auto *track : m_items ) {
if( track->eType != tt_Switch ) {
continue;
}
for( auto const *other : track->join_switches() ) {
++switchjoints;
auto const &location { track->location() };
WriteLog( std::format( "Switch \"{}\" at {:.1f} {:.1f} joined directly to switch \"{}\"", track->name(), location.x, location.z, other->name() ) );
}
}
if( switchjoints > 0 ) {
WriteLog( std::format( "Switches joined directly to other switches: {} joints, left open before", switchjoints ) );
}
if( Global.CreateSwitchTrackbeds ) {
// do this after all connections are established, otherwise missing switch connections
// may prevent us from obtaining texture data for basic track from 'across' a switch
for( auto *track : m_items ) {
// try to assign missing trackbed materials for switches and tracks neighbouring switches
switch( track->eType ) {
case tt_Normal:
case tt_Switch: {
track->copy_adjacent_trackbed_material();
break;
}
default: {
break;
}
} // switch
}
}
auto *isolated = TIsolated::Root();
while( isolated ) {
isolated->AssignEvents();
auto *memorycell = simulation::Memory.find( isolated->asName ); // czy jest komóka o odpowiedniej nazwie
if( memorycell == nullptr ) {
// utworzenie automatycznej komórki
// TODO: determine suitable location for this one, create and add world reference node
scene::node_data nodedata;
nodedata.name = isolated->asName;
memorycell = new TMemCell( nodedata ); // to nie musi mieć nazwy, nazwa w wyszukiwarce wystarczy
// NOTE: autogenerated cells aren't exported; they'll be autogenerated anew when exported file is loaded
memorycell->is_exportable = false;
simulation::Memory.insert( memorycell );
}
// przypisanie powiązanej komórki
isolated->pMemCell = memorycell;
isolated = isolated->Next();
}
// the physics goes by the cant at the joints too, and comes before any geometry is made
for( auto *track : m_items ) {
track->share_joints();
}
TTrack::fetch_default_profiles();
}
// legacy method, sends list of occupied paths over network
void
path_table::TrackBusyList() const {
// wysłanie informacji o wszystkich zajętych odcinkach
for( auto const *path : m_items ) {
if( false == path->name().empty() // musi być nazwa
&& false == path->Dynamics.empty() ) {
// zajęty
multiplayer::WyslijString( path->name(), 8 );
}
}
}
// legacy method, sends list of occupied path sections over network
void
path_table::IsolatedBusyList() const {
// wysłanie informacji o wszystkich odcinkach izolowanych
TIsolated *Current;
for( Current = TIsolated::Root(); Current; Current = Current->Next() ) {
if( Current->Busy() ) { multiplayer::WyslijString( Current->asName, 11 ); }
else { multiplayer::WyslijString( Current->asName, 10 ); }
}
multiplayer::WyslijString( "none", 10 ); // informacja o końcu listy
}
// legacy method, sends state of specified path section over network
void
path_table::IsolatedBusy( std::string const &Name ) const {
// wysłanie informacji o odcinku izolowanym (t)
// Ra 2014-06: do wyszukania użyć drzewka nazw
TIsolated *Current;
for( Current = TIsolated::Root(); Current; Current = Current->Next() ) {
if( Current->asName == Name ) {
if( Current->Busy() ) { multiplayer::WyslijString( Current->asName, 11 ); }
else { multiplayer::WyslijString( Current->asName, 10 ); }
// nie sprawdzaj dalszych
return;
}
}
multiplayer::WyslijString( Name, 10 ); // wolny (technically not found but, eh)
}
namespace {
// Returns the list of segments to walk when laying out sleepers for a given track.
// For plain tracks/turntables we just use the active Segment. For switches, crossings
// and tributaries we use every initialised sub-path so the user gets sleepers covering
// the full footprint of the junction (not just the currently-selected route).
std::vector<TSegment *> sleeper_segments_for( TTrack const &Track )
{
std::vector<TSegment *> out;
switch( Track.eType ) {
case tt_Switch:
case tt_Tributary: {
// both main + diverging branches
if( Track.SwitchExtension ) {
for( int i = 0; i < 2; ++i ) {
auto *seg = Track.SwitchExtension->Segments[ i ].get();
if( seg != nullptr ) { out.push_back( seg ); }
}
}
break;
}
case tt_Cross: {
// a road crossing potentially holds up to 6 connection segments; iterate them all,
// skipping zero-length / null entries.
if( Track.SwitchExtension ) {
for( int i = 0; i < 6; ++i ) {
auto *seg = Track.SwitchExtension->Segments[ i ].get();
if( seg == nullptr ) { continue; }
if( seg->GetLength() <= 0.0 ) { continue; }
out.push_back( seg );
}
}
break;
}
case tt_Normal:
case tt_Table:
default: {
if( Track.Segment ) { out.push_back( Track.Segment.get() ); }
break;
}
}
return out;
}
// Local-space transform (relative to Origin) of the sleeper at distance S along the Segment,
// or none at a degenerate spot (e.g. zero-length sub-segment) where no tangent can be taken.
// Eps is the half-span of the central difference used to extract the tangent.
std::optional<glm::mat4> sleeper_transform( TSegment const &Segment, double const S, double const Eps, glm::dvec3 const &Origin, glm::vec3 const &Offset )
{
glm::dvec3 pos;
glm::vec3 angles;
Segment.RaPositionGet( S, pos, angles );
// tangent direction via central difference (clamped to the segment endpoints)
glm::dvec3 p_back;
glm::dvec3 p_fwd;
glm::vec3 dummy;
Segment.RaPositionGet( std::max( 0.0, S - Eps ), p_back, dummy );
Segment.RaPositionGet( std::min( Segment.GetLength(), S + Eps ), p_fwd, dummy );
auto tangent = glm::vec3( p_fwd - p_back );
if( glm::length2( tangent ) < 1e-8f ) {
// skip this position rather than emit a junk transform with NaN normals.
return std::nullopt;
}
tangent = glm::normalize( tangent );
// build an orthonormal basis around the tangent. world up is the reference; if the
// track is almost vertical we fall back to world X so cross() doesn't collapse.
glm::vec3 up_ref { 0.f, 1.f, 0.f };
if( std::abs( glm::dot( tangent, up_ref ) ) > 0.999f ) { up_ref = glm::vec3( 1.f, 0.f, 0.f ); }
glm::vec3 side = glm::normalize( glm::cross( up_ref, tangent ) );
glm::vec3 up = glm::cross( tangent, side );
// apply track roll (banking) around the tangent / forward axis.
if( float const roll = angles.x; roll != 0.f ) {
auto const roll_mat = glm::rotate( glm::mat4( 1.f ), roll, tangent );
side = glm::vec3( roll_mat * glm::vec4( side, 0.f ) );
up = glm::vec3( roll_mat * glm::vec4( up, 0.f ) );
}
// assemble local transform: columns are (right, up, forward, translation).
// a sleeper modelled with X = sideways, Y = up, Z = along-track now ends up
// correctly oriented along the path tangent regardless of curve direction.
auto const localpos = glm::vec3( pos - Origin );
glm::mat4 m { 1.f };
m[ 0 ] = glm::vec4( side, 0.f );
m[ 1 ] = glm::vec4( up, 0.f );
m[ 2 ] = glm::vec4( tangent, 0.f );
m[ 3 ] = glm::vec4( localpos, 1.f );
if( Offset != glm::vec3( 0.f ) ) {
m = glm::translate( m, Offset );
}
return m;
}
} // anonymous namespace
// Resolves the sleeper model + (optional) replacable skin via the global model/material
// managers, then walks every active sub-segment at the configured spacing and bakes a
// local-space transform matrix (relative to m_origin) for every instance. The renderer
// turns these into final camera-space modelview matrices at draw time.
//
// Per-instance orientation is built from an explicit tangent-based basis (right, up, forward)
// rather than RPY-decomposed angles, so curves and switches stay aligned with the path
// regardless of where they live in the parameter space.
void TTrack::build_sleeper_transforms()
{
m_sleeper_local_transforms.clear();
m_sleeper_model = nullptr;
m_sleeper_skin = 0;
if( false == m_sleeper_enabled ) { return; }
if( m_sleeper_model_name.empty() ) { return; }
if( m_sleeper_frequency <= 0.01f ) { return; }
auto const segments = sleeper_segments_for( *this );
if( segments.empty() ) { return; }
// resolve model
m_sleeper_model = TModelsManager::GetModel( m_sleeper_model_name, false );
if( m_sleeper_model == nullptr ) {
ErrorLog( "Bad track: sleepermodel model \"" + m_sleeper_model_name + "\" failed to load for track \"" + m_name + "\"" );
m_sleeper_enabled = false;
return;
}
// resolve replacable skin (optional)
if( false == m_sleeper_skin_name.empty() && m_sleeper_skin_name != "none" ) {
auto skinpath { m_sleeper_skin_name };
replace_slashes( skinpath );
m_sleeper_skin = GfxRenderer->Fetch_Material( skinpath );
}
auto const spacing = static_cast<double>( m_sleeper_frequency );
// small finite-difference epsilon used to extract the tangent from RaPositionGet.
// RaPositionGet's reported angles are correct in principle but for curves they're
// derived from the polynomial first derivative, which is sensitive to numerical noise
// at the segment endpoints. Sampling positions directly is robust for both straight
// segments and bezier curves, and it costs us two extra evaluations per sleeper.
double const eps = std::min( 0.1, spacing * 0.25 );
// user offset is (left/right, forward/back, up/down) in the local frame established by
// the basis below (x=right, y=up, z=forward). swap y<->z to match the documented axes.
glm::vec3 const local_offset { m_sleeper_offset.x, m_sleeper_offset.z, m_sleeper_offset.y };
for( auto const *segment : segments ) {
auto const length = segment->GetLength();
if( length <= 0.0 ) { continue; }
// start half a frequency in so the first sleeper doesn't sit on the joint.
auto const start = std::min( spacing * 0.5, length * 0.5 );
auto const expected = static_cast<std::size_t>( std::max( 0.0, ( length - start ) / spacing ) ) + 1u;
m_sleeper_local_transforms.reserve( m_sleeper_local_transforms.size() + expected );
for( std::size_t sleeperidx = 0;; ++sleeperidx ) {
auto const s = start + static_cast<double>( sleeperidx ) * spacing;
if( s >= length ) { break; }
if( auto const transform = sleeper_transform( *segment, s, eps, m_origin, local_offset ) ) {
m_sleeper_local_transforms.emplace_back( *transform );
}
}
}
}