From e6fa206e47e65def1acfbf53d17af55f8351ed8a Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Wed, 11 Nov 2026 21:34:39 +0100 Subject: [PATCH] Split stack 3-5c into master (switch blades, 3D sleepers, editor core, SRK stations, tutorial) (#289) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 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 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 9ffed96ec1af6cdafd918ab1ca4c0d75bbd334f5) * 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 :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 _.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 _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 _.scm, any included file named *_.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", 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. _.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/.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 : 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. - 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: , depth: }`: 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 * 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 * 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=", 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 Co-authored-by: maj00r * 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. , 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 --------- Co-authored-by: maj00r Co-authored-by: Hirek193 Co-authored-by: jerrrrycho --- CMakeLists.txt | 75 +- McZapkie/MOVER.h | 2 + McZapkie/Mover.cpp | 2 + application/application.cpp | 25 +- application/editorgestures.h | 251 + application/editormode.cpp | 2903 ++++- application/editormode.h | 2269 +++- application/editormodeconnection.cpp | 615 + application/editormodeconnectioncurve.cpp | 1124 ++ application/editormodedigitize.cpp | 424 + application/editormodegauge.cpp | 207 +- application/editormodegauge.h | 96 + application/editormodegradeline.cpp | 739 ++ application/editormodeinfra.cpp | 423 +- application/editormodejoints.cpp | 467 +- application/editormodejoints.h | 100 + application/editormodekm.cpp | 1026 ++ application/editormodekm.h | 102 + application/editormodelay.cpp | 2515 ++++ application/editormodelineside.cpp | 839 +- application/editormodelineside.h | 156 + application/editormodeminimap.cpp | 530 + application/editormodeminimap.h | 85 + application/editormodenmt.cpp | 4573 +++++++ application/editormodeparallel.cpp | 235 +- application/editormodeparallel.h | 61 + application/editormodeprofile.cpp | 1913 ++- application/editormoderecords.cpp | 576 + application/editormoderide.cpp | 684 ++ application/editormoderide.h | 113 + application/editormoderoad.cpp | 892 +- application/editormoderoute.cpp | 2423 ++++ application/editormodeselection.cpp | 11 +- application/editormodeselftest.cpp | 1368 +-- application/editormodeselftest.h | 46 + application/editormodeselftestjoin.cpp | 1396 +++ application/editormodeselftestmonkey.cpp | 362 + application/editormodeselftestrails.cpp | 1089 ++ application/editormodeselftestscene.cpp | 632 + application/editormodeselftestsignal.cpp | 476 + application/editormodeselftestsleepers.cpp | 164 + application/editormodeselftestsweep.cpp | 301 + application/editormodeselftestswitch.cpp | 1146 ++ application/editormodeselftestterrain.cpp | 1312 ++ application/editormodeselftesttrack.cpp | 994 ++ application/editormodeshared.h | 434 + application/editormodesignal.cpp | 3141 ++++- application/editormodespeed.cpp | 145 +- application/editormodespeed.h | 56 + application/editormodesrk.cpp | 6053 ++++++++++ application/editormodesrk.h | 480 + application/editormodestraights.cpp | 1354 +++ application/editormodesweep.cpp | 1171 +- application/editormodeswitchdesign.cpp | 958 ++ application/editormodeswitchdrive.cpp | 477 + application/editormodeswitchplace.cpp | 2557 ++++ application/editormodeswitchslide.cpp | 1282 ++ application/editormodeswitchtemplate.cpp | 683 ++ application/editormodeswitchtool.cpp | 352 + application/editormodetextures.cpp | 26 +- application/editormodetrack.cpp | 6668 +++------- application/editormodetrackbed.cpp | 172 + application/editormodetrackgizmo.cpp | 755 ++ application/editormodetrackprops.cpp | 2181 ++++ application/editormodetrackshared.h | 336 + application/editormodetrackux.cpp | 1403 ++- application/editormodeturntable.cpp | 188 +- application/editormodevehicle.cpp | 328 +- application/editormodevehicle.h | 80 + application/editormodeviewport.cpp | 208 +- application/editorprojection.h | 8 +- application/editortool.h | 297 + application/editoruilayer.cpp | 86 +- application/editoruilayer.h | 30 + application/editoruipanels.cpp | 315 +- application/editoruipanels.h | 6 + application/scenarioloadermode.cpp | 3 +- application/scriptedinput.cpp | 260 + application/scriptedinput.h | 65 + application/uilayer.cpp | 1 + application/uilayer.h | 2 + editor/editorAlignment.cpp | 4143 ++++++- editor/editorAlignment.hpp | 289 +- editor/editorAlignmentStore.cpp | 1072 ++ editor/editorAlignmentStore.hpp | 130 + editor/editorClips.cpp | 139 + editor/editorClips.hpp | 69 + editor/editorConnections.cpp | 626 + editor/editorConnections.hpp | 107 + editor/editorFormat.hpp | 8 + editor/editorFouling.cpp | 178 + editor/editorFouling.hpp | 57 + editor/editorGauge.cpp | 22 + editor/editorGauge.hpp | 7 + editor/editorGeoMap.cpp | 372 + editor/editorGeoMap.hpp | 101 + editor/editorGeoTiff.hpp | 121 + editor/editorGeometry.hpp | 200 +- editor/editorGroundFollow.cpp | 459 + editor/editorGroundFollow.hpp | 109 + editor/editorHttp.cpp | 268 + editor/editorHttp.hpp | 44 + editor/editorIcons.hpp | 7 + editor/editorIncludeInfo.cpp | 423 +- editor/editorIncludeInfo.hpp | 46 +- editor/editorInfra.cpp | 20 +- editor/editorInfra.hpp | 13 +- editor/editorKilometrage.cpp | 1093 ++ editor/editorKilometrage.hpp | 153 + editor/editorNmt.cpp | 489 + editor/editorNmt.hpp | 118 + editor/editorOrthophoto.cpp | 970 +- editor/editorOrthophoto.hpp | 82 +- editor/editorProfile.cpp | 1154 +- editor/editorProfile.hpp | 77 +- editor/editorRoad.cpp | 61 +- editor/editorRoad.hpp | 2 - editor/editorSettings.cpp | 150 +- editor/editorSettings.hpp | 78 +- editor/editorSpeed.cpp | 52 +- editor/editorStation.cpp | 2723 +++++ editor/editorStation.hpp | 290 + editor/editorSwitchCurve.cpp | 355 + editor/editorSwitchCurve.hpp | 100 + editor/editorSwitchDesign.cpp | 1086 ++ editor/editorSwitchDesign.hpp | 128 + editor/editorSwitchStore.cpp | 484 + editor/editorSwitchStore.hpp | 99 + editor/editorTerrainStreamer.cpp | 219 +- editor/editorTerrainStreamer.hpp | 20 + editor/editorTrack.cpp | 1595 ++- editor/editorTrack.hpp | 238 +- editor/editorTrackPresets.cpp | 233 + editor/editorTrackPresets.hpp | 58 + editor/editorTrackShape.cpp | 737 ++ editor/editorTrackTrace.cpp | 305 + editor/editorTrackTrace.hpp | 72 + editor/icons/editor_icons.png | Bin 52589 -> 50983 bytes editor/icons/editor_icons.py | 62 +- gl/ubo.cpp | 5 + gl/ubo.h | 4 + lang/editor_pl.po | 12065 ++++++++++++++++--- launcher/launchermode.cpp | 1 + launcher/launchermode.h | 6 +- launcher/scenery_list.cpp | 2 +- launcher/scenery_wizard.cpp | 585 +- launcher/scenery_wizard.h | 51 +- model/AnimModel.cpp | 19 +- model/AnimModel.h | 4 +- rendering/geometrybank.cpp | 22 +- rendering/opengl33renderer.cpp | 366 +- rendering/opengl33renderer.h | 42 + rendering/openglrenderer.cpp | 90 +- rendering/openglrenderer.h | 3 + rendering/renderer.h | 2 + scene/heightmapterrain.cpp | 37 +- scene/heightmapterrain.h | 13 + scene/scene.cpp | 13 +- scene/scene.h | 4 + scene/scenelayers.cpp | 189 +- scene/scenelayers.h | 13 +- scene/scenelayerssave.cpp | 76 +- scene/scenenode.cpp | 14 +- scene/scenenode.h | 5 +- simulation/simulationstateserializer.cpp | 2 +- staticFiles/python/local/signal_plate.py | 160 + stb/stb_image.h | 4 +- tests/unit/CMakeLists.txt | 11 + tests/unit/data/fit_past_viaduct.txt | 420 + tests/unit/data/refit_sag.txt | 358 + tests/unit/editor_stubs.cpp | 13 + tests/unit/engine_stubs.cpp | 2 +- tests/unit/test_alignment.cpp | 1164 ++ tests/unit/test_area.cpp | 88 + tests/unit/test_fouling.cpp | 115 + tests/unit/test_geotiff.cpp | 129 + tests/unit/test_ground_fit.cpp | 163 + tests/unit/test_heights.cpp | 42 + tests/unit/test_switch_curve.cpp | 246 + tests/unit/test_win1250.cpp | 8 + tools/editor/drive_headers.py | 89 + tools/editor/editor_headers.py | 91 + tools/editor/indicator_headers.py | 179 + tools/editor/signal_headers.py | 110 +- tools/editor/turntable_headers.py | 104 + tools/editor/usage_headers.py | 168 + utilities/Globals.cpp | 45 + utilities/Globals.h | 7 + utilities/parser.cpp | 9 +- utilities/translation.cpp | 66 +- utilities/translation.h | 8 +- utilities/utilities.cpp | 42 + utilities/utilities.h | 5 + vehicle/DynObj.cpp | 7 + world/EvLaunch.cpp | 2 +- world/EvLaunch.h | 2 +- world/Event.cpp | 21 + world/Event.h | 4 + world/GaugeLine.cpp | 68 + world/GaugeLine.h | 74 + world/Knots.h | 151 + world/RailCarve.cpp | 1455 +++ world/RailCrossings.cpp | 1280 ++ world/RailLayer.cpp | 1623 +++ world/RailLayout.h | 234 + world/RailMaterials.cpp | 234 + world/RailPlan.cpp | 865 ++ world/RailProfile.cpp | 175 + world/Road.cpp | 4 +- world/Road.h | 4 +- world/RoadPoint.cpp | 2 +- world/RoadPoint.h | 2 +- world/Segment.cpp | 619 +- world/Segment.h | 75 +- world/SleeperFeatures.cpp | 258 + world/SleeperFeatures.h | 47 + world/SleeperGeometry.h | 148 + world/SleeperLayout.cpp | 793 ++ world/SleeperLayout.h | 39 + world/SleeperLines.cpp | 322 + world/SleeperLines.h | 82 + world/SleeperModels.cpp | 304 + world/SleeperPaths.cpp | 387 + world/SleeperPaths.h | 133 + world/SleeperRules.h | 93 + world/SleeperWorker.cpp | 267 + world/SleeperWorker.h | 34 + world/Sweep.cpp | 2 +- world/Sweep.h | 2 +- world/Track.cpp | 895 +- world/Track.h | 81 +- world/TrackFeatures.h | 20 + world/TrackRails.h | 81 + world/TrackSleepers.cpp | 442 + world/TrackSleepers.h | 163 + world/Traction.cpp | 2 +- world/Traction.h | 2 +- 237 files changed, 106751 insertions(+), 12842 deletions(-) create mode 100644 application/editorgestures.h create mode 100644 application/editormodeconnection.cpp create mode 100644 application/editormodeconnectioncurve.cpp create mode 100644 application/editormodedigitize.cpp create mode 100644 application/editormodegauge.h create mode 100644 application/editormodegradeline.cpp create mode 100644 application/editormodejoints.h create mode 100644 application/editormodekm.cpp create mode 100644 application/editormodekm.h create mode 100644 application/editormodelay.cpp create mode 100644 application/editormodelineside.h create mode 100644 application/editormodeminimap.cpp create mode 100644 application/editormodeminimap.h create mode 100644 application/editormodenmt.cpp create mode 100644 application/editormodeparallel.h create mode 100644 application/editormoderecords.cpp create mode 100644 application/editormoderide.cpp create mode 100644 application/editormoderide.h create mode 100644 application/editormoderoute.cpp create mode 100644 application/editormodeselftest.h create mode 100644 application/editormodeselftestjoin.cpp create mode 100644 application/editormodeselftestmonkey.cpp create mode 100644 application/editormodeselftestrails.cpp create mode 100644 application/editormodeselftestscene.cpp create mode 100644 application/editormodeselftestsignal.cpp create mode 100644 application/editormodeselftestsleepers.cpp create mode 100644 application/editormodeselftestsweep.cpp create mode 100644 application/editormodeselftestswitch.cpp create mode 100644 application/editormodeselftestterrain.cpp create mode 100644 application/editormodeselftesttrack.cpp create mode 100644 application/editormodeshared.h create mode 100644 application/editormodespeed.h create mode 100644 application/editormodesrk.cpp create mode 100644 application/editormodesrk.h create mode 100644 application/editormodestraights.cpp create mode 100644 application/editormodeswitchdesign.cpp create mode 100644 application/editormodeswitchdrive.cpp create mode 100644 application/editormodeswitchplace.cpp create mode 100644 application/editormodeswitchslide.cpp create mode 100644 application/editormodeswitchtemplate.cpp create mode 100644 application/editormodeswitchtool.cpp create mode 100644 application/editormodetrackbed.cpp create mode 100644 application/editormodetrackgizmo.cpp create mode 100644 application/editormodetrackprops.cpp create mode 100644 application/editormodetrackshared.h create mode 100644 application/editormodevehicle.h create mode 100644 application/editortool.h create mode 100644 application/scriptedinput.cpp create mode 100644 application/scriptedinput.h create mode 100644 editor/editorAlignmentStore.cpp create mode 100644 editor/editorAlignmentStore.hpp create mode 100644 editor/editorClips.cpp create mode 100644 editor/editorClips.hpp create mode 100644 editor/editorConnections.cpp create mode 100644 editor/editorConnections.hpp create mode 100644 editor/editorFouling.cpp create mode 100644 editor/editorFouling.hpp create mode 100644 editor/editorGeoMap.cpp create mode 100644 editor/editorGeoMap.hpp create mode 100644 editor/editorGeoTiff.hpp create mode 100644 editor/editorGroundFollow.cpp create mode 100644 editor/editorGroundFollow.hpp create mode 100644 editor/editorHttp.cpp create mode 100644 editor/editorHttp.hpp create mode 100644 editor/editorKilometrage.cpp create mode 100644 editor/editorKilometrage.hpp create mode 100644 editor/editorNmt.cpp create mode 100644 editor/editorNmt.hpp create mode 100644 editor/editorStation.cpp create mode 100644 editor/editorStation.hpp create mode 100644 editor/editorSwitchCurve.cpp create mode 100644 editor/editorSwitchCurve.hpp create mode 100644 editor/editorSwitchDesign.cpp create mode 100644 editor/editorSwitchDesign.hpp create mode 100644 editor/editorSwitchStore.cpp create mode 100644 editor/editorSwitchStore.hpp create mode 100644 editor/editorTrackPresets.cpp create mode 100644 editor/editorTrackPresets.hpp create mode 100644 editor/editorTrackShape.cpp create mode 100644 editor/editorTrackTrace.cpp create mode 100644 editor/editorTrackTrace.hpp create mode 100644 staticFiles/python/local/signal_plate.py create mode 100644 tests/unit/data/fit_past_viaduct.txt create mode 100644 tests/unit/data/refit_sag.txt create mode 100644 tests/unit/editor_stubs.cpp create mode 100644 tests/unit/test_alignment.cpp create mode 100644 tests/unit/test_area.cpp create mode 100644 tests/unit/test_fouling.cpp create mode 100644 tests/unit/test_geotiff.cpp create mode 100644 tests/unit/test_ground_fit.cpp create mode 100644 tests/unit/test_heights.cpp create mode 100644 tests/unit/test_switch_curve.cpp create mode 100644 tools/editor/drive_headers.py create mode 100644 tools/editor/editor_headers.py create mode 100644 tools/editor/indicator_headers.py create mode 100644 tools/editor/turntable_headers.py create mode 100644 tools/editor/usage_headers.py create mode 100644 world/GaugeLine.cpp create mode 100644 world/GaugeLine.h create mode 100644 world/Knots.h create mode 100644 world/RailCarve.cpp create mode 100644 world/RailCrossings.cpp create mode 100644 world/RailLayer.cpp create mode 100644 world/RailLayout.h create mode 100644 world/RailMaterials.cpp create mode 100644 world/RailPlan.cpp create mode 100644 world/RailProfile.cpp create mode 100644 world/SleeperFeatures.cpp create mode 100644 world/SleeperFeatures.h create mode 100644 world/SleeperGeometry.h create mode 100644 world/SleeperLayout.cpp create mode 100644 world/SleeperLayout.h create mode 100644 world/SleeperLines.cpp create mode 100644 world/SleeperLines.h create mode 100644 world/SleeperModels.cpp create mode 100644 world/SleeperPaths.cpp create mode 100644 world/SleeperPaths.h create mode 100644 world/SleeperRules.h create mode 100644 world/SleeperWorker.cpp create mode 100644 world/SleeperWorker.h create mode 100644 world/TrackFeatures.h create mode 100644 world/TrackRails.h create mode 100644 world/TrackSleepers.cpp create mode 100644 world/TrackSleepers.h diff --git a/CMakeLists.txt b/CMakeLists.txt index a14c686fe..e97e41d03 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -79,6 +79,7 @@ option(WITH_CRASHPAD "Compile with crashpad" OFF) option(WITH_DISCORD_RPC "Compile with DISCORD RICH PRESENCE" ON) option(USE_LTO "Use link-time optimization" OFF) option(WITH_TESTS "Build and run the unit tests with the game, a failing test fails the build" ON) +option(WITH_EDITOR_SELFTESTS "Run the scripts of the editor and launcher self-tests named by the EU07_EDITOR_SELFTEST and EU07_LAUNCHER_SELFTEST variables" OFF) option(WITH_BETTER_RENDERER "Experimental multi-backend renderer based on NVRHI" OFF) option(GENERATE_PDB "Generate executable with program debugging symbols" ON) option(ENABLE_MCC "Enable multicore compilation" ON) @@ -97,6 +98,20 @@ set(SOURCES "model/Texture.cpp" "utilities/Timer.cpp" "world/Track.cpp" +"world/TrackSleepers.cpp" +"world/SleeperPaths.cpp" +"world/SleeperFeatures.cpp" +"world/SleeperLines.cpp" +"world/SleeperLayout.cpp" +"world/SleeperModels.cpp" +"world/SleeperWorker.cpp" +"world/GaugeLine.cpp" +"world/RailCrossings.cpp" +"world/RailMaterials.cpp" +"world/RailProfile.cpp" +"world/RailPlan.cpp" +"world/RailCarve.cpp" +"world/RailLayer.cpp" "world/TrackUneven.cpp" "world/Road.cpp" "world/Sweep.cpp" @@ -172,28 +187,66 @@ set(SOURCES "input/editorkeyboardinput.cpp" "editor/editorSettings.cpp" "editor/editorModelSets.cpp" +"editor/editorTrackPresets.cpp" "editor/editorIncludeInfo.cpp" "editor/editorTerrain.cpp" "editor/editorTrack.cpp" +"editor/editorTrackTrace.cpp" +"editor/editorFouling.cpp" "editor/editorRoad.cpp" "editor/editorAlignment.cpp" +"editor/editorTrackShape.cpp" +"editor/editorGroundFollow.cpp" +"editor/editorAlignmentStore.cpp" +"editor/editorSwitchStore.cpp" +"editor/editorSwitchCurve.cpp" +"editor/editorKilometrage.cpp" +"editor/editorStation.cpp" +"editor/editorSwitchDesign.cpp" +"editor/editorConnections.cpp" +"application/editormodeconnection.cpp" +"application/editormodeconnectioncurve.cpp" +"application/editormodedigitize.cpp" "editor/editorSpeed.cpp" "editor/editorProfile.cpp" "editor/editorGauge.cpp" "editor/editorInfra.cpp" "editor/editorTerrainStreamer.cpp" "editor/editorOrthophoto.cpp" +"editor/editorHttp.cpp" +"editor/editorNmt.cpp" +"editor/editorGeoMap.cpp" "editor/editorPreviews.cpp" "editor/editorIcons.cpp" +"editor/editorClips.cpp" "application/editormode.cpp" "application/editormodetrack.cpp" +"application/editormoderoute.cpp" +"application/editormodestraights.cpp" +"application/editormodelay.cpp" +"application/editormodeswitchplace.cpp" +"application/editormodetrackgizmo.cpp" +"application/editormoderecords.cpp" +"application/editormodeswitchdrive.cpp" +"application/editormodeswitchtool.cpp" +"application/editormodeswitchtemplate.cpp" +"application/editormodenmt.cpp" +"application/editormodegradeline.cpp" +"application/editormodeswitchslide.cpp" +"application/editormodeswitchdesign.cpp" +"application/editormodetrackbed.cpp" "application/editormodetrackux.cpp" +"application/editormodetrackprops.cpp" "application/editormoderoad.cpp" "application/editormodeprofile.cpp" "application/editormodetextures.cpp" "application/editormodegauge.cpp" +"application/editormoderide.cpp" +"application/editormodeminimap.cpp" "application/editormodeinfra.cpp" "application/editormodespeed.cpp" +"application/editormodesrk.cpp" +"application/editormodekm.cpp" "application/editormodejoints.cpp" "application/editormodeparallel.cpp" "application/editormodelineside.cpp" @@ -204,6 +257,17 @@ set(SOURCES "application/editormodesweep.cpp" "application/editormodeturntable.cpp" "application/editormodeselftest.cpp" +"application/editormodeselftestscene.cpp" +"application/editormodeselftestsleepers.cpp" +"application/editormodeselftestsweep.cpp" +"application/editormodeselftesttrack.cpp" +"application/editormodeselftestswitch.cpp" +"application/editormodeselftestjoin.cpp" +"application/editormodeselftestsignal.cpp" +"application/editormodeselftestterrain.cpp" +"application/editormodeselftestrails.cpp" +"application/editormodeselftestmonkey.cpp" +"application/scriptedinput.cpp" "input/editormouseinput.cpp" "application/editoruilayer.cpp" "application/editoruipanels.cpp" @@ -631,6 +695,12 @@ else() target_compile_definitions(eu07_settings INTERFACE WITH_DISCORD_RPC=0) endif() +if(WITH_EDITOR_SELFTESTS) + target_compile_definitions(eu07_settings INTERFACE WITH_EDITOR_SELFTESTS=1) +else() + target_compile_definitions(eu07_settings INTERFACE WITH_EDITOR_SELFTESTS=0) +endif() + find_package(OpenAL REQUIRED) if (TARGET OpenAL::OpenAL) target_link_libraries(eu07_settings INTERFACE OpenAL::OpenAL) @@ -661,7 +731,8 @@ if (WIN32) target_link_libraries(eu07_settings INTERFACE ws2_32) endif() -# http client of the editor's geoportal orthophoto layer: WinHTTP on Windows, libcurl elsewhere when available +# http client of the editor, for the orthophoto, the terrain model and the topo map of geoportal.gov.pl: WinHTTP on Windows, +# libcurl elsewhere when available if (WIN32) target_link_libraries(eu07_settings INTERFACE winhttp) else() @@ -670,7 +741,7 @@ else() target_link_libraries(eu07_settings INTERFACE CURL::libcurl) target_compile_definitions(eu07_settings INTERFACE EU07_WITH_CURL) else() - message(STATUS "libcurl not found: the editor's orthophoto layer will only show cached tiles") + message(STATUS "libcurl not found: the editor's orthophoto and terrain model will only show what's cached, its topo map nothing") endif() endif() diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index 777edc7c3..69678ea44 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -173,6 +173,8 @@ enum DerailReason WRONG_TRACK_TYPE = 4, // Ra: powód wykolejenia: nieodpowiednia trajektoria /// Collision with another vehicle. COLLISION = 5, // powód wykolejenia: zderzenie z innym pojazdem + /// Trailing through a switch with a movable nose set the other way. + TRAILED_SWITCH = 6, // powód wykolejenia: rozprucie rozjazdu z ruchomym dziobem }; /*wagi prawdopodobienstwa dla funkcji FuzzyLogic*/ diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 0099e8e62..71ff76019 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -1531,6 +1531,8 @@ void TMoverParameters::Derail(DerailReason const Reason) ErrorLog("Bad dynamic: " + Name + " derailed due to wrong track type"); // błąd w scenerii else if (Reason == COLLISION) WriteLog("Bad driving: " + Name + " derailed"); // This reason also generates its own message in `TMoverParameters::CollisionDetect()` + else if (Reason == TRAILED_SWITCH) + ErrorLog("Bad driving: " + Name + " derailed trailing through a switch with a movable nose set the other way"); } } diff --git a/application/application.cpp b/application/application.cpp index 157644e8c..96f578514 100644 --- a/application/application.cpp +++ b/application/application.cpp @@ -25,6 +25,7 @@ http://mozilla.org/MPL/2.0/. #include "rendering/renderer.h" #include "application/uilayer.h" #include "utilities/Logs.h" +#include "world/SleeperWorker.h" #include "rendering/screenshot.h" #include "utilities/translation.h" #include "vehicle/Train.h" @@ -84,6 +85,8 @@ void focus_callback(GLFWwindow *window, int focus) void cursor_enter_callback(GLFWwindow *window, int entered) { + if (scripted_input::driving()) + return; ui_layer::cursor_enter_callback(entered); } @@ -100,6 +103,8 @@ void window_resize_callback(GLFWwindow *, int w, int h) void cursor_pos_callback(GLFWwindow *window, double x, double y) { + if (scripted_input::driving()) + return; ui_layer::cursor_pos_callback(x, y); Global.cursor_pos = glm::ivec2(x, y); Application.on_cursor_pos(x, y); @@ -107,22 +112,30 @@ void cursor_pos_callback(GLFWwindow *window, double x, double y) void mouse_button_callback(GLFWwindow *window, int button, int action, int mods) { + if (scripted_input::driving()) + return; Application.on_mouse_button(button, action, mods); } void scroll_callback(GLFWwindow *window, double xoffset, double yoffset) { + if (scripted_input::driving()) + return; Application.on_scroll(xoffset, yoffset); } void key_callback(GLFWwindow *window, int key, int scancode, int action, int mods) { + if (scripted_input::driving()) + return; Application.on_key(key, scancode, action, mods); } void char_callback(GLFWwindow *window, unsigned int c) { + if (scripted_input::driving()) + return; Application.on_char(c); } @@ -727,6 +740,9 @@ void eu07_application::exit() auto const step = [closing](char const *What) { WriteLog(std::format("Closing: {} at {} ms", What, std::chrono::duration_cast(std::chrono::steady_clock::now() - closing).count())); }; + step("the sleepers laid in the background"); + // the sleepers laid in the background read the scenery, which goes below + track_sleepers::stop_background(); step("the black box"); simulation::Blackbox.close(); step("the modes"); @@ -1007,7 +1023,8 @@ GLFWwindow *eu07_application::window(int const Windowindex, bool visible, int wi if (keep_ownership) m_windows.emplace_back(childwindow); - glfwFocusWindow(m_windows.front()); // restore focus to main window + if (glfwGetWindowAttrib(m_windows.front(), GLFW_VISIBLE)) + glfwFocusWindow(m_windows.front()); // restore focus to main window return childwindow; } @@ -1436,8 +1453,10 @@ int eu07_application::init_glfw() Global.bFullScreen = true; } - // test mode keeps its window hidden: glfw, the ui and the input still need one, but nothing is shown in it - auto *mainwindow = window(-1, false == Global.test.enabled, Global.window_size.x, Global.window_size.y, Global.bFullScreen ? monitor : nullptr, true, false); + // test mode keeps its window hidden: glfw, the ui and the input still need one, but nothing is shown in it. + // so does a selftest of the editor run while the computer is in use for something else: never shown nor focused + bool const shown{false == Global.test.enabled && selftest_script("EU07_EDITOR_SELFTEST_HIDDEN") == nullptr}; + auto *mainwindow = window(-1, shown, Global.window_size.x, Global.window_size.y, Global.bFullScreen && shown ? monitor : nullptr, true, false); if (mainwindow == nullptr) { diff --git a/application/editorgestures.h b/application/editorgestures.h new file mode 100644 index 000000000..59c73aa63 --- /dev/null +++ b/application/editorgestures.h @@ -0,0 +1,251 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +// the mouse and the keys drawn as pictures: the lessons of the tutorial, the gestures of the tools and of the vertical profile + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include "imgui/imgui.h" +#include "utilities/translation.h" + +ImU32 const kGestureLit{IM_COL32(90, 175, 255, 255)}; + +// the mouse with the part used lit: LMB, RMB, MMB, wheel (with arrows), move (with arrows); the width it took +inline float gesture_mouse(ImDrawList &List, ImVec2 const At, float const Height, std::string const &Part) +{ + auto const width{std::round(Height * 0.68f)}; + auto const line{ImGui::GetColorU32(ImGuiCol_Text)}; + auto const thickness{std::max(1.0f, Height * 0.07f)}; + auto const rounding{width * 0.5f}; + auto const split{At.y + std::round(Height * 0.45f)}; + auto const middle{At.x + width * 0.5f}; + ImVec2 const high{At.x + width, At.y + Height}; + if (Part == "LMB") + List.AddRectFilled(At, ImVec2(middle, split), kGestureLit, rounding, ImDrawFlags_RoundCornersTopLeft); + if (Part == "RMB") + List.AddRectFilled(ImVec2(middle, At.y), ImVec2(high.x, split), kGestureLit, rounding, ImDrawFlags_RoundCornersTopRight); + List.AddRect(At, high, line, rounding, 0, thickness); + List.AddLine(ImVec2(At.x, split), ImVec2(high.x, split), line, thickness); + List.AddLine(ImVec2(middle, At.y), ImVec2(middle, split), line, thickness); + auto const wheel{std::max(3.0f, std::round(width * 0.24f))}; + ImVec2 const wheel_low{middle - wheel * 0.5f, At.y + Height * 0.1f}; + ImVec2 const wheel_high{middle + wheel * 0.5f, At.y + Height * 0.36f}; + List.AddRectFilled(wheel_low, wheel_high, (Part == "MMB" || Part == "wheel") ? kGestureLit : ImGui::GetColorU32(ImGuiCol_WindowBg), wheel * 0.5f); + List.AddRect(wheel_low, wheel_high, line, wheel * 0.5f, 0, thickness * 0.8f); + auto right{high.x}; + auto const arrow{Height * 0.16f}; + if (Part == "wheel") + { + auto const x{right + arrow * 1.6f}; + List.AddTriangleFilled(ImVec2(x - arrow, At.y + arrow * 1.8f), ImVec2(x + arrow, At.y + arrow * 1.8f), ImVec2(x, At.y + arrow * 0.3f), kGestureLit); + List.AddTriangleFilled(ImVec2(x - arrow, high.y - arrow * 1.8f), ImVec2(x + arrow, high.y - arrow * 1.8f), ImVec2(x, high.y - arrow * 0.3f), kGestureLit); + right = x + arrow; + } + if (Part == "move") + { + auto const reach{Height * 0.42f}; + ImVec2 const centre{right + arrow * 0.8f + reach, At.y + Height * 0.5f}; + List.AddLine(ImVec2(centre.x - reach + arrow, centre.y), ImVec2(centre.x + reach - arrow, centre.y), kGestureLit, thickness); + List.AddLine(ImVec2(centre.x, centre.y - reach + arrow), ImVec2(centre.x, centre.y + reach - arrow), kGestureLit, thickness); + List.AddTriangleFilled(ImVec2(centre.x - reach, centre.y), ImVec2(centre.x - reach + arrow * 1.4f, centre.y - arrow), ImVec2(centre.x - reach + arrow * 1.4f, centre.y + arrow), kGestureLit); + List.AddTriangleFilled(ImVec2(centre.x + reach, centre.y), ImVec2(centre.x + reach - arrow * 1.4f, centre.y + arrow), ImVec2(centre.x + reach - arrow * 1.4f, centre.y - arrow), kGestureLit); + List.AddTriangleFilled(ImVec2(centre.x, centre.y - reach), ImVec2(centre.x + arrow, centre.y - reach + arrow * 1.4f), ImVec2(centre.x - arrow, centre.y - reach + arrow * 1.4f), kGestureLit); + List.AddTriangleFilled(ImVec2(centre.x, centre.y + reach), ImVec2(centre.x - arrow, centre.y + reach - arrow * 1.4f), ImVec2(centre.x + arrow, centre.y + reach - arrow * 1.4f), kGestureLit); + right = centre.x + reach; + } + return right - At.x; +} + +// a key cap with its name; the width it took +inline float gesture_key(ImDrawList &List, ImVec2 const At, float const Height, std::string const &Text) +{ + auto const size{ImGui::CalcTextSize(Text.c_str())}; + auto const width{std::max(std::round(size.x + Height * 0.6f), Height)}; + auto const rounding{Height * 0.2f}; + ImVec2 const high{At.x + width, At.y + Height}; + List.AddRectFilled(At, high, ImGui::GetColorU32(ImGuiCol_FrameBg), rounding); + List.AddRect(At, high, ImGui::GetColorU32(ImGuiCol_TextDisabled), rounding, 0, std::max(1.0f, Height * 0.06f)); + List.AddText(ImVec2(std::round(At.x + (width - size.x) * 0.5f), std::round(At.y + (Height - size.y) * 0.5f)), ImGui::GetColorU32(ImGuiCol_Text), Text.c_str()); + return width; +} + +// the words of a gesture as they're drawn: the parts of the mouse, the keys, "+" between them, other words as text +struct gesture_word +{ + enum class kind + { + mouse, + key, + plus, + text + } what; + std::string text; +}; + +// "Ctrl+wheel", "Shift+click x4", "Drag a point", "Q W E": the keys and the parts of the mouse it names, the rest as text +inline std::vector gesture_words(std::string const &Keys) +{ + static char const *const keys[]{"Ctrl", "Shift", "Alt", "Esc", "Del", "Enter", "Backspace", "Tab", "Space", "Home", "End", "PrtScr"}; + auto const mouse = [](std::string const &Word) -> std::string { + if (Word == "LMB" || Word == "click" || Word == "Click" || Word == "Press") + return "LMB"; + if (Word == "RMB" || Word == "MMB" || Word == "wheel") + return Word; + if (Word == "Wheel") + return "wheel"; + if (Word == "Drag" || Word == "drag" || Word == "move") + return "move"; + return {}; + }; + auto const key = [&](std::string const &Word) { + if (Word.size() == 1 && (std::isupper(static_cast(Word[0])) || std::isdigit(static_cast(Word[0])))) + return true; + if (Word.size() >= 2 && Word[0] == 'F' && std::isdigit(static_cast(Word[1]))) + return true; + return std::find_if(std::begin(keys), std::end(keys), [&](char const *Key) { return Word == Key; }) != std::end(keys); + }; + std::vector words; + std::string text; + auto const flush = [&]() { + if (false == text.empty()) + words.push_back({gesture_word::kind::text, text}); + text.clear(); + }; + std::istringstream stream{Keys}; + for (std::string word; stream >> word;) + { + std::vector parts; + std::size_t from{0}; + for (std::size_t plus; (plus = word.find('+', from)) != std::string::npos && plus > from; from = plus + 1) + parts.push_back(word.substr(from, plus - from)); + parts.push_back(word.substr(from)); + bool const all{std::all_of(parts.begin(), parts.end(), [&](std::string const &Part) { return false == mouse(Part).empty() || key(Part); })}; + if (false == all || (parts.size() == 1 && words.empty() == false && words.back().what == gesture_word::kind::text && false == key(parts[0]) && mouse(parts[0]).empty())) + { + text += (text.empty() ? "" : " ") + word; + continue; + } + flush(); + for (std::size_t index = 0; index < parts.size(); ++index) + { + if (index > 0) + words.push_back({gesture_word::kind::plus, "+"}); + if (auto const part{mouse(parts[index])}; false == part.empty()) + words.push_back({gesture_word::kind::mouse, part}); + else + words.push_back({gesture_word::kind::key, parts[index]}); + } + } + flush(); + return words; +} + +// the mouse and the keys of a gesture only, its words left to the text beside it +inline std::vector gesture_picture(std::string const &Keys) +{ + std::vector words; + for (auto const &word : gesture_words(Keys)) + if (word.what != gesture_word::kind::text && (word.what != gesture_word::kind::plus || (false == words.empty() && words.back().what != gesture_word::kind::plus))) + words.push_back(word); + while (false == words.empty() && words.back().what == gesture_word::kind::plus) + words.pop_back(); + return words; +} + +// the picture says all the words of the gesture: keys alone, no mouse nor words +inline bool gesture_keys_only(std::string const &Keys) +{ + auto const words{gesture_words(Keys)}; + return false == words.empty() && std::all_of(words.begin(), words.end(), [](gesture_word const &Word) { return Word.what == gesture_word::kind::key || Word.what == gesture_word::kind::plus; }); +} + +// the gesture drawn in a row; the width it took +inline float gesture_draw(ImDrawList &List, ImVec2 const At, float const Height, std::vector const &Words, ImU32 const Text) +{ + auto const gap{std::round(Height * 0.2f)}; + float x{0.0f}; + for (auto const &word : Words) + { + ImVec2 const place{At.x + x, At.y}; + switch (word.what) + { + case gesture_word::kind::mouse: x += gesture_mouse(List, place, Height, word.text) + gap; break; + case gesture_word::kind::key: x += gesture_key(List, place, Height, word.text) + gap; break; + case gesture_word::kind::plus: + case gesture_word::kind::text: + { + auto const size{ImGui::CalcTextSize(word.text.c_str())}; + List.AddText(ImVec2(place.x, std::round(At.y + (Height - size.y) * 0.5f)), word.what == gesture_word::kind::plus ? ImGui::GetColorU32(ImGuiCol_TextDisabled) : Text, word.text.c_str()); + x += size.x + gap; + break; + } + } + } + return std::max(0.0f, x - gap); +} + +inline float gesture_width(float const Height, std::vector const &Words) +{ + auto const gap{std::round(Height * 0.2f)}; + auto const arrow{Height * 0.16f}; + float x{0.0f}; + for (auto const &word : Words) + { + switch (word.what) + { + case gesture_word::kind::mouse: + x += std::round(Height * 0.68f) + (word.text == "wheel" ? arrow * 2.6f : word.text == "move" ? arrow * 0.8f + Height * 0.84f : 0.0f); + break; + case gesture_word::kind::key: x += std::max(std::round(ImGui::CalcTextSize(word.text.c_str()).x + Height * 0.6f), Height); break; + default: x += ImGui::CalcTextSize(word.text.c_str()).x; break; + } + x += gap; + } + return std::max(0.0f, x - gap); +} + +// rows of gestures, each drawn with its key and what it does beside it; the keys and the texts are the English ones, translated here +inline void gesture_rows(std::vector> const &Rows) +{ + auto *list{ImGui::GetWindowDrawList()}; + auto const font{ImGui::GetFontSize()}; + auto const size{std::round(font * 1.25f)}; + auto const pad{std::round(font * 0.6f)}; + std::vector> pictures; + float column{0.0f}; + for (auto const &row : Rows) + { + pictures.push_back(gesture_picture(row.first)); + column = std::max(column, gesture_width(size, pictures.back())); + } + for (std::size_t i = 0; i < Rows.size(); ++i) + { + auto const at{ImGui::GetCursorScreenPos()}; + auto const line{ImGui::GetTextLineHeight()}; + auto const height{std::max(size, line)}; + gesture_draw(*list, ImVec2(at.x, at.y + std::round((height - size) * 0.5f)), size, pictures[i], ImGui::GetColorU32(ImGuiCol_Text)); + ImGui::Dummy(ImVec2(column, height)); + ImGui::SameLine(0.0f, pad); + ImGui::SetCursorPosY(ImGui::GetCursorPosY() + std::round((height - line) * 0.5f)); + if (false == gesture_keys_only(Rows[i].first)) + { + ImGui::TextColored(ImVec4(1.0f, 0.83f, 0.3f, 1.0f), "%s", STR_C(Rows[i].first)); + ImGui::SameLine(); + } + ImGui::TextWrapped("%s", STR_C(Rows[i].second)); + } +} diff --git a/application/editormode.cpp b/application/editormode.cpp index f5daa3986..bb1b10fe5 100644 --- a/application/editormode.cpp +++ b/application/editormode.cpp @@ -8,11 +8,15 @@ http://mozilla.org/MPL/2.0/. */ #include "stdafx.h" +#include "world/TrackSleepers.h" #include +#include #include #include #include #include "application/editormode.h" +#include "application/editormodeshared.h" +#include "application/editorgestures.h" #include "scene/scenenodegroups.h" #include "application/editoruilayer.h" #ifndef _WIN32 @@ -23,11 +27,15 @@ extern char **environ; #include "application/editorprojection.h" #include "application/application.h" +#include "editor/editorKilometrage.hpp" #include "editor/editorSettings.hpp" #include "editor/editorModelSets.hpp" +#include "editor/editorTrackPresets.hpp" #include "editor/editorIncludeInfo.hpp" #include "editor/editorGroundMesh.hpp" #include "editor/editorFormat.hpp" +#include "editor/editorAlignmentStore.hpp" +#include "editor/editorSwitchStore.hpp" #include "editor/editorGeometry.hpp" #include "editor/editorIcons.hpp" #include "utilities/translation.h" @@ -75,6 +83,38 @@ namespace using vec3 = glm::vec3; using dvec2 = glm::dvec2; + // the steps of a frame of the editor timed: a frame whose update takes longer than kSlow tells in the log which of them took + // the time, at most twice a second + class frame_steps + { + public: + void step(char const *Name) + { + auto const now{std::chrono::steady_clock::now()}; + m_steps.emplace_back(Name, std::chrono::duration(now - m_last).count()); + m_last = now; + } + ~frame_steps() + { + constexpr double kSlow{50.0}; // ms + auto const total{std::chrono::duration(std::chrono::steady_clock::now() - m_start).count()}; + static auto told{std::chrono::steady_clock::time_point{}}; + if (total < kSlow || m_start - told < std::chrono::milliseconds{500}) + return; + told = m_start; + std::string text{"Editor: slow frame, update " + std::to_string(static_cast(total)) + " ms:"}; + for (auto const &[name, time] : m_steps) + if (time >= 3.0) + text += " " + std::string{name} + " " + std::to_string(static_cast(time)); + WriteLog(text, logtype::generic); + } + + private: + std::chrono::steady_clock::time_point const m_start{std::chrono::steady_clock::now()}; + std::chrono::steady_clock::time_point m_last{m_start}; + std::vector> m_steps; + }; + inline bool is_release(int state) { return state == GLFW_RELEASE; @@ -196,6 +236,12 @@ namespace triangle_grid(std::vector Triangles, glm::dvec2 const &Min, glm::dvec2 const &Max) : m_triangles(std::move(Triangles)), m_min(Min) { glm::dvec2 const extent = glm::max(Max - Min, glm::dvec2(1.0)); + if (false == std::isfinite(extent.x) || false == std::isfinite(extent.y)) + { + m_triangles.clear(); + m_cells.resize(1); + return; + } // ~8 m cells, coarser for big areas so large terrain triangles don't flood the grid m_cellsize = std::max(8.0, std::max(extent.x, extent.y) / 128.0); m_columns = static_cast(std::ceil(extent.x / m_cellsize)) + 1; @@ -237,11 +283,13 @@ namespace private: int column(double const X) const { - return static_cast(std::clamp(std::floor((X - m_min.x) / m_cellsize), 0.0, static_cast(m_columns - 1))); + double const cell = std::floor((X - m_min.x) / m_cellsize); + return cell > 0.0 ? static_cast(std::min(cell, static_cast(m_columns - 1))) : 0; } int row(double const Z) const { - return static_cast(std::clamp(std::floor((Z - m_min.y) / m_cellsize), 0.0, static_cast(m_rows - 1))); + double const cell = std::floor((Z - m_min.y) / m_cellsize); + return cell > 0.0 ? static_cast(std::min(cell, static_cast(m_rows - 1))) : 0; } std::vector m_triangles; @@ -496,6 +544,9 @@ void editor_mode::editormode_input::poll() } editor_mode::editor_mode() { + alignment_store::reset(); + switch_store::reset(); + kilometrage::reset(); m_userinterface = std::make_shared(); // the area fill settings live in the node bank window, in the tab of the fill mode ui()->set_fill_options([this]() { render_area_fill(); }); @@ -513,7 +564,7 @@ editor_mode::editor_mode() { std::string reason; if (Node->from_template() || false == scene::Layers.editable(Node, &reason)) { - ui()->set_status("\"" + (Node->name().empty() ? std::string{"(unnamed node)"} : Node->name()) + "\" can't be edited: " + reason, true); + ui()->set_status(format(STR_C("\"%s\" can't be edited: %s"), name_of(*Node).c_str(), reason.c_str()), true); return; } m_track_window_open = false; @@ -527,6 +578,7 @@ editor_mode::editor_mode() { ui()->set_new_scenery([this]() { m_newscenery_asked = true; }); ui()->set_open_scenery([this]() { m_openscenery_asked = true; }); ui()->set_edit_menu([this]() { render_edit_menu(); }); + ui()->set_tools_menu([this]() { render_track_presets_menu(); }); ui()->set_menu_options([this]() { render_object_menu(); render_view_menu(); @@ -535,21 +587,36 @@ editor_mode::editor_mode() { }); m_roadtool.settings.normalize(); road_select(nullptr); - // the orthophoto is fitted onto the same ground as the area fill uses, terrain tile models included - // the roads built in the editor aren't ground: the imagery goes under them - m_orthophoto.ground_source([](glm::dvec2 const &Min, glm::dvec2 const &Max, bool const Heightmap, std::vector &Out) { - gather_ground_triangles(Min, Max, true, 50.0f, Out, true, Heightmap); - }); - m_orthophoto.height_source([](double const X, double const Z, double &Height) { return EditorTerrain.height_at(X, Z, Height); }); + ground_sources(m_orthophoto); + ui()->set_base_layers([this]() { render_base_layers(); }); editor_track::observe(this); } +void editor_mode::ground_sources(editor_orthophoto &Layer) +{ + // the imagery is fitted onto the same ground as the area fill uses, terrain tile models included + // the roads built in the editor aren't ground: the imagery goes under them + Layer.ground_source([](glm::dvec2 const &Min, glm::dvec2 const &Max, bool const Heightmap, std::vector &Out) { + gather_ground_triangles(Min, Max, true, 50.0f, Out, true, Heightmap); + }); + Layer.height_source([](double const X, double const Z, double &Height) { return EditorTerrain.height_at(X, Z, Height); }); + // the imagery often comes before the terrain made from the model: it lies where the terrain will be + Layer.guess_source([this](double const X, double const Z, double &Height) { + if (nmt_ground(X, Z, Height)) + return true; + // asked for, the tile goes onto it once it comes + if (m_nmt.placed()) + m_nmt.request({X - 1.0, Z - 1.0}, {X + 1.0, Z + 1.0}); + return false; + }); +} + editor_mode::~editor_mode() { editor_track::observe(nullptr); } -std::vector editor_mode::ground_heights(std::vector const &Points, bool const Fresh, std::vector *Found) +std::vector editor_mode::ground_heights(std::vector const &Points, bool const Fresh, std::vector *Found) const { std::vector heights; heights.reserve(Points.size()); @@ -568,6 +635,8 @@ std::vector editor_mode::ground_heights(std::vector const &P for (std::size_t i = 0; i < Points.size(); ++i) { auto const &p = Points[i]; + if (false == std::isfinite(p.x) || false == std::isfinite(p.y) || false == std::isfinite(p.z)) + continue; std::pair const key{static_cast(std::floor(p.x / ground_tile_size)), static_cast(std::floor(p.z / ground_tile_size))}; auto &tile = ground_tiles[key]; bool const missing = (tile.grid == nullptr); @@ -628,7 +697,16 @@ editor_ui *editor_mode::ui() const bool editor_mode::init() { EditorSettings.load(); + Global.EditorOrthoTracks = EditorSettings.top_tracks(); + // the terrain model as the user left it; the settings are read only here, after the mode was made + auto const &model{EditorSettings.terrain_model()}; + m_nmt_state.grow = EditorSettings.terrain_while_laying(); + m_nmt_state.band = std::clamp(model.band, 50.0, 3000.0); + // the formation and the slopes are always made along the tracks: the switch of them is gone, a setting left off by it isn't kept + m_nmt_state.follow = model.follow; + m_terrain_add_count = std::clamp(model.around, 1, 8); EditorModelSets.load(); + EditorTrackPresets.load(); Camera.Init({0, 15, 0}, {glm::radians(-30.0), glm::radians(180.0), 0}, nullptr); return m_input.init(); } @@ -669,23 +747,21 @@ void editor_mode::start_focus(scene::basic_node *node, double duration) double const len = glm::length(dir); dir = len > 1e-3 ? dir / len : glm::normalize(glm::dvec3(1.0, 0.5, 1.0)); + // looking from there straight at the object + fly_to(center, -dir, distance, duration); +} + +void editor_mode::fly_to(glm::dvec3 const &Target, glm::dvec3 const &Look, double const Distance, double const Duration) +{ + // the camera flown off somewhere leaves the track it rode along + m_ride.leave(); m_focus_start_pos = Camera.Pos; m_focus_start_angle = Camera.Angle; - m_focus_target_pos = center + dir * distance; - - // target orientation looks from the target position straight at the object - glm::dvec3 look = center - m_focus_target_pos; - double const looklen = glm::length(look); - if (looklen > 1e-6) - look /= looklen; - m_focus_target_angle = glm::vec3( - static_cast(std::asin(glm::clamp(look.y, -1.0, 1.0))), // pitch - static_cast(std::atan2(-look.x, -look.z)), // yaw - 0.0f); // roll - + m_focus_target_pos = Target - Look * Distance; + m_focus_target_angle = glm::vec3(static_cast(std::asin(std::clamp(Look.y, -1.0, 1.0))), static_cast(std::atan2(-Look.x, -Look.z)), 0.0f); m_focus_active = true; m_focus_time = 0.0; - m_focus_duration = duration; + m_focus_duration = Duration; } void editor_mode::snap_to_ground(scene::basic_node *node, bool const Alone, bool const Joined) @@ -857,6 +933,13 @@ void editor_mode::nullify_history_pointers(scene::basic_node *node) if (!node) return; + if (ui()->node() == node) + ui()->set_node(nullptr); + infra_forget(node); + for (auto *tool : m_tools) + tool->forget(node); + + auto const followed = [node](infra::object_state const &State) { return State.saved.node == node; }; for (auto &s : m_history) { if (s.node_ptr == node) @@ -866,12 +949,14 @@ void editor_mode::nullify_history_pointers(scene::basic_node *node) if (copy.model == node) copy.model = nullptr; } + s.infra.erase(std::remove_if(s.infra.begin(), s.infra.end(), followed), s.infra.end()); } for (auto &s : g_redo) { if (s.node_ptr == node) s.node_ptr = nullptr; + s.infra.erase(std::remove_if(s.infra.begin(), s.infra.end(), followed), s.infra.end()); } // deleted nodes also drop out of the "undo last fill" set @@ -889,6 +974,9 @@ void editor_mode::terrain_history_step() { if (false == m_streamer.active()) return; + // the terrain loaded from the model is taken back as a whole + if (nmt_busy() && false == m_history_busy) + return; if (m_streamer.recording()) { if (terrain_brush() && mouseHold && false == m_history_busy) @@ -926,6 +1014,9 @@ void editor_mode::restore_terrain(EditorSnapshot &Snapshot) void editor_mode::undo_last() { + first_step_done(first_step::undo); + // the warning by the cursor told of the step taken back now: "Ctrl+Z takes it back" is done + ui()->drop_refusal(); // a change of the terrain made a moment ago is a step of its own before it's taken back m_history_busy = true; terrain_history_step(); @@ -950,11 +1041,33 @@ void editor_mode::undo_last() } } +std::string editor_mode::refused(std::string Text) +{ + ui()->set_status(Text, true); + return Text; +} + +void editor_mode::drop_step(std::size_t const Step) +{ + if (Step == 0 || m_history.size() != Step) + return; + auto const redo{g_redo.size()}; + undo_one(); + if (g_redo.size() > redo) + g_redo.erase(g_redo.begin() + redo, g_redo.end()); +} + void editor_mode::undo_one() { if (m_history.empty()) return; + m_nmt_state.restoring = true; + struct restored + { + bool &flag; + ~restored() { flag = false; } + } const restoring{m_nmt_state.restoring}; EditorSnapshot snap = m_history.back(); m_history.pop_back(); @@ -965,6 +1078,13 @@ void editor_mode::undo_one() return; } + if (snap.action == EditorSnapshot::Action::Kilometrage) + { + restore_kilometrage(snap); + g_redo.push_back(std::move(snap)); + return; + } + if (snap.action == EditorSnapshot::Action::Bend) { restore_bend(snap, true); @@ -1070,9 +1190,7 @@ void editor_mode::undo_one() if (auto *model = dynamic_cast(target)) { - nullify_history_pointers(model); - remove_from_hierarchy(model); - simulation::State.delete_model(model); + erase_model(model); m_node = nullptr; ui()->set_node(nullptr); } @@ -1120,6 +1238,12 @@ void editor_mode::redo_one() if (g_redo.empty()) return; + m_nmt_state.restoring = true; + struct restored + { + bool &flag; + ~restored() { flag = false; } + } const restoring{m_nmt_state.restoring}; EditorSnapshot snap = g_redo.back(); g_redo.pop_back(); @@ -1130,6 +1254,13 @@ void editor_mode::redo_one() return; } + if (snap.action == EditorSnapshot::Action::Kilometrage) + { + restore_kilometrage(snap); + m_history.push_back(std::move(snap)); + return; + } + if (snap.action == EditorSnapshot::Action::Bend) { restore_bend(snap, false); @@ -1198,9 +1329,7 @@ void editor_mode::redo_one() { if (auto *model = dynamic_cast(target)) { - nullify_history_pointers(model); - remove_from_hierarchy(model); - simulation::State.delete_model(model); + erase_model(model); m_node = nullptr; ui()->set_node(nullptr); } @@ -1265,24 +1394,58 @@ void editor_mode::redo_one() bool editor_mode::update() { + frame_steps steps; Global.editor_tracks = (current_work_area() == work_area::tracks); selftest_step(); - if (m_vehicle.leave) + steps.step("selftest"); + // the drives of the switches go to the tips of their blades once, as the templates of the scenery are known + if (false == m_drives_checked) + { + EditorIncludes.start(); + if (EditorIncludes.scanned()) + { + m_drives_checked = true; + if (auto const moved{drives_to_blade_tips()}; moved > 0) + { + auto const text{format(STR_P("The drive of %zu switch is moved to the tips of its blades", "The drives of %zu switches are moved to the tips of their blades", static_cast(moved)), moved)}; + ui()->set_status(text, false); + WriteLog("Editor: " + text, logtype::generic); + } + } + } + // after the tool has told its own status + if (false == m_orphan_note.empty()) + { + ui()->set_notice(m_orphan_note); + WriteLog("Editor: " + m_orphan_note); + m_orphan_note.clear(); + } + if (m_vehicle.take_leave()) { - m_vehicle.leave = false; Application.pop_mode(); return true; } + steps.step("start"); Timer::UpdateTimers(true); + move_thrown_switches(); simulation::State.update_clocks(); simulation::Environment.update(); // bindings are matched with the objects by their locations, before anything gets moved if (false == m_bindings_loaded && simulation::is_ready) infra_load(); + // the templates are looked for in the background from the start, for the tools to have them at hand + if (simulation::is_ready) + { + EditorIncludes.start(); + EditorIncludes.poll(); + } auto const deltarealtime = Timer::GetDeltaRenderTime(); + // the whole frame before, drawing included: one slow where its update wasn't took the time drawing + if (deltarealtime > 0.15 && simulation::is_ready) + WriteLog("Editor: slow frame before, " + std::to_string(static_cast(deltarealtime * 1000.0)) + " ms in all", logtype::generic); // reconcile camera fly-mode with the real right-button state. ImGui is always fed the button // events (even when it captures the mouse), so io.MouseDown[1] is authoritative; if a release @@ -1309,6 +1472,7 @@ bool editor_mode::update() m_input.mouse.button(GLFW_MOUSE_BUTTON_LEFT, GLFW_RELEASE); } terrain_history_step(); + steps.step("simulation"); // fixed step render time routines (50 Hz) fTime50Hz += deltarealtime; // accumulate even when paused to keep frame reads stable @@ -1339,8 +1503,10 @@ bool editor_mode::update() } + steps.step("ui"); // variable step routines update_camera(deltarealtime); + steps.step("camera"); // drop the selection if its layer was hidden or locked in the meantime if (m_node != nullptr && false == scene::Layers.editable(m_node)) @@ -1363,6 +1529,9 @@ bool editor_mode::update() { m_include_gesture = false; } + // the gizmo let go of a signal while it wasn't drawn + if (false == m_gizmo_using) + signal_gizmo_end(); // models replaced after changes of includes are destroyed once the renderer can't have them among its pick candidates for (auto &retired : m_retired) { @@ -1377,6 +1546,7 @@ bool editor_mode::update() audio::renderer.update(Global.iPause ? 0.0 : deltarealtime); GfxRenderer->Update(deltarealtime); + steps.step("renderer"); simulation::is_ready = true; @@ -1392,27 +1562,67 @@ bool editor_mode::update() draw_terrain_overlay(); // --- geoportal orthophoto: streamed around the camera, drawn beneath the other overlays --- + // chunks of the terrain come from the files and from the model: the imagery lying at guessed heights goes onto them + // and so do the squares of the model it lies on meanwhile + auto const resident{m_streamer.resident()}; + auto const waiting{m_nmt.waiting()}; + if (resident > m_ortho_resident || waiting < m_ortho_waiting) + { + m_orthophoto.ground_arrived(); + for (auto &layer : m_wms) + layer->ground_arrived(); + } + m_ortho_resident = resident; + m_ortho_waiting = waiting; + steps.step("terrain"); m_orthophoto.update(Camera.Pos); + steps.step("orthophoto"); + update_wms_layers(); + steps.step("wms"); + nmt_update(); + keep_nmt_settings(); + steps.step("nmt"); + // what's drawn over the 3d view stays in it, the docks around it are see-through a little + auto *background{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())}; + background->PushClipRect(ImVec2(editor_ui::view_min().x, editor_ui::view_min().y), ImVec2(editor_ui::view_max().x, editor_ui::view_max().y), true); draw_orthophoto(); + draw_nmt_pending(); + area_update(); + draw_download_area(); + steps.step("imagery"); // --- ImGuizmo: in-viewport transform gizmo for the selected node --- render_gizmo(); // the tools, the gizmo modes and the axes over the 3d view render_viewport_overlays(); + m_ride.draw_hud(); render_track_inspector(); + steps.step("inspector"); + if (ui()->mode() == nodebank_panel::TRACK) + { + draw_track_lines(); + draw_track_labels(); + draw_track_legend(); + } + else if (Global.EditorOrtho && Global.EditorOrthoTracks > 1) + draw_track_lines(); if (selected_track()) draw_track_overlay(); if (route_active()) draw_route_overlay(); if (ui()->mode() == nodebank_panel::TRACK && m_track_tab == track_tab::straights) draw_straights_overlay(); + steps.step("track lines"); if (ui()->mode() == nodebank_panel::TRACK) { if (m_track_box.active && false == ImGui::GetIO().MouseDown[0]) finish_track_box(); update_track_hover(); + steps.step("hover"); point_drag_update(); + switch_slide_update(); + draw_switch_slide(); if (m_track_tab == track_tab::turntable) draw_turntable_overlay(); if (m_track_tab == track_tab::signals) @@ -1421,28 +1631,53 @@ bool editor_mode::update() signal_move_update(); draw_signal_overlay(); } - draw_parallel_preview(); + m_parallel.draw_overlay(); if (m_track_tab == track_tab::lineside) { - draw_hekto_overlay(); - draw_fouling_overlay(); - draw_vehicle_marker(); + m_hekto.draw_overlay(); + m_fouling.draw_overlay(); + m_vehicle.draw_overlay(); } render_track_context(); + steps.step("context"); update_build_tools(); + steps.step("laying"); + tape_update(); update_track_intent(); + steps.step("intent"); draw_track_hover(); draw_track_set(); draw_track_spread(); draw_build_overlay(); + steps.step("laying drawn"); + draw_blade_tips(); draw_track_intent(); - speed_step(); - joints_step(); + draw_tape(); + steps.step("track drawn"); + m_speed.update(); + steps.step("speed"); + m_joints.update(); + steps.step("joints"); + if (m_nmt_state.grade_lines_dirty) + { + m_nmt_state.grade_lines_dirty = false; + grade_lines_store(); + } + m_nmt_state.grade_line_replaced.clear(); + m_srk.update(); + kilometrage::follow(m_track_edits); + m_km.update(); + steps.step("srk km"); draw_track_hints(); + draw_empty_scenery_hint(); draw_profile_overlay(); + draw_grade_line_pick(); draw_infra_overlay(); - draw_speed_overlay(); - draw_joints_overlay(); + m_speed.draw_overlay(); + m_joints.draw_overlay(); + m_srk.draw_overlay(); + m_km.draw_overlay(); + steps.step("overlays"); } else { @@ -1451,8 +1686,9 @@ bool editor_mode::update() bend_drag_update(); draw_bend_overlay(); } - update_gauge(); - render_gauge_window(); + m_gauge.update(); + m_gauge.render_windows(); + m_minimap.render_windows(); // roads: trajectories of the lanes, and the tools of the road window update_road_tool(); @@ -1460,21 +1696,30 @@ bool editor_mode::update() // the roads and the terrain are fields of work, their tools are drawn in the tool options window in place of the edit mode ones ui()->set_workspace(m_terrain_open ? editor_ui::workspace::terrain : m_roadtool.window ? editor_ui::workspace::roads : editor_ui::workspace::none); + steps.step("roads"); // --- array: the one made last is kept in line with its settings --- update_array(); // --- area fill: outline overlay while the mode is active (its settings are drawn in the node bank window) --- if (ui()->mode() == nodebank_panel::FILL) draw_area_fill_outline(); + background->PopClipRect(); draw_ortho_compass(); render_new_scenery_popup(); render_open_scenery_popup(); render_shortcuts_window(); - render_orthophoto_window(); + render_first_steps(); + render_nmt_prompt(); + render_nmt_banner(); + render_nmt_buried(); + render_empty_scenery_hint(); + render_outside_area_hint(); + render_switch_designer(); render_environment_window(); draw_selection_overlay(); render_context_menu(); + steps.step("windows"); // --- ImGui: Editor Settings & History windows --- if(m_settings_open) @@ -1552,82 +1797,32 @@ namespace return changed; } - // grid points without a height (or another value) take the one of the nearest point which has it (by steps along the grid) - template void fill_from_nearest(std::vector &Heights, std::vector &Found, std::size_t const Side) - { - std::deque queue; - for (std::size_t index = 0; index < Found.size(); ++index) - if (Found[index] != 0) - queue.push_back(index); - while (false == queue.empty()) - { - auto const index = queue.front(); - queue.pop_front(); - auto const ix = index % Side, iz = index / Side; - auto const visit = [&](std::size_t const Next) { - if (Found[Next] != 0) - return; - Found[Next] = 1; - Heights[Next] = Heights[index]; - queue.push_back(Next); - }; - if (ix > 0) - visit(index - 1); - if (ix + 1 < Side) - visit(index + 1); - if (iz > 0) - visit(index - Side); - if (iz + 1 < Side) - visit(index + Side); - } - } } // namespace void editor_mode::render_terrain_ui() { if (false == m_streamer.active()) { - ImGui::TextWrapped("%s", STR_C("The scenery has no heightmap terrain yet. It's kept in the folder terrain// of the simulator, " - "and written there when the scenery is saved.")); - if (ImGui::Button(STR_C("Make heightmap terrain for this scenery"))) + ImGui::TextUnformatted(STR_C("The scenery has no terrain yet")); + // the terrain model makes the terrain itself + if (ImGui::CollapsingHeader(STR_C("Terrain model (NMT)"), ImGuiTreeNodeFlags_DefaultOpen)) + render_nmt_ui(); + ImGui::Spacing(); + ImGui::TextDisabled("%s", STR_C("Or without the real ground:")); + if (ImGui::Button(STR_C("Make an empty, flat terrain"))) ensure_terrain(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Kept in the folder terrain// and written there with the scenery (Ctrl+S)")); return; } - ImGui::TextDisabled(STR_C("Folder: %s"), m_streamer.directory().c_str()); - ImGui::TextDisabled(STR_C("Chunks in memory: %zu%s"), m_streamer.resident(), m_streamer.modified() ? STR_C(", changes not saved yet") : ""); + // the real terrain first, open: the tracks put onto it from there + if (nmt_busy()) + ImGui::SetNextItemOpen(true); + if (ImGui::CollapsingHeader(STR_C("Terrain model (NMT)"), ImGuiTreeNodeFlags_DefaultOpen)) + render_nmt_ui(); - // what the left mouse button does - auto tool = static_cast(m_terrain_tool); - auto const radio = [&](char const *Label, terrain_tool const Tool, char const *Tooltip) { - ImGui::RadioButton(Label, &tool, static_cast(Tool)); - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", Tooltip); - }; - // the tools are named like the headers below, which would give them the same IDs - ImGui::PushID("terrain_tools"); - // the tools working on a click, then the brushes - radio(STR_C("Select"), terrain_tool::none, STR_C("LMB picks the models, as in the surroundings")); - ImGui::SameLine(); - radio(STR_C("Chunks"), terrain_tool::chunks, STR_C("LMB adds a chunk shaped as the ground under it, next to the clicked one; Shift+LMB removes the clicked chunk")); - ImGui::SameLine(); - radio(STR_C("Spacing"), terrain_tool::spacing, STR_C("LMB selects the clicked chunk, Ctrl+LMB adds it to the selection or takes it away;\nthe point spacing of the selected chunks is converted in \"Chunk resolution\" below")); - ImGui::SameLine(); - radio(STR_C("Water"), terrain_tool::water, STR_C("LMB adds a point of the outline of a body of water, Shift+LMB takes the last one back")); - ImGui::SameLine(); - radio(STR_C("Fill"), terrain_tool::fill, STR_C("LMB adds a point of the outline of an area to fill with a material, Shift+LMB takes the last one back")); - radio(STR_C("Sculpt"), terrain_tool::sculpt, STR_C("LMB raises the terrain under the brush, Shift+LMB lowers it")); - ImGui::SameLine(); - radio(STR_C("Smooth"), terrain_tool::smooth, STR_C("LMB evens the terrain out under the brush")); - ImGui::SameLine(); - radio(STR_C("Level"), terrain_tool::level, STR_C("LMB leads the terrain under the brush to the target height, Ctrl+LMB takes the target height from what's under the cursor")); - ImGui::SameLine(); - radio(STR_C("Paint"), terrain_tool::paint, STR_C("LMB paints the material chosen in the palette, Shift+LMB the first material of the palette")); - ImGui::SameLine(); - radio(STR_C("Restore"), terrain_tool::restore, STR_C("LMB takes back the touch-ups made over the tracks under the brush:\nthe terrain returns to the shape the modifiers (tracks) give it")); - ImGui::PopID(); - m_terrain_tool = static_cast(tool); - - if (ImGui::CollapsingHeader(STR_C("Chunks"), ImGuiTreeNodeFlags_DefaultOpen)) + // the tools are chosen in the toolbar, here are their settings + if (ImGui::CollapsingHeader(STR_C("Chunks"), m_terrain_tool == terrain_tool::chunks ? ImGuiTreeNodeFlags_DefaultOpen : 0)) { if (spacing_combo(STR_C("Point spacing"), m_terrain_spacing)) m_streamer.default_spacing(m_terrain_spacing); @@ -1662,7 +1857,7 @@ void editor_mode::render_terrain_ui() for (auto it = m_terrain_selection.begin(); it != m_terrain_selection.end();) it = m_streamer.exists(*it) ? std::next(it) : m_terrain_selection.erase(it); if (m_terrain_selection.empty()) - ImGui::TextWrapped("%s", STR_C("No chunk selected. With the Spacing tool LMB selects the clicked chunk, Ctrl+LMB adds one or takes it away.")); + ImGui::TextWrapped("%s", STR_C("No chunk selected. With the Point spacing tool LMB selects the clicked chunk, Ctrl+LMB adds one or takes it away.")); else { bool coarser = false; @@ -1694,6 +1889,10 @@ void editor_mode::render_terrain_ui() ImGui::SameLine(); if (ImGui::Button(STR_C("Clear the selection"))) m_terrain_selection.clear(); + if (ImGui::Button(STR_C("Remove the selected (Del)"))) + remove_selected_chunks(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Takes the selected chunks out of the terrain of the scenery, and out of its files on save; Ctrl+Z brings them back")); ImGui::Checkbox(STR_C("Paint every 0.5 m with 0.5 m spacing"), &m_terrain_convert_paint); if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", STR_C("Chunks converted to 0.5 m get their paint samples every 0.5 m as well (every metre otherwise),\n" @@ -1753,9 +1952,11 @@ void editor_mode::render_terrain_ui() { auto label{layers[i].size > 0.f ? format("%zu: %s (%.1f m)", i, layers[i].material.c_str(), layers[i].size) : format("%zu: %s", i, layers[i].material.c_str())}; if (layers[i].rotation != 0.f) - label += format(STR_C(", turned %.0f deg"), layers[i].rotation); + label += format(STR_C(", turned %.0f°"), layers[i].rotation); if (ImGui::Selectable(label.c_str(), static_cast(i) == m_terrain_layer)) m_terrain_layer = static_cast(i); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("New chunks are covered with the first material. A texture dragged from the browser onto an entry of the palette takes its place")); // a material dropped on an entry takes its place, on every chunk painted with it std::string dropped; if (material_drop(dropped)) @@ -1785,14 +1986,11 @@ void editor_mode::render_terrain_ui() ImGui::SetTooltip("%s", STR_C("Angle the textures of the chosen material are turned by, on every chunk painted with it.\n" "Ctrl+click to type it. To have the material turned in one place only, fill it there with an angle of its own.")); } - ImGui::SetNextItemWidth(160.0f); - ImGui::InputText(STR_C("Material"), m_terrain_material, IM_ARRAYSIZE(m_terrain_material)); - material_drop(m_terrain_material, IM_ARRAYSIZE(m_terrain_material)); + texture_field(STR_C("Material"), 160.0f, m_terrain_material, IM_ARRAYSIZE(m_terrain_material), terrain_texture_offer(nullptr)); ImGui::SameLine(); if (ImGui::Button(STR_C("Add to the palette")) && m_terrain_material[0] != '\0') m_terrain_layer = m_streamer.layer(m_terrain_material, m_terrain_material_size); - ImGui::TextDisabled("%s", STR_C("New chunks are covered with the first material. A chunk holds up to 8 of them. " - "A texture dragged from the browser onto an entry of the palette takes its place.")); + ImGui::TextDisabled("%s", STR_C("A chunk holds up to 8 materials")); } if (ImGui::CollapsingHeader(STR_C("Fill"), m_terrain_tool == terrain_tool::fill ? ImGuiTreeNodeFlags_DefaultOpen : 0)) @@ -1801,7 +1999,7 @@ void editor_mode::render_terrain_ui() if (false == layers.empty()) { auto const &chosen{layers[std::clamp(m_terrain_layer, 0, static_cast(layers.size()) - 1)]}; - ImGui::Text(STR_C("Material: %s (chosen in the palette below)"), chosen.material.c_str()); + ImGui::Text(STR_C("Material: %s (chosen in the palette above)"), chosen.material.c_str()); } ImGui::Text(STR_C("Outline: %zu points"), m_paint_outline.size()); ImGui::SetNextItemWidth(120.0f); @@ -1832,11 +2030,9 @@ void editor_mode::render_terrain_ui() ImGui::SetNextItemWidth(120.0f); if (ImGui::DragFloat(STR_C("Level (m)"), &m_water_level, 0.01f, -1000.0f, 5000.0f, "%.2f")) m_water_level_edited = true; - ImGui::SetNextItemWidth(160.0f); - ImGui::InputText(STR_C("Material##water"), m_water_material, IM_ARRAYSIZE(m_water_material)); - material_drop(m_water_material, IM_ARRAYSIZE(m_water_material)); + texture_field(STR_C("Material##water"), 160.0f, m_water_material, IM_ARRAYSIZE(m_water_material), terrain_texture_offer(STR_C("The default water material"))); if (ImGui::IsItemHovered()) - ImGui::SetTooltip(STR_C("Empty: %s, the water material of the terrain"), m_streamer.manifest().water_material.c_str()); + ImGui::SetTooltip(STR_C("The default one: %s, the water material of the terrain"), m_streamer.manifest().water_material.c_str()); ImGui::BeginDisabled(m_water_points.size() < 3); if (ImGui::Button(STR_C("Make the water"))) { @@ -1868,7 +2064,7 @@ void editor_mode::render_terrain_ui() { ImGui::PushID(static_cast(i)); auto const material = water[i].material.empty() ? std::string(STR_C("default material")) : water[i].material; - if (ImGui::Selectable(format("%s, %.2f m, %zu points, %s", water[i].name.c_str(), water[i].level, water[i].outline.size(), material.c_str()).c_str(), static_cast(i) == m_water_selected)) + if (ImGui::Selectable(format(STR_C("%s, %.2f m, %zu points, %s"), water[i].name.c_str(), water[i].level, water[i].outline.size(), material.c_str()).c_str(), static_cast(i) == m_water_selected)) m_water_selected = static_cast(i); // a texture dropped on an entry becomes the material of that water std::string name; @@ -1906,12 +2102,9 @@ void editor_mode::render_terrain_ui() m_water_material_of = m_water_selected; } bool retexture = false; - ImGui::SetNextItemWidth(160.0f); - ImGui::InputText(STR_C("Material of the chosen"), m_water_selected_material, IM_ARRAYSIZE(m_water_selected_material)); - retexture |= ImGui::IsItemDeactivatedAfterEdit(); - retexture |= material_drop(m_water_selected_material, IM_ARRAYSIZE(m_water_selected_material)); + retexture |= texture_field(STR_C("Material of the chosen"), 160.0f, m_water_selected_material, IM_ARRAYSIZE(m_water_selected_material), terrain_texture_offer(STR_C("The default water material"))); if (ImGui::IsItemHovered()) - ImGui::SetTooltip(STR_C("A material or a texture (drag one from the texture browser).\nEmpty: %s, the water material of the terrain"), m_streamer.manifest().water_material.c_str()); + ImGui::SetTooltip(STR_C("Chosen from the textures, or dragged from the texture browser.\nThe default one: %s, the water material of the terrain"), m_streamer.manifest().water_material.c_str()); ImGui::SetNextItemWidth(120.0f); ImGui::DragFloat(STR_C("Texture repeats every (m)##water"), &m_water_selected_size, 0.1f, 0.0f, 500.0f, "%.1f"); m_water_selected_size = std::max(0.0f, m_water_selected_size); @@ -1937,17 +2130,12 @@ void editor_mode::render_terrain_ui() m_water_material_of = -1; } // the material of the bodies of water which don't name their own - if (false == m_water_default_edited) - std::snprintf(m_water_default_material, sizeof(m_water_default_material), "%s", m_streamer.manifest().water_material.c_str()); - ImGui::SetNextItemWidth(160.0f); - ImGui::InputText(STR_C("Default water material"), m_water_default_material, IM_ARRAYSIZE(m_water_default_material)); - m_water_default_edited = ImGui::IsItemActive(); - bool redefault = ImGui::IsItemDeactivatedAfterEdit(); - redefault |= material_drop(m_water_default_material, IM_ARRAYSIZE(m_water_default_material)); + auto defaultmaterial{m_streamer.manifest().water_material}; + auto const redefault{texture_field(STR_C("Default water material"), 160.0f, defaultmaterial, terrain_texture_offer(nullptr))}; if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", STR_C("Material of the bodies of water which don't name their own")); if (redefault) - m_streamer.water_material(m_water_default_material); + m_streamer.water_material(defaultmaterial); } if (ImGui::CollapsingHeader(STR_C("Modifiers"))) @@ -1959,7 +2147,7 @@ void editor_mode::render_terrain_ui() for (auto const &modifier : modifiers) { ImGui::PushID(modifier.name.c_str()); - ImGui::TextUnformatted(format("%s, %zu points", modifier.name.c_str(), modifier.points.size()).c_str()); + ImGui::TextUnformatted(format(STR_C("%s, %zu points"), modifier.name.c_str(), modifier.points.size()).c_str()); ImGui::SameLine(); if (ImGui::SmallButton(STR_C("Bake"))) baked = modifier.name; @@ -1987,8 +2175,13 @@ void editor_mode::render_terrain_ui() } } - if (ImGui::CollapsingHeader(STR_C("Drawing and files"))) + auto const files{format(STR_C("Folder: %s"), m_streamer.directory().c_str()) + "\n" + format(STR_C("Chunks in memory: %zu%s"), m_streamer.resident(), m_streamer.modified() ? STR_C(", changes not saved yet") : "")}; + auto const drawing{ImGui::CollapsingHeader(STR_C("Drawing and files"))}; + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", files.c_str()); + if (drawing) { + ImGui::TextDisabled("%s", files.c_str()); auto detail{m_streamer.detail()}; ImGui::SetNextItemWidth(160.0f); if (ImGui::SliderFloat(STR_C("Detail"), &detail, 30.0f, 400.0f, "%.0f")) @@ -2168,6 +2361,12 @@ void editor_mode::load_orthophoto_settings() if (scenery == m_orthophoto_scenery) return; m_orthophoto_scenery = scenery; + // a scenery of its own: nobody chose for it yet, unless the user or the scenery keeps the orthophoto on or off + m_orthophoto_chosen = false; + // the height of the terrain model against the tracks of the scenery, as it was fitted or typed in last + m_nmt_state.offset = 0.0; + m_nmt_state.fitted = false; + std::as_const(EditorSettings).terrain_model_offset(scenery, m_nmt_state.offset, m_nmt_state.fitted); auto const &stored = EditorSettings.orthophoto(); editor_orthophoto::config config = m_orthophoto.settings(); @@ -2188,8 +2387,30 @@ void editor_mode::load_orthophoto_settings() config.north = m_georeference_origin.x; config.east = m_georeference_origin.y; } + auto enabled{m_orthophoto.enabled()}; + m_orthophoto_mark.clear(); + if (auto const marked{scene::Layers.empty() ? std::vector{} : scene::Layers.marked(scene::layer_handle{1}, "//$o")}; false == marked.empty() && editor_orthophoto::read_mark(marked.front(), config, enabled)) + { + m_orthophoto_mark = marked.front(); + m_orthophoto.enabled(enabled); + m_orthophoto_chosen = true; + WriteLog(format("Editor: the map settings of the scenery, orthophoto %s", enabled ? "on" : "off")); + } + // the user's choice stands over the scenery's; turned on only where the scenery lies on the map, a fictional one has nothing to + // show, and there it's left to the terrain model once the scenery is placed + if (auto const on{stored.on}; on.has_value() && (false == *on || config.north != 0.0 || config.east != 0.0)) + { + m_orthophoto.enabled(*on); + m_orthophoto_chosen = true; + WriteLog(format("Editor: the orthophoto %s, as the user left it", *on ? "on" : "off")); + } m_orthophoto.settings(config); m_orthophoto_origin_edit = {config.north, config.east}; + // the area the imagery and the terrain model are downloaded in, none in a scenery which has none + m_orthophoto_area_mark = scene::Layers.empty() ? std::vector{} : scene::Layers.marked(scene::layer_handle{1}, "//$z"); + m_orthophoto.area(editor_orthophoto::read_area(m_orthophoto_area_mark)); + if (false == m_orthophoto.area().empty()) + WriteLog(format("Editor: the download area of the scenery, %zu points, %d tiles of the orthophoto", m_orthophoto.area().size(), m_orthophoto.stats().area_tiles)); } void editor_mode::save_orthophoto_settings() @@ -2209,6 +2430,42 @@ void editor_mode::save_orthophoto_settings() EditorSettings.save(); } +void editor_mode::choose_orthophoto(bool const On) +{ + m_orthophoto.enabled(On); + m_orthophoto_chosen = true; + EditorSettings.orthophoto().on = On; + EditorSettings.save(); +} + +void editor_mode::keep_nmt_settings() +{ + // not while a number is being typed in, which changes it at every key + if (ImGui::IsAnyItemActive()) + return; + auto const &state{m_nmt_state}; + auto &stored{EditorSettings.terrain_model()}; + auto changed{stored.band != state.band || stored.around != m_terrain_add_count || stored.shape != state.shape || stored.follow != state.follow}; + stored.band = state.band; + stored.around = m_terrain_add_count; + stored.shape = state.shape; + stored.follow = state.follow; + // the offset of the model is the scenery's, fitted to its tracks or typed in + if (false == m_orthophoto_scenery.empty()) + { + double offset{0.0}; + bool fitted{false}; + std::as_const(EditorSettings).terrain_model_offset(m_orthophoto_scenery, offset, fitted); + if (offset != state.offset || fitted != state.fitted) + { + EditorSettings.terrain_model_offset(m_orthophoto_scenery, state.offset, state.fitted); + changed = true; + } + } + if (changed) + EditorSettings.save(); +} + void editor_mode::render_orthophoto_ui() { load_orthophoto_settings(); @@ -2217,12 +2474,9 @@ void editor_mode::render_orthophoto_ui() bool changed = false; // apply to the layer bool persist = false; // and store in the editor settings - bool enabled = m_orthophoto.enabled(); - if (ImGui::Checkbox(STR_C("Show orthophoto (geoportal.gov.pl)"), &enabled)) - m_orthophoto.enabled(enabled); - - ImGui::Separator(); ImGui::TextUnformatted(STR_C("Scenery origin (0,0,0) in PUWG 1992 / EPSG:2180")); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("PUWG 1992 (EPSG:2180): the coordinate system of the maps of Poland, in metres; the numbers as on geoportal.gov.pl")); // geodetic convention, as displayed by geoportal.gov.pl: X grows north, Y grows east. // applied once editing ends, so half-typed numbers don't trigger downloads ImGui::SetNextItemWidth(160.0f); @@ -2235,7 +2489,8 @@ void editor_mode::render_orthophoto_ui() { config.north = m_orthophoto_origin_edit.x; config.east = m_orthophoto_origin_edit.y; - changed = persist = true; + changed = true; + persist = true; } if (m_georeference) { @@ -2246,9 +2501,12 @@ void editor_mode::render_orthophoto_ui() ImGui::SameLine(); if (ImGui::SmallButton(STR_C("Use it"))) { - config.north = m_orthophoto_origin_edit.x = m_georeference_origin.x; - config.east = m_orthophoto_origin_edit.y = m_georeference_origin.y; - changed = persist = true; + m_orthophoto_origin_edit.x = m_georeference_origin.x; + config.north = m_orthophoto_origin_edit.x; + m_orthophoto_origin_edit.y = m_georeference_origin.y; + config.east = m_orthophoto_origin_edit.y; + changed = true; + persist = true; } } } @@ -2279,110 +2537,135 @@ void editor_mode::render_orthophoto_ui() ImGui::PopItemFlag(); }; - if (ImGui::Checkbox(STR_C("Fit to terrain"), &config.drape)) - changed = persist = true; - if (ImGui::IsItemHovered()) - ImGui::SetTooltip(STR_C("Lays the imagery onto the ground geometry (terrain shapes, terrain tile models, heightmap terrain).\n" - "Places without any ground use the height below.")); - if (config.drape) + auto const stats = m_orthophoto.stats(); + if (stats.failed > 0 || stats.area_failed > 0) { + ImGui::Text(STR_C("Tiles: %d shown, %d loading, %d failed"), stats.resident, stats.loading, stats.failed); ImGui::SameLine(); - if (ImGui::Button(STR_C("Refit"))) + if (ImGui::Button(STR_C("Retry"))) + m_orthophoto.retry_failed(); + } + + ImGui::Separator(); + render_download_area_ui(stats); + ImGui::Separator(); + + if (ImGui::TreeNode(STR_C("More settings"))) + { + if (ImGui::Checkbox(STR_C("Fit to terrain"), &config.drape)) { - // the ground was edited: what's kept of it has to go as well - ground_tiles.clear(); - forget_ground_shapes(); - m_orthophoto.refit(); + changed = true; + persist = true; } if (ImGui::IsItemHovered()) - ImGui::SetTooltip(STR_C("Samples the ground again, after it was edited")); - } - - begin_disabled(!config.drape); - ImGui::SetNextItemWidth(160.0f); - changed |= ImGui::DragFloat(STR_C("Lift above ground (m)"), &config.lift, 0.01f, 0.0f, 50.0f, "%.2f"); - persist |= ImGui::IsItemDeactivatedAfterEdit(); - end_disabled(!config.drape); - if (ImGui::IsItemHovered()) - ImGui::SetTooltip(STR_C("Raises the fitted imagery above the ground. Keep it below the objects you want to see:\n" - "in the scene everything lower than this ends up under the imagery.")); - - begin_disabled(config.drape); - ImGui::SetNextItemWidth(160.0f); - changed |= ImGui::DragFloat(STR_C("Height (m)"), &config.height, 0.1f, -1000.0f, 3000.0f, "%.2f"); - persist |= ImGui::IsItemDeactivatedAfterEdit(); - end_disabled(config.drape); - - if (ImGui::Checkbox(STR_C("Covered by objects and terrain"), &config.in_scene)) - changed = persist = true; - if (ImGui::IsItemHovered()) - ImGui::SetTooltip(STR_C("Draws the imagery as part of the scene, so tracks, models and terrain in front of it hide it.\n" - "It is lit like the scene. Fully opaque, mouse placement lands on it as on any surface;\n" - "translucent, it doesn't catch the mouse.\n" - "Not available with the Better Renderer, which doesn't pick up geometry added in the editor.")); - - ImGui::SetNextItemWidth(160.0f); - changed |= ImGui::SliderFloat(STR_C("Opacity"), &config.opacity, 0.0f, 1.0f, "%.2f"); - persist |= ImGui::IsItemDeactivatedAfterEdit(); - if (config.in_scene && ImGui::IsItemHovered()) - ImGui::SetTooltip(STR_C("In the scene the opacity is part of the textures: the tiles are read again from the cache\n" - "shortly after the slider stops, which takes a moment.")); - - // newest imagery, or the newest imagery taken up to the end of the selected year - int const thisyear = static_cast(std::chrono::year_month_day{std::chrono::floor(std::chrono::system_clock::now())}.year()); - std::string const yearlabel = config.year ? std::to_string(config.year) : std::string(STR_C("Newest")); - ImGui::SetNextItemWidth(160.0f); - if (ImGui::BeginCombo("Photo year", yearlabel.c_str())) - { - if (ImGui::Selectable(STR_C("Newest"), config.year == 0)) + ImGui::SetTooltip(STR_C("Lays the imagery onto the ground geometry (terrain shapes, terrain tile models, heightmap terrain).\n" + "Places without any ground use the height below.")); + if (config.drape) { - config.year = 0; - changed = persist = true; - } - for (int year = thisyear; year >= editor_orthophoto::oldest_year; --year) - { - if (ImGui::Selectable(std::to_string(year).c_str(), config.year == year)) + ImGui::SameLine(); + if (ImGui::Button(STR_C("Refit"))) { - config.year = year; - changed = persist = true; + // the ground was edited: what's kept of it has to go as well + ground_tiles.clear(); + forget_ground_shapes(); + m_orthophoto.refit(); + for (auto &layer : m_wms) + layer->refit(); } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip(STR_C("Samples the ground again, after it was edited")); } - ImGui::EndCombo(); - } - if (ImGui::Checkbox(STR_C("4K tiles where available"), &config.hires)) - changed = persist = true; - if (ImGui::IsItemHovered()) - ImGui::SetTooltip(STR_C("4096 px tiles (~6 cm/px) from the high-resolution orthophoto, for the tiles around the camera.\n" - "Areas it doesn't cover use the standard imagery. Each 4K tile takes ~85 MB of video memory.")); + begin_disabled(!config.drape); + ImGui::SetNextItemWidth(160.0f); + changed |= ImGui::DragFloat(STR_C("Lift above ground (m)"), &config.lift, 0.01f, 0.0f, 50.0f, "%.2f"); + persist |= ImGui::IsItemDeactivatedAfterEdit(); + end_disabled(!config.drape); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip(STR_C("Raises the fitted imagery above the ground. Keep it below the objects you want to see:\n" + "in the scene everything lower than this ends up under the imagery.")); + + begin_disabled(config.drape); + ImGui::SetNextItemWidth(160.0f); + changed |= ImGui::DragFloat(STR_C("Height (m)"), &config.height, 0.1f, -1000.0f, 3000.0f, "%.2f"); + persist |= ImGui::IsItemDeactivatedAfterEdit(); + end_disabled(config.drape); + + if (ImGui::Checkbox(STR_C("Covered by objects and terrain"), &config.in_scene)) + { + changed = true; + persist = true; + } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip(STR_C("Draws the imagery as part of the scene, so tracks, models and terrain in front of it hide it.\n" + "It is lit like the scene. Fully opaque, mouse placement lands on it as on any surface;\n" + "translucent, it doesn't catch the mouse.\n" + "Not available with the Better Renderer, which doesn't pick up geometry added in the editor.")); + + ImGui::SetNextItemWidth(160.0f); + changed |= ImGui::SliderFloat(STR_C("Opacity"), &config.opacity, 0.0f, 1.0f, "%.2f"); + persist |= ImGui::IsItemDeactivatedAfterEdit(); + if (config.in_scene && ImGui::IsItemHovered()) + ImGui::SetTooltip(STR_C("In the scene the opacity is part of the textures: the tiles are read again from the cache\n" + "shortly after the slider stops, which takes a moment.")); + + // newest imagery, or the newest imagery taken up to the end of the selected year + int const thisyear = static_cast(std::chrono::year_month_day{std::chrono::floor(std::chrono::system_clock::now())}.year()); + std::string const yearlabel = config.year ? std::to_string(config.year) : std::string(STR_C("Newest")); + ImGui::SetNextItemWidth(160.0f); + if (ImGui::BeginCombo(STR_C("Photo year"), yearlabel.c_str())) + { + if (ImGui::Selectable(STR_C("Newest"), config.year == 0)) + { + config.year = 0; + changed = true; + persist = true; + } + for (int year = thisyear; year >= editor_orthophoto::oldest_year; --year) + { + if (ImGui::Selectable(std::to_string(year).c_str(), config.year == year)) + { + config.year = year; + changed = true; + persist = true; + } + } + ImGui::EndCombo(); + } + + if (ImGui::Checkbox(STR_C("4K tiles where available"), &config.hires)) + { + changed = true; + persist = true; + } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip(STR_C("4096 px tiles (~6 cm/px) from the high-resolution orthophoto, for the tiles around the camera.\n" + "Areas it doesn't cover use the standard imagery. Each 4K tile takes ~85 MB of video memory.")); + + ImGui::Separator(); + if (stats.failed == 0) + ImGui::Text(STR_C("Tiles: %d shown, %d loading, %d failed"), stats.resident, stats.loading, stats.failed); + if (!editor_orthophoto::can_download()) + ImGui::TextDisabled(STR_C("This build has no HTTP client, only cached tiles are shown")); + ImGui::TextDisabled(STR_C("Cache: %s"), editor_orthophoto::cache_directory().c_str()); + if (ImGui::Button(STR_C("Clear cache"))) + m_orthophoto.clear_cache(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip(STR_C("Deletes downloaded tiles from disk. They are fetched again around the camera.")); + ImGui::TreePop(); + } if (changed) m_orthophoto.settings(config); if (persist) save_orthophoto_settings(); - ImGui::Separator(); - auto const stats = m_orthophoto.stats(); - ImGui::Text(STR_C("Tiles: %d shown, %d loading, %d failed"), stats.resident, stats.loading, stats.failed); - if (stats.failed > 0) - { - ImGui::SameLine(); - if (ImGui::Button(STR_C("Retry"))) - m_orthophoto.retry_failed(); - } - if (!editor_orthophoto::can_download()) - ImGui::TextDisabled(STR_C("This build has no HTTP client, only cached tiles are shown")); - ImGui::TextDisabled(STR_C("Cache: %s"), editor_orthophoto::cache_directory().c_str()); - if (ImGui::Button(STR_C("Clear cache"))) - m_orthophoto.clear_cache(); - if (ImGui::IsItemHovered()) - ImGui::SetTooltip(STR_C("Deletes downloaded tiles from disk. They are fetched again around the camera.")); ImGui::TextDisabled(STR_C("Imagery: GUGiK, geoportal.gov.pl")); } void editor_mode::draw_orthophoto() { - if (!m_orthophoto.enabled()) + if (false == m_orthophoto.enabled() && std::none_of(m_wms.begin(), m_wms.end(), [](auto const &Layer) { return Layer->enabled(); })) return; // the camera was just published to the renderer (update_camera), so build the view from it rather than // from the renderer's previous frame; camera-relative rotation, same projection as the other overlays @@ -2391,7 +2674,11 @@ void editor_mode::draw_orthophoto() glm::mat4 const view = glm::mat4(glm::mat3(viewmatrix)); ImGuiIO const &io = ImGui::GetIO(); float const aspect = io.DisplaySize.y > 0.0f ? io.DisplaySize.x / io.DisplaySize.y : 1.0f; - m_orthophoto.draw(editor_mode::projection_matrix(aspect) * view, Camera.Pos, io.DisplaySize.x, io.DisplaySize.y); + auto const projection{editor_mode::projection_matrix(aspect) * view}; + m_orthophoto.draw(projection, Camera.Pos, io.DisplaySize.x, io.DisplaySize.y); + // the WMS layers over it, the top one of the list last + for (auto layer{m_wms.rbegin()}; layer != m_wms.rend(); ++layer) + (*layer)->draw(projection, Camera.Pos, io.DisplaySize.x, io.DisplaySize.y); } void editor_mode::draw_ortho_compass() const @@ -2417,7 +2704,8 @@ void editor_mode::draw_ortho_compass() const ImGuiIO const &io = ImGui::GetIO(); float const radius{36.0f}; float const margin{16.0f}; - ImVec2 const center{io.DisplaySize.x - margin - radius, margin + radius}; + // in the corner of the view, where the buttons of the toolbar and the hints along its bottom aren't + ImVec2 const center{editor_ui::view_max().x - margin - radius - 14.0f, editor_ui::view_max().y - margin - radius - 54.0f}; auto *drawlist{ImGui::GetForegroundDrawList()}; drawlist->AddCircleFilled(center, radius + 14.0f, IM_COL32(0, 0, 0, 180), 48); drawlist->AddCircle(center, radius - 6.0f, IM_COL32(255, 255, 255, 50), 48, 1.2f); @@ -2445,12 +2733,24 @@ void editor_mode::forget_ground() forget_ground_shapes(); } +void editor_mode::forget_ground_in(glm::dvec2 const &Min, glm::dvec2 const &Max) +{ + for (auto tile{ground_tiles.begin()}; tile != ground_tiles.end();) + { + glm::dvec2 const low{tile->first.first * ground_tile_size, tile->first.second * ground_tile_size}; + if (low.x <= Max.x && low.x + ground_tile_size >= Min.x && low.y <= Max.y && low.y + ground_tile_size >= Min.y) + tile = ground_tiles.erase(tile); + else + ++tile; + } +} + editor_terrain *editor_mode::terrain_at(double X, double Z) { return m_streamer.terrain_at(X, Z); } -std::vector editor_mode::active_terrains() +std::vector editor_mode::active_terrains() const { std::vector out; out.reserve(m_streamer.resident()); @@ -2884,9 +3184,11 @@ bool editor_mode::save() ui()->set_status(STR("The scenery wasn't opened for editing. Start the simulator with: -edit "), true); return false; } + first_step_done(first_step::save); - // the heightmap terrain is kept in files of its own, the scenery only needs the directive which loads it + // the heightmap terrain is kept in files of its own, the scenery only needs the directive which loads it, in a layer of its own std::vector rootstatements; + std::map> statements; if (m_streamer.active()) { std::string error; @@ -2896,28 +3198,56 @@ bool editor_mode::save() return false; } if (false == scene::Layers.terrain_directive()) - rootstatements.emplace_back("heightmap_terrain " + m_streamer.name() + " endheightmap_terrain"); + { + auto const directive{"heightmap_terrain " + m_streamer.name() + " endheightmap_terrain"}; + if (auto const layer{output_layer("teren")}; layer != null_handle) + statements[layer].push_back(directive); + else + rootstatements.push_back(directive); + } } if (m_profile.changed) profile_store(); + switch_store::tidy(); + switch_store::settle(); infra_store(); + m_srk.store(); if (false == m_saved_camera.has_value() || glm::distance(m_saved_camera->first, glm::dvec3{Camera.Pos}) > 0.5 || glm::distance(m_saved_camera->second, glm::vec3{Camera.Angle}) > 0.01f) { m_saved_camera = std::make_pair(glm::dvec3{Camera.Pos}, glm::vec3{Camera.Angle}); scene::Layers.mark(scene::layer_handle{1}, "//$c", {format("%.3f %.3f %.3f %.5f %.5f", Camera.Pos.x, Camera.Pos.y, Camera.Pos.z, Camera.Angle.x, Camera.Angle.y)}); } - auto const terrainadded{false == rootstatements.empty()}; + if (auto const map{editor_orthophoto::mark(m_orthophoto.settings(), m_orthophoto.enabled(), m_orthophoto.settings().north != 0.0 || m_orthophoto.settings().east != 0.0)}; false == m_orthophoto_scenery.empty() && map != m_orthophoto_mark && (m_orthophoto.enabled() || false == m_orthophoto_mark.empty())) + { + m_orthophoto_mark = map; + scene::Layers.mark(scene::layer_handle{1}, "//$o", {map}); + } + if (auto const area{editor_orthophoto::area_lines(m_orthophoto.area())}; false == m_orthophoto_scenery.empty() && area != m_orthophoto_area_mark) + { + m_orthophoto_area_mark = area; + scene::Layers.mark(scene::layer_handle{1}, "//$z", area); + } + auto const terrainadded{false == rootstatements.empty() || false == statements.empty()}; auto const controls{turntable_controls(rootstatements)}; + auto const noses{nose_controls(rootstatements)}; std::vector trailing; - starter_trainset(trailing); - auto const result = scene::Layers.save(rootstatements, trailing); + auto const placed{m_vehicle.trainset_lines(trailing)}; + if (placed == 0) + starter_trainset(trailing); + auto const result = scene::Layers.save(rootstatements, trailing, statements); if (result.success && controls) m_turntable_included = true; - if (result.success && trailing.size() == 3) + if (result.success && noses) + m_nose_included = true; + if (result.success && placed > 0) + m_vehicle.trainsets_written(); + if (result.success && placed == 0 && trailing.size() == 3) { std::istringstream header{trailing.front()}; - std::string keyword, timetable, track; + std::string keyword; + std::string timetable; + std::string track; double offset{0.0}; header >> keyword >> timetable >> track >> offset; if (auto *path{simulation::Paths.find(track)}; path != nullptr && simulation::Vehicles.find("wmb10-6457") == nullptr) @@ -2940,11 +3270,12 @@ void editor_mode::toggle_include(scene::instance_handle const Instance) if (included.dead) { // its directive is gone from the scenery file, and the place it was at with it - ui()->set_status("Include of \"" + *included.file + "\" was removed from the saved scenery, this can't be taken back.", true); + ui()->set_status(format(STR_C("Include of \"%s\" was removed from the saved scenery, this can't be taken back"), included.file->c_str()), true); return; } scene::Layers.removed(Instance, false == included.removed); - ui()->set_status("Include of \"" + *included.file + "\" " + (included.removed ? "removed." : "restored.")); + m_drives_standing.reset(); + ui()->set_status(format(included.removed ? STR_C("Include of \"%s\" removed") : STR_C("Include of \"%s\" restored"), included.file->c_str())); } void editor_mode::restore_include(EditorSnapshot &Snapshot) @@ -2960,7 +3291,7 @@ void editor_mode::restore_include(EditorSnapshot &Snapshot) auto current = scene::Layers.directive(Snapshot.instance); if (current.empty() || scene::Layers.instance(Snapshot.instance).dead) { - ui()->set_status("Include of \"" + Snapshot.node_name + "\" is gone from the scenery, the change can't be taken back.", true); + ui()->set_status(format(STR_C("Include of \"%s\" is gone from the scenery, the change can't be taken back"), Snapshot.node_name.c_str()), true); return; } set_include_directive(Snapshot.instance, Snapshot.serialized); @@ -2980,6 +3311,7 @@ void editor_mode::restore_includes(EditorSnapshot &Snapshot) } scene::Layers.removed(instance, false == scene::Layers.instance(instance).removed); } + m_drives_standing.reset(); for (auto &entry : Snapshot.directives) { auto current = scene::Layers.directive(entry.first); @@ -2992,7 +3324,7 @@ void editor_mode::restore_includes(EditorSnapshot &Snapshot) entry.second = std::move(current); } select_include(0); - ui()->set_status(gone > 0 ? std::to_string(gone) + " of the includes are gone from the saved scenery, they can't be taken back." : std::to_string(Snapshot.instances.size() + Snapshot.directives.size()) + " includes restored.", gone > 0); + ui()->set_status(gone > 0 ? format(STR_C("Includes gone from the saved scenery, they can't be taken back: %zu"), gone) : format(STR_C("Includes restored: %zu"), Snapshot.instances.size() + Snapshot.directives.size()), gone > 0); } void editor_mode::select_include(scene::instance_handle const Instance) @@ -3014,7 +3346,7 @@ void editor_mode::select_include(scene::instance_handle const Instance) if (false == editor_includes::parse_directive(scene::Layers.directive(m_instance), m_include.target, m_include.values)) { m_include.values.clear(); - m_include.issue = "The directive of the include can't be read from the scenery file, its parameters can't be changed."; + m_include.issue = STR_C("The directive of the include can't be read from the scenery file, its parameters can't be changed"); } // with a rotation or a scale in effect the parameters don't translate to a location in the scene in a single way, // see place_include() @@ -3024,13 +3356,22 @@ void editor_mode::select_include(scene::instance_handle const Instance) void editor_mode::set_include_directive(scene::instance_handle const Instance, std::string const &Directive) { - if (false == scene::Layers.modify(Instance, Directive)) + m_drives_standing.reset(); + std::string file; + std::vector values; + if (scene::Layers.tracked(Instance) && editor_includes::parse_directive(Directive, file, values) && scene::Layers.instance(Instance).file != nullptr && + editor_includes::normalized(file) == editor_includes::normalized(*scene::Layers.instance(Instance).file)) + file.clear(); + if (false == scene::Layers.modify(Instance, Directive, file)) return; std::vector retired; simulation::State.rebuild_include(Instance, retired); // the pick of the renderer is resolved a few frames after it's requested, and can still deliver one of these for (auto *model : retired) + { + nullify_history_pointers(model); m_retired.emplace_back(model, 120); + } } void editor_mode::apply_include() @@ -3042,24 +3383,57 @@ void editor_mode::apply_include() if (value == "end" || value.find_first_of("\"\r\n") != std::string::npos) { // either would cut the directive short - ui()->set_status("A parameter of an include can't be \"end\", or have a quotation mark in it.", true); + ui()->set_status(STR_C("A parameter of an include can't be \"end\", or have a quotation mark in it"), true); select_include(m_instance); // back to the values of the directive return; } } auto before = scene::Layers.directive(m_instance); + if (false == m_include.info.signal_kind.empty() + && std::ranges::any_of(m_include.info.parameters, [](auto const &Parameter) { return Parameter.id == 6 && Parameter.role == "texture"; })) + { + // the drawn plate of a signal follows its name; a plate picked from the textures stays, and so does a drawn one given + // another name by hand. While the name is cleared or one the plate can't carry, the plate keeps the last name, and + // follows again once a usable name is typed. No plate, or the texture named like the signal the editor gave before the + // plates were drawn, become the drawn one. The look, the index and the m of the plate go with it + std::string file; + std::vector previous; + if (editor_includes::parse_directive(before, file, previous) && previous.size() >= 6 && m_include.values.size() >= 6) + { + auto const look{signal_plate_style(previous[5])}; + auto const carried = [&](std::string const &Name) { return Name != "none" && signal_plate_drawn(signal_plate(Name, look)); }; + if (previous[0] != m_include.values[0] && m_include.values[5] == previous[5] && carried(m_include.values[0]) + && (previous[5] == signal_plate(previous[0], look) || (false == carried(previous[0]) && signal_plate_drawn(previous[5])) || signal_plate_blank(previous[0], previous[5]))) + m_include.values[5] = signal_plate(m_include.values[0], look); + } + } auto const directive = editor_includes::compose_directive(m_include.target, m_include.values); if (directive == before) return; - std::string read_before, read_after; - if (false == m_include.info.signal_read.empty()) + std::string read_before; + std::string read_after; + // a signal renamed: its indicators are named after it + std::string name_before; + glm::dvec3 standing{0.0}; + // the signal templates known, though no signal tool looked for them yet + if (m_include.info.category == "signal") + signal_scan(true); + if (false == m_include.info.signal_read.empty() || signal_template_of(m_include.target) != nullptr) { std::string file; std::vector previous; if (editor_includes::parse_directive(before, file, previous)) { - read_before = editor_includes::substitute(m_include.info.signal_read, previous); - read_after = editor_includes::substitute(m_include.info.signal_read, m_include.values); + if (false == m_include.info.signal_read.empty()) + { + read_before = editor_includes::substitute(m_include.info.signal_read, previous); + read_after = editor_includes::substitute(m_include.info.signal_read, m_include.values); + } + if (previous.size() >= 4 && false == m_include.values.empty() && previous.front() != m_include.values.front()) + { + name_before = previous.front(); + standing = scene::Layers.instance(m_instance).context.offset + glm::dvec3{std::strtod(previous[1].c_str(), nullptr), std::strtod(previous[2].c_str(), nullptr), std::strtod(previous[3].c_str(), nullptr)}; + } } } if (false == m_include_gesture) @@ -3078,6 +3452,12 @@ void editor_mode::apply_include() else if (read_before != read_after && false == m_history.empty()) signal_renamed(read_before, read_after, m_history.back()); set_include_directive(m_instance, directive); + if (false == name_before.empty() && false == m_history.empty()) + { + std::vector> carried; + signal_indicators_renamed(name_before, m_include.values.front(), standing, carried); + history_add_directives(m_history.back(), carried); + } } void editor_mode::place_include(std::string const &File, int const RotationMode, float const FixedRotation) @@ -3085,7 +3465,7 @@ void editor_mode::place_include(std::string const &File, int const RotationMode, if (scene::Layers.empty()) { // the directive has to go to a scenery file, and without the sources tracked there's no telling which - ui()->set_status("Scenery templates can be placed only in a scenery opened for editing (-edit).", true); + ui()->set_status(STR_C("Scenery templates can be placed only in a scenery opened for editing (-edit)"), true); WriteLog("Editor: scenery templates can be placed only in a scenery opened for editing (-edit)", logtype::generic); return; } @@ -3094,7 +3474,7 @@ void editor_mode::place_include(std::string const &File, int const RotationMode, auto const parameters = editor_includes::parameter_count(File); if (false == editor_includes::load(File, info, issue) || false == editor_includes::complete(info, parameters, &issue)) { - ui()->set_status("Template \"" + File + "\" can't be placed: " + issue, true); + ui()->set_status(format(STR_C("Template \"%s\" can't be placed: %s"), File.c_str(), issue.c_str()), true); return; } @@ -3102,7 +3482,7 @@ void editor_mode::place_include(std::string const &File, int const RotationMode, auto const layer = scene::Layers.resolve(scene::Layers.active()); if (std::string reason; false == scene::Layers.accepts(layer, &reason)) { - ui()->set_status("Template \"" + File + "\" can't be placed: " + (reason.empty() ? "there's no active layer to put it in" : "the active layer can't take it, " + reason), true); + ui()->set_status(format(STR_C("Template \"%s\" can't be placed: %s"), File.c_str(), (reason.empty() ? std::string{STR_C("there's no active layer to put it in")} : format(STR_C("the active layer can't take it, %s"), reason.c_str())).c_str()), true); return; } auto const context = scene::Layers.layer(layer).context_insert(); @@ -3110,7 +3490,7 @@ void editor_mode::place_include(std::string const &File, int const RotationMode, { // a template can pass its parameters to an origin directive, which isn't affected by these, or straight to // the nodes, which are. there's no single set of parameter values which puts both at the cursor - ui()->set_status("Template \"" + File + "\" can't be placed: the file of the active layer would receive it with a rotation or a scale in effect. Pick another layer.", true); + ui()->set_status(format(STR_C("Template \"%s\" can't be placed: the file of the active layer would receive it with a rotation or a scale in effect. Pick another layer"), File.c_str()), true); return; } glm::dvec3 const location = placement_on_ground(Camera.Pos + clamp_mouse_offset_to_max(GfxRenderer->Mouse_Position())); @@ -3124,7 +3504,7 @@ void editor_mode::place_include(std::string const &File, int const RotationMode, auto const instance = scene::Layers.place(layer, File, directive); if (instance == 0) { - ui()->set_status("Template \"" + File + "\" can't be placed in the active layer.", true); + ui()->set_status(format(STR_C("Template \"%s\" can't be placed in the active layer"), File.c_str()), true); return; } // show the models of the template right away. the rest of it comes into play when the saved scenery is loaded @@ -3137,9 +3517,8 @@ void editor_mode::place_include(std::string const &File, int const RotationMode, g_redo.clear(); select_include(instance); - ui()->set_status( - "\"" + info.name + "\" placed in layer \"" + scene::Layers.layer(layer).name + "\": " + std::to_string(preview.first) + " model(s) shown" - + (preview.second > 0 ? ", " + std::to_string(preview.second) + " other statement(s) of the template take effect once the scenery is saved and loaded again." : ".")); + ui()->set_status(format(STR_C("\"%s\" placed in layer \"%s\", models shown: %d"), info.name.c_str(), scene::Layers.layer(layer).name.c_str(), static_cast(preview.first)) + + (preview.second > 0 ? format(STR_C(", other statements of the template, working once the scenery is saved and loaded again: %d"), static_cast(preview.second)) : std::string{})); } void editor_mode::export_scenery() @@ -3225,6 +3604,25 @@ void editor_mode::fill_terrain_area() m_paint_outline.clear(); } +void editor_mode::remove_selected_chunks() +{ + // one step of the history, as the terrain changed in a frame goes + std::size_t removed{0}; + for (auto const &key : m_terrain_selection) + if (m_streamer.exists(key)) + { + m_streamer.remove_chunk(key.first, key.second); + ++removed; + } + m_terrain_selection.clear(); + if (removed > 0) + { + ground_tiles.clear(); + forget_ground_shapes(); + } + m_terrain_status = format(STR_P("%zu chunk removed, Ctrl+Z brings it back", "%zu chunks removed, Ctrl+Z brings them back", removed), removed); +} + void editor_mode::convert_selected_chunks() { // with 0.5 m spacing the paint can be as fine, the other spacings keep a sample per metre @@ -3301,24 +3699,29 @@ void editor_mode::capture_terrain() std::string as_text; model->export_as_text(as_text); push_snapshot(model, EditorSnapshot::Action::Delete, as_text); - nullify_history_pointers(model); - remove_from_hierarchy(model); m_node = nullptr; m_dragging = false; ui()->set_node(nullptr); - simulation::State.delete_model(model); + erase_model(model); } // the ground under a point the cursor landed on. the orthophoto laid over the ground catches the cursor like any // other surface, so the point can hang over the ground by as much as the orthophoto is lifted, or lie on the flat sheet // the orthophoto makes where it's not fitted to the ground. what's put in the scenery is to stand on the ground itself glm::dvec3 editor_mode::placement_on_ground(glm::dvec3 Location) +{ + return ground_at(Location); +} + +glm::dvec3 editor_mode::ground_at(glm::dvec3 Location) const { double constexpr reach = 2.0; // the ground is asked about this far around the point double constexpr slack = 0.5; // a surface this far over the point still is what the cursor landed on double constexpr height_tolerance = 50.0; // with nothing there or lower, how far up the ground is looked for float constexpr terrain_model_radius = 50.0f; // the same models count as ground as for the area fill and the orthophoto + if (false == std::isfinite(Location.x) || false == std::isfinite(Location.y) || false == std::isfinite(Location.z)) + return Location; glm::dvec2 const bmin{Location.x - reach, Location.z - reach}; glm::dvec2 const bmax{Location.x + reach, Location.z + reach}; std::vector triangles; @@ -3362,7 +3765,7 @@ void editor_mode::drop_model_instances() if (selected->radius() >= 50.0f) { // it'd be put on top of itself - ui()->set_status("\"" + selected->Model()->NameGet() + "\" is large enough to count as ground itself, so there's nothing to put it on", true); + ui()->set_status(format(STR_C("\"%s\" is large enough to count as ground itself, so there's nothing to put it on"), selected->Model()->NameGet().c_str()), true); return; } std::vector instances; @@ -3400,11 +3803,11 @@ void editor_mode::drop_model_instances() instance->mark_dirty(); ++moved; } - std::string status = std::to_string(moved) + " of " + std::to_string(instances.size()) + " instances of \"" + selected->Model()->NameGet() + "\" put on the ground"; + std::string status = format(STR_C("%d of %d copies of \"%s\" put on the ground"), moved, static_cast(instances.size()), selected->Model()->NameGet().c_str()); if (moved > 0) - status += "; Ctrl+Z takes them back one at a time"; + status += STR_C("; Ctrl+Z takes them back one at a time"); if (locked > 0) - status += ". " + std::to_string(locked) + " left alone: placed by a template, or on a layer which can't be edited"; + status += format(STR_C(". Left alone, placed by a template or on a layer which can't be edited: %d"), locked); ui()->set_status(status); } @@ -3420,13 +3823,21 @@ void editor_mode::read_georeference() std::error_code error; if (false == std::filesystem::exists(file, error)) { - for (auto const &entry : std::filesystem::directory_iterator(Global.asCurrentSceneryPath, error)) + for (std::filesystem::directory_iterator entry{Global.asCurrentSceneryPath, error}, end; entry != end; entry.increment(error)) { - auto name{entry.path().filename().string()}; + std::string name; + try + { + name = entry->path().filename().string(); + } + catch (std::exception const &) + { + continue; + } std::transform(name.begin(), name.end(), name.begin(), [](unsigned char const Character) { return static_cast(std::tolower(Character)); }); if (name == Global.SceneryFile) { - file = entry.path(); + file = entry->path(); break; } } @@ -3441,7 +3852,8 @@ void editor_mode::read_georeference() // Rainsted writes the origin of the scenery as: //$g , in kilometres std::istringstream words(line.substr(mark + 4)); std::string system; - double east{0.0}, north{0.0}; + double east{0.0}; + double north{0.0}; if (false == static_cast(words >> system >> east >> north) || system.find("1992") == std::string::npos) continue; auto const scale = (east < 10000.0 && north < 10000.0) ? 1000.0 : 1.0; @@ -3458,23 +3870,291 @@ void editor_mode::render_map_menu() { if (false == ImGui::BeginMenu(STR_C("Map"))) return; + if (ImGui::MenuItem(STR_C("Minimap"), "Ctrl+M", m_minimap.is_open())) + m_minimap.toggle(); + ImGui::Separator(); bool enabled = m_orthophoto.enabled(); if (ImGui::MenuItem(STR_C("Orthophoto"), nullptr, enabled)) - m_orthophoto.enabled(false == enabled); + choose_orthophoto(false == enabled); if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", STR_C("Aerial imagery of geoportal.gov.pl under the scenery, laid out by the origin of the scenery")); - ImGui::MenuItem(STR_C("Orthophoto settings..."), nullptr, &m_orthophoto_window); + // the settings among the base layers in the layers window + if (ImGui::MenuItem(STR_C("Orthophoto settings..."), nullptr, orthophoto_settings_open())) + { + ui()->show_layers(); + m_orthophoto_window = true; + } ImGui::EndMenu(); } -void editor_mode::render_orthophoto_window() +bool editor_mode::orthophoto_settings_open() const { - if (false == m_orthophoto_window) - return; - ImGui::SetNextWindowSize(ImVec2(430.0f, 0.0f), ImGuiCond_FirstUseEver); - if (ImGui::Begin((std::string(STR_C("Orthophoto")) + "###orthophoto").c_str(), &m_orthophoto_window)) + // drawn open in the layers window in this frame or in the last one + return ImGui::GetCurrentContext() != nullptr && ImGui::GetFrameCount() - m_orthophoto_frame <= 1; +} + +void editor_mode::render_base_layers() +{ + auto &stored{EditorSettings.wms_layers()}; + bool save{false}; + // the WMS layers of the user's, the top one first, each drawn over the ones under it + int moved{-1}; + int removed{-1}; + for (int i = 0; i < static_cast(stored.size()); ++i) + { + auto &entry{stored[static_cast(i)]}; + ImGui::PushID(i + 1); + save |= ImGui::Checkbox("##visible", &entry.visible); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Show or hide the layer")); + ImGui::SameLine(); + if (ImGui::TreeNode("##wms", "%s", entry.title.empty() ? entry.layers.c_str() : entry.title.c_str())) + { + ImGui::PushTextWrapPos(0.0f); + ImGui::TextDisabled("%s", entry.url.c_str()); + ImGui::TextDisabled(STR_C("Layers: %s"), entry.layers.c_str()); + ImGui::PopTextWrapPos(); + ImGui::SetNextItemWidth(160.0f); + ImGui::SliderFloat(STR_C("Opacity"), &entry.opacity, 0.0f, 1.0f, "%.2f"); + save |= ImGui::IsItemDeactivatedAfterEdit(); + if (false == entry.terms.empty()) + { + ImGui::TextUnformatted(STR_C("Terms of the service:")); + ImGui::PushTextWrapPos(0.0f); + ImGui::TextDisabled("%s", entry.terms.c_str()); + ImGui::PopTextWrapPos(); + } + if (i > 0) + { + if (ImGui::SmallButton(STR_C("Up"))) + moved = i - 1; + ImGui::SameLine(); + } + if (i + 1 < static_cast(stored.size())) + { + if (ImGui::SmallButton(STR_C("Down"))) + moved = i; + ImGui::SameLine(); + } + if (ImGui::SmallButton(STR_C("Remove"))) + removed = i; + ImGui::TreePop(); + } + ImGui::PopID(); + } + // a layer swapped with the one under it, or one taken away; the ones of the view go along + if (moved >= 0 && moved + 1 < static_cast(stored.size())) + { + std::swap(stored[static_cast(moved)], stored[static_cast(moved) + 1]); + if (moved + 1 < static_cast(m_wms.size())) + std::swap(m_wms[static_cast(moved)], m_wms[static_cast(moved) + 1]); + save = true; + } + if (removed >= 0) + { + stored.erase(stored.begin() + removed); + if (removed < static_cast(m_wms.size())) + { + m_wms[static_cast(removed)]->enabled(false); + m_wms[static_cast(removed)]->detach_scene(); + m_wms.erase(m_wms.begin() + removed); + } + save = true; + } + if (save) + EditorSettings.save(); + + // the orthophoto at the bottom, its settings opened here from the map menu too + ImGui::PushID("orthophoto"); + bool enabled{m_orthophoto.enabled()}; + if (ImGui::Checkbox("##visible", &enabled)) + choose_orthophoto(enabled); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Aerial imagery of geoportal.gov.pl under the scenery, laid out by the origin of the scenery")); + ImGui::SameLine(); + if (m_orthophoto_window) + { + ImGui::SetNextItemOpen(true); + m_orthophoto_window = false; + } + if (ImGui::TreeNode("##settings", "%s", STR_C("Orthophoto (geoportal.gov.pl)"))) + { + m_orthophoto_frame = ImGui::GetFrameCount(); render_orthophoto_ui(); - ImGui::End(); + ImGui::TreePop(); + } + ImGui::PopID(); + + // the terrain of the model under the tracks laid, as the terrain panel has it too + if (ImGui::Checkbox(STR_C("Terrain of the model right away while laying"), &m_nmt_state.grow)) + { + EditorSettings.terrain_while_laying(m_nmt_state.grow); + EditorSettings.save(); + } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Where the terrain of the scenery ends, the terrain model is made under the tracks as they're laid, around the cursor from the first point placed; " + "the chunks there are stay as they are. Off, it's made only when asked for")); + + render_wms_adding(); +} + +void editor_mode::render_wms_adding() +{ + auto &adding{m_wms_adding}; + ImGui::PushID("wmsadding"); + if (false == ImGui::TreeNode("##add", "%s", STR_C("Add a WMS layer"))) + { + ImGui::PopID(); + return; + } + ImGui::PushTextWrapPos(0.0f); + ImGui::TextDisabled("%s", STR_C("The address of a WMS service drawing in PUWG 1992 (EPSG:2180). Its tiles are kept in memory only and asked for only around the camera; " + "what the service allows is up to you, its terms are shown below")); + ImGui::PopTextWrapPos(); + ImGui::SetNextItemWidth(-1.0f); + auto const entered{ImGui::InputTextWithHint("##url", "https://...", adding.url.data(), adding.url.size(), ImGuiInputTextFlags_EnterReturnsTrue)}; + std::string const url{adding.url.data()}; + if ((ImGui::Button(STR_C("Read the layers")) || entered) && false == adding.reading.valid() && false == url.empty()) + { + adding.info.reset(); + adding.ticked.clear(); + adding.service = url; + adding.reading = std::async(std::launch::async, [url]() { return editor_orthophoto::describe(url); }); + } + if (adding.reading.valid()) + { + if (adding.reading.wait_for(std::chrono::seconds(0)) == std::future_status::ready) + { + adding.info = adding.reading.get(); + adding.ticked.assign(adding.info->layers.size(), 0); + } + else + ImGui::TextDisabled("%s", STR_C("Reading the capabilities of the service...")); + } + if (adding.info.has_value()) + { + auto const &info{*adding.info}; + ImGui::PushTextWrapPos(0.0f); + if (false == info.error.empty()) + ImGui::TextColored(ImVec4(1.0f, 0.45f, 0.4f, 1.0f), STR_C("The service can't be read: %s"), info.error.c_str()); + if (false == info.title.empty()) + ImGui::TextUnformatted(info.title.c_str()); + if (false == info.terms.empty()) + { + ImGui::TextUnformatted(STR_C("Terms of the service:")); + ImGui::TextDisabled("%s", info.terms.c_str()); + } + if (false == info.puwg && false == info.layers.empty()) + ImGui::TextColored(ImVec4(1.0f, 0.75f, 0.2f, 1.0f), "%s", STR_C("The service doesn't draw in PUWG 1992 (EPSG:2180), the editor can't lay it out")); + ImGui::PopTextWrapPos(); + if (false == info.layers.empty()) + { + ImGui::SetNextItemWidth(-1.0f); + ImGui::InputTextWithHint("##filter", STR_C("Filter the layers"), adding.filter.data(), adding.filter.size()); + auto const filter{ToLower(adding.filter.data())}; + ImGui::BeginChild("##layers", ImVec2(0.0f, std::min(200.0f, ImGui::GetFrameHeightWithSpacing() * static_cast(info.layers.size()) + 4.0f)), true); + for (std::size_t i = 0; i < info.layers.size(); ++i) + { + auto const &[name, title]{info.layers[i]}; + auto const label{title.empty() || title == name ? name : title + " (" + name + ")"}; + if (false == filter.empty() && ToLower(label).find(filter) == std::string::npos) + continue; + bool ticked{adding.ticked[i] != 0}; + ImGui::PushID(static_cast(i)); + if (ImGui::Checkbox(label.c_str(), &ticked)) + adding.ticked[i] = ticked ? 1 : 0; + ImGui::PopID(); + } + ImGui::EndChild(); + std::string layers; + for (std::size_t i = 0; i < info.layers.size(); ++i) + if (adding.ticked[i] != 0) + layers += (layers.empty() ? "" : ",") + info.layers[i].first; + auto const ready{info.puwg && false == layers.empty()}; + if (false == ready) + { + ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true); + ImGui::PushStyleVar(ImGuiStyleVar_Alpha, ImGui::GetStyle().Alpha * 0.5f); + } + auto const add{ImGui::Button(STR_C("Add")) && ready}; + if (false == ready) + { + ImGui::PopStyleVar(); + ImGui::PopItemFlag(); + } + if (add) + { + editorSettings::wms_layer entry; + entry.url = adding.service; + entry.layers = layers; + entry.title = info.title.empty() ? layers : info.title; + entry.terms = info.terms; + // on top of the others + EditorSettings.wms_layers().insert(EditorSettings.wms_layers().begin(), entry); + EditorSettings.save(); + adding.info.reset(); + adding.ticked.clear(); + adding.url.fill('\0'); + adding.filter.fill('\0'); + } + } + } + ImGui::TreePop(); + ImGui::PopID(); +} + +void editor_mode::update_wms_layers() +{ + auto const &stored{EditorSettings.wms_layers()}; + // a layer added or removed: the ones of the view made again, as the settings have them + auto same{m_wms.size() == stored.size()}; + for (std::size_t i = 0; same && i < stored.size(); ++i) + same = m_wms[i]->settings().service == stored[i].url && m_wms[i]->settings().layers == stored[i].layers; + if (false == same) + { + for (auto &layer : m_wms) + { + layer->enabled(false); + layer->detach_scene(); + } + m_wms.clear(); + for (auto const &entry : stored) + { + auto layer{std::make_unique()}; + auto config{layer->settings()}; + config.service = entry.url; + config.layers = entry.layers; + config.hires = false; + config.year = 0; + config.in_scene = false; + layer->settings(config); + ground_sources(*layer); + m_wms.push_back(std::move(layer)); + } + } + // laid out by the origin of the scenery and onto the ground as the orthophoto is, around the camera as far as it + load_orthophoto_settings(); + auto const &base{m_orthophoto.settings()}; + auto const placed{base.north != 0.0 || base.east != 0.0}; + for (std::size_t i = 0; i < m_wms.size(); ++i) + { + auto &layer{*m_wms[i]}; + auto config{layer.settings()}; + if (config.north != base.north || config.east != base.east || config.radius != base.radius || config.drape != base.drape || config.lift != base.lift || config.height != base.height || + config.opacity != stored[i].opacity) + { + config.north = base.north; + config.east = base.east; + config.radius = base.radius; + config.drape = base.drape; + config.lift = base.lift; + config.height = base.height; + config.opacity = stored[i].opacity; + layer.settings(config); + } + layer.enabled(stored[i].visible && placed); + layer.update(Camera.Pos); + } } void editor_mode::render_view_menu() @@ -3485,11 +4165,29 @@ void editor_mode::render_view_menu() toggle_ortho(); if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", STR_C("The view straight down without perspective, as on a map; again for the camera as it was")); - ImGui::MenuItem("Show lanes", nullptr, &m_roadtool.lanes); + if (ImGui::BeginMenu(STR_C("Tracks in the top view"))) + { + render_top_tracks_choice(false); + ImGui::EndMenu(); + } + if (ImGui::BeginMenu(STR_C("Track colours"))) + { + char const *const names[]{"Plain", "By the radius", "By the speed", "By the grade"}; + for (int i = 0; i < 4; ++i) + if (ImGui::MenuItem(STR_C(names[i]), nullptr, static_cast(m_track_colouring) == i)) + m_track_colouring = static_cast(i); + ImGui::EndMenu(); + } if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", "Draws the lanes of the roads with the ways the vehicles take through the junctions"); - if (ImGui::MenuItem(STR_C("Structure gauge"), nullptr, m_gauge.open)) - m_gauge.open = !m_gauge.open; + ImGui::SetTooltip("%s", STR_C("The tracks of the track mode coloured by their radius, speed or grade, with the legend in the corner")); + ImGui::MenuItem(STR_C("Track labels in the top view"), nullptr, &m_track_labels); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Zoomed in from above, the curves get their radius and length and the switches their name and type, as on a plan; where they'd crowd, some are left out")); + ImGui::MenuItem(STR_C("Show lanes"), nullptr, &m_roadtool.lanes); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("The lanes of the roads drawn as the paths the vehicles take")); + if (ImGui::MenuItem(STR_C("Structure gauge"), nullptr, m_gauge.is_open())) + m_gauge.toggle(); if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", STR_C("Checks which models enter the structure gauge of the tracks and the clearance over the roads (skrajnia budowli)")); ImGui::Separator(); @@ -3551,7 +4249,7 @@ void editor_mode::render_environment_window() if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", STR_C("Up to 1 the sky clouds over, past it rain or snow falls, by the air temperature")); auto temperature{Global.AirTemperature}; - auto const air{format("%.1f deg C", Global.AirTemperature)}; + auto const air{format("%.1f °C", Global.AirTemperature)}; if (ImGui::SliderFloat((std::string(STR_C("Air temperature")) + "###airtemperature").c_str(), &temperature, -35.0f, 40.0f, air.c_str())) { Global.AirTemperature = std::clamp(temperature, -35.0f, 40.0f); @@ -3655,10 +4353,19 @@ void editor_mode::render_open_scenery_popup() m_openscenery_list.clear(); m_openscenery_choice.clear(); std::error_code error; - for (auto const &entry : std::filesystem::directory_iterator(Global.asCurrentSceneryPath, error)) + for (std::filesystem::directory_iterator entry{Global.asCurrentSceneryPath, error}, end; entry != end; entry.increment(error)) { - auto const name{entry.path().filename().string()}; - if (entry.is_regular_file(error) && name.size() > 4 && lower(name.substr(name.size() - 4)) == ".scn" && name.front() != '$') + std::string name; + try + { + name = entry->path().filename().string(); + } + catch (std::exception const &) + { + continue; + } + std::error_code status; + if (entry->is_regular_file(status) && name.size() > 4 && lower(name.substr(name.size() - 4)) == ".scn" && name.front() != '$') m_openscenery_list.emplace_back(name); } std::sort(m_openscenery_list.begin(), m_openscenery_list.end(), [&](std::string const &A, std::string const &B) { return lower(A) < lower(B); }); @@ -3719,9 +4426,29 @@ void editor_mode::terrain_workspace(bool const Open) m_terrain_spacing = m_streamer.manifest().spacing; } +editor_mode::texture_offer editor_mode::terrain_texture_offer(char const *None) +{ + return {STR_C("In the palette and on the water of this terrain:"), + [this]() { + std::vector list; + auto const add = [&](std::string const &Name, char const *Note) { + if (Name.empty() || Name == "none" || std::any_of(list.begin(), list.end(), [&](texture_use const &Use) { return Use.name == Name; })) + return; + list.push_back({null_handle, Name, 0, Note}); + }; + for (auto const &layer : m_streamer.manifest().layers) + add(layer.material, STR_C("In the palette of the terrain")); + add(m_streamer.manifest().water_material, STR_C("The default water material")); + for (auto const &body : m_streamer.water()) + add(body.material, STR_C("On a body of water")); + return list; + }, + None, ""}; +} + void editor_mode::render_terrain_tool_options() { - // the orthophoto has a window of its own, see render_orthophoto_window() + // the orthophoto has its settings among the base layers in the layers window, see render_base_layers() render_terrain_ui(); } @@ -3766,9 +4493,7 @@ void editor_mode::undo_last_area_fill() m_node = nullptr; ui()->set_node(nullptr); } - nullify_history_pointers(model); - remove_from_hierarchy(model); - simulation::State.delete_model(model); + erase_model(model); } m_fill_status = format(STR_C("Removed %zu objects of the last fill"), created.size()); } @@ -3922,9 +4647,9 @@ void editor_mode::run_area_fill() m_fill_status = format(STR_C("Placed %zu of %zu objects"), m_fill_last.size(), static_cast(target)); if (points.size() < target) - m_fill_status += " (limited by min. spacing)"; + m_fill_status += STR_C(" (limited by min. spacing)"); if (unsupported > 0) - m_fill_status += ", " + std::to_string(unsupported) + " without ground found (height interpolated)"; + m_fill_status += format(STR_C(", without ground under them (height from the outline): %zu"), unsupported); WriteLog("Editor: area fill - " + m_fill_status, logtype::generic); } @@ -3980,7 +4705,8 @@ void editor_mode::render_area_fill() { ImGui::TextDisabled(STR_C("LMB: add outline point Backspace: remove last point")); double const area = polygon_area_xz(m_fill_points); - ImGui::Text(STR_C("Points: %zu Area: %.0f m2 (%.2f ha)"), m_fill_points.size(), area, area / 10000.0); + // the square sign written as its utf-8 bytes: the game is built without /utf-8 where it has the debug symbols + ImGui::Text(STR_C("Points: %zu Area: %.0f m\xC2\xB2 (%.2f ha)"), m_fill_points.size(), area, area / 10000.0); if (ImGui::Button(STR_C("Remove last point")) && !m_fill_points.empty()) m_fill_points.pop_back(); ImGui::SameLine(); @@ -4002,15 +4728,21 @@ void editor_mode::render_area_fill() ImGui::SetNextItemWidth(120.0f); ImGui::InputFloat(STR_C("Density (objects/ha)"), &m_fill_density, 10.0f, 100.0f, "%.1f"); m_fill_density = std::max(0.0f, m_fill_density); - ImGui::SetNextItemWidth(120.0f); - ImGui::InputFloat(STR_C("Min. spacing (m)"), &m_fill_min_spacing, 0.5f, 2.0f, "%.1f"); - m_fill_min_spacing = std::max(0.0f, m_fill_min_spacing); - ImGui::SetNextItemWidth(200.0f); - ImGui::DragFloatRange2("Scale", &m_fill_scale_min, &m_fill_scale_max, 0.01f, 0.1f, 5.0f, "min %.2f", "max %.2f"); - ImGui::Checkbox(STR_C("Random rotation"), &m_fill_random_rotation); - if (!m_fill_random_rotation) - ui()->render_rotation_controls(); - ImGui::Checkbox(STR_C("Large models count as ground (terrain tiles)"), &m_fill_models_as_ground); + ImGui::PushID("areafill"); + if (ImGui::TreeNode(STR_C("More settings"))) + { + ImGui::SetNextItemWidth(120.0f); + ImGui::InputFloat(STR_C("Min. spacing (m)"), &m_fill_min_spacing, 0.5f, 2.0f, "%.1f"); + m_fill_min_spacing = std::max(0.0f, m_fill_min_spacing); + ImGui::SetNextItemWidth(200.0f); + ImGui::DragFloatRange2(STR_C("Scale"), &m_fill_scale_min, &m_fill_scale_max, 0.01f, 0.1f, 5.0f, "min %.2f", "max %.2f"); + ImGui::Checkbox(STR_C("Random rotation"), &m_fill_random_rotation); + if (!m_fill_random_rotation) + ui()->render_rotation_controls(); + ImGui::Checkbox(STR_C("Large models count as ground (terrain tiles)"), &m_fill_models_as_ground); + ImGui::TreePop(); + } + ImGui::PopID(); ImGui::Text(STR_C("Estimated objects: %.0f"), std::round(area / 10000.0 * m_fill_density)); @@ -4183,9 +4915,7 @@ void editor_mode::shape_array() copies.pop_back(); if (model == nullptr) continue; - nullify_history_pointers(model); - remove_from_hierarchy(model); - simulation::State.delete_model(model); + erase_model(model); } std::string definition; @@ -4270,9 +5000,7 @@ void editor_mode::restore_array_snapshot(EditorSnapshot Snapshot, std::vectorset_node(nullptr); } - nullify_history_pointers(model); - remove_from_hierarchy(model); - simulation::State.delete_model(model); + erase_model(model); } else { @@ -4320,33 +5048,37 @@ void editor_mode::render_array() ImGui::SetTooltip("%s", STR_C("As many copies are made as fit in this length, measured along the row")); } - ImGui::Checkbox(STR_C("Relative offset"), &settings.relative); - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", STR_C("Distance between the copies as a part of the size of the model, along its axes: x, y (up), z.\n" - "1 along an axis puts the copies end to end")); - if (settings.relative) - { - ImGui::SetNextItemWidth(200.0f); - ImGui::DragFloat3(STR_C("x size"), &settings.relative_offset.x, 0.01f, 0.0f, 0.0f, "%.3f"); - } - ImGui::Checkbox(STR_C("Constant offset"), &settings.constant); - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", STR_C("Distance between the copies in metres, along the axes of the model: x, y (up), z.\n" - "With both offsets on the copies are set apart by their sum")); - if (settings.constant) - { - ImGui::SetNextItemWidth(200.0f); - ImGui::DragFloat3("m", &settings.constant_offset.x, 0.05f, 0.0f, 0.0f, "%.3f"); - } ImGui::SetNextItemWidth(120.0f); ImGui::DragFloat(STR_C("Turn per copy (deg)"), &settings.turn, 0.1f, -180.0f, 180.0f, "%.2f"); if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", STR_C("Each copy is turned by this much around the vertical axis against the one before it,\n" "and the row bends with them into an arc")); - ImGui::Checkbox(STR_C("Follow the ground"), &settings.ground); - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", STR_C("The copies are put as high over the ground as the model is, instead of level with it.\n" - "Not for the models large enough to count as ground themselves")); + if (ImGui::TreeNode(STR_C("More settings"))) + { + ImGui::Checkbox(STR_C("Relative offset"), &settings.relative); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Distance between the copies as a part of the size of the model, along its axes: x, y (up), z.\n" + "1 along an axis puts the copies end to end")); + if (settings.relative) + { + ImGui::SetNextItemWidth(200.0f); + ImGui::DragFloat3(STR_C("x size"), &settings.relative_offset.x, 0.01f, 0.0f, 0.0f, "%.3f"); + } + ImGui::Checkbox(STR_C("Constant offset"), &settings.constant); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Distance between the copies in metres, along the axes of the model: x, y (up), z.\n" + "With both offsets on the copies are set apart by their sum")); + if (settings.constant) + { + ImGui::SetNextItemWidth(200.0f); + ImGui::DragFloat3("m", &settings.constant_offset.x, 0.05f, 0.0f, 0.0f, "%.3f"); + } + ImGui::Checkbox(STR_C("Follow the ground"), &settings.ground); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("The copies are put as high over the ground as the model is, instead of level with it.\n" + "Not for the models large enough to count as ground themselves")); + ImGui::TreePop(); + } if (selected != nullptr) { @@ -4438,7 +5170,7 @@ void editor_mode::render_workspaces() }; area const areas[] = { {STR_C("Surroundings"), work_area::surroundings, editor_icons::icon::work_surroundings, STR_C("Models around the line: select, insert, brush, area fill, copy to the node bank")}, - {STR_C("Tracks"), work_area::tracks, editor_icons::icon::work_tracks, STR_C("Tracks and switches, signals, objects along the track, checks of the line")}, + {STR_C("Tracks"), work_area::tracks, editor_icons::icon::work_tracks, STR_C("Tracks and switches, signals, kilometrage and posts along the track, checks of the line")}, {STR_C("Roads"), work_area::roads, editor_icons::icon::work_roads, STR_C("Roads and junctions, level crossings, the points where the traffic comes and goes")}, {STR_C("Terrain"), work_area::terrain, editor_icons::icon::work_terrain, STR_C("Heightmap terrain: chunks, sculpting, painting, water, orthophoto")}, }; @@ -4517,7 +5249,7 @@ void editor_mode::render_edit_menu() if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", STR_C("Puts the copied models at the cursor, around it as they were around the selected one; Ctrl+RMB in the view pastes them where it was clicked")); ImGui::Separator(); - if (ImGui::MenuItem(STR_C("Group"), "Ctrl+G", false, models && selected_nodes().size() > 1)) + if (ImGui::MenuItem(STR_C("Group together"), "Ctrl+G", false, models && selected_nodes().size() > 1)) group_selection(); if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", STR_C("The selected models move together from now on; a click on one selects them all. Shift+LMB adds a model to the selection")); @@ -4526,7 +5258,7 @@ void editor_mode::render_edit_menu() ungroup_selection(); if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", STR_C("The models of the group move each by itself again")); - if (ImGui::MenuItem(STR_C("Drop to the ground"), STR_C("End"), false, selected)) + if (ImGui::MenuItem(STR_C("Drop to the ground"), "End", false, selected)) drop_selection_to_ground(); if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", STR_C("Puts each selected model, also each model of their groups, down onto the terrain or the object under it")); @@ -4540,7 +5272,7 @@ void editor_mode::render_edit_menu() show_track_tab(m_track_window_open ? m_track_tab : track_tab::path); m_track_search.focus = true; } - if (ImGui::MenuItem(STR_C("Bend along the track"), "B", false, ui()->mode() != nodebank_panel::TRACK)) + if (ImGui::MenuItem(STR_C("Bend the selected along the track"), "B", false, ui()->mode() != nodebank_panel::TRACK)) bend_shortcut(); if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", STR_C("Bends the selected model, e.g. a platform edge or a fence, along the nearest track; the settings are in the inspector")); @@ -4554,9 +5286,912 @@ void editor_mode::render_help_menu() ImGui::MenuItem(STR_C("Keyboard shortcuts"), "F1", &m_shortcuts_open); if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", STR_C("The keys of the editor, for each field of work")); + ImGui::MenuItem(STR_C("Tutorial"), nullptr, &m_first_steps_open); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Short lessons: the camera, laying track, curves, the radius at the bends, correcting a curve, joining, switches, switch templates, signals and posts, a whole line step by step, fixing, the gizmo, the grade line, terrain, older sceneries, saving and driving")); ImGui::EndMenu(); } +void editor_mode::first_step_done(first_step const Step) +{ + m_first_steps_done[static_cast(Step)] = true; +} + +void editor_mode::open_kilometrage() +{ + choose_work_area(work_area::tracks); + show_track_tab(track_tab::kilometrage); +} + +namespace +{ + +void tutorial_input(char const *Keys, char const *Text, float const Column) +{ + auto &list{*ImGui::GetWindowDrawList()}; + auto const at{ImGui::GetCursorScreenPos()}; + auto const height{std::round(ImGui::GetTextLineHeight() * 1.45f)}; + auto const gap{std::round(height * 0.2f)}; + float x{0.0f}; + std::istringstream words{Keys}; + for (std::string word; words >> word;) + { + ImVec2 const place{at.x + x, at.y}; + if (word == "+") + { + auto const size{ImGui::CalcTextSize("+")}; + list.AddText(ImVec2(place.x, std::round(at.y + (height - size.y) * 0.5f)), ImGui::GetColorU32(ImGuiCol_TextDisabled), "+"); + x += size.x + gap; + } + else if (word == "LMB" || word == "RMB" || word == "MMB" || word == "wheel" || word == "move") + x += gesture_mouse(list, place, height, word) + gap; + else + x += gesture_key(list, place, height, word) + gap; + } + ImGui::Dummy(ImVec2(std::max(x, Column), height)); + ImGui::SameLine(); + ImGui::SetCursorPosY(ImGui::GetCursorPosY() + std::round((height - ImGui::GetTextLineHeight()) * 0.5f)); + ImGui::TextWrapped("%s", STR_C(Text)); +} + +// a window that grew past the bottom or the right of the screen is moved back onto it +void keep_on_screen(char const *Name) +{ + auto const *window{ImGui::FindWindowByName(Name)}; + if (window == nullptr) + return; + auto const display{ImGui::GetIO().DisplaySize}; + ImVec2 position{window->Pos}; + position.x = std::max(0.0f, std::min(position.x, display.x - window->Size.x)); + position.y = std::max(20.0f, std::min(position.y, display.y - window->Size.y)); + if (position.x != window->Pos.x || position.y != window->Pos.y) + ImGui::SetNextWindowPos(position); +} + +// the strip of the profile: the ground, the track as it lies, the grade line over them with a point of it dragged up and down, +// the grades on both sides of it following +void tutorial_profile_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const High, double const Time) +{ + auto const width{High.x - Low.x}; + auto const height{High.y - Low.y}; + auto const x_of = [&](float const Share) { return Low.x + width * (0.06f + 0.88f * Share); }; + auto const y_of = [&](float const Level) { return Low.y + height * (0.82f - 0.6f * Level); }; + std::vector ground; + for (int i = 0; i <= 60; ++i) + { + auto const share{i / 60.0f}; + ground.emplace_back(x_of(share), y_of(0.25f + 0.35f * std::sin(share * 5.2f + 0.6f) * 0.5f + 0.18f * share)); + } + auto const flags{List.Flags}; + List.Flags &= ~ImDrawListFlags_AntiAliasedFill; + for (std::size_t i = 0; i + 1 < ground.size(); ++i) + List.AddQuadFilled(ground[i], ground[i + 1], ImVec2(ground[i + 1].x, High.y), ImVec2(ground[i].x, High.y), IM_COL32(110, 85, 55, 70)); + List.Flags = flags; + List.AddPolyline(ground.data(), static_cast(ground.size()), IM_COL32(170, 130, 80, 220), 0, 1.5f); + auto const lift{static_cast(0.5 + 0.5 * std::sin(Time * 1.6))}; + std::array const points{ImVec2(x_of(0.0f), y_of(0.32f)), ImVec2(x_of(0.38f), y_of(0.42f)), ImVec2(x_of(0.66f), y_of(0.35f + 0.4f * lift)), ImVec2(x_of(1.0f), y_of(0.55f))}; + List.AddPolyline(points.data(), static_cast(points.size()), IM_COL32(170, 170, 170, 160), 0, 1.0f); + List.AddPolyline(points.data(), static_cast(points.size()), IM_COL32(90, 220, 110, 255), 0, 2.5f); + for (std::size_t i = 0; i < points.size(); ++i) + List.AddCircleFilled(points[i], i == 2 ? 6.0f : 4.5f, i == 2 ? kGestureLit : IM_COL32(250, 210, 80, 255)); + List.AddCircle(points[2], 9.0f, kGestureLit, 0, 1.5f); + for (std::size_t i = 0; i + 1 < points.size(); ++i) + { + auto const grade{-(points[i + 1].y - points[i].y) / (points[i + 1].x - points[i].x) * 40.0f}; + auto const text{std::format("{:+.1f}", std::abs(grade) < 0.05f ? 0.0f : grade)}; + ImVec2 const middle{(points[i].x + points[i + 1].x) * 0.5f, (points[i].y + points[i + 1].y) * 0.5f - ImGui::GetTextLineHeight() - 2.0f}; + List.AddText(ImVec2(middle.x - ImGui::CalcTextSize(text.c_str()).x * 0.5f, middle.y), i == 0 ? IM_COL32(200, 200, 200, 255) : IM_COL32(255, 255, 255, 255), text.c_str()); + } + gesture_mouse(List, ImVec2(points[2].x + 12.0f, points[2].y + 10.0f), height * 0.18f, "LMB"); +} + +// the points of a switch clicked one after another: its start, the ends of its two tracks, the way on, the points along the diverging track +void tutorial_template_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const High, double const Time) +{ + auto const width{High.x - Low.x}; + auto const height{High.y - Low.y}; + auto const at = [&](float const X, float const Y) { return ImVec2(Low.x + width * X, Low.y + height * Y); }; + auto const curve = [&](float const Share) { return at(0.08f + 0.70f * Share, 0.72f - 0.42f * Share * Share); }; + auto const shown{static_cast(std::fmod(static_cast(Time), 10.0f))}; + std::vector line; + for (int i = 0; i <= 24; ++i) + line.push_back(curve(static_cast(i) / 24.0f)); + List.AddLine(at(0.08f, 0.72f), at(0.78f, 0.72f), IM_COL32(150, 150, 150, 130), 3.0f); + List.AddPolyline(line.data(), static_cast(line.size()), IM_COL32(150, 150, 150, 130), ImDrawFlags_None, 3.0f); + std::array const points{at(0.08f, 0.72f), at(0.78f, 0.72f), curve(1.0f), at(0.94f, 0.14f), curve(0.28f), curve(0.5f), curve(0.72f), curve(0.88f)}; + if (shown >= 1) + List.AddLine(points[0], points[1], IM_COL32(255, 255, 255, 230), 1.5f); + if (shown >= 3) + List.AddLine(points[2], points[3], IM_COL32(90, 200, 255, 230), 1.5f); + for (int i = 0; i < static_cast(points.size()) && i <= shown; ++i) + { + List.AddCircleFilled(points[i], 4.0f, i < 4 ? IM_COL32(255, 225, 60, 255) : IM_COL32(120, 255, 120, 255)); + if (i < 4) + List.AddText(ImVec2(points[i].x + 6.0f, points[i].y - 18.0f), IM_COL32(255, 255, 255, 255), std::to_string(i + 1).c_str()); + } + if (shown >= 8) + List.AddPolyline(line.data(), static_cast(line.size()), IM_COL32(255, 90, 200, 255), ImDrawFlags_None, 2.0f); +} + +// the radius of the curve at a bend: the two straights clicked stay, the curve between them grows from sharp to gentle and back +void tutorial_corner_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const High, double const Time) +{ + auto const width{High.x - Low.x}; + auto const height{High.y - Low.y}; + glm::vec2 const from{Low.x + width * 0.04f, Low.y + height * 0.80f}; + glm::vec2 const vertex{Low.x + width * 0.50f, Low.y + height * 0.18f}; + glm::vec2 const to{Low.x + width * 0.96f, Low.y + height * 0.80f}; + auto const point = [](glm::vec2 const Point) { return ImVec2(Point.x, Point.y); }; + List.AddLine(point(from), point(vertex), IM_COL32(150, 150, 150, 130), 1.0f); + List.AddLine(point(vertex), point(to), IM_COL32(150, 150, 150, 130), 1.0f); + List.AddCircleFilled(point(vertex), 4.0f, IM_COL32(255, 255, 255, 255)); + // there and back in 8 s, a moment at each end + auto const cycle{std::fmod(static_cast(Time), 8.0f) / 8.0f}; + auto const swing{std::clamp(1.3f - std::abs(cycle * 2.0f - 1.0f) * 1.6f, 0.0f, 1.0f)}; + auto const share{swing * swing * (3.0f - 2.0f * swing)}; + auto const in{glm::normalize(from - vertex)}; + auto const out{glm::normalize(to - vertex)}; + auto const tangent{glm::mix(0.12f, 0.92f, share) * glm::length(from - vertex)}; + auto const half{std::acos(glm::dot(in, out)) * 0.5f}; + auto const centre{vertex + glm::normalize(in + out) * (tangent / std::cos(half))}; + auto const start{vertex + in * tangent}; + auto const end{vertex + out * tangent}; + auto const begin{std::atan2(start.y - centre.y, start.x - centre.x)}; + auto sweep{std::atan2(end.y - centre.y, end.x - centre.x) - begin}; + while (sweep > glm::pi()) + sweep -= glm::two_pi(); + while (sweep < -glm::pi()) + sweep += glm::two_pi(); + auto const radius{glm::length(start - centre)}; + std::vector line{point(from)}; + for (int i = 0; i <= 32; ++i) + { + auto const angle{begin + sweep * static_cast(i) / 32.0f}; + line.push_back(ImVec2(centre.x + radius * std::cos(angle), centre.y + radius * std::sin(angle))); + } + line.push_back(point(to)); + List.AddPolyline(line.data(), static_cast(line.size()), IM_COL32(230, 190, 90, 255), ImDrawFlags_None, 3.0f); + auto const label{format(STR_C("R %.0f m: %s"), glm::mix(300.0, 6000.0, static_cast(share)), share < 0.5f ? STR_C("a sharp curve, a slow train") : STR_C("a gentle curve, a fast train"))}; + List.AddText(ImVec2(Low.x + (width - ImGui::CalcTextSize(label.c_str()).x) * 0.5f, High.y - ImGui::GetTextLineHeight() - 4.0f), IM_COL32(235, 235, 235, 255), label.c_str()); +} + +// the route of the grade line picked on the map: a click lights up the whole line through the track, Shift and a box only the +// tracks between the outermost ones in it; beside it the strip with a point of the line dragged +void tutorial_route_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const High, double const Time) +{ + auto const split{std::round(Low.x + (High.x - Low.x) * 0.48f)}; + tutorial_profile_sketch(List, ImVec2(split + 6.0f, Low.y), High, Time); + List.AddLine(ImVec2(split + 2.0f, Low.y + 6.0f), ImVec2(split + 2.0f, High.y - 6.0f), ImGui::GetColorU32(ImGuiCol_Border), 1.0f); + auto const width{split - Low.x}; + auto const height{High.y - Low.y}; + auto const at = [&](float const X, float const Y) { return ImVec2(Low.x + width * X, Low.y + height * Y); }; + auto const mix = [](ImVec2 const A, ImVec2 const B, float const T) { return ImVec2(A.x + (B.x - A.x) * T, A.y + (B.y - A.y) * T); }; + auto const ease = [](float const T) { auto const t{std::clamp(T, 0.0f, 1.0f)}; return t * t * (3.0f - 2.0f * t); }; + // the joints of the tracks of the line, and a siding going off it at a switch + std::array const joints{at(0.04f, 0.72f), at(0.18f, 0.64f), at(0.32f, 0.54f), at(0.46f, 0.48f), at(0.60f, 0.46f), at(0.74f, 0.42f), at(0.88f, 0.32f), at(0.98f, 0.24f)}; + int constexpr tracks{7}; + List.AddBezierQuadratic(joints[3], at(0.58f, 0.52f), at(0.80f, 0.66f), IM_COL32(130, 130, 130, 200), 2.0f); + auto const cycle{static_cast(std::fmod(Time, 8.0))}; + bool const boxing{cycle >= 4.0f}; + int first{0}; + int last{tracks - 1}; + bool lit{false}; + ImVec2 cursor; + if (false == boxing) + { + auto const target{mix(joints[4], joints[5], 0.5f)}; + cursor = mix(at(0.75f, 0.92f), target, ease(cycle / 1.0f)); + lit = cycle > 1.3f; + } + else + { + auto const corner{at(0.29f, 0.28f)}; + auto const drag{ease((cycle - 4.6f) / 1.5f)}; + auto const other{mix(corner, at(0.72f, 0.70f), drag)}; + cursor = cycle < 4.6f ? mix(at(0.75f, 0.92f), corner, ease((cycle - 4.0f) / 0.6f)) : other; + if (cycle >= 4.6f && cycle < 6.6f) + { + List.AddRectFilled(corner, other, IM_COL32(90, 175, 255, 40)); + List.AddRect(corner, other, kGestureLit, 0.0f, 0, 1.5f); + } + lit = cycle >= 6.2f; + first = 2; + last = 4; + gesture_key(List, ImVec2(Low.x + 6.0f, Low.y + 6.0f), std::round(ImGui::GetTextLineHeight() * 1.3f), "Shift"); + } + for (int i = 0; i < tracks; ++i) + { + auto const on{lit && i >= first && i <= last}; + List.AddLine(joints[i], joints[i + 1], on ? IM_COL32(90, 220, 110, 255) : IM_COL32(170, 170, 170, 220), on ? 4.0f : 2.0f); + } + for (auto const &joint : joints) + List.AddCircleFilled(joint, 2.5f, IM_COL32(220, 220, 220, 255)); + gesture_mouse(List, ImVec2(cursor.x + 2.0f, cursor.y + 2.0f), std::round(height * 0.16f), "LMB"); + auto const caption{boxing ? STR_C("Shift + a box: between the outermost tracks") : STR_C("LMB on a track: its whole line")}; + List.AddText(ImVec2(Low.x + 6.0f, High.y - ImGui::GetTextLineHeight() - 4.0f), IM_COL32(230, 230, 230, 230), caption); +} + +// a signal put by a track: pressed beside it and dragged along, the arrow tells the way of the trains which see it; then the +// hectometre posts of the line stand up one after the other +void tutorial_signal_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const High, double const Time) +{ + auto const width{High.x - Low.x}; + auto const height{High.y - Low.y}; + auto const at = [&](float const X, float const Y) { return ImVec2(Low.x + width * X, Low.y + height * Y); }; + auto const ease = [](float const T) { auto const t{std::clamp(T, 0.0f, 1.0f)}; return t * t * (3.0f - 2.0f * t); }; + auto const cycle{static_cast(std::fmod(Time, 8.0))}; + // the track seen from above: sleepers and the two rails + auto const middle{at(0.0f, 0.5f).y}; + auto const gauge{height * 0.07f}; + for (int sleeper = 0; sleeper < 40; ++sleeper) + { + auto const x{at(0.02f + 0.025f * static_cast(sleeper), 0.0f).x}; + List.AddLine(ImVec2(x, middle - gauge * 1.6f), ImVec2(x, middle + gauge * 1.6f), IM_COL32(110, 90, 70, 255), 3.0f); + } + List.AddLine(ImVec2(Low.x, middle - gauge), ImVec2(High.x, middle - gauge), IM_COL32(200, 200, 205, 255), 2.0f); + List.AddLine(ImVec2(Low.x, middle + gauge), ImVec2(High.x, middle + gauge), IM_COL32(200, 200, 205, 255), 2.0f); + auto const line{ImGui::GetTextLineHeight()}; + if (cycle < 4.0f) + { + // pressed beside the track, dragged along it + auto const press{at(0.32f, 0.67f)}; + auto const drag{ease((cycle - 1.0f) / 1.4f)}; + ImVec2 const cursor{cycle < 1.0f ? ImVec2(press.x + (1.0f - ease(cycle)) * width * 0.3f, press.y + (1.0f - ease(cycle)) * height * 0.2f) : ImVec2(press.x + width * 0.3f * drag, press.y)}; + if (cycle >= 1.0f) + { + ImVec2 const tip{cursor.x, press.y}; + List.AddLine(press, tip, IM_COL32(255, 210, 60, 255), 3.0f); + if (drag > 0.2f) + List.AddTriangleFilled(ImVec2(tip.x + 8.0f, tip.y), ImVec2(tip.x - 4.0f, tip.y - 7.0f), ImVec2(tip.x - 4.0f, tip.y + 7.0f), IM_COL32(255, 210, 60, 255)); + } + if (cycle >= 2.6f) + { + // the signal by the track: the mast and the head with its lights + auto const foot{at(0.32f, 0.98f)}; + List.AddLine(foot, ImVec2(foot.x, foot.y - height * 0.06f), IM_COL32(200, 200, 200, 255), 3.0f); + ImVec2 const head_low{foot.x - height * 0.04f, foot.y - height * 0.27f}; + ImVec2 const head_high{foot.x + height * 0.04f, foot.y - height * 0.06f}; + List.AddRectFilled(head_low, head_high, IM_COL32(25, 25, 25, 255), height * 0.03f); + List.AddRect(head_low, head_high, IM_COL32(150, 150, 150, 255), height * 0.03f); + std::array const lights{IM_COL32(230, 60, 50, 255), IM_COL32(70, 210, 90, 255), IM_COL32(240, 240, 240, 255)}; + for (std::size_t i = 0; i < lights.size(); ++i) + List.AddCircleFilled(ImVec2(foot.x, head_low.y + height * (0.04f + 0.065f * static_cast(i))), height * 0.025f, lights[i]); + List.AddText(ImVec2(foot.x - height * 0.06f - ImGui::CalcTextSize("S1").x, foot.y - line), IM_COL32(255, 255, 255, 230), "S1"); + } + gesture_mouse(List, ImVec2(cursor.x + 2.0f, cursor.y + 2.0f), std::round(height * 0.16f), "LMB"); + List.AddText(ImVec2(Low.x + 6.0f, Low.y + 4.0f), IM_COL32(230, 230, 230, 230), STR_C("LMB by the track, drag along: the way the trains run")); + return; + } + // the hectometre posts of the line, one after the other + auto const shown{static_cast((cycle - 4.3f) / 0.35f) + 1}; + for (int i = 0; i < std::min(shown, 9); ++i) + { + auto const x{at(0.07f + 0.105f * static_cast(i), 0.0f).x}; + auto const foot{middle - gauge * 3.2f}; + List.AddRectFilled(ImVec2(x - 3.0f, foot - height * 0.14f), ImVec2(x + 3.0f, foot), IM_COL32(240, 240, 240, 255), 1.0f); + auto const text{std::format("12.{}", i + 1)}; + auto const size{ImGui::CalcTextSize(text.c_str())}; + List.AddText(ImVec2(std::round(x - size.x * 0.5f), foot - height * 0.14f - size.y - 1.0f), IM_COL32(255, 220, 120, 255), text.c_str()); + } + List.AddText(ImVec2(Low.x + 6.0f, High.y - line - 4.0f), IM_COL32(230, 230, 230, 230), STR_C("B: posts every 100 m along the whole line at once")); +} + +// a vehicle seen from the side, drawn simply: the body with its windows on two bogies +void tutorial_vehicle(ImDrawList &List, ImVec2 const Low, ImVec2 const High, ImU32 const Body, bool const Locomotive) +{ + auto const width{High.x - Low.x}; + auto const height{High.y - Low.y}; + auto const wheel{height * 0.14f}; + ImVec2 const body_high{High.x, High.y - wheel * 1.6f}; + List.AddRectFilled(Low, body_high, Body, height * 0.12f); + auto const windows{Locomotive ? 2 : 5}; + for (int i = 0; i < windows; ++i) + { + // a locomotive has a window at each end, a coach a row of them + auto window_x{Low.x + width * (0.08f + 0.18f * static_cast(i))}; + if (Locomotive) + window_x = (i == 0 ? Low.x + width * 0.06f : High.x - width * 0.2f); + auto const size{Locomotive ? width * 0.14f : width * 0.12f}; + List.AddRectFilled(ImVec2(window_x, Low.y + height * 0.15f), ImVec2(window_x + size, Low.y + height * 0.42f), IM_COL32(30, 40, 50, 255), 2.0f); + } + for (float const share : {0.22f, 0.78f}) + { + ImVec2 const middle{Low.x + width * share, High.y - wheel}; + List.AddCircleFilled(ImVec2(middle.x - wheel * 1.1f, middle.y), wheel, IM_COL32(40, 40, 40, 255)); + List.AddCircleFilled(ImVec2(middle.x + wheel * 1.1f, middle.y), wheel, IM_COL32(40, 40, 40, 255)); + } +} + +// the trainset tool: a double click on the list puts a vehicle into the train, the train grows on the track, Place and drive +// and it runs off +void tutorial_trainset_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const High, double const Time) +{ + auto const width{High.x - Low.x}; + auto const height{High.y - Low.y}; + auto const at = [&](float const X, float const Y) { return ImVec2(Low.x + width * X, Low.y + height * Y); }; + auto const cycle{static_cast(std::fmod(Time, 9.0))}; + std::array const colours{IM_COL32(200, 60, 50, 255), IM_COL32(60, 120, 70, 255), IM_COL32(70, 100, 160, 255)}; + auto const line{ImGui::GetTextLineHeight()}; + // the list: the side view of each vehicle and its name + for (std::size_t i = 0; i < colours.size(); ++i) + { + auto const slot{static_cast(i)}; + auto const top{0.08f + 0.28f * slot}; + // lit while it's double clicked + if (cycle > 0.8f + 1.4f * slot && cycle < 1.2f + 1.4f * slot) + List.AddRectFilled(at(0.02f, top - 0.02f), at(0.40f, top + 0.24f), IM_COL32(90, 175, 255, 70), 3.0f); + tutorial_vehicle(List, at(0.03f, top), at(0.16f, top + 0.2f), colours[i], i == 0); + List.AddRectFilled(at(0.19f, top + 0.03f), at(0.36f, top + 0.03f + line / height * 0.6f), IM_COL32(220, 220, 220, 200), 2.0f); + List.AddRectFilled(at(0.19f, top + 0.12f), at(0.31f, top + 0.12f + line / height * 0.5f), IM_COL32(150, 150, 150, 160), 2.0f); + } + // the cursor goes down the list double clicking, then to the button + auto const row{std::min(2, static_cast(std::max(0.0f, cycle - 0.4f) / 1.4f))}; + ImVec2 cursor{at(0.30f, 0.16f + 0.28f * static_cast(row))}; + auto const added{std::clamp(static_cast((cycle - 0.8f) / 1.4f) + 1, 0, 3)}; + auto const button_low{at(0.55f, 0.08f)}; + auto const button_high{at(0.95f, 0.30f)}; + if (cycle > 4.6f) + cursor = ImVec2((button_low.x + button_high.x) * 0.5f, (button_low.y + button_high.y) * 0.5f); + bool const pressed{cycle > 5.2f && cycle < 5.6f}; + List.AddRectFilled(button_low, button_high, pressed ? IM_COL32(60, 170, 75, 255) : IM_COL32(50, 140, 64, 255), 4.0f); + auto const label{STR_C("Place and drive")}; + auto const size{ImGui::CalcTextSize(label)}; + List.AddText(ImVec2(std::round((button_low.x + button_high.x - size.x) * 0.5f), std::round((button_low.y + button_high.y - size.y) * 0.5f)), IM_COL32(255, 255, 255, 255), label); + // the track and the train on it, the head on the left; after the button it runs off + auto const rail{at(0.0f, 0.86f).y}; + List.AddLine(ImVec2(at(0.44f, 0.0f).x, rail), ImVec2(High.x, rail), IM_COL32(170, 170, 170, 255), 2.0f); + auto const run{cycle > 5.6f ? (cycle - 5.6f) * (cycle - 5.6f) * width * 0.06f : 0.0f}; + auto const car{width * 0.15f}; + List.PushClipRect(ImVec2(at(0.44f, 0.0f).x, Low.y), High, true); + for (std::size_t i = 0; i < static_cast(added); ++i) + { + auto const front{at(0.46f, 0.0f).x + (car + 3.0f) * static_cast(i) - run}; + tutorial_vehicle(List, ImVec2(front, rail - height * 0.24f), ImVec2(front + car, rail), colours[i], i == 0); + } + List.PopClipRect(); + gesture_mouse(List, ImVec2(cursor.x + 2.0f, cursor.y + 2.0f), std::round(height * 0.16f), "LMB"); + if (cycle < 4.6f) + List.AddText(ImVec2(cursor.x + height * 0.16f, cursor.y), IM_COL32(255, 220, 120, 255), "x2"); +} + +// the terrain model under the tracks: the track laid level sinks onto the ground along, the formation and the slopes under it +void tutorial_terrain_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const High, double const Time) +{ + auto const width{High.x - Low.x}; + auto const height{High.y - Low.y}; + auto const phase{static_cast(std::fmod(Time * 0.3, 1.4))}; + auto const settle{std::clamp(phase / 0.8f, 0.0f, 1.0f)}; + auto const eased{settle * settle * (3.0f - 2.0f * settle)}; + auto const ground_at = [&](float const Share) { return 0.45f + 0.22f * std::sin(Share * 4.0f) + 0.08f * std::sin(Share * 13.0f); }; + auto const smooth_at = [&](float const Share) { return 0.45f + 0.18f * std::sin(Share * 4.0f); }; + auto const x_of = [&](float const Share) { return Low.x + width * Share; }; + auto const y_of = [&](float const Level) { return Low.y + height * (0.95f - 0.75f * Level); }; + int constexpr steps{80}; + std::vector ground; + std::vector track; + for (int i = 0; i <= steps; ++i) + { + auto const share{static_cast(i) / steps}; + ground.emplace_back(x_of(share), y_of(ground_at(share))); + track.emplace_back(x_of(share), y_of(0.55f + (smooth_at(share) + 0.04f - 0.55f) * eased)); + } + auto const flags{List.Flags}; + List.Flags &= ~ImDrawListFlags_AntiAliasedFill; + for (int i = 0; i < steps; ++i) + { + std::array const quad{ground[i], ground[i + 1], ImVec2(ground[i + 1].x, High.y), ImVec2(ground[i].x, High.y)}; + List.AddConvexPolyFilled(quad.data(), static_cast(quad.size()), IM_COL32(95, 120, 70, 120)); + } + if (eased > 0.99f) + for (int i = 0; i < steps; ++i) + { + auto const fill{track[i].y < ground[i].y}; + List.AddQuadFilled(track[i], track[i + 1], ground[i + 1], ground[i], fill ? IM_COL32(190, 150, 90, 150) : IM_COL32(60, 45, 30, 150)); + } + List.Flags = flags; + List.AddPolyline(ground.data(), static_cast(ground.size()), IM_COL32(150, 190, 110, 255), 0, 1.5f); + List.AddPolyline(track.data(), static_cast(track.size()), IM_COL32(230, 230, 230, 255), 0, 3.0f); + auto const label{eased > 0.99f ? STR_C("embankment and cutting") : STR_C("the terrain model")}; + List.AddText(ImVec2(Low.x + 6.0f, Low.y + 4.0f), IM_COL32(220, 220, 220, 200), label); +} + +} // namespace + +// a lesson of the tutorial: its clip or sketch, the mouse and the keys it teaches, the steps to try and the button under it +struct editor_mode::tutorial_lesson +{ + // what the button under a lesson does: opens the tool the lesson is about, or switches the view + enum class trial { reading, top, lay, turnout, select, profile, terrain, plan, trainset, signals, station }; + struct input + { + char const *keys; + char const *text; + }; + struct goal + { + first_step step; + char const *text; + }; + char const *title; + char const *clip; + std::vector inputs; + std::vector goals; + trial action; + void (*sketch)(ImDrawList &, ImVec2, ImVec2, double){nullptr}; +}; + +std::vector const &editor_mode::tutorial_lessons() +{ + using trial = tutorial_lesson::trial; + static std::vector const lessons{ + {"Looking around", + "camera", + {{"RMB + move", "Hold the right mouse button and move the mouse to look around"}, + {"RMB + W S A D", "Keep holding the right button and press W S A D to fly around; E takes you up, Q down"}, + {"O", "Switches between the view from above, like a map, and the normal 3D view"}, + {"wheel", "Zooms in and out at the mouse pointer"}, + {"MMB + move", "Press the wheel down and drag to move the view, from above and in 3D"}, + {"Y", "Rides the camera along the track under the mouse pointer, as from a train; Y again gets off. The tools keep working on the way"}, + {"RMB + W S A D", "While riding: W and S drive, Shift faster; A and D jump to the next track on the left or right; Z picks the way at the next switch"}, + {"F", "Flies to what you have selected"}}, + {{first_step::look, "Look around with the right mouse button held"}, {first_step::top, "Press O: from above to 3D, or back"}, {first_step::ride, "Ride along a track with Y"}}, + trial::top}, + {"Laying track", + "lay", + {{"F3", "Opens Tracks, the part of the editor where track is laid"}, + {"L", "Turns laying on"}, + {"LMB", "Click the ground where the track should start, or the end of a track to carry it on"}, + {"LMB", "Click again wherever the track should turn; the curves are made for you. Until you press Enter it is only a line, not a track"}, + {"Enter", "Lays the track along the line. To carry on, click its end"}, + {"Backspace", "Removes the last point you clicked"}, + {"Esc", "Throws away the points not laid yet, but only when pressed twice within 3 seconds: the first press just warns. With no points left, Esc stops laying"}}, + {{first_step::tracks, "Open Tracks (F3)"}, {first_step::lay, "Turn laying on (L)"}, {first_step::laid, "Click a few points and press Enter"}}, + trial::lay}, + {"Curves", + "curves", + {{"LMB", "Every place where the line turns gets a curve, as big as fits. An orange label means the curve breaks the rules for the speed set in the panel"}, + {"Tab", "To copy a curve from the aerial photo: press Tab, then click points along the middle of the curve; it ends at the last one"}, + {"Alt", "Hold it while clicking: the direction jumps in steps of 15 degrees, or to the angle of a switch to a straight track nearby"}, + {"0 1 2 3", "After the first point: type a number and press Enter, and the next straight piece is that many metres long"}, + {"wheel", "The wheel alone zooms, as everywhere"}}, + {{first_step::bend, "Lay a track that turns"}, {first_step::trace, "Press Tab to copy a curve from the photo"}}, + trial::lay}, + {"Radius of the curves at the bends", + nullptr, + {{"LMB", "Where the line turns, two straight pieces meet at a corner no train could take, so the editor rounds it off with a curve"}, + {"R", "The radius tells how big the curve is, in metres: the bigger it is, the gentler the curve and the faster a train can go round it"}, + {"R", "The editor picks the biggest curve that fits between your points. A slight turn gets only a gentle easing in and out; a sharper one gets a real curve, eased in and out, with the outer rail raised, as the railway rules say"}, + {"LMB", "Points too close together leave little room, so the curve comes out smaller. When it no longer meets the rules, its label turns orange: click the points further apart"}, + {"R L h", "The label of a curve: R is the radius, L the length of the easing into it, h how much higher the outer rail is, in millimetres. A slight turn with no real curve reads 2xL"}}, + {{first_step::bend, "Lay a track that turns and read the label of its curve"}}, + trial::lay, + tutorial_corner_sketch}, + {"Correcting a curve", + "plan", + {{"G", "Turns Plan on. Click a curve to see how it is built; its corner point and its size can be dragged in the view"}, + {"LMB + move", "The strip in the panel shows how much the track turns along the way. Drag a flat part of it up or down to change how sharp that curve is"}, + {"LMB + move", "Drag a sloping part sideways: the easing into the curve gets longer or shorter"}, + {"wheel", "Over the strip, the wheel changes it in small steps"}, + {"LMB", "Apply to the scenery: the tracks are laid again as the plan shows"}}, + {{first_step::plan, "Open the plan of a curve"}, {first_step::plan_band, "Change the curve on the strip"}, {first_step::plan_apply, "Apply the change"}}, + trial::plan}, + {"Joining tracks", + "join", + {{"LMB + move", "Press on the loose end of a track (a pink ring while laying) and drag: a new track comes out of it"}, + {"LMB", "Let go on another loose end: a curve joins the two tracks"}, + {"LMB", "While laying, a click on a loose end joins your track to it exactly, with no gap"}, + {"Ctrl + wheel", "Over the other end: makes the joining curve bigger or smaller"}, + {"Shift + wheel", "Over the other end: tries another way of joining"}}, + {{first_step::join, "Join two loose ends"}, {first_step::wheel, "Change the size of the joining curve with Ctrl+wheel"}}, + trial::lay}, + {"Switches", + "switch", + {{"T", "Turns Switch on. The tiles at the top choose what you put in: a switch, a slip switch or a crossing"}, + {"LMB", "Click the track the switch should go into"}, + {"LMB + move", "Press on it and drag: along the track sets which way the switch points, sideways which side it branches off to; let go to lay it"}, + {"LMB + move", "Drag from a straight track onto the track beside it: two switches joining them (a crossover). Over a crossover going the other way you get a double or a scissors one"}, + {"LMB + move", "Drag from a straight across several tracks running alongside and let go on the farthest: a row of switches leading onto each of them (a switch ladder)"}, + {"Esc", "Back to selecting"}}, + {{first_step::turnout, "Put a switch into a track"}}, + trial::turnout}, + {"Switch templates", + nullptr, + {{"T", "In Switch, the Template editor... button: ready switch shapes and your own. Point at a number to see on the drawing what it means"}, + {"LMB", "To copy a switch from the aerial photo: Click off the view..., then click where the switch starts, the end of its straight track, the end of its branching track and one point further along that branch"}, + {"LMB", "Then at least 3 points along the branching track: its shape and size follow them"}, + {"Backspace", "Removes the last point; Esc stops clicking"}, + {"O", "The view from above; the aerial photo is turned on in the Layers panel"}, + {"LMB", "Make the template: the new switch lies on the photo where it was clicked and changes as its numbers change"}}, + {{first_step::template_open, "Open the template editor"}, {first_step::template_clicked, "Make a template by clicking in the view"}}, + trial::turnout, + tutorial_template_sketch}, + {"Signals and posts", + nullptr, + {{"I", "Turns Signals on. Click a kind of signal in its list; it shows the signals this scenery has"}, + {"LMB", "Click beside a track: the signal stands on that side"}, + {"LMB + move", "Press beside the track and drag along it: the signal faces the trains going the way you dragged"}, + {"LMB + move", "Drag a signal that already stands: it slides along its track"}, + {"X", "Turns Kilometrage on. Click a track where you know the km, by a post or a station: the posts every 100 m and the block signals are numbered after it"}, + {"B", "Things beside the track: posts every 100 m along a whole line at once, the W17 signs by the switches (how far a wagon may stand) and trains. The posts take their numbers from the km set with X, or from the km you type in their panel for the place you clicked"}}, + {{first_step::signal, "Put up a signal"}, {first_step::posts, "Put up the posts along a line"}}, + trial::signals, + tutorial_signal_sketch}, + {"A whole line, step by step", + nullptr, + {{"1", "Lay the tracks of the line (L), and the switches (T) where the stations are"}, + {"2", "Kilometrage (X): click a track where you know the km, by a post or at a station. One point is enough: the posts, the stations and the block signals count from it"}, + {"3", "Station (under More): click a switch of the station, then give its name, its code and the number of the line"}, + {"4", "Station signals (under More): Set the signals puts up the entry, exit and shunting signals of the whole station at once"}, + {"5", "Line block (under More): the block signals on the line out of each station, once the stations are set"}, + {"6", "Posts (B): click the line, then Place the posts, every 100 m along all of it"}, + {"7", "Save with Ctrl+S, put a train on the track and drive: the last lesson"}}, + {}, + trial::station}, + {"Selecting and fixing", + "edit", + {{"Esc", "Turns selecting on"}, + {"LMB", "Click a track to select it; its ends show"}, + {"LMB + move", "Drag an end: where tracks meet, the ones beside follow; a loose end pulls out a new track, or with Ctrl moves by itself"}, + {"RMB", "Click a track: a menu of what can be done with it"}, + {"Del", "Deletes what is selected"}, + {"Ctrl + Z", "Undoes the last change; Ctrl+Y brings it back"}, + {"Q W E", "Handles on the track to move, turn, lengthen or bend it: the next lesson"}}, + {{first_step::select, "Select a track"}, {first_step::undo, "Undo a change"}}, + trial::select}, + {"Editing with the gizmo", + "gizmo", + {{"Q", "Shows arrows on the selected track: drag one to move the track"}, + {"W", "Shows rings: drag one to turn the track, to tilt it up or down, or to raise one rail; the tracks joined to it follow"}, + {"E", "Shows handles that make the track longer at its loose end; a curve stays as sharp as it was"}, + {"LMB + move", "With the handles out there are also points that bend the track: drag one and the track bends after it"}, + {"LMB", "Click a point of the track to put the handles there: Q then moves that point only, W turns the whole track around it"}, + {"Ctrl", "Hold it while dragging to move in even steps"}, + {"Esc", "Lets go of the point; the arrow button above the view hides the handles again"}}, + {{first_step::gizmo, "Show the handles with Q, W or E"}, {first_step::vector, "Bend a track by one of its points, or move it with the handles"}}, + trial::select}, + {"The grade line", + nullptr, + {{"P", "Turns Profile on. Click a track: below the view you see how its whole line goes up and down"}, + {"Shift + LMB", "A click adds another track; a box drawn from empty ground takes the tracks inside it. The route runs between the outermost of them, through the switches"}, + {"LMB + move", "Drag a point of the line: the slopes on both sides of it change with it"}, + {"LMB LMB", "Double-click the line to add a point"}, + {"Del", "Removes the chosen point"}, + {"LMB", "Tracks running side by side share one line: change it, press Apply to the scenery, and the tracks beside it (blue) change too"}, + {"LMB", "To give the route open in Profile a line of its own, press Take off the common grade line"}, + {"Ctrl + wheel", "Over the chart: stretches it up and down, so the slopes are easier to see"}, + {"RMB + move", "Over the chart: moves along the line"}}, + {{first_step::profile, "Open the profile of a track"}, {first_step::profile_point, "Move or add a point"}, {first_step::profile_apply, "Apply it: the tracks take the new heights"}}, + trial::profile, + tutorial_route_sketch}, + {"Terrain from the terrain model", + nullptr, + {{"L", "In a new, empty scenery the first L asks whether you want the real ground of the place or a flat plane"}, + {"F5", "Opens Terrain; the real ground (the terrain model) is in its panel"}, + {"LMB", "Step 1, Location: show where the scenery is, with a click on the map or by typing the place"}, + {"LMB", "Step 2, before there are tracks: Load around the camera brings the ground of that spot from geoportal.gov.pl"}, + {"LMB", "Step 2, once there are tracks: Tracks onto the terrain puts the tracks not fitted yet onto the real ground; Terrain under the tracks brings the ground up or down to them; The terrain of the model only loads the ground along them and leaves the tracks alone"}, + {"F3", "The terrain to some of the tracks only: select them (F3), Terrain in the inspector"}, + {"LMB", "A new track partly under the ground: the message above the view has Fit the ground to the track; one click builds the bank or the cutting along it"}, + {"", "A line you shaped by hand in Profile stays as it is, even when all the tracks are fitted anew, unless you tick that the ones edited by hand go too"}, + {"", "Tracks close side by side (under 5.1 m apart) get one common line of heights; a track crossing others where the ground is low on both sides goes under them"}, + {"Ctrl + Z", "Takes the changes back"}}, + {{first_step::terrain, "Open Terrain (F5)"}, {first_step::nmt, "Load the real ground"}}, + trial::terrain, + tutorial_terrain_sketch}, + {"Sceneries made before", + nullptr, + {{"LMB", "Some tracks can't be changed, for example ones put in from a ready .inc file or lying on a locked layer: the Inspector says why"}, + {"T", "Switches laid earlier keep their shape; a template picked for one in the Inspector gives it the ready shape"}, + {"P", "Heights saved by an older editor are read as they were saved"}, + {"Ctrl + S", "Saving writes only what was changed; the rest of the files stays as it was"}}, + {}, + trial::reading}, + {"Saving and driving", + nullptr, + {{"Ctrl + S", "Saves the scenery"}, + {"LMB", "The trainset tool (the button below): click the track where the train should stand"}, + {"LMB LMB", "Double-click a vehicle in the list to add it to the train; click a vehicle in the train to move it, turn it round or take it out"}, + {"LMB", "Place and drive: the train stands on the track and you sit in the cab"}}, + {{first_step::save, "Save the scenery"}, {first_step::drive, "Drive on the new track"}}, + trial::trainset, + tutorial_trainset_sketch}, + }; + return lessons; +} + +bool editor_mode::tutorial_done(tutorial_lesson const &Lesson) const +{ + return false == Lesson.goals.empty() && std::ranges::all_of(Lesson.goals, [this](tutorial_lesson::goal const &Goal) { return m_first_steps_done[static_cast(Goal.step)]; }); +} + +void editor_mode::note_first_steps() +{ + if (ui()->mode() == nodebank_panel::TRACK) + first_step_done(first_step::tracks); + if (m_lay.active) + first_step_done(first_step::lay); + if (ui()->mode() == nodebank_panel::TRACK && m_track_tab == track_tab::path && selected_track() != nullptr) + first_step_done(first_step::select); + if (current_work_area() == work_area::terrain) + first_step_done(first_step::terrain); + if (ui()->mode() == nodebank_panel::TRACK && m_track_tab == track_tab::route && false == m_route.chain.tracks.empty()) + first_step_done(first_step::plan); + if (ui()->mode() == nodebank_panel::TRACK && m_track_gizmo_on) + first_step_done(first_step::gizmo); + if (m_track_gizmo_using || (m_point_drag.moved && m_track_point.valid() && false == editor_track::is_end(m_track_point.kind))) + first_step_done(first_step::vector); + if (m_ride.active()) + first_step_done(first_step::ride); +} + +char const *editor_mode::tutorial_of_tool() +{ + auto const &lessons{tutorial_lessons()}; + // the first of the lessons named whose steps aren't all reached yet + auto const undone = [&](std::initializer_list const Titles) { + for (auto const *title : Titles) + if (auto const found{std::ranges::find_if(lessons, [title](tutorial_lesson const &Lesson) { return std::string_view{title} == Lesson.title; })}; + found != lessons.end() && false == tutorial_done(*found)) + return title; + return ""; + }; + if (m_lay.active) + return undone({"Laying track", "Radius of the curves at the bends", "Curves", "Joining tracks"}); + if (current_work_area() == work_area::terrain) + return undone({"Terrain from the terrain model"}); + if (ui()->mode() != nodebank_panel::TRACK) + return ""; + switch (m_track_tab) + { + case track_tab::turnout: + return undone({m_switch_designer.open ? "Switch templates" : "Switches"}); + case track_tab::profile: + return undone({"The grade line"}); + case track_tab::route: + case track_tab::straights: + return undone({"Correcting a curve"}); + case track_tab::signals: + case track_tab::kilometrage: + return undone({"Signals and posts"}); + case track_tab::station: + case track_tab::station_signals: + case track_tab::line_block: + return undone({"A whole line, step by step"}); + default: + return ""; + } +} + +void editor_mode::follow_tutorial() +{ + auto const &lessons{tutorial_lessons()}; + auto const open_lesson = [&](std::string_view const Title) { + if (auto const found{std::ranges::find_if(lessons, [Title](tutorial_lesson const &Lesson) { return Title == Lesson.title; })}; found != lessons.end()) + m_tutorial_page = static_cast(found - lessons.begin()); + }; + // the lesson of what's being done now, the next one once its steps are reached; opened when that changes, so a page turned by + // hand stays + if (auto const *followed{tutorial_of_tool()}; m_tutorial_followed != followed) + { + m_tutorial_followed = followed; + open_lesson(followed); + } + if (m_tutorial_goto != nullptr) + { + open_lesson(m_tutorial_goto); + m_tutorial_goto = nullptr; + } + m_tutorial_page = std::clamp(m_tutorial_page, 0, static_cast(lessons.size()) - 1); + auto const &lesson{lessons[m_tutorial_page]}; + if (lesson.clip == nullptr) + m_tutorial_clip.close(); + else if (auto const path{std::string{"lang/editor_tutorial/"} + lesson.clip + ".gif"}; path != m_tutorial_clip.path()) + { + m_tutorial_clip.open(path); + m_tutorial_since = ImGui::GetTime(); + } +} + +void editor_mode::render_first_steps() +{ + if (false == m_first_steps_open) + { + if (false == m_tutorial_clip.path().empty()) + m_tutorial_clip.close(); + return; + } + note_first_steps(); + follow_tutorial(); + auto const &lessons{tutorial_lessons()}; + auto const &lesson{lessons[m_tutorial_page]}; + auto const scale{Global.ui_scale}; + ImGui::SetNextWindowPos(ImVec2(ImGui::GetIO().DisplaySize.x * 0.5f, ImGui::GetIO().DisplaySize.y * 0.5f), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f)); + ImGui::SetNextWindowBgAlpha(1.0f); + ImGui::SetNextWindowSizeConstraints(ImVec2(0.0f, 0.0f), ImVec2(FLT_MAX, ImGui::GetIO().DisplaySize.y - 60.0f)); + keep_on_screen("###tutorial"); + if (ImGui::Begin((std::string(STR_C("Tutorial")) + "###tutorial").c_str(), &m_first_steps_open, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_AlwaysAutoResize)) + { + // floating it's as wide as the clips; docked it takes the width of its dock, the texts wrapped to it + auto const width{ImGui::IsWindowDocked() ? std::max(160.0f * scale, ImGui::GetContentRegionAvail().x) : 520.0f * scale}; + ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + width); + ImGui::TextDisabled(STR_C("Lesson %d of %d"), m_tutorial_page + 1, static_cast(lessons.size())); + ImGui::SameLine(); + ImGui::TextColored(ImVec4(0.55f, 0.8f, 1.0f, 1.0f), "%s", STR_C(lesson.title)); + render_tutorial_media(lesson, width); + render_tutorial_goals(lesson); + render_tutorial_trial(lesson); + ImGui::PopTextWrapPos(); + ImGui::Separator(); + render_tutorial_pages(); + } + ImGui::End(); +} + +void editor_mode::render_tutorial_media(tutorial_lesson const &Lesson, float const Width) +{ + if (Lesson.clip != nullptr && false == m_tutorial_clip.missing()) + { + // the room of a clip still loading, as the clips are recorded: 520 x 325 + auto const height{Width * 325.0f / 520.0f}; + if (auto const texture{m_tutorial_clip.texture(ImGui::GetTime() - m_tutorial_since)}; texture != 0) + { + auto const shown{Width * static_cast(m_tutorial_clip.height()) / static_cast(std::max(1, m_tutorial_clip.width()))}; + ImGui::Image(static_cast(texture), ImVec2(Width, shown)); + if (ImGui::IsItemClicked()) + m_tutorial_since = ImGui::GetTime(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Click: play it from the start")); + } + else + { + auto const at{ImGui::GetCursorScreenPos()}; + ImGui::GetWindowDrawList()->AddRectFilled(at, ImVec2(at.x + Width, at.y + height), ImGui::GetColorU32(ImGuiCol_FrameBg)); + ImGui::Dummy(ImVec2(Width, height)); + } + } + if (Lesson.sketch != nullptr) + { + auto const at{ImGui::GetCursorScreenPos()}; + ImVec2 const end{at.x + Width, at.y + std::round(Width * 0.36f)}; + auto *list{ImGui::GetWindowDrawList()}; + list->AddRectFilled(at, end, ImGui::GetColorU32(ImGuiCol_FrameBg), 4.0f); + list->PushClipRect(at, end, true); + Lesson.sketch(*list, at, end, ImGui::GetTime()); + list->PopClipRect(); + ImGui::Dummy(ImVec2(Width, end.y - at.y)); + } +} + +void editor_mode::render_tutorial_goals(tutorial_lesson const &Lesson) +{ + ImGui::SeparatorText(STR_C("Mouse and keys")); + for (auto const &entry : Lesson.inputs) + tutorial_input(entry.keys, entry.text, 150.0f * Global.ui_scale); + if (false == Lesson.goals.empty()) + ImGui::SeparatorText(STR_C("Try it")); + for (auto const &entry : Lesson.goals) + { + bool const reached{m_first_steps_done[static_cast(entry.step)]}; + ImGui::TextColored(reached ? ImVec4(0.4f, 0.9f, 0.4f, 1.0f) : ImGui::GetStyleColorVec4(ImGuiCol_Text), "%s", reached ? "[x]" : "[ ]"); + ImGui::SameLine(); + if (reached) + ImGui::TextDisabled("%s", STR_C(entry.text)); + else + ImGui::TextWrapped("%s", STR_C(entry.text)); + } + if (Lesson.action == tutorial_lesson::trial::lay && ui()->mode() == nodebank_panel::TRACK && false == GfxRenderer->Mouse_Hit()) + ImGui::TextColored(ImVec4(1.0f, 0.7f, 0.2f, 1.0f), "%s", STR_C("There is no ground under the mouse: the track will lie flat at height 0. Real ground: F5")); +} + +void editor_mode::render_tutorial_trial(tutorial_lesson const &Lesson) +{ + using trial = tutorial_lesson::trial; + if (Lesson.action == trial::top) + { + if (ImGui::Button(Global.EditorOrtho ? STR_C("3D view (O)") : STR_C("Top view, orthographic (O)"))) + toggle_ortho(); + return; + } + if (Lesson.action == trial::terrain) + { + ImGui::BeginDisabled(current_work_area() == work_area::terrain); + if (ImGui::Button(STR_C("Terrain (F5)"))) + choose_work_area(work_area::terrain); + ImGui::EndDisabled(); + return; + } + // a tool of Tracks: the tab its button opens, and the one beside it which counts as that tool open as well + struct tool_button + { + char const *label; + track_tab tab; + track_tab also; + }; + tool_button button{}; + switch (Lesson.action) + { + case trial::lay: + button = {STR_C("Lay track (L)"), track_tab::lay, track_tab::lay}; + break; + case trial::turnout: + button = {STR_C("The switch tool (T)"), track_tab::turnout, track_tab::turnout}; + break; + case trial::select: + button = {STR_C("The select tool (Esc)"), track_tab::path, track_tab::path}; + break; + case trial::profile: + button = {STR_C("The profile tool (P)"), track_tab::profile, track_tab::profile}; + break; + case trial::signals: + button = {STR_C("The signals tool (I)"), track_tab::signals, track_tab::signals}; + break; + case trial::station: + button = {STR_C("The station tool"), track_tab::station, track_tab::station_signals}; + break; + case trial::plan: + button = {STR_C("The plan tool (G)"), track_tab::straights, track_tab::route}; + break; + case trial::trainset: + button = {STR_C("The trainset tool"), track_tab::lineside, track_tab::lineside}; + break; + default: + return; + } + // the trainset tool is open only with its part of the tab expanded + auto const in_use{ui()->mode() == nodebank_panel::TRACK && (m_track_tab == button.tab || m_track_tab == button.also) && (Lesson.action != trial::trainset || m_vehicle.tab().open)}; + ImGui::BeginDisabled(in_use); + if (ImGui::Button(button.label)) + { + choose_work_area(work_area::tracks); + show_track_tab(button.tab); + if (Lesson.action == trial::trainset) + m_vehicle.tab().expand = true; + } + ImGui::EndDisabled(); +} + +void editor_mode::render_tutorial_pages() +{ + auto const &lessons{tutorial_lessons()}; + auto const count{static_cast(lessons.size())}; + ImGui::BeginDisabled(m_tutorial_page == 0); + if (ImGui::Button(STR_C("< Back"))) + --m_tutorial_page; + ImGui::EndDisabled(); + ImGui::SameLine(); + auto const dot{ImGui::GetFrameHeight()}; + for (int index = 0; index < count; ++index) + { + ImGui::PushID(index); + auto const at{ImGui::GetCursorScreenPos()}; + if (ImGui::InvisibleButton("##lesson", ImVec2(dot * 0.8f, dot))) + m_tutorial_page = index; + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C(lessons[index].title)); + ImVec2 const centre{at.x + dot * 0.4f, at.y + dot * 0.5f}; + auto const colour{tutorial_done(lessons[index]) ? IM_COL32(100, 230, 100, 255) : ImGui::GetColorU32(ImGuiCol_TextDisabled)}; + if (index == m_tutorial_page) + ImGui::GetWindowDrawList()->AddCircle(centre, dot * 0.3f, kGestureLit, 0, 2.0f); + ImGui::GetWindowDrawList()->AddCircleFilled(centre, dot * 0.17f, colour); + ImGui::PopID(); + ImGui::SameLine(0.0f, 0.0f); + } + ImGui::SameLine(); + if (m_tutorial_page + 1 < count) + { + if (ImGui::Button(STR_C("Next >"))) + ++m_tutorial_page; + } + else if (ImGui::Button(STR_C("Close"))) + m_first_steps_open = false; + bool show{EditorSettings.first_steps()}; + if (ImGui::Checkbox(STR_C("Show when the editor opens"), &show)) + { + EditorSettings.first_steps(show); + EditorSettings.save(); + } +} + void editor_mode::render_shortcuts_window() { if (false == m_shortcuts_open) @@ -4581,7 +6216,7 @@ void editor_mode::render_shortcuts_window() {"PrtScr", "Screenshot"}, {"Ctrl+Shift+F11", "Export scenery dump"}, {"F11", "Leave the editor"}, - {"F10", "Quit"}}}, + {"F10", "Quit the simulator"}}}, {"Fields of work", {{"F2", "Surroundings"}, {"F3", "Tracks"}, {"F4", "Roads"}, {"F5", "Terrain"}}}, {"Camera", {{"RMB held, mouse", "Look around"}, @@ -4589,8 +6224,18 @@ void editor_mode::render_shortcuts_window() {"RMB held, E / Q", "Fly up / down (Page Up / Page Down in the legacy scheme)"}, {"F", "Fly to the selected"}, {"O", "Top view, orthographic"}}}, + {"Ride along the track", + {{"Y", "Ride along the track under the cursor, the tools working on; Y again leaves"}, + {"RMB held, W / S", "Drive; Shift faster, Ctrl+W / Ctrl+Down much faster"}, + {"RMB held, A / D", "Next track on the left / right"}, + {"Z", "The way at the next switch (it isn't thrown)"}, + {"RMB held, E / Q; wheel", "Higher / lower"}, + {"Ctrl+M", "Minimap, stations by their W4"}}}, {"Gizmo", - {{"Q / W / E", "Translate / rotate / scale"}, {"R", "Local space"}, {"Ctrl held while dragging", "Snap to the step set in the gizmo settings"}}}, + {{"Q / W / E", "Translate / rotate / scale; in the tracks they bring the hidden gizmo out"}, + {"R", "Local space"}, + {"Ctrl held while dragging", "Snap to the step set in the gizmo settings"}, + {"Tool options, Gizmo, Off", "Hides the gizmo, so nothing moves by chance; in the tracks it is hidden until Q, W or E"}}}, {"Surroundings", {{"1 2 3 4 5", "Select, insert, brush, area fill, copy to bank"}, {"LMB", "Select a model, or place one in the insert and brush modes"}, @@ -4605,15 +6250,47 @@ void editor_mode::render_shortcuts_window() {"Tracks", {{"Esc", "Select tool; cancels what's going on first"}, {"L / T / U", "Lay track / switch / turntable"}, - {"G / C", "Straight / curve"}, - {"H / B", "Signals / objects along the track"}, - {"P / V / J / I", "Profile / speed / joints / infrastructure"}, + {"H", "Throw the selected switch over to its other path, in the editor only"}, + {"G (C)", "Plan: a straight, its ends and the middle; a curve, its vertex and radius"}, + {"I / X / B", "Signals / kilometrage / posts along the track"}, + {"P / V / J", "Profile / speed / joints"}, {"Ctrl+F", "Find a track by its name"}, {"Shift+LMB", "Add a track to the selection, drag: a box"}, {"RMB on a track", "What can be done with it"}, - {"K", "Split the selected track at the cursor"}, - {"Enter / Backspace", "Laying track: finish / take the last point back"}, + {"K", "Split the selected track at the cursor, a break of the grade at the height of the ground"}, + {"L, LMB, LMB...", "Lay track: each click a bend of the straights, eased with a large curve; Enter lays them; a click on a free end goes on from it"}, + {"Tab while laying", "The points clicked next go along the middle of a curve seen on the photo, which ends at the last one; Tab again: back to the bends"}, + {"Drag from a free end", "Lead a track out of it: a straight, an arc and a straight where a curve is traced (Tab); onto another free end: join the two"}, + {"Ctrl+wheel", "Dragging from a free end: radius"}, + {"Shift+wheel", "Dragging over another free end: another way to join"}, + {"0-9 while laying", "Type the length of the next straight, Enter puts the point"}, + {"Alt held while laying", "The direction in steps of 15 degrees, or 1:9, 1:6.6... to a straight track; the first click with Alt goes onto the axis of the track"}, + {"N", "Parallel track: LMB on a track, then the side and the spacing"}, + {"Shift+LMB on a track in L", "The Parallel tool (N) with it"}, + {"Enter / Backspace", "Laying track: lay the points clicked / take back the last point"}, + {"Esc twice while laying", "Drop the points clicked and not laid yet"}, {"Del", "Delete the selected tracks"}}}, + {"Plan of a curve", + {{"G, LMB on a curve", "Its design: the vertex and the radius to drag in the view, the curvature in the panel"}, + {"Drag a plateau of the curvature band", "The radius of that arc"}, + {"Drag a ramp sideways", "The length of the transition curve"}, + {"Wheel over the band", "The radius by 5%, a transition by 5 m"}, + {"Apply to the scenery", "Lay the paths by the design; Ctrl+Z takes it back"}}}, + {"Trainset", + {{"B, Trainset, LMB on a track", "Where the train stands"}, + {"LMB LMB on the list", "Adds the vehicle to the train"}, + {"LMB on a vehicle of the train", "Moves it, turns it around or takes it out"}, + {"Place and drive", "Puts the train on the track and gives the cab at once"}}}, + {"Vertical profile", + {{"P, LMB on a track", "The grade line of its whole line, in the strip under the view"}, + {"Shift+LMB box", "The route between the outermost of the tracks, through the switches"}, + {"LMB + move on a point", "Change the grade before and after it"}, + {"LMB LMB on the line", "Add a point"}, + {"Del", "Remove the chosen point"}, + {"Wheel", "Zoom along the line"}, + {"Ctrl+wheel", "Stretch the heights"}, + {"RMB + move", "Move the view along the line"}, + {"Apply in the scenery", "Write the heights into the tracks; Ctrl+Z takes them back"}}}, {"Roads", {{"Esc", "Finish the road being built"}, {"Ctrl held", "Build: straight ahead"}, @@ -4623,22 +6300,54 @@ void editor_mode::render_shortcuts_window() {"Terrain", {{"LMB", "Sculpt: raise; smooth: even out; chunks: add one"}, {"Shift+LMB", "Sculpt: lower; chunks: delete one"}}}, }; ImGui::SetNextWindowSize(ImVec2(620.0f * Global.ui_scale, 560.0f * Global.ui_scale), ImGuiCond_FirstUseEver); + keep_on_screen("###shortcuts"); // it floats over the view, read better on a solid background ImGui::SetNextWindowBgAlpha(0.97f); if (ImGui::Begin((std::string(STR_C("Keyboard shortcuts")) + "###shortcuts").c_str(), &m_shortcuts_open, ImGuiWindowFlags_NoCollapse)) { + static char filter[64]{}; + ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x * 0.6f); + ImGui::InputTextWithHint("##shortcutfilter", STR_C("Find: a key or what it does"), filter, sizeof(filter)); + ImGui::SameLine(); + if (ImGui::Button(STR_C("Tutorial"))) + m_first_steps_open = true; + auto const lower = [](std::string Text) { + std::transform(Text.begin(), Text.end(), Text.begin(), [](unsigned char const Character) { return static_cast(std::tolower(Character)); }); + return Text; + }; + auto const wanted{lower(filter)}; + auto const matches = [&](shortcut const &Item) { return wanted.empty() || lower(STR_C(Item.keys)).find(wanted) != std::string::npos || lower(STR_C(Item.action)).find(wanted) != std::string::npos; }; + auto const picture{std::round(ImGui::GetTextLineHeight() * 1.15f)}; for (auto const &entry : groups) { + if (std::none_of(entry.shortcuts.begin(), entry.shortcuts.end(), matches)) + continue; ImGui::SeparatorText(STR_C(entry.title)); if (false == ImGui::BeginTable(entry.title, 2, ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingStretchProp)) continue; - ImGui::TableSetupColumn("##keys", ImGuiTableColumnFlags_WidthFixed, 190.0f * Global.ui_scale); - ImGui::TableSetupColumn("##action", ImGuiTableColumnFlags_WidthStretch); + ImGui::TableSetupColumn("##keys", ImGuiTableColumnFlags_WidthFixed, 250.0f * Global.ui_scale); + ImGui::TableSetupColumn("##action", ImGuiTableColumnFlags_WidthStretch, 1.0f); for (auto const &item : entry.shortcuts) { + if (false == matches(item)) + continue; ImGui::TableNextColumn(); - ImGui::TextColored(ImGui::GetStyleColorVec4(ImGuiCol_CheckMark), "%s", STR_C(item.keys)); + auto const words{gesture_picture(item.keys)}; + if (false == words.empty()) + { + auto const at{ImGui::GetCursorScreenPos()}; + auto const drawn{gesture_draw(*ImGui::GetWindowDrawList(), at, picture, words, ImGui::GetColorU32(ImGuiCol_Text))}; + ImGui::Dummy(ImVec2(drawn, picture)); + ImGui::SameLine(); + ImGui::SetCursorPosY(ImGui::GetCursorPosY() + std::round((picture - ImGui::GetTextLineHeight()) * 0.5f)); + } + if (words.empty() || false == gesture_keys_only(item.keys)) + ImGui::TextColored(ImGui::GetStyleColorVec4(ImGuiCol_CheckMark), "%s", STR_C(item.keys)); + else + ImGui::NewLine(); ImGui::TableNextColumn(); + if (false == words.empty()) + ImGui::SetCursorPosY(ImGui::GetCursorPosY() + std::round((picture - ImGui::GetTextLineHeight()) * 0.5f)); ImGui::TextWrapped("%s", STR_C(item.action)); } ImGui::EndTable(); @@ -4647,9 +6356,14 @@ void editor_mode::render_shortcuts_window() ImGui::End(); } +bool editor_mode::gizmo_shown() const +{ + return ui()->mode() == nodebank_panel::TRACK ? m_track_gizmo_on : m_gizmo_enabled; +} + void editor_mode::render_gizmo_options() { - if (ImGui::Button(Global.EditorOrtho ? "3D view (O)" : "Top view, orthographic (O)")) + if (ImGui::Button(Global.EditorOrtho ? STR_C("3D view (O)") : STR_C("Top view, orthographic (O)"))) toggle_ortho(); if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", Global.EditorOrtho ? STR_C("Wheel zooms. Hold the wheel and drag to pan.") : STR_C("Top-down orthographic view")); @@ -4657,12 +6371,28 @@ void editor_mode::render_gizmo_options() { ImGui::SameLine(); ImGui::SetNextItemWidth(120.0f); - ImGui::SliderFloat(STR_C("Extent (m), wheel / MMB pan"), &Global.EditorOrthoExtent, 5.0f, 5000.0f, "%.0f", ImGuiSliderFlags_Logarithmic); + ImGui::SliderFloat(STR_C("Extent (m), wheel / MMB pan"), &Global.EditorOrthoExtent, 5.0f, 50000.0f, "%.0f", ImGuiSliderFlags_Logarithmic); if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", STR_C("Wheel zooms. Hold the wheel and drag to pan.")); + ImGui::SameLine(); + render_top_tracks_choice(true); } - ImGui::Checkbox(STR_C("Enabled"), &m_gizmo_enabled); - if (!m_gizmo_enabled) + if (ui()->mode() == nodebank_panel::TRACK && m_track_tab != track_tab::path && m_track_tab != track_tab::turnout && m_track_tab != track_tab::turntable && m_track_tab != track_tab::signals && + m_track_tab != track_tab::lineside) + return; + auto &enabled{ui()->mode() == nodebank_panel::TRACK ? m_track_gizmo_on : m_gizmo_enabled}; + int op{enabled ? static_cast(m_gizmo_op) : -1}; + if (segmented("gizmo", op, + {{-1, STR_C("Off"), "The gizmo hidden: the selected things won't move by chance"}, + {static_cast(gizmo_operation::translate), STR_C("Translate (Q)"), "Arrows which move the selected thing"}, + {static_cast(gizmo_operation::rotate), STR_C("Rotate (W)"), "Rings which turn the selected thing"}, + {static_cast(gizmo_operation::scale), STR_C("Scale (E)"), "Handles which scale the selected thing; a track is lengthened"}})) + { + enabled = op >= 0; + if (enabled) + m_gizmo_op = static_cast(op); + } + if (!enabled) return; if (terrain_brush() || terrain_clicking()) { @@ -4670,15 +6400,6 @@ void editor_mode::render_gizmo_options() return; } - // lets the user pick the transform mode without keyboard shortcuts - int op = static_cast(m_gizmo_op); - ImGui::RadioButton(STR_C("Translate (Q)"), &op, static_cast(gizmo_operation::translate)); - ImGui::SameLine(); - ImGui::RadioButton(STR_C("Rotate (W)"), &op, static_cast(gizmo_operation::rotate)); - ImGui::SameLine(); - ImGui::RadioButton(STR_C("Scale (E)"), &op, static_cast(gizmo_operation::scale)); - m_gizmo_op = static_cast(op); - if (m_gizmo_op != gizmo_operation::scale) // ImGuizmo always scales in local space ImGui::Checkbox(STR_C("Local space (R)"), &m_gizmo_local); if (m_gizmo_op == gizmo_operation::translate) @@ -4692,29 +6413,16 @@ void editor_mode::render_gizmo_options() { auto const located = editor_includes::parameter_with_role(m_include.info, "pos.x") != 0 || editor_includes::parameter_with_role(m_include.info, "pos.y") != 0 || editor_includes::parameter_with_role(m_include.info, "pos.z") != 0; - ImGui::TextDisabled("%s", false == located ? "Include selected, no position parameters described" : + ImGui::TextDisabled("%s", false == located ? STR_C("Include selected, no position parameters described") : false == m_include.placement ? STR_C("Include selected, no gizmo under rotate or scale") : STR_C("Include selected, axes as its template allows")); } - else if (!m_node) + else if (!m_node && ui()->mode() != nodebank_panel::TRACK) ImGui::TextDisabled(STR_C("No node selected")); } void editor_mode::render_gizmo() { - // the transform gizmo is suppressed while editing terrain, so the brush/chunk tool owns the mouse - if (!m_gizmo_enabled || terrain_brush() || terrain_clicking()) - { - m_gizmo_using = false; - return; - } - - if (ui()->mode() == nodebank_panel::TRACK && m_track_tab == track_tab::path && m_track_set.size() >= 2) - { - render_track_set_gizmo(); - return; - } - if (straights_active()) { render_straight_gizmo(); @@ -4727,6 +6435,20 @@ void editor_mode::render_gizmo() return; } + // the transform gizmo is suppressed while editing terrain, so the brush/chunk tool owns the mouse + if (!gizmo_shown() || terrain_brush() || terrain_clicking()) + { + m_gizmo_using = false; + m_track_gizmo_using = false; + return; + } + + if (ui()->mode() == nodebank_panel::TRACK && m_track_tab == track_tab::path && m_track_set.size() >= 2) + { + render_track_set_gizmo(); + return; + } + if (!m_node && m_instance == 0) { m_gizmo_using = false; @@ -4888,11 +6610,16 @@ void editor_mode::render_include_gizmo(glm::mat4 const &View, glm::mat4 const &P if (positions == 0) return; // nothing tells where the include is - // only the axes the template has parameters for can be manipulated + // only the axes the template has parameters for can be manipulated. a signal stands on the ground by its track: it is moved in + // the plan, at the height it has + // not waited for: a scan started again while a signal is selected would stop the editor for its whole length + if (m_include.info.category == "signal") + signal_scan(false); + auto const signal{signal_template_of(m_include.target) != nullptr}; auto operation = 0; for (auto axis = 0; axis < 3; ++axis) { - if (m_gizmo_op == gizmo_operation::translate && position[axis] >= 0) + if (m_gizmo_op == gizmo_operation::translate && position[axis] >= 0 && false == (signal && axis == 1)) operation |= (ImGuizmo::TRANSLATE_X << axis); else if (m_gizmo_op == gizmo_operation::rotate && rotation[axis] >= 0) operation |= (ImGuizmo::ROTATE_X << axis); @@ -4915,11 +6642,20 @@ void editor_mode::render_include_gizmo(glm::mat4 const &View, glm::mat4 const &P glm::vec3 const snapvalue(translating ? m_gizmo_snap : 5.0f); float const *snap = Global.ctrlState && snapvalue.x > 0.0f ? glm::value_ptr(snapvalue) : nullptr; + // in the signal tool a press on the mast drags the signal along its track: the gizmo, whose up axis runs along the + // mast, gives way over a signal and while one is dragged + auto const yield{ui()->mode() == nodebank_panel::TRACK && m_track_tab == track_tab::signals && false == ImGuizmo::IsUsing() && (m_signal.moving || m_signal.placing || signal_hit() >= 0)}; + ImGuizmo::Enable(false == yield); ImGuizmo::Manipulate(glm::value_ptr(View), glm::value_ptr(Projection), static_cast(operation), mode, glm::value_ptr(matrix), nullptr, snap); + ImGuizmo::Enable(true); if (false == ImGuizmo::IsUsing()) + { + signal_gizmo_end(); return; + } m_gizmo_using = true; + signal_gizmo_begin(); float newtranslation[3], newrotation[3], newscale[3]; ImGuizmo::DecomposeMatrixToComponents(glm::value_ptr(matrix), newtranslation, newrotation, newscale); @@ -4949,6 +6685,7 @@ void editor_mode::render_include_gizmo(glm::mat4 const &View, glm::mat4 const &P } } apply_include(); + signal_gizmo_step(); } glm::mat4 editor_mode::projection_matrix(float const Aspect) @@ -4963,7 +6700,11 @@ glm::mat4 editor_mode::projection_matrix(float const Aspect) void editor_mode::toggle_ortho() { + // the view from above isn't one from the track, the ride ends + m_ride.leave(); Global.EditorOrtho = !Global.EditorOrtho; + // either way: a scenery made in the wizard opens seen from above already + first_step_done(first_step::top); if (Global.EditorOrtho) { m_ortho_pitch = Camera.Angle.x; @@ -4974,6 +6715,7 @@ void editor_mode::toggle_ortho() { Camera.Angle.x = m_ortho_pitch; ortho_pan_stop(); + camera_above_ground(); } } @@ -4989,6 +6731,7 @@ void editor_mode::ortho_pan_to(double const Horizontal, double const Vertical) // looked at from the side, a pixel up the screen is more of the ground than one across auto const along{Global.EditorOrtho ? 1.0 : 1.0 / std::max(0.25, std::abs(std::sin(static_cast(Camera.Angle.x))))}; auto const world{RotateY(glm::dvec3{dx * scale, 0.0, dy * scale * along}, static_cast(Camera.Angle.y))}; + m_ride.leave(); Camera.Pos.x -= world.x; Camera.Pos.z -= world.z; Camera.Velocity = {}; @@ -5003,12 +6746,54 @@ void editor_mode::ortho_pan_stop() void editor_mode::on_scroll(double const Xoffset, double const Yoffset) { - if (false == Global.EditorOrtho || ImGui::GetIO().WantCaptureMouse) + if (false == ImGui::GetIO().WantCaptureMouse && track_wheel(Yoffset != 0.0 ? Yoffset : Xoffset)) return; + // riding along the track the wheel the tools left raises and lowers the camera over the rails + if (m_ride.active()) + { + if (false == ImGui::GetIO().WantCaptureMouse && Yoffset != 0.0) + m_ride.wheel(std::clamp(Yoffset, -2.0, 2.0)); + return; + } + // a swipe on a touchpad goes on after the cursor left the window, with no place for the ray under it + if (ImGui::GetIO().WantCaptureMouse || Yoffset == 0.0 || false == ImGui::IsMousePosValid()) + return; + // a fast swipe on a touchpad can come as one big step + auto const notches{std::clamp(Yoffset, -2.0, 2.0)}; + if (false == Global.EditorOrtho) + { + // in 3D the camera flies along the ray under the cursor, by a share of the distance to what it points at; + // a touchpad sends many small steps, together they come to the same + screen_projection const projection; + glm::dvec3 origin; + glm::dvec3 direction; + projection.ray(ImGui::GetIO().MousePos, origin, direction); + // with nothing under the cursor, the ground under the camera stands for it: the level 0 can lie far below the terrain + std::vector found; + auto const below{ground_heights({Camera.Pos}, false, &found)}; + auto const ground{found[0] != 0 ? below[0] : 0.0}; + auto const height{std::max(2.0, std::abs(Camera.Pos.y - ground))}; + glm::dvec3 level; + auto distance{std::min(GfxRenderer->Mouse_Hit() ? glm::length(GfxRenderer->Mouse_Position()) : projection.on_level(ImGui::GetIO().MousePos, ground, level) ? glm::distance(level, origin) : 2.0 * height, 20000.0)}; + // backing away from a point on the horizon would throw the camera kilometres up + if (notches < 0.0) + distance = std::min(distance, std::max(100.0, 4.0 * height)); + auto step{distance * (1.0 - std::pow(0.85, notches))}; + // no nearer than 2 m to the point, not through it + if (notches > 0.0) + step = std::max(0.0, std::min(step, distance - 2.0)); + // a point under the cursor which isn't a number, as one on a broken path, moves the camera nowhere + if (false == std::isfinite(step) || glm::any(glm::isnan(direction)) || glm::any(glm::isinf(direction))) + return; + Camera.Pos += direction * step; + Global.pCamera = Camera; + return; + } auto const before{Global.EditorOrthoExtent}; - auto const after{std::clamp(before * static_cast(std::pow(0.85, Yoffset)), 5.0f, 5000.0f)}; + auto const after{std::clamp(before * static_cast(std::pow(0.85, notches)), 5.0f, 50000.0f)}; screen_projection const projection; - glm::dvec3 origin, direction; + glm::dvec3 origin; + glm::dvec3 direction; projection.ray(ImGui::GetIO().MousePos, origin, direction); auto const scale{static_cast(after) / static_cast(before)}; Camera.Pos.x = origin.x + (Camera.Pos.x - origin.x) * scale; @@ -5025,6 +6810,12 @@ void editor_mode::update_camera(double const Deltatime) Camera.Angle.x = -M_PI_2; Camera.Angle.z = 0.0; } + // riding along the track the camera goes where the track takes it, a framing doesn't fly it off + if (m_ride.active()) + { + m_focus_active = false; + m_ride.advance(Camera, Deltatime, m_input.mouse.button(GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS); + } // focus animation runs after Camera.Update() so it overrides any residual velocity/rotation; // it smoothly drives both position and orientation toward the framed object @@ -5056,13 +6847,59 @@ void editor_mode::update_camera(double const Deltatime) // reset window state (will be set again if UI requires it) Global.CabWindowOpen = false; + // a camera at no finite place, as a zoom or a framing aimed at a broken path could put it, draws nothing sane and can + // stall the graphics card: it goes back to where it last was + auto const number = [](auto const &Vector) { return false == glm::any(glm::isnan(Vector)) && false == glm::any(glm::isinf(Vector)); }; + if (number(Camera.Pos) && number(Camera.Angle)) + { + m_camera_finite_pos = Camera.Pos; + m_camera_finite_angle = Camera.Angle; + m_camera_finite = true; + } + else if (m_camera_finite) + { + WriteLog("Editor: the camera went to no finite place, back where it was", logtype::generic); + Camera.Pos = m_camera_finite_pos; + Camera.Angle = m_camera_finite_angle; + Camera.Velocity = glm::dvec3(0.0); + m_focus_active = false; + } + // publish camera back to global copy Global.pCamera = Camera; } +glm::dvec3 editor_mode::camera_look() const +{ + return {-std::sin(Camera.Angle.y), 0.0, -std::cos(Camera.Angle.y)}; +} + +void editor_mode::ride_enter() +{ + // the track under the cursor, else the one nearest the ground under it, else the one nearest the camera + auto under{track_under_cursor(nullptr, 30.0f)}; + auto *track{under.track}; + auto path{under.path}; + auto point{under.point}; + if (track == nullptr && ImGui::IsMousePosValid()) + { + point = std::as_const(*this).cursor_ground(); + track = kilometrage::track_near(point, 30.0, path); + } + if (track == nullptr) + { + point = Camera.Pos; + track = kilometrage::track_near(point, 200.0, path); + } + if (false == m_ride.enter(track, path, point, camera_look(), true)) + ui()->set_status(STR_C("No track nearby"), true); +} + void editor_mode::enter() { m_statebackup = {Global.pCamera, FreeFlyModeFlag, Global.ControlPicking}; + // the editor changes the tracks, their sleepers are worked out as they're needed + track_sleepers::lay_in_background(false); // the editor may remove the tracks and the vehicles the recording refers to: it ends here simulation::Blackbox.close(); @@ -5129,18 +6966,41 @@ void editor_mode::enter() WriteLog("Editor: camera at the first track, " + track->name()); break; } + if (false == m_saved_camera.has_value() && simulation::Paths.sequence().empty()) + { + std::vector found; + auto const ground{ground_heights({glm::dvec3{0.0, 5000.0, 0.0}}, true, &found).front()}; + Camera.Pos = glm::dvec3{0.0, (found.front() != 0 ? ground : 0.0) + 60.0, 0.0}; + // facing north, the top view with the north up as on a map: the yaw 0 looks along -z, to the south + Camera.Angle = glm::vec3(glm::radians(-45.0f), glm::pi(), 0.0f); + Camera.m_owner = nullptr; + FreeFlyModeFlag = true; + if (false == Global.EditorOrtho) + { + Global.EditorOrthoExtent = 150.0f; + toggle_ortho(); + } + Global.pCamera = Camera; + choose_work_area(work_area::tracks); + WriteLog("Editor: camera over the origin of the empty scenery"); + } + m_first_steps_open = EditorSettings.first_steps(); } Global.ControlPicking = true; EditorModeFlag = true; load_orthophoto_settings(); + m_orthophoto.area_paused(m_area_paused); + m_nmt.prefetch_paused(m_area_paused); Application.set_cursor(GLFW_CURSOR_NORMAL); } void editor_mode::exit() { + m_ride.leave(); + track_sleepers::lay_in_background(true); Global.editor_tracks = false; EditorModeFlag = false; Global.ControlPicking = m_statebackup.picking; @@ -5154,15 +7014,24 @@ void editor_mode::exit() m_track_snap = {}; m_track_point = {}; m_route = {}; - m_route_gizmo_using = false; + m_route_dragging = false; if (Global.EditorOrtho) toggle_ortho(); g_redo.clear(); m_history.clear(); + m_orphans.clear(); m_fill_last.clear(); m_orthophoto.cancel_pending(); m_orthophoto.detach_scene(); // the layer is an editor aid, keep it out of the other modes + for (auto &layer : m_wms) + { + layer->cancel_pending(); + layer->detach_scene(); + } + // the download of the area held while the scenery is driven, it goes on once the editor is back + m_orthophoto.area_paused(true); + m_nmt.prefetch_paused(true); scene::Layers.show_all(); // likewise for hidden scenery layers, the other modes get the scenery as it was defined // drop selection so a stale/dangling node pointer isn't used on the next editor session @@ -5191,15 +7060,17 @@ void editor_mode::delete_model(TAnimModel *model, bool const Joined) m_history.back().joined = Joined; WriteLog(debug, logtype::generic); - // clear history pointers referencing this model before actually deleting it + erase_model(model); +} + +void editor_mode::erase_model(TAnimModel *model) +{ nullify_history_pointers(model); remove_from_hierarchy(model); - if (m_node == model) { m_node = nullptr; m_dragging = false; - ui()->set_node(nullptr); } simulation::State.delete_model(model); } @@ -5220,7 +7091,7 @@ void editor_mode::delete_selected() snap.node_name = *scene::Layers.instance(m_instance).file; m_history.push_back(std::move(snap)); g_redo.clear(); - ui()->set_status("Include of \"" + *scene::Layers.instance(m_instance).file + "\" removed, Ctrl+Z brings it back. Its directive is erased when the scenery is saved."); + ui()->set_status(format(STR_C("Include of \"%s\" removed, Ctrl+Z brings it back. Its directive is erased when the scenery is saved"), scene::Layers.instance(m_instance).file->c_str())); select_include(0); return; } @@ -5273,6 +7144,27 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in if (!anyModifier && m_userinterface->on_key(Key, Action)) return; + // riding along the track the keys drive the camera; Y starts the ride on the track under the cursor + if (false == ImGui::GetIO().WantTextInput) + { + std::string status; + auto const taken{m_ride.key(Key, Action, Mods, camera_look(), m_input.mouse.button(GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS, status)}; + if (false == status.empty()) + ui()->set_status(status, m_ride.active()); + if (taken) + { + // the right button held to drive isn't a click for the menu of the track under the cursor + m_track_context.armed = false; + return; + } + // not with a button held: a drag going on would lose its release to the ride + if (Key == GLFW_KEY_Y && Action == GLFW_PRESS && false == anyModifier && false == m_ride.active() && m_input.mouse.button(GLFW_MOUSE_BUTTON_RIGHT) != GLFW_PRESS && m_input.mouse.button(GLFW_MOUSE_BUTTON_LEFT) != GLFW_PRESS) + { + ride_enter(); + return; + } + } + if (ui()->mode() == nodebank_panel::TRACK && is_press(Action) && (Mods & (GLFW_MOD_CONTROL | GLFW_MOD_ALT)) == 0 && typed_key(Key)) return; @@ -5288,9 +7180,10 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in switch (Key) { case GLFW_KEY_O: toggle_ortho(); break; - case GLFW_KEY_Q: m_gizmo_op = gizmo_operation::translate; break; - case GLFW_KEY_W: m_gizmo_op = gizmo_operation::rotate; break; - case GLFW_KEY_E: m_gizmo_op = gizmo_operation::scale; break; + // in the tracks they also bring the gizmo out, hidden until then + case GLFW_KEY_Q: m_gizmo_op = gizmo_operation::translate; m_track_gizmo_on |= ui()->mode() == nodebank_panel::TRACK; break; + case GLFW_KEY_W: m_gizmo_op = gizmo_operation::rotate; m_track_gizmo_on |= ui()->mode() == nodebank_panel::TRACK; break; + case GLFW_KEY_E: m_gizmo_op = gizmo_operation::scale; m_track_gizmo_on |= ui()->mode() == nodebank_panel::TRACK; break; case GLFW_KEY_R: m_gizmo_local = !m_gizmo_local; break; case GLFW_KEY_B: handled = ui()->mode() != nodebank_panel::TRACK && bend_shortcut(); break; case GLFW_KEY_F1: m_shortcuts_open = !m_shortcuts_open; break; @@ -5300,17 +7193,25 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in case GLFW_KEY_F4: choose_work_area(work_area::roads); break; case GLFW_KEY_F5: choose_work_area(work_area::terrain); break; // the edit modes in the order of the toolbar; in the track mode the digits typed as a value were taken already - case GLFW_KEY_1: choose_edit_mode(nodebank_panel::MODIFY); break; - case GLFW_KEY_2: choose_edit_mode(nodebank_panel::ADD); break; - case GLFW_KEY_3: choose_edit_mode(nodebank_panel::BRUSH); break; - case GLFW_KEY_4: choose_edit_mode(nodebank_panel::FILL); break; - case GLFW_KEY_5: choose_edit_mode(nodebank_panel::COPY); break; + case GLFW_KEY_1: handled = ui()->mode() != nodebank_panel::TRACK; if (handled) choose_edit_mode(nodebank_panel::MODIFY); break; + case GLFW_KEY_2: handled = ui()->mode() != nodebank_panel::TRACK; if (handled) choose_edit_mode(nodebank_panel::ADD); break; + case GLFW_KEY_3: handled = ui()->mode() != nodebank_panel::TRACK; if (handled) choose_edit_mode(nodebank_panel::BRUSH); break; + case GLFW_KEY_4: handled = ui()->mode() != nodebank_panel::TRACK; if (handled) choose_edit_mode(nodebank_panel::FILL); break; + case GLFW_KEY_5: handled = ui()->mode() != nodebank_panel::TRACK; if (handled) choose_edit_mode(nodebank_panel::COPY); break; default: handled = false; break; } if (handled) return; } + // the minimap with the stations + if (Global.ctrlState && false == Global.shiftState && Key == GLFW_KEY_M) + { + if (is_press(Action)) + m_minimap.toggle(); + return; + } + // all docks unpinned and hidden at the edges, for the most of the view, or pinned back if (Global.ctrlState && false == Global.shiftState && Key == GLFW_KEY_SPACE) { @@ -5336,6 +7237,31 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in return; } + // the properties of a track copied and pasted on the selected ones + if (Global.ctrlState && Global.shiftState && (Key == GLFW_KEY_C || Key == GLFW_KEY_V) && ui()->mode() == nodebank_panel::TRACK) + { + if (is_press(Action) && false == ImGui::GetIO().WantTextInput) + { + auto const tracks{selected_tracks()}; + if (Key == GLFW_KEY_C) + { + // the selected track, or the one under the cursor when there are more of them + auto *from{tracks.size() == 1 ? tracks.front() : m_hover.track}; + if (from != nullptr) + copy_track_style(*from); + else + ui()->set_status(STR_C("Select one track, or point at one, to take its properties"), true); + } + else if (m_track_style.values.empty()) + ui()->set_status(STR_C("Take the properties of a track first: Ctrl+Shift+C"), true); + else if (tracks.empty()) + ui()->set_status(STR_C("Select the tracks to set the properties on"), true); + else + paste_track_style(tracks); + } + return; + } + // save; checked ahead of the camera keys, which have S bound to moving back if (Global.ctrlState && false == Global.shiftState && Key == GLFW_KEY_S) { @@ -5400,11 +7326,29 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in break; case GLFW_KEY_DELETE: - if (is_press(Action)) + // the chunks of the terrain selected, where the terrain is the field of work; else what's selected in the scenery + if (is_press(Action) && m_terrain_open && false == m_terrain_selection.empty()) + remove_selected_chunks(); + else if (is_press(Action)) delete_selected(); break; case GLFW_KEY_ESCAPE: + // an open list or menu takes this Esc for itself, the selection behind it stays + if (ImGui::IsPopupOpen("", ImGuiPopupFlags_AnyPopupId | ImGuiPopupFlags_AnyPopupLevel)) + break; + // the switch being clicked off the view given up + if (is_press(Action) && m_switch_designer.open && m_switch_designer.picking) + { + m_switch_designer.picking = false; + break; + } + // the download area being drawn given up, the one before stays + if (is_press(Action) && m_area_drawing.active) + { + area_finish(false); + break; + } if (is_press(Action)) { road_cancel(); @@ -5412,15 +7356,27 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in // the first Esc drops what is going on in the track mode, the next one goes back to the selection if (is_press(Action) && ui()->mode() == nodebank_panel::TRACK) { - if (m_lay.active && false == m_lay.points.empty()) - lay_cancel(); + if (m_tape.active) + m_tape = {}; + else if (m_route.trace.active && route_active()) + route_trace_end(false); + else if (m_lay.active && false == m_lay.points.empty()) + lay_escape(); + else if (m_track_style.picking) + m_track_style.picking = false; + else if (m_profile.picking) + m_profile.picking = false; else if (track_busy()) { cancel_track_tools(); m_straights.tool = 0; } - else if (m_track_tab == track_tab::path && false == m_track_set.empty()) - m_track_set.clear(); + else if (m_track_tab == track_tab::signals && m_signal.picking_read) + m_signal.picking_read = false; + else if (m_track_tab == track_tab::signals && m_signal.armed) + m_signal.armed = false; + else if (m_track_tab == track_tab::path && m_track_set.size() >= 2) + select_tracks({}); else if (m_track_tab != track_tab::path) show_track_tab(track_tab::path); else if (selected_track() != nullptr) @@ -5432,22 +7388,61 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in } break; + case GLFW_KEY_TAB: + // a switch dragged from a free end and bent: its diverging track the other way than the main one, or the same way + if (is_press(Action) && false == anyModifier && m_switch.placing && m_switch.free && false == ImGui::GetIO().WantTextInput) + { + m_switch.one_sided = false == m_switch.one_sided; + break; + } + // laying: the bends of straights or a curve traced, for the points clicked from now on + if (is_press(Action) && false == anyModifier && ui()->mode() == nodebank_panel::TRACK && m_lay.active && false == ImGui::GetIO().WantTextInput) + lay_switch_mode(); + break; + case GLFW_KEY_BACKSPACE: + // the switch being clicked off the view: the last point taken back + if (m_switch_designer.open && m_switch_designer.picking) + { + if (is_press(Action) && false == m_switch_designer.clicks.empty()) + { + m_switch_designer.clicks.pop_back(); + switch_designer_measure(); + } + break; + } + // the download area: the last point taken back + if (is_press(Action) && m_area_drawing.active) + { + if (false == m_area_drawing.points.empty()) + m_area_drawing.points.pop_back(); + break; + } // area fill: remove the last outline point if (is_press(Action) && ui()->mode() == nodebank_panel::FILL && !m_fill_points.empty()) m_fill_points.pop_back(); if (is_press(Action) && ui()->mode() == nodebank_panel::TRACK && m_lay.active && !m_lay.points.empty()) + lay_back(); + if (is_press(Action) && m_route.trace.active && route_active() && !m_route.trace.points.empty()) { - m_lay.points.pop_back(); - if (m_lay.points.empty()) - m_lay.start = {}; + m_route.trace.points.pop_back(); + route_trace_fit(); } break; case GLFW_KEY_ENTER: case GLFW_KEY_KP_ENTER: + // the download area closed, from three points on + if (is_press(Action) && m_area_drawing.active) + { + if (m_area_drawing.points.size() >= 3) + area_finish(true); + break; + } if (is_press(Action) && ui()->mode() == nodebank_panel::TRACK && m_lay.active) lay_enter(); + if (is_press(Action) && m_route.trace.active && route_active()) + route_trace_end(true); break; case GLFW_KEY_K: @@ -5456,7 +7451,11 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in break; } if (is_press(Action) && ui()->mode() == nodebank_panel::TRACK && selected_track() != nullptr) - split_track_at(*selected_track(), Global.pCamera.Pos + GfxRenderer->Mouse_Position()); + { + auto const under{split_spot()}; + if (under.track != nullptr) + split_track_at(*under.track, under.point); + } break; case GLFW_KEY_F: @@ -5500,6 +7499,27 @@ void editor_mode::on_mouse_button(int const Button, int const Action, int const return; } + // a switch being clicked off the view for the template editor takes the left button + if (m_switch_designer.open && m_switch_designer.picking && Button == GLFW_MOUSE_BUTTON_LEFT) + { + // on the terrain under the cursor, then on the level of the first point: no track or ballast in the view catches the point + if (is_press(Action)) + switch_designer_click(m_switch_designer.clicks.empty() ? cursor_terrain(std::as_const(*this).cursor_ground().y) : cursor_level(m_switch_designer.clicks.front().y)); + m_input.mouse.button(Button, Action); + return; + } + + // the download area drawn on the map takes the left button while it's drawn + if (m_area_drawing.active && Button == GLFW_MOUSE_BUTTON_LEFT) + { + if (is_press(Action)) + area_click(Global.shiftState); + else + m_area_drawing.dragged = -1; + m_input.mouse.button(Button, Action); + return; + } + // the chunk, spacing and water tools of the terrain work on a click (Shift: the other way round) if (terrain_clicking() && Button == GLFW_MOUSE_BUTTON_LEFT) { @@ -5611,6 +7631,7 @@ void editor_mode::on_mouse_button(int const Button, int const Action, int const auto *const previous{m_node}; m_node = nullptr; select_include(0); + ui()->set_node(additive ? previous : nullptr); // in a scenery opened for editing selection has its limits. nodes of locked layers are off limits. // nodes defined by a scenery template can't be rewritten one by one on save, so a click on one @@ -5621,12 +7642,12 @@ void editor_mode::on_mouse_button(int const Button, int const Action, int const if (node->from_template() && scene::Layers.removable(node->m_instance, &reason)) { select_include(node->m_instance); - ui()->set_status("Include of \"" + *scene::Layers.instance(m_instance).file + "\" selected. Its parameters are in the node properties, Del removes it from the scenery."); + ui()->set_status(format(STR_C("Include of \"%s\" selected. Its parameters are in the inspector, Del removes it from the scenery"), scene::Layers.instance(m_instance).file->c_str())); node = nullptr; } else if (node->from_template() || false == scene::Layers.editable(node, &reason)) { - ui()->set_status("\"" + (node->name().empty() ? std::string{"(unnamed node)"} : node->name()) + "\" can't be edited: " + reason, true); + ui()->set_status(format(STR_C("\"%s\" can't be edited: %s"), name_of(*node).c_str(), reason.c_str()), true); node = nullptr; } } @@ -5708,11 +7729,28 @@ void editor_mode::on_mouse_button(int const Button, int const Action, int const if (m_extend.active) finish_extend(); if (m_switch.placing) - finish_switch_placement(); + { + // a press let go with no drag places no switch: the track it took is only selected, the ground with no track there + // selects nothing + auto const &io{ImGui::GetIO()}; + if (glm::length(glm::vec2{io.MousePos.x, io.MousePos.y} - m_switch.pressed_at) <= 10.0f) + { + m_switch.placing = false; + if (m_switch.free) + { + m_switch.free = false; + track_click_select(nullptr); + } + } + else + finish_switch_placement(); + } if (m_turntable.placing) turntable_finish_placement(); if (m_signal.placing || m_signal.moving) signal_release(); + if (m_switch.slide.active) + switch_slide_finish(); } m_dragging = false; @@ -5777,11 +7815,11 @@ void editor_mode::on_mouse_button(int const Button, int const Action, int const void editor_mode::render_change_history(){ - ImGui::Begin((std::string(STR_C("Editor History")) + "###editorhistory").c_str(), &m_change_history); + ImGui::Begin((std::string(STR_C("Change History")) + "###editorhistory").c_str(), &m_change_history); int maxsize = m_max_history_size; if (ImGui::InputInt(STR_C("Max history size"), &maxsize)) { - m_max_history_size = std::max(0, maxsize); + m_max_history_size = std::max(1, maxsize); if ((int)m_history.size() > m_max_history_size && m_max_history_size >= 0) { auto remove_count = (int)m_history.size() - m_max_history_size; @@ -5816,8 +7854,9 @@ void editor_mode::render_change_history(){ s.action == EditorSnapshot::Action::TrackEdit ? "TRK" : s.action == EditorSnapshot::Action::RoadEdit ? "ROAD" : s.action == EditorSnapshot::Action::Array ? "ARR" : - s.action == EditorSnapshot::Action::Terrain ? "TER" : "OTH", - s.node_name.empty() ? "(noname)" : s.node_name.c_str(), + s.action == EditorSnapshot::Action::Terrain ? "TER" : + s.action == EditorSnapshot::Action::Kilometrage ? "KM" : "OTH", + s.node_name.empty() ? STR_C("(no name)") : s.node_name.c_str(), s.position.x, s.position.y, s.position.z); if (ImGui::Selectable(buf, m_selected_history_idx == i)) @@ -5835,7 +7874,7 @@ void editor_mode::render_change_history(){ ImGui::SameLine(); ImGui::SameLine(); - if (ImGui::Button(STR_C("Undo Selected"))) + if (ImGui::Button(STR_C("Undo back to the selected"))) { if (m_selected_history_idx >= 0 && m_selected_history_idx < (int)m_history.size()) { @@ -5853,13 +7892,17 @@ void editor_mode::render_change_history(){ void editor_mode::on_event_poll() { + m_selftest.input.deliver(); // game-engine style camera: WSAD/EQ only fly the camera while the right mouse button is held. // when it's released the keyboard is free for gizmo shortcuts, and we flush a zero-movement // command once so the camera doesn't keep coasting on the last velocity it was given. bool const flying = m_input.mouse.button(GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS; if (flying) { - m_input.poll(); + // riding along the track the camera only looks around, the keys drive the ride + if (false == m_ride.active()) + m_input.poll(); + first_step_done(first_step::look); } else if (m_camera_flying) { @@ -5914,3 +7957,51 @@ void editor_mode::starter_trainset(std::vector &Trailing) return; } } + +void editor_mode::render_top_tracks_choice(bool const Combo) +{ + static char const *const labels[]{"Whole", "Without ballast", "Rails only"}; + static char const *const tooltips[]{"The tracks as in the 3D view", "The rails and the sleepers, the ground under them shows", "The rails alone, without the sleepers and the timbers of the switches, as on a plan"}; + auto chosen{std::clamp(Global.EditorOrthoTracks, 0, 2)}; + auto const pick = [&](int const Choice) { + Global.EditorOrthoTracks = Choice; + EditorSettings.top_tracks(Choice); + EditorSettings.save(); + }; + if (false == Combo) + { + for (int choice = 0; choice < 3; ++choice) + { + if (ImGui::MenuItem(STR_C(labels[choice]), nullptr, chosen == choice)) + pick(choice); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C(tooltips[choice])); + } + return; + } + ImGui::SetNextItemWidth(130.0f); + if (ImGui::BeginCombo(STR_C("Tracks"), STR_C(labels[chosen]))) + { + for (int choice = 0; choice < 3; ++choice) + { + if (ImGui::Selectable(STR_C(labels[choice]), chosen == choice)) + pick(choice); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C(tooltips[choice])); + } + ImGui::EndCombo(); + } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("How the top view draws the tracks")); + if (chosen < 2) + return; + ImGui::SameLine(); + auto colour{ImGui::ColorConvertU32ToFloat4(EditorSettings.top_rails())}; + if (ImGui::ColorEdit3("##toprails", &colour.x, ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel)) + { + EditorSettings.top_rails(ImGui::ColorConvertFloat4ToU32(ImVec4(colour.x, colour.y, colour.z, 1.0f))); + EditorSettings.save(); + } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("The colour of the rails, to stand out on the imagery and the map")); +} diff --git a/application/editormode.h b/application/editormode.h index 135ca4a2e..ef6202f38 100644 --- a/application/editormode.h +++ b/application/editormode.h @@ -14,67 +14,67 @@ http://mozilla.org/MPL/2.0/. #include "input/editormouseinput.h" #include "input/editorkeyboardinput.h" #include "vehicle/Camera.h" +#include "application/editormodegauge.h" +#include "application/editormoderide.h" +#include "application/editormodeminimap.h" +#include "application/editormodejoints.h" +#include "application/editormodelineside.h" +#include "application/editormodeparallel.h" +#include "application/editormodespeed.h" +#include "application/editormodesrk.h" +#include "application/editormodekm.h" +#include "application/editormodevehicle.h" +#include "application/editortool.h" #include "scene/sceneeditor.h" #include "scene/scenenode.h" #include "editor/editorTerrain.hpp" #include "editor/editorTerrainStreamer.hpp" #include "editor/editorOrthophoto.hpp" +#include "editor/editorNmt.hpp" +#include "editor/editorGeoMap.hpp" #include "editor/editorTrack.hpp" +#include "editor/editorTrackTrace.hpp" +#include "editor/editorConnections.hpp" #include "editor/editorAlignment.hpp" +#include "editor/editorAlignmentStore.hpp" +#include "editor/editorSwitchStore.hpp" +#include "editor/editorSwitchCurve.hpp" +#include "editor/editorKilometrage.hpp" #include "editor/editorSpeed.hpp" #include "editor/editorRoad.hpp" #include "editor/editorProfile.hpp" +#include "editor/editorGroundFollow.hpp" #include "editor/editorInfra.hpp" #include "editor/editorGauge.hpp" +#include "editor/editorClips.hpp" +#include "editor/editorIcons.hpp" +#include "application/scriptedinput.h" #include "world/Sweep.h" #include #include +#include #include #include +#include #include #include +#include +#include +#include #include +#include #include class TAnimModel; // a tool of a field of work of the editor, a button in the toolbar and over the 3d view struct editor_tool_button; class TTrack; -namespace ui -{ -class vehicles_bank; -struct vehicle_desc; -struct skin_set; -} -class editor_mode : public application_mode, private editor_track::observer +class editor_mode : public application_mode, private editor_track::observer, private editor_services { public: - // model entering the structure gauge, at its deepest place - struct gauge_hit - { - std::string model; - glm::dvec3 point{0.0}; - double depth{0.0}; // m - TTrack const *track{nullptr}; // nearest one, may be gone by now - int path{0}; - glm::dvec2 direction{0.0, 1.0}; // of the track there, in the plan - }; - // joint of the paths found wrong by the joints check - struct joint_issue - { - enum class kind { gap, step, kink, cant, grade, open }; - kind type{kind::gap}; - TTrack *track{nullptr}; - editor_track::point_ref point; - TTrack *other{nullptr}; - editor_track::point_ref theirs; - glm::dvec3 position{0.0}; - double value{0.0}; // m, deg, mm, per mille - bool fixed{false}; - }; // constructors editor_mode(); ~editor_mode() override; @@ -132,7 +132,7 @@ class editor_mode : public application_mode, private editor_track::observer struct stored_profile; struct EditorSnapshot { - enum class Action { Move, Rotate, Scale, Add, Delete, TrackEdit, Other, RoadEdit, Array, Bend, Terrain }; + enum class Action { Move, Rotate, Scale, Add, Delete, TrackEdit, Other, RoadEdit, Array, Bend, Terrain, Kilometrage }; // copy of a model an array made struct array_copy { @@ -168,27 +168,46 @@ class editor_mode : public application_mode, private editor_track::observer std::vector infra; // objects which followed the paths bool profiles{false}; // the stored grade line designs changed too, these were the ones before std::vector profile_library; + std::optional> alignments; // the kept horizontal alignments changed too, these were the ones before + std::optional> switch_records; // the kept switches changed too, these were the ones before + std::optional hand_joints; // the joints of a station put by hand changed too, these were the ones before + std::optional kilometrage; // the kilometrage before the change (Action::Kilometrage) std::vector copies; // models an array added to the one it was made of bool joined{false}; // undone and redone together with the change before it std::shared_ptr terrain; // the heightmap terrain from before the change (Action::Terrain) + std::uint64_t serial{next_serial()}; // of each step made, for the revision of the history + static std::uint64_t next_serial() + { + static std::uint64_t counter{0}; + return ++counter; + } }; void push_snapshot(scene::basic_node *node, EditorSnapshot::Action Action = EditorSnapshot::Action::Move, std::string const &Serialized = std::string()); std::vector m_history; // history of changes to nodes, used for undo functionality std::vector g_redo; + int m_track_edits{0}; // methods void update_camera(double const Deltatime); + // the camera onto the track under the cursor, or the nearest one, to ride along it + void ride_enter(); + // the way the camera looks, in the plan + glm::dvec3 camera_look() const; editor_ui *ui() const; void redo_last(); // a single step of the history, see undo_last() void undo_one(); + void drop_step(std::size_t const Step); + std::string refused(std::string Text); void redo_one(); // the changes of the heightmap terrain since the last step become a step of the history: a stroke of the brush, // or what a frame did; the next change is recorded from now on void terrain_history_step(); // puts the terrain back as the step recorded it, the step left with the state it replaced void restore_terrain(EditorSnapshot &Snapshot); + // swaps the kilometrage with the one the snapshot keeps + void restore_kilometrage(EditorSnapshot &Snapshot); bool m_history_busy{false}; // undo or redo under way void handle_brush_mouse_hold(int Action, int Button); void apply_rotation_for_new_node(scene::basic_node *node, int rotation_mode, float fixed_rotation_value); @@ -205,6 +224,10 @@ class editor_mode : public application_mode, private editor_track::observer glm::vec3 m_focus_target_angle{0.0f}; // camera pitch/yaw/roll facing the focused object double m_focus_time{0.0}; double m_focus_duration{0.6}; + // the last place and angles of the camera which were numbers: a camera gone to no finite place goes back there + glm::dvec3 m_camera_finite_pos{0.0, 0.0, 0.0}; + glm::vec3 m_camera_finite_angle{0.0f}; + bool m_camera_finite{false}; double fTime50Hz{0.0}; // bufor czasu dla komunikacji z PoKeys scene::basic_editor m_editor; @@ -237,7 +260,9 @@ class editor_mode : public application_mode, private editor_track::observer int m_selected_history_idx{-1}; glm::dvec3 clamp_mouse_offset_to_max(const glm::dvec3 &offset); // the ground under a point the cursor landed on, for things which are to stand on the ground - glm::dvec3 placement_on_ground(glm::dvec3 Location); + glm::dvec3 placement_on_ground(glm::dvec3 Location) override; + // the ground under a point, the point itself with none there + glm::dvec3 ground_at(glm::dvec3 Location) const; // puts every instance of the model the selected node shows on the ground under it void drop_model_instances(); void render_object_menu(); @@ -247,6 +272,34 @@ class editor_mode : public application_mode, private editor_track::observer void render_help_menu(); void render_shortcuts_window(); bool m_shortcuts_open{false}; + using first_step = editor_first_step; + // the tutorial: a window of lessons, each with a clip or a sketch, the mouse and the keys it teaches and the steps to try + struct tutorial_lesson; + static std::vector const &tutorial_lessons(); + // a lesson is done once all its steps are + bool tutorial_done(tutorial_lesson const &Lesson) const; + void render_first_steps(); + // the steps reached by what the editor is doing now + void note_first_steps(); + // the lesson of the tool in use: the first of its lessons not done yet, or none + char const *tutorial_of_tool(); + // the lesson the tool in use or a button of a panel asks for opened, and the clip of the lesson open loaded + void follow_tutorial(); + void render_tutorial_media(tutorial_lesson const &Lesson, float const Width); + void render_tutorial_goals(tutorial_lesson const &Lesson); + // the button under a lesson, opening the tool it's about or switching the view + void render_tutorial_trial(tutorial_lesson const &Lesson); + // the buttons to the lesson before and after, and a dot for each lesson, green when it's done + void render_tutorial_pages(); + void first_step_done(first_step const Step) override; + void open_kilometrage() override; + bool m_first_steps_open{false}; + std::array(first_step::count)> m_first_steps_done{}; + int m_tutorial_page{0}; + char const *m_tutorial_goto{nullptr}; // the lesson of this title opened by a button of a panel + std::string m_tutorial_followed; // the lesson the tool in use asked for last: it's opened when that changes + double m_tutorial_since{0.0}; + editor_clips::clip m_tutorial_clip; // deletes what's selected: a road piece or point, a signal, an include of a scenery template, a model, tracks (Del) void delete_selected(); void delete_model(TAnimModel *Model, bool const Joined); @@ -303,6 +356,306 @@ class editor_mode : public application_mode, private editor_track::observer // adds a chunk of the terrain shaped as the ground under it; where there's no ground, carried on level with the nearest point // of it, or at the base height. returns: false if there's a chunk already bool add_chunk_from_ground(heightmap::chunk_key const &Key, float const Spacing, std::uint16_t const Layer = 0); + + // the terrain from the digital terrain model of GUGiK (editormodenmt.cpp) + using nmt_place = ::nmt_place; + struct nmt_state + { + double offset{0.0}; // added to the heights of the model, so they meet the tracks of the scenery + bool fitted{false}; + bool fitting{false}; // waiting for the model under the places of the tracks the offset is worked out from + std::vector fit; + double spread{0.0}; // how much the tracks differ from the model about the offset, m + std::size_t samples{0}; + double band{300.0}; // m from the tracks the chunks made along them reach + bool shape{true}; // the formation and the slopes of the tracks as modifiers of the terrain + bool grow{true}; // while a track is laid, the terrain is made around the cursor where there's none + bool laying{false}; // the tracks committed are being laid: they leave the terrain as it is + bool follow{true}; // a track with its formation edited takes it along, the formation led anew + bool grown{false}; // the chunks waiting were all asked for by growing: the formations aren't made anew after them + bool reshape{false}; // the formations of the tracks laid anew once the chunks waiting are made, as the tracks are put onto the terrain + bool unfitted{false}; // the tracks put onto the terrain are only the ones whose grade line isn't fitted yet + bool redo_hand{false}; // all anew takes the grade lines edited by hand too + std::unordered_set stayed; // the tracks this putting onto the terrain leaves as they are + double grow_time{-10.0}; + double slope{1.5}; + double reach{60.0}; + std::vector pending; // chunks to make once their model is in + // of the chunks waiting, those there already with flat ground, made without the model: the model fills their ground + std::set refill; + std::set given_up; // chunks the growing gave up, next to terrain not from the model: not asked for again + std::size_t made{0}; + std::size_t empty{0}; // chunks not made: the model has no data there + std::size_t foreign{0}; // chunks not made ahead: the terrain beside isn't of the model + std::optional ahead; // how much the terrain made ahead lies over the model + std::set changed; // tracks whose formations are to follow them + std::set gone; // names of the tracks removed, whose formations go with them + double changed_time{0.0}; + bool restoring{false}; // the history is taken back or forward: the terrain comes back with it + std::size_t shaped{0}; + std::string status; + std::string error; + bool common{true}; // the tracks nearly parallel under 5.1 m apart lie on one grade line + static int constexpr grade_line_own{-1}; + static int constexpr grade_line_steep{-2}; + static int constexpr grade_line_off{-3}; // taken off a grade line by hand, stays on its own when the lines are worked out again + static int constexpr grade_line_off_number{-10}; // this and below: taken off the grade line of this number less this + std::map grade_lines; // of each track the number of the grade line it shares, or one of those above + std::set grade_lines_hand; // the tracks put on their grade line by hand: they stay on it when the lines are worked out again + bool grade_lines_loaded{false}; + bool grade_lines_dirty{false}; // the edits of the tracks carried their lines on: stored once, with the next frame + std::unordered_map grade_line_keys; // of the tracks changed, the key each had last, to carry its line on to the next + std::vector> grade_line_replaced; // the first paths of the tracks of a line changed since the last frame: a new track on one takes its line + std::unordered_set on_hump; // the tracks of the humps fitted to the model: no grade line shared levels them + std::size_t grade_lines_changes{0}; + std::string explain; // a track whose run the next sharing of the grade lines tells of in the log, for a selftest + struct surface_place + { + TTrack const *track; + int path; + double share; + int surface; + }; + std::vector surface_places; // what lies on the surface of each group on common timbers + bool camera_check{false}; // chunks were made: the 3d camera may be under them now + std::vector buried; // the tracks just laid, when a part of them is hidden in the ground + double buried_length{0.0}; // m of them hidden + // the tracks of a scenery built at any height put onto the terrain model: the model offset to meet the scenery, then the grade + // line of each line of tracks fitted to the model, the longest first, then the terrain made along them + enum class automatic + { + idle, + fetching, // the model under the tracks + fitting // the grade lines, a few each frame + }; + automatic stage{automatic::idle}; + std::vector probes; // places of the tracks whose model is waited for + std::size_t probes_kept{0}; // the last of the probes, on tracks fitted already: they tell the offset the model had + std::size_t tracks{0}; // rail tracks when the grade lines began, and the paths the grade lines split off since + std::size_t split{0}; + std::vector left; // tracks whose grade line is still to be fitted + std::vector done; // tracks of the lines fitted already: the lines fitted later end on them and don't change them + // the rail tops of the lines fitted already, in squares of the plan: the tracks of a station lie in one plane, a line laid + // near them takes their height for its ground too, the more closely the nearer it is, and a line crossing one of them + // on its level its height on the crossing + struct laid_point + { + glm::dvec3 position{0.0}; + glm::dvec2 direction{0.0, 1.0}; + double grade{0.0}; + double was{0.0}; // the height before the line was fitted + double rails{0.0}; // the height of the rails of the track + TTrack const *track{nullptr}; + }; + std::map, std::vector> laid; + // the points of all the paths as they were laid, for the crossings + std::map, std::vector> paths; + // ends which meet in the plan unlinked, laid apart in height, that the joining of the ends couldn't join as neither of + // them can be changed alone, as of two switches: each with the other one, which a line ending there takes over + std::map, std::tuple> loose; + // the points of the lines over a bridge or a viaduct, the model falling away under them: no formation is laid there + std::map, std::vector> bridged; + // a turntable lies level in its pit, which the model has, at the height of the tracks running up to it: it isn't put onto + // the model, and a line ending on its rim ends there level at its height, turning to the model away from it + struct turntable + { + TTrack *table{nullptr}; + glm::dvec3 centre{0.0}; // at the height of its rails + double rim{0.0}; // m from the centre + std::vector> ends; // of the paths running up to it: track, path, at its end + }; + std::vector turntables; + std::size_t levelled{0}; // turntables moved to the height of their tracks + std::size_t lines{0}; // grade lines fitted and applied + std::size_t refused{0}; // grade lines the checks didn't let apply + std::size_t departures{0}; // grade lines parting from the terrain model by much + // what the last putting of the tracks onto the terrain found, listed in the panel to be looked at: a line the checks + // refused, a line parting from the model by much, a path which didn't take its line + struct finding + { + enum class kind + { + refused, + off, + parted + }; + kind what{kind::refused}; + TTrack *from{nullptr}; // the ends of the line, for its profile + TTrack *to{nullptr}; + double length{0.0}; + glm::dvec3 where{0.0}; // the place to look at + std::string text; + double size{0.0}; // m the line or the path is off by: of one kind the worst told first + }; + std::vector findings; + bool result{false}; // the putting onto the terrain ended: what it did is told in the panel until the next one + bool run{false}; // the tracks are being put onto the terrain, the chunks after the grade lines too: the steps told + std::size_t fetch_most{0}; // the most squares of the model waited for since the loading began, for its progress + // the terrain made under the tracks as they are: the model drawn to them by the difference found at the places along them, + // fading out away from them into the offset of the whole scenery + bool under{false}; + std::vector anchors; // x, z of a place of the tracks, the formation there less the model + std::map, std::vector> anchor_cells; // the anchors in squares of the plan + bool offered{false}; // the terrain was offered to the scenery begun without it + bool prompt{false}; // the offer is shown + bool moving{false}; // the place being picked again + char place[96]{}; // typed: degrees or PUWG 1992 + int shown{-1}; // the frame the terrain panel showed how far the work got + }; + editor_nmt m_nmt; + nmt_state m_nmt_state; + editor_map m_nmt_map; + std::vector nmt_track_places(double const Step) const override; + void nmt_locate() override; + void nmt_fit(); + void nmt_finish_fit(); + // the terrain under the tracks, the tracks left as they are: the model drawn to each of them, its relief kept + void nmt_under_start(); + void nmt_under_anchors(); + // added to the height of the model at the place: the offset of the scenery, drawn to the tracks near them + double nmt_offset_at(double const X, double const Z) const; + std::vector nmt_keys_around() const; + std::vector nmt_keys_along_tracks() const; + // only the chunks there are none of yet: a chunk there is, made from the model or by hand, edited or not, is never made anew. + // Reshape: the formations of the tracks laid anew as the tracks lie now, as when they moved + void nmt_make(std::vector const &Keys, bool const Reshape = false); + enum class nmt_chunk + { + waiting, // for its squares of the model + made, + empty // the model has no data there + }; + // Offset: the heights of the model go up or down by it in the whole chunk, in place of the offsets of the fit + nmt_chunk add_chunk_from_nmt(heightmap::chunk_key const &Key, std::optional const Offset = std::nullopt); + // a chunk there with its ground level all over, as made where there was no ground and no model: none of the shape of the land + bool nmt_flat_chunk(heightmap::chunk_key const &Key) const; + // how much the terrain lies over the model at the points: none where there's too little terrain at them, nor where it + // doesn't follow the model (Foreign), as one made by hand + std::optional nmt_terrain_offset(std::vector const &Points, bool &Foreign) const; + // the same along the edges the chunk shares with the chunks beside it in memory + std::optional nmt_seam_offset(heightmap::chunk_key const &Key, bool &Foreign) const; + // the terrain beside the formation of the track is the one made from the model; Waiting: its squares of the model aren't in yet + // the tracks changed by hand are told to the terrain: their formations laid anew, of the tracks removed taken away, a + // track laid onto the terrain of the model given its own, once the mouse lets go; in the step of the history of the change + void nmt_track_changed(std::vector const &Tracks); + void nmt_track_gone(TTrack const &Track); + void nmt_follow_tracks(); + // the height the ground will have where the terrain is made ahead of the track laid and isn't there yet + bool nmt_ahead(double const X, double const Z, double &Height) const; + // the same, else the height of the model with the offset of the scenery where its square is in: the ground where there's no + // terrain made yet, as under the base map of the top view + bool nmt_ground(double const X, double const Z, double &Height) const; + // the squares of the model under the rectangle are in, none of them waiting to be asked for again + bool nmt_ready(glm::dvec2 const &Min, glm::dvec2 const &Max); + // Only: the paths of these tracks are shaped anew, the modifiers of those removed taken away; null: all of them. the number + // of the modifiers laid + std::size_t nmt_shape_tracks(std::vector const *Only = nullptr); + void nmt_update(); + void nmt_grow(); + void render_nmt_ui(); + // where the scenery lies: the map to click on, the place typed; true once it's placed + bool render_nmt_place(bool const Moving, bool const Button); + // the work under way: what's left of it and the button to stop it; Compact: one line, for the 3d view + void render_nmt_progress(bool const Compact); + // the formations of the tracks led into the terrain, down or up to it, or taken out of it; one step of the history each + void nmt_pull_terrain(std::vector const &Tracks); + void nmt_restore_terrain(std::vector const &Tracks); + // the terrain of the selected tracks in the panel of the tracks + void render_track_terrain(std::vector const &Tracks); + // all the tracks of the scenery onto the terrain model, or it under them: step 2 of the terrain model (Terrain_panel), and in + // the panel of the tracks + void render_nmt_all_tracks(bool const Terrain_panel); + // what the last putting of the tracks onto the terrain did, and the places it found to be looked at, each to be shown + void render_nmt_result(); + // a line from From to To being put onto the terrain kept to be looked at: the place of it to show and what's wrong there + void nmt_note(nmt_state::finding::kind const What, TTrack *From, TTrack *To, double const Length, glm::dvec3 const &Where, std::string Text, double const Size = 0.0); + // the place found shown in the 3d view with the track there selected; Profile: the profile of its line opened too + void nmt_show(nmt_state::finding const &Finding, bool const Profile); + // the chunks waiting for the terrain model and the tiles of the imagery asked for outlined where they will be, so it's seen + // what's on its way + void draw_nmt_pending() const; + // the download area: a polygon drawn on the map, the boundary of what the orthophoto and the terrain model download in the + // background, none of them asking for anything outside it (application/editormodenmt.cpp) + void area_start(); + // Keep: the area drawn taken, else the one before stays + void area_finish(bool const Keep); + // a press of the left button while drawing: a point added, or the one under the cursor taken to drag, Shift: removed + void area_click(bool const Shift); + void area_update(); + // a point of the area (x, z) where it's drawn: over the map of the top view, on the ground in the 3d view + glm::dvec3 area_point(glm::dvec2 const &Point) const; + void draw_download_area() const; + void render_download_area_ui(editor_orthophoto::statistics const &Stats); + // the download area a square of the side, km, around the camera + void area_square(int const Side); + // the chunk of the terrain (x, z) touches the area, or there's none + bool in_download_area(glm::dvec2 const &Low, glm::dvec2 const &High) const; + // over the 3d view while the terrain panel isn't seen + void render_nmt_banner(); + // the grade lines fitted, the tracks nearly parallel under 5.1 m apart brought onto one, a track going away from them fading back onto its own + void nmt_share_grades(); + void grade_lines_load(); + void grade_lines_store(); + bool on_route_grade_line(TTrack const &Track); + std::vector const &grade_line_beside(); + std::size_t grade_line_follow(std::vector const &Before); + void grade_line_take_off(bool const Off); + // the grade line the route shares, by most of its paths; -1 when it shares none + int route_grade_line(); + // the plain tracks from switch to switch the track is one of, a switch by itself; Alone: the track only + static std::vector grade_line_run(TTrack &Track, bool const Alone); + // the run of the track clicked onto the grade line of the route by hand, or off it if it's on it; a route sharing none makes one with it + void grade_line_pick(TTrack &Track, bool const Alone); + // all the tracks of the grade line, wherever they are, for the view while they're picked + std::vector const &grade_line_members(int const Number); + void draw_grade_line_pick(); + // a piece split off a track lies on the grade line the track does + void grade_line_split(TTrack const &Original, TTrack const &Created); + // a track changed keeps its grade line under the key it has after it; a new one between two tracks of a line, a switch put into one, lies on it + void grade_line_captured(TTrack const &Track); + void grade_lines_committed(std::vector const &Tracks); + void grade_line_renamed(TTrack const &Track, std::string const &Old); + void render_profile_grade_line(); + // the tracks laid since the step of the history hidden in the ground, told over the 3d view with the way to fit the ground to them + void nmt_check_buried(std::size_t const From); + void render_nmt_buried(); + // what to do first, in the middle of the view of a scenery with no tracks nor terrain + void render_empty_scenery_hint(); + // the camera outside the download area: no photos there, told at the bottom of the view with the way to the area + void render_outside_area_hint(); + // the 3d camera under the ground, as after the view from above or the terrain model made under it, lifted over it + void camera_above_ground(); + bool nmt_busy() const; + // the terrain made so far stays, what's waiting is dropped, the grade lines not fitted yet are left + void nmt_stop(); + // a scenery begun from nothing, with no tracks nor terrain, is asked as the first track is laid whether it wants the terrain + void nmt_offer(); + void render_nmt_prompt(); + // the place picked in the terrain window: the terrain model and the orthophoto take it + void nmt_place_scenery(glm::dvec2 const &Point); + void nmt_accept_offer(); + // the whole scenery: tracks, includes and models, moved up or down as one undo step + std::size_t nmt_join_ends(); + // the turntables as they lie, each with the ends of the tracks running up to it on its rim + std::vector nmt_turntables() const; + // each turntable level at the height of the tracks running up to it, its include with it, before the grade lines are fitted: + // at the height of the ones fitted already, else of the terrain model beside its rim; the number of them moved + std::size_t nmt_level_turntables(); + // Unfitted: only the tracks whose grade line isn't fitted yet, the scenery left at its height + void nmt_auto_start(bool const Unfitted = false); + void nmt_auto_step(); + // the grade line of the line of tracks through the track fitted to the terrain model and applied; false if it couldn't be. + // The line runs over the tracks not Fitted, the ones fitted stay as they are and the line meets them. Where the model falls + // away under the line by the abutments the tracks go over on a bridge; Laid: the tracks just laid, the formation fills it and + // they are cut only where they can't follow the line otherwise + bool nmt_fit_line(TTrack &Track, std::function const &Fitted, bool const Laid); + // the tracks laid in one go since the history step From put onto the terrain model as one line, as the tracks go onto the + // terrain: the track ending at End then the one the laying goes on from + bool nmt_fit_laid(std::size_t const From, glm::dvec3 const End); + // the tracks laid one after another on one straight or one arc, cut by the grade lines fitted before, made one again + void nmt_merge_laid(std::unordered_set &Laid); + // the points of the paths of the track about a metre apart, in squares of the plan + static void nmt_sample_paths(TTrack const &Track, std::map, std::vector> &Points); // the tool of the terrain the left mouse button works enum class terrain_tool { @@ -325,6 +678,8 @@ class editor_mode : public application_mode, private editor_track::observer } // converts the point spacing of the selected chunks to m_terrain_convert_spacing void convert_selected_chunks(); + // the chunks selected with the spacing tool taken out of the terrain, in one step of the history + void remove_selected_chunks(); // takes the height of whatever is under the cursor (terrain, track, model) for the target of the level brush. returns: false if there's nothing bool pick_terrain_target(); bool terrain_clicking() const { return m_terrain_tool == terrain_tool::chunks || m_terrain_tool == terrain_tool::spacing || m_terrain_tool == terrain_tool::water || m_terrain_tool == terrain_tool::fill; } @@ -334,6 +689,8 @@ class editor_mode : public application_mode, private editor_track::observer void draw_terrain_overlay(); // forgets what's known about the ground, after the terrain changed void forget_ground(); + // the ground gathered where the terrain changed in the rectangle (x, z) gathered again when asked for, the rest kept + void forget_ground_in(glm::dvec2 const &Min, glm::dvec2 const &Max); // conversion of the ground of the terrain files of the scenery (terrain directive, .txtf/.btf) to heightmap terrain struct ground_conversion { @@ -376,6 +733,7 @@ class editor_mode : public application_mode, private editor_track::observer std::string selected; std::map thumbnails; // texture shown for the item of the name, 0: none int loads{0}; // textures read in the frame, a few at most so the browser doesn't stall the editor + int loadsframe{-1}; } m_textures; void render_texture_browser(); // texture of the image of the item of the browser, 0 while there's none @@ -415,7 +773,7 @@ class editor_mode : public application_mode, private editor_track::observer // the chunk of the terrain (if any) covering the given world point editor_terrain *terrain_at(double X, double Z); // the chunks of the terrain held in memory - std::vector active_terrains(); + std::vector active_terrains() const; // samples the selected model instance's geometry into the chunks of the terrain it covers, then removes it void capture_terrain(); bool m_terrain_open{false}; // the terrain is the field of work, chosen in the toolbar @@ -445,8 +803,6 @@ class editor_mode : public application_mode, private editor_track::observer char m_water_selected_material[128]{""}; // material of the chosen water, while it's edited int m_water_material_of{-1}; // the water whose material is in the field above float m_water_selected_size{0.0f}; // metres its texture repeats at, 0: given by the material - char m_water_default_material[128]{""}; // of the waters which don't name their own, while it's edited - bool m_water_default_edited{false}; std::set m_terrain_selection; // chunks chosen with the spacing tool float m_terrain_convert_spacing{1.0f}; // point spacing the selected chunks are converted to bool m_terrain_convert_paint{true}; // chunks converted to 0.5 m get paint samples every 0.5 m too @@ -471,14 +827,24 @@ class editor_mode : public application_mode, private editor_track::observer bool m_opened_at_track{false}; bool m_turntable_included{false}; bool turntable_controls(std::vector &Rootstatements); + bool m_nose_included{false}; + bool nose_controls(std::vector &Rootstatements); void starter_trainset(std::vector &Trailing); std::optional> m_saved_camera; char m_openscenery_search[64]{}; std::vector m_openscenery_list; std::string m_openscenery_choice; void render_open_scenery_popup(); + // the settings of the orthophoto, among the base layers in the layers window: asked to be opened there, the frame they were last + // drawn open in bool m_orthophoto_window{false}; - void render_orthophoto_window(); + // the user turned the orthophoto on or off, or the scenery keeps it so: the terrain model made, or the area drawn, leaves it as it + // is then, it turns it on only where nobody chose + bool m_orthophoto_chosen{false}; + // the user turns the orthophoto on or off: kept with the editor, for every scenery + void choose_orthophoto(bool const On); + int m_orthophoto_frame{-10}; + bool orthophoto_settings_open() const; // view menu: the top view, the lanes of the roads, the structure gauge, the environment void render_view_menu(); // time of day, day of the year, visibility, clouds and air temperature, as the scenery is seen in the editor @@ -487,7 +853,6 @@ class editor_mode : public application_mode, private editor_track::observer // over the 3d view: the tools of the field of work along its left edge, the modes of the gizmo at its top, the axes of the // world and the top view in its top right corner void render_viewport_overlays(); - void render_viewport_tools(); // the tools of the field of work, in the order of the toolbar void work_area_tools(std::vector &Buttons); // the tools of the field of work in the toolbar, as icons with their names @@ -506,16 +871,55 @@ class editor_mode : public application_mode, private editor_track::observer void read_georeference(); void draw_orthophoto(); void draw_ortho_compass() const; - // picks up the stored settings and the origin of the current scenery + // picks up the stored settings and the origin of the current scenery, and the offset of the terrain model the scenery has void load_orthophoto_settings(); void save_orthophoto_settings(); + // the settings of the terrain model changed, kept with the editor, and the offset of the model with the scenery's + void keep_nmt_settings(); editor_orthophoto m_orthophoto; + // the WMS layers of the user's over the orthophoto, the top one first, as the settings of the editor keep them; their tiles are + // kept in memory only + std::vector> m_wms; + // a WMS layer being added: the address typed, what its capabilities tell, read on a thread of its own, the layers ticked + struct wms_adding + { + std::array url{}; + std::array filter{}; + std::future reading; + std::optional info; + std::string service; // the address the capabilities were read of + std::vector ticked; + } m_wms_adding; + // the orthophoto and the WMS layers of the user's at the bottom of the layers window, with their settings + void render_base_layers(); + void render_wms_adding(); + // the WMS layers as the settings have them, laid out by the origin and on the ground of the orthophoto, around the camera + void update_wms_layers(); + // the ground the imagery is fitted onto, the same for the orthophoto and the WMS layers + void ground_sources(editor_orthophoto &Layer); + std::size_t m_ortho_resident{0}; // chunks of the terrain in memory, as the imagery last heard of them + std::size_t m_ortho_waiting{0}; // squares of the terrain model asked for and not in yet, the same std::string m_orthophoto_scenery; // scenery whose origin is loaded + std::string m_orthophoto_mark; + std::vector m_orthophoto_area_mark; // the lines of the download area as the scenery keeps them + // the download area being drawn on the map: its points in the world (x, z), the one dragged + struct area_drawing + { + bool active{false}; + std::vector points; + int dragged{-1}; + } m_area_drawing; + std::vector m_nmt_prefetched; // the download area the terrain model was given + bool m_area_paused{false}; // the download of the area held by the button; out of the editor it's held anyway + int m_area_square{0}; // km, the side of the square around the camera waiting for its yes in place of the area there is + bool m_outside_area_closed{false}; // the note of the camera outside the area closed; open again once it's back inside + int m_empty_hint_frame{-10}; // the frame the panel of the empty scenery was last drawn in glm::dvec2 m_orthophoto_origin_edit{0.0}; // origin being typed in (northing, easting); applied when editing ends // hierarchy management void add_to_hierarchy(scene::basic_node *node); void remove_from_hierarchy(scene::basic_node *node); + void erase_model(TAnimModel *model); scene::basic_node* find_in_hierarchy(const std::string &uuid_str); scene::basic_node* find_node_by_any(scene::basic_node *node_ptr, const std::string &uuid_str, const std::string &name); @@ -597,6 +1001,8 @@ class editor_mode : public application_mode, private editor_track::observer void render_gizmo(); // gizmo settings, drawn in the toolset window void render_gizmo_options(); + // how the top view draws the tracks: as a combo with the colour of the rails, or as items of a menu + void render_top_tracks_choice(bool const Combo); // the tools of the field of work in the toolbar under the menu void render_toolbar(); // an edit mode of the node bank as the field of work, from the toolbar or its key (1-5) @@ -613,12 +1019,20 @@ class editor_mode : public application_mode, private editor_track::observer void choose_work_area(work_area const Area); void render_workspaces(); bool m_gizmo_enabled{true}; // master switch for the in-viewport gizmo + bool m_track_gizmo_on{false}; // the gizmo in the tracks: off until Q, W or E, so a track isn't moved by chance + bool gizmo_shown() const; // the switch of the field of work in use bool m_gizmo_using{false}; // tracks an ongoing drag, so a single undo snapshot is taken per drag bool m_gizmo_local{false}; // manipulate in the object's local space instead of world space gizmo_operation m_gizmo_op{gizmo_operation::translate}; // current transform mode (translate/rotate/scale) float m_gizmo_snap{1.0f}; // translation snap step (metres) applied while Ctrl is held - TTrack *selected_track() const; + TTrack *selected_track() const override; + bool track_editing() const override; + std::size_t history_revision() const override; + glm::dvec3 camera_position() const override; + track_hover const &hovered_track() const override; + std::vector const &track_set() const override; + editor_track_tab current_track_tab() const override; void render_path_ui(); void draw_track_overlay() const; editor_track::point_ref track_handle_hit() const; @@ -626,11 +1040,31 @@ class editor_mode : public application_mode, private editor_track::observer void render_track_gizmo(); void commit_track_drag(bool const Force); void cancel_track_tools(); - void push_track_snapshot(std::vector> States, std::vector Created = {}, std::vector Removed = {}); + void push_track_snapshot(std::vector> States, std::vector Created = {}, std::vector Removed = {}) override; + void push_kilometrage_snapshot() override; + void set_current_node(scene::basic_node *Node) override; + alignment::limits const &route_norms() const override; + void clear_track_point() override; + editor_nmt &terrain_model() override; + double terrain_model_offset() const override; + bool terrain_model_fitted() const override; // false, with the reason, when one of the paths can't be changed, its file not taking the changes back static bool tracks_editable(std::vector const &Tracks, std::string &Reason); void trim_history(); void restore_track_snapshot(EditorSnapshot const &Snapshot, std::vector &Opposite, bool const Undo); + // changes of the kept alignments and switches go into the last step of the history, made just before them + void records_to_history(); + // the paths a drag of the gizmo takes, to tell after it what became of the kept alignments and switches + struct record_watch + { + bool active{false}; + std::vector moving; + std::vector> before; // ends of the first path of each moving track + std::map> on; // the kept alignments and the moving paths on them + std::set whole; // the kept alignments all of whose paths move + } m_record_watch; + void records_watch_begin(); + void records_watch_end(); editor_track::point_ref m_track_point; std::vector m_track_drag; std::vector> m_track_drag_points; @@ -639,71 +1073,93 @@ class editor_mode : public application_mode, private editor_track::observer glm::dvec3 m_track_pivot{0.0}; glm::mat4 m_track_gizmo{1.0f}; bool m_track_gizmo_using{false}; + struct track_gizmo_drag + { + gizmo_operation operation{gizmo_operation::translate}; + bool control{false}; + double angle{0.0}; + int path{-1}; + bool atend{true}; + std::size_t pieces{1}; + std::vector paths; + editor_track::point_ref point; + glm::dvec3 origin{0.0}; + glm::dvec3 axis{0.0}; + double grabbed{0.0}; + double length{0.0}; + double stretch{0.0}; + std::vector> partners; + glm::dvec3 fixed{0.0}; + std::vector>> held; + std::vector extra; + int ring{-1}; + glm::dmat3 basis{1.0}; + glm::dvec3 pivot{0.0}; + double grade{0.0}; + double roll{0.0}; + double roll0{0.0}; + double pivot_chainage{0.0}; + std::vector chainages; + std::vector lengths; + struct switch_joint + { + TTrack *track{nullptr}; + editor_track::point_ref own; + editor_track::point_ref theirs; + glm::dvec3 point{0.0}; + glm::dvec3 tangent{0.0}; + double roll{0.0}; + bool moved{false}; + std::vector>> cluster; + std::vector>> joints; + }; + std::vector switches; + }; + track_gizmo_drag m_track_gizmo_drag; + gizmo_operation track_gizmo_operation(TTrack const &Track, bool const Pointmode) const; + glm::mat4 track_gizmo_frame(TTrack const &Track, bool const Pointmode, gizmo_operation const Operation) const; + void track_gizmo_hold(); + void track_gizmo_settle(); + void track_gizmo_stretch(TTrack &Track, double const Length); + void track_gizmo_control(TTrack &Track, glm::dvec3 Control); + void track_gizmo_point(TTrack &Track, glm::dvec3 const &Position); + void track_gizmo_switches(TTrack &Track); + void track_gizmo_conform(TTrack &Track) const; + bool track_gizmo_clustered(TTrack const *Track) const; + void track_gizmo_spill(TTrack &Track, std::size_t const Pieces); + void track_gizmo_carry(track_gizmo_drag::switch_joint &Link, glm::dvec3 const &Point, glm::dvec3 const &From, glm::dvec3 const &To, double const Grade); + void track_gizmo_roll_switch(track_gizmo_drag::switch_joint const &Link, double const Roll); + void track_gizmo_take_joints(TTrack &Track); + void track_gizmo_take_points(TTrack &Track); + void track_gizmo_take_partners(TTrack &Track); + void track_gizmo_take_switch_joints(TTrack &Track, bool const Controlmode); + track_gizmo_drag::switch_joint track_gizmo_link(TTrack &Track, editor_track::point_ref const &Own, std::pair const &Connection, std::function const &Movable); + void track_gizmo_take_switches(TTrack &Track); + // the other switch of a double switch and the track between them go with the moved or turned switch as a whole + void track_gizmo_take_double(TTrack &Track); + void track_gizmo_measure_rotation(TTrack &Track, bool const Pointmode); + void track_gizmo_measure(TTrack &Track, bool const Pointmode, gizmo_operation const Operation); + void track_gizmo_begin(TTrack &Track, bool const Pointmode, gizmo_operation const Operation); + void track_gizmo_turn_direction(TTrack &Track, double const Angle); + void track_gizmo_turn_grade(TTrack &Track, double const Angle); + void track_gizmo_turn_cant(TTrack &Track, double const Angle); + void track_gizmo_turn(TTrack &Track, int const Axis, double const Angle); + void track_gizmo_rotated(TTrack &Track); + void track_gizmo_scaled(TTrack &Track); + void track_gizmo_moved_point(TTrack &Track, glm::dvec3 const &Position); + void track_gizmo_length(TTrack &Track, double Length); + void track_gizmo_end(TTrack &Track); bool m_track_dirty{false}; bool m_track_drag_on_the_way{false}; // committed, but not as the end of the drag std::chrono::steady_clock::time_point m_track_last_commit; editor_track::state m_track_field_before; - std::array, 3> m_track_materials{}; - std::array m_track_material_edited{}; // path whose texture name is being typed - // typed names of the track circuits, the sleeper model and its skin, and the event to add, for the path - TTrack const *m_track_names_for{nullptr}; - std::array m_track_isolated{}; - std::array m_track_sleeper_model{}; - std::array m_track_sleeper_skin{}; + // the event to add to the path, typed + TTrack const *m_track_events_for{nullptr}; std::array m_track_event{}; int m_track_event_list{0}; std::string m_track_events_missing; - void render_path_circuits(TTrack &Track); + void render_path_events(TTrack &Track); std::string m_track_mode_notice; - // structure gauge along the line of the selected path, shown in the 3d view - struct gauge_state - { - bool open{false}; // window - bool enabled{true}; // tunnel along the selected path - std::vector profiles; - int profile{0}; // railway - int road{-1}; - TTrack const *track{nullptr}; // scanned - std::size_t history{0}; - bool pending{false}; // rescan once the edit ends - struct - { - std::vector surface; // triangles of the tunnel - std::vector edges; // lines - std::vector hits; - } line; // along the selected path - struct - { - bool scanned{false}; - std::size_t history{0}; - std::string profile; - std::vector hits; - } map; // whole scenery - struct - { - std::vector surface; - std::vector edges; - } spot; // tunnel around the hit the camera went to - int current{-1}; // hit the camera went to - bool published{false}; // overlay up to date - std::shared_ptr scan; // of the whole scenery, done in slices over the frames - } m_gauge; - void gauge_load(); - // the chosen railway and road outlines - gauge::choice gauge_choice() const; - std::vector const &gauge_hits() const; - void update_gauge(); - void scan_gauge(TTrack &Track); - void scan_gauge_map(); - void step_gauge_map(); - void finish_gauge_map(); - void gauge_publish(); - void gauge_focus(int Index); - void gauge_spot(gauge_hit const &Hit); - void render_gauge_window(); - void render_gauge_hits(); - bool render_gauge_choice(char const *Label, int &Index, bool Road); - bool render_gauge_outline(int Index); struct route_design { TTrack *from{nullptr}; @@ -716,21 +1172,187 @@ class editor_mode : public application_mode, private editor_track::observer int vertex{-1}; int grip{-1}; bool single{true}; // one curve between its straights, instead of the whole line + bool relaying{false}; // the crossovers of the line were taken out, they go back once it's laid + // crossovers taken out with a line which didn't fit it laid again, tried again as the other lines are laid + struct crossover_out + { + int shape{-1}; + glm::dvec3 press{0.0}, release{0.0}; + std::string name; + std::vector names; // of the switches at the press and at the release + }; + std::vector crossovers_out; + double origin{0.0}; // km of the start, m + int designed{0}; // vertices whose parameters came from the alignment kept in the scenery + int departed{-1}; // alignment kept in the scenery near the fragment, which its paths no longer follow + double departure{0.0}; + // the band of the curvature in the panel: the element under the mouse, the point of it, and what's dragged in it + struct curvature_band + { + int hot{-1}; + double at{-1.0}; + int vertex{-1}; + int part{0}; // 1 the radius, 2 the transition in, 3 the transition out, 4 the transition between two arcs of a compound curve + int arc{0}; // the arc of a compound curve the radius is of, 0 the first; of a transition between arcs the one after it + double value{0.0}; + ImVec2 press{0.0f, 0.0f}; + float metres{1.0f}; // pixels of a metre and of a unit of the curvature, kept as the drag goes + float curvature{1.0f}; + } band; + // the part of a curve whose field the mouse is over in the panel, or which is being edited there, shown in the view + struct curve_focus + { + enum class part + { + whole, + entry, + exit, + arc, // of the radius `arc`, the first one 0 + between // the transition leading into the arc of the radius `arc` + }; + int vertex{-1}; + part what{part::whole}; + int arc{0}; + bool held{false}; // by a field being edited, the mouse over the others doesn't move it + } focus; + // the points clicked when the fragment was laid, kept with its design: the curves keep to them as their transitions and cants + // change, while hold is on + std::vector clicks; + bool hold{true}; + struct click_state + { + double offset{0.0}; // from the line, m + int vertex{-1}; // whose curve it's a point of + bool corner{false}; // a bend of straights clicked, the vertex itself rather than a point of its curve + }; + std::vector click_states; // as the line was at the revision measured + int revision{0}; // of the result, counted as it's computed + int measured{-1}; + // points clicked along the middle of the track seen on the orthophoto, the radii of the curves and their shares fitted to them after each click + struct trace_state + { + bool active{false}; + int radii{0}; // 0: as many as the points need, up to three + std::vector points; + alignment::design before; // taken back by Esc + double rms{0.0}; + double worst{0.0}; + } trace; }; void render_route_ui(); + bool render_route_band(); bool render_route_parameters(); bool render_route_vertices(); bool render_route_vertex(int const Index); void render_route_result(); + void render_route_trace(); + // the camera over the stretch of the line between the chainages, a curve seen whole + void route_show_curve(double const From, double const To); + // the departures of the points clicked from the line and the curves they belong to, measured again when the line changed + void route_measure_clicks(); + // the points clicked along the curve of the vertex, in the plan, the bends of straights left out + std::vector route_clicks_of(int const Vertex) const; + // the radii of the curve of the vertex fitted again to the points clicked along it, its transitions and cants as they are + bool route_hold_clicks(int const Vertex); + // the elements of the part of the curve in focus in the panel, in their order along the line + std::vector route_focused() const; + void route_trace_start(); + void route_trace_fit(); + void route_trace_end(bool const Keep); + int route_trace_hit() const; + glm::dvec3 route_trace_cursor() const; void route_reset(); void route_bind_ends(); bool route_from_curve(TTrack &Track); bool route_from_line(TTrack &Track); + // the first curve of the design and the last one going on from the curves of the tracks adjoining, where they turn their way: a + // curve cut by a switch bent into it, say. Lays the design + void route_curved_ends(); alignment::vertex route_vertex_of(editor_track::curve const &Curve) const; - bool route_load(TTrack &Track) { return m_route.single ? route_from_curve(Track) : route_from_line(Track); } - void route_update() { m_route.result = alignment::compute(m_route.design); } + bool route_load(TTrack &Track); + void route_read_stored(TTrack &Track); + void route_take_stored(int const Index); + void record_switch(TTrack &Track, editor_track::switch_template const &Shape); + void record_double(TTrack &First, TTrack &Second, editor_track::switch_template const &Shape); + // the two switches of a double switch and the plain track between them, found from any of the three + struct double_switch + { + TTrack *first{nullptr}; + TTrack *link{nullptr}; + TTrack *second{nullptr}; + }; + std::optional double_of(TTrack const &Track) const; + // a slip of the scenery the track is a part of: its switches, all its tracks, the switches among them, and its ends where it joins + // the tracks around, A and B of its first track through, C and D of the other one, with the way into the slip at each + struct slip_set + { + switch_store::record record; + std::vector switches; + std::vector parts; + std::array ends{}; + std::array into{}; + }; + std::optional slip_of(TTrack const &Track) const; + // the two tracks of the slip through it from end to end, as they cross where it's taken out + static std::array slip_throughs(slip_set const &Slip); + // the slip taken out with its record, nothing of it put in the history yet; with Throughs its two tracks laid crossing in its + // place, given back + std::vector slip_taken_out(slip_set const &Slip, bool const Throughs); + // the record of the crossing of two plain tracks the track is one of + std::optional crossing_record(TTrack const &Track) const; + // the paths of the set in the order editor_track::place_switch gives them + static std::vector double_paths(double_switch const &Set); + // the switch of the template, or the two switches of a double one with the plain track between them, committed and recorded + std::vector create_switch_set(editor_track::switch_template const &Shape, std::vector const &Paths, TTrack const &Style, std::string const &Name); + // with no Style, as the lay tool lays its tracks + std::vector create_switch_set(editor_track::switch_template const &Shape, std::vector const &Paths, TTrack const *Style, std::string const &Name); + void record_slip(std::vector const &Parts, std::string const &Kind, std::string const &Type, double const Radius, double const Angle, std::string const &Base, double const Middle = 0.0); + void render_switch_record(TTrack const &Track) const; + void route_store(); + bool digitize_drawn(std::vector const &Created, bool const Alone = true) override; + bool digitize_chain(editor_track::chain const &Chain, std::string *Reason = nullptr, TTrack **Culprit = nullptr); + int digitize_parts(editor_track::chain const &Chain, std::string *Reason, int &Skipped); + // the lines kept, the paths left out + void digitize_all(int *Kept = nullptr, int *Failed = nullptr); + // what the digitization of the scenery did, or would do + struct digitize_report + { + int lines{0}; + int lines_failed{0}; + int switches{0}; + int known{0}; // kept in the scenery already + int designed{0}; // of a template of the catalogue + int measured{0}; + int slips{0}; + int unnamed{0}; // no record finds them + int odd{0}; + int recorded{0}; + int crossovers{0}; + int crossovers_known{0}; + int crossovers_recorded{0}; + int crossovers_odd{0}; + int found{0}; + int bound{0}; + std::map types; // of the catalogue + std::map shapes; // measured + std::vector notes; + }; + // the switches without a type kept get the one of the catalogue they are of, or the size measured from their shape + void digitize_switches(digitize_report &Report, bool const Write); + // two switches facing each other from two tracks, their diverging tracks joined by a plain one, are kept as a crossover + void digitize_crossovers(digitize_report &Report, bool const Write); + // the lines, the switches, the crossovers and the objects along the tracks at one go; without Write only counts them + std::string digitize_scenery(bool const Write); + void render_route_stored(); + void route_update() + { + m_route.design.norms.checked = true; + m_route.result = alignment::compute(m_route.design); + ++m_route.revision; + } void route_apply(); - bool route_relay_through_switches(editor_track::chain const &Chain, std::vector> &States, std::vector &Created); + void route_lay(); + bool route_relay_through_switches(editor_track::chain const &Chain, std::vector> &States, std::vector &Created, TTrack *&Last); void route_recommend(alignment::vertex &Vertex) const; void draw_route_overlay() const; void render_route_gizmo(); @@ -760,9 +1382,9 @@ class editor_mode : public application_mode, private editor_track::observer bool fit_has_before{false}; bool fit_has_after{false}; std::vector> drag_states; + std::size_t drag_step{0}; glm::dvec3 preview_start{0.0}; glm::dvec3 preview_end{0.0}; - glm::mat4 gizmo{1.0f}; glm::dvec3 edit_start{0.0}; glm::dvec3 edit_end{0.0}; double edit_length{0.0}; @@ -772,17 +1394,16 @@ class editor_mode : public application_mode, private editor_track::observer bool auto_transitions{true}; double transition{0.0}; int tool{0}; + int tool_before{0}; bool tool_mouse{false}; std::vector detour; editor_track::straight detour_line; glm::dvec3 detour_mouse{0.0}; bool tool_placed{false}; - bool tool_dragging{false}; double tool_at{0.0}; glm::dvec3 tool_point{0.0}; glm::dvec3 tool_handle{0.0}; editor_track::straight tool_line; - glm::mat4 tool_gizmo{1.0f}; std::string status; }; void render_straights_ui(); @@ -794,11 +1415,10 @@ class editor_mode : public application_mode, private editor_track::observer void straights_apply(std::vector const &Lines, std::vector> const &Ends); bool in_straight_set(editor_track::straight const &Line) const; bool place_straight_tool(); - void render_straight_tool_gizmo(); void apply_straight_tool(); double straight_tool_radius(editor_track::straight const &Line) const; void straight_reshape(editor_track::straight const &Line, double const From, double const To, std::function const &Tail, double const Radius); - void straight_refresh(); + void straight_refresh() override; bool start_curve_fit(editor_track::straight const &Line, int const Handle); void update_curve_fit(glm::dvec3 const &Start, glm::dvec3 const &End); void add_detour_point(); @@ -829,9 +1449,35 @@ class editor_mode : public application_mode, private editor_track::observer float roll{0.f}; float radius{0.f}; }; + // the line leaving an end of a switch off its main straight, taken before the switch moves: its paths up to the end of + // the straight past the curve next to the switch. When the switch moves only the paths up to a joint on that straight + // are laid again, so the curve keeps to the end of the switch and the rest of the network stays where it is + struct switch_branch + { + std::size_t joint{0}; + editor_track::chain chain; + std::size_t straight{0}; // the first path of the straight past the curve + alignment::design design; // as the paths lie + alignment::result result; + // made for the new end of the switch + editor_track::chain part; // the paths laid again + std::vector pieces; + alignment::design laid; // of the whole chain + double factor{1.0}; // of the radius and the transitions of the curve + }; struct switch_tool { + std::vector keep_names; // the names the switches laid next take, before the ones of the tool + std::string keep_slip; // the name the slip or the crossing laid next takes, of the one it's laid in place of bool curved{false}; + // a switch placed where there's no track: started on the ground, or at the free end it goes on from in its direction; the direction + // of its main track taken from the drag once it's long enough, then the drag sideways gives the side of the diverging one + bool free{false}; + editor_track::snap_target free_end; + std::optional free_heading; + // from a free end, dragged on past its end: bent, its diverging track turning the other way than the main one, the same way with + // Tab (one-sided) + bool one_sided{false}; std::vector frame; std::vector frame_tracks; std::vector templates; @@ -839,7 +1485,10 @@ class editor_mode : public application_mode, private editor_track::observer int armed{-1}; int last{0}; // template armed the last time bool placing{false}; + // where it was pressed on the screen: let go no farther from there, the press places nothing, a click doesn't lay a switch by chance + glm::vec2 pressed_at{0.f}; double along{0.0}; + double pressed{0.0}; // along a curve: where the press was, the start of the switch drawn from it to the ends of the cant ramps glm::dvec3 point{0.0}; glm::dvec3 mouse{0.0}; editor_track::straight line; @@ -849,18 +1498,163 @@ class editor_mode : public application_mode, private editor_track::observer { std::string name; std::array files; + std::array heights{}; + bool preferred{false}; }; std::vector drives; - bool drives_scanned{false}; + int drives_revision{-1}; // of the include bank the drives were read from int drive{-1}; int drive_side{0}; + struct slide_state + { + bool active{false}; + TTrack *track{nullptr}; + glm::vec2 pressed{0.f}; + double grip{0.0}; + double low{0.0}; + double high{0.0}; + double distance{0.0}; + double length{0.0}; + std::vector joints; + // the lines leaving the switch off its straight: the joint they leave at, the path of the switch in the shown ones + struct branch_line + { + editor_track::joint joint; + std::size_t path{0}; + switch_branch branch; + }; + std::vector branches; + // a switch bent into a curve slides along it: the curve its main track and the tracks next to it make, where the switch + // starts on it; low and high the distances it may go back and on + std::vector frame; + double station{0.0}; + }; + slide_state slide; + double slide_typed{0.0}; + int connection{-1}; + int connection_kind{0}; // the kind of connection chosen last, taken again when the connections are chosen + std::string rail_pick{"60E1"}; // the rail whose templates are listed first where the track doesn't tell its rail + int connection_second{-1}; + double connection_radius{0.0}; + double connection_gap{6.0}; + bool connection_together{false}; + char connection_spacings[64]{"4.75;4.75;5.0"}; + double connection_stub{25.0}; + // the connection a switch dragged makes, as where it's let go tells it, in connection then: let go on the other track a + // crossover, across the tracks between them a ladder; by a crossover there already turned the other way a double crossover + // with it, over it a scissors one + bool recognised{false}; + TTrack *partner{nullptr}; // a switch of the crossover there already }; switch_tool m_switch; - void scan_switch_drives(); + // what the switch tool places: a switch into a straight or a curve, a slip switch or a crossing at a crossing of two + // straights, or a connection of tracks laid whole + enum class switch_kind + { + single, + slip, + crossing, + connection + }; + switch_kind current_switch_kind() const; + void choose_switch_kind(switch_kind const Kind); + bool switch_kind_offered(switch_kind const Kind) const; + bool plan_connection(connection::request &Request, connection::result &Result) const; + // what the drag of the switch being placed makes, from where the cursor is: sets connection and partner of the tool + void recognise_connection(); + // the double or the scissors crossover of the partner and the crossover dragged, on the lines of their tracks + bool plan_partner_connection(connection::request &Request, connection::result &Result) const; + void insert_partner_connection(); + // the switches and the inserts of the connection planned laid, one step of the history. false if they don't fit + bool lay_planned_connection(connection::request const &Request, connection::result const &Plan, TTrack *Style); + void insert_connection(); + void render_connection_options(); + // the name of a kind of connection of tracks, translated + static char const *connection_name(int const Kind); + // the name of a switch template for the lists: where it comes from and its name without the lengths + static std::string switch_template_label(editor_track::switch_template const &Template); + // the name of a switch template for the user: translated, with the speed on its diverging track + static std::string template_name(editor_track::switch_template const &Template); + // the template of the catalogue a record of the switches was laid of, -1 if none: Lengths compares a and b too, which the + // record of a connection keeps for its spacing; Movable: the nose of the frog, either when not given + int matching_template(switch_store::record const &Record, bool const Lengths, std::optional const Movable = std::nullopt) const; + // the template the switch was laid of, -1 if none: a switch of the scenery of its own shape, say + int switch_template_index(TTrack const &Switch) const; + // why the switch can't take another template here, empty when it can + std::string template_change_blocked(TTrack const &Switch) const; + // the template of the catalogue a slip or a crossing was laid of, of the rail before the others; -1 if none + int slip_template_index(switch_store::record const &Record, std::string const &Rail) const; + // the switch of the template of the index in place: its start and its side kept, the tracks it joins following; a switch of a + // crossover takes the crossover with it, laid again, a slip or a crossing is laid again where its tracks cross. One step of the + // history; the status says how it went + bool change_switch_template(TTrack &Switch, int const Index); + bool change_slip_template(TTrack &Part, int const Index); + // the switch, or the double switch it's a part of, given the shape in place, straight or bent into the curve it lies in; Flip: + // the diverging track to the other side. Notes: for the user + bool apply_switch_template(TTrack &Switch, editor_track::switch_template const &Shape, bool const Flip, std::string &Notes); + // the template to choose: the speeds on the diverging track as chips, the templates of the rail by their skos, all the others + // folded under. Fits: those of the kind wanted; Rail: of the track, empty when it doesn't tell; Popup: inside a combo, with no + // windows of its own. Gives the index picked, -1 while none is + int render_template_picker(char const *Id, std::function const &Fits, std::string const &Rail, int const Chosen, bool const Popup); + // the template of the selected switch, slip or crossing, changed with a pick: in a combo for the inspector, else in full; nothing + // for another track + void render_switch_template(TTrack &Track, bool const Combo); + std::string connection_readout(connection::result const &Plan) const; + editor_track::straight straight_near(glm::dvec3 const &Point, std::vector const &Exclude, double const Reach) const; + editor_track::straight straight_through(glm::dvec3 const &Point, glm::dvec2 const &Direction) const; + void record_connection(connection::kind const Kind, std::vector const &Switches, connection::result const &Plan, editor_track::switch_template const &Shape); + bool switch_room(TTrack &Track, double &Low, double &High, std::string &Reason); + bool switch_vacate(TTrack &Track, glm::dvec3 const &From, glm::dvec3 const &To, double const Shift, editor_track::straight const &Line, editor_track::edit &Edit, std::string &Status); + bool move_switch_paths(TTrack &Track, std::vector const &Paths, std::string &Status); + std::optional take_switch_branch(TTrack const &Track, editor_track::joint const &Joint, std::size_t const Index) const; + // for the path of the switch the line leaves, as it'll lie + bool plan_switch_branch(segment_data const &Path, editor_track::joint const &Joint, switch_branch &Branch) const; + void lay_switch_branch(switch_branch const &Branch, editor_track::edit &Edit); + // of the joints off the main straight of the switch, the neighbours in Skip left out + std::vector switch_branches(TTrack const &Track, std::vector const &Joints, std::vector const &Skip = {}) const; + // for the paths the switch has now; the joints of the branches which can be laid are handled, the others are left out. Gives the notes for the user + std::string plan_switch_branches(TTrack const &Track, std::vector const &Joints, std::vector &Branches, std::vector &Handled) const; + // room on the straight of the whole double switch along the axis of its first switch, and the length of the set + bool double_room(double_switch const &Set, double &Low, double &High, double &Length, std::string &Reason); + bool move_double_paths(double_switch const &Set, std::vector const &Paths, std::string &Status); + bool slide_switch(TTrack &Track, double const Distance); + bool switch_slides(TTrack const &Track) const; + // a slip slid along its first track: the slip and the tracks its crossing track goes on into with their ends free move whole, the + // straights of its first track before it and past it give and take the length. Low and High: how far back and on it may go + struct slip_slide + { + glm::dvec3 shift{0.0}; // along its first track, a metre of it + std::vector movers; + // where it joins the tracks of its first track before it and past it: at its ends A and B, or at the joints of its template + // with the straights out to them going along; those tracks, the end of each there + std::array joints{}; + std::array, 2> ends{}; + double low{0.0}; + double high{0.0}; + }; + bool slip_room(slip_set const &Slip, slip_slide &Slide, std::string &Reason) const; + bool slide_slip(slip_set const &Slip, double const Distance); + // a switch bent into a curve, its main track going on into a plain track at each end: the curve the three make, the two tracks, + // where the switch starts on it; false for any other + bool bent_switch_frame(TTrack const &Track, std::vector &Frame, std::array &Sides, double &Station) const; + // the paths of the switch moved along the curve by the distance, shaped as the curve is there + std::vector bent_switch_paths(TTrack const &Track, std::vector const &Frame, double const Station, double const Distance) const; + bool slide_bent_switch(TTrack &Track, double const Distance); + // the switch bent into a curve given the paths, along the curve of the bent_switch_frame: the tracks next to it laid along it up to + // its new ends, one taken up whole going, the curve past the diverging track following. Notes: for the user + bool lay_bent_switch(TTrack &Track, std::vector const &Frame, std::array const &Sides, std::vector const &Paths, std::string &Notes); + void switch_slide_start(TTrack &Track); + void switch_slide_update(); + void switch_slide_finish(); + void draw_switch_slide() const; + // reads the drives from the include bank once it changes; Wait: for the templates being looked for. true if it read them + bool scan_switch_drives(bool Wait = true); std::string switch_name_for_new() const; bool place_switch_drive(TTrack &Switch); + bool flip_switch_drive(TTrack &Switch); + void advance_switch_name(); + void join_last_steps(); bool render_switch_drive_choice(); - int m_turnout_template{0}; struct turntable_template { std::string file; @@ -886,7 +1680,7 @@ class editor_mode : public application_mode, private editor_track::observer struct turntable_tool { std::vector templates; - bool scanned{false}; + int revision{-1}; // of the include bank the templates were read from int chosen{-1}; char name[64]{}; bool placing{false}; @@ -912,7 +1706,7 @@ class editor_mode : public application_mode, private editor_track::observer std::string error; }; turntable_tool m_turntable; - void scan_turntables(); + bool scan_turntables(bool Wait = true); std::string turntable_name_for_new() const; bool turntable_read(TTrack *Table); std::vector turntable_includes(TTrack const &Table); @@ -941,47 +1735,252 @@ class editor_mode : public application_mode, private editor_track::observer editor_track::snap_target origin; editor_track::snap_target snap; glm::vec2 pressed{0.f}; + std::vector line; }; extend_tool m_extend; + // what a point clicked while laying is: a bend of the straights, eased with a large curve, or a point along the middle of a curve + // seen on the photo, the curve ending at the last of these + enum class lay_mode + { + straights, + curve + }; + // a curve traced on the photo as it's laid, how far the points clicked along it are from it + struct lay_trace + { + std::vector points; + std::vector offsets; + double rms{0.0}; + double worst{0.0}; + std::size_t curves{0}; + }; + // the line the points clicked make: its design, the bends among its vertices, the curves traced + struct lay_line_plan + { + alignment::design design; + alignment::result shape; + std::vector corners; + std::vector traces; + // the straights of a fixed direction the next bend slides along: from a free end, out of a curve traced + std::vector> guides; + // where the grade breaks from point to point: the bends kept as such, at the heights clicked; a curve traced, or bends made + // one curve, goes at one grade from end to end + std::vector knots; + }; // lays new track through the clicked points, with no path needed to start from struct lay_tool { bool active{false}; std::vector points; + std::vector modes; // of the points, as each was clicked + lay_mode mode{lay_mode::straights}; + int radii{0}; // of a curve traced: 0 as many as the points need, up to three + bool straights_between{true}; // a curve traced may be two with a straight between them + lay_line_plan plan; // of the line shown editor_track::snap_target start; // free end the track starts from, if any glm::dvec3 mouse{0.0}; editor_track::snap_target mouse_snap; std::vector preview; std::string preview_error; double preview_length{0.0}; + // the line worked out whole last, all its fits done: shown while the one of the cursor now still waits for them on the thread, + // so that the curves don't jump from one fit to the next as each comes + struct worked_out + { + std::vector preview; + std::string error; + double length{0.0}; + lay_line_plan plan; + std::optional eased; + alignment::join_result join; + std::vector points; // the ones clicked it was worked out for + }; + std::optional shown; + // the cursor the line is being worked out for, kept till all its fits are done: what it was worked out from + struct settling_cursor + { + glm::dvec3 mouse{0.0}; + editor_track::snap_target snap; + std::vector points; + std::vector modes; + lay_mode mode{lay_mode::straights}; + int edits{0}; + }; + std::optional settling; + bool whole{true}; // false: each fit shown as it comes, as before, for a selftest to compare double radius{500.0}; - bool transitions{true}; double piece_length{100.0}; bool copy_selected{false}; editor_track::path_style style; + bool own_speed{false}; // the speed of the style also where the track goes on from one with its own, the new tracks given it std::string status; + double status_time{-100.0}; + std::string skew; // what Alt turned the straight to + double escape_time{-100.0}; // when Esc was pressed over points not laid: the second Esc drops them + std::size_t history{0}; // the step of the history the track laid last was begun at }; lay_tool m_lay; + alignment::limits laying_norms() const; + glm::dvec3 lay_angle_snap(glm::dvec3 const &Mouse, std::string &Label) const; + // the straight track Alt turns the laid straight to: the nearest one the straight from From to To crosses, or one along From + TTrack const *skew_reference(glm::dvec3 const &From, glm::dvec3 const &To, double const Reach) const; + void lay_after_history(bool const Undo); + void lay_back(); + void lay_escape(); + std::size_t lay_pending() const; // the points clicked and not laid yet void render_lay_ui(); void render_lay_status(); void lay_click(); void lay_finish(editor_track::snap_target const &End); void lay_cancel(); void lay_enter(); - bool lay_heading(glm::dvec2 &Heading) const; - std::vector lay_pieces(std::vector const &Points, editor_track::snap_target const &End, double &Length, std::string &Error) const; - alignment::result lay_shape(std::vector const &Points, glm::dvec2 const &Startdirection, glm::dvec2 const &Enddirection, alignment::design &Design) const; + // Tab: the bends of straights or the curve traced, for the points clicked from now on + void lay_switch_mode(); + // the points the same in number as their modes, a point with none a bend of straights + void lay_trim(); + // the track through the points clicked, each the way its mode says; End: the free end it finishes at, the last point then + std::vector lay_pieces(std::vector const &Points, std::vector const &Modes, editor_track::snap_target const &End, double &Length, std::string &Error, + lay_line_plan *Plan = nullptr) const; + // Adjoining: the curve next to a free end on a curve goes on from its curvature, where it turns its way; else from a straight there + bool lay_line(std::vector const &Points, std::vector const &Modes, editor_track::snap_target const &End, lay_line_plan &Plan, std::string &Error, bool const Adjoining = true) const; + // whether the points next to the start of the line, or to its end, AtEnd, a free end joined there, are clicked along a curve + static bool traced_from(std::vector const &Points, std::vector const &Modes, bool const AtEnd); + // the curves of a stretch traced, the ones fitted lately kept for the same points + // none while the stretch the cursor moves along is still being fitted; Meanwhile: the fit done last of the same points but the one + // at the cursor until then + // Exact receives whether the fit is the one of these points, not one shown meanwhile; Going: the curve going on from the curve of the + // free end Base starts at, alignment::fit_going_on + std::optional traced_stretch(alignment::design const &Base, std::vector const &Points, int const Radii, bool const Straights, bool const Meanwhile = true, + bool *Exact = nullptr, bool const Going = false) const; + // the curve through a row of bends clicked close along one, by traced_stretch + alignment::stretch_fit bends_fit() const + { + return [this](alignment::design const &Base, std::vector const &Points) { return traced_stretch(Base, Points, 0, false, false); }; + } + mutable std::vector, alignment::trace_stretch>> m_stretch_cache; + // the stretch the cursor moves along is fitted on a thread, the frames drawn meanwhile with the fit done last + mutable alignment::stretch_fitter m_stretch_fitter; + // a fit the line asked the thread for isn't done yet: the line is one of the fits meanwhile + mutable bool m_fits_waiting{false}; + // how much more the curve at the cursor was turned last to reach it, the first one tried for the next line + mutable double m_turned_last{0.0}; void render_switch_ui(); + void render_switch_timbers(); + void render_rail_profile_hint(TTrack &Track); bool start_switch_placement(); void finish_switch_placement(); + // a switch with no track under it: a press on the ground starts it at the free end of a track within reach, none with no free end near + editor_track::snap_target free_switch_end(glm::dvec3 const &Ground) const; + bool free_switch_offered() const; + void start_free_switch(glm::dvec3 const &Ground); + // the start of the switch, the way its main track goes and the side of its diverging one, as the drag gives them so far + void free_switch_pose(glm::dvec3 &Start, glm::dvec2 &Heading, int &Side, double &Grade) const; + // a switch laid on from a free end, dragged on past its end: bent, its main track turning toward the cursor + struct free_bend + { + double radius{0.0}; // of the main track + int turn{1}; // the way the main track turns, 1 to the left + int side{1}; // of the diverging track + std::vector frame; // the curve the switch is bent into + std::vector paths; + switch_curve::switch_report report; + // a free end the cursor is at, which the main track leads into, the diverging one with Shift + editor_track::snap_target target; + bool diverging{false}; + editor_track::branch_link link; + std::string problem; // why it can't lead into the target + }; + // false where it isn't bent: near the switch, along the straight, or not from a free end + bool free_switch_bend(free_bend &Bend) const; + bool free_switch_bend_now(free_bend &Bend) const; + // laid on from an end of a switch: what the norms say of the change of the curvature from that switch to the tracks of this one + std::vector free_switch_exits(std::vector const &Paths) const; + std::vector free_switch_paths() const; + void insert_free_switch(); std::vector switch_preview() const; + std::vector switch_preview_now() const; + // where a switch can't go, or doesn't go where it's dragged: what's in the way blinking in the view, each point told what's there, + // why by the cursor; while it's dragged, and a while after it's refused + struct switch_problem + { + std::string text; + std::vector paths; + std::vector> marks; + }; + // what's at the end of the straight: a curve beginning, a switch, the track ending + std::string straight_end_note(editor_track::straight const &Line, bool const Far) const; + std::optional switch_drag_problem() const; + std::optional straight_switch_problem(editor_track::straight const &Line, double const Length, double const Along, int const Direction) const; + void flash_switch_problem(switch_problem Problem); + void flash_switch_problem(std::string const &Text, std::vector Paths, std::vector> Marks = {}); + void draw_switch_problem(switch_problem const &Problem) const; + switch_problem m_switch_flash; + double m_switch_flash_until{-1.0}; + // a preview worked out once a frame for the drawing and the readouts which all show it: the frame and the state of the tool it + // was worked out for + template struct frame_memo + { + int frame{-1}; + std::vector key; + Result result{}; + bool fresh(std::vector const &Key) const { return frame == ImGui::GetFrameCount() && key == Key; } + void keep(std::vector Key, Result const &Value) + { + frame = ImGui::GetFrameCount(); + key = std::move(Key); + result = Value; + } + }; + std::vector switch_memo_key() const; + mutable frame_memo> m_switch_memo; + mutable frame_memo> m_bend_memo; + mutable frame_memo> m_extend_memo; void insert_switch(editor_track::straight const &Line, double const Along, int const Direction, int const Side); void switch_placed(std::vector const &Created); static std::vector sample_chain(editor_track::chain const &Chain); static curve_sample sample_at(std::vector const &Frame, double const Station); + // the curve a switch goes into as the norms look at it: its headings and its cant along it + std::vector frame_points(std::vector const &Frame) const; + // the way the switch being placed into a curve goes along it and the side its diverging track leaves to, from the drag + void curved_switch_pose(int &Direction, int &Side) const; + // the start of the switch being placed into a curve: where it was pressed, drawn to where the switch meets an end of a cant ramp or + // keeps 6 m off it; What receives which + double curved_switch_start(int const Direction, std::string *What = nullptr) const; + // the switch made of the paths, laid into the curve at the station, as ST-T1-A6 sees it + switch_curve::switch_report curved_switch_report(std::vector const &Paths, std::vector const &Frame, double const Station, int const Direction) const; static double nearest_station(std::vector const &Frame, glm::dvec3 const &Point); static std::vector curved_switch_paths(editor_track::switch_template const &Shape, std::vector const &Frame, double const Station, int const Direction, int const Side); + // the path of a switch template laid into the curve: x of the template across the main track to the Side, z along it from the + // Station on, going Direction along the curve; past Bent along it going on straight as the curve heads there. The heights and the + // cant are those of the line where the point is along it + static segment_data frame_path(segment_data const &Local, std::vector const &Frame, double const Station, int const Direction, int const Side, std::optional const &Bent = std::nullopt); void insert_curved_switch(int const Direction, int const Side); + // a crossover between two tracks running side by side along a curve (editormodeconnectioncurve.cpp) + struct curve_mapping; + // Beyond: the straights past the ends of the curve go with it up to that far, and a straight track that near the curve is taken + // as its part + static bool curve_of(TTrack &Track, editor_track::straight_tolerance const &Tolerance, double const Gauge, std::vector &Frame, std::vector &Tracks, double const Beyond = 0.0); + static void cut_curve(std::vector &Candidates, std::vector const &Frame, glm::dvec3 const &First, glm::dvec3 const &Second, std::vector> &States, std::vector &Created, std::vector &Removed); + void insert_curved_connection(); + struct curved_crossover + { + switch_store::record record; + TTrack *first{nullptr}; + TTrack *second{nullptr}; + TTrack *insert{nullptr}; + }; + // the single crossover the switch is a part of, along a curve or straights + std::optional crossover_of(TTrack const &Switch) const; + bool take_out_crossover(curved_crossover const &Crossover, std::vector> &States, std::vector &Created, std::vector &Removed, TTrack *&First, TTrack *&Second); + bool slide_curved_connection(TTrack &Switch, double const Distance, int const Shape = -1); + // the template a crossover was laid of, -1 if it's not among the templates + int crossover_template(switch_store::record const &Record); + // a crossover laid again from the press on one track to the release by the other, as by the mouse. false if it doesn't fit + // Names: of the switch at the press and of the one at the release, kept when a crossover is laid again + bool lay_crossover(int const Shape, glm::dvec3 const &Press, glm::dvec3 const &Release, double const Reach = 3.0, std::vector const &Names = {}); + // after the grade line of the open route went on its paths: the line on the other side of each crossover of the route + // takes the same change of the heights where it runs beside, and its design with it. returns: how many lines followed + std::size_t follow_crossovers(std::vector const &Before); bool place_switch_on_straight(editor_track::straight const &Line, editor_track::switch_template const &Shape, TTrack const *Style, double const Along, int const Direction, int const Side, bool const Snap, std::vector> &States, std::vector &Created, std::vector &Removed, std::string const &Name = {}); struct crossover_plan { @@ -990,17 +1989,104 @@ class editor_mode : public application_mode, private editor_track::observer double along{0.0}; int direction{1}; int side{1}; - segment_data insert; + std::vector inserts; // a straight one, or an aligning curve between straights onto a track not parallel std::vector paths; + connection::result connection; // as it's kept with the two switches }; bool plan_crossover(crossover_plan &Plan) const; + struct switch_link + { + editor_track::snap_target target; + editor_track::branch_link link; + double along{0.0}; + int forward{1}; + int side{1}; + double moved{0.0}; + std::vector paths; + std::string reason; + }; + bool plan_switch_link(switch_link &Plan) const; + void insert_linked_switch(switch_link const &Plan); + bool plan_branch_link(editor_track::branch_link &Link, std::string &Reason) const; + void finish_branch_link(editor_track::branch_link const &Link); + std::string link_problem(editor_track::snap_target const &Target, editor_track::branch_link const &Link) const; + bool stretchable(editor_track::snap_target const &Target) const; + std::vector link_tracks(editor_track::snap_target const &Target, editor_track::branch_link const &Link, TTrack const &Style, std::vector> &States, std::vector &Created); bool cut_straight(editor_track::straight const &Line, double const From, double const To, std::vector> &States, std::vector &Created, std::vector &Removed, TTrack **Style); - bool insert_double_slip(editor_track::straight const &Line, glm::dvec3 const &Point, editor_track::switch_template const &Shape); + // where a slip or a crossing goes for the cursor at Point on the straight Line: the crossing of Line with the rail track + // nearest the cursor, or the double slip there to be replaced. With no track crossing there and Side given (1 to the left, -1 to + // the right of Line), the slip brings the crossing track along at its own angle, turning off to that side ahead + struct slip_plan + { + std::string problem; + std::string note; + bool lone{false}; // no track crosses Line by the cursor + TTrack *replaces{nullptr}; + TTrack *other{nullptr}; // the crossing track, none where the slip brings it along + glm::dvec2 crossing{0.0}; + glm::dvec2 first{0.0, 1.0}; + glm::dvec2 direction{0.0, 1.0}; + double angle{0.0}; + double alongfirst{0.0}; + double half{0.0}; + // where the slip brings its crossing track along: from the crossing to the joints of its template, past the frogs of the diamond, + // the straights of both tracks laid out that far; the ends of the straights there, in the order of the points + double reach{0.0}; + std::array ends{}; + editor_track::slip_curve curve; + std::array points{}; + }; + bool plan_double_slip(editor_track::straight const &Line, glm::dvec3 const &Point, editor_track::switch_template const &Shape, slip_plan &Plan, int const Side = 0) const; + // a slip is made for its skos: where the tracks cross at another one, the refusal, which tells the template made for theirs; empty + // where it fits, and for a crossing + std::string slip_skew(editor_track::switch_template const &Shape, double const Angle) const; + // the cursor where it points at the straight, at the height of the straight there + glm::dvec3 cursor_on_straight(editor_track::straight const &Line) const; + bool insert_double_slip(editor_track::straight const &Line, glm::dvec3 const &Point, editor_track::switch_template const &Shape, int const Side = 0); + // the side a slip dragged out on a straight with no track crossing it brings its crossing track to: the one through the quarter of + // the cursor + int lone_slip_side() const; bool replace_double_slip(TTrack &Part, editor_track::switch_template const &Shape); - std::vector build_double_slip(glm::dvec3 const &PointA, glm::dvec3 const &PointB, glm::dvec3 const &PointC, glm::dvec3 const &PointD, glm::dvec2 const &Crossing, double const Height, glm::dvec2 const &First, glm::dvec2 const &Second, double const Angle, double const Radius, TTrack &Style); + // Bend: what a path of the slip laid out as on straights turns into where it's bent into a curve + std::vector build_double_slip(glm::dvec3 const &PointA, glm::dvec3 const &PointB, glm::dvec3 const &PointC, glm::dvec3 const &PointD, glm::dvec2 const &Crossing, double const Height, glm::dvec2 const &First, glm::dvec2 const &Second, double const Angle, editor_track::slip_curve const &Curve, TTrack &Style, std::string const &Type = "Rkpd", + std::function const &Bend = {}); + // a slip switch bent into a curve of a side track (ST-T1-A6 11.4 pkt 4b): laid out on the tangent to the curve at its crossing, where + // it was pressed, and bent onto the curve as a switch laid into it is, its crossing track coming along with its ends free. Direction + // and Side as of a switch dragged into a curve: the crossing track goes ahead to that side, through the quarter of the cursor, and the + // slip curve of a single slip lies on that side + struct curved_slip + { + std::string problem; + std::string snapped; // what the ends of the slip were drawn to + double middle{0.0}; // the station of the crossing along the curve + double half{0.0}; // from the crossing to the ends of the slip + double reach{0.0}; // from the crossing to the joints of the template, the straights of both tracks laid out that far + int direction{1}; + double angle{0.0}; + editor_track::slip_curve curve; + // as the slip is laid out on the tangent, before it's bent: its crossing, its tracks going Direction along the curve, its ends + glm::dvec2 crossing{0.0}; + glm::dvec2 first{0.0, 1.0}; + glm::dvec2 second{0.0, 1.0}; + std::array points{}; + }; + bool plan_curved_slip(editor_track::switch_template const &Shape, int const Direction, int const Side, curved_slip &Plan) const; + // the path of the slip laid out on the tangent, bent onto the curve + segment_data bent_slip_path(curved_slip const &Plan, segment_data const &Path) const; + // the two tracks through the slip and its slip curves, each from end to end, bent: the first track, the slip curve leaving it at its + // start, the second track, the other slip curve of a double slip + std::vector curved_slip_lines(curved_slip const &Plan, std::string const &Type) const; + // the straights of both tracks from the ends of the slip out to the joints of the template, bent + std::vector curved_slip_reaches(curved_slip const &Plan) const; + switch_curve::slip_report curved_slip_report(curved_slip const &Plan, std::string const &Type) const; + // the radii of the slip and its cant, as the view and the status tell them + static std::vector slip_report_lines(switch_curve::slip_report const &Report); + void insert_curved_slip(int const Direction, int const Side); bool start_extend(editor_track::snap_target const &End); void finish_extend(); std::vector extend_pieces() const; + // the same for the track shown while it's dragged: its grade line fitted on the thread of the fitter, the frame not waiting for it + std::vector extend_preview() const; // the free end of the path as the start of a new track; false if it isn't free or has no direction static bool free_end(TTrack &Track, int const Path, bool const Atend, extend_tool &Tool); // the free end new pieces are added at: the selected point if it's one, else the end, else the start @@ -1008,33 +2094,120 @@ class editor_mode : public application_mode, private editor_track::observer // adds a straight (Side 0) or a curve to the left (1) or the right (-1) at the free end of the selected track void extend_add(int const Side); void render_extend_ui(); - bool m_extend_freehand{false}; // dragging the ring of a free end draws a curve through the cursor, not a straight + using track_layout = editor_track::layout; + // the shape dragged from a free end, as the mode of laying has it: a straight in the one of the straights, an arc and a straight in + // the one of a curve + track_layout m_track_layout{track_layout::straight}; + double m_join_radius{0.0}; + int m_join_variant{0}; + TTrack const *m_join_track{nullptr}; + editor_track::point_ref m_join_point; + mutable alignment::join_result m_join_last; + // the layout laid on from the end of From with the transition curves of the norms; none where it doesn't fit + std::optional eased_layout(TTrack const *From, glm::dvec3 const &Point, glm::dvec2 const &Direction, glm::dvec3 const &Target, double const Radius) const; + mutable std::optional m_eased_last; + mutable std::optional>> m_eased_cache; + bool track_wheel(double const Offset); + // a touchpad sends fractions of a notch: a choice moves a step for each whole notch gathered, and only one in a gesture when + // Gesture; a pause, another key or the other way starts over + struct wheel_state + { + double rest{0.0}; + double time{-10.0}; + int keys{0}; + bool spent{false}; + }; + wheel_state m_wheel; + int wheel_step(double const Offset, bool const Gesture); + std::string track_shaping(bool const Joined) const; + double design_speed(TTrack const *From, TTrack const *To) const; + // the track whose speed the design takes, none where it's the one set for the laying + TTrack const *speed_track(TTrack const *From, TTrack const *To) const; + // the tracks the laying under way goes on from and to + std::pair laying_ends() const; + std::string design_speed_of(TTrack const *From, TTrack const *To) const; + // what ST-T1-A6 says of the sudden changes of the cant deficiency right behind a switch the pieces laid come out of at Start (From), + // or go into at End (To): of the end of its curve and the first sudden change of the pieces (9.11, tables 9.15, 9.16) + std::vector switch_exit_warnings(TTrack const *From, glm::dvec3 const &Start, TTrack const *To, glm::dvec3 const &End, std::vector const &Pieces) const; + void give_own_speed(std::vector const &Created) const; + std::vector join_pieces(TTrack const *From, editor_track::point_ref const &Frompoint, glm::dvec3 const &Start, glm::dvec2 const &Direction, editor_track::snap_target const &End, double &Length, + std::string &Error) const; double m_extend_length{25.0}; double m_extend_radius{300.0}; bool extend_snap(editor_track::snap_target &Target) const; void update_build_tools(); void draw_build_overlay() const; + // the joint before the blades of the switch being placed or the one selected and the tips of its blades + void draw_blade_tips() const; // modes of the track editor, one at a time: path is the plain selection - enum class track_tab { straights, route, path, turnout, profile, speed, joints, infra, lay, lineside, turntable, signals }; + using track_tab = editor_track_tab; struct track_mode { char const *label; char const *key; track_tab tab; char const *tooltip; + editor_icons::icon picture; + int family; // 0 builds the track, 1 equips it, 2 checks it }; - static std::array const &track_modes(); + static std::array const &track_modes(); + bool track_plan_tab() const { return m_track_tab == track_tab::straights || m_track_tab == track_tab::route; } + // a tool of the station: they share its schematic + bool srk_tab() const { return m_track_tab == track_tab::station || m_track_tab == track_tab::station_signals || m_track_tab == track_tab::line_block; } + track_tab plan_tab_for(TTrack const *Track) const; // the objects along the track: a tab for each tool int m_lineside_tab{0}; void render_lineside_ui(); void arm_switch(); + // the window of the switch templates: the catalogue and the own ones, made of straights, arcs and transition curves + struct switch_designer + { + bool open{false}; + bool loaded{false}; + std::vector catalogue; + std::vector own; + bool from_catalogue{true}; + int selected{-1}; + bool dirty{false}; + bool stretched{true}; + double quick_radius{300.0}; + double quick_ratio{9.0}; + double quick_a{0.0}; + double quick_b{0.0}; + int fit_kind{3}; // of switch_design::tangent_fit + double quick_first{0.0}; // the radius of the first arc of an arc, a straight and an arc, 0: the R + bool picking{false}; // the switch clicked off the view, the orthophoto under it + std::vector clicks; + bool on_view{true}; // the template shown in the view where its first points were clicked + switch_design::design measured; // what the points clicked so far make + bool measured_ready{false}; + std::string measured_text; + int pointed{-1}; // the value under the mouse, its dimension shown on the drawing + int pointed_test{-1}; + double blade_length{5.0}; + double blade_gap{0.15}; + std::string status; + }; + switch_designer m_switch_designer; + void switch_designs_load(); + // the list of the switch tool built again with the own templates, keeping the armed one or arming the one whose label starts with Arm + void switch_templates_refresh(std::string const &Arm = {}); + void render_switch_designer(); + void switch_designer_click(glm::dvec3 const &Point); + void switch_designer_measure(); + void switch_designer_finish(); + void draw_switch_designer_clicks() const; + void draw_cursor_ring(glm::dvec3 const &Point) const; + static std::string grade_line_key(TTrack const &Track); + static std::string grade_line_key(std::string const &Name, TTrack const &Track); + static void move_path_heights(segment_data &Path, double const First, double const Second, std::function const &After = {}); bool m_track_window_open{false}; // the inspector is pinned to the right edge of the screen, the profile strip to the bottom one, both resized from the inner edge void render_track_inspector(); // the track tools in the tool options window, and the selected path in the inspector void render_track_tool_options(); void render_track_selection(); - void show_track_tab(track_tab const Tab); + void show_track_tab(track_tab const Wanted) override; bool track_analysis_tab() const { return m_track_tab == track_tab::profile || m_track_tab == track_tab::speed || m_track_tab == track_tab::joints || m_track_tab == track_tab::infra; } bool track_shortcut(int const Key); bool track_busy() const; // something going on in the mode, which Esc drops before it leaves the mode @@ -1050,10 +2223,15 @@ class editor_mode : public application_mode, private editor_track::observer }; track_name_edit m_track_name; void render_track_name(TTrack &Track); - void render_path_parameters(TTrack &Track); void render_straight_ui(); track_tab m_track_tab{track_tab::path}; void delete_selected_track(); + // the switch thrown over to its other path in the editor, its blades going over as in the simulation; the scenery keeps no state of it + void throw_switch(TTrack &Switch); + // the blades of the switches thrown in the editor moved on by the time of the frame: the time of the simulation stands still in it + void move_thrown_switches(); + std::vector m_thrown_switches; + std::string designs_trimmed(std::vector const &Removed); void start_straight_gesture(int const Tool); void finish_straight_gesture(); void toggle_straight_set(TTrack &Track); @@ -1061,26 +2239,31 @@ class editor_mode : public application_mode, private editor_track::observer { char const *key; std::string action; + char const *raw{nullptr}; // the key before it's translated, its gesture drawn from it }; std::vector track_key_hints(bool const All) const; void render_track_guide(); std::string track_readout() const; void draw_track_hints(); + // a scenery with no tracks yet: in the middle of the view, how the first one is laid + void draw_empty_scenery_hint(); // path under the cursor, outlined before a click so it's known which one the click takes - struct track_hover - { - TTrack *track{nullptr}; - int path{0}; - glm::dvec3 point{0.0}; - double since{0.0}; - }; track_hover m_hover; - track_hover track_under_cursor() const; + track_hover track_under_cursor(TTrack const *Only = nullptr, float const Pixels = 0.0f) const; + track_hover split_spot() const; void update_track_hover(); + void draw_track_lines() const; + // what the colours of the tracks in the view tell + enum class track_colouring { plain, radius, speed, grade }; + track_colouring m_track_colouring{track_colouring::plain}; + void draw_track_legend() const; + // the radii and lengths of the curves and the names and types of the switches written by them, from above, as on a plan + bool m_track_labels{true}; + void draw_track_labels() const; void draw_track_hover() const; struct track_intent { - enum class kind { none, gizmo, select, point, box, straight_set, straight_break, detour, straight_tool, straight_handle, route_vertex, route_grip, switch_at, lay, lay_end, sweep, turntable_place, turntable_exit, turntable_fit, spread, extend_end, signal_place, signal_move }; + enum class kind { none, gizmo, select, point, box, straight_set, straight_break, detour, straight_tool, straight_handle, route_vertex, route_grip, switch_at, switch_free, lay, lay_end, sweep, turntable_place, turntable_exit, turntable_fit, spread, extend_end, signal_place, signal_move, signal_read, switch_slide, pick_style, grade_line_pick, fouling, measure, route_trace, kilometrage, srk_boundary, srk_joint }; kind what{kind::none}; TTrack *track{nullptr}; int path{0}; @@ -1091,6 +2274,17 @@ class editor_mode : public application_mode, private editor_track::observer std::string action; }; track_intent m_intent; + // the measure between two points (M): on the ground, at a free end or on the axis of the track under the cursor + struct tape_state + { + bool active{false}; + std::vector points; + glm::dvec3 mouse{0.0}; + }; + tape_state m_tape; + void tape_update(); + std::string tape_readout() const; + void draw_tape() const; track_intent track_intent_at(int const Mods); bool track_gesture_on() const; void update_track_intent(); @@ -1100,12 +2294,23 @@ class editor_mode : public application_mode, private editor_track::observer void draw_track_intent() const; editor_track::snap_target snap_free_end(glm::dvec3 const &Near, glm::vec2 const &Screen, TTrack const *Self, int const Category, std::vector const &Exclude) const; void draw_free_ends(TTrack const *Self, int const Category, std::vector const &Exclude) const; + // the free ends of the rail tracks around the camera, looked for again after an edit or once the camera leaves the place + struct free_end_cache + { + int edits{-1}; + glm::dvec3 centre{0.0}; + double reach{0.0}; + std::vector points; + }; + mutable free_end_cache m_free_end_cache; + std::vector const &free_end_points(glm::dvec3 const &Centre, double const Reach) const; struct point_drag { bool active{false}; bool moved{false}; glm::vec2 from{0.f}; double height{0.0}; + std::size_t step{0}; }; point_drag m_point_drag; struct handle_drag @@ -1119,7 +2324,8 @@ class editor_mode : public application_mode, private editor_track::observer }; handle_drag m_handle_drag; void handle_drag_start(glm::dvec3 const &Anchor); - bool handle_drag_step(glm::dvec3 &Position); + // Ground: the handle goes onto the ground, at the height of the ballast of the track, unless Shift is held + bool handle_drag_step(glm::dvec3 &Position, TTrack const *Ground = nullptr); void point_drag_start(editor_track::point_ref const &Point); void point_drag_update(); void point_drag_finish(); @@ -1128,6 +2334,17 @@ class editor_mode : public application_mode, private editor_track::observer bool switch_reach(glm::dvec3 const &Ground, glm::dvec3 &Point); glm::dvec3 cursor_ground() const; glm::dvec3 cursor_level(double const Height) const; + glm::dvec3 cursor_terrain(double const Height); + double bed_height(glm::dvec3 const &Point, glm::dvec2 const &Direction, TTrack const *Style) const; + double nearby_ground(glm::dvec3 const &Point) const; + static std::pair trackbed(TTrack const *Style); + std::vector bed_heights(std::vector const &Points, std::vector const &Directions, TTrack const *Style) const; + void follow_ground(std::vector &Pieces, double const Height0, double const Grade0, double const Height1, double const Grade1, TTrack const *Style) const; + ground_follow::grading laying_grading(TTrack const *Style) const; + // the grade lines of the tracks shown while they're laid are fitted on a thread of their own, not to hold up the frames + mutable ground_follow::fitter m_fitter; + mutable bool m_follow_preview{false}; + glm::dvec3 lay_bed(glm::dvec3 const &Point); std::optional m_cursor_override; bool sweep_grabs(glm::dvec3 const &Point); // menu of the path a click of the right mouse button lands on @@ -1145,7 +2362,9 @@ class editor_mode : public application_mode, private editor_track::observer void track_context_release(); void render_track_context(); void split_track_at(TTrack &Track, glm::dvec3 const &Point); - void focus_track(TTrack &Track, int const Path, glm::dvec3 const &Point); + void focus_track(TTrack &Track, int const Path, glm::dvec3 const &Point) override; + // the camera flies over Duration seconds to the place Distance back from the target along Look, looking along it + void fly_to(glm::dvec3 const &Target, glm::dvec3 const &Look, double const Distance, double const Duration = 0.6) override; // paths found by their names struct track_search { @@ -1162,28 +2381,29 @@ class editor_mode : public application_mode, private editor_track::observer struct track_box { bool active{false}; + bool replace{false}; // the tracks in the box become the selection, else they join it glm::vec2 from{0.f}; glm::vec2 to{0.f}; TTrack *hovered{nullptr}; }; track_box m_track_box; - struct track_set_fields - { - double velocity{100.0}; - char rail[128]{}; - char trackbed[128]{}; - char circuits[256]{}; - int environment{0}; - }; - track_set_fields m_track_set_fields; glm::mat4 m_track_set_gizmo{1.0f}; bool m_track_set_using{false}; glm::dvec3 m_track_set_pivot{0.0}; std::vector>> m_track_set_joints; bool in_track_set(TTrack const *Track) const; + // the track is selected: alone or in the set + bool track_selected(TTrack const *Track) const; + // a click in the view: the track under the cursor becomes the selection, or nothing + void track_click_select(TTrack *Hovered); + bool track_set_begin(bool const Rotate); + void track_set_turn(double const Angle); + void track_set_move(glm::dvec3 const &Offset); + void track_set_end(); + glm::dvec3 track_set_centre() const; void track_set_toggle(TTrack &Track); void track_set_prune(); - void start_track_box(); + void start_track_box(bool const Replace = false); void finish_track_box(); void draw_track_set() const; void render_track_set_ui(); @@ -1208,201 +2428,210 @@ class editor_mode : public application_mode, private editor_track::observer void track_set_grow(); void render_track_spread_ui(); void draw_track_spread() const; - // changes each path of the set which can be changed; false from Change: the path stays as it was - void track_set_apply(std::function const &Change, bool const Rebuild, char const *What); - // second track alongside the selected path or the line through it, at a spacing, curves included - struct parallel_tool + // the properties of the selected tracks in the inspector, one sheet for one track and for many; see editormodetrackprops.cpp + // the set when there's one, the selected track otherwise + std::vector selected_tracks(); + void select_tracks(std::vector const &Tracks); + // changes each track which can be changed, in one step of the undo; false from Change: the track stays as it was + std::size_t tracks_apply(std::vector const &Tracks, std::function const &Change, bool const Rebuild, char const *What); + // the model of the timbers, with the fastenings where it has them, set on all the switches and crossings of the scenery, in one + // step of the undo; empty: the one of eu07.ini. returns: the tracks changed + std::size_t set_switch_timbers(std::string const &Model); + int track_property_index(std::string const &Key) const; + std::size_t track_property_apply(int const Property, std::vector const &Tracks, std::string const &Text); + void track_field_finish(); + void track_field_settle(); + void track_textures_scan(); + // a texture in use, offered first in the picker + struct texture_use { - bool open{false}; - bool expand{false}; - double spacing{4.0}; - int side{1}; // 1: to the right, -1: to the left, of the direction of the line - int scope{1}; // 0: the selected path, 1: the line through it, up to the switches - TTrack *built_for{nullptr}; - double built_spacing{0.0}; - int built_side{0}; - int built_scope{-1}; - std::size_t built_history{0}; - TTrack *pair_src{nullptr}; - TTrack *pair_dst{nullptr}; - double measured{0.0}; - std::vector pieces; - std::vector styles; - double length{0.0}; - std::string error; - std::string status; + material_handle material{null_handle}; // null: its image is read by the name + std::string name; + int count{0}; // shown on its tile, 0: nothing + std::string note; // what's said of it above the tiles }; - parallel_tool m_parallel; - TTrack *parallel_source() const; - TTrack *parallel_target() const; - void parallel_update(); - void render_parallel_controls(bool const Scope = true); - void render_parallel_ui(); - void render_parallel_set_ui(); - void parallel_build(); - void parallel_apply(); - bool parallel_preview_visible() const; - void draw_parallel_preview() const; - - // scenery templates standing by the track, placed and checked by the editor - struct template_item + // what the picker of a texture offers besides every texture of the folder + struct texture_offer { - std::string file; - glm::dvec3 location{0.0}; // world space - double yaw{0.0}; - std::vector rest; // parameters after the rotation - bool described{false}; - std::string track; - glm::dvec2 tilt{0.0}; // rot.x and rot.z of a described template, degrees - std::map values; + char const *title; // the heading of the ones in use + std::function()> used; // gathered when the picker opens + char const *none; // the entry for no texture, nullptr: there's none + char const *none_name; // the name that entry gives }; - struct standing_template + // every texture and material under the folder of the textures, read on the first use of the picker + void textures_index(); + // the picker of a texture, in an open combo. returns: true when one is chosen, its name in Chosen + bool texture_picker(texture_offer const &Offer, std::string const &Current, bool const Mixed, std::string &Chosen); + // the same, of a texture of the rails (Kind 0) or of the trackbed (1) + bool track_texture_picker(int const Kind, std::string const &Current, bool const Mixed, std::string &Chosen); + // image of the texture of the name, 0 while there's none + std::uint64_t texture_image(std::vector const &Used, std::string const &Name); + std::uint64_t track_texture_image(int const Kind, std::string const &Name); + // a field of a texture: its image and its name, a click opens the picker, a material of the texture browser can be dropped on it. + // returns: true when another one was chosen, in Value + bool texture_field(char const *Label, float const Width, std::string &Value, texture_offer const &Offer); + // the same, for a name kept in a buffer + bool texture_field(char const *Label, float const Width, char *Buffer, std::size_t const Size, texture_offer const &Offer); + // the textures of the roads and junctions of the scenery + std::vector road_textures_used() const; + // the textures of the palette and of the water of the terrain; None: the entry for no texture of its own, nullptr: there's none + texture_offer terrain_texture_offer(char const *None); + void render_track_properties(std::vector const &Tracks); + void render_track_set_header(std::vector const &Tracks); + void render_track_select_tools(std::vector const &Tracks); + void render_track_style(std::vector const &Tracks); + void copy_track_style(TTrack const &Track); + std::size_t paste_track_style(std::vector const &Tracks); + // which groups of the properties are pasted or put on the tracks by a preset, in the order of the groups of editormodetrackprops.cpp + using track_groups = std::array; + // the values of the properties of the chosen groups put on the tracks, in one step of the undo. returns: the number of the + // tracks changed, none when no value is of the chosen groups + std::optional apply_track_values(std::vector> const &Values, track_groups const &Groups, std::vector const &Tracks, char const *What); + // presets of the properties of the tracks (editorTrackPresets), made from a track and put on the selected ones + void render_track_presets(std::vector const &Tracks); + void render_track_presets_menu(); + std::size_t apply_track_preset(int const Id, std::vector const &Tracks); + std::vector similar_tracks(int const Property, std::vector const &Tracks) const; + // values of the properties over the selected tracks, each with the number of the tracks having it + struct track_values { - scene::instance_handle instance{0}; - std::string file; // lower case, forward slashes - glm::dvec3 location{0.0}; - double yaw{0.0}; - std::vector values; - }; - // includes of the templates whose file names the test accepts, with the location in p2..p4 and the rotation in p5 - std::vector standing_templates(std::function const &Accept) const; - // places them in the active layer, as one step of the undo. returns: how many were placed - std::size_t place_templates(std::vector const &Items, std::string &Error); - // moves them, as one step of the undo - std::size_t move_templates(std::vector> const &Moves); - // takes them out, as one step of the undo - std::size_t remove_templates(std::vector const &Instances); - - // hectometre posts along the line, at every 100 m of the kilometrage - struct hekto_post - { - int hectometres{0}; - double chainage{0.0}; - glm::dvec3 position{0.0}; - double yaw{0.0}; - int standing{-1}; // post already there with this number - }; - struct hekto_found - { - standing_template post; - int hectometres{0}; - double chainage{0.0}; // where it stands along the line - double expected{0.0}; // where its number belongs - double error{0.0}; // m along the line - double distance{0.0}; // m from where it belongs, in the plan - bool wrong{false}; - bool duplicate{false}; // another post with the same number stands nearer to its place - bool outside{false}; // its number belongs past the ends of the line - }; - struct hekto_tool - { - bool open{false}; - bool expand{false}; - TTrack *track{nullptr}; // the line runs through it - glm::dvec3 point{0.0}; // where the kilometrage is given - double km{0.0}; - bool km_read{false}; // the kilometrage was read from the posts already standing - int growth{1}; // 1: grows along the line, -1: against - int side{1}; // 1: to the right of the growing kilometrage, -1: to the left, 0: alternately - double offset{3.0}; // m from the axis - int style{0}; // nowy, stary, zgnity, mixed - int turn{0}; // degrees added to the rotation - double reach{10000.0}; // m each way - double tolerance{5.0}; // m along the line, for the posts standing - bool dirty{true}; + std::size_t signature{0}; + int generation{0}; + int generation_seen{-1}; std::size_t history{0}; - editor_track::route route; - std::vector samples; - double origin{0.0}; // chainage of the point - std::vector posts; - std::vector found; - std::string status; - std::string error; + int frame{-100}; + std::vector>> values; + std::vector applies; + std::size_t unsaved{0}; // of the tracks, changed since the file was written }; - hekto_tool m_hekto; - void hekto_start(TTrack &Track, glm::dvec3 const &Point); - void hekto_update(); - void hekto_read_kilometrage(); - void hekto_place(); - void hekto_fix(); - void hekto_remove_duplicates(); - void render_hekto_ui(); - void draw_hekto_overlay() const; - - // fouling point markers (W17) where the tracks meeting at a switch are the spacing apart - struct fouling_point + track_values m_track_values; + // how the last value given in the sheet went: on how many tracks, and why not on the others + struct track_outcome { - TTrack *track{nullptr}; // the switch - glm::dvec3 position{0.0}; - double yaw{0.0}; - int standing{-1}; // marker already there - }; - struct fouling_found - { - standing_template marker; - int point{-1}; // the fouling point it belongs to - double error{0.0}; // m from where it belongs - double height_error{0.0}; // m over where it belongs - bool wrong{false}; - }; - struct fouling_tool - { - bool open{false}; - bool expand{false}; - int scope{0}; // 0: the selected switch, 1: around the camera, 2: the whole scenery - double reach{1500.0}; - double spacing{3.5}; // m between the axes - double tolerance{2.0}; // m, a marker farther than this from its point is wrong - int height_mode{1}; // 0: on the ground, 1: at the height given over the rail heads - double height{0.0}; // m over the rail heads - double height_tolerance{0.03}; // m, a marker standing higher or lower than this is wrong - int model{0}; // w17, w17_new, w17_old, w17_dwuteo - int turn{0}; - bool dirty{true}; + int property{-1}; + std::string text; + bool refused{false}; // some tracks couldn't take it + std::size_t signature{0}; // of the tracks it was given to std::size_t history{0}; - TTrack *selected{nullptr}; - std::vector points; - std::vector found; - std::string status; - std::string error; + double time{0.0}; }; - fouling_tool m_fouling; - void fouling_update(); - void fouling_place(); - void fouling_fix(); - void render_fouling_ui(); - void draw_fouling_overlay() const; - - // a vehicle put on the selected path, to be driven: it isn't written to the scenery files - struct vehicle_tool + track_outcome m_track_outcome; + // the lines under the rows of the sheet + struct track_note { - bool open{false}; - bool expand{false}; - std::shared_ptr bank; - char search[64]{}; - bool controllable_only{true}; - std::shared_ptr vehicle; - std::shared_ptr skin; - int driver{0}; // 0: a driver, to be driven; 1: nobody, parked - TTrack *track{nullptr}; - glm::dvec3 point{0.0}; - std::string placed; - std::string status; - bool leave{false}; // the editor gives way to the driving at the start of the next frame - struct consist_vehicle + enum class kind { - std::shared_ptr vehicle; - std::shared_ptr skin; - bool turned{false}; + typing, + done, + refused }; - std::vector consist; - int facing{1}; + int property{-1}; + std::string text; + kind type{kind::done}; }; - vehicle_tool m_vehicle; - void vehicle_start(TTrack &Track, glm::dvec3 const &Point); - bool vehicle_place(); - void render_vehicle_ui(); - void draw_vehicle_marker() const; + std::vector m_track_notes; + // the field being typed in, with the tracks it was started on + struct track_field + { + int property{-1}; + std::vector tracks; + std::array text{}; + std::string initial; + int frame{0}; + }; + track_field m_track_field; + std::array, 2> m_track_textures; // of the rails, of the trackbed + std::vector m_texture_used; // the ones in use the open picker offers + std::array m_texture_filter{}; + struct texture_index_entry + { + std::string name; // as the materials are named: relative to the folder of the textures, without the extension + std::string lowered; + bool material{false}; // there's a .mat file of the name + }; + std::vector m_texture_index; // sorted by the name + bool m_texture_indexed{false}; + std::string m_texture_hovered; // the tile under the mouse in the picker, shown large above them + // properties taken from a track, to be set on the selected ones + struct track_style + { + std::string from; + std::vector> values; + // ticked at first by their groups: speed, environment, overhead line, track circuits, rails, trackbed, its shape, sleepers, ride and + // sound, frogs, sleeper placement + track_groups groups{false, false, false, false, true, true, true, true, false, true, true}; + std::map ticks; // changed by hand, by the keys of the properties + bool picking{false}; // the next click on a track in the view takes its properties + bool reveal{false}; // its section of the inspector opens, a track having been taken + }; + track_style m_track_style; + // a property of the track taken which the selected ones have otherwise + struct track_style_line + { + int property{-1}; + std::string now; // as the selected tracks have it, or how many values they have + std::string taken; // as the track taken has it + std::size_t differ{0}; // of the selected tracks, the ones it changes + }; + std::vector track_style_lines(std::vector const &Tracks); + bool track_style_takes(std::string const &Key) const; + struct track_presets_panel + { + int selected{0}; // id of the preset chosen in the inspector + int nameid{0}; // the preset whose name is in the field + char name[128]{}; + }; + track_presets_panel m_track_presets; + std::vector> m_track_similar; + TTrack const *m_track_list_hover{nullptr}; // in the list of the selected tracks + int m_track_list_hover_frame{-1}; + using template_item = ::template_item; + using standing_template = ::standing_template; + // includes of the templates whose file names the test accepts, with the location in p2..p4 and the rotation in p5 + std::vector standing_templates(std::function const &Accept) const override; + struct switch_drive + { + standing_template standing; + int family{-1}; + int index{0}; + }; + std::optional find_switch_drive(TTrack const &Switch, bool Wait = true); + // the drives standing in the scenery by the switch each is set to, read from the files once a frame for all the switches + std::map const &switch_drives_standing(bool Wait = true); + struct drives_standing + { + std::map by_switch; + int frame{-1}; + int revision{-1}; // of the drives scanned + std::size_t instances{0}; + }; + std::optional m_drives_standing; // emptied when an include changes + std::string missing_drive_variant(int const Family, bool const Rightswitch, bool const Driveright) const; + bool replace_switch_drive(TTrack &Switch, int Family, bool Flip); + void apply_switch_drive_choice(TTrack &Switch); + void switch_drive_captured(TTrack const &Track); + void switch_drives_committed(std::vector const &Tracks); + // the drives of the switches deleted go with them, in the step of the undo history the deletion made last + void drives_deleted(std::vector const &Switches); + // the drives of all the switches of the scenery set at the tips of their blades, the ones the earlier versions of the editor set at the + // joint before them too: once, as the scenery is opened, with no step of the undo history; how many moved + std::size_t drives_to_blade_tips(); + bool m_drives_checked{false}; + scene::layer_handle output_layer(std::string const &Part) override; + // places them in the active layer or the given one, as one step of the undo. returns: how many were placed + std::size_t place_templates(std::vector const &Items, std::string &Error, scene::layer_handle Layer = scene::layer_handle{}) override; + // moves them, as one step of the undo + std::size_t move_templates(std::vector> const &Moves) override; + // takes them out, as one step of the undo + std::size_t remove_templates(std::vector const &Instances) override; + bool standing_signals(std::vector &Signals, bool const Wait) override; + std::size_t signal_batch(signal_changes const &Changes, std::vector> States, std::vector Created, std::string &Error) override; + std::string signal_templates_missing(std::vector const &Orders) override; + bool signal_heads(std::vector &Heads, bool const Wait) override; + std::string signal_mount(std::string const &Kind, std::string const &File) override; + std::size_t signal_reattach(std::vector const &Instances) override; + void select_signal(scene::instance_handle const Instance) override; + void render_signal_templates(std::vector const &Kinds) override; struct signal_template { @@ -1417,6 +2646,27 @@ class editor_mode : public application_mode, private editor_track::observer int parameters{0}; bool plate{false}; bool linked{false}; + std::vector speeds; + int aspects{0}; // of a block signal, 3 or 4 + int arms{0}; // of a semaphore, 1 or 2, from its description + // m, of the zero of its model over the rail heads, from its description: where it stands by default + double height{0.0}; + // m, how deep its model reaches under its zero, from its description: none, it isn't put on the ground + std::optional depth; + // the aspects its description lists, by name (Sr1, Od2...) with the event giving each; empty for a template not described so + std::vector> aspect_events; + // of a warning disc: its event for each speed class of the signal after it, stop, vmax, 100, 60, 40 + std::vector> repeats; + }; + // an indicator to put on a signal, a template described as one + struct indicator_template + { + std::string file; + std::string name; + std::string description; + std::string sign; + std::string place; // "head": under the lights of the signal, one under another; "foot": by its foot, the place in its model + std::vector> events; }; struct signal_spot { @@ -1429,6 +2679,10 @@ class editor_mode : public application_mode, private editor_track::observer double offset{0.0}; glm::dvec3 position{0.0}; double yaw{0.0}; + // the path and its list that read the signal: the track it stands by, or past the frog of a switch the track joined to the end + // of its path, which only the trains of that path run on + TTrack *reader{nullptr}; + int reader_list{2}; }; struct signal_standing { @@ -1438,58 +2692,203 @@ class editor_mode : public application_mode, private editor_track::observer std::string read; TTrack *track{nullptr}; int list{0}; - signal_spot spot; - bool on_track{false}; + // every path and list having the read, the first of them in track and list + std::vector> reads; + // the indicators put on it: named after it, at its foot, the highest first + std::vector indicators; }; struct signal_tool { std::vector templates; + std::vector indicators; int revision{-1}; int kind{0}; - std::array chosen{-1, -1, -1, -1, -1, -1, -1}; + std::array chosen{-1, -1, -1, -1, -1, -1, -1, -1}; + bool armed{false}; // a click by a track places the chosen template char filter[64]{}; char name[64]{"A"}; char plate[64]{}; + std::array plate_index{}; // the speed index of the drawn plate, "4" or "12" for 1/2 + bool plate_m{false}; // the drawn plate gets the "m" of a signal giving shunting signals too char linked[64]{"none"}; float height{0.0f}; bool placing{false}; signal_spot press; + signal_spot press_raw; // where the press was, before it went to a round distance to the switch ahead glm::vec2 pressed{0.f}; int facing{0}; std::vector standing; std::size_t standing_history{static_cast(-1)}; - std::size_t standing_redo{static_cast(-1)}; double standing_time{-1.0}; int hover{-1}; scene::instance_handle selected{0}; bool moving{false}; + glm::dvec2 grab{0.0}; + signal_spot home; + bool home_valid{false}; signal_spot moved; bool moved_valid{false}; + // a click on a track gives the read of the signal selected to it + bool picking_read{false}; + // the entry of the selected signal into the gauge of the paths around it, measured again as the history or the selection changes + struct + { + scene::instance_handle instance{0}; + std::size_t history{static_cast(-1)}; + glm::dvec3 location{0.0}; // of the signal, which follows a dragged track without a new step of the history + gauge_tool::gauge_hit hit; + } gauge; + // the signal the gizmo has taken: as it stood then, the frame of its models, the size of the history before the step of the + // gizmo and the directives of its indicators + struct + { + scene::instance_handle instance{0}; + signal_standing from; + glm::dmat3 frame{1.0}; + std::size_t history{0}; + std::vector> directives; + } gizmo; std::string status; }; signal_tool m_signal; - void signal_scan(); + // the way from the spot of a signal along its track to the switch the trains it faces come to first + track_trace::danger signal_danger(signal_spot const &Spot) const; + // the spot moved along its track to a round distance to the switch ahead, 50 m, 100 m..., when it's that near one; Alt leaves it + void signal_snap(signal_spot &Spot, signal_template const &Template) const; + // of the selected signal: the spot it stands at and the way to the switch ahead of it, kept until it or the history changes + struct signal_metre + { + scene::instance_handle instance{0}; + std::size_t history{static_cast(-1)}; + glm::dvec3 location{0.0}; + double yaw{0.0}; + bool valid{false}; + signal_spot spot; + track_trace::danger danger; + }; + mutable signal_metre m_signal_metre; + signal_metre const &signal_metre_of(signal_standing const &Standing) const; + bool signal_scan(bool Wait = true); + signal_template const *signal_current() const; signal_template const *signal_armed() const; signal_template const *signal_template_of(std::string const &File) const; + // the template it is placed by: the one of its file if that is of its kind, else the one chosen for its kind. returns: nullptr if none + signal_template const *signal_template_for(signal_order const &Order) const; bool signal_spot_at(TTrack &Track, int const Path, glm::dvec3 const &Point, glm::dvec3 const &Cursor, int const Facing, int const Side, signal_template const &Template, signal_spot &Spot) const; void signal_refresh(bool const Force = false); + // the signals standing, read by the tracks as they are now, the templates as found so far + std::vector signal_standing_now() const; int signal_hit() const; void signal_press(track_intent const &Intent); void signal_release(); bool signal_place(signal_spot const &Spot, signal_template const &Template); void signal_move_update(); - void signal_move_finish(); + // Moved: the signal moved from its track, the nearest track takes it if that's nearer by more than a little + bool signal_standing_spot(signal_standing const &Standing, signal_spot &Spot, bool const Moved = false) const; + bool signal_drop_at(signal_standing const &Standing, TTrack &Track, int const Path, glm::dvec3 const &Point, int const Side, signal_spot &Spot) const; + bool signal_move_to(signal_standing const &Standing, signal_spot const &Spot, char const *Read, char const *Unread); + indicator_template const *indicator_template_of(std::string const &File) const; + // the indicator put on the signal, named after it: under its lights below the ones there, or at its foot. returns: false if it can't be + bool signal_indicator_add(signal_standing const &Standing, indicator_template const &Indicator); + bool signal_indicator_remove(scene::instance_handle const Indicator); + // the indicators under the lights of the signal at Upper and Lower in its list, the highest first, swapped: each takes the place of the other + bool signal_indicators_swap(signal_standing const &Standing, std::size_t const Upper, std::size_t const Lower); + // the signal set the distance from the axis of its track in the plan and its height, raised over where it stands by default (over the rail heads, on a gantry), unless none + bool signal_set_across(signal_standing const &Standing, std::optional const Offset, std::optional const Height); + // the distance from the axis and the height over where it stands by default From has, carried to To, a spot of the same signal + // along its track: a signal set across or raised by hand keeps it as it is dragged or snapped + void signal_carry(signal_spot const &From, signal_spot &To, signal_template const &Template) const; + // the height of the zero of the model of a signal at Position by the track of the axis at Axis, as it stands by default: as far over + // the rail heads as its description gives, lower only where its bottom would hang over the ground; a gantry as high over the rails + // as chosen + double signal_default_height(signal_template const &Template, glm::dvec3 const &Axis, glm::dvec3 const &Position) const; + // how much higher the default height of To is than of From at Position by the track of the axis at Axis: what a signal given the + // template To in place of From goes up by, to stand as raised as it was + double signal_default_change(signal_template const &From, signal_template const &To, glm::dvec3 const &Axis, glm::dvec3 const &Position) const; + // the indicators of the signal moved after it to the place and the frame it has now, at the same place by it as they were, the + // directives they had going to Directives + void signal_indicators_follow(signal_standing const &Standing, glm::dmat3 const &Before, std::vector> &Directives); + bool render_signal_indicators(signal_standing const &Found); + // the indicators put on the signal named Name standing at Location, as the scenery has them now, the highest first: the list of + // the tool is kept up only while the tool is open + std::vector signal_indicators_of(std::string const &Name, glm::dvec3 const &Location) const; + // the indicators of the signal named Before at Location named After it, the directives they had going to Directives once each + void signal_indicators_renamed(std::string const &Before, std::string const &After, glm::dvec3 const &Location, std::vector> &Directives); + // the directives of more includes taken back by the step: one of a single include is made one of them + void history_add_directives(EditorSnapshot &Step, std::vector> const &Directives); + // the signal of the selected include taken by the gizmo: its indicators go with it, and once it's let go it is moved as a drag of + // the signal tool moves it, read by the path it stands by then, out of the gauge, as one step of the history + void signal_gizmo_begin(); + void signal_gizmo_step(); + void signal_gizmo_end(); + // the height of the lowest lamp of the signal in the world, from the geometry of its lamps; 0 when it has none + double signal_lowest_lamp(scene::instance_handle const Instance) const; + // the deepest entry of the models of the signal into the gauge of the paths around it + gauge_tool::gauge_hit signal_gauge(scene::instance_handle const Instance); + // the signal just placed or moved, at Local in its file, taken across away from the axis of each path whose gauge it enters, a few + // times at most, its directive changed with it. returns: the way it went, metres, and in Hit the entry it still makes + double signal_off_gauge(scene::instance_handle const Instance, std::string const &File, std::vector &Values, glm::dvec3 Local, gauge_tool::gauge_hit &Hit); + // a sentence more to the status about it, none when the signal kept out of the gauge where it was put + void signal_gauge_note(std::string &Status, double const Shift, gauge_tool::gauge_hit const &Hit, bool const Gantry) const; + bool signal_flip(scene::instance_handle const Instance); + bool signal_turn(scene::instance_handle const Instance); + bool signal_swap(scene::instance_handle const Instance, std::string const &File); + // the signal set to the aspect in the editor, as its event sets it in the game: only how it looks, nothing saved + bool signal_show_aspect(scene::instance_handle const Instance, std::string const &Aspect, std::string const &Event); + signal_standing const *signal_standing_of(scene::instance_handle const Instance) const; bool signal_delete(scene::instance_handle const Instance); void signal_detach_events(std::string const &Read, std::vector> &States); + // a track split in two: the reads of the signals placed since the scenery was opened, not bound yet, go to the piece by the signal + void signal_split(TTrack &Original, TTrack &Created); + // the list of a path the trains the signal faces read it from, as they run by the point of the path nearest to it + int signal_read_list(signal_standing const &Standing, TTrack const &Track, int const Path) const; + // the read of the signal in exactly these lists of these paths, as one step taken back by Ctrl+Z + bool signal_read_set(signal_standing const &Standing, std::vector> const &Reads); + // a click on a track while picking the path that reads the selected signal: its read goes there, or one more there with Add, + // or off it with Add when it's there already + bool signal_read_pick(TTrack &Track, int const Path, bool const Add); + std::string signal_read_label(TTrack const &Track, int const Path, bool const Add) const; void signal_renamed(std::string const &Before, std::string const &After, EditorSnapshot &Snapshot); + // the plate a signal of this name gets when none is picked: one drawn by python/local/signal_plate.py with the given style + // ("look=toned", with "&index=12" and "&m=1" when it has them), or none for a name it can't carry + static std::string signal_plate(std::string const &Name, std::string const &Style); + // true for a plate signal_plate() gives, of any name and look + static bool signal_plate_drawn(std::string_view Plate); + static bool signal_plate_blank(std::string const &Name, std::string const &Plate); + static std::string signal_plate_text(std::string const &Name); + // what a drawn plate is drawn with but its name, kept through a rename; for one not drawn the look set in the editor + static std::string signal_plate_style(std::string const &Plate); void signal_select(scene::instance_handle const Instance); std::string signal_next_name(std::string const &Name) const; void render_signal_ui(); void render_signal_palette(); void render_signal_selected(); + // the paths reading the signal, each turned the other way or removed, a path picked or the one the editor gives. returns: true when they changed + bool render_signal_reads(signal_standing const &Found); + // of the signal selected: its template and another one for it, the aspects it can be set to; true when it got another one + bool render_signal_template(signal_standing const &Found, signal_template const &Item); + // the list of the templates the signal can take instead, Across those of another mount too: the file picked, empty for none + std::string signal_swap_combo(signal_template const &Item, bool const Across) const; + void render_signal_aspects(signal_standing const &Found, signal_template const &Item); void draw_signal_overlay() const; std::string signal_intent_label(signal_template const &Template, signal_spot const &Spot) const; std::string signal_variant(signal_template const &Template, signal_spot const &Spot) const; + // what a deleted track carried and no other one took, its read events and track circuits, for a track laid in its place + struct orphan_record + { + TTrack *track{nullptr}; // retired; the record waits while it stays so + std::vector> events; // the name, the list it was on + std::vector circuits; + // the tracks given the circuits: while one stays the circuits don't wait, once a step other than an undo removes one they + // are its own + std::vector given; + bool fresh{false}; // made by the step being taken + }; + std::vector m_orphans; + std::string m_orphan_note; // shown by the cursor after the step which made it + void orphans_register(std::vector const &Removed, std::vector const &Kept); + // Created: made by the step, their circuits the ones of the tracks they were made from; Changed: the others it changed + void orphans_take_over(std::vector const &Created, std::vector const &Changed); // a model laid along the track: bent to follow it, or repeated along it struct sweep_tool @@ -1501,6 +2900,7 @@ class editor_mode : public application_mode, private editor_track::observer char search[64]{}; std::vector models; bool scanned{false}; + int revision{-1}; // of the include bank the templates were taken from // parameters of a template laid along the track, with their names std::string parameters_for; std::vector> parameters; @@ -1599,13 +2999,17 @@ class editor_mode : public application_mode, private editor_track::observer bool marker_valid{false}; glm::dvec3 marker{0.0}; std::string status; - int dragging{0}; + int dragging{0}; // 1: the cross along and aside, 2: up, 3: only along, 4: the start of the model, 5: its end sweep_node::state drag_state; + std::shared_ptr drag_line; // the line as it was when the drag began + double drag_first{0.0}; // m along it, where the model began and ended then + double drag_last{0.0}; glm::dvec3 drag_anchor{0.0}; double drag_station{0.0}; std::string drag_label; sweep_node *hover{nullptr}; bool over_marker{false}; + int over_end{0}; // the handle under the cursor: 1 at the start of the model, 2 at its end std::string label; std::string details; }; @@ -1623,6 +3027,16 @@ class editor_mode : public application_mode, private editor_track::observer void bend_reanchor(sweep_node::state &State, int const Side, int const Height, glm::dvec3 const &Point) const; double bend_fixed(sweep_node const &Sweep, glm::dvec3 const &Point) const; void bend_stretch(sweep_node const &Sweep, double const Fixed, double const Length, glm::dvec3 const &Point, sweep_node::state &State) const; + // the model laid along another track: it stays where it stands, with its length + void bend_retrack(sweep_node const &Sweep, TTrack const &Track, sweep_node::state &State) const; + // the handles at the ends of the model, at the height and the side of its reference point + std::array bend_ends(sweep_node const &Sweep) const; + // a drag of the model begun: 1 the cross along and aside, 2 up, 3 only along, 4 the start, 5 the end + void bend_drag_begin(int const Kind); + // the end of the model taken to the point, the line lengthened through the tracks joined there; the length it has then + double bend_end_to(bool const Atend, glm::dvec3 const &Point, sweep_node::state &State) const; + std::string bend_selftest(std::string const &Command, std::istringstream &Words); + void sweep_relink(sweep_node const &Sweep); void bend_pick(glm::dvec3 const &Point); glm::dvec3 bend_marker(sweep_node const &Sweep) const; void restore_bend(EditorSnapshot &Snapshot, bool const Undo); @@ -1637,8 +3051,24 @@ class editor_mode : public application_mode, private editor_track::observer std::size_t next{0}; int wait{0}; bool quitting{false}; + scripted_input input; + std::string badge; // the mouse or the keys drawn over the view, for the clips of the tutorial + glm::vec2 badge_at{0.0f}; // its bottom left corner, in the pixels of the window }; selftest m_selftest; + using selftest_result = editor_selftest_result; + selftest_result selftest_scene(std::string const &command, std::istringstream &words); + selftest_result selftest_sleepers(std::string const &command, std::istringstream &words); + selftest_result selftest_sweep(std::string const &command, std::istringstream &words); + selftest_result selftest_track(std::string const &command, std::istringstream &words); + selftest_result selftest_switch(std::string const &command, std::istringstream &words); + selftest_result selftest_rails(std::string const &command, std::istringstream &words); + selftest_result selftest_join(std::string const &command, std::istringstream &words); + selftest_result selftest_signal(std::string const &command, std::istringstream &words); + selftest_result selftest_terrain(std::string const &command, std::istringstream &words); + selftest_result selftest_props(std::string const &command, std::istringstream &words); + selftest_result selftest_monkey(std::string const &command, std::istringstream &words); + selftest_result selftest_dispatch(std::string const &command, std::istringstream &words); void selftest_step(); // a value typed during a gesture, taken instead of the one the cursor gives std::string m_typed; @@ -1646,7 +3076,6 @@ class editor_mode : public application_mode, private editor_track::observer char const *typed_meaning() const; std::vector typed_values() const; bool typed_key(int const Key); - void typed_extend(); glm::dvec3 typed_lay(glm::dvec3 const &Mouse) const; void typed_turn(); bool m_route_tab{true}; @@ -1659,10 +3088,20 @@ class editor_mode : public application_mode, private editor_track::observer TTrack *to{nullptr}; TTrack *picked_from{nullptr}; TTrack *picked_to{nullptr}; - double run_length{3000.0}; + double run_length{std::numeric_limits::infinity()}; // the whole line through the track clicked + std::vector followed; // the selection the route was last taken from editor_track::route route; std::vector samples; + std::vector created; // the paths the last apply split off the route std::vector terrain; // NaN where there's no terrain + std::vector model; // the ground of the terrain model (NMT) as measured; NaN where it's not known + bool model_waiting{false}; // squares of the model under the route still to come + double model_polled{0.0}; + // what the joined ends take their height and grade from, when it's a switch: shown on the plot + std::string start_inherits, end_inherits; + // depth of the formation under the grade line, the rail top, of the track of each sample: the formation, not the rails, + // lies on the ground + std::vector beds; profile::line line; profile::context context; std::vector issues; @@ -1689,10 +3128,23 @@ class editor_mode : public application_mode, private editor_track::observer double view_centre{0.0}; float exaggeration{20.0f}; bool show_terrain{true}; + bool show_model{true}; bool show_track{true}; bool show_plan{true}; + bool whole_grade_line{true}; // applied, the tracks sharing the grade line of the route go with it + profile::line line_read; // the line before it was edited + bool fitting{false}; // the line comes from the fit to the terrain model: any error of it refuses it + std::vector beside; // those of them lying by it, for the route and the state of the tracks below + std::tuple beside_of{nullptr, 0, 0, 0}; + bool picking{false}; // a click on a track in the view puts it on the grade line of the route or takes it off + std::vector members; // of the grade line picked, wherever they are + std::tuple members_of{-1, 0, 0}; int selected{-1}; int dragging{-1}; + // where the point was grabbed: the mouse there, the point against the mouse; the point moves once the mouse does + ImVec2 drag_press{0.0f, 0.0f}; + glm::dvec2 drag_grab{0.0}; + bool drag_moved{false}; int curve_grip{-1}; bool panning{false}; bool changed{false}; @@ -1702,6 +3154,9 @@ class editor_mode : public application_mode, private editor_track::observer int hover_grip{-1}; bool hover_line{false}; int shown{-2}; // point in the side panel + bool show_remarks{false}; + float strip_top{-1.0f}; // the top of the strip over the 3d view, -1 while it isn't shown + int edits{-1}; // of the tracks, when the route was last read std::string status; std::string error; }; @@ -1714,19 +3169,50 @@ class editor_mode : public application_mode, private editor_track::observer glm::dvec3 start{0.0}, end{0.0}, middle{0.0}; // of the route, world space double origin{0.0}; profile::line line; + double departure{-1.0}; // of the track from the design when it was kept; -1 as kept by an older editor }; std::vector m_profiles; bool m_profiles_loaded{false}; void profile_library_load(); void profile_library_mark(std::vector Layers); + // the last step takes the kept grade lines back to the library given, as they were before it changed them + void profiles_to_history(std::vector Library); + // the kept grade lines back to the library given, the step changing them given up before it went to the history + void profiles_restore(std::vector Library); + // the tracks whose grade line was fitted, by name, with the shape they had then, kept as "//$t" comment lines: a track + // changed since, by hand or taken back, isn't fitted any more + struct fitted_mark + { + scene::layer_handle layer{null_handle}; + std::uint64_t shape{0}; + bool hand{false}; + }; + std::map, fitted_mark> m_fitted; // by the name and the shape: scenery files have names used twice + bool m_fitted_loaded{false}; + void fitted_load(); + void fitted_set(std::vector const &Tracks, bool const Hand = false); + bool grade_fitted(TTrack const &Track); + bool grade_hand(TTrack const &Track); // its grade line was edited with the profile tool, and it wasn't changed since + bool nmt_stays(TTrack const &Track); // this putting of the tracks onto the terrain leaves it as it is + static std::uint64_t fitted_shape(TTrack const &Track); int profile_find(bool &Reversed) const; bool profile_restore(); + bool profile_restore_parts(); + // the route a kept design was laid over, as it runs now; none when its paths moved or are gone + std::optional profile_stored_route(stored_profile const &Entry, TTrack **From = nullptr, TTrack **To = nullptr) const; + // the kept designs over the tracks moved, as by the grade lines shared, laid anew onto them where they part from them; returns how + // many were, how many couldn't be without an error and are left as they were + std::pair profile_refit_stored(std::unordered_set const &Moved); void profile_store(); void profile_forget(); void profile_open_stored(std::size_t const Index); void profile_edited(); + // the radii of its neighbours were for the breaks of the grade it made, they follow the limits after it + void profile_remove_point(int const Index); void render_profile_body(); void render_profile_strip(); + void render_profile_header(); + void render_profile_empty(); void render_profile_toolbar(); void render_profile_points(); void render_profile_source(); @@ -1735,18 +3221,33 @@ class editor_mode : public application_mode, private editor_track::observer void profile_open(TTrack *From, TTrack *To); void profile_open_run(TTrack &Track); void profile_take(editor_track::route Route, TTrack *From, TTrack *To); + void profile_open_selection(std::vector const &Tracks); + void profile_follow_selection(); void profile_resample(); + // the ground of the terrain model under the route, as it was measured before any earthworks + void profile_sample_model(); void profile_recognize(); void profile_fit_ground(); + // depth of the foot of the ballast under the rail top, and its distance from the axis static std::pair profile_ballast(TTrack const &Track); + // false for a track with no trackbed of its own, as the switches of the older sceneries whose bed is an include + static bool profile_own_bed(TTrack const &Track); void profile_shape_ground(); std::pair profile_generate_ground(std::vector> const &Beds, double const Reach); void profile_restore_ground(); void render_profile_earthworks(); void profile_check(); - void profile_apply(); + // Terrain: the heightmap terrain follows the tracks changed. Bridges: stretches of the route over a bridge or a viaduct, the + // paths over them cut off at their ends and set to the bridge environment + void profile_apply(bool const Terrain = false, std::vector const &Bridges = {}, double const Fewest = 0.0); + // the terrain under the tracks changed by the last Edits steps of the history which changed tracks + void profile_follow_terrain(std::size_t const Edits); void profile_fit_view(); + // the camera to the part of the route the plot shows; the plot to the part of the route the camera shows, its zoom kept + void profile_frame_view(); + void profile_to_camera(); void profile_after_undo(); + void profile_follow_edits(); struct profile_view; void render_profile_canvas(float const Height); void profile_fit_exaggeration(profile_view const &View); @@ -1799,9 +3300,28 @@ class editor_mode : public application_mode, private editor_track::observer std::vector> m_bindings_unresolved; // lines kept as they are bool m_bindings_loaded{false}; std::vector m_infra_buffer; // states of the objects before the change in progress + std::vector> m_drive_buffer; bool m_infra_suspended{false}; + // the point objects which go with a path: the signals and the warning discs it reads, the SHP resonators, and the controls of the + // block sections, the signs and the posts by the path nearest to them + struct point_object + { + scene::instance_handle include{0}; + glm::dvec3 location{0.0}; + TTrack *reader{nullptr}; + TTrack *nearest{nullptr}; // of one no path reads + infra::category group{infra::category::other}; + }; + std::vector m_point_objects; + std::size_t m_point_objects_revision{static_cast(-1)}; + std::size_t m_point_objects_count{0}; + void infra_adopt(TTrack &Track); + int infra_bound_count() const; // by the infra tool, not the ones a change of their track took along + std::set> m_infra_carried; // the objects their tracks moved since the tool cleared it + std::string infra_carried_note(); // a line of the status telling how many, empty for none; clears them void infra_load(); void infra_store(); + void infra_forget(scene::basic_node const *Node); std::vector infra_scope() const; void infra_recognize(); void infra_bind_chosen(); @@ -1815,72 +3335,32 @@ class editor_mode : public application_mode, private editor_track::observer void tracks_committed(std::vector const &Tracks) override; void track_retired(TTrack &Track) override; void track_split(TTrack &Original, TTrack &Created, segment_data const &First) override; + void track_renamed(TTrack const &Track, std::string const &Old) override; void infra_move(infra::binding &Binding); void infra_attach(EditorSnapshot &Snapshot); void render_infra_body(); - // speed limits of the paths checked against what their geometry allows - struct speed_state - { - bool open{false}; - int scope{0}; // 0: the line through the selected path, 1: the whole scenery - speed_check::options options; - std::vector> queue; - std::size_t next{0}; - std::vector results; - bool show_all{false}; - int limits{0}; // 0: all the paths, 1: only those with a speed limit set, 2: only those without - int selected{-1}; - std::size_t history{0}; // size of the undo history at the check - std::string status; - }; - speed_state m_speed; - void render_speed_body(); - void speed_start(); - void speed_step(); - void speed_focus(int const Index); - // with Branches the limits of the switch branches count too, otherwise they're only warnings - void speed_apply(std::vector const &Indices, bool const Branches); - std::vector speed_listed() const; - void draw_speed_overlay() const; + gauge_tool m_gauge{*this, *this, *this, *this}; + speed_tool m_speed{*this, *this, *this, *this}; + joints_tool m_joints{*this, *this, *this, *this}; + vehicle_tool m_vehicle{*this, *this}; + hekto_tool m_hekto{*this, *this, *this, *this, *this, *this}; + fouling_tool m_fouling{*this, *this, *this, *this, *this}; + parallel_tool m_parallel{*this, *this, *this, *this}; + srk_tool m_srk{*this, *this, *this, *this, *this, *this}; + km_tool m_km{*this, *this, *this, *this}; + track_ride m_ride; + minimap_tool m_minimap{*this, *this, m_ride}; + std::vector m_tools{&m_gauge, &m_speed, &m_joints, &m_vehicle, &m_hekto, &m_fouling, &m_parallel, &m_srk, &m_km, &m_ride, &m_minimap}; - // joints of the paths: ends which almost meet, steps, kinks, jumps of the cant and of the grade - struct joints_state - { - bool open{false}; - int scope{0}; // 0: around the camera, 1: the whole scenery - double reach{2000.0}; - double gap{1.0}; // m, free ends closer than this to another end - double step{0.005}; // m - double angle{0.2}; // deg - double cant{5.0}; // mm - double grade{10.0}; // per mille - bool free_ends{false}; - std::vector queue; - std::size_t next{0}; - std::vector issues; - int filter{-1}; - int selected{-1}; - std::size_t history{0}; - std::string status; - }; - joints_state m_joints; - void joints_start(); - void joints_step(); - void joints_check(TTrack &Track); - void joints_focus(int const Index); - bool joint_fix(joint_issue &Issue, std::vector> &States, std::vector &Changed); - void joints_fix(std::vector const &Indices); - void render_joints_body(); - void draw_joints_overlay() const; void infra_rebase(); void render_infra_search(); void render_infra_candidates(); void render_infra_bound(); void draw_infra_overlay() const; - bool m_route_gizmo_using{false}; - glm::mat4 m_route_gizmo{1.0f}; + bool m_route_dragging{false}; + alignment::design m_route_drag_from; float m_track_snap_radius{1.0f}; bool m_track_align_tangent{true}; bool m_track_drag_connected{true}; @@ -1950,20 +3430,13 @@ class editor_mode : public application_mode, private editor_track::observer bool hashover{false}; glm::dvec3 mouse{0.0}; std::string status; - char surface[128]{}; - char sides[2][128]{}; - char filter[64]{"asph"}; - char kerbtext[128]{}; - char mediantext[128]{}; - char banktext[128]{}; - char islandtext[128]{"none"}; }; void render_road_tool_options(); // the change of the road tool void road_choose_tool(int const Tool); void render_road_selection(); bool render_road_layout(road_node::state &State); - bool render_road_material(char const *Label, char *Buffer, std::size_t const Size, std::string &Value); + bool render_road_material(char const *Label, std::string &Value); void render_junction_layout(junction_node &Junction); void junction_apply(junction_node &Junction, junction_node::state const &State); // leads the banks of the corners of a junction to the ground beside it @@ -2011,7 +3484,7 @@ class editor_mode : public application_mode, private editor_track::observer void road_profile(std::vector &Pieces, double const *Firstgrade, double const *Lastgrade, bool const Fresh); // height of the ground under each of the points, with the roads not taken for the ground. a point with nothing under it keeps its height // Found: set for the points which have the ground under them - std::vector ground_heights(std::vector const &Points, bool const Fresh, std::vector *Found = nullptr); + std::vector ground_heights(std::vector const &Points, bool const Fresh, std::vector *Found = nullptr) const; void push_road_snapshot(editor_road::record Record); void restore_road_snapshot(EditorSnapshot const &Snapshot, std::vector &Opposite, bool const Undo); road_tool m_roadtool; diff --git a/application/editormodeconnection.cpp b/application/editormodeconnection.cpp new file mode 100644 index 000000000..275e5754e --- /dev/null +++ b/application/editormodeconnection.cpp @@ -0,0 +1,615 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "application/editormode.h" +#include "application/editoruilayer.h" +#include "application/editormodeshared.h" +#include "editor/editorFormat.hpp" +#include "editor/editorAlignmentStore.hpp" +#include "editor/editorSwitchStore.hpp" +#include "editor/editorGeometry.hpp" +#include "application/editormodetrackshared.h" + +#include "scene/scene.h" +#include "simulation/simulation.h" +#include "world/Track.h" +#include "utilities/translation.h" + +#include "imgui/imgui.h" +#include +#include +#include + +namespace +{ + +using geometry::cross; +using geometry::plan_distance; +using geometry::plan_of; + +std::vector spacings_of(char const *Text) +{ + std::string text{Text}; + for (auto &letter : text) + if (letter == ';') + letter = ' '; + else if (letter == ',') + letter = '.'; + std::istringstream words{text}; + std::vector result; + double value{0.0}; + while (words >> value) + result.push_back(value); + return result; +} + +bool usable_in_connection(editor_track::switch_template const &Template) +{ + return false == Template.double_slip && false == Template.twofold(); +} + +// m: a switch let go this near the other track is dragged onto it, at least this far from its own track +double constexpr kOntoTrack{1.5}; +double constexpr kOffTrack{2.5}; +// m: the furthest the switches of two crossovers meeting on one track are apart for a double crossover +double constexpr kDoubleGap{50.0}; + +// whether the main track of the switch runs along the line +bool on_line(TTrack const &Switch, connection::line const &Line) +{ + auto const &main{Switch.m_paths.front()}; + return std::abs(Line.lateral(main.points[segment_data::point::start])) < 0.05 && std::abs(Line.lateral(main.points[segment_data::point::end])) < 0.05; +} + +// the line along the main track of the switch, reaching far past both of its ends +connection::line line_through(TTrack const &Switch) +{ + double constexpr reach{2000.0}; + auto const &main{Switch.m_paths.front()}; + auto const start{main.points[segment_data::point::start]}; + auto const end{main.points[segment_data::point::end]}; + connection::line result; + result.direction = glm::normalize(plan_of(end - start)); + result.grade = (end.y - start.y) / std::max(1e-9, glm::length(plan_of(end - start))); + result.start = start - glm::dvec3{result.direction.x, result.grade, result.direction.y} * reach; + result.length = 2.0 * reach; + return result; +} + +} // namespace + +char const *editor_mode::connection_name(int const Kind) +{ + switch (static_cast(Kind)) + { + case connection::kind::double_crossover: return STR_C("Double crossover"); + case connection::kind::scissors: return STR_C("Scissors crossover"); + case connection::kind::ladder: return STR_C("Switch ladder"); + default: return STR_C("Crossover"); + } +} + +editor_track::straight editor_mode::straight_near(glm::dvec3 const &Point, std::vector const &Exclude, double const Reach) const +{ + TTrack *found{nullptr}; + auto best{Reach}; + for (auto *section : simulation::Region->sections(Point, static_cast(std::max(40.0, Reach)))) + for (auto const &cell : section->m_cells) + for (auto *track : cell.m_paths) + { + if (track->eType != tt_Normal || track->m_editorremoved || track->m_paths.empty() || std::find(Exclude.begin(), Exclude.end(), track) != Exclude.end() || false == editor_track::is_straight(*track, m_straights.tolerance)) + continue; + auto const &path{track->m_paths.front()}; + auto const a{plan_of(path.points[segment_data::point::start])}; + auto const segment{plan_of(path.points[segment_data::point::end]) - a}; + auto const t{std::clamp(glm::dot(plan_of(Point) - a, segment) / std::max(1e-9, glm::dot(segment, segment)), 0.0, 1.0)}; + auto const distance{glm::distance(plan_of(Point), a + segment * t)}; + if (distance < best) + { + best = distance; + found = track; + } + } + return found != nullptr ? editor_track::find_straight(*found, m_straights.tolerance) : editor_track::straight{}; +} + +editor_track::straight editor_mode::straight_through(glm::dvec3 const &Point, glm::dvec2 const &Direction) const +{ + for (auto *section : simulation::Region->sections(Point, 40.f)) + for (auto const &cell : section->m_cells) + for (auto *track : cell.m_paths) + { + if (track->eType != tt_Normal || track->m_editorremoved || track->m_paths.empty() || false == editor_track::is_straight(*track, m_straights.tolerance)) + continue; + auto const &path{track->m_paths.front()}; + auto const a{plan_of(path.points[segment_data::point::start])}; + auto const segment{plan_of(path.points[segment_data::point::end]) - a}; + auto const length{glm::length(segment)}; + if (length < 1e-6 || std::abs(cross(segment / length, Direction)) > 1e-3 || std::abs(cross(segment / length, plan_of(Point) - a)) > 0.02) + continue; + auto const t{glm::dot(plan_of(Point) - a, segment) / (length * length)}; + if (t >= -1e-6 && t <= 1.0 + 1e-6) + return editor_track::find_straight(*track, m_straights.tolerance); + } + return {}; +} + +bool editor_mode::plan_connection(connection::request &Request, connection::result &Result) const +{ + auto const &tool{m_switch}; + Result = {}; + if (false == tool.placing || tool.curved || tool.connection < 0 || tool.armed < 0 || tool.armed >= static_cast(tool.templates.size()) || tool.line.tracks.empty()) + return false; + auto const &line{tool.line}; + Request = {}; + Request.type = static_cast(tool.connection); + Request.from = connection::of(line); + Request.first = tool.templates[tool.armed]; + auto const second{tool.connection_second >= 0 && tool.connection_second < static_cast(tool.templates.size()) ? tool.connection_second : tool.armed}; + Request.second = tool.templates[second]; + Request.radius = tool.connection_radius; + Request.gap = tool.connection_gap; + Request.together = tool.connection_together; + Request.stub = tool.connection_stub; + Request.spacings = spacings_of(tool.connection_spacings); + Request.along = tool.along; + glm::dvec2 const offset{plan_of(tool.mouse - tool.point)}; + Request.forward = glm::dot(offset, line.direction) >= 0.0 ? 1 : -1; + glm::dvec2 const travel{line.direction * static_cast(Request.forward)}; + Request.side = cross(travel, offset) >= 0.0 ? 1 : -1; + std::vector const exclude(line.tracks.begin(), line.tracks.end()); + auto const other{straight_near(tool.mouse, exclude, 8.0)}; + if (false == other.tracks.empty()) + { + auto const target{connection::of(other)}; + if (Request.type != connection::kind::ladder) + { + Request.to.push_back(target); + Request.target = target.along(tool.mouse); + } + else if (std::abs(cross(target.direction, line.direction)) < 1e-3) + { + auto const side{cross(travel, plan_of(target.point(target.along(tool.point)) - tool.point)) > 0.0 ? 1.0 : -1.0}; + auto const lateral = [&](glm::dvec3 const &Point) { return side * cross(travel, plan_of(Point - tool.point)); }; + auto const outermost{lateral(target.point(target.along(tool.point)))}; + std::map> fan; + auto const better = [](double const One, double const Two) { return (One < 0.0) != (Two < 0.0) ? One >= 0.0 : std::abs(One) < std::abs(Two); }; + auto const centre{(tool.point + tool.mouse) * 0.5}; + for (auto *section : simulation::Region->sections(centre, static_cast(glm::length(offset) * 0.5 + 200.0))) + for (auto const &cell : section->m_cells) + for (auto *track : cell.m_paths) + { + if (track->eType != tt_Normal || track->m_editorremoved || track->m_paths.empty() || std::find(exclude.begin(), exclude.end(), track) != exclude.end() || false == editor_track::is_straight(*track, m_straights.tolerance)) + continue; + auto const &path{track->m_paths.front()}; + auto const a{path.points[segment_data::point::start]}; + auto const b{path.points[segment_data::point::end]}; + auto const direction{plan_of(b - a)}; + if (glm::length(direction) < 1e-6 || std::abs(cross(glm::normalize(direction), line.direction)) > 1e-3) + continue; + auto const distance{lateral(a)}; + auto const along1{glm::dot(travel, plan_of(a - tool.point))}; + auto const along2{glm::dot(travel, plan_of(b - tool.point))}; + if (distance < 1.0 || distance > outermost + 0.05 || std::max(along1, along2) <= 0.0) + continue; + auto const nearer{std::min(along1, along2)}; + auto &entry{fan[std::lround(distance * 20.0)]}; + if (entry.second == nullptr || better(nearer, entry.first)) + entry = {nearer, track}; + } + for (auto const &entry : fan) + Request.to.push_back(connection::of(editor_track::find_straight(*entry.second.second, m_straights.tolerance))); + } + } + Result = connection::plan(Request); + return Result.valid; +} + +void editor_mode::recognise_connection() +{ + auto &tool{m_switch}; + // a connection chosen by a script stays as it was chosen + if (false == tool.recognised && tool.connection >= 0) + return; + tool.connection = -1; + tool.recognised = false; + tool.partner = nullptr; + if (false == tool.placing || tool.free || tool.armed < 0 || tool.armed >= static_cast(tool.templates.size()) || tool.templates[tool.armed].double_slip || tool.templates[tool.armed].twofold()) + return; + auto const mark = [&](connection::kind const Kind) { + tool.connection = static_cast(Kind); + tool.recognised = true; + }; + // let go at a free end, the switch joins it + auto const own{tool.curved ? std::vector(tool.frame_tracks.begin(), tool.frame_tracks.end()) : std::vector(tool.line.tracks.begin(), tool.line.tracks.end())}; + if (editor_track::find_free_end(nullptr, ::track_mode::kRailCategory, tool.mouse, ::track_mode::kLaySnapRadius, own).track != nullptr) + return; + if (tool.curved) + { + // along a curve a crossover only, let go on the track running beside it + if (tool.frame.size() < 2 || plan_distance(sample_at(tool.frame, nearest_station(tool.frame, tool.mouse)).position, tool.mouse) < kOffTrack) + return; + for (auto *section : simulation::Region->sections(tool.mouse, 40.f)) + for (auto const &cell : section->m_cells) + for (auto *track : cell.m_paths) + if (track->eType == tt_Normal && false == track->m_editorremoved && false == track->m_paths.empty() && std::find(tool.frame_tracks.begin(), tool.frame_tracks.end(), track) == tool.frame_tracks.end() && + plan_distance(editor_track::point_at(*track, editor_track::nearest_parameter(*track, tool.mouse)), tool.mouse) < kOntoTrack) + { + mark(connection::kind::crossover); + return; + } + return; + } + if (tool.line.tracks.empty()) + return; + auto const line{connection::of(tool.line)}; + if (std::abs(line.lateral(tool.mouse)) < kOffTrack) + return; + std::vector const exclude(tool.line.tracks.begin(), tool.line.tracks.end()); + auto const other{straight_near(tool.mouse, exclude, kOntoTrack)}; + if (other.tracks.empty()) + return; + auto const otherline{connection::of(other)}; + mark(connection::kind::crossover); + // a crossover between the two tracks turned the other way: behind the press, or past it on the other track, a double crossover + // with it; over it a scissors one + auto const forward{glm::dot(plan_of(tool.mouse - tool.point), line.direction) >= 0.0 ? 1.0 : -1.0}; + auto const press{line.along(tool.point)}; + auto nearest{kDoubleGap}; + for (auto *section : simulation::Region->sections(tool.point, 200.f)) + for (auto const &cell : section->m_cells) + for (auto *track : cell.m_paths) + { + if (track->eType != tt_Switch || track->m_editorremoved || track->m_paths.size() < 2 || false == on_line(*track, line)) + continue; + auto const crossover{crossover_of(*track)}; + if (false == crossover.has_value()) + continue; + auto const *opposite{crossover->first == track ? crossover->second : crossover->first}; + if (false == on_line(*opposite, otherline)) + continue; + auto const &main{track->m_paths.front()}; + auto const way{glm::dot(plan_of(main.points[segment_data::point::end] - main.points[segment_data::point::start]), line.direction) >= 0.0 ? 1.0 : -1.0}; + if (way == forward) + continue; + // along this track in the way the crossover there runs from it to the other one: its switch here starts at 0, the one on + // the other track at Span; the one dragged, turned the other way, crosses it from 0 to twice that + auto const span{way * (line.along(opposite->m_paths.front().points[segment_data::point::start]) - line.along(main.points[segment_data::point::start]))}; + auto const at{way * (press - line.along(main.points[segment_data::point::start]))}; + if (span <= 0.0) + continue; + double gap; + bool together{false}; + if (at < 0.0) + { + gap = -at; + together = true; + } + else if (at > 2.0 * span) + gap = at - 2.0 * span; + else + gap = 0.0; + if (gap >= nearest) + continue; + nearest = gap; + tool.partner = track; + tool.connection = static_cast(at >= 0.0 && at <= 2.0 * span ? connection::kind::scissors : connection::kind::double_crossover); + tool.connection_together = together; + tool.connection_gap = gap; + } + if (tool.partner != nullptr) + return; + // across tracks running parallel between the two, a ladder onto all of them + if (std::abs(cross(other.direction, tool.line.direction)) < 1e-3) + { + tool.connection = static_cast(connection::kind::ladder); + connection::request request; + connection::result plan; + plan_connection(request, plan); + if (request.to.size() < 2) + tool.connection = static_cast(connection::kind::crossover); + } +} + +bool editor_mode::plan_partner_connection(connection::request &Request, connection::result &Result) const +{ + auto const &tool{m_switch}; + Result = {}; + auto const crossover{tool.partner != nullptr ? crossover_of(*tool.partner) : std::nullopt}; + if (false == crossover.has_value() || tool.connection < 0) + return false; + auto *opposite{crossover->first == tool.partner ? crossover->second : crossover->first}; + auto const shape{editor_track::template_of_switch(tool.partner)}; + if (false == shape.has_value()) + return false; + // on lines through the crossover there, the double or the scissors one starting with it + Request = {}; + Request.type = static_cast(tool.connection); + Request.from = line_through(*tool.partner); + Request.to = {line_through(*opposite)}; + Request.along = Request.from.along(tool.partner->m_paths.front().points[segment_data::point::start]); + Request.forward = 1; + Request.target = Request.to.front().along(opposite->m_paths.front().points[segment_data::point::start]); + Request.first = *shape; + Request.second = *shape; + Request.radius = tool.connection_radius; + Request.gap = tool.connection_gap; + Request.together = tool.connection_together; + Result = connection::plan(Request); + return Result.valid; +} + +void editor_mode::insert_partner_connection() +{ + auto &tool{m_switch}; + tool.placing = false; + connection::request request; + connection::result plan; + auto const fail = [&](std::string const &Reason) { + tool.status = Reason; + ui()->set_status(Reason, true); + flash_switch_problem(Reason, {}, {{tool.partner->location(), ""}}); + }; + if (false == plan_partner_connection(request, plan)) + return fail(plan.error.empty() ? std::string{STR_C("The connection doesn't fit with the crossover there")} : plan.error); + auto const crossover{crossover_of(*tool.partner)}; + auto *here{tool.partner}; + auto *opposite{crossover->first == here ? crossover->second : crossover->first}; + auto const armed{tool.armed}; + auto const shape{crossover_template(crossover->record)}; + tool.armed = armed; + if (shape < 0) + return fail(STR_C("The template the crossover was laid of isn't among the templates")); + auto const press{here->m_paths.front().points[segment_data::point::start]}; + auto const heading{plan_of(here->m_paths.front().points[segment_data::point::end] - press)}; + auto const release{opposite->m_paths.front().points[segment_data::point::start]}; + std::vector const names{here->name(), opposite->name()}; + // the crossover there taken out, then laid again with the other one, one step of the history + profile_library_load(); + auto library{m_profiles}; + std::vector> states; + std::vector created; + std::vector removed; + TTrack *first{nullptr}; + TTrack *second{nullptr}; + if (false == take_out_crossover(*crossover, states, created, removed, first, second)) + return fail(STR_C("The crossover there can't be taken out")); + auto *nearplain{crossover->first == here ? first : second}; + auto *farplain{crossover->first == here ? second : first}; + switch_store::follow(); + push_track_snapshot(std::move(states), std::move(created), std::move(removed)); + records_to_history(); + if (crossover->record.lifted()) + profiles_to_history(std::move(library)); + auto const from{editor_track::find_straight(*nearplain, m_straights.tolerance)}; + auto const to{editor_track::find_straight(*farplain, m_straights.tolerance)}; + if (from.tracks.empty() || to.tracks.empty()) + { + undo_last(); + return fail(STR_C("The tracks of the crossover there aren't straights")); + } + request.from = connection::of(from); + request.to = {connection::of(to)}; + request.along = request.from.along(press); + request.forward = glm::dot(request.from.direction, heading) >= 0.0 ? 1 : -1; + request.target = request.to.front().along(release); + request.first = tool.templates[shape]; + request.second = tool.templates[shape]; + plan = connection::plan(request); + tool.keep_names = names; + auto const laid{plan.valid && lay_planned_connection(request, plan, from.tracks.front())}; + tool.keep_names.clear(); + if (false == laid) + { + auto const reason{plan.valid ? tool.status : plan.error}; + undo_last(); + return fail(reason); + } + join_last_steps(); +} + +std::string editor_mode::connection_readout(connection::result const &Plan) const +{ + if (false == Plan.valid) + return Plan.error; + auto text{format(STR_C("%s: %d switches, spacing %.2f m"), connection_name(m_switch.connection), static_cast(Plan.switches.size()), Plan.spacing)}; + if (false == Plan.straights.empty()) + { + text += STR_C(", straight inserts"); + for (auto const length : Plan.straights) + text += format(" %.2f", length); + text += " m"; + } + if (Plan.points > 0.0) + text += format(STR_C(", mathematical points %.2f m apart"), Plan.points); + if (Plan.radius > 0.0) + text += format(STR_C(", aligning curve R %.0f m"), Plan.radius); + if (Plan.crossing && Plan.angle > 1e-6) + text += format(STR_C(", crossing 1:%.2f"), 1.0 / std::tan(Plan.angle)); + if (false == Plan.fan.empty()) + { + text += STR_C(", tracks at"); + for (auto const offset : Plan.fan) + text += format(" %.2f", offset); + text += " m"; + } + if (false == Plan.warning.empty()) + text += "\n" + Plan.warning; + return text; +} + +void editor_mode::insert_connection() +{ + auto &tool{m_switch}; + connection::request request; + connection::result plan; + auto const planned{plan_connection(request, plan)}; + // the switches as they'd go, blinking where they don't fit + auto const preview{planned ? std::vector{} : switch_preview()}; + tool.placing = false; + if (false == planned) + { + tool.status = plan.error.empty() ? std::string{STR_C("Drag onto the other track")} : plan.error; + ui()->set_status(tool.status, true); + flash_switch_problem(tool.status, preview, {{tool.mouse, ""}}); + return; + } + lay_planned_connection(request, plan, tool.line.tracks.front()); +} + +bool editor_mode::lay_planned_connection(connection::request const &Request, connection::result const &Plan, TTrack *Style) +{ + auto &tool{m_switch}; + auto const &request{Request}; + auto const &plan{Plan}; + std::vector> states; + std::vector created; + std::vector removed; + auto *style{Style}; + auto const fail = [&](std::string const &Reason) { + for (auto *track : created) + editor_track::retire(*track); + for (auto entry{states.rbegin()}; entry != states.rend(); ++entry) + { + editor_track::apply(*entry->first, entry->second); + editor_track::commit({entry->first}); + } + for (auto *track : removed) + { + editor_track::revive(*track); + editor_track::commit({track}); + } + if (auto before{switch_store::take_changes()}) + switch_store::restore(std::move(*before)); + if (auto before{alignment_store::take_changes()}) + alignment_store::restore(std::move(*before)); + straight_refresh(); + tool.status = Reason; + ui()->set_status(Reason, true); + }; + std::vector switches; + for (auto const &entry : plan.switches) + { + auto const &shape{entry.second ? request.second : request.first}; + auto const name{switch_name_for_new()}; + auto const before{created.size()}; + auto const start{entry.paths[0].points[segment_data::point::start]}; + auto const end{entry.paths[0].points[segment_data::point::end]}; + if (entry.line >= 0) + { + auto const &target{entry.line == 0 ? request.from : request.to[entry.line - 1]}; + auto const found{straight_through((start + end) * 0.5, target.direction)}; + if (found.tracks.empty()) + { + fail(STR_C("A switch of the connection goes where its track isn't a plain straight")); + return false; + } + auto const forward{glm::dot(found.direction, plan_of(end - start)) > 0.0 ? 1 : -1}; + if (false == place_switch_on_straight(found, shape, nullptr, found.along(start), forward, entry.side, false, states, created, removed, name)) + { + fail(tool.status); + return false; + } + } + else + { + auto const made{create_switch_set(shape, entry.paths, *style, name)}; + if (made.empty()) + { + fail(tool.status); + return false; + } + created.insert(created.end(), made.begin(), made.end()); + } + auto const made{std::find_if(created.begin() + static_cast(before), created.end(), [](TTrack const *Track) { return Track != nullptr && Track->eType == tt_Switch; })}; + // in the plan: the height is the track's there, which needn't keep to one grade as the line of the plan does + if (made == created.end() || plan_distance((*made)->m_paths.front().points[segment_data::point::start], start) > 0.01) + { + fail(STR_C("A switch of the connection doesn't fit where it was planned, its straight is too short")); + return false; + } + switches.push_back(*made); + advance_switch_name(); + } + // the inserts meet the switches at the heights they were put at + std::vector ends; + for (auto const *track : switches) + for (auto const &path : track->m_paths) + for (auto const index : {segment_data::point::start, segment_data::point::end}) + ends.push_back(path.points[index]); + std::vector inserts; + for (auto insert : plan.inserts) + { + for (auto const index : {segment_data::point::start, segment_data::point::end}) + for (auto const &end : ends) + if (plan_distance(insert.points[index], end) < 0.05) + { + insert.points[index].y = end.y; + break; + } + if (auto *track{editor_track::create_path(*style, insert)}) + inserts.push_back(track); + } + editor_track::commit(inserts); + digitize_drawn(inserts); + created.insert(created.end(), inserts.begin(), inserts.end()); + if (plan.crossing) + { + auto const first{glm::normalize(plan_of(plan.ends[1] - plan.ends[0]))}; + auto second{glm::normalize(plan_of(plan.ends[3] - plan.ends[2]))}; + if (glm::dot(first, second) < 0.0) + second = -second; + auto const parts{build_double_slip(plan.ends[0], plan.ends[1], plan.ends[2], plan.ends[3], plan_of(plan.centre), plan.centre.y, first, second, plan.angle, editor_track::slip_curve{}, *style, "Skrz")}; + editor_track::commit(parts); + created.insert(created.end(), parts.begin(), parts.end()); + } + record_connection(request.type, switches, plan, request.first); + push_track_snapshot(std::move(states), std::move(created), std::move(removed)); + straight_refresh(); + first_step_done(first_step::turnout); + m_track_point = {}; + m_node = switches.front(); + ui()->set_node(m_node); + std::string names; + for (auto *track : switches) + { + if (place_switch_drive(*track)) + join_last_steps(); + names += (names.empty() ? "" : ", ") + track->name(); + } + tool.status = format(STR_C("%s laid, switches %s"), connection_name(static_cast(request.type)), names.c_str()) + "\n" + connection_readout(plan); + ui()->set_status(tool.status, false); + return true; +} + +void editor_mode::render_connection_options() +{ + auto &tool{m_switch}; + // of the connections a switch dragged onto the track beside makes + if (false == begin_fields("##connectionoptions")) + return; + auto const label = [&](int const Index) { return Index < 0 || Index >= static_cast(tool.templates.size()) ? std::string{STR_C("The same as the first one")} : switch_template_label(tool.templates[Index]); }; + field_row("Other switches of a connection##connectionsecond"); + if (ImGui::BeginCombo("##connectionsecond", label(tool.connection_second).c_str())) + { + if (ImGui::Selectable(STR_C("The same as the first one"), tool.connection_second < 0)) + tool.connection_second = -1; + for (int i = 0; i < static_cast(tool.templates.size()); ++i) + if (usable_in_connection(tool.templates[i]) && ImGui::Selectable((switch_template_label(tool.templates[i]) + "##connectionsecond" + std::to_string(i)).c_str(), tool.connection_second == i)) + tool.connection_second = i; + ImGui::EndCombo(); + } + item_tooltip("Template of the switches on the other track and along a ladder, when a switch is dragged onto the track beside; the first switch is the one chosen on the list above"); + field_row("Aligning curve R, m##connectionradius"); + ImGui::InputDouble("##connectionradius", &tool.connection_radius, 10.0, 100.0, "%.0f"); + tool.connection_radius = std::clamp(tool.connection_radius, 0.0, 10000.0); + item_tooltip("Of the curve between switches of different angles or on tracks that aren't parallel, and at the end of a ladder; 0: the radius of the sharper switch"); + ImGui::EndTable(); +} diff --git a/application/editormodeconnectioncurve.cpp b/application/editormodeconnectioncurve.cpp new file mode 100644 index 000000000..15e8f8c67 --- /dev/null +++ b/application/editormodeconnectioncurve.cpp @@ -0,0 +1,1124 @@ +/* +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/. +*/ + +// a crossover between two tracks running side by side along a curve: planned as between straights in the frame of the curve +// (along it, across it) and laid onto the curve, the switches, the insert and the other track on the plane the cant tilts the +// inner track to. The outer track goes up to that plane over the crossover, with ramps on both sides + +#include "stdafx.h" +#include "application/editormode.h" +#include "application/editoruilayer.h" +#include "application/editormodeshared.h" +#include "application/editormodetrackshared.h" +#include "editor/editorFormat.hpp" +#include "editor/editorGeometry.hpp" +#include "editor/editorSwitchStore.hpp" +#include "simulation/simulation.h" +#include "utilities/Logs.h" +#include "utilities/translation.h" +#include "world/Track.h" + +#include + +using geometry::bezier; +using geometry::plan_distance; +using geometry::plan_of; + +namespace +{ + +// of the ramps the outer track goes up to the crossover and down from it by, a share of the change of grade which needs a +// vertical curve: the ramps break the grade line without one +double constexpr kRampShare{0.9}; +double constexpr kOtherReach{10.0}; // m, from the release to the other track +double constexpr kStraightReach{track_mode::kCrossoverStraights}; + +// the first curved track a straight track leads to along its straight, either way, within the reach +TTrack *curve_ahead(TTrack &Track, editor_track::straight_tolerance const &Tolerance, double const Reach) +{ + TTrack *found{nullptr}; + auto nearest{Reach}; + for (auto const throughend : {true, false}) + { + TTrack const *previous{&Track}; + TTrack *current{throughend ? Track.trNext : Track.trPrev}; + double distance{0.0}; + for (int count = 0; current != nullptr && count < 1000 && distance < nearest; ++count) + { + if (current->eType != tt_Normal || current->m_editorremoved || current->m_paths.empty()) + break; + if (false == editor_track::is_straight(*current, Tolerance)) + { + found = current; + nearest = distance; + break; + } + auto const &path{current->m_paths.front()}; + distance += plan_distance(path.points[segment_data::point::start], path.points[segment_data::point::end]); + auto *next{current->trPrev == previous ? current->trNext : current->trPrev}; + previous = current; + current = next; + } + } + return found; +} + +// the lift of the outer track along its line: from First at the chainage From to Second at To in a straight line, down to none over +// the ramps beyond them +struct outer_lift +{ + double from, to; + double first, second; + double ramp; + + double at(double const Chainage) const + { + if (Chainage <= from - ramp || Chainage >= to + ramp) + return 0.0; + if (Chainage < from) + return first * (Chainage - (from - ramp)) / ramp; + if (Chainage > to) + return second * ((to + ramp) - Chainage) / ramp; + return to - from > 1e-6 ? first + (second - first) * (Chainage - from) / (to - from) : first; + } + double grade(double const Chainage) const + { + if (Chainage > from - ramp && Chainage < from) + return first / ramp; + if (Chainage > to && Chainage < to + ramp) + return -second / ramp; + if (Chainage >= from && Chainage <= to && to - from > 1e-6) + return (second - first) / (to - from); + return 0.0; + } + std::vector breaks(double const Length) const + { + std::vector found; + for (auto const chainage : {from - ramp, from, to, to + ramp}) + if (chainage > 0.5 && chainage < Length - 0.5) + found.push_back(chainage); + return found; + } +}; + +} // namespace + +// the plan of a connection between straights laid onto the curve: its x across the curve, minus to the left, its z the station +struct editor_mode::curve_mapping +{ + std::vector const &frame; + + glm::dvec3 point(glm::dvec3 const &Local) const + { + auto const sample{sample_at(frame, Local.z)}; + glm::dvec2 const left{-sample.tangent.y, sample.tangent.x}; + auto const lateral{-Local.x}; + auto const planar{plan_of(sample.position) + left * lateral}; + return {planar.x, sample.position.y + Local.y - lateral * std::tan(glm::radians(static_cast(sample.roll))), planar.y}; + } + glm::dvec2 tangent(glm::dvec3 const &Local, glm::dvec2 const &Direction) const + { + auto const sample{sample_at(frame, Local.z)}; + glm::dvec2 const left{-sample.tangent.y, sample.tangent.x}; + return glm::normalize(sample.tangent * Direction.y - left * Direction.x); + } + float roll(glm::dvec3 const &Local) const { return sample_at(frame, Local.z).roll; } + // the height of the tilted plane at the point of the plan + double height(glm::dvec2 const &Planar) const + { + auto const sample{sample_at(frame, nearest_station(frame, {Planar.x, 0.0, Planar.y}))}; + auto const lateral{glm::dot(Planar - plan_of(sample.position), glm::dvec2{-sample.tangent.y, sample.tangent.x})}; + return sample.position.y - lateral * std::tan(glm::radians(static_cast(sample.roll))); + } + + segment_data path(segment_data const &Local) const + { + auto const &start{Local.points[segment_data::point::start]}; + auto const &end{Local.points[segment_data::point::end]}; + auto const &control1{Local.points[segment_data::point::control1]}; + auto const &control2{Local.points[segment_data::point::control2]}; + glm::dvec2 const chord{end.x - start.x, end.z - start.z}; + auto const localstart{glm::normalize(control1 != glm::dvec3{} ? plan_of(control1) : chord)}; + auto const localend{glm::normalize(control2 != glm::dvec3{} ? -plan_of(control2) : chord)}; + auto const p0{point(start)}; + auto const p3{point(end)}; + auto const t0{tangent(start, localstart)}; + auto const t3{tangent(end, localend)}; + auto const handle{plan_distance(p0, p3) / 3.0}; + segment_data result; + result.points[segment_data::point::start] = p0; + result.points[segment_data::point::end] = p3; + result.points[segment_data::point::control1] = {t0.x * handle, (p3.y - p0.y) / 3.0, t0.y * handle}; + result.points[segment_data::point::control2] = {-t3.x * handle, -(p3.y - p0.y) / 3.0, -t3.y * handle}; + // the heights of the inner points on the tilted plane + auto const h1{height(plan_of(bezier{result}.point(1.0 / 3.0)))}; + auto const h2{height(plan_of(bezier{result}.point(2.0 / 3.0)))}; + auto const y1{3.0 * h1 - 1.5 * h2 - 5.0 / 6.0 * p0.y + p3.y / 3.0}; + auto const y2{3.0 * h2 - 1.5 * h1 + p0.y / 3.0 - 5.0 / 6.0 * p3.y}; + result.points[segment_data::point::control1].y = y1 - p0.y; + result.points[segment_data::point::control2].y = y2 - p3.y; + // the cant of a path is told along it: a path running against the stations of the curve has it the other way round + result.rolls = {roll(start) * (localstart.y >= 0.0 ? 1.f : -1.f), roll(end) * (localend.y >= 0.0 ? 1.f : -1.f)}; + result.radius = Local.radius; + bezier const curve{result}; + auto const begin{plan_of(curve.first(0.0))}; + auto const finish{plan_of(curve.first(1.0))}; + auto const turn{glm::length(begin) > 1e-9 && glm::length(finish) > 1e-9 ? geometry::signed_angle(begin, finish) : 0.0}; + if (std::abs(turn) > 1e-6) + result.radius = static_cast(curve.plan_length() / turn); + else + result.radius = 0.f; + for (auto const &piece : Local.pieces) + result.pieces.push_back(path(piece)); + return result; + } +}; + +// the curve the track is a part of, as a frame of samples, and its tracks +bool editor_mode::curve_of(TTrack &Track, editor_track::straight_tolerance const &Tolerance, double const Gauge, std::vector &Frame, std::vector &Tracks, double const Beyond) +{ + auto *base{&Track}; + if (Beyond > 0.0 && Track.eType == tt_Normal && editor_track::is_straight(Track, Tolerance)) + base = curve_ahead(Track, Tolerance, Beyond); + if (base == nullptr) + return false; + editor_track::curve curve; + editor_track::chain chain; + std::string error; + if (false == editor_track::find_curve(*base, Tolerance, Gauge, curve) || false == editor_track::find_chain(curve.from, curve.to, chain, error, true)) + return false; + for (auto const &part : editor_track::chain_parts(chain)) + if (std::find(part.tracks.begin(), part.tracks.end(), base) != part.tracks.end()) + { + chain = part; + break; + } + if (Beyond > 0.0) + { + // the straights past both ends, as far as the reach, taken along the curve: the one before it from its far end + auto const taken = [&](editor_track::straight_run const &Run) { + std::size_t count{0}; + for (double reached{0.0}; count < Run.tracks.size() && reached < Beyond; ++count) + { + auto const &path{Run.tracks[count]->m_paths.front()}; + reached += plan_distance(path.points[segment_data::point::start], path.points[segment_data::point::end]); + } + return count; + }; + auto const before{editor_track::straight_beyond(chain, false, Tolerance)}; + auto const after{editor_track::straight_beyond(chain, true, Tolerance)}; + editor_track::chain extended; + for (auto i{taken(before)}; i-- > 0;) + { + extended.tracks.push_back(before.tracks[i]); + extended.forward.push_back(false == before.outward[i]); + } + extended.tracks.insert(extended.tracks.end(), chain.tracks.begin(), chain.tracks.end()); + extended.forward.insert(extended.forward.end(), chain.forward.begin(), chain.forward.end()); + for (std::size_t i = 0, count = taken(after); i < count; ++i) + { + extended.tracks.push_back(after.tracks[i]); + extended.forward.push_back(after.outward[i]); + } + chain = std::move(extended); + } + if (std::find(chain.tracks.begin(), chain.tracks.end(), &Track) == chain.tracks.end()) + return false; + Frame = sample_chain(chain); + Tracks = chain.tracks; + return Frame.size() >= 2; +} + +// the paths of the curve between the points cut off at both, right at the points, and taken out, the switch to go in their place +void editor_mode::cut_curve(std::vector &Candidates, std::vector const &Frame, glm::dvec3 const &First, glm::dvec3 const &Second, std::vector> &States, std::vector &Created, std::vector &Removed) +{ + auto const one{nearest_station(Frame, First)}; + auto const two{nearest_station(Frame, Second)}; + auto const From{std::min(one, two)}; + auto const To{std::max(one, two)}; + for (auto const &point : {First, Second}) + { + for (auto *candidate : std::vector(Candidates)) + { + if (candidate->m_editorremoved || candidate->eType != tt_Normal) + continue; + auto const t{editor_track::nearest_parameter(*candidate, point)}; + if (plan_distance(editor_track::point_at(*candidate, t), point) > 0.05) + continue; + if (t > 0.002 && t < 0.998) + { + if (std::find(Created.begin(), Created.end(), candidate) == Created.end() && std::none_of(States.begin(), States.end(), [&](auto const &Entry) { return Entry.first == candidate; })) + States.emplace_back(candidate, editor_track::capture(*candidate)); + if (auto *second{editor_track::split_path(*candidate, t)}) + { + Created.push_back(second); + Candidates.push_back(second); + } + } + break; + } + } + for (auto *candidate : Candidates) + { + if (candidate->m_editorremoved) + continue; + auto const where{nearest_station(Frame, editor_track::point_at(*candidate, 0.5))}; + if (where > From + 0.01 && where < To - 0.01) + { + editor_track::retire(*candidate); + // a piece split off in this step goes as if it had never been made: kept among the ones made and the ones taken out + // too, an undo would retire it and then bring it back + if (auto const made{std::find(Created.begin(), Created.end(), candidate)}; made != Created.end()) + Created.erase(made); + else + Removed.push_back(candidate); + } + } +} + +void editor_mode::insert_curved_connection() +{ + auto &tool{m_switch}; + tool.placing = false; + auto const fail = [&](std::string const &Reason) { + tool.status = Reason; + ui()->set_status(Reason, true); + flash_switch_problem(Reason, {}, {{tool.point, ""}}); + }; + if (tool.connection != static_cast(connection::kind::crossover)) + return fail(STR("Along a curve only a crossover can be laid")); + // the curve pressed on with the straights past its ends: from a transition the crossover goes on onto the straight + auto pressedframe{tool.frame}; + auto pressedtracks{tool.frame_tracks}; + auto *pressed{tool.frame_tracks.front()}; + { + auto nearest{std::numeric_limits::max()}; + for (auto *track : tool.frame_tracks) + if (false == track->m_editorremoved) + if (auto const distance{plan_distance(editor_track::point_at(*track, editor_track::nearest_parameter(*track, tool.point)), tool.point)}; distance < nearest) + { + nearest = distance; + pressed = track; + } + std::vector frame; + std::vector tracks; + if (curve_of(*pressed, m_straights.tolerance, m_route.design.norms.gauge, frame, tracks, kStraightReach)) + { + pressedframe = std::move(frame); + pressedtracks = std::move(tracks); + } + } + // the other track: one beside this curve near the release, running along with it + TTrack *other{nullptr}; + auto best{kOtherReach}; + for (auto *track : simulation::Paths.sequence()) + { + if (track == nullptr || track->m_editorremoved || track->eType != tt_Normal || track->m_paths.empty() || std::find(pressedtracks.begin(), pressedtracks.end(), track) != pressedtracks.end()) + continue; + auto const distance{plan_distance(editor_track::point_at(*track, editor_track::nearest_parameter(*track, tool.mouse)), tool.mouse)}; + if (distance < best) + { + best = distance; + other = track; + } + } + if (other == nullptr) + return fail(STR("Drag onto the other track")); + std::vector otherframe; + std::vector othertracks; + if (false == curve_of(*other, m_straights.tolerance, m_route.design.norms.gauge, otherframe, othertracks, kStraightReach)) + return fail(STR("The other track isn't a curve running along this one")); + // the inner track is the frame: the plane of its cant carries the crossover, the outer track goes up onto it + auto innerframe{pressedframe}; + auto innertracks{pressedtracks}; + auto station{nearest_station(innerframe, tool.point)}; + auto const at{sample_at(innerframe, station)}; + auto const across{sample_at(otherframe, nearest_station(otherframe, at.position))}; + glm::dvec2 const left{-at.tangent.y, at.tangent.x}; + auto offset{glm::dot(plan_of(across.position) - plan_of(at.position), left)}; + auto lift{at.position.y - offset * std::tan(glm::radians(static_cast(at.roll))) - across.position.y}; + bool swapped{false}; + if (lift < -0.005) + { + // the plane falls towards the other track: that one is the inner one + std::swap(innerframe, otherframe); + std::swap(innertracks, othertracks); + station = nearest_station(innerframe, at.position); + auto const inner{sample_at(innerframe, station)}; + glm::dvec2 const innerleft{-inner.tangent.y, inner.tangent.x}; + offset = glm::dot(plan_of(at.position) - plan_of(inner.position), innerleft); + lift = inner.position.y - offset * std::tan(glm::radians(static_cast(inner.roll))) - at.position.y; + swapped = true; + } + WriteLog(format("Editor: curved crossover - at station %.1f, inner roll %.3f deg, other roll %.3f deg, offset %.3f m, lift %.3f m%s", station, at.roll, across.roll, offset, lift, swapped ? ", the other track is the inner one" : ""), logtype::generic); + if (std::abs(offset) < 3.0 || std::abs(offset) > 30.0) + return fail(format(STR_C("The tracks are %.2f m apart, too close or too far for a crossover"), std::abs(offset))); + + // the crossover planned as between two straights, in the frame of the inner curve + auto const total{innerframe.back().station}; + connection::request request; + request.type = connection::kind::crossover; + request.from.start = {0.0, 0.0, 0.0}; + request.from.direction = {0.0, 1.0}; + request.from.length = total; + connection::line to; + to.start = {-offset, 0.0, 0.0}; + to.direction = {0.0, 1.0}; + to.length = total; + request.to.push_back(to); + request.first = tool.templates[tool.armed]; + auto const second{tool.connection_second >= 0 && tool.connection_second < static_cast(tool.templates.size()) ? tool.connection_second : tool.armed}; + request.second = tool.templates[second]; + request.radius = tool.connection_radius; + auto const release{nearest_station(innerframe, tool.mouse)}; + auto const press{swapped ? nearest_station(innerframe, tool.point) : station}; + request.forward = release >= press ? 1 : -1; + // the plan starts on the track pressed on + if (swapped) + { + request.from.start = {-offset, 0.0, 0.0}; + request.to.front().start = {0.0, 0.0, 0.0}; + } + request.along = press; + request.target = release; + // the side of the travel along the starting track the other one lies on + auto const across_plan{request.to.front().start.x - request.from.start.x}; + request.side = -request.forward * across_plan >= 0.0 ? 1 : -1; + auto plan{connection::plan(request)}; + if (false == plan.valid) + { + // the other side, if the side was taken the wrong way round + request.side = -request.side; + plan = connection::plan(request); + } + if (false == plan.valid) + return fail(plan.error.empty() ? std::string{STR("The crossover doesn't fit on the curve")} : plan.error); + + curve_mapping const mapping{innerframe}; + std::vector> states; + std::vector created; + std::vector removed; + auto *style{pressed}; + // the kept grade lines before the outer track went up, the design of which goes up with it + std::optional> library; + auto const undo_all = [&]() { + for (auto *track : created) + editor_track::retire(*track); + for (auto entry{states.rbegin()}; entry != states.rend(); ++entry) + { + editor_track::apply(*entry->first, entry->second); + editor_track::commit({entry->first}); + } + for (auto *track : removed) + { + editor_track::revive(*track); + editor_track::commit({track}); + } + if (library.has_value()) + profiles_restore(std::move(*library)); + straight_refresh(); + }; + + // the outer track up onto the plane of the inner one over the crossover, with ramps on both sides + auto const outerline{swapped ? 0 : 1}; + double low{std::numeric_limits::max()}, high{std::numeric_limits::lowest()}; + for (auto const &entry : plan.switches) + for (auto const &path : entry.paths) + for (auto const end : {segment_data::point::start, segment_data::point::end}) + { + low = std::min(low, path.points[end].z); + high = std::max(high, path.points[end].z); + } + auto *outertrack{swapped ? pressed : other}; + for (auto const &entry : plan.switches) + WriteLog(format("Editor: curved crossover - planned switch on %d: %.3f %.3f -> %.3f %.3f; extent %.3f..%.3f", entry.line, entry.paths.front().points[segment_data::point::start].x, entry.paths.front().points[segment_data::point::start].z, entry.paths.front().points[segment_data::point::end].x, entry.paths.front().points[segment_data::point::end].z, low, high), logtype::generic); + glm::dvec3 flatfrom{0.0}, flatto{0.0}; + outer_lift raise{0.0, 0.0, 0.0, 0.0, 0.0}; + { + auto route{editor_track::run_route(*outertrack, 3000.0)}; + auto const samples{editor_track::sample_route(route, 1.0)}; + if (samples.size() < 2) + return fail(STR("The outer track can't be followed")); + // the chainage of the point projected onto the line between the samples + auto const chainage_of = [&](glm::dvec3 const &Point) { + double best{std::numeric_limits::max()}; + double chainage{0.0}; + for (std::size_t i = 0; i + 1 < samples.size(); ++i) + { + auto const a{plan_of(samples[i].position)}; + auto const run{plan_of(samples[i + 1].position) - a}; + auto const t{std::clamp(glm::dot(plan_of(Point) - a, run) / std::max(1e-12, glm::dot(run, run)), 0.0, 1.0)}; + if (auto const distance{glm::length(plan_of(Point) - (a + run * t))}; distance < best) + { + best = distance; + chainage = samples[i].chainage + (samples[i + 1].chainage - samples[i].chainage) * t; + } + } + return chainage; + }; + // the outer track lies at -offset in the frame of the inner one, whichever of them was pressed on + auto const outerx{-offset}; + auto c1{chainage_of(mapping.point({outerx, 0.0, low}))}; + auto c2{chainage_of(mapping.point({outerx, 0.0, high}))}; + // the top of the ramps where the switch on the outer track ends: no short paths left between the two + if (c1 > c2) + std::swap(c1, c2); + // the switch on the outer track lies on the plane of the inner one at both its ends: the grade lines of the two tracks needn't run + // alike, so the lift goes along in a straight line through what the two ends need + auto ca{c1}, cb{c2}; + auto la{lift}, lb{lift}; + for (auto const &entry : plan.switches) + if (entry.line == outerline) + { + auto const path{mapping.path(entry.paths.front())}; + auto const &a{path.points[segment_data::point::start]}; + auto const &b{path.points[segment_data::point::end]}; + ca = chainage_of(a); + cb = chainage_of(b); + la = a.y - editor_track::sampled_elevation(samples, ca); + lb = b.y - editor_track::sampled_elevation(samples, cb); + break; + } + auto const rise{std::abs(cb - ca) > 1.0 ? (lb - la) / (cb - ca) : 0.0}; + raise = {c1, c2, la + rise * (c1 - ca), la + rise * (c2 - ca), 0.0}; + if (std::max(std::abs(raise.first), std::abs(raise.second)) > 0.002) + { + raise.ramp = std::max(std::abs(raise.first), std::abs(raise.second)) / (std::max(0.5, kRampShare * m_profile.line.norms.curve_threshold) / 1000.0); + flatfrom = editor_track::sampled_position(samples, c1); + flatto = editor_track::sampled_position(samples, c2); + auto const breaks{raise.breaks(route.length)}; + // the design of the outer track before, kept or read from the track, to go up with it + auto *first{route.spans.front().track}; + auto *last{route.spans.back().track}; + profile_library_load(); + library = m_profiles; + profile_take(route, first, last); + auto const before{m_profile.line}; + std::vector> raisestates; + std::vector raisecreated; + editor_track::apply_profile( + route, [&](double const Chainage) { return editor_track::sampled_elevation(samples, Chainage) + raise.at(Chainage); }, + [&](double const Chainage) { return editor_track::sampled_grade(samples, Chainage) + raise.grade(Chainage); }, breaks, raisestates, raisecreated); + states.insert(states.end(), raisestates.begin(), raisestates.end()); + created.insert(created.end(), raisecreated.begin(), raisecreated.end()); + // the raised grade line kept as the design of the outer track, in place of the one it had: its points gone up with it + // and the corners of the ramps, straight between them as the ramps are + if (false == route.spans.empty()) + { + profile_take(route, route.spans.front().track, route.spans.back().track); + std::vector points; + for (auto point : before.points) + { + point.elevation += raise.at(point.chainage); + points.push_back(point); + } + for (auto const chainage : breaks) + { + profile::pvi corner; + corner.chainage = chainage; + corner.elevation = profile::elevation(before, chainage) + raise.at(chainage); + corner.automatic = false; + points.push_back(corner); + } + std::sort(points.begin(), points.end(), [](auto const &Left, auto const &Right) { return Left.chainage < Right.chainage; }); + std::vector line; + for (auto const &point : points) + { + if (false == line.empty() && point.chainage - line.back().chainage < 0.5) + { + // the corner of a ramp before a point of the design at the same place + if (false == point.automatic && point.radius == 0.0) + line.back() = point; + continue; + } + line.push_back(point); + } + if (line.size() >= 2) + { + m_profile.line = before; + m_profile.line.points = std::move(line); + m_profile.selected = -1; + profile_check(); + profile_store(); + } + } + WriteLog(format("Editor: curved crossover - the outer track %s raised by %.3f .. %.3f m from %.1f to %.1f m of its line, ramps %.1f m", outertrack->name().c_str(), raise.first, raise.second, c1, c2, raise.ramp), logtype::generic); + } + } + // the outer curve again, as it lies now + std::vector outerframe; + std::vector outertracks; + { + auto const probe{mapping.point({-offset, 0.0, 0.5 * (low + high)})}; + TTrack *closest{nullptr}; + auto nearest{1.0}; + for (auto *track : simulation::Paths.sequence()) + { + if (track == nullptr || track->m_editorremoved || track->eType != tt_Normal || track->m_paths.empty()) + continue; + auto const distance{plan_distance(editor_track::point_at(*track, editor_track::nearest_parameter(*track, probe)), probe)}; + if (distance < nearest) + { + nearest = distance; + closest = track; + } + } + if (closest == nullptr || false == curve_of(*closest, m_straights.tolerance, m_route.design.norms.gauge, outerframe, outertracks, kStraightReach)) + { + undo_all(); + return fail(STR("The outer track can't be followed after it went up")); + } + } + // the inner curve again: the outer track may be split where the ramps end + if (false == swapped) + innertracks = pressedtracks; + + std::vector switches; + for (auto const &entry : plan.switches) + { + auto const &shape{entry.second ? request.second : request.first}; + std::vector paths; + for (auto const &local : entry.paths) + paths.push_back(mapping.path(local)); + auto const onouter{entry.line == outerline}; + auto &frame{onouter ? outerframe : innerframe}; + auto &candidates{onouter ? outertracks : innertracks}; + // the other track runs along at the distance the crossover was planned for, else its switch would miss it + for (auto const end : {segment_data::point::start, segment_data::point::end}) + { + auto const &point{paths.front().points[end]}; + if (auto const off{plan_distance(sample_at(frame, nearest_station(frame, point)).position, point)}; off > 0.1) + { + WriteLog(format("Editor: curved crossover - the switch on %s misses it by %.3f m at %.3f %.3f, station %.1f of %.1f", onouter ? "the outer track" : "the inner track", off, point.x, point.z, nearest_station(frame, point), frame.empty() ? 0.0 : frame.back().station), + logtype::generic); + undo_all(); + return fail(STR("The other track doesn't run along at the same distance there")); + } + } + cut_curve(candidates, frame, paths.front().points[segment_data::point::start], paths.front().points[segment_data::point::end], states, created, removed); + // the ends of the main track of the switch onto the ends of the paths cut off, which the curve put a little apart + auto const snap = [&](glm::dvec3 const &Point) { + glm::dvec3 found{Point}; + auto nearest{0.1}; + for (auto *candidate : candidates) + { + if (candidate->m_editorremoved || candidate->m_paths.empty()) + continue; + for (auto const which : {segment_data::point::start, segment_data::point::end}) + if (auto const distance{glm::distance(candidate->m_paths.front().points[which], Point)}; distance < nearest) + { + nearest = distance; + found = candidate->m_paths.front().points[which]; + } + } + return found; + }; + auto const begin{paths.front().points[segment_data::point::start]}; + auto const finish{paths.front().points[segment_data::point::end]}; + auto const start{snap(begin)}; + auto const end{snap(finish)}; + for (auto &path : paths) + { + if (glm::distance(path.points[segment_data::point::start], begin) < 1e-6) + { + path.points[segment_data::point::start] = start; + if (false == path.pieces.empty()) + path.pieces.front().points[segment_data::point::start] = start; + } + } + paths.front().points[segment_data::point::end] = end; + if (false == paths.front().pieces.empty()) + paths.front().pieces.back().points[segment_data::point::end] = end; + auto const made{create_switch_set(shape, paths, *style, switch_name_for_new())}; + if (made.empty()) + { + undo_all(); + return fail(tool.status.empty() ? std::string{STR("A switch of the crossover couldn't be made")} : tool.status); + } + created.insert(created.end(), made.begin(), made.end()); + for (auto *track : made) + if (track->eType == tt_Switch) + switches.push_back(track); + advance_switch_name(); + } + std::vector inserts; + for (auto const &insert : plan.inserts) + if (auto *track{editor_track::create_path(*style, mapping.path(insert))}) + inserts.push_back(track); + editor_track::commit(inserts); + digitize_drawn(inserts); + created.insert(created.end(), inserts.begin(), inserts.end()); + if (switches.empty()) + { + undo_all(); + return fail(STR("The crossover couldn't be laid")); + } + record_connection(request.type, switches, plan, request.first); + // the lift kept with the crossover, so it can be taken back when the crossover moves or goes + if (raise.ramp > 0.0) + for (auto entry : switch_store::connections(*switches.front())) + if (entry.kind == "connection" && entry.name == switches.front()->name()) + { + entry.lift = raise.first; + entry.lift_end = raise.second; + entry.lift_from = flatfrom; + entry.lift_to = flatto; + entry.ramp = raise.ramp; + switch_store::put(entry, entry.layer); + } + push_track_snapshot(std::move(states), std::move(created), std::move(removed)); + // the design of the outer track goes back down with it + if (library.has_value()) + profiles_to_history(std::move(*library)); + straight_refresh(); + first_step_done(first_step::turnout); + m_node = switches.front(); + ui()->set_node(m_node); + std::string names; + for (auto *track : switches) + { + if (place_switch_drive(*track)) + join_last_steps(); + names += (names.empty() ? "" : ", ") + track->name(); + } + tool.status = format(STR_C("Crossover laid along the curve, switches %s, the tracks %.2f m apart"), names.c_str(), std::abs(offset)); + if (raise.ramp > 0.0) + tool.status += format(STR_C("\nThe outer track went up %.3f m onto the plane of the cant of the inner one, with ramps of %.1f per mille"), std::max(std::abs(raise.first), std::abs(raise.second)), std::max(0.5, kRampShare * m_profile.line.norms.curve_threshold)); + tool.status += "\n" + connection_readout(plan); + ui()->set_status(tool.status, false); +} + +// the crossover laid along a curve the switch is a part of: its record, its two switches and the insert between them +std::optional editor_mode::crossover_of(TTrack const &Switch) const +{ + if (Switch.eType != tt_Switch || Switch.m_editorremoved) + return std::nullopt; + for (auto const &entry : switch_store::connections(Switch)) + { + if (entry.kind != "connection" || entry.type != connection::word(connection::kind::crossover) || entry.parts.size() != 2) + continue; + curved_crossover result; + result.record = entry; + result.first = simulation::Paths.find(entry.parts[0]); + result.second = simulation::Paths.find(entry.parts[1]); + if (result.first == nullptr || result.second == nullptr || result.first->m_editorremoved || result.second->m_editorremoved || result.first->m_paths.size() < 2 || result.second->m_paths.size() < 2) + continue; + auto const &end{result.first->m_paths[1].points[segment_data::point::end]}; + auto const &other{result.second->m_paths[1].points[segment_data::point::end]}; + for (auto const &[track, point] : editor_track::connected_points(*result.first, end)) + { + if (track == nullptr || track->m_editorremoved || track->eType != tt_Normal || track->m_paths.size() != 1) + continue; + auto const &path{track->m_paths.front()}; + if (plan_distance(path.points[segment_data::point::start], other) < 0.05 || plan_distance(path.points[segment_data::point::end], other) < 0.05) + result.insert = track; + } + if (result.insert != nullptr) + return result; + } + return std::nullopt; +} + +// the crossover taken out: the main tracks of its switches plain paths again, of the same shape, the insert gone, the outer track +// down by the lift it went up by. Gives the plain paths in place of the first and the second switch +bool editor_mode::take_out_crossover(curved_crossover const &Crossover, std::vector> &States, std::vector &Created, std::vector &Removed, TTrack *&First, TTrack *&Second) +{ + TTrack const *style{nullptr}; + for (auto const &[track, point] : editor_track::connected_points(*Crossover.first, Crossover.first->m_paths.front().points[segment_data::point::start])) + if (track != nullptr && track->eType == tt_Normal && false == track->m_editorremoved) + style = track; + if (style == nullptr) + style = Crossover.insert; + std::vector plains; + for (auto *track : {Crossover.first, Crossover.second}) + { + auto *plain{editor_track::create_path(*style, track->m_paths.front())}; + if (plain == nullptr) + return false; + plains.push_back(plain); + Created.push_back(plain); + } + for (auto *track : {Crossover.first, Crossover.second, Crossover.insert}) + { + editor_track::retire(*track); + Removed.push_back(track); + } + editor_track::commit(plains); + switch_store::forget(Crossover.first->name()); + switch_store::forget(Crossover.second->name()); + First = plains[0]; + Second = plains[1]; + auto const &record{Crossover.record}; + if (false == record.lifted() || record.ramp <= 0.0) + return true; + // the outer track is the one the level stretch of the lift lies on + TTrack *outer{nullptr}; + for (auto *plain : plains) + if (plan_distance(editor_track::point_at(*plain, editor_track::nearest_parameter(*plain, record.lift_from)), record.lift_from) < 1.0 || + plan_distance(editor_track::point_at(*plain, editor_track::nearest_parameter(*plain, record.lift_to)), record.lift_to) < 1.0) + outer = plain; + if (outer == nullptr) + return true; + auto route{editor_track::run_route(*outer, 3000.0)}; + auto const samples{editor_track::sample_route(route, 1.0)}; + if (samples.size() < 2) + return true; + auto const chainage_of = [&](glm::dvec3 const &Point) { + double best{std::numeric_limits::max()}; + double chainage{0.0}; + for (std::size_t i = 0; i + 1 < samples.size(); ++i) + { + auto const a{plan_of(samples[i].position)}; + auto const run{plan_of(samples[i + 1].position) - a}; + auto const t{std::clamp(glm::dot(plan_of(Point) - a, run) / std::max(1e-12, glm::dot(run, run)), 0.0, 1.0)}; + if (auto const distance{glm::length(plan_of(Point) - (a + run * t))}; distance < best) + { + best = distance; + chainage = samples[i].chainage + (samples[i + 1].chainage - samples[i].chainage) * t; + } + } + return chainage; + }; + outer_lift lowered{chainage_of(record.lift_from), chainage_of(record.lift_to), record.lift, record.lift_end, record.ramp}; + if (lowered.from > lowered.to) + { + std::swap(lowered.from, lowered.to); + std::swap(lowered.first, lowered.second); + } + auto const breaks{lowered.breaks(route.length)}; + profile_take(route, route.spans.front().track, route.spans.back().track); + auto const before{m_profile.line}; + editor_track::apply_profile( + route, [&](double const Chainage) { return editor_track::sampled_elevation(samples, Chainage) - lowered.at(Chainage); }, + [&](double const Chainage) { return editor_track::sampled_grade(samples, Chainage) - lowered.grade(Chainage); }, breaks, States, Created); + // the design of the outer track down with it, the corners of the ramps left out where the line runs on straight through them + profile_take(route, route.spans.front().track, route.spans.back().track); + std::vector points; + for (auto point : before.points) + { + point.elevation -= lowered.at(point.chainage); + points.push_back(point); + } + for (std::size_t k = 1; k + 1 < points.size();) + { + auto const in{(points[k].elevation - points[k - 1].elevation) / std::max(1e-6, points[k].chainage - points[k - 1].chainage)}; + auto const out{(points[k + 1].elevation - points[k].elevation) / std::max(1e-6, points[k + 1].chainage - points[k].chainage)}; + if (std::abs(out - in) < 1e-7) + points.erase(points.begin() + static_cast(k)); + else + ++k; + } + if (points.size() >= 2) + { + m_profile.line = before; + m_profile.line.points = std::move(points); + m_profile.selected = -1; + profile_check(); + profile_store(); + } + WriteLog(format("Editor: curved crossover - the outer track %s down by %.3f .. %.3f m again", outer->name().c_str(), record.lift, record.lift_end), logtype::generic); + return true; +} + +// the crossover along a curve moved along it by the distance, from its first switch towards the second: taken out and laid again, +// of the template Shape when it's given +bool editor_mode::slide_curved_connection(TTrack &Switch, double const Distance, int const Shape) +{ + auto const crossover{crossover_of(Switch)}; + if (false == crossover.has_value()) + return false; + auto &tool{m_switch}; + auto const shape{Shape >= 0 ? Shape : crossover_template(crossover->record)}; + if (shape < 0) + { + tool.status = STR_C("The template the crossover was laid of isn't among the templates"); + ui()->set_status(tool.status, true); + return false; + } + std::vector const names{crossover->first->name(), crossover->second->name()}; + auto const firststart{crossover->first->m_paths.front().points[segment_data::point::start]}; + auto const firstend{crossover->first->m_paths.front().points[segment_data::point::end]}; + auto const secondstart{crossover->second->m_paths.front().points[segment_data::point::start]}; + std::vector> states; + std::vector created; + std::vector removed; + TTrack *first{nullptr}; + TTrack *second{nullptr}; + // the design of the outer track comes down with the lift taken back, an undo puts both back + profile_library_load(); + auto library{m_profiles}; + if (false == take_out_crossover(*crossover, states, created, removed, first, second)) + return false; + // the new places of the press and of the release, along the two curves, or the two straights + std::vector firstframe, secondframe; + std::vector firsttracks, secondtracks; + glm::dvec3 press, release; + if (curve_of(*first, m_straights.tolerance, m_route.design.norms.gauge, firstframe, firsttracks, kStraightReach) && curve_of(*second, m_straights.tolerance, m_route.design.norms.gauge, secondframe, secondtracks, kStraightReach)) + { + auto const towards{nearest_station(firstframe, firstend) >= nearest_station(firstframe, firststart) ? 1.0 : -1.0}; + press = sample_at(firstframe, nearest_station(firstframe, firststart) + towards * Distance).position; + auto const ahead{nearest_station(secondframe, secondstart) >= nearest_station(secondframe, firststart) ? 1.0 : -1.0}; + release = sample_at(secondframe, nearest_station(secondframe, secondstart) + ahead * Distance).position; + } + else + { + auto direction{plan_of(firstend - firststart)}; + direction = glm::length(direction) > 1e-9 ? glm::normalize(direction) : glm::dvec2{0.0, 1.0}; + press = firststart + glm::dvec3{direction.x, 0.0, direction.y} * Distance; + release = secondstart + glm::dvec3{direction.x, 0.0, direction.y} * Distance; + firsttracks = {first}; + } + switch_store::follow(); + push_track_snapshot(std::move(states), std::move(created), std::move(removed)); + records_to_history(); + if (crossover->record.lifted()) + profiles_to_history(std::move(library)); + // laid again + if (false == lay_crossover(shape, press, release, 3.0, names)) + { + auto const reason{tool.status}; + undo_last(); + tool.status = reason.empty() ? std::string{STR_C("The crossover doesn't fit there")} : reason; + ui()->set_status(tool.status, true); + return false; + } + join_last_steps(); + tool.status = (Shape >= 0 ? format(STR_C("Crossover laid again of %s"), template_name(tool.templates[shape]).c_str()) : format(STR_C("Crossover moved %.2f m"), Distance)) + "\n" + tool.status; + ui()->set_status(tool.status, false); + return true; +} + +std::size_t editor_mode::follow_crossovers(std::vector const &Before) +{ + auto &state{m_profile}; + auto const changedroute{state.route}; + auto *changedfrom{state.from}; + auto *changedto{state.to}; + auto const after{state.samples}; + auto const changedline{state.line}; + if (Before.size() < 2 || after.size() < 2) + return 0; + double constexpr follow{25.0}; + double constexpr leave{50.0}; + // how much the route went up at the point beside it, and how far the point is from it + auto const change_at = [&](glm::dvec3 const &Point, double &Distance, double &Chainage) { + Distance = std::numeric_limits::max(); + Chainage = 0.0; + for (std::size_t i = 0; i + 1 < after.size(); ++i) + { + auto const a{plan_of(after[i].position)}; + auto const run{plan_of(after[i + 1].position) - a}; + auto const t{std::clamp(glm::dot(plan_of(Point) - a, run) / std::max(1e-12, glm::dot(run, run)), 0.0, 1.0)}; + if (auto const distance{glm::length(plan_of(Point) - (a + run * t))}; distance < Distance) + { + Distance = distance; + Chainage = after[i].chainage + (after[i + 1].chainage - after[i].chainage) * t; + } + } + auto const weight{std::clamp((leave - Distance) / (leave - follow), 0.0, 1.0)}; + return weight * (editor_track::sampled_elevation(after, Chainage) - editor_track::sampled_elevation(Before, Chainage)); + }; + std::vector done; + std::size_t followed{0}; + for (auto const &span : changedroute.spans) + { + if (span.track == nullptr || span.track->eType != tt_Switch) + continue; + auto const crossover{crossover_of(*span.track)}; + if (false == crossover.has_value()) + continue; + auto *other{crossover->first == span.track ? crossover->second : crossover->first}; + // on the same grade line it goes with the route anyway, grade_line_follow sees to it; what a fit to the terrain leaves as it is stays + if ((m_profile.whole_grade_line && false == m_profile.fitting && on_route_grade_line(*other)) || (m_profile.fitting && m_nmt_state.stayed.contains(other))) + continue; + if (std::any_of(changedroute.spans.begin(), changedroute.spans.end(), [&](auto const &Span) { return Span.track == other; }) || std::find(done.begin(), done.end(), other) != done.end()) + continue; + done.push_back(other); + auto route{editor_track::run_route(*other, 3000.0)}; + auto const samples{editor_track::sample_route(route, 1.0)}; + if (samples.size() < 2) + continue; + // the change of each point of the other line + std::vector changes(samples.size(), 0.0); + std::vector distances(samples.size(), 0.0); + bool any{false}; + for (std::size_t i = 0; i < samples.size(); ++i) + { + double chainage; + changes[i] = change_at(samples[i].position, distances[i], chainage); + any = any || std::abs(changes[i]) > 0.001; + } + if (false == any) + continue; + auto const change = [&](double const Chainage) { + auto const at{std::clamp(Chainage, samples.front().chainage, samples.back().chainage)}; + auto const next{std::lower_bound(samples.begin(), samples.end(), at, [](auto const &Sample, double const Value) { return Sample.chainage < Value; })}; + if (next == samples.begin()) + return changes.front(); + if (next == samples.end()) + return changes.back(); + auto const i{static_cast(std::distance(samples.begin(), next))}; + auto const f{(at - samples[i - 1].chainage) / std::max(1e-9, samples[i].chainage - samples[i - 1].chainage)}; + return changes[i - 1] + (changes[i] - changes[i - 1]) * f; + }; + // where the grade line of the route breaks, the other line breaks too + std::vector breaks; + for (auto const &point : changedline.points) + { + auto const at{editor_track::sampled_position(after, point.chainage)}; + double best{std::numeric_limits::max()}; + double chainage{0.0}; + for (auto const &sample : samples) + if (auto const distance{plan_distance(sample.position, at)}; distance < best) + { + best = distance; + chainage = sample.chainage; + } + if (best < follow && chainage > 0.5 && chainage < route.length - 0.5) + breaks.push_back(chainage); + } + // and where it starts and stops running beside the route + for (std::size_t i = 1; i < samples.size(); ++i) + for (auto const bound : {follow, leave}) + if ((distances[i - 1] < bound) != (distances[i] < bound) && samples[i].chainage > 0.5 && samples[i].chainage < route.length - 0.5) + breaks.push_back(samples[i].chainage); + std::sort(breaks.begin(), breaks.end()); + breaks.erase(std::unique(breaks.begin(), breaks.end(), [](double const A, double const B) { return std::abs(A - B) < 1.0; }), breaks.end()); + profile_take(route, route.spans.front().track, route.spans.back().track); + auto const designed{m_profile.line}; + std::vector> states; + std::vector created; + editor_track::apply_profile( + route, [&](double const Chainage) { return editor_track::sampled_elevation(samples, Chainage) + change(Chainage); }, + [&](double const Chainage) { return editor_track::sampled_grade(samples, Chainage) + (change(Chainage + 0.5) - change(Chainage - 0.5)); }, breaks, states, created); + profile_library_load(); + auto library{m_profiles}; + push_track_snapshot(std::move(states), std::move(created)); + m_history.back().profiles = true; + m_history.back().profile_library = std::move(library); + join_last_steps(); + // its design changed by as much + profile_take(route, route.spans.front().track, route.spans.back().track); + std::vector points; + for (auto point : designed.points) + { + point.elevation += change(point.chainage); + points.push_back(point); + } + for (auto const chainage : breaks) + { + profile::pvi point; + point.chainage = chainage; + point.elevation = profile::elevation(designed, chainage) + change(chainage); + points.push_back(point); + } + std::sort(points.begin(), points.end(), [](auto const &Left, auto const &Right) { return Left.chainage < Right.chainage; }); + std::vector line; + for (auto const &point : points) + if (line.empty() || point.chainage - line.back().chainage >= 0.5) + line.push_back(point); + if (line.size() >= 2) + { + m_profile.line = designed; + m_profile.line.points = std::move(line); + m_profile.selected = -1; + profile_check(); + profile_store(); + } + ++followed; + WriteLog(format("Editor: vertical profile - the track %s across the crossover %s followed the change", other->name().c_str(), crossover->first->name().c_str()), logtype::generic); + } + if (followed > 0) + { + // the route the user works on open again + profile_take(changedroute, changedfrom, changedto); + } + return followed; +} + +int editor_mode::crossover_template(switch_store::record const &Record) +{ + auto &tool{m_switch}; + show_track_tab(track_tab::turnout); + arm_switch(); + if (auto const found{matching_template(Record, false)}; found >= 0) + return found; + // switches of no template of the catalogue, as the digitized ones of the old sceneries: the first one is the template + if (Record.source != "measured" || Record.parts.empty()) + return -1; + auto own{editor_track::template_of_switch(simulation::Paths.find(Record.parts.front()))}; + if (false == own.has_value()) + return -1; + tool.templates.push_back(std::move(*own)); + return static_cast(tool.templates.size()) - 1; +} + +bool editor_mode::lay_crossover(int const Shape, glm::dvec3 const &Press, glm::dvec3 const &Release, double const Reach, std::vector const &Names) +{ + auto &tool{m_switch}; + tool.keep_names = Names; + struct forget_names + { + std::vector &names; + ~forget_names() { names.clear(); } + } const forget{tool.keep_names}; + // the plain path the press falls on + TTrack *closest{nullptr}; + auto nearest{Reach}; + for (auto *track : simulation::Paths.sequence()) + { + if (track == nullptr || track->m_editorremoved || track->eType != tt_Normal || track->m_paths.empty()) + continue; + if (auto const distance{plan_distance(editor_track::point_at(*track, editor_track::nearest_parameter(*track, Press)), Press)}; distance < nearest) + { + nearest = distance; + closest = track; + } + } + if (closest == nullptr || Shape < 0) + return false; + show_track_tab(track_tab::turnout); + arm_switch(); + tool.armed = Shape; + tool.connection = static_cast(connection::kind::crossover); + tool.connection_second = -1; + m_node = closest; + ui()->set_node(m_node); + // the press onto the path, where the line went sideways + auto const press{editor_track::point_at(*closest, editor_track::nearest_parameter(*closest, Press))}; + m_cursor_override = press; + auto const started{start_switch_placement()}; + m_cursor_override.reset(); + if (false == started) + return false; + tool.mouse = {Release.x, tool.point.y, Release.z}; + auto const steps{m_history.size()}; + if (tool.curved) + insert_curved_connection(); + else + insert_connection(); + if (m_history.size() == steps) + return false; + // both switches joined to their tracks at the start and at the end of the main track, else the line under them moved + // and it's taken back + for (auto *track : std::vector{m_node != nullptr ? dynamic_cast(m_node) : nullptr}) + if (auto const crossover{track != nullptr ? crossover_of(*track) : std::nullopt}) + for (auto *part : {crossover->first, crossover->second}) + for (auto const which : {segment_data::point::start, segment_data::point::end}) + { + auto const joined{editor_track::connected_points(*part, part->m_paths.front().points[which])}; + if (std::none_of(joined.begin(), joined.end(), [&](auto const &Entry) { return Entry.first != part && Entry.first != nullptr && false == Entry.first->m_editorremoved; })) + { + undo_last(); + tool.status = STR_C("The crossover wouldn't join the tracks there"); + return false; + } + } + return true; +} diff --git a/application/editormodedigitize.cpp b/application/editormodedigitize.cpp new file mode 100644 index 000000000..75e76f817 --- /dev/null +++ b/application/editormodedigitize.cpp @@ -0,0 +1,424 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +// the digitization of a scenery made without the editor: its lines kept with their designs, its switches with their types out of +// the catalogue, its crossovers as connections and the objects along the tracks bound to them, at one go + +#include "stdafx.h" +#include "application/editormode.h" +#include "application/editormodeshared.h" +#include "application/editoruilayer.h" +#include "editor/editorAlignmentStore.hpp" +#include "editor/editorConnections.hpp" +#include "editor/editorFormat.hpp" +#include "editor/editorGeometry.hpp" +#include "editor/editorSwitchStore.hpp" +#include "simulation/simulation.h" +#include "utilities/Logs.h" +#include "utilities/translation.h" +#include "world/Track.h" +#include +#include +#include +#include + +namespace +{ + +using geometry::bezier; +using geometry::plan_of; +using geometry::signed_angle; + +// how far the size of a switch may be from the template to be of it: the length of the main and the diverging track, the angle +double constexpr kMainTolerance{0.10}; +double constexpr kBranchTolerance{0.15}; +double constexpr kAngleTolerance{0.0025}; +// a plain track this short between the ends of two switches is a part of a slip +double constexpr kSlipLink{6.0}; +// the longest insert of a crossover +double constexpr kInsertLongest{150.0}; +// the tracks a crossover joins lie this far apart +double constexpr kSpacingLeast{2.5}; +double constexpr kSpacingMost{15.0}; +// radii of the diverging track the switches are made with; a measured one this close to one of them is taken for it +double constexpr kNominalRadii[]{150.0, 190.0, 205.0, 230.0, 265.0, 300.0, 500.0, 760.0, 1200.0}; +double constexpr kNominalNear{0.04}; + +double nominal_radius(double const Radius) +{ + for (auto const nominal : kNominalRadii) + if (std::abs(Radius - nominal) <= kNominalNear * nominal) + return nominal; + return std::round(Radius); +} + +std::vector parts_of(segment_data const &Path) +{ + std::vector parts; + if (Path.pieces.empty()) + parts.push_back(&Path); + else + for (auto const &piece : Path.pieces) + parts.push_back(&piece); + return parts; +} + +double path_length(segment_data const &Path) +{ + double length{0.0}; + for (auto const *part : parts_of(Path)) + length += bezier{*part}.plan_length(); + return length; +} + +glm::dvec2 heading(segment_data const &Path, bool const End) +{ + auto const parts{parts_of(Path)}; + bezier const curve{End ? *parts.back() : *parts.front()}; + auto const direction{plan_of(curve.first(End ? 1.0 : 0.0))}; + if (glm::length(direction) > 1e-9) + return glm::normalize(direction); + auto const chord{plan_of(Path.points[segment_data::point::end] - Path.points[segment_data::point::start])}; + return glm::length(chord) > 1e-9 ? glm::normalize(chord) : glm::dvec2{0.0, 1.0}; +} + +// in the plan, + to the left, at the middle of the longest part of the path +double curvature(segment_data const &Path) +{ + segment_data const *longest{nullptr}; + double length{-1.0}; + for (auto const *part : parts_of(Path)) + if (auto const l{bezier{*part}.plan_length()}; l > length) + { + length = l; + longest = part; + } + if (longest == nullptr || false == geometry::has_controls(*longest)) + return 0.0; + bezier const curve{*longest}; + auto const first{plan_of(curve.first(0.5))}; + auto const second{plan_of(curve.second(0.5))}; + auto const speed{glm::length(first)}; + return speed > 1e-9 ? (first.x * second.y - first.y * second.x) / (speed * speed * speed) : 0.0; +} + +struct switch_size +{ + double main{0.0}; + double branch{0.0}; + double angle{0.0}; // between the ends of the two tracks + double radius{0.0}; // of the diverging track of the straight switch the switch is made of +}; + +switch_size size_of(segment_data const &Main, segment_data const &Branch) +{ + switch_size size; + size.main = path_length(Main); + size.branch = path_length(Branch); + size.angle = std::abs(signed_angle(heading(Main, true), heading(Branch, true))); + auto const bend{std::abs(curvature(Branch) - curvature(Main))}; + size.radius = bend > 1e-6 ? 1.0 / bend : 0.0; + return size; +} + +// the template of the catalogue the size is of: the rail of the track and a movable nose decide between the same shapes +int matching(std::vector const &Templates, std::vector> const &Sizes, switch_size const &Size, std::string const &Rail, bool const Movable) +{ + int best{-1}; + auto score{std::numeric_limits::max()}; + for (auto const &[index, size] : Sizes) + { + auto const &shape{Templates[index]}; + auto const main{std::abs(size.main - Size.main)}; + auto const branch{std::abs(size.branch - Size.branch)}; + auto const angle{std::abs(size.angle - Size.angle)}; + if (main > kMainTolerance || branch > kBranchTolerance || angle > kAngleTolerance) + continue; + auto value{main / kMainTolerance + branch / kBranchTolerance + angle / kAngleTolerance}; + if (false == Rail.empty() && shape.rail != Rail) + value += 10.0; + if (shape.movable != Movable) + value += 5.0; + if (value < score) + { + score = value; + best = index; + } + } + return best; +} + +bool usable_switch(TTrack const *Track) +{ + return Track != nullptr && false == Track->m_editorremoved && Track->eType == tt_Switch && Track->m_paths.size() == 2; +} + +bool named(TTrack const &Track) +{ + return false == Track.name().empty() && Track.name() != "none"; +} + +glm::dvec3 far_end(segment_data const &Path, editor_track::point_kind const Kind) +{ + return Path.points[Kind == editor_track::point_kind::start ? segment_data::point::end : segment_data::point::start]; +} + +// the end of the path meets an end of another switch, right there or over a short plain track: the paths of a slip do +bool towards_switch(TTrack const &Track, glm::dvec3 const &Point) +{ + for (auto const &[other, point] : editor_track::connected_points(Track, Point)) + { + if (other == nullptr || other == &Track || other->m_editorremoved) + continue; + if (other->eType == tt_Switch && point.kind == editor_track::point_kind::end) + return true; + if (other->eType != tt_Normal || other->m_paths.size() != 1 || path_length(other->m_paths.front()) > kSlipLink) + continue; + for (auto const &[next, nextpoint] : editor_track::connected_points(*other, far_end(other->m_paths.front(), point.kind))) + if (next != nullptr && next != other && next != &Track && next->eType == tt_Switch && nextpoint.kind == editor_track::point_kind::end) + return true; + } + return false; +} + +bool slip_part(TTrack const &Switch) +{ + return towards_switch(Switch, Switch.m_paths[0].points[segment_data::point::end]) && towards_switch(Switch, Switch.m_paths[1].points[segment_data::point::end]); +} + +} // namespace + +void editor_mode::digitize_switches(digitize_report &Report, bool const Write) +{ + auto const templates{editor_track::standard_switch_templates()}; + std::vector> sizes; + for (int i = 0; i < static_cast(templates.size()); ++i) + { + auto const &shape{templates[i]}; + if (shape.source == nullptr && false == shape.double_slip && false == shape.twofold()) + sizes.emplace_back(i, size_of(shape.local[0], shape.local[1])); + } + for (auto *track : simulation::Paths.sequence()) + { + if (false == usable_switch(track)) + continue; + ++Report.switches; + if (switch_store::named(*track).has_value()) + { + ++Report.known; + continue; + } + if (slip_part(*track)) + { + ++Report.slips; + continue; + } + auto const &main{track->m_paths[0]}; + auto const &branch{track->m_paths[1]}; + if (geometry::plan_distance(main.points[segment_data::point::start], branch.points[segment_data::point::start]) > geometry::same_point) + { + ++Report.odd; + Report.notes.push_back(track->name() + ": " + STR("the tracks of the switch don't start at the same point")); + continue; + } + auto const size{size_of(main, branch)}; + auto const movable{track->SwitchExtension != nullptr && track->SwitchExtension->m_movablenose}; + auto const found{matching(templates, sizes, size, editor_track::rail_of(track), movable)}; + editor_track::switch_template shape; + if (found >= 0) + { + shape = templates[found]; + ++Report.designed; + ++Report.types[shape.label.substr(0, shape.label.find(" "))]; + } + else + { + shape.source = track; + shape.radius = nominal_radius(size.radius); + shape.ratio = size.angle > 1e-6 ? 1.0 / std::tan(size.angle) : 0.0; + ++Report.measured; + ++Report.shapes[format("L %.2f / %.2f 1:%.2f R %.0f", size.main, size.branch, shape.ratio, shape.radius)]; + } + if (false == named(*track)) + { + // the record finds the switch by its name; the names of the scenery stay as they are + ++Report.unnamed; + continue; + } + if (Write && found >= 0) + record_switch(*track, shape); + else if (Write) + { + switch_store::record entry; + entry.kind = "switch"; + entry.name = track->name(); + entry.parts = {entry.name}; + entry.radius = shape.radius; + entry.ratio = shape.ratio; + entry.source = "measured"; + auto const rail{editor_track::rail_of(track)}; + entry.rail = rail.empty() ? std::string{"-"} : rail; + switch_store::place(entry, *track); + switch_store::classify(entry, *track); + switch_store::put(entry, alignment_store::layer_of(*track)); + } + ++Report.recorded; + } +} + +void editor_mode::digitize_crossovers(digitize_report &Report, bool const Write) +{ + std::set> seen; + for (auto *first : simulation::Paths.sequence()) + { + if (false == usable_switch(first) || slip_part(*first)) + continue; + auto const &branch{first->m_paths[1]}; + auto const end{branch.points[segment_data::point::end]}; + // the insert: plain tracks from the end of the diverging track up to the end of the diverging track of another switch + std::vector insert; + TTrack *second{nullptr}; + auto *from{static_cast(first)}; + auto point{end}; + double length{0.0}; + bool direct{false}; + while (second == nullptr && length <= kInsertLongest) + { + TTrack *next{nullptr}; + editor_track::point_ref at; + for (auto const &[other, ref] : editor_track::connected_points(*from, point)) + { + if (other == nullptr || other == from || other->m_editorremoved || std::find(insert.begin(), insert.end(), other) != insert.end()) + continue; + if (usable_switch(other) && other != first && ref.path == 1 && ref.kind == editor_track::point_kind::end) + { + second = other; + direct = insert.empty(); + break; + } + if (other->eType == tt_Normal && other->m_paths.size() == 1) + { + next = other; + at = ref; + } + } + if (second != nullptr || next == nullptr) + break; + insert.push_back(next); + length += path_length(next->m_paths.front()); + point = far_end(next->m_paths.front(), at.kind); + from = next; + } + if (second == nullptr || slip_part(*second)) + continue; + if (seen.count({second, first}) > 0) + continue; + seen.insert({first, second}); + // the two switches face each other from two tracks side by side + auto const along{heading(first->m_paths[0], false)}; + auto const back{heading(second->m_paths[0], false)}; + if (glm::dot(along, back) > -0.9) + continue; + auto const spacing{std::abs(geometry::cross(along, plan_of(second->m_paths[0].points[segment_data::point::start] - first->m_paths[0].points[segment_data::point::start])))}; + if (spacing < kSpacingLeast || spacing > kSpacingMost) + continue; + ++Report.crossovers; + auto const name = [](TTrack const *Track) { return name_of(*Track); }; + auto const note = [&](std::string const &Why) { Report.notes.push_back(name(first) + " + " + name(second) + ": " + Why); }; + if (false == switch_store::connections(*first).empty()) + { + ++Report.crossovers_known; + continue; + } + if (direct || insert.size() != 1) + { + ++Report.crossovers_odd; + note(direct ? STR("the diverging tracks meet without an insert between them") : format(STR_C("the insert is made of %zu paths"), insert.size())); + continue; + } + auto const one{switch_store::named(*first)}; + auto const other{switch_store::named(*second)}; + if (Write && (false == one.has_value() || false == other.has_value())) + { + ++Report.crossovers_odd; + note(STR("a switch of it has no type kept")); + continue; + } + if (one.has_value() && other.has_value() && (std::abs(one->radius - other->radius) > kNominalNear * one->radius || std::abs(one->ratio - other->ratio) > kNominalNear * one->ratio)) + { + ++Report.crossovers_odd; + note(format(STR_C("the switches differ: %s and %s"), switch_store::label(*one).c_str(), switch_store::label(*other).c_str())); + continue; + } + if (Write) + { + auto entry{*one}; + entry.kind = "connection"; + entry.name = first->name(); + entry.parts = {first->name(), second->name()}; + entry.number = "-"; + switch_store::place(entry, *first); + switch_store::classify(entry, *first); + entry.type = connection::word(connection::kind::crossover); + entry.a = spacing; + entry.b = length; + switch_store::put(entry, alignment_store::layer_of(*first)); + WriteLog(format("Editor: digitizing - crossover %s + %s kept, %s, spacing %.2f m, insert %.2f m", first->name().c_str(), second->name().c_str(), switch_store::label(entry).c_str(), spacing, length), logtype::generic); + } + ++Report.crossovers_recorded; + } +} + +std::string editor_mode::digitize_scenery(bool const Write) +{ + digitize_report report; + if (Write) + digitize_all(&report.lines, &report.lines_failed); + digitize_switches(report, Write); + digitize_crossovers(report, Write); + if (Write) + { + switch_store::settle(); + auto const scope{m_infra.scope}; + m_infra.scope = 3; + infra_recognize(); + report.found = static_cast(m_infra.candidates.size()); + auto const before{infra_bound_count()}; + infra_bind_chosen(); + report.bound = infra_bound_count() - before; + m_infra.scope = scope; + } + auto text{format(STR_C("Switches: %d, kept already %d, of the catalogue %d, measured %d, parts of slips %d, odd %d"), report.switches, report.known, report.designed, report.measured, report.slips, report.odd)}; + if (report.unnamed > 0) + text += format(STR_C(", without a name, left out %d"), report.unnamed); + text += "\n" + format(STR_C("Crossovers: %d, kept already %d, recorded %d, left out %d"), report.crossovers, report.crossovers_known, report.crossovers_recorded, report.crossovers_odd); + if (Write) + { + text = format(STR_C("Lines digitized: %d, paths left out: %d"), report.lines, report.lines_failed) + "\n" + text; + text += "\n" + format(STR_C("Objects by the tracks: %d found, %d bound"), report.found, report.bound); + } + WriteLog("Editor: digitizing the scenery\n" + text, logtype::generic); + std::vector> types; + for (auto const &[label, count] : report.types) + types.emplace_back(count, label); + std::sort(types.rbegin(), types.rend()); + for (auto const &[count, label] : types) + WriteLog(format("Editor: digitizing - %4d x %s", count, label.c_str()), logtype::generic); + std::vector> shapes; + for (auto const &[label, count] : report.shapes) + shapes.emplace_back(count, label); + std::sort(shapes.rbegin(), shapes.rend()); + for (std::size_t i = 0; i < std::min(shapes.size(), 20); ++i) + WriteLog(format("Editor: digitizing - measured %4d x %s", shapes[i].first, shapes[i].second.c_str()), logtype::generic); + for (std::size_t i = 0; i < std::min(report.notes.size(), 30); ++i) + WriteLog("Editor: digitizing - " + report.notes[i], logtype::generic); + if (Write) + ui()->set_status(text, report.odd + report.crossovers_odd + report.lines_failed > 0); + return text; +} diff --git a/application/editormodegauge.cpp b/application/editormodegauge.cpp index 298724e70..7e11b9615 100644 --- a/application/editormodegauge.cpp +++ b/application/editormodegauge.cpp @@ -8,7 +8,8 @@ http://mozilla.org/MPL/2.0/. */ #include "stdafx.h" -#include "application/editormode.h" +#include "application/editormodegauge.h" +#include "editor/editorTrack.hpp" #include "application/editoruilayer.h" #include "editor/editorFormat.hpp" #include "editor/editorGauge.hpp" @@ -326,7 +327,7 @@ template void visit_triangles(TSubModel *Submodel, glm::dmat4 } // the triangle enters the gauge when any point of a grid spread over it does; the deepest such point goes to the hit -void scan_triangle(corridor const &Space, glm::dvec3 const &A, glm::dvec3 const &B, glm::dvec3 const &C, editor_mode::gauge_hit &Hit) +void scan_triangle(corridor const &Space, glm::dvec3 const &A, glm::dvec3 const &B, glm::dvec3 const &C, gauge_tool::gauge_hit &Hit) { auto const middle{(A + B + C) / 3.0}; if (false == Space.close(middle, std::max({glm::distance(middle, A), glm::distance(middle, B), glm::distance(middle, C)}))) @@ -353,24 +354,24 @@ void scan_triangle(corridor const &Space, glm::dvec3 const &A, glm::dvec3 const } // the deepest place of the model in the gauge, added to the hits when it enters it -void scan_model(corridor const &Space, TAnimModel &Instance, std::vector &Hits) +void scan_model(corridor const &Space, TAnimModel &Instance, std::vector &Hits) { if (false == Instance.visible() || Instance.Model() == nullptr || Instance.Model()->GetSMRoot() == nullptr) return; if (false == Space.nearby(Instance.location(), Instance.radius())) return; - editor_mode::gauge_hit hit{Instance.name(), Instance.location()}; + gauge_tool::gauge_hit hit{Instance.name(), Instance.location()}; visit_triangles(Instance.Model()->GetSMRoot(), placement(Instance), [&](glm::dvec3 const &A, glm::dvec3 const &B, glm::dvec3 const &C) { scan_triangle(Space, A, B, C, hit); }); if (hit.depth > 0.0) Hits.push_back(std::move(hit)); } // the same for the copies of a model laid along a curve -void scan_sweep(corridor const &Space, sweep_node &Sweep, std::vector &Hits) +void scan_sweep(corridor const &Space, sweep_node &Sweep, std::vector &Hits) { if (Sweep.m_editorremoved || false == Space.nearby(Sweep.location(), Sweep.radius())) return; - editor_mode::gauge_hit hit{Sweep.name(), Sweep.location()}; + gauge_tool::gauge_hit hit{Sweep.name(), Sweep.location()}; for (auto const &shape : Sweep.create_shapes()) { auto const &vertices{shape.data().vertices}; @@ -381,13 +382,13 @@ void scan_sweep(corridor const &Space, sweep_node &Sweep, std::vector &Hits) +void sort_hits(std::vector &Hits) { std::sort(Hits.begin(), Hits.end(), [](auto const &Left, auto const &Right) { return Left.depth > Right.depth; }); } // the models entering the gauge, the deepest first -void scan_models(corridor const &Space, std::vector &Hits) +void scan_models(corridor const &Space, std::vector &Hits) { for (auto *instance : simulation::Instances.sequence()) if (instance != nullptr) @@ -438,7 +439,7 @@ bool edit_points(std::vector &Points) bool edited{false}; bool inserted{false}; int remove{-1}; - ImGui::Columns(3, STR_C("gaugeoutline"), false); + ImGui::Columns(3, "gaugeoutline", false); ImGui::SetColumnWidth(0, 110.0f); ImGui::SetColumnWidth(1, 110.0f); ImGui::TextDisabled(STR_C("Half-width")); @@ -483,6 +484,60 @@ bool edit_points(std::vector &Points) return edited; } +// the railway outline drawn across the track at the size of the panel, so the name in the list has a shape +void gauge_sketch(gauge::profile const &Profile) +{ + auto const width{ImGui::GetContentRegionAvail().x}; + auto const height{std::round(ImGui::GetFontSize() * 9.0f)}; + auto const low{ImGui::GetCursorScreenPos()}; + ImGui::Dummy(ImVec2(width, height)); + if (Profile.outline.size() < 2) + return; + double top{0.0}; + double half{0.0}; + for (auto const &point : Profile.outline) + { + top = std::max(top, point.height); + half = std::max(half, point.half_width); + } + if (top <= 0.0 || half <= 0.0) + return; + auto const pad{ImGui::GetFontSize() * 1.2f}; + auto const scale{static_cast(std::min((height - pad * 2.0f) / top, (width - pad * 2.0f) / (half * 2.0)))}; + ImVec2 const base{std::round(low.x + width * 0.5f), std::round(low.y + height - pad)}; + auto const at = [&](double const X, double const Y) { return ImVec2(base.x + static_cast(X) * scale, base.y - static_cast(Y) * scale); }; + auto *draw{ImGui::GetWindowDrawList()}; + draw->AddRectFilled(low, ImVec2(low.x + width, low.y + height), ImGui::GetColorU32(ImGuiCol_FrameBg), 4.0f); + // ballast, a sleeper and the two rails + ImVec2 const ballast[]{at(-2.1, -0.6), at(2.1, -0.6), at(1.55, -0.2), at(-1.55, -0.2)}; + draw->AddConvexPolyFilled(ballast, 4, IM_COL32(110, 100, 90, 255)); + draw->AddRectFilled(at(-1.3, -0.2), at(1.3, -0.13), IM_COL32(150, 150, 150, 255)); + for (double const side : {-0.7175, 0.7175}) + draw->AddRectFilled(at(side - 0.04, -0.13), at(side + 0.04, 0.0), IM_COL32(210, 210, 215, 255)); + // the outline, the right half from the bottom up and its mirror back down + std::vector points; + for (auto const &point : Profile.outline) + points.push_back(at(point.half_width, point.height)); + for (auto point{Profile.outline.rbegin()}; point != Profile.outline.rend(); ++point) + points.push_back(at(-point->half_width, point->height)); + auto const accent{IM_COL32(120, 200, 255, 255)}; + auto const flags{draw->Flags}; + draw->Flags &= ~ImDrawListFlags_AntiAliasedFill; + draw->AddConcavePolyFilled(points.data(), static_cast(points.size()), IM_COL32(120, 200, 255, 40)); + draw->Flags = flags; + draw->AddPolyline(points.data(), static_cast(points.size()), accent, ImDrawFlags_Closed, 2.0f); + // the height over the top and the widest half at its height + auto const widest{std::max_element(Profile.outline.begin(), Profile.outline.end(), [](auto const &A, auto const &B) { return A.half_width < B.half_width; })}; + auto const tall{format("%.2f m", top)}; + auto const size{ImGui::CalcTextSize(tall.c_str())}; + draw->AddText(ImVec2(std::round(base.x - size.x * 0.5f), std::round(at(0.0, top).y - size.y - 2.0f)), accent, tall.c_str()); + auto const wide{format("%.2f m", widest->half_width * 2.0)}; + auto const y{at(0.0, widest->height).y}; + draw->AddLine(ImVec2(at(-widest->half_width, 0.0).x, y), ImVec2(at(widest->half_width, 0.0).x, y), IM_COL32(255, 220, 120, 160), 1.0f); + auto const wsize{ImGui::CalcTextSize(wide.c_str())}; + draw->AddText(ImVec2(std::round(base.x - wsize.x * 0.5f), std::round(y - wsize.y - 1.0f)), IM_COL32(255, 220, 120, 255), wide.c_str()); +} + } // namespace struct gauge_scan @@ -496,7 +551,7 @@ struct gauge_scan std::chrono::steady_clock::time_point started; }; -void editor_mode::gauge_load() +void gauge_tool::gauge_load() { if (m_gauge.profiles.empty()) m_gauge.profiles = gauge::load_profiles(gauge_file); @@ -514,18 +569,53 @@ void editor_mode::gauge_load() } } -gauge::choice editor_mode::gauge_choice() const +gauge::choice gauge_tool::gauge_choice() const { auto const pick{[&](int const Index) { return Index >= 0 ? &m_gauge.profiles[Index] : nullptr; }}; return {pick(m_gauge.profile), pick(m_gauge.road)}; } -std::vector const &editor_mode::gauge_hits() const +std::vector const &gauge_tool::gauge_hits() const { return m_gauge.map.scanned ? m_gauge.map.hits : m_gauge.line.hits; } -void editor_mode::update_gauge() +gauge_tool::gauge_hit gauge_tool::gauge_models(std::vector const &Models) +{ + gauge_load(); + auto const choice{gauge_choice()}; + gauge_hit deepest; + // a line along each path which may reach the models + std::vector lines; + for (auto *track : simulation::Paths.sequence()) + { + if (track == nullptr || track->m_editorremoved) + continue; + auto const close{std::any_of(Models.begin(), Models.end(), [&](TAnimModel const *Model) { + return Model != nullptr && geometry::plan_distance(Model->location(), track->location()) <= static_cast(Model->radius() + track->radius()) + 6.0; + })}; + if (false == close || false == editor_track::is_supported(*track) || outline_of(choice, *track) == nullptr) + continue; + for (int path = 0; path < static_cast(track->m_paths.size()); ++path) + { + editor_track::route route; + route.spans.push_back({track, path, true}); + if (auto line{track_line(choice, *track, route)}) + lines.push_back(std::move(*line)); + } + } + if (lines.empty()) + return deepest; + corridor const space{lines}; + std::vector hits; + for (auto *model : Models) + if (model != nullptr) + scan_model(space, *model, hits); + sort_hits(hits); + return hits.empty() ? deepest : hits.front(); +} + +void gauge_tool::update() { if (m_gauge.scan) step_gauge_map(); @@ -536,9 +626,9 @@ void editor_mode::update_gauge() m_gauge.published = false; return; } - auto *track{m_gauge.enabled ? selected_track() : nullptr}; + auto *track{m_gauge.enabled ? m_selection.selected_track() : nullptr}; // the geometry is rescanned once the edit ends - if (ImGui::IsMouseDown(0) || m_track_gizmo_using || m_dragging) + if (ImGui::IsMouseDown(0) || m_design.track_editing()) m_gauge.pending = true; else if (track == nullptr) { @@ -549,19 +639,19 @@ void editor_mode::update_gauge() m_gauge.published = false; } } - else if (track != m_gauge.track || m_history.size() != m_gauge.history || m_gauge.pending) + else if (track != m_gauge.track || m_history.history_revision() != m_gauge.history || m_gauge.pending) { m_gauge.track = track; - m_gauge.history = m_history.size(); + m_gauge.history = m_history.history_revision(); m_gauge.pending = false; scan_gauge(*track); m_gauge.published = false; } - if (false == m_gauge.published || glm::distance(Camera.Pos, EditorOverlay.origin) > gauge_origin_range) + if (false == m_gauge.published || glm::distance(m_view.camera_position(), EditorOverlay.origin) > gauge_origin_range) gauge_publish(); } -void editor_mode::scan_gauge(TTrack &Track) +void gauge_tool::scan_gauge(TTrack &Track) { gauge_load(); m_gauge.line = {}; @@ -577,7 +667,7 @@ void editor_mode::scan_gauge(TTrack &Track) m_gauge.current = -1; } -void editor_mode::scan_gauge_map() +void gauge_tool::scan_gauge_map() { gauge_load(); auto scan{std::make_shared()}; @@ -590,7 +680,7 @@ void editor_mode::scan_gauge_map() scan->space.emplace(scan->lines); m_gauge.map = {}; m_gauge.map.scanned = true; - m_gauge.map.history = m_history.size(); + m_gauge.map.history = m_history.history_revision(); auto const name{[](gauge::profile const *Profile) { return Profile != nullptr ? Profile->name : std::string{"-"}; }}; m_gauge.map.profile = name(chosen.railway) + ", " + name(chosen.road); m_gauge.current = -1; @@ -598,7 +688,7 @@ void editor_mode::scan_gauge_map() m_gauge.scan = std::move(scan); } -void editor_mode::step_gauge_map() +void gauge_tool::step_gauge_map() { auto &scan{*m_gauge.scan}; auto const &instances{simulation::Instances.sequence()}; @@ -621,7 +711,7 @@ void editor_mode::step_gauge_map() finish_gauge_map(); } -void editor_mode::finish_gauge_map() +void gauge_tool::finish_gauge_map() { auto const scan{std::move(m_gauge.scan)}; auto &hits{m_gauge.map.hits}; @@ -636,11 +726,11 @@ void editor_mode::finish_gauge_map() gauge_focus(0); } -void editor_mode::gauge_publish() +void gauge_tool::gauge_publish() { m_gauge.published = true; EditorOverlay.clear(); - EditorOverlay.origin = Camera.Pos; + EditorOverlay.origin = m_view.camera_position(); auto const batch{[](glm::vec4 const &Color, unsigned int const Type, std::vector const &Points) { gfx::editor_overlay::batch result{Color, Type}; result.points.reserve(Points.size()); @@ -663,7 +753,7 @@ void editor_mode::gauge_publish() batch({0.2f, 1.0f, 0.3f, 0.5f}, GL_LINES, m_gauge.spot.edges)}; } -void editor_mode::gauge_focus(int const Index) +void gauge_tool::gauge_focus(int const Index) { auto const &hits{gauge_hits()}; if (hits.empty()) @@ -675,18 +765,12 @@ void editor_mode::gauge_focus(int const Index) // along the track, tangent to the gauge at the height of the place, from the end nearer to the camera glm::dvec3 look{hit.direction.x, 0.0, hit.direction.y}; look = glm::length(look) > 1e-6 ? glm::normalize(look) : glm::dvec3(0.0, 0.0, 1.0); - if (glm::dot(Camera.Pos - hit.point, look) > 0.0) + if (glm::dot(m_view.camera_position() - hit.point, look) > 0.0) look = -look; - m_focus_start_pos = Camera.Pos; - m_focus_start_angle = Camera.Angle; - m_focus_target_pos = hit.point - look * gauge_view_distance; - m_focus_target_angle = glm::vec3(static_cast(std::asin(std::clamp(look.y, -1.0, 1.0))), static_cast(std::atan2(-look.x, -look.z)), 0.0f); - m_focus_active = true; - m_focus_time = 0.0; - m_focus_duration = 0.6; + m_view.fly_to(hit.point, look, gauge_view_distance); } -void editor_mode::gauge_spot(gauge_hit const &Hit) +void gauge_tool::gauge_spot(gauge_hit const &Hit) { m_gauge.spot = {}; auto const &paths{simulation::Paths.sequence()}; @@ -703,7 +787,7 @@ void editor_mode::gauge_spot(gauge_hit const &Hit) build_tunnel(*line, m_gauge.spot.surface, m_gauge.spot.edges); } -void editor_mode::render_gauge_window() +void gauge_tool::render_windows() { if (false == m_gauge.open) return; @@ -721,13 +805,15 @@ void editor_mode::render_gauge_window() bool changed{render_gauge_choice("Railway", m_gauge.profile, false)}; if (ImGui::IsItemHovered()) ImGui::SetTooltip(STR_C("GPL: unified structure gauge, widened only in the curves under 250 m.\nG1, G2, GA, GB, GC: limit (GSZ) and nominal (NSZ) installation gauges, widened by 3750/R in all curves.")); + if (m_gauge.profile >= 0) + gauge_sketch(m_gauge.profiles[m_gauge.profile]); changed |= render_gauge_choice("Road", m_gauge.road, true); if (ImGui::IsItemHovered()) ImGui::SetTooltip(STR_C("Clearance over the roads, from 0.5 m beyond the edges of the carriageway")); if (m_gauge.scan) { - auto const label{format("Scanning the map %.0f%%, %zu found", m_gauge.scan->progress * 100.f, m_gauge.map.hits.size())}; + auto const label{format(STR_C("Scanning the scenery %.0f%%, %zu found"), m_gauge.scan->progress * 100.f, m_gauge.map.hits.size())}; ImGui::ProgressBar(m_gauge.scan->progress, ImVec2(-70.0f, 0.0f), label.c_str()); ImGui::SameLine(); if (ImGui::SmallButton(STR_C("Cancel"))) @@ -735,7 +821,7 @@ void editor_mode::render_gauge_window() if (ImGui::IsItemHovered()) ImGui::SetTooltip(STR_C("Stops the scan and keeps the models found so far")); } - else if (ImGui::Button(STR_C("Find the violations on the whole map"))) + else if (ImGui::Button(STR_C("Find the violations in the whole scenery"))) scan_gauge_map(); else if (ImGui::IsItemHovered()) ImGui::SetTooltip(STR_C("Checks the models along all tracks of the scenery against the chosen gauge\nand lists them, the deepest first.\nRuns in the background, the list fills up as it goes")); @@ -748,7 +834,7 @@ void editor_mode::render_gauge_window() m_gauge.current = -1; m_gauge.published = false; } - else if (m_gauge.map.history != m_history.size()) + else if (m_gauge.map.history != m_history.history_revision()) ImGui::TextColored(ImVec4(1.0f, 0.75f, 0.3f, 1.0f), STR_C("The scenery changed since the scan (%s)"), m_gauge.map.profile.c_str()); } render_gauge_hits(); @@ -759,17 +845,17 @@ void editor_mode::render_gauge_window() ImGui::End(); } -void editor_mode::render_gauge_hits() +void gauge_tool::render_gauge_hits() { auto const &hits{gauge_hits()}; if (false == m_gauge.map.scanned && (false == m_gauge.enabled || m_gauge.track == nullptr)) return; if (hits.empty()) { - ImGui::TextDisabled(m_gauge.map.scanned ? STR_C("No model enters the gauge on the map") : STR_C("The gauge is clear along this line")); + ImGui::TextDisabled("%s", m_gauge.map.scanned ? STR_C("No model in the scenery enters the gauge") : STR_C("The gauge is clear along this line")); return; } - ImGui::TextColored(ImVec4(1.0f, 0.35f, 0.3f, 1.0f), STR_C("%zu models enter the gauge%s"), hits.size(), m_gauge.map.scanned ? STR_C(" on the map") : ""); + ImGui::TextColored(ImVec4(1.0f, 0.35f, 0.3f, 1.0f), STR_C("%zu models enter the gauge%s"), hits.size(), m_gauge.map.scanned ? STR_C(" in the whole scenery") : ""); if (ImGui::ArrowButton("##gaugeprevious", ImGuiDir_Left)) gauge_focus(m_gauge.current - 1); ImGui::SameLine(); @@ -784,18 +870,22 @@ void editor_mode::render_gauge_hits() for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; ++i) { auto const &hit{hits[i]}; - auto const label{(hit.model.empty() ? std::string{"(unnamed)"} : hit.model) + " " + std::to_string(static_cast(std::lround(hit.depth * 100.0))) + " cm##" + std::to_string(i)}; + auto const label{(hit.model.empty() ? STR("(no name)") : hit.model) + " " + std::to_string(static_cast(std::lround(hit.depth * 100.0))) + " cm##" + std::to_string(i)}; if (ImGui::Selectable(label.c_str(), m_gauge.current == i)) gauge_focus(i); } ImGui::EndChild(); } -bool editor_mode::render_gauge_choice(char const *Label, int &Index, bool const Road) +bool gauge_tool::render_gauge_choice(char const *Label, int &Index, bool const Road) { bool changed{false}; - ImGui::SetNextItemWidth(-60.0f); - if (ImGui::BeginCombo(Label, Index >= 0 ? m_gauge.profiles[Index].name.c_str() : STR_C("none"))) + ImGui::PushID(Label); + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted(STR_C(Label)); + ImGui::SameLine(std::round(ImGui::GetCursorStartPos().x + std::max(ImGui::CalcTextSize(STR_C("Railway")).x, ImGui::CalcTextSize(STR_C("Road")).x) + ImGui::GetStyle().ItemSpacing.x)); + ImGui::SetNextItemWidth(-FLT_MIN); + if (ImGui::BeginCombo("##profile", Index >= 0 ? m_gauge.profiles[Index].name.c_str() : STR_C("(none)"))) { for (int i = 0; i < static_cast(m_gauge.profiles.size()); ++i) if ((m_gauge.profiles[i].kind == gauge::kind::road) == Road && ImGui::Selectable(m_gauge.profiles[i].name.c_str(), i == Index)) @@ -805,10 +895,11 @@ bool editor_mode::render_gauge_choice(char const *Label, int &Index, bool const } ImGui::EndCombo(); } + ImGui::PopID(); return changed; } -bool editor_mode::render_gauge_outline(int const Index) +bool gauge_tool::render_gauge_outline(int const Index) { if (Index < 0) return false; @@ -816,7 +907,7 @@ bool editor_mode::render_gauge_outline(int const Index) if (false == ImGui::TreeNode(&profile, STR_C("Outline of %s (right half)"), profile.name.c_str())) return false; ImGui::TextDisabled(profile.kind == gauge::kind::road ? STR_C("Metres from the edge of the carriageway and above the road, bottom up.") - : "PKP PLK standard, volume II; below 1170 mm the limit installation gauge.\nMetres from the track axis and above the rail top, bottom up."); + : STR_C("PKP PLK standard, volume II; below 1170 mm the limit installation gauge.\nMetres from the track axis and above the rail top, bottom up.")); bool edited{edit_points(profile.outline)}; if (ImGui::SmallButton(STR_C("Restore the starting outlines"))) { @@ -829,3 +920,23 @@ bool editor_mode::render_gauge_outline(int const Index) ImGui::TreePop(); return edited; } + +editor_selftest_result gauge_tool::selftest(std::string const &Command, std::istringstream &Words) +{ + if (Command == "gauge") + { + std::string name; + Words >> name; + if (auto *track{simulation::Paths.find(name)}) + { + scan_gauge(*track); + WriteLog(format("SELFTEST gauge %s: %d hits", name.c_str(), static_cast(m_gauge.line.hits.size()))); + for (auto const &hit : m_gauge.line.hits) + WriteLog(format("SELFTEST gauge hit %s depth %.3f at %.2f %.2f %.2f", hit.model.c_str(), hit.depth, hit.point.x, hit.point.y, hit.point.z)); + } + else + WriteLog("SELFTEST gauge " + name + ": no such track"); + return editor_selftest_result::handled; + } + return editor_selftest_result::unhandled; +} diff --git a/application/editormodegauge.h b/application/editormodegauge.h new file mode 100644 index 000000000..b37a85c0d --- /dev/null +++ b/application/editormodegauge.h @@ -0,0 +1,96 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include "application/editortool.h" +#include "editor/editorGauge.hpp" + +#include +#include +#include + +class TAnimModel; + +class gauge_tool final : public editor_tool +{ + public: + // model entering the structure gauge, at its deepest place + struct gauge_hit + { + std::string model; + glm::dvec3 point{0.0}; + double depth{0.0}; // m + TTrack const *track{nullptr}; // nearest one, may be gone by now + int path{0}; + glm::dvec2 direction{0.0, 1.0}; // of the track there, in the plan + }; + gauge_tool(editor_selection &Selection, editor_view &View, editor_history &History, editor_track_design &Design) : m_selection{Selection}, m_view{View}, m_history{History}, m_design{Design} {} + void update() override; + void render_windows() override; + editor_selftest_result selftest(std::string const &Command, std::istringstream &Words) override; + bool is_open() const { return m_gauge.open; } + // the deepest entry of the models into the outlines of the paths around them, of the outline chosen in the window; a hit of + // depth 0 when they keep out of them all + gauge_hit gauge_models(std::vector const &Models); + void toggle() { m_gauge.open = !m_gauge.open; } + + private: + editor_selection &m_selection; + editor_view &m_view; + editor_history &m_history; + editor_track_design &m_design; + // structure gauge along the line of the selected path, shown in the 3d view + struct gauge_state + { + bool open{false}; // window + bool enabled{true}; // tunnel along the selected path + std::vector profiles; + int profile{0}; // railway + int road{-1}; + TTrack const *track{nullptr}; // scanned + std::size_t history{0}; + bool pending{false}; // rescan once the edit ends + struct + { + std::vector surface; // triangles of the tunnel + std::vector edges; // lines + std::vector hits; + } line; // along the selected path + struct + { + bool scanned{false}; + std::size_t history{0}; + std::string profile; + std::vector hits; + } map; // whole scenery + struct + { + std::vector surface; + std::vector edges; + } spot; // tunnel around the hit the camera went to + int current{-1}; // hit the camera went to + bool published{false}; // overlay up to date + std::shared_ptr scan; // of the whole scenery, done in slices over the frames + } m_gauge; + void gauge_load(); + // the chosen railway and road outlines + gauge::choice gauge_choice() const; + std::vector const &gauge_hits() const; + void scan_gauge(TTrack &Track); + void scan_gauge_map(); + void step_gauge_map(); + void finish_gauge_map(); + void gauge_publish(); + void gauge_focus(int Index); + void gauge_spot(gauge_hit const &Hit); + void render_gauge_hits(); + bool render_gauge_choice(char const *Label, int &Index, bool Road); + bool render_gauge_outline(int Index); +}; diff --git a/application/editormodegradeline.cpp b/application/editormodegradeline.cpp new file mode 100644 index 000000000..8f2dd51ee --- /dev/null +++ b/application/editormodegradeline.cpp @@ -0,0 +1,739 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +// the grade lines the tracks nearly parallel share: kept in the scenery, followed when the profile tool changes a route of them, a route +// taken off them and back, tracks clicked onto the line of the route and off it by hand + +#include "stdafx.h" +#include "application/editormode.h" +#include "application/editorprojection.h" +#include "application/editormodeshared.h" +#include "editor/editorFormat.hpp" +#include "editor/editorGeometry.hpp" +#include "simulation/simulation.h" +#include "utilities/translation.h" +#include "world/Track.h" + +#include "imgui/imgui.h" +#include +#include +#include +#include +#include +#include +#include + +namespace +{ +std::string const kGradeLineMark{"//$w"}; +} // namespace + +// the ends of the path up or down by these, what's between them in proportion; After is given the path and each of its pieces then +void editor_mode::move_path_heights(segment_data &Path, double const First, double const Second, std::function const &After) +{ + auto const origin{Path.points[segment_data::point::start]}; + auto const chord{geometry::plan_of(Path.points[segment_data::point::end] - origin)}; + auto const square{std::max(1e-9, glm::dot(chord, chord))}; + auto const by = [&](glm::dvec3 const &Point) { return glm::mix(First, Second, std::clamp(glm::dot(geometry::plan_of(Point - origin), chord) / square, 0.0, 1.0)); }; + auto const lay = [&](segment_data &Part) { + auto &points{Part.points}; + auto const start{points[segment_data::point::start]}; + auto const end{points[segment_data::point::end]}; + if (points[segment_data::point::control1] != glm::dvec3{} || points[segment_data::point::control2] != glm::dvec3{}) + { + points[segment_data::point::control1].y += by(start + points[segment_data::point::control1]) - by(start); + points[segment_data::point::control2].y += by(end + points[segment_data::point::control2]) - by(end); + } + points[segment_data::point::start].y += by(start); + points[segment_data::point::end].y += by(end); + if (After) + After(Part); + }; + for (auto &piece : Path.pieces) + lay(piece); + lay(Path); +} + +// a track on a grade line is told by its name and where it starts in the plan: scenery files have names used twice, and the height of a +// track on the line changes with it +std::string editor_mode::grade_line_key(TTrack const &Track) +{ + return grade_line_key(Track.name(), Track); +} + +std::string editor_mode::grade_line_key(std::string const &Name, TTrack const &Track) +{ + if (Track.m_paths.empty()) + return Name; + auto const &start{Track.m_paths.front().points[segment_data::point::start]}; + return format("%s@%lld,%lld", Name.c_str(), static_cast(std::llround(start.x)), static_cast(std::llround(start.z))); +} + +// the grade lines shared go to the scenery files as "//$w" comment lines, by those keys +void editor_mode::grade_lines_load() +{ + auto &state{m_nmt_state}; + if (state.grade_lines_loaded) + return; + state.grade_lines_loaded = true; + for (auto const layer : scene::Layers.marked_layers(kGradeLineMark)) + for (auto const &text : scene::Layers.marked(layer, kGradeLineMark)) + { + std::istringstream line{text}; + std::string keyword, name, hand; + int number{0}; + line >> keyword >> name >> number; + if (keyword == "gradeline" && false == line.fail()) + { + state.grade_lines[name] = number; + if (line >> hand && hand == "hand") + state.grade_lines_hand.insert(name); + } + } +} + +void editor_mode::grade_lines_store() +{ + if (scene::Layers.empty()) + return; + std::map> lines; + for (auto const layer : scene::Layers.marked_layers(kGradeLineMark)) + lines[layer]; + for (auto const *track : simulation::Paths.sequence()) + { + if (track == nullptr || track->m_editorremoved) + continue; + auto const key{grade_line_key(*track)}; + auto const found{m_nmt_state.grade_lines.find(key)}; + if (found == m_nmt_state.grade_lines.end() || found->second == nmt_state::grade_line_own || found->second == nmt_state::grade_line_steep) + continue; + auto const hand{found->second >= 0 && m_nmt_state.grade_lines_hand.contains(key)}; + auto layer{scene::Layers.resolve(track->layer())}; + if (false == scene::Layers.valid(layer) || false == scene::Layers.accepts(layer)) + layer = scene::Layers.active(); + auto &those{lines[layer]}; + if (those.empty()) + those.emplace_back("# the tracks sharing a grade line, each with the number of it; the simulation skips these lines"); + those.push_back(format("gradeline %s %d%s", key.c_str(), found->second, hand ? " hand" : "")); + } + for (auto &[layer, those] : lines) + if (scene::Layers.valid(layer)) + scene::Layers.mark(layer, kGradeLineMark, std::move(those)); +} + +bool editor_mode::on_route_grade_line(TTrack const &Track) +{ + grade_lines_load(); + auto const &lines{m_nmt_state.grade_lines}; + auto const found{lines.find(grade_line_key(Track))}; + if (found == lines.end() || found->second < 0) + return false; + return std::any_of(m_profile.route.spans.begin(), m_profile.route.spans.end(), [&](auto const &Span) { + auto const own{lines.find(grade_line_key(*Span.track))}; + return own != lines.end() && own->second == found->second; + }); +} + +std::vector const &editor_mode::grade_line_beside() +{ + double constexpr kBeside{200.0}; // m from the route, the width of a station; farther it has nothing to do with this one + auto &state{m_profile}; + std::tuple const of{state.route.spans.empty() ? nullptr : state.route.spans.front().track, state.route.spans.size(), static_cast(m_track_edits), m_nmt_state.grade_lines_changes}; + if (of == state.beside_of) + return state.beside; + state.beside_of = of; + state.beside.clear(); + grade_lines_load(); + std::unordered_set numbers; + std::unordered_set route; + for (auto const &span : state.route.spans) + { + route.insert(span.track); + if (auto const found{m_nmt_state.grade_lines.find(grade_line_key(*span.track))}; found != m_nmt_state.grade_lines.end() && found->second >= 0) + numbers.insert(found->second); + } + if (numbers.empty() || state.samples.size() < 2) + return state.beside; + auto const lying_by = [&](glm::dvec3 const &Point) { + for (auto const &sample : state.samples) + if (glm::length(glm::dvec2{sample.position.x - Point.x, sample.position.z - Point.z}) < kBeside) + return true; + return false; + }; + for (auto *track : simulation::Paths.sequence()) + { + if (track == nullptr || track->m_editorremoved || route.contains(track) || track->m_paths.empty()) + continue; + auto const found{m_nmt_state.grade_lines.find(grade_line_key(*track))}; + if (found != m_nmt_state.grade_lines.end() && numbers.contains(found->second) && (lying_by(track->m_paths.front().points[segment_data::point::start]) || lying_by(track->m_paths.front().points[segment_data::point::end]))) + state.beside.push_back(track); + } + // and whatever lies on common timbers with them, on a grade line or not: those stay on one surface + std::unordered_set taken{route}; + taken.insert(state.beside.begin(), state.beside.end()); + std::unordered_set surfaces; + for (auto const &place : m_nmt_state.surface_places) + if (taken.contains(place.track)) + surfaces.insert(place.surface); + for (auto const &place : m_nmt_state.surface_places) + if (surfaces.contains(place.surface) && taken.insert(place.track).second && false == place.track->m_editorremoved) + state.beside.push_back(const_cast(place.track)); + return state.beside; +} + +// the tracks beside the route on the grade line it shares go up and down with it, by what it changed by abreast of them, however far +// across the station: a surface on common timbers stays one. Past the ends of the route the change fades from kFollow to kLeave beyond +// them; a track joined to them from off the grade line takes the change at that end only +std::size_t editor_mode::grade_line_follow(std::vector const &Before) +{ + double constexpr kFollow{0.0}; // m + double constexpr kLeave{50.0}; // m + auto &state{m_profile}; + auto const after{state.samples}; + if (false == state.whole_grade_line || Before.size() < 2 || after.size() < 2) + return 0; + auto const beside{grade_line_beside()}; + if (beside.empty()) + return 0; + auto const change_at = [&](glm::dvec3 const &Point) { + auto closest{std::numeric_limits::max()}; + auto chainage{0.0}; + auto past{0.0}; + for (std::size_t i = 0; i + 1 < after.size(); ++i) + { + auto const a{geometry::plan_of(after[i].position)}; + auto const run{geometry::plan_of(after[i + 1].position) - a}; + auto const along{glm::dot(geometry::plan_of(Point) - a, run) / std::max(1e-12, glm::dot(run, run))}; + auto const t{std::clamp(along, 0.0, 1.0)}; + if (auto const distance{glm::length(geometry::plan_of(Point) - (a + run * t))}; distance < closest) + { + closest = distance; + chainage = after[i].chainage + (after[i + 1].chainage - after[i].chainage) * t; + // how far along the way of the route it lies past its first or its last point + past = (i == 0 && along < 0.0) || (i + 2 == after.size() && along > 1.0) ? std::abs(along - t) * glm::length(run) : 0.0; + } + } + return std::clamp((kLeave - past) / (kLeave - kFollow), 0.0, 1.0) * (editor_track::sampled_elevation(after, chainage) - editor_track::sampled_elevation(Before, chainage)); + }; + auto const key_of = [](glm::dvec3 const &Point) { return std::pair{static_cast(std::round(Point.x * 20.0)), static_cast(std::round(Point.z * 20.0))}; }; + // the ends of the route itself lie where they should already, those of the switches on it with them + std::set> route_ends; + std::unordered_set route; + for (auto const &span : state.route.spans) + { + route.insert(span.track); + for (auto const &path : span.track->m_paths) + for (auto const end : {segment_data::point::start, segment_data::point::end}) + route_ends.insert(key_of(path.points[end])); + } + std::map, double> moves; + auto any{false}; + for (auto const *track : beside) + for (auto const &path : track->m_paths) + for (auto const end : {segment_data::point::start, segment_data::point::end}) + if (auto const key{key_of(path.points[end])}; false == route_ends.contains(key) && false == moves.contains(key)) + { + auto const move{change_at(path.points[end])}; + moves[key] = move; + any = any || std::abs(move) >= 0.001; + } + if (false == any) + return 0; + // the tracks going on from them off the grade line take the change in over a length, however short each of them is + double constexpr kRampIn{60.0}; // m, 0.3 m in over it is 5 per mille + std::unordered_set const members(beside.begin(), beside.end()); + struct joined + { + std::pair to; + double length; + }; + std::map, std::vector> ways; + for (auto const *track : simulation::Paths.sequence()) + if (track != nullptr && false == track->m_editorremoved && false == route.contains(track) && false == members.contains(track)) + for (auto const &path : track->m_paths) + { + auto const a{key_of(path.points[segment_data::point::start])}; + auto const b{key_of(path.points[segment_data::point::end])}; + auto const length{glm::length(geometry::plan_of(path.points[segment_data::point::end] - path.points[segment_data::point::start]))}; + ways[a].push_back({b, length}); + ways[b].push_back({a, length}); + } + struct ramp + { + double from; // the change where it begins + double gone; // m from there + }; + std::map, ramp> ramps; + std::vector> waiting; + for (auto const &[key, move] : moves) + { + ramps[key] = {move, 0.0}; + waiting.push_back(key); + } + auto const height_of = [](ramp const &Ramp) { return Ramp.from * std::max(0.0, 1.0 - Ramp.gone / kRampIn); }; + while (false == waiting.empty()) + { + auto const here{waiting.back()}; + waiting.pop_back(); + auto const ramp_here{ramps.at(here)}; + auto const found{ways.find(here)}; + if (found == ways.end()) + continue; + for (auto const &way : found->second) + { + if (route_ends.contains(way.to) || moves.contains(way.to) || ramp_here.gone + way.length >= kRampIn) + continue; + ramp const further{ramp_here.from, ramp_here.gone + way.length}; + if (auto const known{ramps.find(way.to)}; known == ramps.end() || std::abs(height_of(further)) > std::abs(height_of(known->second))) + { + ramps[way.to] = further; + waiting.push_back(way.to); + } + } + } + for (auto const &[key, ramped] : ramps) + moves[key] = height_of(ramped); + auto const move_of = [&](glm::dvec3 const &Point) { + auto const found{moves.find(key_of(Point))}; + return found != moves.end() ? found->second : 0.0; + }; + editor_track::edit edit; + std::vector moved; + for (auto *track : simulation::Paths.sequence()) + { + if (track == nullptr || track->m_editorremoved || route.contains(track)) + continue; + auto const touched{std::any_of(track->m_paths.begin(), track->m_paths.end(), [&](auto const &Path) { return moves.contains(key_of(Path.points[segment_data::point::start])) || moves.contains(key_of(Path.points[segment_data::point::end])); })}; + if (false == touched) + continue; + edit.capture(*track); + moved.push_back(track); + for (auto &path : track->m_paths) + move_path_heights(path, move_of(path.points[segment_data::point::start]), move_of(path.points[segment_data::point::end])); + } + if (moved.empty()) + return 0; + editor_track::commit(moved); + push_track_snapshot(std::move(edit.states), {}); + join_last_steps(); + fitted_set(moved, true); + return moved.size(); +} + +void editor_mode::grade_line_take_off(bool const Off) +{ + auto &lines{m_nmt_state.grade_lines}; + std::size_t changed{0}; + grade_lines_load(); + for (auto const &span : m_profile.route.spans) + { + auto const found{lines.find(grade_line_key(*span.track))}; + if (found == lines.end()) + continue; + auto &line{found->second}; + if (Off && line >= 0) + { + line = nmt_state::grade_line_off_number - line; + m_nmt_state.grade_lines_hand.erase(found->first); + } + else if (false == Off && line <= nmt_state::grade_line_off_number) + line = nmt_state::grade_line_off_number - line; + else if (false == Off && line == nmt_state::grade_line_off) + line = nmt_state::grade_line_own; + else + continue; + ++changed; + } + ++m_nmt_state.grade_lines_changes; + grade_lines_store(); + m_profile.status = format(Off ? STR_P("%zu track taken off the common grade line, it goes on its own now", "%zu tracks taken off the common grade line, they go on their own now", changed) : STR_P("%zu track back on the common grade line", "%zu tracks back on the common grade line", changed), changed); +} + +int editor_mode::route_grade_line() +{ + grade_lines_load(); + std::map lengths; + for (auto const &span : m_profile.route.spans) + if (auto const found{m_nmt_state.grade_lines.find(grade_line_key(*span.track))}; found != m_nmt_state.grade_lines.end() && found->second >= 0) + lengths[found->second] += span.track->Length(); + auto best{-1}; + auto longest{-1.0}; + for (auto const &[number, length] : lengths) + if (length > longest) + { + best = number; + longest = length; + } + return best; +} + +std::vector editor_mode::grade_line_run(TTrack &Track, bool const Alone) +{ + std::vector run{&Track}; + if (Alone || Track.eType != tt_Normal) + return run; + std::unordered_set seen{&Track}; + for (auto const forward : {true, false}) + { + TTrack const *previous{&Track}; + auto *current{forward ? Track.trNext : Track.trPrev}; + while (current != nullptr && current->eType == tt_Normal && false == current->m_editorremoved && seen.insert(current).second) + { + run.push_back(current); + auto *next{current->trPrev == previous ? current->trNext : current->trPrev}; + previous = current; + current = next; + } + } + return run; +} + +// put on by hand, or taken off, the tracks stay so when the lines are worked out again: a map of fiction has no terrain model to tell +// them by +void editor_mode::grade_line_pick(TTrack &Track, bool const Alone) +{ + auto &state{m_profile}; + auto &lines{m_nmt_state.grade_lines}; + auto &hand{m_nmt_state.grade_lines_hand}; + grade_lines_load(); + std::unordered_set route; + for (auto const &span : state.route.spans) + route.insert(span.track); + if (route.contains(&Track)) + { + state.status = STR("This is the route itself: the button above takes it off the common grade line"); + return; + } + auto const line_of = [&](TTrack const &Of) { + auto const found{lines.find(grade_line_key(Of))}; + return found != lines.end() ? found->second : nmt_state::grade_line_own; + }; + auto number{route_grade_line()}; + auto const run{grade_line_run(Track, Alone)}; + std::size_t changed{0}; + if (number >= 0 && line_of(Track) == number) + { + for (auto const *track : run) + if (line_of(*track) == number && false == route.contains(track)) + { + auto const key{grade_line_key(*track)}; + lines[key] = nmt_state::grade_line_off_number - number; + hand.erase(key); + ++changed; + } + state.status = format(STR_P("%zu track taken off the common grade line of the route", "%zu tracks taken off the common grade line of the route", changed), changed); + } + else + { + auto const made{number < 0}; + if (made) + { + // a new one, by a number no other line has, nor one a track taken off keeps + number = 0; + for (auto const &[key, line] : lines) + number = std::max(number, line >= 0 ? line + 1 : line <= nmt_state::grade_line_off_number ? nmt_state::grade_line_off_number - line + 1 : 0); + for (auto const *track : route) + { + auto const key{grade_line_key(*track)}; + lines[key] = number; + hand.insert(key); + } + } + for (auto const *track : run) + if (false == route.contains(track)) + { + auto const key{grade_line_key(*track)}; + lines[key] = number; + hand.insert(key); + ++changed; + } + state.status = format(made ? STR_P("A common grade line made of the route and %zu track", "A common grade line made of the route and %zu tracks", changed) + : STR_P("%zu track put on the common grade line of the route", "%zu tracks put on the common grade line of the route", changed), + changed); + } + ++m_nmt_state.grade_lines_changes; + grade_lines_store(); +} + +void editor_mode::grade_line_split(TTrack const &Original, TTrack const &Created) +{ + grade_lines_load(); + auto &lines{m_nmt_state.grade_lines}; + auto const found{lines.find(grade_line_key(Original))}; + if (found == lines.end() || Created.m_paths.empty()) + return; + auto const line{found->second}; + auto const hand{m_nmt_state.grade_lines_hand.contains(found->first)}; + auto const key{grade_line_key(Created)}; + lines[key] = line; + if (hand) + m_nmt_state.grade_lines_hand.insert(key); + ++m_nmt_state.grade_lines_changes; + m_nmt_state.grade_lines_dirty = true; +} + +void editor_mode::grade_line_captured(TTrack const &Track) +{ + if (scene::Layers.empty()) + return; + grade_lines_load(); + auto const key{grade_line_key(Track)}; + m_nmt_state.grade_line_keys.try_emplace(&Track, key); + if (false == Track.m_paths.empty() && m_nmt_state.grade_lines.contains(key)) + m_nmt_state.grade_line_replaced.emplace_back(key, Track.m_paths.front()); +} + +// what the track had under its key before goes on under the one it has now; the key it had stays too, for an undo bringing it back. A +// track never changed before is new: one lying where a track of a line lay before the change takes its line, so the pieces of it laid +// anew and a switch put into it; one between two tracks of a line at the ends of its first path lies on it, put on by hand if both of +// them are, so the link of a crossover between two switches of it +void editor_mode::grade_lines_committed(std::vector const &Tracks) +{ + auto &state{m_nmt_state}; + if (false == state.grade_lines_loaded) + return; + auto &lines{state.grade_lines}; + auto &hand{state.grade_lines_hand}; + auto changed{false}; + auto const carry = [&](std::string const &From, std::string const &To) { + auto const found{lines.find(From)}; + if (From == To || found == lines.end() || lines.contains(To)) + return; + auto const line{found->second}; + auto const byhand{hand.contains(From)}; + lines[To] = line; + if (byhand) + hand.insert(To); + changed = true; + }; + std::vector fresh; + for (auto *track : Tracks) + { + if (track == nullptr || track->m_editorremoved || track->m_paths.empty()) + continue; + auto const key{grade_line_key(*track)}; + auto const known{state.grade_line_keys.find(track)}; + if (known == state.grade_line_keys.end()) + { + if (false == lines.contains(key)) + fresh.push_back(track); + continue; + } + carry(known->second, key); + known->second = key; + } + auto const lying_on = [&](TTrack const &Track) -> std::string const * { + double constexpr kOn{0.3}; // m off the path it lay on + geometry::bezier const mine{Track.m_paths.front()}; + auto const middle{mine.point(0.5)}; + auto const way{geometry::plan_of(mine.point(0.55) - mine.point(0.45))}; + if (glm::length(way) < 1e-9) + return nullptr; + for (auto const &[key, path] : state.grade_line_replaced) + { + geometry::bezier const theirs{path}; + auto const reach{theirs.plan_length()}; + if (geometry::plan_distance(middle, theirs.point(0.5)) > 0.5 * reach + kOn) + continue; + int constexpr kSteps{64}; + for (int k = 0; k < kSteps; ++k) + { + auto const a{theirs.point(static_cast(k) / kSteps)}; + auto const b{theirs.point(static_cast(k + 1) / kSteps)}; + auto const run{geometry::plan_of(b - a)}; + auto const square{glm::dot(run, run)}; + if (square < 1e-12) + continue; + auto const t{std::clamp(glm::dot(geometry::plan_of(middle - a), run) / square, 0.0, 1.0)}; + if (glm::length(geometry::plan_of(middle - a) - run * t) < kOn && std::abs(glm::dot(glm::normalize(run), glm::normalize(way))) > 0.98) + return &key; + } + } + return nullptr; + }; + for (auto *&track : fresh) + if (auto const *was{lying_on(*track)}; was != nullptr && lines.contains(*was)) + { + auto const line{lines.at(*was)}; + auto const byhand{hand.contains(*was)}; + auto const key{grade_line_key(*track)}; + lines[key] = line; + if (byhand) + hand.insert(key); + state.grade_line_keys.try_emplace(track, key); + track = nullptr; + changed = true; + } + auto const lines_at = [&](TTrack const &Track, glm::dvec3 const &Point) { + std::map found; + for (auto const &[other, end] : editor_track::connected_points(Track, Point)) + if (other != &Track && false == other->m_editorremoved) + if (auto const entry{lines.find(grade_line_key(*other))}; entry != lines.end() && entry->second >= 0) + found[entry->second] = found[entry->second] || hand.contains(entry->first); + return found; + }; + // the switches first, the link between two of them after + for (int pass = 0; pass < 3; ++pass) + { + auto any{false}; + for (auto *&track : fresh) + { + if (track == nullptr) + continue; + auto const &path{track->m_paths.front()}; + auto const start{lines_at(*track, path.points[segment_data::point::start])}; + auto const end{lines_at(*track, path.points[segment_data::point::end])}; + auto number{-1}; + auto byhand{false}; + for (auto const &[line, lefthand] : start) + if (auto const other{end.find(line)}; other != end.end()) + { + // two lines at both ends tell nothing + number = number < 0 ? line : -2; + byhand = lefthand && other->second; + } + if (number < 0) + continue; + auto const key{grade_line_key(*track)}; + lines[key] = number; + if (byhand) + hand.insert(key); + state.grade_line_keys.try_emplace(track, key); + track = nullptr; + any = changed = true; + } + if (false == any) + break; + } + if (changed) + { + ++state.grade_lines_changes; + state.grade_lines_dirty = true; + } +} + +void editor_mode::grade_line_renamed(TTrack const &Track, std::string const &Old) +{ + if (Old.empty() || scene::Layers.empty()) + return; + grade_lines_load(); + auto &state{m_nmt_state}; + auto const from{grade_line_key(Old, Track)}; + auto const to{grade_line_key(Track)}; + auto const found{state.grade_lines.find(from)}; + if (found != state.grade_lines.end() && false == state.grade_lines.contains(to)) + { + auto const line{found->second}; + auto const byhand{state.grade_lines_hand.contains(from)}; + state.grade_lines[to] = line; + if (byhand) + state.grade_lines_hand.insert(to); + ++state.grade_lines_changes; + state.grade_lines_dirty = true; + } + if (auto const known{state.grade_line_keys.find(&Track)}; known != state.grade_line_keys.end()) + known->second = to; +} + +std::vector const &editor_mode::grade_line_members(int const Number) +{ + auto &state{m_profile}; + std::tuple const of{Number, m_nmt_state.grade_lines_changes, static_cast(m_track_edits)}; + if (of == state.members_of) + return state.members; + state.members_of = of; + state.members.clear(); + if (Number < 0) + return state.members; + grade_lines_load(); + for (auto const *track : simulation::Paths.sequence()) + if (track != nullptr && false == track->m_editorremoved) + if (auto const found{m_nmt_state.grade_lines.find(grade_line_key(*track))}; found != m_nmt_state.grade_lines.end() && found->second == Number) + state.members.push_back(track); + return state.members; +} + +// while they're picked: the tracks of the grade line of the route wherever they are, the run under the mouse in the colour of what a +// click does with it +void editor_mode::draw_grade_line_pick() +{ + auto const &state{m_profile}; + if (false == state.open || false == state.picking || state.route.spans.empty()) + return; + screen_projection const projection; + auto *drawlist{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())}; + auto const draw = [&](TTrack const &Track, ImU32 const Colour, float const Width) { + for (auto const &path : Track.m_paths) + { + geometry::bezier const curve{path}; + auto const count{std::clamp(static_cast(curve.plan_length() / 3.0), 2, 64)}; + auto previous{curve.point(0.0)}; + for (int k = 1; k <= count; ++k) + { + auto const next{curve.point(static_cast(k) / count)}; + projection.line(drawlist, previous, next, Colour, Width); + previous = next; + } + } + }; + auto const number{route_grade_line()}; + for (auto const *track : grade_line_members(number)) + draw(*track, IM_COL32(70, 170, 255, 220), 3.0f); + if (m_intent.what != track_intent::kind::grade_line_pick || m_intent.track == nullptr) + return; + auto const found{m_nmt_state.grade_lines.find(grade_line_key(*m_intent.track))}; + auto const leaving{number >= 0 && found != m_nmt_state.grade_lines.end() && found->second == number}; + for (auto const *track : grade_line_run(*m_intent.track, m_intent.index == 1)) + draw(*track, leaving ? IM_COL32(255, 90, 70, 235) : IM_COL32(90, 230, 110, 235), 5.0f); +} + +void editor_mode::render_profile_grade_line() +{ + auto &state{m_profile}; + grade_lines_load(); + auto const &lines{m_nmt_state.grade_lines}; + std::size_t shared{0}, off{0}; + for (auto const &span : state.route.spans) + if (auto const found{lines.find(grade_line_key(*span.track))}; found != lines.end()) + { + shared += found->second >= 0 ? 1 : 0; + off += found->second == nmt_state::grade_line_off || found->second <= nmt_state::grade_line_off_number ? 1 : 0; + } + auto const number{route_grade_line()}; + if (shared > 0) + ImGui::TextUnformatted(format(STR_C("Common grade line %d, %zu tracks on it"), number + 1, grade_line_members(number).size()).c_str()); + else + ImGui::TextDisabled("%s", STR_C("The route shares no grade line with other tracks")); + if (state.picking) + { + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.85f, 0.55f, 0.1f, 1.0f)); + if (ImGui::Button(STR_C("Click the tracks in the view, Esc: done"), ImVec2(-FLT_MIN, 0.0f))) + state.picking = false; + ImGui::PopStyleColor(); + } + else if (ImGui::Button(shared > 0 ? STR_C("Put tracks on it or take them off...") : STR_C("Make a common grade line..."), ImVec2(-FLT_MIN, 0.0f))) + state.picking = true; + item_tooltip("Then click the tracks in the view: a click puts the stretch from switch to switch on the common grade line of the route, on a blue one takes it off; Shift+click the track only.\nWhat's set by hand stays when the lines are worked out again from the terrain model; there needn't be one"); + if (shared > 0) + { + auto const beside{grade_line_beside().size()}; + ImGui::Checkbox(STR_C("Move the whole common grade line"), &state.whole_grade_line); + item_tooltip("Applied, the tracks and switches lying on one grade line with this route go up and down with it, the ones on common timbers staying on one surface.\nUnticked, only the route changes"); + ImGui::TextDisabled(STR_P("%zu track beside goes with the route (blue in the view)", "%zu tracks beside go with the route (blue in the view)", beside), beside); + if (ImGui::SmallButton(STR_C("Take off the common grade line"))) + grade_line_take_off(true); + item_tooltip("This route gets a grade line of its own: the tracks beside no longer go with it, and it doesn't go with them, also when the lines are worked out again"); + } + if (off > 0) + { + if (ImGui::SmallButton(STR_C("Back on the common grade line"))) + grade_line_take_off(false); + item_tooltip("The route lies on the common grade line again. Its height doesn't change by this; if it's off the tracks beside, fit it to them with the grade line or by working out the lines anew"); + } +} diff --git a/application/editormodeinfra.cpp b/application/editormodeinfra.cpp index e805c5452..d5212f56a 100644 --- a/application/editormodeinfra.cpp +++ b/application/editormodeinfra.cpp @@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "application/editormode.h" #include "application/editorprojection.h" +#include "application/editormodeshared.h" #include "editor/editorFormat.hpp" #include "editor/editorGeometry.hpp" @@ -48,6 +49,12 @@ using geometry::plan_distance; using geometry::plan_of; std::string const kBindingMark{"//$b"}; +// the templates of the signalling which go with a path without a signal template of their own: the SHP resonator, read by its +// event, and the control of a block section, by the path nearest to it +std::string const kResonatorFile{"rezonator.inc"}; +std::string const kControlFile{"sbl_odstep.inc"}; +double constexpr kAdoptReach{12.0}; // m, of a point object from the axis of its path +double constexpr kBoundReach{30.0}; // m, of a point object bound by hand, as far as a changed path looks for it template bool contains(std::vector const &Items, Type_ const &Item) @@ -65,6 +72,8 @@ ImU32 colour(infra::category const Category, int const Alpha = 255) case infra::category::catenary: return IM_COL32(80, 200, 255, Alpha); case infra::category::logic: return IM_COL32(220, 120, 255, Alpha); case infra::category::other: return IM_COL32(200, 200, 200, Alpha); + case infra::category::equipment: return IM_COL32(255, 150, 60, Alpha); + case infra::category::environment: return IM_COL32(110, 190, 110, Alpha); } return IM_COL32(200, 200, 200, Alpha); } @@ -94,6 +103,11 @@ class live_nodes { return Node != nullptr && m_nodes.count(Node) > 0; } + void forget(scene::basic_node const *Node) + { + m_nodes.erase(Node); + m_valid = false; + } private: std::unordered_set m_nodes; @@ -123,15 +137,9 @@ struct include_place int yaw{-1}; glm::dvec3 offset{0.0}; std::string description; // name and category of the template + std::string category; // of the description of the template }; -bool numeric(std::string const &Text, double &Value) -{ - char *end{nullptr}; - Value = std::strtod(Text.c_str(), &end); - return false == Text.empty() && *end == '\0'; -} - bool include_place_of(scene::instance_handle const Instance, include_place &Place) { if (false == scene::Layers.tracked(Instance)) @@ -164,6 +172,7 @@ bool include_place_of(scene::instance_handle const Instance, include_place &Plac Place.yaw = index("rot.y"); Place.offset = included.context.offset; Place.description = info.name + ' ' + info.category; + Place.category = info.category; return Place.position[0] >= 0 && Place.position[1] >= 0 && Place.position[2] >= 0; } @@ -287,6 +296,7 @@ void move_traction(TTraction *Traction, std::array const &Points) Traction->location(glm::mix(Points[1], Points[0], 0.5)); Traction->m_area.radius = -1.f; simulation::Region->insert_and_register(Traction); + GfxRenderer->Erase(Traction->m_geometry); Traction->m_geometry = gfx::geometry_handle{}; auto §ion{simulation::Region->section(Traction->location())}; if (section.m_geometrycreated) @@ -658,15 +668,18 @@ std::optional read_binding(std::string const &Text, scene::layer { double const tolerance{0.05}; std::istringstream line{Text}; - std::string kindname, key; - int group{0}, turns{0}, count{0}; + std::string kindname; + std::string key; + int group{0}; + int turns{0}; + int count{0}; glm::dvec3 location; line >> kindname >> group >> location.x >> location.y >> location.z >> key >> turns >> count; if (line.fail() || count < 1 || count > 4) return std::nullopt; location = Context.to_world(location); infra::binding binding; - binding.group = static_cast(std::clamp(group, 0, static_cast(infra::category::other))); + binding.group = static_cast(std::clamp(group, 0, static_cast(infra::category::environment))); binding.turns = (turns != 0); auto found{false}; if (kindname == infra::name(infra::kind::model)) @@ -707,7 +720,8 @@ std::optional read_binding(std::string const &Text, scene::layer for (int i = 0; i < count && found; ++i) { int path{0}; - glm::dvec3 start, end; + glm::dvec3 start; + glm::dvec3 end; line >> path >> start.x >> start.y >> start.z >> end.x >> end.y >> end.z; start = Context.to_world(start); end = Context.to_world(end); @@ -768,6 +782,17 @@ void editor_mode::infra_load() logtype::generic); } +void editor_mode::infra_forget(scene::basic_node const *Node) +{ + Live.forget(Node); + auto const held = [Node](infra::binding const &Binding) { return Binding.type != infra::kind::include && Binding.node == Node; }; + m_bindings.erase(std::remove_if(m_bindings.begin(), m_bindings.end(), held), m_bindings.end()); + m_infra_buffer.erase(std::remove_if(m_infra_buffer.begin(), m_infra_buffer.end(), [&](infra::object_state const &State) { return held(State.saved); }), m_infra_buffer.end()); + for (auto &candidate : m_infra.candidates) + if (held(candidate.binding)) + candidate.binding.node = nullptr; +} + void editor_mode::infra_store() { if (false == m_bindings_loaded || scene::Layers.empty()) @@ -784,7 +809,7 @@ void editor_mode::infra_store() { std::vector points; std::optional yaw; - if (binding.anchors.empty() || false == object_points(binding, points, yaw)) + if (binding.adopted || binding.anchors.empty() || false == object_points(binding, points, yaw)) continue; auto layer{scene::Layers.resolve(binding.anchors.front().at.track->layer())}; if (false == scene::Layers.valid(layer) || false == scene::Layers.accepts(layer)) @@ -851,6 +876,18 @@ infra::binding *editor_mode::infra_find(infra::binding const &Binding) return nullptr; } +std::string editor_mode::infra_carried_note() +{ + auto const count{m_infra_carried.size()}; + m_infra_carried.clear(); + return count > 0 ? format(STR_P("\n%zu object by the tracks moved sideways with them", "\n%zu objects by the tracks moved sideways with them", count), count) : std::string{}; +} + +int editor_mode::infra_bound_count() const +{ + return static_cast(std::count_if(m_bindings.begin(), m_bindings.end(), [](infra::binding const &Binding) { return false == Binding.adopted; })); +} + void editor_mode::infra_recognize() { auto &state{m_infra}; @@ -865,7 +902,10 @@ void editor_mode::infra_recognize() state.error = (state.scope == 2 ? STR_C("Open the vertical profile of a route first") : state.scope == 3 ? STR_C("The scenery has no paths the editor can handle") : STR_C("Select a path first")); return; } - state.read = state.overruled = state.unread = state.elsewhere = 0; + state.read = 0; + state.overruled = 0; + state.unread = 0; + state.elsewhere = 0; track_index index; std::unordered_set names; std::unordered_set const scope(state.tracks.begin(), state.tracks.end()); @@ -955,15 +995,15 @@ void editor_mode::infra_recognize() Binding.label = object_label(Binding); candidate.offset = Binding.anchors.front().offset; candidate.reason = Reason; - candidate.bound = (infra_find(Binding) != nullptr); - candidate.chosen = (false == candidate.bound && Binding.group != infra::category::other); + auto const *existing{infra_find(Binding)}; + candidate.bound = (existing != nullptr && false == existing->adopted); + candidate.chosen = (false == candidate.bound && Binding.group != infra::category::other && Binding.group != infra::category::environment); candidate.binding = std::move(Binding); state.read += candidate.reader != nullptr ? 1 : 0; state.overruled += candidate.nearer != nullptr ? 1 : 0; state.unread += candidate.unread ? 1 : 0; state.candidates.push_back(std::move(candidate)); }; - auto const rule_reason = [](infra::category const Group, char const *What) { return Group == infra::category::other ? std::string{"nearby, no rule matches the "} + What : std::string{"the "} + What + " matches a rule"; }; for (auto *model : simulation::Instances.sequence()) { @@ -974,7 +1014,7 @@ void editor_mode::infra_recognize() binding.type = infra::kind::model; binding.node = model; binding.group = infra::classify(model->Model()->NameGet() + ' ' + model->name(), state.rules); - add(binding, rule_reason(binding.group, "file name"), corridor); + add(binding, binding.group == infra::category::other ? STR("nearby, no rule matches the file name") : STR("the file name matches a rule"), corridor); } for (scene::instance_handle handle = 1; handle <= scene::Layers.instance_count(); ++handle) { @@ -984,8 +1024,15 @@ void editor_mode::infra_recognize() infra::binding binding; binding.type = infra::kind::include; binding.include = handle; + // the kind the description of the template names, else by the rules + if (auto const named{infra::category_named(place.category)}) + { + binding.group = *named; + add(binding, STR("the description of the template says what it is"), corridor); + continue; + } binding.group = infra::classify(place.file + ' ' + place.description, state.rules); - add(binding, rule_reason(binding.group, "template or its description"), corridor); + add(binding, binding.group == infra::category::other ? STR("nearby, no rule matches the template or its description") : STR("the template or its description matches a rule"), corridor); } for (auto *piece : simulation::Traction.sequence()) { @@ -995,7 +1042,7 @@ void editor_mode::infra_recognize() binding.type = infra::kind::traction; binding.node = piece; binding.group = infra::category::catenary; - add(binding, "wire over the track", corridor); + add(binding, STR("wire over the track"), corridor); } for (auto *memcell : simulation::Memory.sequence()) { @@ -1006,7 +1053,7 @@ void editor_mode::infra_recognize() binding.node = memcell; binding.group = infra::category::logic; auto const named{false == memcell->asTrackName.empty() && names.count(memcell->asTrackName) > 0}; - add(binding, named ? "names the path " + memcell->asTrackName : std::string{"nearby"}, named ? std::max(corridor, 50.0) : corridor); + add(binding, named ? format(STR_C("names the path %s"), memcell->asTrackName.c_str()) : STR("nearby"), named ? std::max(corridor, 50.0) : corridor); } for (auto *launcher : simulation::Events.launchers()) { @@ -1016,7 +1063,7 @@ void editor_mode::infra_recognize() binding.type = infra::kind::launcher; binding.node = launcher; binding.group = infra::category::logic; - add(binding, "nearby", corridor); + add(binding, STR("nearby"), corridor); } std::stable_sort(state.candidates.begin(), state.candidates.end(), [](infra_candidate const &A, infra_candidate const &B) { return A.binding.group < B.binding.group; }); state.status = format(STR_C("%d object(s) found along %d path(s)"), static_cast(state.candidates.size()), static_cast(state.tracks.size())); @@ -1125,25 +1172,179 @@ void editor_mode::infra_buffer(infra::binding const &Binding, bool const Refresh m_infra_buffer.push_back(infra_state_of(Binding)); } +void editor_mode::infra_adopt(TTrack &Track) +{ + auto const revision{history_revision()}; + if (revision != m_point_objects_revision || scene::Layers.instance_count() != m_point_objects_count) + { + m_point_objects_revision = revision; + m_point_objects_count = scene::Layers.instance_count(); + m_point_objects.clear(); + std::unordered_map readers; + for (auto *track : simulation::Paths.sequence()) + if (track != nullptr && false == track->m_editorremoved) + for (int list = 0; list < 6; ++list) + for (auto const &event : editor_track::events(*track, list)) + if (false == event.first.empty()) + readers.emplace(ToLower(event.first), track); + static auto const rules{infra::default_rules()}; + // an indicator goes with its signal: by the path reading the signal named by its first parameter, not by the path nearest + // to it, which can be another one + std::unordered_map signal_reads; + std::vector> marks; + for (scene::instance_handle handle = 1; handle <= scene::Layers.instance_count(); ++handle) + { + include_place place; + if (false == include_place_of(handle, place) || place.values.empty() || false == scene::Layers.removable(handle)) + continue; + point_object object; + object.include = handle; + object.location = include_location(place); + auto const file{ToLower(place.file)}; + if (indicator_template_of(place.file) != nullptr) + { + object.group = infra::category::sign; + marks.emplace_back(std::move(object), ToLower(place.values.front())); + continue; + } + auto const *signal{signal_template_of(place.file)}; + std::string read; + if (signal != nullptr) + { + object.group = infra::category::signal; + read = signal->read.empty() ? std::string{} : editor_includes::substitute(signal->read, place.values); + signal_reads[ToLower(place.values.front())] = read; + } + else if (file == kResonatorFile) + { + object.group = infra::category::equipment; + read = place.values.front() + "_shp"; + } + else if (file == kControlFile) + object.group = infra::category::logic; + else + { + auto const named{infra::category_named(place.category)}; + object.group = named.has_value() ? *named : infra::classify(place.file + ' ' + place.description, rules); + if (object.group != infra::category::signal && object.group != infra::category::sign) + continue; + } + if (false == read.empty()) + if (auto const reader{readers.find(ToLower(read))}; reader != readers.end()) + object.reader = reader->second; + m_point_objects.push_back(std::move(object)); + } + // one whose signal no path reads is left where it is + for (auto &[object, name] : marks) + if (auto const read{signal_reads.find(name)}; read != signal_reads.end() && false == read->second.empty()) + if (auto const reader{readers.find(ToLower(read->second))}; reader != readers.end()) + { + object.reader = reader->second; + m_point_objects.push_back(std::move(object)); + } + // the path nearest to each one no path reads, the objects by cells of the plan + auto constexpr cell{200.0}; + auto const key = [&](double const Value) { return static_cast(std::floor(Value / cell)); }; + std::map, std::vector> cells; + for (std::size_t i = 0; i < m_point_objects.size(); ++i) + if (m_point_objects[i].reader == nullptr) + cells[{key(m_point_objects[i].location.x), key(m_point_objects[i].location.z)}].push_back(i); + std::vector nearest(m_point_objects.size(), kAdoptReach); + for (auto *track : simulation::Paths.sequence()) + { + if (cells.empty() || track == nullptr || track->m_editorremoved || false == editor_track::is_supported(*track)) + continue; + auto const area{area_of(*track)}; + auto const reach{area.radius + kAdoptReach}; + for (auto x = key(area.centre.x - reach); x <= key(area.centre.x + reach); ++x) + for (auto z = key(area.centre.z - reach); z <= key(area.centre.z + reach); ++z) + { + auto const found{cells.find({x, z})}; + if (found == cells.end()) + continue; + for (auto const i : found->second) + { + auto &object{m_point_objects[i]}; + if (plan_distance(object.location, area.centre) > area.radius + nearest[i]) + continue; + infra::station station; + bool interior; + auto const distance{infra::project(*track, object.location, station, interior)}; + if (distance < nearest[i] && beside(station, object.location, interior)) + { + nearest[i] = distance; + object.nearest = track; + } + } + } + } + } + auto const area{area_of(Track)}; + for (auto const &object : m_point_objects) + { + if (plan_distance(object.location, area.centre) > area.radius + kAdoptReach) + continue; + infra::binding binding; + binding.type = infra::kind::include; + binding.include = object.include; + if (infra_find(binding) != nullptr) + continue; + // of the line of the track: read by it or by a path of its run, else nearest to it; not one of the track alongside + if (object.reader != nullptr && object.reader != &Track) + { + auto const spans{editor_track::run_route(*object.reader, 250.0).spans}; + if (std::none_of(spans.begin(), spans.end(), [&](auto const &Span) { return Span.track == &Track; })) + continue; + } + if (object.reader == nullptr && object.nearest != &Track) + continue; + infra::station station; + bool interior; + if (infra::project(Track, object.location, station, interior) > kAdoptReach || false == beside(station, object.location, interior)) + continue; + std::vector points; + std::optional yaw; + if (false == object_points(binding, points, yaw) || points.empty()) + continue; + binding.group = object.group; + binding.anchors.push_back(infra::make_anchor(station, points.front())); + binding.turns = yaw.has_value() && object.group != infra::category::logic; + if (binding.turns) + binding.yaw = turn_of(binding, *yaw); + binding.label = object_label(binding); + binding.adopted = true; + binding.measured = points.front(); + m_bindings.push_back(std::move(binding)); + } +} + void editor_mode::track_captured(TTrack const &Track) { sweeps_captured(Track); + switch_drive_captured(Track); + grade_line_captured(Track); if (m_infra_suspended || false == m_infra.follow) return; infra_load(); + // the signals and the like of the track follow it, staying where they stand along it + infra_adopt(const_cast(Track)); if (m_bindings.empty()) return; Live.refresh(); - for (auto &binding : m_bindings) + std::vector gone; + for (std::size_t index = 0; index < m_bindings.size(); ++index) { + auto &binding{m_bindings[index]}; if (std::none_of(binding.anchors.begin(), binding.anchors.end(), [&](infra::anchor const &Anchor) { return Anchor.at.track == &Track; }) || false == alive(binding)) continue; - // an object moved by hand since it was bound is measured again, as long as the path is the way it was measured + // an object moved by hand since it was bound is measured again, as long as the path is the way it was measured. one of a single + // point moved away from the track, off its side, doesn't follow it any more: measured along it, it would be taken back to its end std::vector points; std::optional yaw; + auto away{false}; if (object_points(binding, points, yaw) && points.size() == binding.anchors.size()) { - for (std::size_t i = 0; i < points.size(); ++i) + for (std::size_t i = 0; i < points.size() && false == away; ++i) { auto &anchor{binding.anchors[i]}; if (anchor.at.track != &Track || anchor.at.path >= static_cast(Track.m_paths.size())) @@ -1154,18 +1355,37 @@ void editor_mode::track_captured(TTrack const &Track) auto placed{anchor}; if (glm::distance(infra::place(placed), points[i]) <= 0.01) continue; - anchor = infra::make_anchor(anchor.at.track, anchor.at.path, points[i]); + infra::station station; + bool interior{false}; + auto const reach{binding.adopted ? kAdoptReach : kBoundReach}; + if (points.size() == 1 && (infra::project(const_cast(Track), points[i], station, interior) > reach || false == beside(station, points[i], interior))) + away = true; + else + anchor = infra::make_anchor(anchor.at.track, anchor.at.path, points[i]); } - if (binding.turns && yaw.has_value() && binding.anchors.front().at.track == &Track) + if (false == away && binding.turns && yaw.has_value() && binding.anchors.front().at.track == &Track) binding.yaw = turn_of(binding, *yaw); } + if (away) + { + WriteLog("Editor: " + binding.label + " moved away from track " + Track.name() + ", it doesn't follow it any more"); + gone.push_back(index); + continue; + } + if (binding.adopted && false == points.empty()) + binding.measured = points.front(); infra_buffer(binding, true); } + infra_unbind(std::move(gone)); } void editor_mode::tracks_committed(std::vector const &Tracks) { + nmt_track_changed(Tracks); + m_joints.tracks_committed(Tracks); sweeps_committed(Tracks); + switch_drives_committed(Tracks); + grade_lines_committed(Tracks); if (m_infra_suspended || false == m_infra.follow) return; infra_load(); @@ -1191,6 +1411,7 @@ void editor_mode::tracks_committed(std::vector const &Tracks) // only a path running where the old one did, not the one alongside return nearest_beside(*everywhere, Foot, 1.0, Station); }; + std::vector dropped; for (auto &binding : m_bindings) { auto const affected{std::any_of(binding.anchors.begin(), binding.anchors.end(), [&](infra::anchor const &Anchor) { @@ -1198,6 +1419,14 @@ void editor_mode::tracks_committed(std::vector const &Tracks) })}; if (false == affected || false == alive(binding)) continue; + std::vector standing; + std::optional facing; + if (binding.adopted && (false == object_points(binding, standing, facing) || standing.empty() || glm::distance(standing.front(), binding.measured) > 0.01)) + { + // moved by another tool while its track was being changed: it stays where that put it, bound again with the next change + dropped.push_back(binding.include); + continue; + } auto moved{binding}; auto lost{false}; for (auto &anchor : moved.anchors) @@ -1224,33 +1453,71 @@ void editor_mode::tracks_committed(std::vector const &Tracks) } auto const offset{anchor.offset}; auto const height{anchor.height}; + // a path taking the object over may run the other way: the object stays on its side, turned as it was + auto const before{plan_of(anchor.end - anchor.start)}; anchor = infra::make_anchor(station, anchor.foot); - anchor.offset = offset; + auto const reversed{glm::length(before) > 1e-6 && glm::dot(before, infra::frame_at(anchor.at).forward) < 0.0}; + anchor.offset = reversed ? -offset : offset; anchor.height = height; + if (reversed && &anchor == &moved.anchors.front()) + moved.yaw = clamp_circular(moved.yaw + 180.0); } if (lost) { - binding.lost = true; + if (binding.adopted) + dropped.push_back(binding.include); + else + binding.lost = true; continue; } + if (binding.adopted) + { + // where nothing moved, the directive stays as it is written + auto const there{infra::place(moved.anchors.front())}; + auto const turned{facing.has_value() && moved.turns ? std::abs(clamp_circular(infra::heading(infra::frame_at(moved.anchors.front().at).forward) + moved.yaw - *facing + 180.0) - 180.0) : 0.0}; + if (glm::distance(there, standing.front()) < 0.005 && turned < 0.01) + { + moved.lost = false; + binding = std::move(moved); + continue; + } + } infra_buffer(binding, false); moved.lost = false; binding = std::move(moved); infra_move(binding); + m_infra_carried.emplace(binding.node, binding.include); + if (binding.adopted) + { + std::vector points; + std::optional yaw; + if (object_points(binding, points, yaw) && false == points.empty()) + binding.measured = points.front(); + } for (auto &entry : m_infra_buffer) if (entry.saved.same(binding)) entry.moved = true; } + if (false == dropped.empty()) + m_bindings.erase(std::remove_if(m_bindings.begin(), m_bindings.end(), [&](infra::binding const &Binding) { return Binding.adopted && contains(dropped, Binding.include); }), m_bindings.end()); } -void editor_mode::track_retired(TTrack &) +void editor_mode::track_retired(TTrack &Track) { + nmt_track_gone(Track); tracks_committed({}); } +void editor_mode::track_renamed(TTrack const &Track, std::string const &Old) +{ + grade_line_renamed(Track, Old); +} + void editor_mode::track_split(TTrack &Original, TTrack &Created, segment_data const &First) { sweeps_split(Original, Created); + grade_line_split(Original, Created); + signal_split(Original, Created); if (m_infra_suspended || Created.m_paths.empty()) return; auto const length{infra::plan_length(First)}; @@ -1327,6 +1594,9 @@ void editor_mode::infra_attach(EditorSnapshot &Snapshot) auto const involved = [&](infra::object_state const &State) { if (State.moved) return true; + // one the editor bound for the change which didn't move: its own changes, if any, are taken back by the tool which made them + if (State.saved.adopted) + return false; for (auto const &anchor : State.saved.anchors) { if (contains(Snapshot.created, anchor.at.track) || contains(Snapshot.removed, anchor.at.track)) @@ -1361,7 +1631,7 @@ void editor_mode::render_infra_body() "models and includes turn with the path and stay upright. The move is a part of the undo step of the change.")); ImGui::SameLine(); ImGui::Checkbox(STR_C("Show in 3D"), &state.show); - ImGui::Text(STR_C("Objects bound in the scenery: %d"), static_cast(m_bindings.size())); + ImGui::Text(STR_C("Objects bound in the scenery: %d"), infra_bound_count()); if (false == m_bindings_unresolved.empty()) { ImGui::SameLine(); @@ -1408,31 +1678,35 @@ void editor_mode::render_infra_search() char const *const scopes[] = {STR_C("Selected path"), STR_C("Line through the selected path"), STR_C("Route of the vertical profile"), STR_C("Whole scenery")}; ImGui::SetNextItemWidth(260.f); ImGui::Combo(STR_C("Look along"), &state.scope, scopes, IM_ARRAYSIZE(scopes)); - if (state.scope == 1) + if (ImGui::TreeNode(STR_C("More settings"))) { - ImGui::SetNextItemWidth(120.f); - ImGui::InputFloat(STR_C("Reach each way, m"), &state.reach, 100.f, 500.f, "%.0f"); - state.reach = std::clamp(state.reach, 10.f, 20000.f); - } - ImGui::SetNextItemWidth(120.f); - ImGui::InputFloat(STR_C("Corridor each side of the axis, m"), &state.corridor, 0.5f, 2.f, "%.1f"); - state.corridor = std::clamp(state.corridor, 0.5f, 50.f); - if (ImGui::TreeNode(STR_C("Rules for names of the files"))) - { - ImGui::TextDisabled(STR_C("Parts of the names, separated by spaces; the first rule which matches decides")); - for (std::size_t i = 0; i < state.rules.size(); ++i) + if (state.scope == 1) { - auto &rule{state.rules[i]}; - char buffer[512]; - std::snprintf(buffer, sizeof(buffer), "%s", rule.keywords.c_str()); - ImGui::SetNextItemWidth(360.f); - if (ImGui::InputText((std::string{infra::name(rule.group)} + "##rule" + std::to_string(i)).c_str(), buffer, sizeof(buffer))) - rule.keywords = buffer; + ImGui::SetNextItemWidth(120.f); + ImGui::InputFloat(STR_C("Reach each way, m"), &state.reach, 100.f, 500.f, "%.0f"); + state.reach = std::clamp(state.reach, 10.f, 20000.f); + } + ImGui::SetNextItemWidth(120.f); + ImGui::InputFloat(STR_C("Corridor each side of the axis, m"), &state.corridor, 0.5f, 2.f, "%.1f"); + state.corridor = std::clamp(state.corridor, 0.5f, 50.f); + if (ImGui::TreeNode(STR_C("Rules for names of the files"))) + { + ImGui::TextDisabled("%s", STR_C("Parts of the names, separated by spaces; the first rule which matches decides")); + for (std::size_t i = 0; i < state.rules.size(); ++i) + { + auto &rule{state.rules[i]}; + char buffer[512]; + std::snprintf(buffer, sizeof(buffer), "%s", rule.keywords.c_str()); + ImGui::SetNextItemWidth(360.f); + if (ImGui::InputText((std::string{STR_C(infra::name(rule.group))} + "##rule" + std::to_string(i)).c_str(), buffer, sizeof(buffer))) + rule.keywords = buffer; + } + if (ImGui::SmallButton(STR_C("Default rules"))) + state.rules = infra::default_rules(); + ImGui::TextDisabled("%s", STR_C("Includes are matched by the template name and its //$e description, models by the file and node name;\n" + "traction is always the catenary, memory cells and event launchers the logic")); + ImGui::TreePop(); } - if (ImGui::SmallButton(STR_C("Default rules"))) - state.rules = infra::default_rules(); - ImGui::TextDisabled(STR_C("Includes are matched by the template name and its //$e description, models by the file and node name;\n" - "traction is always the catenary, memory cells and event launchers the logic")); ImGui::TreePop(); } if (ImGui::Button(STR_C("Find objects"))) @@ -1478,31 +1752,15 @@ void editor_mode::render_infra_candidates() if (state.read > 0 || state.unread > 0) { - ImGui::TextColored(readcolour, STR_C("%d read by the paths"), state.read); - if (ImGui::IsItemHovered()) - ImGui::SetTooltip(STR_C("The memory cell of the object is read by a getvalues event of a path, listed by the path, inside a multiple\n" - "event or written loose as :event. The object is bound to the thread of that path, not to the nearest one")); - if (state.overruled > 0) - { - ImGui::SameLine(); - ImGui::TextColored(warncolour, STR_C("%d of them nearer to another path"), state.overruled); - if (ImGui::IsItemHovered()) - ImGui::SetTooltip(STR_C("By the distance alone these would go to the wrong thread. Check them in 3D: the dashed line goes to the nearer path")); - } - if (state.unread > 0) - { - ImGui::SameLine(); - ImGui::TextColored(warncolour, STR_C("%d signal(s) not read by any path"), state.unread); - if (ImGui::IsItemHovered()) - ImGui::SetTooltip(STR_C("The signal has a memory cell, but no event of a path reads it: the vehicles won't see it.\nBound to the nearest path")); - } - static char const *const filters[] = {"All", "Read by a path", "Nearer to another path", "Not read"}; - for (int i = 0; i < IM_ARRAYSIZE(filters); ++i) - { - if (i > 0) - ImGui::SameLine(); - ImGui::RadioButton(STR_C(filters[i]), &state.filter, i); - } + std::string const labels[]{format("%s (%d)", STR_C("All"), static_cast(candidates.size())), format("%s (%d)", STR_C("Read by a path"), state.read), + format("%s (%d)", STR_C("Nearer to another path"), state.overruled), format("%s (%d)", STR_C("Not read"), state.unread)}; + choice_chips("infrafilter", state.filter, + {{0, labels[0].c_str()}, + {1, labels[1].c_str(), + "The memory cell of the object is read by a getvalues event of a path, listed by the path, inside a multiple\n" + "event or written loose as :event. The object is bound to the thread of that path, not to the nearest one"}, + {2, labels[2].c_str(), "By the distance alone these would go to the wrong thread. Check them in 3D: the dashed line goes to the nearer path"}, + {3, labels[3].c_str(), "The signal has a memory cell, but no event of a path reads it: the vehicles won't see it.\nBound to the nearest path"}}); } ImGui::BeginChild("##infracandidates", ImVec2(0.f, 260.f), true); @@ -1516,7 +1774,7 @@ void editor_mode::render_infra_candidates() if (rows.empty()) continue; ImGui::PushStyleColor(ImGuiCol_Text, ImGui::ColorConvertU32ToFloat4(colour(group))); - auto const open{ImGui::TreeNodeEx(format("%s (%d)", infra::name(group), static_cast(rows.size())).c_str(), group == infra::category::other ? 0 : ImGuiTreeNodeFlags_DefaultOpen)}; + auto const open{ImGui::TreeNodeEx(format("%s (%d)", STR_C(infra::name(group)), static_cast(rows.size())).c_str(), group == infra::category::other || group == infra::category::environment ? 0 : ImGuiTreeNodeFlags_DefaultOpen)}; ImGui::PopStyleColor(); ImGui::SameLine(); if (ImGui::SmallButton((std::string{STR_C("all##g")} + infra::name(group)).c_str())) @@ -1547,7 +1805,7 @@ void editor_mode::render_infra_candidates() { state.hovered = i; std::string text{format(STR_C("%s, %s\n%.2f m %s of the axis, %.2f m above the rail top\n%s"), infra::name(candidate.binding.type), anchor.at.track != nullptr ? anchor.at.track->name().c_str() : "-", std::abs(candidate.offset), - candidate.offset >= 0.0 ? "right" : "left", anchor.height, candidate.reason.c_str())}; + candidate.offset >= 0.0 ? STR_C("on the right") : STR_C("on the left"), anchor.height, candidate.reason.c_str())}; if (candidate.reader != nullptr) text += format(STR_C("\nRead by the path %s: event %s, getvalues of the memory cell %s"), candidate.reader->name().c_str(), candidate.event.c_str(), candidate.cell.c_str()) + (candidate.loose ? STR(" (written loose, the path takes it by the name)") : std::string{}); @@ -1591,9 +1849,9 @@ void editor_mode::render_infra_bound() std::unordered_set const tracks(scope.begin(), scope.end()); std::vector along; for (std::size_t i = 0; i < m_bindings.size(); ++i) - if (std::any_of(m_bindings[i].anchors.begin(), m_bindings[i].anchors.end(), [&](infra::anchor const &Anchor) { return tracks.count(Anchor.at.track) > 0; })) + if (false == m_bindings[i].adopted && std::any_of(m_bindings[i].anchors.begin(), m_bindings[i].anchors.end(), [&](infra::anchor const &Anchor) { return tracks.count(Anchor.at.track) > 0; })) along.push_back(i); - ImGui::Text(STR_C("%d of %d"), static_cast(along.size()), static_cast(m_bindings.size())); + ImGui::Text(STR_C("%d of %d"), static_cast(along.size()), infra_bound_count()); if (false == along.empty()) { ImGui::SameLine(); @@ -1657,7 +1915,8 @@ void editor_mode::draw_infra_overlay() const drawlist->AddCircleFilled(screen, Size, Colour); }; for (auto const &binding : m_bindings) - draw(binding, binding.lost ? overlay_color::invalid : IM_COL32(90, 230, 110, 220), 3.5f); + if (false == binding.adopted) + draw(binding, binding.lost ? overlay_color::invalid : IM_COL32(90, 230, 110, 220), 3.5f); auto const object = [&](infra_candidate const &Candidate) { std::vector points; std::optional yaw; diff --git a/application/editormodejoints.cpp b/application/editormodejoints.cpp index c50d9d825..12c1e4357 100644 --- a/application/editormodejoints.cpp +++ b/application/editormodejoints.cpp @@ -8,11 +8,13 @@ http://mozilla.org/MPL/2.0/. */ #include "stdafx.h" -#include "application/editormode.h" -#include "application/editoruilayer.h" +#include "application/editormodejoints.h" +#include "editor/editorNmt.hpp" +#include "application/editormodeshared.h" #include "application/editorprojection.h" #include "editor/editorFormat.hpp" #include "editor/editorGeometry.hpp" +#include "editor/editorProfile.hpp" #include "scene/scene.h" #include "scene/scenelayers.h" @@ -25,6 +27,8 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include +#include #include #include @@ -38,8 +42,18 @@ double const kLinked{0.02}; // m, ends this close are joined by the simulation double const kOverlayRange{3000.0}; double const kGauge{1.5}; // m between the rails, for the cant int const kRailCategory{1}; +double const kModelStep{5.0}; // m between the places of the tracks compared with the terrain model +std::size_t const kModelRun{200}; // places of a path whose model is asked for at once +double const kModelPoll{0.25}; // s between the looks whether the model is in +double const kUnfitted{30.0}; // m; a scenery whose tracks lie this far from the model as a whole isn't fitted to it +// a track over the model by more than the depth goes on a bridge or a viaduct the model leaves out where the model falls away by +// the abutments, steeper than the banks, within the reach along the track both ways; as the grade lines fitted to the model +// tell them. By the abutments the track is over the model by less +double const kBridgeDepth{1.0}; // m +double const kAbutment{100.0}; // per mille +double const kBridgeReach{200.0}; // m -using kind = editor_mode::joint_issue::kind; +using kind = joints_tool::joint_issue::kind; bool rail(TTrack const &Track) { @@ -78,16 +92,11 @@ double plan_angle(glm::dvec3 const &A, glm::dvec3 const &B) return glm::degrees(std::acos(std::clamp(glm::dot(glm::normalize(a), glm::normalize(b)), -1.0, 1.0))); } -using end_key = std::tuple; - -end_key key_of(TTrack const *Track, editor_track::point_ref const &Point) +std::tuple key_of(TTrack const *Track, editor_track::point_ref const &Point) { return {Track, Point.path, static_cast(Point.kind)}; } -// pairs of the ends already looked at in the check under way -std::set> reported; - char const *kind_name(kind const Kind) { switch (Kind) @@ -97,19 +106,21 @@ char const *kind_name(kind const Kind) case kind::kink: return "kink"; case kind::cant: return "cant jump"; case kind::grade: return "grade break"; + case kind::model: return "off the terrain model"; default: return "free end"; } } -std::string value_text(editor_mode::joint_issue const &Issue) +std::string value_text(joints_tool::joint_issue const &Issue) { switch (Issue.type) { case kind::gap: return format("%.3f m", Issue.value); case kind::step: return format("%.1f mm", Issue.value * 1000.0); - case kind::kink: return format("%.3f deg", Issue.value); + case kind::kink: return format("%.3f\xc2\xb0", Issue.value); case kind::cant: return format("%.1f mm", Issue.value); - case kind::grade: return format("%.1f %%o", Issue.value); + case kind::grade: return format("%.1f \xe2\x80\xb0", Issue.value); + case kind::model: return format("%+.2f m", Issue.value); default: return "-"; } } @@ -123,20 +134,19 @@ ImU32 kind_colour(kind const Kind) case kind::kink: return IM_COL32(255, 190, 60, 225); case kind::cant: return IM_COL32(200, 120, 255, 225); case kind::grade: return IM_COL32(90, 200, 255, 220); + case kind::model: return IM_COL32(70, 200, 190, 235); default: return IM_COL32(200, 200, 200, 200); } } -std::string name_of(TTrack const *Track) +std::string label_of(TTrack const *Track) { - if (Track == nullptr) - return "-"; - return Track->name().empty() ? std::string{"(noname)"} : Track->name(); + return Track == nullptr ? std::string{"-"} : ::name_of(*Track); } } // namespace -void editor_mode::joints_start() +void joints_tool::joints_start() { auto &state{m_joints}; state.queue.clear(); @@ -144,7 +154,7 @@ void editor_mode::joints_start() state.issues.clear(); state.selected = -1; state.status.clear(); - reported.clear(); + m_reported.clear(); glm::dvec3 const camera{Global.pCamera.Pos}; for (auto *track : simulation::Paths.sequence()) { @@ -154,13 +164,152 @@ void editor_mode::joints_start() continue; state.queue.push_back(track); } - state.history = m_history.size(); + state.history = m_history.history_revision(); + state.places.clear(); + state.runs.clear(); + state.run_next = 0; + state.model_waiting = false; + state.model_asked = false; + state.model_polled = 0.0; + state.model_unplaced = false; + if (false == state.model_check || state.queue.empty()) + return; + m_ground.nmt_locate(); + if (false == m_ground.terrain_model().placed()) + { + state.model_unplaced = true; + return; + } + std::set const queued(state.queue.begin(), state.queue.end()); + for (auto const &place : m_ground.nmt_track_places(kModelStep)) + if (place.shapes && queued.count(place.track) > 0) + { + if (state.places.empty() || state.places.back().track != place.track || state.places.back().path != place.path || state.places.size() - state.runs.back().first >= kModelRun) + state.runs.emplace_back(state.places.size(), state.places.size()); + state.places.push_back(place); + state.runs.back().second = state.places.size(); + } + state.model_waiting = false == state.places.empty(); } -void editor_mode::joints_check(TTrack &Track) +bool joints_tool::joints_model() { auto &state{m_joints}; - auto const once = [&](end_key const &A, end_key const &B) { return reported.insert(A < B ? std::make_pair(A, B) : std::make_pair(B, A)).second; }; + auto const now{ImGui::GetTime()}; + if (state.model_asked && now - state.model_polled < kModelPoll) + return false; + state.model_polled = now; + auto const box = [&](std::pair const &Run, glm::dvec2 &Min, glm::dvec2 &Max) { + Min = glm::dvec2{std::numeric_limits::max()}; + Max = glm::dvec2{std::numeric_limits::lowest()}; + for (auto i = Run.first; i < Run.second; ++i) + { + glm::dvec2 const at{state.places[i].position.x, state.places[i].position.z}; + Min = glm::min(Min, at - kBridgeReach); + Max = glm::max(Max, at + kBridgeReach); + } + }; + glm::dvec2 low, high; + // all of it asked for once, then the runs looked over in turn as their squares come + if (false == state.model_asked) + { + for (auto const &run : state.runs) + { + box(run, low, high); + m_ground.terrain_model().request(low, high); + } + state.model_asked = true; + } + while (state.run_next < state.runs.size()) + { + box(state.runs[state.run_next], low, high); + if (false == m_ground.terrain_model().request(low, high)) + return false; + ++state.run_next; + } + std::vector differences(state.places.size(), std::numeric_limits::quiet_NaN()); + std::vector known; + for (std::size_t i = 0; i < state.places.size(); ++i) + if (double height; m_ground.terrain_model().height(state.places[i].position.x, state.places[i].position.z, height)) + { + differences[i] = state.places[i].crown - (height + m_ground.terrain_model_offset()); + known.push_back(differences[i]); + } + auto shift{0.0}; + if (false == m_ground.terrain_model_fitted() && false == known.empty()) + { + std::nth_element(known.begin(), known.begin() + known.size() / 2, known.end()); + if (std::abs(known[known.size() / 2]) > kUnfitted) + shift = known[known.size() / 2]; + } + // a place on a bridge or a viaduct the model leaves out isn't off it: the route through its track sampled both ways, the + // stretches over the model as on a bridge found along it + std::map, std::vector>> routes; + auto const on_bridge = [&](nmt_place const &Place) { + auto found{routes.find(Place.track)}; + if (found == routes.end()) + { + auto route{editor_track::run_route(*Place.track, kBridgeReach)}; + auto samples{editor_track::sample_route(route, 1.0)}; + std::vector chainages, heights, ground; + for (auto const &sample : samples) + { + chainages.push_back(sample.chainage); + heights.push_back(sample.position.y - route.spans[sample.span].track->rail_height()); + double height; + ground.push_back(m_ground.terrain_model().height(sample.position.x, sample.position.z, height) ? height + m_ground.terrain_model_offset() + shift : std::numeric_limits::quiet_NaN()); + } + auto spans{profile::bridged(chainages, heights, ground, kBridgeDepth, kAbutment)}; + found = routes.emplace(Place.track, std::make_pair(std::move(samples), std::move(spans))).first; + } + auto const &[samples, spans]{found->second}; + auto nearest{std::numeric_limits::max()}; + double at{0.0}; + for (auto const &sample : samples) + if (auto const distance{geometry::plan_distance(sample.position, Place.position)}; distance < nearest) + { + nearest = distance; + at = sample.chainage; + } + return nearest <= 1.0 && std::any_of(spans.begin(), spans.end(), [&](profile::departure const &Span) { return at >= Span.from - kModelStep && at <= Span.to + kModelStep; }); + }; + // the place of each path the farthest from the model + std::map, std::size_t> worst; + for (std::size_t i = 0; i < state.places.size(); ++i) + { + if (false == std::isfinite(differences[i])) + continue; + differences[i] -= shift; + if (std::abs(differences[i]) <= state.model || (differences[i] > 0.0 && on_bridge(state.places[i]))) + continue; + auto const key{std::make_pair(state.places[i].track, state.places[i].path)}; + auto const found{worst.find(key)}; + if (found == worst.end()) + worst.emplace(key, i); + else if (std::abs(differences[i]) > std::abs(differences[found->second])) + found->second = i; + } + for (auto const &entry : worst) + { + auto const &place{state.places[entry.second]}; + joint_issue issue; + issue.type = kind::model; + issue.track = place.track; + issue.point = {place.path, editor_track::point_kind::start}; + issue.position = place.position; + issue.value = differences[entry.second]; + state.issues.push_back(issue); + } + state.places.clear(); + state.runs.clear(); + state.model_waiting = false; + return true; +} + +void joints_tool::joints_check(TTrack &Track, std::vector &Issues, std::set> &Seen, bool const Open) const +{ + auto const &state{m_joints}; + auto const once = [&](end_key const &A, end_key const &B) { return Seen.insert(A < B ? std::make_pair(A, B) : std::make_pair(B, A)).second; }; for (int i = 0; i < static_cast(Track.m_paths.size()); ++i) { for (auto const kind_of_end : {editor_track::point_kind::start, editor_track::point_kind::end}) @@ -198,17 +347,17 @@ void editor_mode::joints_check(TTrack &Track) { nearest.type = kind::gap; nearest.position = position; - state.issues.push_back(nearest); + Issues.push_back(nearest); } } - else if (state.free_ends) + else if (Open) { joint_issue open; open.type = kind::open; open.track = &Track; open.point = point; open.position = position; - state.issues.push_back(open); + Issues.push_back(open); } continue; } @@ -233,7 +382,7 @@ void editor_mode::joints_check(TTrack &Track) auto const add = [&](kind const Kind, double const Value) { issue.type = Kind; issue.value = Value; - state.issues.push_back(issue); + Issues.push_back(issue); }; if (step > state.step) add(kind::step, step); @@ -248,10 +397,45 @@ void editor_mode::joints_check(TTrack &Track) } } -void editor_mode::joints_step() +void joints_tool::tracks_committed(std::vector const &Tracks) +{ + for (auto *track : Tracks) + if (track != nullptr) + m_live.pending.insert(track); +} + +void joints_tool::live_update() +{ + auto &live{m_live}; + auto const gone = [](TTrack const *Track) { return Track != nullptr && Track->m_editorremoved; }; + std::erase_if(live.issues, [&](joint_issue const &Issue) { return gone(Issue.track) || gone(Issue.other); }); + if (live.pending.empty() || ImGui::IsMouseDown(ImGuiMouseButton_Left) || ImGui::IsMouseDown(ImGuiMouseButton_Right)) + return; + // the joints of a track changed are looked at again, from its side and from the side of the tracks it joins + std::set checked; + for (auto *track : live.pending) + { + if (track->m_editorremoved || false == rail(*track)) + continue; + checked.insert(track); + for (auto const &path : track->m_paths) + for (auto const index : {segment_data::point::start, segment_data::point::end}) + for (auto const &connection : editor_track::connected_points(*track, path.points[index])) + if (rail(*connection.first)) + checked.insert(connection.first); + } + live.pending.clear(); + std::erase_if(live.issues, [&](joint_issue const &Issue) { return checked.contains(Issue.track) || checked.contains(Issue.other); }); + std::set> seen; + for (auto *track : checked) + joints_check(*track, live.issues, seen, false); +} + +void joints_tool::update() { auto &state{m_joints}; - if (state.next >= state.queue.size()) + live_update(); + if (state.next >= state.queue.size() && false == state.model_waiting) return; auto const deadline{std::chrono::steady_clock::now() + std::chrono::milliseconds(15)}; while (state.next < state.queue.size() && std::chrono::steady_clock::now() < deadline) @@ -259,25 +443,31 @@ void editor_mode::joints_step() auto *track{state.queue[state.next++]}; if (track->m_editorremoved) continue; - joints_check(*track); + joints_check(*track, state.issues, m_reported, state.free_ends); } if (state.next < state.queue.size()) return; + if (state.model_waiting && false == joints_model()) + return; std::stable_sort(state.issues.begin(), state.issues.end(), [](joint_issue const &A, joint_issue const &B) { if (A.type != B.type) return A.type < B.type; - return A.value > B.value; + return std::abs(A.value) > std::abs(B.value); }); - std::array counts{}; + std::array counts{}; for (auto const &issue : state.issues) ++counts[static_cast(issue.type)]; state.status = format(STR_C("%zu paths checked: %d gaps, %d steps, %d kinks, %d cant jumps, %d grade breaks"), state.queue.size(), counts[0], counts[1], counts[2], counts[3], counts[4]); + if (state.model_check && state.model_unplaced) + state.status += STR_C(", the terrain model left out: the scenery isn't placed on the map (the orthophoto settings)"); + else if (state.model_check) + state.status += format(STR_C(", %d paths off the terrain model"), counts[5]); if (state.free_ends) - state.status += format(STR_C(", %d free ends"), counts[5]); + state.status += format(STR_C(", %d free ends"), counts[6]); WriteLog("Editor: joints check - " + state.status, logtype::generic); } -void editor_mode::joints_focus(int const Index) +void joints_tool::joints_focus(int const Index) { auto &state{m_joints}; if (Index < 0 || Index >= static_cast(state.issues.size())) @@ -287,15 +477,14 @@ void editor_mode::joints_focus(int const Index) auto const &paths{simulation::Paths.sequence()}; if (std::find(paths.begin(), paths.end(), issue.track) == paths.end() || issue.track->m_editorremoved) return; - m_node = issue.track; - m_track_point = {}; - ui()->set_node(m_node); - focus_track(*issue.track, issue.point.path, issue.position); + m_selection.set_current_node(issue.track); + m_selection.clear_track_point(); + m_view.focus_track(*issue.track, issue.point.path, issue.position); } -bool editor_mode::joint_fix(joint_issue &Issue, std::vector> &States, std::vector &Changed) +bool joints_tool::joint_fix(joint_issue &Issue, std::vector> &States, std::vector &Changed) { - if (Issue.fixed || Issue.type == kind::open || Issue.track == nullptr || Issue.other == nullptr || Issue.track->m_editorremoved || Issue.other->m_editorremoved) + if (Issue.fixed || Issue.type == kind::open || Issue.type == kind::model || Issue.track == nullptr || Issue.other == nullptr || Issue.track->m_editorremoved || Issue.other->m_editorremoved) return false; auto const movable = [](TTrack const *Track) { std::string reason; @@ -357,7 +546,7 @@ bool editor_mode::joint_fix(joint_issue &Issue, std::vector const &Indices) +void joints_tool::joints_fix(std::vector const &Indices) { auto &state{m_joints}; std::vector> states; @@ -375,67 +564,94 @@ void editor_mode::joints_fix(std::vector const &Indices) state.status = STR_C("Nothing could be fixed: the paths are switches or in the files which can't be changed"); return; } - push_track_snapshot(std::move(states)); + m_history.push_track_snapshot(std::move(states)); editor_track::commit(changed); for (auto *track : changed) track->mark_dirty(); - state.history = m_history.size(); + state.history = m_history.history_revision(); state.status = format(STR_C("%zu joints fixed, Ctrl+Z takes them back"), count); WriteLog("Editor: joints check - " + state.status, logtype::generic); } -void editor_mode::render_joints_body() +void joints_tool::render_options() { auto &state{m_joints}; - ImGui::TextDisabled("%s", STR_C("Ends of the paths which almost meet, steps, kinks,\njumps of the cant and of the grade at the joints")); - ImGui::RadioButton(STR_C("Around the camera"), &state.scope, 0); - ImGui::SameLine(); - ImGui::RadioButton(STR_C("Whole scenery"), &state.scope, 1); - bool const running{state.next < state.queue.size()}; + ImGui::PushTextWrapPos(0.0f); + ImGui::TextDisabled("%s", STR_C("Looks for faults at the joints of the tracks")); + ImGui::PopTextWrapPos(); + segmented("jointscope", state.scope, {{0, STR_C("Around the camera")}, {1, STR_C("Whole scenery")}}); + bool const running{state.next < state.queue.size() || state.model_waiting}; if (running) { - auto const progress{static_cast(state.next) / static_cast(state.queue.size())}; - ImGui::ProgressBar(progress, ImVec2(-70.0f, 0.0f), format(STR_C("Checking %zu / %zu"), state.next, state.queue.size()).c_str()); + if (state.next < state.queue.size()) + { + auto const progress{static_cast(state.next) / static_cast(state.queue.size())}; + ImGui::ProgressBar(progress, ImVec2(-70.0f, 0.0f), format(STR_C("Checking %zu / %zu"), state.next, state.queue.size()).c_str()); + } + else + { + auto const progress{static_cast(state.run_next) / static_cast(std::max(1, state.runs.size()))}; + ImGui::ProgressBar(progress, ImVec2(-70.0f, 0.0f), format(STR_C("Terrain model %zu / %zu"), state.run_next, state.runs.size()).c_str()); + } ImGui::SameLine(); if (ImGui::SmallButton(STR_C("Cancel"))) + { state.queue.resize(state.next); + state.model_waiting = false; + } } - else if (ImGui::Button(STR_C("Check"))) + else { - joints_start(); + ImGui::PushStyleColor(ImGuiCol_Button, ImGui::ColorConvertU32ToFloat4(family_colour(2, 0.55f))); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImGui::ColorConvertU32ToFloat4(family_colour(2, 0.75f))); + if (ImGui::Button(STR_C("Check"), ImVec2(-1.0f, tall_button_height()))) + joints_start(); + ImGui::PopStyleColor(2); + item_tooltip("Finds the gaps between the ends of the tracks, the steps, the kinks and the jumps of the cant and of the grade"); } - if (ImGui::TreeNode(STR_C("Limits"))) + if (ImGui::TreeNode(STR_C("Thresholds"))) { - ImGui::PushItemWidth(100.0f); - if (state.scope == 0) - ImGui::InputDouble(STR_C("Around the camera (m)"), &state.reach, 0.0, 0.0, "%.0f"); - ImGui::InputDouble(STR_C("Gap up to (m)"), &state.gap, 0.0, 0.0, "%.2f"); - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", STR_C("A free end closer than this to the end of another path is a gap: the trains don't go across it.\nThe simulation joins the ends no more than 2 cm apart")); - ImGui::InputDouble(STR_C("Step (m)"), &state.step, 0.0, 0.0, "%.3f"); - ImGui::InputDouble(STR_C("Kink (deg)"), &state.angle, 0.0, 0.0, "%.2f"); - ImGui::InputDouble(STR_C("Cant jump (mm)"), &state.cant, 0.0, 0.0, "%.1f"); - ImGui::InputDouble(STR_C("Grade break (per mille)"), &state.grade, 0.0, 0.0, "%.1f"); - ImGui::Checkbox(STR_C("Free ends too"), &state.free_ends); - ImGui::PopItemWidth(); + if (begin_fields("##jointlimits", 0.55f)) + { + auto const limit = [](char const *Label, char const *Id, double &Value, char const *Format) { + field_row(Label); + ImGui::InputDouble(Id, &Value, 0.0, 0.0, Format); + }; + if (state.scope == 0) + limit("Around the camera (m)", "##jointreach", state.reach, "%.0f"); + limit("Gap up to (m)", "##jointgap", state.gap, "%.2f"); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("A free end closer than this to the end of another path is a gap: the trains don't go across it.\nThe simulation joins the ends no more than 2 cm apart")); + limit("Step (m)", "##jointstep", state.step, "%.3f"); + limit("Kink (deg)", "##jointkink", state.angle, "%.2f"); + limit("Cant jump (mm)", "##jointcant", state.cant, "%.1f"); + limit("Grade break (per mille)", "##jointgrade", state.grade, "%.1f"); + limit("Off the terrain model (m)", "##jointmodel", state.model, "%.2f"); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("The track lies higher or lower than the terrain model (NMT) says the ground is, by more than this.\nEach path is listed once, at its place the farthest off; bridges and tunnels are left out")); + ImGui::EndTable(); + } + toggle_chips("jointflags", {{STR_C("Free ends too"), &state.free_ends}, {STR_C("Against the terrain model"), &state.model_check}}); state.reach = std::clamp(state.reach, 50.0, 50000.0); state.gap = std::clamp(state.gap, 0.03, 20.0); state.step = std::max(0.001, state.step); state.angle = std::max(0.01, state.angle); state.cant = std::max(0.5, state.cant); state.grade = std::max(0.5, state.grade); - ImGui::TextDisabled("%s", STR_C("Change the limits, then Check again")); + state.model = std::max(0.05, state.model); + ImGui::TextDisabled("%s", STR_C("Change the thresholds, then Check again")); ImGui::TreePop(); } if (false == state.status.empty()) ImGui::TextWrapped("%s", state.status.c_str()); if (state.issues.empty()) return; - if (state.history != m_history.size()) + if (state.history != m_history.history_revision()) ImGui::TextColored(ImVec4(1.0f, 0.75f, 0.3f, 1.0f), "%s", STR_C("The scenery changed since the check")); int filter{state.filter + 1}; ImGui::SetNextItemWidth(150.0f); - auto const filters{std::string{STR_C("All")} + '\0' + STR_C("gap") + '\0' + STR_C("step") + '\0' + STR_C("kink") + '\0' + STR_C("cant jump") + '\0' + STR_C("grade break") + '\0' + STR_C("free end") + '\0' + '\0'}; + auto const filters{std::string{STR_C("All")} + '\0' + STR_C("gap") + '\0' + STR_C("step") + '\0' + STR_C("kink") + '\0' + STR_C("cant jump") + '\0' + STR_C("grade break") + '\0' + STR_C("off the terrain model") + '\0' + + STR_C("free end") + '\0' + '\0'}; if (ImGui::Combo("##jointfilter", &filter, filters.c_str())) state.filter = filter - 1; std::vector listed; @@ -446,7 +662,7 @@ void editor_mode::render_joints_body() if (state.filter >= 0 && static_cast(issue.type) != state.filter) continue; listed.push_back(i); - if (false == issue.fixed && issue.type != kind::open) + if (false == issue.fixed && issue.type != kind::open && issue.type != kind::model) fixable.push_back(i); } if (false == fixable.empty()) @@ -482,9 +698,9 @@ void editor_mode::render_joints_body() ImGui::NextColumn(); ImGui::TextUnformatted(issue.fixed ? STR_C("fixed") : value_text(issue).c_str()); ImGui::NextColumn(); - ImGui::TextUnformatted(name_of(issue.track).c_str()); + ImGui::TextUnformatted(label_of(issue.track).c_str()); ImGui::NextColumn(); - ImGui::TextUnformatted(name_of(issue.other).c_str()); + ImGui::TextUnformatted(label_of(issue.other).c_str()); ImGui::NextColumn(); } ImGui::Columns(1); @@ -492,24 +708,39 @@ void editor_mode::render_joints_body() if (chosen) { auto &issue{state.issues[state.selected]}; - ImGui::Text("%s %s: %s / %s", STR_C(kind_name(issue.type)), value_text(issue).c_str(), name_of(issue.track).c_str(), name_of(issue.other).c_str()); - if (false == issue.fixed && issue.type != kind::open && ImGui::Button(STR_C("Fix this one"))) + ImGui::Text("%s %s: %s / %s", STR_C(kind_name(issue.type)), value_text(issue).c_str(), label_of(issue.track).c_str(), label_of(issue.other).c_str()); + if (false == issue.fixed && issue.type != kind::open && issue.type != kind::model && ImGui::Button(STR_C("Fix this one"))) joints_fix({state.selected}); } } -void editor_mode::draw_joints_overlay() const +void joints_tool::draw_overlay() const { auto const &state{m_joints}; - if (false == state.open || state.issues.empty()) - return; screen_projection const projection; auto *drawlist{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())}; glm::dvec3 const camera{Global.pCamera.Pos}; + if (false == state.open) + { + for (auto const &issue : m_live.issues) + { + ImVec2 screen; + if ((false == Global.EditorOrtho && glm::distance(issue.position, camera) > kOverlayRange) || false == projection.project(issue.position, screen)) + continue; + auto const colour{kind_colour(issue.type)}; + drawlist->AddCircle(screen, 9.0f, colour, 16, 2.0f); + auto const text{std::string{STR_C(kind_name(issue.type))} + " " + value_text(issue)}; + drawlist->AddRectFilled(ImVec2(screen.x + 11.0f, screen.y - 9.0f), ImVec2(screen.x + 17.0f + ImGui::CalcTextSize(text.c_str()).x, screen.y + 9.0f), IM_COL32(0, 0, 0, 150), 3.0f); + drawlist->AddText(ImVec2(screen.x + 14.0f, screen.y - 7.0f), colour, text.c_str()); + } + return; + } + if (state.issues.empty()) + return; for (int i = 0; i < static_cast(state.issues.size()); ++i) { auto const &issue{state.issues[i]}; - if (issue.fixed || (state.filter >= 0 && static_cast(issue.type) != state.filter) || glm::distance(issue.position, camera) > kOverlayRange) + if (issue.fixed || (state.filter >= 0 && static_cast(issue.type) != state.filter) || (false == Global.EditorOrtho && glm::distance(issue.position, camera) > kOverlayRange)) continue; ImVec2 screen; if (false == projection.project(issue.position, screen)) @@ -520,3 +751,87 @@ void editor_mode::draw_joints_overlay() const drawlist->AddText(ImVec2(screen.x + 13.0f, screen.y - 7.0f), colour, text.c_str()); } } + +editor_selftest_result joints_tool::selftest(std::string const &Command, std::istringstream &Words) +{ + if (Command == "jointsmodel") + { + // the whole scenery against the terrain model, as the check of the panel does it, waiting for the model + static bool started{false}; + if (false == started) + { + double threshold{0.5}; + Words >> threshold; + m_joints.scope = 1; + m_joints.model_check = true; + m_joints.model = threshold; + joints_start(); + started = true; + } + update(); + if (m_joints.next < m_joints.queue.size() || m_joints.model_waiting) + return editor_selftest_result::again; + started = false; + std::size_t count{0}; + for (auto const &issue : m_joints.issues) + { + if (issue.type != joint_issue::kind::model) + continue; + if (count == 40) + break; + ++count; + WriteLog(format("SELFTEST jointsmodel: %+.2f m at %.1f %.1f, %s path %d", issue.value, issue.position.x, issue.position.z, issue.track != nullptr ? issue.track->name().c_str() : "-", issue.point.path)); + } + WriteLog("SELFTEST jointsmodel: " + m_joints.status); + return editor_selftest_result::handled; + } + if (Command == "jointslive") + { + live_update(); + std::string text; + for (auto const &issue : m_live.issues) + { + text += format(" [%s %s at %.1f %.1f, %s / %s", kind_name(issue.type), value_text(issue).c_str(), issue.position.x, issue.position.z, issue.track != nullptr ? issue.track->name().c_str() : "-", issue.other != nullptr ? issue.other->name().c_str() : "-"); + // which way the other end lies, across or up + if (issue.type == joint_issue::kind::gap && issue.other != nullptr) + { + auto const off{editor_track::point_position(*issue.other, issue.theirs) - issue.position}; + text += format(", off %+.3f %+.3f %+.3f", off.x, off.y, off.z); + } + text += "]"; + } + WriteLog(format("SELFTEST jointslive: %zu pending, %zu marked", m_live.pending.size(), m_live.issues.size()) + text); + return editor_selftest_result::handled; + } + if (Command == "joints") + { + std::vector points; + for (glm::dvec3 point{0.0}; Words >> point.x >> point.z;) + points.push_back(point); + auto const scope{m_joints.scope}; + auto const model{m_joints.model_check}; + m_joints.scope = 1; + m_joints.model_check = false; + joints_start(); + while (m_joints.next < m_joints.queue.size()) + update(); + m_joints.scope = scope; + m_joints.model_check = model; + char const *const kinds[]{"gap", "step", "kink", "cant jump", "grade break", "off the terrain model", "free end"}; + int around{0}; + for (auto const &issue : m_joints.issues) + { + if (false == points.empty() && issue.type == joint_issue::kind::open) + continue; + if (false == points.empty() && std::none_of(points.begin(), points.end(), [&](glm::dvec3 const &Point) { return geometry::plan_distance(Point, issue.position) < 5.0; })) + continue; + ++around; + auto const name = [](TTrack const *Track) { return Track == nullptr ? std::string{"-"} : Track->name() + (Track->eType == tt_Switch ? "(switch)" : ""); }; + auto const rise{issue.other != nullptr ? editor_track::point_position(*issue.other, issue.theirs).y - issue.position.y : 0.0}; + WriteLog(format("SELFTEST joints: %s %.3f at %.1f %.1f, %s / %s, rise %.3f", kinds[static_cast(issue.type)], issue.value, issue.position.x, issue.position.z, name(issue.track).c_str(), name(issue.other).c_str(), rise)); + } + WriteLog(format("SELFTEST joints: %d issues around the points, %zu in all", around, m_joints.issues.size())); + return editor_selftest_result::handled; + } + return editor_selftest_result::unhandled; +} diff --git a/application/editormodejoints.h b/application/editormodejoints.h new file mode 100644 index 000000000..01617d889 --- /dev/null +++ b/application/editormodejoints.h @@ -0,0 +1,100 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include "application/editortool.h" + +#include +#include +#include +#include +#include + +class joints_tool final : public editor_tool +{ + public: + // joint of the paths found wrong by the joints check + struct joint_issue + { + enum class kind { gap, step, kink, cant, grade, model, open }; + kind type{kind::gap}; + TTrack *track{nullptr}; + editor_track::point_ref point; + TTrack *other{nullptr}; + editor_track::point_ref theirs; + glm::dvec3 position{0.0}; + double value{0.0}; // m, deg, mm, per mille; m of the track over the terrain model + bool fixed{false}; + }; + joints_tool(editor_selection &Selection, editor_view &View, editor_history &History, editor_ground &Ground) : m_selection{Selection}, m_view{View}, m_history{History}, m_ground{Ground} {} + void update() override; + void draw_overlay() const override; + void render_options() override; + editor_selftest_result selftest(std::string const &Command, std::istringstream &Words) override; + void set_open(bool const Open) { m_joints.open = Open; } + // the tracks just changed, checked at their joints once the change is over + void tracks_committed(std::vector const &Tracks); + double kink_angle() const { return m_joints.angle; } + + private: + editor_selection &m_selection; + editor_view &m_view; + editor_history &m_history; + editor_ground &m_ground; + // joints of the paths: ends which almost meet, steps, kinks, jumps of the cant and of the grade + struct joints_state + { + bool open{false}; + int scope{0}; // 0: around the camera, 1: the whole scenery + double reach{2000.0}; + double gap{1.0}; // m, free ends closer than this to another end + double step{0.005}; // m + double angle{0.2}; // deg + double cant{5.0}; // mm + double grade{10.0}; // per mille + double model{0.5}; // m, the track over or under the terrain model (NMT) + bool free_ends{false}; + bool model_check{true}; + std::vector queue; + std::size_t next{0}; + // the places of the tracks compared with the terrain model, in runs of one path each, once the model under them is in + std::vector places; + std::vector> runs; + std::size_t run_next{0}; + bool model_waiting{false}; + bool model_asked{false}; + double model_polled{0.0}; + bool model_unplaced{false}; + std::vector issues; + int filter{-1}; + int selected{-1}; + std::size_t history{0}; + std::string status; + }; + joints_state m_joints; + using end_key = std::tuple; + // pairs of the ends already looked at in the check under way + std::set> m_reported; + // the joints of the tracks changed last, marked while the panel is closed + struct live_state + { + std::set pending; + std::vector issues; + }; + live_state m_live; + void live_update(); + void joints_start(); + void joints_check(TTrack &Track, std::vector &Issues, std::set> &Seen, bool const Open) const; + // the paths lying off the terrain model by more than the threshold. returns: false while the model under them is coming + bool joints_model(); + void joints_focus(int const Index); + bool joint_fix(joint_issue &Issue, std::vector> &States, std::vector &Changed); + void joints_fix(std::vector const &Indices); +}; diff --git a/application/editormodekm.cpp b/application/editormodekm.cpp new file mode 100644 index 000000000..2135d4afe --- /dev/null +++ b/application/editormodekm.cpp @@ -0,0 +1,1026 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "application/editormodekm.h" +#include "application/editorgestures.h" +#include "application/editormodeshared.h" +#include "application/editorprojection.h" +#include "editor/editorFormat.hpp" +#include "editor/editorGeometry.hpp" +#include "editor/editorTrack.hpp" + +#include "simulation/simulation.h" +#include "utilities/Globals.h" +#include "utilities/Logs.h" +#include "utilities/utilities.h" +#include "world/Track.h" + +#include "imgui/imgui.h" +#include "utilities/translation.h" +#include +#include +#include +#include +#include +#include + +namespace +{ + +using geometry::plan_distance; +using geometry::plan_of; + +double constexpr kOverlayRange{3000.0}; +double constexpr kTickRange{1500.0}; // m, of the hectometres shown in the scenery +double constexpr kLabelRange{700.0}; // m, of the km written there, farther ones crowd the horizon +double constexpr kDigitRange{250.0}; // m, of the hectometres written there +double constexpr kRailHead{0.18}; // m, above the axis of a path +double constexpr kPickReach{15.0}; // m from a point of the km a click on a track takes it +double constexpr kReadoutReach{30.0}; // m from the axis of a line its km is shown by the mouse +double constexpr kPostReach{60000.0}; // m along the line each way, of the posts read +double constexpr kPostCorridor{15.0}; // m from the track, posts farther away belong to another line +double constexpr kPostTolerance{10.0}; // m, of the distance between two posts against their numbers +double constexpr kCurve{10000.0}; // m, of the radius a jump of the km is on a curve under +double constexpr kStation{300.0}; // m from a switch a jump of the km is at a station + +ImU32 constexpr kAxis{IM_COL32(110, 200, 255, 220)}; +ImU32 constexpr kGuessed{IM_COL32(110, 200, 255, 90)}; +ImU32 constexpr kTick{IM_COL32(235, 240, 250, 230)}; +ImU32 constexpr kKm{IM_COL32(255, 215, 90, 255)}; +ImU32 constexpr kJump{IM_COL32(255, 95, 215, 255)}; +ImU32 constexpr kMark{IM_COL32(95, 220, 140, 255)}; +ImU32 constexpr kAstray{IM_COL32(240, 90, 80, 255)}; + +// the digits after the rotation make the number of a hectometre post, the last one the hectometre +bool hectometres_of(std::vector const &Values, int &Hectometres) +{ + if (Values.size() < 6) + return false; + Hectometres = 0; + for (std::size_t i = 5; i < Values.size(); ++i) + { + double digit; + if (false == numeric(Values[i], digit) || digit < 0.0 || digit > 9.0) + return false; + Hectometres = Hectometres * 10 + static_cast(digit); + } + return true; +} + +// chainage of the point of the samples nearest to the point, and how far from them it is +double project(std::vector const &Samples, glm::dvec3 const &Point, double &Distance) +{ + Distance = std::numeric_limits::max(); + double chainage{0.0}; + auto const point{plan_of(Point)}; + for (std::size_t i = 1; i < Samples.size(); ++i) + { + auto const a{plan_of(Samples[i - 1].position)}; + auto const ab{plan_of(Samples[i].position) - a}; + auto const length2{glm::dot(ab, ab)}; + auto const t{length2 > 1e-12 ? std::clamp(glm::dot(point - a, ab) / length2, 0.0, 1.0) : 0.0}; + if (auto const distance{glm::length(point - (a + ab * t))}; distance < Distance) + { + Distance = distance; + chainage = Samples[i - 1].chainage + (Samples[i].chainage - Samples[i - 1].chainage) * t; + } + } + return chainage; +} + +std::size_t sample_at(std::vector const &Samples, double const Chainage) +{ + auto const found{std::lower_bound(Samples.begin(), Samples.end(), Chainage, [](editor_track::route_sample const &Sample, double const Value) { return Sample.chainage < Value; })}; + return std::min(static_cast(found - Samples.begin()), Samples.size() - 1); +} + +// the number of a line: blanks taken out +std::string line_of(std::string const &Text) +{ + std::string result; + for (auto const c : Text) + if (false == std::isspace(static_cast(c))) + result += c; + return result; +} + +// a km typed as PKP PLK write it, 100,234, or with a point +bool km_of(char const *Text, double &Km) +{ + std::string text{Text}; + std::replace(text.begin(), text.end(), ',', '.'); + char *end{nullptr}; + auto const value{std::strtod(text.c_str(), &end)}; + if (end == text.c_str() || false == std::isfinite(value)) + return false; + Km = value; + return true; +} + +std::string mark_text(kilometrage::mark const &Mark) +{ + return Mark.beyond.has_value() ? kilometrage::text(Mark.km) + " = " + kilometrage::text(*Mark.beyond) : kilometrage::text(Mark.km); +} + +void draw_label(ImDrawList *List, ImVec2 const At, ImU32 const Ground, ImU32 const Colour, std::string const &Text) +{ + auto const size{ImGui::CalcTextSize(Text.c_str())}; + List->AddRectFilled(ImVec2(At.x - size.x * 0.5f - 4.0f, At.y - size.y - 4.0f), ImVec2(At.x + size.x * 0.5f + 4.0f, At.y), Ground, 3.0f); + List->AddText(ImVec2(At.x - size.x * 0.5f, At.y - size.y - 2.0f), Colour, Text.c_str()); +} + +void draw_arrow(screen_projection const &Projection, ImDrawList *List, glm::dvec3 const &From, glm::dvec2 const &Way, double const Length, ImU32 const Colour) +{ + glm::dvec3 const along{Way.x, 0.0, Way.y}; + glm::dvec3 const across{-Way.y, 0.0, Way.x}; + auto const tip{From + along * Length}; + Projection.line(List, From, tip, Colour, 3.0f); + Projection.line(List, tip, tip - along * (Length * 0.3) + across * (Length * 0.15), Colour, 3.0f); + Projection.line(List, tip, tip - along * (Length * 0.3) - across * (Length * 0.15), Colour, 3.0f); +} + +} // namespace + +void km_tool::refresh() +{ + m_drawn.clear(); + for (auto const &line : kilometrage::lines()) + { + auto const *axis{kilometrage::axis_of(line)}; + if (axis == nullptr || axis->points.size() < 2) + continue; + drawn entry; + entry.line = line; + entry.points = axis->points; + auto const low{axis->anchors.front().chainage - 1.0}; + auto const high{axis->anchors.back().chainage + 1.0}; + for (auto const chainage : axis->chainage) + entry.guessed.push_back(chainage < low || chainage > high ? 1 : 0); + for (auto const &anchor : axis->anchors) + if (std::abs(anchor.after - anchor.before) >= 1e-6) + { + auto const way{kilometrage::direction_on(*axis, anchor.chainage)}; + entry.ticks.push_back({kilometrage::point_on(*axis, anchor.chainage), {-way.y, 0.0, way.x}, 0, true}); + } + for (auto const &hectometre : kilometrage::hectometres(*axis)) + entry.ticks.push_back({hectometre.at, {-hectometre.rising.y, 0.0, hectometre.rising.x}, hectometre.number, false}); + m_drawn.push_back(std::move(entry)); + // the shorter track where the tracks run apart + for (auto const &side : axis->sides) + { + drawn apart; + apart.line = line; + apart.points = side.points; + apart.guessed.assign(side.points.size(), 0); + m_drawn.push_back(std::move(apart)); + } + } + m_revision = kilometrage::revision(); + m_drawn_once = true; +} + +void km_tool::update() +{ + if (false == m_open) + return; + auto const &marks{kilometrage::marks()}; + // after an undo the point edited may be gone + if (m_edited >= 0 && (m_edited >= static_cast(marks.size()) || false == m_pick.has_value() || plan_distance(marks[m_edited].point, m_pick->point) > 0.5)) + m_edited = -1; + if (false == m_drawn_once || kilometrage::revision() != m_revision) + refresh(); +} + +void km_tool::forget(scene::basic_node const *Node) +{ + if (m_pick.has_value() && m_pick->track == Node) + m_pick->track = nullptr; +} + +glm::dvec2 km_tool::rising() const +{ + if (false == m_pick.has_value()) + return {0.0, 1.0}; + return m_pick->along * (m_against ? -1.0 : 1.0); +} + +std::string km_tool::jump_warning(glm::dvec3 const &Point) const +{ + auto *track{kilometrage::track_near(Point, 6.0)}; + if (track == nullptr) + return {}; + auto route{editor_track::run_route(*track, kStation + 50.0)}; + auto const samples{editor_track::sample_route(route, 2.0)}; + if (samples.size() < 2) + return {}; + double gap{0.0}; + auto const at{project(samples, Point, gap)}; + bool curve{false}; + bool station{false}; + for (auto const &sample : samples) + { + auto const apart{std::abs(sample.chainage - at)}; + if (apart <= 30.0 && std::abs(sample.curvature) > 1.0 / kCurve) + curve = true; + if (apart <= kStation && sample.span < route.spans.size() && route.spans[sample.span].track->eType != tt_Normal) + station = true; + } + if (curve && station) + return STR("Id-1 § 19: the km shouldn't jump on a curve nor at a station, move the jump to a straight on the open line"); + if (curve) + return STR("Id-1 § 19: the km shouldn't jump on a curve, move the jump to a straight"); + if (station) + return STR("Id-1 § 19: the km shouldn't jump at a station, move the jump out to the open line"); + return {}; +} + +void km_tool::pick(TTrack &Track, glm::dvec3 const &Point) +{ + auto const t{editor_track::nearest_parameter(Track, Point)}; + picked entry; + entry.track = &Track; + entry.point = editor_track::point_at(Track, t); + auto const ahead{plan_of(editor_track::point_at(Track, std::min(1.0, t + 0.01)) - editor_track::point_at(Track, std::max(0.0, t - 0.01)))}; + entry.along = glm::length(ahead) > 1e-9 ? glm::normalize(ahead) : glm::dvec2{0.0, 1.0}; + entry.path = kilometrage::path_near(Track, Point, entry.on); + m_status.clear(); + m_route_status.clear(); + m_edited = -1; + auto const &marks{kilometrage::marks()}; + auto nearest{kPickReach}; + for (std::size_t index = 0; index < marks.size(); ++index) + if (auto const distance{plan_distance(marks[index].point, entry.point)}; distance < nearest) + { + nearest = distance; + m_edited = static_cast(index); + } + if (m_edited >= 0) + { + auto const &mark{marks[m_edited]}; + entry.point = mark.point; + m_line = mark.line; + m_km = mark.km; + m_jump = mark.beyond.has_value(); + m_beyond = mark.beyond.value_or(mark.km); + m_against = glm::dot(mark.way, entry.along) < 0.0; + } + else + { + // the line the point lies on, and its km there + if (auto const line{kilometrage::line_at(entry.point, kReadoutReach)}; false == line.empty()) + m_line = line; + double km{0.0}; + if (false == m_line.empty() && kilometrage::km_at(m_line, entry.point, km, kReadoutReach)) + { + m_km = std::round(km * 1000.0) / 1000.0; + auto const *axis{kilometrage::axis_of(m_line)}; + double gap{0.0}; + auto const along{kilometrage::chainage_at(*axis, entry.point, gap)}; + m_against = glm::dot(kilometrage::direction_on(*axis, along) * static_cast(axis->growth), entry.along) < 0.0; + } + m_jump = false; + m_beyond = m_km; + } + m_pick = entry; +} + +std::string km_tool::readout(glm::dvec3 const &Point) const +{ + std::string result; + for (auto const &line : kilometrage::lines()) + { + double km{0.0}; + if (false == kilometrage::km_at(line, Point, km, kReadoutReach)) + continue; + if (false == result.empty()) + result += '\n'; + result += format(STR_C("line %s: km %s"), line.c_str(), kilometrage::text(km).c_str()); + } + return result; +} + +void km_tool::put() +{ + m_status.clear(); + if (false == m_pick.has_value()) + return; + auto const line{line_of(m_line)}; + if (line.empty()) + { + m_status = STR("Give the number of the line first"); + return; + } + if (m_jump && std::abs(m_beyond - m_km) < 0.0005) + { + m_status = STR("A jump needs another km on from the point"); + return; + } + kilometrage::mark entry; + entry.line = line; + entry.point = m_pick->point; + entry.way = rising(); + entry.km = m_km; + if (m_jump) + entry.beyond = m_beyond; + if (m_edited >= 0) + kilometrage::change(static_cast(m_edited), entry); + else + { + kilometrage::put(entry); + m_edited = static_cast(kilometrage::marks().size()) - 1; + } + m_line = line; + m_history.push_kilometrage_snapshot(); + m_status = format(STR_C("Line %s: km %s at the point"), line.c_str(), mark_text(entry).c_str()); +} + +void km_tool::remove() +{ + m_status.clear(); + if (m_edited < 0) + return; + kilometrage::remove(static_cast(m_edited)); + m_edited = -1; + m_history.push_kilometrage_snapshot(); + m_status = STR("The point of the km removed"); +} + +void km_tool::show(std::size_t const Index) +{ + auto const &marks{kilometrage::marks()}; + if (Index >= marks.size()) + return; + auto const point{marks[Index].point}; + if (auto *track{kilometrage::track_near(point, 6.0)}; track != nullptr) + pick(*track, point); + m_view.fly_to(point, glm::normalize(glm::dvec3{-1.0, -0.8, -1.0}), 40.0); +} + +void km_tool::show_via(std::size_t const Index) +{ + auto const &vias{kilometrage::vias()}; + if (Index >= vias.size()) + return; + auto const point{vias[Index].point}; + auto const line{vias[Index].line}; + int path{0}; + if (auto *track{kilometrage::track_near(point, 6.0, path)}; track != nullptr) + { + pick(*track, point); + m_line = line; + } + m_view.fly_to(point, glm::normalize(glm::dvec3{-1.0, -0.8, -1.0}), 40.0); +} + +int km_tool::via_here() const +{ + if (false == m_pick.has_value() || m_pick->track == nullptr) + return -1; + auto const &vias{kilometrage::vias()}; + for (std::size_t index = 0; index < vias.size(); ++index) + { + if (vias[index].line != m_line) + continue; + int path{0}; + if (kilometrage::track_near(vias[index].point, 6.0, path) == m_pick->track && path == m_pick->path) + return static_cast(index); + } + return -1; +} + +void km_tool::lead_along() +{ + m_route_status.clear(); + if (false == m_pick.has_value() || m_pick->track == nullptr) + return; + auto const line{line_of(m_line)}; + if (line.empty()) + { + m_route_status = STR("Give the number of the line first"); + return; + } + auto const astray_of = [&]() { + auto const *axis{kilometrage::axis_of(line)}; + return axis != nullptr ? axis->astray.size() : kilometrage::marks().size(); + }; + auto const before{kilometrage::current()}; + auto const astray{astray_of()}; + kilometrage::via entry; + entry.line = line; + entry.point = m_pick->on; + kilometrage::put(entry); + auto const *axis{kilometrage::axis_of(line)}; + if (axis == nullptr || false == axis->runs_along(m_pick->track, m_pick->path)) + { + kilometrage::restore(before); + m_route_status = STR("The line can't run along this track: no way leads from it onto the line"); + return; + } + m_line = line; + m_history.push_kilometrage_snapshot(); + m_route_status = format(STR_C("Line %s runs along this track now"), line.c_str()); + if (auto const lost{astray_of()}; lost > astray) + m_route_status += "\n" + format(STR_P("%zu point of the km is off the line now: the track leads it away from it", "%zu points of the km are off the line now: the track leads it away from them", lost - astray), lost - astray); +} + +void km_tool::drop_via() +{ + m_route_status.clear(); + auto const index{via_here()}; + if (index < 0) + return; + kilometrage::remove_via(static_cast(index)); + m_history.push_kilometrage_snapshot(); + m_route_status = format(STR_C("Line %s runs along the straight paths of the switches here again"), m_line.c_str()); +} + +void km_tool::read_posts() +{ + m_status.clear(); + auto const line{line_of(m_line)}; + if (false == m_pick.has_value() || m_pick->track == nullptr) + { + m_status = STR("Click a track of the line first"); + return; + } + if (line.empty()) + { + m_status = STR("Give the number of the line first"); + return; + } + auto route{editor_track::run_route(*m_pick->track, kPostReach)}; + auto const samples{editor_track::sample_route(route, 2.0)}; + if (samples.size() < 2) + { + m_status = STR("No line through this track"); + return; + } + auto const length{samples.back().chainage}; + struct post + { + double chainage{0.0}; + int hectometres{0}; + }; + std::vector posts; + for (auto const &standing : m_templates.standing_templates([](std::string const &File) { return File.find("hekto") != std::string::npos; })) + { + post entry; + if (false == hectometres_of(standing.values, entry.hectometres)) + continue; + double distance{0.0}; + entry.chainage = project(samples, standing.location, distance); + if (distance > kPostCorridor || entry.chainage <= 0.0 || entry.chainage >= length) + continue; + posts.push_back(entry); + } + if (posts.size() < 2) + { + m_status = STR("Fewer than two hectometre posts stand along the line, nothing to read"); + return; + } + std::sort(posts.begin(), posts.end(), [](post const &A, post const &B) { return A.chainage < B.chainage; }); + // runs of posts numbered by the distance between them, a post of the same number by the other track taken once + auto const fits = [](post const &From, post const &To, int const Sign) { + auto const counted{(To.hectometres - From.hectometres) * 100.0}; + auto const apart{To.chainage - From.chainage}; + return counted != 0.0 && (Sign == 0 || (counted > 0.0 ? 1 : -1) == Sign) && std::abs(std::abs(counted) - apart) <= std::max(kPostTolerance, apart * 0.02); + }; + auto const sign_of = [](std::vector const &Run) { return Run.size() < 2 ? 0 : Run.back().hectometres > Run.front().hectometres ? 1 : -1; }; + std::vector> runs; + std::size_t twins{0}; + for (auto const &entry : posts) + { + if (false == runs.empty()) + { + auto &run{runs.back()}; + if (entry.hectometres == run.back().hectometres && entry.chainage - run.back().chainage < kPostTolerance * 3.0) + { + ++twins; + continue; + } + if (fits(run.back(), entry, sign_of(run))) + { + run.push_back(entry); + continue; + } + } + runs.push_back({entry}); + } + // a post alone between the runs is one out of place + std::size_t stray{0}; + std::vector> kept; + for (auto &run : runs) + { + if (run.size() < 2) + { + ++stray; + continue; + } + if (false == kept.empty() && fits(kept.back().back(), run.front(), sign_of(kept.back())) && sign_of(kept.back()) == sign_of(run)) + kept.back().insert(kept.back().end(), run.begin(), run.end()); + else + kept.push_back(std::move(run)); + } + std::size_t rising{0}; + std::size_t falling{0}; + for (auto const &run : kept) + (sign_of(run) > 0 ? rising : falling) += run.size(); + auto const growth{rising >= falling ? 1 : -1}; + kept.erase(std::remove_if(kept.begin(), kept.end(), [&](std::vector const &Run) { + if (sign_of(Run) == growth) + return false; + stray += Run.size(); + return true; + }), kept.end()); + if (kept.empty()) + { + m_status = STR("The numbers of the posts don't go by 100 m anywhere along the line, nothing read"); + return; + } + auto const mark_at = [&](double const Chainage, double const Km, std::optional const Beyond) { + kilometrage::mark entry; + entry.line = line; + entry.point = editor_track::sampled_position(samples, Chainage); + entry.way = samples[sample_at(samples, Chainage)].direction * static_cast(growth); + entry.km = Km; + entry.beyond = Beyond; + return entry; + }; + std::vector made; + std::size_t jumps{0}; + std::size_t misplaced{0}; + for (std::size_t r = 0; r < kept.size(); ++r) + { + auto const &run{kept[r]}; + auto const &first{run.front()}; + auto const &last{run.back()}; + // the jump to the next run at the post it starts the irregular hectometre at, along the rising km + auto const jump_before{r > 0 && growth > 0}; + auto const jump_after{r + 1 < kept.size() && growth < 0}; + if (jump_before) + { + auto const &previous{kept[r - 1].back()}; + made.push_back(mark_at(first.chainage, previous.hectometres / 10.0 + (first.chainage - previous.chainage) / 1000.0, first.hectometres / 10.0)); + } + else + made.push_back(mark_at(first.chainage, first.hectometres / 10.0, std::nullopt)); + if (jump_after) + { + auto const &next{kept[r + 1].front()}; + made.push_back(mark_at(last.chainage, next.hectometres / 10.0 + (next.chainage - last.chainage) / 1000.0, last.hectometres / 10.0)); + } + else + made.push_back(mark_at(last.chainage, last.hectometres / 10.0, std::nullopt)); + if (jump_before || jump_after) + { + ++jumps; + if (false == jump_warning((jump_before ? made[made.size() - 2] : made.back()).point).empty()) + ++misplaced; + } + } + // the points of the line along the stretch read give way to the ones read + auto const &standing{kilometrage::marks()}; + for (auto index{static_cast(standing.size()) - 1}; index >= 0; --index) + { + if (standing[index].line != line) + continue; + double gap{0.0}; + project(samples, standing[index].point, gap); + if (gap <= kPostCorridor) + kilometrage::remove(static_cast(index)); + } + for (auto &entry : made) + kilometrage::put(std::move(entry)); + m_line = line; + m_edited = -1; + m_history.push_kilometrage_snapshot(); + m_status = format(STR_C("%zu posts read: %zu points of the km, %zu jumps"), posts.size() - twins, made.size(), jumps); + if (stray > 0) + m_status += "\n" + format(STR_P("%zu post doesn't fit its neighbours and was left out", "%zu posts don't fit their neighbours and were left out", stray), stray); + if (misplaced > 0) + m_status += "\n" + format(STR_P("%zu jump lies on a curve or at a station, Id-1 § 19 wants none there", "%zu jumps lie on a curve or at a station, Id-1 § 19 wants none there", misplaced), misplaced); +} + +void km_tool::render_options() +{ + ImGui::TextWrapped("%s", STR_C("One point of a known km is enough: the hectometre posts, the stations and the block signals of the line count from it")); + ImGui::TextDisabled("%s", STR_C("The km of a railway line: the points where the km is known, from a post or a document, and where it jumps. The km of the rest go from them along the axis of the line: between the tracks of a double-track one, along the longer track where the tracks run on formations of their own, the shorter one getting an irregular hectometre")); + ImGui::Spacing(); + gesture_rows({{"LMB on a track", "a point of the km there, or the one standing by it"}}); + auto const &marks{kilometrage::marks()}; + auto const lines{kilometrage::lines()}; + std::size_t jumps{0}; + for (auto const &mark : marks) + if (mark.beyond.has_value()) + ++jumps; + metric_tiles({{format("%zu", lines.size()), STR_C("lines"), kAxis}, {format("%zu", marks.size()), STR_C("points"), kMark}, {format("%zu", jumps), STR_C("jumps"), kJump}}); + + step_heading(1, STR_C("A point of the km")); + if (false == m_pick.has_value()) + ImGui::TextDisabled("%s", STR_C("Click a track where the km is known: by a post, a station or a bridge")); + else + { + if (begin_fields("##kmpoint")) + { + field_row("Line"); + std::array buffer{}; + m_line.copy(buffer.data(), buffer.size() - 1); + if (ImGui::InputTextWithHint("##kmline", "91", buffer.data(), buffer.size())) + m_line = line_of(buffer.data()); + item_tooltip("The number of the railway line, as 91: a scenery can hold several lines, each with its own km"); + auto const km_field = [&](char const *Label, char const *Id, double &Value) { + field_row(Label); + std::array text{}; + kilometrage::text(Value).copy(text.data(), text.size() - 1); + if (ImGui::InputText(Id, text.data(), text.size())) + km_of(text.data(), Value); + }; + km_field("Km", "##kmkm", m_km); + item_tooltip("The km of the point, as PKP PLK write it: 100,234 is km 100 and 234 m. At a jump: the km the point is reached at, coming along the rising km"); + field_row("Jump"); + ImGui::Checkbox("##kmjump", &m_jump); + item_tooltip("The km jumps at the point: a line built anew, shortened or lengthened keeps the km of the rest. The irregular hectometre is " + "marked by a black stripe under the digit of the post (Id-1 § 19)"); + if (m_jump) + { + km_field("Km on", "##kmbeyond", m_beyond); + item_tooltip("The km on from the point, along the rising km"); + } + ImGui::EndTable(); + } + auto const *axis{m_line.empty() ? nullptr : kilometrage::axis_of(m_line)}; + auto const fixed{axis != nullptr && axis->anchors.size() > 1 && std::abs(axis->anchors.back().before - axis->anchors.front().before) > 1e-6}; + if (false == fixed) + { + int way{m_against ? 1 : 0}; + if (segmented("##kmway", way, {{0, STR_C("Rise this way"), "The km rise the way the arrow at the point shows"}, {1, STR_C("Rise the other way"), "The km rise against the arrow"}})) + m_against = way == 1; + } + if (m_jump) + if (auto const warning{jump_warning(m_pick->point)}; false == warning.empty()) + ImGui::TextColored(ImVec4(1.0f, 0.75f, 0.3f, 1.0f), "%s", warning.c_str()); + if (main_button(m_edited >= 0 ? STR_C("Change the point") : STR_C("Put the point of the km"), ImVec2(-1.0f, tall_button_height()))) + put(); + item_tooltip("The point goes to the file of the scenery with the track, the simulation skips it. One step of undo"); + if (m_edited >= 0) + { + if (ImGui::Button(STR_C("Remove the point"), ImVec2(-1.0f, 0.0f))) + remove(); + item_tooltip("One step of undo"); + } + } + + step_heading(2, STR_C("The way through a station")); + auto const *line_axis{m_line.empty() ? nullptr : kilometrage::axis_of(m_line)}; + if (false == m_pick.has_value() || m_pick->track == nullptr) + ImGui::TextDisabled("%s", STR_C("Through a station the km run along the straight paths of the switches. Click a track of the station to lead them along it instead")); + else if (line_axis == nullptr) + ImGui::TextDisabled("%s", STR_C("Put a point of the km of the line first")); + else if (auto const via{via_here()}; via >= 0) + { + if (std::find(line_axis->blocked.begin(), line_axis->blocked.end(), static_cast(via)) != line_axis->blocked.end()) + ImGui::TextColored(ImVec4(1.0f, 0.45f, 0.4f, 1.0f), "%s", STR_C("The line doesn't run along this track: another track chosen leads it elsewhere")); + else + ImGui::TextUnformatted(format(STR_C("Line %s runs along this track, as chosen"), m_line.c_str()).c_str()); + if (ImGui::Button(STR_C("Back onto the straight paths"), ImVec2(-1.0f, 0.0f))) + drop_via(); + item_tooltip("The track chosen is forgotten, the line runs along the straight paths of the switches here again. One step of undo"); + } + else if (line_axis->runs_along(m_pick->track, m_pick->path)) + ImGui::TextDisabled("%s", format(STR_C("Line %s runs along this track"), m_line.c_str()).c_str()); + else + { + ImGui::TextDisabled("%s", format(STR_C("Line %s doesn't run along this track"), m_line.c_str()).c_str()); + if (ImGui::Button(STR_C("Lead the km along this track"), ImVec2(-1.0f, 0.0f))) + lead_along(); + item_tooltip("The line runs along the track clicked, along the path of the switch clicked, and on along the straight paths of the switches " + "until it meets its tracks again; where it doesn't, as at a junction, it goes on that way. One step of undo"); + } + if (false == m_route_status.empty()) + ImGui::TextColored(ImVec4(1.0f, 0.75f, 0.3f, 1.0f), "%s", m_route_status.c_str()); + + step_heading(3, STR_C("From the posts")); + if (ImGui::Button(STR_C("Read the km from the posts"), ImVec2(-1.0f, 0.0f))) + read_posts(); + item_tooltip("Reads the hectometre posts standing along the line through the track clicked: a point of the km at the first and the last " + "post of each run numbered by 100 m, a jump where two runs meet. The points of the line along it before give way. One step of undo"); + if (false == m_status.empty()) + ImGui::TextColored(ImVec4(1.0f, 0.75f, 0.3f, 1.0f), "%s", m_status.c_str()); + + step_heading(4, STR_C("The points of the lines")); + if (lines.empty()) + { + ImGui::TextDisabled("%s", STR_C("None yet")); + return; + } + for (auto const &line : lines) + { + auto const *axis{kilometrage::axis_of(line)}; + auto const count{static_cast(std::count_if(marks.begin(), marks.end(), [&](kilometrage::mark const &Mark) { return Mark.line == line; }))}; + if (false == ImGui::CollapsingHeader(format("%s %s (%zu)###kmline%s", STR_C("Line"), line.c_str(), count, line.c_str()).c_str(), ImGuiTreeNodeFlags_DefaultOpen)) + continue; + if (axis == nullptr) + { + ImGui::TextColored(ImVec4(1.0f, 0.45f, 0.4f, 1.0f), "%s", STR_C("No track by the points of the line")); + continue; + } + ImGui::TextDisabled("%s", format(STR_C("%.1f km of the axis, %s"), axis->length() / 1000.0, axis->between ? STR_C("between the tracks") : STR_C("along the track")).c_str()); + if (false == axis->sides.empty()) + { + ImGui::TextDisabled("%s", format(STR_P("%zu stretch with the tracks on formations of their own", "%zu stretches with the tracks on formations of their own", axis->sides.size()), axis->sides.size()).c_str()); + item_tooltip("Where the tracks part more than 15 m and come together again, the km run along the longer one, the shorter one goes by " + "its own length and its last hectometre before they meet takes up the difference, as PKP GK-1 gives it (6.1.12)"); + } + auto const &vias{kilometrage::vias()}; + for (std::size_t index = 0; index < vias.size(); ++index) + { + if (vias[index].line != line) + continue; + auto const blocked{std::find(axis->blocked.begin(), axis->blocked.end(), index) != axis->blocked.end()}; + double km{0.0}; + auto const label{kilometrage::km_at(line, vias[index].point, km, kReadoutReach) ? format(STR_C("Along the track chosen by km %s"), kilometrage::text(km).c_str()) : std::string{STR_C("Along the track chosen")}}; + if (blocked) + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 0.45f, 0.4f, 1.0f)); + if (ImGui::Selectable((label + "##kmvia" + std::to_string(index)).c_str(), false)) + show_via(index); + if (blocked) + ImGui::PopStyleColor(); + item_tooltip(blocked ? "The line doesn't run along this track: another track chosen leads it elsewhere" : "Through the station the line runs along this track, not along the straight paths of the switches"); + } + auto const rows{axis->anchors.size() + axis->astray.size()}; + if (false == ImGui::BeginTable(("##kmmarks" + line).c_str(), 4, ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_ScrollY, ImVec2(0.0f, std::min(260.0f, ImGui::GetTextLineHeightWithSpacing() * (rows + 1.5f))))) + continue; + ImGui::TableSetupScrollFreeze(0, 1); + ImGui::TableSetupColumn(STR_C("Km"), ImGuiTableColumnFlags_WidthStretch, 0.4f); + ImGui::TableSetupColumn(STR_C("In the scenery"), ImGuiTableColumnFlags_WidthStretch, 0.22f); + ImGui::TableSetupColumn(STR_C("By the km"), ImGuiTableColumnFlags_WidthStretch, 0.22f); + ImGui::TableSetupColumn(STR_C("Off by"), ImGuiTableColumnFlags_WidthStretch, 0.16f); + ImGui::TableHeadersRow(); + auto const growth{axis->growth}; + for (std::size_t i = 0; i < axis->anchors.size(); ++i) + { + auto const &anchor{axis->anchors[i]}; + auto const &mark{marks[anchor.mark]}; + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + if (ImGui::Selectable((mark_text(mark) + "##kmmark" + std::to_string(anchor.mark)).c_str(), static_cast(anchor.mark) == m_edited, ImGuiSelectableFlags_SpanAllColumns)) + show(anchor.mark); + if (i == 0) + continue; + auto const &previous{axis->anchors[i - 1]}; + auto const scenery{anchor.chainage - previous.chainage}; + auto const counted{std::abs((growth > 0 ? anchor.before - previous.after : previous.before - anchor.after) * 1000.0)}; + ImGui::TableNextColumn(); + ImGui::Text("%.0f m", scenery); + ImGui::TableNextColumn(); + ImGui::Text("%.0f m", counted); + ImGui::TableNextColumn(); + auto off{scenery > 1.0 ? (scenery - counted) / scenery * 100.0 : 0.0}; + if (std::abs(off) < 0.05) + off = 0.0; + if (std::abs(off) > 2.0) + ImGui::TextColored(ImVec4(1.0f, 0.75f, 0.3f, 1.0f), "%+.1f%%", off); + else + ImGui::Text("%+.1f%%", off); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("How much longer the stretch is in the scenery than by the km: the km between the points are stretched to it evenly")); + } + for (auto const index : axis->astray) + { + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 0.45f, 0.4f, 1.0f)); + if (ImGui::Selectable((mark_text(marks[index]) + "##kmmark" + std::to_string(index)).c_str(), static_cast(index) == m_edited, ImGuiSelectableFlags_SpanAllColumns)) + show(index); + ImGui::PopStyleColor(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("The point is away from the axis of the line the other points make: the main paths of the switches don't lead to it")); + } + ImGui::EndTable(); + } +} + +void km_tool::draw_overlay() const +{ + if (false == m_open) + return; + screen_projection const projection; + auto *drawlist{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())}; + glm::dvec3 const camera{Global.pCamera.Pos}; + auto const near_enough = [&](glm::dvec3 const &Point, double const Range) { return Global.EditorOrtho || glm::distance(Point, camera) < Range; }; + glm::dvec3 const lift{0.0, kRailHead, 0.0}; + for (auto const &entry : m_drawn) + { + // the axis, faint where the km run on past the last point + for (std::size_t i = 1; i < entry.points.size(); i += 5) + { + auto const next{std::min(i + 4, entry.points.size() - 1)}; + if (near_enough(entry.points[next], kOverlayRange)) + projection.line(drawlist, entry.points[i - 1] + lift, entry.points[next] + lift, entry.guessed[next] != 0 ? kGuessed : kAxis, Global.EditorOrtho ? 4.0f : 2.5f); + } + for (auto const &tick : entry.ticks) + { + if (false == near_enough(tick.at, kTickRange)) + continue; + auto const centre{tick.at + lift}; + auto const whole{tick.hectometres % 10 == 0}; + auto const reach{tick.jump ? 3.5 : whole ? 2.6 : 1.4}; + projection.line(drawlist, centre - tick.across * reach, centre + tick.across * reach, tick.jump ? kJump : whole ? kKm : kTick, tick.jump || whole ? 3.5f : 2.0f); + if (tick.jump) + continue; + ImVec2 screen; + if (whole && near_enough(tick.at, kLabelRange) && projection.project(centre + tick.across * reach + glm::dvec3{0.0, 0.6, 0.0}, screen)) + draw_label(drawlist, screen, IM_COL32(0, 0, 0, 170), kKm, format("km %d", tick.hectometres / 10)); + else if (false == whole && near_enough(tick.at, kDigitRange) && projection.project(centre + tick.across * reach + glm::dvec3{0.0, 0.4, 0.0}, screen)) + draw_label(drawlist, screen, IM_COL32(0, 0, 0, 140), kTick, std::to_string(std::abs(tick.hectometres) % 10)); + } + } + // the points of the km: a pole with the km over it, the arrow the way the km rise + auto const &marks{kilometrage::marks()}; + for (std::size_t index = 0; index < marks.size(); ++index) + { + auto const &mark{marks[index]}; + if (false == near_enough(mark.point, kLabelRange * 2.0)) + continue; + auto astray{true}; + for (auto const &entry : m_drawn) + if (entry.line == mark.line) + if (auto const *axis{kilometrage::axis_of(mark.line)}; axis != nullptr) + astray = std::find(axis->astray.begin(), axis->astray.end(), index) != axis->astray.end(); + auto const colour{astray ? kAstray : mark.beyond.has_value() ? kJump : kMark}; + auto const foot{mark.point + lift}; + auto const top{foot + glm::dvec3{0.0, 3.0, 0.0}}; + projection.line(drawlist, foot, top, colour, static_cast(index) == m_edited ? 4.0f : 2.5f); + draw_arrow(projection, drawlist, foot, mark.way, 6.0, colour); + ImVec2 screen; + if (projection.project(top, screen)) + draw_label(drawlist, screen, colour, IM_COL32(16, 18, 22, 255), mark.line + ": " + mark_text(mark)); + } + // the tracks chosen for the way through a station: a rhombus on the track + auto const &vias{kilometrage::vias()}; + for (std::size_t index = 0; index < vias.size(); ++index) + { + auto const &via{vias[index]}; + ImVec2 screen; + if (false == near_enough(via.point, kLabelRange * 2.0) || false == projection.project(via.point + lift, screen)) + continue; + auto blocked{false}; + if (auto const *axis{kilometrage::axis_of(via.line)}; axis != nullptr) + blocked = std::find(axis->blocked.begin(), axis->blocked.end(), index) != axis->blocked.end(); + auto const colour{blocked ? kAstray : kAxis}; + auto const r{8.0f}; + drawlist->AddQuadFilled(ImVec2(screen.x, screen.y - r), ImVec2(screen.x + r, screen.y), ImVec2(screen.x, screen.y + r), ImVec2(screen.x - r, screen.y), colour); + drawlist->AddQuad(ImVec2(screen.x, screen.y - r), ImVec2(screen.x + r, screen.y), ImVec2(screen.x, screen.y + r), ImVec2(screen.x - r, screen.y), IM_COL32(16, 18, 22, 255), 1.5f); + draw_label(drawlist, ImVec2(screen.x, screen.y - r - 2.0f), colour, IM_COL32(16, 18, 22, 255), format(STR_C("%s: this way"), via.line.c_str())); + } + if (m_pick.has_value() && m_edited < 0) + { + auto const foot{m_pick->point + lift}; + ImVec2 screen; + if (projection.project(foot, screen)) + drawlist->AddCircle(screen, 9.0f, kKm, 20, 2.5f); + draw_arrow(projection, drawlist, foot, rising(), 8.0, kKm); + } +} + +editor_selftest_result km_tool::selftest(std::string const &Command, std::istringstream &Words) +{ + if (Command == "kmpick") + { + // kmpick track= [at=<0..1>]: a click on the track + auto const values{selftest_values(Words)}; + auto const found{values.find("track")}; + auto *track{found != values.end() ? simulation::Paths.find(found->second) : nullptr}; + if (track == nullptr) + { + WriteLog("SELFTEST kmpick: no such track"); + return editor_selftest_result::handled; + } + auto const at{values.count("at") ? std::atof(values.at("at").c_str()) : 0.5}; + auto const path{values.count("path") ? std::atoi(values.at("path").c_str()) : 0}; + pick(*track, path > 0 && path < static_cast(track->m_paths.size()) ? geometry::bezier{track->m_paths[path]}.point(at) : editor_track::point_at(*track, at)); + auto const *axis{m_line.empty() ? nullptr : kilometrage::axis_of(m_line)}; + WriteLog(format("SELFTEST kmpick %s: line %s km %s jump %d against %d edited %d at %.1f %.1f path %d along %d via %d", track->name().c_str(), m_line.c_str(), kilometrage::text(m_km).c_str(), m_jump ? 1 : 0, m_against ? 1 : 0, m_edited, m_pick->point.x, m_pick->point.z, + m_pick->path, axis != nullptr && axis->runs_along(m_pick->track, m_pick->path) ? 1 : 0, via_here())); + return editor_selftest_result::handled; + } + if (Command == "kmset") + { + // kmset line= km= [beyond=] [against=1]: the fields set and the point put + auto const values{selftest_values(Words)}; + if (auto const line{values.find("line")}; line != values.end()) + m_line = line->second; + if (auto const km{values.find("km")}; km != values.end()) + km_of(km->second.c_str(), m_km); + m_jump = values.count("beyond") > 0; + if (m_jump) + km_of(values.at("beyond").c_str(), m_beyond); + if (auto const against{values.find("against")}; against != values.end()) + m_against = against->second == "1"; + put(); + WriteLog("SELFTEST kmset: " + m_status); + return editor_selftest_result::handled; + } + if (Command == "kmvia") + { + // kmvia [line=] [remove=1]: the line led along the track picked, or back onto the straight paths there + auto const values{selftest_values(Words)}; + if (auto const line{values.find("line")}; line != values.end()) + m_line = line->second; + if (values.count("remove") > 0) + drop_via(); + else + lead_along(); + auto text{m_route_status}; + std::replace(text.begin(), text.end(), '\n', ';'); + WriteLog("SELFTEST kmvia: " + text); + return editor_selftest_result::handled; + } + if (Command == "kmremove") + { + remove(); + WriteLog("SELFTEST kmremove: " + m_status); + return editor_selftest_result::handled; + } + if (Command == "kmposts") + { + // kmposts line=: the km read from the posts along the line through the track picked + auto const values{selftest_values(Words)}; + if (auto const line{values.find("line")}; line != values.end()) + m_line = line->second; + read_posts(); + WriteLog("SELFTEST kmposts: " + m_status); + return editor_selftest_result::handled; + } + if (Command == "kmstate") + { + WriteLog(format("SELFTEST kmstate: picked %d line %s km %s jump %d edited %d", m_pick.has_value() ? 1 : 0, m_line.c_str(), kilometrage::text(m_km).c_str(), m_jump ? 1 : 0, m_edited)); + return editor_selftest_result::handled; + } + if (Command == "kmshow") + { + // kmshow mark=: the point of the km picked, the camera over it + auto const values{selftest_values(Words)}; + auto const index{values.count("mark") ? std::atoi(values.at("mark").c_str()) : 0}; + show(static_cast(std::max(index, 0))); + WriteLog(format("SELFTEST kmshow %d: line %s km %s edited %d", index, m_line.c_str(), kilometrage::text(m_km).c_str(), m_edited)); + return editor_selftest_result::handled; + } + if (Command == "kmlist") + { + refresh(); + for (auto const &entry : m_drawn) + { + std::string list; + for (std::size_t i = 0; i < entry.ticks.size() && entry.points.size() < 2000; ++i) + list += format(" %d@%.0f,%.0f", entry.ticks[i].hectometres, entry.ticks[i].at.x, entry.ticks[i].at.z); + WriteLog(format("SELFTEST kmlist ticks %s: %zu points, %zu ticks", entry.line.c_str(), entry.points.size(), entry.ticks.size()) + list); + } + auto const &marks{kilometrage::marks()}; + WriteLog(format("SELFTEST kmlist: %zu points", marks.size())); + for (auto const &line : kilometrage::lines()) + { + auto const *axis{kilometrage::axis_of(line)}; + if (axis == nullptr) + { + WriteLog("SELFTEST kmlist line " + line + ": no axis"); + continue; + } + std::string list; + for (auto const &anchor : axis->anchors) + list += format(" %s@%.0f/%.1f", mark_text(marks[anchor.mark]).c_str(), anchor.chainage, anchor.gap); + for (auto const &side : axis->sides) + WriteLog(format("SELFTEST kmlist apart: %.1f m of track by %.1f m of axis (%.1f..%.1f), km %s..%s", side.length, side.to - side.from, side.from, side.to, kilometrage::text(kilometrage::km_on(*axis, side, 0.0)).c_str(), + kilometrage::text(kilometrage::km_on(*axis, side, side.length)).c_str())); + WriteLog(format("SELFTEST kmlist line %s: axis %.0f m %s growth %d, %zu astray, %zu blocked, km %s..%s:", line.c_str(), axis->length(), axis->between ? "between" : "along", axis->growth, axis->astray.size(), axis->blocked.size(), kilometrage::text(kilometrage::km_on(*axis, 0.0)).c_str(), + kilometrage::text(kilometrage::km_on(*axis, axis->length())).c_str()) + + list); + } + return editor_selftest_result::handled; + } + if (Command == "kmat") + { + // kmat track= [at=<0..1>]: the km of the lines there + auto const values{selftest_values(Words)}; + auto const found{values.find("track")}; + auto *track{found != values.end() ? simulation::Paths.find(found->second) : nullptr}; + if (track == nullptr) + { + WriteLog("SELFTEST kmat: no such track"); + return editor_selftest_result::handled; + } + auto const at{values.count("at") ? std::atof(values.at("at").c_str()) : 0.5}; + auto text{readout(editor_track::point_at(*track, at))}; + std::replace(text.begin(), text.end(), '\n', ';'); + WriteLog(format("SELFTEST kmat %s %.2f: ", track->name().c_str(), at) + (text.empty() ? std::string{"-"} : text)); + return editor_selftest_result::handled; + } + return editor_selftest_result::unhandled; +} diff --git a/application/editormodekm.h b/application/editormodekm.h new file mode 100644 index 000000000..2e22bafb4 --- /dev/null +++ b/application/editormodekm.h @@ -0,0 +1,102 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include "application/editortool.h" +#include "editor/editorKilometrage.hpp" + +#include +#include +#include +#include + +// the kilometrage of the lines: the points of a line where its km is known and where it jumps, the km of the rest from them +class km_tool final : public editor_tool +{ + public: + km_tool(editor_selection &Selection, editor_view &View, editor_history &History, editor_templates &Templates) + : m_selection{Selection}, m_view{View}, m_history{History}, m_templates{Templates} + { + } + void update() override; + void draw_overlay() const override; + void render_options() override; + void forget(scene::basic_node const *Node) override; + editor_selftest_result selftest(std::string const &Command, std::istringstream &Words) override; + void set_open(bool const Open) { m_open = Open; } + // the point of the track clicked: a new point of the km there, or the one standing by it + void pick(TTrack &Track, glm::dvec3 const &Point); + // the km of the lines at the point, a line of text each, empty where none reaches + std::string readout(glm::dvec3 const &Point) const; + + private: + editor_selection &m_selection; + editor_view &m_view; + editor_history &m_history; + editor_templates &m_templates; + bool m_open{false}; + struct picked + { + TTrack *track{nullptr}; + glm::dvec3 point{0.0}; // on the axis of the track + glm::dvec2 along{0.0, 1.0}; // of the track there, in the plan + int path{0}; // of the switch, the one nearest to the click + glm::dvec3 on{0.0}; // the point of it nearest to the click + }; + std::optional m_pick; + int m_edited{-1}; // of the marks, the one standing by the point picked, -1 for a new one + std::string m_line; + double m_km{0.0}; + bool m_jump{false}; + double m_beyond{0.0}; + bool m_against{false}; // the km rise against the track picked + std::string m_status; + std::string m_route_status; // of the way through a station + // what the overlay draws, made again when the axes change + struct tick + { + glm::dvec3 at{0.0}; + glm::dvec3 across{0.0}; // in the plan, a unit + int hectometres{0}; + bool jump{false}; + }; + struct drawn + { + std::string line; + std::vector points; + std::vector guessed; // of the points, beyond the last point of the km: the km run on from it + std::vector ticks; + }; + std::vector m_drawn; + std::size_t m_revision{0}; + bool m_drawn_once{false}; + + void refresh(); + void put(); + void remove(); + // the point of the km picked and the camera over it + void show(std::size_t const Index); + // the line of the field led along the track picked, along the path of the switch picked, instead of the straight paths of the + // switches; one step of the history + void lead_along(); + // the line back on the straight paths of the switches by the track picked; one step of the history + void drop_via(); + // of the vias of the line of the field, the one on the track picked, -1 for none + int via_here() const; + // the track of the via picked and the camera over it + void show_via(std::size_t const Index); + // the hectometre posts standing along the line through the track picked read into points of the km: the first and the last + // post of each run of them numbered by 100 m, a jump where the runs meet; one step of the history + void read_posts(); + // the way the km rise at the point picked, in the plan + glm::dvec2 rising() const; + // warnings of a jump at the point: Id-1 § 19 wants none on a curve nor at a station + std::string jump_warning(glm::dvec3 const &Point) const; +}; diff --git a/application/editormodelay.cpp b/application/editormodelay.cpp new file mode 100644 index 000000000..ed7e8c78b --- /dev/null +++ b/application/editormodelay.cpp @@ -0,0 +1,2515 @@ +/* +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: +*/ + + +#include "stdafx.h" +#include "application/editormode.h" +#include "editor/editorSettings.hpp" +#include "application/editoruilayer.h" +#include "application/editorprojection.h" +#include "application/editormodeshared.h" +#include "editor/editorFormat.hpp" +#include "editor/editorAlignmentStore.hpp" +#include "editor/editorSwitchStore.hpp" +#include "editor/editorGeometry.hpp" +#include "editor/editorGroundFollow.hpp" +#include "editor/editorIncludeInfo.hpp" + +#include "utilities/Globals.h" +#include "rendering/renderer.h" +#include "world/Track.h" +#include "world/TrackFeatures.h" +#include "scene/scene.h" +#include "scene/scenelayers.h" +#include "simulation/simulation.h" +#include "utilities/Logs.h" +#include "utilities/translation.h" + +#include "imgui/imgui.h" +#include "imgui/ImGuizmo.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "application/editormodetrackshared.h" + +using namespace track_mode; + +namespace +{ + +// the curve of the track of a free end the line goes on from or into: the one of a plain track always, the one of the diverging track +// of a switch where a curve is traced from it, Traced; the bends of straights begin there with a straight, the curvature jumping as at +// the start of the switch +// the way a line through the points heads at the last of them: along the circle through the last three, along the last two where they +// keep straight +glm::dvec2 heading_at_end(std::vector const &Points) +{ + auto const count{Points.size()}; + auto const chord{Points[count - 1] - Points[count - 2]}; + if (count < 3) + return chord; + auto const &first{Points[count - 3]}; + auto const ab{Points[count - 2] - first}; + auto const ac{Points[count - 1] - first}; + auto const twice{2.0 * cross(ab, ac)}; + if (std::abs(twice) < 1e-6 * glm::length(ab) * glm::length(ac)) + return chord; + auto const centre{first + glm::dvec2{ac.y * glm::dot(ab, ab) - ab.y * glm::dot(ac, ac), ab.x * glm::dot(ac, ac) - ac.x * glm::dot(ab, ab)} / twice}; + auto const radial{Points[count - 1] - centre}; + glm::dvec2 tangent{-radial.y, radial.x}; + return glm::dot(tangent, chord) < 0.0 ? -tangent : tangent; +} + +// a stretch fitted from its far end back, its points the other way round and the first one last, as the line runs: the arcs of its curve +// and their transitions in the other order, the offsets of the points but the first, the heading it leaves the first point with +alignment::trace_stretch turned_round(alignment::trace_stretch const &Fit) +{ + auto result{Fit}; + auto const &curve{Fit.vertices.front()}; + auto &turned{result.vertices.front()}; + turned.transition_in = curve.transition_out; + turned.transition_out = curve.transition_in; + if (curve.compound && false == curve.arcs.empty()) + { + // the arcs from the far end: the first one of the vertex, then its arcs, each with the transition before it + std::vector arcs{{curve.radius, 0.0, curve.share, curve.first_cant}}; + arcs.insert(arcs.end(), curve.arcs.begin(), curve.arcs.end()); + std::reverse(arcs.begin(), arcs.end()); + // the transition between two arcs moves to the arc after it the other way round + for (std::size_t i = arcs.size(); i-- > 1;) + arcs[i].transition = arcs[i - 1].transition; + turned.radius = arcs.front().radius; + turned.share = arcs.front().share; + turned.first_cant = arcs.front().cant; + turned.arcs.assign(arcs.begin() + 1, arcs.end()); + } + if (false == result.offsets.empty()) + result.offsets.pop_back(); + std::reverse(result.offsets.begin(), result.offsets.end()); + result.leaving = -Fit.leaving; + return result; +} + +// only a curve traced next to a free end goes on from its curve; the bends of straights begin with a straight there, out of the curve +// of a plain track by a transition, not as a compound curve of its radius and the one of the bend +bool goes_on_curved(editor_track::snap_target const &End, bool const Traced) +{ + return End.track != nullptr && Traced && (End.track->eType == tt_Normal || End.track->eType == tt_Switch); +} + +// the curve of the track of a free end the line laid goes on from at its start, or into at its end: its radius, the side it turns to +// as the line runs and its cant leaning into the turn; nothing on a straight +void adjoining_curve(editor_track::snap_target const &End, bool const Atend, bool const Traced, double const Gauge, alignment::design &Design) +{ + if (false == goes_on_curved(End, Traced)) + return; + auto const bend{editor_track::bend_at(*End.track, End.position)}; + if (false == bend.has_value() || std::abs(bend->curvature) < 1e-4) + return; + // the curvature as the track goes on beyond its end: the way the line runs at its start, against it at its end + auto const curvature{Atend ? -bend->curvature : bend->curvature}; + auto const cant{Gauge * std::sin(glm::radians(bend->roll)) * (bend->curvature > 0.0 ? 1.0 : -1.0)}; + (Atend ? Design.end_radius : Design.start_radius) = 1.0 / std::abs(curvature); + (Atend ? Design.end_turn : Design.start_turn) = curvature > 0.0 ? 1 : -1; + (Atend ? Design.end_cant : Design.start_cant) = std::max(0.0, cant); + (Atend ? Design.end_curved : Design.start_curved) = true; + // the curve of a switch goes on at its radius, with no transition to another one in the switch's way + (Atend ? Design.end_held : Design.start_held) = End.track->eType == tt_Switch; +} + +} // namespace + +void editor_mode::update_build_tools() +{ + glm::dvec3 const ground{cursor_ground()}; + auto const &io{ImGui::GetIO()}; + glm::vec2 const cursor{io.MousePos.x, io.MousePos.y}; + m_straights.detour_mouse = ground; + auto const joining = [&](editor_track::snap_target const &Target) { + if (Target.track == m_join_track && Target.point == m_join_point) + return; + m_join_track = Target.track; + m_join_point = Target.point; + m_join_radius = 0.0; + m_join_variant = 0; + }; + bool const pointing{m_cursor_override.has_value() || ImGui::IsMousePosValid()}; + if (m_extend.active) + { + if (pointing) + m_extend.mouse = cursor_terrain(m_extend.point.y); + m_extend.snap = m_extend.track != nullptr ? snap_free_end(m_extend.mouse, cursor, m_extend.track, m_extend.track->iCategoryFlag & 15, {m_extend.track}) : editor_track::snap_target{}; + if (m_extend.snap.track == nullptr) + m_extend.mouse.y = EditorSettings.heights() == editorSettings::lay_heights::level ? m_extend.point.y : bed_height(m_extend.mouse, plan_of(m_extend.mouse - m_extend.point), m_extend.track); + joining(m_extend.snap); + } + if (m_switch.placing) + { + m_switch.mouse = cursor_level(m_switch.point.y); + recognise_connection(); + // a switch with no track takes the direction of its main track once the drag is long enough, dragged sideways after that it + // takes the side; back by its start the direction is free again + if (auto &tool{m_switch}; tool.free && tool.free_end.track == nullptr) + { + auto const offset{plan_of(tool.mouse - tool.point)}; + if (glm::length(offset) < kFreeSwitchRelease) + tool.free_heading.reset(); + else if (false == tool.free_heading.has_value() && glm::length(offset) >= kFreeSwitchLock) + tool.free_heading = glm::normalize(offset); + } + } + auto &lay{m_lay}; + lay.preview.clear(); + lay.preview_error.clear(); + lay.preview_length = 0.0; + if (false == lay.active) + return; + // a slow preview tells in the log where the time went: the cursor on the ground, the snap, the height, the plan of the line + auto stamp{std::chrono::steady_clock::now()}; + auto const lap = [&]() { + auto const now{std::chrono::steady_clock::now()}; + auto const time{std::chrono::duration(now - stamp).count()}; + stamp = now; + return time; + }; + // geometric ray, same as extend: Mouse_Position() is a delayed depth pick and lags the cursor + double const height{false == lay.points.empty() ? lay.points.back().y : lay.start.track != nullptr ? lay.start.position.y : ground.y}; + if (pointing) + lay.mouse = typed_lay(cursor_terrain(height)); + auto const oncursor{lap()}; + lay.skew.clear(); + if (pointing && ImGui::GetIO().KeyAlt && m_typed.empty() && false == lay.points.empty()) + lay.mouse = lay_angle_snap(lay.mouse, lay.skew); + lay.mouse_snap = m_typed.empty() ? snap_free_end(lay.mouse, cursor, nullptr, kRailCategory, {}) : editor_track::find_free_end(nullptr, kRailCategory, lay.mouse, kLaySnapRadius, {}); + auto const snapping{lap()}; + if (lay.mouse_snap.track == nullptr) + lay.mouse = lay_bed(lay.mouse); + auto const bedding{lap()}; + if (false == m_extend.active) + joining(lay.points.empty() ? editor_track::snap_target{} : lay.mouse_snap); + lay_trim(); + lay.plan = {}; + if (lay.points.empty()) + { + lay.shown.reset(); + lay.settling.reset(); + return; + } + // the line worked out last stays shown as long as the points clicked go on from its ones; one through a point taken back doesn't + if (lay.shown.has_value() && (lay.shown->points.size() > lay.points.size() || false == std::equal(lay.shown->points.begin(), lay.shown->points.end(), lay.points.begin()))) + lay.shown.reset(); + // the line is worked out for the cursor where it was when its fits were asked for, till the thread has done them all, frame after + // frame: then for where the cursor is by then. Another point clicked, or a track changed, the cursor is taken where it is + if (auto const &settling{lay.settling}; + false == lay.whole || (settling.has_value() && (settling->points != lay.points || settling->modes != lay.modes || settling->mode != lay.mode || settling->edits != m_track_edits))) + lay.settling.reset(); + if (false == lay.settling.has_value()) + lay.settling = lay_tool::settling_cursor{lay.mouse, lay.mouse_snap, lay.points, lay.modes, lay.mode, m_track_edits}; + auto const &mouse{lay.settling->mouse}; + // the cursor is the next point, in the mode it would be clicked in + auto points{lay.points}; + auto modes{lay.modes}; + auto end{lay.settling->snap}; + if (end.track != nullptr && glm::distance(end.position, points.front()) > 1.0) + { + points.push_back(end.position); + modes.push_back(lay.mode); + } + else + { + end = {}; + if (plan_distance(mouse, points.back()) > 1.0) + { + points.push_back(mouse); + modes.push_back(lay.mode); + } + } + m_fits_waiting = false; + m_follow_preview = true; + lay.preview = lay_pieces(points, modes, end, lay.preview_length, lay.preview_error, &lay.plan); + m_follow_preview = false; + if (false == m_fits_waiting || false == lay.whole) + { + lay.shown = lay_tool::worked_out{lay.preview, lay.preview_error, lay.preview_length, lay.plan, m_eased_last, m_join_last, lay.points}; + lay.settling.reset(); + } + else if (lay.shown.has_value()) + { + // all of what the line shown was worked out with: the readout tells of it too + auto const &shown{*lay.shown}; + lay.preview = shown.preview; + lay.preview_error = shown.error; + lay.preview_length = shown.length; + lay.plan = shown.plan; + m_eased_last = shown.eased; + m_join_last = shown.join; + } + auto const planning{lap()}; + if (oncursor + snapping + bedding + planning > 30.0) + { + std::string kinds; + for (auto const mode : modes) + kinds += mode == lay_mode::curve ? 'c' : 's'; + WriteLog(format("Editor: slow lay preview: cursor on the ground %.0f ms, snap %.0f ms, height %.0f ms, plan %.0f ms; points %s, from a free end %d, to one %d, %zu pieces, L %.0f m%s", oncursor, snapping, bedding, + planning, kinds.c_str(), lay.start.track != nullptr ? 1 : 0, end.track != nullptr ? 1 : 0, lay.preview.size(), lay.preview_length, + lay.preview_error.empty() ? "" : (", " + lay.preview_error).c_str()), + logtype::generic); + } +} + +bool editor_mode::free_end(TTrack &Track, int const Path, bool const Atend, extend_tool &Tool) +{ + editor_track::point_ref const point{Path, Atend ? editor_track::point_kind::end : editor_track::point_kind::start}; + if (Path < 0 || Path >= static_cast(Track.m_paths.size()) || editor_track::is_connected(Track, point)) + return false; + auto const &path{Track.m_paths[Path]}; + auto const &start{path.points[segment_data::point::start]}; + auto const &end{path.points[segment_data::point::end]}; + auto const &control1{path.points[segment_data::point::control1]}; + auto const &control2{path.points[segment_data::point::control2]}; + glm::dvec3 tangent; + if (Atend) + tangent = control2 != glm::dvec3{} ? -control2 : end - (start + control1); + else + tangent = -(control1 != glm::dvec3{} ? control1 : (end + control2) - start); + glm::dvec2 const planar{tangent.x, tangent.z}; + if (glm::length(planar) < 1e-6) + return false; + Tool.path = Path; + Tool.atend = Atend; + Tool.track = &Track; + Tool.point = editor_track::point_position(Track, point); + Tool.direction = glm::normalize(planar); + Tool.grade = tangent.y / glm::length(planar); + Tool.mouse = Tool.point; + return true; +} + +bool editor_mode::chosen_free_end(extend_tool &Tool) +{ + auto *track{selected_track()}; + if (track == nullptr || (track->eType != tt_Normal && track->eType != tt_Switch) || false == editor_track::is_supported(*track)) + return false; + if (m_track_point.valid() && editor_track::is_end(m_track_point.kind) && free_end(*track, m_track_point.path, m_track_point.kind == editor_track::point_kind::end, Tool)) + return true; + for (int i = 0; i < static_cast(track->m_paths.size()); ++i) + for (auto const atend : {true, false}) + if (free_end(*track, i, atend, Tool)) + return true; + return false; +} + +bool editor_mode::start_extend(editor_track::snap_target const &End) +{ + auto *track{End.track}; + if (track == nullptr || (track->eType != tt_Normal && track->eType != tt_Switch) || false == editor_track::is_supported(*track)) + return false; + extend_tool tool; + if (false == free_end(*track, End.point.path, End.point.kind == editor_track::point_kind::end, tool)) + return false; + auto const &io{ImGui::GetIO()}; + m_extend = tool; + m_extend.origin = End; + m_extend.pressed = {io.MousePos.x, io.MousePos.y}; + m_extend.active = true; + if (track->eType == tt_Switch && End.point.path == 1 && End.point.kind == editor_track::point_kind::end) + m_extend.line = editor_track::find_straight(*track, m_straights.tolerance).tracks; + return true; +} + +bool editor_mode::extend_snap(editor_track::snap_target &Target) const +{ + auto const &tool{m_extend}; + if (false == tool.active || tool.track == nullptr) + return false; + Target = tool.snap; + return Target.track != nullptr && glm::distance(Target.position, tool.point) > 0.5; +} + +glm::dvec3 editor_mode::cursor_ground() const +{ + glm::dvec3 const ground{Global.pCamera.Pos + GfxRenderer->Mouse_Position()}; + if (GfxRenderer->Mouse_Hit()) + return ground; + screen_projection const projection; + glm::dvec3 level; + if (projection.on_level(ImGui::GetIO().MousePos, 0.0, level)) + return level; + return {ground.x, 0.0, ground.z}; +} + +glm::dvec3 editor_mode::cursor_level(double const Height) const +{ + if (m_cursor_override.has_value()) + return glm::dvec3{m_cursor_override->x, Height, m_cursor_override->z}; + glm::dvec3 const ground{cursor_ground()}; + screen_projection const projection; + glm::dvec3 level; + if (false == projection.on_level(ImGui::GetIO().MousePos, Height, level) || (false == Global.editor_tracks && glm::distance(level, glm::dvec3{Global.pCamera.Pos}) > static_cast(kMaxPlacementDistance))) + return ground; + return level; +} + +editor_track::snap_target editor_mode::snap_free_end(glm::dvec3 const &Near, glm::vec2 const &Screen, TTrack const *Self, int const Category, std::vector const &Exclude) const +{ + screen_projection const projection; + auto const reach{Global.EditorOrtho ? std::max(kJointRange, static_cast(Global.EditorOrthoExtent) * 2.0) : kJointRange}; + editor_track::snap_target result; + auto best{kSnapPixels * kSnapPixels}; + for (auto const &candidate : editor_track::free_ends(Self, Category, glm::dvec3{Global.pCamera.Pos}, reach, Exclude)) + { + ImVec2 screen; + if (false == projection.project(candidate.position, screen)) + continue; + auto const distance{(screen.x - Screen.x) * (screen.x - Screen.x) + (screen.y - Screen.y) * (screen.y - Screen.y)}; + if (distance < best) + { + best = distance; + result = candidate; + } + } + if (result.track == nullptr && m_track_snap_radius > 0.0f) + result = editor_track::find_free_end(Self, Category, Near, m_track_snap_radius, Exclude); + return result; +} + +std::vector const &editor_mode::free_end_points(glm::dvec3 const &Centre, double const Reach) const +{ + auto &cache{m_free_end_cache}; + if (cache.edits != m_track_edits || glm::distance(cache.centre, Centre) > cache.reach * 0.25 || Reach > cache.reach * 1.01 || Reach < cache.reach * 0.5) + { + cache.edits = m_track_edits; + cache.centre = Centre; + cache.reach = Reach * 1.25; + cache.points.clear(); + for (auto const &end : editor_track::free_ends(nullptr, kRailCategory, Centre, cache.reach, {})) + cache.points.push_back(end.position); + } + return cache.points; +} + +// the cursor as a ring on the ground, of about the width of the track, to be laid over it on the photo +void editor_mode::draw_cursor_ring(glm::dvec3 const &Point) const +{ + screen_projection const projection; + ImVec2 centre; + if (ImGui::GetIO().WantCaptureMouse || false == projection.project(Point, centre)) + return; + auto *drawlist{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())}; + double constexpr kCursorRadius{0.75}; // m + int constexpr kCursorSteps{36}; + auto const on_ring = [&](int const Step) { + auto const angle{2.0 * glm::pi() * Step / kCursorSteps}; + return Point + glm::dvec3{std::cos(angle) * kCursorRadius, 0.0, std::sin(angle) * kCursorRadius}; + }; + for (int i = 0; i < kCursorSteps; ++i) + projection.line(drawlist, on_ring(i), on_ring(i + 1), IM_COL32(255, 255, 255, 240), 1.5f); + drawlist->AddCircleFilled(centre, 1.5f, IM_COL32(255, 255, 255, 240)); + ImGui::SetMouseCursor(ImGuiMouseCursor_None); +} + +void editor_mode::draw_free_ends(TTrack const *Self, int const Category, std::vector const &Exclude) const +{ + screen_projection const projection; + auto *drawlist{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())}; + auto const &display{ImGui::GetIO().DisplaySize}; + auto const reach{Global.EditorOrtho ? std::max(kJointRange, static_cast(Global.EditorOrthoExtent) * 2.0) : std::min(kJointRange, kDotsRange)}; + for (auto const &candidate : editor_track::free_ends(Self, Category, glm::dvec3{Global.pCamera.Pos}, reach, Exclude)) + { + ImVec2 screen; + if (projection.project(candidate.position, screen) && screen.x >= 0.0f && screen.y >= 0.0f && screen.x <= display.x && screen.y <= display.y) + drawlist->AddCircle(screen, 7.0f, IM_COL32(255, 60, 255, 170), 12, 1.5f); + } +} + +bool editor_mode::switch_reach(glm::dvec3 const &Ground, glm::dvec3 &Point) +{ + auto *selected{selected_track()}; + if (m_track_tab != track_tab::turnout || m_switch.armed < 0 || selected == nullptr || selected->eType != tt_Normal || selected->m_paths.empty()) + return false; + auto const &line{current_straight()}; + if (false == line.tracks.empty()) + { + auto const along{std::clamp(line.along(Ground), 0.0, line.length)}; + Point = line.start + glm::dvec3{line.direction.x, line.grade, line.direction.y} * along; + } + else + { + Point = editor_track::point_at(*selected, editor_track::nearest_parameter(*selected, Ground)); + } + return plan_distance(Point, Ground) <= kSwitchReach; +} + +void editor_mode::handle_drag_start(glm::dvec3 const &Anchor) +{ + auto const &io{ImGui::GetIO()}; + m_handle_drag = {}; + m_handle_drag.active = true; + m_handle_drag.from = {io.MousePos.x, io.MousePos.y}; + m_handle_drag.height = Anchor.y; + m_handle_drag.position = Anchor; + screen_projection const projection; + glm::dvec3 level; + if (projection.on_level(io.MousePos, Anchor.y, level)) + m_handle_drag.offset = {Anchor.x - level.x, 0.0, Anchor.z - level.z}; +} + +bool editor_mode::handle_drag_step(glm::dvec3 &Position, TTrack const *Ground) +{ + auto &drag{m_handle_drag}; + auto const &io{ImGui::GetIO()}; + if (false == drag.active) + return false; + if (false == io.MouseDown[0]) + { + drag = {}; + return false; + } + glm::vec2 const mouse{io.MousePos.x, io.MousePos.y}; + if (false == drag.moved && glm::length(mouse - drag.from) < kDragPixels) + return false; + drag.moved = true; + screen_projection const projection; + glm::dvec3 level; + if (projection.on_level(io.MousePos, drag.height, level) && (Global.editor_tracks || glm::distance(level, glm::dvec3{Global.pCamera.Pos}) <= static_cast(kMaxPlacementDistance))) + { + drag.position = level + drag.offset; + if (Ground != nullptr && false == io.KeyShift) + drag.position.y = bed_height(drag.position, {0.0, 0.0}, Ground); + else + drag.position.y = drag.height; + } + Position = drag.position; + return true; +} + +void editor_mode::point_drag_start(editor_track::point_ref const &Point) +{ + auto *track{selected_track()}; + m_track_point = Point; + m_point_drag = {}; + if (track == nullptr || false == Point.valid() || Point.path >= static_cast(track->m_paths.size())) + return; + auto const &io{ImGui::GetIO()}; + m_point_drag.active = true; + m_point_drag.from = {io.MousePos.x, io.MousePos.y}; + m_point_drag.height = editor_track::point_position(*track, Point).y; +} + +void editor_mode::point_drag_update() +{ + auto &drag{m_point_drag}; + if (false == drag.active) + return; + auto const &io{ImGui::GetIO()}; + if (false == io.MouseDown[0]) + { + point_drag_finish(); + return; + } + auto *track{selected_track()}; + if (track == nullptr || false == m_track_point.valid() || m_track_point.path >= static_cast(track->m_paths.size())) + { + drag = {}; + return; + } + glm::vec2 const mouse{io.MousePos.x, io.MousePos.y}; + if (false == drag.moved) + { + if (glm::length(mouse - drag.from) < kDragPixels) + return; + std::string reason; + if (false == editor_track::can_edit_geometry(*track, reason)) + { + ui()->set_status(reason, true); + drag = {}; + return; + } + drag.moved = true; + m_track_drag = {track}; + m_track_drag_points.clear(); + m_track_joints.clear(); + m_track_snap = {}; + if (editor_track::is_end(m_track_point.kind) && m_track_drag_connected) + { + for (auto const &connection : editor_track::connected_points(*track, editor_track::point_position(*track, m_track_point))) + { + std::string neighbourreason; + if (false == editor_track::can_edit_geometry(*connection.first, neighbourreason)) + continue; + m_track_drag_points.emplace_back(connection); + if (std::find(m_track_drag.begin(), m_track_drag.end(), connection.first) == m_track_drag.end()) + m_track_drag.emplace_back(connection.first); + } + } + std::vector> states; + for (auto *dragged : m_track_drag) + states.emplace_back(dragged, editor_track::capture(*dragged)); + push_track_snapshot(std::move(states)); + drag.step = m_history.size(); + records_watch_begin(); + } + screen_projection const projection; + glm::dvec3 position; + if (false == projection.on_level(io.MousePos, drag.height, position) || (false == Global.editor_tracks && glm::distance(position, glm::dvec3{Global.pCamera.Pos}) > static_cast(kMaxPlacementDistance))) + return; + // an end goes onto the ground at the height of the ballast, as a point laid; with Shift it keeps its height + if (editor_track::is_end(m_track_point.kind) && false == io.KeyShift) + { + auto const &path{track->m_paths[m_track_point.path]}; + auto const tangent{geometry::bezier{path}.first(m_track_point.kind == editor_track::point_kind::end ? 1.0 : 0.0)}; + position.y = bed_height(position, plan_of(tangent), track); + } + m_track_snap = {}; + if (editor_track::is_end(m_track_point.kind) && m_track_drag_points.empty()) + { + std::vector const exclude(m_track_drag.begin(), m_track_drag.end()); + m_track_snap = snap_free_end(position, mouse, track, track->iCategoryFlag & 15, exclude); + if (m_track_snap.track != nullptr) + position = m_track_snap.position; + } + editor_track::move_point(*track, m_track_point, position); + for (auto const &connection : m_track_drag_points) + editor_track::move_point(*connection.first, connection.second, position); + m_track_dirty = true; + commit_track_drag(false); +} + +void editor_mode::point_drag_finish() +{ + auto const drag{m_point_drag}; + m_point_drag = {}; + if (false == drag.active || false == drag.moved) + return; + if (auto *track{selected_track()}; track != nullptr && m_track_snap.track != nullptr && m_track_point.valid()) + { + editor_track::snap_point(*track, m_track_point, m_track_snap, m_track_align_tangent); + m_track_dirty = true; + } + m_track_snap = {}; + commit_track_drag(true); + records_watch_end(); + m_track_drag.clear(); + m_track_drag_points.clear(); + m_track_joints.clear(); +} + +std::optional editor_mode::eased_layout(TTrack const *From, glm::dvec3 const &Point, glm::dvec2 const &Direction, glm::dvec3 const &Target, double const Radius) const +{ + m_eased_last.reset(); + // from the end of a curved track the line goes on from its curvature: a curve from it, a straight after a transition out of it, never + // with a jump of the curvature at the end; at the diverging track of a switch a curve from it, a straight right from its end, as the + // switch goes on with a straight + if (From == nullptr || (From->eType != tt_Normal && (From->eType != tt_Switch || m_track_layout == track_layout::straight))) + return std::nullopt; + auto const end{editor_track::bend_at(*From, Point)}; + if (false == end.has_value()) + return std::nullopt; + alignment::lay_request request; + request.start.position = Point; + request.start.direction = Direction; + request.start.roll = end->roll; + request.curvature = end->curvature; + request.target = Target; + switch (m_track_layout) + { + case track_layout::straight: request.kind = alignment::lay_kind::straight; break; + case track_layout::arc: request.kind = alignment::lay_kind::arc; break; + case track_layout::straight_arc: request.kind = alignment::lay_kind::straight_arc; break; + default: request.kind = alignment::lay_kind::arc_straight; break; + } + request.radius = Radius; + request.speed = design_speed(From, nullptr); + request.piece_length = m_lay.piece_length; + request.norms = laying_norms(); + // the diverging track of a switch has no cant: the line out of its curve is laid for the speed the curve lets with the unbalanced + // acceleration alone, as ease_out_of does + if (From->eType == tt_Switch && std::abs(end->curvature) > 1e-9) + request.speed = std::min(request.speed, std::sqrt(12.96 * request.norms.unbalanced / std::abs(end->curvature))); + if (false == m_eased_cache.has_value() || m_eased_cache->first != request) + m_eased_cache.emplace(request, alignment::lay_on(request)); + m_eased_last = m_eased_cache->second; + return m_eased_last; +} + +namespace +{ + +// the cant of a track joined goes on into the track laid, whatever shape that one has: its difference fades along the pieces from the +// joint, over as many of them as the cant takes at the ramp a transition curve has at the least, or over all of them where they're shorter +void lead_cant(std::vector &Pieces, double const Roll, double const Gauge, bool const From_start) +{ + double constexpr ramp_slope{1.5}; // mm of the cant to a metre + if (Pieces.empty()) + return; + auto const here{From_start ? Pieces.front().rolls[0] : Pieces.back().rolls[1]}; + auto const difference{Roll - static_cast(here)}; + if (std::abs(difference) < 1e-3) + return; + auto const wanted{Gauge * std::abs(std::sin(glm::radians(difference))) / ramp_slope}; + std::vector lengths; + auto reach{0.0}; + for (std::size_t i = 0; i < Pieces.size(); ++i) + { + lengths.push_back(geometry::bezier{Pieces[From_start ? i : Pieces.size() - 1 - i]}.plan_length()); + if (reach < wanted) + reach += lengths.back(); + } + auto along{0.0}; + for (std::size_t i = 0; i < Pieces.size() && along < reach; ++i) + { + auto &piece{Pieces[From_start ? i : Pieces.size() - 1 - i]}; + auto const nearer{difference * (1.0 - along / reach)}; + along += lengths[i]; + auto const further{difference * (1.0 - std::min(along / reach, 1.0))}; + piece.rolls[From_start ? 0 : 1] += static_cast(nearer); + piece.rolls[From_start ? 1 : 0] += static_cast(further); + } +} + +} // namespace + +std::vector editor_mode::extend_pieces() const +{ + m_eased_last.reset(); + std::vector result; + auto const &tool{m_extend}; + editor_track::snap_target target; + if (extend_snap(target)) + { + editor_track::branch_link link; + std::string reason; + if (plan_branch_link(link, reason)) + { + m_join_last = {}; + return link.pieces; + } + double length; + std::string error; + return join_pieces(tool.track, {tool.path, tool.atend ? editor_track::point_kind::end : editor_track::point_kind::start}, tool.point, tool.direction, target, length, error); + } + m_join_last = {}; + auto radius{m_lay.radius}; + if (auto const values{typed_values()}; false == values.empty() && (m_track_layout == track_layout::arc_straight || m_track_layout == track_layout::straight_arc) && std::abs(values[0]) >= 1.0) + radius = std::abs(values[0]); + if (m_track_layout != track_layout::straight && tool.track != nullptr && tool.track->eType == tt_Switch && tool.track->m_paths.size() > 1 && tool.path == 1 && tool.atend) + { + auto const &diverging{tool.track->m_paths[1]}; + bezier const curve{diverging}; + auto const begin{plan_of(curve.first(0.0))}; + auto const finish{plan_of(curve.first(1.0))}; + auto const turn{glm::length(begin) > 1e-9 && glm::length(finish) > 1e-9 ? geometry::signed_angle(begin, finish) : 0.0}; + if (auto const branch{editor_track::branch_radius(diverging)}; branch > 0.0) + { + int const side{turn > 0.0 ? 1 : -1}; + auto const &direction{tool.direction}; + auto const centre{plan_of(tool.point) + glm::dvec2{-direction.y, direction.x} * (side * branch)}; + auto const angle{geometry::signed_angle(plan_of(tool.point) - centre, plan_of(tool.mouse) - centre) * side}; + if (angle * branch < 0.5) + return result; + auto pieces{arc_pieces(tool.point, direction, tool.grade, branch, std::min(angle, glm::pi()), side)}; + for (auto &piece : pieces) + piece.rolls = {diverging.rolls[1], diverging.rolls[1]}; + follow_ground(pieces, tool.point.y, tool.grade, tool.mouse.y, std::numeric_limits::quiet_NaN(), tool.track); + return pieces; + } + } + auto const eased{eased_layout(tool.track, tool.point, tool.direction, tool.mouse, radius)}; + auto pieces{eased.has_value() && false == eased->pieces.empty() ? eased->pieces : editor_track::layout_pieces(m_track_layout, tool.point, tool.direction, tool.grade, tool.mouse, radius)}; + follow_ground(pieces, tool.point.y, tool.grade, tool.mouse.y, std::numeric_limits::quiet_NaN(), tool.track); + if (tool.track != nullptr) + lead_cant(pieces, -editor_track::joint_roll(*tool.track, {tool.path, tool.atend ? editor_track::point_kind::end : editor_track::point_kind::start}), laying_norms().gauge, true); + return pieces; +} + +std::vector editor_mode::extend_preview() const +{ + auto const &tool{m_extend}; + auto const &io{ImGui::GetIO()}; + std::vector key{tool.mouse.x, tool.mouse.y, tool.mouse.z, tool.point.x, tool.point.z, io.MousePos.x, io.MousePos.y, tool.snap.position.x, tool.snap.position.z, + static_cast(reinterpret_cast(tool.track)), static_cast(reinterpret_cast(tool.snap.track)), static_cast(tool.path), + static_cast(tool.active) + 2.0 * tool.atend + 4.0 * io.KeyShift + 8.0 * io.KeyCtrl + 16.0 * io.KeyAlt, m_join_radius, static_cast(m_join_variant), + static_cast(m_track_layout), static_cast(m_history.size())}; + if (false == m_extend_memo.fresh(key)) + { + m_follow_preview = true; + m_extend_memo.keep(std::move(key), extend_pieces()); + m_follow_preview = false; + } + return m_extend_memo.result; +} + +TTrack const *editor_mode::speed_track(TTrack const *From, TTrack const *To) const +{ + if (m_lay.own_speed && m_lay.style.velocity > 0.0) + return nullptr; + TTrack const *result{nullptr}; + for (auto const *track : {From, To}) + if (track != nullptr && editor_track::velocity(*track) > 0.0 && (result == nullptr || editor_track::velocity(*track) < editor_track::velocity(*result))) + result = track; + return result; +} + +double editor_mode::design_speed(TTrack const *From, TTrack const *To) const +{ + if (auto const *track{speed_track(From, To)}; track != nullptr) + return editor_track::velocity(*track); + return m_lay.style.velocity > 0.0 ? m_lay.style.velocity : 100.0; +} + +std::pair editor_mode::laying_ends() const +{ + if (m_extend.active) + { + editor_track::snap_target target; + return {m_extend.track, extend_snap(target) ? target.track : nullptr}; + } + if (m_lay.active && false == m_lay.points.empty()) + return {m_lay.start.track, m_lay.points.size() == 1 ? m_lay.mouse_snap.track : nullptr}; + return {nullptr, nullptr}; +} + +std::string editor_mode::design_speed_of(TTrack const *From, TTrack const *To) const +{ + auto const speed{design_speed(From, To)}; + if (auto const *track{speed_track(From, To)}; track != nullptr) + return format(STR_C("design speed %.0f km/h, that of the track %s"), speed, name_of(*track).c_str()); + return format(STR_C("design speed %.0f km/h, set for the laying"), speed); +} + +std::vector editor_mode::switch_exit_warnings(TTrack const *From, glm::dvec3 const &Start, TTrack const *To, glm::dvec3 const &End, std::vector const &Pieces) const +{ + auto const *switched{From != nullptr && From->eType == tt_Switch ? From : To != nullptr && To->eType == tt_Switch ? To : nullptr}; + if (switched == nullptr || Pieces.empty()) + return {}; + auto const &joint{switched == From ? Start : End}; + // 1/m, positive to the left, as the piece runs + auto const curvature_at = [](segment_data const &Piece, double const T) { return bezier{Piece}.plan_curvature(T); }; + // the path of the switch ending at the joint, its pieces from the joint back into the switch, each with its curvature at its ends as + // the line runs on beyond the joint + std::vector> back; + for (auto const &path : switched->m_paths) + for (auto const atend : {false, true}) + { + if (false == back.empty() || glm::distance(path.points[atend ? segment_data::point::end : segment_data::point::start], joint) > 0.05) + continue; + std::vector pieces{path.pieces.empty() ? std::vector{path} : path.pieces}; + if (atend) + std::reverse(pieces.begin(), pieces.end()); + for (auto const &piece : pieces) + back.push_back({bezier{piece}.plan_length(), atend ? curvature_at(piece, 1.0) : -curvature_at(piece, 0.0), atend ? curvature_at(piece, 0.0) : -curvature_at(piece, 1.0)}); + } + // the curve the switch ends with, and the straight of a straight frog after it + double straight{0.0}; + std::optional curvature; + for (auto const &[length, inner, outer] : back) + { + if (std::abs(inner) > 1e-4 || std::abs(outer) > 1e-4) + { + curvature = inner; + break; + } + straight += length; + } + if (false == curvature.has_value()) + return {}; + // the pieces laid as the line runs on from the switch + std::vector> line; + if (switched == From) + for (auto const &piece : Pieces) + line.push_back({bezier{piece}.plan_length(), curvature_at(piece, 0.0), curvature_at(piece, 1.0)}); + else + for (auto piece{Pieces.rbegin()}; piece != Pieces.rend(); ++piece) + line.push_back({bezier{*piece}.plan_length(), -curvature_at(*piece, 1.0), -curvature_at(*piece, 0.0)}); + // no faster than the diverging track of the switch lets + auto const speed{std::min(design_speed(From, To), editor_track::diverging_speed(1.0 / std::abs(*curvature)))}; + return switch_curve::check_exit(*curvature, straight, line, speed, laying_norms().gauge).warnings; +} + +void editor_mode::give_own_speed(std::vector const &Created) const +{ + if (false == m_lay.own_speed || m_lay.style.velocity <= 0.0) + return; + for (auto *track : Created) + editor_track::velocity(*track, m_lay.style.velocity); +} + +std::vector editor_mode::join_pieces(TTrack const *From, editor_track::point_ref const &Frompoint, glm::dvec3 const &Start, glm::dvec2 const &Direction, editor_track::snap_target const &End, double &Length, + std::string &Error) const +{ + alignment::join_request request; + request.start.position = Start; + request.start.direction = Direction; + request.start.roll = From != nullptr ? -editor_track::joint_roll(*From, Frompoint) : 0.0; + request.end.position = End.position; + request.end.direction = plan_of(End.direction); + request.end.roll = End.track != nullptr ? editor_track::joint_roll(*End.track, End.point) : 0.0; + request.radius = m_join_radius; + request.variant = m_join_variant; + request.speed = design_speed(From, End.track); + request.kink = m_joints.kink_angle() * 0.5; + request.shape = m_route.design.shape; + request.norms = laying_norms(); + auto result{alignment::join(request)}; + if (result.kind != alignment::join_kind::straight && result.kind != alignment::join_kind::arc && glm::length(request.end.direction) > 1e-9) + { + auto const grade{(End.position.y - Start.y) / std::max(1.0, plan_distance(Start, End.position))}; + auto const curved = [](TTrack const *Track) { return Track != nullptr && (Track->eType == tt_Normal || Track->eType == tt_Switch); }; + auto const in{curved(From) ? editor_track::ease_out_of(*From, Start, grade, request.speed, request.norms) : editor_track::easing{}}; + auto const out{curved(End.track) ? editor_track::ease_out_of(*End.track, End.position, -grade, request.speed, request.norms) : editor_track::easing{}}; + if (auto eased{eased_join(request, in, out)}) + result = std::move(*eased); + } + Length = result.length; + std::vector notes; + for (auto const &warning : result.warnings) + if (m_join_radius > 0.0 || std::find(result.radius_warnings.begin(), result.radius_warnings.end(), warning) == result.radius_warnings.end()) + notes.push_back(warning); + if (result.kind == alignment::join_kind::bezier) + notes.insert(notes.begin(), STR_C("No curve fits between the ends, they are joined with a free curve")); + Error = lines_of(notes); + m_join_last = result; + return result.pieces; +} + +void editor_mode::finish_extend() +{ + auto const &io{ImGui::GetIO()}; + if (glm::length(glm::vec2{io.MousePos.x, io.MousePos.y} - m_extend.pressed) < kDragPixels) + { + m_extend.active = false; + if (m_lay.active && m_lay.points.empty() && m_extend.origin.track != nullptr) + { + m_lay.status.clear(); + m_lay.start = m_extend.origin; + m_lay.points.push_back(m_extend.origin.position); + } + else if (false == m_lay.active && m_extend.origin.track != nullptr && m_extend.origin.track == selected_track()) + m_track_point = m_extend.origin.point; + return; + } + std::string reason; + if (editor_track::branch_link link; plan_branch_link(link, reason)) + { + finish_branch_link(link); + return; + } + if (false == reason.empty()) + ui()->set_status(reason, true); + crossover_plan plan; + editor_track::snap_target target; + if (false == extend_snap(target) && plan_crossover(plan)) + { + auto *origin{m_extend.track}; + m_extend.active = false; + std::vector> states; + std::vector created; + std::vector removed; + if (false == place_switch_on_straight(plan.target, plan.shape, origin, plan.along, plan.direction, plan.side, false, states, created, removed, switch_name_for_new())) + return; + auto *placed{*std::find_if(created.begin(), created.end(), [](TTrack const *Track) { return Track != nullptr && Track->eType == tt_Switch; })}; + std::vector inserts; + for (auto piece : plan.inserts) + { + if (glm::distance(piece.points[segment_data::point::start], piece.points[segment_data::point::end]) <= 0.01) + continue; + // meeting the two switches at the heights they're at + for (auto const index : {segment_data::point::start, segment_data::point::end}) + for (auto const *track : {origin, placed}) + if (auto const &end{track->m_paths.back().points[segment_data::point::end]}; geometry::plan_distance(piece.points[index], end) < 0.05) + piece.points[index].y = end.y; + if (auto *insert{editor_track::create_path(*origin, piece)}) + inserts.push_back(insert); + } + editor_track::commit(inserts); + created.insert(created.end(), inserts.begin(), inserts.end()); + // kept as a crossover, so it's taken out, slid and followed as one + record_connection(connection::kind::crossover, {origin, placed}, plan.connection, editor_track::template_of_switch(origin).value_or(plan.shape)); + push_track_snapshot(std::move(states), std::move(created), std::move(removed)); + straight_refresh(); + if (place_switch_drive(*placed)) + join_last_steps(); + advance_switch_name(); + return; + } + auto const pieces{extend_pieces()}; + auto *style{m_extend.track}; + m_extend.active = false; + if (pieces.empty() || style == nullptr) + return; + // the track laid takes only its heights from the ground: the terrain is shaped under it by the buttons of the terrain model + m_nmt_state.laying = true; + std::vector created; + for (auto const &piece : pieces) + created.push_back(editor_track::create_path(*style, piece)); + give_own_speed(created); + editor_track::commit(created); + auto const from{m_history.size()}; + push_track_snapshot({}, created); + first_step_done(first_step::laid); + if (target.track != nullptr) + first_step_done(first_step::join); + if (auto const warnings{switch_exit_warnings(style, pieces.front().points[segment_data::point::start], target.track, target.position, pieces)}; false == warnings.empty()) + ui()->set_status(lines_of(warnings), true); + m_node = created.back(); + ui()->set_node(m_node); + nmt_fit_laid(from, created.back()->m_paths.front().points[segment_data::point::end]); + m_nmt_state.laying = false; + straight_refresh(); +} + +void editor_mode::extend_add(int const Side) +{ + extend_tool tool; + if (false == chosen_free_end(tool)) + return; + auto const length{std::max(0.5, m_extend_length)}; + std::vector pieces; + if (Side == 0) + { + segment_data path; + path.points[segment_data::point::start] = tool.point; + path.points[segment_data::point::end] = {tool.point.x + tool.direction.x * length, tool.point.y + tool.grade * length, tool.point.z + tool.direction.y * length}; + pieces.push_back(path); + } + else + { + auto const radius{std::max(10.0, m_extend_radius)}; + pieces = arc_pieces(tool.point, tool.direction, tool.grade, radius, std::min(length / radius, glm::radians(180.0)), Side); + } + std::vector created; + for (auto const &piece : pieces) + created.push_back(editor_track::create_path(*tool.track, piece)); + editor_track::commit(created); + push_track_snapshot({}, created); + m_node = created.back(); + ui()->set_node(m_node); + m_track_point = {}; + straight_refresh(); +} + +void editor_mode::render_extend_ui() +{ + extend_tool tool; + if (false == chosen_free_end(tool)) + return; + if (false == ImGui::CollapsingHeader(STR_C("Continue from the free end"))) + return; + if (begin_fields("##extendfields", 0.3f)) + { + field_row("Length (m)##extend"); + ImGui::DragScalar("##extendlength", ImGuiDataType_Double, &m_extend_length, 0.5f, nullptr, nullptr, "%.1f"); + item_tooltip("Length of the next piece, along the curve for the curves"); + field_row("R (m)##extend"); + ImGui::DragScalar("##extendradius", ImGuiDataType_Double, &m_extend_radius, 5.0f, nullptr, nullptr, "%.0f"); + item_tooltip("Radius of the curves added"); + ImGui::EndTable(); + } + m_extend_length = std::clamp(m_extend_length, 0.5, 5000.0); + m_extend_radius = std::clamp(m_extend_radius, 10.0, 100000.0); + auto const gap{std::round(ImGui::GetFontSize() * 0.3f)}; + auto const width{std::floor((ImGui::GetContentRegionAvail().x - 2.0f * gap) / 3.0f)}; + auto const at = [](ImVec2 const Low, ImVec2 const High, float const X, float const Y) { return ImVec2(Low.x + (High.x - Low.x) * X, Low.y + (High.y - Low.y) * Y); }; + auto const piece = [&](char const *Id, char const *Label, int const Bend) { + return sketch_tile(Id, Label, false, width, [&](ImDrawList &List, ImVec2 Low, ImVec2 High, ImU32 Line, ImU32) { + List.AddLine(at(Low, High, 0.0f, 0.5f), at(Low, High, 0.4f, 0.5f), Line, 2.0f); + List.AddCircleFilled(at(Low, High, 0.4f, 0.5f), 2.5f, IM_COL32(230, 90, 70, 255)); + if (Bend == 0) + List.AddLine(at(Low, High, 0.4f, 0.5f), at(Low, High, 1.0f, 0.5f), IM_COL32(255, 210, 60, 255), 2.0f); + else + List.AddBezierQuadratic(at(Low, High, 0.4f, 0.5f), at(Low, High, 0.75f, 0.5f), at(Low, High, 0.95f, Bend > 0 ? 0.08f : 0.92f), IM_COL32(255, 210, 60, 255), 2.0f); + }); + }; + if (piece("##extendstraight", STR_C("Straight"), 0)) + extend_add(0); + item_tooltip("Adds a straight at the free end; the new piece gets selected, so the next click goes on from it"); + ImGui::SameLine(0.0f, gap); + if (piece("##extendleft", STR_C("Curve left"), 1)) + extend_add(1); + ImGui::SameLine(0.0f, gap); + if (piece("##extendright", STR_C("Curve right"), -1)) + extend_add(-1); +} + +int editor_mode::wheel_step(double const Offset, bool const Gesture) +{ + auto const &io{ImGui::GetIO()}; + auto const now{ImGui::GetTime()}; + int const keys{(io.KeyCtrl ? 1 : 0) | (io.KeyShift ? 2 : 0) | (io.KeyAlt ? 4 : 0)}; + auto &wheel{m_wheel}; + if (now - wheel.time > 0.3 || keys != wheel.keys || (wheel.rest != 0.0 && (wheel.rest > 0.0) != (Offset > 0.0))) + { + wheel.rest = 0.0; + wheel.spent = false; + } + wheel.time = now; + wheel.keys = keys; + wheel.rest += Offset; + if ((Gesture && wheel.spent) || std::abs(wheel.rest) < 1.0 - 1e-6) + return 0; + int const step{wheel.rest > 0.0 ? 1 : -1}; + wheel.rest -= step; + wheel.spent = true; + return step; +} + +bool editor_mode::track_wheel(double const Offset) +{ + auto const &io{ImGui::GetIO()}; + if (m_switch.placing && m_switch.connection >= 0 && Offset != 0.0 && (io.KeyCtrl || io.KeyShift || io.KeyAlt)) + { + auto &tool{m_switch}; + int const step{wheel_step(Offset, false == io.KeyCtrl)}; + if (step == 0) + return true; + // the kind of a connection a switch dragged makes comes from where it's let go + if (io.KeyShift) + { + if (false == tool.recognised) + tool.connection = (tool.connection + step + connection::kind_count) % connection::kind_count; + } + else if (io.KeyCtrl) + { + static double const radii[]{0.0, 150.0, 190.0, 250.0, 300.0, 400.0, 500.0, 600.0, 800.0, 1000.0, 1200.0, 1500.0, 2000.0, 3000.0}; + int index{0}; + for (int i = 0; i < static_cast(std::size(radii)); ++i) + if (radii[i] <= tool.connection_radius + 1e-6) + index = i; + tool.connection_radius = radii[std::clamp(index + step, 0, static_cast(std::size(radii)) - 1)]; + } + else if (false == tool.recognised) + tool.connection_together = false == tool.connection_together; + return true; + } + if ((false == io.KeyCtrl && false == io.KeyShift) || Offset == 0.0) + return false; + bool const laying{m_lay.active && false == m_lay.points.empty()}; + if (false == m_extend.active && false == laying) + return false; + int const step{wheel_step(Offset, false == io.KeyCtrl)}; + if (step == 0) + return true; + editor_track::snap_target target; + bool const joined{m_extend.active ? extend_snap(target) : m_lay.mouse_snap.track != nullptr && m_lay.start.track != nullptr}; + static double const radii[]{100.0, 150.0, 190.0, 250.0, 300.0, 400.0, 500.0, 600.0, 800.0, 1000.0, 1200.0, 1500.0, 2000.0, 3000.0, 4000.0, 6000.0}; + auto const next_radius = [&](double const Current) { + if (step > 0) + { + for (auto const radius : radii) + if (radius > Current * 1.001) + return radius; + return std::end(radii)[-1]; + } + for (auto radius{std::rbegin(radii)}; radius != std::rend(radii); ++radius) + if (*radius < Current * 0.999) + return *radius; + return radii[0]; + }; + first_step_done(io.KeyCtrl ? first_step::wheel : first_step::shape); + if (io.KeyCtrl && io.KeyShift) + { + static double const speeds[]{20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0, 120.0, 140.0, 160.0, 200.0, 250.0}; + auto const [from, to]{laying_ends()}; + auto const current{design_speed(from, to)}; + int index{0}; + for (int i = 0; i < static_cast(std::size(speeds)); ++i) + if (speeds[i] <= current + 1e-6) + index = i; + if (step < 0 && speeds[index] < current - 1e-6) + ++index; + m_lay.style.velocity = speeds[std::clamp(index + step, 0, static_cast(std::size(speeds)) - 1)]; + m_lay.own_speed = true; + return true; + } + if (io.KeyCtrl) + { + if (false == joined) + m_lay.radius = next_radius(m_lay.radius); + else if (m_join_radius <= 0.0) + m_join_radius = next_radius(m_join_last.radius > 0.0 ? m_join_last.radius : 500.0); + else if (step > 0 && m_join_radius >= std::end(radii)[-1]) + m_join_radius = 0.0; + else + m_join_radius = next_radius(m_join_radius); + return true; + } + if (joined) + m_join_variant += step; + return true; +} + +std::vector editor_mode::lay_pieces(std::vector const &Points, std::vector const &Modes, editor_track::snap_target const &End, double &Length, std::string &Error, + lay_line_plan *Plan) const +{ + auto const &tool{m_lay}; + Length = 0.0; + m_eased_last.reset(); + if (Points.size() < 2) + return {}; + auto const unknown{std::numeric_limits::quiet_NaN()}; + if (Points.size() == 2 && End.track != nullptr) + { + // two free ends: the curve between them is the one the join finds + if (tool.start.track != nullptr) + { + auto const leaving{-plan_of(tool.start.direction)}; + if (glm::length(leaving) < 1e-6) + { + Error = STR_C("Two points lie on one another"); + return {}; + } + return join_pieces(tool.start.track, tool.start.point, Points[0], glm::normalize(leaving), End, Length, Error); + } + // from a point to a free end: the shape of the layout laid back from the end + m_join_last = {}; + std::vector pieces; + if (glm::length(plan_of(End.direction)) > 1e-6) + { + auto const eased{eased_layout(End.track, End.position, glm::normalize(-plan_of(End.direction)), Points[0], tool.radius)}; + auto const laid{eased.has_value() && false == eased->pieces.empty()}; + auto const back{laid ? eased->pieces : editor_track::layout_pieces(m_track_layout, End.position, glm::normalize(-plan_of(End.direction)), -grade_of(End.direction), Points[0], tool.radius)}; + for (auto piece{back.rbegin()}; piece != back.rend(); ++piece) + pieces.push_back(reversed(*piece)); + Error = laid ? narrowed(m_track_layout, tool.radius, eased->radius) : narrowed(pieces, m_track_layout, tool.radius); + follow_ground(pieces, Points[0].y, unknown, End.position.y, grade_of(End.direction), End.track); + } + for (auto const &piece : pieces) + Length += bezier{piece}.plan_length(); + if (pieces.empty()) + Error = STR_C("The track can't be laid through these points"); + lead_cant(pieces, editor_track::joint_roll(*End.track, End.point), laying_norms().gauge, false); + return pieces; + } + m_join_last = {}; + lay_line_plan plan; + if (false == lay_line(Points, Modes, End, plan, Error)) + return {}; + auto const &design{plan.design}; + auto const &shape{plan.shape}; + Error = lines_of(shape.warnings); + auto const count = [&](alignment::result const &Shape, alignment::design const &Design) { + return std::max(alignment::minimum_pieces(Shape, Design), static_cast(std::ceil(Shape.length / std::max(5.0, tool.piece_length)))); + }; + std::vector pieces; + // the curvature of the track laid has to go on from the one of the plain track it joins, a jump gets a transition curve between them + auto const grade{(Points.back().y - Points.front().y) / std::max(1.0, plan_distance(Points.front(), Points.back()))}; + // out of the curve of a plain track a line which doesn't go on with it begins by a transition; at the end of the diverging track of a + // switch it goes on with the curve of the switch or begins with a straight right there, as lay_line decided, never eased + auto const eased = [&](editor_track::snap_target const &Joint, double const Chainage, double const Sign) { + if (Joint.track == nullptr || Joint.track->eType != tt_Normal) + return editor_track::easing{}; + auto result{editor_track::ease_out_of(*Joint.track, Joint.position, grade * Sign, design.speed, design.norms)}; + auto const own{Sign * curvature_at(shape, Chainage)}; + if (std::abs(own - result.curvature) <= 0.05 * std::abs(result.curvature)) + result.pieces.clear(); + return result; + }; + auto const in{eased(tool.start, 0.0, 1.0)}; + auto const out{eased(End, shape.length, -1.0)}; + if ((false == in.pieces.empty() || false == out.pieces.empty()) && editor_track::eases_room(in, out, Points.front(), design.start_direction, Points.back(), design.end_direction)) + { + auto easeddesign{design}; + // an end moved out of the curve of the adjoining track is on a straight + if (false == in.pieces.empty()) + { + easeddesign.start = in.end; + easeddesign.start_direction = in.direction; + easeddesign.start_curved = false; + easeddesign.start_radius = 0.0; + easeddesign.start_turn = 0; + } + if (false == out.pieces.empty()) + { + easeddesign.end = out.end; + easeddesign.end_direction = -out.direction; + easeddesign.end_curved = false; + easeddesign.end_radius = 0.0; + easeddesign.end_turn = 0; + } + // a straight with no bend, clicked on from the end the way it went: after the transition it runs on the way the transition leaves, + // as far as the point clicked + if (false == in.pieces.empty() && out.pieces.empty() && End.track == nullptr && easeddesign.vertices.empty()) + { + auto const along{glm::normalize(in.direction)}; + auto const distance{glm::dot(plan_of(easeddesign.end - in.end), along)}; + easeddesign.end = {in.end.x + along.x * distance, easeddesign.end.y, in.end.z + along.y * distance}; + easeddesign.end_direction = along; + } + // the bends stay where they are, measured from the ends moved + if (easeddesign.vertices.size() >= 2 && shape.vertices.size() == easeddesign.vertices.size()) + { + easeddesign.vertices.front().offset = std::max(0.1, glm::dot(shape.vertices.front() - plan_of(easeddesign.start), glm::normalize(easeddesign.start_direction))); + easeddesign.vertices.back().offset = std::max(0.1, glm::dot(plan_of(easeddesign.end) - shape.vertices.back(), glm::normalize(easeddesign.end_direction))); + } + auto const easedshape{alignment::ease_corners(easeddesign, plan.corners, {}, bends_fit())}; + if (easedshape.valid) + { + Length = editor_track::eased_length(in, easedshape.length, out); + Error = lines_of(easedshape.warnings); + pieces = editor_track::eased_pieces(in, alignment::pieces(easedshape, easeddesign, count(easedshape, easeddesign)), out); + plan.design = easeddesign; + plan.shape = easedshape; + } + else + Error = STR("The curvature changes abruptly where the track joins, there's no room for a transition curve") + (easedshape.errors.empty() ? std::string{} : ": " + easedshape.errors.front()); + } + if (pieces.empty()) + { + Length = shape.length; + pieces = alignment::pieces(shape, design, count(shape, design)); + // a line lay_line begins at the end of the transition out of the curve of the free end keeps the transition before it + auto const after = [&](editor_track::easing const &Easing, glm::dvec3 const &Joint, glm::dvec3 const &Own) { return false == Easing.pieces.empty() && plan_distance(Joint, Own) > 0.01; }; + auto const &before{after(in, Points.front(), design.start) ? in : editor_track::easing{}}; + auto const &beyond{after(out, Points.back(), design.end) ? out : editor_track::easing{}}; + Length = editor_track::eased_length(before, Length, beyond); + pieces = editor_track::eased_pieces(before, pieces, beyond); + } + // the heights: fitted to the ground, or from point to point through the points clicked + TTrack const *style{tool.start.track != nullptr ? tool.start.track : End.track != nullptr ? End.track : tool.copy_selected ? selected_track() : nullptr}; + auto const grade0{tool.start.track != nullptr ? -grade_of(tool.start.direction) : unknown}; + auto const grade1{End.track != nullptr ? grade_of(End.direction) : unknown}; + if (EditorSettings.heights() == editorSettings::lay_heights::fitted) + follow_ground(pieces, Points.front().y, grade0, Points.back().y, grade1, style); + else + ground_follow::follow_points(pieces, plan.knots, {Points.front().y, grade0, Points.back().y, grade1}); + if (tool.start.track != nullptr) + lead_cant(pieces, -editor_track::joint_roll(*tool.start.track, tool.start.point), design.norms.gauge, true); + if (End.track != nullptr) + lead_cant(pieces, editor_track::joint_roll(*End.track, End.point), design.norms.gauge, false); + if (Plan != nullptr) + *Plan = std::move(plan); + return pieces; +} + +bool editor_mode::traced_from(std::vector const &Points, std::vector const &Modes, bool const AtEnd) +{ + if (Points.size() < (AtEnd ? 3u : 2u)) + return false; + auto const index{AtEnd ? Points.size() - 2 : std::size_t{1}}; + return index < Modes.size() && Modes[index] == lay_mode::curve; +} + +bool editor_mode::lay_line(std::vector const &Points, std::vector const &Modes, editor_track::snap_target const &End, lay_line_plan &Plan, std::string &Error, bool const Adjoining) const +{ + auto const &tool{m_lay}; + Plan = {}; + auto &design{Plan.design}; + design.norms = laying_norms(); + design.shape = m_route.design.shape; + design.speed = design_speed(tool.start.track, End.track); + design.start = Points.front(); + auto const joined{End.track != nullptr && glm::length(plan_of(End.direction)) > 1e-6}; + // from a free end on a curve, or to one, the curve laid next to it turning its way goes on from its curvature: it begins right at the + // end, not on a straight, its transition going from that curvature. A line which doesn't turn its way begins from a straight there: out + // of the curve of a plain track by the transition lay_pieces lays, right at the end of the diverging track of a switch, as the switch + // goes on with a straight. The curve goes on only with a curve traced from it, the bends of straights begin with a straight + if (Adjoining) + { + if (tool.start.track != nullptr && glm::length(plan_of(tool.start.direction)) > 1e-6) + adjoining_curve(tool.start, false, traced_from(Points, Modes, false), design.norms.gauge, design); + if (joined) + adjoining_curve(End, true, traced_from(Points, Modes, true), design.norms.gauge, design); + } + auto const curved{design.start_curved || design.end_curved}; + auto const from_straight = [&]() { return curved && lay_line(Points, Modes, End, Plan, Error, false); }; + // the end of the transition out of the curve of the free end, the start of the line where a curve traced next to it is laid from a + // straight there; the same at the end + std::optional> easedstart; + std::optional> easedend; + // the points between the start and the end: a free end reached is the last point + auto const inner{Points.size() - (joined ? 1 : 0)}; + auto const mode_of = [&](std::size_t const Index) { return Index < Modes.size() ? Modes[Index] : lay_mode::straights; }; + auto const lifted = [](glm::dvec2 const &Point, double const Height) { return glm::dvec3{Point.x, Height, Point.y}; }; + auto const apart = [&](glm::dvec2 const &Direction) { + if (glm::length(Direction) > 1e-6) + return true; + Error = STR_C("Two points lie on one another"); + return false; + }; + + // the straight the line goes on along: a point of it and, where it's fixed, its direction + auto anchor{Points.front()}; + std::optional along; + if (tool.start.track != nullptr && glm::length(plan_of(tool.start.direction)) > 1e-6) + along = glm::normalize(-plan_of(tool.start.direction)); + auto const startdirection{along}; + struct bend + { + glm::dvec3 position{0.0}; + alignment::vertex vertex; + bool corner{true}; + }; + std::vector bends; + // a bend clicked after a straight of a fixed direction goes onto it, as far along it as it was clicked + auto const onto = [&](glm::dvec3 const &Point) { + auto const distance{std::max(1.0, glm::dot(plan_of(Point - anchor), *along))}; + Plan.guides.emplace_back(anchor, lifted(plan_of(anchor) + *along * (distance + std::max(30.0, 0.2 * distance)), anchor.y)); + return lifted(plan_of(anchor) + *along * distance, Point.y); + }; + // the straights meet where the two lines cross, ahead of both points + auto const meeting = [](glm::dvec2 const &From, glm::dvec2 const &Along, glm::dvec2 const &To, glm::dvec2 const &Arriving, glm::dvec2 &Point) { + double t, u; + if (false == geometry::lines_cross(From, Along, To, Arriving, t, u) || t <= 0.0 || u <= 0.0) + return false; + Point = From + Along * t; + return true; + }; + auto const straight_bend = [&](glm::dvec3 Point) { + if (along.has_value()) + { + Point = onto(Point); + along.reset(); + } + bends.push_back({Point, {}, true}); + anchor = Point; + }; + + std::size_t i{1}; + while (i < inner) + { + auto last{i}; + while (last < inner && mode_of(last) == lay_mode::curve) + ++last; + auto const reaching{last == inner && joined}; + // the stretch right from the free end the line starts at, and whether the curve of the end goes on into it: where it turns its way + auto const fromend{bends.empty() && Plan.traces.empty() && along.has_value()}; + auto const goes_on = [&](glm::dvec2 const &Heading) { return fromend && design.start_curved && cross(*along, Heading) * design.start_turn > 1e-9; }; + // a line from the end of the diverging track of a switch which doesn't go on with its curve begins with a straight right there + auto const switched = [](editor_track::snap_target const &Joint) { return Joint.track != nullptr && Joint.track->eType == tt_Switch; }; + auto const straight_from_end = [&]() { + if (fromend && switched(tool.start)) + design.start_curved = false; + }; + // one point of a curve right after a free end on a curve: the curve of the end goes on as far as abreast of the point, seen from + // its centre, the line ending on it there; the curve fitted to the points once more of them are clicked + if (i == 1 && last == 2 && false == reaching && fromend && design.start_curved && design.start_radius > 0.0) + { + auto const radius{design.start_radius}; + auto const side{design.start_turn > 0 ? 1.0 : -1.0}; + auto const from{plan_of(anchor)}; + glm::dvec2 const inward{-along->y * side, along->x * side}; + auto const centre{from + inward * radius}; + auto const outward{plan_of(Points[1]) - centre}; + if (glm::length(outward) > 0.5) + { + // how far round the curve turns to there + auto sweep{std::fmod(side * (std::atan2(outward.y, outward.x) - std::atan2(from.y - centre.y, from.x - centre.x)), 2.0 * glm::pi())}; + if (sweep < 0.0) + sweep += 2.0 * glm::pi(); + if (sweep > 1e-3 && sweep < glm::pi()) + { + alignment::vertex curve; + curve.radius = radius; + curve.cant = design.start_cant; + bends.push_back({lifted(from + *along * (radius * std::tan(0.5 * sweep)), anchor.y), curve, false}); + anchor = lifted(centre + glm::normalize(outward) * radius, Points[1].y); + along = turned(*along, side * sweep); + i = last; + continue; + } + } + } + // a bend of straights, or a point of a curve too alone to make one + if (last == i || (last - i < 2 && false == reaching)) + { + straight_from_end(); + straight_bend(Points[i]); + ++i; + continue; + } + lay_trace trace; + std::vector traced; + for (auto k{i}; k < last; ++k) + { + trace.points.push_back(Points[k]); + traced.push_back(plan_of(Points[k])); + } + i = last; + // the straight the curve comes from: the one of the free end or of the curve before, else the one through the last two + // points clicked before the curve, the last of them then no bend + auto entry{anchor}; + glm::dvec2 entering; + // how far back the curve may begin before the point it comes from: up to the bend or the start before it, half the way back + // to a curve traced before, nothing before a free end + double behind{0.0}; + // the first point clicked, with no heading of its own: the curve fitted may start out of it any way + auto loose{false}; + if (along.has_value()) + { + entering = *along; + if (false == bends.empty()) + behind = 0.5 * plan_distance(entry, bends.back().position); + } + else if (false == bends.empty() && bends.back().corner) + { + entry = bends.back().position; + bends.pop_back(); + auto const before{bends.empty() ? Points.front() : bends.back().position}; + entering = plan_of(entry - before); + behind = plan_distance(entry, before) * (bends.empty() || bends.back().corner ? 1.0 : 0.5); + } + else + { + entering = traced.front() - plan_of(anchor); + loose = bends.empty(); + } + if (false == apart(entering)) + return false; + entering = glm::normalize(entering); + // where the curve ends: at the free end the line finishes at, else at the last point clicked, heading as the circle through the last + // three points does there; a point clicked after it in the mode of the straights, the curve heads for it there, the straight + // to it as clicked + auto exit{trace.points.back()}; + glm::dvec2 leaving; + auto const headed{false == reaching && last < inner}; + if (reaching) + { + exit = End.position; + leaving = glm::normalize(plan_of(End.direction)); + } + else if (headed) + { + leaving = plan_of(Points[last]) - plan_of(exit); + if (false == apart(leaving)) + return false; + leaving = glm::normalize(leaving); + } + else + { + std::vector chain{plan_of(entry)}; + chain.insert(chain.end(), traced.begin(), traced.end()); + leaving = heading_at_end(chain); + if (false == apart(leaving)) + return false; + leaving = glm::normalize(leaving); + } + auto base{design}; + base.start = entry; + base.start_direction = entering; + base.end = exit; + base.end_direction = leaving; + // the curve may begin before the point the straight was clicked at; it ends where the last point is + base.start_reserve = behind; + base.end_reserve = 0.0; + // the curve of the free end it starts at goes on into it where it turns its way, as the one of the free end it finishes at; + // otherwise it begins, or ends, from a straight there: right at a switch, out of the curve of a plain track by a transition + std::vector fitted_points{traced}; + auto const easing = [&](editor_track::snap_target const &Joint) { return switched(Joint) ? editor_track::easing{} : editor_track::ease_out_of(*Joint.track, Joint.position, 0.0, design.speed, design.norms); }; + base.start_curved = goes_on(leaving); + if (fromend && design.start_curved && false == base.start_curved) + { + design.start_curved = false; + if (auto const in{easing(tool.start)}; false == in.pieces.empty()) + { + base.start = in.end; + base.start_direction = in.direction; + easedstart = std::make_pair(in.end, in.direction); + std::erase_if(fitted_points, [&](glm::dvec2 const &Point) { return glm::distance(Point, plan_of(entry)) <= in.length; }); + } + } + base.end_curved = reaching && design.end_curved && cross(entering, leaving) * design.end_turn > 1e-9; + if (reaching && design.end_curved && false == base.end_curved) + { + design.end_curved = false; + if (auto const out{easing(End)}; false == out.pieces.empty()) + { + base.end = out.end; + base.end_direction = -out.direction; + easedend = std::make_pair(out.end, -out.direction); + std::erase_if(fitted_points, [&](glm::dvec2 const &Point) { return glm::distance(Point, plan_of(exit)) <= out.length; }); + } + } + { + auto const fit_to = [&](glm::dvec2 const &Leaving, bool const Meanwhile, bool &Exact) { + auto trial{base}; + trial.end_direction = Leaving; + return fitted_points.empty() ? std::optional{alignment::trace_stretch{}} : traced_stretch(trial, fitted_points, tool.radii, tool.straights_between, Meanwhile, &Exact); + }; + // a curve going on from the curve of the free end the line starts at: fitted as its curvature runs from that of the end to the + // last point, where it ends on the straight it comes out to; between the straights only where no such curve follows the points + bool exact{true}; + std::optional fitted; + std::optional going; + if (base.start_curved && false == reaching && false == headed && false == fitted_points.empty()) + if (auto const along{traced_stretch(base, fitted_points, tool.radii, tool.straights_between, true, &exact, true)}; along.has_value() && along->valid) + going = along; + // from a switch the curve goes on at its radius; where that doesn't keep to the points, m, and they show a straight right at the + // switch, as the switch goes on with one, the curve fitted from it beginning a few metres on at least, not a curve of another + // radius right there, and keeping to them much closer, that one + constexpr double kGoingClose{0.08}; + constexpr double kGoingWithin{0.3}; + constexpr double kStraightFirst{5.0}; + if (going.has_value() && base.start_held && (going->rms > kGoingClose || going->worst > kGoingWithin)) + { + auto straight{base}; + straight.start_curved = false; + auto const straight_first = [&](alignment::trace_stretch const &Fit) { + if (Fit.vertices.empty()) + return true; + auto trial{straight}; + trial.vertices = Fit.vertices; + trial.norms.checked = false; + auto const laid{alignment::compute(trial)}; + return laid.valid && false == laid.elements.empty() && laid.elements.front().kind == alignment::element_kind::straight && laid.elements.front().length >= kStraightFirst; + }; + if (auto const other{traced_stretch(straight, fitted_points, tool.radii, tool.straights_between, true)}; other.has_value() && other->valid && other->rms < 0.75 * going->rms && straight_first(*other)) + { + // the jump of the curvature there the switch has as it has one at its start: nothing to warn of + going.reset(); + base.start_curved = false; + design.start_curved = false; + design.start_radius = 0.0; + design.start_turn = 0; + } + } + // the same into the curve of the free end the line finishes at, from the first point clicked: fitted from that end back, the + // line starting from the first point on the straight the curve comes out of + std::optional into; + if (false == going.has_value() && reaching && base.end_curved && loose && false == fitted_points.empty()) + { + auto back{base}; + back.start = base.end; + back.start_direction = -leaving; + back.start_curved = true; + back.start_held = base.end_held; + back.start_radius = base.end_radius; + back.start_turn = -base.end_turn; + back.start_cant = base.end_cant; + back.end = entry; + back.end_direction = -entering; + back.end_curved = false; + back.end_held = false; + back.start_reserve = back.end_reserve = 0.0; + std::vector points{fitted_points.rbegin(), fitted_points.rend()}; + points.push_back(plan_of(entry)); + if (auto const fit{traced_stretch(back, points, tool.radii, tool.straights_between, true, &exact, true)}; fit.has_value() && fit->valid && false == fit->vertices.empty()) + into = turned_round(*fit); + } + if (going.has_value()) + { + fitted = going; + leaving = going->leaving; + base.end_direction = leaving; + // the arc of a switch going on ends abreast of the last point + exit = lifted(going->ending, exit.y); + } + else if (into.has_value()) + { + fitted = into; + entering = into->leaving; + base.start_direction = entering; + } + else + fitted = fit_to(leaving, true, exact); + // the curve ends at the last point: where the one fitted ends short of it, the straight after it going on to the point, the line + // leaves the point turning more, by bisection where it turns too much for a curve to reach the point. A few fits more, done on + // the thread from frame to frame while the cursor moves + if (false == going.has_value() && false == reaching && false == headed && exact && fitted.has_value() && fitted->valid && false == fitted->vertices.empty()) + { + // how far along the line laid its curves reach + auto const curves_reach = [](alignment::result const &Laid) { + double reach{0.0}; + for (auto const &element : Laid.elements) + if (element.kind != alignment::element_kind::straight) + reach = std::max(reach, element.chainage + element.length); + return reach; + }; + // the radius the last curve ends with + auto const end_radius = [](alignment::vertex const &Vertex) { return std::max(10.0, Vertex.arcs.empty() ? Vertex.radius : Vertex.arcs.back().radius); }; + auto const short_of = [&](alignment::trace_stretch const &Fit, glm::dvec2 const &Leaving) -> std::optional { + if (false == Fit.valid) + return std::nullopt; + auto trial{base}; + trial.end_direction = Leaving; + trial.vertices = Fit.vertices; + trial.norms.checked = false; + auto const laid{alignment::compute(trial)}; + if (false == laid.valid) + return std::nullopt; + return laid.length - curves_reach(laid); + }; + auto const turn{cross(entering, leaving) >= 0.0 ? 1.0 : -1.0}; + auto const turned = [&](double const Angle) { return geometry::turned(leaving, turn * Angle); }; + auto const ending{end_radius(fitted->vertices.back())}; + // the last two points clicked on the straight after the curve, as the mode asks for: the straight goes through them, the curve + // fitted with their heading ending before them; before the last one alone, where the last three points show a line much + // flatter than the end of the curve. Only points showing the curve going on draw it on to the last one + // a fit of the straight clicked after the curve is still on the thread + bool straight_waiting{false}; + auto const clicked_straight = [&]() -> std::optional> { + constexpr double kFlatter{4.0}; + auto const count{fitted_points.size()}; + if (count < 4) + return std::nullopt; + auto const chord{fitted_points[count - 1] - fitted_points[count - 2]}; + if (glm::length(chord) < 1e-6) + return std::nullopt; + auto const fitted_heading = [&](glm::dvec2 const &Heading) -> std::optional { + bool again{true}; + auto const fit{fit_to(Heading, false, again)}; + if (false == fit.has_value()) + straight_waiting = true; + if (false == fit.has_value() || false == fit->valid || fit->vertices.empty()) + return std::nullopt; + return fit; + }; + auto const chorded{glm::normalize(chord)}; + auto heading{chorded}; + // the heading of two points clicked a little off is a little off too: turned a bit either way, and to where the closeness + // to all the points says the bottom is, the heading the curve keeps closest to them with. A few fits more, done on the + // thread from frame to frame while the cursor moves + auto const rotated = [&](double const Angle) { return geometry::turned(chorded, Angle); }; + // none for points clicked as closely as this: their heading is good as it is + constexpr double kClose{0.05}; + auto const step{std::clamp(0.5 / glm::length(chord), 0.002, 0.03)}; + auto fit{fitted_heading(heading)}; + if (false == fit.has_value()) + { + // the two turned either way asked for with it, the thread fitting them one after another, not a frame after + if (straight_waiting && tool.whole) + { + fitted_heading(rotated(-step)); + fitted_heading(rotated(step)); + } + return std::nullopt; + } + auto const minus{fit->rms > kClose ? fitted_heading(rotated(-step)) : std::nullopt}; + auto const plus{fit->rms > kClose ? fitted_heading(rotated(step)) : std::nullopt}; + if (minus.has_value() && plus.has_value()) + { + auto const centre{fit->rms}; + auto angle{0.0}; + if (minus->rms < fit->rms) + { + fit = minus; + angle = -step; + } + if (plus->rms < fit->rms) + { + fit = plus; + angle = step; + } + if (auto const bend{minus->rms - 2.0 * centre + plus->rms}; bend > 1e-12) + { + auto const bottom{std::clamp(0.5 * step * (minus->rms - plus->rms) / bend, -2.0 * step, 2.0 * step)}; + if (auto const there{fitted_heading(rotated(bottom))}; there.has_value() && there->rms < fit->rms) + { + fit = there; + angle = bottom; + } + } + heading = rotated(angle); + } + auto trial{base}; + trial.end_direction = heading; + trial.vertices = fit->vertices; + trial.norms.checked = false; + auto const laid{alignment::compute(trial)}; + if (false == laid.valid) + return std::nullopt; + auto const reach{curves_reach(laid)}; + auto const projections{alignment::project(laid, {fitted_points[count - 2], fitted_points[count - 1]})}; + if (projections.size() < 2 || projections[1].chainage < reach) + return std::nullopt; + if (projections[0].chainage < reach) + { + // the circle through the last three points + auto const before{fitted_points[count - 2] - fitted_points[count - 3]}; + auto const turn{std::abs(cross(before, chord))}; + auto const circle{turn > 1e-12 ? glm::length(before) * glm::length(chord) * glm::length(before + chord) / (2.0 * turn) : std::numeric_limits::max()}; + if (circle < kFlatter * end_radius(fit->vertices.back())) + return std::nullopt; + } + return std::make_pair(*fit, heading); + }; + auto const first{short_of(*fitted, leaving)}; + auto const straight{first.has_value() && *first > 0.5 ? clicked_straight() : std::nullopt}; + if (straight.has_value()) + { + fitted = straight->first; + leaving = straight->second; + base.end_direction = leaving; + } + else if (straight_waiting && tool.whole) + { + // the line waits for the straight: no more turns asked for meanwhile, the thread fitting them before it + } + else if (first.has_value() && *first > 0.5) + { + auto low{0.0}; + auto lowshort{*first}; + std::optional high; + auto best{fitted}; + auto bestangle{0.0}; + // by 15 degrees at most: more is no longer the heading the points show + constexpr double kMost{0.26}; + auto angle{std::min(kMost, lowshort / ending)}; + // the turn the line before was given first: the cursor has moved on a little since, it's near enough most often + if (tool.whole && m_turned_last > 0.0) + angle = std::min(kMost, m_turned_last); + auto waited{false}; + for (int i = 0; i < 8; ++i) + { + bool again{true}; + auto const trial{fit_to(turned(angle), false, again)}; + if (false == trial.has_value()) + { + waited = true; + break; + } + if (auto const left{short_of(*trial, turned(angle))}; left.has_value() && *left >= 0.0) + { + low = angle; + lowshort = *left; + best = trial; + bestangle = angle; + if (lowshort <= 0.5) + break; + } + else + high = angle; + if (false == high.has_value() && low >= kMost) + break; + angle = high.has_value() ? 0.5 * (low + *high) : std::min(kMost, low + lowshort / ending); + } + if (false == waited) + m_turned_last = bestangle; + fitted = best; + leaving = turned(bestangle); + base.end_direction = leaving; + } + } + if (false == fitted.has_value()) + { + Error = STR_C("Fitting the curve to the points..."); + return false; + } + auto const &fit{*fitted}; + if (false == fit.valid) + { + Error = STR_C("No curve follows the points clicked along it"); + return from_straight(); + } + for (auto const &vertex : fit.vertices) + bends.push_back({lifted(vertex.position, entry.y), vertex, false}); + if (fit.vertices.empty()) + { + // a straight: the two lines are one + exit = lifted(plan_of(entry) + entering * glm::dot(plan_of(exit - entry), entering), exit.y); + leaving = entering; + } + trace.offsets = fit.offsets; + trace.rms = fit.rms; + trace.worst = fit.worst; + trace.curves = fit.vertices.size(); + } + Plan.traces.push_back(std::move(trace)); + anchor = exit; + along = leaving; + } + + // the end: the free end reached, the end of a curve traced, or the last point clicked + glm::dvec3 end; + glm::dvec2 ending; + if (joined) + { + end = End.position; + ending = glm::normalize(plan_of(End.direction)); + if (along.has_value() && (false == bends.empty() || false == Plan.traces.empty())) + { + // from the straight out of a curve traced to the one of the free end: a bend where they meet + glm::dvec2 corner; + if (meeting(plan_of(anchor), *along, plan_of(end), -ending, corner)) + bends.push_back({lifted(corner, anchor.y), {}, true}); + } + } + else if (along.has_value()) + { + end = anchor; + ending = *along; + } + else + { + if (bends.empty()) + { + Error = STR_C("Click at least two points"); + return false; + } + end = bends.back().position; + bends.pop_back(); + ending = plan_of(end) - plan_of(bends.empty() ? Points.front() : bends.back().position); + if (false == apart(ending)) + return false; + ending = glm::normalize(ending); + } + if (plan_distance(end, Points.front()) < 1.0) + { + Error = STR_C("Click at least two points"); + return false; + } + design.end = end; + design.end_direction = ending; + if (startdirection.has_value()) + design.start_direction = *startdirection; + else + { + auto const first{plan_of(bends.empty() ? end : bends.front().position) - plan_of(Points.front())}; + if (false == apart(first)) + return false; + design.start_direction = glm::normalize(first); + } + if (easedstart.has_value()) + std::tie(design.start, design.start_direction) = *easedstart; + if (easedend.has_value()) + { + std::tie(design.end, design.end_direction) = *easedend; + end = design.end; + } + // the last bend goes onto the line of the free end, as far before it as it was clicked: one clicked past it would come into the end + // the wrong way, the joint turned round + if (joined && false == bends.empty() && bends.back().corner && glm::dot(plan_of(end - bends.back().position), design.end_direction) <= 0.0) + { + Error = STR_C("The last point clicked lies past the free end: the track can't come into it from there"); + return false; + } + for (auto const &bend : bends) + { + auto vertex{bend.corner ? alignment::vertex{} : bend.vertex}; + vertex.position = plan_of(bend.position); + design.vertices.push_back(vertex); + Plan.corners.push_back(bend.corner ? 1 : 0); + } + if (design.vertices.size() >= 2) + { + design.vertices.front().offset = glm::dot(plan_of(bends.front().position - design.start), design.start_direction); + design.vertices.back().offset = glm::dot(plan_of(end - bends.back().position), design.end_direction); + } + Plan.shape = alignment::ease_corners(design, Plan.corners, {}, bends_fit()); + if (false == Plan.shape.valid) + { + Error = Plan.shape.errors.empty() ? std::string{STR_C("The track can't be laid through these points")} : Plan.shape.errors.front(); + return from_straight(); + } + // the grade breaks at the bends which stayed bends; along a curve, traced or made of bends, it goes on even from end to end + for (std::size_t k = 0; k < design.vertices.size() && k < Plan.corners.size(); ++k) + { + if (Plan.corners[k] != 1) + continue; + for (auto const &bend : bends) + if (bend.corner && glm::distance(plan_of(bend.position), design.vertices[k].position) < 1e-3) + { + Plan.knots.push_back(bend.position); + break; + } + } + return true; +} + +std::optional editor_mode::traced_stretch(alignment::design const &Base, std::vector const &Points, int const Radii, bool const Straights, bool const Meanwhile, + bool *Exact, bool const Going) const +{ + if (Exact != nullptr) + *Exact = true; + // the stretches traced before the one the cursor moves along are the same from frame to frame: their fits are kept + // the curves of the adjoining tracks it goes on from or into, signed by their turn, and their cants + auto const curvature = [](bool const Curved, double const Radius, int const Turn) { return Curved && Radius > 0.0 ? Turn / Radius : 0.0; }; + std::vector key{Base.start.x, Base.start.z, Base.start_direction.x, Base.start_direction.y, Base.end.x, Base.end.z, Base.end_direction.x, Base.end_direction.y, Base.speed, + static_cast(Base.shape), static_cast(Radii), Straights ? 1.0 : 0.0, Base.start_reserve, Base.end_reserve, + curvature(Base.start_curved, Base.start_radius, Base.start_turn), Base.start_curved ? Base.start_cant : 0.0, curvature(Base.end_curved, Base.end_radius, Base.end_turn), + Base.end_curved ? Base.end_cant : 0.0, (Going ? 1.0 : 0.0) + (Base.start_held ? 2.0 : 0.0) + (Base.end_held ? 4.0 : 0.0)}; + for (auto const &point : Points) + { + key.push_back(point.x); + key.push_back(point.y); + } + auto &cache{m_stretch_cache}; + for (auto entry{cache.begin()}; entry != cache.end(); ++entry) + if (entry->first == key) + { + std::rotate(cache.begin(), entry, std::next(entry)); + return cache.front().second; + } + auto const keep = [&](alignment::trace_stretch const &Fit) { + cache.insert(cache.begin(), {key, Fit}); + if (cache.size() > 16) + cache.pop_back(); + }; + alignment::trace_stretch fit; + if (false == m_follow_preview) + { + fit = Going ? alignment::fit_going_on(Base, Points) : alignment::fit_trace_stretch(Base, Points, Radii, Straights); + keep(fit); + return fit; + } + // shown while the cursor moves: fitted on the thread, the frames meanwhile drawn with the fit done last for the same points but + // the one at the cursor, or with no curve yet + if (m_stretch_fitter.done(key, fit)) + { + keep(fit); + return fit; + } + m_fits_waiting = true; + m_stretch_fitter.ask({key, Base, Points, Radii, Straights, Going}); + std::vector last; + auto const header{std::size_t{19}}; + if (Meanwhile && m_stretch_fitter.latest(last, fit) && last.size() >= header + 2 && key.size() >= header + 2 && std::equal(key.begin(), key.begin() + 4, last.begin()) && + std::equal(key.begin() + 8, key.begin() + header, last.begin() + 8)) + { + auto const common{std::min(last.size(), key.size()) - 2}; + if (std::equal(key.begin() + header, key.begin() + common, last.begin() + header)) + { + if (Exact != nullptr) + *Exact = false; + return fit; + } + } + return {}; +} + +void editor_mode::lay_trim() +{ + auto &tool{m_lay}; + tool.modes.resize(tool.points.size(), lay_mode::straights); +} + +void editor_mode::lay_switch_mode() +{ + auto &tool{m_lay}; + tool.mode = tool.mode == lay_mode::straights ? lay_mode::curve : lay_mode::straights; + m_track_layout = tool.mode == lay_mode::curve ? track_layout::arc_straight : track_layout::straight; + if (tool.mode == lay_mode::curve) + first_step_done(first_step::trace); + tool.status = tool.mode == lay_mode::curve ? STR("Curve: click points along the middle of the track, the curve ends at the last one. Tab: back to the straights") + : STR("Straights: each point clicked is a bend of the straights, eased with a large curve. Tab: a curve traced on the photo"); + tool.status_time = ImGui::GetTime(); +} + +void editor_mode::lay_click() +{ + auto &tool{m_lay}; + tool.status.clear(); + lay_trim(); + auto const snap{tool.mouse_snap}; + if (snap.track != nullptr && false == tool.points.empty() && glm::distance(snap.position, tool.points.front()) > 1.0) + { + // reaching a free end finishes the track there, in line with the path it joins + tool.points.push_back(snap.position); + tool.modes.push_back(tool.mode); + lay_finish(snap); + return; + } + if (tool.points.empty()) + { + tool.start = snap; + auto point{snap.track != nullptr ? snap.position : tool.mouse}; + if (auto const *axis{snap.track == nullptr && ImGui::GetIO().KeyAlt ? skew_reference(point, point, kSkewSeat) : nullptr}) + { + auto const &path{axis->m_paths.front()}; + auto const &from{path.points[segment_data::point::start]}; + auto const &to{path.points[segment_data::point::end]}; + auto const along{std::clamp(glm::dot(plan_of(point - from), plan_of(to - from)) / glm::dot(plan_of(to - from), plan_of(to - from)), 0.0, 1.0)}; + point = from + (to - from) * along; + } + tool.points.push_back(point); + tool.modes.push_back(tool.mode); + return; + } + // the points only make the line shown: it's laid by Enter, or by a click on a free end + auto const &point{tool.mouse}; + if (plan_distance(point, tool.points.back()) < 1.0) + return; + m_typed.clear(); + tool.points.push_back(point); + tool.modes.push_back(tool.mode); +} + +void editor_mode::lay_finish(editor_track::snap_target const &End) +{ + auto &tool{m_lay}; + lay_trim(); + double length; + std::string error; + lay_line_plan plan; + auto const pieces{lay_pieces(tool.points, tool.modes, End, length, error, &plan)}; + auto const eased{m_eased_last}; + tool.status_time = ImGui::GetTime(); + if (pieces.empty()) + { + tool.status = error.empty() ? std::string{STR_C("Click at least two points")} : error; + if (End.track != nullptr && false == tool.points.empty()) + { + tool.points.pop_back(); + lay_trim(); + } + return; + } + auto const *style{tool.start.track != nullptr ? tool.start.track : End.track}; + if (style == nullptr && tool.copy_selected) + style = selected_track(); + // the track laid takes only its heights from the ground: the terrain is shaped under it by the buttons of the terrain model + m_nmt_state.laying = true; + std::vector created; + for (auto const &piece : pieces) + created.push_back(style != nullptr ? editor_track::create_path(*style, piece) : editor_track::create_path(tool.style, piece)); + give_own_speed(created); + editor_track::commit(created); + // the scenery keeps the design the tracks were laid by, as it is, for the plan to edit; read from the paths again it wouldn't be + // the same, a compound curve with transitions between its arcs least of all. A track laid with no design of the line, between two + // free ends or back from one, keeps none: the plan reads its curves when it's opened + // with the points clicked, which the plan fits the curves to again when their transitions or cants change + if (plan.shape.valid && false == created.empty() && false == scene::Layers.empty()) + alignment_store::store(plan.design, plan.shape, 0.0, alignment_store::layer_of(*created.front()), "drawn", 0.0, tool.points); + tool.history = m_history.size(); + push_track_snapshot({}, created); + first_step_done(first_step::laid); + if (plan.shape.valid && false == plan.shape.curves.empty()) + first_step_done(first_step::bend); + if (End.track != nullptr) + first_step_done(first_step::join); + tool.status = format(STR_P("Laid %.1f m of track in %zu piece, Ctrl+Z takes it back", "Laid %.1f m of track in %zu pieces, Ctrl+Z takes it back", static_cast(created.size())), length, created.size()); + if (false == error.empty()) + tool.status += "\n" + error; + if (eased.has_value() && eased->compound) + tool.status += "\n" + format(STR_C("Compound curve: R %.0f m goes on into R %.0f m through a transition curve of %.0f m"), eased->from_radius, eased->radius, eased->entry); + // the curves next to the free ends going on from the curves of their tracks + if (plan.shape.valid) + for (auto const &curve : plan.shape.curves) + if (auto const on{curve_goes_on(curve)}; false == on.empty()) + tool.status += "\n" + format(STR_C("Curve %d %s"), curve.vertex + 1, on.c_str()); + if (eased.has_value() && false == eased->note.empty()) + tool.status += "\n" + eased->note; + for (auto const &warning : switch_exit_warnings(tool.start.track, tool.points.front(), End.track, End.position, pieces)) + tool.status += "\n" + warning; + { + std::vector> run; + if (tool.start.track != nullptr && tool.start.track->eType == tt_Normal) + run.emplace_back(tool.start.track, tool.start.point.kind == editor_track::point_kind::end); + for (auto *track : created) + run.emplace_back(track, true); + if (End.track != nullptr && End.track->eType == tt_Normal) + run.emplace_back(End.track, End.point.kind == editor_track::point_kind::start); + editor_track::curve curve; + if (run.size() > created.size() && editor_track::analyse_curve(run, m_route.design.norms.gauge, curve) && curve.compound) + for (std::size_t i = 1; i < curve.arcs.size(); ++i) + if (curve.arcs[i].transition < 1.0) + { + tool.status += "\n" + format(STR_C("Compound curve: R %.0f m meets R %.0f m with no transition curve between them"), curve.arcs[i - 1].radius, curve.arcs[i].radius); + break; + } + } + if (scene::Layers.active() == null_handle && style == nullptr) + tool.status += "\n" + STR("The scenery isn't opened for editing: new track won't be saved"); + m_node = created.back(); + ui()->set_node(m_node); + if (nmt_fit_laid(tool.history, created.back()->m_paths.front().points[segment_data::point::end])) + tool.status += "\n" + STR("The grade line of the whole track laid in a row fitted to the terrain model, as the tracks go onto the terrain"); + m_nmt_state.laying = false; + nmt_check_buried(tool.history); + WriteLog("Editor: " + tool.status, logtype::generic); + tool.points.clear(); + tool.modes.clear(); + tool.start = {}; + straight_refresh(); +} + +void editor_mode::lay_enter() +{ + auto &tool{m_lay}; + if (false == m_typed.empty()) + { + lay_click(); + return; + } + lay_trim(); + if (tool.points.empty()) + return; + auto const end{tool.mouse_snap}; + if (end.track != nullptr && glm::distance(end.position, tool.points.front()) > 1.0) + { + tool.points.push_back(end.position); + tool.modes.push_back(tool.mode); + lay_finish(end); + return; + } + // a single point is no track: Enter drops it + if (tool.points.size() < 2) + { + lay_cancel(); + return; + } + // the laying ends with the track laid: the next click starts anew where it's made, a click on the free end left goes on from + // it. Going on by itself, a click made elsewhere afterwards led a loop out of that end to it + lay_finish({}); +} + +void editor_mode::lay_cancel() +{ + auto &tool{m_lay}; + tool.points.clear(); + tool.modes.clear(); + tool.start = {}; + tool.preview.clear(); + tool.plan = {}; + tool.status.clear(); +} + +std::size_t editor_mode::lay_pending() const +{ + return m_lay.points.size(); +} + +void editor_mode::lay_escape() +{ + auto &tool{m_lay}; + lay_trim(); + // the points clicked are no track yet and nothing brings them back: a slip of Esc only warns, the second one drops them + auto const pending{lay_pending()}; + if (tool.points.size() < 2 || ImGui::GetTime() - tool.escape_time < 3.0) + { + lay_cancel(); + tool.escape_time = -100.0; + return; + } + tool.escape_time = ImGui::GetTime(); + tool.status = format(STR_P("Esc again drops the point not laid, Enter lays it", "Esc again drops the %zu points not laid, Enter lays them", static_cast(pending)), pending); + tool.status_time = tool.escape_time; +} + +void editor_mode::lay_after_history(bool const Undo) +{ + auto &tool{m_lay}; + if (tool.points.empty()) + return; + if (false == Undo) + { + lay_cancel(); + return; + } + // the free end the points go on from taken back + if (tool.start.track != nullptr && tool.start.track->m_editorremoved) + lay_cancel(); +} + +void editor_mode::lay_back() +{ + auto &tool{m_lay}; + lay_trim(); + // the points not laid yet, the last one first; the tracks laid go back with Ctrl+Z + if (tool.points.size() > 1) + { + tool.points.pop_back(); + tool.modes.pop_back(); + return; + } + tool.points.clear(); + tool.modes.clear(); + tool.start = {}; +} + +glm::dvec3 editor_mode::lay_angle_snap(glm::dvec3 const &Mouse, std::string &Label) const +{ + Label.clear(); + auto const &last{m_lay.points.back()}; + glm::dvec2 const offset{Mouse.x - last.x, Mouse.z - last.z}; + auto const length{glm::length(offset)}; + if (length < 1.0) + return Mouse; + auto const leaving{m_lay.start.track != nullptr ? -plan_of(m_lay.start.direction) : glm::dvec2{0.0}}; + glm::dvec2 reference{glm::length(leaving) > 1e-6 ? glm::normalize(leaving) : glm::dvec2{0.0, 1.0}}; + auto const step{glm::radians(15.0)}; + auto angle{std::round(signed_angle(reference, offset / length) / step) * step}; + if (auto const *axis{skew_reference(last, Mouse, kSkewReach)}) + { + auto const &path{axis->m_paths.front()}; + reference = glm::normalize(plan_of(path.points[segment_data::point::end] - path.points[segment_data::point::start])); + auto const relative{signed_angle(reference, offset / length)}; + angle = std::round(relative / step) * step; + double ratio{0.0}; + for (auto const n : kSkewRatios) + for (auto const base : {0.0, glm::pi()}) + for (auto const side : {-1.0, 1.0}) + { + auto const candidate{base + side * std::atan(1.0 / n)}; + if (std::abs(std::remainder(relative - candidate, 2.0 * glm::pi())) < std::abs(std::remainder(relative - angle, 2.0 * glm::pi()))) + { + angle = candidate; + ratio = n; + } + } + auto const name{name_of(*axis)}; + auto const degrees{glm::degrees(std::abs(std::remainder(angle, glm::pi())))}; + Label = ratio > 0.0 ? format(STR_C("1:%g to %s"), ratio, name.c_str()) : degrees < 0.1 ? format(STR_C("parallel to %s"), name.c_str()) : format(STR_C("%.0f deg to %s"), degrees, name.c_str()); + } + auto const heading{turned(reference, angle) * length}; + return {last.x + heading.x, Mouse.y, last.z + heading.y}; +} + +TTrack const *editor_mode::skew_reference(glm::dvec3 const &From, glm::dvec3 const &To, double const Reach) const +{ + auto const from{plan_of(From)}; + auto const leg{plan_of(To) - from}; + auto const length{glm::length(leg)}; + TTrack const *nearest{nullptr}; + auto best{std::numeric_limits::max()}; + for (auto *section : simulation::Region->sections((From + To) * 0.5, static_cast(std::min(0.5 * length + Reach, 2000.0)))) + for (auto const &cell : section->m_cells) + for (auto *track : cell.m_directories.paths) + { + if (track == nullptr || track->eType != tt_Normal || track->m_editorremoved || (track->iCategoryFlag & 15) != kRailCategory || track->m_paths.size() != 1 || + false == editor_track::is_straight(*track, m_straights.tolerance)) + continue; + auto const &path{track->m_paths.front()}; + auto const a{plan_of(path.points[segment_data::point::start])}; + auto const axis{plan_of(path.points[segment_data::point::end]) - a}; + auto const span{glm::length(axis)}; + if (span < 1.0) + continue; + auto const along{std::clamp(glm::dot(from - a, axis) / span, 0.0, span)}; + auto distance{glm::distance(from, a + axis / span * along)}; + if (distance > Reach) + distance = std::numeric_limits::max(); + if (auto const determinant{cross(leg, axis)}; length > 1.0 && std::abs(determinant) > 1e-9) + { + auto const t{cross(a - from, axis) / determinant}; + auto const u{cross(a - from, leg) / determinant}; + if (t >= 0.0 && t <= 1.0 && u >= 0.0 && u <= 1.0) + distance = std::min(distance, t * length); + } + if (distance < best) + { + best = distance; + nearest = track; + } + } + return nearest; +} + +track_hover editor_mode::split_spot() const +{ + auto const *selected{selected_track()}; + if (selected == nullptr || ui()->mode() != nodebank_panel::TRACK || ImGui::GetIO().WantCaptureMouse) + return {}; + return track_under_cursor(selected, 20.0f); +} + +alignment::limits editor_mode::laying_norms() const +{ + auto norms{m_route.design.norms}; + norms.checked = true; + return norms; +} + +void editor_mode::render_lay_ui() +{ + auto &tool{m_lay}; + // the points clicked are no track until they're laid: said first, with the keys as buttons + if (tool.points.size() > 1) + { + auto const pending{lay_pending()}; + ImGui::TextColored(ImVec4(1.0f, 0.83f, 0.3f, 1.0f), "%s", format(STR_P("Not laid yet: %zu point", "Not laid yet: %zu points", static_cast(pending)), pending).c_str()); + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.18f, 0.45f, 0.22f, 1.0f)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.24f, 0.56f, 0.28f, 1.0f)); + if (ImGui::Button(STR_C("Lay (Enter)"))) + { + // the cursor is over the panel: no free end under it to join + tool.mouse_snap = {}; + lay_enter(); + } + ImGui::PopStyleColor(2); + ImGui::SameLine(); + if (ImGui::Button(STR_C("Drop the points"))) + lay_cancel(); + item_tooltip("Esc twice does the same"); + ImGui::Separator(); + } + if (int mode{tool.mode == lay_mode::curve ? 1 : 0}; + segmented("laymode", mode, + {{0, STR_C("Straights Tab"), "Each point clicked is a bend of the straights: the bend eased with two transition curves meeting, with no cant, of a large radius; where they don't fit, an arc with the transitions and the cant of the norms, as large as fits"}, + {1, STR_C("Curve Tab"), "Click points along the middle of a curve seen on the photo: the curve, compound or with a straight in it, is fitted to them and ends at the last one, heading as they do there. It comes from the straight before it, of the points clicked before or of the free end, and goes on with the curve of a free end, a switch too, where the points turn its way"}}) && + (mode == 1) != (tool.mode == lay_mode::curve)) + lay_switch_mode(); + ImGui::PushItemWidth(120.0f); + if (tool.mode == lay_mode::straights) + { + ImGui::TextDisabled("%s", STR_C("Radius of the curves at the bends")); + ImGui::SameLine(); + if (ImGui::SmallButton("?##corners")) + { + m_first_steps_open = true; + m_tutorial_goto = "Radius of the curves at the bends"; + } + item_tooltip("What it is: the lesson of the tutorial"); + ImGui::PushTextWrapPos(0.0f); + ImGui::TextDisabled("%s", STR_C("The largest radius that fits between your points is taken: two transition curves meeting, with no cant, from 6000 m down to 2000 m, and below that an arc with the transitions and the cant of the norms")); + ImGui::PopTextWrapPos(); + } + else + { + ImGui::PopItemWidth(); + segmented("layradii", tool.radii, + {{0, STR_C("Auto"), "As few radii as follow the points, up to three"}, {1, STR_C("1 R"), "One radius"}, {2, STR_C("2 R"), "A compound curve of two radii"}, {3, STR_C("3 R"), "A compound curve of three radii"}}); + ImGui::Checkbox(STR_C("Two curves with a straight between them, where the points show one"), &tool.straights_between); + item_tooltip("The points along the curve may make two curves, turning the same way or not, with a straight between them, where these follow the points much closer than one curve"); + if (auto const &traces{tool.plan.traces}; false == traces.empty() && false == traces.back().offsets.empty()) + { + auto const &trace{traces.back()}; + auto const colour = [](double const Departure) { return Departure <= 0.1 ? IM_COL32(90, 220, 110, 255) : Departure <= 0.3 ? IM_COL32(255, 200, 60, 255) : IM_COL32(255, 90, 70, 255); }; + metric_tiles({{format("%zu", trace.points.size()), STR_C("points"), ImGui::GetColorU32(ImGuiCol_Text)}, + {format("%.0f cm", trace.rms * 100.0), STR_C("departure"), colour(trace.rms)}, + {format("%.0f cm", trace.worst * 100.0), STR_C("at most"), colour(trace.worst)}}); + } + else + { + ImGui::PushTextWrapPos(0.0f); + ImGui::TextDisabled("%s", STR_C("Click points along the middle of the track on the photo; the curve ends at the last one")); + ImGui::PopTextWrapPos(); + } + ImGui::PushItemWidth(120.0f); + } + ImGui::DragScalar(STR_C("Speed (km/h)"), ImGuiDataType_Double, &tool.style.velocity, 1.0f, nullptr, nullptr, "%.0f"); + item_tooltip("Speed limit of the new paths, and the design speed of the transition curves and of the cant; the speed of the track joined comes first, and none higher than the radius allows"); + value_chips("speeds", tool.style.velocity, {40.0, 60.0, 80.0, 100.0, 120.0, 160.0}, "%.0f"); + tool.style.velocity = std::clamp(tool.style.velocity, 0.0, 400.0); + ImGui::PopItemWidth(); + ImGui::Checkbox(STR_C("This speed also on from a track with a speed of its own"), &tool.own_speed); + item_tooltip("Off: a track laid on from another one, or joined to it, is designed for the speed of that track and takes it.\nOn: it's designed for the speed above and the new tracks get it.\nWhile laying: Ctrl+Shift+wheel"); + if (auto const [from, to]{laying_ends()}; from != nullptr || to != nullptr) + ImGui::TextDisabled("%s", design_speed_of(from, to).c_str()); + ImGui::TextDisabled("%s", STR_C("Height of the track on the ground")); + if (int heights{static_cast(EditorSettings.heights())}; + segmented("layheights", heights, + {{0, STR_C("Fitted"), "The grades fitted to the ground as Tracks onto the terrain fits them: vertical curves of the norms, the bumps of the ground gone past; the terrain is left as it is. On the terrain model the whole track laid in a row is fitted again at each click"}, + {1, STR_C("Point to point"), "Each bend of the straights clicked at the height of the ground, an even grade between them: the grade changes only at the bends. A curve traced, or bends clicked close along a curve, goes at an even grade from one end of it to the other"}, + {2, STR_C("Flat"), "The track goes on at the height it's laid from, whatever the ground; the first point on the ground"}})) + { + EditorSettings.heights(static_cast(heights)); + EditorSettings.save(); + } + // the curves of the line shown, those below the norms in the colour of a warning: they're laid all the same + if (auto const &plan{tool.plan}; tool.active && plan.shape.valid && false == plan.shape.curves.empty()) + { + ImGui::SeparatorText(STR_C("Curves of the track laid")); + ImGui::TextDisabled("%s", STR_C("R: radius, L: transition curve (m), h: cant (mm)")); + for (auto const &curve : plan.shape.curves) + { + auto const meets{alignment::meets_norms(curve, plan.design)}; + auto const text{format("%d. %s", curve.vertex + 1, curve_label(curve, laying_norms()).c_str())}; + if (meets) + ImGui::TextUnformatted(text.c_str()); + else + ImGui::TextColored(ImVec4(1.0f, 0.55f, 0.15f, 1.0f), "%s", text.c_str()); + if (ImGui::IsItemHovered()) + { + std::string notes; + auto const tag{format(STR_C("Vertex %zu"), static_cast(curve.vertex + 1))}; + for (auto const &warning : plan.shape.warnings) + if (warning.rfind(tag + ":", 0) == 0) + notes += (notes.empty() ? "" : "\n") + warning; + ImGui::SetTooltip("%s", notes.empty() ? STR_C("Meets the norms for the speed") : notes.c_str()); + } + } + } + if (auto *track{selected_track()}; track != nullptr) + { + std::string reason; + if (editor_track::can_edit_geometry(*track, reason)) + render_extend_ui(); + } + if (false == ImGui::TreeNode(STR_C("More settings"))) + { + render_lay_status(); + return; + } + ImGui::TextDisabled("%s", STR_C("Dragged from a free end, or laid from a point to one")); + ImGui::PushItemWidth(120.0f); + ImGui::DragScalar(STR_C("Curve radius (m)"), ImGuiDataType_Double, &tool.radius, 5.0f, nullptr, nullptr, "%.0f"); + item_tooltip("Drag to change, Ctrl+click to type the value. While dragging: Ctrl+wheel"); + value_chips("radii", tool.radius, {190.0, 300.0, 500.0, 800.0, 1200.0, 2000.0}, "%.0f"); + tool.radius = std::max(10.0, tool.radius); + ImGui::PopItemWidth(); + ImGui::Spacing(); + ImGui::PushItemWidth(120.0f); + ImGui::DragScalar(STR_C("Longest path (m)"), ImGuiDataType_Double, &tool.piece_length, 1.0f, nullptr, nullptr, "%.0f"); + tool.piece_length = std::clamp(tool.piece_length, 5.0, 1000.0); + ImGui::PopItemWidth(); + ImGui::TextDisabled("%s", STR_C("Look of the new track")); + int source{tool.copy_selected ? 1 : 0}; + if (segmented("laylook", source, + {{0, STR_C("These textures"), "The rails and the trackbed chosen below.\nA track started or finished at a free end always takes them from the track it joins"}, + {1, STR_C("Like the selected one"), "Takes the textures and the other parameters from the selected track.\nA track started or finished at a free end always takes them from the track it joins"}})) + tool.copy_selected = source == 1; + if (false == tool.copy_selected) + { + auto const column{std::round(ImGui::GetCursorPosX() + std::max(ImGui::CalcTextSize(STR_C("Rails")).x, ImGui::CalcTextSize(STR_C("Trackbed")).x) + ImGui::GetStyle().ItemSpacing.x)}; + auto const texture_row = [&](int const Kind, char const *Label, std::string &Value) { + ImGui::PushID(Kind); + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted(Label); + ImGui::SameLine(column); + auto const side{ImGui::GetFrameHeight()}; + auto const corner{ImGui::GetCursorScreenPos()}; + if (auto const image{Value.empty() || Value == "none" ? 0 : track_texture_image(Kind, Value)}; image != 0) + { + ImGui::Image(static_cast(image), ImVec2(side, side), ImVec2(0, 1), ImVec2(1, 0)); + if (ImGui::IsItemHovered()) + { + auto const big{std::round(ImGui::GetFontSize() * 14.0f)}; + ImGui::BeginTooltip(); + ImGui::Image(static_cast(image), ImVec2(big, big), ImVec2(0, 1), ImVec2(1, 0)); + ImGui::TextUnformatted(Value.c_str()); + ImGui::EndTooltip(); + } + } + else + { + ImGui::Dummy(ImVec2(side, side)); + ImGui::GetWindowDrawList()->AddRect(corner, ImVec2(corner.x + side, corner.y + side), ImGui::GetColorU32(ImGuiCol_Border)); + } + ImGui::SameLine(0.0f, 4.0f); + ImGui::SetNextItemWidth(-FLT_MIN); + ImGui::SetNextWindowSizeConstraints(ImVec2(ImGui::GetFontSize() * 36.0f, 0.0f), ImVec2(FLT_MAX, FLT_MAX)); + auto const slash{Value.find_last_of('/')}; + auto const preview{Value.empty() || Value == "none" ? std::string{STR_C("No texture")} : slash == std::string::npos ? Value : Value.substr(slash + 1)}; + if (ImGui::BeginCombo("##texture", preview.c_str(), ImGuiComboFlags_HeightLargest)) + { + if (std::string chosen; track_texture_picker(Kind, Value, false, chosen)) + { + Value = chosen; + ImGui::CloseCurrentPopup(); + } + ImGui::EndCombo(); + } + item_tooltip(Kind == 0 ? "Texture of the rails.\nA material dragged from the texture browser can be dropped here" : "Texture of the trackbed (ballast) under the rails.\nA material dragged from the texture browser can be dropped here"); + if (std::string dropped; material_drop(dropped)) + Value = dropped; + ImGui::PopID(); + }; + texture_row(0, STR_C("Rails"), tool.style.rail); + texture_row(1, STR_C("Trackbed"), tool.style.ballast); + } + ImGui::TreePop(); + render_lay_status(); +} + +void editor_mode::render_lay_status() +{ + auto const &tool{m_lay}; + if (scene::Layers.active() == null_handle) + ImGui::TextColored(ImVec4(1.0f, 0.7f, 0.2f, 1.0f), STR_C("The scenery isn't opened for editing: new track won't be saved")); + if (tool.active && false == tool.preview_error.empty()) + ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.3f, 1.0f), "%s", tool.preview_error.c_str()); + if (false == tool.status.empty()) + ImGui::TextWrapped("%s", tool.status.c_str()); +} diff --git a/application/editormodelineside.cpp b/application/editormodelineside.cpp index f28ff72a5..1c2fc9e9c 100644 --- a/application/editormodelineside.cpp +++ b/application/editormodelineside.cpp @@ -9,11 +9,15 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "application/editormode.h" +#include "application/editormodelineside.h" +#include "application/editormodeshared.h" #include "application/editoruilayer.h" #include "application/editorprojection.h" #include "editor/editorFormat.hpp" #include "editor/editorGeometry.hpp" #include "editor/editorIncludeInfo.hpp" +#include "editor/editorKilometrage.hpp" +#include "editor/editorTrackTrace.hpp" #include "scene/scene.h" #include "scene/scenelayers.h" @@ -33,30 +37,19 @@ namespace using geometry::bezier; using geometry::plan_distance; +using geometry::heading_of; using geometry::plan_of; double const kSampleStep{2.0}; // m between the samples of the line double const kLineCorridor{15.0}; // m from the axis, posts farther away belong to another line double const kOverlayRange{3000.0}; +float const kFoulingPick{12.0f}; // px from a point of the fouling overlay a click takes it double const kFoulingTrace{250.0}; // m from the start of a switch the tracks are followed for double const kRailHeight{0.18}; // m from the points of a track to the heads of its rails int const kRailCategory{1}; char const *const kHektoStyles[] = {"nowy", "stary", "zgnity"}; char const *const kFoulingModels[] = {"ip/pkp/w17.inc", "ip/pkp/w17_new.inc", "ip/pkp/w17_old.inc", "ip/pkp/w17_dwuteo.inc"}; -std::string normalized(std::string Text) -{ - std::transform(Text.begin(), Text.end(), Text.begin(), [](unsigned char const Character) { return static_cast(Character == '\\' ? '/' : std::tolower(Character)); }); - return Text; -} - -bool numeric(std::string const &Text, double &Value) -{ - char *end{nullptr}; - Value = std::strtod(Text.c_str(), &end); - return false == Text.empty() && *end == '\0'; -} - std::string number(double const Value, int const Decimals) { auto text{format("%.*f", Decimals, Value)}; @@ -65,12 +58,6 @@ std::string number(double const Value, int const Decimals) return text; } -double heading_of(glm::dvec2 const &Direction) -{ - auto const degrees{glm::degrees(std::atan2(Direction.x, Direction.y))}; - return degrees < 0.0 ? degrees + 360.0 : degrees; -} - // index of the sample at or before the chainage std::size_t sample_index(std::vector const &Samples, double const Chainage) { @@ -150,72 +137,6 @@ std::string km_text(int const Hectometres) return format("%d.%d", Hectometres / 10, Hectometres % 10); } -// points along the track from the end of a path on, the way a train goes: through a switch along its main track -std::vector trace(TTrack &Track, int const Path, bool const Forward, double const Limit) -{ - std::vector points; - auto *track{&Track}; - auto path{Path}; - auto forward{Forward}; - double length{0.0}; - for (int guard = 0; guard < 64 && track != nullptr && length < Limit; ++guard) - { - bezier const curve{track->m_paths[path]}; - auto const count{std::clamp(static_cast(curve.plan_length() / 1.0), 4, 400)}; - for (int k = points.empty() ? 0 : 1; k <= count; ++k) - { - auto const point{curve.point(forward ? static_cast(k) / count : 1.0 - static_cast(k) / count)}; - if (false == points.empty()) - length += plan_distance(points.back(), point); - points.push_back(point); - } - auto const exit{points.back()}; - TTrack *next{nullptr}; - int nextpath{0}; - bool nextforward{true}; - for (auto const &connection : editor_track::connected_points(*track, exit)) - { - auto *other{connection.first}; - if (other == track || (other->iCategoryFlag & 15) != kRailCategory) - continue; - bool const start{connection.second.kind == editor_track::point_kind::start}; - // entering a switch at its start the train takes the main track - if (next == nullptr || (other == next && start && connection.second.path == 0)) - { - next = other; - nextpath = connection.second.path; - nextforward = start; - } - } - track = next; - path = nextpath; - forward = nextforward; - } - return points; -} - -// nearest point of the polyline -glm::dvec3 nearest_on(std::vector const &Line, glm::dvec3 const &Point, double &Distance) -{ - Distance = std::numeric_limits::max(); - glm::dvec3 result{Point}; - auto const point{plan_of(Point)}; - for (std::size_t i = 1; i < Line.size(); ++i) - { - auto const a{plan_of(Line[i - 1])}; - auto const ab{plan_of(Line[i]) - a}; - auto const length2{glm::dot(ab, ab)}; - auto const t{length2 > 1e-12 ? std::clamp(glm::dot(point - a, ab) / length2, 0.0, 1.0) : 0.0}; - auto const distance{glm::length(point - (a + ab * t))}; - if (distance < Distance) - { - Distance = distance; - result = glm::mix(Line[i - 1], Line[i], t); - } - } - return result; -} - void draw_label(ImDrawList *Draw, ImVec2 const At, ImU32 const Colour, std::string const &Text) { auto const size{ImGui::CalcTextSize(Text.c_str())}; @@ -235,7 +156,7 @@ std::vector editor_mode::standing_templates(std: auto const &included{scene::Layers.instance(handle)}; if (included.removed || included.dead || included.file == nullptr) continue; - auto const file{normalized(*included.file)}; + auto const file{editor_includes::normalized(*included.file)}; if (false == Accept(file) || included.context.rotation != glm::vec3{0.f} || included.context.scale != glm::vec3{1.f}) continue; std::string target; @@ -257,8 +178,82 @@ std::vector editor_mode::standing_templates(std: return result; } -std::size_t editor_mode::place_templates(std::vector const &Items, std::string &Error) +scene::layer_handle editor_mode::output_layer(std::string const &Part) { + if (scene::Layers.empty()) + return null_handle; + auto stem{scene::Layers.layer(scene::layer_handle{1}).name}; + if (auto const slash{stem.find_last_of("/\\")}; slash != std::string::npos) + stem.erase(0, slash + 1); + if (auto const dot{stem.rfind('.')}; dot != std::string::npos) + stem.erase(dot); + stem.erase(0, stem.find_first_not_of('$')); + if (stem.empty()) + stem = "scenery"; + std::string reason; + auto const take = [&](scene::layer_handle const Layer) { + if (Layer == null_handle || false == scene::Layers.accepts(Layer, &reason)) + return false; + scene::Layers.visible(Layer, true); + scene::Layers.locked(Layer, false); + return true; + }; + // the first line of the files made here, which tells them from the files of the scenery named alike + auto const header{"// scenery layer created in the editor for its " + Part + " part"}; + auto const headed = [&](std::string const &Name) { + std::ifstream input{Global.asCurrentSceneryPath + Name, std::ios_base::binary}; + std::string first; + std::getline(input, first); + if (false == first.empty() && first.back() == '\r') + first.pop_back(); + return first == header; + }; + // the layer included which the test takes, by its name in lower case and its name as given, if it can take more. returns: + // null_handle if none + auto const included = [&](auto const &Named) -> scene::layer_handle { + for (std::size_t index = 1; index <= scene::Layers.size(); ++index) + if (auto const &existing{scene::Layers.layer(static_cast(index))}; false == existing.dead && false == existing.removed && Named(ToLower(existing.name), existing.name)) + if (auto const layer{scene::Layers.resolve(static_cast(index))}; take(layer)) + return layer; + return null_handle; + }; + auto const name_of = [&](int const Attempt) { return ToLower(stem + "_" + Part + (Attempt > 1 ? std::to_string(Attempt) : std::string{}) + ".scm"); }; + for (int attempt = 1; attempt <= 9; ++attempt) + if (auto const layer{included([&](std::string const &Name, std::string const &) { return Name == name_of(attempt); })}; layer != null_handle) + return layer; + // the one made here for the scenery saved under another name before, the file it was copied from: what the part made stays + // in one file. a file of the scenery of a name alike, without the first line written here, is left as it is + auto const part{"_" + ToLower(Part)}; + if (auto const layer{included([&](std::string const &Name, std::string const &Given) { + if (false == Name.ends_with(".scm")) + return false; + auto base{Name.substr(0, Name.size() - 4)}; + if (false == base.empty() && std::isdigit(static_cast(base.back()))) + base.pop_back(); + return base.size() > part.size() && base.ends_with(part) && headed(Given); + })}; + layer != null_handle) + return layer; + // a file of that name the scenery doesn't include, or one which can't take more, gives way to the next number + for (int attempt = 1; attempt <= 9; ++attempt) + { + auto const name{name_of(attempt)}; + auto known{false}; + for (std::size_t index = 1; index <= scene::Layers.size() && false == known; ++index) + if (auto const &existing{scene::Layers.layer(static_cast(index))}; false == existing.dead && false == existing.removed && ToLower(existing.name) == name) + known = true; + if (known) + continue; + if (auto const layer{scene::Layers.create(name, scene::layer_handle{1}, reason, false, header)}; take(layer)) + return layer; + } + WriteLog("Editor: no layer for " + Part + ", the active one takes it: " + reason, logtype::generic); + return null_handle; +} + +std::size_t editor_mode::place_templates(std::vector const &Items, std::string &Error, scene::layer_handle const Layer) +{ + m_drives_standing.reset(); if (Items.empty()) return 0; if (scene::Layers.empty()) @@ -266,7 +261,7 @@ std::size_t editor_mode::place_templates(std::vector const &Items Error = STR_C("Templates can be placed only in a scenery opened for editing (-edit)"); return 0; } - auto const layer{scene::Layers.resolve(scene::Layers.active())}; + auto const layer{scene::Layers.resolve(Layer != null_handle ? Layer : scene::Layers.active())}; if (std::string reason; false == scene::Layers.accepts(layer, &reason)) { Error = STR_C("The active layer can't take them: ") + (reason.empty() ? std::string{STR_C("there's no active layer")} : reason); @@ -292,7 +287,8 @@ std::size_t editor_mode::place_templates(std::vector const &Items } else { - std::vector values{"none", number(local.x, 3), number(local.y, 3), number(local.z, 3), number(item.yaw, 2)}; + auto const name{item.values.find("name")}; + std::vector values{name != item.values.end() ? name->second : std::string{"none"}, number(local.x, 3), number(local.y, 3), number(local.z, 3), number(item.yaw, 2)}; values.insert(values.end(), item.rest.begin(), item.rest.end()); directive = editor_includes::compose_directive(item.file, values); } @@ -345,6 +341,7 @@ std::size_t editor_mode::move_templates(std::vector const &Instances) { + m_drives_standing.reset(); EditorSnapshot snap; for (auto const instance : Instances) { @@ -363,18 +360,18 @@ std::size_t editor_mode::remove_templates(std::vector co return count; } -void editor_mode::hekto_start(TTrack &Track, glm::dvec3 const &Point) +void hekto_tool::start(TTrack &Track, glm::dvec3 const &Point) { auto &tool{m_hekto}; tool.track = &Track; tool.point = Point; tool.km_read = false; tool.dirty = true; - tool.expand = true; + m_tab.expand = true; tool.status.clear(); } -void editor_mode::hekto_read_kilometrage() +void hekto_tool::hekto_read_kilometrage() { auto &tool{m_hekto}; auto const &found{tool.found}; @@ -415,13 +412,13 @@ void editor_mode::hekto_read_kilometrage() tool.status = format(STR_C("Kilometrage read from %zu posts standing along the line"), found.size()); } -void editor_mode::hekto_update() +void hekto_tool::hekto_update() { auto &tool{m_hekto}; - if (false == tool.dirty && tool.history == m_history.size()) + if (false == tool.dirty && tool.history == m_history.history_revision()) return; tool.dirty = false; - tool.history = m_history.size(); + tool.history = m_history.history_revision(); tool.posts.clear(); tool.found.clear(); tool.error.clear(); @@ -446,7 +443,7 @@ void editor_mode::hekto_update() double distance; tool.origin = project(tool.samples, tool.point, distance); auto const length{tool.samples.back().chainage}; - for (auto const &standing : standing_templates([](std::string const &File) { return File.find("hekto") != std::string::npos; })) + for (auto const &standing : m_templates.standing_templates([](std::string const &File) { return File.find("hekto") != std::string::npos; })) { hekto_found post; post.post = standing; @@ -457,65 +454,101 @@ void editor_mode::hekto_update() continue; tool.found.push_back(post); } - if (false == tool.km_read) + tool.line_set = kilometrage::line_at(tool.point); + tool.line = tool.own_km ? std::string{} : tool.line_set; + if (tool.line.empty() && false == tool.km_read) { tool.km_read = true; hekto_read_kilometrage(); } - auto const chainage_of = [&](int const Hectometres) { return tool.origin + tool.growth * (Hectometres / 10.0 - tool.km) * 1000.0; }; - for (auto &post : tool.found) - { - post.expected = chainage_of(post.hectometres); - post.error = post.chainage - post.expected; - post.outside = true; - } - auto const km_at = [&](double const Chainage) { return tool.km + tool.growth * (Chainage - tool.origin) / 1000.0; }; - auto const low{std::max(0, static_cast(std::ceil(std::min(km_at(0.0), km_at(length)) * 10.0 - 1e-6)))}; - auto const high{static_cast(std::floor(std::max(km_at(0.0), km_at(length)) * 10.0 + 1e-6))}; - for (int hectometres = low; hectometres <= high && tool.posts.size() < 5000; ++hectometres) - { - hekto_post post; - post.hectometres = hectometres; - post.chainage = chainage_of(hectometres); - if (post.chainage < 0.0 || post.chainage > length) - continue; - auto const axis{editor_track::sampled_position(tool.samples, post.chainage)}; - auto const growing{sampled_direction(tool.samples, post.chainage) * static_cast(tool.growth)}; + auto const place = [&](hekto_post &Post) { + auto const axis{editor_track::sampled_position(tool.samples, Post.chainage)}; + auto const growing{sampled_direction(tool.samples, Post.chainage) * static_cast(Post.growth)}; glm::dvec2 const left{-growing.y, growing.x}; // alternately: the even hectometres on the right, the odd ones on the left of the growing kilometrage - auto const side{tool.side != 0 ? tool.side : (hectometres % 2 == 0 ? 1 : -1)}; + auto const side{tool.side != 0 ? tool.side : (Post.hectometres % 2 == 0 ? 1 : -1)}; auto const planar{plan_of(axis) + left * (side * tool.offset)}; - post.position = placement_on_ground({planar.x, axis.y, planar.y}); - post.yaw = std::fmod(heading_of(growing) + tool.turn, 360.0); - // of the posts with this number the one nearest to the place stands for it, the others are duplicates. it stands wrong - // when it's farther from the place than allowed: along the line, across it, or on the other side - auto best{std::numeric_limits::max()}; - for (int i = 0; i < static_cast(tool.found.size()); ++i) + Post.position = m_ground.placement_on_ground({planar.x, axis.y, planar.y}); + Post.yaw = std::fmod(heading_of(growing) + tool.turn, 360.0); + tool.posts.push_back(Post); + }; + auto const *axis{tool.line.empty() ? nullptr : kilometrage::axis_of(tool.line)}; + if (axis != nullptr) + { + // the hectometres of the kilometrage of the line, the jumps in it too + double km{0.0}; + if (kilometrage::km_at(tool.line, tool.point, km)) + tool.km = std::round(km * 1000.0) / 1000.0; + tool.growth = kilometrage::growth_at(tool.line, tool.point, sampled_direction(tool.samples, tool.origin)) < 0 ? -1 : 1; + for (auto const &hectometre : kilometrage::hectometres(*axis)) { - auto &found{tool.found[i]}; - if (found.hectometres != hectometres) + hekto_post post; + post.hectometres = hectometre.number; + post.chainage = project(tool.samples, hectometre.at, distance); + if (distance > kLineCorridor || post.chainage <= 0.0 || post.chainage >= length || hectometre.number < 0 || tool.posts.size() >= 5000) continue; - found.outside = false; - found.distance = plan_distance(found.post.location, post.position); - if (found.distance < best) + post.growth = glm::dot(hectometre.rising, sampled_direction(tool.samples, post.chainage)) < 0.0 ? -1 : 1; + place(post); + } + std::sort(tool.posts.begin(), tool.posts.end(), [](hekto_post const &A, hekto_post const &B) { return A.chainage < B.chainage; }); + } + else + { + auto const km_at = [&](double const Chainage) { return tool.km + tool.growth * (Chainage - tool.origin) / 1000.0; }; + auto const low{std::max(0, static_cast(std::ceil(std::min(km_at(0.0), km_at(length)) * 10.0 - 1e-6)))}; + auto const high{static_cast(std::floor(std::max(km_at(0.0), km_at(length)) * 10.0 + 1e-6))}; + for (int hectometres = low; hectometres <= high && tool.posts.size() < 5000; ++hectometres) + { + hekto_post post; + post.hectometres = hectometres; + post.chainage = tool.origin + tool.growth * (hectometres / 10.0 - tool.km) * 1000.0; + post.growth = tool.growth; + if (post.chainage < 0.0 || post.chainage > length) + continue; + place(post); + } + } + // each post standing goes with the place of its number nearest to it; of the posts going with a place the one nearest to it + // stands for it, the others are duplicates. it stands wrong when it's farther from the place than allowed: along the line, + // across it, or on the other side + for (auto &found : tool.found) + { + found.outside = true; + found.place = -1; + for (int i = 0; i < static_cast(tool.posts.size()); ++i) + { + auto const &post{tool.posts[i]}; + if (post.hectometres != found.hectometres) + continue; + auto const distance{plan_distance(found.post.location, post.position)}; + if (found.place < 0 || distance < found.distance) { - best = found.distance; - post.standing = i; + found.outside = false; + found.place = i; + found.distance = distance; + found.expected = post.chainage; + found.error = found.chainage - post.chainage; } } - for (int i = 0; i < static_cast(tool.found.size()); ++i) - { - auto &found{tool.found[i]}; - if (found.hectometres != hectometres) - continue; - found.duplicate = i != post.standing; - found.wrong = false == found.duplicate && found.distance > tool.tolerance; - } - tool.posts.push_back(post); + } + for (int i = 0; i < static_cast(tool.found.size()); ++i) + { + auto const &found{tool.found[i]}; + if (found.place < 0) + continue; + auto &post{tool.posts[found.place]}; + if (post.standing < 0 || found.distance < tool.found[post.standing].distance) + post.standing = i; + } + for (int i = 0; i < static_cast(tool.found.size()); ++i) + { + auto &found{tool.found[i]}; + found.duplicate = found.place >= 0 && tool.posts[found.place].standing != i; + found.wrong = found.place >= 0 && false == found.duplicate && found.distance > tool.tolerance; } } -void editor_mode::hekto_remove_duplicates() +void hekto_tool::hekto_remove_duplicates() { auto &tool{m_hekto}; hekto_update(); @@ -523,13 +556,13 @@ void editor_mode::hekto_remove_duplicates() for (auto const &found : tool.found) if (found.duplicate) instances.push_back(found.post.instance); - auto const removed{remove_templates(instances)}; - tool.status = format(STR_C("%zu duplicate hectometre posts removed, Ctrl+Z brings them back"), removed); + auto const removed{m_templates.remove_templates(instances)}; + tool.status = format(STR_P("%zu duplicate hectometre post removed, Ctrl+Z brings it back", "%zu duplicate hectometre posts removed, Ctrl+Z brings them back", static_cast(removed)), removed); WriteLog("Editor: " + tool.status); tool.dirty = true; } -void editor_mode::hekto_place() +void hekto_tool::hekto_place() { auto &tool{m_hekto}; hekto_update(); @@ -546,13 +579,18 @@ void editor_mode::hekto_place() items.push_back(std::move(item)); } std::string error; - auto const placed{place_templates(items, error)}; - tool.status = placed > 0 ? format(STR_C("%zu hectometre posts placed, Ctrl+Z takes them back"), placed) : error; + auto const layer{items.empty() ? null_handle : m_templates.output_layer("hektometry")}; + auto const placed{m_templates.place_templates(items, error, layer)}; + tool.status = placed > 0 ? format(STR_P("%zu hectometre post placed, Ctrl+Z takes it back", "%zu hectometre posts placed, Ctrl+Z takes them back", static_cast(placed)), placed) : error; + if (placed > 0 && layer != null_handle) + tool.status += format(STR_C(" (layer \"%s\")"), scene::Layers.layer(layer).name.c_str()); + if (placed > 0) + m_guide.first_step_done(editor_first_step::posts); WriteLog("Editor: " + tool.status, logtype::generic); tool.dirty = true; } -void editor_mode::hekto_fix() +void hekto_tool::hekto_fix() { auto &tool{m_hekto}; hekto_update(); @@ -566,16 +604,16 @@ void editor_mode::hekto_fix() item.yaw = post.yaw; moves.emplace_back(tool.found[post.standing].post, item); } - auto const moved{move_templates(moves)}; - tool.status = format(STR_C("%zu hectometre posts moved to their places, Ctrl+Z takes it back"), moved); + auto const moved{m_templates.move_templates(moves)}; + tool.status = format(STR_P("%zu hectometre post moved to its place, Ctrl+Z takes it back", "%zu hectometre posts moved to their places, Ctrl+Z takes it back", static_cast(moved)), moved); WriteLog("Editor: " + tool.status, logtype::generic); tool.dirty = true; } -void editor_mode::render_hekto_ui() +void hekto_tool::render_options() { auto &tool{m_hekto}; - auto *selected{selected_track()}; + auto *selected{m_selection.selected_track()}; if (tool.track == nullptr || (selected != nullptr && selected != tool.track && ImGui::SmallButton(STR_C("Along the line of the selected path")))) { if (selected == nullptr) @@ -583,50 +621,80 @@ void editor_mode::render_hekto_ui() ImGui::TextDisabled("%s", STR_C("Select a path of the line, or RMB on it: Hectometre posts")); return; } - hekto_start(*selected, bezier{selected->m_paths.front()}.point(0.0)); + start(*selected, bezier{selected->m_paths.front()}.point(0.0)); } auto const changed = [&](bool const Changed) { if (Changed) tool.dirty = true; }; - ImGui::PushItemWidth(110.0f); - changed(ImGui::InputDouble(STR_C("Kilometre at the point (km)"), &tool.km, 0.0, 0.0, "%.3f")); - ImGui::SameLine(); - if (ImGui::SmallButton(STR_C("Read from the posts"))) + if (false == tool.line.empty()) { - tool.km_read = false; - tool.dirty = true; + ImGui::TextWrapped("%s", format(STR_C("The km of line %s, as the Kilometrage tool sets them, its jumps too"), tool.line.c_str()).c_str()); + ImGui::TextDisabled("%s", format(STR_C("km %s at the point"), kilometrage::text(tool.km).c_str()).c_str()); + if (ImGui::SmallButton(STR_C("Give the km here instead"))) + { + tool.own_km = true; + tool.km_read = false; + tool.dirty = true; + } + item_tooltip("The posts go by the km given at the point and the way it grows, without the jumps of the line"); + } + else + { + if (false == tool.line_set.empty() && ImGui::SmallButton(format(STR_C("Follow the km of line %s"), tool.line_set.c_str()).c_str())) + { + tool.own_km = false; + tool.dirty = true; + } + if (tool.line_set.empty()) + { + // no km of the line yet: the one typed below is of the posts alone + ImGui::TextWrapped("%s", STR_C("The line has no km set yet: the posts count from the km typed here")); + if (ImGui::SmallButton(STR_C("Set the km of the line (X)"))) + m_guide.open_kilometrage(); + item_tooltip("Set with the Kilometrage tool, the km of the line serves the posts, the stations and the block signals, typed once"); + } + if (begin_fields("##hektokm", 0.45f)) + { + field_row("Kilometre at the point (km)"); + changed(ImGui::InputDouble("##hektokilometre", &tool.km, 0.0, 0.0, "%.3f")); + ImGui::TableNextRow(); + ImGui::TableSetColumnIndex(1); + if (ImGui::Button(STR_C("Read from the posts"), ImVec2(-FLT_MIN, 0.0f))) + { + tool.km_read = false; + tool.dirty = true; + } + ImGui::EndTable(); + } + ImGui::TextDisabled("%s", STR_C("The kilometrage grows")); + changed(segmented("growth", tool.growth, {{1, STR_C("along the line")}, {-1, STR_C("against it")}})); } - ImGui::TextDisabled("%s", STR_C("The kilometrage grows")); - ImGui::SameLine(); - changed(ImGui::RadioButton(STR_C("along the line"), &tool.growth, 1)); - ImGui::SameLine(); - changed(ImGui::RadioButton(STR_C("against it"), &tool.growth, -1)); ImGui::TextDisabled("%s", STR_C("Side, looking where it grows")); - ImGui::SameLine(); - changed(ImGui::RadioButton(STR_C("right"), &tool.side, 1)); - ImGui::SameLine(); - changed(ImGui::RadioButton(STR_C("left"), &tool.side, -1)); - ImGui::SameLine(); - changed(ImGui::RadioButton(STR_C("alternately"), &tool.side, 0)); - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", STR_C("The even hectometres on the right, the odd ones on the left")); - changed(ImGui::InputDouble(STR_C("From the axis (m)"), &tool.offset, 0.0, 0.0, "%.2f")); - tool.offset = std::clamp(tool.offset, 1.5, 30.0); - char const *styles[] = {"nowy", "stary", "zgnity", "mixed"}; - ImGui::Combo(STR_C("Posts"), &tool.style, styles, IM_ARRAYSIZE(styles)); - char const *turns[] = {"0", "90", "180", "270"}; - int turn{tool.turn / 90}; - if (ImGui::Combo(STR_C("Turned by (deg)"), &turn, turns, IM_ARRAYSIZE(turns))) + changed(segmented("side", tool.side, {{1, STR_C("on the right")}, {-1, STR_C("on the left")}, {0, STR_C("alternately"), "The even hectometres on the right, the odd ones on the left"}})); + if (ImGui::TreeNode(STR_C("More settings"))) { - tool.turn = turn * 90; - tool.dirty = true; + ImGui::TextDisabled("%s", STR_C("Look")); + segmented("hektostyle", tool.style, {{0, STR_C("new")}, {1, STR_C("old")}, {2, STR_C("rotten")}, {3, STR_C("mixed"), "New, old and rotten ones at random, mostly new"}}); + ImGui::TextDisabled("%s", STR_C("Turned by (deg)")); + if (segmented("hektoturn", tool.turn, {{0, "0"}, {90, "90"}, {180, "180"}, {270, "270"}})) + tool.dirty = true; + if (begin_fields("##hektofields", 0.6f)) + { + field_row("From the axis (m)"); + changed(ImGui::InputDouble("##hektooffset", &tool.offset, 0.0, 0.0, "%.2f")); + field_row("Along the line each way (m)"); + changed(ImGui::InputDouble("##hektoreach", &tool.reach, 0.0, 0.0, "%.0f")); + field_row("Tolerance (m)"); + changed(ImGui::InputDouble("##hektotolerance", &tool.tolerance, 0.0, 0.0, "%.1f")); + item_tooltip("A post standing farther than this from its place counts as wrong"); + ImGui::EndTable(); + } + ImGui::TreePop(); } - changed(ImGui::InputDouble(STR_C("Along the line each way (m)"), &tool.reach, 0.0, 0.0, "%.0f")); + tool.offset = std::clamp(tool.offset, 1.5, 30.0); tool.reach = std::clamp(tool.reach, 100.0, 100000.0); - changed(ImGui::InputDouble(STR_C("A post standing off by more (m) is wrong"), &tool.tolerance, 0.0, 0.0, "%.1f")); tool.tolerance = std::clamp(tool.tolerance, 0.5, 50.0); - ImGui::PopItemWidth(); hekto_update(); if (false == tool.error.empty()) { @@ -636,15 +704,18 @@ void editor_mode::render_hekto_ui() auto const missing{std::count_if(tool.posts.begin(), tool.posts.end(), [](hekto_post const &Post) { return Post.standing < 0; })}; auto const wrong{std::count_if(tool.found.begin(), tool.found.end(), [](hekto_found const &Post) { return Post.wrong; })}; auto const duplicates{std::count_if(tool.found.begin(), tool.found.end(), [](hekto_found const &Post) { return Post.duplicate; })}; - ImGui::Text(STR_C("Line %.0f m, km %s - %s: %d posts to place, %zu standing, %d of them wrong"), tool.samples.empty() ? 0.0 : tool.samples.back().chainage, tool.posts.empty() ? "-" : km_text(std::min(tool.posts.front().hectometres, tool.posts.back().hectometres)).c_str(), - tool.posts.empty() ? "-" : km_text(std::max(tool.posts.front().hectometres, tool.posts.back().hectometres)).c_str(), static_cast(missing), tool.found.size(), static_cast(wrong)); - if (missing > 0 && ImGui::Button(format(STR_C("Place %d posts"), static_cast(missing)).c_str())) - hekto_place(); + ImGui::Text(STR_C("To place: %d"), static_cast(missing)); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip(STR_C("Line %.0f m, km %s - %s. Standing: %zu, %d of them wrong"), tool.samples.empty() ? 0.0 : tool.samples.back().chainage, tool.posts.empty() ? "-" : km_text(std::min(tool.posts.front().hectometres, tool.posts.back().hectometres)).c_str(), + tool.posts.empty() ? "-" : km_text(std::max(tool.posts.front().hectometres, tool.posts.back().hectometres)).c_str(), tool.found.size(), static_cast(wrong)); + if (missing > 0) + { + if (main_button(format(STR_P("Place %d post", "Place %d posts", static_cast(missing)), static_cast(missing)).c_str(), ImVec2(-1.0f, tall_button_height()))) + hekto_place(); + } if (duplicates > 0) { - if (missing > 0) - ImGui::SameLine(); - if (ImGui::Button(format(STR_C("Remove %d duplicate posts"), static_cast(duplicates)).c_str())) + if (ImGui::Button(format(STR_P("Remove %d duplicate post", "Remove %d duplicate posts", static_cast(duplicates)), static_cast(duplicates)).c_str())) hekto_remove_duplicates(); if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", STR_C("Posts with a number another post nearer to its place already has")); @@ -653,9 +724,9 @@ void editor_mode::render_hekto_ui() { if (wrong > 0) { - if (missing > 0 || duplicates > 0) + if (duplicates > 0) ImGui::SameLine(); - if (ImGui::Button(format(STR_C("Move %d wrong posts to their places"), static_cast(wrong)).c_str())) + if (ImGui::Button(format(STR_P("Move %d wrong post to its place", "Move %d wrong posts to their places", static_cast(wrong)), static_cast(wrong)).c_str())) hekto_fix(); } ImGui::BeginChild("##hektowrong", ImVec2(0.0f, std::min(6, static_cast(wrong + duplicates)) * ImGui::GetTextLineHeightWithSpacing() + 6.0f), true); @@ -666,14 +737,7 @@ void editor_mode::render_hekto_ui() auto const label{post.duplicate ? format(STR_C("km %s duplicate##%u"), km_text(post.hectometres).c_str(), post.post.instance) : format(STR_C("km %s stands %.1f m from its place##%u"), km_text(post.hectometres).c_str(), post.distance, post.post.instance)}; if (ImGui::Selectable(label.c_str())) { - glm::dvec3 const look{glm::normalize(glm::dvec3{-1.0, -0.8, -1.0})}; - m_focus_start_pos = Camera.Pos; - m_focus_start_angle = Camera.Angle; - m_focus_target_pos = post.post.location - look * 20.0; - m_focus_target_angle = glm::vec3(static_cast(std::asin(look.y)), static_cast(std::atan2(-look.x, -look.z)), 0.0f); - m_focus_active = true; - m_focus_time = 0.0; - m_focus_duration = 0.6; + m_view.fly_to(post.post.location, glm::normalize(glm::dvec3{-1.0, -0.8, -1.0}), 20.0); } } ImGui::EndChild(); @@ -682,10 +746,10 @@ void editor_mode::render_hekto_ui() ImGui::TextWrapped("%s", tool.status.c_str()); } -void editor_mode::draw_hekto_overlay() const +void hekto_tool::draw_overlay() const { auto const &tool{m_hekto}; - if (false == tool.open || tool.track == nullptr) + if (false == m_tab.open || tool.track == nullptr) return; screen_projection const projection; auto *drawlist{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())}; @@ -726,16 +790,16 @@ void editor_mode::draw_hekto_overlay() const } } -void editor_mode::fouling_update() +void fouling_tool::fouling_update() { auto &tool{m_fouling}; - auto *selected{selected_track()}; + auto *selected{m_selection.selected_track()}; if (tool.scope == 0 && selected != tool.selected) tool.dirty = true; - if (false == tool.dirty && tool.history == m_history.size()) + if (false == tool.dirty && tool.history == m_history.history_revision()) return; tool.dirty = false; - tool.history = m_history.size(); + tool.history = m_history.history_revision(); tool.selected = selected; tool.points.clear(); tool.found.clear(); @@ -762,39 +826,19 @@ void editor_mode::fouling_update() { if (track->m_paths.size() < 2 || false == editor_track::is_supported(*track)) continue; - auto const main{trace(*track, 0, true, kFoulingTrace)}; - auto const branch{trace(*track, 1, true, kFoulingTrace)}; - if (main.size() < 2 || branch.size() < 2) + track_trace::fouling found; + if (false == track_trace::fouling_of(*track, tool.spacing, kFoulingTrace, found)) continue; - glm::dvec3 previous{branch.front()}; - double previousdistance{0.0}; - for (std::size_t i = 1; i < branch.size(); ++i) - { - double distance; - nearest_on(main, branch[i], distance); - if (distance < tool.spacing) - { - previous = branch[i]; - previousdistance = distance; - continue; - } - auto const f{distance - previousdistance > 1e-9 ? (tool.spacing - previousdistance) / (distance - previousdistance) : 1.0}; - auto const onbranch{glm::mix(previous, branch[i], std::clamp(f, 0.0, 1.0))}; - double unused; - auto const onmain{nearest_on(main, onbranch, unused)}; - fouling_point point; - point.track = track; - auto const middle{(onbranch + onmain) * 0.5}; - // the points of the paths are at the rail foot, the heads of the rails are the height of the rail over them - point.position = tool.height_mode == 1 ? glm::dvec3{middle.x, 0.5 * (onbranch.y + onmain.y) + kRailHeight + tool.height, middle.z} : placement_on_ground({middle.x, std::max(onbranch.y, onmain.y), middle.z}); - auto const back{plan_of(previous - branch[i])}; - point.yaw = std::fmod(heading_of(glm::length(back) > 1e-9 ? glm::normalize(back) : glm::dvec2{0.0, 1.0}) + tool.turn, 360.0); - tool.points.push_back(point); - break; - } + fouling_point point; + point.track = track; + auto const middle{(found.branch + found.main) * 0.5}; + // the points of the paths are at the rail foot, the heads of the rails are the height of the rail over them + point.position = tool.height_mode == 1 ? glm::dvec3{middle.x, 0.5 * (found.branch.y + found.main.y) + kRailHeight + tool.height, middle.z} : m_ground.placement_on_ground({middle.x, std::max(found.branch.y, found.main.y), middle.z}); + point.yaw = std::fmod(heading_of(found.back) + tool.turn, 360.0); + tool.points.push_back(point); } // markers standing: each goes to the nearest fouling point, the others are left alone - auto const markers{standing_templates([](std::string const &File) { return File.find("w17") != std::string::npos || File.find("ukres") != std::string::npos; })}; + auto const markers{m_templates.standing_templates([](std::string const &File) { return File.find("w17") != std::string::npos || File.find("ukres") != std::string::npos; })}; for (auto const &marker : markers) { int nearest{-1}; @@ -832,14 +876,15 @@ void editor_mode::fouling_update() tool.status = format(STR_C("%zu switches, %zu fouling points: %d without a marker, %d markers standing wrong"), switches.size(), tool.points.size(), static_cast(missing), static_cast(wrong)); } -void editor_mode::fouling_place() +void fouling_tool::place(int const Only) { auto &tool{m_fouling}; fouling_update(); std::vector items; - for (auto const &point : tool.points) + for (int i = 0; i < static_cast(tool.points.size()); ++i) { - if (point.standing >= 0) + auto const &point{tool.points[i]}; + if (point.standing >= 0 || (Only >= 0 && i != Only)) continue; template_item item; item.file = kFoulingModels[std::clamp(tool.model, 0, 3)]; @@ -850,20 +895,21 @@ void editor_mode::fouling_place() items.push_back(std::move(item)); } std::string error; - auto const placed{place_templates(items, error)}; - tool.status = placed > 0 ? format(STR_C("%zu fouling point markers placed, Ctrl+Z takes them back"), placed) : error; + auto const placed{m_templates.place_templates(items, error)}; + tool.status = placed > 0 ? format(STR_P("%zu fouling point marker placed, Ctrl+Z takes it back", "%zu fouling point markers placed, Ctrl+Z takes them back", static_cast(placed)), placed) : error; WriteLog("Editor: " + tool.status, logtype::generic); tool.dirty = true; } -void editor_mode::fouling_fix() +void fouling_tool::fix(int const Only) { auto &tool{m_fouling}; fouling_update(); std::vector> moves; - for (auto const &found : tool.found) + for (int i = 0; i < static_cast(tool.found.size()); ++i) { - if (false == found.wrong) + auto const &found{tool.found[i]}; + if (false == found.wrong || (Only >= 0 && i != Only)) continue; template_item item; auto const &point{tool.points[found.point]}; @@ -880,79 +926,151 @@ void editor_mode::fouling_fix() } moves.emplace_back(found.marker, item); } - auto const moved{move_templates(moves)}; - tool.status = format(STR_C("%zu fouling point markers moved to their places, Ctrl+Z takes it back"), moved); + auto const moved{m_templates.move_templates(moves)}; + tool.status = format(STR_P("%zu fouling point marker moved to its place, Ctrl+Z takes it back", "%zu fouling point markers moved to their places, Ctrl+Z takes it back", static_cast(moved)), moved); WriteLog("Editor: " + tool.status, logtype::generic); tool.dirty = true; } -void editor_mode::render_fouling_ui() +std::optional> fouling_tool::hit() const +{ + auto const &tool{m_fouling}; + screen_projection const projection; + auto const &mouse{ImGui::GetIO().MousePos}; + glm::dvec3 const camera{Global.pCamera.Pos}; + std::optional> result; + auto best{kFoulingPick * kFoulingPick}; + auto const consider = [&](glm::dvec3 const &Position, int const Index, bool const Marker) { + ImVec2 screen; + if (glm::distance(Position, camera) > kOverlayRange || false == projection.project(Position, screen)) + return; + auto const distance2{(screen.x - mouse.x) * (screen.x - mouse.x) + (screen.y - mouse.y) * (screen.y - mouse.y)}; + if (distance2 < best) + { + best = distance2; + result = std::make_pair(Index, Marker); + } + }; + for (int i = 0; i < static_cast(tool.points.size()); ++i) + if (tool.points[i].standing < 0) + consider(tool.points[i].position, i, false); + for (int i = 0; i < static_cast(tool.found.size()); ++i) + if (tool.found[i].wrong) + consider(tool.found[i].marker.location, i, true); + return result; +} + +void fouling_tool::render_options() { auto &tool{m_fouling}; - ImGui::TextDisabled("%s", STR_C("W17 where the axes of the tracks meeting at a switch are the spacing apart,\nhalf way between them")); auto const changed = [&](bool const Changed) { if (Changed) tool.dirty = true; }; - changed(ImGui::RadioButton(STR_C("The selected switch"), &tool.scope, 0)); - ImGui::SameLine(); - changed(ImGui::RadioButton(STR_C("Around the camera"), &tool.scope, 1)); - ImGui::SameLine(); - changed(ImGui::RadioButton(STR_C("Whole scenery"), &tool.scope, 2)); - ImGui::PushItemWidth(110.0f); - if (tool.scope == 1) - changed(ImGui::InputDouble(STR_C("Around the camera (m)"), &tool.reach, 0.0, 0.0, "%.0f")); - changed(ImGui::InputDouble(STR_C("Spacing of the axes (m)"), &tool.spacing, 0.0, 0.0, "%.2f")); - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", STR_C("3.5 m on the straight track; more on the curves, where the cars lean out")); - changed(ImGui::InputDouble(STR_C("A marker off by more (m) is wrong"), &tool.tolerance, 0.0, 0.0, "%.1f")); - changed(ImGui::RadioButton(STR_C("On the ground"), &tool.height_mode, 0)); - ImGui::SameLine(); - changed(ImGui::RadioButton(STR_C("Over the rail heads"), &tool.height_mode, 1)); - if (tool.height_mode == 1) + changed(segmented("foulingscope", tool.scope, {{0, STR_C("The selected switch")}, {1, STR_C("Around the camera")}, {2, STR_C("Whole scenery")}})); + fouling_update(); + if (false == tool.error.empty()) + ImGui::TextColored(ImVec4(1.0f, 0.8f, 0.3f, 1.0f), "%s", tool.error.c_str()); + else { - ImGui::SameLine(); - changed(ImGui::InputDouble(STR_C("by (m)"), &tool.height, 0.0, 0.0, "%.3f")); - changed(ImGui::InputDouble(STR_C("A marker higher or lower by more (m) is wrong"), &tool.height_tolerance, 0.0, 0.0, "%.3f")); - tool.height_tolerance = std::clamp(tool.height_tolerance, 0.005, 1.0); + ImGui::TextWrapped("%s", tool.status.c_str()); + auto const missing{std::count_if(tool.points.begin(), tool.points.end(), [](fouling_point const &Point) { return Point.standing < 0; })}; + auto const wrong{std::count_if(tool.found.begin(), tool.found.end(), [](fouling_found const &Found) { return Found.wrong; })}; + auto const tall{tall_button_height()}; + if (missing > 0) + { + if (main_button(format(STR_P("Place %d marker", "Place %d markers", static_cast(missing)), static_cast(missing)).c_str(), ImVec2(-1.0f, tall))) + place(); + } + if (wrong > 0) + { + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.6f, 0.4f, 0.1f, 1.0f)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.7f, 0.48f, 0.15f, 1.0f)); + if (ImGui::Button(format(STR_P("Move %d wrong marker to its place", "Move %d wrong markers to their places", static_cast(wrong)), static_cast(wrong)).c_str(), ImVec2(-1.0f, tall))) + fix(); + ImGui::PopStyleColor(2); + } + if (missing + wrong > 0) + { + // each one: a click flies there, the button fixes it alone; in the view a click on its point does the same + ImGui::TextDisabled("%s", STR_C("Click the green or red point in the view: that one only")); + ImGui::BeginChild("##foulinglist", ImVec2(0.0f, std::min(8, static_cast(missing + wrong)) * ImGui::GetFrameHeightWithSpacing() + 6.0f), true); + auto const look{glm::normalize(glm::dvec3{-1.0, -0.8, -1.0})}; + for (int i = 0; i < static_cast(tool.points.size()); ++i) + { + auto const &point{tool.points[i]}; + if (point.standing >= 0) + continue; + ImGui::PushID(i); + if (ImGui::SmallButton(STR_C("Place"))) + place(i); + ImGui::SameLine(); + if (ImGui::Selectable(format(STR_C("%s: no W17"), point.track->name().c_str()).c_str())) + m_view.fly_to(point.position, look, 25.0); + ImGui::PopID(); + } + for (int i = 0; i < static_cast(tool.found.size()); ++i) + { + auto const &found{tool.found[i]}; + if (false == found.wrong) + continue; + ImGui::PushID(1000000 + i); + if (ImGui::SmallButton(STR_C("Fix"))) + fix(i); + ImGui::SameLine(); + if (ImGui::Selectable(format(STR_C("%s: W17 %.1f m off, %+.2f m high"), tool.points[found.point].track->name().c_str(), found.error, found.height_error).c_str())) + m_view.fly_to(found.marker.location, look, 25.0); + ImGui::PopID(); + } + ImGui::EndChild(); + } } - char const *models[] = {"w17", "w17_new", "w17_old", "w17_dwuteo"}; - ImGui::Combo(STR_C("Marker"), &tool.model, models, IM_ARRAYSIZE(models)); - char const *turns[] = {"0", "90", "180", "270"}; - int turn{tool.turn / 90}; - if (ImGui::Combo(STR_C("Turned by (deg)"), &turn, turns, IM_ARRAYSIZE(turns))) + if (ImGui::TreeNode(STR_C("More settings"))) { - tool.turn = turn * 90; - tool.dirty = true; + if (begin_fields("##foulingfields", 0.6f)) + { + if (tool.scope == 1) + { + field_row("Around the camera (m)"); + changed(ImGui::InputDouble("##foulingreach", &tool.reach, 0.0, 0.0, "%.0f")); + } + field_row("Spacing of the axes (m)"); + changed(ImGui::InputDouble("##foulingspacing", &tool.spacing, 0.0, 0.0, "%.2f")); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s\n%s", STR_C("W17 where the axes of the tracks meeting at a switch are the spacing apart,\nhalf way between them"), STR_C("Nominally 3.50 m (Standardy techniczne PLK, tom II, 6.5). Where a track lies there in a curve under 250 m,\nthe widening of the gauge from its radius on the side of the other track is added by itself, of both tracks summed (6.6),\nand the leaning of the cars of a track on its cant towards the other one, taken 3.25 m up (Ie-1, bD)")); + field_row("Tolerance (m)"); + changed(ImGui::InputDouble("##foulingtolerance", &tool.tolerance, 0.0, 0.0, "%.1f")); + item_tooltip("A marker standing farther than this from its place counts as wrong"); + ImGui::EndTable(); + } + changed(segmented("foulingheight", tool.height_mode, {{0, STR_C("On the ground")}, {1, STR_C("Over the rail heads")}})); + if (tool.height_mode == 1 && begin_fields("##foulingheights", 0.6f)) + { + field_row("by (m)"); + changed(ImGui::InputDouble("##foulingby", &tool.height, 0.0, 0.0, "%.3f")); + field_row("Height tolerance (m)"); + changed(ImGui::InputDouble("##foulingheighttolerance", &tool.height_tolerance, 0.0, 0.0, "%.3f")); + item_tooltip("A marker higher or lower than its place by more than this counts as wrong"); + tool.height_tolerance = std::clamp(tool.height_tolerance, 0.005, 1.0); + ImGui::EndTable(); + } + ImGui::TextDisabled("%s", STR_C("Marker")); + segmented("foulingmodel", tool.model, + {{0, "w17", "Round post (ip/pkp/w17.inc)"}, {1, "w17_new", "Round post, taller than w17 (ip/pkp/w17_new.inc)"}, {2, "w17_old", "Square post (ip/pkp/w17_old.inc)"}, {3, STR_C("I-beam"), "Post of an HEB I-beam (ip/pkp/w17_dwuteo.inc)"}}); + ImGui::TextDisabled("%s", STR_C("Turned by (deg)")); + if (segmented("foulingturn", tool.turn, {{0, "0"}, {90, "90"}, {180, "180"}, {270, "270"}})) + tool.dirty = true; + ImGui::TreePop(); } - ImGui::PopItemWidth(); tool.reach = std::clamp(tool.reach, 50.0, 50000.0); tool.spacing = std::clamp(tool.spacing, 2.0, 10.0); tool.tolerance = std::clamp(tool.tolerance, 0.2, 20.0); - fouling_update(); - if (false == tool.error.empty()) - { - ImGui::TextColored(ImVec4(1.0f, 0.5f, 0.3f, 1.0f), "%s", tool.error.c_str()); - return; - } - ImGui::TextWrapped("%s", tool.status.c_str()); - auto const missing{std::count_if(tool.points.begin(), tool.points.end(), [](fouling_point const &Point) { return Point.standing < 0; })}; - auto const wrong{std::count_if(tool.found.begin(), tool.found.end(), [](fouling_found const &Found) { return Found.wrong; })}; - if (missing > 0 && ImGui::Button(format(STR_C("Place %d markers"), static_cast(missing)).c_str())) - fouling_place(); - if (wrong > 0) - { - if (missing > 0) - ImGui::SameLine(); - if (ImGui::Button(format(STR_C("Move %d wrong markers to their places"), static_cast(wrong)).c_str())) - fouling_fix(); - } } -void editor_mode::draw_fouling_overlay() const +void fouling_tool::draw_overlay() const { auto const &tool{m_fouling}; - if (false == tool.open) + if (false == m_tab.open) return; screen_projection const projection; auto *drawlist{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())}; @@ -981,3 +1099,134 @@ void editor_mode::draw_fouling_overlay() const projection.line(drawlist, found.marker.location, tool.points[found.point].position, IM_COL32(255, 70, 60, 160), 1.5f); } } + +editor_selftest_result hekto_tool::selftest(std::string const &Command, std::istringstream &Words) +{ + if (Command == "hekto") + { + auto values{selftest_values(Words)}; + auto *track{simulation::Paths.find(values["track"])}; + if (track == nullptr) + { + WriteLog("SELFTEST hekto: no such track"); + return editor_selftest_result::handled; + } + start(*track, track->m_paths.front().points[segment_data::point::start]); + auto &tool{m_hekto}; + if (values.count("reach")) + tool.reach = std::stod(values["reach"]); + tool.own_km = values["own"] == "1"; + tool.dirty = true; + hekto_update(); + if (values.count("km")) + { + tool.km = std::stod(values["km"]); + tool.growth = values["growth"] == "-1" ? -1 : 1; + } + tool.side = values["side"] == "alt" ? 0 : values["side"] == "left" ? -1 : 1; + tool.dirty = true; + hekto_update(); + auto const missing{std::count_if(tool.posts.begin(), tool.posts.end(), [](hekto_post const &Post) { return Post.standing < 0; })}; + auto const wrong{std::count_if(tool.found.begin(), tool.found.end(), [](hekto_found const &Post) { return Post.wrong; })}; + auto const duplicates{std::count_if(tool.found.begin(), tool.found.end(), [](hekto_found const &Post) { return Post.duplicate; })}; + WriteLog(format("SELFTEST hekto: line %s km %.3f growth %d, %zu posts along %.0f m, %d to place, %zu standing, %d wrong, %d duplicate. %s", tool.line.empty() ? "-" : tool.line.c_str(), tool.km, tool.growth, tool.posts.size(), tool.samples.empty() ? 0.0 : tool.samples.back().chainage, static_cast(missing), tool.found.size(), + static_cast(wrong), static_cast(duplicates), tool.status.c_str())); + for (std::size_t i = 0; i < tool.posts.size() && i < 4; ++i) + { + auto const &post{tool.posts[i]}; + double lateral; + glm::dvec3 const axis{editor_track::sampled_position(tool.samples, post.chainage)}; + auto const direction{editor_track::sampled_position(tool.samples, post.chainage + 1.0) - axis}; + glm::dvec2 const offset{post.position.x - axis.x, post.position.z - axis.z}; + lateral = glm::length(offset); + auto const right{(direction.x * offset.y - direction.z * offset.x) * post.growth >= 0.0}; + WriteLog(format("SELFTEST hekto post %d.%d at %.1f m, %.2f m from the axis, %s of the growing kilometrage, at %.1f %.1f %.1f", post.hectometres / 10, post.hectometres % 10, post.chainage, lateral, right ? "right" : "left", post.position.x, post.position.y, + post.position.z)); + } + if (values["list"] == "1") + { + std::string list; + for (auto const &post : tool.posts) + list += format(" %d@%.0f", post.hectometres, post.chainage); + WriteLog("SELFTEST hekto posts:" + list); + } + if (values["place"] == "1") + { + hekto_place(); + WriteLog("SELFTEST hekto: " + tool.status); + } + return editor_selftest_result::handled; + } + return editor_selftest_result::unhandled; +} + +glm::dvec3 fouling_tool::position_of(std::pair const &Hit) const +{ + return Hit.second ? m_fouling.found[Hit.first].marker.location : m_fouling.points[Hit.first].position; +} + +void fouling_tool::check_selected_switch() +{ + m_fouling.scope = 0; + m_fouling.dirty = true; + m_tab.expand = true; +} + +editor_selftest_result fouling_tool::selftest(std::string const &Command, std::istringstream &Words) +{ + if (Command == "fouling") + { + auto values{selftest_values(Words)}; + auto &tool{m_fouling}; + if (values["show"] == "1") + { + m_view.show_track_tab(editor_track_tab::lineside); + m_tab.expand = true; + } + tool.scope = std::stoi(values.count("scope") ? values["scope"] : "2"); + tool.height_mode = values["mode"] == "ground" ? 0 : 1; + tool.height = std::stod(values.count("height") ? values["height"] : "0"); + tool.dirty = true; + fouling_update(); + WriteLog("SELFTEST fouling: " + tool.status); + int shown{0}; + for (auto const &found : tool.found) + { + if (false == found.wrong) + continue; + if (shown == 5) + break; + ++shown; + WriteLog(format("SELFTEST fouling: %s %.2f m off, %+.3f m high", found.marker.file.c_str(), found.error, found.height_error)); + } + if (values["place"] == "one") + { + // the first fouling point without a marker alone, as a click on it in the view + for (int index = 0; index < static_cast(tool.points.size()); ++index) + if (tool.points[index].standing < 0) + { + place(index); + break; + } + tool.dirty = true; + fouling_update(); + WriteLog("SELFTEST fouling one: " + tool.status); + } + if (values["place"] == "1") + { + place(); + tool.dirty = true; + fouling_update(); + WriteLog("SELFTEST fouling after placing: " + tool.status); + } + if (values["fix"] == "1") + { + fix(); + tool.dirty = true; + fouling_update(); + WriteLog("SELFTEST fouling after the fix: " + tool.status); + } + return editor_selftest_result::handled; + } + return editor_selftest_result::unhandled; +} diff --git a/application/editormodelineside.h b/application/editormodelineside.h new file mode 100644 index 000000000..1ace4a1ce --- /dev/null +++ b/application/editormodelineside.h @@ -0,0 +1,156 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include "application/editortool.h" + +#include +#include +#include +#include + +// hectometre posts along the line, at every 100 m of the kilometrage +class hekto_tool final : public editor_tool +{ + public: + hekto_tool(editor_selection &Selection, editor_view &View, editor_history &History, editor_templates &Templates, editor_ground &Ground, editor_guide &Guide) : m_selection{Selection}, m_view{View}, m_history{History}, m_templates{Templates}, m_ground{Ground}, m_guide{Guide} {} + void draw_overlay() const override; + void render_options() override; + editor_selftest_result selftest(std::string const &Command, std::istringstream &Words) override; + tool_tab &tab() { return m_tab; } + void start(TTrack &Track, glm::dvec3 const &Point); + + private: + editor_selection &m_selection; + editor_view &m_view; + editor_history &m_history; + editor_templates &m_templates; + editor_ground &m_ground; + editor_guide &m_guide; + tool_tab m_tab; + struct hekto_post + { + int hectometres{0}; + double chainage{0.0}; + glm::dvec3 position{0.0}; + double yaw{0.0}; + int growth{1}; // 1: the kilometrage grows along the line there, -1: against + int standing{-1}; // post already there with this number + }; + struct hekto_found + { + standing_template post; + int hectometres{0}; + double chainage{0.0}; // where it stands along the line + double expected{0.0}; // where its number belongs + double error{0.0}; // m along the line + double distance{0.0}; // m from where it belongs, in the plan + bool wrong{false}; + bool duplicate{false}; // another post with the same number stands nearer to its place + bool outside{false}; // its number belongs past the ends of the line + int place{-1}; // of the posts, the one with its number nearest to it + }; + struct hekto_state + { + TTrack *track{nullptr}; // the line runs through it + glm::dvec3 point{0.0}; // where the kilometrage is given + double km{0.0}; + bool km_read{false}; // the kilometrage was read from the posts already standing + int growth{1}; // 1: grows along the line, -1: against + std::string line; // of the kilometrage set for the line in the Kilometrage tool the posts follow, empty for the one given here + std::string line_set; // the line the Kilometrage tool sets the kilometrage of at the point, empty for none + bool own_km{false}; // the kilometrage given here, even where the line has one set + int side{1}; // 1: to the right of the growing kilometrage, -1: to the left, 0: alternately + double offset{3.0}; // m from the axis + int style{0}; // nowy, stary, zgnity, mixed + int turn{0}; // degrees added to the rotation + double reach{10000.0}; // m each way + double tolerance{5.0}; // m along the line, for the posts standing + bool dirty{true}; + std::size_t history{0}; + editor_track::route route; + std::vector samples; + double origin{0.0}; // chainage of the point + std::vector posts; + std::vector found; + std::string status; + std::string error; + }; + hekto_state m_hekto; + void hekto_update(); + void hekto_read_kilometrage(); + void hekto_place(); + void hekto_fix(); + void hekto_remove_duplicates(); +}; + +// fouling point markers (W17) where the tracks meeting at a switch are the spacing apart +class fouling_tool final : public editor_tool +{ + public: + fouling_tool(editor_selection &Selection, editor_view &View, editor_history &History, editor_templates &Templates, editor_ground &Ground) : m_selection{Selection}, m_view{View}, m_history{History}, m_templates{Templates}, m_ground{Ground} {} + void draw_overlay() const override; + void render_options() override; + editor_selftest_result selftest(std::string const &Command, std::istringstream &Words) override; + tool_tab &tab() { return m_tab; } + // the markers put at the fouling points without one, or at the one only + void place(int const Only = -1); + // the markers standing wrong moved to their places, or the one found only + void fix(int const Only = -1); + // the fouling point without a marker or the marker standing wrong under the cursor: the index of the point or of the + // marker found, and whether it's a marker + std::optional> hit() const; + glm::dvec3 position_of(std::pair const &Hit) const; + void check_selected_switch(); + + private: + editor_selection &m_selection; + editor_view &m_view; + editor_history &m_history; + editor_templates &m_templates; + editor_ground &m_ground; + tool_tab m_tab; + struct fouling_point + { + TTrack *track{nullptr}; // the switch + glm::dvec3 position{0.0}; + double yaw{0.0}; + int standing{-1}; // marker already there + }; + struct fouling_found + { + standing_template marker; + int point{-1}; // the fouling point it belongs to + double error{0.0}; // m from where it belongs + double height_error{0.0}; // m over where it belongs + bool wrong{false}; + }; + struct fouling_state + { + int scope{1}; // 0: the selected switch, 1: around the camera, 2: the whole scenery + double reach{1500.0}; + double spacing{3.5}; // m between the axes + double tolerance{2.0}; // m, a marker farther than this from its point is wrong + int height_mode{1}; // 0: on the ground, 1: at the height given over the rail heads + double height{0.0}; // m over the rail heads + double height_tolerance{0.03}; // m, a marker standing higher or lower than this is wrong + int model{0}; // w17, w17_new, w17_old, w17_dwuteo + int turn{0}; + bool dirty{true}; + std::size_t history{0}; + TTrack *selected{nullptr}; + std::vector points; + std::vector found; + std::string status; + std::string error; + }; + fouling_state m_fouling; + void fouling_update(); +}; diff --git a/application/editormodeminimap.cpp b/application/editormodeminimap.cpp new file mode 100644 index 000000000..2717cd447 --- /dev/null +++ b/application/editormodeminimap.cpp @@ -0,0 +1,530 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "application/editormodeminimap.h" +#include "application/editormoderide.h" +#include "application/editoruilayer.h" +#include "editor/editorFormat.hpp" +#include "editor/editorKilometrage.hpp" +#include "simulation/simulation.h" +#include "utilities/Globals.h" +#include "utilities/Logs.h" +#include "utilities/translation.h" +#include "utilities/utilities.h" +#include "vehicle/Camera.h" +#include "world/Event.h" +#include "world/MemCell.h" +#include "world/Segment.h" +#include "world/Track.h" +#include "imgui/imgui.h" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + +constexpr char const *stop_prefix{"PassengerStopPoint:"}; + +// the name of the station out of the text of a stop point, cut at '#' which only makes the text unique +std::string stop_name(std::string const &Text) +{ + auto name{Text.substr(std::string{stop_prefix}.size())}; + if (auto const hash{name.find('#')}; hash != std::string::npos) + name.erase(hash); + while (false == name.empty() && std::isspace(static_cast(name.back()))) + name.pop_back(); + return name; +} + +// lower case without the polish letters, of a text in windows-1250 +std::string folded(std::string Text) +{ + win1250_to_ascii(Text); + std::transform(Text.begin(), Text.end(), Text.begin(), [](unsigned char const Character) { return static_cast(std::tolower(Character)); }); + return Text; +} + +// the way the camera looks in the plan +glm::dvec3 camera_look() +{ + return {-std::sin(Global.pCamera.Angle.y), 0.0, -std::cos(Global.pCamera.Angle.y)}; +} + +// the path of the track nearest to the point and the point of it, for a track and a point given +int path_at(TTrack const &Track, glm::dvec3 const &Point, glm::dvec3 &On) +{ + return kilometrage::path_near(Track, Point, On); +} + +} // namespace + +bool minimap_tool::stale(std::size_t &Seen) const +{ + auto const now{m_history.history_revision() * 1000003u ^ simulation::Paths.sequence().size() * 7919u ^ simulation::Memory.sequence().size() * 104729u ^ simulation::Events.sequence().size()}; + if (now == Seen) + return false; + Seen = now; + return true; +} + +void minimap_tool::gather_lines() +{ + if (false == stale(m_lines_seen)) + return; + m_lines.clear(); + m_low = glm::dvec2{std::numeric_limits::max()}; + m_high = glm::dvec2{std::numeric_limits::lowest()}; + for (auto *track : simulation::Paths.sequence()) + { + if (track == nullptr || track->m_editorremoved || (track->iCategoryFlag & 1) == 0 || track->eType == tt_Cross) + continue; + for (int path = 0; path < track->path_count(); ++path) + { + track_ride_walk::place const place{track, track->eType == tt_Switch ? path : -1, 0.0}; + auto const *segment{track_ride_walk::segment(place)}; + if (segment == nullptr || segment->GetLength() <= 0.0) + continue; + line drawn; + drawn.track = track; + drawn.low = glm::dvec2{std::numeric_limits::max()}; + drawn.high = glm::dvec2{std::numeric_limits::lowest()}; + auto const count{std::clamp(static_cast(segment->GetLength() / 10.0), 1, 32)}; + for (int i = 0; i <= count; ++i) + { + auto const point{segment->FastGetPoint(static_cast(i) / count)}; + glm::dvec2 const plan{point.x, point.z}; + drawn.points.push_back(plan); + drawn.low = glm::min(drawn.low, plan); + drawn.high = glm::max(drawn.high, plan); + } + m_low = glm::min(m_low, drawn.low); + m_high = glm::max(m_high, drawn.high); + m_lines.push_back(std::move(drawn)); + } + } +} + +void minimap_tool::gather_stations() +{ + if (false == stale(m_stations_seen)) + return; + std::map found; + // the texts are in windows-1250; the ones of the events lost their polish letters as they were read + auto const add = [&](std::string const &Text, bool const Letters, glm::dvec3 const &Point, TTrack *Track) { + auto const name{stop_name(Text)}; + if (name.empty()) + return; + auto const key{folded(name)}; + auto &entry{found[key]}; + entry.key = key; + // the timetables join the words with underscores + if (entry.name.empty() || Letters) + { + entry.name = win1250_to_utf8(name); + std::replace(entry.name.begin(), entry.name.end(), '_', ' '); + } + if (Track == nullptr) + { + int path{0}; + Track = kilometrage::track_near(Point, 15.0, path); + } + entry.stops.push_back({Point, Track}); + }; + for (auto *cell : simulation::Memory.sequence()) + if (cell != nullptr && cell->Text().starts_with(stop_prefix)) + add(cell->Text(), true, cell->location(), cell->Track); + for (auto *event : simulation::Events.sequence()) + if (auto const *values{dynamic_cast(event)}; values != nullptr && values->input_command() == TCommandType::cm_PassengerStopPoint) + add(values->input_text(), false, values->input_location(), nullptr); + std::vector stations; + for (auto &entry : found) + stations.push_back(std::move(entry.second)); + // the next stop kept for the stations still there + for (auto &station : stations) + for (auto const &old : m_stations) + if (old.key == station.key) + station.next = old.next; + m_stations = std::move(stations); +} + +std::vector const &minimap_tool::stations() +{ + gather_stations(); + return m_stations; +} + +void minimap_tool::go_to(station &Station) +{ + if (Station.stops.empty()) + return; + auto const &stop{Station.stops[Station.next % Station.stops.size()]}; + ++Station.next; + m_marked = Station.key; + // a map not going with the camera goes over to the stop + if (false == m_follow) + m_centre = {stop.point.x, stop.point.z}; + glm::dvec3 on{stop.point}; + auto const path{stop.track != nullptr ? path_at(*stop.track, stop.point, on) : 0}; + if (m_ride.active()) + { + if (stop.track != nullptr && m_ride.enter(stop.track, path, stop.point, camera_look(), true)) + return; + m_ride.leave(); + } + // from behind and above the stop, looking along the track and down to it + auto ahead{camera_look()}; + if (stop.track != nullptr) + { + track_ride_walk::place place{stop.track, stop.track->eType == tt_Switch ? path : -1, 0.0}; + if (auto const *segment{track_ride_walk::segment(place)}) + { + place.s = track_ride_walk::nearest_distance(*segment, stop.point); + glm::dvec3 point, forward; + if (track_ride_walk::frame(place, point, forward)) + { + on = point; + ahead = glm::dot(glm::dvec2{forward.x, forward.z}, glm::dvec2{ahead.x, ahead.z}) >= 0.0 ? forward : -forward; + } + } + } + auto const plan{std::hypot(ahead.x, ahead.z)}; + glm::dvec3 const look{glm::normalize(glm::dvec3{ahead.x / std::max(plan, 1e-9) * 0.9, -0.42, ahead.z / std::max(plan, 1e-9) * 0.9})}; + m_view.fly_to(on, look, 45.0, 0.8); +} + +void minimap_tool::go_to_point(glm::dvec3 const &Point, double const Reach) +{ + int path{0}; + auto *track{kilometrage::track_near(Point, Reach, path)}; + glm::dvec3 on{Point}; + if (track != nullptr) + kilometrage::path_near(*track, Point, on); + if (m_ride.active()) + { + if (track != nullptr && m_ride.enter(track, path, on, camera_look(), false)) + return; + m_ride.leave(); + } + auto const ahead{camera_look()}; + glm::dvec3 const look{glm::normalize(glm::dvec3{ahead.x * 0.8, -0.6, ahead.z * 0.8})}; + if (track != nullptr) + m_view.fly_to(on, look, 60.0, 0.6); + else + m_view.fly_to(glm::dvec3{Point.x, m_view.camera_position().y, Point.z}, look, 0.0, 0.6); +} + +void minimap_tool::forget(scene::basic_node const *Node) +{ + if (Node == nullptr) + return; + for (auto &station : m_stations) + for (auto &stop : station.stops) + if (stop.track == Node) + stop.track = nullptr; + for (auto &drawn : m_lines) + if (drawn.track == Node) + drawn.track = nullptr; +} + +void minimap_tool::render_search() +{ + gather_stations(); + ImGui::SetNextItemWidth(-1.0f); + // enter goes to the first one found + auto const entered{ImGui::InputTextWithHint("##stationsearch", STR_C("Find a station"), m_search, sizeof(m_search), ImGuiInputTextFlags_EnterReturnsTrue)}; + if (m_stations.empty()) + { + ImGui::TextDisabled("%s", STR_C("No W4 in the scenery")); + return; + } + auto const wanted{folded(utf8_to_win1250(m_search))}; + std::vector shown; + for (int i = 0; i < static_cast(m_stations.size()); ++i) + if (wanted.empty() || m_stations[i].key.find(wanted) != std::string::npos) + shown.push_back(i); + auto const rows{std::min(static_cast(shown.size()), 6)}; + if (shown.empty()) + { + ImGui::TextDisabled("%s", STR_C("Nothing found")); + return; + } + if (entered) + { + // the field lets the keys go, they drive the ride from there; a click on the station goes on to its next stop + go_to(m_stations[shown.front()]); + } + if (ImGui::BeginChild("##stations", ImVec2(0.0f, (rows + 0.3f) * ImGui::GetTextLineHeightWithSpacing()), ImGuiChildFlags_Borders)) + { + for (auto const index : shown) + { + auto &station{m_stations[index]}; + auto const label{station.stops.size() > 1 ? format("%s (%d)##%d", station.name.c_str(), static_cast(station.stops.size()), index) : format("%s##%d", station.name.c_str(), index)}; + if (ImGui::Selectable(label.c_str(), station.key == m_marked)) + go_to(station); + if (ImGui::IsItemHovered() && station.stops.size() > 1) + ImGui::SetTooltip("%s", STR_C("Click again for the next W4")); + } + } + ImGui::EndChild(); +} + +void minimap_tool::render_map(float const Height) +{ + gather_lines(); + auto const width{ImGui::GetContentRegionAvail().x}; + ImVec2 const size{std::max(width, 50.0f), std::max(Height, 80.0f)}; + auto const origin{ImGui::GetCursorScreenPos()}; + auto const camera{m_view.camera_position()}; + if (false == m_fitted && false == m_lines.empty()) + { + m_fitted = true; + m_centre = {camera.x, camera.z}; + m_scale = 2.0; + } + if (m_follow) + m_centre = {camera.x, camera.z}; + + // a window of its own: its own list of what's drawn, which mustn't go over 65536 vertices on the renderers without offsets + if (false == ImGui::BeginChild("##minimapcanvas", size, ImGuiChildFlags_None, ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse)) + { + ImGui::EndChild(); + return; + } + ImGui::InvisibleButton("##minimap", size); + auto const hovered{ImGui::IsItemHovered()}; + auto const &io{ImGui::GetIO()}; + glm::vec2 const mouse{io.MousePos.x, io.MousePos.y}; + glm::dvec2 const middle{origin.x + size.x * 0.5, origin.y + size.y * 0.5}; + // x to the right, z down: as the top view looking north along -z + auto const to_world = [&](glm::vec2 const &Screen) { return glm::dvec2{m_centre.x + (Screen.x - middle.x) * m_scale, m_centre.y + (Screen.y - middle.y) * m_scale}; }; + auto const to_screen = [&](glm::dvec2 const &World) { return ImVec2(static_cast(middle.x + (World.x - m_centre.x) / m_scale), static_cast(middle.y + (World.y - m_centre.y) / m_scale)); }; + if (hovered && io.MouseWheel != 0.0f) + { + auto const under{to_world(mouse)}; + m_scale = std::clamp(m_scale * std::pow(0.8, static_cast(io.MouseWheel)), 0.05, 500.0); + if (false == m_follow) + m_centre = {under.x - (mouse.x - middle.x) * m_scale, under.y - (mouse.y - middle.y) * m_scale}; + } + if (ImGui::IsItemActivated()) + { + m_pressed = mouse; + m_dragging = false; + } + if (ImGui::IsItemActive()) + { + if (glm::length(mouse - m_pressed) > 4.0f) + m_dragging = true; + if (m_dragging && (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)) + { + m_follow = false; + m_centre.x -= io.MouseDelta.x * m_scale; + m_centre.y -= io.MouseDelta.y * m_scale; + } + } + if (ImGui::IsItemDeactivated() && false == m_dragging) + { + auto const world{to_world(mouse)}; + go_to_point(glm::dvec3{world.x, camera.y, world.y}, std::max(20.0, 12.0 * m_scale)); + } + + auto *drawlist{ImGui::GetWindowDrawList()}; + ImVec2 const corner{origin.x + size.x, origin.y + size.y}; + drawlist->PushClipRect(origin, corner, true); + drawlist->AddRectFilled(origin, corner, IM_COL32(28, 32, 36, 255)); + auto const low{to_world({origin.x, origin.y})}; + auto const high{to_world({corner.x, corner.y})}; + auto const *ridden{m_ride.track()}; + // what's left of the vertices for the tracks, some kept for the stations, the camera and the scale + auto const budget{drawlist->VtxBuffer.Size + 56000}; + auto full{false}; + std::vector points; + std::unordered_set dots; + for (auto const &drawn : m_lines) + { + if (drawn.track == nullptr || drawn.high.x < low.x || drawn.low.x > high.x || drawn.high.y < low.y || drawn.low.y > high.y) + continue; + if (drawlist->VtxBuffer.Size > budget) + { + full = true; + break; + } + auto const colour{drawn.track == ridden ? IM_COL32(255, 170, 40, 255) : drawn.track->eType == tt_Switch ? IM_COL32(150, 200, 255, 230) : IM_COL32(200, 200, 200, 210)}; + auto const extent{std::max(drawn.high.x - drawn.low.x, drawn.high.y - drawn.low.y) / m_scale}; // px + // a track a pixel long a dot, one dot a pixel + if (extent < 1.5) + { + auto const at{to_screen(drawn.low)}; + if (dots.insert((static_cast(static_cast(static_cast(std::floor(at.x)))) << 32) | static_cast(static_cast(std::floor(at.y)))).second) + drawlist->AddRectFilled(at, ImVec2(at.x + 1.0f, at.y + 1.0f), colour); + continue; + } + auto const width{drawn.track == ridden ? 3.0f : 1.0f}; + // a short one from end to end, the longer ones through their points a few pixels apart + if (extent < 16.0 && drawn.track != ridden) + { + drawlist->AddLine(to_screen(drawn.points.front()), to_screen(drawn.points.back()), colour, width); + continue; + } + points.clear(); + for (auto const &point : drawn.points) + { + auto const at{to_screen(point)}; + if (points.empty() || &point == &drawn.points.back() || std::abs(at.x - points.back().x) + std::abs(at.y - points.back().y) > 4.0f) + points.push_back(at); + } + drawlist->AddPolyline(points.data(), static_cast(points.size()), colour, ImDrawFlags_None, width); + } + // the stations: a dot at each stop, the name at the first one in sight + for (int i = 0; i < static_cast(m_stations.size()); ++i) + { + auto const &station{m_stations[i]}; + auto const marked{station.key == m_marked}; + bool named{false}; + for (auto const &stop : station.stops) + { + auto const at{to_screen({stop.point.x, stop.point.z})}; + if (at.x < origin.x - 50.0f || at.x > corner.x + 50.0f || at.y < origin.y - 20.0f || at.y > corner.y + 20.0f) + continue; + // the stops stop short of the limit of the list too, a few hundred vertices kept for the camera and the scale + if (drawlist->VtxBuffer.Size > 64500) + { + full = true; + break; + } + drawlist->AddCircleFilled(at, marked ? 5.0f : 3.5f, marked ? IM_COL32(255, 80, 60, 255) : IM_COL32(255, 220, 60, 255)); + if (false == named && (marked || m_scale < 25.0)) + { + named = true; + drawlist->AddText(ImVec2(at.x + 6.0f, at.y - ImGui::GetTextLineHeight() * 0.5f), IM_COL32(255, 235, 150, 255), station.name.c_str()); + } + } + } + // the camera, a triangle the way it looks + { + auto const at{to_screen({camera.x, camera.z})}; + auto const look{camera_look()}; + ImVec2 const forward{static_cast(look.x), static_cast(look.z)}; + ImVec2 const side{-forward.y, forward.x}; + auto const point = [&](float const Ahead, float const Across) { return ImVec2(at.x + forward.x * Ahead + side.x * Across, at.y + forward.y * Ahead + side.y * Across); }; + drawlist->AddTriangleFilled(point(11.0f, 0.0f), point(-6.0f, 6.0f), point(-6.0f, -6.0f), IM_COL32(255, 60, 60, 255)); + drawlist->AddTriangle(point(11.0f, 0.0f), point(-6.0f, 6.0f), point(-6.0f, -6.0f), IM_COL32(0, 0, 0, 255), 1.0f); + } + // the scale bar + { + auto metres{100.0 * m_scale}; + auto const magnitude{std::pow(10.0, std::floor(std::log10(metres)))}; + metres = metres / magnitude >= 5.0 ? 5.0 * magnitude : metres / magnitude >= 2.0 ? 2.0 * magnitude : magnitude; + auto const pixels{static_cast(metres / m_scale)}; + ImVec2 const from{origin.x + 8.0f, corner.y - 10.0f}; + drawlist->AddLine(from, ImVec2(from.x + pixels, from.y), IM_COL32(255, 255, 255, 220), 2.0f); + auto const text{metres >= 1000.0 ? format("%g km", metres / 1000.0) : format("%g m", metres)}; + drawlist->AddText(ImVec2(from.x, from.y - ImGui::GetTextLineHeight() - 2.0f), IM_COL32(255, 255, 255, 220), text.c_str()); + } + if (full) + { + auto const *text{STR_C("Zoom in to see all the tracks")}; + drawlist->AddText(ImVec2(origin.x + 8.0f, origin.y + 6.0f), IM_COL32(255, 200, 120, 255), text); + } + drawlist->PopClipRect(); + ImGui::EndChild(); +} + +void minimap_tool::render_windows() +{ + if (false == m_open) + return; + // first in the top right corner of the view, over the scene rather than over the panels + ImVec2 const size{340.0f * Global.ui_scale, 460.0f * Global.ui_scale}; + ImGui::SetNextWindowPos(ImVec2(editor_ui::view_max().x - size.x - 60.0f, editor_ui::view_min().y + 50.0f), ImGuiCond_FirstUseEver); + ImGui::SetNextWindowSize(size, ImGuiCond_FirstUseEver); + ImGui::SetNextWindowBgAlpha(0.97f); + if (false == ImGui::Begin((std::string(STR_C("Minimap")) + "###minimap").c_str(), &m_open)) + { + ImGui::End(); + return; + } + render_search(); + ImGui::Checkbox(STR_C("Follow the camera"), &m_follow); + ImGui::SameLine(); + if (ImGui::SmallButton(STR_C("Whole scenery")) && false == m_lines.empty()) + { + m_fitted = true; + m_follow = false; + m_centre = (m_low + m_high) * 0.5; + auto const room{ImGui::GetContentRegionAvail()}; + m_scale = std::max((m_high.x - m_low.x) / std::max(room.x, 50.0f), (m_high.y - m_low.y) / std::max(room.y, 80.0f)) * 1.05; + } + render_map(ImGui::GetContentRegionAvail().y); + ImGui::End(); +} + +editor_selftest_result minimap_tool::selftest(std::string const &Command, std::istringstream &Words) +{ + if (Command == "minimap") + { + // minimap <0|1|2>: the window shown or hidden, 2: shown with the whole scenery in it, as its button does + int open{1}; + Words >> open; + m_open = open != 0; + if (open == 2) + { + gather_lines(); + m_fitted = true; + m_follow = false; + m_centre = (m_low + m_high) * 0.5; + m_scale = std::max(m_high.x - m_low.x, m_high.y - m_low.y) / 300.0; + } + return editor_selftest_result::handled; + } + if (Command == "stations") + { + // stations: logs the stations the W4 name, with their stops + gather_stations(); + WriteLog(format("SELFTEST stations: %d", static_cast(m_stations.size()))); + for (auto const &station : m_stations) + for (auto const &stop : station.stops) + WriteLog(format("SELFTEST station %s at %.2f %.2f %.2f track %s", station.name.c_str(), stop.point.x, stop.point.y, stop.point.z, stop.track != nullptr ? stop.track->name().c_str() : "-")); + return editor_selftest_result::handled; + } + if (Command == "station") + { + // station : the camera to the next stop of the first station whose name holds the text, as a click on the list + std::string text; + std::getline(Words >> std::ws, text); + gather_stations(); + auto const wanted{folded(utf8_to_win1250(text))}; + auto const found{std::find_if(m_stations.begin(), m_stations.end(), [&](station const &Station) { return Station.key.find(wanted) != std::string::npos; })}; + if (found == m_stations.end()) + WriteLog("SELFTEST station " + text + ": none"); + else + { + go_to(*found); + WriteLog("SELFTEST station " + text + ": " + found->name); + } + return editor_selftest_result::handled; + } + if (Command == "minimapclick") + { + // minimapclick : as a click on the map there + double x{0.0}; + double z{0.0}; + Words >> x >> z; + go_to_point(glm::dvec3{x, m_view.camera_position().y, z}, 30.0); + WriteLog(format("SELFTEST minimapclick %.2f %.2f", x, z)); + return editor_selftest_result::handled; + } + return editor_selftest_result::unhandled; +} diff --git a/application/editormodeminimap.h b/application/editormodeminimap.h new file mode 100644 index 000000000..07ceaebb5 --- /dev/null +++ b/application/editormodeminimap.h @@ -0,0 +1,85 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include "application/editortool.h" + +#include +#include + +class track_ride; + +// the tracks of the scenery seen from above with the camera on them, and the stations the stop indicators (W4) name, to find +// one by its name and go there +class minimap_tool final : public editor_tool +{ + public: + // a stop of passenger trains, as a W4 marks it + struct stop + { + glm::dvec3 point{0.0}; + TTrack *track{nullptr}; + }; + struct station + { + std::string name; // as shown + std::string key; // lower case, without the polish letters, the stops of the same name gathered by it + std::vector stops; + std::size_t next{0}; // the stop gone to the next time + }; + + minimap_tool(editor_view &View, editor_history &History, track_ride &Ride) : m_view{View}, m_history{History}, m_ride{Ride} {} + void render_windows() override; + void forget(scene::basic_node const *Node) override; + editor_selftest_result selftest(std::string const &Command, std::istringstream &Words) override; + bool is_open() const { return m_open; } + void toggle() { m_open = !m_open; } + // the stations of the scenery, gathered again where the scenery changed + std::vector const &stations(); + // the camera to the next stop of the station: riding along the track it rides on from there, else it flies over to it + void go_to(station &Station); + // the camera to the track nearest to the point of the plan, or above the point where there's none near + void go_to_point(glm::dvec3 const &Point, double const Reach); + + private: + // a path of a rail track as the map draws it + struct line + { + TTrack *track{nullptr}; + glm::dvec2 low{0.0}; + glm::dvec2 high{0.0}; + std::vector points; // x, z + }; + void gather_lines(); + void gather_stations(); + void render_search(); + void render_map(float const Height); + bool stale(std::size_t &Seen) const; + + editor_view &m_view; + editor_history &m_history; + track_ride &m_ride; + bool m_open{false}; + std::vector m_lines; + glm::dvec2 m_low{0.0}; // of all the lines + glm::dvec2 m_high{0.0}; + std::size_t m_lines_seen{~std::size_t{0}}; + std::vector m_stations; + std::size_t m_stations_seen{~std::size_t{0}}; + char m_search[64]{}; + std::string m_marked; // the key of the station last gone to, drawn larger + // the map + glm::dvec2 m_centre{0.0}; // x, z + double m_scale{4.0}; // m a pixel + bool m_follow{true}; // the centre goes with the camera + bool m_fitted{false}; + glm::vec2 m_pressed{0.0f}; + bool m_dragging{false}; +}; diff --git a/application/editormodenmt.cpp b/application/editormodenmt.cpp new file mode 100644 index 000000000..9476dc5cf --- /dev/null +++ b/application/editormodenmt.cpp @@ -0,0 +1,4573 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +// the heightmap terrain made from the digital terrain model of GUGiK: the scenery placed as its orthophoto is, the heights +// of the model moved up or down to meet the tracks it has already, the chunks around the camera or along the tracks made as +// the model comes in, and the formation of each track with its slopes kept as a modifier of the terrain + +#include "stdafx.h" +#include "application/editormode.h" +#include "application/editormodeshared.h" +#include "application/editoruilayer.h" +#include "application/editorprojection.h" +#include "editor/editorFormat.hpp" +#include "editor/editorGeometry.hpp" +#include "editor/editorKilometrage.hpp" +#include "editor/editorSettings.hpp" +#include "model/AnimModel.h" +#include "utilities/Globals.h" +#include "simulation/simulation.h" +#include "utilities/Logs.h" +#include "utilities/translation.h" +#include "world/Track.h" + +#include "imgui/imgui.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + +// how many places of the tracks the offset of the model is worked out from at most, each needing its square of the model +std::size_t constexpr fit_places{48}; +// the terrain under the tracks: places along them every so many m, the squares they're kept in, how far from the tracks the +// difference at them draws the model; past that the offset of the whole scenery +double constexpr anchor_step{25.0}; +double constexpr anchor_cell{100.0}; +double constexpr anchor_reach{300.0}; +double constexpr anchor_near{5.0}; + +std::pair anchor_cell_of(double const X, double const Z) +{ + return {static_cast(std::floor(X / anchor_cell)), static_cast(std::floor(Z / anchor_cell))}; +} + +// a path whose ends lie this far apart is an error of the scenery, as a point typed wrong: no grade line, no formation and no +// terrain along it +double constexpr broken_path{5000.0}; + +bool rail(TTrack const &Track) +{ + if ((Track.iCategoryFlag & 15) != 1 || Track.m_editorremoved || Track.m_paths.empty()) + return false; + auto const &path{Track.m_paths.front()}; + return geometry::plan_distance(path.points[segment_data::point::start], path.points[segment_data::point::end]) <= broken_path; +} + +// a choice of the new scenery as a card: a sketch of the ground a track lies on, the name and what it means; true when clicked. +// the real terrain: hills under an aerial photo, the track along them; none: the flat plane at 0 drawn as a grid +bool ground_card(char const *Id, char const *Title, char const *Text, bool const Hills, bool const Enabled, float const Width) +{ + auto const font{ImGui::GetFontSize()}; + auto const pad{std::round(font * 0.6f)}; + auto const sketch{std::round(font * 4.0f)}; + auto const wrap{Width - 2.0f * pad}; + auto const title{ImGui::CalcTextSize(Title, nullptr, false, wrap)}; + auto const text{ImGui::CalcTextSize(Text, nullptr, false, wrap)}; + auto const height{pad + sketch + pad * 0.6f + title.y + pad * 0.3f + text.y + pad}; + auto const top{ImGui::GetCursorScreenPos()}; + ImGui::BeginDisabled(false == Enabled); + auto const clicked{ImGui::InvisibleButton(Id, ImVec2(Width, height))}; + ImGui::EndDisabled(); + auto const hovered{Enabled && ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)}; + auto *list{ImGui::GetWindowDrawList()}; + ImVec2 const bottom{top.x + Width, top.y + height}; + auto const rounding{std::round(font * 0.4f)}; + auto const accent{family_colour(0)}; + list->AddRectFilled(top, bottom, ImGui::GetColorU32(hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), rounding); + list->AddRect(top, bottom, hovered ? accent : ImGui::GetColorU32(ImGuiCol_Border), rounding, 0, hovered ? 2.0f : 1.0f); + auto const alpha{Enabled ? 1.0f : 0.35f}; + auto const tint = [&](ImU32 const Colour) { return (Colour & ~IM_COL32_A_MASK) | (static_cast(((Colour >> IM_COL32_A_SHIFT) & 0xFF) * alpha) << IM_COL32_A_SHIFT); }; + ImVec2 const low{top.x + pad, top.y + pad}; + ImVec2 const high{top.x + Width - pad, top.y + pad + sketch}; + list->AddRectFilled(low, high, tint(IM_COL32(20, 26, 34, 255)), rounding * 0.6f); + list->PushClipRect(low, high, true); + int constexpr steps{48}; + auto const x_of = [&](float const Share) { return low.x + (high.x - low.x) * Share; }; + if (Hills) + { + auto const ground = [](float const Share) { return 0.45f + 0.18f * std::sin(Share * 7.0f + 0.4f) + 0.08f * std::sin(Share * 17.0f); }; + std::vector line; + for (int i = 0; i <= steps; ++i) + { + auto const share{static_cast(i) / steps}; + line.emplace_back(x_of(share), low.y + (high.y - low.y) * ground(share)); + } + // the strips under the line drawn without the soft edges, else seams show between them + auto const flags{list->Flags}; + list->Flags &= ~ImDrawListFlags_AntiAliasedFill; + for (int i = 0; i < steps; ++i) + list->AddQuadFilled(line[i], line[i + 1], ImVec2(line[i + 1].x, high.y), ImVec2(line[i].x, high.y), tint(IM_COL32(70, 110, 55, 200))); + list->Flags = flags; + list->AddPolyline(line.data(), static_cast(line.size()), tint(IM_COL32(150, 200, 110, 255)), 0, 1.5f); + // the track goes along the ground, a little above it on embankments, below it in cuttings + std::vector track; + for (int i = 0; i <= steps; ++i) + { + auto const share{static_cast(i) / steps}; + auto const smooth{0.45f + 0.09f * std::sin(share * 7.0f + 0.4f)}; + track.emplace_back(x_of(share), low.y + (high.y - low.y) * smooth - 2.0f); + } + list->AddPolyline(track.data(), static_cast(track.size()), tint(IM_COL32(235, 235, 235, 255)), 0, 2.5f); + } + else + { + auto const horizon{low.y + (high.y - low.y) * 0.35f}; + auto const grid{tint(IM_COL32(120, 130, 150, 120))}; + for (int i = 0; i <= 4; ++i) + { + auto const t{static_cast(i) / 4.0f}; + auto const y{horizon + (high.y - horizon) * t * t}; + list->AddLine(ImVec2(low.x, y), ImVec2(high.x, y), grid); + } + auto const middle{(low.x + high.x) * 0.5f}; + for (int i = -6; i <= 6; ++i) + list->AddLine(ImVec2(middle + i * (high.x - low.x) * 0.06f, horizon), ImVec2(middle + i * (high.x - low.x) * 0.22f, high.y), grid); + auto const level{horizon + (high.y - horizon) * 0.45f}; + list->AddLine(ImVec2(low.x, level), ImVec2(high.x, level), tint(IM_COL32(235, 235, 235, 255)), 2.5f); + } + list->PopClipRect(); + auto y{high.y + pad * 0.6f}; + list->AddText(nullptr, 0.0f, ImVec2(low.x, y), tint(ImGui::GetColorU32(ImGuiCol_Text)), Title, nullptr, wrap); + y += title.y + pad * 0.3f; + list->AddText(nullptr, 0.0f, ImVec2(low.x, y), tint(ImGui::GetColorU32(ImGuiCol_TextDisabled)), Text, nullptr, wrap); + return clicked && Enabled; +} + +// what a way of putting the tracks and the terrain together does, drawn along a track: onto, the track goes along the hills of +// the model; under, the track stays level and the ground comes to it; only, the hills of the model as they are over a level track +enum class way_sketch { onto, under, only }; + +// a way of the tracks and the terrain as a card the width of the panel: the sketch on the left, the name and what it's for on +// the right, the one to take first lit green; true when clicked +bool way_card(char const *Id, char const *Title, char const *Text, way_sketch const Sketch, bool const First, bool const Enabled) +{ + auto const font{ImGui::GetFontSize()}; + auto const pad{std::round(font * 0.5f)}; + auto const width{ImGui::GetContentRegionAvail().x}; + ImVec2 const sketch{std::round(font * 4.5f), std::round(font * 2.8f)}; + auto const left{pad + sketch.x + pad}; + auto const wrap{std::max(font * 4.0f, width - left - pad)}; + auto const title{ImGui::CalcTextSize(Title, nullptr, false, wrap)}; + auto const text{ImGui::CalcTextSize(Text, nullptr, false, wrap)}; + auto const height{pad + std::max(sketch.y, title.y + pad * 0.25f + text.y) + pad}; + auto const top{ImGui::GetCursorScreenPos()}; + ImGui::BeginDisabled(false == Enabled); + auto const clicked{ImGui::InvisibleButton(Id, ImVec2(width, height))}; + ImGui::EndDisabled(); + auto const hovered{Enabled && ImGui::IsItemHovered()}; + auto const held{Enabled && ImGui::IsItemActive()}; + auto *list{ImGui::GetWindowDrawList()}; + ImVec2 const bottom{top.x + width, top.y + height}; + auto const rounding{std::round(font * 0.4f)}; + auto const lit{First && Enabled}; + auto const green{IM_COL32(70, 170, 85, 255)}; + auto const fill{lit ? (held ? IM_COL32(45, 110, 55, 255) : hovered ? IM_COL32(40, 95, 50, 255) : IM_COL32(32, 72, 40, 255)) + : ImGui::GetColorU32(held ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg)}; + list->AddRectFilled(top, bottom, fill, rounding); + list->AddRect(top, bottom, lit ? green : hovered ? family_colour(0) : ImGui::GetColorU32(ImGuiCol_Border), rounding, 0, lit || hovered ? 2.0f : 1.0f); + auto const alpha{Enabled ? 1.0f : 0.35f}; + auto const tint = [&](ImU32 const Colour) { return (Colour & ~IM_COL32_A_MASK) | (static_cast(((Colour >> IM_COL32_A_SHIFT) & 0xFF) * alpha) << IM_COL32_A_SHIFT); }; + ImVec2 const low{top.x + pad, top.y + (height - sketch.y) * 0.5f}; + ImVec2 const high{low.x + sketch.x, low.y + sketch.y}; + list->AddRectFilled(low, high, tint(IM_COL32(20, 26, 34, 255)), rounding * 0.6f); + list->PushClipRect(low, high, true); + int constexpr steps{40}; + auto const at = [&](float const Share, float const Height) { return ImVec2(low.x + sketch.x * Share, low.y + sketch.y * Height); }; + auto const hills = [](float const Share) { return 0.52f + 0.2f * std::sin(Share * 6.0f + 0.4f) + 0.07f * std::sin(Share * 15.0f); }; + auto const level{0.5f}; + // the ground as a line and the strips under it, drawn without the soft edges, else seams show between them + auto const ground = [&](auto const &Height, ImU32 const Colour) { + std::vector line; + for (int i = 0; i <= steps; ++i) + { + auto const share{static_cast(i) / steps}; + line.push_back(at(share, Height(share))); + } + auto const flags{list->Flags}; + list->Flags &= ~ImDrawListFlags_AntiAliasedFill; + for (int i = 0; i < steps; ++i) + list->AddQuadFilled(line[i], line[i + 1], ImVec2(line[i + 1].x, high.y), ImVec2(line[i].x, high.y), tint(Colour)); + list->Flags = flags; + list->AddPolyline(line.data(), static_cast(line.size()), tint(IM_COL32(150, 200, 110, 255)), 0, 1.5f); + }; + auto const track = [&](auto const &Height) { + std::vector line; + for (int i = 0; i <= steps; ++i) + { + auto const share{static_cast(i) / steps}; + line.push_back(at(share, Height(share))); + line.back().y -= 2.0f; + } + list->AddPolyline(line.data(), static_cast(line.size()), tint(IM_COL32(235, 235, 235, 255)), 0, 2.5f); + }; + switch (Sketch) + { + case way_sketch::onto: + // the track goes along the ground, a little above it on embankments, below it in cuttings + ground(hills, IM_COL32(70, 110, 55, 220)); + track([](float const Share) { return 0.52f + 0.1f * std::sin(Share * 6.0f + 0.4f); }); + break; + case way_sketch::under: + { + // the hills of the model faint where they were, the ground drawn up and down to the level track, fading out of it + std::vector was; + for (int i = 0; i <= steps; ++i) + { + auto const share{static_cast(i) / steps}; + was.push_back(at(share, hills(share))); + } + list->AddPolyline(was.data(), static_cast(was.size()), tint(IM_COL32(150, 200, 110, 90)), 0, 1.0f); + ground([&](float const Share) { return level + 0.04f + 0.25f * (hills(Share) - level); }, IM_COL32(70, 110, 55, 220)); + track([&](float) { return level; }); + break; + } + case way_sketch::only: + // the level track first, the hills over it: it shows above the hollows and goes into the hills + track([&](float) { return level; }); + ground(hills, IM_COL32(70, 110, 55, 235)); + break; + } + list->PopClipRect(); + auto const x{top.x + left}; + auto y{top.y + (height - (title.y + pad * 0.25f + text.y)) * 0.5f}; + list->AddText(nullptr, 0.0f, ImVec2(x, y), tint(ImGui::GetColorU32(ImGuiCol_Text)), Title, nullptr, wrap); + y += title.y + pad * 0.25f; + list->AddText(nullptr, 0.0f, ImVec2(x, y), tint(lit ? IM_COL32(200, 225, 200, 255) : ImGui::GetColorU32(ImGuiCol_TextDisabled)), Text, nullptr, wrap); + return clicked && Enabled; +} + +// m, the squares of the plan the points of the lines are kept in +double constexpr kPlanCell{50.0}; + +// a bridge or a tunnel keeps the model under it as it is, and a turntable its pit +bool shapes_ground(TTrack const &Track) +{ + return Track.eEnvironment != e_bridge && Track.eEnvironment != e_tunnel && Track.eType != tt_Table; +} + +// the name the formation of a track is known by in the terrain, of a track with no name where it lies: two of the same name +// would be one formation +std::string formation_name(TTrack const &Track) +{ + if (false == Track.name().empty() || Track.m_paths.empty()) + return Track.name(); + auto const &points{Track.m_paths.front().points}; + auto const &start{points[segment_data::point::start]}; + auto const &end{points[segment_data::point::end]}; + return format("@%.2f,%.2f>%.2f,%.2f", start.x, start.z, end.x, end.z); +} + +// an end of a path no other path is linked to +struct loose_end +{ + TTrack *track{nullptr}; + int path{0}; + bool atend{false}; + glm::dvec3 point{0.0}; + glm::dvec3 outward{0.0}; // off the path along it +}; + +loose_end end_of(TTrack &Track, int const Path, bool const Atend) +{ + auto const &points{Track.m_paths[Path].points}; + auto const &point{points[Atend ? segment_data::point::end : segment_data::point::start]}; + auto const &control{points[Atend ? segment_data::point::control2 : segment_data::point::control1]}; + auto const &other{points[Atend ? segment_data::point::start : segment_data::point::end]}; + return {&Track, Path, Atend, point, control != glm::dvec3{} ? -control : point - other}; +} + +// a track runs up to a turntable with its end this near the rim, facing the centre this closely (the cosine), as high as the +// table give or take, the table dropped into its pit too; the model this far past the rim lies beside the pit, past its wall; +// the line keeps level this far off the rim +double constexpr kRimNear{0.3}; // m +double constexpr kRimFacing{0.9}; +double constexpr kRimLevel{3.0}; // m +double constexpr kPitWall{1.5}; // m +double constexpr kRunUp{10.0}; // m + +bool on_rim(loose_end const &End, glm::dvec3 const &Centre, double const Rim) +{ + auto const outward{geometry::plan_of(End.outward)}; + auto const inward{geometry::plan_of(Centre - End.point)}; + return std::abs(glm::length(inward) - Rim) <= kRimNear && std::abs(End.point.y - Centre.y) <= kRimLevel && glm::length(outward) > 1e-6 && + glm::dot(outward, inward) >= kRimFacing * glm::length(outward) * glm::length(inward); +} + +// ends which meet in the plan facing each other, laid apart in height by hand, so the game doesn't join them; farther apart +// than a track over another can be, they lie on two levels +std::vector> loose_pairs() +{ + double constexpr kLevel{2.0}; // m + auto const linked = [](TTrack const &Track, int const Path, bool const Atend) { + if (Track.eType == tt_Switch && Track.SwitchExtension) + return (Atend ? Track.SwitchExtension->pNexts[Path & 1] : Track.SwitchExtension->pPrevs[Path & 1]) != nullptr; + return (Atend ? Track.trNext : Track.trPrev) != nullptr; + }; + std::map, std::vector> cells; + for (auto *track : simulation::Paths.sequence()) + { + if (track == nullptr || false == rail(*track) || track->Length() < 0.01) + continue; + for (int i = 0; i < static_cast(track->m_paths.size()); ++i) + for (auto const atend : {false, true}) + if (false == linked(*track, i, atend)) + { + auto const end{end_of(*track, i, atend)}; + cells[{static_cast(std::floor(end.point.x)), static_cast(std::floor(end.point.z))}].push_back(end); + } + } + std::vector> result; + std::set> taken; + for (auto const &[cell, ends] : cells) + for (auto const &a : ends) + { + if (taken.contains({a.track, a.path, a.atend})) + continue; + loose_end const *match{nullptr}; + for (int dx = -1; dx <= 1 && match == nullptr; ++dx) + for (int dz = -1; dz <= 1 && match == nullptr; ++dz) + { + auto const found{cells.find({cell.first + dx, cell.second + dz})}; + if (found == cells.end()) + continue; + auto const outward{geometry::plan_of(a.outward)}; + for (auto const &b : found->second) + if (b.track != a.track && false == taken.contains({b.track, b.path, b.atend}) && geometry::plan_distance(a.point, b.point) <= geometry::same_point && + std::abs(a.point.y - b.point.y) <= kLevel && glm::dot(outward, geometry::plan_of(b.outward)) < -0.5 * glm::length(outward) * glm::length(geometry::plan_of(b.outward))) + { + match = &b; + break; + } + } + if (match == nullptr) + continue; + taken.insert({a.track, a.path, a.atend}); + taken.insert({match->track, match->path, match->atend}); + result.emplace_back(a, *match); + } + return result; +} + +} // namespace + +std::vector editor_mode::nmt_track_places(double const Step) const +{ + std::vector result; + // a track with no trackbed of its own, as the switches of the older sceneries whose bed is an include, lies in the bed of + // the others + std::vector depths; + for (auto *track : simulation::Paths.sequence()) + if (track != nullptr && rail(*track) && profile_own_bed(*track)) + depths.push_back(profile_ballast(*track).first); + std::nth_element(depths.begin(), depths.begin() + depths.size() / 2, depths.end()); + auto const usual{depths.empty() ? 0.0 : depths[depths.size() / 2]}; + for (auto *track : simulation::Paths.sequence()) + { + if (track == nullptr || false == rail(*track)) + continue; + auto const rails{static_cast(track->rail_height())}; + for (std::size_t path = 0; path < track->m_paths.size(); ++path) + { + // the ballast drawn under the path: a switch has it of the plain track it goes on into, as the renderer lays it + auto const *source{track}; + if (track->eType == tt_Switch && track->SwitchExtension != nullptr && path < 2) + { + auto const *previous{track->SwitchExtension->pPrevs[path]}; + auto const *next{track->SwitchExtension->pNexts[path]}; + source = previous != nullptr && previous->eType != tt_Switch ? previous : next != nullptr && next->eType != tt_Switch ? next : track; + } + auto ballast{profile_ballast(*source)}; + if (false == profile_own_bed(*source)) + ballast.first = usual; + geometry::bezier const curve{track->m_paths[path]}; + auto const &points{track->m_paths[path].points}; + auto const chord{glm::distance(points[segment_data::point::start], points[segment_data::point::end])}; + auto const count{std::max(1, static_cast(std::ceil(chord * 1.1 / Step)))}; + for (int i = 0; i <= count; ++i) + { + auto const at{curve.point(static_cast(i) / count)}; + result.push_back({at, at.y - ballast.first, at.y - rails, ballast.second, track, static_cast(path), shapes_ground(*track)}); + } + } + } + // a track passing over another one by more than the clearance, as at a flyover whose bridge is a model: where the slopes of its + // embankment would bury the track below, it stands on a bridge, and the ground there is the lower track's + double constexpr clearance{3.0}; + double constexpr cell{20.0}; + auto const key_of = [&](double const X, double const Z) { return (static_cast(std::floor(X / cell)) << 32) ^ (static_cast(std::floor(Z / cell)) & 0xffffffff); }; + std::unordered_map> grid; + double widest{0.0}; + double lowest{std::numeric_limits::max()}, highest{std::numeric_limits::lowest()}; + for (std::size_t i = 0; i < result.size(); ++i) + { + grid[key_of(result[i].position.x, result[i].position.z)].push_back(i); + widest = std::max(widest, result[i].half_width); + lowest = std::min(lowest, result[i].crown); + highest = std::max(highest, result[i].formation); + } + // the farthest the slopes of an embankment over a track can reach + auto const reach{2.0 * widest + m_nmt_state.slope * std::max(0.0, highest - lowest)}; + auto const span{static_cast(std::ceil(std::min(reach, 60.0) / cell))}; + std::vector over(result.size(), 0); + for (std::size_t i = 0; i < result.size(); ++i) + { + auto const &place{result[i]}; + if (false == place.shapes) + continue; + auto const cx{static_cast(std::floor(place.position.x / cell))}; + auto const cz{static_cast(std::floor(place.position.z / cell))}; + for (auto dz = -span; dz <= span && 0 == over[i]; ++dz) + for (auto dx = -span; dx <= span && 0 == over[i]; ++dx) + { + auto const found{grid.find(((cx + dx) << 32) ^ ((cz + dz) & 0xffffffff))}; + if (found == grid.end()) + continue; + for (auto const j : found->second) + { + auto const &other{result[j]}; + if (other.track == place.track) + continue; + auto const height{place.formation - other.crown}; + if (height < clearance) + continue; + auto const distance{glm::distance(glm::dvec2{place.position.x, place.position.z}, glm::dvec2{other.position.x, other.position.z})}; + if (distance <= place.half_width + other.half_width + m_nmt_state.slope * height) + { + over[i] = 1; + break; + } + } + } + } + for (std::size_t i = 0; i < result.size(); ++i) + if (over[i] != 0) + result[i].shapes = false; + // nor where the grade lines went over the model falling away by the abutments of a bridge or a viaduct + double constexpr bridged_near{1.0}; + double constexpr bridged_level{1.0}; + auto const &bridged{m_nmt_state.bridged}; + if (false == bridged.empty()) + for (auto &place : result) + { + if (false == place.shapes) + continue; + auto const cx{static_cast(std::floor(place.position.x / kPlanCell))}; + auto const cz{static_cast(std::floor(place.position.z / kPlanCell))}; + for (int dx = -1; dx <= 1 && place.shapes; ++dx) + for (int dz = -1; dz <= 1 && place.shapes; ++dz) + if (auto const cell{bridged.find({cx + dx, cz + dz})}; cell != bridged.end()) + for (auto const &point : cell->second) + if (glm::length(glm::dvec2{point.x - place.position.x, point.z - place.position.z}) <= bridged_near && std::abs(point.y - place.position.y) <= bridged_level) + { + place.shapes = false; + break; + } + } + return result; +} + +void editor_mode::nmt_locate() +{ + auto const &config{m_orthophoto.settings()}; + m_nmt.place(config.north, config.east); +} + +void editor_mode::nmt_fit() +{ + nmt_locate(); + auto &state{m_nmt_state}; + state.error.clear(); + state.under = false; + state.fit.clear(); + auto const places{nmt_track_places(25.0)}; + std::vector shaped; + std::copy_if(places.begin(), places.end(), std::back_inserter(shaped), [](nmt_place const &Place) { return Place.shapes; }); + if (shaped.empty()) + { + state.offset = 0.0; + state.fitted = true; + state.status = STR("No tracks to fit the terrain model to: its heights are taken as they are"); + return; + } + // spread over the whole scenery, each place asking for its square of the model + auto const every{std::max(1, shaped.size() / fit_places)}; + for (std::size_t i = 0; i < shaped.size(); i += every) + state.fit.push_back(shaped[i]); + state.fitting = true; + state.fetch_most = 0; + state.status = STR("Fetching the terrain model under the tracks..."); +} + +void editor_mode::nmt_under_start() +{ + nmt_locate(); + auto &state{m_nmt_state}; + state.error.clear(); + state.fit.clear(); + state.anchors.clear(); + state.anchor_cells.clear(); + for (auto const &place : nmt_track_places(anchor_step)) + if (place.shapes) + state.fit.push_back(place); + if (state.fit.empty()) + { + state.status = STR("No tracks to make the terrain under"); + return; + } + state.under = true; + state.fitting = true; + state.fetch_most = 0; + state.result = false; + state.findings.clear(); + state.status = STR("Fetching the terrain model under the tracks..."); +} + +void editor_mode::nmt_under_anchors() +{ + auto &state{m_nmt_state}; + struct found + { + glm::dvec2 at; + double difference; + TTrack const *track; + int path; + }; + std::vector places; + for (auto const &place : state.fit) + if (double height; m_nmt.height(place.position.x, place.position.z, height)) + places.push_back({{place.position.x, place.position.z}, place.crown - height, place.track, place.path}); + state.anchors.clear(); + state.anchor_cells.clear(); + for (std::size_t i = 0; i < places.size(); ++i) + { + // a place where the model is off, as a bridge it doesn't know of or a cutting dug since, doesn't pull the terrain around + // it: the median of the places around it along the same path + std::vector around; + for (auto j{i >= 4 ? i - 4 : 0}; j < std::min(places.size(), i + 5); ++j) + if (places[j].track == places[i].track && places[j].path == places[i].path) + around.push_back(places[j].difference); + std::nth_element(around.begin(), around.begin() + around.size() / 2, around.end()); + state.anchor_cells[anchor_cell_of(places[i].at.x, places[i].at.y)].push_back(state.anchors.size()); + state.anchors.emplace_back(places[i].at.x, places[i].at.y, around[around.size() / 2]); + } +} + +double editor_mode::nmt_offset_at(double const X, double const Z) const +{ + auto const &state{m_nmt_state}; + if (false == state.under || state.anchors.empty()) + return state.offset; + // the places near weigh the most, down to nothing at the reach; the offset of the scenery weighs as one place at the reach + auto const cell{anchor_cell_of(X, Z)}; + auto const span{static_cast(std::ceil(anchor_reach / anchor_cell))}; + auto const outermost{1.0 / (anchor_reach * anchor_reach + anchor_near * anchor_near)}; + double sum{state.offset * outermost}; + double weights{outermost}; + for (int dz = -span; dz <= span; ++dz) + for (int dx = -span; dx <= span; ++dx) + { + auto const found{state.anchor_cells.find({cell.first + dx, cell.second + dz})}; + if (found == state.anchor_cells.end()) + continue; + for (auto const index : found->second) + { + auto const &anchor{state.anchors[index]}; + auto const squared{(anchor.x - X) * (anchor.x - X) + (anchor.y - Z) * (anchor.y - Z)}; + if (squared >= anchor_reach * anchor_reach) + continue; + auto const weight{1.0 / (squared + anchor_near * anchor_near) - outermost}; + sum += anchor.z * weight; + weights += weight; + } + } + return sum / weights; +} + +void editor_mode::nmt_finish_fit() +{ + auto &state{m_nmt_state}; + std::vector differences; + for (auto const &place : state.fit) + if (double height; m_nmt.height(place.position.x, place.position.z, height)) + differences.push_back(place.crown - height); + state.fitting = false; + if (differences.empty()) + { + state.status = STR("The terrain model has no data under the tracks: is the scenery placed where it is?"); + return; + } + std::sort(differences.begin(), differences.end()); + state.offset = differences[differences.size() / 2]; + std::vector deviations; + for (auto const difference : differences) + deviations.push_back(std::abs(difference - state.offset)); + std::sort(deviations.begin(), deviations.end()); + state.spread = deviations[deviations.size() / 2]; + state.fitted = true; + state.samples = differences.size(); + state.status = format(STR_P("The tracks lie %+.2f m against the terrain model (%zu place, they differ by %.2f m around it)", "The tracks lie %+.2f m against the terrain model (%zu places, they differ by %.2f m around it)", state.samples), state.offset, state.samples, state.spread); + if (state.spread > 10.0) + state.status += STR(". That's far too much: the place of the scenery is likely wrong, check the orthophoto"); + WriteLog("Editor: NMT - " + state.status, logtype::generic); + if (false == state.under) + return; + // the terrain under the tracks: drawn to them place by place, then made along them + nmt_under_anchors(); + auto const status{state.status}; + nmt_make(nmt_keys_along_tracks(), true); + state.status = status + "\n" + state.status; +} + +std::vector editor_mode::nmt_keys_around() const +{ + std::vector result; + auto const centre{heightmap::chunk_at(Camera.Pos.x, Camera.Pos.z)}; + auto const first{-(m_terrain_add_count - 1) / 2}; + for (int dz = 0; dz < m_terrain_add_count; ++dz) + for (int dx = 0; dx < m_terrain_add_count; ++dx) + { + heightmap::chunk_key const key{centre.first + first + dx, centre.second + first + dz}; + // none outside the download area + if (auto const low{heightmap::chunk_corner(key)}; in_download_area(low, low + glm::dvec2{heightmap::chunk_size})) + result.push_back(key); + } + return result; +} + +std::vector editor_mode::nmt_keys_along_tracks() const +{ + std::set keys; + auto const reach{static_cast(std::ceil(m_nmt_state.band / heightmap::chunk_size))}; + for (auto const &place : nmt_track_places(heightmap::chunk_size * 0.5)) + { + auto const at{heightmap::chunk_at(place.position.x, place.position.z)}; + for (int dz = -reach; dz <= reach; ++dz) + for (int dx = -reach; dx <= reach; ++dx) + { + heightmap::chunk_key const key{at.first + dx, at.second + dz}; + auto const low{heightmap::chunk_corner(key)}; + // the chunk reaches within the band of the track + glm::dvec2 const nearest{std::clamp(place.position.x, low.x, low.x + heightmap::chunk_size), std::clamp(place.position.z, low.y, low.y + heightmap::chunk_size)}; + if (glm::distance(nearest, glm::dvec2{place.position.x, place.position.z}) <= m_nmt_state.band && in_download_area(low, low + glm::dvec2{heightmap::chunk_size})) + keys.insert(key); + } + } + return {keys.begin(), keys.end()}; +} + +void editor_mode::nmt_make(std::vector const &Keys, bool const Reshape) +{ + auto &state{m_nmt_state}; + if (false == ensure_terrain()) + { + state.status = STR("The heightmap terrain can't be opened"); + return; + } + nmt_locate(); + state.given_up.clear(); + std::size_t queued{0}; + for (auto const &key : Keys) + { + if (std::find(state.pending.begin(), state.pending.end(), key) != state.pending.end()) + continue; + // a chunk of flat ground there, as made with no model or no ground under it, gets the ground of the model as a new one would + if (m_streamer.exists(key)) + { + if (false == nmt_flat_chunk(key)) + continue; + state.refill.insert(key); + } + state.pending.push_back(key); + ++queued; + } + state.made = 0; + state.empty = 0; + state.foreign = 0; + state.fetch_most = 0; + state.error.clear(); + // the chunks are the last step of the tracks put onto the terrain only after their grade lines + if (false == Reshape || queued == 0) + state.run = false; + if (queued > 0) + { + state.grown = false; + state.reshape = Reshape; + } + // the terrain comes with its photos, unless the user turned them off + if (queued > 0 && false == m_orthophoto.enabled() && false == m_orthophoto_chosen) + m_orthophoto.enabled(true); + state.status = queued > 0 ? format(STR_P("%zu chunk to make from the terrain model", "%zu chunks to make from the terrain model", queued), queued) : STR("There's terrain there already"); + // with chunks to make the formations are laid once they're made + if (Reshape && queued == 0 && state.shape) + { + nmt_shape_tracks(); + state.status += format(STR_P("; the formation of %zu path shaped", "; the formation of %zu paths shaped", state.shaped), state.shaped); + } +} + +bool editor_mode::nmt_ready(glm::dvec2 const &Min, glm::dvec2 const &Max) +{ + return m_nmt.request(Min, Max) && false == m_nmt.retrying(Min, Max); +} + +std::optional editor_mode::nmt_terrain_offset(std::vector const &Points, bool &Foreign) const +{ + Foreign = false; + std::vector differences; + for (auto const &point : Points) + if (double terrain, model; m_streamer.height_at(point.x, point.y, terrain) && m_nmt.height(point.x, point.y, model)) + differences.push_back(terrain - model); + if (differences.size() < 5) + return std::nullopt; + std::nth_element(differences.begin(), differences.begin() + differences.size() / 2, differences.end()); + auto const median{differences[differences.size() / 2]}; + // the formations of the tracks and the touch-ups of the brushes leave the terrain here and there, the rest keeps to the model + auto const along{std::count_if(differences.begin(), differences.end(), [&](double const Difference) { return std::abs(Difference - median) <= 0.3; })}; + if (static_cast(along) < 0.7 * static_cast(differences.size())) + { + Foreign = true; + return std::nullopt; + } + return median; +} + +std::optional editor_mode::nmt_seam_offset(heightmap::chunk_key const &Key, bool &Foreign) const +{ + auto const low{heightmap::chunk_corner(Key)}; + auto const size{heightmap::chunk_size}; + int constexpr steps{16}; + struct side + { + int dx; + int dz; + glm::dvec2 from; + glm::dvec2 to; + }; + side const sides[]{{-1, 0, low, {low.x, low.y + size}}, {1, 0, {low.x + size, low.y}, low + glm::dvec2{size}}, {0, -1, low, {low.x + size, low.y}}, {0, 1, {low.x, low.y + size}, low + glm::dvec2{size}}}; + std::vector points; + for (auto const &edge : sides) + if (m_streamer.exists({Key.first + edge.dx, Key.second + edge.dz})) + for (int i = 0; i <= steps; ++i) + points.push_back(edge.from + (edge.to - edge.from) * (static_cast(i) / steps) + glm::dvec2{edge.dx, edge.dz} * 0.01); + return nmt_terrain_offset(points, Foreign); +} + +void editor_mode::nmt_track_changed(std::vector const &Tracks) +{ + auto &state{m_nmt_state}; + if (state.restoring || state.laying || state.stage != nmt_state::automatic::idle || Tracks.empty() || false == m_streamer.active()) + return; + for (auto *track : Tracks) + if (track != nullptr) + state.changed.insert(track); + state.changed_time = ImGui::GetTime(); +} + +void editor_mode::nmt_track_gone(TTrack const &Track) +{ + auto &state{m_nmt_state}; + if (state.restoring || state.stage != nmt_state::automatic::idle || Track.name().empty() || false == m_streamer.active()) + return; + state.gone.insert(Track.name()); + state.changed_time = ImGui::GetTime(); +} + +void editor_mode::nmt_follow_tracks() +{ + auto &state{m_nmt_state}; + if (state.changed.empty() && state.gone.empty()) + return; + if (false == state.follow) + { + state.changed.clear(); + state.gone.clear(); + return; + } + if (state.stage != nmt_state::automatic::idle || state.fitting || ImGui::GetTime() - state.changed_time < 0.3 || ImGui::IsMouseDown(ImGuiMouseButton_Left) || ImGui::IsMouseDown(ImGuiMouseButton_Right)) + return; + // laying on, from the end of the track laid or dragged from a free end, the terrain waits for the laying to end: shaping it + // goes through every chunk under the tracks, a stall each click + if ((m_lay.active && false == m_lay.points.empty()) || m_extend.active) + return; + if (false == m_streamer.active()) + { + state.changed.clear(); + state.gone.clear(); + return; + } + auto const &modifiers{m_streamer.modifiers()}; + auto const of = [](heightmap::modifier const &Modifier, std::string const &Track) { return Modifier.name == "nmt " + Track || Modifier.name.starts_with("nmt " + Track + " "); }; + std::vector dropped; + for (auto const &name : state.gone) + if (simulation::Paths.find(name) == nullptr) + for (auto const &modifier : modifiers) + if (of(modifier, name)) + dropped.push_back(modifier.name); + state.gone.clear(); + // the tracks with a formation take it along; one with none leaves the terrain as it is, until it's drawn to the track + std::vector shaped; + for (auto *track : simulation::Paths.sequence()) + { + if (track == nullptr || false == state.changed.contains(track) || track->m_editorremoved || false == rail(*track) || track->name().empty()) + continue; + if (std::any_of(modifiers.begin(), modifiers.end(), [&](heightmap::modifier const &Modifier) { return of(Modifier, track->name()); })) + shaped.push_back(track); + } + state.changed.clear(); + if (dropped.empty() && shaped.empty()) + return; + // the terrain follows in the step of the history of the change of the tracks + terrain_history_step(); + auto const *top{m_history.empty() ? nullptr : m_history.back().terrain.get()}; + m_streamer.remove_modifiers(dropped); + auto const laid{shaped.empty() ? std::size_t{0} : nmt_shape_tracks(&shaped)}; + if (false == dropped.empty()) + forget_ground(); + terrain_history_step(); + auto const count{m_history.size()}; + auto const of_tracks = [](EditorSnapshot const &Step) { return Step.action == EditorSnapshot::Action::TrackEdit || (Step.action == EditorSnapshot::Action::Terrain && Step.joined); }; + if (count >= 2 && m_history.back().action == EditorSnapshot::Action::Terrain && m_history.back().terrain.get() != top && of_tracks(m_history[count - 2])) + m_history.back().joined = true; + WriteLog(format("Editor: NMT - the terrain followed the tracks: %zu formations laid, %zu taken away", laid, dropped.size()), logtype::generic); +} + +bool editor_mode::nmt_ahead(double const X, double const Z, double &Height) const +{ + auto const &state{m_nmt_state}; + if (false == state.grow || false == state.ahead.has_value() || false == m_nmt.placed() || false == m_nmt.height(X, Z, Height)) + return false; + Height += *state.ahead; + return true; +} + +bool editor_mode::nmt_ground(double const X, double const Z, double &Height) const +{ + if (nmt_ahead(X, Z, Height)) + return true; + if (false == m_nmt.placed() || false == m_nmt.height(X, Z, Height)) + return false; + Height += nmt_offset_at(X, Z); + return true; +} + +editor_mode::nmt_chunk editor_mode::add_chunk_from_nmt(heightmap::chunk_key const &Key, std::optional const Offset) +{ + auto const low{heightmap::chunk_corner(Key)}; + auto const high{low + glm::dvec2{heightmap::chunk_size}}; + if (false == nmt_ready(low - glm::dvec2{2.0}, high + glm::dvec2{2.0})) + return nmt_chunk::waiting; + auto const cells{heightmap::cells_for(m_terrain_spacing)}; + auto const side{static_cast(cells) + 1}; + auto const step{heightmap::chunk_size / cells}; + std::vector heights(side * side, m_terrain_baseheight); + std::vector found(side * side, 0); + // the offset over the chunk, every sixteenth of its side and between them along straight lines: it changes slowly + int constexpr coarse{16}; + std::array offsets; + for (int iz = 0; iz <= coarse; ++iz) + for (int ix = 0; ix <= coarse; ++ix) + offsets[iz * (coarse + 1) + ix] = Offset.has_value() ? *Offset : nmt_offset_at(low.x + ix * heightmap::chunk_size / coarse, low.y + iz * heightmap::chunk_size / coarse); + auto const offset_at = [&](double const X, double const Z) { + auto const u{std::clamp((X - low.x) / heightmap::chunk_size * coarse, 0.0, static_cast(coarse))}; + auto const v{std::clamp((Z - low.y) / heightmap::chunk_size * coarse, 0.0, static_cast(coarse))}; + auto const i{std::min(static_cast(u), coarse - 1)}; + auto const j{std::min(static_cast(v), coarse - 1)}; + auto const fu{u - i}; + auto const fv{v - j}; + auto const at = [&](int const I, int const J) { return offsets[J * (coarse + 1) + I]; }; + return (at(i, j) * (1.0 - fu) + at(i + 1, j) * fu) * (1.0 - fv) + (at(i, j + 1) * (1.0 - fu) + at(i + 1, j + 1) * fu) * fv; + }; + bool any{false}; + for (std::size_t iz = 0; iz < side; ++iz) + for (std::size_t ix = 0; ix < side; ++ix) + { + auto const index{iz * side + ix}; + if (double height; m_nmt.height(low.x + ix * step, low.y + iz * step, height)) + { + heights[index] = height + offset_at(low.x + ix * step, low.y + iz * step); + found[index] = 1; + any = true; + } + } + if (false == any) + return nmt_chunk::empty; + // where the model has no data the chunk goes on level with its nearest point + fill_from_nearest(heights, found, side); + auto const height = [&](double const X, double const Z) { + auto const ix{static_cast(std::clamp(std::lround((X - low.x) / step), 0, cells))}; + auto const iz{static_cast(std::clamp(std::lround((Z - low.y) / step), 0, cells))}; + return static_cast(heights[iz * side + ix]); + }; + if (false == m_streamer.exists(Key)) + { + m_streamer.add_chunk(Key.first, Key.second, m_terrain_spacing, height); + return nmt_chunk::made; + } + // a chunk of flat ground there already takes the heights of the model under the formations laid on it, which stay: the ground + // under them shaped, not a touch-up over them + auto const touchup{m_streamer.touch_up()}; + m_streamer.touch_up(false); + m_streamer.reshape(low, high, [&](double const X, double const Z, float &Height) { + Height = height(X, Z); + return true; + }); + m_streamer.touch_up(touchup); + return nmt_chunk::made; +} + +bool editor_mode::nmt_flat_chunk(heightmap::chunk_key const &Key) const +{ + auto const middle{heightmap::chunk_corner(Key) + glm::dvec2{0.5 * heightmap::chunk_size}}; + auto const *terrain{m_streamer.terrain_at(middle.x, middle.y)}; + if (terrain == nullptr || terrain->key() != Key) + return false; + auto const &data{terrain->data()}; + auto const &ground{data.base.empty() ? data.heights : data.base}; + if (ground.empty()) + return false; + auto const [lowest, highest]{std::minmax_element(ground.begin(), ground.end())}; + return *highest - *lowest < 0.01f; +} + +std::size_t editor_mode::nmt_shape_tracks(std::vector const *Only) +{ + auto &state{m_nmt_state}; + if (false == ensure_terrain()) + return 0; + auto const wanted = [&](TTrack const *Track) { return Only == nullptr || std::find(Only->begin(), Only->end(), Track) != Only->end(); }; + // one modifier per path: the formation under its axis and the slopes from its edges to the ground. laid over each other the + // modifiers keep the highest of the slopes going down and the lowest of those going up, so tracks side by side share one + // formation instead of a saw of their own ones + // a path broken by a bridge, as over another track, gets a modifier for each piece on the ground + std::map, heightmap::modifier> modifiers; + std::map, int> pieces; + double constexpr step{5.0}; + std::pair previous{nullptr, -1}; + bool broken{false}; + std::vector over; + for (auto const &place : nmt_track_places(step)) + { + if (false == wanted(place.track)) + continue; + std::pair const path{place.track, place.path}; + if (path != previous) + broken = false; + previous = path; + if (false == place.shapes) + { + broken = true; + over.push_back(place); + continue; + } + auto &piece{pieces[path]}; + if (broken) + { + ++piece; + broken = false; + } + auto &modifier{modifiers[{place.track, place.path, piece}]}; + if (modifier.name.empty()) + { + modifier.name = "nmt " + formation_name(*place.track) + (place.track->m_paths.size() > 1 ? " " + std::to_string(place.path) : std::string{}) + (piece > 0 ? " #" + std::to_string(piece) : std::string{}); + modifier.slope = state.slope; + modifier.reach = state.reach; + } + modifier.points.push_back({{place.position.x, place.position.z}, place.formation, place.half_width}); + } + // a formation which ends by a bridge or a tunnel ends square against its abutment, its portal, whichever path goes on over it + auto const walled = [&](heightmap::corridor_point const &End) { + return std::any_of(over.begin(), over.end(), [&](nmt_place const &Place) { + return glm::distance(glm::dvec2{Place.position.x, Place.position.z}, End.position) <= step * 1.5 && std::abs(Place.formation - End.formation) <= 1.0; + }); + }; + std::vector laid; + for (auto &[path, modifier] : modifiers) + if (modifier.points.size() >= 2) + { + modifier.open_start = walled(modifier.points.front()); + modifier.open_end = walled(modifier.points.back()); + laid.push_back(std::move(modifier)); + } + if (Only != nullptr) + { + // the formations as they are already aren't led into the terrain again + auto const same = [](heightmap::modifier const &A, heightmap::modifier const &B) { + return A.slope == B.slope && A.reach == B.reach && A.rounding == B.rounding && A.open_start == B.open_start && A.open_end == B.open_end && A.points.size() == B.points.size() && + std::equal(A.points.begin(), A.points.end(), B.points.begin(), [](heightmap::corridor_point const &P, heightmap::corridor_point const &Q) { + return glm::distance(P.position, Q.position) < 1e-6 && std::abs(P.formation - Q.formation) < 1e-6 && std::abs(P.half_width - Q.half_width) < 1e-6; + }); + }; + auto const &existing{m_streamer.modifiers()}; + // the formations the tracks have, the ones as they are already too: those only aren't led again, nor taken out as gone + std::unordered_set kept; + for (auto const &modifier : laid) + kept.insert(modifier.name); + std::erase_if(laid, [&](heightmap::modifier const &Modifier) { + auto const found{std::find_if(existing.begin(), existing.end(), [&](heightmap::modifier const &Other) { return Other.name == Modifier.name; })}; + return found != existing.end() && same(*found, Modifier); + }); + for (auto *track : *Only) + state.changed.erase(track); + // the modifiers the tracks don't have any more: of the pieces of a path gone, of the tracks removed + std::vector gone; + for (auto const *track : *Only) + { + if (track == nullptr || track->name().empty()) + continue; + auto const own{"nmt " + track->name()}; + for (auto const &modifier : m_streamer.modifiers()) + if ((modifier.name == own || modifier.name.starts_with(own + " ")) && false == kept.contains(modifier.name)) + gone.push_back(modifier.name); + } + m_streamer.remove_modifiers(gone); + } + if (Only == nullptr) + { + // the formations of the tracks there are no more, or are on bridges now, and of the tracks with no name laid over each + // other under one name before + std::vector gone; + for (auto const &modifier : m_streamer.modifiers()) + if (modifier.name.starts_with("nmt ") && std::none_of(laid.begin(), laid.end(), [&](heightmap::modifier const &Laid) { return Laid.name == modifier.name; })) + gone.push_back(modifier.name); + m_streamer.remove_modifiers(gone); + } + auto const count{laid.size()}; + m_streamer.modifiers(std::move(laid)); + forget_ground(); + if (Only == nullptr) + { + state.shaped = modifiers.size(); + state.changed.clear(); + state.gone.clear(); + } + return count; +} + +void editor_mode::nmt_update() +{ + auto &state{m_nmt_state}; + // the squares of the model in the download area to the disk cache, where the scenery is placed and its terrain is there + if (auto const wanted{m_nmt.placed() && m_streamer.active() ? m_orthophoto.area() : std::vector{}}; wanted != m_nmt_prefetched) + { + m_nmt_prefetched = wanted; + m_nmt.prefetch(wanted); + } + nmt_offer(); + nmt_follow_tracks(); + if (state.stage != nmt_state::automatic::idle) + { + nmt_auto_step(); + return; + } + if (state.fitting) + { + bool all{true}; + for (auto const &place : state.fit) + all = nmt_ready(glm::dvec2{place.position.x, place.position.z} - glm::dvec2{1.0}, glm::dvec2{place.position.x, place.position.z} + glm::dvec2{1.0}) && all; + if (all) + nmt_finish_fit(); + return; + } + nmt_grow(); + if (state.pending.empty()) + { + if (std::exchange(state.camera_check, false) && false == Global.EditorOrtho) + camera_above_ground(); + return; + } + state.camera_check = true; + // a few chunks a frame, those whose model is in. the terrain made ahead of the track laid isn't a step of the history: + // Ctrl+Z takes back the track, not the ground under it + auto const unrecorded{state.grown && m_streamer.recording()}; + if (unrecorded) + { + terrain_history_step(); + m_streamer.end_change(); + } + int made{0}; + std::size_t apart{0}; + std::vector changed; + for (auto it{state.pending.begin()}; it != state.pending.end() && made < 4;) + { + auto const refilled{state.refill.contains(*it)}; + if (false == refilled && m_streamer.exists(*it)) + { + it = state.pending.erase(it); + continue; + } + // ahead of the track the terrain goes on from the one there is, at its height over the model + std::optional offset; + if (state.grown && false == refilled) + { + bool foreign{false}; + offset = nmt_seam_offset(*it, foreign); + if (foreign) + { + state.given_up.insert(*it); + it = state.pending.erase(it); + ++state.foreign; + ++made; + continue; + } + if (false == offset.has_value()) + { + ++apart; + ++it; + continue; + } + } + auto const chunk{add_chunk_from_nmt(*it, offset)}; + if (chunk == nmt_chunk::waiting) + { + ++it; + continue; + } + if (offset.has_value() && chunk == nmt_chunk::made) + state.ahead = offset; + if (chunk == nmt_chunk::made) + changed.push_back(*it); + state.refill.erase(*it); + it = state.pending.erase(it); + ++made; + if (chunk == nmt_chunk::made) + ++state.made; + else + ++state.empty; + } + // the chunks ahead which no terrain made from the model touches any more are given up + if (made == 0 && apart > 0 && apart == state.pending.size()) + { + state.foreign += apart; + state.given_up.insert(state.pending.begin(), state.pending.end()); + state.pending.clear(); + state.refill.clear(); + made = 1; + } + // the last ones may have got here as chunks the streamer has read in meanwhile, nothing made: all waited for is there all the same, + // the formations of the tracks led into it + if (made > 0 || state.pending.empty()) + { + // the ground gathered again only where the chunks were made: the rest of it is as it was, gathering all of it again frame after + // frame as the terrain grows around the cursor was felt + for (auto const &key : changed) + { + auto const low{heightmap::chunk_corner(key)}; + forget_ground_in(low, low + glm::dvec2{heightmap::chunk_size}); + } + state.status = format(STR_C("Chunks made from the terrain model: %zu, waiting for it: %zu"), state.made, state.pending.size()); + if (state.empty > 0) + state.status += format(STR_P("; %zu chunk not made, the model has no data there", "; %zu chunks not made, the model has no data there", state.empty), state.empty); + if (state.foreign > 0) + state.status += format(STR_P("; %zu chunk not made ahead, the terrain beside isn't the real one", "; %zu chunks not made ahead, the terrain beside isn't the real one", state.foreign), state.foreign); + if (state.pending.empty()) + { + state.run = false; + // not after the chunks grown around the cursor: the streamer leads the formations there are into a chunk as it's made, and + // shaping all of them again took the whole scenery through the terrain, 12 s of a frame each time the laying went on + if (state.shape && state.reshape && false == state.grown) + { + nmt_shape_tracks(); + state.status += format(STR_P("; the formation of %zu path shaped", "; the formation of %zu paths shaped", state.shaped), state.shaped); + } + // the photos laid onto the new ground + m_orthophoto.refit(); + for (auto &layer : m_wms) + layer->refit(); + first_step_done(first_step::nmt); + } + } + if (unrecorded) + m_streamer.begin_change(); +} + +void editor_mode::nmt_grow() +{ + auto &state{m_nmt_state}; + auto const now{ImGui::GetTime()}; + if (false == state.grow || now - state.grow_time < 0.5 || false == m_nmt.placed()) + return; + state.grow_time = now; + // around the cursor of the tool laying the tracks, the terrain under them once they're laid: from the first point placed, or as a + // track is dragged from a free end; not around the camera, nor with the tool merely chosen + if (false == m_lay.active && false == m_extend.active) + return; + auto const at{m_extend.active ? m_extend.mouse : m_lay.mouse}; + // nothing asked for outside the download area + if (false == in_download_area({at.x - 100.0, at.z - 100.0}, {at.x + 100.0, at.z + 100.0})) + return; + // the model under it meanwhile, for the height of the first point laid where there's no terrain yet, as over the base map + m_nmt.request({at.x - 100.0, at.z - 100.0}, {at.x + 100.0, at.z + 100.0}); + auto const laying{m_extend.active || false == m_lay.points.empty()}; + if (false == laying || m_streamer.resident() == 0) + return; + glm::dvec2 const cursor{at.x, at.z}; + double constexpr grow_reach{400.0}; // m around the cursor + auto const reach{static_cast(std::ceil(grow_reach / heightmap::chunk_size))}; + auto const centre{heightmap::chunk_at(at.x, at.z)}; + std::vector> missing; + for (int dz = -reach; dz <= reach; ++dz) + for (int dx = -reach; dx <= reach; ++dx) + { + heightmap::chunk_key const key{centre.first + dx, centre.second + dz}; + auto const low{heightmap::chunk_corner(key)}; + glm::dvec2 const nearest{std::clamp(cursor.x, low.x, low.x + heightmap::chunk_size), std::clamp(cursor.y, low.y, low.y + heightmap::chunk_size)}; + auto const distance{glm::distance(nearest, cursor)}; + if (distance <= grow_reach && false == m_streamer.exists(key) && false == state.given_up.contains(key) && std::find(state.pending.begin(), state.pending.end(), key) == state.pending.end() && + in_download_area(low, low + glm::dvec2{heightmap::chunk_size})) + missing.emplace_back(distance, key); + } + if (missing.empty()) + return; + std::sort(missing.begin(), missing.end()); + if (state.pending.empty()) + { + state.grown = true; + state.made = 0; + state.empty = 0; + state.foreign = 0; + } + for (auto const &chunk : missing) + state.pending.push_back(chunk.second); + if (false == m_orthophoto.enabled() && false == m_orthophoto_chosen) + m_orthophoto.enabled(true); + WriteLog(format("Editor: NMT - %zu chunks around the cursor to make", missing.size()), logtype::generic); +} + +bool editor_mode::nmt_busy() const +{ + auto const &state{m_nmt_state}; + return state.fitting || state.stage != nmt_state::automatic::idle || (false == state.pending.empty() && false == state.grown); +} + +void editor_mode::nmt_stop() +{ + auto &state{m_nmt_state}; + if (false == nmt_busy()) + return; + auto const lines{state.stage == nmt_state::automatic::fitting && state.lines > 0}; + m_nmt.cancel(); + state.fitting = false; + state.fit.clear(); + state.probes.clear(); + state.left.clear(); + state.done.clear(); + state.laid.clear(); + state.paths.clear(); + state.loose.clear(); + state.turntables.clear(); + state.stage = nmt_state::automatic::idle; + state.pending.clear(); + state.refill.clear(); + state.run = false; + // the lines fitted so far stay, and what they found is told + state.result = state.result || lines; + m_profile.open = false; + state.status = format(STR_P("Stopped: %zu chunk made stays", "Stopped: %zu chunks made stay", state.made), state.made); + if (lines) + state.status += STR("; so do the grade lines fitted, Ctrl+Z takes them back"); + WriteLog("Editor: NMT - " + state.status, logtype::generic); +} + +void editor_mode::render_nmt_progress(bool const Compact) +{ + auto &state{m_nmt_state}; + float fraction{0.0f}; + std::string text; + // of the tracks put onto the terrain the step too: the model, the grade lines, the chunks + int step{0}; + if (state.stage == nmt_state::automatic::fetching || state.fitting) + { + auto const waiting{m_nmt.waiting()}; + // the squares asked for come in one by one: how many of the most waited for are in; none waited for, only read from the disk + state.fetch_most = std::max(state.fetch_most, waiting); + fraction = state.fetch_most > 0 ? 1.0f - static_cast(waiting) / static_cast(state.fetch_most) : -1.0f * static_cast(ImGui::GetTime()); + text = format(STR_P("Terrain model: %zu square left", "Terrain model: %zu squares left", waiting), waiting); + step = 1; + } + else if (state.stage == nmt_state::automatic::fitting && state.tracks > 0) + { + fraction = 1.0f - static_cast(state.left.size()) / static_cast(std::max(state.tracks, state.left.size())); + text = format(STR_P("Grade lines: %zu fitted, %zu track left", "Grade lines: %zu fitted, %zu tracks left", state.left.size()), state.lines, state.left.size()); + step = 2; + } + else if (false == state.pending.empty()) + { + auto const total{state.made + state.empty + state.pending.size()}; + fraction = static_cast(state.made + state.empty) / static_cast(std::max(1, total)); + text = format(STR_C("Chunks: %zu of %zu"), state.made + state.empty, total); + step = 3; + } + else + return; + if (state.run) + text = format("%d/3 ", step) + text; + auto const stoppable{nmt_busy()}; + auto const stop{STR_C("Stop")}; + auto const button{ImGui::CalcTextSize(stop).x + ImGui::GetStyle().FramePadding.x * 2.0f}; + auto const width{Compact ? std::round(ImGui::GetFontSize() * 16.0f) : stoppable ? -(button + ImGui::GetStyle().ItemSpacing.x) : -FLT_MIN}; + ImGui::ProgressBar(fraction, ImVec2(width, Compact ? 0.0f : tall_button_height()), text.c_str()); + if (false == stoppable) + return; + ImGui::SameLine(); + if (ImGui::Button(stop, ImVec2(0.0f, Compact ? 0.0f : tall_button_height()))) + nmt_stop(); + item_tooltip("Stops loading: the terrain made so far stays"); +} + +void editor_mode::nmt_pull_terrain(std::vector const &Tracks) +{ + auto &state{m_nmt_state}; + std::vector rails; + for (auto *track : Tracks) + if (track != nullptr && false == track->m_editorremoved && rail(*track)) + rails.push_back(track); + if (rails.empty()) + { + state.status = STR("No tracks to draw the terrain to"); + return; + } + if (false == ensure_terrain()) + { + state.status = STR("The heightmap terrain can't be opened"); + return; + } + terrain_history_step(); + auto const laid{nmt_shape_tracks(&rails)}; + terrain_history_step(); + state.status = format(STR_P("The terrain drawn to %zu track: %zu formations led into it, Ctrl+Z takes it back", "The terrain drawn to %zu tracks: %zu formations led into it, Ctrl+Z takes it back", rails.size()), rails.size(), laid); + WriteLog("Editor: NMT - " + state.status, logtype::generic); +} + +void editor_mode::nmt_restore_terrain(std::vector const &Tracks) +{ + auto &state{m_nmt_state}; + if (false == m_streamer.active()) + return; + std::vector gone; + for (auto const *track : Tracks) + { + if (track == nullptr) + continue; + auto const own{"nmt " + formation_name(*track)}; + for (auto const &modifier : m_streamer.modifiers()) + if ((modifier.name == own || modifier.name.starts_with(own + " ")) && std::find(gone.begin(), gone.end(), modifier.name) == gone.end()) + gone.push_back(modifier.name); + } + terrain_history_step(); + m_streamer.remove_modifiers(gone); + if (false == gone.empty()) + forget_ground(); + terrain_history_step(); + state.status = format(STR_P("%zu formation taken out of the terrain, Ctrl+Z takes it back", "%zu formations taken out of the terrain, Ctrl+Z takes it back", gone.size()), gone.size()); + WriteLog("Editor: NMT - " + state.status, logtype::generic); +} + +void editor_mode::render_track_terrain(std::vector const &Tracks) +{ + auto &state{m_nmt_state}; + // a scenery with no terrain made nor any place on the map has nothing to draw to its tracks + if (false == m_streamer.active() && false == m_nmt.placed()) + return; + if (false == ImGui::CollapsingHeader(format("%s###trackterrain", STR_C("Terrain")).c_str())) + return; + auto const busy{nmt_busy()}; + auto const spacing{ImGui::GetStyle().ItemSpacing.x}; + auto const half{std::floor((ImGui::GetContentRegionAvail().x - spacing) * 0.5f)}; + { + std::size_t rails{0}, done{0}; + for (auto const *track : Tracks) + if (track != nullptr && rail(*track)) + { + ++rails; + if (grade_fitted(*track)) + ++done; + } + if (rails == 1) + ImGui::TextDisabled("%s", done > 0 ? STR_C("Its grade line is fitted to the terrain") : STR_C("Its grade line isn't fitted to the terrain yet")); + else if (rails > 1) + ImGui::TextDisabled(STR_C("Grade lines fitted to the terrain: %zu of %zu"), done, rails); + item_tooltip("A track is fitted when its grade line was fitted to the terrain model or applied with the profile, and it wasn't changed since"); + } + ImGui::BeginDisabled(busy); + if (ImGui::Button(STR_C("Draw the terrain to the track"), ImVec2(half, 0.0f))) + nmt_pull_terrain(Tracks); + item_tooltip("The formation and the slopes of the selected tracks led into the terrain, down or up to it; elsewhere the terrain stays as it is"); + ImGui::SameLine(); + if (ImGui::Button(STR_C("The whole run"), ImVec2(-FLT_MIN, 0.0f))) + { + m_track_set = Tracks; + track_set_grow(); + select_tracks(m_track_set); + nmt_pull_terrain(m_track_set); + } + item_tooltip("The tracks joined to the selected ones added to the selection, by the rules of the spread, and the terrain drawn to all of them"); + if (ImGui::Button(STR_C("Restore the terrain"), ImVec2(half, 0.0f))) + nmt_restore_terrain(Tracks); + item_tooltip("The formations of the selected tracks taken out of the terrain: the ground goes back to how it was before them"); + ImGui::EndDisabled(); + toggle_chips("nmtfollow", {{STR_C("The terrain follows the tracks edited"), &state.follow, "A track with its formation moved or changed takes it along; off: the terrain stays as it is until it's drawn to the tracks again"}}); + ImGui::Separator(); + ImGui::TextDisabled("%s", STR_C("All the tracks of the scenery")); + render_nmt_all_tracks(false); + if (busy) + render_nmt_progress(true); + else if (false == state.status.empty()) + { + ImGui::PushTextWrapPos(0.0f); + ImGui::TextDisabled("%s", state.status.c_str()); + ImGui::PopTextWrapPos(); + } +} + +// the tracks of the whole scenery and the terrain model: the way to take first big, what it does told under it, then the other +// two, each with the case it's for; step 3 of the terrain model in the field of the terrain (Terrain_panel), and in the panel of +// the tracks +void editor_mode::render_nmt_all_tracks(bool const Terrain_panel) +{ + auto &state{m_nmt_state}; + auto const busy{nmt_busy()}; + auto const placed{m_nmt.placed()}; + std::size_t unfitted{0}, all{0}, hand{0}; + std::unordered_map named; + for (auto const *track : simulation::Paths.sequence()) + if (track != nullptr && false == track->m_editorremoved && rail(*track)) + { + ++all; + ++named[track->name()]; + if (false == grade_fitted(*track)) + ++unfitted; + else if (grade_hand(*track)) + ++hand; + } + auto const told{[](char const *Text) { + ImGui::PushTextWrapPos(0.0f); + ImGui::TextDisabled("%s", Text); + ImGui::PopTextWrapPos(); + }}; + if (false == placed) + { + ImGui::PushTextWrapPos(0.0f); + ImGui::TextColored(ImVec4(1.0f, 0.75f, 0.3f, 1.0f), "%s", STR_C("First the place of the scenery on the map: F5 Terrain, Terrain model (NMT), step 1")); + ImGui::PopTextWrapPos(); + } + // three ways as cards, each with a sketch and the case it's for, the one to take first lit: what to click is seen at a glance. + // The tracks fitted already stay as they are: a track laid or changed since goes onto the model, all of them only when asked + auto const ready{false == busy && placed}; + auto const onto_text{unfitted == all ? std::string{STR_C("Recommended: the tracks go down or up onto the real terrain, each line on a grade line within its norms, with the formation and the slopes")} + : unfitted > 0 ? format(STR_C("The tracks laid or changed since the last time go onto the terrain model (%zu of %zu); the ones fitted stay as they are"), unfitted, all) + : std::string{STR_C("All the tracks are fitted to the terrain; a track changed since goes onto it again")}}; + if (way_card("##nmtonto", STR_C("Tracks onto the terrain"), onto_text.c_str(), way_sketch::onto, true, ready && unfitted > 0)) + nmt_auto_start(true); + item_tooltip("The terrain model is loaded along the tracks and the tracks go onto it, wherever the scenery was built: the top of the ballast at the height of the model, the grade line of every line fitted to it within the limits of the line, switches and the tracks beside them on one grade line, the formation and the slopes made along them. Where the model is off the tracks keep their line and it's reported. A turntable stays level in its pit at the height of the tracks running up to it, which reach it level. The tracks fitted already, by it or with the profile, and not changed since stay as they are, and the new lines meet them"); + // the fitted ones too, and which are left after it: under the card they belong to + ImGui::BeginDisabled(false == ready || all == 0); + if (unfitted < all && ImGui::SmallButton(STR_C("All anew, the fitted ones too"))) + ImGui::OpenPopup("##nmtallanew"); + item_tooltip("All the tracks are fitted to the terrain model again, the ones fitted already too: their grade lines may change; the scenery isn't moved"); + if (ImGui::BeginPopup("##nmtallanew")) + { + ImGui::TextUnformatted(format(STR_C("%zu tracks get new grade lines; Ctrl+Z takes it back"), all - (state.redo_hand ? 0 : hand)).c_str()); + if (hand > 0) + ImGui::Checkbox(format(STR_C("The %zu edited by hand too"), hand).c_str(), &state.redo_hand); + if (ImGui::Button(STR_C("Fit them anew"))) + { + nmt_auto_start(false); + state.redo_hand = false; + ImGui::CloseCurrentPopup(); + } + ImGui::SameLine(); + if (ImGui::Button(STR_C("Cancel"))) + ImGui::CloseCurrentPopup(); + ImGui::EndPopup(); + } + ImGui::EndDisabled(); + if (unfitted > 0 && unfitted < all) + { + ImGui::SameLine(); + // which they are, a few after the putting onto the terrain: the ones it couldn't fit + if (ImGui::SmallButton(format(STR_P("Show the %zu track not fitted", "Show the %zu tracks not fitted", unfitted), unfitted).c_str())) + { + std::vector those; + for (auto *track : simulation::Paths.sequence()) + if (track != nullptr && rail(*track) && false == grade_fitted(*track)) + those.push_back(track); + if (false == those.empty()) + { + select_tracks(those); + focus_track(*those.front(), 0, geometry::bezier{those.front()->m_paths.front()}.point(0.5)); + } + } + item_tooltip("They are selected, the first one in the 3d view"); + } + ImGui::Spacing(); + if (way_card("##nmtunder", STR_C("Terrain under the tracks"), STR_C("The tracks stay at their heights and the terrain comes up or down to them: for a scenery built level or at heights of its own"), way_sketch::under, false, ready && all > 0)) + nmt_under_start(); + item_tooltip("The tracks aren't touched: the terrain model is loaded along them and drawn to them, at each place by as much as the tracks lie above or below it there, fading out away from them, so its relief stays and the tracks don't end up in deep cuttings; then the formation and the slopes along them. For a scenery built level or at its own heights"); + ImGui::Spacing(); + if (way_card("##nmtonly", STR_C("The terrain of the model only"), STR_C("The real terrain along the tracks as it is; the tracks stay where they are, under it or over it"), way_sketch::only, false, ready)) + nmt_make(nmt_keys_along_tracks()); + item_tooltip("Loads the terrain model as it is along the tracks, with the height offset above; the tracks stay where they are"); + // under the three ways, which stay seen together: what the last of them did + render_nmt_result(); + std::string twice; + std::size_t repeated{0}; + for (auto const &[name, count] : named) + if (count > 1 && false == name.empty() && name != "none") + { + if (++repeated <= 12) + twice += (twice.empty() ? "" : ", ") + name; + } + if (repeated > 0) + { + told(format(STR_P("%zu track name is used more than once in the scenery", "%zu track names are used more than once in the scenery", repeated), repeated).c_str()); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s%s", twice.c_str(), repeated > 12 ? ", ..." : ""); + } + if (hand > 0) + told(format(STR_P("%zu track with its grade line edited by hand stays as it is", "%zu tracks with their grade lines edited by hand stay as they are", hand), hand).c_str()); + if (Terrain_panel) + { + ImGui::Spacing(); + told(STR_C("The terrain to some of the tracks only: select them (F3), Terrain in the inspector")); + } +} + +void editor_mode::nmt_note(nmt_state::finding::kind const What, TTrack *From, TTrack *To, double const Length, glm::dvec3 const &Where, std::string Text, double const Size) +{ + // only of the tracks put onto the terrain all together: a track laid onto it is told of as it's laid + if (m_nmt_state.stage != nmt_state::automatic::fitting) + return; + m_nmt_state.findings.push_back({What, From, To, Length, Where, std::move(Text), Size}); +} + +void editor_mode::nmt_show(nmt_state::finding const &Finding, bool const Profile) +{ + double constexpr reach{10.0}; // m, a track this near the place is the one of the line, if it was split since + int path{0}; + auto *track{kilometrage::track_near(Finding.where, reach, path)}; + if (track != nullptr) + { + select_track(track); + focus_track(*track, path, Finding.where); + } + else + fly_to(Finding.where, glm::normalize(glm::dvec3{0.0, -0.5, 1.0}), 40.0); + if (false == Profile) + return; + show_track_tab(track_tab::profile); + auto const alive = [](TTrack const *Track) { return Track != nullptr && false == Track->m_editorremoved; }; + if (alive(Finding.from) && alive(Finding.to)) + profile_open(Finding.from, Finding.to); + else if (track != nullptr) + profile_open_run(*track); +} + +void editor_mode::render_nmt_result() +{ + auto &state{m_nmt_state}; + if (false == state.result || nmt_busy()) + return; + using kind = nmt_state::finding::kind; + auto const count = [&](kind const What) { return static_cast(std::count_if(state.findings.begin(), state.findings.end(), [&](nmt_state::finding const &Finding) { return Finding.what == What; })); }; + ImVec4 const good{0.45f, 0.85f, 0.45f, 1.0f}; + ImVec4 const bad{1.0f, 0.45f, 0.35f, 1.0f}; + ImVec4 const doubt{1.0f, 0.75f, 0.3f, 1.0f}; + ImVec4 const calm{0.6f, 0.62f, 0.66f, 1.0f}; + auto const refused{count(kind::refused)}; + auto const off{count(kind::off)}; + auto const parted{count(kind::parted)}; + ImGui::Spacing(); + ImGui::TextUnformatted(STR_C("What the last putting onto the terrain did")); + metric_tiles({{std::to_string(state.lines), STR_C("lines fitted"), ImGui::ColorConvertFloat4ToU32(good)}, + {std::to_string(refused), STR_C("refused"), ImGui::ColorConvertFloat4ToU32(refused > 0 ? bad : calm)}, + {std::to_string(off), STR_C("off the line"), ImGui::ColorConvertFloat4ToU32(off > 0 ? doubt : calm)}, + {std::to_string(parted), STR_C("apart from the model"), ImGui::ColorConvertFloat4ToU32(parted > 0 ? doubt : calm)}}); + if (state.levelled > 0) + ImGui::TextDisabled(STR_C("Turntables set level: %zu"), state.levelled); + if (state.findings.empty()) + { + ImGui::TextColored(good, "%s", STR_C("Nothing to look at: every line lies on the model")); + return; + } + // the refused first, then the paths off their lines, then the lines apart from the model, the farther the sooner + std::vector order(state.findings.size()); + for (std::size_t i = 0; i < order.size(); ++i) + order[i] = i; + std::stable_sort(order.begin(), order.end(), [&](std::size_t const A, std::size_t const B) { + auto const &a{state.findings[A]}; + auto const &b{state.findings[B]}; + return a.what != b.what ? a.what < b.what : a.size > b.size; + }); + auto const rows{std::min(7.0f, static_cast(order.size()))}; + auto const row{ImGui::GetTextLineHeightWithSpacing() * 2.0f}; + ImGui::TextDisabled("%s", STR_C("To look at, each with its place and its profile:")); + ImGui::BeginChild("##nmtfindings", ImVec2(0.0f, std::round(row * rows + ImGui::GetStyle().WindowPadding.y * 2.0f)), true); + auto const show{STR_C("Show")}; + auto const profile{STR_C("Profile")}; + ImGuiListClipper clipper; + clipper.Begin(static_cast(order.size()), row); + std::optional> clicked; + while (clipper.Step()) + for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; ++i) + { + auto const &finding{state.findings[order[i]]}; + ImGui::PushID(static_cast(order[i])); + // the buttons first, where the long names of the tracks don't push them out of the panel + if (ImGui::SmallButton(show)) + clicked = {order[i], false}; + item_tooltip("The place in the 3d view, the track there selected"); + ImGui::SameLine(); + if (ImGui::SmallButton(profile)) + clicked = {order[i], true}; + item_tooltip("The profile of the line opened: its grade line, the terrain model under it and what the checks say"); + ImGui::SameLine(); + auto const colour{finding.what == kind::refused ? bad : doubt}; + auto const *label{finding.what == kind::refused ? STR_C("refused") : finding.what == kind::off ? STR_C("off the line") : STR_C("apart from the model")}; + ImGui::TextColored(colour, "%s", label); + ImGui::SameLine(); + ImGui::TextUnformatted(finding.text.c_str()); + if (ImGui::IsItemHovered() && false == finding.text.empty()) + ImGui::SetTooltip("%s", finding.text.c_str()); + auto const alive = [](TTrack const *Track) { return Track != nullptr && false == Track->m_editorremoved; }; + auto const ends{alive(finding.from) && alive(finding.to) ? (finding.from == finding.to ? finding.from->name() : finding.from->name() + " .. " + finding.to->name()) : std::string{}}; + ImGui::TextDisabled("%s", format(STR_C("the line %s, %.0f m"), ends.c_str(), finding.length).c_str()); + ImGui::PopID(); + } + ImGui::EndChild(); + if (clicked) + nmt_show(state.findings[clicked->first], clicked->second); +} + +void editor_mode::draw_nmt_pending() const +{ + auto const &state{m_nmt_state}; + auto const imagery{m_orthophoto.waiting()}; + if (state.pending.empty() && imagery.empty()) + return; + // where the ground will be: by the terrain there or beside it, else the model with the offset of the scenery, else level + // with the nearest chunk there is, or the nearest track + glm::dvec2 const camera{Camera.Pos.x, Camera.Pos.z}; + double fallback{0.0}; + { + auto nearest{std::numeric_limits::max()}; + std::vector chunks; + m_streamer.collect(chunks); + for (auto const *chunk : chunks) + if (auto const middle{chunk->centre()}; glm::distance(glm::dvec2{middle.x, middle.z}, camera) < nearest) + { + nearest = glm::distance(glm::dvec2{middle.x, middle.z}, camera); + fallback = middle.y; + } + if (chunks.empty()) + for (auto const *track : simulation::Paths.sequence()) + if (track != nullptr && false == track->m_paths.empty()) + if (auto const &point{track->m_paths.front().points[segment_data::point::start]}; glm::distance(geometry::plan_of(point), camera) < nearest) + { + nearest = glm::distance(geometry::plan_of(point), camera); + fallback = point.y; + } + } + auto const height = [&](double const X, double const Z, double &Height) { + if (m_streamer.height_at(X, Z, Height) || nmt_ground(X, Z, Height)) + return true; + Height = fallback; + return true; + }; + screen_projection const projection; + auto *drawlist{ImGui::GetBackgroundDrawList()}; + auto const time{ImGui::GetTime()}; + auto const pulse{static_cast(0.5 + 0.5 * std::sin(time * 4.0))}; + auto const dots{std::string(static_cast(time * 3.0) % 4, '.')}; + int constexpr steps{8}; // points along each edge, the outline following the ground + auto const square = [&](glm::dvec2 const &Low, glm::dvec2 const &High, int const Red, int const Green, int const Blue, std::string const &Label) { + auto const size{High - Low}; + std::vector outline; + for (int side = 0; side < 4; ++side) + for (int i = 0; i < steps; ++i) + { + auto const along{static_cast(i) / steps}; + glm::dvec2 const point{side == 0 ? Low + glm::dvec2{size.x * along, 0.0} : side == 1 ? Low + glm::dvec2{size.x, size.y * along} : side == 2 ? High - glm::dvec2{size.x * along, 0.0} : High - glm::dvec2{size.x, size.y * along}}; + double y; + ImVec2 screen; + if (false == height(point.x, point.y, y) || false == projection.project({point.x, y + 0.5, point.y}, screen)) + return; + outline.push_back(screen); + } + auto const edge{IM_COL32(Red, Green, Blue, static_cast(140.0f + 100.0f * pulse))}; + drawlist->AddConvexPolyFilled(outline.data(), static_cast(outline.size()), IM_COL32(Red, Green, Blue, static_cast(10.0f + 15.0f * pulse))); + drawlist->AddPolyline(outline.data(), static_cast(outline.size()), edge, ImDrawFlags_Closed, 2.0f); + // named where the name fits in + auto const middle{(Low + High) * 0.5}; + auto const text{Label + dots}; + auto const extent{ImGui::CalcTextSize(text.c_str())}; + auto const [left, right]{std::minmax_element(outline.begin(), outline.end(), [](ImVec2 const &A, ImVec2 const &B) { return A.x < B.x; })}; + double y; + ImVec2 label; + if (right->x - left->x > extent.x * 1.1f && height(middle.x, middle.y, y) && projection.project({middle.x, y + 0.5, middle.y}, label)) + drawlist->AddText({label.x - extent.x * 0.5f, label.y - extent.y * 0.5f}, edge, text.c_str()); + }; + // the nearest first, as many as can be drawn without the frame feeling it + auto const nearest = [&](std::vector> Areas, std::size_t const Most) { + auto const away = [&](std::pair const &Area) { return glm::distance((Area.first + Area.second) * 0.5, camera); }; + if (Areas.size() > Most) + { + std::nth_element(Areas.begin(), Areas.begin() + Most, Areas.end(), [&](auto const &A, auto const &B) { return away(A) < away(B); }); + Areas.resize(Most); + } + return Areas; + }; + for (auto const &[low, high] : nearest(imagery, 64)) + square(low, high, 255, 190, 70, STR("Orthophoto loading")); + std::vector> chunks; + for (auto const &key : state.pending) + chunks.emplace_back(heightmap::chunk_corner(key), heightmap::chunk_corner(key) + glm::dvec2{heightmap::chunk_size}); + for (auto const &[low, high] : nearest(chunks, 64)) + square(low, high, 90, 170, 255, STR("Terrain model loading")); +} + +// --------------------------------------------------------------------------------------------- +// the download area + +void editor_mode::area_start() +{ + auto &drawing{m_area_drawing}; + drawing = {}; + drawing.active = true; + // the area there is taken up to be changed + for (auto const &point : m_orthophoto.area()) + drawing.points.push_back(m_orthophoto.to_world(point)); + // drawn over the orthophoto of the top view, unless the user turned it off + if (false == m_orthophoto.enabled() && false == m_orthophoto_chosen) + m_orthophoto.enabled(true); + if (false == Global.EditorOrtho) + toggle_ortho(); + WriteLog("Editor: drawing the download area"); +} + +void editor_mode::area_finish(bool const Keep) +{ + auto &drawing{m_area_drawing}; + if (Keep && drawing.points.size() >= 3) + { + std::vector polygon; + for (auto const &point : drawing.points) + polygon.push_back(m_orthophoto.to_puwg(point)); + m_orthophoto.area(std::move(polygon)); + WriteLog(format("Editor: the download area of %zu points, %d tiles of the orthophoto", drawing.points.size(), m_orthophoto.stats().area_tiles)); + } + drawing = {}; +} + +glm::dvec3 editor_mode::area_point(glm::dvec2 const &Point) const +{ + double height{Camera.Pos.y - 2.0}; + if (false == Global.EditorOrtho && false == m_streamer.height_at(Point.x, Point.y, height) && false == nmt_ground(Point.x, Point.y, height)) + height = 0.0; + return {Point.x, height, Point.y}; +} + +void editor_mode::area_click(bool const Shift) +{ + auto &drawing{m_area_drawing}; + screen_projection const projection; + // the point under the cursor, within 10 pixels + int nearest{-1}; + auto best{100.0f}; + for (std::size_t i = 0; i < drawing.points.size(); ++i) + if (auto const distance{projection.mouse_distance2(area_point(drawing.points[i]))}; distance < best) + { + best = distance; + nearest = static_cast(i); + } + if (nearest >= 0) + { + if (Shift) + drawing.points.erase(drawing.points.begin() + nearest); + else + drawing.dragged = nearest; + return; + } + if (Shift) + return; + auto const cursor{std::as_const(*this).cursor_ground()}; + drawing.points.emplace_back(cursor.x, cursor.z); +} + +void editor_mode::area_update() +{ + auto &drawing{m_area_drawing}; + if (false == drawing.active || drawing.dragged < 0) + return; + if (false == ImGui::IsMouseDown(0) || drawing.dragged >= static_cast(drawing.points.size())) + { + drawing.dragged = -1; + return; + } + auto const cursor{std::as_const(*this).cursor_ground()}; + drawing.points[drawing.dragged] = {cursor.x, cursor.z}; +} + +void editor_mode::draw_download_area() const +{ + auto const &drawing{m_area_drawing}; + std::vector points; + if (drawing.active) + points = drawing.points; + else + for (auto const &point : m_orthophoto.area()) + points.push_back(m_orthophoto.to_world(point)); + // shown while it's drawn and with the settings of the orthophoto open + if (points.empty() || (false == drawing.active && false == orthophoto_settings_open())) + return; + screen_projection const projection; + auto *drawlist{ImGui::GetBackgroundDrawList()}; + // the tiles of the area as they are: in the disk cache, failed; the ones waiting left clear + if (false == drawing.active && orthophoto_settings_open()) + for (auto const &square : m_orthophoto.area_squares()) + { + if (square.state == 0) + continue; + std::array corners; + auto seen{true}; + glm::dvec2 const at[]{square.low, {square.high.x, square.low.y}, square.high, {square.low.x, square.high.y}}; + for (int i = 0; i < 4 && seen; ++i) + seen = projection.project(area_point(at[i]), corners[i]); + if (seen) + drawlist->AddQuadFilled(corners[0], corners[1], corners[2], corners[3], square.state == 1 ? IM_COL32(90, 220, 120, 45) : IM_COL32(240, 80, 70, 80)); + } + auto const edge{IM_COL32(80, 220, 255, 230)}; + auto const closing{IM_COL32(80, 220, 255, drawing.active ? 110 : 230)}; + // the edge back to the first point from three points on + auto const edges{points.size() >= 3 ? points.size() : points.size() - 1}; + for (std::size_t i = 0; i < edges; ++i) + { + auto const last{i + 1 == points.size()}; + projection.line(drawlist, area_point(points[i]), area_point(points[(i + 1) % points.size()]), last ? closing : edge, 2.0f); + } + if (false == drawing.active) + return; + // the points, the one under the cursor larger, and the line on to the cursor + ImVec2 screen; + for (auto const &point : points) + if (projection.project(area_point(point), screen)) + drawlist->AddCircleFilled(screen, projection.mouse_distance2(area_point(point)) < 100.0f ? 6.0f : 4.0f, edge); + if (false == points.empty() && drawing.dragged < 0 && false == ImGui::GetIO().WantCaptureMouse) + { + auto const cursor{std::as_const(*this).cursor_ground()}; + projection.line(drawlist, area_point(points.back()), area_point({cursor.x, cursor.z}), closing, 1.5f); + } +} + +void editor_mode::area_square(int const Side) +{ + auto const centre{m_orthophoto.to_puwg({Camera.Pos.x, Camera.Pos.z})}; + auto const half{Side * 500.0}; + m_orthophoto.area({{centre.x - half, centre.y - half}, {centre.x + half, centre.y - half}, {centre.x + half, centre.y + half}, {centre.x - half, centre.y + half}}); + WriteLog(format("Editor: the download area a square of %d km around the camera, %d tiles of the orthophoto", Side, m_orthophoto.stats().area_tiles)); +} + +bool editor_mode::in_download_area(glm::dvec2 const &Low, glm::dvec2 const &High) const +{ + auto const &area{m_orthophoto.area()}; + if (area.empty()) + return true; + // the square in PUWG: the easting grows to the west of the scenery, the northing with z + auto const &config{m_orthophoto.settings()}; + return geometry::square_touches(area, config.east - High.x, config.north + Low.y, High.x - Low.x); +} + +void editor_mode::render_download_area_ui(editor_orthophoto::statistics const &Stats) +{ + auto &drawing{m_area_drawing}; + ImGui::TextUnformatted(STR_C("Download area")); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("A polygon drawn on the map: what the settings ask for inside it, the orthophoto and the terrain model,\n" + "goes to the disk cache in the background, and nothing outside it is downloaded, also around the camera")); + if (drawing.active) + { + ImGui::TextColored(ImVec4(1.0f, 0.85f, 0.3f, 1.0f), "%s", STR_C("Click the points of the area on the map. Enter closes it, Backspace takes the last point back, Esc gives up;\n" + "a point dragged moves, Shift+click removes it")); + ImGui::Text(STR_C("%zu points"), drawing.points.size()); + ImGui::SameLine(); + if (drawing.points.size() >= 3 && ImGui::Button(STR_C("Done"))) + area_finish(true); + ImGui::SameLine(); + if (ImGui::Button(STR_C("Cancel"))) + area_finish(false); + return; + } + auto const &area{m_orthophoto.area()}; + ImGui::PushTextWrapPos(0.0f); + ImGui::TextDisabled("%s", area.empty() ? STR_C("None: the photos are downloaded around the camera, wherever it goes") + : STR_C("The aerial photos and the shape of the ground are downloaded only inside it; outside it there are none")); + ImGui::PopTextWrapPos(); + if (ImGui::Button(area.empty() ? STR_C("Draw on the map") : STR_C("Draw again"))) + area_start(); + if (false == area.empty()) + { + ImGui::SameLine(); + if (ImGui::Button(STR_C("Remove"))) + m_orthophoto.area({}); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("No range: the photos around the camera, wherever it goes. The photos downloaded already stay on the disk")); + } + // a square around the camera, in place of the one drawn: what the wizard of a new scenery gives. Where the scenery lies on + // the map must be known for it, or the square would lie anywhere + auto const &config{m_orthophoto.settings()}; + auto const located{config.north != 0.0 || config.east != 0.0}; + ImGui::BeginDisabled(false == located); + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted(STR_C("Square around the camera:")); + for (auto const side : {1, 2, 5, 10}) + { + ImGui::SameLine(); + if (ImGui::SmallButton(format(STR_C("%d x %d km##areasquare"), side, side).c_str())) + { + // the area there is, drawn with care, or one this large, replaced only with a yes + m_area_square = side; + if (area.empty() && side < 10) + area_square(side); + else + ImGui::OpenPopup("##areasquare"); + } + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) + ImGui::SetTooltip("%s", located ? format(STR_C("The range of the photos a square of %d x %d km, the camera in its middle"), side, side).c_str() : STR_C("Enter the origin of this scenery first")); + } + ImGui::EndDisabled(); + if (ImGui::BeginPopup("##areasquare")) + { + auto const size{static_cast(m_area_square) * m_area_square}; + ImGui::Text(STR_C("The range of the photos a square of %d x %d km around the camera?"), m_area_square, m_area_square); + if (false == area.empty()) + ImGui::TextColored(ImVec4(1.0f, 0.75f, 0.3f, 1.0f), "%s", STR_C("It replaces the area there is now, which can't be taken back")); + if (size >= 50.0) + ImGui::TextColored(ImVec4(1.0f, 0.75f, 0.3f, 1.0f), STR_C("%.0f sq km: the download takes long and needs a lot of disk space"), size); + if (ImGui::Button(STR_C("Replace"))) + { + area_square(m_area_square); + ImGui::CloseCurrentPopup(); + } + ImGui::SameLine(); + if (ImGui::Button(STR_C("Cancel"))) + ImGui::CloseCurrentPopup(); + ImGui::EndPopup(); + } + if (area.empty()) + return; + ImGui::Text(STR_C("Area: %d of %d tiles in the cache, %d failed"), Stats.area_cached, Stats.area_tiles, Stats.area_failed); + ImGui::SameLine(); + if (ImGui::SmallButton(m_area_paused ? STR_C("Resume") : STR_C("Pause"))) + { + m_area_paused = false == m_area_paused; + m_orthophoto.area_paused(m_area_paused); + m_nmt.prefetch_paused(m_area_paused); + } + if (auto const terrain{m_nmt.prefetched()}; terrain.total > 0) + { + ImGui::Text(STR_C("Terrain model: %d of %d squares in the cache, %d failed"), terrain.cached, terrain.total, terrain.failed); + // the ones there are only looked up again + if (terrain.failed > 0) + { + ImGui::SameLine(); + if (ImGui::SmallButton((std::string{STR_C("Retry")} + "##terrainarea").c_str())) + m_nmt.prefetch(m_nmt_prefetched); + } + } +} + +void editor_mode::render_nmt_banner() +{ + auto const &state{m_nmt_state}; + if (false == nmt_busy() || state.shown >= ImGui::GetFrameCount() - 1) + return; + auto const low{editor_ui::view_min()}; + auto const high{editor_ui::view_max()}; + ImGui::SetNextWindowPos(ImVec2((low.x + high.x) * 0.5f, low.y + std::round(ImGui::GetFontSize() * 3.6f)), ImGuiCond_Always, ImVec2(0.5f, 0.0f)); + ImGui::SetNextWindowViewport(ImGui::GetMainViewport()->ID); + ImGui::SetNextWindowBgAlpha(0.88f); + if (ImGui::Begin("##nmtbanner", nullptr, + ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav | ImGuiWindowFlags_NoDocking)) + { + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted(STR_C("Loading the real terrain")); + ImGui::SameLine(); + render_nmt_progress(true); + bool again{false}; + if (auto const error{m_nmt.error(&again)}; false == error.empty()) + { + ImGui::TextColored(ImVec4(1.0f, 0.5f, 0.3f, 1.0f), "%s", STR(error).c_str()); + if (again) + { + ImGui::SameLine(); + if (ImGui::SmallButton(STR_C("Try again"))) + m_nmt.retry(); + } + } + } + ImGui::End(); +} + +void editor_mode::nmt_check_buried(std::size_t const From) +{ + auto &state{m_nmt_state}; + state.buried.clear(); + state.buried_length = 0.0; + if (false == EditorSettings.terrain_buried_ask() || false == m_streamer.active()) + return; + // the top of the rails this near the ground leaves the sleepers and the ballast under it + double constexpr clearance{0.1}; + double constexpr step{5.0}; + double constexpr noticed{1.0}; + std::vector laid; + std::unordered_set seen; + double hidden{0.0}; + for (auto index{From}; index < m_history.size(); ++index) + for (auto const *track : m_history[index].created) + { + if (track == nullptr || track->m_editorremoved || false == rail(*track) || false == seen.insert(track).second) + continue; + laid.push_back(track->name()); + auto const &path{track->m_paths.front()}; + geometry::bezier const curve{path}; + auto const length{geometry::chord_length(path)}; + auto const count{std::max(1, static_cast(std::ceil(length / step)))}; + std::vector along, probes; + for (int i = 0; i < count; ++i) + { + along.push_back(curve.point((i + 0.5) / count)); + probes.emplace_back(along.back().x, 5000.0, along.back().z); + } + std::vector found; + auto const ground{ground_heights(probes, true, &found)}; + for (int i = 0; i < count; ++i) + if (found[i] != 0 && along[i].y < ground[i] + clearance) + hidden += length / count; + } + if (hidden < noticed) + return; + state.buried = std::move(laid); + state.buried_length = hidden; +} + +void editor_mode::render_nmt_buried() +{ + auto &state{m_nmt_state}; + if (state.buried.empty()) + return; + // gone on to other work the message would only be in the way: the same is done by Terrain in the inspector + if (current_work_area() == work_area::terrain || (ui()->mode() == nodebank_panel::TRACK && m_track_tab != track_tab::lay && m_track_tab != track_tab::path)) + { + state.buried.clear(); + return; + } + // taken back with Ctrl+Z there's nothing to tell of + std::vector tracks; + for (auto const &name : state.buried) + if (auto *track{simulation::Paths.find(name)}; track != nullptr && false == track->m_editorremoved) + tracks.push_back(track); + if (tracks.empty()) + { + state.buried.clear(); + return; + } + auto const low{editor_ui::view_min()}; + auto const high{editor_ui::view_max()}; + ImGui::SetNextWindowPos(ImVec2((low.x + high.x) * 0.5f, low.y + std::round(ImGui::GetFontSize() * (nmt_busy() ? 7.0f : 3.6f))), ImGuiCond_Always, ImVec2(0.5f, 0.0f)); + ImGui::SetNextWindowViewport(ImGui::GetMainViewport()->ID); + ImGui::SetNextWindowBgAlpha(0.94f); + if (ImGui::Begin("##nmtburied", nullptr, ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav | ImGuiWindowFlags_NoDocking)) + { + ImGui::Text(STR_C("%.0f m of the new track is hidden in the ground, you can't see it there"), state.buried_length); + ImGui::TextDisabled("%s", STR_C("Only the ground along the track changes; Ctrl+Z takes it back")); + ImGui::BeginDisabled(nmt_busy()); + if (main_button(STR_C("Fit the ground to the track"), ImVec2(0.0f, tall_button_height()))) + { + nmt_pull_terrain(tracks); + ui()->set_status(state.status, false); + state.buried.clear(); + } + ImGui::EndDisabled(); + ImGui::SameLine(); + if (ImGui::Button(STR_C("Leave it"), ImVec2(0.0f, tall_button_height()))) + state.buried.clear(); + ImGui::SameLine(); + ImGui::AlignTextToFramePadding(); + bool ask{EditorSettings.terrain_buried_ask()}; + if (ImGui::Checkbox(STR_C("Tell me each time"), &ask)) + { + EditorSettings.terrain_buried_ask(ask); + EditorSettings.save(); + } + } + ImGui::End(); +} + +void editor_mode::render_empty_scenery_hint() +{ + // the panel of the empty scenery of the tracks shown, in this frame or the last: it says the same + if (m_lay.active || m_terrain_open || m_nmt_state.prompt || m_streamer.resident() > 0 || ImGui::IsPopupOpen(nullptr, ImGuiPopupFlags_AnyPopupId) || ImGui::GetFrameCount() - m_empty_hint_frame <= 1) + return; + auto const &tracks{simulation::Paths.sequence()}; + if (std::any_of(tracks.begin(), tracks.end(), [](TTrack const *Track) { return Track != nullptr && false == Track->m_editorremoved && rail(*Track); })) + return; + auto const low{editor_ui::view_min()}; + auto const high{editor_ui::view_max()}; + auto *list{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())}; + auto const line = [&](char const *Text, float const Size, float const Y, ImU32 const Color) { + auto const width{ImGui::GetFont()->CalcTextSizeA(Size, FLT_MAX, 0.0f, Text).x}; + list->AddText(ImGui::GetFont(), Size, ImVec2(std::round((low.x + high.x - width) * 0.5f), Y), Color, Text); + }; + auto const font{ImGui::GetFontSize()}; + auto const middle{(low.y + high.y) * 0.5f}; + line(STR_C("This scenery is still empty"), font * 1.6f, middle - font * 2.2f, IM_COL32(255, 255, 255, 255)); + line(STR_C("Click Laying on the toolbar or press L, then click the points of the track"), font, middle, IM_COL32(210, 215, 225, 255)); +} + +void editor_mode::render_outside_area_hint() +{ + auto const &area{m_orthophoto.area()}; + auto const &config{m_orthophoto.settings()}; + // with no place of the scenery on the map the camera is nowhere in it + if (area.empty() || false == m_orthophoto.enabled() || (config.north == 0.0 && config.east == 0.0)) + return; + if (geometry::point_in_polygon(area, m_orthophoto.to_puwg({Camera.Pos.x, Camera.Pos.z}))) + { + m_outside_area_closed = false; + return; + } + // the camera riding a track has its own lines at the bottom of the view, where this one would cover them + if (m_outside_area_closed || m_area_drawing.active || m_ride.active() || ImGui::IsPopupOpen(nullptr, ImGuiPopupFlags_AnyPopupId)) + return; + auto const low{editor_ui::view_min()}; + auto const high{editor_ui::view_max()}; + auto const font{ImGui::GetFontSize()}; + // above the strip of the profile and above the row of the keys of the tools at the bottom of the view + auto const bottom{m_profile.strip_top > low.y + 4.0f * font ? std::min(high.y, m_profile.strip_top) : high.y}; + ImGui::SetNextWindowPos(ImVec2((low.x + high.x) * 0.5f, bottom - std::round(font * 2.8f)), ImGuiCond_Always, ImVec2(0.5f, 1.0f)); + ImGui::SetNextWindowViewport(ImGui::GetMainViewport()->ID); + ImGui::SetNextWindowBgAlpha(0.88f); + if (ImGui::Begin("##outsidearea", nullptr, ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav | ImGuiWindowFlags_NoDocking)) + { + ImGui::AlignTextToFramePadding(); + ImGui::TextColored(ImVec4(1.0f, 0.8f, 0.35f, 1.0f), "%s", STR_C("The camera is outside the range: no aerial photos and no terrain model here")); + ImGui::SameLine(); + if (ImGui::SmallButton(orthophoto_settings_open() ? STR_C("Draw the range again") : STR_C("Range settings..."))) + { + if (orthophoto_settings_open()) + area_start(); + else + { + ui()->show_layers(); + m_orthophoto_window = true; + } + } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("The range is the download area in Map > Orthophoto settings...; drawn again it can take this place in")); + ImGui::SameLine(); + if (ImGui::SmallButton("x##outsidearea")) + m_outside_area_closed = true; + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Hidden until the camera is back inside the range and out again")); + } + ImGui::End(); +} + +void editor_mode::camera_above_ground() +{ + std::vector found; + auto const ground{ground_heights({glm::dvec3{Camera.Pos.x, 5000.0, Camera.Pos.z}}, true, &found).front()}; + if (found.front() == 0 || Camera.Pos.y > ground + 2.0) + return; + Camera.Pos.y = ground + 40.0; + // looking down, to see what the view from above showed around it + Camera.Angle.x = -0.9; + Camera.Velocity = {}; + m_focus_active = false; + Global.pCamera = Camera; +} + +bool editor_mode::render_nmt_place(bool const Moving, bool const Button) +{ + auto &state{m_nmt_state}; + auto &map{m_nmt_map}; + auto const width{ImGui::GetContentRegionAvail().x}; + auto const height{std::round(std::min(width * 0.65f, ImGui::GetFontSize() * 16.0f))}; + ImGui::TextWrapped("%s", STR_C("Click the middle of the scenery on the map")); + item_tooltip("The point 0,0,0 of the scenery. The wheel zooms the map, a drag moves it"); + ImGui::BeginChild("##nmtmap", ImVec2(width, height), false, ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse); + if (map.render({width, height})) + { + auto const degrees{editor_geo::to_degrees(map.point())}; + std::snprintf(state.place, sizeof(state.place), "%.6f, %.6f", degrees.x, degrees.y); + } + ImGui::EndChild(); + ImGui::SetNextItemWidth(-FLT_MIN); + glm::dvec2 typed; + auto const understood{editor_geo::parse_place(state.place, typed)}; + if (ImGui::InputTextWithHint("##nmtplace", STR_C("or type it: 52.2297, 21.0122"), state.place, sizeof(state.place)) && editor_geo::parse_place(state.place, typed)) + { + map.pick(typed); + map.show(typed, 8.0); + } + item_tooltip("Degrees as the online maps copy them (latitude, longitude), or the X and Y of PUWG 1992, the coordinates of the Polish maps of geoportal.gov.pl"); + if (state.place[0] != '\0' && false == understood) + ImGui::TextColored(ImVec4(1.0f, 0.5f, 0.3f, 1.0f), "%s", STR_C("Not a place in Poland: two numbers, degrees or the X and Y of PUWG 1992")); + else if (map.picked()) + ImGui::TextDisabled(STR_C("X %.0f, Y %.0f in PUWG 1992"), map.point().y, map.point().x); + if (Moving && m_streamer.resident() > 0) + { + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0.95f, 0.75f, 0.3f, 1.0f)); + ImGui::TextWrapped("%s", STR_C("The terrain made already stays as it is")); + ImGui::PopStyleColor(); + } + if (false == Button) + return false; + auto const cancel{STR_C("Cancel")}; + auto const cancel_width{ImGui::CalcTextSize(cancel).x + ImGui::GetStyle().FramePadding.x * 2.0f}; + bool placed{false}; + ImGui::BeginDisabled(false == map.picked()); + if (main_button(STR_C("The scenery is here"), ImVec2(Moving ? -(cancel_width + ImGui::GetStyle().ItemSpacing.x) : -FLT_MIN, tall_button_height()))) + { + nmt_place_scenery(map.point()); + placed = true; + } + ImGui::EndDisabled(); + if (Moving) + { + ImGui::SameLine(); + if (ImGui::Button(cancel, ImVec2(0.0f, tall_button_height()))) + state.moving = false; + } + return placed; +} + +void editor_mode::render_nmt_ui() +{ + auto &state{m_nmt_state}; + state.shown = ImGui::GetFrameCount(); + nmt_locate(); + auto const busy{nmt_busy()}; + step_heading(1, STR_C("Location")); + if (false == m_nmt.placed() || state.moving) + { + if (render_nmt_place(state.moving, true)) + state.moving = false; + if (false == m_nmt.placed()) + return; + } + else + { + auto const &config{m_orthophoto.settings()}; + auto const degrees{editor_geo::to_degrees({config.east, config.north})}; + ImGui::AlignTextToFramePadding(); + ImGui::Text(STR_C("%.5f N, %.5f E"), degrees.x, degrees.y); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip(STR_C("X %.0f, Y %.0f in PUWG 1992, the coordinates of the Polish maps; the place is shared with the orthophoto"), config.north, config.east); + ImGui::SameLine(); + ImGui::BeginDisabled(busy); + if (ImGui::SmallButton(STR_C("Change..."))) + { + glm::dvec2 const point{config.east, config.north}; + m_nmt_map.pick(point); + m_nmt_map.show(point, 8.0); + std::snprintf(state.place, sizeof(state.place), "%.6f, %.6f", degrees.x, degrees.y); + state.moving = true; + } + ImGui::EndDisabled(); + } + + auto const tracks{std::any_of(simulation::Paths.sequence().begin(), simulation::Paths.sequence().end(), [](TTrack const *Track) { return Track != nullptr && rail(*Track); })}; + // the progress shown at the step whose button began it + auto const tracks_busy{state.stage != nmt_state::automatic::idle || (state.fitting && state.under)}; + if (tracks) + { + step_heading(2, STR_C("Tracks and terrain")); + if (tracks_busy) + render_nmt_progress(false); + else + render_nmt_all_tracks(true); + ImGui::Spacing(); + if (busy && false == tracks_busy) + render_nmt_progress(false); + } + else + { + // no tracks yet: the model as it is around the camera, a square of it + step_heading(2, STR_C("Load")); + if (busy) + render_nmt_progress(false); + else + { + if (main_button(STR_C("Load around the camera"), ImVec2(-FLT_MIN, tall_button_height()))) + { + if (m_streamer.resident() == 0) + state.offset = 0.0; + nmt_make(nmt_keys_around()); + } + item_tooltip("Loads the terrain model as it is around the camera, with the height offset above; the tracks stay where they are"); + if (begin_fields("##nmtload", 0.5f)) + { + field_row("Area"); + segmented("nmtarea", m_terrain_add_count, {{2, "0.5 km", "A square of 500 m around the camera"}, {4, "1 km", "A square of 1 km around the camera"}, {8, "2 km", "A square of 2 km around the camera"}}); + ImGui::EndTable(); + } + } + ImGui::PushTextWrapPos(0.0f); + ImGui::TextDisabled("%s", STR_C("A chunk there is already is never made anew")); + ImGui::PopTextWrapPos(); + } + if (ImGui::TreeNode(STR_C("Settings"))) + { + if (toggle_chips("nmtgrow", {{STR_C("Terrain of the model right away while laying"), &state.grow, + "Where the terrain of the scenery ends, the terrain model is made under the tracks as they're laid, around the cursor from the first point placed; " + "the chunks there are stay as they are. Off, it's made only when asked for"}}) >= 0) + { + EditorSettings.terrain_while_laying(state.grow); + EditorSettings.save(); + } + // with tracks the model as it is is a card of step 2, the band of it and the square around the camera are here + if (tracks && begin_fields("##nmtoffset", 0.5f)) + { + field_row("Band along the tracks (m)"); + ImGui::InputDouble("##nmtbandwidth", &state.band, 50.0, 250.0, "%.0f"); + item_tooltip("How far from the tracks, on both sides, the terrain model is loaded"); + field_row("Height offset of the model (m)"); + ImGui::InputDouble("##nmtheightoffset", &state.offset, 0.1, 1.0, "%.2f"); + item_tooltip("Added to the heights of the model, for a scenery built at heights of its own; the tracks put onto the terrain find it by themselves"); + ImGui::TableNextRow(); + ImGui::TableSetColumnIndex(1); + ImGui::BeginDisabled(busy); + if (ImGui::Button(STR_C("Fit to the tracks"), ImVec2(-FLT_MIN, 0.0f))) + nmt_fit(); + ImGui::EndDisabled(); + item_tooltip("Compares the formation of the tracks with the terrain model and moves the model up or down to meet them, as a scenery built at height 0 needs"); + ImGui::EndTable(); + } + if (tracks) + { + ImGui::BeginDisabled(busy); + if (ImGui::Button(STR_C("Load around the camera"), ImVec2(-FLT_MIN, 0.0f))) + nmt_make(nmt_keys_around()); + item_tooltip("Loads the terrain model as it is around the camera, with the height offset above; the tracks stay where they are"); + ImGui::EndDisabled(); + } + ImGui::TreePop(); + } + state.band = std::clamp(state.band, 50.0, 3000.0); + ImGui::Spacing(); + // while the work goes on the bar above tells how far it got + if (false == state.status.empty() && false == busy) + { + ImGui::PushTextWrapPos(0.0f); + ImGui::TextDisabled("%s", state.status.c_str()); + ImGui::PopTextWrapPos(); + } + if (false == state.error.empty()) + { + ImGui::PushTextWrapPos(0.0f); + ImGui::TextColored(ImVec4(1.0f, 0.5f, 0.3f, 1.0f), "%s", state.error.c_str()); + ImGui::PopTextWrapPos(); + } + bool again{false}; + if (auto const error{m_nmt.error(&again)}; false == error.empty()) + { + ImGui::PushTextWrapPos(0.0f); + ImGui::TextColored(ImVec4(1.0f, 0.5f, 0.3f, 1.0f), "%s", STR(error).c_str()); + ImGui::PopTextWrapPos(); + if (again && ImGui::Button(STR_C("Try again"))) + m_nmt.retry(); + if (again) + item_tooltip("The squares of the model the service didn't give are asked for again; it happens by itself every 15 s too"); + } + ImGui::TextDisabled("%s", STR_C("Terrain model: GUGiK, geoportal.gov.pl")); +} + +void editor_mode::nmt_place_scenery(glm::dvec2 const &Point) +{ + auto &state{m_nmt_state}; + auto config{m_orthophoto.settings()}; + config.north = Point.y; + config.east = Point.x; + m_orthophoto.settings(config); + m_orthophoto_origin_edit = {config.north, config.east}; + save_orthophoto_settings(); + nmt_locate(); + // the heights fitted to the tracks at the place before mean nothing here + state.offset = 0.0; + state.fitted = false; + state.under = false; + state.anchors.clear(); + state.anchor_cells.clear(); +} + +void editor_mode::nmt_offer() +{ + auto &state{m_nmt_state}; + if (state.offered || false == m_lay.active || false == EditorSettings.terrain_offer()) + return; + state.offered = true; + if (m_streamer.resident() > 0 || std::any_of(simulation::Paths.sequence().begin(), simulation::Paths.sequence().end(), [](TTrack const *Track) { return Track != nullptr && rail(*Track); })) + return; + nmt_locate(); + state.prompt = true; +} + +void editor_mode::nmt_accept_offer() +{ + auto &state{m_nmt_state}; + if (false == m_nmt.placed() && m_nmt_map.picked()) + nmt_place_scenery(m_nmt_map.point()); + // no tracks to fit to: the heights of the model as they are + state.offset = 0.0; + nmt_make(nmt_keys_around()); + state.prompt = false; +} + +void editor_mode::render_nmt_prompt() +{ + auto &state{m_nmt_state}; + if (false == state.prompt) + return; + char const *const title{STR_C("Terrain for the new scenery###nmtoffer")}; + if (false == ImGui::IsPopupOpen(title)) + ImGui::OpenPopup(title); + ImGui::SetNextWindowSize(ImVec2(520.0f * Global.ui_scale, 0.0f)); + if (false == ImGui::BeginPopupModal(title, nullptr, ImGuiWindowFlags_NoResize)) + return; + ImGui::TextWrapped("%s", STR_C("The scenery has no terrain yet. Load the terrain model and the aerial photos around here? The tracks laid then go along the real ground.")); + bool const placed{m_nmt.placed()}; + if (false == placed) + render_nmt_place(false, false); + auto const known{placed || m_nmt_map.picked()}; + ImGui::Spacing(); + auto const gap{std::round(ImGui::GetFontSize() * 0.6f)}; + auto const width{std::floor((ImGui::GetContentRegionAvail().x - gap) * 0.5f)}; + if (ground_card("##terrain", STR_C("Load the terrain"), STR_C("The terrain model and the aerial photos of geoportal.gov.pl around here; the tracks go along the real ground"), true, known, width)) + { + nmt_accept_offer(); + ImGui::CloseCurrentPopup(); + } + if (false == known) + item_tooltip("Pick where the scenery lies first"); + ImGui::SameLine(0.0f, gap); + if (ground_card("##flat", STR_C("Without terrain"), STR_C("The tracks lie on the flat plane at the height 0; the terrain can be loaded later in Terrain (F5)"), false, true, width)) + { + state.prompt = false; + ImGui::CloseCurrentPopup(); + } + ImGui::Spacing(); + bool ask{EditorSettings.terrain_offer()}; + if (ImGui::Checkbox(STR_C("Ask with every new scenery"), &ask)) + { + EditorSettings.terrain_offer(ask); + EditorSettings.save(); + } + ImGui::EndPopup(); +} + +std::size_t editor_mode::nmt_join_ends() +{ + // the loose ends are one joint before the grade lines run over them; of two switches, which can't be changed alone, the + // lines over them take each other over as they're fitted + std::vector> states; + std::vector changed; + auto const remember = [&](TTrack *Track) { + if (std::find(changed.begin(), changed.end(), Track) != changed.end()) + return; + states.emplace_back(Track, editor_track::capture(*Track)); + changed.push_back(Track); + }; + std::size_t joined{0}; + m_nmt_state.loose.clear(); + for (auto pair : loose_pairs()) + { + if (pair.first.track->eType != tt_Normal) + std::swap(pair.first, pair.second); + auto const &a{pair.first}; + auto const &b{pair.second}; + if (a.track->eType != tt_Normal) + { + // two switches: the lines over them meet as they're fitted + m_nmt_state.loose[{a.track, a.path, a.atend}] = {b.track, b.path, b.atend}; + m_nmt_state.loose[{b.track, b.path, b.atend}] = {a.track, a.path, a.atend}; + continue; + } + if (b.track->eType != tt_Normal && false == editor_track::is_supported(*b.track)) + continue; + auto const height{b.track->eType == tt_Normal ? (a.point.y + b.point.y) * 0.5 : b.point.y}; + for (auto const *side : {&a, &b}) + { + if (side->track->eType != tt_Normal) + continue; + remember(side->track); + side->track->m_paths[side->path].points[side->atend ? segment_data::point::end : segment_data::point::start].y = height; + } + ++joined; + } + if (changed.empty()) + return 0; + editor_track::commit(changed); + push_track_snapshot(std::move(states)); + WriteLog(format("Editor: NMT - %zu joints of tracks laid apart in height joined", joined), logtype::generic); + return joined; +} + +std::vector editor_mode::nmt_turntables() const +{ + std::vector result; + for (auto *track : simulation::Paths.sequence()) + { + if (track == nullptr || track->eType != tt_Table || false == rail(*track)) + continue; + auto const &points{track->m_paths.front().points}; + nmt_state::turntable table; + table.table = track; + table.centre = glm::mix(points[segment_data::point::start], points[segment_data::point::end], 0.5); + table.rim = 0.5 * geometry::plan_distance(points[segment_data::point::start], points[segment_data::point::end]); + if (table.rim < 1.0) + continue; + result.push_back(std::move(table)); + } + if (result.empty()) + return result; + for (auto *track : simulation::Paths.sequence()) + { + if (track == nullptr || track->eType == tt_Table || false == rail(*track)) + continue; + for (int path = 0; path < static_cast(track->m_paths.size()); ++path) + for (auto const atend : {false, true}) + { + auto const end{end_of(*track, path, atend)}; + for (auto &table : result) + if (on_rim(end, table.centre, table.rim)) + table.ends.emplace_back(track, path, atend); + } + } + return result; +} + +std::size_t editor_mode::nmt_level_turntables() +{ + auto &state{m_nmt_state}; + state.turntables = nmt_turntables(); + std::vector> states; + std::vector changed; + std::vector> moves; + std::vector> models; + std::vector standing; + if (false == state.turntables.empty()) + standing = standing_templates([](std::string const &) { return true; }); + for (auto &table : state.turntables) + { + // the height of the tracks running up to it: of the ones fitted already, which stay as they are, else of the model beside + // the rim past the wall of the pit, out along each of them + std::vector fitted, model; + for (auto const &[track, path, atend] : table.ends) + { + auto const end{end_of(*track, path, atend)}; + if (nmt_stays(*track)) + fitted.push_back(end.point.y); + auto const away{geometry::plan_of(end.point - table.centre) / std::max(1e-6, geometry::plan_distance(end.point, table.centre))}; + for (int metre = 0; metre <= 6; ++metre) + if (double height; m_nmt.height(end.point.x + away.x * (kPitWall + metre), end.point.z + away.y * (kPitWall + metre), height)) + model.push_back(height + state.offset + track->rail_height()); + } + auto &heights{fitted.empty() ? model : fitted}; + if (heights.empty()) + { + WriteLog(format("Editor: NMT - turntable %s left at %.2f m: %s", table.table->name().c_str(), table.centre.y, table.ends.empty() ? "no tracks run up to it" : "no terrain model beside it"), logtype::generic); + continue; + } + std::nth_element(heights.begin(), heights.begin() + heights.size() / 2, heights.end()); + auto const height{heights[heights.size() / 2]}; + auto const rise{height - table.centre.y}; + WriteLog(format("Editor: NMT - turntable %s level at %.2f m, from %.2f m (%+.2f), the height of its %zu tracks %s", table.table->name().c_str(), height, table.centre.y, rise, table.ends.size(), + fitted.empty() ? "on the model beside its rim" : "fitted already"), + logtype::generic); + auto &points{table.table->m_paths.front().points}; + table.centre.y = height; + if (std::abs(points[segment_data::point::start].y - height) < 0.001 && std::abs(points[segment_data::point::end].y - height) < 0.001) + continue; + states.emplace_back(table.table, editor_track::capture(*table.table)); + points[segment_data::point::start].y = height; + points[segment_data::point::end].y = height; + points[segment_data::point::control1].y = 0.0; + points[segment_data::point::control2].y = 0.0; + table.table->m_paths.front().pieces.clear(); + changed.push_back(table.table); + // its include, the pit and the bridge, by the name of the table in its parameters; a model of its name standing apart + std::set included; + for (auto const &item : standing) + if (false == item.values.empty() && ToLower(item.values.front()) == table.table->name() && geometry::plan_distance(item.location, table.centre) <= 1.0) + { + template_item moved; + moved.file = item.file; + moved.location = item.location + glm::dvec3{0.0, rise, 0.0}; + moved.yaw = item.yaw; + moves.emplace_back(item, moved); + included.insert(item.instance); + } + auto const apart{models.size()}; + if (auto *model{simulation::Instances.find(table.table->name())}; model != nullptr && false == included.contains(model->m_instance) && geometry::plan_distance(model->location(), table.centre) <= table.rim) + models.emplace_back(model, rise); + WriteLog(format("Editor: NMT - turntable %s moved %+.2f m with %zu include(s) and %zu model(s) of its name", table.table->name().c_str(), rise, included.size(), models.size() - apart), logtype::generic); + } + if (changed.empty()) + return 0; + editor_track::commit(changed); + push_track_snapshot(std::move(states)); + if (move_templates(moves) > 0 && m_history.size() >= 2) + m_history.back().joined = true; + for (auto const &[model, rise] : models) + { + push_snapshot(model, EditorSnapshot::Action::Move); + m_history.back().joined = true; + m_editor.translate(model, model->location() + glm::dvec3{0.0, rise, 0.0}, true); + } + return changed.size(); +} + +bool editor_mode::nmt_stays(TTrack const &Track) +{ + auto const &state{m_nmt_state}; + return (state.unfitted && grade_fitted(Track)) || (false == state.redo_hand && grade_hand(Track)); +} + +void editor_mode::nmt_auto_start(bool const Unfitted) +{ + auto &state{m_nmt_state}; + state.error.clear(); + state.under = false; + state.unfitted = Unfitted; + state.result = false; + state.findings.clear(); + nmt_locate(); + state.probes.clear(); + state.probes_kept = 0; + // the tracks fitted already, when they stay as they are, tell the offset of the model they were fitted to, which isn't kept + // from one opening of the scenery to the next: a few hundred of their places are measured too, after the others + std::vector kept; + for (auto const &place : nmt_track_places(20.0)) + if (place.shapes) + (nmt_stays(*place.track) ? kept : state.probes).push_back(place); + if (state.probes.empty()) + { + state.status = Unfitted && false == kept.empty() ? STR("All the tracks are fitted to the terrain already") : STR("No tracks to put onto the terrain"); + return; + } + auto const every{std::max(1, kept.size() / 400)}; + for (std::size_t i = 0; i < kept.size(); i += every) + state.probes.push_back(kept[i]); + state.probes_kept = (kept.size() + every - 1) / every; + state.lines = 0; + state.refused = 0; + state.departures = 0; + state.levelled = 0; + state.findings.clear(); + state.result = false; + state.run = true; + state.fetch_most = 0; + state.stage = nmt_state::automatic::fetching; + state.status = STR("Fetching the terrain model under the tracks..."); +} + +bool editor_mode::nmt_fit_line(TTrack &Track, std::function const &Fitted, bool const Laid) +{ + auto &profile{m_profile}; + auto const &fitted{Fitted}; + // the line runs over the tracks not fitted yet around the track: the ones fitted stay as they are + auto route{editor_track::run_route(Track, profile.run_length)}; + auto const at{std::find_if(route.spans.begin(), route.spans.end(), [&](auto const &Span) { return Span.track == &Track; })}; + auto const middle{geometry::bezier{Track.m_paths.front()}.point(0.5)}; + if (at == route.spans.end()) + { + nmt_note(nmt_state::finding::kind::refused, &Track, &Track, Track.Length(), middle, STR("No line of tracks runs over the track")); + return false; + } + auto first{at}; + while (first != route.spans.begin() && false == fitted(std::prev(first)->track)) + --first; + auto last{at}; + while (std::next(last) != route.spans.end() && false == fitted(std::next(last)->track)) + ++last; + route.spans = {first, std::next(last)}; + profile.open = true; + profile.status.clear(); + profile.error.clear(); + auto *from{route.spans.front().track}; + auto *to{route.spans.back().track}; + profile_take(std::move(route), from, to); + if (false == profile.error.empty() || profile.samples.empty()) + { + nmt_note(nmt_state::finding::kind::refused, from, to, profile.route.length, middle, profile.error.empty() ? STR("The line has no profile") : profile.error); + return false; + } + // an end which goes on into a line fitted already keeps its height and grade; any other end is free, the tracks past it are + // fitted later and meet this line then + auto const joint = [&](bool const Atend, double &Height) { + double grade; + TTrack *adjoining{nullptr}; + int path{0}; + if (false == editor_track::adjoining_grade(profile.route, Atend, grade, &adjoining, &path) || adjoining == nullptr || false == fitted(adjoining)) + return false; + auto const &end{Atend ? profile.samples.back().position : profile.samples.front().position}; + auto const &points{adjoining->m_paths[path].points}; + auto const &start{points[segment_data::point::start]}; + auto const &finish{points[segment_data::point::end]}; + Height = geometry::plan_distance(start, end) < geometry::plan_distance(finish, end) ? start.y : finish.y; + return true; + }; + profile.context.start_joined = profile.context.start_joined && joint(false, profile.context.start_elevation); + profile.context.end_joined = profile.context.end_joined && joint(true, profile.context.end_elevation); + auto const on_route = [&](TTrack const *Other) { return std::any_of(profile.route.spans.begin(), profile.route.spans.end(), [&](auto const &Span) { return Span.track == Other; }); }; + // an end on a switch which meets a switch fitted already unlinked, laid apart in height, takes it over as if it went on into it + auto const partner_of = [&](editor_track::route_span const &Span, bool const Atend) -> std::optional { + auto const found{m_nmt_state.loose.find({Span.track, Span.path, Atend})}; + if (found == m_nmt_state.loose.end() || on_route(std::get<0>(found->second))) + return std::nullopt; + auto const end{end_of(*std::get<0>(found->second), std::get<1>(found->second), std::get<2>(found->second))}; + if (glm::length(geometry::plan_of(end.outward)) < 1e-6) + return std::nullopt; + return end; + }; + auto const loose_into = [&](editor_track::route_span const &Span, bool const Atend) -> std::optional { + auto const end{partner_of(Span, Atend)}; + return end.has_value() && fitted(end->track) ? end : std::nullopt; + }; + // rising off the end met, into the route at its start and against it at its end + auto const rising = [](loose_end const &End) { return End.outward.y / glm::length(geometry::plan_of(End.outward)); }; + if (false == profile.context.start_joined) + if (auto const end{loose_into(profile.route.spans.front(), false == profile.route.spans.front().forward)}) + { + profile.context.start_joined = true; + profile.context.start_elevation = end->point.y; + profile.context.start_grade = rising(*end); + } + if (false == profile.context.end_joined) + if (auto const end{loose_into(profile.route.spans.back(), profile.route.spans.back().forward)}) + { + profile.context.end_joined = true; + profile.context.end_elevation = end->point.y; + profile.context.end_grade = -rising(*end); + } + // the ground of the line: the terrain model on its axis, the top of the ballast with the rails on it, and the rail tops of + // the lines fitted already beside it on the same level as the model here, which tell its height the more closely the + // nearer they are. What doesn't agree with the line, a bridge over it, the ground under a viaduct, the fit lets go of by + // itself + double constexpr kModel{0.15}; // m, the tolerance of the model + double constexpr kRail{0.02}; // m, of a rail top next to the line, growing by kSpread a metre of the distance + double constexpr kSpread{0.01}; + double constexpr kLevel{0.5}; // m, a rail top farther from the model or from the line lies on another level + double constexpr kSameLevel{1.0}; // m, tracks authored closer in height lie on one level, farther one over the other + double constexpr kReach{50.0}; + auto const nearest = [&](glm::dvec3 const &Point, double &Distance) { + Distance = std::numeric_limits::max(); + double height{0.0}; + auto const cx{static_cast(std::floor(Point.x / kPlanCell))}; + auto const cz{static_cast(std::floor(Point.z / kPlanCell))}; + for (int dx = -1; dx <= 1; ++dx) + for (int dz = -1; dz <= 1; ++dz) + { + auto const cell{m_nmt_state.laid.find({cx + dx, cz + dz})}; + if (cell == m_nmt_state.laid.end()) + continue; + for (auto const &laid : cell->second) + if (auto const distance{glm::length(glm::dvec2{laid.position.x - Point.x, laid.position.z - Point.z})}; distance < Distance) + { + Distance = distance; + height = laid.position.y; + } + } + return height; + }; + // an end of the line, or the other path of a switch of it, which leads through the tracks not fitted yet into a line fitted + // already, as at a crossover, ties the two where it leaves the line: there the line keeps to the height of the other, on + // along its grade over the tracks between, give or take what the plain tracks among these can climb with curves of the least + // radius. A switch lies in its plane and climbs nothing. Where they can climb more than a little, the curves of the norms of + // the line come first: what it can't keep to, the tracks between take over + double constexpr kJoin{0.002}; // m + double constexpr kClimbing{0.05}; // m + double constexpr kFarthest{200.0}; + profile::ground_fit options; + // an end on the rim of a turntable runs up to it level at its height, as far as kRunUp off it or half the line, which turns to + // the ground only past that, not at the edge of the pit; the model in the pit isn't its ground + auto const first_chainage{profile.samples.front().chainage}; + auto const last_chainage{profile.samples.back().chainage}; + for (auto const atend : {false, true}) + { + auto const &span{atend ? profile.route.spans.back() : profile.route.spans.front()}; + auto const end{end_of(*span.track, span.path, atend ? span.forward : false == span.forward)}; + auto const table{std::find_if(m_nmt_state.turntables.begin(), m_nmt_state.turntables.end(), [&](nmt_state::turntable const &Table) { return on_rim(end, Table.centre, Table.rim); })}; + if (table == m_nmt_state.turntables.end()) + continue; + auto const height{table->centre.y}; + auto const level{std::min(kRunUp, 0.5 * (last_chainage - first_chainage))}; + auto const from{atend ? last_chainage - level : first_chainage}; + (atend ? profile.context.end_joined : profile.context.start_joined) = true; + (atend ? profile.context.end_elevation : profile.context.start_elevation) = height; + (atend ? profile.context.end_grade : profile.context.start_grade) = 0.0; + profile.context.switches.push_back({from, from + level, table->table->name()}); + for (int metre = 0; from + metre <= from + level + 1e-6; ++metre) + options.bounds.push_back({from + metre, height - kJoin, height + kJoin, false}); + WriteLog(format("Editor: NMT line %s runs up to turntable %s level at %.2f m over %.1f m", Track.name().c_str(), table->table->name().c_str(), height, level), logtype::generic); + } + auto const in_pit =[&](glm::dvec3 const &Point) { + return std::any_of(m_nmt_state.turntables.begin(), m_nmt_state.turntables.end(), [&](nmt_state::turntable const &Table) { return geometry::plan_distance(Point, Table.centre) < Table.rim + kPitWall; }); + }; + auto const length_of =[](TTrack const &Track, int const Path) { return Track.eType == tt_Switch ? Track.SwitchExtension->Segments[Path]->GetLength() : Track.Segment->GetLength(); }; + std::vector exits; + exits.push_back({profile.route.spans.front().track, profile.route.spans.front().path, false == profile.route.spans.front().forward}); + exits.push_back({profile.route.spans.back().track, profile.route.spans.back().path, profile.route.spans.back().forward}); + for (auto const &span : profile.route.spans) + if (span.track->eType == tt_Switch && span.track->m_paths.size() >= 2) + for (auto const outward : {true, false}) + exits.push_back({span.track, 1 - span.path, outward}); + // a switch entered at the far end of a path has the far end of its other path on its plane as high, when as far along it + auto const frog_beside = [](TTrack const &Switch, int const Path) { + if (Switch.m_paths.size() < 2) + return false; + auto const &entered{Switch.m_paths[Path].points}; + auto const &other{Switch.m_paths[1 - Path].points}; + auto const &origin{entered[segment_data::point::start]}; + auto const &control{entered[segment_data::point::control1]}; + auto const along{geometry::plan_of(control != glm::dvec3{} ? control : entered[segment_data::point::end] - origin)}; + if (glm::length(along) < 1e-6) + return false; + auto const ahead = [&](glm::dvec3 const &Point) { return glm::dot(geometry::plan_of(Point - origin), glm::normalize(along)); }; + return std::abs(ahead(entered[segment_data::point::end]) - ahead(other[segment_data::point::end])) <= 0.5; + }; + for (auto const &exiting : exits) + { + auto const &exit{exiting.track->m_paths[exiting.path].points[exiting.forward ? segment_data::point::end : segment_data::point::start]}; + auto const bind = [&](double const Height, double const Between, double const Bending) { + std::size_t nearest{0}; + for (std::size_t i = 1; i < profile.samples.size(); ++i) + if (geometry::plan_distance(profile.samples[i].position, exit) < geometry::plan_distance(profile.samples[nearest].position, exit)) + nearest = i; + auto const climbing{Bending * Between / (4.0 * profile.line.norms.radius_min)}; + options.bounds.push_back({profile.samples[nearest].chainage, Height - kJoin - climbing, Height + kJoin + climbing, climbing >= kClimbing}); + }; + // the tracks it leads into, the nearest first, through both paths of a switch met at its start and across the frog of one + // met at the end of a path, onto the end of its other path + struct walk + { + editor_track::route_span span; + double between{0.0}; // m, over the tracks not fitted yet + double bending{0.0}; // m, of these the plain tracks + }; + std::vector open{{exiting, 0.0, 0.0}}; + std::set> seen; + while (false == open.empty()) + { + auto const nearest{std::min_element(open.begin(), open.end(), [](walk const &A, walk const &B) { return A.between < B.between; })}; + auto const step{*nearest}; + open.erase(nearest); + if (step.between >= kFarthest || false == seen.insert({step.span.track, step.span.path, step.span.forward}).second) + continue; + auto onward{editor_track::continuations(step.span)}; + onward.erase(std::remove_if(onward.begin(), onward.end(), [&](editor_track::continuation const &Next) { return on_route(Next.span.track); }), onward.end()); + // met unlinked, laid apart in height: on as if linked + if (onward.empty()) + if (auto const end{partner_of(step.span, step.span.forward)}) + onward.push_back({{end->track, end->path, false == end->atend}, -rising(*end)}); + for (auto const &[next, grade] : onward) + { + auto const &points{next.track->m_paths[next.path].points}; + auto const entry{points[next.forward ? segment_data::point::start : segment_data::point::end].y}; + if (fitted(next.track)) + { + bind(entry - grade * step.between, step.between, step.bending); + continue; + } + auto const length{length_of(*next.track, next.path)}; + open.push_back({next, step.between + length, step.bending + (next.track->eType == tt_Switch ? 0.0 : length)}); + if (false == next.forward && next.track->eType == tt_Switch && frog_beside(*next.track, next.path)) + open.push_back({{next.track, 1 - next.path, true}, step.between, step.bending}); + } + } + } + // the lines fitted already close beside it on its level, as authored, are ground it never lets go of, however far they are + // off: side by side the tracks lie on one formation, in one plane, as near as the curves of the norms let them. The nearest + // on each side. Where they run so near that the timbers carry both, at a switch, a crossover, they are at one height, on + // any vertical curve the timbers lie on + double constexpr kNear{8.0}; // m between the axes + double constexpr kHeld{5.0}; // m, the reach of their rail tops + double constexpr kTimbers{2.65}; // m between the axes, about the length of a sleeper + double constexpr kTimbered{0.005}; // m + // the stretches of the line about a track it crosses on another level, as the model tells it further on: the rails at the height + // of that track are nothing to the line there, however near and however the file has them + double constexpr kOtherSide{2.0}; // m + struct other_level + { + TTrack const *track; + double chainage; + double reach; // m along the line on both sides + double height; + }; + std::vector other_levels; + auto const on_other_level = [&](double const Chainage, double const Height) { + return std::any_of(other_levels.begin(), other_levels.end(), [&](other_level const &Other) { return std::abs(Chainage - Other.chainage) <= Other.reach && std::abs(Height - Other.height) < kOtherSide; }); + }; + auto const alongside = [&](editor_track::route_sample const &Sample) { + std::array, 2> sides{std::pair{kNear, nullptr}, std::pair{kNear, nullptr}}; + auto const along{glm::normalize(Sample.direction)}; + auto const cx{static_cast(std::floor(Sample.position.x / kPlanCell))}; + auto const cz{static_cast(std::floor(Sample.position.z / kPlanCell))}; + for (int dx = -1; dx <= 1; ++dx) + for (int dz = -1; dz <= 1; ++dz) + { + auto const cell{m_nmt_state.laid.find({cx + dx, cz + dz})}; + if (cell == m_nmt_state.laid.end()) + continue; + for (auto const &point : cell->second) + { + glm::dvec2 const offset{point.position.x - Sample.position.x, point.position.z - Sample.position.z}; + auto const across{along.x * offset.y - along.y * offset.x}; + if (std::abs(glm::dot(offset, along)) > 1.0 || std::abs(across) >= kNear || std::abs(point.was - Sample.position.y) > kSameLevel || on_other_level(Sample.chainage, point.position.y)) + continue; + auto &side{sides[across > 0.0 ? 0 : 1]}; + if (std::abs(across) < side.first) + side = {std::abs(across), &point}; + } + } + return sides; + }; + auto const count{profile.samples.size()}; + std::vector sampled(count), model(count, std::numeric_limits::quiet_NaN()); + std::vector plan(count); + std::vector chainages, ground, tolerances, reaches; + // where the line crosses another track at an angle, with no joint with it, the model shows the formation of the one on top and tells + // nothing of the other: there it's no ground of the line, the height comes from the terrain on both sides, a line low there going under + double constexpr kCrossedNear{2.0}; // m + double constexpr kCrossedSine{0.5}; // 30 degrees + double constexpr kCrossedReach{20.0}; // m along the line on both sides, about what the formation with its slopes takes + std::vector crossed(count, 0); + for (std::size_t i = 0; i < count; ++i) + { + auto const &sample{profile.samples[i]}; + auto const along{glm::normalize(sample.direction)}; + auto const cx{static_cast(std::floor(sample.position.x / kPlanCell))}; + auto const cz{static_cast(std::floor(sample.position.z / kPlanCell))}; + for (int dx = -1; dx <= 1 && crossed[i] == 0; ++dx) + for (int dz = -1; dz <= 1 && crossed[i] == 0; ++dz) + if (auto const cell{m_nmt_state.paths.find({cx + dx, cz + dz})}; cell != m_nmt_state.paths.end()) + for (auto const &point : cell->second) + if (false == on_route(point.track) && glm::length(glm::dvec2{point.position.x - sample.position.x, point.position.z - sample.position.z}) < kCrossedNear && std::abs(along.x * glm::normalize(point.direction).y - along.y * glm::normalize(point.direction).x) > kCrossedSine) + { + crossed[i] = 1; + break; + } + } + std::vector no_ground(count, 0); + for (std::size_t i = 0; i < count; ++i) + if (crossed[i] != 0) + for (std::size_t j = 0; j < count; ++j) + if (std::abs(profile.samples[j].chainage - profile.samples[i].chainage) <= kCrossedReach) + no_ground[j] = 1; + for (std::size_t i = 0; i < count; ++i) + { + auto const &sample{profile.samples[i]}; + auto const *track{sample.span < profile.route.spans.size() ? profile.route.spans[sample.span].track : nullptr}; + sampled[i] = sample.chainage; + plan[i] = {sample.position.x, sample.position.z}; + if (double height; no_ground[i] == 0 && track != nullptr && shapes_ground(*track) && false == in_pit(sample.position) && m_nmt.height(sample.position.x, sample.position.z, height)) + model[i] = height + m_nmt_state.offset + track->rail_height(); + } + // a path which the line crosses on its level, as authored, makes a crossing with it: over it the two lie in one plane, the + // grade doesn't break nor does a vertical curve reach; the line crosses a line fitted already at its height, the rail tops + // of the two at one + double constexpr kCrossing{0.75}; // m, the nearest the samples of the two come, a metre apart + double constexpr kCrossed{0.035}; // the sine of the least angle the axes cross at + double constexpr kGauge{1.435}; // m + struct crossing + { + double chainage; + double height; + double sine; + double distance; + TTrack const *track; + glm::dvec2 at; // where the axes meet + glm::dvec2 along; // the way of the line there + }; + auto const crossings_of = [&](std::map, std::vector> const &Points) { + std::vector found; + auto const across = [](glm::dvec2 const &A, glm::dvec2 const &B) { return A.x * B.y - A.y * B.x; }; + for (auto const &sample : profile.samples) + { + auto const *track{profile.route.spans[sample.span].track}; + auto const cx{static_cast(std::floor(sample.position.x / kPlanCell))}; + auto const cz{static_cast(std::floor(sample.position.z / kPlanCell))}; + auto const along{glm::normalize(sample.direction)}; + for (int dx = -1; dx <= 1; ++dx) + for (int dz = -1; dz <= 1; ++dz) + { + auto const cell{Points.find({cx + dx, cz + dz})}; + if (cell == Points.end()) + continue; + for (auto const &point : cell->second) + { + glm::dvec2 const offset{point.position.x - sample.position.x, point.position.z - sample.position.z}; + auto const other{glm::normalize(point.direction)}; + auto const sine{across(along, other)}; + if (point.track == track || glm::length(offset) > kCrossing || std::abs(point.was - sample.position.y) > kSameLevel || std::abs(sine) < kCrossed) + continue; + // where the axes meet + auto const here{across(offset, other) / sine}; + auto const there{across(offset, along) / sine}; + found.push_back({sample.chainage + here, point.position.y + there * point.grade + point.rails - track->rail_height(), std::abs(sine), glm::length(offset), point.track, glm::dvec2{sample.position.x, sample.position.z} + along * here, along}); + } + } + } + // the nearest samples of each crossing tell it + std::sort(found.begin(), found.end(), [](crossing const &A, crossing const &B) { return std::tie(A.track, A.chainage) < std::tie(B.track, B.chainage); }); + std::vector result; + for (auto const &one : found) + if (one.chainage < 0.0 || one.chainage > profile.route.length || on_route(one.track)) + continue; + else if (result.empty() || result.back().track != one.track || one.chainage - result.back().chainage > 5.0) + result.push_back(one); + else if (one.distance < result.back().distance) + result.back() = one; + return result; + }; + // the height of a crossing of a line fitted already is ground the line keeps to as closely as to the switches beside, though + // not past the curves of the norms: where an end fitted another way is too near, as near as they let it + double constexpr kCrossingHeight{0.005}; // m + struct crossing_hold + { + double chainage; + double height; + double tolerance; + double reach; + }; + std::vector crossing_holds; + for (auto const &found : crossings_of(m_nmt_state.laid)) + { + // the ground on both sides well below the track crossed, or well above it: one goes under the other, however the file has them, + // which often lays both at one height. It's read past the formation of the track crossed, which takes the longer stretch of the + // line the lower the angle: nearer the model shows that formation, or the cutting under it, and tells nothing of this line + double constexpr kFormation{10.0}; // m to the side of the axis of the track crossed + double constexpr kFormationReach{150.0}; // m along the line at most + auto const reach{std::clamp(kFormation / found.sine, kCrossedReach, kFormationReach)}; + auto const terrain_towards = [&](int const Way) { + auto const last{static_cast(count) - 1}; + auto const from{std::min(last, static_cast(std::distance(sampled.begin(), std::lower_bound(sampled.begin(), sampled.end(), found.chainage + Way * reach))))}; + for (auto at{from}; at >= 0 && at <= last; at += Way) + if (std::isfinite(model[at])) + return model[at]; + return std::numeric_limits::quiet_NaN(); + }; + auto const before{terrain_towards(-1)}; + auto const after{terrain_towards(1)}; + auto const sides{std::isfinite(before) && std::isfinite(after)}; + auto const above{sides && before > found.height + kOtherSide && after > found.height + kOtherSide}; + auto const below{sides && before < found.height - kOtherSide && after < found.height - kOtherSide}; + if (above || below) + other_levels.push_back({found.track, found.chainage, std::max(reach, kNear / found.sine), found.height}); + if (above) + continue; + if (below) + { + // under it far enough for a train and what carries the track above, whatever the model has of the formation of that track + double constexpr kUnder{6.0}; // m, rail to rail + double constexpr kUnderReach{30.0}; // m, the ground the line lets go of for it + for (std::size_t i = 0; i < count; ++i) + if (std::abs(sampled[i] - found.chainage) <= reach && model[i] > std::max(before, after) + kOtherSide) + model[i] = std::numeric_limits::quiet_NaN(); + crossing_holds.push_back({found.chainage, std::min(found.height - kUnder, std::max(before, after)), kRail, kUnderReach}); + continue; + } + crossing_holds.push_back({found.chainage, found.height, kCrossingHeight, kLevel}); + } + for (std::size_t i = 0; i < count; ++i) + { + auto const &sample{profile.samples[i]}; + auto const *track{sample.span < profile.route.spans.size() ? profile.route.spans[sample.span].track : nullptr}; + chainages.push_back(sample.chainage); + ground.push_back(model[i]); + tolerances.push_back(kModel); + reaches.push_back(kModel); + double distance; + auto const beside{nearest(sample.position, distance)}; + if (no_ground[i] == 0 && distance < kReach && (false == std::isfinite(model[i]) || std::abs(beside - model[i]) <= kLevel) && false == on_other_level(sample.chainage, beside)) + { + chainages.push_back(sample.chainage); + ground.push_back(beside); + tolerances.push_back(std::max(kRail, kSpread * distance)); + reaches.push_back(kLevel); + } + if (track != nullptr && no_ground[i] == 0) + for (auto const &[apart, point] : alongside(sample)) + if (point != nullptr) + { + chainages.push_back(sample.chainage); + ground.push_back(point->position.y + point->rails - track->rail_height()); + tolerances.push_back(apart < kTimbers ? kTimbered : std::max(kRail, kSpread * apart)); + reaches.push_back(kHeld); + } + // a line fitted already crossing it or beside it on another level, one track going under the other, as authored: the difference + // stays, whatever the model has there, which knows nothing of the cutting or of the bridge + double constexpr kOtherLevel{2.5}; // m in the plan + double constexpr kOtherFarthest{25.0}; // m in height, more isn't a track it has anything to do with + double constexpr kOtherReach{30.0}; // m, the ground the line lets go of for it + auto closest{kOtherLevel}; + nmt_state::laid_point const *other{nullptr}; + auto const cx{static_cast(std::floor(sample.position.x / kPlanCell))}; + auto const cz{static_cast(std::floor(sample.position.z / kPlanCell))}; + for (int dx = -1; dx <= 1; ++dx) + for (int dz = -1; dz <= 1; ++dz) + if (auto const cell{m_nmt_state.laid.find({cx + dx, cz + dz})}; cell != m_nmt_state.laid.end()) + for (auto const &point : cell->second) + { + auto const levels{std::abs(point.was - sample.position.y)}; + auto const distance{glm::length(glm::dvec2{point.position.x - sample.position.x, point.position.z - sample.position.z})}; + if (point.track != track && levels > kSameLevel && levels <= kOtherFarthest && distance < closest && false == on_other_level(sample.chainage, point.position.y)) + { + closest = distance; + other = &point; + } + } + if (other != nullptr) + { + chainages.push_back(sample.chainage); + ground.push_back(other->position.y + (sample.position.y - other->was)); + tolerances.push_back(kRail); + reaches.push_back(kOtherReach); + } + } + if (std::none_of(ground.begin(), ground.end(), [](double const Height) { return std::isfinite(Height); })) + { + nmt_note(nmt_state::finding::kind::refused, from, to, profile.route.length, middle, STR("The terrain model has no data under the line")); + return false; + } + // no farther than the path crossed has rails: the middle of a double slip, a few metres crossed at a low angle, keeps to + // itself, the switches about it have zones of their own + for (auto const &found : crossings_of(m_nmt_state.paths)) + { + // a track going over or under isn't crossed on the rails + if (std::any_of(other_levels.begin(), other_levels.end(), [&](other_level const &Other) { return Other.track == found.track; })) + continue; + auto const half{std::min(30.0, kGauge / found.sine + 1.5)}; + auto first{std::numeric_limits::max()}; + auto last{std::numeric_limits::lowest()}; + for (auto const &path : found.track->m_paths) + for (auto const end : {segment_data::point::start, segment_data::point::end}) + { + auto const along{glm::dot(glm::dvec2{path.points[end].x, path.points[end].z} - found.at, found.along)}; + first = std::min(first, along); + last = std::max(last, along); + } + auto const from{std::max(-half, first - 1.5)}; + auto const to{std::min(half, last + 1.5)}; + if (from < to) + profile.context.switches.push_back({found.chainage + from, found.chainage + to, found.track->name()}); + } + for (auto const &hold : crossing_holds) + { + auto const at{static_cast(std::distance(chainages.begin(), std::upper_bound(chainages.begin(), chainages.end(), hold.chainage)))}; + chainages.insert(chainages.begin() + at, hold.chainage); + ground.insert(ground.begin() + at, hold.height); + tolerances.insert(tolerances.begin() + at, hold.tolerance); + reaches.insert(reaches.begin() + at, hold.reach); + } + // the switches of the tracks beside, the ones of the crossovers above all, lie on bearers common with this track or close + // to it: no break of the grade on them either, so the tracks of the station stay in one plane + double constexpr kShared{7.0}; // m, about the spacing of the tracks + for (auto *other : simulation::Paths.sequence()) + { + if (other == nullptr || other->eType != tt_Switch || other->m_paths.empty() || false == rail(*other)) + continue; + if (std::any_of(profile.route.spans.begin(), profile.route.spans.end(), [&](auto const &Span) { return Span.track == other; })) + continue; + auto const &points{other->m_paths.front().points}; + double from{std::numeric_limits::max()}; + double to{std::numeric_limits::lowest()}; + for (auto const end : {segment_data::point::start, segment_data::point::end}) + { + auto const &point{points[end]}; + double best{kShared}; + double chainage{0.0}; + for (auto const &sample : profile.samples) + if (auto const distance{glm::length(glm::dvec2{sample.position.x - point.x, sample.position.z - point.z})}; distance < best) + { + best = distance; + chainage = sample.chainage; + } + if (best < kShared) + { + from = std::min(from, chainage); + to = std::max(to, chainage); + } + } + if (from < to) + profile.context.switches.push_back({from, to, other->name()}); + } + std::sort(profile.context.switches.begin(), profile.context.switches.end(), [](auto const &Left, auto const &Right) { return Left.from < Right.from; }); + auto settings{profile.line}; + settings.join_start = true; + settings.join_end = true; + settings.speed = editor_track::route_speed(profile.route); + // the grades as steep as the ground has them, up to 50 per mille whatever the norms of the line; the vertical curves of the norms, + // sharper only on a hump of a marshalling yard + options.tolerance = kModel; + options.grade_max = 50.0; + options.follow_length = 60.0; + options.follow_height = 4.0; + options.follow_steepest = 100.0; + options.follow_tolerance = 0.05; + options.humps = profile::humps(chainages, ground, profile.context, kModel, tolerances); + options.hump_radius = 300.0; + for (auto const &hump : options.humps) + profile.context.humps.push_back({hump.from, hump.to, {}}); + auto line{profile::fit_ground(chainages, ground, profile.context, settings, options, tolerances, reaches)}; + if (line.points.size() < 2) + { + nmt_note(nmt_state::finding::kind::refused, from, to, profile.route.length, middle, STR("No grade line fits the terrain model under the line")); + return false; + } + profile.line = std::move(line); + profile.selected = -1; + profile_check(); + auto const fitted_line{profile.line}; + auto const authored{profile.samples}; + // where the model falls away under the line by the abutments, the line goes over on a bridge or a viaduct: its paths there + // are cut off and set to the bridge, the formation is laid up to it, the ground under it stays as the model has it + double constexpr kBridged{1.0}; // m + double constexpr kAbutment{100.0}; // per mille + // spans a few metres apart are one bridge on its piers; what is shorter than that is a culvert under the embankment + double constexpr kPier{5.0}; // m + double constexpr kCulvert{3.0}; // m + double constexpr kFewest{0.03}; // m, how far a path just laid may part from the line before it's cut + std::vector heights(count); + for (std::size_t i = 0; i < count; ++i) + heights[i] = profile::elevation(fitted_line, sampled[i]); + std::vector bridges; + for (auto const &stretch : Laid ? std::vector{} : profile::bridged(sampled, heights, model, kBridged, kAbutment)) + if (false == bridges.empty() && stretch.from - bridges.back().to < kPier) + { + bridges.back().to = stretch.to; + bridges.back().depth = std::min(bridges.back().depth, stretch.depth); + } + else + bridges.push_back(stretch); + bridges.erase(std::remove_if(bridges.begin(), bridges.end(), [&](profile::departure const &Bridge) { return Bridge.to - Bridge.from < kCulvert; }), bridges.end()); + profile.fitting = true; + profile_apply(false, bridges, Laid ? kFewest : 0.0); + profile.fitting = false; + auto const applied{profile.error.empty()}; + // where the line parts from the model: under it a gap, a bridge or a viaduct, over it a wall or a structure above the track + auto const parted{profile::departures(fitted_line, sampled, model, 2.0 * kModel)}; + if (false == parted.empty()) + ++m_nmt_state.departures; + std::size_t agreeing{0}; + std::size_t modelled{0}; + for (std::size_t i = 0; i < count; ++i) + if (std::isfinite(model[i])) + { + ++modelled; + agreeing += std::abs(profile::elevation(fitted_line, sampled[i]) - model[i]) <= kModel ? 1 : 0; + } + // how soon past a switch or its shared timbers the grade changes, the nearest break or start of a curve of the line + if (applied) + { + auto const breaks{profile::breaks(profile.line)}; + double nearest{std::numeric_limits::max()}; + std::string where; + for (auto const &zone : profile.context.switches) + for (auto const at : breaks) + { + auto const gap{at >= zone.to ? at - zone.to : at <= zone.from ? zone.from - at : -1.0}; + if (gap >= 0.0 && gap < nearest) + { + nearest = gap; + where = format("%.1f m %s %s (%.1f..%.1f), the break at %.1f", gap, at >= zone.to ? "past" : "before", zone.name.c_str(), zone.from, zone.to, at); + } + } + if (false == where.empty()) + WriteLog(format("Editor: NMT line %s .. %s: the grade changes %s", from->name().c_str(), to->name().c_str(), where.c_str()), logtype::generic); + } + // where the paths didn't take the line + double off{0.0}; + std::size_t off_at{0}; + if (applied) + for (std::size_t i = 0; i < profile.samples.size(); ++i) + if (auto const departure{std::abs(profile.samples[i].position.y - profile::elevation(profile.line, profile.samples[i].chainage))}; departure > off) + { + off = departure; + off_at = i; + } + if (off > 0.05) + { + auto const &sample{profile.samples[off_at]}; + auto const *track{profile.route.spans[sample.span].track}; + WriteLog(format("Editor: NMT line %s: the path %s (%s, %.0f m) is off the line by %.3f m at %.0f m", Track.name().c_str(), track->name().c_str(), track->eType == tt_Switch ? "switch" : "track", track->Length(), off, sample.chainage), logtype::generic); + } + if (applied) + for (auto const &hump : options.humps) + for (auto const &span : profile.route.spans) + if (span.from < hump.to && span.to > hump.from) + m_nmt_state.on_hump.insert(span.track); + if (applied) + for (auto const &sample : profile.samples) + { + auto const *track{sample.span < profile.route.spans.size() ? profile.route.spans[sample.span].track : nullptr}; + m_nmt_state.laid[{static_cast(std::floor(sample.position.x / kPlanCell)), static_cast(std::floor(sample.position.z / kPlanCell))}].push_back( + {sample.position, sample.direction, sample.grade, editor_track::sampled_elevation(authored, sample.chainage), track != nullptr ? static_cast(track->rail_height()) : 0.0, track}); + } + auto const spans{applied ? bridges : std::vector{}}; + for (auto const &stretch : spans) + for (std::size_t i = 0; i < count; ++i) + if (sampled[i] >= stretch.from && sampled[i] <= stretch.to) + m_nmt_state.bridged[{static_cast(std::floor(plan[i].x / kPlanCell)), static_cast(std::floor(plan[i].y / kPlanCell))}].push_back({plan[i].x, heights[i], plan[i].y}); + // told in the panel too: the line refused and why, the path which didn't take it, the worst place where it parts from the model + // other than over a bridge found + auto const place_at = [&](double const Chainage) { + return std::min_element(profile.samples.begin(), profile.samples.end(), [&](auto const &A, auto const &B) { return std::abs(A.chainage - Chainage) < std::abs(B.chainage - Chainage); })->position; + }; + if (false == applied) + { + auto why{profile.error}; + for (auto const &issue : profile.issues) + if (issue.error) + { + why += (why.empty() ? "" : ": ") + issue.text; + break; + } + nmt_note(nmt_state::finding::kind::refused, from, to, profile.route.length, place_at(0.5 * profile.route.length), why); + } + else if (off > 0.05) + { + auto const &sample{profile.samples[off_at]}; + nmt_note(nmt_state::finding::kind::off, from, to, profile.route.length, sample.position, format(STR_C("The path %s keeps off the line by %.2f m"), profile.route.spans[sample.span].track->name().c_str(), off), off); + } + if (applied) + { + // a ditch or a culvert of a few metres under the line, a few decimetres of the model, is no news: what's long and deep is + double constexpr kTold{0.5}; // m + double constexpr kToldLength{10.0}; // m + profile::departure const *worst{nullptr}; + for (auto const &stretch : parted) + if (std::abs(stretch.depth) >= kTold && stretch.to - stretch.from >= kToldLength && + false == std::any_of(spans.begin(), spans.end(), [&](profile::departure const &Bridge) { return stretch.depth < 0.0 && stretch.from < Bridge.to && stretch.to > Bridge.from; }) && + (worst == nullptr || std::abs(stretch.depth) > std::abs(worst->depth))) + worst = &stretch; + if (worst != nullptr) + nmt_note(nmt_state::finding::kind::parted, from, to, profile.route.length, place_at(0.5 * (worst->from + worst->to)), + worst->depth < 0.0 ? format(STR_C("Over a dip of the model %.1f m deep along %.0f m: a bridge, a culvert or the model off"), -worst->depth, worst->to - worst->from) + : format(STR_C("Under the model by %.1f m along %.0f m: a cutting, a wall or the model off"), worst->depth, worst->to - worst->from), + std::abs(worst->depth)); + } + // the line in the log: how much of it lies on the model, where it parts from it, its grades, why it wasn't applied, its + // course in the plan + std::string text{format("Editor: NMT line %s: %s .. %s, %.0f m, on the model within %.2f m over %.1f%%, parts from it", applied ? "applied" : "refused", from->name().c_str(), to->name().c_str(), profile.route.length, kModel, + 100.0 * static_cast(agreeing) / static_cast(std::max(1, modelled)))}; + for (auto const &stretch : parted) + text += format(" %s %.0f..%.0f %.1f m", stretch.depth < 0.0 ? "under" : "over", stretch.from, stretch.to, std::abs(stretch.depth)); + if (false == spans.empty()) + { + text += ", bridged"; + for (auto const &stretch : spans) + text += format(" %.0f..%.0f", stretch.from, stretch.to); + } + for (auto const &hump : options.humps) + text += format(", a hump %.0f..%.0f, its crest at %.0f %.1f m high", hump.from, hump.to, hump.crest, hump.height); + text += ", grades"; + for (std::size_t i = 1; i < fitted_line.points.size(); ++i) + { + auto const &a{fitted_line.points[i - 1]}; + auto const &b{fitted_line.points[i]}; + text += format(" %+.2f/%.0f", 1000.0 * (b.elevation - a.elevation) / std::max(1e-6, b.chainage - a.chainage), b.chainage - a.chainage); + } + if (false == applied) + { + text += "; " + profile.error; + for (auto const &issue : profile.issues) + if (issue.error) + text += " | " + issue.text; + } + text += "; plan"; + for (std::size_t i = 0; i < profile.samples.size(); i += 10) + text += format(" %.1f,%.1f", profile.samples[i].position.x, profile.samples[i].position.z); + text += format(" %.1f,%.1f", profile.samples.back().position.x, profile.samples.back().position.z); + WriteLog(text, logtype::generic); + return applied; +} + +void editor_mode::nmt_sample_paths(TTrack const &Track, std::map, std::vector> &Points) +{ + // the bridge of a turntable turns: it crosses no line nor lies beside one + if (Track.eType == tt_Table) + return; + for (auto const &path : Track.m_paths) + { + geometry::bezier const curve{path}; + auto const chord{glm::distance(path.points[segment_data::point::start], path.points[segment_data::point::end])}; + auto const count{std::max(1, static_cast(std::ceil(chord * 1.1)))}; + for (int i = 0; i <= count; ++i) + { + auto const t{static_cast(i) / count}; + auto const at{curve.point(t)}; + auto const tangent{curve.first(t)}; + auto const run{glm::length(glm::dvec2{tangent.x, tangent.z})}; + if (run > 1e-9) + Points[{static_cast(std::floor(at.x / kPlanCell)), static_cast(std::floor(at.z / kPlanCell))}].push_back( + {at, glm::dvec2{tangent.x, tangent.z} / run, tangent.y / run, at.y, static_cast(Track.rail_height()), &Track}); + } + } +} + +void editor_mode::nmt_merge_laid(std::unordered_set &Laid) +{ + auto const direction = [](segment_data const &Path) { + auto const control{geometry::plan_of(Path.points[segment_data::point::control1])}; + auto const chord{geometry::plan_of(Path.points[segment_data::point::end] - Path.points[segment_data::point::start])}; + auto const along{glm::length(control) > 1e-6 ? control : chord}; + return along / std::max(1e-12, glm::length(along)); + }; + auto const straight = [&](segment_data const &Path) { + if (std::abs(Path.radius) > 1e-3f) + return false; + auto const along{direction(Path)}; + return std::abs(geometry::cross(along, geometry::plan_of(Path.points[segment_data::point::end] - Path.points[segment_data::point::start]))) < 1e-3 + && std::abs(geometry::cross(along, geometry::plan_of(Path.points[segment_data::point::control2]))) < 1e-3; + }; + struct circle + { + glm::dvec2 centre{0.0}; + double radius{0.0}; + int side{0}; + double angle{0.0}; + }; + auto const arc = [&](segment_data const &Path) -> std::optional { + auto const radius{std::abs(static_cast(Path.radius))}; + if (radius < 1e-3 || glm::length(geometry::plan_of(Path.points[segment_data::point::control1])) < 1e-6) + return std::nullopt; + auto const start{geometry::plan_of(Path.points[segment_data::point::start])}; + auto const end{geometry::plan_of(Path.points[segment_data::point::end])}; + auto const along{direction(Path)}; + auto const side{geometry::cross(along, end - start) > 0.0 ? 1 : -1}; + circle result{start + glm::dvec2{-along.y, along.x} * (side * radius), radius, side, 0.0}; + if (std::abs(glm::distance(result.centre, end) - radius) > 0.01) + return std::nullopt; + result.angle = std::abs(geometry::signed_angle(start - result.centre, end - result.centre)); + return result; + }; + auto const alike = [](TTrack const &A, TTrack const &B) { + return editor_track::velocity(A) == editor_track::velocity(B) && A.eEnvironment == B.eEnvironment && A.iCategoryFlag == B.iCategoryFlag && A.iDamageFlag == B.iDamageFlag; + }; + editor_track::edit edit; + for (bool merged{true}; merged;) + { + merged = false; + for (auto *track : simulation::Paths.sequence()) + { + if (track == nullptr || track->m_editorremoved || false == Laid.contains(track) || track->eType != tt_Normal || track->m_paths.size() != 1) + continue; + auto *next{track->trNext}; + if (next == nullptr || next == track || next->m_editorremoved || false == Laid.contains(next) || next->eType != tt_Normal || next->m_paths.size() != 1 || next->trPrev != track || false == alike(*track, *next)) + continue; + auto const &first{track->m_paths.front()}; + auto const &second{next->m_paths.front()}; + if (glm::distance(first.points[segment_data::point::end], second.points[segment_data::point::start]) > 1e-3) + continue; + auto const length{geometry::bezier(first).plan_length() + geometry::bezier(second).plan_length()}; + if (length > geometry::longest_path) + continue; + auto path{first}; + path.pieces.clear(); + if (straight(first) && straight(second) && std::abs(geometry::cross(direction(first), direction(second))) < 1e-5 && glm::dot(direction(first), direction(second)) > 0.0) + { + path.points[segment_data::point::control1] = {}; + path.points[segment_data::point::control2] = {}; + path.radius = 0.f; + } + else if (auto const a{arc(first)}, b{arc(second)}; + a && b && a->side == b->side && std::abs(a->radius - b->radius) < 1e-3 * a->radius && glm::distance(a->centre, b->centre) < 0.01 && a->angle + b->angle <= glm::radians(90.0)) + { + auto const pieces{geometry::arc_pieces(first.points[segment_data::point::start], direction(first), 0.0, a->radius, a->angle + b->angle, a->side)}; + if (pieces.size() != 1) + continue; + path.points[segment_data::point::control1] = pieces.front().points[segment_data::point::control1]; + path.points[segment_data::point::control2] = pieces.front().points[segment_data::point::control2]; + } + else + continue; + path.points[segment_data::point::end] = second.points[segment_data::point::end]; + path.rolls[1] = second.rolls[1]; + edit.capture(*track); + editor_track::retire(*next); + Laid.erase(next); + edit.removed.push_back(next); + track->m_paths.front() = path; + editor_track::commit({track}); + merged = true; + } + } + if (false == edit.removed.empty()) + push_track_snapshot(std::move(edit.states), {}, std::move(edit.removed)); +} + +bool editor_mode::nmt_fit_laid(std::size_t const From, glm::dvec3 const End) +{ + auto &state{m_nmt_state}; + if (EditorSettings.heights() != editorSettings::lay_heights::fitted || state.stage != nmt_state::automatic::idle || false == m_nmt.placed() || From >= m_history.size()) + return false; + std::unordered_set laid; + for (auto step{From}; step < m_history.size(); ++step) + for (auto const *track : m_history[step].created) + if (track != nullptr && false == track->m_editorremoved && rail(*track)) + laid.insert(track); + auto const at_end = [&]() -> TTrack * { + for (auto *track : simulation::Paths.sequence()) + if (track != nullptr && laid.contains(track) && track->eType == tt_Normal && geometry::plan_distance(track->m_paths.front().points[segment_data::point::end], End) < 0.01) + return track; + return nullptr; + }; + auto const steps{m_history.size()}; + nmt_merge_laid(laid); + auto *last{at_end()}; + if (last == nullptr) + return false; + // the tracks around stay as they are, as lines fitted already: the line keeps level with the ones beside it, the more closely + // the nearer they are, and crosses the ones it crosses at their height + double constexpr kAround{60.0}; // m + glm::dvec2 low{std::numeric_limits::max()}; + glm::dvec2 high{std::numeric_limits::lowest()}; + for (auto const *track : laid) + for (auto const &path : track->m_paths) + for (auto const end : {segment_data::point::start, segment_data::point::end}) + { + low = glm::min(low, geometry::plan_of(path.points[end])); + high = glm::max(high, geometry::plan_of(path.points[end])); + } + low -= kAround; + high += kAround; + std::map, std::vector> around; + for (auto *track : simulation::Paths.sequence()) + { + if (track == nullptr || track->m_editorremoved || false == rail(*track) || laid.contains(track)) + continue; + auto const &points{track->m_paths.front().points}; + auto const a{geometry::plan_of(points[segment_data::point::start])}; + auto const b{geometry::plan_of(points[segment_data::point::end])}; + if (std::max(a.x, b.x) < low.x || std::min(a.x, b.x) > high.x || std::max(a.y, b.y) < low.y || std::min(a.y, b.y) > high.y) + continue; + nmt_sample_paths(*track, around); + } + // the state of the tracks going onto the terrain lent to the one line, the profile tool left as it was + auto const profile{m_profile}; + auto fitted_lines{std::exchange(state.laid, around)}; + auto paths{std::exchange(state.paths, std::move(around))}; + auto loose{std::exchange(state.loose, {})}; + auto turntables{std::exchange(state.turntables, nmt_turntables())}; + auto const departures{state.departures}; + auto const applied{nmt_fit_line(*last, [&](TTrack const *Other) { return false == laid.contains(Other); }, true)}; + auto const error{m_profile.error}; + state.laid = std::move(fitted_lines); + state.paths = std::move(paths); + state.loose = std::move(loose); + state.turntables = std::move(turntables); + state.departures = departures; + m_profile = profile; + // taken back with the laying + for (auto step{steps}; step < m_history.size(); ++step) + m_history[step].joined = true; + if (applied) + { + laid.clear(); + for (auto step{From}; step < m_history.size(); ++step) + for (auto const *track : m_history[step].created) + if (track != nullptr && false == track->m_editorremoved) + laid.insert(track); + if (auto *track{at_end()}; track != nullptr) + { + m_node = track; + ui()->set_node(m_node); + } + } + else if (false == error.empty()) + WriteLog("Editor: the track laid not put onto the terrain model - " + error, logtype::generic); + return applied; +} + +namespace +{ + +// things joined one to another in sets, each set told by its root +template > +class joined_sets +{ +public: + Thing root(Thing Of) const + { + for (auto found{m_parent.find(Of)}; found != m_parent.end() && found->second != Of; found = m_parent.find(Of)) + Of = found->second; + return Of; + } + // the set of the first root goes into the set of the second + void join_roots(Thing const &A, Thing const &B) + { + m_parent[A] = B; + m_parent.try_emplace(B, B); + } + void join(Thing const &A, Thing const &B) + { + if (auto const a{root(A)}, b{root(B)}; a != b) + join_roots(a, b); + } + // joined to anything at all + bool joined(Thing const &Of) const + { + return m_parent.contains(Of); + } + +private: + Map m_parent; +}; + +// of the least squares the moves of the grade lines shared are: the sum of the unknowns at, each by its factor, is to come to the value, +// as closely as the weight tells; an unknown under 0 ends the ones taken +struct grade_term +{ + std::array at; + std::array by; + double value; + double weight; +}; + +// the unknowns of the least squares of the terms, by conjugate gradients on the normal equations, with the iterations it took +std::vector grade_moves(std::vector const &Terms, int const Unknowns, int &Iterations) +{ + auto const multiply = [&](std::vector const &In, std::vector &Out) { + std::fill(Out.begin(), Out.end(), 0.0); + for (auto const &one : Terms) + { + auto sum{0.0}; + for (int k = 0; k < 5 && one.at[k] >= 0; ++k) + sum += one.by[k] * In[one.at[k]]; + sum *= one.weight; + for (int k = 0; k < 5 && one.at[k] >= 0; ++k) + Out[one.at[k]] += one.by[k] * sum; + } + }; + std::vector moves(Unknowns, 0.0), residual(Unknowns, 0.0), diagonal(Unknowns, 0.0); + for (auto const &one : Terms) + for (int k = 0; k < 5 && one.at[k] >= 0; ++k) + { + residual[one.at[k]] += one.weight * one.by[k] * one.value; + diagonal[one.at[k]] += one.weight * one.by[k] * one.by[k]; + } + std::vector direction(Unknowns), product(Unknowns); + auto rho{0.0}; + for (int i = 0; i < Unknowns; ++i) + { + direction[i] = residual[i] / diagonal[i]; + rho += residual[i] * direction[i]; + } + auto const first_rho{std::max(rho, 1e-30)}; + for (Iterations = 0; Iterations < 30000 && rho > 1e-14 * first_rho; ++Iterations) + { + multiply(direction, product); + auto bottom{0.0}; + for (int i = 0; i < Unknowns; ++i) + bottom += direction[i] * product[i]; + if (bottom <= 0.0) + break; + auto const step{rho / bottom}; + auto next{0.0}; + for (int i = 0; i < Unknowns; ++i) + { + moves[i] += step * direction[i]; + residual[i] -= step * product[i]; + next += residual[i] * residual[i] / diagonal[i]; + } + auto const beta{next / rho}; + rho = next; + for (int i = 0; i < Unknowns; ++i) + direction[i] = residual[i] / diagonal[i] + beta * direction[i]; + } + return moves; +} + +// the grade a path rises out of an end with, by its control there: a path on a vertical curve rises otherwise than along its chord, a +// long one with the whole curve on it by 16 permille +double rise_out(segment_data const &Path, bool const Atend) +{ + auto const &points{Path.points}; + auto const control{points[Atend ? segment_data::point::control2 : segment_data::point::control1]}; + auto const along{glm::length(geometry::plan_of(control))}; + if (along > 1e-6) + return control.y / along; + auto const length{geometry::plan_distance(points[segment_data::point::start], points[segment_data::point::end])}; + return (points[segment_data::point::end].y - points[segment_data::point::start].y) * (Atend ? -1.0 : 1.0) / std::max(1e-9, length); +} + +// a path going out of a joint: of which track, the way and the grade it leaves the joint with +struct leaving +{ + TTrack const *track; + glm::dvec2 way; + double grade; // rising out of the joint +}; + +leaving leaving_of(TTrack const *Track, segment_data const &Path, bool const Atend) +{ + auto const &points{Path.points}; + auto const control{geometry::plan_of(points[Atend ? segment_data::point::control2 : segment_data::point::control1])}; + auto const chord{geometry::plan_of(points[segment_data::point::end] - points[segment_data::point::start]) * (Atend ? -1.0 : 1.0)}; + auto const rise{(points[segment_data::point::end].y - points[segment_data::point::start].y) * (Atend ? -1.0 : 1.0)}; + if (glm::length(control) > 1e-6) + return leaving{Track, glm::normalize(control), points[Atend ? segment_data::point::control2 : segment_data::point::control1].y / glm::length(control)}; + return leaving{Track, chord / std::max(1e-9, glm::length(chord)), rise / std::max(1e-9, glm::length(chord))}; +} + +// the path on the cubic of these grades along it from end to end, its pieces too +void on_vertical_curve(segment_data &Path, double const First, double const Last) +{ + auto const origin{Path.points[segment_data::point::start]}; + auto const chord{geometry::plan_of(Path.points[segment_data::point::end] - origin)}; + auto const square{std::max(1e-9, glm::dot(chord, chord))}; + auto const length{std::sqrt(square)}; + auto const rise{Path.points[segment_data::point::end].y - origin.y}; + auto const second{3.0 * rise - (2.0 * First + Last) * length}; + auto const third{(First + Last) * length - 2.0 * rise}; + auto const height = [&](double const U) { return origin.y + U * (First * length + U * (second + U * third)); }; + auto const slope = [&](double const U) { return (First * length + U * (2.0 * second + U * 3.0 * third)) / length; }; + auto const lay = [&](segment_data &Part) { + auto &points{Part.points}; + if (points[segment_data::point::control1] == glm::dvec3{} && points[segment_data::point::control2] == glm::dvec3{}) + { + points[segment_data::point::control1] = (points[segment_data::point::end] - points[segment_data::point::start]) / 3.0; + points[segment_data::point::control2] = (points[segment_data::point::start] - points[segment_data::point::end]) / 3.0; + } + auto const along = [&](glm::dvec3 const &Point) { return std::clamp(glm::dot(geometry::plan_of(Point - origin), chord) / square, 0.0, 1.0); }; + auto const from{along(points[segment_data::point::start])}; + auto const to{along(points[segment_data::point::end])}; + points[segment_data::point::control1].y = slope(from) * glm::length(geometry::plan_of(points[segment_data::point::control1])); + points[segment_data::point::control2].y = -slope(to) * glm::length(geometry::plan_of(points[segment_data::point::control2])); + points[segment_data::point::start].y = height(from); + points[segment_data::point::end].y = height(to); + }; + for (auto &piece : Path.pieces) + lay(piece); + lay(Path); +} + +} // namespace + +void editor_mode::nmt_share_grades() +{ + // one grade line for the tracks side by side: over the grade lines fitted one by one, what each joint moves by is worked out for all + // of them at once. Tracks nearly parallel under 5.1 m apart come to one height, the moves change evenly along a line, so what was fitted stays + // smooth, and each joint keeps to where it was as far as these let it: a track going away from the others is on its own again. + // Tracks over 1 m apart in height lie on another level; a long steep one, a hump, stays as it is and tells nothing to those beside it. + // It's told for a whole run of tracks from switch to switch: one with nothing beside it over 15 m and a quarter of its length has a grade line of its own. + // The tracks and switches on common timbers lie on one surface whatever else is told of them, a plane tilting along and across as the + // ground goes, each such group its own; on it they come to one grade line as far as tracks side by side do. A switch lies in its plane + auto &state{m_nmt_state}; + // nothing fitted now, nothing to share: what stays lies as it was + if (false == state.common || (false == state.stayed.empty() && state.lines == 0)) + return; + double constexpr kApart{5.1}; // m between the axes + double constexpr kParallel{0.985}; // the cosine of the angle of tracks nearly parallel, 10 degrees: the links of a crossover are, a track crossing isn't + double constexpr kLevel{1.0}; // m, as the lines keep to tracks on another level + double constexpr kSteep{0.025}; + double constexpr kSteepLength{15.0}; // m, shorter ones are the links of a crossover between tracks at two heights + double constexpr kSpacing{5.0}; // m between the places looked at on a track + double constexpr kMoved{0.00001}; // m, any less stays: what a joint moves by goes on all the tracks at it, a millimetre left on a short one is a grade of its own + // how closely each is kept to, the weights being one over the square + double constexpr kKeep{0.5}; // m, a joint to where it was + double constexpr kBeside{0.01}; // m, tracks side by side + double constexpr kEven{0.0005}; // the change of grade the moves make at a joint + double constexpr kTimbers{2.65}; // m between the axes, about the length of a sleeper + double constexpr kOnTimbers{0.001}; // m, how closely tracks on common timbers keep to the surface of their group + double constexpr kPlane{0.005}; // m, how closely the second path of a switch keeps to the plane of the first + double constexpr kAway{15.0}; // m of a run with no track beside it, as much as its ends at the switches may part from the others + double constexpr kBroken{0.015}; // a grade breaking more than this at a joint is to go, a smaller one is the vertical curve fitted + using key = std::pair; + auto const key_of = [](glm::dvec3 const &Point) { return key{static_cast(std::round(Point.x * 20.0)), static_cast(std::round(Point.z * 20.0))}; }; + std::vector tracks; + for (auto *track : simulation::Paths.sequence()) + if (track != nullptr && false == track->m_editorremoved && rail(*track) && track->eType != tt_Table) + tracks.push_back(track); + auto const steep = [&](TTrack const &Track) { + if (state.on_hump.contains(&Track)) + return true; + return std::any_of(Track.m_paths.begin(), Track.m_paths.end(), [&](segment_data const &Path) { + auto const &start{Path.points[segment_data::point::start]}; + auto const &end{Path.points[segment_data::point::end]}; + auto const length{geometry::plan_distance(start, end)}; + return length >= kSteepLength && std::abs(end.y - start.y) > kSteep * length; + }); + }; + struct link + { + int to; + double length; + glm::dvec2 out; + double rise; // the grade rising out of the joint along the path, by its control there + }; + std::map indices; + std::vector> links; + std::vector fixed; + std::vector heights; + auto const index_of = [&](glm::dvec3 const &Point) { + auto const [found, added]{indices.try_emplace(key_of(Point), static_cast(links.size()))}; + if (added) + { + links.emplace_back(); + fixed.push_back(0); + heights.push_back(Point.y); + } + return found->second; + }; + struct place + { + glm::dvec3 position; + glm::dvec2 along; + double share; + int first; + int second; + TTrack const *track; + int path{0}; + std::size_t index{0}; + double length{0.0}; // m of the track it stands for, half a step at an end: a joint is shared by the tracks meeting at it + }; + std::vector all; + std::vector timber_all; // of all the tracks, the ones held apart too + std::unordered_set hump_nodes; + std::unordered_set stayed_nodes; + for (auto const *track : tracks) + { + auto const held{steep(*track)}; + for (auto const &path : track->m_paths) + { + auto const &start{path.points[segment_data::point::start]}; + auto const &end{path.points[segment_data::point::end]}; + auto const a{index_of(start)}; + auto const b{index_of(end)}; + auto const chord{geometry::plan_of(end - start)}; + auto const length{glm::length(chord)}; + if (a == b || length < 1e-3) + continue; + links[a].push_back({b, length, chord / length, rise_out(path, false)}); + links[b].push_back({a, length, -chord / length, rise_out(path, true)}); + // the joints of a switch keep its heights: a track ending there meets it + if (track->eType == tt_Switch) + { + heights[a] = start.y; + heights[b] = end.y; + } + if (held) + fixed[a] = fixed[b] = 1; + if (state.on_hump.contains(track)) + hump_nodes.insert({a, b}); + // what stays where it is holds its ends whatever comes up to them; nothing else moves it + if (state.stayed.contains(track)) + { + heights[a] = start.y; + heights[b] = end.y; + fixed[a] = fixed[b] = 1; + stayed_nodes.insert({a, b}); + } + geometry::bezier const curve{path}; + // no farther apart than the spacing: a track beside is looked for within 0.6 of it along, sparser places leave it unseen + auto const count{std::max(1, static_cast(std::ceil(length / kSpacing)))}; + for (int i = 0; i <= count; ++i) + { + auto const share{static_cast(i) / count}; + auto const tangent{geometry::plan_of(curve.first(share))}; + place const here{curve.point(share), glm::length(tangent) > 1e-9 ? glm::normalize(tangent) : chord / length, share, a, b, track, static_cast(&path - track->m_paths.data()), timber_all.size(), length / count * (i == 0 || i == count ? 0.5 : 1.0)}; + timber_all.push_back(here); + if (held) + continue; + all.push_back(here); + } + } + } + // the places in squares of a size, the ones around a place looked through for what's beside it + using cells = std::map>; + auto const cell_at = [](glm::dvec3 const &Point, double const Size) { return key{static_cast(std::floor(Point.x / Size)), static_cast(std::floor(Point.z / Size))}; }; + auto const cells_of = [&](std::vector const &Places, double const Size, auto const &Taken) { + cells result; + for (auto const &here : Places) + if (Taken(here)) + result[cell_at(here.position, Size)].push_back(&here); + return result; + }; + auto const around = [&](cells const &Cells, glm::dvec3 const &Point, double const Size, auto const &Each) { + auto const cell{cell_at(Point, Size)}; + for (int dx = -1; dx <= 1; ++dx) + for (int dz = -1; dz <= 1; ++dz) + if (auto const found{Cells.find({cell.first + dx, cell.second + dz})}; found != Cells.end()) + for (auto const *other : found->second) + Each(*other); + }; + auto const every = [](place const &) { return true; }; + auto const places{cells_of(all, kApart, every)}; + auto const timber_places{cells_of(timber_all, kApart, every)}; + std::vector terms; + auto const nodes{static_cast(links.size())}; + // a dead end holds firmer: nothing past it, the even moves would carry the tilt of the station on along the run as on a lever, the + // end of a line at the edge of the scenery going up by metres + double constexpr kDeadEnd{0.05}; // m + for (int i = 0; i < nodes; ++i) + terms.push_back({{i, -1, -1, -1}, {1.0, 0.0, 0.0, 0.0}, 0.0, fixed[i] != 0 ? 1e8 : links[i].size() == 1 ? 1.0 / (kDeadEnd * kDeadEnd) : 1.0 / (kKeep * kKeep)}); + for (int i = 0; i < nodes; ++i) + for (std::size_t a = 0; a < links[i].size(); ++a) + for (std::size_t b = a + 1; b < links[i].size(); ++b) + if (glm::dot(links[i][a].out, links[i][b].out) < -0.7) + { + auto const in{1.0 / links[i][a].length}; + auto const on{1.0 / links[i][b].length}; + // the grade the joint breaks by, of the paths at it, not of their chords: the chords of a curve on few paths break where + // the paths don't, and taking that out would break them + auto const change{links[i][b].rise + links[i][a].rise}; + // by the true lengths, an even move breaks no grade on a short track either; what a track under 0.5 m has of it goes by height, the numbers staying of a size + auto const scale{std::min(1.0, std::min(links[i][a].length, links[i][b].length) / 0.5)}; + terms.push_back({{links[i][b].to, i, links[i][a].to, -1}, {scale * on, -scale * (on + in), scale * in, 0.0}, std::abs(change) > kBroken ? -scale * change : 0.0, 1.0 / (kEven * kEven)}); + } + // the runs from switch to switch: plain tracks meeting at a joint nothing else meets at + std::vector> at_node(nodes); + for (auto const *track : tracks) + for (auto const &path : track->m_paths) + for (auto const end : {segment_data::point::start, segment_data::point::end}) + at_node[indices.at(key_of(path.points[end]))].push_back(track); + joined_sets runs; + for (auto const &meeting : at_node) + if (meeting.size() == 2 && meeting[0] != meeting[1] && meeting[0]->eType == tt_Normal && meeting[1]->eType == tt_Normal) + runs.join(meeting[0], meeting[1]); + // who was put on a grade line by hand stays on it, with the others put on it wherever they lie, never on another one so put + grade_lines_load(); + std::unordered_map held; + for (auto const *track : tracks) + { + auto const key{grade_line_key(*track)}; + if (auto const found{state.grade_lines.find(key)}; found != state.grade_lines.end() && found->second >= 0 && state.grade_lines_hand.contains(key)) + held[track] = found->second; + } + // the nearest place of another track on each side of one, of those taken, under the reach from it: nearly parallel to it, on its + // level and across the track, not past its end - the next piece of a line isn't beside it + auto const nearest_of = [&](place const &Here, cells const &Cells, double const Reach, auto const &Taken) { + std::array, 2> sides{std::pair{Reach, nullptr}, std::pair{Reach, nullptr}}; + around(Cells, Here.position, Reach, [&](place const &Other) { + if (Other.track == Here.track || Other.first == Here.first || Other.first == Here.second || Other.second == Here.first || Other.second == Here.second || false == Taken(Other)) + return; + glm::dvec2 const offset{Other.position.x - Here.position.x, Other.position.z - Here.position.z}; + if (std::abs(glm::dot(offset, Here.along)) > 0.6 * kSpacing || std::abs(Other.position.y - Here.position.y) > kLevel || std::abs(glm::dot(Here.along, Other.along)) < kParallel) + return; + auto const across{Here.along.x * offset.y - Here.along.y * offset.x}; + auto &side{sides[across > 0.0 ? 0 : 1]}; + if (std::abs(across) < side.first) + side = {std::abs(across), &Other}; + }); + return sides; + }; + std::unordered_set apart; + // the nearest track on each side, of the ones not held apart + auto const nearest_sides = [&](place const &Here) { + return nearest_of(Here, places, kApart, [&](place const &Other) { return false == apart.contains(runs.root(Other.track)) || held.contains(Other.track); }); + }; + // two places side by side at one height: the joints of each move as the places lie between them + auto const side_by_side = [&](place const &Here, place const &Other) { + terms.push_back({{Here.first, Here.second, Other.first, Other.second}, {1.0 - Here.share, Here.share, -(1.0 - Other.share), -Other.share}, Other.position.y - Here.position.y, 1.0 / (kBeside * kBeside)}); + }; + // the run of a track named by a selftest: how long, the places of it with nothing beside, whether it went on its own and on which line + auto const explain = [&](char const *Stage) { + for (auto const *track : tracks) + { + if (std::string::npos == state.explain.find(" " + track->name() + " ")) + continue; + auto const *run{runs.root(track)}; + std::size_t members{0}; + auto length{0.0}; + for (auto const *other : tracks) + if (runs.root(other) == run) + { + ++members; + for (auto const &path : other->m_paths) + length += geometry::plan_distance(path.points[segment_data::point::start], path.points[segment_data::point::end]); + } + std::size_t lonely{0}; + std::string where; + for (auto const &here : all) + if (runs.root(here.track) == run && here.track->eType == tt_Normal) + if (auto const sides{nearest_sides(here)}; sides[0].second == nullptr && sides[1].second == nullptr) + { + ++lonely; + if (lonely <= 40) + where += format(" %s(%.0f,%.0f,%.2f)", here.track->name().c_str(), here.position.x, here.position.z, here.position.y); + } + auto const found{state.grade_lines.find(grade_line_key(*track))}; + WriteLog(format("Editor: NMT share, %s: %s in a run of %zu tracks over %.0f m from %s, apart %d, line %d, %zu places with nothing beside:%s", Stage, track->name().c_str(), members, length, + run->name().c_str(), apart.contains(run) ? 1 : 0, found != state.grade_lines.end() ? found->second : -100, lonely, where.c_str()), + logtype::generic); + } + }; + { + // a run beside the others nearly all along stays with them: the switches at its ends often lie a few tens of metres off theirs + double constexpr kAwayShare{0.25}; + std::unordered_map alone, whole; + for (auto const &here : all) + if (here.track->eType == tt_Normal) + { + whole[runs.root(here.track)] += here.length; + if (auto const sides{nearest_sides(here)}; sides[0].second == nullptr && sides[1].second == nullptr) + alone[runs.root(here.track)] += here.length; + } + explain("alone"); + for (auto const &[run, length] : alone) + if (length > kAway && length > kAwayShare * whole[run]) + apart.insert(run); + } + // who was taken off a grade line by hand stays off them + auto const taken_off = [&](TTrack const &Track) { + auto const found{state.grade_lines.find(grade_line_key(Track))}; + return found != state.grade_lines.end() && (found->second == nmt_state::grade_line_off || found->second <= nmt_state::grade_line_off_number); + }; + std::unordered_set off; + for (auto const *track : tracks) + if (taken_off(*track)) + { + off.insert(track); + apart.insert(runs.root(track)); + } + std::size_t pairs{0}; + // the tracks on one grade line together, as they're tied side by side and along the runs + joined_sets tied; + // of a group tied, the grade line one of it was put on by hand: two groups of two such lines don't tie + std::unordered_map tied_held(held.begin(), held.end()); + auto const held_of = [&](TTrack const *Root) { + auto const found{tied_held.find(Root)}; + return found != tied_held.end() ? found->second : -1; + }; + auto const tie = [&](TTrack const *A, TTrack const *B) { + auto const *a{tied.root(A)}; + auto const *b{tied.root(B)}; + if (a == b) + return true; + auto const of_a{held_of(a)}; + auto const of_b{held_of(b)}; + if (of_a >= 0 && of_b >= 0 && of_a != of_b) + return false; + tied.join_roots(a, b); + if (of_b < 0 && of_a >= 0) + tied_held[b] = of_a; + return true; + }; + { + std::unordered_map first; + for (auto const &[track, line] : held) + if (auto const [found, added]{first.try_emplace(line, track)}; false == added) + tie(track, found->second); + } + for (auto const &here : all) + { + auto const inapart{apart.contains(runs.root(here.track))}; + if (inapart && false == held.contains(here.track)) + continue; + for (auto const &[distance, other] : nearest_sides(here)) + if (other != nullptr) + { + if (false == tie(here.track, other->track)) + continue; + ++pairs; + if (false == inapart) + tie(here.track, runs.root(here.track)); + side_by_side(here, *other); + } + } + // the tracks put on one line by hand further apart than the ones side by side, across a platform say, go up and down together too: + // each place of them with the nearest place of another track of that line on each side + double constexpr kHandApart{40.0}; // m between the axes + std::size_t hand_pairs{0}; + if (false == held.empty()) + { + auto const held_places{cells_of(all, kHandApart, [&](place const &Here) { return held.contains(Here.track); })}; + for (auto const &[cell, those] : held_places) + for (auto const *here : those) + { + auto const line{held.at(here->track)}; + for (auto const &[distance, other] : nearest_of(*here, held_places, kHandApart, [&](place const &Other) { return held.at(Other.track) == line; })) + { + // the ones side by side are tied already + if (other == nullptr || distance < kApart) + continue; + ++hand_pairs; + side_by_side(*here, *other); + } + } + } + // the groups on common timbers: tracks and switches tied by the places under a sleeper's length apart, each group on a plane of its + // own, whose three numbers are worked out with the moves + std::size_t on_timbers{0}; + // of a plain track only the stretch under the timbers counts: a long one with switches at both ends doesn't make one group of them + double constexpr kStretch{40.0}; // m + using stretch = std::tuple; + auto const stretch_of = [&](place const &Here) { + auto const &points{Here.track->m_paths[Here.path].points}; + auto const along{Here.share * geometry::plan_distance(points[segment_data::point::start], points[segment_data::point::end])}; + return stretch{Here.track, Here.track->eType == tt_Switch ? 0 : Here.path, Here.track->eType == tt_Switch ? 0 : static_cast(along / kStretch)}; + }; + joined_sets> timbered; + std::vector on_surface(timber_all.size(), 0); + for (auto const &here : timber_all) + around(timber_places, here.position, kApart, [&](place const &Other) { + if (Other.track <= here.track || (here.track->eType != tt_Switch && Other.track->eType != tt_Switch)) + return; + glm::dvec2 const offset{Other.position.x - here.position.x, Other.position.z - here.position.z}; + if (glm::length(offset) >= kTimbers || std::abs(glm::dot(offset, here.along)) > 0.6 * kSpacing || std::abs(Other.position.y - here.position.y) > kLevel) + return; + ++on_timbers; + on_surface[here.index] = on_surface[Other.index] = 1; + timbered.join(stretch_of(here), stretch_of(Other)); + }); + state.surface_places.clear(); + std::map surfaces; + struct surface_sum + { + double count{0.0}; + glm::dvec3 sum{0.0}; + }; + std::vector sums; + for (auto const &here : timber_all) + if (on_surface[here.index] != 0) + { + auto const [found, added]{surfaces.try_emplace(timbered.root(stretch_of(here)), static_cast(sums.size()))}; + if (added) + sums.emplace_back(); + sums[found->second].count += 1.0; + sums[found->second].sum += here.position; + } + double constexpr kSurfaceScale{100.0}; // m, of the tilts worked out, for numbers of a size with the others + std::unordered_set timbered_tracks; + for (auto const &here : timber_all) + if (on_surface[here.index] != 0) + { + // a steep track holds its heights, but not against the timbers it shares; a hump gives way to them as little as they let it + double constexpr kHumpKeep{0.05}; // m + for (auto const node : {here.first, here.second}) + if (false == stayed_nodes.contains(node)) + terms[node].weight = 1.0 / (hump_nodes.contains(node) ? kHumpKeep * kHumpKeep : kKeep * kKeep); + timbered_tracks.insert(here.track); + auto const surface{surfaces.at(timbered.root(stretch_of(here)))}; + auto const middle{sums[surface].sum / sums[surface].count}; + auto const level{nodes + 3 * surface}; + terms.push_back({{here.first, here.second, level, level + 1, level + 2}, {1.0 - here.share, here.share, -1.0, -(here.position.x - middle.x) / kSurfaceScale, -(here.position.z - middle.z) / kSurfaceScale}, middle.y - here.position.y, 1.0 / (kOnTimbers * kOnTimbers)}); + state.surface_places.push_back({here.track, here.path, here.share, surface}); + } + for (std::size_t surface = 0; surface < sums.size(); ++surface) + for (int k = 0; k < 3; ++k) + terms.push_back({{nodes + 3 * static_cast(surface) + k, -1, -1, -1, -1}, {1.0, 0.0, 0.0, 0.0, 0.0}, 0.0, 1.0}); + auto const unknowns{nodes + 3 * static_cast(sums.size())}; + // the end of the second path of a switch on the plane of the first + for (auto const *track : tracks) + { + if (track->eType != tt_Switch || track->m_paths.size() < 2) + continue; + auto const &main{track->m_paths[0].points}; + auto const &branch{track->m_paths[1].points}; + auto const start{indices.at(key_of(main[segment_data::point::start]))}; + auto const finish{indices.at(key_of(main[segment_data::point::end]))}; + auto const tip{indices.at(key_of(branch[segment_data::point::end]))}; + auto const chord{geometry::plan_of(main[segment_data::point::end] - main[segment_data::point::start])}; + auto const square{glm::dot(chord, chord)}; + if (start == tip || finish == tip || start != indices.at(key_of(branch[segment_data::point::start])) || square < 1e-6) + continue; + auto const share{glm::dot(geometry::plan_of(branch[segment_data::point::end] - main[segment_data::point::start]), chord) / square}; + auto const off{heights[tip] - (heights[start] + share * (heights[finish] - heights[start]))}; + terms.push_back({{tip, start, finish, -1}, {1.0, -(1.0 - share), -share, 0.0}, -off, 1.0 / (kPlane * kPlane)}); + } + // who lies on which, for the map of them: a number of each grade line shared, those on their own and the ones held apart + state.grade_lines.clear(); + { + std::unordered_map numbers; + std::unordered_map sizes; + for (auto const &here : all) + if (false == apart.contains(runs.root(here.track)) && tied.joined(here.track)) + ++sizes[tied.root(here.track)]; + // the lines put by hand keep their numbers, the others worked out get ones besides them + std::set kept; + for (auto const &[track, line] : held) + kept.insert(line); + int next{0}; + for (auto const *track : tracks) + { + auto line{nmt_state::grade_line_own}; + if (off.contains(track)) + line = nmt_state::grade_line_off; + else if (auto const found{held.find(track)}; found != held.end()) + line = found->second; + else if (steep(*track)) + line = nmt_state::grade_line_steep; + else if (false == apart.contains(runs.root(track))) + { + // by the run: a track of it with nothing beside itself lies on the line the rest of the run does + auto const root{tied.root(runs.root(track))}; + if (auto const by_hand{held_of(root)}; by_hand >= 0) + line = by_hand; + else if (sizes.contains(root)) + { + auto const [number, added]{numbers.try_emplace(root, 0)}; + if (added) + { + while (kept.contains(next)) + ++next; + number->second = next++; + } + line = number->second; + } + } + state.grade_lines[grade_line_key(*track)] = line; + } + WriteLog(format("Editor: NMT - %zu grade lines shared, %zu of them put by hand, their tracks further apart tied at %zu places", numbers.size() + kept.size(), kept.size(), hand_pairs), logtype::generic); + explain("lines"); + ++state.grade_lines_changes; + grade_lines_store(); + } + // the least squares of all of it + int iterations{0}; + auto const moves{grade_moves(terms, unknowns, iterations)}; + // the joints of the runs of the tracks named by a selftest: the height before and the move, held or not + for (auto const *track : tracks) + if (std::string::npos != state.explain.find(" " + track->name() + " ")) + { + std::string joints; + for (auto const *other : tracks) + if (runs.root(other) == runs.root(track)) + for (auto const &path : other->m_paths) + { + auto const at{indices.at(key_of(path.points[segment_data::point::end]))}; + joints += format(" %s %.2f%+.2f%s", other->name().c_str(), heights[at], moves[at], fixed[at] != 0 ? " held" : ""); + } + WriteLog(format("Editor: NMT share, moved: %s, the ends of the run:%s", track->name().c_str(), joints.c_str()), logtype::generic); + } + // what the end moves by, with what it's off the others at its joint, the switch there first + auto const move_of = [&](glm::dvec3 const &Point) { + auto const at{indices.at(key_of(Point))}; + auto const off{heights[at] - Point.y}; + return moves[at] + (std::abs(off) <= 1.0 ? off : 0.0); + }; + editor_track::edit edit; + std::vector moved; + auto largest{0.0}; + TTrack const *largest_at{nullptr}; + double constexpr kTilted{0.005}; // how far the mean grade at the ends of a path may be from its grade from end to end + double constexpr kTiltedShortest{5.0}; // m, a shorter one tells little by the grades at its ends + std::size_t straightened{0}; + for (auto *track : tracks) + { + if (state.stayed.contains(track)) + continue; + auto changed{false}; + for (auto const &path : track->m_paths) + for (auto const end : {segment_data::point::start, segment_data::point::end}) + { + if (std::abs(move_of(path.points[end])) > largest) + { + largest = std::abs(move_of(path.points[end])); + largest_at = track; + } + changed = changed || std::abs(move_of(path.points[end])) >= kMoved; + } + if (false == changed) + continue; + edit.capture(*track); + moved.push_back(track); + // a switch on common timbers lies straight between its ends, no vertical curve taking it off their surface; the other paths where + // the grades at their ends, which average to the grade from end to end on a vertical curve, are far from it: the ends were brought + // to the tracks adjoining with the grades left as they were, and the path waves between them + auto const settle = [&](segment_data &Part) { + auto &points{Part.points}; + if (points[segment_data::point::control1] == glm::dvec3{} && points[segment_data::point::control2] == glm::dvec3{}) + return; + auto const span{geometry::plan_of(points[segment_data::point::end] - points[segment_data::point::start])}; + auto const rise{points[segment_data::point::end].y - points[segment_data::point::start].y}; + auto const tilted = [&] { + auto const length{glm::length(span)}; + auto const before{glm::length(geometry::plan_of(points[segment_data::point::control1]))}; + auto const after{glm::length(geometry::plan_of(points[segment_data::point::control2]))}; + if (length < kTiltedShortest || before < 1e-3 || after < 1e-3) + return false; + return std::abs((points[segment_data::point::control1].y / before - points[segment_data::point::control2].y / after) * 0.5 - rise / length) > kTilted; + }; + if (track->eType == tt_Switch ? timbered_tracks.contains(track) : tilted()) + { + auto const grade{rise / std::max(1e-9, glm::dot(span, span))}; + points[segment_data::point::control1].y = grade * glm::dot(geometry::plan_of(points[segment_data::point::control1]), span); + points[segment_data::point::control2].y = grade * glm::dot(geometry::plan_of(points[segment_data::point::control2]), span); + straightened += track->eType == tt_Switch ? 0 : 1; + } + }; + for (auto &path : track->m_paths) + move_path_heights(path, move_of(path.points[segment_data::point::start]), move_of(path.points[segment_data::point::end]), settle); + } + // a switch lies straight, but a change of grade that needs a curve isn't left bare at its joints: it goes on a vertical curve over the + // whole of the switch, the ends of the paths taking the grades of the tracks going on from them and staying where they are + double constexpr kBare{0.002}; // the change of grade which needs a vertical curve + double constexpr kCrest{2000.0}; // m, the sharpest convex curve a switch may lie on + std::vector> leaving_at(nodes); + for (auto const *track : tracks) + for (auto const &path : track->m_paths) + { + leaving_at[indices.at(key_of(path.points[segment_data::point::start]))].push_back(leaving_of(track, path, false)); + leaving_at[indices.at(key_of(path.points[segment_data::point::end]))].push_back(leaving_of(track, path, true)); + } + // the grade the end of a path of a switch is to rise out of the joint with, two switches meeting sharing the difference, and how much + // the grade breaks there now + struct onward + { + double grade; + double broken; + }; + auto const going_on = [&](TTrack const *Track, segment_data const &Path, bool const Atend) -> std::optional { + auto const own{leaving_of(Track, Path, Atend)}; + leaving const *best{nullptr}; + for (auto const &other : leaving_at[indices.at(key_of(Path.points[Atend ? segment_data::point::end : segment_data::point::start]))]) + if (other.track != Track && glm::dot(own.way, other.way) < -0.9 && (best == nullptr || glm::dot(own.way, other.way) < glm::dot(own.way, best->way))) + best = &other; + if (best == nullptr) + return std::nullopt; + return onward{best->track->eType == tt_Switch && false == state.stayed.contains(best->track) ? (own.grade - best->grade) * 0.5 : -best->grade, std::abs(own.grade + best->grade)}; + }; + std::size_t curved{0}; + for (auto *track : tracks) + { + if (track->eType != tt_Switch || state.stayed.contains(track) || track->m_paths.empty()) + continue; + auto const before{going_on(track, track->m_paths.front(), false)}; + auto bare{before && before->broken > kBare}; + std::vector> after; + for (auto const &path : track->m_paths) + { + after.push_back(going_on(track, path, true)); + bare = bare || (after.back() && after.back()->broken > kBare); + } + if (false == bare) + continue; + edit.capture(*track); + if (std::find(moved.begin(), moved.end(), track) == moved.end()) + moved.push_back(track); + ++curved; + std::optional blades; // the paths leave the blades with one grade, the first path tells it + for (std::size_t i = 0; i < track->m_paths.size(); ++i) + { + auto &path{track->m_paths[i]}; + auto const length{glm::length(geometry::plan_of(path.points[segment_data::point::end] - path.points[segment_data::point::start]))}; + if (length < 1e-3) + continue; + auto const chord{(path.points[segment_data::point::end].y - path.points[segment_data::point::start].y) / length}; + // the grades along the path; an end with no track going on from it makes the curve even + auto first{before ? before->grade : after[i] ? 2.0 * chord + after[i]->grade : chord}; + auto last{after[i] ? -after[i]->grade : before ? 2.0 * chord - before->grade : chord}; + auto const least_bare = [&](double const Grade) { return Grade + std::clamp(chord - Grade, -kBare, kBare); }; + if (blades) + { + // from the grade at the blades one bend reaches only so far by the far end + first = *blades; + auto const a{-2.0 * (first - chord)}; + auto const b{-0.5 * (first - chord)}; + auto const bent{chord + std::clamp(last - chord, std::min(a, b), std::max(a, b))}; + last = std::abs(bent - last) <= kBare ? bent : least_bare(last); + } + else + { + auto const bend_first{(6.0 * chord - 4.0 * first - 2.0 * last) / length}; + auto const bend_last{(-6.0 * chord + 2.0 * first + 4.0 * last) / length}; + // the ends can't be met by one bend: only what a curve is needed for is taken off them, the rest stays at the joints + if (bend_first * bend_last < 0.0 || std::min(bend_first, bend_last) < -1.0 / kCrest) + { + first = least_bare(first); + last = least_bare(last); + } + blades = first; + } + on_vertical_curve(path, first, last); + } + } + WriteLog(format("Editor: NMT - one grade line for tracks under %.1f m apart: %zu runs of tracks on their own, %zu places side by side, %zu on common timbers in %zu groups, %d joints, %d iterations, %zu tracks moved, by %.2f m at most (%s), %zu paths straightened, %zu switches on a vertical curve", kApart, apart.size(), pairs, on_timbers, sums.size(), nodes, iterations, moved.size(), largest, largest_at != nullptr ? largest_at->name().c_str() : "-", straightened, curved), logtype::generic); + if (moved.empty()) + return; + profile_library_load(); + auto library{m_profiles}; + editor_track::commit(moved); + push_track_snapshot(std::move(edit.states), {}); + fitted_set(moved); + // the designs of the lines fitted one by one go with the tracks they moved + auto const [refitted, failed]{profile_refit_stored({moved.begin(), moved.end()})}; + if (refitted > 0) + profiles_to_history(std::move(library)); + WriteLog(format("Editor: NMT - %zu designs laid anew onto the tracks moved, %zu left as they were", refitted, failed), logtype::generic); +} + +void editor_mode::nmt_auto_step() +{ + auto &state{m_nmt_state}; + if (state.stage == nmt_state::automatic::fetching) + { + bool all{true}; + for (auto const &place : state.probes) + all = nmt_ready(glm::dvec2{place.position.x, place.position.z} - glm::dvec2{1.0}, glm::dvec2{place.position.x, place.position.z} + glm::dvec2{1.0}) && all; + auto const waiting{m_nmt.waiting()}; + state.status = format(STR_P("Fetching the terrain model under the tracks: %zu square left", "Fetching the terrain model under the tracks: %zu squares left", waiting), waiting); + if (false == all) + return; + // the scenery stays at its own heights, the terrain model meets it: offset by how far the tracks lie from it, so the lines + // fitted one after another meet at heights near their own; the grade lines then follow the model so offset + // the places of the tracks fitted already, the last ones, apart + std::vector differences, kept; + auto const first_kept{state.probes.size() - std::min(state.probes_kept, state.probes.size())}; + for (std::size_t i = 0; i < state.probes.size(); ++i) + if (double height; m_nmt.height(state.probes[i].position.x, state.probes[i].position.z, height)) + (i < first_kept ? differences : kept).push_back(height - state.probes[i].crown); + if (differences.empty()) + { + state.stage = nmt_state::automatic::idle; + state.status = STR("The terrain model has no data under the tracks: is the scenery placed where it is?"); + return; + } + std::nth_element(differences.begin(), differences.begin() + differences.size() / 2, differences.end()); + auto const lift{differences[differences.size() / 2]}; + if (state.unfitted && false == kept.empty()) + { + // the tracks fitted already stay where they are, and the model keeps the offset they were fitted to, told by them + std::nth_element(kept.begin(), kept.begin() + kept.size() / 2, kept.end()); + auto const offset{-kept[kept.size() / 2]}; + if (std::abs(offset - state.offset) > 0.05) + state.offset = offset; + WriteLog(format("Editor: NMT - the tracks fitted already lie on the terrain model offset %+.2f m, kept; the ones not fitted yet lie %+.2f m against it", state.offset, -lift - state.offset), logtype::generic); + } + else + { + // the offset of the run before kept where the tracks fitted to it lie within 5 cm of it: they don't creep a centimetre a run + auto const offset{std::abs(lift) > 0.05 ? -lift : 0.0}; + if (std::abs(offset - state.offset) > 0.05) + state.offset = offset; + WriteLog(format("Editor: NMT - the terrain model offset %+.2f m to the scenery", state.offset), logtype::generic); + } + state.fitted = true; + nmt_join_ends(); + state.levelled = nmt_level_turntables(); + // the longest tracks first: the main lines lead, the sidings join them + state.left.clear(); + for (auto *track : simulation::Paths.sequence()) + if (track != nullptr && rail(*track) && track->eType != tt_Table && false == nmt_stays(*track)) + state.left.push_back(track); + std::sort(state.left.begin(), state.left.end(), [](TTrack *Left, TTrack *Right) { return Left->Length() > Right->Length(); }); + state.tracks = state.left.size(); + state.split = 0; + state.done.clear(); + // the tracks fitted before are lines fitted already: the new ones run up to them and meet them as they are + state.stayed.clear(); + for (auto *track : simulation::Paths.sequence()) + if (track != nullptr && rail(*track) && nmt_stays(*track)) + { + state.done.push_back(track); + state.stayed.insert(track); + } + state.laid.clear(); + state.bridged.clear(); + state.on_hump.clear(); + // every path sampled as laid, for the crossings of the lines + state.paths.clear(); + for (auto *track : simulation::Paths.sequence()) + if (track != nullptr && rail(*track)) + nmt_sample_paths(*track, state.paths); + state.stage = nmt_state::automatic::fitting; + return; + } + // a few lines a frame: the longest track next to the lines fitted already, so that a line meets the ones it leads into as + // it's fitted, not when the lines between them come; the longest of all where none is next to them + for (int line = 0; line < 2 && false == state.left.empty(); ++line) + { + std::unordered_set const fitted(state.done.begin(), state.done.end()); + auto const touches = [&](TTrack *Track) { + for (int path = 0; path < static_cast(Track->m_paths.size()); ++path) + for (auto const forward : {true, false}) + { + auto const onward{editor_track::continuations({Track, path, forward})}; + if (std::any_of(onward.begin(), onward.end(), [&](editor_track::continuation const &Next) { return fitted.contains(Next.span.track); })) + return true; + if (auto const loose{state.loose.find({Track, path, forward})}; loose != state.loose.end() && fitted.contains(std::get<0>(loose->second))) + return true; + } + return false; + }; + auto const next{std::find_if(state.left.begin(), state.left.end(), touches)}; + if (next != state.left.end()) + std::rotate(state.left.begin(), next, next + 1); + auto *track{state.left.front()}; + auto const name{track->name()}; + auto const known{simulation::Paths.sequence().size()}; + if (nmt_fit_line(*track, [&](TTrack const *Other) { return fitted.contains(Other); }, false)) + ++state.lines; + else + ++state.refused; + // the tracks of the line are done, whether it went or not; so is every path made meanwhile, split off by the grade line or + // by the lines following it over the crossovers: the next line over them would lay them again, and split them again + std::set done{track}; + state.done.push_back(track); + for (auto const &span : m_profile.route.spans) + if (done.insert(span.track).second) + state.done.push_back(span.track); + auto const &sequence{simulation::Paths.sequence()}; + std::string made; + for (auto i{known}; i < sequence.size(); ++i) + if (auto *piece{sequence[i]}; piece != nullptr && done.insert(piece).second) + { + state.done.push_back(piece); + if (made.size() < 300) + made += ' ' + piece->name(); + } + auto const added{sequence.size() - known}; + state.split += added; + if (added > 20) + WriteLog(format("Editor: NMT line %s made %zu paths:%s", name.c_str(), added, made.c_str()), logtype::generic); + if (state.split > state.tracks / 2 + 200) + { + // something lays the same tracks over and over: stopped before it takes all the memory + state.left.clear(); + state.error = format(STR_P("Stopped: the grade lines split off %zu path from %zu tracks, more than they should; Ctrl+Z takes the changes back", "Stopped: the grade lines split off %zu paths from %zu tracks, more than they should; Ctrl+Z takes the changes back", state.split), state.split, state.tracks); + WriteLog("Editor: NMT - " + state.error, logtype::generic); + break; + } + state.left.erase(std::remove_if(state.left.begin(), state.left.end(), [&](TTrack *Track) { return done.contains(Track); }), state.left.end()); + } + state.status = format(STR_C("Terrain model offset %+.2f m to the scenery; grade lines fitted to the terrain: %zu, refused by the checks: %zu, tracks left: %zu"), state.offset, state.lines, state.refused, state.left.size()); + if (state.departures > 0) + state.status += format(STR_P("\n%zu line parts from the terrain model by over 0.5 m: the model or the track is off there, the terrain follows the tracks (the log names it)", "\n%zu lines part from the terrain model by over 0.5 m: the model or the track is off there, the terrain follows the tracks (the log names them)", state.departures), state.departures); + if (state.levelled > 0) + state.status += format(STR_P("\n%zu turntable set level at the height of the tracks running up to it, which reach it level", "\n%zu turntables set level at the height of the tracks running up to them, which reach them level", state.levelled), state.levelled); + if (false == state.left.empty()) + return; + state.result = true; + // the last line fitted isn't left in the profile, its tracks may be gone: the profile opens on what's selected + m_profile.open = false; + m_profile.route = {}; + m_profile.samples.clear(); + m_profile.followed.clear(); + nmt_share_grades(); + state.done.clear(); + state.laid.clear(); + state.paths.clear(); + state.loose.clear(); + state.turntables.clear(); + state.stage = nmt_state::automatic::idle; + WriteLog("Editor: NMT - " + state.status, logtype::generic); + nmt_make(nmt_keys_along_tracks(), true); +} diff --git a/application/editormodeparallel.cpp b/application/editormodeparallel.cpp index 24090fd0e..28861b93f 100644 --- a/application/editormodeparallel.cpp +++ b/application/editormodeparallel.cpp @@ -8,9 +8,9 @@ http://mozilla.org/MPL/2.0/. */ #include "stdafx.h" -#include "application/editormode.h" -#include "application/editoruilayer.h" +#include "application/editormodeparallel.h" #include "application/editorprojection.h" +#include "application/editormodeshared.h" #include "editor/editorFormat.hpp" #include "editor/editorGeometry.hpp" @@ -23,6 +23,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/translation.h" #include #include +#include namespace { @@ -30,13 +31,103 @@ namespace using geometry::bezier; using geometry::cross; using geometry::plan_of; +using geometry::signed_angle; double const kParallelReach{5000.0}; // m each way along the line double const kSpacings[] = {3.5, 4.0, 4.5, 4.75, 5.0, 6.0}; -std::string name_of(TTrack const &Track) +// the side of the new track as a picture: three rows, the new track on the left of the line, the line with its direction, +// the new track on the right; the side chosen drawn with the spacing marked, the other faint. a click on a row chooses its side +bool side_picker(int &Side, double const Spacing) { - return Track.name().empty() ? std::string{"(noname)"} : Track.name(); + auto const font{ImGui::GetFontSize()}; + auto const width{ImGui::GetContentRegionAvail().x}; + auto const row{std::round(font * 1.7f)}; + auto const height{row * 3.0f}; + auto const top{ImGui::GetCursorScreenPos()}; + ImGui::InvisibleButton("##side", ImVec2(width, height)); + auto const hovered{ImGui::IsItemHovered()}; + auto const mouse{ImGui::GetIO().MousePos}; + auto const middle{std::round(top.y + row * 1.5f)}; + auto const pointed{hovered ? (mouse.y < top.y + row ? -1 : mouse.y >= top.y + row * 2.0f ? 1 : 0) : 0}; + bool changed{false}; + if (ImGui::IsItemClicked() && pointed != 0 && pointed != Side) + { + Side = pointed; + changed = true; + } + auto *list{ImGui::GetWindowDrawList()}; + ImVec2 const bottom{top.x + width, top.y + height}; + auto const rounding{std::round(font * 0.35f)}; + list->AddRectFilled(top, bottom, ImGui::GetColorU32(ImGuiCol_FrameBg), rounding); + if (pointed != 0 && pointed != Side) + list->AddRectFilled(ImVec2(top.x, pointed < 0 ? top.y : top.y + row * 2.0f), ImVec2(bottom.x, pointed < 0 ? top.y + row : bottom.y), ImGui::GetColorU32(ImGuiCol_FrameBgHovered), rounding); + auto const pad{std::round(font * 0.6f)}; + char const *const labels[]{STR_C("Left"), STR_C("selected"), STR_C("Right")}; + float column{0.0f}; + for (auto const *label : labels) + column = std::max(column, ImGui::CalcTextSize(label).x); + auto const left{top.x + pad + column + pad}; + auto const right{bottom.x - pad * 2.0f}; + auto const gauge{std::round(font * 0.36f)}; + // a track as two rails, sleepers under the solid ones + auto const track = [&](float const Y, ImU32 const Colour, bool const Dashed) { + // the sleepers a whole number of pixels apart, never less than one + auto const sleeper{std::max(1.0f, std::round(font * 0.9f))}; + if (false == Dashed) + for (int k = 0; left + font * 0.3f + sleeper * static_cast(k) < right; ++k) + { + auto const x{left + font * 0.3f + sleeper * static_cast(k)}; + list->AddLine(ImVec2(x, Y - gauge * 0.95f), ImVec2(x, Y + gauge * 0.95f), (Colour & ~IM_COL32_A_MASK) | IM_COL32(0, 0, 0, 90), 2.0f); + } + for (auto const rail : {Y - gauge * 0.5f, Y + gauge * 0.5f}) + { + if (false == Dashed) + { + list->AddLine(ImVec2(left, rail), ImVec2(right, rail), Colour, 1.5f); + continue; + } + for (int k = 0; left + font * static_cast(k) < right; ++k) + { + auto const x{left + font * static_cast(k)}; + list->AddLine(ImVec2(x, rail), ImVec2(std::min(right, x + font * 0.55f), rail), Colour, 1.0f); + } + } + }; + auto const line{ImGui::GetColorU32(ImGuiCol_Text, 0.85f)}; + track(middle, line, false); + auto const arrow{std::round(font * 0.45f)}; + list->AddTriangleFilled(ImVec2(right + pad * 1.2f, middle), ImVec2(right + pad * 0.2f - arrow * 0.4f, middle - arrow), ImVec2(right + pad * 0.2f - arrow * 0.4f, middle + arrow), line); + auto const label_at = [&](int const Row, char const *Label, bool const Lit) { + auto const size{ImGui::CalcTextSize(Label)}; + list->AddText(ImVec2(top.x + pad + column - size.x, std::round(top.y + row * (Row + 0.5f) - size.y * 0.5f)), ImGui::GetColorU32(Lit ? ImGuiCol_Text : ImGuiCol_TextDisabled), Label); + }; + label_at(1, labels[1], false); + auto const accent{family_colour(0)}; + for (auto const side : {-1, 1}) + { + auto const y{middle + side * row}; + auto const chosen{side == Side}; + track(y, chosen ? accent : ImGui::GetColorU32(ImGuiCol_TextDisabled, 0.6f), false == chosen); + label_at(side < 0 ? 0 : 2, labels[side < 0 ? 0 : 2], chosen); + if (false == chosen) + continue; + // the spacing, axis to axis + auto const x{std::round(left + (right - left) * 0.62f)}; + ImU32 const dimension{IM_COL32(255, 210, 60, 255)}; + list->AddLine(ImVec2(x, middle), ImVec2(x, y), dimension, 1.5f); + list->AddTriangleFilled(ImVec2(x, middle), ImVec2(x - 3.0f, middle + side * 6.0f), ImVec2(x + 3.0f, middle + side * 6.0f), dimension); + list->AddTriangleFilled(ImVec2(x, y), ImVec2(x - 3.0f, y - side * 6.0f), ImVec2(x + 3.0f, y - side * 6.0f), dimension); + char text[32]; + std::snprintf(text, sizeof(text), "%.2f m", Spacing); + auto const size{ImGui::CalcTextSize(text)}; + ImVec2 const at{x + 6.0f, std::round((middle + y) * 0.5f - size.y * 0.5f)}; + list->AddRectFilled(ImVec2(at.x - 3.0f, at.y), ImVec2(at.x + size.x + 3.0f, at.y + size.y), ImGui::GetColorU32(ImGuiCol_FrameBg), 3.0f); + list->AddText(at, dimension, text); + } + if (hovered) + ImGui::SetTooltip("%s", pointed != 0 && pointed != Side ? STR_C("A click: the new track on this side") : STR_C("Left and right as seen along the line, the way the arrow points")); + return changed; } segment_data reversed(segment_data const &Path) @@ -76,6 +167,23 @@ double curvature(segment_data const &Path, bool const Atend) return speed > 1e-9 ? cross(first, second) / (speed * speed * speed) : 0.0; } +std::optional arc_curvature(segment_data const &Path) +{ + auto const [control1, control2] = controls(Path); + auto const along{plan_of(control1)}; + auto const back{-plan_of(control2)}; + if (glm::length(along) < 1e-9 || glm::length(back) < 1e-9) + return std::nullopt; + auto const turn{signed_angle(glm::normalize(along), glm::normalize(back))}; + if (std::abs(turn) < 1e-6) + return std::nullopt; + auto const radius{glm::length(plan_of(Path.points[segment_data::point::end] - Path.points[segment_data::point::start])) / (2.0 * std::sin(std::abs(turn) * 0.5))}; + auto const control{4.0 / 3.0 * std::tan(std::abs(turn) * 0.25) * radius}; + if (std::abs(glm::length(along) - control) > 1e-4 * control || std::abs(glm::length(back) - control) > 1e-4 * control) + return std::nullopt; + return std::copysign(1.0 / radius, turn); +} + glm::dvec2 direction(segment_data const &Path, bool const Atend) { auto const [control1, control2] = controls(Path); @@ -103,21 +211,23 @@ double lateral_of(TTrack const &Src, TTrack const &Dst) } // namespace -TTrack *editor_mode::parallel_source() const +TTrack *parallel_tool::parallel_source() const { - if (m_track_set.size() >= 2) - return m_track_set.front(); - return selected_track(); + auto const &set{m_selection.track_set()}; + if (set.size() >= 2) + return set.front(); + return m_selection.selected_track(); } -TTrack *editor_mode::parallel_target() const +TTrack *parallel_tool::parallel_target() const { - if (m_track_set.size() != 2) + auto const &set{m_selection.track_set()}; + if (set.size() != 2) return nullptr; - return m_track_set.back() != m_track_set.front() ? m_track_set.back() : nullptr; + return set.back() != set.front() ? set.back() : nullptr; } -void editor_mode::parallel_update() +void parallel_tool::parallel_update() { auto &tool{m_parallel}; auto *track{parallel_source()}; @@ -138,13 +248,13 @@ void editor_mode::parallel_update() else if (track != nullptr && target != nullptr) tool.measured = std::abs(lateral_of(*track, *target)); - if (track == tool.built_for && tool.spacing == tool.built_spacing && tool.side == tool.built_side && tool.scope == tool.built_scope && m_history.size() == tool.built_history) + if (track == tool.built_for && tool.spacing == tool.built_spacing && tool.side == tool.built_side && tool.scope == tool.built_scope && m_history.history_revision() == tool.built_history) return; tool.built_for = track; tool.built_spacing = tool.spacing; tool.built_side = tool.side; tool.built_scope = tool.scope; - tool.built_history = m_history.size(); + tool.built_history = m_history.history_revision(); tool.pieces.clear(); tool.styles.clear(); tool.length = 0.0; @@ -188,8 +298,9 @@ void editor_mode::parallel_update() { auto const &source{sources[i].second}; auto const [control1, control2] = controls(source); - auto const startscale{1.0 - curvature(source, false) * offset}; - auto const endscale{1.0 - curvature(source, true) * offset}; + auto const arc{arc_curvature(source)}; + auto const startscale{1.0 - (arc.has_value() ? *arc : curvature(source, false)) * offset}; + auto const endscale{1.0 - (arc.has_value() ? *arc : curvature(source, true)) * offset}; if (startscale < 0.05 || endscale < 0.05) { tool.pieces.clear(); @@ -205,14 +316,14 @@ void editor_mode::parallel_update() piece.rolls = source.rolls; auto const middle{0.5 * (curvature(source, false) + curvature(source, true))}; if (source.radius != 0.0f && std::abs(middle) > 1e-7) - piece.radius = static_cast(std::copysign(std::abs((1.0 - middle * offset) / middle), static_cast(source.radius))); + piece.radius = static_cast(std::copysign(std::abs(std::abs(static_cast(source.radius)) - std::copysign(offset, middle)), static_cast(source.radius))); tool.length += bezier{piece}.plan_length(); tool.pieces.push_back(piece); tool.styles.push_back(sources[i].first); } } -void editor_mode::parallel_build() +void parallel_tool::parallel_build() { auto &tool{m_parallel}; parallel_update(); @@ -222,7 +333,8 @@ void editor_mode::parallel_build() for (std::size_t i = 0; i < tool.pieces.size(); ++i) created.push_back(editor_track::create_path(*tool.styles[i], tool.pieces[i])); editor_track::commit(created); - push_track_snapshot({}, created); + m_design.digitize_drawn(created); + m_history.push_track_snapshot({}, created); tool.status = format(STR_C("Parallel track of %zu paths, %.1f m, %.2f m away; Ctrl+Z takes it back"), created.size(), tool.length, tool.spacing); if (scene::Layers.active() == null_handle) tool.status += "\n" + std::string{STR_C("The scenery isn't opened for editing, the new track won't be saved")}; @@ -230,7 +342,7 @@ void editor_mode::parallel_build() tool.built_for = nullptr; } -void editor_mode::parallel_apply() +void parallel_tool::parallel_apply() { auto &tool{m_parallel}; auto *target{parallel_target()}; @@ -267,64 +379,55 @@ void editor_mode::parallel_apply() if (joint.other != nullptr) committed.push_back(joint.other); editor_track::commit(committed); - push_track_snapshot(std::move(states)); + m_history.push_track_snapshot(std::move(states)); tool.status = format(STR_C("%s set parallel to %s, %.2f m away; Ctrl+Z takes it back"), name_of(*target).c_str(), name_of(*parallel_source()).c_str(), tool.spacing); WriteLog("Editor: " + tool.status, logtype::generic); tool.built_for = nullptr; - straight_refresh(); + m_design.straight_refresh(); } -void editor_mode::render_parallel_controls(bool const Scope) +void parallel_tool::render_parallel_controls(bool const Scope) { auto &tool{m_parallel}; if (Scope) - { - ImGui::RadioButton(STR_C("This path"), &tool.scope, 0); - ImGui::SameLine(); - ImGui::RadioButton(STR_C("The line, up to the switches"), &tool.scope, 1); - } - ImGui::RadioButton(STR_C("Left"), &tool.side, -1); - ImGui::SameLine(); - ImGui::RadioButton(STR_C("Right"), &tool.side, 1); - ImGui::SameLine(); - ImGui::TextDisabled("%s", STR_C("(of the direction of the line, see the preview)")); - ImGui::SetNextItemWidth(90.0f); - ImGui::InputDouble(STR_C("Spacing (m)"), &tool.spacing, 0.0, 0.0, "%.2f"); + segmented("scope", tool.scope, {{0, STR_C("This path"), "Only beside the selected path"}, {1, STR_C("The line, up to the switches"), "Beside the whole line of the selected path, up to the switches: its curves go along with R minus or plus the spacing"}}); + side_picker(tool.side, tool.spacing); + ImGui::SetNextItemWidth(std::round(ImGui::GetFontSize() * 6.0f)); + ImGui::InputDouble("##spacing", &tool.spacing, 0.0, 0.0, STR_C("%.2f m")); + item_tooltip("Spacing of the axes of the tracks; the usual ones beside it"); tool.spacing = std::clamp(tool.spacing, 1.5, 100.0); - for (auto const spacing : kSpacings) - { - ImGui::SameLine(); - if (ImGui::SmallButton(format("%.2f", spacing).c_str())) - tool.spacing = spacing; - } + ImGui::SameLine(); + value_chips("spacings", tool.spacing, {kSpacings[0], kSpacings[1], kSpacings[2], kSpacings[3], kSpacings[4], kSpacings[5]}, "%.2f"); } -void editor_mode::render_parallel_ui() +void parallel_tool::render_options() { auto &tool{m_parallel}; - ImGui::TextDisabled("%s", STR_C("First select a straight path (LMB). Then a second track is laid beside it.\nAlong the line the curves are included: R minus or plus the spacing, same transitions and cant.")); + ImGui::PushTextWrapPos(0.0f); if (parallel_target() != nullptr) - ImGui::TextDisabled("%s", STR_C("Two paths selected: set the spacing of the other in Select. The first must be a straight.")); - else if (auto *source{parallel_source()}; source == nullptr) - ImGui::TextColored(ImVec4(1.0f, 0.8f, 0.3f, 1.0f), "%s", STR_C("First select a straight path in the view.")); - else if (source->eType != tt_Normal || false == editor_track::is_straight(*source, m_straights.tolerance)) - ImGui::TextColored(ImVec4(1.0f, 0.8f, 0.3f, 1.0f), "%s", STR_C("The selected path isn't a straight. Select a straight first.")); + ImGui::TextDisabled("%s", STR_C("Two tracks selected: set the spacing of the other in the Select tool")); + else if (parallel_source() == nullptr) + ImGui::TextColored(ImVec4(1.0f, 0.8f, 0.3f, 1.0f), "%s", STR_C("Click a track in the view: the new one goes beside it.")); + ImGui::PopTextWrapPos(); render_parallel_controls(); parallel_update(); if (false == tool.error.empty()) + { + ImGui::PushTextWrapPos(0.0f); ImGui::TextColored(ImVec4(1.0f, 0.5f, 0.3f, 1.0f), "%s", tool.error.c_str()); + ImGui::PopTextWrapPos(); + } else if (false == tool.pieces.empty()) { - if (ImGui::Button(format(STR_C("Lay %zu paths, %.1f m"), tool.pieces.size(), tool.length).c_str())) + if (main_button(format(STR_P("Lay %zu track, %.1f m", "Lay %zu tracks, %.1f m", static_cast(tool.pieces.size())), tool.pieces.size(), tool.length).c_str(), ImVec2(-1.0f, tall_button_height()))) parallel_build(); - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", STR_C("First select a straight. Creates a new track beside it; the selected path stays.")); + item_tooltip("A new track beside the one selected, as in the preview; the selected stays as it is. Ctrl+Z takes it back"); } if (false == tool.status.empty()) ImGui::TextWrapped("%s", tool.status.c_str()); } -void editor_mode::render_parallel_set_ui() +void parallel_tool::render_set_options() { auto &tool{m_parallel}; auto *source{parallel_source()}; @@ -333,8 +436,8 @@ void editor_mode::render_parallel_set_ui() return; if (false == ImGui::CollapsingHeader(STR_C("Make parallel"), ImGuiTreeNodeFlags_DefaultOpen)) return; - ImGui::TextWrapped("%s", STR_C("First selected must be a straight. It stays; the other is moved to this spacing.")); - ImGui::TextWrapped("%s", format(STR_C("%s stays. %s is moved to this spacing, taking its curves."), name_of(*source).c_str(), name_of(*target).c_str()).c_str()); + ImGui::TextWrapped("%s", STR_C("The first selected track must be a straight")); + ImGui::TextWrapped("%s", format(STR_C("%s stays, %s moves to this spacing with its curves"), name_of(*source).c_str(), name_of(*target).c_str()).c_str()); if (tool.measured > 0.05) ImGui::TextDisabled("%s", format(lateral_of(*source, *target) >= 0.0 ? STR_C("Now %.2f m on the right") : STR_C("Now %.2f m on the left"), tool.measured).c_str()); tool.scope = 0; @@ -348,18 +451,16 @@ void editor_mode::render_parallel_set_ui() ImGui::TextWrapped("%s", tool.status.c_str()); } -bool editor_mode::parallel_preview_visible() const +bool parallel_tool::parallel_preview_visible() const { if (m_parallel.pieces.empty() || parallel_source() != m_parallel.built_for) return false; - if (m_track_tab == track_tab::lay) - return m_lay.points.empty(); - if (m_track_tab == track_tab::path) + if (m_view.current_track_tab() == editor_track_tab::parallel) return true; - return m_track_tab == track_tab::lineside && m_parallel.open; + return m_view.current_track_tab() == editor_track_tab::path && parallel_target() != nullptr; } -void editor_mode::draw_parallel_preview() const +void parallel_tool::draw_overlay() const { if (false == parallel_preview_visible()) return; @@ -388,3 +489,17 @@ void editor_mode::draw_parallel_preview() const drawlist->AddText(ImVec2(screen.x + 12.0f, screen.y - 8.0f), IM_COL32(90, 255, 120, 255), label.c_str()); } } + +editor_selftest_result parallel_tool::selftest(std::string const &Command, std::istringstream &Words) +{ + if (Command == "parallel") + { + Words >> m_parallel.spacing >> m_parallel.side; + m_parallel.scope = 1; + m_parallel.built_for = nullptr; + parallel_build(); + WriteLog("SELFTEST parallel: " + m_parallel.status + " " + m_parallel.error); + return editor_selftest_result::handled; + } + return editor_selftest_result::unhandled; +} diff --git a/application/editormodeparallel.h b/application/editormodeparallel.h new file mode 100644 index 000000000..d10ef41b2 --- /dev/null +++ b/application/editormodeparallel.h @@ -0,0 +1,61 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include "application/editortool.h" + +#include +#include + +// second track alongside the selected path or the line through it, at a spacing, curves included +class parallel_tool final : public editor_tool +{ + public: + parallel_tool(editor_selection &Selection, editor_view &View, editor_history &History, editor_track_design &Design) : m_selection{Selection}, m_view{View}, m_history{History}, m_design{Design} {} + void draw_overlay() const override; + void render_options() override; + editor_selftest_result selftest(std::string const &Command, std::istringstream &Words) override; + tool_tab &tab() { return m_tab; } + void render_set_options(); + + private: + editor_selection &m_selection; + editor_view &m_view; + editor_history &m_history; + editor_track_design &m_design; + tool_tab m_tab; + struct parallel_state + { + double spacing{4.0}; + int side{1}; // 1: to the right, -1: to the left, of the direction of the line + int scope{1}; // 0: the selected path, 1: the line through it, up to the switches + TTrack *built_for{nullptr}; + double built_spacing{0.0}; + int built_side{0}; + int built_scope{-1}; + std::size_t built_history{0}; + TTrack *pair_src{nullptr}; + TTrack *pair_dst{nullptr}; + double measured{0.0}; + std::vector pieces; + std::vector styles; + double length{0.0}; + std::string error; + std::string status; + }; + parallel_state m_parallel; + TTrack *parallel_source() const; + TTrack *parallel_target() const; + void parallel_update(); + void render_parallel_controls(bool const Scope = true); + void parallel_build(); + void parallel_apply(); + bool parallel_preview_visible() const; +}; diff --git a/application/editormodeprofile.cpp b/application/editormodeprofile.cpp index 4fafe1d3c..2b7956f97 100644 --- a/application/editormodeprofile.cpp +++ b/application/editormodeprofile.cpp @@ -10,12 +10,20 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "application/editormode.h" #include "application/editorprojection.h" +#include "application/editorgestures.h" +#include "application/editormodeshared.h" +#include "application/editoruilayer.h" #include "editor/editorFormat.hpp" +#include "editor/editorAlignmentStore.hpp" #include "editor/editorGeometry.hpp" +#include "editor/editorSwitchStore.hpp" #include "world/Track.h" #include "scene/scenelayers.h" #include "simulation/simulation.h" +#include "utilities/Globals.h" +#include "utilities/glmHelpers.h" +#include "world/TrackSleepers.h" #include "utilities/Logs.h" #include "utilities/translation.h" @@ -38,6 +46,15 @@ ImU32 const kGradeLine{IM_COL32(90, 230, 110, 255)}; ImU32 const kTangents{IM_COL32(255, 210, 60, 130)}; ImU32 const kTrack{IM_COL32(190, 190, 190, 255)}; ImU32 const kTerrain{IM_COL32(170, 120, 70, 255)}; +ImU32 const kFormation{IM_COL32(215, 185, 140, 200)}; +ImU32 const kModel{IM_COL32(70, 200, 190, 230)}; // the ground of the terrain model, as measured +double constexpr kNoBed{0.05}; // m, a trackbed shallower is none +// a design the track lay on when it was kept, within kApplied, was applied; where the track parts from it by more than kStale since, +// it was changed by other tools, and the line is read from the track there, over the stretch and kStaleMargin around it +double constexpr kApplied{0.01}; +double constexpr kStale{0.02}; +double constexpr kStaleMargin{15.0}; +double constexpr kDesignOff{0.25}; // m, of a line put together or read that says little of the track ImU32 const kGrid{IM_COL32(255, 255, 255, 22)}; ImU32 const kLabel{IM_COL32(200, 200, 200, 200)}; ImU32 const kSwitch{IM_COL32(160, 100, 220, 45)}; @@ -45,6 +62,8 @@ ImU32 const kError{IM_COL32(255, 80, 70, 255)}; ImU32 const kWarning{IM_COL32(255, 200, 60, 255)}; ImU32 const kPlan{IM_COL32(120, 190, 255, 255)}; ImU32 const kSwitchLabel{IM_COL32(200, 160, 255, 220)}; +ImU32 const kShared{IM_COL32(160, 100, 220, 110)}; // hatching, the colour of the switches +ImU32 const kSharedEdge{IM_COL32(200, 160, 255, 220)}; ImU32 const kChip{IM_COL32(14, 15, 19, 210)}; // text on a dark plate, readable over the lines of the plot @@ -64,15 +83,8 @@ double nice_step(double const Approximate) return power * 10.0; } -double route_speed(editor_track::route const &Route) -{ - double speed{-1.0}; - for (auto const &span : Route.spans) - speed = std::max(speed, editor_track::velocity(*span.track)); - return speed > 0.0 ? speed : 100.0; -} - std::string const kProfileMark{"//$p"}; +std::string const kFittedMark{"//$t"}; profile::line reversed_line(profile::line Line, double const Length) { @@ -92,11 +104,54 @@ bool end_locked(profile::line const &Line, profile::context const &Context, int return false; } +// an error of the line where the edit changes nothing holds nothing up: a long route read from the track has some, fitted to the terrain +// model at last, and a change elsewhere on it doesn't make them worse +bool errors_in_change(std::vector const &Issues, profile::line const &Line, profile::line const &Read, std::vector const &Samples) +{ + double constexpr kAround{60.0}; // m on both sides of the error + for (auto const &issue : Issues) + { + if (false == issue.error) + continue; + if (Samples.empty()) + return true; + for (auto const &sample : Samples) + if (std::abs(sample.chainage - issue.chainage) <= kAround && std::abs(profile::elevation(Line, sample.chainage) - profile::elevation(Read, sample.chainage)) > kStale) + { + WriteLog(format("Editor: vertical profile - held up at %.1f m, the line changed by %.3f m there: %s", sample.chainage, profile::elevation(Line, sample.chainage) - profile::elevation(Read, sample.chainage), issue.text.c_str()), logtype::generic); + return true; + } + } + return false; +} + bool has_errors(std::vector const &Issues) { return std::any_of(Issues.begin(), Issues.end(), [](profile::issue const &Issue) { return Issue.error; }); } +// the chainage of the point on the route sampled, projected onto the stretch between the samples; false off the route +bool sampled_chainage(std::vector const &Samples, glm::dvec3 const &Point, double &Chainage) +{ + double best{0.3}; + bool found{false}; + for (std::size_t i = 0; i + 1 < Samples.size(); ++i) + { + glm::dvec2 const a{Samples[i].position.x, Samples[i].position.z}; + glm::dvec2 const b{Samples[i + 1].position.x, Samples[i + 1].position.z}; + glm::dvec2 const p{Point.x, Point.z}; + auto const run{b - a}; + auto const t{std::clamp(glm::dot(p - a, run) / std::max(1e-12, glm::dot(run, run)), 0.0, 1.0)}; + if (auto const distance{glm::length(p - (a + run * t))}; distance < best) + { + best = distance; + Chainage = Samples[i].chainage + (Samples[i + 1].chainage - Samples[i].chainage) * t; + found = true; + } + } + return found; +} + } // format of the lines, coordinates in the space of the file: @@ -125,7 +180,9 @@ void editor_mode::profile_library_load() { stored_profile entry; entry.layer = layer; - glm::dvec3 start, end, middle; + glm::dvec3 start; + glm::dvec3 end; + glm::dvec3 middle; line >> entry.length >> start.x >> start.y >> start.z >> end.x >> end.y >> end.z >> middle.x >> middle.y >> middle.z; if (line.fail()) { @@ -144,7 +201,8 @@ void editor_mode::profile_library_load() std::string word; if (keyword == "speed") { - int start{1}, end{1}; + int start{1}; + int end{1}; line >> entry.line.speed >> word >> entry.origin >> word >> start >> end; entry.line.join_start = (start != 0); entry.line.join_end = (end != 0); @@ -154,6 +212,8 @@ void editor_mode::profile_library_load() auto &norms{entry.line.norms}; line >> norms.grade_max >> norms.grade_switch_max >> norms.radius_factor >> norms.radius_min >> norms.curve_threshold >> norms.element_min >> norms.fixed_tolerance; } + else if (keyword == "departure") + line >> entry.departure; else if (keyword == "point") { profile::pvi point; @@ -201,6 +261,8 @@ void editor_mode::profile_library_mark(std::vector Layers) lines.push_back(format("speed %.1f origin %.4f join %d %d", entry.line.speed, entry.origin, entry.line.join_start ? 1 : 0, entry.line.join_end ? 1 : 0)); auto const &norms{entry.line.norms}; lines.push_back(format("norms %.4f %.4f %.4f %.1f %.4f %.2f %.4f", norms.grade_max, norms.grade_switch_max, norms.radius_factor, norms.radius_min, norms.curve_threshold, norms.element_min, norms.fixed_tolerance)); + if (entry.departure >= 0.0) + lines.push_back(format("departure %.4f", entry.departure)); for (auto const &point : entry.line.points) lines.push_back(format("point %.4f %.4f %.1f %d", point.chainage, context.to_local({0.0, point.elevation, 0.0}).y, point.radius, point.automatic ? 1 : 0)); lines.emplace_back("end"); @@ -209,6 +271,123 @@ void editor_mode::profile_library_mark(std::vector Layers) } } +void editor_mode::profiles_to_history(std::vector Library) +{ + if (m_history.empty() || m_history.back().action != EditorSnapshot::Action::TrackEdit || m_history.back().profiles) + return; + m_history.back().profiles = true; + m_history.back().profile_library = std::move(Library); +} + +void editor_mode::profiles_restore(std::vector Library) +{ + std::vector layers; + for (auto const *library : {&std::as_const(m_profiles), &std::as_const(Library)}) + for (auto const &entry : *library) + layers.push_back(entry.layer); + m_profiles = std::move(Library); + profile_library_mark(std::move(layers)); +} + +std::uint64_t editor_mode::fitted_shape(TTrack const &Track) +{ + // the points of the paths to a centimetre: what's read back from the files is the same shape + std::uint64_t hash{1469598103934665603ull}; + auto const add = [&](std::int64_t const Value) { + for (int i = 0; i < 8; ++i) + hash = (hash ^ static_cast((Value >> (8 * i)) & 0xff)) * 1099511628211ull; + }; + for (auto const &path : Track.m_paths) + for (auto const &point : path.points) + for (int axis = 0; axis < 3; ++axis) + // through the precision of the files first: what's read back from one has the shape it had when it was written + add(std::llround(std::round(point[axis] * 10000.0) / 100.0)); + return hash; +} + +void editor_mode::fitted_load() +{ + if (m_fitted_loaded) + return; + m_fitted_loaded = true; + m_fitted.clear(); + for (auto const layer : scene::Layers.marked_layers(kFittedMark)) + for (auto const &text : scene::Layers.marked(layer, kFittedMark)) + { + std::istringstream line{text}; + std::string keyword, name, shape, kind; + line >> keyword >> name >> shape; + if (keyword == "fitted" && false == line.fail()) + { + line >> kind; + auto const value{std::strtoull(shape.c_str(), nullptr, 16)}; + m_fitted[{name, value}] = {layer, value, kind == "hand"}; + } + } +} + +void editor_mode::fitted_set(std::vector const &Tracks, bool const Hand) +{ + fitted_load(); + std::vector layers; + for (auto const *track : Tracks) + { + if (track == nullptr || track->m_editorremoved || track->name().empty()) + continue; + scene::layer_handle layer{null_handle}; + if (false == scene::Layers.empty()) + { + layer = scene::Layers.resolve(track->layer()); + if (false == scene::Layers.valid(layer) || false == scene::Layers.accepts(layer)) + layer = scene::Layers.active(); + } + // a mark of the name in another layer leaves it when it's written again + for (auto found{m_fitted.lower_bound({track->name(), 0})}; found != m_fitted.end() && found->first.first == track->name(); ++found) + if (found->second.layer != layer) + layers.push_back(found->second.layer); + auto const shape{fitted_shape(*track)}; + m_fitted[{track->name(), shape}] = {layer, shape, Hand}; + layers.push_back(layer); + } + if (scene::Layers.empty()) + return; + std::sort(layers.begin(), layers.end()); + layers.erase(std::unique(layers.begin(), layers.end()), layers.end()); + // the marks of the tracks there are no more, or changed since, aren't written again + std::set> standing; + for (auto const *track : simulation::Paths.sequence()) + if (track != nullptr && false == track->m_editorremoved && false == track->name().empty()) + standing.emplace(track->name(), fitted_shape(*track)); + for (auto const layer : layers) + { + if (false == scene::Layers.valid(layer)) + continue; + std::vector lines; + for (auto const &[key, mark] : m_fitted) + { + if (mark.layer != layer || false == standing.contains(key)) + continue; + if (lines.empty()) + lines.emplace_back("# the tracks whose grade line was fitted in the track editor, with their shape then; the simulation skips these lines"); + lines.push_back(format("fitted %s %016llx%s", key.first.c_str(), static_cast(mark.shape), mark.hand ? " hand" : "")); + } + scene::Layers.mark(layer, kFittedMark, std::move(lines)); + } +} + +bool editor_mode::grade_hand(TTrack const &Track) +{ + fitted_load(); + auto const found{m_fitted.find({Track.name(), fitted_shape(Track)})}; + return found != m_fitted.end() && found->second.hand; +} + +bool editor_mode::grade_fitted(TTrack const &Track) +{ + fitted_load(); + return m_fitted.contains({Track.name(), fitted_shape(Track)}); +} + int editor_mode::profile_find(bool &Reversed) const { auto const &state{m_profile}; @@ -241,14 +420,214 @@ bool editor_mode::profile_restore() bool reversed; auto const index{profile_find(reversed)}; if (index < 0) - return false; + return profile_restore_parts(); auto const &entry{m_profiles[index]}; state.line = reversed ? reversed_line(entry.line, entry.length) : entry.line; state.origin = entry.origin; state.selected = -1; state.changed = false; profile_check(); - state.status = STR_C("Design read from the scenery file ") + scene::Layers.layer(entry.layer).name + format(STR_C(", largest departure from the track %.3f m"), state.departure); + if (entry.departure >= 0.0 && entry.departure <= kApplied && state.departure > kStale) + return profile_restore_parts(); + state.status = format(STR_C("Design read from the scenery file %s, largest departure from the track %.3f m"), scene::Layers.layer(entry.layer).name.c_str(), state.departure); + return true; +} + +// the designs kept for routes lying along this one, as the lines the tracks were fitted with one by one: their points carried +// over to the chainage of this route, straight between them where none lies, as over a switch none of them runs through +bool editor_mode::profile_restore_parts() +{ + auto &state{m_profile}; + auto const &samples{state.samples}; + if (samples.size() < 2) + return false; + auto const locate = [&](glm::dvec3 const &Point, double &Chainage) { return sampled_chainage(samples, Point, Chainage); }; + auto const length{state.route.length}; + // the direction of the route at the chainage, in the plan + auto const heading = [&](double const Chainage) { + auto const a{editor_track::sampled_position(samples, std::max(0.0, Chainage - 1.0))}; + auto const b{editor_track::sampled_position(samples, std::min(length, Chainage + 1.0))}; + return glm::dvec2{b.x - a.x, b.z - a.z}; + }; + std::vector points; + std::size_t parts{0}; + std::size_t retaken{0}; + // the ends of this route inside a kept design take their heights from it + std::optional start, end; + // the newer designs first: where two lie over the same stretch, the one kept later is the one meant + std::vector> covered; + auto const taken = [&](double const Chainage) { return std::any_of(covered.begin(), covered.end(), [&](auto const &Stretch) { return Chainage > Stretch.first + 0.25 && Chainage < Stretch.second - 0.25; }); }; + for (auto entries{m_profiles.rbegin()}; entries != m_profiles.rend(); ++entries) + { + auto const &entry{*entries}; + // the design laid over this route at least in part: one of its ends on it, the route running on towards the other + double a{0.0}, b{0.0}; + auto const first{locate(entry.start, a)}; + auto const last{locate(entry.end, b)}; + if (false == first && false == last) + continue; + double origin, direction; + double scale{1.0}; + if (first && last) + { + // the route between the ends of the design got longer or shorter, as when a track of it was moved: the points go along + scale = std::abs(b - a) / std::max(1.0, entry.length); + if (scale < 0.8 || scale > 1.25) + continue; + direction = b >= a ? 1.0 : -1.0; + origin = a; + } + else + { + auto const anchor{first ? a : b}; + auto const towards{first ? entry.end - entry.start : entry.start - entry.end}; + auto const along{glm::dot(heading(anchor), glm::dvec2{towards.x, towards.z})}; + if (std::abs(along) < 1e-9) + continue; + // the chainage of the design grows along the route or against it + direction = (along > 0.0) == first ? 1.0 : -1.0; + origin = first ? a : b - direction * entry.length; + } + auto const local = [&](double const Chainage) { return (Chainage - origin) * direction / scale; }; + // the stretch of this route over the paths of the design, from where it meets it: off it, as past the switch where this + // route turns away, the design says nothing + auto const extent_low{std::min(origin, origin + direction * entry.length * scale)}; + auto const extent_high{std::max(origin, origin + direction * entry.length * scale)}; + auto low{extent_low}; + auto high{extent_high}; + if (auto const own{profile_stored_route(entry)}) + { + std::set> paths; + for (auto const &span : own->spans) + paths.emplace(span.track, span.path); + auto const &spans{state.route.spans}; + auto const on = [&](std::size_t const Index) { return paths.count({spans[Index].track, spans[Index].path}) > 0; }; + auto const anchor{first ? a : b}; + std::optional at; + for (std::size_t i = 0; i < spans.size(); ++i) + if (on(i) && anchor >= spans[i].from - 0.3 && anchor <= spans[i].to + 0.3) + { + at = i; + break; + } + if (false == at.has_value()) + continue; + auto left{*at}; + auto right{*at}; + while (left > 0 && on(left - 1)) + --left; + while (right + 1 < spans.size() && on(right + 1)) + ++right; + low = std::max(low, spans[left].from); + high = std::min(high, spans[right].to); + } + auto const inside = [&](double const Chainage) { return Chainage > 0.25 && Chainage < length - 0.25 && Chainage >= low - 0.25 && Chainage <= high + 0.25; }; + // where the track was changed since the design was applied to it, by the gizmo or by dragging its points, the track holds: + // the design gives way there to the line read from the track + std::vector> stale; + if (entry.departure >= 0.0 && entry.departure <= kApplied) + { + for (auto const &sample : samples) + { + if (sample.chainage < low - 0.25 || sample.chainage > high + 0.25) + continue; + auto const designed{profile::elevation(entry.line, std::clamp(local(sample.chainage), 0.0, entry.length))}; + if (std::abs(designed - sample.position.y) <= kStale) + continue; + if (false == stale.empty() && sample.chainage - stale.back().second <= kStaleMargin) + stale.back().second = sample.chainage; + else + stale.emplace_back(sample.chainage, sample.chainage); + } + for (auto &stretch : stale) + { + stretch.first = std::max(low, stretch.first - kStaleMargin); + stretch.second = std::min(high, stretch.second + kStaleMargin); + } + } + auto const changed = [&](double const Chainage) { return std::any_of(stale.begin(), stale.end(), [&](auto const &Stretch) { return Chainage >= Stretch.first - 0.25 && Chainage <= Stretch.second + 0.25; }); }; + for (auto point : entry.line.points) + { + point.chainage = origin + direction * point.chainage * scale; + point.joint = false; + if (inside(point.chainage) && false == taken(point.chainage) && false == changed(point.chainage)) + points.push_back(point); + } + for (auto const &stretch : stale) + { + std::vector chainages, elevations, grades; + for (auto const &sample : samples) + if (sample.chainage >= stretch.first - 1e-6 && sample.chainage <= stretch.second + 1e-6) + { + chainages.push_back(sample.chainage); + elevations.push_back(sample.position.y); + grades.push_back(sample.grade); + } + if (chainages.size() < 2) + continue; + profile::recognition options; + options.minimum_length = 5.0; + options.detail = kStale; + for (auto point : profile::recognize(chainages, elevations, grades, options).points) + { + point.joint = false; + if (point.chainage >= 0.0 && point.chainage <= length && false == taken(point.chainage)) + points.push_back(point); + } + ++retaken; + } + // where this route turns off the design, its height there: between two designs the line goes straight, over the switches. + // where it runs on past the end of the design, onto track laid since, the break gets the vertical curve of the limits + for (auto const edge : {low, high}) + if (edge > 0.5 && edge < length - 0.5 && false == taken(edge) && false == changed(edge)) + { + profile::pvi point; + point.chainage = edge; + point.elevation = profile::elevation(entry.line, std::clamp(local(edge), 0.0, entry.length)); + point.automatic = std::abs(edge - (edge == low ? extent_low : extent_high)) < 0.5; + points.push_back(point); + } + if (false == start.has_value() && false == changed(0.0) && local(0.0) >= -0.25 && local(0.0) <= entry.length + 0.25) + start = profile::elevation(entry.line, std::clamp(local(0.0), 0.0, entry.length)); + if (false == end.has_value() && false == changed(length) && local(length) >= -0.25 && local(length) <= entry.length + 0.25) + end = profile::elevation(entry.line, std::clamp(local(length), 0.0, entry.length)); + covered.emplace_back(low, high); + ++parts; + } + if (parts == 0) + return false; + std::sort(points.begin(), points.end(), [](auto const &Left, auto const &Right) { return Left.chainage < Right.chainage; }); + std::vector line; + for (auto point : points) + { + point.chainage = std::clamp(point.chainage, 0.0, length); + if (false == line.empty() && point.chainage - line.back().chainage < 0.5) + continue; + line.push_back(point); + } + if (line.empty() || line.front().chainage > 0.5) + line.insert(line.begin(), profile::pvi{0.0, start.value_or(samples.front().position.y)}); + else + line.front().chainage = 0.0; + if (line.back().chainage < length - 0.5) + line.push_back(profile::pvi{length, end.value_or(samples.back().position.y)}); + else + line.back().chainage = length; + line.front().radius = 0.0; + line.back().radius = 0.0; + state.line.points = std::move(line); + state.selected = -1; + state.changed = false; + profile_check(); + // designs that don't come together along the track, its heights changed since by more than they tell: the track is what stands + if (state.departure > kDesignOff) + { + profile_recognize(); + return true; + } + state.status = format(STR_C("Design put together from %zu designs kept for the routes along this one, largest departure from the track %.3f m"), parts, state.departure); + if (retaken > 0) + state.status += format(STR_C("; %zu stretches changed on the track since read from it again"), retaken); return true; } @@ -270,9 +649,28 @@ void editor_mode::profile_store() entry.middle = editor_track::sampled_position(state.samples, state.route.length * 0.5); entry.origin = state.origin; entry.line = state.line; - auto &points{entry.line.points}; - points.erase(std::remove_if(points.begin(), points.end(), [](profile::pvi const &Point) { return Point.joint; }), points.end()); + entry.departure = state.departure; + // the joints are kept as points of their own: read back over a longer route, where the end is no longer joined, the line + // keeps the curve it was laid with + for (auto &point : entry.line.points) + if (point.joint) + { + point.joint = false; + point.automatic = false; + } + // the designs of shorter routes this one runs all along are taken over by it: kept, they'd be put together with it again + std::vector layers; + for (auto i{m_profiles.size()}; i-- > 0;) + { + auto const &old{m_profiles[i]}; + double a{0.0}, b{0.0}; + if (old.length + 0.5 < entry.length && sampled_chainage(state.samples, old.start, a) && sampled_chainage(state.samples, old.end, b) && std::abs(std::abs(b - a) - old.length) <= 1.5) + { + layers.push_back(old.layer); + m_profiles.erase(m_profiles.begin() + static_cast(i)); + } + } bool reversed; auto const index{profile_find(reversed)}; if (index >= 0) @@ -290,7 +688,8 @@ void editor_mode::profile_store() entry.layer = layer; m_profiles.push_back(entry); } - profile_library_mark({entry.layer}); + layers.push_back(entry.layer); + profile_library_mark(layers); state.changed = false; } @@ -305,15 +704,11 @@ void editor_mode::profile_forget() auto const layer{m_profiles[index].layer}; m_profiles.erase(m_profiles.begin() + index); profile_library_mark({layer}); - state.status = STR_C("The design will be removed from ") + scene::Layers.layer(layer).name + STR_C(" on save"); + state.status = format(STR_C("The design will be removed from %s on save"), scene::Layers.layer(layer).name.c_str()); } -void editor_mode::profile_open_stored(std::size_t const Index) +std::optional editor_mode::profile_stored_route(stored_profile const &Entry, TTrack **From, TTrack **To) const { - auto &state{m_profile}; - if (Index >= m_profiles.size()) - return; - auto const entry{m_profiles[Index]}; auto const touching = [](glm::dvec3 const &Point) { std::vector result; for (auto *track : simulation::Paths.sequence()) @@ -330,19 +725,130 @@ void editor_mode::profile_open_stored(std::size_t const Index) } return result; }; - for (auto *from : touching(entry.start)) - for (auto *to : touching(entry.end)) + for (auto *from : touching(Entry.start)) + for (auto *to : touching(Entry.end)) { + // the route of the fewest paths, or where the design was laid along another, the one as long through its middle; the length of + // a route comes with its samples + auto const fits = [&](editor_track::route &Route) { + auto const samples{editor_track::sample_route(Route, 1.0)}; + return false == samples.empty() && std::abs(Route.length - Entry.length) <= 0.5 && plan_distance(samples.front().position, Entry.start) <= 0.1 && plan_distance(editor_track::sampled_position(samples, Route.length * 0.5), Entry.middle) <= 0.5; + }; editor_track::route route; std::string error; - if (false == editor_track::find_route(from, to, route, error) || std::abs(route.length - entry.length) > 0.5) + if ((false == editor_track::find_route(from, to, route, error) || false == fits(route)) && (false == editor_track::find_route_along(from, to, Entry.length, Entry.middle, route) || false == fits(route))) continue; - auto const samples{editor_track::sample_route(route, 1.0)}; - if (samples.empty() || plan_distance(samples.front().position, entry.start) > 0.1 || plan_distance(editor_track::sampled_position(samples, route.length * 0.5), entry.middle) > 0.5) - continue; - profile_open(from, to); - return; + if (From != nullptr) + *From = from; + if (To != nullptr) + *To = to; + return route; } + return std::nullopt; +} + +std::pair editor_mode::profile_refit_stored(std::unordered_set const &Moved) +{ + // the designs were applied to the tracks one line at a time, the grade lines shared moved the tracks after them: a design left as + // it was parts from them, and a profile opened over them reads the stretches changed from the track again, a polyline bending + // wherever it falls, on the switches too. Each is laid anew onto the tracks as they lie now, as a line is onto the ground, within a + // centimetre and to the norms; one which can't be without an error stays as it was + double constexpr kTolerance{0.01}; // m + double constexpr kReach{100.0}; // m, however far a track is, it's what the line keeps to + double constexpr kSteepest{50.0}; // per mille, as the lines are fitted to the terrain, past the limit of the norms + profile_library_load(); + auto &state{m_profile}; + auto const show_model{state.show_model}; + state.show_model = false; + std::size_t refitted{0}, failed{0}; + std::vector layers; + for (auto &entry : m_profiles) + { + auto route{profile_stored_route(entry)}; + if (false == route.has_value() || std::none_of(route->spans.begin(), route->spans.end(), [&](editor_track::route_span const &Span) { return Moved.contains(Span.track); })) + continue; + state.route = std::move(*route); + profile_resample(); + auto const &samples{state.samples}; + if (samples.size() < 2) + continue; + state.line = entry.line; + state.changed = false; + profile_check(); + if (state.departure <= kStale && false == has_errors(state.issues)) + continue; + auto const before{state.departure}; + // the tracks are no ground with structures to go past: the line keeps to all of them, as steep as they are, as sharply bent as + // on a hump the line was fitted to + std::vector chainages, heights; + for (auto const &sample : samples) + { + chainages.push_back(sample.chainage); + heights.push_back(sample.position.y); + } + std::vector const tolerances(samples.size(), kTolerance * 0.5); + std::vector const reaches(samples.size(), kReach); + profile::ground_fit options; + options.tolerance = kTolerance; + options.grade_max = kSteepest; + options.humps = profile::humps(chainages, heights, state.context, kTolerance); + options.hump_radius = 300.0; + auto line{profile::fit_ground(chainages, heights, state.context, entry.line, options, tolerances, reaches)}; + if (line.points.size() < 2) + continue; + state.line = std::move(line); + profile_check(); + if (has_errors(state.issues)) + { + ++failed; + std::string errors; + for (auto const &issue : state.issues) + if (issue.error) + errors += " | " + issue.text; + WriteLog(format("Editor: vertical profile - the design of %.0f m from %.1f %.1f, %.3f m off the tracks moved, can't be laid onto them anew without an error, it stays as it was%s", state.route.length, entry.start.x, entry.start.z, before, errors.c_str()), logtype::generic); + continue; + } + ++refitted; + entry.length = state.route.length; + entry.start = samples.front().position; + entry.end = samples.back().position; + entry.middle = editor_track::sampled_position(samples, state.route.length * 0.5); + entry.line = state.line; + entry.departure = state.departure; + for (auto &point : entry.line.points) + if (point.joint) + { + point.joint = false; + point.automatic = false; + } + layers.push_back(entry.layer); + } + state.show_model = show_model; + state.open = false; + state.route = {}; + state.samples.clear(); + if (false == layers.empty()) + profile_library_mark(std::move(layers)); + return {refitted, failed}; +} + +void editor_mode::profile_open_stored(std::size_t const Index) +{ + auto &state{m_profile}; + if (Index >= m_profiles.size()) + return; + auto const entry{m_profiles[Index]}; + TTrack *from{nullptr}; + TTrack *to{nullptr}; + // the route the design lies along, not the one of the fewest paths between its ends + if (auto route{profile_stored_route(entry, &from, &to)}) + { + state.open = true; + state.status.clear(); + state.error.clear(); + profile_take(std::move(*route), from, to); + return; + } state.open = true; state.error = STR_C("The route of the stored design isn't in the scenery any more (paths moved or removed)"); } @@ -351,6 +857,21 @@ void editor_mode::profile_edited() { m_profile.changed = true; profile_check(); + first_step_done(first_step::profile_point); +} + +void editor_mode::profile_remove_point(int const Index) +{ + auto &state{m_profile}; + auto &points{state.line.points}; + if (Index <= 0 || Index + 1 >= static_cast(points.size())) + return; + points.erase(points.begin() + Index); + for (auto const neighbour : {Index - 1, Index}) + if (neighbour > 0 && neighbour + 1 < static_cast(points.size()) && false == points[neighbour].joint) + points[neighbour].automatic = true; + state.selected = -1; + profile_edited(); } void editor_mode::profile_open(TTrack *From, TTrack *To) @@ -381,16 +902,79 @@ void editor_mode::profile_open_run(TTrack &Track) profile_take(std::move(route), from, to); } +// the route from one end of the selected tracks to the other: of the two of them farthest apart, through the switches between +void editor_mode::profile_open_selection(std::vector const &Tracks) +{ + auto const middle = [](TTrack const &Track) { return geometry::bezier{Track.m_paths.front()}.point(0.5); }; + TTrack *from{nullptr}; + TTrack *to{nullptr}; + double farthest{-1.0}; + for (std::size_t i = 0; i < Tracks.size(); ++i) + for (std::size_t j = i + 1; j < Tracks.size(); ++j) + if (auto const distance{plan_distance(middle(*Tracks[i]), middle(*Tracks[j]))}; distance > farthest) + { + farthest = distance; + from = Tracks[i]; + to = Tracks[j]; + } + if (from == nullptr || to == nullptr) + return; + profile_open(from, to); + auto &state{m_profile}; + if (state.route.spans.empty()) + return; + auto const off{std::count_if(Tracks.begin(), Tracks.end(), [&](TTrack const *Track) { + return std::none_of(state.route.spans.begin(), state.route.spans.end(), [&](editor_track::route_span const &Span) { return Span.track == Track; }); + })}; + if (off > 0) + state.status = format(STR_C("%d of the selected tracks are off the route from %s to %s"), static_cast(off), from->name().c_str(), to->name().c_str()); +} + +// the route follows the selection: one track gives its whole line unless it's on the route already, several give the route +// from one end of them to the other; the changes of the design left are kept for the save +void editor_mode::profile_follow_selection() +{ + auto &state{m_profile}; + auto const tracks{selected_tracks()}; + if (tracks == state.followed) + return; + state.followed = tracks; + if (tracks.empty()) + return; + auto const on_route{std::any_of(state.route.spans.begin(), state.route.spans.end(), [&](editor_track::route_span const &Span) { return Span.track == tracks.front(); })}; + if (tracks.size() == 1 && on_route) + return; + if (state.changed) + profile_store(); + if (tracks.size() == 1) + profile_open_run(*tracks.front()); + else + profile_open_selection(tracks); +} + void editor_mode::profile_take(editor_track::route Route, TTrack *From, TTrack *To) { auto &state{m_profile}; - state.from = state.picked_from = From; - state.to = state.picked_to = To; + state.picked_from = From; + state.from = state.picked_from; + state.picked_to = To; + state.to = state.picked_to; state.route = std::move(Route); state.selected = -1; + state.edits = m_track_edits; + first_step_done(first_step::profile); profile_resample(); if (false == profile_restore()) + { profile_recognize(); + if (false == state.samples.empty()) + { + auto const km{alignment_store::chainage_at(state.samples.front().position)}; + auto const further{alignment_store::chainage_at(editor_track::sampled_position(state.samples, std::min(state.route.length, 5.0)))}; + if (km.has_value() && further.has_value() && *further > *km) + state.origin = *km; + } + } profile_fit_view(); } @@ -409,22 +993,143 @@ void editor_mode::profile_resample() for (std::size_t i = 0; i < samples.size(); ++i) if (found[i] != 0) state.terrain[i] = heights[i]; + profile_sample_model(); + state.beds.assign(samples.size(), 0.0); + std::vector bedless(samples.size(), 0); + std::vector own; + for (std::size_t i = 0; i < samples.size(); ++i) + if (samples[i].span < state.route.spans.size()) + { + auto const &track{*state.route.spans[samples[i].span].track}; + state.beds[i] = profile_ballast(track).first; + bedless[i] = profile_own_bed(track) ? 0 : 1; + if (bedless[i] == 0) + own.push_back(state.beds[i]); + } + // a track with no trackbed of its own, as the switches of the older sceneries whose bed is an include, lies in the bed of + // the others + if (false == own.empty()) + { + std::nth_element(own.begin(), own.begin() + own.size() / 2, own.end()); + for (std::size_t i = 0; i < samples.size(); ++i) + if (bedless[i] != 0) + state.beds[i] = own[own.size() / 2]; + } auto &context{state.context}; context = {}; context.length = state.route.length; if (samples.empty()) return; + std::optional open; for (auto const &span : state.route.spans) - if (span.track->eType != tt_Normal) + { + if (auto const found{switch_store::named(*span.track)}) + { + if (open.has_value() && open->name == found->name && span.from - context.switches.back().to <= std::max(found->a + found->b, context.switches.back().to - context.switches.back().from)) + { + context.switches.back().to = span.to; + continue; + } + auto const label{switch_store::label(*found)}; + context.switches.push_back({span.from, span.to, found->number != "-" ? found->number + ' ' + label : label}); + open = found; + } + else if (span.track->eType != tt_Normal) + { context.switches.push_back({span.from, span.to, span.track->name()}); + open.reset(); + } + } + // where the rails of the route lie on timbers shared with another track, at a switch, a crossover, a crossing, the grade + // doesn't break nor does a vertical curve reach: the timbers carry both tracks in one plane + { + auto const before{context.switches.size()}; + for (auto const &span : state.route.spans) + { + auto const length{span.track->eType == tt_Switch ? span.track->SwitchExtension->Segments[span.path]->GetLength() : span.track->Segment->GetLength()}; + if (length < 1e-6) + continue; + auto const scale{(span.to - span.from) / length}; + for (auto const &zone : track_sleepers::shared_zones(*span.track, span.path)) + { + auto const a{span.forward ? span.from + zone.first * scale : span.to - zone.second * scale}; + auto const b{span.forward ? span.from + zone.second * scale : span.to - zone.first * scale}; + // the stretches of a switch on the route are its own zone already + auto const inside{std::any_of(context.switches.begin(), context.switches.begin() + static_cast(before), [&](auto const &Zone) { return a >= Zone.from - 0.5 && b <= Zone.to + 0.5; })}; + if (false == inside && b - a > 0.1) + context.switches.push_back({a, b, STR("shared timbers")}); + } + } + std::sort(context.switches.begin(), context.switches.end(), [](auto const &Left, auto const &Right) { return Left.from < Right.from; }); + } context.start_elevation = samples.front().position.y; context.end_elevation = samples.back().position.y; - context.start_joined = editor_track::adjoining_grade(state.route, false, context.start_grade); - context.end_joined = editor_track::adjoining_grade(state.route, true, context.end_grade); + TTrack *adjoining{nullptr}; + int path{0}; + bool entered{false}; + // a joined end on a switch inherits its height and grade from the switch, which lies in one plane + auto const inherits = [&](bool const Joined, double const Elevation, double const Grade) { + if (false == Joined || adjoining == nullptr || adjoining->eType != tt_Switch) + return std::string{}; + auto const found{switch_store::named(*adjoining)}; + auto const point{entered ? "P1" : path == 0 ? "P2" : "P4"}; + return format(STR_C("Grade line from the switch %s (%s): %.2f m, %+.2f per mille"), (found ? switch_store::label(*found) : adjoining->name()).c_str(), point, Elevation, Grade * 1000.0); + }; + context.start_joined = editor_track::adjoining_grade(state.route, false, context.start_grade, &adjoining, &path, &entered); + state.start_inherits = inherits(context.start_joined, context.start_elevation, context.start_grade); + adjoining = nullptr; + context.end_joined = editor_track::adjoining_grade(state.route, true, context.end_grade, &adjoining, &path, &entered); + state.end_inherits = inherits(context.end_joined, context.end_elevation, context.end_grade); profile_check(); } +void editor_mode::profile_sample_model() +{ + auto &state{m_profile}; + auto const &samples{state.samples}; + state.model.assign(samples.size(), std::numeric_limits::quiet_NaN()); + state.model_waiting = false; + state.model_polled = ImGui::GetTime(); + if (samples.empty() || false == state.show_model) + return; + nmt_locate(); + if (false == m_nmt.placed()) + return; + // the squares along the route, not all those under the rectangle around it: a long line crosses the grid + std::size_t constexpr run{200}; + for (std::size_t first = 0; first < samples.size(); first += run) + { + glm::dvec2 low{samples[first].position.x, samples[first].position.z}; + auto high{low}; + for (auto i = first; i < std::min(samples.size(), first + run + 1); ++i) + { + low = glm::min(low, glm::dvec2{samples[i].position.x, samples[i].position.z}); + high = glm::max(high, glm::dvec2{samples[i].position.x, samples[i].position.z}); + } + if (false == m_nmt.request(low - glm::dvec2{2.0}, high + glm::dvec2{2.0})) + state.model_waiting = true; + } + std::vector differences; + for (std::size_t i = 0; i < samples.size(); ++i) + if (double height; m_nmt.height(samples[i].position.x, samples[i].position.z, height)) + { + state.model[i] = height; + differences.push_back(samples[i].position.y - height); + } + // a scenery put onto the model lies at its heights, or as far from them as the model was found to lie from it; one built at + // heights of its own, never put onto it, is compared by the shape: the model goes as far as the route lies from it + auto offset{m_nmt_state.offset}; + if (false == m_nmt_state.fitted && false == differences.empty()) + { + std::nth_element(differences.begin(), differences.begin() + differences.size() / 2, differences.end()); + if (auto const median{differences[differences.size() / 2]}; std::abs(median) > 30.0) + offset = median; + } + for (auto &height : state.model) + height += offset; +} + void editor_mode::profile_recognize() { auto &state{m_profile}; @@ -436,12 +1141,24 @@ void editor_mode::profile_recognize() grades.push_back(sample.grade); } auto const norms{state.line.norms}; - state.line = profile::recognize(chainages, elevations, grades, {}); - state.line.norms = norms; - state.line.speed = route_speed(state.route); - state.selected = -1; - profile_check(); - state.status = format(STR_C("Grade line recognized from the track: %zu points, largest departure %.3f m"), state.line.points.size(), state.departure); + auto const read = [&](profile::recognition const &Options) { + state.line = profile::recognize(chainages, elevations, grades, Options); + state.line.norms = norms; + state.line.speed = editor_track::route_speed(state.route); + state.selected = -1; + profile_check(); + }; + state.changed = false; + read({}); + // the constant grades alone don't tell a line bent all along: its bends read as they lie + if (state.departure > kDesignOff) + { + profile::recognition options; + options.minimum_length = 5.0; + options.detail = kStale; + read(options); + } + state.status = format(STR_P("Grade line recognized from the track: %zu point, largest departure %.3f m", "Grade line recognized from the track: %zu points, largest departure %.3f m", state.line.points.size()), state.line.points.size(), state.departure); } void editor_mode::profile_fit_ground() @@ -456,33 +1173,44 @@ void editor_mode::profile_fit_ground() return; } auto settings{state.line}; - settings.speed = route_speed(state.route); - auto line{profile::fit_ground(chainages, state.terrain, state.context, settings, state.fit)}; + settings.speed = editor_track::route_speed(state.route); + // the grade line is the rail top: it's fitted so the formation under it, not the rails, follows the ground + auto ground{state.terrain}; + for (std::size_t i = 0; i < ground.size() && i < state.beds.size(); ++i) + ground[i] += state.beds[i]; + auto line{profile::fit_ground(chainages, ground, state.context, settings, state.fit)}; if (line.points.size() < 2) return; state.line = std::move(line); state.selected = -1; state.error.clear(); profile_check(); - double fill{0.0}, cut{0.0}; + double fill{0.0}; + double cut{0.0}; for (std::size_t i = 0; i < state.samples.size(); ++i) { if (false == std::isfinite(state.terrain[i])) continue; - auto const difference{profile::elevation(state.line, state.samples[i].chainage) - state.terrain[i]}; + auto const difference{profile::elevation(state.line, state.samples[i].chainage) - (i < state.beds.size() ? state.beds[i] : 0.0) - state.terrain[i]}; fill = std::max(fill, difference); cut = std::max(cut, -difference); } - state.status = format(STR_C("Grade line fitted to the ground: %zu points, embankment up to %.2f m, cutting up to %.2f m"), state.line.points.size(), fill, cut); + state.status = format(STR_P("Grade line fitted to the ground: %zu point, embankment up to %.2f m, cutting up to %.2f m", "Grade line fitted to the ground: %zu points, embankment up to %.2f m, cutting up to %.2f m", state.line.points.size()), state.line.points.size(), fill, cut); } std::pair editor_mode::profile_ballast(TTrack const &Track) { - auto const depth{std::max(0.0, static_cast(Track.fTexHeight1 - Track.fTexHeightOffset))}; + // the ballast is laid from the foot of the rails down, the rail top being the grade line + auto const depth{std::max(0.0, static_cast(Track.fTexHeight1 - Track.fTexHeightOffset)) + Track.rail_height()}; auto const foot{0.5 * std::abs(Track.fTrackWidth) + std::abs(Track.fTexWidth) + std::abs(Track.fTexSlope)}; return {depth, std::max(0.5, foot)}; } +bool editor_mode::profile_own_bed(TTrack const &Track) +{ + return Track.fTexHeight1 - Track.fTexHeightOffset > kNoBed; +} + std::pair editor_mode::profile_generate_ground(std::vector> const &Beds, double const Reach) { auto &state{m_profile}; @@ -504,7 +1232,8 @@ std::pair editor_mode::profile_generate_ground(std::vector(cells) + 1}; - int made{0}, skipped{0}; + int made{0}; + int skipped{0}; for (auto const &key : keys) { if (m_streamer.exists(key)) @@ -626,7 +1355,8 @@ void editor_mode::profile_shape_ground() } modifier.points.push_back(points.back()); - double fill{0.0}, cut{0.0}; + double fill{0.0}; + double cut{0.0}; for (std::size_t i = 0; i < samples.size(); ++i) { if (i >= state.terrain.size() || false == std::isfinite(state.terrain[i])) @@ -641,11 +1371,11 @@ void editor_mode::profile_shape_ground() m_streamer.modifier(std::move(modifier)); forget_ground(); - auto status{format(STR_C("Terrain shaped by the modifier \"%s\" (%zu points): embankment up to %.2f m, cutting up to %.2f m"), works.modifier.c_str(), count, fill, cut)}; + auto status{format(STR_P("Terrain shaped by the modifier \"%s\" (%zu point): embankment up to %.2f m, cutting up to %.2f m", "Terrain shaped by the modifier \"%s\" (%zu points): embankment up to %.2f m, cutting up to %.2f m", count), works.modifier.c_str(), count, fill, cut)}; if (generated.first > 0) - status += format(STR_C("; %d chunk(s) of terrain made under the route"), generated.first); + status += format(STR_P("; %d chunk of terrain made under the route", "; %d chunks of terrain made under the route", generated.first), generated.first); if (generated.second > 0) - status += format(STR_C("; %d chunk(s) left out: the scenery has its own ground there, convert it to shape it"), generated.second); + status += format(STR_P("; %d chunk left out: the scenery has its own ground there, convert it to shape it", "; %d chunks left out: the scenery has its own ground there, convert it to shape it", generated.second), generated.second); state.error.clear(); profile_resample(); state.status = status; @@ -760,16 +1490,19 @@ void editor_mode::render_profile_earthworks() auto &works{state.earthworks}; if (false == ImGui::TreeNode(STR_C("Shape the terrain to the grade line"))) return; - ImGui::TextWrapped("%s", STR_C("Only the heightmap terrain changes: a formation under the track and slopes to the ground, kept as a modifier of the terrain which follows the grade line when it's shaped again; the triangles and models of the scenery stay as they are.")); + ImGui::TextWrapped("%s", STR_C("Only the heightmap terrain changes: a formation and slopes are made, the models of the scenery stay as they are")); render_ground_conversion(); - auto const drag = [](char const *Label, double &Value, float const Speed, char const *Format) { return ImGui::DragScalar(STR_C(Label), ImGuiDataType_Double, &Value, Speed, nullptr, nullptr, Format); }; - ImGui::PushItemWidth(90.0f); - ImGui::Checkbox(STR_C("Make terrain where the route has none"), &works.generate); - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", STR_C("Chunks of heightmap terrain are made along the route where there's none, from the ground around,\nthen shaped. Where the scenery has its own ground triangles the chunk is left out: convert them instead")); - ImGui::Checkbox(STR_C("Formation under the ballast of the track"), &works.from_ballast); - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", STR_C("The terrain goes as deep under the track as its ballast reaches and as wide as its foot,\nread from each path of the route; off: the values given below")); + auto const drag = [](char const *Label, double &Value, float const Speed, char const *Format) { + field_row(Label); + ImGui::PushID(Label); + auto const edited{ImGui::DragScalar("##value", ImGuiDataType_Double, &Value, Speed, nullptr, nullptr, Format)}; + ImGui::PopID(); + return edited; + }; + toggle_chips("earthworks", {{STR_C("Make terrain where the route has none"), &works.generate, + "Chunks of heightmap terrain are made along the route where there's none, from the ground around,\nthen shaped. Where the scenery has its own ground triangles the chunk is left out: convert them instead"}, + {STR_C("Formation under the ballast of the track"), &works.from_ballast, + "The terrain goes as deep under the track as its ballast reaches and as wide as its foot,\nread from each path of the route; off: the values given below"}}); if (works.from_ballast) { if (false == state.route.spans.empty() && state.route.spans.front().track != nullptr) @@ -778,19 +1511,29 @@ void editor_mode::render_profile_earthworks() ImGui::TextDisabled(STR_C("Ballast %.2f m deep, its foot %.2f m from the axis"), bed.first, bed.second); } } - else + if (false == works.from_ballast && begin_fields("##earthworkfields", 0.55f)) { drag("Formation below the track (m)", works.depth, 0.01f, "%.2f"); drag("Half width of the formation (m)", works.half_width, 0.05f, "%.2f"); if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", STR_C("From the axis of the route to the edge of the formation;\nfor two tracks add the distance between them")); + ImGui::EndTable(); } - drag("Slopes 1 : n, n", works.slope, 0.05f, "%.2f"); - drag("Slopes reach at most (m)", works.reach, 1.0f, "%.0f"); - drag("Rounding of the edges (m)", works.rounding, 0.1f, "%.1f"); - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", STR_C("Length over which the slope bends into the formation and into the ground; 0: sharp edges")); - ImGui::PopItemWidth(); + ImGui::PushID("earthworkmore"); + if (ImGui::TreeNode(STR_C("More settings"))) + { + if (begin_fields("##earthworkslopes", 0.55f)) + { + drag("Slopes 1 : n, n", works.slope, 0.05f, "%.2f"); + drag("Slopes reach at most (m)", works.reach, 1.0f, "%.0f"); + drag("Rounding of the edges (m)", works.rounding, 0.1f, "%.1f"); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Length over which the slope bends into the formation and into the ground; 0: sharp edges")); + ImGui::EndTable(); + } + ImGui::TreePop(); + } + ImGui::PopID(); works.rounding = std::clamp(works.rounding, 0.0, 20.0); works.depth = std::clamp(works.depth, 0.0, 5.0); works.half_width = std::clamp(works.half_width, 0.5, 30.0); @@ -798,12 +1541,18 @@ void editor_mode::render_profile_earthworks() works.reach = std::clamp(works.reach, 1.0, 200.0); if (has_errors(state.issues)) ImGui::TextDisabled("%s", STR_C("Correct the errors of the grade line first")); - else if (ImGui::Button(STR_C("Shape the terrain"))) - profile_shape_ground(); + else + { + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.18f, 0.42f, 0.24f, 1.0f)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.22f, 0.52f, 0.30f, 1.0f)); + if (ImGui::Button(STR_C("Shape the terrain"), ImVec2(-FLT_MIN, ImGui::GetFrameHeight() * 1.3f))) + profile_shape_ground(); + item_tooltip("Makes the formation and the slopes along the route in the heightmap terrain.\nThey're kept as a modifier of the terrain, which follows the grade line when you shape it again; the triangles and models of the scenery stay as they are"); + ImGui::PopStyleColor(2); + } if (false == works.modifier.empty() || false == works.generated.empty()) { - ImGui::SameLine(); - if (ImGui::Button(STR_C("Restore the terrain"))) + if (ImGui::Button(STR_C("Restore the terrain"), ImVec2(-FLT_MIN, 0.0f))) profile_restore_ground(); if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", STR_C("Removes the modifier of the route, and takes away the terrain the shaping made")); @@ -823,6 +1572,9 @@ void editor_mode::profile_check() { auto &state{m_profile}; auto &points{state.line.points}; + // what the edits start from + if (false == state.changed) + state.line_read = state.line; // joint points come and go, the selection follows the point it was made on struct mark { @@ -862,16 +1614,117 @@ void editor_mode::profile_fit_view() state.exaggeration = 0.0f; } -void editor_mode::profile_apply() +void editor_mode::profile_to_camera() +{ + auto &state{m_profile}; + if (state.samples.empty()) + return; + // where the view looks: from above the camera itself, else the middle of the view on the level of the route + glm::dvec3 target{Camera.Pos}; + if (false == Global.EditorOrtho) + { + auto const low{editor_ui::view_min()}; + auto const high{editor_ui::view_max()}; + glm::dvec3 point; + if (screen_projection{}.on_level(ImVec2{(low.x + high.x) * 0.5f, (low.y + high.y) * 0.5f}, state.samples[state.samples.size() / 2].position.y, point)) + target = point; + } + auto best{std::numeric_limits::max()}; + double chainage{0.0}; + for (auto const &sample : state.samples) + if (auto const distance{geometry::plan_distance(sample.position, target)}; distance < best) + { + best = distance; + chainage = sample.chainage; + } + auto const span{state.view_to - state.view_from}; + state.view_from = chainage - 0.5 * span; + state.view_to = chainage + 0.5 * span; +} + +void editor_mode::profile_frame_view() +{ + auto const &state{m_profile}; + std::vector points; + for (auto const &sample : state.samples) + if (sample.chainage >= state.view_from && sample.chainage <= state.view_to) + points.push_back(sample.position); + auto const &io{ImGui::GetIO()}; + if (points.size() < 2 || io.DisplaySize.y <= 0.0f) + return; + glm::dvec3 low{points.front()}; + glm::dvec3 high{points.front()}; + for (auto const &point : points) + { + low = glm::min(low, point); + high = glm::max(high, point); + } + auto const centre{(low + high) * 0.5}; + // the room the docks and the strip of the plot leave to the view, and how far its middle lies from the middle of the screen, + // in pixels + glm::dvec2 const screen{io.DisplaySize.x, io.DisplaySize.y}; + auto const viewlow{editor_ui::view_min()}; + auto viewhigh{editor_ui::view_max()}; + if (state.strip_top > viewlow.y + 100.0f) + viewhigh.y = std::min(viewhigh.y, state.strip_top); + auto const width{std::max(50.0, static_cast(viewhigh.x - viewlow.x))}; + auto const height{std::max(50.0, static_cast(viewhigh.y - viewlow.y))}; + glm::dvec2 const shift{(viewlow.x + viewhigh.x) * 0.5 - screen.x * 0.5, (viewlow.y + viewhigh.y) * 0.5 - screen.y * 0.5}; + double constexpr margin{1.1}; + if (Global.EditorOrtho) + { + auto const yaw{static_cast(Camera.Angle.y)}; + double extent{5.0}; + for (auto const &point : points) + { + auto const local{RotateY(point - centre, -yaw)}; + extent = std::max({extent, std::abs(local.x) * margin * screen.y / width, std::abs(local.z) * margin * screen.y / height}); + } + Global.EditorOrthoExtent = std::clamp(static_cast(extent), 5.0f, 50000.0f); + auto const scale{2.0 * static_cast(Global.EditorOrthoExtent) / screen.y}; + auto const offset{RotateY(glm::dvec3{shift.x * scale, 0.0, shift.y * scale}, yaw)}; + m_ride.leave(); + Camera.Pos.x = centre.x - offset.x; + Camera.Pos.z = centre.z - offset.z; + Camera.Velocity = {}; + m_focus_active = false; + Global.pCamera = Camera; + return; + } + // seen from the side, as the plot shows it: the start on the left, from a little above + glm::dvec3 chord{points.back().x - points.front().x, 0.0, points.back().z - points.front().z}; + chord = glm::length(chord) > 1e-6 ? glm::normalize(chord) : glm::dvec3{1.0, 0.0, 0.0}; + glm::dvec3 const up{0.0, 1.0, 0.0}; + auto const look{glm::normalize(glm::cross(up, chord) + glm::dvec3{0.0, -0.4, 0.0})}; + auto const right{glm::normalize(glm::cross(look, up))}; + auto const above{glm::cross(right, look)}; + auto const tangent{std::tan(glm::radians(static_cast(Global.FieldOfView) / std::max(0.01, static_cast(Global.ZoomFactor))) * 0.5)}; + auto const across{tangent * width / screen.y}; + auto const upward{tangent * height / screen.y}; + double distance{10.0}; + for (auto const &point : points) + { + auto const offset{point - centre}; + auto const depth{glm::dot(offset, look)}; + distance = std::max({distance, std::abs(glm::dot(offset, right)) * margin / across - depth, std::abs(glm::dot(offset, above)) * margin / upward - depth}); + } + distance = std::min(distance, 8000.0); + auto const pixel{2.0 * distance * tangent / screen.y}; + fly_to(centre - right * (shift.x * pixel) + above * (shift.y * pixel), look, distance, 0.35); +} + +void editor_mode::profile_apply(bool const Terrain, std::vector const &Bridges, double const Fewest) { auto &state{m_profile}; state.status.clear(); state.error.clear(); if (state.route.spans.empty() || state.line.points.size() < 2) return; - if (has_errors(state.issues)) + auto const edits{m_track_edits}; + if (state.changed && false == state.fitting ? errors_in_change(state.issues, state.line, state.line_read, state.samples) : has_errors(state.issues)) { state.error = STR_C("Correct the errors to apply the grade line"); + state.show_remarks = true; return; } std::vector tracks; @@ -883,17 +1736,71 @@ void editor_mode::profile_apply() return; } auto const line{state.line}; + auto const before{state.samples}; std::vector> states; std::vector created; + std::vector ends; + for (auto const &span : state.route.spans) + ends.insert(ends.end(), {span.from, span.to}); + auto cuts{profile::breaks(line)}; + // an edit goes onto the track as what it changed in the line: where it changed nothing the track stays as it lies, whatever the line + // read from it is off it by, and isn't cut + bool const edit_only{state.changed && false == state.fitting}; + auto const read_line{state.line_read}; + auto const changed_at = [&](double const Chainage) { return profile::elevation(line, Chainage) - profile::elevation(read_line, Chainage); }; + if (edit_only) + std::erase_if(cuts, [&](double const Cut) { + double constexpr kCutNear{1.0}; // m + double constexpr kNoChange{0.001}; // m + return std::abs(changed_at(Cut - kCutNear)) < kNoChange && std::abs(changed_at(Cut + kCutNear)) < kNoChange; + }); + auto const height_at = [&](double const Chainage) { return edit_only ? editor_track::sampled_elevation(before, Chainage) + changed_at(Chainage) : profile::elevation(line, Chainage); }; + auto const grade_at = [&](double const Chainage) { return edit_only ? editor_track::sampled_grade(before, Chainage) + profile::grade(line, Chainage) - profile::grade(read_line, Chainage) : profile::grade(line, Chainage); }; + // the paths are cut only at the breaks they can't go over keeping to the line within a hair: one cut there, by a joint, or by + // another cut, would leave a sliver of a track, the line applied again leaving more of them by the first, the ballast mapped + // on each from its start. A path just laid keeps to it as closely as Fewest + double constexpr kFollow{0.002}; // m + cuts = profile::fewest_breaks(cuts, ends, Fewest > 0.0 ? Fewest : kFollow, height_at, grade_at); + // a bridge ends at a joint or a break of the line by its abutment rather than leave a sliver of a path there + double constexpr kBridgeSnap{1.0}; // m + auto joints{cuts}; + joints.insert(joints.end(), ends.begin(), ends.end()); + auto bridges{Bridges}; + for (auto &bridge : bridges) + for (auto *end : {&bridge.from, &bridge.to}) + if (auto const nearest{std::min_element(joints.begin(), joints.end(), [&](double const A, double const B) { return std::abs(A - *end) < std::abs(B - *end); })}; + nearest != joints.end() && std::abs(*nearest - *end) <= kBridgeSnap) + *end = *nearest; + for (auto const &bridge : bridges) + cuts.insert(cuts.end(), {bridge.from, bridge.to}); + std::sort(cuts.begin(), cuts.end()); auto const gaps{editor_track::apply_profile( - state.route, [&](double const Chainage) { return profile::elevation(line, Chainage); }, [&](double const Chainage) { return profile::grade(line, Chainage); }, profile::breaks(line), states, created)}; + state.route, height_at, grade_at, cuts, states, created)}; + // the paths over a bridge sound and light as on one, and get no formation; within what a cut too near an end leaves on + double constexpr kBridgeEnd{0.5}; // m + std::size_t bridged{0}; + for (auto const &span : state.route.spans) + if (span.track->eEnvironment != e_bridge && span.track->eEnvironment != e_tunnel + && std::any_of(bridges.begin(), bridges.end(), [&](profile::departure const &Bridge) { return span.from >= Bridge.from - kBridgeEnd && span.to <= Bridge.to + kBridgeEnd; })) + { + span.track->eEnvironment = e_bridge; + ++bridged; + } auto const changed{states.size()}; auto const added{created.size()}; + state.created = created; + { + auto marked{tracks}; + marked.insert(marked.end(), created.begin(), created.end()); + fitted_set(marked, edit_only); + } // the stored design changes with the paths, an undo takes both back profile_library_load(); auto library{m_profiles}; bool const pushed{false == states.empty() || false == created.empty()}; push_track_snapshot(std::move(states), std::move(created)); + state.edits = m_track_edits; + first_step_done(first_step::profile_apply); if (pushed) { m_history.back().profiles = true; @@ -903,24 +1810,89 @@ void editor_mode::profile_apply() state.to = state.route.spans.back().track; profile_resample(); profile_store(); - state.status = format(STR_C("Grade line applied: %zu paths changed, %zu added, largest departure %.3f m"), changed, added, state.departure); + state.status = format(STR_P("Grade line applied: %zu path changed, %zu added, largest departure %.3f m", "Grade line applied: %zu paths changed, %zu added, largest departure %.3f m", changed), changed, added, state.departure); if (false == scene::Layers.empty()) - state.status += "\nThe paths and the design (//$p lines) go to the scenery files on save"; - auto const name = [](TTrack const *Track) { return Track->name().empty() ? std::string{"(noname)"} : Track->name(); }; + state.status += STR_C("\nThe paths and the design (//$p lines) go to the scenery files on save"); + if (bridged > 0) + state.status += format(STR_P("\nOver a bridge or a viaduct: %zu path", "\nOver a bridge or a viaduct: %zu paths", bridged), bridged); + auto const name = [](TTrack const *Track) { return name_of(*Track); }; auto const closed{std::count_if(gaps.begin(), gaps.end(), [](auto const &Gap) { return Gap.closed; })}; if (closed > 0) - state.status += "\nPaths off the route brought to the height of the switches:"; + state.status += STR_C("\nPaths off the route brought to its height:"); for (auto const &gap : gaps) if (gap.closed) - state.status += format("\n %s at %s: %+.3f m", name(gap.neighbour).c_str(), name(gap.track).c_str(), -gap.gap); + state.status += format(STR_C("\n %s at %s: %+.3f m"), name(gap.neighbour).c_str(), name(gap.track).c_str(), -gap.gap); if (closed < static_cast(gaps.size())) - state.status += "\nSwitch ends off the adjoining paths, which can't be changed here:"; + state.status += STR_C("\nSwitch ends off the adjoining paths, which can't be changed here:"); for (auto const &gap : gaps) if (false == gap.closed) state.status += format("\n %s -> %s: %+.3f m", name(gap.track).c_str(), name(gap.neighbour).c_str(), gap.gap); + // the tracks on the other side of the crossovers of the route go up and down with it + auto const followed{follow_crossovers(before)}; + if (followed > 0) + state.status += format(STR_C("\nThe tracks across %zu crossover(s) followed the change"), followed); + // a line fitted to the terrain model goes by itself: the ones sharing its grade line are worked out after them all + if (auto const beside{state.fitting ? std::size_t{0} : grade_line_follow(before)}; beside > 0) + state.status += format(STR_P("\nThe common grade line: %zu track beside went with the route", "\nThe common grade line: %zu tracks beside went with the route", beside), beside); + if (Terrain) + profile_follow_terrain(static_cast(m_track_edits - edits)); WriteLog("Editor: vertical profile - " + state.status, logtype::generic); } +void editor_mode::profile_follow_terrain(std::size_t const Edits) +{ + auto &state{m_profile}; + // the heightmap terrain the scenery has; the ground of a scenery without it stays as it is + if (false == m_streamer.active() || Edits == 0) + return; + std::vector tracks; + std::size_t found{0}; + for (auto step{m_history.rbegin()}; step != m_history.rend() && found < Edits; ++step) + { + if (step->action != EditorSnapshot::Action::TrackEdit) + continue; + ++found; + for (auto const &entry : step->tracks) + tracks.push_back(entry.first); + tracks.insert(tracks.end(), step->created.begin(), step->created.end()); + tracks.insert(tracks.end(), step->removed.begin(), step->removed.end()); + } + std::erase(tracks, nullptr); + std::sort(tracks.begin(), tracks.end()); + tracks.erase(std::unique(tracks.begin(), tracks.end()), tracks.end()); + if (tracks.empty()) + return; + // the route shaped by the earthworks of the profile keeps its modifier, shaped again to the new grade line; the tracks + // shaped one by one, as the terrain model lays them, get their formations anew + auto const name = [](TTrack const *Track) { return Track != nullptr && false == Track->name().empty() ? Track->name() : std::string{"?"}; }; + auto const route{"route " + name(state.from) + " - " + name(state.to)}; + auto const &modifiers{m_streamer.modifiers()}; + auto const has = [&](std::string const &Name) { return std::any_of(modifiers.begin(), modifiers.end(), [&](heightmap::modifier const &Modifier) { return Modifier.name == Name; }); }; + auto const shaped{has(route) || (false == state.earthworks.modifier.empty() && has(state.earthworks.modifier))}; + auto const own{std::any_of(tracks.begin(), tracks.end(), [&](TTrack const *Track) { + return false == Track->name().empty() && std::any_of(modifiers.begin(), modifiers.end(), [&](heightmap::modifier const &Modifier) { return Modifier.name == "nmt " + Track->name() || Modifier.name.starts_with("nmt " + Track->name() + " "); }); + })}; + auto status{state.status}; + std::size_t laid{0}; + if (false == shaped || own) + laid = nmt_shape_tracks(&tracks); + if (shaped) + { + profile_shape_ground(); + status += "\n" + state.status; + } + else + profile_resample(); + if (laid > 0) + status += format(STR_P("\nThe terrain followed the tracks: %zu formation laid anew", "\nThe terrain followed the tracks: %zu formations laid anew", laid), laid); + state.status = status; + // the terrain goes back with the grade line in one step + auto const before{m_history.empty() ? EditorSnapshot::Action::Other : m_history.back().action}; + terrain_history_step(); + if (before != EditorSnapshot::Action::Terrain && false == m_history.empty() && m_history.back().action == EditorSnapshot::Action::Terrain) + m_history.back().joined = true; +} + void editor_mode::profile_after_undo() { auto &state{m_profile}; @@ -937,27 +1909,43 @@ void editor_mode::profile_after_undo() { state.route = {}; state.samples.clear(); - state.selected = state.dragging = state.curve_grip = -1; + state.selected = -1; + state.dragging = -1; + state.curve_grip = -1; return; } profile_resample(); } +// the tracks of the route changed by another tool or by an undo: the route read again, the design kept in the scenery read +// again over it unless it's being changed +void editor_mode::profile_follow_edits() +{ + auto &state{m_profile}; + if (state.edits == m_track_edits) + return; + state.edits = m_track_edits; + if (state.route.spans.empty() || state.dragging >= 0) + return; + auto const kept{false == state.changed}; + profile_after_undo(); + if (kept && false == state.route.spans.empty()) + profile_restore(); +} + void editor_mode::render_profile_body() { auto &state{m_profile}; + profile_follow_selection(); + step_heading(1, STR_C("Route")); render_profile_source(); if (state.route.spans.empty()) { - ImGui::TextWrapped("%s", STR_C("Select a path in the view, then build the route along the line, or set its start and end paths (switches are passed through)")); - if (state.picked_from != nullptr) - ImGui::Text(STR_C("Start: %s"), state.picked_from->name().c_str()); if (false == state.error.empty()) ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.3f, 1.0f), "%s", state.error.c_str()); return; } - ImGui::Separator(); - ImGui::TextWrapped(STR_C("Route: %zu paths, %.2f m, %s ... %s"), state.route.spans.size(), state.route.length, state.route.spans.front().track->name().c_str(), state.route.spans.back().track->name().c_str()); + ImGui::TextWrapped(STR_P("%zu path, %.2f m: %s ... %s", "%zu paths, %.2f m: %s ... %s", state.route.spans.size()), state.route.spans.size(), state.route.length, state.route.spans.front().track->name().c_str(), state.route.spans.back().track->name().c_str()); { bool reversed; auto const stored{profile_find(reversed)}; @@ -972,77 +1960,213 @@ void editor_mode::render_profile_body() ImGui::TextDisabled(STR_C("The design goes to the scenery file of the route on save")); } + render_profile_grade_line(); + step_heading(2, STR_C("Grade line")); if (render_profile_parameters()) profile_edited(); + step_heading(3, STR_C("Terrain")); + render_profile_earthworks(); } void editor_mode::render_profile_strip() { + profile_follow_edits(); + // the strip follows the selection by itself: the panel of the tool needn't be the one in front + profile_follow_selection(); auto &state{m_profile}; auto const &io{ImGui::GetIO()}; - ImGui::SetNextWindowPos(ImVec2(8.0f, io.DisplaySize.y - 360.0f), ImGuiCond_FirstUseEver); - ImGui::SetNextWindowSize(ImVec2(std::max(600.0f, io.DisplaySize.x - 500.0f), 320.0f), ImGuiCond_FirstUseEver); - auto const title{std::string{STR_C("Vertical profile")} + format(" %.2f m###profilestrip", state.route.length)}; + // along the bottom of the 3d view, as wide as it; each time the profile opens, wherever it was left before + auto const low{editor_ui::view_min()}; + auto const high{editor_ui::view_max()}; + auto const width{std::max(480.0f, high.x - low.x)}; + auto const height{std::clamp((high.y - low.y) * 0.5f, 260.0f, std::max(260.0f, high.y - low.y - 80.0f))}; + ImGui::SetNextWindowPos(ImVec2(low.x, high.y - height), ImGuiCond_Appearing); + ImGui::SetNextWindowSize(ImVec2(width, height), ImGuiCond_Appearing); + auto title{std::string{STR_C("Vertical profile")}}; + if (false == state.route.spans.empty()) + title += format(STR_P(" %s > %s, %zu path, %.2f m", " %s > %s, %zu paths, %.2f m", state.route.spans.size()), state.route.spans.front().track->name().c_str(), state.route.spans.back().track->name().c_str(), state.route.spans.size(), state.route.length); + title += "###profilestrip"; if (ImGui::Begin(title.c_str(), nullptr, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse)) { - auto const side{std::clamp(ImGui::GetContentRegionAvail().x * 0.28f, 280.0f, 420.0f)}; - ImGui::BeginChild("##profileplot", ImVec2(-side, 0.0f), false, ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse); - render_profile_toolbar(); - render_profile_canvas(ImGui::GetContentRegionAvail().y); - ImGui::EndChild(); - ImGui::SameLine(); - ImGui::BeginChild("##profileside", ImVec2(0.0f, 0.0f), false); - if (ImGui::BeginTabBar("##profiletabs")) + // a window left past the edge of the screen comes back into it + auto const position{ImGui::GetWindowPos()}; + auto const size{ImGui::GetWindowSize()}; + state.strip_top = ImGui::IsWindowDocked() ? -1.0f : position.y; + if (false == ImGui::IsWindowDocked() && (position.y + size.y > io.DisplaySize.y + 1.0f || position.x + 80.0f > io.DisplaySize.x || position.x + size.x < 80.0f)) + ImGui::SetWindowPos(ImVec2(std::clamp(position.x, 0.0f, std::max(0.0f, io.DisplaySize.x - size.x)), std::max(0.0f, std::min(position.y, io.DisplaySize.y - size.y)))); + if (state.route.spans.empty()) + render_profile_empty(); + else { - // a click on a point in the plot brings its tab forward - bool const picked{state.selected >= 0 && state.selected != state.shown}; - state.shown = state.selected; - if (ImGui::BeginTabItem(STR_C("Point"), nullptr, picked ? ImGuiTabItemFlags_SetSelected : 0)) + render_profile_header(); + auto const side{std::clamp(ImGui::GetContentRegionAvail().x * 0.3f, 250.0f, 400.0f)}; + ImGui::BeginChild("##profileplot", ImVec2(-side, 0.0f), false, ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse); + render_profile_toolbar(); + render_profile_canvas(ImGui::GetContentRegionAvail().y); + ImGui::EndChild(); + ImGui::SameLine(); + ImGui::BeginChild("##profileside", ImVec2(0.0f, 0.0f), false); + if (ImGui::BeginTabBar("##profiletabs")) { - render_profile_point(); - ImGui::EndTabItem(); + // a click on a point in the plot brings its tab forward, a click on the state of the grade line the remarks + bool const picked{state.selected >= 0 && state.selected != state.shown}; + state.shown = state.selected; + if (ImGui::BeginTabItem(STR_C("Point"), nullptr, picked ? ImGuiTabItemFlags_SetSelected : 0)) + { + render_profile_point(); + ImGui::EndTabItem(); + } + if (ImGui::BeginTabItem(format("%s (%zu)###profilepoints", STR_C("Points"), state.line.points.size()).c_str())) + { + ImGui::BeginChild("##profilepointlist"); + render_profile_points(); + ImGui::EndChild(); + ImGui::EndTabItem(); + } + bool const errors{has_errors(state.issues)}; + if (false == state.issues.empty()) + ImGui::PushStyleColor(ImGuiCol_Text, errors ? ImVec4(1.0f, 0.45f, 0.4f, 1.0f) : ImVec4(1.0f, 0.8f, 0.3f, 1.0f)); + bool const remarks{ImGui::BeginTabItem(format("%s (%zu)###profileremarks", STR_C("Remarks"), state.issues.size()).c_str(), nullptr, state.show_remarks ? ImGuiTabItemFlags_SetSelected : 0)}; + state.show_remarks = false; + if (false == state.issues.empty()) + ImGui::PopStyleColor(); + if (remarks) + { + render_profile_issues(); + ImGui::EndTabItem(); + } + ImGui::EndTabBar(); } - if (ImGui::BeginTabItem(format("%s (%zu)###profilepoints", STR_C("Points"), state.line.points.size()).c_str())) - { - ImGui::BeginChild("##profilepointlist"); - render_profile_points(); - ImGui::EndChild(); - ImGui::EndTabItem(); - } - bool const errors{has_errors(state.issues)}; - if (false == state.issues.empty()) - ImGui::PushStyleColor(ImGuiCol_Text, errors ? ImVec4(1.0f, 0.45f, 0.4f, 1.0f) : ImVec4(1.0f, 0.8f, 0.3f, 1.0f)); - bool const remarks{ImGui::BeginTabItem(format("%s (%zu)###profileremarks", STR_C("Remarks"), state.issues.size()).c_str())}; - if (false == state.issues.empty()) - ImGui::PopStyleColor(); - if (remarks) - { - render_profile_issues(); - ImGui::EndTabItem(); - } - ImGui::EndTabBar(); + ImGui::EndChild(); } - ImGui::EndChild(); } ImGui::End(); } -void editor_mode::render_profile_source() +void editor_mode::render_profile_header() +{ + auto &state{m_profile}; + auto const errors{std::count_if(state.issues.begin(), state.issues.end(), [](profile::issue const &Issue) { return Issue.error; })}; + auto const warnings{static_cast(state.issues.size()) - errors}; + if (ImGui::Button(STR_C("From the track"))) + { + profile_recognize(); + state.changed = true; + } + item_tooltip("The points of the grade line read from the track as it lies now"); + ImGui::SameLine(); + if (ImGui::Button(STR_C("To the ground"))) + { + profile_fit_ground(); + state.changed = true; + } + item_tooltip("Places the breaks of the grade line along the ground under the route,\nwithin the limits and with the least earthworks; the ground itself stays as it is"); + ImGui::SameLine(0.0f, 2.0f); + ImGui::SetNextItemWidth(ImGui::CalcTextSize("+00.00 m").x + ImGui::GetStyle().FramePadding.x * 2.0f); + ImGui::DragScalar("##fittolerance", ImGuiDataType_Double, &state.fit.tolerance, 0.05f, nullptr, nullptr, STR_C("+-%.2f m")); + state.fit.tolerance = std::clamp(state.fit.tolerance, 0.05, 50.0); + item_tooltip("How far the grade line may depart from the ground before it breaks;\nmore gives fewer breaks and higher embankments and deeper cuttings"); + ImGui::SameLine(0.0f, ImGui::GetFontSize()); + // the state of the grade line against the limits; a click lists the remarks + std::string chip; + ImVec4 colour; + if (errors > 0) + { + chip = warnings > 0 ? format(STR_C("%d errors, %d warnings"), static_cast(errors), static_cast(warnings)) : format(STR_C("%d errors"), static_cast(errors)); + colour = ImVec4(1.0f, 0.45f, 0.38f, 1.0f); + } + else if (warnings > 0) + { + chip = format(STR_C("%d warnings"), static_cast(warnings)); + colour = ImVec4(1.0f, 0.8f, 0.3f, 1.0f); + } + else + { + chip = STR_C("Within the limits"); + colour = ImVec4(0.45f, 0.9f, 0.45f, 1.0f); + } + if (state_chip((chip + "###profilestate").c_str(), colour)) + state.show_remarks = true; + item_tooltip(state.issues.empty() ? "The grade line meets the limits of the line" : "Click: the list of the remarks; a click on a remark shows its place"); + // apply at the right end, as far as there's room + auto const label{std::string{STR_C("Apply to the scenery")} + (state.departure > 0.0005 ? " *" : "")}; + auto const button{ImGui::CalcTextSize(label.c_str()).x + ImGui::GetStyle().FramePadding.x * 2.0f}; + auto const right{ImGui::GetWindowContentRegionMax().x - button}; + ImGui::SameLine(0.0f, ImGui::GetFontSize()); + if (ImGui::GetCursorPosX() < right) + ImGui::SetCursorPosX(right); + ImGui::BeginDisabled(errors > 0); + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.2f, 0.55f, 0.25f, 1.0f)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.25f, 0.68f, 0.3f, 1.0f)); + if (ImGui::Button((label + "###profileapply").c_str())) + profile_apply(true); + ImGui::PopStyleColor(2); + ImGui::EndDisabled(); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) + { + if (errors > 0) + ImGui::SetTooltip("%s", STR_C("Correct the errors first: the red remarks, a click on the state shows them")); + else if (state.departure > 0.0005) + ImGui::SetTooltip(STR_C("Sets the heights of the track along the route to the grade line, the track moves by up to %.3f m; Ctrl+Z takes it back"), state.departure); + else + ImGui::SetTooltip("%s", STR_C("The track lies on the grade line already")); + } + if (false == state.error.empty()) + ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.3f, 1.0f), "%s", state.error.c_str()); +} + +void editor_mode::render_profile_empty() { auto &state{m_profile}; auto *selected{selected_track()}; - if (ImGui::Button(STR_C("Along the line from the selected path")) && selected != nullptr) - profile_open_run(*selected); - ImGui::SameLine(); - ImGui::PushItemWidth(70.0f); - ImGui::DragScalar(STR_C("m each way"), ImGuiDataType_Double, &state.run_length, 10.0f, nullptr, nullptr, "%.0f"); - ImGui::PopItemWidth(); - state.run_length = std::clamp(state.run_length, 10.0, 50000.0); - if (ImGui::Button(STR_C("Start: selected path")) && selected != nullptr) - state.picked_from = selected; - ImGui::SameLine(); - if (ImGui::Button(STR_C("End: selected path")) && selected != nullptr && state.picked_from != nullptr) - profile_open(state.picked_from, selected); + auto const available{ImGui::GetContentRegionAvail()}; + auto *draw{ImGui::GetWindowDrawList()}; + auto const line{ImGui::GetTextLineHeight()}; + auto const mouse{std::round(line * 2.6f)}; + auto const headline{std::string{STR_C("Click a track in the view")}}; + auto const detail{std::string{STR_C("The grade line of its whole line shows here; Shift+LMB on more tracks or Shift+drag a box: the route from one end of them to the other. Drag the points of the line up and down, then apply it to the scenery.")}}; + auto const wrap{std::min(available.x - 40.0f, 560.0f)}; + auto const top{ImGui::GetCursorScreenPos().y + std::max(0.0f, available.y * 0.5f - mouse - line * 2.0f)}; + auto const left{ImGui::GetCursorScreenPos().x + std::max(0.0f, (available.x - wrap) * 0.5f)}; + gesture_mouse(*draw, ImVec2(left, top), mouse, "LMB"); + auto *font{ui_layer::font_bold != nullptr ? ui_layer::font_bold : ImGui::GetFont()}; + auto const big{ui_layer::font_bold != nullptr ? ui_layer::font_bold->FontSize : ImGui::GetFontSize() * 1.2f}; + auto const textleft{left + mouse * 0.68f + line}; + draw->AddText(font, big, ImVec2(textleft, top + line * 0.2f), ImGui::GetColorU32(ImGuiCol_Text), headline.c_str()); + draw->AddText(ImGui::GetFont(), ImGui::GetFontSize(), ImVec2(textleft, top + big + line * 0.6f), ImGui::GetColorU32(ImGuiCol_TextDisabled), detail.c_str(), nullptr, wrap - (textleft - left)); + auto const detailsize{ImGui::CalcTextSize(detail.c_str(), nullptr, false, wrap - (textleft - left))}; + ImGui::SetCursorScreenPos(ImVec2(textleft, std::max(top + mouse, top + big + line * 0.6f + detailsize.y) + line)); + if (selected != nullptr) + { + if (ImGui::Button(format(STR_C("Along the line of %s"), selected->name().c_str()).c_str())) + profile_open_run(*selected); + ImGui::SameLine(); + } + profile_library_load(); + if (false == m_profiles.empty() && ImGui::Button(format(STR_C("Designs kept in the scenery (%zu)..."), m_profiles.size()).c_str())) + ImGui::OpenPopup("##profilekept"); + if (ImGui::BeginPopup("##profilekept")) + { + for (std::size_t i = 0; i < m_profiles.size(); ++i) + { + auto const &entry{m_profiles[i]}; + ImGui::PushID(static_cast(i)); + if (ImGui::Selectable(format(STR_P("%s %.1f m, %zu point", "%s %.1f m, %zu points", entry.line.points.size()), scene::Layers.layer(entry.layer).name.c_str(), entry.length, entry.line.points.size()).c_str())) + profile_open_stored(i); + ImGui::PopID(); + } + ImGui::EndPopup(); + } + if (false == state.error.empty()) + { + ImGui::SetCursorScreenPos(ImVec2(textleft, ImGui::GetCursorScreenPos().y)); + ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.3f, 1.0f), "%s", state.error.c_str()); + } +} + +void editor_mode::render_profile_source() +{ + gesture_rows({{"LMB on a track", "its whole line"}, {"Shift+LMB on more tracks", "the route between the outermost ones"}, {"Shift+drag a box", "the route over the tracks in it"}}); profile_library_load(); if (false == m_profiles.empty() && ImGui::TreeNode("##profilestored", STR_C("Designs kept in the scenery (%zu)"), m_profiles.size())) { @@ -1053,7 +2177,7 @@ void editor_mode::render_profile_source() if (ImGui::SmallButton(STR_C("Open"))) profile_open_stored(i); ImGui::SameLine(); - ImGui::Text(STR_C("%s %.1f m, %zu points, from (%.1f, %.1f) to (%.1f, %.1f)"), scene::Layers.layer(entry.layer).name.c_str(), entry.length, entry.line.points.size(), entry.start.x, entry.start.z, entry.end.x, entry.end.z); + ImGui::Text(STR_P("%s %.1f m, %zu point, from (%.1f, %.1f) to (%.1f, %.1f)", "%s %.1f m, %zu points, from (%.1f, %.1f) to (%.1f, %.1f)", entry.line.points.size()), scene::Layers.layer(entry.layer).name.c_str(), entry.length, entry.line.points.size(), entry.start.x, entry.start.z, entry.end.x, entry.end.z); ImGui::PopID(); } ImGui::TreePop(); @@ -1065,11 +2189,19 @@ bool editor_mode::render_profile_parameters() auto &state{m_profile}; auto &line{state.line}; bool changed{false}; - auto const drag = [](char const *Label, double &Value, float const Speed, char const *Format) { return ImGui::DragScalar(STR_C(Label), ImGuiDataType_Double, &Value, Speed, nullptr, nullptr, Format); }; - ImGui::PushItemWidth(120.0f); - drag("Chainage of the start (m)", state.origin, 1.0f, "%.2f"); - changed |= drag("Design speed (km/h)", line.speed, 1.0f, "%.0f"); - ImGui::PopItemWidth(); + auto const drag = [](char const *Label, double &Value, float const Speed, char const *Format) { + field_row(Label); + ImGui::PushID(Label); + auto const edited{ImGui::DragScalar("##value", ImGuiDataType_Double, &Value, Speed, nullptr, nullptr, Format)}; + ImGui::PopID(); + return edited; + }; + if (begin_fields("##profileline", 0.5f)) + { + drag("Chainage of the start (m)", state.origin, 1.0f, "%.2f"); + changed |= drag("Design speed (km/h)", line.speed, 1.0f, "%.0f"); + ImGui::EndTable(); + } line.speed = std::max(1.0, line.speed); auto const join_tooltip = [] { if (ImGui::IsItemHovered()) @@ -1085,18 +2217,31 @@ bool editor_mode::render_profile_parameters() changed |= ImGui::Checkbox(STR_C("Join the adjoining track at the end"), &line.join_end); join_tooltip(); } - if (ImGui::TreeNode(STR_C("Limits"))) + if (ImGui::TreeNode(STR_C("Norms"))) { auto &norms{line.norms}; - ImGui::PushItemWidth(90.0f); - changed |= drag("Maximum grade (per mille)", norms.grade_max, 0.1f, "%.2f"); - changed |= drag("Maximum grade over switches (per mille)", norms.grade_switch_max, 0.1f, "%.2f"); - changed |= drag("Vertical curve R >= k*V^2, k", norms.radius_factor, 0.01f, "%.2f"); - changed |= drag("Vertical curve R min (m)", norms.radius_min, 10.0f, "%.0f"); - changed |= drag("Vertical curve needed above a change of (per mille)", norms.curve_threshold, 0.1f, "%.2f"); - changed |= drag("Constant grade between curves at least (m)", norms.element_min, 1.0f, "%.0f"); - changed |= drag("Tolerance at fixed points (m)", norms.fixed_tolerance, 0.001f, "%.3f"); - ImGui::PopItemWidth(); + auto const table{begin_fields("##profilelimits", 0.6f)}; + changed |= table && drag("Maximum grade (per mille)", norms.grade_max, 0.1f, "%.2f"); + if (table) + { + changed |= drag("Maximum grade over switches (per mille)", norms.grade_switch_max, 0.1f, norms.grade_switch_max > 0.0 ? "%.2f" : STR_C("as the line")); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("0: the limit of the line, a switch may lie on its grade.\nA lower one for the tracks of a station where the vehicles stand, e.g. 2.5")); + changed |= drag("Vertical curve R >= k*V^2, k", norms.radius_factor, 0.01f, "%.2f"); + item_tooltip("The required radius of a vertical curve grows with the square of the design speed: R = k * V^2, V in km/h"); + changed |= drag("Vertical curve R min (m)", norms.radius_min, 10.0f, "%.0f"); + item_tooltip("A vertical curve is never smaller than this, even at a low speed"); + changed |= drag("Vertical curve needed above a change of (per mille)", norms.curve_threshold, 0.1f, "%.2f"); + item_tooltip("A smaller change of grade may stay a sharp break, without a curve"); + changed |= drag("Constant grade between curves at least (m)", norms.element_min, 1.0f, "%.0f"); + item_tooltip("The shortest stretch of one grade between two vertical curves; 0: not checked"); + changed |= drag("Tolerance at fixed points (m)", norms.fixed_tolerance, 0.001f, "%.3f"); + item_tooltip("How far the grade line may pass from a fixed point, e.g. the joint with the adjoining track, before it's reported"); + ImGui::EndTable(); + } + norms.grade_switch_max = std::max(0.0, norms.grade_switch_max); + norms.radius_factor = std::max(0.0, norms.radius_factor); + norms.radius_min = std::max(10.0, norms.radius_min); if (ImGui::SmallButton(STR_C("Automatic R at all points"))) { for (auto &point : line.points) @@ -1106,48 +2251,21 @@ bool editor_mode::render_profile_parameters() ImGui::TextDisabled(STR_C("Required R for %.0f km/h: %.0f m"), line.speed, profile::required_radius(line)); ImGui::TreePop(); } - - ImGui::Separator(); auto const errors{std::count_if(state.issues.begin(), state.issues.end(), [](profile::issue const &Issue) { return Issue.error; })}; auto const warnings{static_cast(state.issues.size()) - errors}; - if (errors > 0) - ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.3f, 1.0f), STR_C("%d errors, %d warnings: see the Remarks in the strip"), static_cast(errors), static_cast(warnings)); - else if (warnings > 0) - ImGui::TextColored(ImVec4(1.0f, 0.8f, 0.3f, 1.0f), STR_C("%d warnings: see the Remarks in the strip"), static_cast(warnings)); + ImGui::PushTextWrapPos(0.0f); + auto const good{IM_COL32(100, 230, 100, 255)}; + ImGui::BeginGroup(); + metric_tiles({{format("%d", static_cast(errors)), STR_C("errors"), errors > 0 ? IM_COL32(255, 100, 80, 255) : good}, + {format("%d", static_cast(warnings)), STR_C("warnings"), warnings > 0 ? IM_COL32(255, 200, 80, 255) : good}, + {format("%.3f m", state.departure), STR_C("off the track"), ImGui::GetColorU32(ImGuiCol_Text)}}); + ImGui::EndGroup(); + item_tooltip("From the track, To the ground and Apply to the scenery are over the plot of the strip"); + if (errors + warnings > 0) + ImGui::TextDisabled("%s", STR_C("The list of them: Remarks in the strip under the view")); else ImGui::TextColored(ImVec4(0.4f, 0.9f, 0.4f, 1.0f), "%s", STR_C("The grade line meets the limits")); - ImGui::TextDisabled(STR_C("Largest departure from the track: %.3f m"), state.departure); - if (ImGui::Button(STR_C("Recognize from the track"))) - { - profile_recognize(); - state.changed = true; - } - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", STR_C("Sets the points of the grade line from the existing track")); - ImGui::SameLine(); - if (ImGui::Button(STR_C("Fit to the ground"))) - { - profile_fit_ground(); - state.changed = true; - } - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", STR_C("Places the breaks of the grade line along the ground under the route,\nwithin the limits and with the least earthworks; the ground itself stays as it is")); - ImGui::PushItemWidth(70.0f); - ImGui::DragScalar(STR_C("m off the ground##fittolerance"), ImGuiDataType_Double, &state.fit.tolerance, 0.05f, nullptr, nullptr, "%.2f"); - ImGui::PopItemWidth(); - state.fit.tolerance = std::clamp(state.fit.tolerance, 0.05, 50.0); - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", STR_C("How far the grade line may depart from the ground before it breaks;\nmore gives fewer breaks and higher embankments and deeper cuttings")); - ImGui::SameLine(); - ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.2f, 0.55f, 0.25f, 1.0f)); - ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.25f, 0.68f, 0.3f, 1.0f)); - if (ImGui::Button(STR_C("Apply to the scenery"), ImVec2(-1.0f, 0.0f))) - profile_apply(); - ImGui::PopStyleColor(2); - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", STR_C("Sets the heights of the track along the route to the grade line, Ctrl+Z takes it back")); - ImGui::Separator(); - render_profile_earthworks(); + ImGui::PopTextWrapPos(); return changed; } @@ -1191,7 +2309,13 @@ void editor_mode::render_profile_point() auto const count{static_cast(points.size())}; if (state.selected >= count) state.selected = -1; - auto const drag = [](char const *Label, double &Value, float const Speed, char const *Format) { return ImGui::DragScalar(STR_C(Label), ImGuiDataType_Double, &Value, Speed, nullptr, nullptr, Format); }; + auto const drag = [](char const *Label, double &Value, float const Speed, char const *Format) { + field_row(Label); + ImGui::PushID(Label); + auto const edited{ImGui::DragScalar("##value", ImGuiDataType_Double, &Value, Speed, nullptr, nullptr, Format)}; + ImGui::PopID(); + return edited; + }; auto const kind_of = [](double const Change) { return Change > 0.0 ? STR_C("sag") : STR_C("crest"); }; if (state.selected < 0) { @@ -1205,7 +2329,7 @@ void editor_mode::render_profile_point() ImGui::Text(STR_C("Point %d: joint with the adjoining track"), index + 1); ImGui::Text(STR_C("km %s H %.3f m R %.0f m"), profile::format_chainage(point.chainage + state.origin).c_str(), point.elevation, point.radius); ImGui::Text(STR_C("Grade %+.2f -> %+.2f per mille (%s)"), profile::grade_after(state.line, index - 1) * 1000.0, profile::grade_after(state.line, index) * 1000.0, kind_of(change)); - ImGui::TextWrapped("%s", STR_C("Placed automatically, moves with the neighbouring point; untick the joining in the inspector to edit the end freely")); + ImGui::TextWrapped("%s", STR_C("Placed automatically, moves with the neighbouring point; untick the joining in the tool options to edit the end freely")); } else { @@ -1216,54 +2340,66 @@ void editor_mode::render_profile_point() ImGui::Text(STR_C("Point %d"), index + 1); ImGui::SameLine(); ImGui::TextDisabled(STR_C("km %s%s"), profile::format_chainage(point.chainage + state.origin).c_str(), locked ? STR_C(", joined to the adjoining track") : end ? STR_C(", end of the route") : ""); - ImGui::PushItemWidth(std::max(90.0f, ImGui::GetContentRegionAvail().x * 0.4f)); - auto chainage{point.chainage + state.origin}; - if (false == end && drag("Chainage (m)", chainage, 0.5f, "%.2f")) + if (begin_fields("##profilepoint", 0.45f)) { - point.chainage = std::clamp(chainage - state.origin, points[index - 1].chainage + 0.5, points[index + 1].chainage - 0.5); - changed = true; - } - if (locked) - ImGui::Text(STR_C("Elevation %.3f m"), point.elevation); - else - changed |= drag("Elevation (m)", point.elevation, 0.01f, "%.3f"); - if (index > 0 && false == locked) - { - auto grade{profile::grade_after(state.line, index - 1) * 1000.0}; - if (drag("Grade before (per mille)", grade, 0.05f, "%+.2f")) + auto chainage{point.chainage + state.origin}; + if (false == end && drag("Chainage (m)", chainage, 0.5f, "%.2f")) { - point.elevation = points[index - 1].elevation + grade / 1000.0 * (point.chainage - points[index - 1].chainage); + point.chainage = std::clamp(chainage - state.origin, points[index - 1].chainage + 0.5, points[index + 1].chainage - 0.5); changed = true; } - } - if (index + 1 < count) - { - auto grade{profile::grade_after(state.line, index) * 1000.0}; - if (drag("Grade after (per mille)", grade, 0.05f, "%+.2f")) + if (locked) { - points[index + 1].elevation = point.elevation + grade / 1000.0 * (points[index + 1].chainage - point.chainage); - changed = true; + field_row("Elevation (m)"); + ImGui::Text("%.3f", point.elevation); } - } - if (false == end) - { - if (drag("Vertical curve R (m)", point.radius, 10.0f, "%.0f")) + else + changed |= drag("Elevation (m)", point.elevation, 0.01f, "%.3f"); + if (index > 0 && false == locked) { - point.automatic = false; - changed = true; + auto grade{profile::grade_after(state.line, index - 1) * 1000.0}; + if (drag("Grade before (per mille)", grade, 0.05f, "%+.2f")) + { + point.elevation = points[index - 1].elevation + grade / 1000.0 * (point.chainage - points[index - 1].chainage); + changed = true; + } } - point.radius = std::max(0.0, point.radius); - ImGui::SameLine(); - changed |= ImGui::Checkbox(STR_C("auto"), &point.automatic); - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", STR_C("R follows the limits: the required radius where the change of grade needs a curve; 0: no curve")); - auto const change{(profile::grade_after(state.line, index) - profile::grade_after(state.line, index - 1)) * 1000.0}; - auto const tangent{point.radius * std::abs(change) / 2000.0}; - ImGui::TextDisabled(STR_C("Change of grade %+.2f per mille, %s"), change, kind_of(change)); - if (point.radius > 0.0) - ImGui::TextDisabled(STR_C("Tangent T %.2f m, sagitta f %.3f m"), tangent, tangent * tangent / (2.0 * point.radius)); + if (index + 1 < count) + { + auto grade{profile::grade_after(state.line, index) * 1000.0}; + if (drag("Grade after (per mille)", grade, 0.05f, "%+.2f")) + { + points[index + 1].elevation = point.elevation + grade / 1000.0 * (points[index + 1].chainage - point.chainage); + changed = true; + } + } + if (false == end) + { + field_row("Vertical curve R (m)"); + auto const box{ImGui::GetFrameHeight() + ImGui::GetStyle().ItemInnerSpacing.x + ImGui::CalcTextSize(STR_C("auto")).x}; + ImGui::SetNextItemWidth(std::max(40.0f, ImGui::GetContentRegionAvail().x - box - ImGui::GetStyle().ItemSpacing.x)); + if (ImGui::DragScalar("##pointradius", ImGuiDataType_Double, &point.radius, 10.0f, nullptr, nullptr, "%.0f")) + { + point.automatic = false; + changed = true; + } + if (ImGui::IsItemHovered()) + { + auto const change{(profile::grade_after(state.line, index) - profile::grade_after(state.line, index - 1)) * 1000.0}; + auto const tangent{point.radius * std::abs(change) / 2000.0}; + auto text{std::string{STR_C("The radius of the vertical curve which rounds off the break of the grade here")} + "\n" + format(STR_C("Change of grade %+.2f per mille, %s"), change, kind_of(change))}; + if (point.radius > 0.0) + text += "\n" + format(STR_C("Tangent T %.2f m, sagitta f %.3f m"), tangent, tangent * tangent / (2.0 * point.radius)); + ImGui::SetTooltip("%s", text.c_str()); + } + point.radius = std::max(0.0, point.radius); + ImGui::SameLine(); + changed |= ImGui::Checkbox(STR_C("auto"), &point.automatic); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("R follows the limits: the required radius where the change of grade needs a curve; 0: no curve")); + } + ImGui::EndTable(); } - ImGui::PopItemWidth(); if (index + 1 < count && ImGui::Button(STR_C("Add a point after"))) { profile::pvi inserted; @@ -1278,9 +2414,8 @@ void editor_mode::render_profile_point() ImGui::SameLine(); if (ImGui::Button(STR_C("Remove Del"))) { - points.erase(points.begin() + index); - state.selected = -1; - changed = true; + profile_remove_point(index); + return; } } } @@ -1363,53 +2498,96 @@ struct editor_mode::profile_view void editor_mode::render_profile_toolbar() { auto &state{m_profile}; - auto *draw{ImGui::GetWindowDrawList()}; - auto const swatch = [&](ImU32 const Colour) { - auto const at{ImGui::GetCursorScreenPos()}; - auto const height{ImGui::GetFrameHeight()}; - draw->AddLine(ImVec2(at.x, at.y + height * 0.5f), ImVec2(at.x + 16.0f, at.y + height * 0.5f), Colour, 3.0f); - ImGui::Dummy(ImVec2(16.0f, height)); - ImGui::SameLine(0.0f, 4.0f); + // the next item on the same line while it fits, past the edge of the plot on the next one + auto const edge{ImGui::GetWindowPos().x + ImGui::GetWindowContentRegionMax().x}; + auto const next = [&](float const Gap, float const Width) { + ImGui::SameLine(0.0f, Gap); + if (ImGui::GetCursorScreenPos().x + Width > edge) + ImGui::NewLine(); }; - auto const legend = [&](ImU32 const Colour, char const *Label) { - swatch(Colour); - ImGui::AlignTextToFramePadding(); - ImGui::TextUnformatted(STR_C(Label)); - ImGui::SameLine(0.0f, 14.0f); - }; - auto const toggle = [&](ImU32 const Colour, char const *Label, bool &Value) { - swatch(Colour); - ImGui::Checkbox(STR_C(Label), &Value); - ImGui::SameLine(0.0f, 14.0f); - }; - legend(kGradeLine, "Grade line"); - legend(kTangents, "Tangents"); - toggle(kTrack, STR_C("Track"), state.show_track); - toggle(kTerrain, STR_C("Terrain"), state.show_terrain); - toggle(kPlan, STR_C("Plan curvature"), state.show_plan); - legend(kSwitchLabel, "Switches"); - ImGui::SetNextItemWidth(130.0f); + auto const pill = [](char const *Label) { return ImGui::CalcTextSize(Label).x + ImGui::GetFrameHeight() * 1.75f; }; + ImGui::AlignTextToFramePadding(); + ImGui::TextDisabled("%s", STR_C("Show:")); + next(ImGui::GetStyle().ItemSpacing.x, pill(STR_C("Track"))); + pill_toggle(STR_C("Track"), kTrack, state.show_track); + next(4.0f, pill(STR_C("Terrain"))); + pill_toggle(STR_C("Terrain"), kTerrain, state.show_terrain); + if (m_nmt.placed()) + { + next(4.0f, pill(STR_C("Terrain model"))); + if (pill_toggle(STR_C("Terrain model"), kModel, state.show_model)) + profile_sample_model(); + item_tooltip(state.model_waiting ? "The ground of the terrain model (NMT) as it was measured, before the earthworks; its squares along the route are still being fetched" + : "The ground of the terrain model (NMT) as it was measured, before the earthworks"); + } + next(4.0f, pill(STR_C("Plan curvature"))); + pill_toggle(STR_C("Plan curvature"), kPlan, state.show_plan); + next(6.0f, ImGui::CalcTextSize("(?)").x); + ImGui::TextDisabled("(?)"); + if (ImGui::IsItemHovered()) + { + ImGui::BeginTooltip(); + ImGui::TextUnformatted(STR_C("Legend")); + ImGui::Separator(); + auto *draw{ImGui::GetWindowDrawList()}; + auto const entry = [&](ImU32 const Colour, char const *Label) { + auto const at{ImGui::GetCursorScreenPos()}; + auto const height{ImGui::GetTextLineHeight()}; + draw->AddLine(ImVec2(at.x, at.y + height * 0.5f), ImVec2(at.x + 22.0f, at.y + height * 0.5f), Colour, 3.0f); + ImGui::Dummy(ImVec2(22.0f, height)); + ImGui::SameLine(0.0f, 8.0f); + ImGui::TextUnformatted(STR_C(Label)); + }; + entry(kGradeLine, "Grade line"); + entry(kTangents, "Tangents"); + entry(kTrack, "Track"); + entry(kTerrain, "Terrain"); + entry(kFormation, "Formation"); + entry(kModel, "Terrain model"); + entry(kPlan, "Plan curvature"); + entry(kSwitchLabel, "Switches"); + entry(kSharedEdge, "Shared timbers"); + entry(kError, "Errors"); + entry(kWarning, "Warnings"); + ImGui::EndTooltip(); + } + next(14.0f, 120.0f); + ImGui::SetNextItemWidth(120.0f); ImGui::SliderFloat("##exaggeration", &state.exaggeration, 1.0f, 500.0f, STR_C("heights x%.0f"), ImGuiSliderFlags_Logarithmic); if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", STR_C("Exaggeration of the heights against the lengths, also Ctrl+wheel over the plot")); - ImGui::SameLine(); + next(ImGui::GetStyle().ItemSpacing.x, ImGui::CalcTextSize(STR_C("Fit")).x + ImGui::GetStyle().FramePadding.x * 2.0f); if (ImGui::Button(STR_C("Fit"))) profile_fit_view(); if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", STR_C("Shows the whole route")); + // the camera and the plot brought to one another only when asked: the camera doesn't turn as the plot is zoomed + auto const button = [](char const *Label) { return ImGui::CalcTextSize(Label).x + ImGui::GetStyle().FramePadding.x * 2.0f; }; + next(14.0f, button(STR_C("Camera to the plot"))); + if (ImGui::Button(STR_C("Camera to the plot"))) + profile_frame_view(); + item_tooltip("Moves the camera to the part of the route the plot shows"); + next(ImGui::GetStyle().ItemSpacing.x, button(STR_C("Plot to the camera"))); + if (ImGui::Button(STR_C("Plot to the camera"))) + profile_to_camera(); + item_tooltip("Moves the plot to the part of the route where the camera is, its zoom kept"); } void editor_mode::render_profile_canvas(float const Height) { auto &state{m_profile}; auto const available{ImGui::GetContentRegionAvail()}; - ImVec2 const size{std::max(200.0f, available.x), std::max(100.0f, Height)}; + auto const hintheight{std::round(ImGui::GetTextLineHeight() * 1.2f)}; + auto const hintrow{hintheight + 8.0f}; + ImVec2 const size{std::max(200.0f, available.x), std::max(100.0f, Height - hintrow)}; ImVec2 const corner{ImGui::GetCursorScreenPos()}; ImGui::InvisibleButton("##profilecanvas", size); bool const hovered{ImGui::IsItemHovered()}; if (state.exaggeration <= 0.0f) profile_fit_exaggeration(profile_view{state, corner, size}); + if (state.model_waiting && ImGui::GetTime() - state.model_polled > 0.5) + profile_sample_model(); profile_navigate(profile_view{state, corner, size}, hovered); profile_view const view{state, corner, size}; if (profile_canvas_edit(view, hovered)) @@ -1428,24 +2606,38 @@ void editor_mode::render_profile_canvas(float const Height) profile_canvas_tooltip(); } - // what the mouse does over the thing under it - char const *hint{"wheel: zoom Ctrl+wheel: heights RMB/MMB drag: pan double click on the line: add a point"}; - if (state.dragging >= 0) - hint = "Ctrl: only the height Shift: keep the grade before"; - else if (state.curve_grip >= 0 || state.hover_grip >= 0) - hint = "drag up or down: radius of the vertical curve"; - else if (state.hover_point >= 0) - hint = "drag: move the point Ctrl+drag: only the height Shift+drag: keep the grade before Del: remove"; - else if (state.hover_line) - hint = "double click: add a point here"; - if (hovered || state.dragging >= 0 || state.curve_grip >= 0) - { - auto const text{std::string{STR_C(hint)}}; - auto const size{ImGui::CalcTextSize(text.c_str())}; - plot_label(*draw, ImVec2(view.bottom_right().x - size.x - 8.0f, view.plot_bottom() - size.y - 6.0f), IM_COL32(255, 255, 255, 230), text); - } draw->PopClipRect(); + // what the mouse does over the thing under it, along the bottom of the plot + std::vector> hints{{"wheel", "zoom"}, {"Ctrl+wheel", "heights"}, {"RMB move", "pan"}, {"LMB LMB", "on the line: add a point"}}; + if (state.dragging >= 0) + hints = {{"Ctrl", "only the height"}, {"Shift", "keep the grade before"}}; + else if (state.curve_grip >= 0 || state.hover_grip >= 0) + hints = {{"LMB move", "up or down: radius of the vertical curve"}}; + else if (state.hover_point >= 0) + hints = {{"LMB move", "move the point"}, {"Ctrl+LMB", "only the height"}, {"Shift+LMB", "keep the grade before"}, {"Del", "remove"}}; + else if (state.hover_line) + hints = {{"LMB LMB", "add a point here"}}; + { + auto const height{hintheight}; + auto x{corner.x + 6.0f}; + auto const y{corner.y + size.y + 4.0f}; + draw->AddRectFilled(ImVec2(corner.x, corner.y + size.y), ImVec2(corner.x + size.x, corner.y + size.y + hintrow), IM_COL32(14, 15, 19, 255)); + draw->PushClipRect(ImVec2(corner.x, corner.y + size.y), ImVec2(corner.x + size.x, corner.y + size.y + hintrow), true); + for (auto const &hint : hints) + { + auto const words{gesture_words(hint.first)}; + auto const text{STR(hint.second)}; + if (x + gesture_width(height, words) + 6.0f + ImGui::CalcTextSize(text.c_str()).x > corner.x + size.x - 6.0f) + break; + x += gesture_draw(*draw, ImVec2(x, y), height, words, kLabel) + 6.0f; + draw->AddText(ImVec2(x, std::round(y + (height - ImGui::GetTextLineHeight()) * 0.5f)), IM_COL32(235, 235, 235, 255), text.c_str()); + x += ImGui::CalcTextSize(text.c_str()).x + 18.0f; + } + draw->PopClipRect(); + } + ImGui::Dummy(ImVec2(size.x, hintrow)); + auto const &points{state.line.points}; if (state.dragging >= 0 && state.dragging < static_cast(points.size())) { @@ -1470,7 +2662,8 @@ void editor_mode::render_profile_canvas(float const Height) void editor_mode::profile_fit_exaggeration(profile_view const &View) { auto &state{m_profile}; - double low{std::numeric_limits::max()}, high{std::numeric_limits::lowest()}; + double low{std::numeric_limits::max()}; + double high{std::numeric_limits::lowest()}; for (auto const &sample : state.samples) { low = std::min(low, sample.position.y); @@ -1482,7 +2675,10 @@ void editor_mode::profile_fit_exaggeration(profile_view const &View) high = std::max(high, point.elevation); } if (low > high) - low = high = 0.0; + { + low = 0.0; + high = 0.0; + } auto const range{std::max(1.0, (high - low) * 1.3)}; state.exaggeration = static_cast(std::clamp(View.across / (range / View.height), 1.0, 500.0)); state.view_centre = (low + high) * 0.5; @@ -1574,9 +2770,20 @@ bool editor_mode::profile_canvas_edit(profile_view const &View, bool const Hover auto const point{hit_point()}; auto const grip{point < 0 ? hit_grip() : -1}; if (point >= 0) - state.selected = state.dragging = point; + { + state.dragging = point; + state.selected = state.dragging; + state.drag_press = mouse; + state.drag_grab = {points[point].chainage - View.chainage_of(mouse.x), points[point].elevation - View.height_of(mouse.y)}; + state.drag_moved = false; + } else if (grip >= 0) - state.selected = state.curve_grip = grip; + { + state.curve_grip = grip; + state.selected = state.curve_grip; + state.drag_press = mouse; + state.drag_moved = false; + } else state.selected = -1; } @@ -1598,47 +2805,47 @@ bool editor_mode::profile_canvas_edit(profile_view const &View, bool const Hover } if (state.dragging >= 0 && state.dragging < static_cast(points.size())) { - if (ImGui::IsMouseDown(0)) + // a click selects the point, it moves only when dragged, by as much as the mouse went + state.drag_moved = state.drag_moved || std::abs(mouse.x - state.drag_press.x) > 3.0f || std::abs(mouse.y - state.drag_press.y) > 3.0f; + if (false == ImGui::IsMouseDown(0)) + state.dragging = -1; + else if (state.drag_moved) { auto const index{state.dragging}; auto &point{points[index]}; bool const end{index == 0 || index + 1 == static_cast(points.size())}; auto const incoming{index > 0 ? profile::grade_after(line, index - 1) : 0.0}; if (false == end && false == io.KeyCtrl) - point.chainage = std::clamp(std::round(View.chainage_of(mouse.x) * 100.0) / 100.0, points[index - 1].chainage + 0.5, points[index + 1].chainage - 0.5); + point.chainage = std::clamp(std::round((View.chainage_of(mouse.x) + state.drag_grab.x) * 100.0) / 100.0, points[index - 1].chainage + 0.5, points[index + 1].chainage - 0.5); if (end_locked(line, state.context, index)) ; else if (io.KeyShift && index > 0) point.elevation = points[index - 1].elevation + incoming * (point.chainage - points[index - 1].chainage); else - point.elevation = std::round(View.height_of(mouse.y) * 1000.0) / 1000.0; + point.elevation = std::round((View.height_of(mouse.y) + state.drag_grab.y) * 1000.0) / 1000.0; changed = true; } - else - state.dragging = -1; } else state.dragging = -1; if (state.curve_grip > 0 && state.curve_grip + 1 < static_cast(points.size())) { - if (ImGui::IsMouseDown(0)) + // a click on the grip leaves the radius as it is + state.drag_moved = state.drag_moved || std::abs(mouse.y - state.drag_press.y) > 3.0f; + if (false == ImGui::IsMouseDown(0)) + state.curve_grip = -1; + else if (state.drag_moved) { auto const sagitta{View.height_of(mouse.y) - points[state.curve_grip].elevation}; points[state.curve_grip].radius = std::max(10.0, std::round(profile::radius_for_sagitta(line, state.curve_grip, sagitta) / 10.0) * 10.0); points[state.curve_grip].automatic = false; changed = true; } - else - state.curve_grip = -1; } else state.curve_grip = -1; if ((Hovered || ImGui::IsWindowFocused()) && state.selected > 0 && state.selected + 1 < static_cast(points.size()) && false == points[state.selected].joint && ImGui::IsKeyPressed(ImGuiKey_Delete)) - { - points.erase(points.begin() + state.selected); - state.selected = -1; - changed = true; - } + profile_remove_point(state.selected); return changed; } @@ -1670,9 +2877,43 @@ void editor_mode::draw_profile_canvas(profile_view const &View, ImDrawList &Draw } for (auto const &zone : state.context.switches) { - Draw.AddRectFilled(ImVec2(View.x_of(zone.from), plottop), ImVec2(std::max(View.x_of(zone.to), View.x_of(zone.from) + 2.0f), plotbottom), kSwitch); - if (View.x_of(zone.to) - View.x_of(zone.from) > 20.0f || View.across < 0.5) - Draw.AddText(ImVec2(View.x_of(zone.from) + 2.0f, plotbottom - 16.0f), kSwitchLabel, zone.name.c_str()); + auto const left{View.x_of(zone.from)}; + auto const right{std::max(View.x_of(zone.to), left + 2.0f)}; + if (zone.name == STR("shared timbers")) + { + // the timbers shared with another track, past a switch or at a crossing: drawn with their bounds, nothing + // breaks the grade over them + Draw.PushClipRect(ImVec2(left, plottop), ImVec2(right, plotbottom), true); + auto const height{plotbottom - plottop}; + for (int k = 0; left - height + 8.0f * static_cast(k) < right; ++k) + { + auto const x{left - height + 8.0f * static_cast(k)}; + Draw.AddLine(ImVec2(x, plotbottom), ImVec2(x + height, plottop), kShared, 1.5f); + } + Draw.PopClipRect(); + Draw.AddLine(ImVec2(left, plottop), ImVec2(left, plotbottom), kSharedEdge, 1.0f); + Draw.AddLine(ImVec2(right, plottop), ImVec2(right, plotbottom), kSharedEdge, 1.0f); + if (right - left > 4.0f) + Draw.AddText(ImVec2(left + 2.0f, plotbottom - 32.0f), kSharedEdge, zone.name.c_str()); + continue; + } + Draw.AddRectFilled(ImVec2(left, plottop), ImVec2(right, plotbottom), kSwitch); + if (right - left > 20.0f || View.across < 0.5) + Draw.AddText(ImVec2(left + 2.0f, plotbottom - 16.0f), kSwitchLabel, zone.name.c_str()); + } + // the ends which inherit the grade line from a switch, said where they are + if (false == state.start_inherits.empty()) + { + auto const x{View.x_of(0.0)}; + Draw.AddLine(ImVec2(x, plottop), ImVec2(x, plotbottom), kSwitchLabel, 2.0f); + Draw.AddText(ImVec2(x + 4.0f, plottop + 18.0f), kSwitchLabel, ("<- " + state.start_inherits).c_str()); + } + if (false == state.end_inherits.empty()) + { + auto const x{View.x_of(state.route.length)}; + auto const text{state.end_inherits + " ->"}; + Draw.AddLine(ImVec2(x, plottop), ImVec2(x, plotbottom), kSwitchLabel, 2.0f); + Draw.AddText(ImVec2(x - 4.0f - ImGui::CalcTextSize(text.c_str()).x, plottop + 34.0f), kSwitchLabel, text.c_str()); } auto const polyline = [&](auto const &Height, ImU32 const Colour, float const Thickness) { @@ -1723,7 +2964,11 @@ void editor_mode::draw_profile_canvas(profile_view const &View, ImDrawList &Draw open = true; } polyline([&](std::size_t const I) { return state.terrain[I]; }, kTerrain, 1.5f); + // the formation under the grade line, which is what meets the ground + polyline([&](std::size_t const I) { return profile::elevation(state.line, samples[I].chainage) - (I < state.beds.size() ? state.beds[I] : 0.0); }, kFormation, 1.0f); } + if (state.show_model && state.model.size() == samples.size()) + polyline([&](std::size_t const I) { return state.model[I]; }, kModel, 1.5f); if (state.show_track) polyline([&](std::size_t const I) { return samples[I].position.y; }, kTrack, 1.5f); @@ -1834,7 +3079,13 @@ void editor_mode::profile_canvas_tooltip() const auto const next{std::lower_bound(samples.begin(), samples.end(), state.hover, [](editor_track::route_sample const &Sample, double const Value) { return Sample.chainage < Value; })}; auto const index{static_cast(std::distance(samples.begin(), std::min(next, std::prev(samples.end()))))}; if (index < state.terrain.size() && false == std::isnan(state.terrain[index])) - ImGui::TextColored(ImGui::ColorConvertU32ToFloat4(kTerrain), STR_C("Terrain %.3f m, %s %.2f m"), state.terrain[index], designed > state.terrain[index] ? STR_C("fill") : STR_C("cut"), std::abs(designed - state.terrain[index])); + { + auto const formation{designed - (index < state.beds.size() ? state.beds[index] : 0.0)}; + ImGui::TextColored(ImGui::ColorConvertU32ToFloat4(kFormation), STR_C("Formation %.3f m, %.2f m under the rail top"), formation, designed - formation); + ImGui::TextColored(ImGui::ColorConvertU32ToFloat4(kTerrain), STR_C("Terrain %.3f m, %s %.2f m"), state.terrain[index], formation > state.terrain[index] ? STR_C("fill") : STR_C("cut"), std::abs(formation - state.terrain[index])); + } + if (state.show_model && index < state.model.size() && false == std::isnan(state.model[index])) + ImGui::TextColored(ImGui::ColorConvertU32ToFloat4(kModel), STR_C("Terrain model %.3f m, the grade line %+.2f m from it"), state.model[index], designed - state.model[index]); auto const &span{state.route.spans[samples[index].span]}; ImGui::TextDisabled("%s%s", span.track->name().c_str(), span.track->eType != tt_Normal ? STR_C(" (switch, tilted as a whole with its branch)") : ""); ImGui::EndTooltip(); @@ -1862,16 +3113,78 @@ void editor_mode::draw_profile_overlay() const previous = next; designedprevious = designed; } + // the tracks sharing the grade line that go with the route + if (state.whole_grade_line) + for (auto const *track : state.beside) + for (auto const &path : track->m_paths) + projection.line(drawlist, path.points[segment_data::point::start], path.points[segment_data::point::end], IM_COL32(70, 170, 255, 200), 2.0f); + // the grade line told in the view: the grades of its straight stretches, the ranges of its vertical curves, its points + glm::dvec3 const eye{Global.pCamera.Pos}; + double constexpr labels_range{1500.0}; + auto const on_line = [&](double const Chainage) { + auto position{editor_track::sampled_position(samples, Chainage)}; + position.y = profile::elevation(state.line, Chainage); + return position; + }; + auto const label = [&](glm::dvec3 const &At, std::string const &Text, ImU32 const Colour) { + ImVec2 screen; + if (glm::distance(At, eye) > labels_range || false == projection.project(At + glm::dvec3{0.0, 1.5, 0.0}, screen)) + return; + auto const size{ImGui::CalcTextSize(Text.c_str())}; + ImVec2 const corner{screen.x - size.x * 0.5f - 4.0f, screen.y - size.y - 4.0f}; + drawlist->AddRectFilled(corner, ImVec2(corner.x + size.x + 8.0f, corner.y + size.y + 4.0f), IM_COL32(20, 20, 24, 190), 3.0f); + drawlist->AddText(ImVec2(corner.x + 4.0f, corner.y + 2.0f), Colour, Text.c_str()); + }; auto const &points{state.line.points}; + auto const curves{profile::curves(state.line)}; + // the straight stretches between the curves + for (std::size_t k = 0; k + 1 < points.size(); ++k) + { + auto from{points[k].chainage}; + auto to{points[k + 1].chainage}; + for (auto const &curve : curves) + { + if (curve.point == k) + from = std::max(from, curve.end); + if (curve.point == k + 1) + to = std::min(to, curve.start); + } + if (to - from < 5.0) + continue; + auto const grade{(points[k + 1].elevation - points[k].elevation) / std::max(1e-6, points[k + 1].chainage - points[k].chainage) * 1000.0}; + label(on_line((from + to) * 0.5), format("%+.2f o/oo L %.0f m", grade, points[k + 1].chainage - points[k].chainage), kGradeLine); + } + // the vertical curves: their range along the track, the ends marked, the radius at the point + for (auto const &curve : curves) + { + glm::dvec3 previouscurve{on_line(curve.start)}; + auto const steps{std::max(2, static_cast((curve.end - curve.start) / 2.0))}; + for (int s = 1; s <= steps; ++s) + { + auto const next{on_line(curve.start + (curve.end - curve.start) * s / steps)}; + projection.line(drawlist, previouscurve, next, kTangents, 5.0f); + previouscurve = next; + } + for (auto const end : {curve.start, curve.end}) + { + auto const at{on_line(end)}; + auto const sample{editor_track::sampled_position(samples, std::min(state.route.length, end + 0.5)) - editor_track::sampled_position(samples, std::max(0.0, end - 0.5))}; + glm::dvec2 across{-sample.z, sample.x}; + across = glm::length(across) > 1e-9 ? glm::normalize(across) * 2.0 : glm::dvec2{2.0, 0.0}; + projection.line(drawlist, at - glm::dvec3{across.x, 0.0, across.y}, at + glm::dvec3{across.x, 0.0, across.y}, kTangents, 2.0f); + } + label(on_line(points[curve.point].chainage) + glm::dvec3{0.0, 1.2, 0.0}, format("R %.0f T %.1f m", points[curve.point].radius, curve.tangent), kTangents); + } for (int i = 0; i < static_cast(points.size()); ++i) { - auto position{editor_track::sampled_position(samples, points[i].chainage)}; - position.y = profile::elevation(state.line, points[i].chainage); + auto const position{on_line(points[i].chainage)}; ImVec2 screen; if (false == projection.project(position, screen)) continue; drawlist->AddCircleFilled(screen, i == state.selected ? 7.0f : 5.0f, overlay_color::marked); drawlist->AddText(ImVec2(screen.x + 8.0f, screen.y - 16.0f), overlay_color::marked, format("%d", i + 1).c_str()); + if (glm::distance(position, eye) <= labels_range * 0.5) + drawlist->AddText(ImVec2(screen.x + 8.0f, screen.y - 2.0f), overlay_color::marked, format("km %s, %.2f m", profile::format_chainage(points[i].chainage + state.origin).c_str(), points[i].elevation).c_str()); } if (state.hover >= 0.0 && state.hover <= state.route.length) { diff --git a/application/editormoderecords.cpp b/application/editormoderecords.cpp new file mode 100644 index 000000000..67498ba73 --- /dev/null +++ b/application/editormoderecords.cpp @@ -0,0 +1,576 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "application/editormode.h" +#include "application/editoruilayer.h" +#include "application/editormodeshared.h" +#include "editor/editorFormat.hpp" +#include "editor/editorAlignmentStore.hpp" +#include "editor/editorSwitchStore.hpp" +#include "editor/editorGeometry.hpp" + +#include "world/Track.h" +#include "scene/scenelayers.h" +#include "simulation/simulation.h" +#include "utilities/Logs.h" +#include "utilities/translation.h" + +#include "imgui/imgui.h" +#include +#include +#include +#include + +namespace +{ + +using geometry::bezier; +using geometry::plan_of; +using geometry::signed_angle; +using geometry::turned; +using path_ends = std::pair; + +struct record_drift +{ + int followed{0}; + int departed{0}; + double departure{0.0}; + double cant{0.0}; + std::string layer; +}; + +glm::dvec2 chord_direction(glm::dvec3 const &Start, glm::dvec3 const &End) +{ + auto const direction{plan_of(End - Start)}; + return glm::length(direction) > 1e-9 ? glm::normalize(direction) : glm::dvec2{0.0, 1.0}; +} + +path_ends const &ends_before(std::vector const &Moving, std::vector const &Before, TTrack const *Track) +{ + return Before[static_cast(std::find(Moving.begin(), Moving.end(), Track) - Moving.begin())]; +} + +bool lies_on(int const Record, TTrack const &Track) +{ + bezier const curve{Track.m_paths.front()}; + std::array constexpr samples{0.0, 0.5, 1.0}; + return std::ranges::all_of(samples, [&](double const T) { return alignment_store::on_record(Record, curve.point(T), alignment_store::tolerance).has_value(); }); +} + +bool covers_record(int const Record, std::vector const &Moving) +{ + for (auto *track : simulation::Paths.sequence()) + if (track != nullptr && false == track->m_editorremoved && track->eType == tt_Normal && false == track->m_paths.empty() && std::find(Moving.begin(), Moving.end(), track) == Moving.end() && lies_on(Record, *track)) + return false; + return true; +} + +bool carried_rigidly(int const Record, std::vector const &Tracks, std::vector const &Moving, std::vector const &Before, record_drift &Drift) +{ + auto const &first{ends_before(Moving, Before, Tracks.front())}; + auto const &path{Tracks.front()->m_paths.front()}; + auto const &start{path.points[segment_data::point::start]}; + auto const from{chord_direction(first.first, first.second)}; + auto const to{chord_direction(start, path.points[segment_data::point::end])}; + auto const angle{signed_angle(from, to)}; + auto const carried = [&](glm::dvec3 const &Old, glm::dvec3 const &Current) { return glm::distance(plan_of(start) + turned(plan_of(Old) - plan_of(first.first), angle), plan_of(Current)) <= 0.01; }; + for (auto const *track : Tracks) + { + auto const &was{ends_before(Moving, Before, track)}; + auto const &now{track->m_paths.front()}; + if (false == carried(was.first, now.points[segment_data::point::start]) || false == carried(was.second, now.points[segment_data::point::end])) + return false; + } + if (glm::distance(first.first, start) > 1e-4 || std::abs(angle) > 1e-7) + { + alignment_store::transform(Record, first.first, from, start, to); + ++Drift.followed; + } + return true; +} + +void measure_departure(int const Record, std::vector const &Tracks, record_drift &Drift) +{ + auto const &records{alignment_store::records()}; + auto const gauge{records[Record].design.norms.gauge}; + for (auto const *track : Tracks) + { + if (track->m_editorremoved) + continue; + auto const &path{track->m_paths.front()}; + bezier const curve{path}; + double largest{0.0}; + for (auto const t : {0.0, 0.5, 1.0}) + { + auto const found{alignment_store::on_record(Record, curve.point(t), 1000.0)}; + largest = std::max(largest, found.has_value() ? found->offset : 1000.0); + } + if (largest > alignment_store::tolerance) + { + ++Drift.departed; + Drift.departure = std::max(Drift.departure, largest); + Drift.layer = scene::Layers.layer(records[Record].layer).name; + continue; + } + for (auto const end : {0, 1}) + if (auto const found{alignment_store::on_record(Record, curve.point(end), alignment_store::tolerance)}) + { + auto const actual{gauge * std::sin(std::abs(glm::radians(static_cast(path.rolls[end]))))}; + Drift.cant = std::max(Drift.cant, std::abs(actual - alignment_store::cant_at(Record, found->chainage))); + } + } +} + +std::vector drift_notes(record_drift const &Drift) +{ + std::vector notes; + if (Drift.followed > 0) + notes.push_back(STR("The kept design of the line went along with its paths")); + if (Drift.departed > 0) + notes.push_back(format(STR_P("%d path left the design kept in %s, by up to %.2f m: Ctrl+Z takes it back, the Plan tool (G) lays it by the design again or forgets the design", + "%d paths left the design kept in %s, by up to %.2f m: Ctrl+Z takes it back, the Plan tool (G) lays them by the design again or forgets it", Drift.departed), + Drift.departed, Drift.layer.c_str(), Drift.departure)); + if (Drift.cant > 5.0) + notes.push_back(format(STR_C("The cant differs from the kept design by up to %.0f mm"), Drift.cant)); + return notes; +} + +switch_store::record switch_entry(editor_track::switch_template const &Shape) +{ + switch_store::record entry; + if (Shape.source == nullptr) + { + entry.type = Shape.type; + entry.rail = Shape.rail; + entry.radius = Shape.radius; + entry.ratio = Shape.ratio; + entry.a = Shape.a; + entry.b = Shape.b; + entry.source = "designed"; + } + else if (auto const known{switch_store::of(*Shape.source)}; known.has_value() && known->kind == "switch") + { + entry = *known; + entry.number = "-"; + } + else + { + // Rz, Rlj or Rld, as classify finds it by the shape + entry.type = "Rz"; + entry.radius = Shape.radius; + entry.ratio = Shape.ratio; + entry.source = "measured"; + } + return entry; +} + +template +bool edit_dashed(char const *Label, std::string &Value) +{ + std::array text{}; + std::snprintf(text.data(), text.size(), "%s", Value == "-" ? "" : Value.c_str()); + if (false == ImGui::InputText(Label, text.data(), text.size(), ImGuiInputTextFlags_EnterReturnsTrue) && false == ImGui::IsItemDeactivatedAfterEdit()) + return false; + Value = text[0] != '\0' ? text.data() : "-"; + return true; +} + +} // namespace + +void editor_mode::records_watch_begin() +{ + auto &watch{m_record_watch}; + watch = {}; + watch.active = true; + watch.moving = m_track_drag; + for (auto const &link : m_track_gizmo_drag.switches) + for (auto const &member : link.cluster) + if (std::find(watch.moving.begin(), watch.moving.end(), member.first) == watch.moving.end()) + watch.moving.push_back(member.first); + for (auto *track : watch.moving) + { + auto const &path{track->m_paths.front()}; + watch.before.emplace_back(path.points[segment_data::point::start], path.points[segment_data::point::end]); + if (track->eType != tt_Normal) + continue; + if (auto const found{alignment_store::on_track(*track)}) + watch.on[found->record].push_back(track); + } + for (auto const &[record, tracks] : watch.on) + if (covers_record(record, watch.moving)) + watch.whole.insert(record); +} + +// what the drag of the gizmo did to the kept alignments and switches: an alignment all of whose paths were moved or turned as a +// whole goes along with them, paths pulled out of an alignment or given another cant are told about, as are switches bent out +// of the shape of their type; switches moved as a whole take their records along +void editor_mode::records_watch_end() +{ + auto &watch{m_record_watch}; + if (false == watch.active) + return; + watch.active = false; + record_drift drift; + for (auto const &[record, tracks] : watch.on) + if (watch.whole.count(record) == 0 || false == carried_rigidly(record, tracks, watch.moving, watch.before, drift)) + measure_departure(record, tracks, drift); + auto notes{drift_notes(drift)}; + switch_store::follow(); + for (auto const *track : watch.moving) + if (track->eType == tt_Switch && false == track->m_editorremoved) + if (auto const known{switch_store::named(*track)}; known.has_value() && false == switch_store::of(*track).has_value()) + notes.push_back(format(STR_C("Switch %s lost the shape of its type %s: Ctrl+Z takes it back"), track->name().c_str(), switch_store::label(*known).c_str())); + records_to_history(); + if (false == notes.empty()) + { + std::string text; + for (auto const ¬e : notes) + text += (text.empty() ? "" : "\n") + note; + ui()->set_status(text, drift.departed > 0 || drift.cant > 5.0 || notes.size() > static_cast(drift.followed > 0 ? 1 : 0)); + WriteLog("Editor: " + text, logtype::generic); + } + watch = {}; +} + +void editor_mode::records_to_history() +{ + auto alignments{alignment_store::take_changes()}; + auto switches{switch_store::take_changes()}; + if (m_history.empty() || m_history.back().action != EditorSnapshot::Action::TrackEdit) + return; + auto &last{m_history.back()}; + if (alignments.has_value() && false == last.alignments.has_value()) + last.alignments = std::move(alignments); + if (switches.has_value() && false == last.switch_records.has_value()) + last.switch_records = std::move(switches); +} + +// the switch is kept in the scenery with its type: of the catalogue template, of the switch of the scenery it was copied +// from, or measured; on a curve it is an arc switch, one-sided when it diverges to the side the curve turns to +void editor_mode::record_switch(TTrack &Track, editor_track::switch_template const &Shape) +{ + if (Track.eType != tt_Switch || Track.m_paths.size() < 2 || Track.name().empty() || scene::Layers.empty()) + return; + auto entry{switch_entry(Shape)}; + entry.kind = "switch"; + entry.name = Track.name(); + entry.parts = {entry.name}; + switch_store::place(entry, Track); + switch_store::classify(entry, Track); + switch_store::put(entry, alignment_store::layer_of(Track)); +} + +// a double switch is kept as one record of its two switches, with the type, the size and the side of the first one +void editor_mode::record_double(TTrack &First, TTrack &Second, editor_track::switch_template const &Shape) +{ + if (First.eType != tt_Switch || Second.eType != tt_Switch || First.m_paths.size() < 2 || First.name().empty() || Second.name().empty() || scene::Layers.empty()) + return; + auto entry{switch_entry(Shape)}; + entry.kind = "double"; + entry.name = First.name(); + entry.parts = {First.name(), Second.name()}; + switch_store::place(entry, First); + switch_store::classify(entry, First); + switch_store::put(entry, alignment_store::layer_of(First)); +} + +void editor_mode::record_connection(connection::kind const Kind, std::vector const &Switches, connection::result const &Plan, editor_track::switch_template const &Shape) +{ + if (Switches.empty() || Switches.front()->eType != tt_Switch || Switches.front()->m_paths.size() < 2 || scene::Layers.empty()) + return; + auto entry{switch_entry(Shape)}; + entry.kind = "connection"; + entry.name = Switches.front()->name(); + for (auto const *track : Switches) + if (track->name().empty()) + return; + else + entry.parts.push_back(track->name()); + switch_store::place(entry, *Switches.front()); + switch_store::classify(entry, *Switches.front()); + entry.type = connection::word(Kind); + entry.a = Plan.spacing; + entry.b = Plan.straights.empty() ? 0.0 : Plan.straights.front(); + switch_store::put(entry, alignment_store::layer_of(*Switches.front())); +} + +std::optional editor_mode::double_of(TTrack const &Track) const +{ + auto const of_switch = [](TTrack const &Switch) -> std::optional { + if (Switch.eType != tt_Switch || Switch.m_editorremoved) + return std::nullopt; + auto const known{switch_store::named(Switch)}; + if (false == known.has_value() || known->kind != "double" || known->parts.size() != 2) + return std::nullopt; + auto *first{simulation::Paths.find(known->parts[0])}; + auto *second{simulation::Paths.find(known->parts[1])}; + for (auto const *part : {first, second}) + if (part == nullptr || part->m_editorremoved || part->eType != tt_Switch || part->m_paths.size() != 2) + return std::nullopt; + if (first == second) + return std::nullopt; + auto const start{second->m_paths.front().points[segment_data::point::start]}; + for (auto const &[other, point] : editor_track::connected_points(*first, first->m_paths.front().points[segment_data::point::end])) + { + if (other->m_editorremoved || other->eType != tt_Normal || other->m_paths.size() != 1) + continue; + auto const &path{other->m_paths.front()}; + auto const opposite{path.points[point.kind == editor_track::point_kind::start ? segment_data::point::end : segment_data::point::start]}; + if (glm::distance(opposite, start) < geometry::same_point) + return double_switch{first, other, second}; + } + return std::nullopt; + }; + if (Track.eType == tt_Switch) + return of_switch(Track); + if (Track.eType != tt_Normal || Track.m_editorremoved || Track.m_paths.size() != 1) + return std::nullopt; + for (auto const index : {segment_data::point::start, segment_data::point::end}) + for (auto const &[other, point] : editor_track::connected_points(Track, Track.m_paths.front().points[index])) + if (other->eType == tt_Switch) + if (auto const found{of_switch(*other)}; found.has_value() && found->link == &Track) + return found; + return std::nullopt; +} + +std::optional editor_mode::slip_of(TTrack const &Track) const +{ + if (Track.m_editorremoved) + return std::nullopt; + auto const record_of = [](TTrack const &Each) -> std::optional { + if (Each.eType != tt_Switch || Each.m_editorremoved) + return std::nullopt; + auto found{switch_store::named(Each)}; + return found.has_value() && found->kind == "slip" ? found : std::nullopt; + }; + // the record of the switch, or of a switch of the slip the track between them is joined to + auto known{record_of(Track)}; + if (false == known.has_value() && Track.eType == tt_Normal && Track.m_paths.size() == 1) + for (auto const index : {segment_data::point::start, segment_data::point::end}) + for (auto const &[other, point] : editor_track::connected_points(Track, Track.m_paths.front().points[index])) + if (false == known.has_value()) + known = record_of(*other); + if (false == known.has_value()) + return std::nullopt; + slip_set slip; + slip.record = *known; + for (auto const &name : known->parts) + { + auto *part{simulation::Paths.find(name)}; + if (part == nullptr || part->m_editorremoved || part->eType != tt_Switch || part->m_paths.size() < 2) + return std::nullopt; + slip.switches.push_back(part); + } + if (slip.switches.size() < 2) + return std::nullopt; + // where the straights of its first and its last switch meet: the joints of its tracks near it are inside the slip, its ends far off + auto const &first{slip.switches.front()->m_paths.front()}; + auto const &last{slip.switches.back()->m_paths.front()}; + auto const a{plan_of(first.points[segment_data::point::start])}; + auto const d{plan_of(last.points[segment_data::point::start])}; + auto const da{editor_track::end_direction(first, editor_track::point_kind::start)}; + auto const dd{editor_track::end_direction(last, editor_track::point_kind::start)}; + double alongfirst, alonglast; + if (false == geometry::lines_cross(a, da, d, dd, alongfirst, alonglast)) + return std::nullopt; + auto const crossing{a + da * alongfirst}; + auto const inside{0.5 * glm::distance(a, crossing)}; + slip.parts = slip.switches; + for (std::size_t i = 0; i < slip.parts.size(); ++i) + for (auto const &path : slip.parts[i]->m_paths) + for (auto const index : {segment_data::point::start, segment_data::point::end}) + { + auto const &position{path.points[index]}; + if (glm::distance(plan_of(position), crossing) > inside) + continue; + for (auto const &[other, point] : editor_track::connected_points(*slip.parts[i], position)) + if (false == other->m_editorremoved && std::find(slip.parts.begin(), slip.parts.end(), other) == slip.parts.end()) + slip.parts.push_back(other); + } + // its ends, each with the way into the slip there + std::vector> ends; + for (auto const *part : slip.parts) + for (auto const &path : part->m_paths) + for (auto const atend : {false, true}) + { + auto const &position{path.points[atend ? segment_data::point::end : segment_data::point::start]}; + if (glm::distance(plan_of(position), crossing) <= inside || + std::any_of(ends.begin(), ends.end(), [&](auto const &End) { return glm::distance(End.first, position) < geometry::same_point; })) + continue; + auto const &control{path.points[atend ? segment_data::point::control2 : segment_data::point::control1]}; + auto const into{plan_of(control != glm::dvec3{} ? control : path.points[atend ? segment_data::point::start : segment_data::point::end] - position)}; + if (glm::length(into) < 1e-9) + return std::nullopt; + ends.emplace_back(position, glm::normalize(into)); + } + if (ends.size() != 4) + return std::nullopt; + // A where its first switch starts, B on along its first track, D where its last switch starts, C the other one + auto const at = [&](glm::dvec2 const &Point) { + return static_cast(std::min_element(ends.begin(), ends.end(), [&](auto const &One, auto const &Other) { return glm::distance(plan_of(One.first), Point) < glm::distance(plan_of(Other.first), Point); }) - + ends.begin()); + }; + auto const ia{at(a)}; + auto const id{at(d)}; + if (ia == id) + return std::nullopt; + std::vector others; + for (std::size_t i = 0; i < 4; ++i) + if (i != ia && i != id) + others.push_back(i); + if (others.size() != 2) + return std::nullopt; + // of the other two the one farther on along the first track + auto const ahead = [&](std::size_t const Index) { return glm::dot(plan_of(ends[Index].first) - crossing, da); }; + auto const ib{ahead(others[0]) >= ahead(others[1]) ? others[0] : others[1]}; + auto const ic{ib == others[0] ? others[1] : others[0]}; + std::size_t const order[]{ia, ib, ic, id}; + for (std::size_t i = 0; i < 4; ++i) + { + slip.ends[i] = ends[order[i]].first; + slip.into[i] = ends[order[i]].second; + } + return slip; +} + +std::vector editor_mode::slip_taken_out(slip_set const &Slip, bool const Throughs) +{ + switch_store::forget(Slip.record.name); + auto &style{*Slip.switches.front()}; + auto const velocity{speed_check::path_velocity(style, 0)}; + for (auto *part : Slip.parts) + editor_track::retire(*part); + std::vector laid; + if (false == Throughs) + return laid; + for (auto const &path : slip_throughs(Slip)) + if (auto *through{editor_track::create_path(style, path)}) + { + editor_track::velocity(*through, velocity); + laid.push_back(through); + } + editor_track::commit(laid); + return laid; +} + +std::optional editor_mode::crossing_record(TTrack const &Track) const +{ + if (Track.eType != tt_Normal || Track.m_editorremoved) + return std::nullopt; + auto const known{switch_store::named(Track)}; + if (false == known.has_value() || known->kind != "crossing" || known->parts.size() != 2) + return std::nullopt; + for (auto const &name : known->parts) + if (auto const *part{simulation::Paths.find(name)}; part == nullptr || part->m_editorremoved || part->eType != tt_Normal || part->m_paths.size() != 1) + return std::nullopt; + return known; +} + +std::array editor_mode::slip_throughs(slip_set const &Slip) +{ + // from end to end, a straight where the slip is one, else heading out of the ends as the slip does + auto const through = [&](std::size_t const From, std::size_t const To) { + segment_data path; + path.points[segment_data::point::start] = Slip.ends[From]; + path.points[segment_data::point::end] = Slip.ends[To]; + auto const chord{plan_of(Slip.ends[To] - Slip.ends[From])}; + auto const length{glm::length(chord)}; + if (length > 1e-6 && std::abs(geometry::cross(Slip.into[From], chord / length)) + std::abs(geometry::cross(Slip.into[To], chord / length)) > 1e-5) + { + auto const handle{length / 3.0}; + auto const rise{Slip.ends[To].y - Slip.ends[From].y}; + path.points[segment_data::point::control1] = {Slip.into[From].x * handle, rise / 3.0, Slip.into[From].y * handle}; + path.points[segment_data::point::control2] = {Slip.into[To].x * handle, -rise / 3.0, Slip.into[To].y * handle}; + path.radius = static_cast(Slip.record.main_radius); + } + return path; + }; + return {through(0, 1), through(2, 3)}; +} + +std::vector editor_mode::double_paths(double_switch const &Set) +{ + auto link{Set.link->m_paths.front()}; + auto const joint{Set.first->m_paths.front().points[segment_data::point::end]}; + if (glm::distance(link.points[segment_data::point::start], joint) > glm::distance(link.points[segment_data::point::end], joint)) + link = geometry::reversed(link); + return {Set.first->m_paths[0], Set.first->m_paths[1], Set.second->m_paths[0], Set.second->m_paths[1], link}; +} + +void editor_mode::record_slip(std::vector const &Parts, std::string const &Kind, std::string const &Type, double const Radius, double const Angle, std::string const &Base, double const Middle) +{ + if (Parts.empty() || scene::Layers.empty()) + return; + switch_store::record entry; + entry.kind = Kind; + entry.name = Base; + entry.type = Type; + entry.radius = Radius; + entry.middle = Middle; + entry.ratio = Angle > 1e-9 ? 1.0 / std::tan(Angle) : 0.0; + for (auto const *part : Parts) + if (part != nullptr && false == part->name().empty() && (Kind == "crossing" || part->eType == tt_Switch)) + entry.parts.push_back(part->name()); + if (entry.parts.empty()) + return; + auto const *first{simulation::Paths.find(entry.parts.front())}; + if (first == nullptr || first->m_paths.empty()) + return; + switch_store::place(entry, *first); + // a slip bent into a curve, as a switch is + entry.main_radius = switch_store::main_radius_of(*first); + switch_store::put(entry, alignment_store::layer_of(*first)); +} + +void editor_mode::render_switch_record(TTrack const &Track) const +{ + auto const known{switch_store::of(Track)}; + if (false == known.has_value()) + { + ImGui::TextDisabled("%s", STR_C("The scenery keeps no type for this switch, it's read from its shape")); + return; + } + auto entry{*known}; + ImGui::Text(STR_C("Type kept in the scenery: %s"), switch_store::label(entry).c_str()); + if (ImGui::IsItemHovered()) + { + std::string text; + if (entry.kind == "switch" && entry.main_radius != 0.0) + text = format(STR_C("Diverging track R %.0f m: the R %.0f m of the type bent with the main track"), switch_store::branch_radius(entry), entry.radius); + if (entry.source == "measured") + text += (text.empty() ? "" : "\n") + std::string{STR_C("The size is measured from the shape of the switch, it's of no template of the catalogue")}; + if (false == text.empty()) + ImGui::SetTooltip("%s", text.c_str()); + } + bool changed{false}; + if (begin_fields("##switchrecord", 0.4f)) + { + field_row("Number##switchnumber"); + changed |= edit_dashed<32>("##switchnumber", entry.number); + item_tooltip("Number of the switch in the station, as the plans of the station give it"); + field_row("Rail##switchrail"); + changed |= edit_dashed<16>("##switchrail", entry.rail); + item_tooltip("Rail of the switch: 60E1, 49E1..."); + auto km{entry.km.has_value() ? *entry.km / 1000.0 : 0.0}; + field_row("Km of the start##switchkm"); + if (ImGui::InputDouble("##switchkm", &km, 0.0, 0.0, "%.3f", ImGuiInputTextFlags_EnterReturnsTrue)) + { + entry.km = km * 1000.0; + changed = true; + } + item_tooltip("Chainage of the start of the switch; taken from the horizontal alignment kept in the scenery when the switch lies on one"); + ImGui::EndTable(); + } + if (changed) + { + switch_store::put(entry, entry.layer); + switch_store::settle(); + } +} diff --git a/application/editormoderide.cpp b/application/editormoderide.cpp new file mode 100644 index 000000000..6e74bffd4 --- /dev/null +++ b/application/editormoderide.cpp @@ -0,0 +1,684 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "application/editormoderide.h" +#include "application/editoruilayer.h" +#include "editor/editorFormat.hpp" +#include "editor/editorKilometrage.hpp" +#include "simulation/simulation.h" +#include "utilities/Logs.h" +#include "utilities/translation.h" +#include "vehicle/Camera.h" +#include "world/Segment.h" +#include "world/Track.h" +#include "imgui/imgui.h" +#include +#include +#include +#include +#include + +namespace track_ride_walk +{ + +namespace +{ + +double plan_length(glm::dvec3 const &Vector) +{ + return std::hypot(Vector.x, Vector.z); +} + +glm::dvec3 plan_unit(glm::dvec3 const &Vector) +{ + auto const length{plan_length(Vector)}; + return length > 1e-9 ? glm::dvec3{Vector.x / length, 0.0, Vector.z / length} : glm::dvec3{0.0}; +} + +glm::dvec3 point_of(TSegment const &Segment, double const Distance) +{ + glm::dvec3 point{0.0}; + glm::vec3 rotation{0.0f}; + Segment.RaPositionGet(std::clamp(Distance, 0.0, Segment.GetLength()), point, rotation); + return point; +} + +// the track goes on there for the camera: there is one, it wasn't removed, it isn't a crossroads of roads +bool passable(TTrack const *Track) +{ + return Track != nullptr && false == Track->m_editorremoved && Track->eType != tt_Cross && segment({const_cast(Track), Track->eType == tt_Switch ? 0 : -1, 0.0}) != nullptr; +} + +// the path of a switch entered from its frog: the one whose end at Point2 is nearest to where the camera came from +int path_from_frog(TTrack const &Switch, glm::dvec3 const &From) +{ + auto best{0}; + auto nearest{std::numeric_limits::max()}; + for (int path = 0; path < Switch.path_count(); ++path) + { + auto const *segment{Switch.path_segment(path)}; + if (segment == nullptr) + continue; + if (auto const distance{glm::distance(point_of(*segment, segment->GetLength()), From)}; distance < nearest) + { + nearest = distance; + best = path; + } + } + return best; +} + +// the next track over the joint at the end the place is moving to (Direction 1: Point2, -1: Point1); Place becomes the +// start of it and Direction the way along it. False where the track ends +bool cross_joint(place &Place, int &Direction, int const Choice, bool &Facing) +{ + auto const *segment{track_ride_walk::segment(Place)}; + if (segment == nullptr) + return false; + auto const exit{point_of(*segment, Direction > 0 ? segment->GetLength() : 0.0)}; + double way{static_cast(Direction)}; + auto *next{Place.track->Connected(Direction, way, Place.track->eType == tt_Switch ? Place.path : -1)}; + if (false == passable(next)) + return false; + auto const direction{way > 0.0 ? 1 : -1}; + auto path{-1}; + if (next->eType == tt_Switch) + { + // both paths of a switch start at its Point1, at the blades + if (direction > 0) + { + path = switch_path(*next, Choice); + Facing = true; + } + else + path = path_from_frog(*next, exit); + } + Place.track = next; + Place.path = path; + Direction = direction; + auto const *entered{track_ride_walk::segment(Place)}; + Place.s = direction > 0 ? 0.0 : entered->GetLength(); + return true; +} + +} // namespace + +TSegment *segment(place const &Place) +{ + if (Place.track == nullptr) + return nullptr; + if (Place.track->eType == tt_Switch) + return Place.track->SwitchExtension != nullptr ? Place.track->path_segment(std::clamp(Place.path, 0, 1)) : nullptr; + return Place.track->Segment.get(); +} + +bool frame(place const &Place, glm::dvec3 &Point, glm::dvec3 &Forward) +{ + auto const *path{segment(Place)}; + if (path == nullptr) + return false; + auto const length{path->GetLength()}; + Point = point_of(*path, Place.s); + // the direction from two points around the place, the same on any kind of path + auto const step{std::min(0.5, std::max(length * 0.5, 1e-3))}; + auto const from{std::max(0.0, Place.s - step)}; + auto const to{std::min(length, Place.s + step)}; + Forward = to > from ? point_of(*path, to) - point_of(*path, from) : glm::dvec3{0.0, 0.0, 1.0}; + auto const size{glm::length(Forward)}; + Forward = size > 1e-9 ? Forward / size : glm::dvec3{0.0, 0.0, 1.0}; + return true; +} + +int switch_path(TTrack const &Switch, int const Choice) +{ + if (Switch.eType != tt_Switch || Switch.SwitchExtension == nullptr) + return -1; + // how much each path turns away from the way in at the blades + double turn[2]{0.0, 0.0}; + for (int path = 0; path < 2; ++path) + { + auto const *segment{Switch.path_segment(path)}; + if (segment == nullptr || segment->GetLength() <= 0.0) + { + turn[path] = std::numeric_limits::max(); + continue; + } + auto const length{segment->GetLength()}; + auto const in{plan_unit(point_of(*segment, std::min(1.0, length * 0.5)) - point_of(*segment, 0.0))}; + auto const out{plan_unit(point_of(*segment, length) - point_of(*segment, std::max(0.0, length - 1.0)))}; + turn[path] = std::acos(std::clamp(glm::dot(in, out), -1.0, 1.0)); + } + auto const straighter{turn[1] < turn[0] ? 1 : 0}; + return (Choice % 2) == 0 ? straighter : 1 - straighter; +} + +halt walk(place &Place, double const Distance, int const Choice, int &Flips, bool &Facing) +{ + Flips = 0; + Facing = false; + if (segment(Place) == nullptr) + return halt::end; + Place.s = std::clamp(Place.s, 0.0, segment(Place)->GetLength()); + auto direction{Distance >= 0.0 ? 1 : -1}; + auto left{std::abs(Distance)}; + // the joints passed in one step; a ring of tracks of no length would hold it here for ever + for (int joint = 0; joint < 10000; ++joint) + { + auto const length{segment(Place)->GetLength()}; + auto const target{Place.s + direction * left}; + if (target >= 0.0 && target <= length) + { + Place.s = target; + return halt::none; + } + left = std::max(0.0, left - (direction > 0 ? length - Place.s : Place.s)); + auto const before{direction}; + if (false == cross_joint(Place, direction, Choice, Facing)) + { + Place.s = direction > 0 ? length : 0.0; + return halt::end; + } + if (direction != before) + ++Flips; + } + return halt::end; +} + +TTrack *facing_switch_ahead(place Place, int Direction, double const Reach, double &Distance) +{ + auto travelled{0.0}; + for (int joint = 0; joint < 1000; ++joint) + { + auto const *path{segment(Place)}; + if (path == nullptr) + return nullptr; + travelled += Direction > 0 ? path->GetLength() - Place.s : Place.s; + if (travelled > Reach) + return nullptr; + auto facing{false}; + if (false == cross_joint(Place, Direction, 0, facing)) + return nullptr; + if (facing) + { + Distance = travelled; + return Place.track; + } + } + return nullptr; +} + +double nearest_distance(TSegment const &Segment, glm::dvec3 const &Point) +{ + auto const length{Segment.GetLength()}; + if (length <= 0.0) + return 0.0; + auto const off = [&](double const Distance) { return plan_length(point_of(Segment, Distance) - Point); }; + auto const steps{std::clamp(static_cast(std::ceil(length / 2.0)), 8, 4000)}; + auto const step{length / steps}; + auto best{0.0}; + auto nearest{std::numeric_limits::max()}; + for (int i = 0; i <= steps; ++i) + { + if (auto const distance{off(i * step)}; distance < nearest) + { + nearest = distance; + best = i * step; + } + } + // golden section within a step on either side + auto low{std::max(0.0, best - step)}; + auto high{std::min(length, best + step)}; + constexpr double ratio{0.6180339887498949}; + for (int i = 0; i < 40 && high - low > 1e-4; ++i) + { + auto const a{high - ratio * (high - low)}; + auto const b{low + ratio * (high - low)}; + if (off(a) < off(b)) + high = b; + else + low = a; + } + return 0.5 * (low + high); +} + +} // namespace track_ride_walk + +namespace +{ + +constexpr double glide_time{0.35}; // s +constexpr double side_reach{20.0}; // m to the track alongside +constexpr double switch_reach{400.0}; // m ahead the switch is shown + +glm::dvec3 plan_right(glm::dvec3 const &Forward) +{ + auto const length{std::hypot(Forward.x, Forward.z)}; + return length > 1e-9 ? glm::dvec3{-Forward.z / length, 0.0, Forward.x / length} : glm::dvec3{1.0, 0.0, 0.0}; +} + +// which way a path of a switch turns away from the other one, seen from the blades +char const *turn_name(TTrack const &Switch, int const Path) +{ + auto const *path{Switch.path_segment(Path)}; + auto const *other{Switch.path_segment(1 - Path)}; + if (path == nullptr || other == nullptr) + return STR_C("straight on"); + glm::dvec3 start, forward; + track_ride_walk::frame({const_cast(&Switch), Path, 0.0}, start, forward); + glm::dvec3 end, ignored; + track_ride_walk::frame({const_cast(&Switch), Path, path->GetLength()}, end, ignored); + glm::dvec3 otherend; + track_ride_walk::frame({const_cast(&Switch), 1 - Path, other->GetLength()}, otherend, ignored); + if (track_ride_walk::switch_path(Switch, 0) == Path) + return STR_C("straight on"); + auto const right{plan_right(forward)}; + return glm::dot(end - otherend, right) > 0.0 ? STR_C("to the right") : STR_C("to the left"); +} + +} // namespace + +bool track_ride::enter(TTrack *Track, int const Path, glm::dvec3 const &Near, glm::dvec3 const &Look, bool const Orient) +{ + if (Track == nullptr || Track->m_editorremoved || Track->eType == tt_Cross) + return false; + track_ride_walk::place place{Track, Track->eType == tt_Switch ? std::clamp(Path, 0, 1) : -1, 0.0}; + auto const *path{track_ride_walk::segment(place)}; + if (path == nullptr) + return false; + place.s = track_ride_walk::nearest_distance(*path, Near); + m_place = place; + m_direction = 1; + m_direction = look_direction(Look); + m_speed = 0.0; + m_choice = 0; + m_forward = m_back = m_up = m_down = false; + m_glide_pending = true; + m_orient_pending = Orient; + m_km.clear(); + m_km_age = 1e9; + m_switch = nullptr; + return true; +} + +void track_ride::leave() +{ + m_place = {}; + m_speed = 0.0; + m_switch = nullptr; + m_forward = m_back = m_up = m_down = false; +} + +int track_ride::look_direction(glm::dvec3 const &Look) const +{ + glm::dvec3 point, forward; + if (false == track_ride_walk::frame(m_place, point, forward)) + return m_direction; + auto const along{forward.x * Look.x + forward.z * Look.z}; + // looking across the track keeps the way it was + if (std::abs(along) < 0.15 * std::hypot(Look.x, Look.z)) + return m_direction; + return along >= 0.0 ? 1 : -1; +} + +glm::dvec3 track_ride::rail_point() const +{ + glm::dvec3 point{0.0}, forward; + track_ride_walk::frame(m_place, point, forward); + return point; +} + +void track_ride::cycle_choice() +{ + m_choice = (m_choice + 1) % 2; +} + +bool track_ride::key(int const Key, int const Action, int const Mods, glm::dvec3 const &Look, bool const Driving, std::string &Status) +{ + m_shift = (Mods & GLFW_MOD_SHIFT) != 0; + m_ctrl = (Mods & GLFW_MOD_CONTROL) != 0; + if (Key == GLFW_KEY_LEFT_SHIFT || Key == GLFW_KEY_RIGHT_SHIFT) + m_shift = Action != GLFW_RELEASE; + if (Key == GLFW_KEY_LEFT_CONTROL || Key == GLFW_KEY_RIGHT_CONTROL) + m_ctrl = Action != GLFW_RELEASE; + if (false == active()) + return false; + auto const held{Action != GLFW_RELEASE}; + auto const press{Action == GLFW_PRESS}; + // with Ctrl or Alt the ride keeps only Ctrl+W and Ctrl+arrows, the much faster drive; the shortcuts of the editor get the + // rest (Ctrl+S saves, Ctrl+Z and Ctrl+Y undo and redo). Releases go on to the editor too, it may have seen the key go down + // before the ride + auto const shortcut{(Mods & GLFW_MOD_ALT) != 0 || (m_ctrl && Key != GLFW_KEY_W && Key != GLFW_KEY_UP && Key != GLFW_KEY_DOWN)}; + auto const hold = [&](bool &Flag) { + Flag = held && Driving && false == shortcut; + return Flag; + }; + switch (Key) + { + case GLFW_KEY_W: + case GLFW_KEY_UP: return hold(m_forward); + case GLFW_KEY_S: + case GLFW_KEY_DOWN: return hold(m_back); + case GLFW_KEY_E: + case GLFW_KEY_PAGE_UP: return hold(m_up); + case GLFW_KEY_Q: + case GLFW_KEY_PAGE_DOWN: return hold(m_down); + case GLFW_KEY_A: + case GLFW_KEY_LEFT: + case GLFW_KEY_D: + case GLFW_KEY_RIGHT: + if (shortcut || false == Driving) + return false; + if (press && false == jump_side(Key == GLFW_KEY_A || Key == GLFW_KEY_LEFT ? -1 : 1, Look)) + Status = STR("No track alongside"); + return held; + case GLFW_KEY_Z: + if (shortcut) + return false; + if (press) + cycle_choice(); + return held; + case GLFW_KEY_Y: + if (shortcut) + return false; + if (press) + leave(); + return held; + default: return false; + } +} + +void track_ride::wheel(double const Notches) +{ + m_height = std::clamp(m_height * std::pow(0.85, -Notches), 0.5, 500.0); +} + +void track_ride::advance(TCamera &Camera, double const Deltatime, bool const Driving) +{ + if (false == active()) + return; + if (m_place.track->m_editorremoved || track_ride_walk::segment(m_place) == nullptr) + { + leave(); + return; + } + auto const dt{std::clamp(Deltatime, 0.0, 0.1)}; + // the window takes the keys, their releases among them, and the right button let go leaves them to the editor: none is held + // for the ride then + if (ImGui::GetIO().WantCaptureKeyboard || false == Driving) + m_forward = m_back = m_up = m_down = false; + // the path may have got shorter, an undo or a change of the track under the ride + m_place.s = std::clamp(m_place.s, 0.0, track_ride_walk::segment(m_place)->GetLength()); + glm::dvec3 const look{-std::sin(Camera.Angle.y), 0.0, -std::cos(Camera.Angle.y)}; + // standing, the way ahead is the one the camera looks; a camera about to be turned along the track looks there already + if (std::abs(m_speed) < 0.5 && false == m_orient_pending) + m_direction = look_direction(look); + + auto const top{m_ctrl ? 250.0 : m_shift ? 60.0 : 20.0}; + auto const wanted{static_cast((m_forward ? 1 : 0) - (m_back ? 1 : 0)) * top}; + auto const rate{(wanted == 0.0 || wanted * m_speed < 0.0 ? 2.5 : 1.2) * std::max(top, std::abs(m_speed))}; + m_speed = m_speed < wanted ? std::min(wanted, m_speed + rate * dt) : std::max(wanted, m_speed - rate * dt); + + if (m_speed != 0.0) + { + int flips{0}; + bool facing{false}; + auto const halted{track_ride_walk::walk(m_place, m_direction * m_speed * dt, m_choice, flips, facing)}; + if (flips % 2 != 0) + m_direction = -m_direction; + if (facing) + m_choice = 0; + if (halted == track_ride_walk::halt::end) + m_speed = 0.0; + } + if (m_up != m_down) + m_height = std::clamp(m_height + (m_up ? 1.0 : -1.0) * std::clamp(m_height, 2.0, 50.0) * (m_shift ? 3.0 : 1.0) * dt, 0.5, 500.0); + + // the switch ahead + m_switch = track_ride_walk::facing_switch_ahead(m_place, m_speed < 0.0 ? -m_direction : m_direction, switch_reach, m_switch_distance); + m_km_age += dt; + if (m_km_age > 0.5) + { + m_km_age = 0.0; + auto const at{rail_point()}; + double km{0.0}; + auto const line{kilometrage::line_at(at)}; + m_km = false == line.empty() && kilometrage::km_at(line, at, km) ? kilometrage::text(km) : std::string{}; + } + + if (m_orient_pending) + { + // along the way ahead, a little down to the rails + m_orient_pending = false; + glm::dvec3 point, forward; + track_ride_walk::frame(m_place, point, forward); + auto const ahead{forward * static_cast(m_direction)}; + Camera.Angle.y = static_cast(std::atan2(-ahead.x, -ahead.z)); + Camera.Angle.x = -0.12f; + Camera.Angle.z = 0.0f; + } + auto const target{rail_point() + glm::dvec3{0.0, m_height, 0.0}}; + if (m_glide_pending) + { + m_glide_from = Camera.Pos; + m_glide = 0.0; + m_glide_pending = false; + } + if (m_glide < 1.0) + { + m_glide = std::min(1.0, m_glide + dt / glide_time); + auto const eased{m_glide * m_glide * (3.0 - 2.0 * m_glide)}; + Camera.Pos = glm::mix(m_glide_from, target, eased); + } + else + Camera.Pos = target; + Camera.Velocity = glm::dvec3{0.0}; +} + +bool track_ride::jump_side(int const Side, glm::dvec3 const &Look) +{ + glm::dvec3 here, forward; + if (false == track_ride_walk::frame(m_place, here, forward)) + return false; + auto const ahead{forward * static_cast(look_direction(Look))}; + auto const right{plan_right(ahead)}; + auto const category{m_place.track->iCategoryFlag & 15}; + auto const parallel{std::cos(30.0 * M_PI / 180.0)}; + track_ride_walk::place best; + auto nearest{side_reach}; + auto bestforward{forward}; + for (auto *track : simulation::Paths.sequence()) + { + if (track == nullptr || track == m_place.track || track->m_editorremoved || track->eType == tt_Cross || (track->iCategoryFlag & 15) != category) + continue; + for (int path = 0; path < track->path_count(); ++path) + { + track_ride_walk::place candidate{track, track->eType == tt_Switch ? path : -1, 0.0}; + auto const *segment{track_ride_walk::segment(candidate)}; + if (segment == nullptr) + continue; + // far off tracks out at once: no point of the path nearer than the reach + auto const length{segment->GetLength()}; + auto const first{segment->FastGetPoint_0()}; + auto const last{segment->FastGetPoint_1()}; + if (std::min(std::hypot(first.x - here.x, first.z - here.z), std::hypot(last.x - here.x, last.z - here.z)) > 0.6 * length + side_reach + 1.0) + continue; + candidate.s = track_ride_walk::nearest_distance(*segment, here); + glm::dvec3 point, along; + track_ride_walk::frame(candidate, point, along); + auto const offset{point - here}; + auto const across{(offset.x * right.x + offset.z * right.z) * Side}; + auto const lengthwise{offset.x * ahead.x + offset.z * ahead.z}; + // alongside on that side, about across from the camera, running the same way + if (across < 1.5 || across >= nearest || std::abs(lengthwise) > 2.0 + 0.25 * across || std::abs(along.x * ahead.x + along.z * ahead.z) < parallel) + continue; + nearest = across; + best = candidate; + bestforward = along; + } + } + if (best.track == nullptr) + return false; + auto const speed{m_speed}; + auto const goingahead{m_direction == look_direction(Look)}; + m_place = best; + // the way ahead stays the same on the new track + auto const aheadnow{bestforward.x * ahead.x + bestforward.z * ahead.z >= 0.0 ? 1 : -1}; + m_direction = goingahead ? aheadnow : -aheadnow; + m_speed = speed; + m_glide_pending = true; + m_choice = 0; + return true; +} + +void track_ride::forget(scene::basic_node const *Node) +{ + if (Node != nullptr && Node == m_place.track) + leave(); +} + +void track_ride::draw_hud() const +{ + if (false == active()) + return; + auto *drawlist{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())}; + auto const pad{6.0f}; + auto const height{ImGui::GetTextLineHeight()}; + + std::string line{m_place.track->name().empty() ? std::string{"?"} : m_place.track->name()}; + if (false == m_km.empty()) + line += " km " + m_km; + line += format(" %.0f km/h %s %.1f m", std::abs(m_speed) * 3.6, STR_C("height"), m_height); + std::string ahead; + if (m_switch != nullptr) + ahead = format(STR_C("Switch in %.0f m: %s (Z changes)"), m_switch_distance, turn_name(*m_switch, track_ride_walk::switch_path(*m_switch, m_choice))); + // the keys only standing, out of the way while driving + std::string keys; + if (std::abs(m_speed) < 0.5) + keys = STR("RMB held: W/S drive, A/D next track, Q/E height Y leave"); + + // over the bottom of the view, above the bar of the keys of the tools; the rows keep their places as the others come and go + auto const centre{0.5f * (editor_ui::view_min().x + editor_ui::view_max().x)}; + auto y{editor_ui::view_max().y - 12.0f - height * 2.5f - 3.0f * (height + pad * 1.5f)}; + auto const row = [&](std::string const &Text, ImU32 const Background, ImU32 const Foreground) { + if (false == Text.empty()) + { + auto const size{ImGui::CalcTextSize(Text.c_str())}; + ImVec2 const from{centre - 0.5f * size.x - pad, y - pad * 0.5f}; + ImVec2 const to{centre + 0.5f * size.x + pad, y + size.y + pad * 0.5f}; + drawlist->AddRectFilled(from, to, Background, 4.0f); + drawlist->AddText(ImVec2(from.x + pad, y), Foreground, Text.c_str()); + } + y += height + pad * 1.5f; + }; + row(line, IM_COL32(20, 60, 110, 215), IM_COL32(255, 255, 255, 255)); + row(ahead, m_choice != 0 ? IM_COL32(150, 100, 10, 225) : IM_COL32(0, 0, 0, 170), IM_COL32(255, 255, 255, 240)); + row(keys, IM_COL32(0, 0, 0, 120), IM_COL32(220, 220, 220, 210)); +} + +editor_selftest_result track_ride::selftest(std::string const &Command, std::istringstream &Words) +{ + auto const report = [this](char const *What) { + if (false == active()) + { + WriteLog(format("SELFTEST %s: not riding", What)); + return; + } + auto const at{rail_point()}; + WriteLog(format("SELFTEST %s: %s path %d s %.3f direction %d speed %.2f choice %d at %.3f %.3f %.3f", What, m_place.track->name().c_str(), m_place.path, m_place.s, m_direction, m_speed, m_choice, at.x, at.y, at.z)); + }; + if (Command == "ride") + { + // ride [path] [s]: onto the track at the distance, looking towards the growing distance + std::string name; + int path{0}; + double s{0.0}; + Words >> name >> path >> s; + auto *track{simulation::Paths.find(name)}; + track_ride_walk::place place{track, track != nullptr && track->eType == tt_Switch ? path : -1, 0.0}; + auto const *segment{track_ride_walk::segment(place)}; + if (segment == nullptr || false == enter(track, path, glm::dvec3{0.0}, glm::dvec3{0.0, 0.0, 1.0}, true)) + { + WriteLog("SELFTEST ride " + name + ": no such track"); + return editor_selftest_result::handled; + } + m_place.s = std::clamp(s, 0.0, segment->GetLength()); + m_direction = 1; + report("ride"); + return editor_selftest_result::handled; + } + if (Command == "ridewalk") + { + // ridewalk [choice]: the place moved ahead by the distance (negative: back), the switches and tracks logged + // before and after, they mustn't change + double metres{0.0}; + int choice{0}; + Words >> metres >> choice; + if (false == active()) + { + report("ridewalk"); + return editor_selftest_result::handled; + } + auto const states = [] { + std::string text; + for (auto *track : simulation::Paths.sequence()) + if (track != nullptr && track->eType == tt_Switch && track->SwitchExtension != nullptr) + text += std::to_string(track->SwitchExtension->CurrentIndex); + return text; + }; + auto const before{states()}; + int flips{0}; + bool facing{false}; + auto const halted{track_ride_walk::walk(m_place, m_direction * metres, choice, flips, facing)}; + if (flips % 2 != 0) + m_direction = -m_direction; + WriteLog(format("SELFTEST ridewalk %.3f choice %d: flips %d facing %d %s, switches %s", metres, choice, flips, facing ? 1 : 0, halted == track_ride_walk::halt::end ? "halted at an end" : "on the way", before == states() ? "kept" : "THROWN")); + report("ridewalk"); + return editor_selftest_result::handled; + } + if (Command == "ridejump") + { + // ridejump <-1|1>: to the track alongside on the left or the right of the way ahead + int side{1}; + Words >> side; + glm::dvec3 point, forward; + if (false == track_ride_walk::frame(m_place, point, forward)) + { + report("ridejump"); + return editor_selftest_result::handled; + } + auto const jumped{jump_side(side, forward * static_cast(m_direction))}; + WriteLog(format("SELFTEST ridejump %d: %s", side, jumped ? "jumped" : "no track alongside")); + report("ridejump"); + return editor_selftest_result::handled; + } + if (Command == "rideahead") + { + // rideahead: the switch ahead entered from its blades and the path the camera would take there + double distance{0.0}; + auto *ahead{active() ? track_ride_walk::facing_switch_ahead(m_place, m_direction, switch_reach, distance) : nullptr}; + if (ahead == nullptr) + WriteLog("SELFTEST rideahead: no switch ahead"); + else + WriteLog(format("SELFTEST rideahead: %s in %.2f m, straight path %d", ahead->name().c_str(), distance, track_ride_walk::switch_path(*ahead, 0))); + return editor_selftest_result::handled; + } + if (Command == "rideprobe") + { + report("rideprobe"); + return editor_selftest_result::handled; + } + if (Command == "rideleave") + { + leave(); + WriteLog("SELFTEST rideleave"); + return editor_selftest_result::handled; + } + return editor_selftest_result::unhandled; +} diff --git a/application/editormoderide.h b/application/editormoderide.h new file mode 100644 index 000000000..62b190f66 --- /dev/null +++ b/application/editormoderide.h @@ -0,0 +1,113 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include "application/editortool.h" + +#include + +class TTrack; +class TSegment; +class TCamera; + +// the place of the camera riding along the tracks +namespace track_ride_walk +{ + +struct place +{ + TTrack *track{nullptr}; + int path{-1}; // of a switch, -1 on other tracks + double s{0.0}; // m from Point1 of the path +}; + +// how the walk ended +enum class halt +{ + none, + end, // the track ends there, or goes on into a crossroads of roads +}; + +// the path the place is on +TSegment *segment(place const &Place); +// the point of the path and its unit direction towards the growing distance +bool frame(place const &Place, glm::dvec3 &Point, glm::dvec3 &Forward); +// the path of a switch taken from the blades: 0 the one going on straighter, 1 the other one +int switch_path(TTrack const &Switch, int const Choice); +// moves the place by Distance along the path (negative: towards Point1), over the joints to the next tracks; a switch +// entered from its blades is left by the path Choice gives (switch_path), one entered from the frog by the path it came on; +// the switches aren't thrown and nothing on the tracks learns of it. Flips is how many times the counting of the distance +// turned round on the way, at the joints of tracks running the other way. Facing is set to true when a switch was +// entered from the blades +halt walk(place &Place, double const Distance, int const Choice, int &Flips, bool &Facing); +// the nearest switch ahead to be entered from its blades, moving towards the growing distance (Direction 1) or the other +// way (-1), within Reach; null when there's none +TTrack *facing_switch_ahead(place Place, int Direction, double const Reach, double &Distance); +// the distance along the path nearest to the point, in the plan +double nearest_distance(TSegment const &Segment, glm::dvec3 const &Point); + +} // namespace track_ride_walk + +// the camera riding along the tracks as a vehicle: the keys drive it over the joints and switches and jump it over to the +// tracks alongside, the mouse looks around as it does when flying +class track_ride final : public editor_tool +{ + public: + bool active() const { return m_place.track != nullptr; } + // onto the path at the point nearest to Near, the way ahead the one nearer to Look; Orient: the camera turns to look + // along the track, else it keeps looking where it did. False where it can't + bool enter(TTrack *Track, int const Path, glm::dvec3 const &Near, glm::dvec3 const &Look, bool const Orient); + void leave(); + TTrack const *track() const { return m_place.track; } + // a key while riding; true when it was taken. Status is a message to show. The keys driving the ride are taken only with + // Driving, the right button held as it is to fly the camera; without it they're the editor's + bool key(int const Key, int const Action, int const Mods, glm::dvec3 const &Look, bool const Driving, std::string &Status); + void wheel(double const Notches); + // the keys held moved the place by the time passed, the camera is put above the rails there; none is held without Driving + void advance(TCamera &Camera, double const Deltatime, bool const Driving); + // to the track nearest the place on the side (-1 left, 1 right) of the way the camera looks; false with none within reach + bool jump_side(int const Side, glm::dvec3 const &Look); + // the bar of the ride over the view + void draw_hud() const; + void forget(scene::basic_node const *Node) override; + editor_selftest_result selftest(std::string const &Command, std::istringstream &Words) override; + + static constexpr double default_height{3.0}; // m over the rails + + private: + // the direction of the growing distance the camera looks + int look_direction(glm::dvec3 const &Look) const; + void cycle_choice(); + glm::dvec3 rail_point() const; + + track_ride_walk::place m_place; + int m_direction{1}; // the growing distance (1) or the other way (-1), which is ahead + double m_speed{0.0}; // m/s ahead, negative backwards + double m_height{default_height}; + int m_choice{0}; // at the next switch from its blades + // keys held + bool m_forward{false}; + bool m_back{false}; + bool m_up{false}; + bool m_down{false}; + bool m_shift{false}; + bool m_ctrl{false}; + // the camera glides over from where it was, as it enters or jumps over + glm::dvec3 m_glide_from{0.0}; + double m_glide{1.0}; // 0..1, done at 1 + bool m_glide_pending{false}; // starts from where the camera is on the next step + bool m_orient_pending{false}; // the camera turns along the track on the next step + // the switch ahead, for the bar + TTrack *m_switch{nullptr}; + double m_switch_distance{0.0}; + // kilometrage of the place, worked out now and then + std::string m_km; + double m_km_age{1e9}; +}; diff --git a/application/editormoderoad.cpp b/application/editormoderoad.cpp index 30ced2694..9c44c0550 100644 --- a/application/editormoderoad.cpp +++ b/application/editormoderoad.cpp @@ -10,8 +10,12 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "application/editormode.h" #include "application/editoruilayer.h" +#include "application/editormodeshared.h" +#include "application/editorgestures.h" +#include "editor/editorFormat.hpp" #include "utilities/Globals.h" +#include "utilities/translation.h" #include "rendering/renderer.h" #include "world/Track.h" #include "world/Road.h" @@ -22,8 +26,9 @@ http://mozilla.org/MPL/2.0/. #include #include #include -#include #include +#include +#include namespace { @@ -119,12 +124,6 @@ bool is_curved(segment_data const &Path) return Path.points[segment_data::point::control1] != glm::dvec3{0.0} || Path.points[segment_data::point::control2] != glm::dvec3{0.0}; } -void copy_text(char *Buffer, std::size_t const Size, std::string const &Text) -{ - // as much of the text as fits, always terminated - Buffer[Text.copy(Buffer, Size - 1)] = 0; -} - std::string lower_case(std::string Text) { std::transform(Text.begin(), Text.end(), Text.begin(), [](unsigned char c) { return static_cast(std::tolower(c)); }); @@ -171,10 +170,15 @@ roadpoint_node::kind_type point_kind(int const Index) char const *point_label(roadpoint_node::kind_type const Kind) { - return Kind == roadpoint_node::kind_type::spawn ? "spawn point" : - Kind == roadpoint_node::kind_type::despawn ? "removal point" : - Kind == roadpoint_node::kind_type::crosswalk ? "pedestrian crossing" : - "level crossing"; + return Kind == roadpoint_node::kind_type::spawn ? STR_C("spawn point") : + Kind == roadpoint_node::kind_type::despawn ? STR_C("removal point") : + Kind == roadpoint_node::kind_type::crosswalk ? STR_C("pedestrian crossing") : + STR_C("level crossing"); +} + +std::string cannot_change(std::string const &Name, std::string const &Reason) +{ + return format(STR_C("\"%s\" can't be changed: %s"), Name.c_str(), STR(Reason).c_str()); } // gathers new definitions for the pieces which meet or end at provided points. @@ -258,7 +262,7 @@ void editor_mode::update_road_tool() tool.mouse = camera + GfxRenderer->Mouse_Position(); if (glm::distance(tool.mouse, camera) > kReach) { - tool.plan.error = "The cursor isn't over anything near enough"; + tool.plan.error = STR_C("The cursor isn't over anything near enough"); tool.hastarget = false; tool.aimedkind = -1; return; @@ -307,9 +311,9 @@ void editor_mode::road_select(road_node *Road) tool.junction = nullptr; tool.settings = Road->definition(); std::string reason; - tool.status = "Selected: " + (Road->name().empty() ? std::string{"(unnamed road)"} : Road->name()); + tool.status = format(STR_C("Selected: %s"), Road->name().empty() ? STR_C("(unnamed road)") : Road->name().c_str()); if (false == editor_road::can_edit(*Road, &reason)) - tool.status += ". It can't be changed: " + reason; + tool.status += ". " + format(STR_C("It can't be changed: %s"), STR(reason).c_str()); } else { @@ -317,12 +321,6 @@ void editor_mode::road_select(road_node *Road) tool.settings.missing = {}; } tool.varied = tool.settings.changing(); - copy_text(tool.surface, sizeof(tool.surface), tool.settings.surface); - for (int side = 0; side < 2; ++side) - copy_text(tool.sides[side], sizeof(tool.sides[side]), tool.settings.sides[side].material); - copy_text(tool.kerbtext, sizeof(tool.kerbtext), tool.settings.kerbmaterial); - copy_text(tool.mediantext, sizeof(tool.mediantext), tool.settings.median.material); - copy_text(tool.banktext, sizeof(tool.banktext), tool.settings.bankmaterial); } void editor_mode::junction_select(junction_node *Junction) @@ -333,15 +331,9 @@ void editor_mode::junction_select(junction_node *Junction) return; tool.selected = nullptr; std::string reason; - tool.status = "Selected: " + Junction->name(); + tool.status = format(STR_C("Selected: %s"), Junction->name().c_str()); if (false == editor_road::can_edit(*Junction, &reason)) - tool.status += ". It can't be changed: " + reason; - // the fields for the names of materials are shared with the roads - copy_text(tool.surface, sizeof(tool.surface), Junction->definition().surface); - copy_text(tool.sides[0], sizeof(tool.sides[0]), Junction->definition().side.material); - copy_text(tool.kerbtext, sizeof(tool.kerbtext), Junction->definition().kerbmaterial); - copy_text(tool.banktext, sizeof(tool.banktext), Junction->definition().bankmaterial); - copy_text(tool.mediantext, sizeof(tool.mediantext), Junction->definition().medianmaterial); + tool.status += ". " + format(STR_C("It can't be changed: %s"), STR(reason).c_str()); } void editor_mode::roadpoint_select(roadpoint_node *Point) @@ -351,9 +343,9 @@ void editor_mode::roadpoint_select(roadpoint_node *Point) if (Point == nullptr) return; std::string reason; - tool.status = "Selected: " + Point->name(); + tool.status = format(STR_C("Selected: %s"), Point->name().c_str()); if (false == editor_road::can_edit(*Point, &reason)) - tool.status += ". It can't be changed: " + reason; + tool.status += ". " + format(STR_C("It can't be changed: %s"), STR(reason).c_str()); } // works out the point a click of the place tool would make with the cursor where it is @@ -378,7 +370,7 @@ void editor_mode::roadpoint_aim(bool const Fresh) auto const *road{editor_road::nearest(tool.mouse, kSideMargin)}; if (road == nullptr) { - tool.targetnote = "Point at a road"; + tool.targetnote = STR_C("Point at a road"); return; } // the stripes go across the road, whichever part of it the cursor is over @@ -393,12 +385,12 @@ void editor_mode::roadpoint_aim(bool const Fresh) auto const *road{editor_road::nearest(tool.mouse, kSideMargin)}; if (road == nullptr) { - tool.targetnote = "Point at the place a road crosses the rails"; + tool.targetnote = STR_C("Point at the place a road crosses the rails"); return; } if (road->definition().changing()) { - tool.targetnote = "The road gains or loses lanes on this piece; a level crossing goes on a piece which keeps its lanes"; + tool.targetnote = STR_C("The road gains or loses lanes on this piece; a level crossing goes on a piece which keeps its lanes"); return; } glm::dvec3 middle{0.0}; @@ -413,14 +405,14 @@ void editor_mode::roadpoint_aim(bool const Fresh) { tool.target.position = road->definition().point(editor_road::nearest_parameter(road->definition(), tool.mouse)); tool.target.clearance = std::max(tool.stopmargin, 2.0f); - tool.targetnote = "No rails cross the road here; a crossing put here won't close until some do"; + tool.targetnote = STR_C("No rails cross the road here; a crossing put here won't close until some do"); } tool.hastarget = true; return; } if (false == editor_road::nearest_lane(tool.mouse, kLaneReach, tool.target.position, tool.targetdirection)) { - tool.targetnote = "Point at a lane of a road"; + tool.targetnote = STR_C("Point at a lane of a road"); return; } tool.hastarget = true; @@ -439,7 +431,7 @@ void editor_mode::roadpoint_place() auto const created{editor_road::create(std::vector{tool.target})}; if (created.empty()) { - tool.status = "No scenery is loaded"; + tool.status = STR_C("No scenery is loaded"); return; } auto const *point{created.front()}; @@ -447,35 +439,33 @@ void editor_mode::roadpoint_place() editor_road::record record; record.points_created = created; push_road_snapshot(std::move(record)); - char text[64]; switch (state.kind) { case roadpoint_node::kind_type::crossing: { - std::snprintf(text, sizeof(text), "%.1f", state.clearance); - tool.status = "Level crossing made: " + std::to_string(point->stops().size()) + " lanes stop " + text + " m from its middle, "; - tool.status += std::to_string(point->rails()) + " tracks are watched for trains."; + tool.status = format(STR_C("Level crossing made, Ctrl+Z takes it back. Lanes stopping %.1f m from its middle: %d, tracks watched for trains: %d"), static_cast(state.clearance), + static_cast(point->stops().size()), static_cast(point->rails())); break; } case roadpoint_node::kind_type::spawn: { - tool.status = (state.vehicles.empty() ? std::string{"Spawn point made, with no vehicles: nothing appears there until it's given some (Select, click the point)."} : - "Spawn point made, with up to " + std::to_string(state.count) + " vehicles on the roads at a time. They appear while the simulation runs."); + tool.status = (state.vehicles.empty() ? std::string{STR_C("Spawn point made, with no vehicles: nothing appears there until it's given some (Select, click the point)")} : + format(STR_C("Spawn point made, Ctrl+Z takes it back. Vehicles on the roads at a time: up to %d. They appear while the simulation runs"), state.count)); break; } case roadpoint_node::kind_type::despawn: { - tool.status = "Removal point made, it takes vehicles from " + std::to_string(point->lanes().size()) + (point->lanes().size() == 1 ? " lane." : " lanes."); + tool.status = format(STR_C("Removal point made, Ctrl+Z takes it back. Lanes it takes vehicles from: %d"), static_cast(point->lanes().size())); break; } case roadpoint_node::kind_type::crosswalk: { - tool.status = "Pedestrian crossing painted."; + tool.status = STR_C("Pedestrian crossing painted, Ctrl+Z takes it back"); break; } } if (false == tool.targetnote.empty()) - tool.status += " " + tool.targetnote + "."; + tool.status += ". " + tool.targetnote; } // replaces the definition of a level crossing or a traffic point, as a step which can be taken back @@ -485,14 +475,14 @@ void editor_mode::roadpoint_apply(roadpoint_node &Point, roadpoint_node::state c std::string reason; if (false == editor_road::can_edit(Point, &reason)) { - tool.status = "\"" + Point.name() + "\" can't be changed: " + reason; + tool.status = cannot_change(Point.name(), reason); return; } editor_road::record record; record.points.emplace_back(&Point, Point.definition()); editor_road::apply(std::vector>{{&Point, State}}); push_road_snapshot(std::move(record)); - tool.status = "Changed"; + tool.status = STR_C("Changed, Ctrl+Z takes it back"); } // draws controls for a level crossing or a traffic point. returns: true if something was changed @@ -513,34 +503,30 @@ bool editor_mode::render_roadpoint_layout(roadpoint_node::state &State, roadpoin { if (Point != nullptr) { - ImGui::Text("%d lanes stop here, %d tracks are watched for trains", static_cast(Point->stops().size()), static_cast(Point->rails())); + ImGui::Text(STR_C("Lanes stopping here: %d, tracks watched for trains: %d"), static_cast(Point->stops().size()), static_cast(Point->rails())); if (Point->rails() == 0) - ImGui::TextColored(warning, "No rails pass through it, so it never closes"); + ImGui::TextColored(warning, "%s", STR_C("No rails pass through it, so it never closes")); // the crossing is tied to what's there when it's made or changed, and when the roads change - if (ImGui::Button("Look for the rails again")) + if (ImGui::Button(STR_C("Look for the rails again"))) changed = true; - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", "For when the tracks were laid or changed after the crossing was made."); - if (number("Stop this far from the middle [m]", State.clearance, 0.5f, "%.1f")) + item_tooltip("For when the tracks were laid or changed after the crossing was made"); + if (number(STR_C("Stop distance from the middle [m]"), State.clearance, 0.5f, "%.1f")) changed = true; - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", "Where the vehicles stop, measured along the road from the middle of the crossing.\n" - "The tracks passing within that distance from the middle are the ones the crossing is closed for."); + item_tooltip("Where the vehicles stop, measured along the road from the middle of the crossing.\n" + "The crossing closes for the tracks passing within that distance from the middle"); } else { - if (number("Stop this far from the outermost track [m]", tool.stopmargin, 0.5f, "%.1f")) + if (number(STR_C("Stop distance from the track [m]"), tool.stopmargin, 0.5f, "%.1f")) tool.stopmargin = std::clamp(tool.stopmargin, 2.0f, 50.0f); - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", "Where the vehicles stop, measured along the road from the axis of the first track they'd get to."); + item_tooltip("Where the vehicles stop, measured along the road from the axis of the first track they'd get to"); } - if (number("Closes with a train this far away [m]", State.warning, 50.0f, "%.0f")) + if (number(STR_C("Closing distance [m]"), State.warning, 50.0f, "%.0f")) changed = true; - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", "Measured along the tracks, both ways, with both ways of each switch counted.\n" - "A rail vehicle within that distance which gets nearer closes the crossing, and so does one right at it.\n" - "It opens a few seconds after the last one is gone."); - if (ImGui::Checkbox("Paint the stop lines", &State.stoplines)) + item_tooltip("How far a train is when the crossing closes. Measured along the tracks, both ways, with both ways of each switch counted.\n" + "A rail vehicle within that distance which gets nearer closes the crossing, and so does one right at it.\n" + "It opens a few seconds after the last one is gone"); + if (ImGui::Checkbox(STR_C("Paint the stop lines"), &State.stoplines)) changed = true; break; } @@ -549,34 +535,31 @@ bool editor_mode::render_roadpoint_layout(roadpoint_node::state &State, roadpoin if (Point != nullptr) { if (Point->lanes().empty()) - ImGui::TextColored(warning, "It isn't on a lane, so nothing appears here"); + ImGui::TextColored(warning, "%s", STR_C("It isn't on a lane, so nothing appears here")); else if (Point->vehicles() == 0) - ImGui::TextDisabled("The vehicles are made when the simulation runs"); + ImGui::TextDisabled("%s", STR_C("The vehicles are made when the simulation runs")); else - ImGui::Text("%d vehicles made, %d of them wait for their turn", static_cast(Point->vehicles()), static_cast(Point->waiting())); + ImGui::Text(STR_C("Vehicles made: %d, waiting for their turn: %d"), static_cast(Point->vehicles()), static_cast(Point->waiting())); } - if (number("A vehicle every [s]", State.interval, 1.0f, "%.0f")) + if (number(STR_C("A vehicle every [s]"), State.interval, 1.0f, "%.0f")) changed = true; - if (number("Uneven by [0-1]", State.variation, 0.1f, "%.2f")) + if (number(STR_C("Randomness [0-1]"), State.variation, 0.1f, "%.2f")) changed = true; - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", "Part of the time between vehicles which is drawn at random each time.\n" - "0: they come like clockwork, 1: anything from one right after another to twice the time."); - if (number("Speed [km/h]", State.velocity, 5.0f, "%.0f")) + item_tooltip("Part of the time between vehicles which is drawn at random each time.\n" + "0: they come like clockwork, 1: anything from one right after another to twice the time"); + if (number(STR_C("Speed [km/h]"), State.velocity, 5.0f, "%.0f")) changed = true; - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", "The speed the vehicles appear with. From there on the drivers go by the speed limits of the lanes."); + item_tooltip("The speed the vehicles appear with. From there on the drivers go by the speed limits of the lanes"); ImGui::SetNextItemWidth(120.0f); - if (ImGui::InputInt("Vehicles on the roads at a time", &State.count, 1, 5, flags)) + if (ImGui::InputInt(STR_C("Vehicles at a time"), &State.count, 1, 5, flags)) changed = true; - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", "How many vehicles of this point can be on the scenery at once. That many are made along with the scenery,\n" - "drawn from the listed ones in turn; one of those which wait is put on the road each time its turn comes,\n" - "until all of them are out. A vehicle taken by a removal point goes back to wait for its next turn,\n" - "and so does one which stood still for 15 seconds, other than at a closed level crossing, or went backwards."); + item_tooltip("How many vehicles of this point can be on the scenery at once. That many are made along with the scenery,\n" + "drawn from the listed ones in turn; one of those which wait is put on the road each time its turn comes,\n" + "until all of them are out. A vehicle taken by a removal point goes back to wait for its next turn,\n" + "and so does one which stood still for 15 seconds, other than at a closed level crossing, or went backwards"); // the set ImGui::Separator(); - ImGui::Text("Vehicles of the set: %d", static_cast(State.vehicles.size())); + ImGui::Text(STR_C("Vehicles of the set: %d"), static_cast(State.vehicles.size())); int removed{-1}; for (std::size_t index = 0; index < State.vehicles.size(); ++index) { @@ -584,6 +567,7 @@ bool editor_mode::render_roadpoint_layout(roadpoint_node::state &State, roadpoin ImGui::PushID(static_cast(index)); if (ImGui::SmallButton("x")) removed = static_cast(index); + item_tooltip("Remove from the set"); ImGui::SameLine(); if (vehicle.load > 0) ImGui::Text("%s / %s, %s, %d %s", vehicle.folder.c_str(), vehicle.type.c_str(), vehicle.skin.c_str(), vehicle.load, vehicle.loadtype.c_str()); @@ -597,14 +581,18 @@ bool editor_mode::render_roadpoint_layout(roadpoint_node::state &State, roadpoin changed = true; } if (State.vehicles.empty()) - ImGui::TextColored(warning, "No vehicles, so nothing appears here"); + ImGui::TextColored(warning, "%s", STR_C("No vehicles, so nothing appears here")); ImGui::InputTextMultiline("##vehicles", tool.vehicles, sizeof(tool.vehicles), ImVec2(-1.0f, ImGui::GetTextLineHeight() * 5.0f)); - if (ImGui::Button("Add to the set")) + item_tooltip("node -1 0 none dynamic \n" + " enddynamic\n" + "or , one vehicle a line.\n" + "The path, the offset, the driver and the velocity don't matter"); + if (ImGui::Button(STR_C("Add to the set"))) { auto const parsed{roadpoint_node::parse_vehicles(tool.vehicles)}; if (parsed.empty()) { - tool.status = "No vehicle found in the text"; + tool.status = STR_C("No vehicle found in the text"); } else { @@ -614,36 +602,35 @@ bool editor_mode::render_roadpoint_layout(roadpoint_node::state &State, roadpoin } } ImGui::SameLine(); - if (ImGui::Button("Empty the set") && false == State.vehicles.empty()) + if (ImGui::Button(STR_C("Empty the set")) && false == State.vehicles.empty()) { State.vehicles.clear(); changed = true; } - ImGui::TextDisabled("Paste the vehicles the way they're put in a scenery:"); - ImGui::TextDisabled("node -1 0 none dynamic "); - ImGui::TextDisabled(" enddynamic"); - ImGui::TextDisabled("or as , one vehicle a line."); - ImGui::TextDisabled("The path, the offset, the driver and the velocity don't matter."); + ImGui::TextDisabled("%s", STR_C("Paste the vehicles above the way a scenery lists them")); + item_tooltip("node -1 0 none dynamic \n" + " enddynamic\n" + "or , one vehicle a line.\n" + "The path, the offset, the driver and the velocity don't matter"); break; } case roadpoint_node::kind_type::despawn: { if (Point != nullptr) - ImGui::Text("Takes vehicles from %d %s", static_cast(Point->lanes().size()), Point->lanes().size() == 1 ? "lane" : "lanes"); - if (number("Takes vehicles this close [m]", State.radius, 0.5f, "%.1f")) + ImGui::Text(STR_C("Lanes it takes vehicles from: %d"), static_cast(Point->lanes().size())); + if (number(STR_C("Reach [m]"), State.radius, 0.5f, "%.1f")) changed = true; - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", "Road vehicles on the lanes passing within this distance from the point are taken off the road when they get here,\n" - "except for the one the user drives. Vehicles which came from a spawn point go back to wait for their next turn.\n" - "The distance it starts with takes in a single lane."); + item_tooltip("Road vehicles on the lanes passing within this distance from the point are taken off the road when they get here,\n" + "except for the one the user drives. Vehicles which came from a spawn point go back to wait for their next turn.\n" + "The distance it starts with takes in a single lane"); break; } case roadpoint_node::kind_type::crosswalk: { - if (number("Length along the road [m]", State.length, 0.5f, "%.1f")) + if (number(STR_C("Length along the road [m]"), State.length, 0.5f, "%.1f")) changed = true; - ImGui::TextDisabled("Stripes painted from one edge of the road to the other."); - ImGui::TextDisabled("The drivers don't stop for it: there's nobody to cross."); + ImGui::TextDisabled("%s", STR_C("Stripes across the whole road")); + item_tooltip("The drivers don't stop for it: there's nobody to cross"); break; } } @@ -659,17 +646,17 @@ void editor_mode::junction_apply(junction_node &Junction, junction_node::state c std::string reason; if (false == editor_road::can_edit(Junction, &reason)) { - tool.status = "\"" + Junction.name() + "\" can't be changed: " + reason; + tool.status = cannot_change(Junction.name(), reason); // what the window shows goes back to what the junction is like junction_select(&Junction); - tool.status = "\"" + Junction.name() + "\" can't be changed: " + reason; + tool.status = cannot_change(Junction.name(), reason); return; } editor_road::record record; record.junctions.emplace_back(&Junction, Junction.definition()); editor_road::apply(std::vector>{{&Junction, State}}); push_road_snapshot(std::move(record)); - tool.status = "Changed"; + tool.status = STR_C("Changed, Ctrl+Z takes it back"); } // draws controls for what a junction is like, and makes the changes as they're made @@ -685,61 +672,62 @@ void editor_mode::render_junction_layout(junction_node &Junction) }; auto limit{state.velocity > 0.f ? state.velocity : 0.f}; - if (number("Speed limit [km/h], 0: none", limit, 5.0f, "%.0f")) + if (number(STR_C("Speed limit [km/h]"), limit, 5.0f, "%.0f")) { state.velocity = (limit > 0.f ? limit : -1.f); changed = true; } + item_tooltip("0: no limit"); auto centre{static_cast(state.centre.y)}; - if (number("Height of the middle [m]", centre, 0.1f, "%.2f")) + if (number(STR_C("Height of the middle [m]"), centre, 0.1f, "%.2f")) { state.centre.y = centre; changed = true; } - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", "The surface is spanned between the ends of the roads and this point.\nThe ends of the roads are raised or lowered as points: select the white dot at the end of a road."); + item_tooltip("The surface is spanned between the ends of the roads and this point.\nThe ends of the roads are raised or lowered as points: select the white dot at the end of a road"); // appearance ImGui::Separator(); - char const *colours[]{"none", "white", "orange"}; + char const *colours[]{STR_C("no markings"), STR_C("white"), STR_C("orange")}; int colour{state.markings == road_node::marking_colour::white ? 1 : state.markings == road_node::marking_colour::orange ? 2 : 0}; ImGui::SetNextItemWidth(120.0f); - if (ImGui::Combo("Markings", &colour, colours, 3)) + if (ImGui::Combo(STR_C("Markings"), &colour, colours, 3)) { state.markings = (colour == 1 ? road_node::marking_colour::white : colour == 2 ? road_node::marking_colour::orange : road_node::marking_colour::none); changed = true; } - if (render_road_material("Surface", tool.surface, sizeof(tool.surface), state.surface)) + if (render_road_material("Surface", state.surface)) changed = true; - if (number("Texture length [m]", state.texturelength, 0.5f, "%.2f")) + if (number(STR_C("Texture length [m]"), state.texturelength, 0.5f, "%.2f")) { state.texturelength = std::max(0.1f, state.texturelength); changed = true; } + item_tooltip("How many metres of the surface one copy of the texture covers"); // what the corners between the roads are lined with - if (ImGui::Checkbox("Kerb around the corners", &state.kerbs)) + if (ImGui::Checkbox(STR_C("Kerb around the corners"), &state.kerbs)) changed = true; if (state.kerbs) { ImGui::Indent(); - if (number("Kerb width [m]", state.kerbwidth, 0.05f, "%.2f")) + if (number(STR_C("Kerb width [m]"), state.kerbwidth, 0.05f, "%.2f")) { state.kerbwidth = std::clamp(state.kerbwidth, 0.05f, 2.0f); changed = true; } - if (render_road_material("Kerb material", tool.kerbtext, sizeof(tool.kerbtext), state.kerbmaterial)) + if (render_road_material("Kerb material", state.kerbmaterial)) changed = true; - if (state.side.type != road_node::side_type::sidewalk && number("Kerb height [m]", state.kerbheight, 0.01f, "%.2f")) + if (state.side.type != road_node::side_type::sidewalk && number(STR_C("Kerb height [m]"), state.kerbheight, 0.01f, "%.2f")) { state.kerbheight = std::clamp(state.kerbheight, 0.0f, 1.0f); changed = true; } ImGui::Unindent(); } - char const *sidetypes[]{"none", "shoulder", "sidewalk"}; + char const *sidetypes[]{STR_C("no side"), STR_C("shoulder"), STR_C("sidewalk")}; int type{state.side.type == road_node::side_type::shoulder ? 1 : state.side.type == road_node::side_type::sidewalk ? 2 : 0}; ImGui::SetNextItemWidth(120.0f); - if (ImGui::Combo("Sides of the corners", &type, sidetypes, 3)) + if (ImGui::Combo(STR_C("Beside the corners"), &type, sidetypes, 3)) { state.side.type = (type == 1 ? road_node::side_type::shoulder : type == 2 ? road_node::side_type::sidewalk : road_node::side_type::none); if (state.side.type != road_node::side_type::none && state.side.width <= 0.0f) @@ -749,18 +737,18 @@ void editor_mode::render_junction_layout(junction_node &Junction) if (state.side.type != road_node::side_type::none) { ImGui::Indent(); - if (number("Width [m]", state.side.width, 0.25f, "%.2f")) + if (number(STR_C("Width [m]"), state.side.width, 0.25f, "%.2f")) { state.side.width = std::clamp(state.side.width, 0.1f, 20.0f); changed = true; } - if (render_road_material("Material", tool.sides[0], sizeof(tool.sides[0]), state.side.material)) + if (render_road_material("Material", state.side.material)) changed = true; if (state.side.material.empty() || state.side.material == "none") - ImGui::TextDisabled("Pick a material to have the sides drawn"); + ImGui::TextDisabled("%s", STR_C("Pick a material to have the sides drawn")); if (state.side.type == road_node::side_type::sidewalk) { - if (number("Kerb height [m]", state.kerbheight, 0.01f, "%.2f")) + if (number(STR_C("Kerb height [m]"), state.kerbheight, 0.01f, "%.2f")) { state.kerbheight = std::clamp(state.kerbheight, 0.0f, 1.0f); changed = true; @@ -768,12 +756,12 @@ void editor_mode::render_junction_layout(junction_node &Junction) } else { - if (number("Bank width [m]", state.slope.x, 0.25f, "%.2f")) + if (number(STR_C("Bank width [m]"), state.slope.x, 0.25f, "%.2f")) { state.slope.x = std::clamp(state.slope.x, 0.0f, 20.0f); changed = true; } - if (number("Bank drop [m]", state.slope.y, 0.1f, "%.2f")) + if (number(STR_C("Bank height [m]"), state.slope.y, 0.1f, "%.2f")) { state.slope.y = std::clamp(state.slope.y, 0.0f, 20.0f); changed = true; @@ -783,32 +771,31 @@ void editor_mode::render_junction_layout(junction_node &Junction) } // banks leading from the corners to the ground - if (ImGui::CollapsingHeader("Banks to the ground")) + if (ImGui::CollapsingHeader(STR_C("Banks to the ground##banks"))) { - if (render_road_material("Bank material", tool.banktext, sizeof(tool.banktext), state.bankmaterial)) + if (render_road_material("Bank material", state.bankmaterial)) changed = true; - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", "What the banks are covered with next to a sidewalk, a kerb or the bare edge.\nA bank of a shoulder is covered with the material of the shoulder."); + item_tooltip("What the banks are covered with next to a sidewalk, a kerb or the bare edge.\nA bank of a shoulder is covered with the material of the shoulder"); ImGui::SetNextItemWidth(120.0f); - if (ImGui::InputFloat("Run for a metre of drop [m]", &tool.bankgrade, 0.25f, 0.5f, "%.2f")) + if (ImGui::InputFloat(STR_C("Bank slope 1:n"), &tool.bankgrade, 0.25f, 0.5f, "%.2f")) tool.bankgrade = std::clamp(tool.bankgrade, 0.25f, 10.0f); - if (ImGui::Button("Lead the banks to the ground")) + item_tooltip("n: metres across for a metre of height; 1.5 is a usual embankment"); + if (ImGui::Button(STR_C("Lead the banks to the ground"))) { if (changed) junction_apply(Junction, state); junction_bank_to_ground(Junction); return; } - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", "Looks for the ground past each corner, at both roads the corner runs between,\n" - "and sets the bank of the corner to reach it. Done for the roads too, the banks meet at the ends of the roads."); + item_tooltip("Looks for the ground past each corner, at both roads the corner runs between,\n" + "and sets the bank of the corner to reach it. Done for the roads too, the banks meet at the ends of the roads"); auto banked{false}; for (auto const &arm : state.arms) banked = banked || arm.bank.set; if (banked) { ImGui::SameLine(); - if (ImGui::Button("Remove them")) + if (ImGui::Button(STR_C("Remove the banks"))) { for (auto &arm : state.arms) arm.bank = road_node::bank_data{}; @@ -820,41 +807,40 @@ void editor_mode::render_junction_layout(junction_node &Junction) { // where a road changes its lanes: what's between its two directions, if the roads keep them apart ImGui::Separator(); - char const *mediantypes[]{"nothing, the ground shows", "surface closed to the traffic", "island"}; + char const *mediantypes[]{STR_C("nothing, the ground shows"), STR_C("surface closed to the traffic"), STR_C("island")}; int median{state.median == road_node::median_type::gap ? 0 : state.median == road_node::median_type::island ? 2 : 1}; ImGui::SetNextItemWidth(220.0f); - if (ImGui::Combo("Between the directions", &median, mediantypes, 3)) + if (ImGui::Combo(STR_C("Between the directions"), &median, mediantypes, 3)) { state.median = (median == 0 ? road_node::median_type::gap : median == 2 ? road_node::median_type::island : road_node::median_type::painted); changed = true; } - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", "Shows where a road which keeps its two directions apart meets this stretch:\n" - "what's between the directions is led on to the other road, where it closes or carries on."); - if (state.median == road_node::median_type::island && render_road_material("Island material", tool.mediantext, sizeof(tool.mediantext), state.medianmaterial)) + item_tooltip("Shows where a road which keeps its two directions apart meets this stretch:\n" + "what's between the directions is led on to the other road, where it closes or carries on"); + if (state.median == road_node::median_type::island && render_road_material("Island material", state.medianmaterial)) changed = true; } // the roads - if (ImGui::CollapsingHeader("Roads of the junction", ImGuiTreeNodeFlags_DefaultOpen)) + if (ImGui::CollapsingHeader(STR_C("Roads of the junction##arms"), ImGuiTreeNodeFlags_DefaultOpen)) { - ImGui::TextDisabled("The lanes are taken from the roads: change them on the road, the junction follows."); - ImGui::TextDisabled("The roads are numbered in the view. Lanes are counted from the middle of the road;"); - ImGui::TextDisabled("automatic: the inner lane turns left, the outer one right, all go straight."); + ImGui::TextDisabled("%s", STR_C("Lanes come from the roads: change them on the road")); + item_tooltip("The junction follows the roads. The roads are numbered in the view. Lanes are counted from the middle of the road;\n" + "automatic: the inner lane turns left, the outer one right, all go straight on"); for (std::size_t arm = 0; arm < state.arms.size(); ++arm) { ImGui::PushID(static_cast(arm)); auto &data{state.arms[arm]}; - ImGui::Text("%d: %d in, %d out, %.2f m a lane", static_cast(arm) + 1, data.incoming, data.outgoing, data.width); + ImGui::Text(STR_C("%d: %d in, %d out, lanes %.2f m wide"), static_cast(arm) + 1, data.incoming, data.outgoing, data.width); if (state.arms.size() > 2) { ImGui::SameLine(); - if (ImGui::Checkbox("Stop line", &data.stopline)) + if (ImGui::Checkbox(STR_C("Stop line"), &data.stopline)) changed = true; // stripes for the pedestrians, across the whole road where it meets the junction ImGui::SameLine(); bool zebra{data.crosswalk > 0.f}; - if (ImGui::Checkbox("Pedestrian crossing", &zebra)) + if (ImGui::Checkbox(STR_C("Pedestrian crossing"), &zebra)) { data.crosswalk = (zebra ? 4.f : 0.f); changed = true; @@ -868,13 +854,14 @@ void editor_mode::render_junction_layout(junction_node &Junction) data.crosswalk = std::clamp(data.crosswalk, 1.0f, 20.0f); changed = true; } + item_tooltip("Length of the pedestrian crossing along the road"); } } if (data.incoming > 0 && state.arms.size() > 2) { ImGui::Indent(); // the entries are in the order of the stored values - char const *priorities[]{"no sign: gives way to the right", "has the right of way", "gives way", "stops, then gives way"}; + char const *priorities[]{STR_C("no sign: gives way to the right"), STR_C("has the right of way"), STR_C("gives way"), STR_C("stops, then gives way")}; int priority{static_cast(data.priority)}; ImGui::SetNextItemWidth(220.0f); if (ImGui::Combo("##priority", &priority, priorities, 4)) @@ -882,13 +869,14 @@ void editor_mode::render_junction_layout(junction_node &Junction) data.priority = static_cast(std::clamp(priority, 0, 3)); changed = true; } + item_tooltip("Right of way of the traffic coming in from this road"); // ways each lane can be left by - char const *ways[]{"automatic", "left", "straight", "left, straight", "right", "left, right", "straight, right", "any"}; + char const *ways[]{STR_C("automatic"), STR_C("left"), STR_C("straight on"), STR_C("left, straight on"), STR_C("right"), STR_C("left, right"), STR_C("straight on, right"), STR_C("any way")}; for (int lane = 0; lane < data.incoming; ++lane) { ImGui::PushID(100 + lane); int turns{static_cast(lane) < data.turns.size() ? data.turns[lane] & 7 : 0}; - auto const label{"lane " + std::to_string(lane + 1) + " goes"}; + auto const label{format(STR_C("Lane %d goes"), lane + 1)}; ImGui::SetNextItemWidth(140.0f); if (ImGui::Combo(label.c_str(), &turns, ways, 8)) { @@ -928,7 +916,7 @@ editor_mode::road_plan editor_mode::road_preview(bool const Fresh) auto const leaving{tool.reversed ? layout.forward : layout.backward}; float lanewidth{0.f}; auto const evenlanes{editor_road::lane_width(layout, 0.0, lanewidth)}; - char const *unevenlanes{"Lanes of the road being built differ in width, and a junction takes roads with lanes of the same width"}; + char const *unevenlanes{STR_C("Lanes of the road being built differ in width, and a junction takes roads with lanes of the same width")}; // where the road is led to. a loose end of a road or an arm of a junction near the cursor comes first plan.snap = editor_road::find_end(tool.mouse, kSnapRadius); @@ -959,10 +947,9 @@ editor_mode::road_plan editor_mode::road_preview(bool const Fresh) // the junction has its ways through made for a set of lanes at each arm; a single roadway of a road takes the lanes it has if (false == evenlanes || arriving != plan.snap.backward || leaving != plan.snap.forward || std::abs(lanewidth - plan.snap.width) > 0.01f) { - char width[32]; - std::snprintf(width, sizeof(width), "%.2f", plan.snap.width); - plan.error = std::string{plan.snap.junction != nullptr ? "This arm of the junction" : "This roadway"} + " takes a road with "; - plan.error += std::to_string(plan.snap.backward) + " lane(s) leading to it and " + std::to_string(plan.snap.forward) + " away from it, " + width + " m wide each"; + plan.error = format(plan.snap.junction != nullptr ? STR_C("This arm of the junction takes a road with lanes: %d leading to it and %d away from it, %.2f m wide each") : + STR_C("This roadway takes a road with lanes: %d leading to it and %d away from it, %.2f m wide each"), + plan.snap.backward, plan.snap.forward, static_cast(plan.snap.width)); return plan; } } @@ -1013,7 +1000,7 @@ editor_mode::road_plan editor_mode::road_preview(bool const Fresh) glm::dvec2 const away{target.x - tool.point.x, target.z - tool.point.z}; if (glm::length(away) < 1.0) { - plan.error = "Move the cursor to where the road is to go"; + plan.error = STR_C("Move the cursor to where the road is to go"); return plan; } // the axis of the road goes away from the junction, so the lanes going against it are the ones leading into the junction @@ -1042,13 +1029,13 @@ editor_mode::road_plan editor_mode::road_preview(bool const Fresh) shared = shared || touches(plan.end, road); if (shared) { - plan.error = "The junctions at both ends would take the same piece of road; lead the road somewhere else first"; + plan.error = STR_C("The junctions at both ends would take the same piece of road; lead the road somewhere else first"); return plan; } } if (glm::distance(start, target) > kLongestStretch) { - plan.error = "Too far from the last point"; + plan.error = STR_C("Too far from the last point"); return plan; } plan.pieces = editor_road::plan(start, hasdirection ? &direction : nullptr, target, tied ? &enddirection : nullptr, Global.ctrlState, plan.error); @@ -1171,7 +1158,7 @@ bool editor_mode::road_lift_start() for (auto const &point : tool.points) tool.lift_from.push_back(point.y); tool.lifting = true; - tool.status = "Drag up or down, let go to set the heights. Ctrl while dragging: by centimetres"; + tool.status = STR_C("Drag up or down, let go to set the heights. Ctrl while dragging: by centimetres"); return true; } @@ -1207,7 +1194,7 @@ void editor_mode::road_click() glm::dvec3 const ground{camera + GfxRenderer->Mouse_Position()}; if (glm::distance(ground, camera) > kReach) { - tool.status = "The click didn't land on anything near enough"; + tool.status = STR_C("The click didn't land on anything near enough"); return; } tool.mouse = ground; @@ -1245,12 +1232,12 @@ void editor_mode::road_click() tool.points.emplace_back(joint); tool.selected = nullptr; tool.junction = nullptr; - tool.status = std::to_string(tool.points.size()) + (tool.points.size() == 1 ? " point selected" : " points selected"); + tool.status = format(STR_C("Points selected: %d"), static_cast(tool.points.size())); return; } tool.points.clear(); if (under == nullptr && junction_under == nullptr) - tool.status = "No road here"; + tool.status = STR_C("No road here"); road_select(under); junction_select(junction_under); return; @@ -1259,7 +1246,7 @@ void editor_mode::road_click() std::string reason; if (false == editor_road::available(&reason)) { - tool.status = reason; + tool.status = STR(reason); return; } if (tool.ring) @@ -1282,7 +1269,7 @@ void editor_mode::road_click() // started from a loose end of a road it carries that road on, started from an arm of a junction it's the road the junction is made for there if (false == editor_road::can_join(end, &reason)) { - tool.status = "Can't build from here: " + reason; + tool.status = format(STR_C("Can't build from here: %s"), STR(reason).c_str()); return; } tool.point = end.position; @@ -1303,7 +1290,7 @@ void editor_mode::road_click() tool.settings.median.width = {gap, gap}; // the banks were made for the ground where they are tool.settings.banks = {}; - tool.status = "Carrying on \"" + end.road->name() + "\" with its layout"; + tool.status = format(STR_C("Carrying on \"%s\" with its layout"), end.road->name().c_str()); } else { @@ -1324,8 +1311,8 @@ void editor_mode::road_click() tool.settings.lanes.clear(); tool.settings.changes.clear(); tool.settings.normalize(); - tool.status = (end.junction != nullptr ? "Leading a road out of \"" + end.junction->name() + "\", with the lanes the junction has there" : - "Carrying on one of the roadways of \"" + end.road->name() + "\" as a one-way road"); + tool.status = (end.junction != nullptr ? format(STR_C("Leading a road out of \"%s\", with the lanes the junction has there"), end.junction->name().c_str()) : + format(STR_C("Carrying on one of the roadways of \"%s\" as a one-way road"), end.road->name().c_str())); } road_select(nullptr); } @@ -1341,24 +1328,24 @@ void editor_mode::road_click() tool.branchroad = road; tool.branchat = editor_road::nearest_parameter(road->definition(), ground); tool.point = road->definition().point(tool.branchat); - tool.status = "Leading a road out of the side of \"" + road->name() + "\": click where it goes"; + tool.status = format(STR_C("Leading a road out of the side of \"%s\": click where it goes"), road->name().c_str()); } else if (auto *junction{editor_road::nearest_junction(ground)}; junction != nullptr) { // started from a junction it's another road of that junction if (junction->definition().arms.size() >= 4) { - tool.status = "\"" + junction->name() + "\" has four roads already"; + tool.status = format(STR_C("\"%s\" has four roads already"), junction->name().c_str()); return; } tool.branchjunction = junction; tool.point = junction->definition().centre; - tool.status = "Leading another road out of \"" + junction->name() + "\": click where it goes"; + tool.status = format(STR_C("Leading another road out of \"%s\": click where it goes"), junction->name().c_str()); } else { tool.point = ground + glm::dvec3{0.0, tool.offset, 0.0}; - tool.status = "Start set"; + tool.status = STR_C("Start set: click the next points, Esc finishes"); } } tool.chain = true; @@ -1368,12 +1355,12 @@ void editor_mode::road_click() auto plan{road_preview(true)}; if (plan.pieces.empty()) { - tool.status = "Can't build this: " + plan.error; + tool.status = format(STR_C("Can't build this: %s"), STR(plan.error).c_str()); return; } if (plan.snap.valid() && false == editor_road::can_join(plan.snap, &reason)) { - tool.status = "Can't join here: " + reason; + tool.status = format(STR_C("Can't join here: %s"), STR(reason).c_str()); return; } auto pieces{plan.pieces}; @@ -1442,15 +1429,15 @@ void editor_mode::road_click() if (created.empty()) { tool.chain = false; - tool.status = "The road wasn't created"; + tool.status = STR_C("The road wasn't created"); return; } if (plan.snap.valid() || plan.hasend) { tool.chain = false; - tool.status = (plan.snap.valid() ? "Joined with \"" + (plan.snap.road != nullptr ? plan.snap.road->name() : plan.snap.junction->name()) + "\"" : - plan.end.junction != nullptr ? "Led into \"" + plan.end.junction->name() + "\" as another of its roads" : - std::string{"Led into the side of the road, with a junction made there"}); + tool.status = (plan.snap.valid() ? format(STR_C("Joined with \"%s\", Ctrl+Z takes it back"), (plan.snap.road != nullptr ? plan.snap.road->name() : plan.snap.junction->name()).c_str()) : + plan.end.junction != nullptr ? format(STR_C("Led into \"%s\" as another of its roads, Ctrl+Z takes it back"), plan.end.junction->name().c_str()) : + std::string{STR_C("Led into the side of the road, with a junction made there, Ctrl+Z takes it back")}); return; } glm::dvec2 const planar{tangent.x, tangent.z}; @@ -1462,9 +1449,10 @@ void editor_mode::road_click() } tool.grade = grade; tool.hasgrade = true; - tool.status = std::to_string(created.size()) + (created.size() == 1 ? " piece added" : " pieces added"); + tool.status = format(STR_C("Pieces added: %d"), static_cast(created.size())); if (plan.hasstart) - tool.status += (plan.start.junction != nullptr ? ", as another road of the junction" : ", with a junction where the road leaves"); + tool.status += (plan.start.junction != nullptr ? STR_C(", as another road of the junction") : STR_C(", with a junction where the road leaves")); + tool.status += STR_C(", Ctrl+Z takes them back"); } void editor_mode::road_apply() @@ -1486,7 +1474,7 @@ void editor_mode::road_apply() { // what the window shows goes back to what the road is like road_select(tool.selected); - tool.status = "\"" + road->name() + "\" can't be changed: " + reason; + tool.status = cannot_change(road->name(), reason); return; } auto state{tool.settings}; @@ -1519,11 +1507,11 @@ void editor_mode::road_apply() auto const fitted{record.roads.size() + record.roads_removed.size() + record.junctions.size() + record.junctions_created.size() - pieces.size()}; push_road_snapshot(std::move(record)); tool.settings = tool.selected->definition(); - tool.status = (pieces.size() == 1 ? std::string{"Changed."} : "Changed " + std::to_string(pieces.size()) + " pieces."); + tool.status = (pieces.size() == 1 ? std::string{STR_C("Changed, Ctrl+Z takes it back")} : format(STR_C("Pieces changed: %d, Ctrl+Z takes it back"), static_cast(pieces.size()))); if (fitted > 0) - tool.status += " What's next to it was fitted to it."; + tool.status += std::string{". "} + STR_C("What's next to it was fitted to it"); if (false == notes.empty()) - tool.status += " " + notes; + tool.status += ". " + notes; } bool editor_mode::road_delete() @@ -1538,14 +1526,14 @@ bool editor_mode::road_delete() auto *point{tool.marker}; if (false == editor_road::can_edit(*point, &reason)) { - tool.status = "Can't delete: " + reason; + tool.status = format(STR_C("Can't delete: %s"), STR(reason).c_str()); return true; } editor_road::remove(std::vector{point}); record.points_removed.emplace_back(point); push_road_snapshot(std::move(record)); tool.marker = nullptr; - tool.status = "\"" + point->name() + "\" deleted, Ctrl+Z brings it back"; + tool.status = format(STR_C("\"%s\" deleted, Ctrl+Z brings it back"), point->name().c_str()); return true; } if (false == tool.points.empty()) @@ -1557,27 +1545,27 @@ bool editor_mode::road_delete() auto *junction{tool.junction}; if (false == editor_road::can_edit(*junction, &reason)) { - tool.status = "Can't delete: " + reason; + tool.status = format(STR_C("Can't delete: %s"), STR(reason).c_str()); return true; } editor_road::remove(std::vector{junction}); record.junctions_removed.emplace_back(junction); push_road_snapshot(std::move(record)); tool.junction = nullptr; - tool.status = "\"" + junction->name() + "\" deleted, Ctrl+Z brings it back"; + tool.status = format(STR_C("\"%s\" deleted, Ctrl+Z brings it back"), junction->name().c_str()); return true; } auto *road{tool.selected}; if (false == editor_road::can_edit(*road, &reason)) { - tool.status = "Can't delete: " + reason; + tool.status = format(STR_C("Can't delete: %s"), STR(reason).c_str()); return true; } editor_road::remove(std::vector{road}); record.roads_removed.emplace_back(road); push_road_snapshot(std::move(record)); tool.selected = nullptr; - tool.status = "\"" + road->name() + "\" deleted, Ctrl+Z brings it back"; + tool.status = format(STR_C("\"%s\" deleted, Ctrl+Z brings it back"), road->name().c_str()); return true; } @@ -1588,13 +1576,13 @@ void editor_mode::road_roundabout(glm::dvec3 const &Ground) std::string reason; if (false == editor_road::available(&reason)) { - tool.status = reason; + tool.status = STR(reason); return; } auto const states{editor_road::roundabout(Ground + glm::dvec3{0.0, tool.offset, 0.0}, tool.ringradius, tool.settings, tool.island)}; if (states.empty()) { - tool.status = "The roundabout is too small for its lanes: give it a larger radius"; + tool.status = STR_C("The roundabout is too small for its lanes: give it a larger radius"); return; } for (auto const &state : states) @@ -1603,7 +1591,7 @@ void editor_mode::road_roundabout(glm::dvec3 const &Ground) { if (editor_road::nearest(state.point(t), 0.0) != nullptr || editor_road::nearest_junction(state.point(t)) != nullptr) { - tool.status = "There's a road in the way. Make the roundabout next to it, then lead the road into its side"; + tool.status = STR_C("There's a road in the way. Make the roundabout next to it, then lead the road into its side"); return; } } @@ -1611,13 +1599,13 @@ void editor_mode::road_roundabout(glm::dvec3 const &Ground) auto const created{editor_road::create(states)}; if (created.empty()) { - tool.status = "The roundabout wasn't created"; + tool.status = STR_C("The roundabout wasn't created"); return; } editor_road::record record; record.roads_created = created; push_road_snapshot(std::move(record)); - tool.status = "Roundabout made. Untick Roundabout and lead roads out of its side, or into it: the traffic joining it gives way to the traffic going around."; + tool.status = STR_C("Roundabout made, Ctrl+Z takes it back. Untick Roundabout and lead roads out of its side, or into it: the traffic joining it gives way to the traffic going around"); } // how far from specified point, and how far down, a slope of the grade set for the banks gets to the ground @@ -1675,11 +1663,11 @@ void editor_mode::junction_bank_to_ground(junction_node &Junction) } junction_apply(Junction, state); auto &tool{m_roadtool}; - if (tool.status == "Changed") + if (tool.status == STR_C("Changed, Ctrl+Z takes it back")) { - tool.status = "Banks of the junction led to the ground."; + tool.status = STR_C("Banks of the junction led to the ground, Ctrl+Z takes it back"); if ((false == sided || state.side.type != road_node::side_type::shoulder) && (state.bankmaterial.empty() || state.bankmaterial == "none")) - tool.status += " Pick a bank material to have them drawn."; + tool.status += std::string{". "} + STR_C("Pick a bank material to have them drawn"); } } @@ -1695,7 +1683,7 @@ void editor_mode::road_bank_to_ground() { if (false == editor_road::can_edit(*road, &reason)) { - tool.status = "\"" + road->name() + "\" can't be changed: " + reason; + tool.status = cannot_change(road->name(), reason); return; } } @@ -1733,10 +1721,10 @@ void editor_mode::road_bank_to_ground() editor_road::apply(changes); push_road_snapshot(std::move(record)); road_select(tool.selected); - tool.status = "Banks of " + std::to_string(changes.size()) + (changes.size() == 1 ? " piece" : " pieces") + " led to the ground."; + tool.status = format(STR_C("Banks led to the ground, pieces: %d, Ctrl+Z takes it back"), static_cast(changes.size())); auto const &layout{tool.selected->definition()}; if ((layout.sides[0].type != road_node::side_type::shoulder || layout.sides[1].type != road_node::side_type::shoulder) && (layout.bankmaterial.empty() || layout.bankmaterial == "none")) - tool.status += " Pick a bank material to have them drawn where the road has no shoulder."; + tool.status += std::string{". "} + STR_C("Pick a bank material to have them drawn where the road has no shoulder"); } // takes the selected points out of their roads @@ -1751,14 +1739,14 @@ bool editor_mode::road_points_delete() std::string error; if (editor_road::dissolve(point, record, error)) ++taken; - else if (notes.find(error) == std::string::npos) - notes += " A point was left: " + error + "."; + else if (auto const note{". " + format(STR_C("A point was left: %s"), STR(error).c_str())}; notes.find(note) == std::string::npos) + notes += note; } push_road_snapshot(std::move(record)); // the points which stayed are still selected, so it's clear which ones these are tool.points.erase(std::remove_if(tool.points.begin(), tool.points.end(), [](glm::dvec3 const &Point) { return editor_road::ends_at(Point).empty(); }), tool.points.end()); - tool.status = (taken == 0 ? std::string{"Nothing deleted."} : taken == 1 ? std::string{"Point deleted, Ctrl+Z brings it back."} : - std::to_string(taken) + " points deleted, Ctrl+Z brings them back."); + tool.status = (taken == 0 ? std::string{STR_C("Nothing deleted")} : taken == 1 ? std::string{STR_C("Point deleted, Ctrl+Z brings it back")} : + format(STR_C("Points deleted: %d, Ctrl+Z brings them back"), taken)); tool.status += notes; return true; } @@ -1772,12 +1760,12 @@ bool editor_mode::road_split() std::string reason; if (false == editor_road::can_edit(*road, &reason)) { - tool.status = "Can't split: " + reason; + tool.status = format(STR_C("Can't split: %s"), STR(reason).c_str()); return true; } if (road->definition().changing()) { - tool.status = "Can't split a piece which gains or loses lanes; give it the same lanes at both ends first"; + tool.status = STR_C("Can't split a piece which gains or loses lanes; give it the same lanes at both ends first"); return true; } editor_road::record record; @@ -1785,13 +1773,14 @@ bool editor_mode::road_split() auto *created{editor_road::split(*road, editor_road::nearest_parameter(road->definition(), tool.mouse))}; if (created == nullptr) { - tool.status = "Can't split this close to the end"; + tool.status = STR_C("Can't split this close to the end"); return true; } record.roads_created.emplace_back(created); push_road_snapshot(std::move(record)); road_select(road); - tool.status = "Split in two: \"" + road->name() + "\" and \"" + created->name() + "\". Click the point between them to set the width or the height of the road there"; + tool.status = format(STR_C("Split in two: \"%s\" and \"%s\", Ctrl+Z takes it back. Click the point between them to set the width or the height of the road there"), road->name().c_str(), + created->name().c_str()); return true; } @@ -1801,7 +1790,7 @@ bool editor_mode::road_points_apply(std::vectorname() + "\" can't be changed: " + reason; + tool.status = cannot_change(change.first->name(), reason); return false; } record.roads.emplace_back(change.first, change.first->definition()); @@ -1819,7 +1808,7 @@ bool editor_mode::road_points_apply(std::vectorname() + "\" can't be changed: " + reason; + tool.status = cannot_change(change.first->name(), reason); return false; } record.junctions.emplace_back(change.first, change.first->definition()); @@ -1831,9 +1820,9 @@ bool editor_mode::road_points_apply(std::vector(Changes.size())); if (false == notes.empty()) - tool.status += " " + notes; + tool.status += ". " + notes; return true; } @@ -1971,61 +1960,44 @@ void editor_mode::restore_road_snapshot(EditorSnapshot const &Snapshot, std::vec tool.aimedkind = -1; } -// a field for the name of a material, with a list of the ones in the texture folder to pick from. returns: true if the material was changed -bool editor_mode::render_road_material(char const *Label, char *Buffer, std::size_t const Size, std::string &Value) +// a field of the material of a part of a road or of a junction. returns: true if the material was changed +bool editor_mode::render_road_material(char const *Label, std::string &Value) { - auto &tool{m_roadtool}; - bool picked{false}; ImGui::PushID(Label); - ImGui::SetNextItemWidth(200.0f); - if (ImGui::InputText("##name", Buffer, Size, ImGuiInputTextFlags_EnterReturnsTrue) || ImGui::IsItemDeactivatedAfterEdit()) - { - auto const name{lower_case(Buffer)}; - if (name != Value && name.find(' ') == std::string::npos) - { - Value = name.empty() ? std::string{"none"} : name; - picked = true; - } - copy_text(Buffer, Size, Value); - } - ImGui::SameLine(); - if (ImGui::Button("...")) - ImGui::OpenPopup("pick"); - ImGui::SameLine(); - ImGui::TextUnformatted(Label); - if (ImGui::BeginPopup("pick")) - { - ImGui::TextDisabled("Materials and images found in the texture folder"); - ImGui::SetNextItemWidth(200.0f); - ImGui::InputText("Filter", tool.filter, sizeof(tool.filter)); - auto const filter{lower_case(tool.filter)}; - std::vector listed; - for (auto const &name : editor_road::materials()) - if (filter.empty() || name.find(filter) != std::string::npos) - listed.emplace_back(&name); - ImGui::BeginChild("list", ImVec2(340.0f, 280.0f), true); - ImGuiListClipper clipper; - clipper.Begin(static_cast(listed.size())); - while (clipper.Step()) - { - for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; ++i) - { - if (ImGui::Selectable(listed[i]->c_str(), *listed[i] == Value)) - { - Value = *listed[i]; - copy_text(Buffer, Size, Value); - picked = true; - ImGui::CloseCurrentPopup(); - } - } - } - ImGui::EndChild(); - ImGui::EndPopup(); - } + auto const picked{texture_field(STR_C(Label), 200.0f, Value, {STR_C("On the roads of this scenery:"), [this]() { return road_textures_used(); }, STR_C("No texture"), "none"})}; ImGui::PopID(); + if (picked) + Value = lower_case(Value); return picked; } +std::vector editor_mode::road_textures_used() const +{ + std::map counted; + auto const count = [&](std::set const &Names) { + for (auto const &name : Names) + if (false == name.empty() && name != "none") + ++counted[name]; + }; + for (auto const *road : simulation::Roads.sequence()) + if (road != nullptr && false == road->m_editorremoved) + { + auto const &state{road->definition()}; + count({state.surface, state.sides[0].material, state.sides[1].material, state.kerbmaterial, state.bankmaterial, state.median.material}); + } + for (auto const *junction : simulation::Junctions.sequence()) + if (junction != nullptr && false == junction->m_editorremoved) + { + auto const &state{junction->definition()}; + count({state.surface, state.side.material, state.kerbmaterial, state.bankmaterial, state.medianmaterial}); + } + std::vector list; + for (auto const &[name, number] : counted) + list.push_back({null_handle, name, number, format(STR_P("On %d road or junction", "On %d roads or junctions", static_cast(number)), number)}); + std::stable_sort(list.begin(), list.end(), [](auto const &Left, auto const &Right) { return Left.count > Right.count; }); + return list; +} + // draws controls for the layout of a road. returns: true if the layout was changed in a way which calls for the road to be made anew bool editor_mode::render_road_layout(road_node::state &State) { @@ -2036,7 +2008,6 @@ bool editor_mode::render_road_layout(road_node::state &State) ImGui::SetNextItemWidth(120.0f); return ImGui::InputFloat(Label, &Value, Step, Step * 4.0f, Format, ImGuiInputTextFlags_EnterReturnsTrue); }; - auto const material = [this](char const *Label, char *Buffer, std::size_t const Size, std::string &Value) { return render_road_material(Label, Buffer, Size, Value); }; // lanes. a piece of a road which is there already can end with other lanes than it starts with { @@ -2044,35 +2015,36 @@ bool editor_mode::render_road_layout(road_node::state &State) int counts[2][2]{{State.lanes_at(0, true), State.lanes_at(0, false)}, {State.lanes_at(1, true), State.lanes_at(1, false)}}; bool relaned{false}; ImGui::SetNextItemWidth(120.0f); - if (ImGui::InputInt(selecting && tool.varied ? "Lanes along the axis, at the start" : "Lanes along the axis", &counts[0][0])) + if (ImGui::InputInt(selecting && tool.varied ? STR_C("Lanes along the axis, at the start") : STR_C("Lanes along the axis"), &counts[0][0])) relaned = true; + item_tooltip("Lanes going the way the road was built, from its start to its end; drawn green with Show lanes"); ImGui::SetNextItemWidth(120.0f); - if (ImGui::InputInt(selecting && tool.varied ? "Lanes against the axis, at the start" : "Lanes against the axis", &counts[0][1])) + if (ImGui::InputInt(selecting && tool.varied ? STR_C("Lanes against the axis, at the start") : STR_C("Lanes against the axis"), &counts[0][1])) relaned = true; + item_tooltip("Lanes going back, from the end of the road to its start; drawn orange with Show lanes"); if (selecting) { // ticked it only shows the lanes of the end to be set; unticked it gives the end the lanes of the start - if (ImGui::Checkbox("Other lanes at the end of the piece", &tool.varied) && false == tool.varied && State.changing()) + if (ImGui::Checkbox(STR_C("Other lanes at the end of the piece"), &tool.varied) && false == tool.varied && State.changing()) relaned = true; - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", "The road gains or loses lanes along this piece: it gets wider or narrower, a lane it gains branches off the outermost lane\n" - "of its direction (two at most), a lane it loses joins the outermost one left.\n" - "What's next to the piece is fitted to the lanes the piece has at that end.\n" - "The axis goes the way the lanes drawn in green do: the start of the piece is where these come from.\n" - "Split the piece (K) first to have the lanes change over a part of it."); + item_tooltip("The road gains or loses lanes along this piece: it gets wider or narrower, a lane it gains branches off the outermost lane\n" + "of its direction (two at most), a lane it loses joins the outermost one left.\n" + "What's next to the piece is fitted to the lanes the piece has at that end.\n" + "The axis goes the way the lanes drawn in green do: the start of the piece is where these come from.\n" + "Split the piece (K) first to have the lanes change over a part of it"); if (tool.varied) { ImGui::SetNextItemWidth(120.0f); - if (ImGui::InputInt("Lanes along the axis, at the end", &counts[1][0])) + if (ImGui::InputInt(STR_C("Lanes along the axis, at the end"), &counts[1][0])) relaned = true; ImGui::SetNextItemWidth(120.0f); - if (ImGui::InputInt("Lanes against the axis, at the end", &counts[1][1])) + if (ImGui::InputInt(STR_C("Lanes against the axis, at the end"), &counts[1][1])) relaned = true; } } // the traffic going along the axis gets on the piece at its start, the one going against it at its end if (State.lanes_at(1, true) - State.lanes_at(0, true) > 2 || State.lanes_at(0, false) - State.lanes_at(1, false) > 2) - ImGui::TextColored(ImVec4(1.0f, 0.5f, 0.3f, 1.0f), "A lane forks into three at most: lanes past the second one gained can't be got on"); + ImGui::TextColored(ImVec4(1.0f, 0.5f, 0.3f, 1.0f), "%s", STR_C("A lane forks into three at most: lanes past the second one gained can't be got on")); if (relaned) { if (false == selecting || false == tool.varied) @@ -2085,7 +2057,7 @@ bool editor_mode::render_road_layout(road_node::state &State) changed = true; } } - if (number("Lane width [m]", State.lanewidth, 0.25f, "%.2f")) + if (number(STR_C("Lane width [m]"), State.lanewidth, 0.25f, "%.2f")) { State.lanewidth = std::clamp(State.lanewidth, 1.0f, 10.0f); for (auto &lane : State.lanes) @@ -2093,33 +2065,29 @@ bool editor_mode::render_road_layout(road_node::state &State) changed = true; } float limit{State.velocity > 0.0f ? State.velocity : 0.0f}; - if (number("Speed limit [km/h], 0: none", limit, 10.0f, "%.0f")) + if (number(STR_C("Speed limit [km/h]"), limit, 10.0f, "%.0f")) { State.velocity = (limit > 0.0f ? limit : -1.0f); for (auto &lane : State.lanes) lane.velocity = State.velocity; changed = true; } + item_tooltip("0: no limit"); // appearance ImGui::Separator(); - char const *colours[]{"none", "white", "orange"}; + char const *colours[]{STR_C("no markings"), STR_C("white"), STR_C("orange")}; int colour{State.markings == road_node::marking_colour::white ? 1 : State.markings == road_node::marking_colour::orange ? 2 : 0}; ImGui::SetNextItemWidth(120.0f); - if (ImGui::Combo("Markings", &colour, colours, 3)) + if (ImGui::Combo(STR_C("Markings"), &colour, colours, 3)) { State.markings = (colour == 1 ? road_node::marking_colour::white : colour == 2 ? road_node::marking_colour::orange : road_node::marking_colour::none); changed = true; } - if (material("Surface", tool.surface, sizeof(tool.surface), State.surface)) + if (render_road_material("Surface", State.surface)) changed = true; - if (number("Texture length [m]", State.texturelength, 0.5f, "%.2f")) - { - State.texturelength = std::max(0.1f, State.texturelength); - changed = true; - } - char const *sidenames[]{"Left side", "Right side"}; - char const *sidetypes[]{"none", "shoulder", "sidewalk"}; + char const *sidenames[]{STR_C("Left side"), STR_C("Right side")}; + char const *sidetypes[]{STR_C("no side"), STR_C("shoulder"), STR_C("sidewalk")}; for (int side = 0; side < 2; ++side) { ImGui::PushID(side); @@ -2136,58 +2104,44 @@ bool editor_mode::render_road_layout(road_node::state &State) if (data.type != road_node::side_type::none) { ImGui::Indent(); - if (number("Width [m]", data.width, 0.25f, "%.2f")) + if (number(STR_C("Width [m]"), data.width, 0.25f, "%.2f")) { data.width = std::clamp(data.width, 0.1f, 20.0f); changed = true; } - if (material("Material", tool.sides[side], sizeof(tool.sides[side]), data.material)) + if (render_road_material("Material", data.material)) changed = true; if (data.material.empty() || data.material == "none") - ImGui::TextDisabled("Pick a material to have the side drawn"); + ImGui::TextDisabled("%s", STR_C("Pick a material to have the side drawn")); ImGui::Unindent(); } ImGui::PopID(); } // kerbs - if (ImGui::Checkbox("Kerb on the left", &State.kerbs[0])) + if (ImGui::Checkbox(STR_C("Kerb on the left"), &State.kerbs[0])) changed = true; ImGui::SameLine(); - if (ImGui::Checkbox("on the right", &State.kerbs[1])) + if (ImGui::Checkbox(STR_C("on the right##kerb"), &State.kerbs[1])) changed = true; auto const island{State.divided() && State.median.type == road_node::median_type::island}; if (State.kerbs[0] || State.kerbs[1] || island) { ImGui::Indent(); - if (number("Kerb width [m]", State.kerbwidth, 0.05f, "%.2f")) - { - State.kerbwidth = std::clamp(State.kerbwidth, 0.05f, 2.0f); - changed = true; - } - if (material("Kerb material", tool.kerbtext, sizeof(tool.kerbtext), State.kerbmaterial)) + if (render_road_material("Kerb material", State.kerbmaterial)) changed = true; if ((State.kerbs[0] || State.kerbs[1]) && (State.kerbmaterial.empty() || State.kerbmaterial == "none")) - ImGui::TextDisabled("Pick a material to have the kerbs drawn"); + ImGui::TextDisabled("%s", STR_C("Pick a material to have the kerbs drawn")); ImGui::Unindent(); } - if (State.kerbs[0] || State.kerbs[1] || island || State.sides[0].type == road_node::side_type::sidewalk || State.sides[1].type == road_node::side_type::sidewalk) - { - if (number("Kerb height [m]", State.kerbheight, 0.01f, "%.2f")) - { - State.kerbheight = std::clamp(State.kerbheight, 0.0f, 1.0f); - changed = true; - } - } if (State.sides[0].type == road_node::side_type::shoulder || State.sides[1].type == road_node::side_type::shoulder) { - if (number("Bank width [m]", State.slope.x, 0.25f, "%.2f")) + if (number(STR_C("Bank width [m]"), State.slope.x, 0.25f, "%.2f")) { State.slope.x = std::clamp(State.slope.x, 0.0f, 20.0f); changed = true; } - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", "The bank every shoulder of the road is closed with, unless the side has a bank of its own set below."); - if (number("Bank drop [m]", State.slope.y, 0.1f, "%.2f")) + item_tooltip("The bank every shoulder of the road is closed with, unless the side has a bank of its own set below"); + if (number(STR_C("Bank height [m]"), State.slope.y, 0.1f, "%.2f")) { State.slope.y = std::clamp(State.slope.y, 0.0f, 20.0f); changed = true; @@ -2195,12 +2149,11 @@ bool editor_mode::render_road_layout(road_node::state &State) } // banks leading to the ground - if (ImGui::CollapsingHeader("Banks to the ground")) + if (ImGui::CollapsingHeader(STR_C("Banks to the ground##banks"))) { - ImGui::TextDisabled("A slope from the edge of the road down, or up, to the ground."); - ImGui::TextDisabled("Set here it goes to every piece the changes go to; the button below"); - ImGui::TextDisabled("works out each piece on its own."); - char const *banknames[]{"Bank on the left", "Bank on the right"}; + ImGui::TextDisabled("%s", STR_C("A slope from the edge of the road to the ground")); + item_tooltip("It goes down, or up, to the ground. Set here it goes to every piece the changes go to;\nthe button below works out each piece on its own"); + char const *banknames[]{STR_C("Bank on the left"), STR_C("Bank on the right")}; for (int side = 0; side < 2; ++side) { ImGui::PushID(100 + side); @@ -2217,44 +2170,43 @@ bool editor_mode::render_road_layout(road_node::state &State) if (bank.set) { ImGui::Indent(); - if (number("Width at the start [m]", bank.width[0], 0.5f, "%.2f")) + if (number(STR_C("Width at the start [m]"), bank.width[0], 0.5f, "%.2f")) changed = true; - if (number("Drop at the start [m]", bank.drop[0], 0.25f, "%.2f")) + if (number(STR_C("Height at the start [m]"), bank.drop[0], 0.25f, "%.2f")) changed = true; - if (number("Width at the end [m]", bank.width[1], 0.5f, "%.2f")) + if (number(STR_C("Width at the end [m]"), bank.width[1], 0.5f, "%.2f")) changed = true; - if (number("Drop at the end [m]", bank.drop[1], 0.25f, "%.2f")) + if (number(STR_C("Height at the end [m]"), bank.drop[1], 0.25f, "%.2f")) changed = true; ImGui::Unindent(); } ImGui::PopID(); } - if (material("Bank material", tool.banktext, sizeof(tool.banktext), State.bankmaterial)) + if (render_road_material("Bank material", State.bankmaterial)) changed = true; - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", "What a bank is covered with next to a sidewalk, a kerb or the bare edge of the road.\nA bank of a shoulder is covered with the material of the shoulder."); + item_tooltip("What a bank is covered with next to a sidewalk, a kerb or the bare edge of the road.\nA bank of a shoulder is covered with the material of the shoulder"); if (tool.selected != nullptr) { ImGui::SetNextItemWidth(120.0f); - if (ImGui::InputFloat("Run for a metre of drop [m]", &tool.bankgrade, 0.25f, 0.5f, "%.2f")) + if (ImGui::InputFloat(STR_C("Bank slope 1:n"), &tool.bankgrade, 0.25f, 0.5f, "%.2f")) tool.bankgrade = std::clamp(tool.bankgrade, 0.25f, 10.0f); - if (ImGui::Button("Lead the banks to the ground")) + item_tooltip("n: metres across for a metre of height; 1.5 is a usual embankment"); + if (ImGui::Button(STR_C("Lead the banks to the ground"))) { road_bank_to_ground(); // the layout shown was replaced with what the road is like now return false; } - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", "Looks for the ground on both sides of the road, at the start and at the end of each piece,\n" - "and sets the banks to reach it with the slope given above: down where the road is over the ground, up where it's cut into it.\n" - "Done for the selected piece, or for every piece of the road if the changes go to the whole road."); + item_tooltip("Looks for the ground on both sides of the road, at the start and at the end of each piece,\n" + "and sets the banks to reach it with the slope given above: down where the road is over the ground, up where it's cut into it.\n" + "Done for the selected piece, or for every piece of the road if the changes go to the whole road"); } } // the two directions kept apart - if (State.forward > 0 && State.backward > 0 && ImGui::CollapsingHeader("Between the directions")) + if (State.forward > 0 && State.backward > 0 && ImGui::CollapsingHeader(STR_C("Between the directions##median"))) { - char const *mediantypes[]{"nothing, the ground shows", "surface closed to the traffic", "island"}; + char const *mediantypes[]{STR_C("nothing, the ground shows"), STR_C("surface closed to the traffic"), STR_C("island")}; int type{State.median.type == road_node::median_type::gap ? 0 : State.median.type == road_node::median_type::island ? 2 : 1}; ImGui::SetNextItemWidth(220.0f); if (ImGui::Combo("##median", &type, mediantypes, 3)) @@ -2262,49 +2214,78 @@ bool editor_mode::render_road_layout(road_node::state &State) State.median.type = (type == 0 ? road_node::median_type::gap : type == 2 ? road_node::median_type::island : road_node::median_type::painted); changed = true; } - if (number("Apart at the start [m]", State.median.width[0], 0.5f, "%.2f")) + char const *apart{"How far apart the two directions are led at each end of the piece; 0 at one end and more at the other makes them part along it.\n" + "Set for each piece on its own. The pieces next to it follow it where they meet, and so do the junctions.\n" + "A road with its directions apart can be carried on as two one-way roads: start the Build tool\n" + "on the middle of one of its roadways, at an end of the road with nothing attached"}; + if (number(STR_C("Apart at the start [m]"), State.median.width[0], 0.5f, "%.2f")) changed = true; - if (number("Apart at the end [m]", State.median.width[1], 0.5f, "%.2f")) + item_tooltip(apart); + if (number(STR_C("Apart at the end [m]"), State.median.width[1], 0.5f, "%.2f")) changed = true; - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", "How far apart the two directions are led at each end of the piece; 0 at one end and more at the other makes them part along it.\n" - "Set for each piece on its own. The pieces next to it follow it where they meet, and so do the junctions.\n" - "A road with its directions apart can be carried on as two one-way roads: start the Build tool\n" - "on the middle of one of its roadways, at an end of the road with nothing attached."); + item_tooltip(apart); if (State.median.type == road_node::median_type::island) { - if (material("Island material", tool.mediantext, sizeof(tool.mediantext), State.median.material)) + if (render_road_material("Island material", State.median.material)) changed = true; - ImGui::TextDisabled("The island is as high as the kerbs; with a kerb material set it gets kerbs of its own."); - if (number("Rounded at the start [m]", State.median.round[0], 0.5f, "%.2f")) + item_tooltip("The island is as high as the kerbs; with a kerb material set it gets kerbs of its own"); + char const *rounded{"Length of the rounded end of the island at that end of the piece; half of the width of the island makes it a half circle.\n" + "0: the island is cut straight, with a face. Use it where the next piece has no island"}; + if (number(STR_C("Rounded at the start [m]"), State.median.round[0], 0.5f, "%.2f")) changed = true; - if (number("Rounded at the end [m]", State.median.round[1], 0.5f, "%.2f")) + item_tooltip(rounded); + if (number(STR_C("Rounded at the end [m]"), State.median.round[1], 0.5f, "%.2f")) changed = true; - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", "Length of the rounded end of the island at that end of the piece; half of the width of the island makes it a half circle.\n" - "0: the island is cut straight, with a face. Use it where the next piece has no island."); + item_tooltip(rounded); } } - // traffic - if (number("Traffic share, 100: like any other", State.weight, 10.0f, "%.0f")) + ImGui::PushID("layout"); + if (ImGui::TreeNode(STR_C("More settings"))) { - State.weight = std::clamp(State.weight, 0.0f, 10000.0f); - changed = true; + if (number(STR_C("Texture length [m]"), State.texturelength, 0.5f, "%.2f")) + { + State.texturelength = std::max(0.1f, State.texturelength); + changed = true; + } + item_tooltip("How many metres of the surface one copy of the texture covers"); + if (State.kerbs[0] || State.kerbs[1] || island) + { + if (number(STR_C("Kerb width [m]"), State.kerbwidth, 0.05f, "%.2f")) + { + State.kerbwidth = std::clamp(State.kerbwidth, 0.05f, 2.0f); + changed = true; + } + } + if (State.kerbs[0] || State.kerbs[1] || island || State.sides[0].type == road_node::side_type::sidewalk || State.sides[1].type == road_node::side_type::sidewalk) + { + if (number(STR_C("Kerb height [m]"), State.kerbheight, 0.01f, "%.2f")) + { + State.kerbheight = std::clamp(State.kerbheight, 0.0f, 1.0f); + changed = true; + } + } + // traffic + if (number(STR_C("Traffic share"), State.weight, 10.0f, "%.0f")) + { + State.weight = std::clamp(State.weight, 0.0f, 10000.0f); + changed = true; + } + item_tooltip("How willing the drivers are to take this road when they leave a junction, next to the other roads they can take there.\n" + "100: like any other. With 100 for the main road and 20 for a dirt road leaving it, one vehicle in six turns into the dirt road.\n" + "0: nobody takes it, unless there's no other way"); + if (ImGui::Checkbox(STR_C("Part of a roundabout"), &State.roundabout)) + changed = true; + item_tooltip("A junction made on this road gives the right of way to the traffic going along it,\nand tells the traffic of the road joining it to give way"); + ImGui::TreePop(); } - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", "How willing the drivers are to take this road when they leave a junction, next to the other roads they can take there.\n" - "With 100 for the main road and 20 for a dirt road leaving it, one vehicle in six turns into the dirt road.\n" - "0: nobody takes it, unless there's no other way."); - if (ImGui::Checkbox("Part of a roundabout", &State.roundabout)) - changed = true; - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", "A junction made on this road gives the right of way to the traffic going along it,\nand tells the traffic of the road joining it to give way."); + ImGui::PopID(); // single lanes, and the rules for changing between them - if (ImGui::CollapsingHeader("Lanes and lane changes", ImGuiTreeNodeFlags_DefaultOpen)) + if (ImGui::CollapsingHeader(STR_C("Lanes and lane changes##lanes"))) { - ImGui::TextDisabled("Left to right when facing along the axis. f: along the axis, b: against it"); + ImGui::TextDisabled("%s", STR_C("Left to right, facing along the axis")); + item_tooltip("f: a lane along the axis, b: against it"); for (std::size_t lane = 0; lane < State.lanes.size(); ++lane) { ImGui::PushID(static_cast(lane)); @@ -2317,6 +2298,7 @@ bool editor_mode::render_road_layout(road_node::state &State) data.width = std::clamp(data.width, 1.0f, 10.0f); changed = true; } + item_tooltip("Width of the lane"); ImGui::SameLine(); float lanelimit{data.velocity > 0.0f ? data.velocity : 0.0f}; if (number("km/h##velocity", lanelimit, 10.0f, "%.0f")) @@ -2324,17 +2306,19 @@ bool editor_mode::render_road_layout(road_node::state &State) data.velocity = (lanelimit > 0.0f ? lanelimit : -1.0f); changed = true; } + item_tooltip("Speed limit of the lane, 0: no limit"); if (lane + 1 < State.lanes.size() && lane < State.changes.size()) { // the entries are in the order of the stored values: none, to the right, to the left, both auto const next{State.lane_id(lane + 1)}; - auto const toright{"only " + id + " to " + next}; - auto const toleft{"only " + next + " to " + id}; - char const *modes[]{"no lane change", toright.c_str(), toleft.c_str(), "lane change both ways"}; + auto const toright{format(STR_C("only %s to %s"), id.c_str(), next.c_str())}; + auto const toleft{format(STR_C("only %s to %s"), next.c_str(), id.c_str())}; + char const *modes[]{STR_C("no lane change"), toright.c_str(), toleft.c_str(), STR_C("lane change both ways")}; ImGui::Indent(); ImGui::SetNextItemWidth(200.0f); if (ImGui::Combo("##change", &State.changes[lane], modes, 4)) changed = true; + item_tooltip("Which way a vehicle may change between these two lanes"); ImGui::Unindent(); } ImGui::PopID(); @@ -2366,50 +2350,54 @@ void editor_mode::render_road_tool_options() auto &tool{m_roadtool}; std::string reason; if (false == editor_road::available(&reason)) - ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "%s", reason.c_str()); + ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "%s", STR(reason).c_str()); // the tools and what the place tool puts are chosen in the toolbar if (tool.tool == 1) { - if (ImGui::Checkbox("Roundabout", &tool.ring)) + if (ImGui::Checkbox(STR_C("Roundabout"), &tool.ring)) road_cancel(); + item_tooltip("A one-way road going around, with the lanes set below as the lanes along the axis.\nThen untick this and lead the roads out of its side, or into it"); if (tool.ring) { - ImGui::TextDisabled("LMB: put a roundabout around the cursor. It's a one-way road going around,"); - ImGui::TextDisabled("with the lanes set below as the lanes along the axis."); - ImGui::TextDisabled("Then untick this and lead the roads out of its side, or into it."); + gesture_rows({{"LMB", "a roundabout around the cursor"}}); ImGui::SetNextItemWidth(120.0f); - if (ImGui::InputFloat("Radius of the middle of its road [m]", &tool.ringradius, 1.0f, 5.0f, "%.1f")) + if (ImGui::InputFloat(STR_C("Radius [m]##ring"), &tool.ringradius, 1.0f, 5.0f, "%.1f")) tool.ringradius = std::clamp(tool.ringradius, 8.0f, 200.0f); - render_road_material("Island in the middle", tool.islandtext, sizeof(tool.islandtext), tool.island); - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", "What the middle is covered with; it's raised on a kerb as high as the kerbs of the road.\nnone: the middle is left as it is."); + item_tooltip("Radius of the middle of the road going around"); + render_road_material("Island in the middle", tool.island); + item_tooltip("What the middle is covered with; it's raised on a kerb as high as the kerbs of the road.\nNo texture: the middle is left as it is"); } else { - ImGui::TextDisabled("LMB: start, then each next point. Ctrl: straight ahead. Esc: finish"); - ImGui::TextDisabled("Start or end on a loose end of a road to join it."); - ImGui::TextDisabled("Start or end on the side of a road to make a junction there,"); - ImGui::TextDisabled("or on a junction to give it another road."); + gesture_rows({{"LMB", "the start, then each next point"}, + {"Ctrl", "straight ahead"}, + {"Esc", "finish the road"}, + {"LMB on a road or a junction", "the new road is joined to it there"}}); } if (tool.chain) { - if (ImGui::Button("Finish (Esc)")) + if (ImGui::Button(STR_C("Finish (Esc)"))) road_cancel(); } // how the road is put on the ground - ImGui::SetNextItemWidth(120.0f); - if (ImGui::InputFloat("Height above the ground [m]", &tool.offset, 0.05f, 0.25f, "%.2f")) - tool.offset = std::clamp(tool.offset, -10.0f, 100.0f); - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", "How far over the ground under the cursor the points are put.\nA few centimetres keep the surface from flickering where it lies on the ground."); - ImGui::Checkbox("Follow the ground", &tool.follow); - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", "On: the road is led over the ground between the clicked points, in pieces as short as the ground calls for,\nwith the profile rounded so the slope doesn't change abruptly.\nOff: the road goes straight from a point to the next one, like a ramp or a viaduct."); - ImGui::SetNextItemWidth(120.0f); - if (ImGui::InputFloat("Speed limit on new junctions [km/h]", &tool.crossingspeed, 5.0f, 10.0f, "%.0f")) - tool.crossingspeed = std::clamp(tool.crossingspeed, 5.0f, 200.0f); + ImGui::Checkbox(STR_C("Follow the ground"), &tool.follow); + item_tooltip("On: the road is led over the ground between the clicked points, in pieces as short as the ground calls for,\nwith the profile rounded so the slope doesn't change abruptly.\nOff: the road goes straight from a point to the next one, like a ramp or a viaduct"); + ImGui::PushID("build"); + if (ImGui::TreeNode(STR_C("More settings"))) + { + ImGui::SetNextItemWidth(120.0f); + if (ImGui::InputFloat(STR_C("Height above the ground [m]"), &tool.offset, 0.05f, 0.25f, "%.2f")) + tool.offset = std::clamp(tool.offset, -10.0f, 100.0f); + item_tooltip("How far over the ground under the cursor the points are put.\nA few centimetres keep the surface from flickering where it lies on the ground"); + ImGui::SetNextItemWidth(120.0f); + if (ImGui::InputFloat(STR_C("Junction speed limit [km/h]"), &tool.crossingspeed, 5.0f, 10.0f, "%.0f")) + tool.crossingspeed = std::clamp(tool.crossingspeed, 5.0f, 200.0f); + item_tooltip("The speed limit the junctions made by the new roads get"); + ImGui::TreePop(); + } + ImGui::PopID(); ImGui::Separator(); // what's set here is what the next pieces get render_road_layout(tool.settings); @@ -2419,21 +2407,10 @@ void editor_mode::render_road_tool_options() tool.placekind = std::clamp(tool.placekind, 0, 3); switch (tool.placekind) { - case 0: - ImGui::TextDisabled("LMB on a road where the rails cross it. The vehicles stop ahead"); - ImGui::TextDisabled("of the rails for as long as a train is coming."); - break; - case 1: - ImGui::TextDisabled("LMB on a lane. The vehicles of the set appear there one by one"); - ImGui::TextDisabled("and drive on the way the lane goes."); - break; - case 3: - ImGui::TextDisabled("LMB on a road: stripes are painted across it there."); - break; - default: - ImGui::TextDisabled("LMB on a lane. The vehicles which get there are taken off the road;"); - ImGui::TextDisabled("put one where the road leaves the scenery."); - break; + case 0: gesture_rows({{"LMB on a road", "where the rails cross it; the vehicles stop ahead of the rails while a train is coming"}}); break; + case 1: gesture_rows({{"LMB on a lane", "the vehicles of the set appear there one by one and drive the way the lane goes"}}); break; + case 3: gesture_rows({{"LMB on a road", "stripes are painted across it there"}}); break; + default: gesture_rows({{"LMB on a lane", "the vehicles getting there are taken off the road; put one where the road leaves the scenery"}}); break; } ImGui::Separator(); // what's set here is what the next points get @@ -2442,7 +2419,7 @@ void editor_mode::render_road_tool_options() render_roadpoint_layout(placing, nullptr); } else - ImGui::TextDisabled("The selected road is set up in the inspector"); + ImGui::TextDisabled("%s", STR_C("The selected road is set up in the inspector")); if (false == tool.status.empty()) { ImGui::Separator(); @@ -2460,7 +2437,7 @@ void editor_mode::render_road_selection() return ImGui::InputFloat(Label, &Value, Step, Step * 4.0f, Format, ImGuiInputTextFlags_EnterReturnsTrue); }; if (tool.tool != 0) - ImGui::TextDisabled("The select tool shows the road picked in the view here"); + ImGui::TextDisabled("%s", STR_C("The Select tool shows the road picked in the view here")); else if (tool.marker != nullptr) { auto &point{*tool.marker}; @@ -2468,38 +2445,36 @@ void editor_mode::render_road_selection() ImGui::Text("%s, %s", point.name().c_str(), point_label(state.kind)); if (render_roadpoint_layout(state, &point)) roadpoint_apply(point, state); - if (ImGui::Button("Delete (Del)")) + if (ImGui::Button(STR_C("Delete (Del)"))) road_delete(); } else if (false == tool.points.empty()) { // the road at the selected points - ImGui::Text("%d %s selected", static_cast(tool.points.size()), tool.points.size() == 1 ? "point" : "points"); - ImGui::TextDisabled("Shift+LMB: add a point, or take it out. K on a selected piece: make a point at the cursor"); + ImGui::Text(STR_C("Points selected: %d"), static_cast(tool.points.size())); + gesture_rows({{"Shift+LMB", "adds a point, or takes it out"}, {"K", "on a selected piece: a point at the cursor"}}); auto const ends{editor_road::ends_at(tool.points.front())}; if (false == ends.empty()) { auto const &layout{ends.front().road->definition()}; auto width{static_cast(layout.width(ends.front().atend ? 1 : 0) * layout.taper[ends.front().atend ? 1 : 0])}; - if (number("Road width here [m]", width, 0.25f, "%.2f")) + if (number(STR_C("Road width here [m]"), width, 0.25f, "%.2f")) road_point_width(std::clamp(width, 1.0f, 100.0f)); - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", "Combined width of the lanes at this point; each lane takes its share of it.\nThe pieces on both sides get wider or narrower along their length to meet it.\nSelect several points to keep the width over the pieces between them."); + item_tooltip("Combined width of the lanes at this point; each lane takes its share of it.\nThe pieces on both sides get wider or narrower along their length to meet it.\nSelect several points to keep the width over the pieces between them"); // heights: set outright, moved by a step, or taken from the ground auto height{static_cast(tool.points.front().y)}; - if (number("Height [m]", height, 0.1f, "%.2f")) + if (number(STR_C("Height [m]"), height, 0.1f, "%.2f")) road_point_heights(std::vector(tool.points.size(), height)); - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", "Height of the axis of the road at the point; with several points selected all are put at this height.\nThe slopes of the pieces at the point are kept, so the road stays smooth."); + item_tooltip("Height of the axis of the road at the point; with several points selected all are put at this height.\nThe slopes of the pieces at the point are kept, so the road stays smooth"); std::vector heights; for (auto const &point : tool.points) heights.emplace_back(point.y); - auto const moved{ImGui::Button("Lower") ? -1.0 : 0.0}; + auto const moved{ImGui::Button(STR_C("Lower")) ? -1.0 : 0.0}; ImGui::SameLine(); - auto const raised{ImGui::Button("Raise") ? 1.0 : 0.0}; + auto const raised{ImGui::Button(STR_C("Raise")) ? 1.0 : 0.0}; ImGui::SameLine(); ImGui::SetNextItemWidth(80.0f); - if (ImGui::InputFloat("by [m]", &tool.heightstep, 0.0f, 0.0f, "%.2f")) + if (ImGui::InputFloat(STR_C("by [m]##heightstep"), &tool.heightstep, 0.0f, 0.0f, "%.2f")) tool.heightstep = std::clamp(tool.heightstep, 0.01f, 50.0f); if (moved + raised != 0.0) { @@ -2508,7 +2483,7 @@ void editor_mode::render_road_selection() entry += (moved + raised) * tool.heightstep; road_point_heights(heights); } - if (ImGui::Button("Put on the ground")) + if (ImGui::Button(STR_C("Put on the ground"))) { // a point with nothing under it comes back with the height it has, and is left where it is auto const ground{ground_heights(tool.points, true)}; @@ -2518,31 +2493,30 @@ void editor_mode::render_road_selection() road_point_heights(heights); } if (ImGui::IsItemHovered()) - ImGui::SetTooltip("Puts each point %.2f m over the ground under it; the height above the ground is set in the Build tool.", tool.offset); + ImGui::SetTooltip(STR_C("Puts each point %.2f m over the ground under it; the height above the ground is set in the Build tool"), tool.offset); } - if (ImGui::Button(tool.points.size() == 1 ? "Delete the point (Del)" : "Delete the points (Del)")) + if (ImGui::Button(tool.points.size() == 1 ? STR_C("Delete the point (Del)") : STR_C("Delete the points (Del)"))) road_points_delete(); - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", "Takes the point out of the road: the pieces on its two sides become one piece,\n" - "led from the far end of one to the far end of the other the way the road goes there.\n" - "A point the road ends at takes the last piece of the road with it."); + item_tooltip("Takes the point out of the road: the pieces on its two sides become one piece,\n" + "led from the far end of one to the far end of the other the way the road goes there.\n" + "A point the road ends at takes the last piece of the road with it"); } else if (tool.junction != nullptr) { auto &junction{*tool.junction}; if (junction.definition().arms.size() == 2) { - ImGui::Text("%s, a stretch where the road changes its lanes", junction.name().c_str()); - ImGui::TextDisabled("It's drawn as a part of the road, and leads the lanes of one side to the lanes of the other."); + ImGui::Text(STR_C("%s, a stretch where the road changes its lanes"), junction.name().c_str()); + ImGui::TextDisabled("%s", STR_C("A part of the road, leading the lanes of one side to the other")); } else { - ImGui::Text("%s, %d roads, %d ways through", junction.name().c_str(), static_cast(junction.definition().arms.size()), static_cast(junction.movements().size())); - ImGui::TextDisabled("The ways through are made for the roads attached at the moment."); - ImGui::TextDisabled("Build tool, LMB on the junction: lead another road out of it"); + ImGui::Text(STR_C("%s, roads: %d, ways through: %d"), junction.name().c_str(), static_cast(junction.definition().arms.size()), static_cast(junction.movements().size())); + ImGui::TextDisabled("%s", STR_C("The ways through follow the roads attached now")); + item_tooltip("Build tool, LMB on the junction: lead another road out of it"); } render_junction_layout(junction); - if (ImGui::Button("Delete (Del)")) + if (ImGui::Button(STR_C("Delete (Del)"))) road_delete(); } else if (tool.selected != nullptr) @@ -2550,28 +2524,26 @@ void editor_mode::render_road_selection() auto const &road{*tool.selected}; auto const &layout{road.definition()}; if (layout.changing()) - ImGui::Text("%s, %.1f m, %d + %d to %d + %d lanes", road.name().c_str(), layout.length(), layout.lanes_at(0, true), layout.lanes_at(0, false), layout.lanes_at(1, true), + ImGui::Text(STR_C("%s, %.1f m, lanes %d + %d to %d + %d"), road.name().c_str(), layout.length(), layout.lanes_at(0, true), layout.lanes_at(0, false), layout.lanes_at(1, true), layout.lanes_at(1, false)); else - ImGui::Text("%s, %.1f m, %d + %d lanes", road.name().c_str(), layout.length(), layout.forward, layout.backward); - if (ImGui::Button("Delete (Del)")) + ImGui::Text(STR_C("%s, %.1f m, lanes %d + %d"), road.name().c_str(), layout.length(), layout.forward, layout.backward); + if (ImGui::Button(STR_C("Delete (Del)"))) road_delete(); ImGui::SameLine(); - ImGui::TextDisabled("K: split at the cursor"); + ImGui::TextDisabled("%s", STR_C("K: split at the cursor")); if (tool.settings.changing()) - ImGui::TextDisabled("This piece has lanes of its own at its end, so it's changed alone"); + ImGui::TextDisabled("%s", STR_C("This piece has lanes of its own at its end, so it's changed alone")); else - ImGui::Checkbox("Changes go to the whole road", &tool.whole); - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("%s", "A road is a string of pieces. With this on a change of the layout is made to all of them,\nexcept for the lane change rules, which are always set for the selected piece alone.\nWith this off the selected piece alone is changed, and the road next to it is fitted to it:\nmade wider or narrower towards it, or given a stretch where the lanes change if their number differs.\nSplit a piece (K) to get a piece of the length you need."); + ImGui::Checkbox(STR_C("Changes go to the whole road"), &tool.whole); + item_tooltip("A road is a string of pieces. With this on a change of the layout is made to all of them,\nexcept for the lane change rules, which are always set for the selected piece alone.\nWith this off the selected piece alone is changed, and the road next to it is fitted to it:\nmade wider or narrower towards it, or given a stretch where the lanes change if their number differs.\nSplit a piece (K) to get a piece of the length you need"); ImGui::Separator(); if (tool.selected != nullptr && render_road_layout(tool.settings)) road_apply(); } else { - ImGui::TextDisabled("LMB: select a road piece, a junction, a point where pieces meet,"); - ImGui::TextDisabled("a level crossing or a traffic point"); + gesture_rows({{"LMB", "a road piece, a junction, a point where pieces meet, a level crossing or a traffic point"}}); } } @@ -2743,28 +2715,28 @@ void editor_mode::draw_road_overlay() const } } if (labelled) - drawlabel(State.position, Color, closed ? "crossing, closed" : "crossing"); + drawlabel(State.position, Color, closed ? STR_C("crossing, closed") : STR_C("crossing")); break; } case roadpoint_node::kind_type::spawn: { drawpoint(State.position, Color, 11.0f, false); if (labelled) - drawlabel(State.position, Color, "spawn"); + drawlabel(State.position, Color, STR_C("spawn")); break; } case roadpoint_node::kind_type::despawn: { drawring(State.position, State.radius, Color); if (labelled) - drawlabel(State.position, Color, "removal"); + drawlabel(State.position, Color, STR_C("removal")); break; } case roadpoint_node::kind_type::crosswalk: { drawpoint(State.position, Color, 11.0f, false); if (labelled) - drawlabel(State.position, Color, "pedestrians"); + drawlabel(State.position, Color, STR_C("pedestrians")); break; } } @@ -2812,7 +2784,7 @@ void editor_mode::draw_road_overlay() const auto const centre{tool.mouse + glm::dvec3{0.0, tool.offset, 0.0}}; drawring(centre, tool.ringradius + 0.5 * layout.width(), kPreviewColor); drawring(centre, std::max(0.0, tool.ringradius - 0.5 * layout.width()), kPreviewColor); - hint = "LMB: put a roundabout here"; + hint = STR_C("LMB: put a roundabout here"); } else if (tool.tool == 1) { @@ -2823,7 +2795,7 @@ void editor_mode::draw_road_overlay() const if (plan.pieces.empty()) { projection.line(drawlist, tool.point, tool.mouse, kRefusedColor, 2.0f); - hint = plan.error + " "; + hint = STR(plan.error) + " "; } else { @@ -2841,9 +2813,9 @@ void editor_mode::draw_road_overlay() const } if (plan.snap.valid()) drawpoint(plan.snap.position, kSnapColor, 14.0f, false); - hint += (tool.branchroad != nullptr ? "LMB: lead the road out to the cursor, with a junction where it leaves Esc: give up" : - tool.branchjunction != nullptr ? "LMB: lead the road out to the cursor, as another road of the junction Esc: give up" : - "LMB: build up to the cursor Ctrl: straight ahead Esc: finish Ctrl+Z: undo the last piece"); + hint += (tool.branchroad != nullptr ? STR_C("LMB: lead the road out to the cursor, with a junction where it leaves Esc: give up") : + tool.branchjunction != nullptr ? STR_C("LMB: lead the road out to the cursor, as another road of the junction Esc: give up") : + STR_C("LMB: build up to the cursor Ctrl: straight ahead Esc: finish Ctrl+Z: undo the last piece")); } else { @@ -2851,17 +2823,17 @@ void editor_mode::draw_road_overlay() const if (end.valid()) { drawpoint(end.position, kSnapColor, 14.0f, false); - hint = "LMB: carry on from this end"; + hint = STR_C("LMB: carry on from this end"); } else if (tool.hashover) { drawpoint(tool.hover, kSnapColor, 5.0f, true); drawpoint(tool.hover, kSnapColor, 14.0f, false); - hint = "LMB: lead a road out of here, with a junction"; + hint = STR_C("LMB: lead a road out of here, with a junction"); } else { - hint = "LMB: set where the road starts; on a loose end of a road to carry it on, on the side of a road or on a junction to lead a road out of it"; + hint = STR_C("LMB: set where the road starts; on a loose end of a road to carry it on, on the side of a road or on a junction to lead a road out of it"); } } } @@ -2880,13 +2852,13 @@ void editor_mode::draw_road_overlay() const projection.line(drawlist, tip, tip - direction * 1.2 + across * 0.8, kPreviewColor, 2.0f); projection.line(drawlist, tip, tip - direction * 1.2 - across * 0.8, kPreviewColor, 2.0f); } - hint = std::string{"LMB: put a "} + point_label(tool.target.kind) + " here"; + hint = format(STR_C("LMB: put a %s here"), point_label(tool.target.kind)); if (false == tool.targetnote.empty()) hint += " " + tool.targetnote; } else { - hint = (tool.targetnote.empty() ? std::string{"LMB: put a "} + point_label(point_kind(tool.placekind)) + " on a road" : tool.targetnote); + hint = (tool.targetnote.empty() ? format(STR_C("LMB: put a %s on a road"), point_label(point_kind(tool.placekind))) : tool.targetnote); } } else @@ -2917,16 +2889,16 @@ void editor_mode::draw_road_overlay() const } auto const mouse{ImGui::GetIO().MousePos}; char label[64]; - std::snprintf(label, sizeof(label), "%+.2f m, to %.2f m", offset, tool.points.empty() ? 0.0 : tool.points.front().y + offset); + std::snprintf(label, sizeof(label), STR_C("%+.2f m, to %.2f m"), offset, tool.points.empty() ? 0.0 : tool.points.front().y + offset); drawlist->AddRectFilled(ImVec2(mouse.x + 14.0f, mouse.y - 4.0f), ImVec2(mouse.x + 22.0f + ImGui::CalcTextSize(label).x, mouse.y + 18.0f), IM_COL32(0, 0, 0, 170), 3.0f); drawlist->AddText(ImVec2(mouse.x + 18.0f, mouse.y - 2.0f), lifted, label); } - hint = tool.lifting ? "Drag up or down: the height of the selected points Ctrl: finer let go: set" : - tool.marker != nullptr ? "LMB: select a piece, a junction, a point or a marker Del: delete Ctrl+Z: undo" : - false == tool.points.empty() ? "LMB: select a point (under the terrain too) Shift+LMB: add a point or take it out Alt+LMB drag: the height Del: delete the points Ctrl+Z: undo" : - tool.selected != nullptr ? "LMB: select a piece, a junction or a point (white dot) K: split at the cursor Del: delete Ctrl+Z: undo" : - tool.junction != nullptr ? "LMB: select a piece, a junction or a point (white dot) Del: delete Ctrl+Z: undo" : - "LMB: select a piece, a junction, a point (white dot) or a marker"; + hint = tool.lifting ? STR_C("Drag up or down: the height of the selected points Ctrl: finer let go: set") : + tool.marker != nullptr ? STR_C("LMB: select a piece, a junction, a point or a marker Del: delete Ctrl+Z: undo") : + false == tool.points.empty() ? STR_C("LMB: select a point (under the terrain too) Shift+LMB: add a point or take it out Alt+LMB drag: the height Del: delete the points Ctrl+Z: undo") : + tool.selected != nullptr ? STR_C("LMB: select a piece, a junction or a point (white dot) K: split at the cursor Del: delete Ctrl+Z: undo") : + tool.junction != nullptr ? STR_C("LMB: select a piece, a junction or a point (white dot) Del: delete Ctrl+Z: undo") : + STR_C("LMB: select a piece, a junction, a point (white dot) or a marker"); } // shown above the place the track tools put their hints at ImVec2 const position{editor_ui::view_min().x + 12.0f, editor_ui::view_max().y - 56.0f}; diff --git a/application/editormoderoute.cpp b/application/editormoderoute.cpp new file mode 100644 index 000000000..dd79147ac --- /dev/null +++ b/application/editormoderoute.cpp @@ -0,0 +1,2423 @@ +/* +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: +*/ + + +#include "stdafx.h" +#include "application/editormode.h" +#include "application/editoruilayer.h" +#include "application/editorprojection.h" +#include "application/editormodeshared.h" +#include "application/editorgestures.h" +#include "editor/editorFormat.hpp" +#include "editor/editorAlignmentStore.hpp" +#include "editor/editorSwitchStore.hpp" +#include "editor/editorGeometry.hpp" +#include "editor/editorIncludeInfo.hpp" + +#include "utilities/Globals.h" +#include "rendering/renderer.h" +#include "world/Track.h" +#include "world/TrackFeatures.h" +#include "scene/scene.h" +#include "scene/scenelayers.h" +#include "simulation/simulation.h" +#include "utilities/Logs.h" +#include "utilities/translation.h" + +#include "imgui/imgui.h" +#include "imgui/ImGuizmo.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "application/editormodetrackshared.h" + +using namespace track_mode; + +bool editor_mode::route_active() const +{ + return ui()->mode() == nodebank_panel::TRACK && m_track_tab == track_tab::route && false == m_route.chain.tracks.empty(); +} + +void editor_mode::route_recommend(alignment::vertex &Vertex) const +{ + auto sharpest{Vertex.radius}; + if (Vertex.compound) + for (auto const &arc : Vertex.arcs) + sharpest = std::min(sharpest, arc.radius); + auto const recommended{alignment::recommend(m_route.design.speed, sharpest, laying_norms())}; + Vertex.cant = recommended.cant; + // the cants of the arcs in proportion to their curvature, as the norms recommend them + Vertex.first_cant = -1.0; + for (auto &arc : Vertex.arcs) + arc.cant = -1.0; + Vertex.transition_in = recommended.transition; + Vertex.transition_out = recommended.transition; + alignment::recommend_between(Vertex, m_route.design.speed, laying_norms()); +} + +void editor_mode::route_bind_ends() +{ + auto const &chain{m_route.chain}; + auto &design{m_route.design}; + design.start = chain.start; + design.end = chain.end; + design.start_direction = glm::normalize(plan_of(chain.start_direction)); + design.end_direction = glm::normalize(plan_of(chain.end_direction)); + design.start_grade = grade_of(chain.start_direction); + design.end_grade = grade_of(chain.end_direction); + design.start_radius = chain.start_radius; + design.end_radius = chain.end_radius; + design.start_turn = chain.start_turn; + design.end_turn = chain.end_turn; + design.start_reserve = editor_track::run_reserve(editor_track::straight_beyond(chain, false, m_straights.tolerance)); + design.end_reserve = editor_track::run_reserve(editor_track::straight_beyond(chain, true, m_straights.tolerance)); +} + +void editor_mode::route_reset() +{ + auto &route{m_route}; + route.chain = {}; + route.error.clear(); + route.status.clear(); + route.vertex = -1; + route.grip = -1; + route.result = {}; + route.trace = {}; + route.clicks.clear(); + route.click_states.clear(); + route.measured = -1; + if (route.from == nullptr || route.to == nullptr) + return; + if (false == editor_track::find_chain(route.from, route.to, route.chain, route.error, true)) + return; + if (false == route.chain.switches.empty()) + route.status = format(STR_C("The fragment runs through %zu switches along their main tracks. They move as a whole with the line, " + "so they have to fall on its straights"), + route.chain.switches.size()); + + auto const &chain{route.chain}; + alignment::design design; + design.norms = route.design.norms; + design.shape = route.design.shape; + design.transition_pieces = route.design.transition_pieces; + design.speed = chain.velocity > 0.0 ? chain.velocity : 100.0; + route.design = design; + route_bind_ends(); + design = route.design; + + glm::dvec2 intersection; + if (false == alignment::collinear(design)) + { + alignment::vertex vertex; + vertex.radius = chain.radius > 0.0 ? std::max(10.0, std::round(chain.radius / 10.0) * 10.0) : 1000.0; + route_recommend(vertex); + if (alignment::tangent_intersection(design, intersection)) + { + route.design.vertices.push_back(vertex); + } + else + { + auto const distance{plan_distance(design.start, design.end)}; + vertex.offset = distance / 3.0; + route.design.vertices.push_back(vertex); + route.design.vertices.push_back(vertex); + } + } + route_update(); +} + +bool editor_mode::route_from_curve(TTrack &Track) +{ + editor_track::curve curve; + if (false == editor_track::find_curve(Track, m_straights.tolerance, m_route.design.norms.gauge, curve)) + { + m_route.chain = {}; + m_route.result = {}; + m_route.vertex = -1; + m_route.grip = -1; + m_route.error = STR_C("No curve here: LMB on a curve"); + return false; + } + m_route.from = curve.from; + m_route.to = curve.to; + route_reset(); + if (m_route.chain.tracks.empty()) + return false; + auto &design{m_route.design}; + auto vertex{route_vertex_of(curve)}; + m_route.designed = curve.designed.has_value() ? 1 : 0; + if (curve.reversals == 0) + { + design.vertices = {vertex}; + route_curved_ends(); + } + else + { + auto const distance{plan_distance(design.start, design.end)}; + vertex.offset = distance / 3.0; + vertex.compound = false; + vertex.reverse_turn = false; + design.vertices = {vertex, vertex}; + route_update(); + } + m_route.status = format(STR_P("Curve of %zu path, turning %d deg", "Curve of %zu paths, turning %d deg", m_route.chain.tracks.size()), m_route.chain.tracks.size(), static_cast(std::round(glm::degrees(curve.turn)))); + return true; +} + +void editor_mode::route_curved_ends() +{ + auto &design{m_route.design}; + design.start_curved = false; + design.end_curved = false; + if (design.vertices.empty() || m_route.chain.tracks.empty()) + { + route_update(); + return; + } + // a curve beginning right at an end of the fragment at the curvature of the track adjoining there, turning its way, goes on from it, + // as a curve laid on from the diverging track of a switch does: laid so again, not from a straight there; so next to a switch laid + // into the curve too. A track of R 10 km or more is a straight there, as the lay tool takes it. The way the first curve and the last + // one turn by the legs of the polygon + auto const count{design.vertices.size()}; + auto const turn_of = [&](bool const Atend) { + if (count == 1) + return cross(design.start_direction, design.end_direction) > 0.0 ? 1 : -1; + glm::dvec2 const in{Atend ? design.vertices[count - 1].position - design.vertices[count - 2].position : design.start_direction}; + glm::dvec2 const out{Atend ? design.end_direction : design.vertices[1].position - design.vertices[0].position}; + return cross(in, out) > 0.0 ? 1 : -1; + }; + auto const goes_on = [&](bool const Atend) { + auto const radius{Atend ? design.end_radius : design.start_radius}; + if (radius <= 0.0 || radius >= 10000.0 || (Atend ? design.end_turn : design.start_turn) != turn_of(Atend)) + return false; + // within a tenth: the path of a switch bent into the curve approximates it at its ends, R 860 m at the start of one in R 800 m + auto const *track{Atend ? m_route.chain.tracks.back() : m_route.chain.tracks.front()}; + auto const bend{editor_track::bend_at(*track, Atend ? m_route.chain.end : m_route.chain.start)}; + return bend.has_value() && std::abs(std::abs(bend->curvature) - 1.0 / radius) <= 0.1 / radius; + }; + design.start_curved = goes_on(false); + design.end_curved = (count > 1 || false == design.start_curved) && goes_on(true); + route_update(); + // a curve read from its paths as going on from the curve adjoining it which the design can't lay along them so, as one whose arc + // going on is too short to be read as an arc: read from a straight there, whichever of the two keeps closer to its paths + if (design.start_curved || design.end_curved) + { + auto const departure = [&]() { + TTrack *worst{nullptr}; + return m_route.result.valid ? alignment_store::deviation(m_route.result, m_route.chain.tracks, worst) : std::numeric_limits::max(); + }; + auto const curved{departure()}; + if (curved > 0.25) + { + auto const kept{design}; + design.start_curved = false; + design.end_curved = false; + route_update(); + if (departure() >= curved) + { + design = kept; + route_update(); + } + } + } +} + +alignment::vertex editor_mode::route_vertex_of(editor_track::curve const &Curve) const +{ + if (Curve.designed.has_value()) + return *Curve.designed; + alignment::vertex vertex; + vertex.radius = Curve.radius > 0.0 ? std::max(1.0, Curve.radius) : 1000.0; + vertex.transition_in = std::max(0.0, Curve.transition_in); + vertex.transition_out = std::max(0.0, Curve.transition_out); + vertex.cant = std::max(0.0, Curve.cant); + vertex.reverse_turn = std::abs(Curve.turn) > glm::pi(); + compound_from(Curve, vertex); + return vertex; +} + + +bool editor_mode::route_load(TTrack &Track) +{ + m_route.designed = 0; + if (false == (m_route.single ? route_from_curve(Track) : route_from_line(Track))) + return false; + route_read_stored(Track); + // the points clicked along the line when it was laid, wherever they're kept + m_route.clicks = alignment_store::clicks_along(m_route.result, 3.0); + m_route.measured = -1; + return true; +} + +// the design kept in the scenery for the fragment takes the place of the one read from the paths; its chainage is carried on +void editor_mode::route_read_stored(TTrack &Track) +{ + auto &route{m_route}; + route.departed = -1; + route.departure = 0.0; + route.origin = 0.0; + if (route.chain.tracks.empty()) + return; + auto const chain{route.chain}; + bool reversed; + auto index{alignment_store::find(chain.start, chain.end, reversed)}; + route.departed = alignment_store::departed(chain.tracks, route.departure); + auto const loose{std::any_of(chain.tracks.begin(), chain.tracks.end(), [](TTrack const *Track) { return false == alignment_store::on_track(*Track).has_value(); })}; + bool digitized{false}; + int parts{0}; + int skipped{0}; + std::string failure; + if (index < 0 && route.departed < 0 && loose && false == route.single) + { + parts = digitize_parts(chain, &failure, skipped); + if (parts == 1 && skipped == 0) + { + alignment_store::settle(); + index = alignment_store::find(chain.start, chain.end, reversed); + digitized = true; + } + else if (parts > 0) + { + alignment_store::settle(); + route_from_line(Track); + route.departed = alignment_store::departed(route.chain.tracks, route.departure); + } + } + if (index >= 0 && false == reversed && false == route.single) + { + route_take_stored(index); + } + else if (auto const km{alignment_store::chainage_at(chain.start)}) + { + auto const ahead{chain.start + glm::dvec3{route.design.start_direction.x, 0.0, route.design.start_direction.y}}; + auto const further{alignment_store::chainage_at(ahead)}; + if (further.has_value() && *further > *km) + route.origin = *km; + } + if (digitized && route.designed == 0) + route.status += STR_C("\nThe line is digitized now, a straight"); + else if (digitized) + route.status += format(STR_C("\nThe line is digitized now, curves kept in the scenery: %d"), route.designed); + else if (parts > 0) + route.status += format(STR_C("\nThe line is digitized in parts: %d, paths left out: %d"), parts, skipped) + (failure.empty() ? std::string{} : " - " + failure); + else if (skipped > 0 && loose && skipped < static_cast(chain.tracks.size())) + route.status += format(STR_C("\nPaths left out of the digitized line: %d"), skipped) + (failure.empty() ? std::string{} : " - " + failure); + else if (false == failure.empty()) + route.status += STR_C("\nThe line can't be digitized: ") + failure; + else if (route.designed > 0) + route.status += format(STR_C("\nCurves read from the design kept in the scenery: %d"), route.designed); + else if (false == route.design.vertices.empty()) + route.status += STR_C("\nCurves recognized from the paths, the scenery keeps no design for them"); +} + +void editor_mode::route_take_stored(int const Index) +{ + auto &route{m_route}; + auto const &records{alignment_store::records()}; + if (Index < 0 || Index >= static_cast(records.size())) + return; + auto const &stored{records[Index]}; + auto &design{route.design}; + design.vertices = stored.design.vertices; + design.shape = stored.design.shape; + design.speed = stored.design.speed; + design.norms = stored.design.norms; + design.transition_pieces = stored.design.transition_pieces; + design.arc_piece_angle = stored.design.arc_piece_angle; + // a curve laid going on from the curve of the track adjoining keeps going on from it, its radius the one which begins it there + design.start_curved = stored.design.start_curved; + design.end_curved = stored.design.end_curved; + design.start_cant = stored.design.start_cant; + design.end_cant = stored.design.end_cant; + route.designed = static_cast(design.vertices.size()); + route.origin = stored.origin; + route.vertex = -1; + route.grip = -1; + route_update(); +} + +void editor_mode::render_route_stored() +{ + auto &route{m_route}; + auto km{route.origin / 1000.0}; + if (begin_fields("##routeorigin")) + { + field_row("Km of the start"); + if (ImGui::InputDouble("##routekm", &km, 0.0, 0.0, "%.3f")) + route.origin = km * 1000.0; + item_tooltip("Chainage of the start of the fragment, kept with the design in the scenery; the vertical profile of these paths counts from it"); + ImGui::EndTable(); + } + auto const &records{alignment_store::records()}; + if (route.departed < 0 || route.departed >= static_cast(records.size()) || false == scene::Layers.valid(records[route.departed].layer)) + return; + auto const &layer{scene::Layers.layer(records[route.departed].layer).name}; + ImGui::PushTextWrapPos(0.0f); + ImGui::TextColored(ImVec4(1.0f, 0.7f, 0.2f, 1.0f), STR_C("The design kept in %s for this fragment departs from its paths by up to %.2f m"), layer.c_str(), route.departure); + ImGui::PopTextWrapPos(); + if (ImGui::SmallButton(STR_C("Take the kept design"))) + { + route_take_stored(route.departed); + route.status = STR_C("The kept design is loaded, applying it lays the paths by it again"); + } + item_tooltip("Loads the design kept in the scenery in place of the one read from the paths; nothing changes until it's applied"); + ImGui::SameLine(); + if (ImGui::SmallButton(STR_C("Forget the kept design"))) + { + alignment_store::forget(route.departed); + alignment_store::settle(); + route.departed = -1; + route.status = format(STR_C("The kept design will be removed from %s on save"), layer.c_str()); + } + item_tooltip("The paths stay as they are, the scenery no longer keeps a design for them"); +} + +void editor_mode::route_store() +{ + auto &route{m_route}; + if (false == route.result.valid || route.chain.tracks.empty() || scene::Layers.empty()) + return; + alignment_store::store(route.design, route.result, route.origin, alignment_store::layer_of(*route.chain.tracks.front()), "designed", 0.0, route.clicks); + route.departed = -1; + route.departure = 0.0; +} + +bool editor_mode::digitize_drawn(std::vector const &Created, bool const Alone) +{ + std::vector drawn; + for (auto *track : Created) + if (track != nullptr && track->eType == tt_Normal && false == track->m_editorremoved && false == track->m_paths.empty()) + drawn.push_back(track); + if (drawn.empty() || scene::Layers.empty()) + return false; + editor_track::chain chain; + std::string error; + if (editor_track::find_run(*drawn.front(), kDrawnReach, chain, error) && digitize_chain(chain)) + return true; + if (Alone && editor_track::find_chain(drawn.front(), drawn.back(), chain, error) && chain.tracks.size() == drawn.size() && digitize_chain(chain)) + return true; + WriteLog("Editor: the drawn paths don't make a line of straights, arcs and transition curves, no design kept for them", logtype::generic); + return false; +} + +void editor_mode::digitize_all(int *Kept, int *Failed) +{ + std::set visited; + int kept{0}; + int failed{0}; + std::string first; + for (auto *track : simulation::Paths.sequence()) + { + if (track == nullptr || track->m_editorremoved || track->eType != tt_Normal || track->m_paths.empty() || false == editor_track::is_supported(*track) || visited.count(track) > 0) + continue; + if (alignment_store::on_track(*track).has_value()) + continue; + editor_track::chain chain; + std::string error; + if (false == editor_track::find_run(*track, kDrawnReach, chain, error) || chain.tracks.empty()) + { + visited.insert(track); + continue; + } + visited.insert(chain.tracks.begin(), chain.tracks.end()); + std::string reason; + kept += digitize_parts(chain, &reason, failed); + if (first.empty()) + first = reason; + } + alignment_store::settle(); + if (Kept != nullptr) + *Kept = kept; + if (Failed != nullptr) + *Failed = failed; + auto text{format(STR_C("Lines digitized: %d, paths left out: %d"), kept, failed)}; + if (false == first.empty()) + text += STR_C(", the first: ") + first; + WriteLog("Editor: " + text, logtype::generic); + ui()->set_status(text, failed > 0); + if (false == m_route.chain.tracks.empty()) + route_load(*m_route.chain.tracks[m_route.chain.tracks.size() / 2]); +} + +int editor_mode::digitize_parts(editor_track::chain const &Chain, std::string *Reason, int &Skipped) +{ + auto const count{Chain.tracks.size()}; + if (count == 0 || std::all_of(Chain.tracks.begin(), Chain.tracks.end(), [](TTrack const *Track) { return alignment_store::on_track(*Track).has_value(); })) + return 0; + TTrack *culprit{nullptr}; + std::string reason; + if (digitize_chain(Chain, &reason, &culprit)) + return 1; + if (count == 1) + { + ++Skipped; + reason = name_of(*Chain.tracks.front()) + ": " + reason; + WriteLog("Editor: digitizing - " + reason, logtype::generic); + if (Reason != nullptr && Reason->empty()) + *Reason = reason; + return 0; + } + auto const found{static_cast(std::find(Chain.tracks.begin(), Chain.tracks.end(), culprit) - Chain.tracks.begin())}; + auto const split{found < count ? std::max(1, found) : count / 2}; + int parts{0}; + for (auto const &[first, last] : {std::pair{0, split - 1}, std::pair{split, count - 1}}) + { + editor_track::chain part; + std::string error; + if (editor_track::find_chain(Chain.tracks[first], Chain.tracks[last], part, error) && part.tracks.size() == last - first + 1) + parts += digitize_parts(part, Reason, Skipped); + else + Skipped += static_cast(last - first + 1); + } + return parts; +} + +bool editor_mode::digitize_chain(editor_track::chain const &Chain, std::string *Reason, TTrack **Culprit) +{ + if (Chain.tracks.empty() || scene::Layers.empty()) + return false; + auto const name = [](TTrack const *Track) { return Track == nullptr || Track->name().empty() ? std::string{STR_C("(no name)")} : Track->name(); }; + auto const nearest = [&](glm::dvec2 const &Point) { + TTrack *found{nullptr}; + double distance{std::numeric_limits::max()}; + for (auto *track : Chain.tracks) + for (auto const end : {segment_data::point::start, segment_data::point::end}) + if (auto const d{glm::distance(plan_of(track->m_paths.front().points[end]), Point)}; d < distance) + { + distance = d; + found = track; + } + return found; + }; + alignment::design design; + design.norms = m_route.design.norms; + design.transition_pieces = m_route.design.transition_pieces; + design.arc_piece_angle = m_route.design.arc_piece_angle; + design.speed = Chain.velocity > 0.0 ? Chain.velocity : 100.0; + design.start = Chain.start; + design.end = Chain.end; + if (glm::length(plan_of(Chain.start_direction)) < 1e-9 || glm::length(plan_of(Chain.end_direction)) < 1e-9) + return false; + design.start_direction = glm::normalize(plan_of(Chain.start_direction)); + design.end_direction = glm::normalize(plan_of(Chain.end_direction)); + design.start_grade = grade_of(Chain.start_direction); + design.end_grade = grade_of(Chain.end_direction); + design.start_radius = Chain.start_radius; + design.end_radius = Chain.end_radius; + design.start_turn = Chain.start_turn; + design.end_turn = Chain.end_turn; + auto const preferred{m_route.design.shape}; + auto const other{preferred == alignment::transition_shape::clothoid ? alignment::transition_shape::cubic_parabola : alignment::transition_shape::clothoid}; + alignment::result result; + alignment::design best; + alignment::result bestresult; + double closest{std::numeric_limits::max()}; + TTrack *farthest{nullptr}; + bool fits{false}; + for (auto const attempt : {0, 1, 2, 3}) + { + auto const shape{attempt % 2 == 0 ? preferred : other}; + design.shape = shape; + if (attempt == 2) + { + design.norms.arc_min = 0.0; + design.norms.arc_min_factor = 0.0; + } + design.vertices.clear(); + for (auto const &entry : editor_track::recognize_line(Chain, m_straights.tolerance, design.norms.gauge, shape)) + { + if (entry.kink) + { + if (Reason != nullptr) + *Reason = format(STR_C("the straights meet with no curve at path %s"), name(nearest(entry.position)).c_str()); + if (Culprit != nullptr) + *Culprit = nearest(entry.position); + return false; + } + auto vertex{route_vertex_of(entry.shape)}; + vertex.position = entry.position; + design.vertices.push_back(vertex); + } + if (design.vertices.size() >= 2) + { + design.vertices.front().offset = std::max(0.0, glm::dot(design.vertices.front().position - plan_of(design.start), design.start_direction)); + design.vertices.back().offset = std::max(0.0, glm::dot(plan_of(design.end) - design.vertices.back().position, design.end_direction)); + } + result = alignment::compute(design); + if (alignment_store::follows(result, Chain.tracks)) + { + fits = true; + break; + } + TTrack *worst{nullptr}; + if (auto const away{alignment_store::deviation(result, Chain.tracks, worst)}; away < closest) + { + closest = away; + farthest = worst; + best = design; + bestresult = result; + } + } + double fit{0.0}; + if (false == fits && closest <= kDigitizeFit) + { + design = best; + result = bestresult; + fit = closest; + fits = true; + } + if (false == fits) + { + if (Culprit != nullptr) + *Culprit = farthest; + if (Reason != nullptr) + *Reason = closest < std::numeric_limits::max() ? format(STR_C("the curves read from the paths leave path %s by %.2f m"), name(farthest).c_str(), closest) : std::string{STR_C("the paths don't make a line of straights, arcs and transition curves")}; + return false; + } + auto const &records{alignment_store::records()}; + std::set covered; + for (auto *track : Chain.tracks) + if (auto const found{alignment_store::on_track(*track)}) + covered.insert(found->record); + double origin{0.0}; + for (auto const index : covered) + { + auto const &old{records[index]}; + auto const start{alignment_store::chainage_on(result, alignment_store::kept_start(old))}; + auto const end{alignment_store::chainage_on(result, alignment_store::kept_end(old))}; + if (false == start.has_value() || false == end.has_value()) + return false; + if (index == *covered.begin() && *end > *start) + origin = old.origin + old.from - *start; + } + auto const layer{covered.empty() ? alignment_store::layer_of(*Chain.tracks.front()) : records[*covered.begin()].layer}; + for (auto index{covered.rbegin()}; index != covered.rend(); ++index) + alignment_store::forget(*index); + alignment_store::store(design, result, origin, layer, "drawn", fit); + return true; +} + +bool editor_mode::route_from_line(TTrack &Track) +{ + auto &route{m_route}; + editor_track::chain run; + if (false == editor_track::find_run(Track, kLineReach, run, route.error)) + return false; + route.from = run.tracks.front(); + route.to = run.tracks.back(); + route_reset(); + if (route.chain.tracks.empty()) + return false; + auto &design{route.design}; + auto const found{editor_track::recognize_line(route.chain, m_straights.tolerance, design.norms.gauge, design.shape)}; + route.designed = 0; + if (false == found.empty()) + { + design.vertices.clear(); + for (auto const &entry : found) + { + alignment::vertex vertex; + if (entry.kink) + { + vertex.radius = std::max(10.0, std::round(alignment::recommend(design.speed, 1000.0, design.norms).radius_min / 10.0) * 10.0); + vertex.transition_in = 0.0; + vertex.transition_out = 0.0; + vertex.cant = 0.0; + } + else + { + vertex = route_vertex_of(entry.shape); + if (entry.shape.designed.has_value()) + ++route.designed; + } + vertex.position = entry.position; + design.vertices.push_back(vertex); + } + if (design.vertices.size() >= 2) + { + design.vertices.front().offset = std::max(0.0, glm::dot(design.vertices.front().position - plan_of(design.start), design.start_direction)); + design.vertices.back().offset = std::max(0.0, glm::dot(plan_of(design.end) - design.vertices.back().position, design.end_direction)); + } + route_curved_ends(); + } + route.status = format(STR_P("Line of %zu path, %.0f m, %zu vertices", "Line of %zu paths, %.0f m, %zu vertices", route.chain.tracks.size()), route.chain.tracks.size(), route.chain.length, design.vertices.size()); + return true; +} + +void editor_mode::route_apply() +{ + m_route.error.clear(); + route_lay(); + if (false == m_route.error.empty()) + refused(m_route.error); +} + +void editor_mode::route_lay() +{ + auto &route{m_route}; + route.status.clear(); + m_infra_carried.clear(); + if (false == route.result.valid || route.chain.tracks.empty()) + return; + editor_track::chain chain; + if (false == editor_track::find_chain(route.from, route.to, chain, route.error, true)) + return; + if (glm::distance(chain.start, route.chain.start) > 1e-3 || glm::distance(chain.end, route.chain.end) > 1e-3) + { + route.error = STR_C("The fragment changed since it was selected, select it again"); + return; + } + auto involved{chain.tracks}; + for (auto const &passage : chain.switches) + involved.push_back(passage.track); + if (false == tracks_editable(involved, route.error)) + return; + // the crossovers of the line can't be moved as their switches are: they're taken out, the line laid again, and they go back + // where they were, onto the new line + if (false == route.relaying) + { + struct again + { + int shape; + glm::dvec3 press, release; + std::string name; + std::vector names; // of the switches at the press and at the release + }; + std::vector crossovers; + std::vector seen; + // a line which ends on a switch of a crossover would be laid again only up to it, the crossover left on a kink + for (auto const &end : {chain.start, chain.end}) + for (auto *track : chain.tracks) + for (auto const &[other, point] : editor_track::connected_points(*track, end)) + if (other != nullptr && other->eType == tt_Switch && crossover_of(*other).has_value()) + { + route.error = format(STR_C("The line ends on the switch %s of a crossover: move the crossover off the curve or take it out, change both lines, then lay it again"), other->name().c_str()); + return; + } + std::vector switches; + for (auto const &passage : chain.switches) + switches.push_back(passage.track); + for (auto *switchtrack : switches) + { + auto const crossover{crossover_of(*switchtrack)}; + if (false == crossover.has_value() || std::find(seen.begin(), seen.end(), crossover->first) != seen.end()) + continue; + seen.push_back(crossover->first); + // the press on this line, the release on the other one + auto *here{crossover->first == switchtrack ? crossover->first : crossover->second}; + auto *there{here == crossover->first ? crossover->second : crossover->first}; + crossovers.push_back({crossover_template(crossover->record), here->m_paths.front().points[segment_data::point::start], there->m_paths.front().points[segment_data::point::start], crossover->first->name(), {here->name(), there->name()}}); + } + if (false == crossovers.empty()) + { + auto const tab{m_track_tab}; + std::vector> states; + std::vector created; + std::vector removed; + // the designs of the outer tracks come down with the lifts taken back, an undo puts them back + profile_library_load(); + auto library{m_profiles}; + bool lifted{false}; + for (auto *switchtrack : switches) + if (auto const crossover{crossover_of(*switchtrack)}) + { + TTrack *first{nullptr}; + TTrack *second{nullptr}; + lifted = lifted || crossover->record.lifted(); + take_out_crossover(*crossover, states, created, removed, first, second); + } + switch_store::follow(); + push_track_snapshot(std::move(states), std::move(created), std::move(removed)); + records_to_history(); + if (lifted) + profiles_to_history(std::move(library)); + show_track_tab(tab); + // the line between the same points again: taking the lift back may have cut its paths + auto const end_at = [&](glm::dvec3 const &Point) -> TTrack * { + for (auto *track : simulation::Paths.sequence()) + if (track != nullptr && false == track->m_editorremoved && track->eType == tt_Normal && false == track->m_paths.empty()) + for (auto const which : {segment_data::point::start, segment_data::point::end}) + if (plan_distance(track->m_paths.front().points[which], Point) < 0.01) + return track; + return nullptr; + }; + auto *start{end_at(route.chain.start)}; + auto *finish{end_at(route.chain.end)}; + editor_track::chain refreshed; + std::string error; + if (start != nullptr && finish != nullptr && editor_track::find_chain(start, finish, refreshed, error, true)) + { + route.from = start; + route.to = finish; + route.chain = refreshed; + } + route.relaying = true; + auto const steps{m_history.size()}; + route_apply(); + route.relaying = false; + if (m_history.size() == steps) + { + undo_last(); + return; + } + join_last_steps(); + std::string back, left; + for (auto const &crossover : crossovers) + { + // the new line moved sideways: the press onto it, the release onto the other line + if (lay_crossover(crossover.shape, crossover.press, crossover.release, 30.0, crossover.names)) + { + join_last_steps(); + back += (back.empty() ? "" : ", ") + crossover.name; + } + else + { + left += (left.empty() ? "" : ", ") + crossover.name; + route.crossovers_out.push_back({crossover.shape, crossover.press, crossover.release, crossover.name, crossover.names}); + } + } + show_track_tab(tab); + if (false == back.empty()) + route.status += "\n" + format(STR_C("Crossovers laid again on the new line: %s"), back.c_str()); + if (false == left.empty()) + route.status += "\n" + format(STR_C("Crossovers taken out which don't fit the new line, lay them again: %s"), left.c_str()); + return; + } + } + + std::vector> states; + std::vector created; + // takes back what was done before the paths were re-laid + auto const undo = [&]() { + for (auto *track : created) + editor_track::retire(*track); + for (auto entry = states.rbegin(); entry != states.rend(); ++entry) + { + editor_track::apply(*entry->first, entry->second); + editor_track::commit({entry->first}); + } + }; + auto *from{route.from}; + auto *to{route.to}; + auto const startextension{route.result.start_extension}; + auto const endextension{route.result.end_extension}; + if (startextension > 0.0 || endextension > 0.0) + { + auto const before{chain}; + if (startextension > 0.0) + from = editor_track::take_straight(editor_track::straight_beyond(before, false, m_straights.tolerance), from, before.start, route.result.start, states, created); + if (endextension > 0.0) + to = editor_track::take_straight(editor_track::straight_beyond(before, true, m_straights.tolerance), to, before.end, route.result.end, states, created); + std::string error; + auto const found{editor_track::find_chain(from, to, chain, error, true)}; + auto const startoff{found && startextension > 0.0 ? plan_distance(chain.start, route.result.start) : 0.0}; + auto const endoff{found && endextension > 0.0 ? plan_distance(chain.end, route.result.end) : 0.0}; + if (false == found || startoff > 5.0 || endoff > 5.0) + { + auto const startrun{editor_track::straight_beyond(before, false, m_straights.tolerance)}; + auto const endrun{editor_track::straight_beyond(before, true, m_straights.tolerance)}; + WriteLog(format("editor: cutting the straights failed: found %d, start %.2f m off (extension %.2f, run %zu paths %.2f m), end %.2f m off (extension %.2f, run %zu paths %.2f m), chain %zu paths, from %s, to %s, error '%s'", found ? 1 : 0, startoff, + startextension, startrun.tracks.size(), startrun.length, endoff, endextension, endrun.tracks.size(), endrun.length, chain.tracks.size(), from != nullptr ? from->name().c_str() : "-", to != nullptr ? to->name().c_str() : "-", error.c_str())); + undo(); + route.error = error.empty() ? format(STR_C("The adjoining straights can't be cut at the ends of the curve: the start misses by %.1f m, the end by %.1f m"), startoff, endoff) : error; + return; + } + if (false == tracks_editable(chain.tracks, route.error)) + { + undo(); + return; + } + } + for (auto *track : chain.tracks) + if (std::none_of(states.begin(), states.end(), [&](auto const &Entry) { return Entry.first == track; })) + states.emplace_back(track, editor_track::capture(*track)); + std::vector relaid; + if (chain.switches.empty()) + { + std::vector intervals; + auto pieces{alignment::pieces_at(route.result, route.design, chain.tracks.size(), editor_track::chain_joints(chain), intervals)}; + editor_track::keep_heights(chain, pieces); + relaid = editor_track::relay(chain, pieces, &to, &intervals); + } + else if (false == route_relay_through_switches(chain, states, relaid, to)) + { + undo(); + return; + } + // the straights were cut along their own direction, the curve ends where the design says: the ends are brought together + auto const added{relaid.size()}; + created.insert(created.end(), relaid.begin(), relaid.end()); + push_track_snapshot(std::move(states), std::move(created)); + + route.from = from; + route.to = to; + editor_track::find_chain(route.from, route.to, route.chain, route.error, true); + if (startextension > 0.0 || endextension > 0.0) + { + route_bind_ends(); + auto &vertices{route.design.vertices}; + if (vertices.size() >= 2) + { + vertices.front().offset += startextension; + vertices.back().offset += endextension; + } + route_update(); + } + route_store(); + records_to_history(); + route.status = added > 0 ? format(STR_P("Re-laid %zu path, added %zu", "Re-laid %zu paths, added %zu", chain.tracks.size()), chain.tracks.size(), added) : format(STR_P("Re-laid %zu path", "Re-laid %zu paths", chain.tracks.size()), chain.tracks.size()); + if (startextension > 0.0 || endextension > 0.0) + route.status += format(STR_C(", the curve took over %.2f / %.2f m of the adjoining straights"), startextension, endextension); + route.status += infra_carried_note(); + // the crossovers taken out before which fit the lines now + if (false == route.relaying && false == route.crossovers_out.empty()) + { + auto const tab{m_track_tab}; + std::string back; + for (auto out{route.crossovers_out.begin()}; out != route.crossovers_out.end();) + if (lay_crossover(out->shape, out->press, out->release, 30.0, out->names)) + { + join_last_steps(); + back += (back.empty() ? "" : ", ") + out->name; + out = route.crossovers_out.erase(out); + } + else + ++out; + show_track_tab(tab); + if (false == back.empty()) + route.status += "\n" + format(STR_C("Crossovers laid again on the new line: %s"), back.c_str()); + } + WriteLog("Editor: route design - " + route.status, logtype::generic); +} + +// the switches of the chain are moved as a whole onto the designed line, the regular paths between them re-laid +bool editor_mode::route_relay_through_switches(editor_track::chain const &Chain, std::vector> &States, std::vector &Created, TTrack *&Last) +{ + auto &route{m_route}; + auto const &result{route.result}; + auto const name = [](TTrack const *Track) { return name_of(*Track); }; + auto const plan = [](glm::dvec3 const &Vector) { return glm::normalize(plan_of(Vector)); }; + struct placement + { + TTrack *track; + double from, length; // chainage along the new line + glm::dvec3 entry; // of the main track, where the chain comes in + double angle; + }; + // chainages along the old line, the switches keep their distance from the nearer end of the chain + double before{0.0}; + std::vector starts; + std::size_t next{0}; + for (std::size_t i = 0; i <= Chain.tracks.size(); ++i) + { + for (; next < Chain.switches.size() && Chain.switches[next].before == i; ++next) + { + starts.push_back(before); + before += bezier{Chain.switches[next].track->m_paths.front()}.plan_length(); + } + if (i < Chain.tracks.size()) + before += bezier{Chain.tracks[i]->m_paths.front()}.plan_length(); + } + auto const oldlength{before}; + std::vector placements; + std::vector ends; // of the switches along the new line + for (std::size_t k = 0; k < Chain.switches.size(); ++k) + { + auto const &passage{Chain.switches[k]}; + auto const &main{passage.track->m_paths.front()}; + auto const length{bezier{main}.plan_length()}; + auto const from{starts[k] + length * 0.5 < oldlength * 0.5 ? starts[k] : result.length - (oldlength - starts[k])}; + if (from < 0.0 || from + length > result.length || (false == ends.empty() && from < ends.back() - 0.01)) + { + route.error = format(STR_C("The switch %s doesn't fit on the designed line"), name(passage.track).c_str()); + return false; + } + auto const entry{main.points[passage.forward ? segment_data::point::start : segment_data::point::end]}; + auto const exit{main.points[passage.forward ? segment_data::point::end : segment_data::point::start]}; + bezier const curve{main}; + auto const direction{passage.forward ? plan(curve.first(0.0)) : -plan(curve.first(1.0))}; + auto const first{alignment::evaluate(result, from)}; + auto const last{alignment::evaluate(result, from + length)}; + auto const angle{signed_angle(direction, plan(first.direction))}; + // where the other end of the main track goes, set against the line + auto const moved{plan_of(first.position) + turned(plan_of(exit - entry), angle)}; + auto const departure{glm::distance(moved, plan_of(last.position))}; + if (departure > 0.02) + { + route.error = format(STR_C("The switch %s would leave the designed line by %.2f m at its other end: it lies in a curve of the design. " + "Move the vertices so that the switch falls on a straight"), + name(passage.track).c_str(), departure); + return false; + } + placements.push_back({passage.track, from, length, entry, angle}); + ends.push_back(from); + ends.push_back(from + length); + } + // the regular parts between the switches, cut at the joints of their paths set square onto the new line where they follow one + // another along it, else one interval each; the switches taking the ones between + auto const parts{editor_track::chain_parts(Chain)}; + std::vector breaks; + std::vector counts; + std::vector> owners; // of each interval: the part, -1 for none, and its path, -1 for any + std::size_t part{0}; + for (std::size_t k = 0; k <= Chain.switches.size(); ++k) + { + auto const first{k == 0 ? std::size_t{0} : Chain.switches[k - 1].before}; + auto const last{k == Chain.switches.size() ? Chain.tracks.size() : Chain.switches[k].before}; + if (last > first && part < parts.size()) + { + auto const inner{alignment::breaks_at(result, editor_track::chain_joints(parts[part]), k == 0 ? 0.0 : ends[2 * k - 1], k == Chain.switches.size() ? result.length : ends[2 * k])}; + if (last - first > 1 && inner.size() + 1 == last - first) + for (std::size_t j = 0; j < last - first; ++j) + { + if (j > 0) + breaks.push_back(inner[j - 1]); + counts.push_back(1); + owners.emplace_back(static_cast(part), static_cast(j)); + } + else + { + counts.push_back(last - first); + owners.emplace_back(static_cast(part), -1); + } + ++part; + } + else + { + counts.push_back(last - first); + owners.emplace_back(-1, -1); + } + if (k < Chain.switches.size()) + { + breaks.push_back(ends[2 * k]); + breaks.push_back(ends[2 * k + 1]); + counts.push_back(1); + owners.emplace_back(-1, -1); + } + } + if (part != parts.size()) + { + route.error = STR_C("The paths between the switches can't be read as a chain"); + return false; + } + std::vector intervals; + auto const pieces{alignment::pieces(result, route.design, 0, breaks, counts, &intervals)}; + std::vector> groups(parts.size()); + std::vector> paths(parts.size()); // of each piece of a part, its path, where its joints cut the line + for (std::size_t i = 0; i < pieces.size() && i < intervals.size(); ++i) + if (intervals[i] < owners.size() && owners[intervals[i]].first >= 0) + { + auto const &[owner, path]{owners[intervals[i]]}; + groups[owner].push_back(pieces[i]); + if (path >= 0) + paths[owner].push_back(static_cast(path)); + } + for (std::size_t i = 0; i < parts.size(); ++i) + if (groups[i].size() < parts[i].tracks.size()) + { + route.error = STR_C("The designed line between the switches is too short for the paths there"); + return false; + } + + // all checked, the changes go in + auto const remember = [&](TTrack *Track) { + if (std::none_of(States.begin(), States.end(), [&](auto const &Entry) { return Entry.first == Track; })) + States.emplace_back(Track, editor_track::capture(*Track)); + }; + for (auto const &place : placements) + { + auto joints{editor_track::joints(*place.track)}; + joints.erase(std::remove_if(joints.begin(), joints.end(), [&](editor_track::joint const &Joint) { return std::find(Chain.tracks.begin(), Chain.tracks.end(), Joint.other) != Chain.tracks.end(); }), joints.end()); + remember(place.track); + std::vector changed{place.track}; + for (auto const &joint : joints) + { + remember(joint.other); + if (std::find(changed.begin(), changed.end(), joint.other) == changed.end()) + changed.push_back(joint.other); + } + // the heights stay, the paths between the switches keep theirs too + auto target{alignment::evaluate(result, place.from).position}; + target.y = place.entry.y; + editor_track::place(*place.track, place.entry, target, place.angle); + editor_track::follow(*place.track, joints); + editor_track::commit(changed); + } + for (std::size_t i = 0; i < parts.size(); ++i) + { + auto group{groups[i]}; + editor_track::keep_heights(parts[i], group); + TTrack *last{nullptr}; + auto const added{editor_track::relay(parts[i], group, &last, paths[i].size() == group.size() ? &paths[i] : nullptr)}; + if (last != nullptr && parts[i].tracks.back() == Chain.tracks.back()) + Last = last; + Created.insert(Created.end(), added.begin(), added.end()); + } + return true; +} + +glm::dvec3 editor_mode::route_vertex_position(int const Vertex) const +{ + auto const &design{m_route.design}; + auto const &result{m_route.result}; + auto const count{static_cast(design.vertices.size())}; + glm::dvec2 const start{design.start.x, design.start.z}; + glm::dvec2 const end{design.end.x, design.end.z}; + glm::dvec2 position; + if (Vertex < static_cast(result.vertices.size()) && false == result.vertices.empty()) + position = result.vertices[Vertex]; + else if (count == 1) + { + if (false == alignment::tangent_intersection(design, position)) + position = (start + end) * 0.5; + } + else if (Vertex == 0) + position = start + glm::normalize(design.start_direction) * design.vertices.front().offset; + else if (Vertex == count - 1) + position = end - glm::normalize(design.end_direction) * design.vertices.back().offset; + else + position = design.vertices[Vertex].position; + + auto const height{Vertex < static_cast(result.vertex_elevations.size()) ? result.vertex_elevations[Vertex] : design.start.y + (design.end.y - design.start.y) * (Vertex + 1) / (count + 1.0)}; + return {position.x, height, position.y}; +} + +bool editor_mode::route_hit(int &Vertex, int &Grip) const +{ + if (false == route_active()) + return false; + screen_projection const projection; + float best = kHandleRadius * kHandleRadius; + int hit{-1}; + for (int i = 0; i < static_cast(m_route.design.vertices.size()); ++i) + { + if (auto const distance{projection.mouse_distance2(route_vertex_position(i))}; distance < best) + { + best = distance; + hit = i; + } + } + int griphit{-1}; + for (int i = 0; i < static_cast(m_route.result.vertex_chainages.size()) && m_route.result.length > 0.0; ++i) + { + if (auto const distance{projection.mouse_distance2(alignment::evaluate(m_route.result, m_route.result.vertex_chainages[i]).position)}; distance < best) + { + best = distance; + griphit = i; + hit = -1; + } + } + Vertex = hit; + Grip = griphit; + return hit >= 0 || griphit >= 0; +} + +void editor_mode::route_show_curve(double const From, double const To) +{ + auto const &result{m_route.result}; + if (result.elements.empty() || To <= From) + return; + glm::dvec3 low{std::numeric_limits::max()}; + glm::dvec3 high{std::numeric_limits::lowest()}; + for (int i = 0; i <= 32; ++i) + { + auto const point{alignment::evaluate(result, From + (To - From) * i / 32.0).position}; + low = glm::min(low, point); + high = glm::max(high, point); + } + auto const along{plan_of(alignment::evaluate(result, (From + To) * 0.5).direction)}; + auto const flat{glm::length(along) > 1e-9 ? glm::normalize(along) : glm::dvec2{0.0, 1.0}}; + // from above, leaning a little along the line, the whole curve in sight + auto const look{glm::normalize(glm::dvec3{flat.x * 0.45, -1.0, flat.y * 0.45})}; + auto const extent{std::max(high.x - low.x, high.z - low.z)}; + fly_to((low + high) * 0.5, look, std::clamp(extent * 1.2, 60.0, 3000.0)); +} + +std::vector editor_mode::route_focused() const +{ + using part = route_design::curve_focus::part; + auto const &focus{m_route.focus}; + auto const &result{m_route.result}; + std::vector own; + if (focus.vertex < 0) + return own; + for (std::size_t i = 0; i < result.elements.size(); ++i) + if (result.elements[i].vertex == focus.vertex && result.elements[i].length > 1e-6) + own.push_back(i); + if (own.empty() || focus.what == part::whole) + return own; + // the arcs of a compound curve found by the curvature at the start and at the end of each element and their radii + auto const same = [](double const A, double const B) { return std::abs(A - B) <= 1e-6 * std::max(std::abs(A), std::abs(B)) + 1e-12; }; + std::vector radii; + for (auto const &curve : result.curves) + if (curve.vertex == focus.vertex) + radii = curve.radii.size() > 1 ? curve.radii : std::vector{curve.radius}; + std::vector found; + for (auto const i : own) + { + auto const [start, end] {alignment::end_curvatures(result.elements[i])}; + auto const arc{static_cast(focus.arc)}; + switch (focus.what) + { + case part::entry: if (i == own.front() && start == 0.0 && end > 0.0) found.push_back(i); break; + case part::exit: if (i == own.back() && end == 0.0 && start > 0.0) found.push_back(i); break; + case part::arc: if (arc < radii.size() && radii[arc] > 0.0 && same(start, 1.0 / radii[arc]) && same(end, start)) found.push_back(i); break; + case part::between: + if (arc >= 1 && arc < radii.size() && radii[arc] > 0.0 && radii[arc - 1] > 0.0 && same(start, 1.0 / radii[arc - 1]) && same(end, 1.0 / radii[arc])) + found.push_back(i); + break; + default: break; + } + } + // a part of no length, the arc of two transition curves meeting say, shows the whole curve + return found.empty() ? own : found; +} + +void editor_mode::route_measure_clicks() +{ + auto &route{m_route}; + if (route.measured == route.revision) + return; + route.measured = route.revision; + route.click_states.clear(); + auto const &result{route.result}; + if (route.clicks.empty() || false == result.valid) + return; + std::vector plan; + for (auto const &click : route.clicks) + plan.push_back(plan_of(click)); + auto const projections{alignment::project(result, plan)}; + auto const count{static_cast(route.design.vertices.size())}; + for (std::size_t i = 0; i < plan.size() && i < projections.size(); ++i) + { + route_design::click_state state; + state.offset = projections[i].offset; + // the curve nearest along the line, as the points traced in the plan go to their curves + for (int k = 0; k < count && k < static_cast(result.vertex_chainages.size()); ++k) + if (state.vertex < 0 || std::abs(result.vertex_chainages[k] - projections[i].chainage) < std::abs(result.vertex_chainages[state.vertex] - projections[i].chainage)) + state.vertex = k; + for (int k = 0; k < count && false == state.corner; ++k) + state.corner = plan_distance(route.clicks[i], route_vertex_position(k)) < 0.05; + route.click_states.push_back(state); + } +} + +std::vector editor_mode::route_clicks_of(int const Vertex) const +{ + auto const &route{m_route}; + std::vector points; + for (std::size_t i = 0; i < route.click_states.size() && i < route.clicks.size(); ++i) + { + auto const &state{route.click_states[i]}; + // a point clicked far off the line belongs to none of its curves + if (state.vertex == Vertex && false == state.corner && std::abs(state.offset) <= 3.0) + points.push_back(plan_of(route.clicks[i])); + } + return points; +} + +bool editor_mode::route_hold_clicks(int const Vertex) +{ + auto &route{m_route}; + route_measure_clicks(); + auto const points{route_clicks_of(Vertex)}; + if (points.size() < 3 || Vertex < 0 || Vertex >= static_cast(route.design.vertices.size())) + return false; + auto design{route.design}; + design.norms.checked = true; + auto const fit{alignment::refit_radii(design, static_cast(Vertex), points)}; + if (false == fit.valid) + return false; + route.design.vertices[Vertex] = fit.fitted; + return true; +} + +void editor_mode::draw_route_overlay() const +{ + auto const &route{m_route}; + auto const &design{route.design}; + auto const &result{route.result}; + screen_projection const projection; + ImDrawList *drawlist = ImGui::GetBackgroundDrawList(ImGui::GetMainViewport()); + auto const &start{result.valid ? result.start : design.start}; + auto const &end{result.valid ? result.end : design.end}; + + std::vector polygon{start}; + for (int i = 0; i < static_cast(design.vertices.size()); ++i) + polygon.push_back(route_vertex_position(i)); + polygon.push_back(end); + for (std::size_t i = 0; i + 1 < polygon.size(); ++i) + projection.line(drawlist, polygon[i], polygon[i + 1], IM_COL32(255, 210, 60, 150), 1.5f); + + if (result.length > 0.0 && result.profile.size() >= 2) + { + for (auto const &e : result.elements) + { + ImU32 const color = e.kind == alignment::element_kind::straight ? IM_COL32(255, 255, 255, 230) : e.kind == alignment::element_kind::arc ? overlay_color::grip : IM_COL32(255, 140, 30, 255); + int const steps = std::clamp(static_cast(e.length / 2.0), 1, 400); + auto previous{alignment::evaluate(result, e.chainage).position}; + for (int j = 1; j <= steps; ++j) + { + auto const next{alignment::evaluate(result, e.chainage + e.length * j / steps).position}; + projection.line(drawlist, previous, next, color, 3.0f); + previous = next; + } + ImVec2 screen; + if (projection.project(alignment::evaluate(result, e.chainage).position, screen)) + drawlist->AddCircleFilled(screen, 3.5f, overlay_color::highlight); + } + // what the mouse points at in the band of the curvature in the panel + if (route.band.hot >= 0 && route.band.hot < static_cast(result.elements.size())) + { + auto const &e{result.elements[route.band.hot]}; + int const steps = std::clamp(static_cast(e.length / 2.0), 1, 400); + auto previous{alignment::evaluate(result, e.chainage).position}; + for (int j = 1; j <= steps; ++j) + { + auto const next{alignment::evaluate(result, e.chainage + e.length * j / steps).position}; + projection.line(drawlist, previous, next, IM_COL32(255, 255, 255, 110), 8.0f); + previous = next; + } + } + // the cant ramps: their ends across the track, the ones moved off the transitions brighter, with how the cant goes along them + for (auto const &ramp : result.ramps) + { + if (ramp.cant < 0.5) + continue; + auto const colour{ramp.own ? IM_COL32(255, 170, 40, 255) : IM_COL32(255, 170, 40, 120)}; + for (auto const end : {ramp.from, ramp.to}) + { + auto const station{alignment::evaluate(result, end)}; + glm::dvec3 const across{-station.direction.z * 2.0, 0.0, station.direction.x * 2.0}; + projection.line(drawlist, station.position - across, station.position + across, colour, 3.0f); + } + ImVec2 screen; + if (ramp.own && projection.project(alignment::evaluate(result, (ramp.from + ramp.to) * 0.5).position, screen)) + drawlist->AddText({screen.x + 8.0f, screen.y + 6.0f}, colour, format(STR_C("ramp %.0f m, %.0f mm"), ramp.to - ramp.from, ramp.cant).c_str()); + } + // the part of the curve whose fields are pointed at or edited in the panel, lit up and named + if (auto const focused{route_focused()}; false == focused.empty()) + { + using part = route_design::curve_focus::part; + auto const &focus{route.focus}; + for (auto const index : focused) + { + auto const &e{result.elements[index]}; + int const steps = std::clamp(static_cast(e.length / 2.0), 1, 400); + auto previous{alignment::evaluate(result, e.chainage).position}; + for (int j = 1; j <= steps; ++j) + { + auto const next{alignment::evaluate(result, e.chainage + e.length * j / steps).position}; + projection.line(drawlist, previous, next, IM_COL32(60, 230, 255, 120), 11.0f); + projection.line(drawlist, previous, next, IM_COL32(200, 250, 255, 255), 3.0f); + previous = next; + } + } + auto const &first{result.elements[focused.front()]}; + auto const &last{result.elements[focused.back()]}; + alignment::curve_report const *report{nullptr}; + for (auto const &curve : result.curves) + if (curve.vertex == focus.vertex) + report = &curve; + std::string name; + if (report != nullptr) + { + auto const compound{report->radii.size() > 1}; + auto const arc{static_cast(focus.arc)}; + switch (focus.what) + { + case part::entry: name = format(STR_C("W%d transition in %.0f m"), focus.vertex + 1, first.length); break; + case part::exit: name = format(STR_C("W%d transition out %.0f m"), focus.vertex + 1, last.length); break; + case part::between: name = format(STR_C("W%d transition R%d-R%d %.0f m"), focus.vertex + 1, focus.arc, focus.arc + 1, first.length); break; + case part::arc: + if (compound && arc < report->radii.size()) + name = format(STR_C("W%d R%d %.0f m cant %.0f mm"), focus.vertex + 1, focus.arc + 1, report->radii[arc], arc < report->cants.size() ? report->cants[arc] : report->cant); + else + name = format(STR_C("W%d R %.0f m cant %.0f mm"), focus.vertex + 1, report->radius, report->cant); + break; + default: name = format("W%d ", focus.vertex + 1) + curve_label(*report, design.norms); break; + } + } + ImVec2 middle; + if (false == name.empty() && projection.project(alignment::evaluate(result, (first.chainage + last.chainage + last.length) * 0.5).position, middle)) + { + auto const size{ImGui::GetFontSize() * 1.25f}; + auto const text{ImGui::GetFont()->CalcTextSizeA(size, FLT_MAX, 0.0f, name.c_str())}; + ImVec2 const corner{middle.x - text.x * 0.5f, middle.y - text.y - 22.0f}; + drawlist->AddRectFilled(ImVec2(corner.x - 6.0f, corner.y - 3.0f), ImVec2(corner.x + text.x + 6.0f, corner.y + text.y + 3.0f), IM_COL32(10, 20, 30, 210), 4.0f); + drawlist->AddText(ImGui::GetFont(), size, corner, IM_COL32(200, 250, 255, 255), name.c_str()); + drawlist->AddLine(ImVec2(middle.x, corner.y + text.y + 3.0f), middle, IM_COL32(200, 250, 255, 200), 1.5f); + } + } + ImVec2 pointed; + if (route.band.at >= 0.0 && projection.project(alignment::evaluate(result, std::min(route.band.at, result.length)).position, pointed)) + { + drawlist->AddCircleFilled(pointed, 5.0f, overlay_color::highlight); + drawlist->AddCircle(pointed, 10.0f, overlay_color::highlight, 20, 2.0f); + } + } + + for (auto const atend : {false, true}) + { + auto const &point{atend ? end : start}; + auto const direction{atend ? design.end_direction : design.start_direction}; + ImVec2 screen; + if (projection.project(point, screen)) + drawlist->AddRectFilled(ImVec2(screen.x - 5.0f, screen.y - 5.0f), ImVec2(screen.x + 5.0f, screen.y + 5.0f), IM_COL32(70, 140, 255, 255)); + auto const arrow{glm::dvec3{direction.x, 0.0, direction.y} * (atend ? 15.0 : -15.0)}; + projection.line(drawlist, point, point + arrow, IM_COL32(70, 140, 255, 255), 2.0f); + } + for (int i = 0; i < static_cast(design.vertices.size()); ++i) + { + ImVec2 screen; + if (false == projection.project(route_vertex_position(i), screen)) + continue; + drawlist->AddCircleFilled(screen, 6.0f, overlay_color::marked); + if (i == route.vertex) + drawlist->AddCircle(screen, 11.0f, overlay_color::highlight, 16, 2.5f); + if (i < static_cast(result.vertex_chainages.size()) && result.length > 0.0 && projection.project(alignment::evaluate(result, result.vertex_chainages[i]).position, screen)) + { + drawlist->AddCircleFilled(screen, 6.0f, overlay_color::grip, 4); + if (i == route.grip) + drawlist->AddCircle(screen, 11.0f, overlay_color::highlight, 16, 2.5f); + auto const *report{i < static_cast(result.curves.size()) ? &result.curves[i] : nullptr}; + auto radius{format("R %.0f", report != nullptr ? report->radius : design.vertices[i].radius)}; + if (report != nullptr && report->radii.size() >= 2) + { + radius = "R"; + for (std::size_t k = 0; k < report->radii.size(); ++k) + radius += format(k == 0 ? " %.0f" : " / %.0f", report->radii[k]); + } + drawlist->AddText(ImVec2(screen.x + 9.0f, screen.y + 4.0f), overlay_color::grip, radius.c_str()); + } + drawlist->AddText(ImVec2(screen.x + 9.0f, screen.y - 18.0f), overlay_color::marked, format("W%d", i + 1).c_str()); + } + // the points clicked when the line was laid, in the colours of their departure; how far each is, along the curve in focus + for (std::size_t i = 0; i < route.clicks.size() && i < route.click_states.size(); ++i) + { + auto const &state{route.click_states[i]}; + ImVec2 screen; + if (state.corner || std::abs(state.offset) > 3.0 || false == projection.project(route.clicks[i], screen)) + continue; + auto const departure{std::abs(state.offset)}; + auto const colour{departure <= 0.1 ? IM_COL32(90, 220, 110, 255) : departure <= 0.3 ? IM_COL32(255, 200, 60, 255) : IM_COL32(255, 90, 70, 255)}; + drawlist->AddCircleFilled(screen, 4.5f, IM_COL32(0, 0, 0, 200), 12); + drawlist->AddCircleFilled(screen, 3.0f, colour, 12); + if (state.vertex == route.focus.vertex) + drawlist->AddText(ImVec2(screen.x + 7.0f, screen.y - 7.0f), colour, format("%.0f cm", departure * 100.0).c_str()); + } + if (route.trace.points.empty()) + return; + std::vector plan; + for (auto const &point : route.trace.points) + plan.push_back(plan_of(point)); + auto const projections{alignment::project(result, plan)}; + auto const hit{route_trace_hit()}; + for (std::size_t i = 0; i < route.trace.points.size(); ++i) + { + ImVec2 screen; + if (false == projection.project(route.trace.points[i], screen)) + continue; + auto const departure{i < projections.size() ? std::abs(projections[i].offset) : 0.0}; + auto const colour{departure <= 0.1 ? IM_COL32(90, 220, 110, 255) : departure <= 0.3 ? IM_COL32(255, 200, 60, 255) : IM_COL32(255, 90, 70, 255)}; + drawlist->AddCircle(screen, 5.0f, IM_COL32(0, 0, 0, 200), 12, 3.5f); + drawlist->AddCircle(screen, 5.0f, colour, 12, 2.0f); + if (static_cast(i) == hit) + drawlist->AddCircle(screen, 10.0f, overlay_color::highlight, 16, 2.0f); + if (i < projections.size()) + drawlist->AddText(ImVec2(screen.x + 8.0f, screen.y - 7.0f), colour, format("%.0f cm", departure * 100.0).c_str()); + } +} + +void editor_mode::render_route_trace() +{ + auto &trace{m_route.trace}; + // the curve is traced on the photo with the laying (Tab), the plan has no button of its own for it + if (false == trace.active) + return; + ImGui::SeparatorText(STR_C("Tracing the curve")); + if (segmented("traceradii", trace.radii, + {{0, STR_C("Auto"), "As few radii as follow the points, up to three"}, {1, STR_C("1 R"), "One radius"}, {2, STR_C("2 R"), "A compound curve of two radii"}, {3, STR_C("3 R"), "A compound curve of three radii"}})) + route_trace_fit(); + if (trace.points.empty()) + { + ImGui::PushTextWrapPos(0.0f); + ImGui::TextDisabled("%s", STR_C("Click points along the middle of the track on the photo, spread over the whole curve; a few on the straights at its ends help too")); + ImGui::PopTextWrapPos(); + } + else + { + auto const colour = [](double const Departure) { return Departure <= 0.1 ? IM_COL32(90, 220, 110, 255) : Departure <= 0.3 ? IM_COL32(255, 200, 60, 255) : IM_COL32(255, 90, 70, 255); }; + metric_tiles({{format("%zu", trace.points.size()), STR_C("points"), ImGui::GetColorU32(ImGuiCol_Text)}, + {format("%.0f cm", trace.rms * 100.0), STR_C("departure"), colour(trace.rms)}, + {format("%.0f cm", trace.worst * 100.0), STR_C("at most"), colour(trace.worst)}}); + } + if (main_button(STR_C("Apply Enter"), ImVec2(-1.0f, 0.0f))) + route_trace_end(true); + if (ImGui::Button(STR_C("Drop Esc"))) + route_trace_end(false); + ImGui::SameLine(); + ImGui::BeginDisabled(trace.points.empty()); + if (ImGui::Button(STR_C("Take out the last point Backspace"))) + { + trace.points.pop_back(); + route_trace_fit(); + } + ImGui::EndDisabled(); +} + +void editor_mode::route_trace_start() +{ + auto &trace{m_route.trace}; + trace.active = true; + trace.points.clear(); + trace.before = m_route.design; + trace.rms = 0.0; + trace.worst = 0.0; +} + +// every point goes to the curve nearest to it along the line, the curves without points keep their shape +void editor_mode::route_trace_fit() +{ + auto &route{m_route}; + auto &trace{route.trace}; + auto design{route.design}; + trace.rms = 0.0; + trace.worst = 0.0; + if (trace.points.empty() || design.vertices.empty() || false == route.result.valid) + return; + std::vector plan; + for (auto const &point : trace.points) + plan.push_back(plan_of(point)); + auto const projections{alignment::project(route.result, plan)}; + std::vector> owned(design.vertices.size()); + for (std::size_t i = 0; i < plan.size(); ++i) + { + std::size_t nearest{0}; + for (std::size_t k = 1; k < route.result.vertex_chainages.size() && k < owned.size(); ++k) + if (std::abs(route.result.vertex_chainages[k] - projections[i].chainage) < std::abs(route.result.vertex_chainages[nearest] - projections[i].chainage)) + nearest = k; + owned[nearest].push_back(plan[i]); + } + for (std::size_t k = 0; k < owned.size(); ++k) + { + if (owned[k].empty()) + continue; + auto const fit{alignment::fit_trace(design, k, owned[k], trace.radii)}; + if (fit.valid) + design.vertices[k] = fit.fitted; + } + route.design = design; + route_update(); + double sum{0.0}; + for (auto const &projection : alignment::project(route.result, plan)) + { + sum += projection.offset * projection.offset; + trace.worst = std::max(trace.worst, std::abs(projection.offset)); + } + trace.rms = std::sqrt(sum / static_cast(plan.size())); +} + +void editor_mode::route_trace_end(bool const Keep) +{ + auto &trace{m_route.trace}; + if (false == trace.active) + return; + auto const traced{false == trace.points.empty()}; + if (false == Keep) + { + m_route.design = trace.before; + route_update(); + } + trace = {}; + if (Keep && traced) + route_apply(); +} + +// the photo under the cursor where the depth finds it, else the level of the design there +glm::dvec3 editor_mode::route_trace_cursor() const +{ + if (GfxRenderer->Mouse_Hit()) + return cursor_ground(); + auto const &result{m_route.result}; + auto point{cursor_level(alignment::elevation(result, result.length * 0.5))}; + if (auto const projections{alignment::project(result, {plan_of(point)})}; false == projections.empty()) + point = cursor_level(alignment::elevation(result, projections.front().chainage)); + return point; +} + +int editor_mode::route_trace_hit() const +{ + screen_projection const projection; + float best{kHandleRadius * kHandleRadius}; + int hit{-1}; + for (int i = 0; i < static_cast(m_route.trace.points.size()); ++i) + if (auto const distance{projection.mouse_distance2(m_route.trace.points[i])}; distance < best) + { + best = distance; + hit = i; + } + return hit; +} + +void editor_mode::render_route_gizmo() +{ + auto &route{m_route}; + auto const count{static_cast(route.design.vertices.size())}; + bool const grip{route.grip >= 0 && route.grip < count && route.grip < static_cast(route.result.vertex_chainages.size())}; + if (false == grip && (route.vertex < 0 || route.vertex >= count)) + { + m_route_dragging = false; + return; + } + + auto const position{grip ? alignment::evaluate(route.result, route.result.vertex_chainages[route.grip]).position : route_vertex_position(route.vertex)}; + glm::dvec3 moved{position}; + if (false == handle_drag_step(moved)) + { + if (m_route_dragging) + { + m_route_dragging = false; + route_apply(); + } + return; + } + if (false == m_route_dragging) + m_route_drag_from = route.design; + m_route_dragging = true; + if (grip) + { + auto &vertex{route.design.vertices[route.grip]}; + auto const corner{route_vertex_position(route.grip)}; + auto const distance{plan_distance(moved, corner)}; + for (auto const &curve : route.result.curves) + { + if (curve.vertex != route.grip || vertex.reverse_turn) + continue; + auto const secant{1.0 / std::cos(curve.deflection * 0.5) - 1.0}; + if (secant > 1e-6) + vertex.radius = std::max(10.0, std::round(distance / secant)); + } + route_update(); + return; + } + auto &vertex{route.design.vertices[route.vertex]}; + glm::dvec2 const point{moved.x, moved.z}; + if (count >= 2) + { + if (route.vertex == 0) + vertex.offset = std::max(0.1, glm::dot(point - plan_of(route.design.start), glm::normalize(route.design.start_direction))); + else if (route.vertex == count - 1) + vertex.offset = std::max(0.1, glm::dot(plan_of(route.design.end) - point, glm::normalize(route.design.end_direction))); + else + vertex.position = point; + } + route_update(); +} + +void editor_mode::render_route_ui() +{ + auto &route{m_route}; + if (false == route.error.empty()) + ImGui::TextColored(ImVec4(1.0f, 0.35f, 0.3f, 1.0f), "%s", route.error.c_str()); + if (route.chain.tracks.empty()) + return; + + ImGui::AlignTextToFramePadding(); + ImGui::TextDisabled(STR_P("%zu path, %.2f m", "%zu paths, %.2f m", route.chain.tracks.size()), route.chain.tracks.size(), route.chain.length); + auto const reset{STR_C("Reset design")}; + auto const reset_width{ImGui::CalcTextSize(reset).x + ImGui::GetStyle().FramePadding.x * 2.0f}; + ImGui::SameLine(std::max(ImGui::GetCursorPosX(), ImGui::GetWindowContentRegionMax().x - reset_width)); + if (ImGui::Button(reset)) + { + auto *track{route.chain.tracks[route.chain.tracks.size() / 2]}; + route_load(*track); + return; + } + item_tooltip("Reads the curves of the line from the scenery again, dropping the changes not applied"); + auto changed{render_route_band()}; + render_route_trace(); + render_route_stored(); + changed |= render_route_vertices(); + if (ImGui::CollapsingHeader(STR_C("Design speed and limits"))) + changed |= render_route_parameters(); + if (changed) + route_update(); + + ImGui::Separator(); + render_route_result(); + + if (ImGui::CollapsingHeader(STR_C("Digitize the whole scenery"))) + { + ImGui::PushTextWrapPos(0.0f); + ImGui::TextDisabled("%s", STR_C("Keeps the plan of the lines in the scenery as straights, arcs and transitions, so the tools can edit them; the paths stay as they are")); + ImGui::PopTextWrapPos(); + if (ImGui::Button(STR_C("Digitize all the tracks"))) + { + digitize_all(); + return; + } + item_tooltip("Every line of the scenery not digitized yet is kept in it with its straights, arcs and transition curves, the way the drawn tracks are kept; the paths stay as they are"); + ImGui::SameLine(); + if (ImGui::Button(STR_C("Digitize the scenery"))) + { + digitize_scenery(true); + return; + } + item_tooltip("All at once: the lines, the switches with their types out of the catalogue (or the size measured from their shape), the crossovers as connections of switches and the signals, signs, poles and catenary bound to the tracks. The paths and the objects stay as they are, the scenery keeps it on save"); + } +} + +// the curvature along the fragment, the way the designers draw it: straights on the axis, the transitions as ramps, +// the arcs as plateaus at 1/R, in the colours of the overlay in the view. dragging a plateau changes its radius, +// dragging a ramp sideways the length of the transition, the wheel does both in steps +bool editor_mode::render_route_band() +{ + auto &route{m_route}; + auto &design{route.design}; + auto const &result{route.result}; + auto &band{route.band}; + band.hot = -1; + band.at = -1.0; + if (result.elements.empty() || result.length <= 1e-3 || design.vertices.empty()) + { + band.vertex = -1; + return false; + } + auto const font{ImGui::GetFontSize()}; + auto const pad{std::round(font * 0.5f)}; + auto const width{ImGui::GetContentRegionAvail().x}; + auto const height{std::round(font * 6.0f)}; + auto const top{ImGui::GetCursorScreenPos()}; + ImGui::InvisibleButton("##curvature", ImVec2(width, height)); + ImGui::SetItemKeyOwner(ImGuiKey_MouseWheelY); + auto const hovered{ImGui::IsItemHovered()}; + auto const active{ImGui::IsItemActive()}; + auto *list{ImGui::GetWindowDrawList()}; + ImVec2 const bottom{top.x + width, top.y + height}; + list->AddRectFilled(top, bottom, ImGui::GetColorU32(ImGuiCol_FrameBg), std::round(font * 0.35f)); + + auto const ends = [](alignment::element const &Element) -> std::pair { + auto const sign{static_cast(Element.turn)}; + auto const [start, end]{alignment::end_curvatures(Element)}; + return {sign * start, sign * end}; + }; + auto const colour = [](alignment::element const &Element) { + return Element.kind == alignment::element_kind::straight ? IM_COL32(255, 255, 255, 230) : Element.kind == alignment::element_kind::arc ? overlay_color::grip : IM_COL32(255, 140, 30, 255); + }; + double peak{0.0}; + bool left{false}, right{false}; + for (auto const &element : result.elements) + { + auto const [from, to]{ends(element)}; + peak = std::max({peak, std::abs(from), std::abs(to)}); + left |= from > 1e-9 || to > 1e-9; + right |= from < -1e-9 || to < -1e-9; + } + auto const line{ImGui::GetTextLineHeight()}; + auto const inner_left{top.x + pad}; + auto const inner_width{width - 2.0f * pad}; + auto const plot_top{top.y + pad * 0.5f + line}; + auto const plot_bottom{bottom.y - pad * 0.5f - line}; + auto const both{left && right}; + auto const axis{both ? std::round((plot_top + plot_bottom) * 0.5f) : plot_bottom}; + // the curves to one side only grow upwards + auto const flip{(false == both && right) ? -1.0f : 1.0f}; + auto const dragging{band.vertex >= 0}; + auto const metres{dragging ? band.metres : inner_width / static_cast(result.length)}; + auto const curvature{dragging ? band.curvature : (peak > 0.0 ? (axis - plot_top) * 0.85f / static_cast(peak) : 0.0f)}; + auto const x_of = [&](double const Chainage) { return inner_left + static_cast(Chainage) * metres; }; + auto const y_of = [&](double const K) { return axis - flip * static_cast(K) * curvature; }; + auto const mouse{ImGui::GetIO().MousePos}; + auto const count{static_cast(result.elements.size())}; + + // what of its vertex each element is: an arc, the arcs of a compound curve counted from the first one, which are elements of an even + // curvature as an arc is, or a transition, in from the straight, out to it, or between two arcs, which goes on from the arc before it + struct role + { + int part{0}; + int arc{0}; + }; + std::vector roles(static_cast(count)); + std::vector arcs(design.vertices.size(), 0); + { + int vertex{-1}; + int arc{-1}; + double last{0.0}; + for (int i = 0; i < count; ++i) + { + auto const &element{result.elements[i]}; + if (element.vertex != vertex) + { + vertex = element.vertex; + arc = -1; + last = 0.0; + } + if (element.vertex < 0 || element.vertex >= static_cast(design.vertices.size()) || element.kind == alignment::element_kind::straight) + continue; + auto const [from, to]{ends(element)}; + if (element.kind == alignment::element_kind::arc || (std::abs(from - to) <= 1e-6 * std::abs(from) && std::abs(from) > 1e-9)) + { + // the next arc where the curvature isn't the one of the arc before, an arc cut in parts staying one + if (arc < 0 || std::abs(std::abs(from) - last) > 1e-6 * std::abs(from)) + ++arc; + last = std::abs(from); + roles[i] = {1, arc}; + arcs[element.vertex] = std::max(arcs[element.vertex], arc + 1); + } + else + roles[i] = std::abs(from) <= 1e-9 ? role{2, 0} : std::abs(to) <= 1e-9 ? role{3, 0} : role{4, arc + 1}; + } + } + // the element under the mouse and what of it a drag changes: near the ends of a plateau the transitions either side of it, also the + // ones of no length yet + int under{-1}; + int part{0}; + int arc{0}; + if (hovered && false == dragging) + { + for (int i = 0; i < count; ++i) + { + auto const &element{result.elements[i]}; + if (mouse.x < x_of(element.chainage) || mouse.x >= x_of(element.chainage + element.length)) + continue; + under = i; + part = roles[i].part; + arc = roles[i].arc; + if (part == 1) + { + auto const from{x_of(element.chainage)}; + auto const to{x_of(element.chainage + element.length)}; + auto const edge{std::min(std::round(font * 0.5f), (to - from) * 0.25f)}; + if (mouse.x < from + edge) + part = arc == 0 ? 2 : 4; + else if (mouse.x >= to - edge) + { + part = arc + 1 >= arcs[element.vertex] ? 3 : 4; + arc += 1; + } + } + break; + } + } + auto const value_of = [&](int const Vertex, int const Part, int const Arc) -> double & { + auto &vertex{design.vertices[Vertex]}; + auto const later{Arc >= 1 && Arc <= static_cast(vertex.arcs.size())}; + switch (Part) + { + case 1: return later ? vertex.arcs[Arc - 1].radius : vertex.radius; + case 2: return vertex.transition_in; + case 3: return vertex.transition_out; + default: return later ? vertex.arcs[Arc - 1].transition : vertex.transition_in; + } + }; + auto const rounded_radius = [](double const Radius) { + auto const step{Radius < 1000.0 ? 1.0 : 10.0}; + return std::clamp(std::round(Radius / step) * step, 10.0, 100000.0); + }; + bool changed{false}; + if (part != 0 && ImGui::IsItemActivated()) + { + band.vertex = result.elements[under].vertex; + band.part = part; + band.arc = arc; + band.value = value_of(band.vertex, part, arc); + band.press = mouse; + band.metres = metres; + band.curvature = curvature; + } + if (band.vertex >= 0 && band.vertex < static_cast(design.vertices.size()) && active) + { + auto &value{value_of(band.vertex, band.part, band.arc)}; + double wanted{value}; + if (band.part == 1) + { + int turn{1}; + for (auto const &element : result.elements) + if (element.vertex == band.vertex && element.turn != 0) + turn = element.turn; + auto const start{y_of(turn / std::max(1.0, band.value)) + (mouse.y - band.press.y)}; + auto const k{(axis - start) * flip * turn / std::max(1e-6f, curvature)}; + wanted = rounded_radius(1.0 / std::max(1e-5, static_cast(k))); + } + else + { + // the transition in grows to the left, from where it starts; the others to the right + auto const shift{(mouse.x - band.press.x) / std::max(1e-6f, metres)}; + wanted = std::max(0.0, std::round(band.value + (band.part == 2 ? -shift : shift))); + } + if (wanted != value) + { + value = wanted; + changed = true; + } + ImGui::SetMouseCursor(band.part == 1 ? ImGuiMouseCursor_ResizeNS : ImGuiMouseCursor_ResizeEW); + } + else if (dragging && false == active) + { + band.vertex = -1; + } + if (part != 0) + { + ImGui::SetMouseCursor(part == 1 ? ImGuiMouseCursor_ResizeNS : ImGuiMouseCursor_ResizeEW); + if (auto const wheel{ImGui::GetIO().MouseWheel}; wheel != 0.0f) + { + auto &value{value_of(result.elements[under].vertex, part, arc)}; + value = part == 1 ? rounded_radius(value * (wheel > 0.0f ? 0.95 : 1.0 / 0.95)) : std::max(0.0, std::round(value / 5.0) * 5.0 + (wheel > 0.0f ? 5.0 : -5.0)); + changed = true; + } + } + + ImGui::PushClipRect(top, bottom, true); + auto const disabled{ImGui::GetColorU32(ImGuiCol_TextDisabled)}; + list->AddLine(ImVec2(inner_left, axis), ImVec2(inner_left + inner_width, axis), ImGui::GetColorU32(ImGuiCol_TextDisabled, 0.5f)); + auto const hot_vertex{dragging ? band.vertex : under >= 0 ? result.elements[under].vertex : -1}; + for (int i = 0; i < count; ++i) + { + auto const &element{result.elements[i]}; + auto const [from, to]{ends(element)}; + ImVec2 const a{x_of(element.chainage), y_of(from)}; + ImVec2 const b{x_of(element.chainage + element.length), y_of(to)}; + auto const lit{element.vertex >= 0 && element.vertex == hot_vertex}; + auto const tint{colour(element)}; + if (element.kind != alignment::element_kind::straight) + list->AddQuadFilled(ImVec2(a.x, axis), a, b, ImVec2(b.x, axis), (tint & ~IM_COL32_A_MASK) | (lit ? IM_COL32(0, 0, 0, 90) : IM_COL32(0, 0, 0, 40))); + list->AddLine(a, b, tint, lit ? 3.0f : 2.0f); + if (i > 0) + list->AddLine(ImVec2(a.x, axis - 3.0f), ImVec2(a.x, axis + 3.0f), disabled); + } + // the labels: the radius over its plateau, the transition lengths along the axis, the km of the ends at the bottom + std::vector> taken; + auto const place = [&](float const Left, float const Right) { + for (auto const &range : taken) + if (Left < range.second + 4.0f && Right > range.first - 4.0f) + return false; + taken.emplace_back(Left, Right); + return true; + }; + auto const start_km{format("km %s", profile::format_chainage(route.origin).c_str())}; + auto const end_km{format("km %s", profile::format_chainage(route.origin + result.length).c_str())}; + auto const label_y{bottom.y - pad * 0.25f - line}; + auto const start_size{ImGui::CalcTextSize(start_km.c_str())}; + auto const end_size{ImGui::CalcTextSize(end_km.c_str())}; + place(inner_left, inner_left + start_size.x); + list->AddText(ImVec2(inner_left, label_y), disabled, start_km.c_str()); + if (place(inner_left + inner_width - end_size.x, inner_left + inner_width)) + list->AddText(ImVec2(inner_left + inner_width - end_size.x, label_y), disabled, end_km.c_str()); + for (auto const &element : result.elements) + { + auto const from{x_of(element.chainage)}; + auto const to{x_of(element.chainage + element.length)}; + auto const middle{(from + to) * 0.5f}; + if (dragging && element.vertex == band.vertex) + continue; + if (element.kind == alignment::element_kind::arc || (element.kind == alignment::element_kind::spiral && element.curvature_start == element.curvature_end && element.radius > 0.0)) + { + auto const &vertex{design.vertices[std::clamp(element.vertex, 0, static_cast(design.vertices.size()) - 1)]}; + auto text{format("R %.0f", element.radius)}; + if (vertex.cant > 0.0) + { + auto const longer{text + format(" \xc2\xb7 %.0f mm", vertex.cant)}; + if (ImGui::CalcTextSize(longer.c_str()).x <= to - from) + text = longer; + } + auto const size{ImGui::CalcTextSize(text.c_str())}; + auto const y{ends(element).first * flip >= 0.0 ? y_of(ends(element).first) - size.y - 1.0f : y_of(ends(element).first) + 1.0f}; + if (size.x <= std::max(to - from, size.x * 0.8f)) + list->AddText(ImVec2(std::round(middle - size.x * 0.5f), std::round(std::max(top.y + 1.0f, y))), colour(element), text.c_str()); + } + else if (element.kind == alignment::element_kind::transition_in || element.kind == alignment::element_kind::transition_out) + { + auto const text{format("%.0f m", element.length)}; + auto const size{ImGui::CalcTextSize(text.c_str())}; + if (both) + { + auto const y{ends(element).first + ends(element).second > 0.0 ? axis + 2.0f : axis - size.y - 2.0f}; + if (size.x <= to - from + 8.0f) + list->AddText(ImVec2(std::round(middle - size.x * 0.5f), std::round(y)), colour(element), text.c_str()); + } + else if (place(middle - size.x * 0.5f, middle + size.x * 0.5f)) + list->AddText(ImVec2(std::round(middle - size.x * 0.5f), label_y), colour(element), text.c_str()); + } + } + // the point under the mouse, shown in the view too + if (hovered || dragging) + { + auto const at{std::clamp(static_cast((mouse.x - inner_left) / std::max(1e-6f, metres)), 0.0, result.length)}; + band.at = at; + band.hot = dragging ? -1 : under; + if (false == dragging) + list->AddLine(ImVec2(mouse.x, plot_top), ImVec2(mouse.x, plot_bottom), IM_COL32(255, 255, 255, 60)); + } + if (dragging && band.vertex >= 0 && band.vertex < static_cast(design.vertices.size())) + { + auto const value{value_of(band.vertex, band.part, band.arc)}; + auto const text{band.part == 1 ? format("R %.0f m", value) : format("%.0f m", value)}; + auto const size{ImGui::CalcTextSize(text.c_str())}; + ImVec2 const at{std::clamp(mouse.x + pad, top.x, bottom.x - size.x - pad), std::clamp(mouse.y - size.y - pad, top.y, bottom.y - size.y)}; + list->AddRectFilled(ImVec2(at.x - 3.0f, at.y - 1.0f), ImVec2(at.x + size.x + 3.0f, at.y + size.y + 1.0f), IM_COL32(0, 0, 0, 170), 3.0f); + list->AddText(at, IM_COL32(255, 255, 255, 255), text.c_str()); + } + ImGui::PopClipRect(); + if (changed) + first_step_done(first_step::plan_band); + + if (part != 0 && false == dragging && ImGui::IsItemHovered(ImGuiHoveredFlags_ForTooltip)) + { + auto const index{result.elements[under].vertex}; + auto const &vertex{design.vertices[index]}; + auto const value{value_of(index, part, arc)}; + ImGui::BeginTooltip(); + if (part == 1 && arcs[index] > 1) + ImGui::Text(STR_C("Curve %d, arc R%d: %.0f m"), index + 1, arc + 1, value); + else if (part == 1) + ImGui::Text(STR_C("Curve %d: R %.0f m, cant %.0f mm"), index + 1, value, vertex.cant); + else if (part == 4) + ImGui::Text(STR_C("Curve %d, transition between R%d and R%d: %.0f m"), index + 1, arc, arc + 1, value); + else + ImGui::Text(part == 2 ? STR_C("Transition into curve %d: %.0f m") : STR_C("Transition out of curve %d: %.0f m"), index + 1, value); + gesture_rows({{"Drag", part == 1 ? "up or down: the radius" : "sideways: the length"}, {"Wheel", part == 1 ? "the radius by 5%" : "the length by 5 m"}}); + ImGui::EndTooltip(); + } + return changed; +} + +bool editor_mode::render_route_parameters() +{ + auto &design{m_route.design}; + bool changed{false}; + ImGui::TextDisabled("%s", STR_C("Design speed (km/h)")); + ImGui::SetNextItemWidth(-FLT_MIN); + changed |= ImGui::InputDouble("##designspeed", &design.speed, 10.0, 20.0, "%.0f"); + item_tooltip("Speed the cant, the transitions and the recommended radius are designed for"); + changed |= value_chips("designspeeds", design.speed, {60.0, 80.0, 100.0, 120.0, 160.0, 200.0}, "%.0f"); + design.speed = std::max(1.0, design.speed); + ImGui::TextDisabled("%s", STR_C("Transition curve")); + int shape = static_cast(design.shape); + if (segmented("transitionshape", shape, + {{static_cast(alignment::transition_shape::cubic_parabola), STR_C("Cubic parabola"), "The usual one on the Polish lines"}, + {static_cast(alignment::transition_shape::clothoid), STR_C("Clothoid"), "Curvature growing linearly with the length"}})) + { + design.shape = static_cast(shape); + changed = true; + } + + if (ImGui::TreeNode(STR_C("Norms"))) + { + auto &norms{design.norms}; + if (begin_fields("##routelimits", 0.6f)) + { + auto const limit = [&](char const *Label, char const *Id, double &Value, char const *Format) { + field_row(Label); + changed |= ImGui::InputDouble(Id, &Value, 0.0, 0.0, Format); + }; + limit("Rail axes distance (mm)", "##gauge", norms.gauge, "%.0f"); + limit("Unbalanced acceleration (m/s2)", "##unbalanced", norms.unbalanced, "%.2f"); + limit("Maximum cant (mm)", "##cantmax", norms.cant_max, "%.0f"); + limit("Cant change rate (mm/s)", "##cantrate", norms.cant_rate, "%.0f"); + limit("Cant ramp 1:(k*V), k", "##ramp", norms.ramp_factor, "%.1f"); + limit("Unbalanced acc. change rate (m/s3)", "##jerk", norms.jerk, "%.2f"); + limit("Straight between curves (s of travel)", "##tangent", norms.tangent_min_time, "%.1f"); + ImGui::EndTable(); + } + norms.gauge = std::max(100.0, norms.gauge); + norms.cant_rate = std::max(1.0, norms.cant_rate); + norms.jerk = std::max(0.01, norms.jerk); + ImGui::TreePop(); + } + return changed; +} + +bool editor_mode::render_route_vertices() +{ + bool changed{false}; + auto const count{static_cast(m_route.design.vertices.size())}; + m_route.focus = {}; + route_measure_clicks(); + if (false == m_route.clicks.empty()) + { + ImGui::Checkbox(STR_C("Keep to the points clicked"), &m_route.hold); + item_tooltip("The scenery keeps the points clicked when the line was laid: a curve whose transitions or cants are changed gets its radii fitted to them again, so it stays where it was seen on the photo"); + ImGui::SameLine(); + if (ImGui::SmallButton(STR_C("Fit all to them"))) + { + for (int i = 0; i < count; ++i) + changed |= route_hold_clicks(i); + } + item_tooltip("The radii of every curve fitted again to the points clicked along it, the transitions and the cants as they are"); + } + for (int i = 0; i < count; ++i) + { + ImGui::PushID(i); + changed |= render_route_vertex(i); + ImGui::PopID(); + } + return changed; +} + +bool editor_mode::render_route_vertex(int const Index) +{ + auto &route{m_route}; + auto &design{route.design}; + auto &vertex{design.vertices[Index]}; + bool changed{false}; + // a transition or a cant changed, the edit done: the curve fitted to the points clicked again, its radii given by them + bool settled{false}; + using part = route_design::curve_focus::part; + // the field just drawn shows its part of the curve in the view while the mouse is over it or it's being edited + auto const mark = [&](part const What, int const Arc) { + if (ImGui::IsItemActive()) + route.focus = {Index, What, Arc, true}; + else if (false == route.focus.held && ImGui::IsItemHovered()) + route.focus = {Index, What, Arc, false}; + }; + ImGui::BeginGroup(); + // named as the vertex is in the view, W1, W2..., with where it lies along the line + { + auto from{-1.0}; + auto to{-1.0}; + for (auto const &e : route.result.elements) + if (e.vertex == Index) + { + from = from < 0.0 ? e.chainage : from; + to = e.chainage + e.length; + } + auto title{format(STR_C("Curve W%d"), Index + 1)}; + if (from >= 0.0) + title += format(" km %s - %s", profile::format_chainage(route.origin + from).c_str(), profile::format_chainage(route.origin + to).c_str()); + // the vertex picked in the view stands out + auto const picked{route.vertex == Index || route.grip == Index}; + if (picked) + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::ColorConvertU32ToFloat4(overlay_color::highlight)); + ImGui::SeparatorText(title.c_str()); + if (picked) + ImGui::PopStyleColor(); + mark(part::whole, 0); + if (from >= 0.0) + { + if (ImGui::SmallButton(STR_C("Show in the view"))) + route_show_curve(from, to); + item_tooltip("The camera flies over the curve, which is lit up in the view while the mouse is over its fields"); + mark(part::whole, 0); + } + // how far the curve is from the points clicked along it when it was laid + std::size_t clicked{0}; + double sum{0.0}; + double worst{0.0}; + for (auto const &state : route.click_states) + if (state.vertex == Index && false == state.corner && std::abs(state.offset) <= 3.0) + { + ++clicked; + sum += state.offset * state.offset; + worst = std::max(worst, std::abs(state.offset)); + } + if (clicked > 0) + { + ImGui::SameLine(); + auto const colour{worst <= 0.1 ? ImVec4(0.35f, 0.86f, 0.43f, 1.0f) : worst <= 0.3 ? ImVec4(1.0f, 0.78f, 0.24f, 1.0f) : ImVec4(1.0f, 0.35f, 0.27f, 1.0f)}; + ImGui::TextColored(colour, STR_C("points clicked %zu: %.0f cm on average, at most %.0f cm"), clicked, std::sqrt(sum / static_cast(clicked)) * 100.0, worst * 100.0); + item_tooltip("The points clicked along the curve when it was laid, kept in the scenery, and how far the curve is from them now"); + mark(part::whole, 0); + if (clicked >= 3) + { + ImGui::SameLine(); + if (ImGui::SmallButton(STR_C("Fit to them"))) + changed |= route_hold_clicks(Index); + item_tooltip("The radii of the curve and their shares fitted again to the points clicked, the transitions and the cants as they are"); + } + } + } + // two fields in a row, the name and the unit inside them, a bar in the colour of the element in the band and in the view + auto const half{std::floor((ImGui::GetContentRegionAvail().x - ImGui::GetStyle().ItemSpacing.x) * 0.5f)}; + auto const field = [&](char const *Id, double &Value, float const Speed, char const *Format, ImU32 const Colour, char const *Tooltip, part const What) { + ImGui::SetNextItemWidth(half); + auto const edited{ImGui::DragScalar(Id, ImGuiDataType_Double, &Value, Speed, nullptr, nullptr, Format)}; + // the radius is the user's own, the curve no longer fitted after it + settled |= What != part::arc && ImGui::IsItemDeactivatedAfterEdit(); + mark(What, 0); + auto const low{ImGui::GetItemRectMin()}; + auto const high{ImGui::GetItemRectMax()}; + ImGui::GetWindowDrawList()->AddRectFilled(low, ImVec2(low.x + 3.0f, high.y), Colour, 2.0f, ImDrawFlags_RoundCornersLeft); + item_tooltip(Tooltip); + return edited; + }; + ImU32 const transition{IM_COL32(255, 140, 30, 255)}; + // the first curve, or the last one, may go on from the curve of the track adjoining at that end: it begins right there, its radius + // the one which begins it there, its entry, or exit, the transition between the two curves + auto const count{static_cast(design.vertices.size())}; + for (auto const atend : {false, true}) + { + auto const radius{atend ? design.end_radius : design.start_radius}; + if ((atend ? Index + 1 != count : Index != 0) || radius <= 0.0 || radius >= 10000.0 || (atend && count == 1 && design.start_curved)) + continue; + auto &curved{atend ? design.end_curved : design.start_curved}; + changed |= ImGui::Checkbox((format(atend ? STR_C("Goes into the curve of the track at the end (R %.0f m)") : STR_C("Goes on from the curve of the track at the start (R %.0f m)"), radius) + (atend ? "##curvedend" : "##curvedstart")).c_str(), &curved); + item_tooltip("The curve begins right at the end of the fragment, at the curvature of the track adjoining there, where it turns the same way; its radius is the one " + "which begins it there, the transition at that end goes between the two curves"); + } + changed |= field("##radius", vertex.radius, 5.0f, vertex.compound ? STR_C("R1 %.0f m") : STR_C("R %.0f m"), overlay_color::grip, "Radius of the arc: drag sideways, or a double click to type it", part::arc); + ImGui::SameLine(); + changed |= field("##cant", vertex.cant, 1.0f, STR_C("cant %.0f mm"), IM_COL32(240, 170, 60, 255), + vertex.compound ? "Height of the outer rail above the inner one on the sharpest arc; the arcs with no cant of their own get it in proportion to their curvature" + : "Height of the outer rail above the inner one", + part::whole); + changed |= field("##entry", vertex.transition_in, 1.0f, STR_C("entry %.0f m"), transition, "Length of the transition curve leading into the arc", part::entry); + ImGui::SameLine(); + changed |= field("##exit", vertex.transition_out, 1.0f, STR_C("exit %.0f m"), transition, "Length of the transition curve leading out of the arc", part::exit); + ImGui::PushItemWidth(110.0f); + if (ImGui::Checkbox(STR_C("Two transition curves, no arc"), &vertex.spirals)) + { + changed = true; + if (vertex.spirals) + vertex.compound = false; + } + item_tooltip("The bend eased the way the lines are drawn: two transition curves meeting at the radius, with no arc between them and no cant; their lengths follow from the radius and the angle"); + if (false == vertex.spirals && ImGui::Checkbox(STR_C("Compound curve (several radii)"), &vertex.compound)) + { + changed = true; + if (vertex.compound && vertex.arcs.empty()) + vertex.arcs.push_back({std::max(10.0, std::round(vertex.radius * 0.6 / 10.0) * 10.0), 0.0, 1.0}); + } + if (false == vertex.spirals) + item_tooltip("Curve made of arcs of different radii, each one its own path, joined with transitions"); + if (vertex.compound) + { + auto total{std::max(0.0, vertex.share)}; + for (auto const &arc : vertex.arcs) + total += std::max(0.0, arc.share); + auto const percent = [&](double const Share) { return total > 0.0 ? 100.0 * std::max(0.0, Share) / total : 0.0; }; + auto const cants{alignment::compound_cants(vertex)}; + // the cant of one arc: the one in proportion to the curvature until it's given its own + auto const arc_cant = [&](int const Arc, double &Cant) { + auto value{static_cast(Arc) < cants.size() ? cants[Arc] : std::max(0.0, Cant)}; + auto edited{ImGui::DragScalar(format(STR_C("Cant of R%d (mm)"), Arc + 1).c_str(), ImGuiDataType_Double, &value, 1.0f, nullptr, nullptr, "%.0f")}; + settled |= ImGui::IsItemDeactivatedAfterEdit(); + mark(part::arc, Arc); + if (edited) + Cant = std::max(0.0, value); + item_tooltip("The cant of this arc, ramped along the transition curves to the arcs either side of it; until it's set here, the cant of the curve in proportion to the curvature of the arc"); + ImGui::SameLine(); + if (Cant < 0.0) + ImGui::TextDisabled("%s", STR_C("auto")); + else if (ImGui::SmallButton(STR_C("auto"))) + { + Cant = -1.0; + edited = true; + settled = true; + } + item_tooltip("The cant of the arc in proportion to its curvature again"); + return edited; + }; + changed |= ImGui::DragScalar(format(STR_C("Share of R%d"), 1).c_str(), ImGuiDataType_Double, &vertex.share, 0.01f, nullptr, nullptr, "%.2f"); + mark(part::arc, 0); + ImGui::SameLine(); + ImGui::TextDisabled("%.0f%%", percent(vertex.share)); + changed |= arc_cant(0, vertex.first_cant); + int removed{-1}; + for (int k = 0; k < static_cast(vertex.arcs.size()); ++k) + { + auto &arc{vertex.arcs[k]}; + ImGui::PushID(k); + ImGui::Separator(); + changed |= ImGui::DragScalar(format(STR_C("Radius R%d (m)"), k + 2).c_str(), ImGuiDataType_Double, &arc.radius, 5.0f, nullptr, nullptr, "%.0f"); + mark(part::arc, k + 1); + ImGui::SameLine(); + if (ImGui::SmallButton("x")) + removed = k; + item_tooltip("Takes this radius out of the curve"); + mark(part::arc, k + 1); + changed |= ImGui::DragScalar(format(STR_C("Transition R%d-R%d (m)"), k + 1, k + 2).c_str(), ImGuiDataType_Double, &arc.transition, 1.0f, nullptr, nullptr, "%.0f"); + settled |= ImGui::IsItemDeactivatedAfterEdit(); + mark(part::between, k + 1); + changed |= ImGui::DragScalar(format(STR_C("Share of R%d"), k + 2).c_str(), ImGuiDataType_Double, &arc.share, 0.01f, nullptr, nullptr, "%.2f"); + mark(part::arc, k + 1); + ImGui::SameLine(); + ImGui::TextDisabled("%.0f%%", percent(arc.share)); + changed |= arc_cant(k + 1, arc.cant); + arc.radius = std::max(1.0, arc.radius); + arc.transition = std::max(0.0, arc.transition); + arc.share = std::max(0.0, arc.share); + ImGui::PopID(); + } + vertex.share = std::max(0.0, vertex.share); + if (removed >= 0) + { + vertex.arcs.erase(vertex.arcs.begin() + removed); + if (vertex.arcs.empty()) + vertex.compound = false; + changed = true; + } + if (ImGui::SmallButton(STR_C("Add a radius"))) + { + auto const last{vertex.arcs.empty() ? vertex.radius : vertex.arcs.back().radius}; + vertex.arcs.push_back({std::max(10.0, std::round(last * 0.8 / 10.0) * 10.0), 0.0, 1.0}); + changed = true; + } + item_tooltip("Another arc after the last one, the angle of the curve is shared out by the shares"); + ImGui::Separator(); + } + ImGui::PopItemWidth(); + vertex.radius = std::max(1.0, vertex.radius); + vertex.transition_in = std::max(0.0, vertex.transition_in); + vertex.transition_out = std::max(0.0, vertex.transition_out); + vertex.cant = std::max(0.0, vertex.cant); + { + // the transitions follow the radii, which follow the points clicked: a few rounds settle them + auto const reshape = [&](auto const &Shape) { + for (int pass = 0; pass < 3; ++pass) + { + Shape(); + if (false == route.hold || false == route_hold_clicks(Index)) + break; + } + changed = true; + }; + if (ImGui::SmallButton(STR_C("Apply recommended for V"))) + reshape([&] { route_recommend(vertex); }); + if (ImGui::IsItemHovered()) + { + auto const recommended{alignment::recommend(design.speed, vertex.radius, design.norms)}; + ImGui::SetTooltip("%s\n%s", STR_C("Cant and transitions recommended for the design speed and the radius"), + format(STR_C("For %.0f km/h: R min %.0f m, cant %.0f mm (equilibrium %.0f, min %.0f), transition %.0f m"), design.speed, recommended.radius_min, recommended.cant, recommended.cant_equilibrium, recommended.cant_min, recommended.transition).c_str()); + } + if (false == vertex.spirals) + { + ImGui::SameLine(); + if (ImGui::SmallButton(STR_C("Transitions for these cants"))) + reshape([&] { alignment::norm_transitions(vertex, design.speed, design.norms); }); + item_tooltip("The transition curves as long as the norms ask for at these radii and cants, the cants staying: a cant lowered asks for longer ones"); + mark(part::whole, 0); + } + } + // the cant ramps at the ends of the curve: along its transitions, or where they're put, off a switch laid on a transition say + if (false == vertex.spirals && ImGui::TreeNode(STR_C("Cant ramps"))) + { + std::vector ramps; + for (auto const &ramp : route.result.ramps) + if (ramp.vertex == Index) + ramps.push_back(ramp); + auto const ramp = [&](char const *Id, char const *Label, double &Offset, double &Length, std::size_t const Which, part const What) { + ImGui::PushID(Id); + auto along{Length < 0.0}; + if (ImGui::Checkbox(Label, &along)) + { + // let go of the transition where it lay along it, to be moved from there + Length = along ? -1.0 : Which < ramps.size() ? ramps[Which].to - ramps[Which].from : 0.0; + Offset = 0.0; + changed = true; + } + mark(What, 0); + item_tooltip("The norms recommend the cant ramp along the transition curve; off it, it may lie on the straight before the curve or on the arc, a switch on the transition keeping the same cant all along"); + if (false == along) + { + ImGui::SetNextItemWidth(half); + changed |= ImGui::DragScalar("##offset", ImGuiDataType_Double, &Offset, 0.5f, nullptr, nullptr, STR_C("into the curve %.1f m")); + mark(What, 0); + item_tooltip("How far the outer end of the ramp lies into the curve from its end, below 0 out along the straight before it"); + ImGui::SameLine(); + ImGui::SetNextItemWidth(half); + changed |= ImGui::DragScalar("##length", ImGuiDataType_Double, &Length, 0.5f, nullptr, nullptr, STR_C("length %.1f m")); + mark(What, 0); + item_tooltip("The length of the ramp, the cant rising evenly along it"); + Length = std::max(0.0, Length); + } + if (Which < ramps.size() && ramps[Which].to > ramps[Which].from) + ImGui::TextDisabled(STR_C("km %s - %s, %.2f mm/m"), profile::format_chainage(route.origin + ramps[Which].from).c_str(), profile::format_chainage(route.origin + ramps[Which].to).c_str(), + ramps[Which].cant / (ramps[Which].to - ramps[Which].from)); + ImGui::PopID(); + }; + ramp("in", STR_C("Ramp in along the transition curve"), vertex.ramp_in_offset, vertex.ramp_in_length, 0, part::entry); + ramp("out", STR_C("Ramp out along the transition curve"), vertex.ramp_out_offset, vertex.ramp_out_length, 1, part::exit); + ImGui::TreePop(); + } + if (ImGui::TreeNode(STR_C("Details"))) + { + for (auto const &curve : route.result.curves) + { + if (curve.vertex != Index) + continue; + ImGui::Text(STR_C("Deflection %.4f deg, tangents %.2f / %.2f m, arc %.2f m"), glm::degrees(curve.deflection), curve.tangent_in, curve.tangent_out, curve.arc_length); + ImGui::Text(STR_C("Unbalanced acc. %.3f m/s2, cant rate %.1f / %.1f mm/s, acc. rate %.3f / %.3f m/s3"), curve.unbalanced, curve.cant_rate_in, curve.cant_rate_out, curve.jerk_in, curve.jerk_out); + } + changed |= ImGui::Checkbox(STR_C("Turn the longer way (over 180 deg)"), &vertex.reverse_turn); + item_tooltip("For the loops: the curve turns by more than a half circle"); + ImGui::TreePop(); + } + ImGui::EndGroup(); + if (route.focus.vertex != Index && false == route.focus.held && ImGui::IsItemHovered()) + route.focus = {Index, part::whole, 0, false}; + if (settled && route.hold) + changed |= route_hold_clicks(Index); + return changed; +} + +void editor_mode::render_route_result() +{ + auto const &route{m_route}; + auto const &design{route.design}; + auto const &result{route.result}; + if (result.length > 0.0 && (result.start_extension > 0.0 || result.end_extension > 0.0)) + ImGui::Text(STR_C("Takes over %.2f m of the straight at the start, %.2f m at the end"), result.start_extension, result.end_extension); + for (auto const &error : result.errors) + ImGui::TextColored(ImVec4(1.0f, 0.35f, 0.3f, 1.0f), "%s", error.c_str()); + for (auto const &warning : result.warnings) + ImGui::TextColored(ImVec4(1.0f, 0.7f, 0.2f, 1.0f), "%s", warning.c_str()); + + ImGui::PushID("routeresult"); + if (result.length > 0.0 && ImGui::TreeNode(STR_C("Details"))) + { + auto const pieces{alignment::minimum_pieces(result, design)}; + ImGui::Text(STR_P("Length %.2f m (now %.2f m), %zu element", "Length %.2f m (now %.2f m), %zu elements", result.elements.size()), result.length, route.chain.length, result.elements.size()); + ImGui::TextDisabled(STR_C("Paths: %zu in the fragment, %zu needed%s"), route.chain.tracks.size(), pieces, pieces > route.chain.tracks.size() ? STR_C(" (copies of the neighbours will be added)") : ""); + ImGui::TreePop(); + } + ImGui::PopID(); + if (ImGui::TreeNode(STR_C("Elements"))) + { + ImGui::TextDisabled(STR_C("Straight available beyond the ends: %.2f / %.2f m"), design.start_reserve, design.end_reserve); + static char const *const kinds[] = {"straight", "transition", "arc", "transition", "transition between arcs"}; + for (auto const &e : result.elements) + ImGui::Text("km %s %-10s L %8.2f m%s", profile::format_chainage(m_route.origin + e.chainage).c_str(), STR_C(kinds[static_cast(e.kind)]), e.length, e.kind == alignment::element_kind::straight ? "" : (" R " + std::to_string(static_cast(std::round(e.radius))) + " m").c_str()); + ImGui::TreePop(); + } + + if (result.valid) + { + if (main_button(STR_C("Apply to the scenery"), ImVec2(-1.0f, 28.0f))) + { + route_apply(); + first_step_done(first_step::plan_apply); + } + } + else + { + ImGui::TextDisabled(STR_C("Correct the errors to apply the design")); + } + if (false == route.status.empty()) + ImGui::TextUnformatted(route.status.c_str()); +} + +editor_track::straight const &editor_mode::current_straight() +{ + auto *track{selected_track()}; + if (track != m_straights.current_for) + { + m_straights.current_for = track; + m_straights.handle = -1; + m_straights.current = track != nullptr ? editor_track::find_straight(*track, m_straights.tolerance) : editor_track::straight{}; + find_neighbour_straights(); + } + return m_straights.current; +} diff --git a/application/editormodeselection.cpp b/application/editormodeselection.cpp index a8c845339..42d3d5d50 100644 --- a/application/editormodeselection.cpp +++ b/application/editormodeselection.cpp @@ -11,6 +11,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "application/editormode.h" +#include "application/editormodeshared.h" #include "application/editoruilayer.h" #include "application/editorprojection.h" #include "editor/editorFormat.hpp" @@ -269,7 +270,9 @@ void editor_mode::group_selection() std::string reason; if (node->from_template() || false == scene::Layers.editable(node, &reason)) { - ui()->set_status("\"" + (node->name().empty() ? std::string{"(unnamed node)"} : node->name()) + "\" can't be grouped: " + reason, true); + if (reason.empty()) + reason = STR("it's a part of a scenery template"); + ui()->set_status(format(STR_C("\"%s\" can't be grouped: %s"), name_of(*node).c_str(), reason.c_str()), true); return; } } @@ -332,7 +335,7 @@ void editor_mode::render_context_menu() if (count > 1) ImGui::TextDisabled(STR_C("%zu models selected"), count); else if (selected) - ImGui::TextDisabled("%s", m_node->name().empty() ? "(unnamed node)" : m_node->name().c_str()); + ImGui::TextDisabled("%s", name_of(*m_node).c_str()); else ImGui::TextDisabled("%s", STR_C("Nothing selected")); ImGui::Separator(); @@ -347,11 +350,11 @@ void editor_mode::render_context_menu() if (item(STR_C("Paste here"), "Ctrl+V", false == m_clipboard.empty(), STR_C("Puts the copied models here, around this point as they were around the selected one"))) paste_clipboard(m_contextpoint); ImGui::Separator(); - if (item(STR_C("Group"), "Ctrl+G", model && count > 1, STR_C("The selected models move together from now on; a click on one selects them all"))) + if (item(STR_C("Group together"), "Ctrl+G", model && count > 1, STR_C("The selected models move together from now on; a click on one selects them all"))) group_selection(); if (item(STR_C("Ungroup"), "Ctrl+Shift+G", selected && m_node->group() > 1, STR_C("The models of the group move each by itself again"))) ungroup_selection(); - if (item(STR_C("Drop to the ground"), STR_C("End"), selected, STR_C("Puts each selected model, also each model of their groups, down onto the terrain or the object under it"))) + if (item(STR_C("Drop to the ground"), "End", selected, STR_C("Puts each selected model, also each model of their groups, down onto the terrain or the object under it"))) drop_selection_to_ground(); ImGui::Separator(); if (item(STR_C("Fly to the selected"), "F", selected, STR_C("The camera flies to the selected model and looks at it"))) diff --git a/application/editormodeselftest.cpp b/application/editormodeselftest.cpp index 98d4a1e2d..f81b73f3a 100644 --- a/application/editormodeselftest.cpp +++ b/application/editormodeselftest.cpp @@ -14,6 +14,8 @@ http://mozilla.org/MPL/2.0/. #include "application/application.h" #include "application/editoruilayer.h" #include "application/editorprojection.h" +#include "application/editorgestures.h" +#include "imgui/imgui.h" #include "simulation/simulation.h" #include "simulation/simulationtime.h" @@ -21,6 +23,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Globals.h" #include "utilities/Logs.h" #include "world/Track.h" +#include "world/TrackRails.h" #include "world/MemCell.h" #include "world/Event.h" #include "vehicle/DynObj.h" @@ -29,21 +32,52 @@ http://mozilla.org/MPL/2.0/. #include "rendering/renderer.h" #include "world/Sweep.h" #include "input/keyboardinput.h" +#include "launcher/textures_scanner.h" #include #include #include #include "editor/editorFormat.hpp" +#include "editor/editorAlignmentStore.hpp" +#include "editor/editorSwitchStore.hpp" +#include "scene/sceneterrain.h" +#include "editor/editorSpeed.hpp" +#include #include #include #include #include #include +#include "application/editormodeselftest.h" + +editor_mode::selftest_result editor_mode::selftest_dispatch(std::string const &command, std::istringstream &words) +{ + for (auto const group : {&editor_mode::selftest_scene, &editor_mode::selftest_sleepers, &editor_mode::selftest_sweep, &editor_mode::selftest_track, &editor_mode::selftest_switch, &editor_mode::selftest_rails, &editor_mode::selftest_join, &editor_mode::selftest_signal, &editor_mode::selftest_terrain, &editor_mode::selftest_props, &editor_mode::selftest_monkey}) + if (auto const result{(this->*group)(command, words)}; result != selftest_result::unhandled) + return result; + for (auto *tool : m_tools) + if (auto const result{tool->selftest(command, words)}; result != selftest_result::unhandled) + return result; + return selftest_result::unhandled; +} + // the script is a text file, one action a line: // wait // camera from the first point, looking at the second // select +// selectat the path nearest the point, within 3 m, as a click on it +// trackends logs the ends of the first path of the track against the ground under them +// kbreak K on the track nearest the point: split there, a break of the grade at the height of the ground +// blade [name] logs the blades of each switch cut from the rails: tip, 50 mm head, full head, heel, drop of the head, open flangeway, the gauge lines apart against x^2/2R, vertices in both positions +// frog [name] logs where the inner rails of each switch cross: distance on both paths, 1:n, throat, nose, check rails +// guards [name] logs each guard rail and what each of its ends and breaks is cut along; a fault when a cut is not along a rail or a glued end not on the guard rail of the other track +// railtime lays out the rails of every track, as when its geometry is made, and logs how long it took +// throw <0|1> sets every switch to the path and moves its blades there at once +// crossings [name] logs where rails of tracks cross rails of other tracks and of what kind (acute, obtuse, middle acute or obtuse, wide), checks that each acute crossing has one partner and one nose +// switchtimbers the model of the timbers set on all the switches and crossings, as the buttons of the switch tool do it +// frogkey name [on|off] sets or clears the frogs key of a switch (one undo step); logs the key, whether it is written, the frog and the crossings +// geomhash [name] logs the number of vertices and a hash of the drawn geometry of each rail track (rails, trackbed, cut faces), to compare builds; exact: the bits of every value, userdata and tread materials too // sweep =... model, params (separated by commas), lateral, height, side (origin, near, far, // centre), top (origin, bottom, top, edge), mode (bend, repeat), step, // length (original, all, or metres), from, to, widen (0, 1), face (0, 1), tilt (0, 1) @@ -71,6 +105,8 @@ http://mozilla.org/MPL/2.0/. // checkspans logs whether the text the scenery files hold at each node's place starts and ends it // spread logs the paths the spread from the track takes // newscenery the editor starts again with the wizard of a new scenery +// mapstate logs the orthophoto, the top view and the //$o line of the scenery +// trainset [km/h] the trainset tool puts the vehicle in the middle of the track // vehicles logs each vehicle: its head, facing, and what its couplers hold // terrainmode the terrain field of work, with its texture browser // terrainsculpt , terrainpaint , @@ -88,9 +124,90 @@ http://mozilla.org/MPL/2.0/. // terrainturn the textures of the palette entry turned // terrainwater [size] material and repeat of a body of water; terrainwaterdefault // orthophoto [in scene 0|1] the imagery layer on, placed and fitted as given +// orthoarea ... | clear the download area through the points of the world, as drawn on the map; orthoareapause 0|1 +// orthohires 0|1 the 4K tiles on or off; orthostats logs the tiles, the area and the requests made +// orthosettings [on|radius|opacity|lift|height|year|hires|drape|scene ]... the settings of the orthophoto changed as its +// panel and its checkbox change them, kept with the editor, and logged with the origin of the scenery +// nmtsettings [band|around|shape|common|follow|grow|offset|fitted ]... the settings of the terrain model changed as the terrain +// panel changes them, and logged with the offset of the model to the scenery +// join [radius] [variant] [transitions 0|1] the free ends at the points joined, as a drag from one to the other +// layto from the free end at the first point towards the second, as a drag in the layout +// layclicks ... clicks of the lay tool at the points, a free end within 3 m joined +// laymonkey [case] random lines laid to and from the free ends of the scenery, as the preview shows them: gaps and +// angles at the joints, loops, the turning wasted and the sharpest curve logged; case: that one alone +// layspeed the speed set for the laying, and whether it goes also on from a track with its own +// laymode , laytrace as the panel of the laying sets them +// endcurves logs every free end of the rails: where, the way out and the curvature its track goes on with +// curvejoint logs the paths meeting at the end nearest the point, the curvature of each and its jump from the ones before to the ones after +// cantcheck