mirror of
https://github.com/MaSzyna-EU07/maszyna.git
synced 2026-11-19 22:44:59 +01:00
* feat(track): the rail code split by concern, the blades of the switches with the key frogs shaped from their templates The rails are laid by code of their own instead of inside Track.cpp: gauge lines (GaugeLine), knot lines (Knots.h), crossings and check rails (RailCrossings), rail materials (RailMaterials), measuring the rail profile (RailProfile), planning the cuts (RailPlan), the carving scan (RailCarve) and laying the geometry (RailLayer). A switch with the key frogs draws its blades from the tip where their planed nose ends to the heel, bent as they're thrown, and the rail behind them from the heel on, where they were laid from the start of the switch before; on a switch of the catalogue they start at the cut tip of the tables, 1.248 m from the joint at R 190, 1.5 m at R 300 (track_features::blades). The frogs cut from the rails, the wing and the check rails are built but switched off (track_features::crossings), the rails laid whole as before. The switches without the key keep the blades they had. A switch path can be a chain of pieces: pieces1 and pieces2 keep the parts of each path after the classic bezier, which stays as the approximation older versions read. A path with its radius given is a curve however gently it bends, a plain track a straight only where both of its control vectors lie along it. A vehicle trailing through a switch with a movable nose set the other way runs off the rails at it (TRAILED_SWITCH). * feat(render): the shared treads of the rails and their cut faces drawn, the cut faces in the matte variants of the rail materials Both renderers draw the treads a track shares with the rails it crosses, in the pick pass too, and a pass of their own for the faces where the rails are cut, the ends of the blades among them, in the matte variants of the rail materials, so the cut faces don't shine like the head the wheels polish. * feat(vehicle): an axle on a switch keeps to the path it came on, and coming from the frog end trails the switch through where the wheels reach the blades The switch thrown under an axle no longer moves it over onto the other path; it runs on along the one it entered. Coming from the frog end, where the blades are shaped or the frog has a movable nose, the switch set the other way is trailed through (rozprucie) only where the wheels get to the blades or to the nose, not as the axle enters the track; the other switches are trailed through as it enters, as before. * fix(track): the tracks drawn straight before, which their second control vector bends now, written to the log The simulator told a straight by the first control vector of a path alone, so a track whose second control vector bent it was drawn straight; now it's a curve. Such a track is named in the log as it loads, so a scenery made counting on the straight can be found: 25 tracks of lk357. Paths with both control vectors along them bend a centimetre or so at most and aren't named. * feat(track): 3D sleepers and switch timbers laid where the simulator makes the ballast, switched off in the build The sleepers of a track running alone are laid square to it, the timbers of the switches and crossings across the tracks running over them, shared by them, of the models set with sleepers3d and sleepers3dplain in eu07.ini; sleepers3dbed tells whether the ballast is laid under them too, lowered so they stick out of it. The layout of a cluster of tracks is worked out once and kept till a track of it changes, in a thread of its own while the simulation runs. timbermodel of a track, read and written back before, takes the place of the model of sleepers3d there. All of it is off whatever eu07.ini sets (track_features::sleepers), the tracks keeping their ballast and their sleeper models. * feat(render): the 3D sleepers and switch timbers drawn in instanced batches Render_Timbers lays the beams of the tracks in range where they're out of date and draws those of a run of tracks of a cell gathered by the model and its part or its level of detail, in as few instanced batches as they fit in; in the shadow pass only those near the camera. A track with them leaves its old sleeper model out. OpenGL 3.3 renderer only. * fix(track): the counts of what's wrong with the sleepers kept safe from the thread laying them, and that thread stopped before what it works with goes The counts of the beams clipped, dropped and off the plane, of the slowest and the biggest cluster, are counted by the thread working out the layouts in the background as well as by the simulation laying a cluster itself, and were plain values written by both; they're atomic now. What the thread keeps the clusters in, their version and the counts were made after the worker, as it first asked for them, and so destroyed before it at the exit while its thread could still be laying a cluster; they're made first now, the worker stopping and joining its thread before they go. The tracks go with the paths of the simulation, made before the worker. * revert(track): a tributary and a track of an unknown type load as before They came in with the rail code from the guards of the editor against crashing, and don't belong with the blades: a track of an unknown type loaded as a normal track of the railway could be joined to it and run on, and a tributary loaded as a river with its first path lost the second one when the editor saved the scenery. Both load as on master again; the place where the editor crashed on them is to be guarded where it is. * fix(track): the tracks drawn straight before named in the log once, as they load, and the paths of the switches with no radius told a straight as before in one term The log of the tracks the second control vector bends now was written each time the segments of a track were made again, as a track with its unevenness loads and as the editor changes or drags a track; it's written only the first time, as the track loads. The paths of a switch or a crossing with no radius keep the rule of master, a straight told by the first control vector alone, its two terms being the same length; they're one term now, with the comment saying so. * fix(track): the thread laying the sleepers stopped as the application exits, and loading no models itself The thread reads the scenery, which the application deletes as it exits well before the statics go: it's stopped and joined first thing in exit() now, the worker destroyed with the statics only where the application exits some other way, and not started again after. The models the beams are made of were loaded by the thread where it didn't find them, through the renderer, out of the thread of the renderer, into a map read by the simulation meanwhile: they're found under a lock now and loaded only by the threads other than it, again for all the tracks whenever a track changed since, before a layout is asked of it. With the 3D sleepers off in the build their settings aren't exported, and a track changed doesn't look for the tracks around to lay their beams again. * feat(track): the 3D sleepers turned on with sleepers3d in eu07.ini, no longer switched off in the build track_features::sleepers is gone: sleepers3d <model> in eu07.ini lays them, none (the default) lays nothing and the tracks keep their ballast, as before. The sleepers3d settings are written back with the others. The editor changes the tracks, so while it's open their sleepers are worked out on the main thread as they're needed, not in the background. * fix(render): only the part of a timber model drawn, not what else the model holds A timber model of parts may hold more than its begin, main and end, as the kits with the fastenings of the rails do. Those were drawn with each part of each timber, in the middle of the track; they aren't laid, so they're skipped now. * fix(track): the 3D sleepers laid only for a renderer which draws them Only the OpenGL 3.3 renderer draws the beams. With another one a track set to them lost its ballast to them, lowered or not laid at all with sleepers3dbed no, and nothing was drawn in its place. Draws_Timbers() of the renderer tells now, and where it's false the tracks keep their ballast, as with sleepers3d none. * fix(render): the submodels of a timber model left as they were after its parts are drawn They were all made visible after a part was drawn, the ones the model hides itself too, like Light_On, while the same model may stand in the scenery. The submodels of the top level besides the parts are listed as the model is loaded, hidden while a part is drawn and given back their own visibility after. The parts have to be at the top level of the model for that; a model with them deeper is logged and drawn whole. Render_Timbers no longer looks the model up under the lock for every run of tracks, the name set is enough there. * fix(render): a vertex whose faces give its texture no direction gets a tangent across its normal, not a NaN one The cut ends of the rails have one spot of the texture on all their corners, so their tangent came out of normalize() as NaN. The normal-mapped shaders then shaded them with a NaN normal: about half of the vertices of the cuts and frogs, and the end faces of the rails. * feat(track): the frogs cut from the rails turned on with frogs in eu07.ini, no longer switched off in the build frogs yes cuts the rails of the plain tracks and of the switches with the key frogs where they cross other rails, into frogs, wing rails and check rails. It's off by default: the rails are laid whole as before, the blades of the switches with the key are shaped still. * refactor(editor): the track mode file split into the files of its tools, the code as it was A pure move, so that the commits after it show what changes in each tool rather than a 4800-line file rewritten. The member functions of editor_mode go to the file the editor of this branch has them in: route, straights, lay, switchplace, switchdrive, switchtool, trackgizmo, and the rest stays in editormodetrack.cpp. The helpers of its anonymous namespace go to editormodetrackshared.h, as they were but inline, in namespace track_mode, which the files use. No line of code changes; the files add only their license, includes and the using line. * feat(editor): the groundwork the tools of the editor share - The tool interface (editortool.h), the gestures of the mouse (editorgestures.h) and what the modes share (editormodeshared.h); the projection, viewport, selection and texture picking taking them up. - Scripted input (scriptedinput): the input of a selftest script fed to the editor as if typed and clicked, the real mouse and keyboard ignored meanwhile; EU07_EDITOR_SELFTEST_HIDDEN draws into a window never shown nor focused. - The ui layers and panels of the editor, its settings, icons and the info of the includes; the layers of the scenery and their saving; the launcher mode. - utilities: user_cache_path (the cache folder of the system for the user) and the helpers of the translations. - stb_image: the gif loader takes the frame two back from the frames it decoded, not from before its buffer. - tools/editor: the scripts making the headers of the drives, the turntables, the editor and its usage. - Unit tests: test_area and the stubs of the editor the tests link. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the tracks laid along an alignment, to the PKP PLK norms, with their grade line and the ground - The alignment of the laying (editorAlignment, editorAlignmentStore): straights, transition curves and arcs with the cant of the norms for the speed, the radius below the minimum for it a warning; the lay, route and straights tools build on it, the route plan reading the curves going on from the tracks adjoining. - The grade line (editorProfile, the profile and gradeline tools): fitted to the terrain model or edited by hand, the tracks fitted marked in the scenery (//$f), the shared grade lines of nearly parallel tracks (//$n). - The ground under the tracks (editorGroundFollow, trackbed): the terrain drawn to the tracks and restored, the tracks put onto the terrain. - Connections between tracks (editorConnections, the connection and connection curve tools), the track presets, the shape of a track (editorTrackShape), digitizing tracks from the orthophoto, the properties sheet of the tracks (trackprops) and the track ux. - Unit tests: alignment, ground fit, heights, with the data of two fits. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the switches placed, slid and designed from their templates - The switch templates (editorSwitchStore, the template tool): the catalogue switches and the user's own, kept with the settings; the designer (editorSwitchDesign) with a drawing of the dimensions, a and b typed in with the shape making up the rest, a switch clicked off the orthophoto. - The curve of a switch laid into a curve (editorSwitchCurve), placement on a straight or into a curve, slide along it, crossovers and double slips (switchplace, switchslide), the drives of the switches (switchdrive) and the records of the switches placed (records). - Unit tests: test_switch_curve. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the tools of the infrastructure beside the tracks The gauge, speed, joints, lineside, parallel tracks, vehicles, signals, turntables, sweep and road tools with headers of their own; the kilometrage of the lines (editorKilometrage, the km tool); the infrastructure, roads and speeds behind them (editorInfra, editorRoad, editorSpeed). Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the terrain model of geoportal.gov.pl and the orthophoto downloaded for the editor - editorNmt: the squares of the terrain model at 1 m (NMT GRID1, the WCS service of geoportal.gov.pl) fetched by two workers, kept in editor/cache/nmt/grid1 of the game folder, the heights of the scenery taken from them; the nmt mode loads it along the tracks or around the camera. - editorHttp: the HTTP client of both, WinHTTP on Windows, libcurl elsewhere where it's built with it; without it the caches only. - The orthophoto: its cache moved to the cache folder of the system for the user, the download area a polygon on the topo map (//$a) filled in the background, the 4K imagery, the tiles waiting outlined on the ground. - editorGeoMap: the topo map of the top view; heightmapterrain and the terrain streamer grow the terrain made from the model around the camera. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(launcher): the scenery wizard picks the place of a new scenery on the topo map the editor shares The wizard drops its own map download and decoding for the topo map widget of the editor (editorGeoMap). The place clicked becomes the geographic reference of the new scenery (//$g PUWG1992), and the scenery starts with the orthophoto of the editor on (//$o), lying under it in place. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the tools wired into the editor mode and the build editor_mode takes the tools of the commits before: its header declares them, editormode.cpp and the track mode drive them, and the renderers draw their overlays (opengl33 and legacy). CMakeLists lists the new sources and adds WITH_EDITOR_SELFTESTS (off by default); the unit tests build the new test files. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the selftests of the editor split by what they test The scripts of EU07_EDITOR_SELFTEST run the commands of editormodeselftest*.cpp: scene, track, rails, join, switch, signal, sleepers, sweep, terrain, monkey. The code is in every build; only with WITH_EDITOR_SELFTESTS=ON does the editor read the variables and run a script. The selftests of master now need the option too. The tree builds again with this commit. * feat(editor): the Polish texts of the editor, all of them in one update of editor_pl.po * fix(editor): the marks of the editor moved off the letters the starters read, and its lines told by their words The starters read some letters in a scenery file: the Starter the title //$n, the attachments //$f and the old scenery //$a, StarterNG and the launcher of the game the attachments //$f and the title //$n. The editor wrote its download area, shared grade lines and fitted tracks under them, and took every line of those marks as its own: saved, a scenery lost its title and attachments, and the starters showed the lines of the editor as them. - The download area is //$z, the shared grade lines //$w, the fitted tracks //$t. - Their lines and those of //$o are told by their first words, as //$h, //$r and //$k were: //$o only as "on 0" or "on 1", the origin or the settings of older builds after it, so a trainset described as "on ..." isn't taken. - The lines older builds wrote under //$a, //$n and //$f are read only by the words the editor wrote in them, or by its own comment line before them, under the new mark. Each save writes them again with it, also when the editor didn't change them; the lines of the starters stay. * fix(editor): a square of the terrain model cut short isn't read, and the squares are kept in the user's cache The service puts the directory of its GeoTIFF before the pixels, so a file cut short by a write or a fetch broken off was read whole, the pixels missing coming out as heights of 0 m, for good. - The reader (editorGeoTiff.hpp, with unit tests) wants all the strips the rows need, each within the file. - A square is written under a name of its own and renamed. - The squares are kept in the user's cache folder (nmt/grid1), as the orthophoto, since the game folder may not be writable; without one, in the game folder as before. The ones older builds kept there are moved over as each is asked for, a damaged one deleted. - Capabilities that didn't come aren't kept as the fallback name for the session: the next square asks again. * chore(editor): the http client said to serve the terrain model and the topo map too, the gif fix of stb_image marked local - CMake names the orthophoto, the terrain model and the topo map as what goes without libcurl. - The fix of the gif frame two back in stb_image is ours, not upstream's (v2.30 still has the old line): a comment at the line says so, for an update of stb_image to keep it. * fix(editor): the lines moved off the letters of the starters in a merged layer written once, not again with each save A merged layer's text goes into the file of its target on save, and the target is read again; the marked lines of the merged layer were dropped only for the marks the editor had changed. The lines moved to the new letters stayed with their old places, and the next save of the session wrote them into the target once more. - After a save, the marked lines of every merged layer are dropped; those of its target are read again from its file. - The lines of a dead layer aren't written again. - The selftest layermerge merges the layer of one file into another's, as the layers panel does. * feat(editor): the station as the signalling sees it, found from a switch of it, and its schematic editorStation: the switches joined by plain track no longer than 1.5 km, the tracks between them and the lines leading out, 400 m of each beyond the outermost switch; laid out as a schematic along the main track through the station. The track circuits, the signals and their lights, the lengths of the station tracks and the lines to the next stations are worked out from it for the signalling tool. Nothing uses it yet: the signalling tool, wired in the next commit, does. It builds on its own. * feat(editor): the signalling of a station in the Signalling tab, laid out from a switch of it as on the lines of PKP PLK LMB on a switch in the Signalling tab opens its station: the schematic in a window of its own, the name, the code, the line and the km of the station, and the steps of its signalling, each one step of undo: - the switches numbered along the station after its code, bpd_1, the parts of a slip bpd_15a..d; the drives and the objects naming a switch follow it, events written by hand keep the old names; - the tracks cut at the joints of the track circuits, Ie-4, and the circuits named, bpd_iz1, bpd_it1; - the entry, exit and shunting signals placed and named, A, F1, Tm1, from the templates chosen; - the signals of the lines out: the automatic block of three or four aspects, the block sections no shorter than the braking distance, or the semi-automatic one with a warning disc; block boundaries drawn by hand; - the lights each signal needs for its routes, Ie-1 and Ie-4 § 8, its template fitted to them; - the SHP track resonators the signals lack, rezonator.inc; - the lengths of the station tracks as a table, and what the station and its lines still lack, with Repair. The stations described are kept as //$s lines in the files of their layers. * fix(editor): the signals of a station and of its lines not placed with no template for a kind, no track cut for them first - Set the signals and Set the line signals cut the tracks first, and only then found no template for a kind. They stopped there, but the cuts stayed as a step of undo. Now they ask for the templates first, by the lookup signal_batch() uses (signal_template_for(), behind editor_signals::signal_templates_missing()). Without one nothing is cut. - Set the signals and Set the track circuits again under Track lengths had the ids of the buttons of the steps above them. ImGui flagged them when hovered. Each now has an id of its own. * fix(utilities): win1250_to_utf8 turns the polish letters into utf-8, not into themselves utilities.cpp starts with a byte order mark, so the compiler reads it as utf-8. The game's targets don't get /utf-8, though: set_target_properties(... COMPILE_OPTIONS ...) in the MSVC block of CMakeLists.txt replaces the options add_compile_options gave them. So the string literals went into the program in the code page of the system, windows-1250 on a polish one, and the map of win1250_to_utf8 turned each letter into itself. What read windows-1250 through it got no utf-8: the names, descriptions and categories of the sceneries and the names of the textures in the launcher, and the descriptions of the templates in the editor. The editor writes such a description back through utf8_to_win1250, which makes a question mark of each byte that doesn't start a utf-8 sequence, so the letters it had read unchanged didn't come back. The utf-8 sequences are written as bytes now, the way utf8_to_win1250 has them, so they don't depend on the options. The options stay as they are: with /utf-8 other literals of the files with a byte order mark would change, the "±" of the table of Bezogonkow would take two bytes and move the letters after it. The unit tests check the letters and that the text given is valid utf-8. (cherry picked from commit9ffed96ec1) * fix(editor): the switches renamed only after the events by their old names are shown, the station records in windows-1250 and in the file the scenery had Number the switches renames the switches and what the editor writes along with them, but not the events written by hand: a switch event aiming at a switch, or <name>:event0 and the others named after it, would keep the old name and lose its switch. Now the first click lists them in the status, up to six and how many more, and renames nothing. A second click with the same renames goes ahead. The name of a station is written in windows-1250, like the rest of the scenery file. A name read that isn't valid utf-8 is taken for windows-1250; the utf-8 the earlier builds wrote is read as it is. utf8_to_win1250 moves from editorIncludeInfo.cpp to the utilities, beside win1250_to_utf8, and the unit tests check both ways. The record of a station that had none goes beside the records of the other stations, in the file marked with them, so a scenery saved under another name keeps them in one file. output_layer takes, after <scenery>_<part>.scm, an included file of the part of another name, the one of the scenery it was copied from, before it makes a new one. The comments: the joints of the track circuits stand 4.2 m beyond the fouling points, where the axes are 3.5 m apart, as joints() counts them; the regulation of the lengths is cited with its date and title. * fix(editor): a scenery saved under another name keeps one file of the keys by the movable noses, not the old one beside its own The editor writes the keys by the movable noses on each save to <scenery>_dzioby.scm and includes it. A copy of a scenery, saved under another name, still included the file of the scenery it came from, and its save wrote a file of its own and included it too, so each key stood twice. Now the save leaves out of the scenery the other files of such keys it includes, told by the line the editor writes at their start. Their files stay on the disk, for the scenery they were made for. A file made by hand, without that line, stays included. The turntable controls had the same, fixed the same way on their own. * fix(editor): a file of the scenery named like a part of a tool isn't taken for the one the tool made output_layer took, after <scenery>_<part>.scm, any included file named *_<part>.scm, so that a scenery saved under another name goes on with the file of the scenery it was copied from. A file of the scenery named alike, written by hand, such as rejon_teren.scm, got the terrain directive, the hectometre posts or the new signals too. The files output_layer makes start with a line of their own now, "// scenery layer created in the editor for its <part> part", and a file of another name is taken only with that line. A layer gets it through the new parameter of scene::node_layers::create(); the others start with the general line as before. <scenery>_<part>.scm of the scenery itself is taken without the line, as it was. A file made for a part by an earlier build has only the general line, so a copy saved from it gets a file of its own. * feat(editor): a player of GIF clips for the windows of the editor editor_clips::clip plays a GIF in an ImGui window, looped, from the time given. stb_image decodes the whole file on a thread of its own, so the window isn't held up; until then the clip says it's loading. The frames are kept as stb_image decoded them, and the one shown is a texture of the ImGui renderer (Create_Image), made again only when the frame changes. A file that isn't there is told missing at once, with no thread started. Nothing uses it yet; the tutorial of the next commit shows its clips with it. * feat(editor): Help > Tutorial, fifteen short lessons of the editor The lessons: looking around, laying track, curves, the radius of the curves at the bends, correcting a curve, joining tracks, switches, switch templates, signals and posts, selecting and fixing, editing with the gizmo, the grade line, terrain from the terrain model, sceneries made before, saving and driving. Each lesson has: - in eight lessons, a looping clip from lang/editor_tutorial/<lesson>.gif, played from the start on a click; in six others, a moving drawing (the radius at a bend, a switch template clicked, the signals, the grade line, the terrain, a trainset); - the mouse buttons and keys drawn as pictures beside what they do; - ticks that fill in as the user does it, told by the tools through editor_guide::first_step_done(); - a button that turns the tool of the lesson on; - Back / Next and a dot per lesson, green when the lesson is done. The window follows the work: when the tool in use changes, it turns to the first lesson of that tool not done yet, and a page turned by hand stays until then. In a lesson of laying it warns when there's no ground under the cursor. Where it opens: - by itself when an editor session starts, until "Show when the editor opens" is unticked (first_steps in the editor's settings); - from the Help menu; - from a Tutorial button beside Lay a track in the hint of an empty scenery, which isn't drawn while the tutorial is open; - at its lesson, from a "?" by the radius at the bends in the lay panel. A lesson whose clip isn't there is shown without it; the clips aren't in this commit. editor_guide is a new role of the editor, given to the hekto-post and trainset tools. Selftest command tutorial <page>: opens the tutorial at a lesson, from 0; -1 closes it. * fix(editor): the lessons of the tutorial say what the editor does The lesson texts checked one by one against the tools; the ones that told otherwise: - Switches: a connection isn't chosen at the top of the panel, its kind comes from where the drag is let go (a crossover onto the other track, over a crossover the other way a double one, or scissors where they overlap). - Switches: a ladder leads onto the parallel tracks it's dragged across, let go on the farthest, with the straights up to where they start; it lays no missing tracks. - Terrain: there is no step 3. Step 1 is Location, step 2 is Load around the camera while there are no tracks and Tracks and terrain with its three ways once there are. The rows had the step numbers in the keys column, and 1, 2 and 3 switch the edit modes in the Terrain field. Now the steps show the mouse, the terrain under some tracks only is a row of F3 (the line the terrain panel shows), and the rows that only tell what the fit does have no key. - Sceneries made before: a plain include can be changed; the row lists what can't: an include template (.inc), the binary terrain cache, a file included twice or with parameters, a locked or hidden layer. - Laying: the second Esc drops the points only within 3 s. - The radius at the bends: two transition curves from 6000 m down to 2000 m while they're long enough for the speed, then an arc; a label turns orange where the curve breaks the norms, not because it came out smaller; two transitions meeting read 2xL and R; the labels of each transition curve are on laid tracks, close up. - Signals and posts: the W17 markers go by the selected switch, around the camera or the whole scenery, not along a line. - Selecting and fixing: E lengthens the track, the control vectors bend it. - The gizmo: at a point Q moves the point alone, W turns the whole track about it. The tooltip of Help > Tutorial no longer speaks of clips: the tutorial goes without them. lang/editor_pl.po has the new texts. * fix(editor): the lessons of the tutorial in plain words Every row, goal and warning of the tutorial is said again for someone who has never laid a track, in English and in Polish: - the words of the railway and of the editor are said in everyday ones, or explained where they come: the radius (how big the curve is), the transition curve (the easing into it), the cant (the outer rail raised), the gizmo (handles on the track), the control vectors (points that bend it), the grade line (how the line goes up and down), the terrain model (the real ground), the orthophoto (the aerial photo), the hectometre posts (every 100 m), W17 (how far a wagon may stand); - what only a designer needs is left out: the 6000 and 2000 m of the radius ladder, the compound curve, the hump, the kinds of include that can't be changed; - the buttons are named as the panels name them: Apply to the scenery, Template editor..., the tiles of the switch tool; - the Polish names of three lessons say what they are about ("Uchwyty na torze (gizmo)", "Wzniesienia i spadki", "Prawdziwy teren"). Their English titles stay, the lessons are found by them; - the warning of no ground under the cursor tells what happens to the track; - two captions of the drawings say what they show (the tracks inside a box, posts every 100 m), and in Polish the button of the top view is "Widok z góry (O)", without "ortogonalny". What each row tells of is the same as before. The msgid of the length typed while laying stays, the window of the keys (F1) uses it. * feat(editor): the semaphores and the warning discs chosen by what their descriptions say they show The descriptions of the signal templates can now say what a semaphore shows and what a disc repeats, and the editor reads it: - signal: {arms: 2, aspects: {Sr1: ..., Sr2: ..., Sr3: ..., Sz: ...}, repeats: {stop: ..., vmax: ..., "40": ...}} is kept with the template, the events named for each aspect - the palette shows a template with arms as a semaphore of its arms, with 1 arm / 2 arms and Sz picking the template of the same tile that has them - the signals of SRK take a semaphore whose aspects cover what the signal needs (Sr3 where a speed is reduced, Sz on the main signals), the fewest arms that do it, and say which one does when the placed one hasn't them or has more than it needs - the warning disc before a semaphore is one whose repeats cover stop, the highest speed and 40 km/h when the semaphore shows Sr3; SRK writes no events of the routes, so this only chooses and checks the disc - the linked signal (parameter 7) is read for the role link as well as text - signal_headers.py keeps the keys written by hand in a description (arms, aspects, repeats, the description and the parameters from 6 on) when it writes the guessed ones again - signaltemplates of the self test lists what the templates say and the heads made of them * feat(editor): the shaped discs swapped and set by hand, the warning discs checked by what they repeat The shaped shunting and stop discs (mk1, tzm, z1) are known to the signalling, but it doesn't place them by itself: - a shaped disc chosen in the palette for the shunting or the stop signals is placed by hand only; the signalling of a station takes the light template of the kind there, and says so when there is none - the template of a shunting or a stop signal standing can be swapped for a light or a shaped one of another mount as well (dwarf and mast, not gantry) - a signal whose description lists its aspects shows a button for each under its card: it sets the signal to that aspect in the editor, by the animations, the lights and the submodels its event sets off, the time standing still; nothing of it is saved. TAnimContainer::Finish takes an animation to its end at once, giving the submodel its angles, multi_event::branches tells the events set off when the condition isn't met From the review of the descriptions: - a shaped warning disc standing before a semaphore described is checked by the events it repeats: stop, the highest speed and 40 km/h of a second arm told apart; one which doesn't is offered the disc which does, and Fit swaps it - the disc offered is of the mount of the disc chosen, taken from the template even when it isn't described - 1 arm / 2 arms / Sz of the palette pick the template leaning as the chosen one and most like it by its name - a semaphore described with its arms but not its aspects has Sr1, Sr2 and with a second arm Sr3 - Fit leaves a semaphore having what it needs with its arms, for the events written by hand to the aspects of a second one; the messages of the fitting speak of what the signals need, not of their lights - signal_headers.py warns of a signal map written as a block, whose keys it can't keep * fix(editor): an aspect shown by hand doesn't name a vehicle that may be gone The Show button runs the events of the aspect outside the queue. run() writes the vehicle that set the event off last into the log, and nothing clears that pointer, so a train deleted since would have been read after it was freed. The queue sets the activator anew each time, so it is cleared before the run. * fix(editor): a disc not described is only offered the one that tells, a light stand-in of the mount of the shaped one - A shaped warning disc whose template doesn't say what it repeats may tell all its semaphore shows as well. It is no longer marked as not fitting: the disc described is offered as a hint, and Fit leaves it be. A disc whose template isn't among the scanned, its mount not known, is offered nothing rather than discs of any mount. - A shaped disc chosen for shunting or stop is stood in for by a light template of its own mount first, a dwarf for a dwarf. - The tooltip of the aspect buttons says the trains read the signal as its events set it last, in a run started from the editor too. - The Polish texts of the fitting speak of signals, not semaphores, since it takes the discs too. * refactor: the Sonar remarks on the switch blades taken care of - the big functions of the rails split into helpers with one job each: the carving, the laying and the planning of the rails, their crossings, the blades, the lofted spans of a segment, the profile of a rail measured piece by piece, the joining of the switches - the floating-point loop counters are while loops doing the same additions, so the samples come out where they did - C arrays are std::array, the two sides of the paths path_sides; the ends of a cut are two parts of one struct, ending and starting - the rail laid by a course of its own, not eleven parameters - the globals kept in functions, the nested ternaries taken apart, one declaration per statement, explicit captures, ranges algorithms, std::format, std::numbers, emplace_back, structured bindings - the region finds the sections around a point into a list the caller gives, so the search for the rails around a track shares no list with another thread - check_rails and create_track_rail_profile are const, the pool of the reused chunks can't be copied The geometry of every chunk of lk357 and td_fog, with the frogs on and off, comes out the same as before. * refactor: the Sonar remarks on the 3D sleepers taken care of - the big functions of the sleepers split into helpers with one job each: the clusters and the lines of timbers, the gaps under the rails, the models and their parts, the check of the layout, the drawing of the timbers in instanced batches - the tracks near a track found into a list of their own, the region searched into a list the caller keeps, not the one the region shares with the main thread; the callbacks are templates, not std::function - the layout of a cluster takes a span of its tracks - the globals kept in functions, the parts of a beam int constants, beam_overhang no longer hidden by a field of the same name - scoped_lock, jthread, contains, ranges algorithms, std::format, emplace_back, structured bindings, explicit captures, upper-case literal suffixes, one declaration per statement - the uniform buffer takes a span of bytes * fix(editor): the editor core builds with GCC again - kCrossoverStraights is constexpr, so the connection curve can take it into a constant expression; GCC refused a double that was only const there. - the track_hover alias inside editor_mode dropped: declared after hovered_track had already used the name, it changed what the name meant in the class (-Wchanges-meaning); the definitions name the shared track_hover. - <cstring> included where the rail self-test uses std::memcpy, which MSVC reached through other headers. * refactor: the second round of Sonar remarks on the switch blades - the carve of a throwable part takes the cut before it only where there is one, as only that cut makes it throwable - the splitting of a grooved profile by the floor of its groove moved out of the rail layer into a class of its own, which is given the profile, the size of the rail, the texture of the plates and the side - the rail drawing is made by a const function - the triangles of an ear-clipped outline go in as the arrays they are, the search for a corner within an ear is an any_of, the loop pruning thin corners keeps the count it started with, as it stops at the first - the bytes of the blocks of a texture are taken off the file through its buffer, with no cast of their storage - the log of a carved part takes the tracks around it as a span - the joint length of a switch, a constant, isn't captured, and the directions at the ends of a crossroads are tested in one condition each * refactor: the Sonar remarks on the tutorial - the window of the tutorial in smaller pieces: the steps reached, the lesson followed and its clip, the clip or the sketch of a lesson, its keys and steps, the button under it and the buttons of the pages; the lessons are a table of their own, the button of each kind of lesson picked from a switch - a clip whose delays add up to nothing shows no frame instead of dividing by them - the frames of a clip are decoded by a function of their own, on a thread kept with them and joined once it's done, or as the editor closes, instead of a detached one - the sleepers of the signal sketch counted by a whole number, the texts of the sketches made by std::format, their points kept in std::array, the whole numbers turned into floats where it's meant * fix: the bugs and vulnerabilities Sonar found in the editor core - the loops stepping along a track, a curve or the view count their steps by a whole number and take the station as so many steps from the first, instead of adding a fraction up, which drifts - the self-test of the guard rails keeps the plan of the rails of the track against while it goes through them: the range of the loop was in a plan made for it and gone before the loop began - the generators of the self-tests and of a unit test are seeded on purpose, so a run can be repeated: marked for Sonar as such - the tool writing the descriptions of the templates takes the names out of its tables only where they stay in the data folder * fix: the loops of the signalling stepping by a whole number the places of the block signals along a line and the marks of the chainage under the plan of a station are counted by a whole number and taken as so many steps from the first, instead of adding a fraction up, which drifts; Sonar took the counters of floats for bugs * refactor: the checks of the signal heads and the signal sheet in smaller pieces the remarks Sonar made on the signal descriptions: the warning about a disc on the mount of a signal is worked out by a function of its own, the fit and the aspects of a head, the swap of a template and its aspects in the sheet of a signal are drawn by members of their own, the walk over the events of a signal is a free function instead of a std::function held by a lambda, and the description of an include is read a part at a time; the names of the kinds are kept in a std::array and looked up by the algorithms of ranges, a name is taken as a std::string_view where it is only compared, and the locals named event, which hid the enumerator, are renamed * style: a space after a comma in the join self-test * style: a space after the question mark in the terrain sketch * style: a space after the question mark in the status of the fitting * refactor: the last Sonar remarks on the small fixes the opening of a scenario catches the exception the scenery throws when it can't be read, not any runtime error; the vehicle moved between trainsets keeps its source by a reference to const; the messages of a track of an unknown type and of a tributary are raw string literals; the parser opens a file by a std::filesystem::path, and the log of a file it can't open still names its folder and its name * refactor: the crossings of a track found without casting its const away the radius of a node can be read off a const one: radius_() is const across the nodes, the ones of the tracks and the models marked override, and a const radius() gives the radius worked out already, or works it out anew without keeping it; the helpers finding the crossings of a track only read it and take it const, its own run of rails typed apart from the ones of the tracks it crosses, which the crossings found name; the triangles of a filled outline are pushed as named corners * refactor: the paths around a track sampled without casting its const away the sampling of the paths and the clusters of tracks laid together only read the tracks, so they take and keep them const: the path sampled points at a const track, the tracks near one are found from a const one by its const radius, and a cluster holds const tracks; the shared zones of the timbers no longer cast the const of their track away * fix(editor): the Sonar blocker remarks on the stack, no side effects in the operands of && and ||, no local named final (S912, S1669) Counting the leftover signals, the pieces of a station walk, the places with nothing beside a run and the joints and fouling points logged by the self-tests no longer counts inside a condition; the last span of a straight is named tail. The counts and what they log are the same. * revert(vehicle): an axle on a switch follows the switch as it is set, as before the stack The axle kept to the path it came on, so a switch thrown under a moving train no longer sent the rest of it onto the other branch, and coming from the frog end it trailed shaped blades only where the wheels reached them. That changed the running of every switch in every scenery, and the AI still scans its route by the switch as set. TrkFoll is as on master again, and the trailing point of the blades it used is gone. * revert(track): a path is told a straight by its first control vector alone again, as the sceneries are made for A plain track was drawn bent where its second control vector was off the chord though the first lay along it, and a path with a radius given was never straightened. Tracks of existing sceneries drawn straight before would have been drawn bent, with their length, cant and the models along them. TTrack::straightened is the rule of master, for plain tracks and the paths of switches. The editor keeps a bend dragged with the second control vector, or set by joining the tangents, by moving the first one 2.5 cm off the chord to the side of the bend, past the tolerance, so the track is drawn, saved and read back bent, by older builds too; the second one dragged back along the chord takes the first one back onto it. * feat(track): the switches joined directly to other switches at load told in the log A switch right after another one is joined to it as the sceneries load, where its end was left open before and vehicles came off the track there. Each switch joined so is logged with its place and the number of ends, and the whole number once, so a scenery can be checked for places that run differently now. * fix(editor): a bend kept by lengthening the first control vector, not turning it keep_bent moved the first control vector 2.5 cm sideways, which turned the start tangent: a kink of 0.29 deg on a 15 m track, flagged by the joints check, and against the fixed direction at a switch or a locked track. Now the vector keeps its direction and gets 2.5 cm longer than a third of the chord, which the simulator no longer takes for a straight. It is also applied after an end is moved or snapped, since a new chord or a snap onto a neighbour could bring the vector back within the tolerance. With the second vector back on the chord, the first goes back to a third of it. * fix(track): each switch joined directly to another one logged with both names join_switches counted ends, while one join links both switches, and only the first switch of a pair was named. It now returns the switches joined to, and the log names both of each joint and gives the number of joints. * fix(editor): a path drawn bent is kept bent through every edit, one drawn straight is left as it is The first control vector is made longer past the 2 cm tolerance only where the path was drawn bent before the edit, or where the edit itself sets the second vector: the end of the path moved, its first vector, its second one, a neighbour followed or its grade taken, the controls aligned at a joint, an end snapped. A path drawn straight keeps being straight when its ends move, and the paths of a track that the edit doesn't bend aren't changed. Moving the second vector back along the chord takes the first one back to a third of the chord where it was made longer here. * fix(app): a scenery that can't be opened takes the game back to the launcher whatever the file system throws Catches std::runtime_error again, as master did: invalid_scenery_exception is one of them, and so is what the file system throws while the scenery is opened. * fix(track): the beams worked out in the background don't read the ends a switch is set to The ballast a switch trackbed takes is asked of the tracks joined to its main path, as the trackbed is made at the load, not of the ends the switch is set to now, which change as it's thrown while the thread runs. What the thread reads with no lock against the main thread is written down where it runs, with the two things driving can change: a switch thrown and a turntable turned. * perf(render): the cut faces of a track drawn with nothing put on the heap, a track with none passed over at once * chore(track): the switch drawing the cut faces in the unrolled material read only in the builds with the self-tests * docs(track): the blades flag said to be switched on, and what frogs in eu07.ini changes of it * fix(editor): a response over 64 MB is refused, curl kept to http and https, the address read as UTF-8 The body of a map or of a service the user typed is read into memory up to 64 MB and fails above that, with WinHTTP and with curl. curl follows at most 10 redirects and only to http or https. WinHTTP gets the address widened from UTF-8, so a pasted one with letters past ASCII isn't turned into garbage. * fix(editor): only the orthophoto an older editor kept is deleted from the settings folder, not all its cache The geoportal folder of the old cache is removed, and the cache folder itself only where nothing else is left in it. * fix(editor): the square metre of the outlined area written as its UTF-8 bytes, shown right where /utf-8 doesn't reach * docs(track): why the velocity read for a switch is put back after its segments are made * fix(track): the blade tips and the open ends of a track take the dark of the rail, not the colour of a worn tread No wheel runs over them, so their cut faces aren't drawn as worn: the beige the matte material gives a worn face is left to the cut faces of the frogs. * fix(editor): a neighbour followed or given its grade is bent only where its second vector really changed follow() and follow_grade() write the second vector of a track joined at its end back as it was when the joint didn't turn or keep its grade; a track the simulator draws straight with that vector off the chord was made bent then, though the edit never touched it. Its first vector is lengthened now only where the path was drawn bent or the second vector took another direction or grade. * fix(track): the open ends of a track laid with cuts take the dark of the rail too The rails a frog or a crossing cuts are laid piece by piece; the caps of their pieces at the open ends of the track were drawn worn with the cuts of the frogs. They aren't worn now, as the open ends of the other tracks. * fix(editor): a neighbour drawn straight is bent only where the edit took its second vector off the chord follow_grade() sets the height of the second vector anew on every graded joint, a fraction of a millimetre off the height the scenery has, so a change of the vector bent a track whose second vector stood off the chord sideways already, though the simulator draws it straight. follow() and follow_grade() keep a path drawn straight bent now only where its second vector lay along the chord before the edit and stands off it after; a path drawn bent is kept bent as before. How far the vector stands off the chord is measured in one place, keep_bent() uses it too. * docs(editor): the comment of keep_bent above keep_bent again, not above the measure of the chord * Editor: signal reads kept by the signal, level crossing discs, signals out of the gauge, indicators, the signalling tools split (#307) * fix(editor): the read of a signal stays by it as its track is split, on a switch and when it is moved, and a level crossing disc is placed The trains find a signal by its read, a passive event in a list of the track, and measure the way to the cell it reads along three tracks further at most. The editor let the read drift away from the signal, or put it where trains of another path read it. - A track split in two: a read the trains scan for (a passive event) goes to the piece by the point it reads, whatever its list; before, those of the runs towards the end stayed on the first piece. Five splits left the reads of A, B, C and J on the first piece while the signals stood on the sixth, out of the reach of the trains. The reads of signals placed since the scenery was opened, not bound to an event yet, go to the piece by their signal the same way. - A signal moved off its track jumped back to that track's end once the track was changed: the track had taken it up as its object and measured it again along itself. A moved signal is let go by the track it stood by, and an object of a single point moved off the side of its track no longer follows it. - A switch reads its events to the trains of both its paths. A signal past the frog of a path, where the axes are a gauge apart, is passed by the trains of that path only, so its read goes to the track joined to the far end of the path, in the list of the trains running from the switch onto it or the other way. Before the frog it stays on the switch. Moving the signal across the frog takes the read between the two. - A signal by a switch on the side of its other path stood on that path, in the way of its trains (0.45 m from its axis); it is refused there, placed or moved, with the reason. - The kind crossing of the descriptions (tsosp, tsospn) is known: the level crossing disc is listed in the palette and placed with its read. Checked in the editor on a hidden desktop: five splits of a track with bound and fresh reads, a signal moved to another track and the old one raised, signals placed before and past the frog of a switch on both paths, turned and moved across the frog, saved and opened again with the reads bound, the tracks raised, shifted and bent with the signals following. Unit tests pass. * fix(editor): a split keeps reads far off the path and bound objects up to 30 m by their pieces A read the trains scan for moves to the piece by the point it reads only from event1 and event2, only when it isn't ignored and only when that point is within 50 m of one of the pieces; a read at the station building stays in its list. An object bound by hand keeps its binding as its path moves up to 30 m from it, an adopted one up to 12 m as before. * feat(editor): the tracks that read a signal are drawn and can be picked, flipped or dropped The selected signal shows each read of its _sem_info as a thick band over the reading track, arrows in the way the read is scanned, a line from the foot of the signal and a plate with the list and the track; the hovered one shows them thinner and placing or moving a signal shows where it will be read. The panel lists the reads: each can be turned the other way or removed, "Pick the path" takes a click on a track (with Shift one read more or less) and "By the path it stands by" puts back the read the signal gets when it is placed. Each change is one step of the undo. The self-test gets signalread, signalreadflip, signalreaddrop and signalreaddefault, and the probe lists every read of a signal. * fix(editor): a moved or turned signal keeps the reads picked by hand, and a read set again isn't an undo step Moving a signal, taking it across the track or turning it put back only the read by the track it stands by and dropped the others: those stay on their tracks now, on the other list when the signal is turned. Setting the reads the signal has already says so and adds no step to the undo. Picking a reading track disarms the template, so a click after Esc doesn't place a signal, and the signals are listed again after any change of the history, also once it is full. * feat(editor): a signal is placed out of the gauge of the tracks around it As a signal is placed, moved, taken across or turned, its models are measured against the gauge chosen in the Gauge window along every path near it. One that enters it is taken sideways, away from the axis of the track whose gauge it enters, as deep as it went in and 3 cm more, in the same step of the undo; between two tracks too close for it, it stays where it was put and the status tells which gauge it enters and how deep. A gantry is only measured. The panel of the selected signal tells when it stands in the gauge, with a button to move it out, and the view marks the deepest place. The gauge tool measures any models against the paths around them for it. The self-test places a signal at a given offset and its probe tells the gauge. * fix(editor): a moved signal leaves only the read of the track it stood by, and the gauge is checked on its level The reads a moved signal keeps were all but the first one listed, which is the first track of the scenery having it, not the one the signal stood by: a read picked by hand could go and the track it left could keep it. It is the read of the track it stood by that goes with it now, and turned, eventall1 and eventall2 swap as well. A track more than 2 m above or below the foot doesn't push the signal aside, the status tells the real distance it went, the gauge is measured again when the signal follows a dragged track, and the marker in the view shows only what is up to date. * feat(editor): indicators put on a signal from the panel, they move and go with it The indicators of scenery/pkp/wskazniki described as "category: indicator" are offered under the selected signal, grouped by their sign. One is put in as an include named after the signal, on the srk layer: - a lit one (place: head) under the lowest lamp of the signal, 0.73 m below it and 5 cm ahead of the mast, each next one 0.45 m lower; a dwarf signal is refused, it has no mast for one; - a plate (place: foot) at the foot of the signal, its model has its place by the mast built in. The panel lists the indicators standing by the signal with a Remove button. They are found as the includes whose first parameter is the signal's name, within 1 m of it in plan. When the signal is flipped, turned or moved, they keep their place in its frame, in the same undo step; deleting the signal deletes them too. If the signal and the indicator both define an event, the status says so, since the scenery keeps only one of them. The self-test gets signalindicator and signalindicatordrop, and its signalprobe gives each indicator's height and the height of the lowest lamp. * feat(tools): indicator descriptions and the indicators taken out of the signal templates indicator_headers.py writes //$e descriptions into the LED indicators of scenery/pkp/wskazniki (W19, W20, W21, W24, W26) with the events each shows. It also makes the indicators that were so far only built into the signal templates: - W1 of the warning discs, new, old and with the light strip; - W1 and W18 (new and old) of the block signals; - the I, II and III plates of the repeaters. The plates fixed flat to the mast are moved 4 cm ahead. Their back is 5 cm from the mast's axis, while the mast is 6.1 cm thick and its clamp under them 8.3 cm, so the mast went through the plate, in the templates too. * fix(editor): a signal turned or moved by the gizmo is read and kept out of the gauge, its indicators go with it everywhere The gizmo of an include only rewrote the numbers of a signal. Its read stayed on the event it had, even when the signal was turned to the trains of the other direction. Its indicators stayed behind, its height could be dragged off the ground, and the gauge wasn't checked. Now: - the gizmo moves a signal in the plan only, at the height it has; - while it is dragged, its indicators keep their place by it; - once it is let go, the drag is made again as a move of the signal tool, one step of the history: the read goes to the event of the trains it faces on the path it stands by, and it is taken out of the gauge; - dropped away from every track, it goes back where it stood. The indicators of a signal are found in the scenery now, not in the list the signal tool keeps up only while it is open: - deleted from another tab, the signal takes them with it; - a signal renamed in the node properties gives its new name to them in the same step of the history; - in the station and line batches, a renamed signal renames them, and a removed one removes them; - the binding of objects to tracks puts them on the path reading their signal, not on the one nearest to them, and a signal moved by hand lets go of them too. Also: - a signal on a gantry takes no indicator from the list; - an indicator a signal has already isn't put on it twice; - the signals and their indicators are found in one pass over the includes, the indicators by the name of their signal; - a step of the history with tracks is always one of their edit, so they are taken back with the includes. The self-test gets signalgizmo, which turns and moves a signal as the gizmo does. * fix(tools): indicator_headers.py keeps the files it replaces, writes beside the data on request - An indicator it made, found changed, is put into a tar in editor_backup before it's written again. - --sidecar writes the descriptions of the lit indicators into editor/templates, as the other header scripts do, the files of the game left alone. - The indicators it makes are copies: the signal templates keep their own, and the docstring and the files say so. * fix(editor): a signal moved by the gizmo by another track is read by it, the templates known without the signal tool - At the end of a gizmo move the nearest track takes the signal when it is nearer than its own by more than 0.5 m; a track it was dropped onto, within 1.2 m of its axis, doesn't, so a signal only turned between two tracks or dropped onto one in a switch keeps its own. - The signal templates and indicators are looked for when a signal is renamed or its gizmo shown, so its indicators follow without the signal tool opened first. - A drop refused puts the gizmo and the node properties back where the signal stands. - The indicators follow only once the gizmo made its step, and the ones not changed are left alone: grabbed and let go it changes nothing. * fix(editor): a signal dropped by the gizmo onto a track keeps its own, the gizmo doesn't wait for the template scan - When the nearest path to the drop is within 1.2 m of its axis, the signal keeps its own track, instead of only that path being left out: dropped onto a middle track it no longer goes to the track beyond it. - The gizmo starts the signal template scan without waiting for it, so a rescan with a signal selected doesn't stop the editor; renaming a signal still waits. * feat(editor): the signalling split into Signals, Station, Station signals and Line block The one Signalling tool held the signals placed by hand, the whole wizard of a station and its checks; each is now a tool of its own in the toolbar: - Signals (I): the palette, a signal placed by a track, dragged along it, selected; a click on a switch no longer opens a station. - Station: LMB on a switch lays the station out; its name, code, line, km, speed and braking distance, the numbers of the switches, the track circuits, the number of the selected track, the list of the switches. - Station signals: the signals of the whole station placed at once, the template of each of their kinds (main, shunt) chosen in a table, and below what the signalling lacks: the repairs, the SHP resonators, the track lengths, the signal heads. - Line block: the block of each line, the block boundaries drawn by hand, the line signals, the templates of the block signals and warning discs. The station tools share the open station and its schematic; Station signals and Line block show what the Station tool set for it, the line and the km in red where the line block needs them. The template table replaces the palette in the station tools, so choosing a template there no longer arms placing. Two icons drawn for the new tools, in editor_icons.py too; the png is drawn by the same shapes, Pillow wasn't at hand. The tracktab self-test takes a tool by its name, and srkopen shows the Station tool. * feat(editor): a signal shows its distance from the track axis and to the switch ahead, and goes to 50, 100 m... from it - editor/editorTrackTrace: the track followed the way a train runs, shared by the W17 markers and the signals. The fouling point of a switch (where the axes of its tracks are 3.5 m apart) moved here from the lineside tool, and danger_ahead finds where a train first comes to a switch: the start of one it runs onto from its start, or the fouling point of one it runs onto from behind, which may lie behind the point (a signal in the fouling zone). - The card of the selected signal: its distance from the axis of its track, and along it to the start or the fouling point of the switch ahead, in red when it stands inside the fouling zone. The overlay draws the same as a dimension line beside the track on the side of the signal, with the distance at the place. - Placed, dragged along or moved with the gizmo, a signal goes to a round distance to the switch ahead (50 m steps) when within 2.5 m of one; Alt keeps it where it is. The drag of a new one is measured from where it was pressed. - The fixes of the review of the split: the click label of the station tools in their own branch and a plain select in Signals, the card of a signal picked from the check lists shown in Station signals, and the help texts naming the Templates table and the Signals tool. - Self-tests: signalprobe logs the distance from the axis and to the switch ahead, signal snap=1 snaps as placing does. * feat(editor): the fouling point widened in the curves under 250 m, as the standard of the gauge says Standardy techniczne PKP PLK, tom II (from 2025-07-17), 6.5-6.6: the W17 marker stands where the axes of the tracks are nominally 3.50 m apart; where one of the tracks lies there in a curve under 250 m that spacing grows by the widening of the gauge from its radius (annex 1, table 1), the widenings of both summed when both lie in curves. - editor/editorFouling: the fouling point found along the axes of the main track and the branch, standing on its own: at each point of the branch the spacing wanted is the nominal one plus, for each track, the widening on the side of the other track from its radius there (taken over 5 m each way): 50000/R - 185 mm towards the centre of the curve, 60000/R - 225 mm away from it, none from 250 m up. - gauge::curve_widening gives table 1 of the gauge the editor checks already. - The W17 tool and the distance of a signal to the switch ahead both use it; the card of a signal shows how far apart the axes are at the fouling point, the help of the W17 tool says where the figures come from. - Unit tests: a straight branch at 1:9, a branch in a curve of 300 m (no widening) and of 200 m (outer widening), both tracks in curves (both widenings summed) and a straight branch off a curving track. * feat(editor): the cant leans the cars into the fouling point, and the fixes of the review of the metre - The fouling point takes the cant in, as Ie-1 wants it placed "with the gauge, the cant and the widening in the curves": the cars of a track on a cant lean towards the inside of its curve by D Hi / 1500 (bD of table 1 of the standard of the gauge), so when the other track lies on that side the spacing wanted grows by it, taken at 3.05 m over the rail top, the top of the widest part of GPL-1. The cant of each point comes from the roll of its path as the gauge tool takes it. At any radius, as the table has it; the track leaning away adds nothing. - Below 150 m, where table 1 ends, the widening from the radius is that of 150 m rather than the formula run on. - A switch run onto from behind has its fouling point looked for once its own path is walked too, so one lying on that path is found rather than skipped for a farther switch. - A point behind a signal lies on the track of the farther end of its segment, so a signal snapped back over a joint lands at the round distance rather than at the joint. - Alt keeping a signal off the round distances reads the key from ImGui, which Global.altState misses while ImGui holds the keyboard. The gizmo doesn't snap a signal:a1d10bb0says 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, whichd70f189cmissed, and a cant on the straight counts too. - The leaning is taken 3.25 m over the rail top, the top of the widest part of the cars, rather than 3.05 m of GPL-1. - Unit tests: a cant against the curve, a cant on the straight, and the leaning away still adding nothing. * fix(editor): the station tools tell by the mouse what a button came to, and the fields of a station read as empty What a button of the Station, Station signals and Line block tools came to was written at the foot of the panel, under the lists, scrolled away: a click which refused for want of the code of the station looked as if nothing happened. It's told now by the mouse which clicked, a refusal in red as the other tools do, and in the status bar. The fields of a station still empty show their examples as such, "e.g. BPd", not as values typed in; the Station tool says above its steps that the code is to be typed first, Station signals that the code and the track circuits are wanted, the code marked there as needed. The check of a warning disc and of a block section went by the braking distance of the station, while Set the line signals places them by the one of their line: on lk357 a disc placed 700 m before Z, the line run at 100 km/h, was marked as standing nearer than the 1000 m of the station. A signal of a line out is checked by the braking distance of its line now. * feat(editor): the joints of the track circuits put, moved and taken away by hand, kept by the station The Station tool gets Edit the joints by hand: LMB on a plain track of the station puts a joint there, LMB on a joint takes it, then on a track moves it, on it again takes it away. The circuits are set again at once, one step of undo each. The joints so changed are kept in the //$s record of the station (joints +x/y/z for one put, -x/y/z for a planned one taken away), so Set the track circuits keeps them; As planned forgets them. The undo step carries the hand joints of the station with the tracks. srkjoint drives it in the self-tests. * feat(editor): the indicators under the lights reordered, a signal set from the axis and raised, standing on the ground by default The indicators under the lights of the selected signal get arrows up and down: one changes places with the indicator above or below it, a plate at the foot keeps its own. One step of undo each. The distance of the selected signal from the axis of its track is typed in the panel, it moves across as far along the track as it stands, the gauge pushing it out again where it comes too near. Its height is set the same way, raised over where it stands by default, over the rail heads on a gantry. A signal is put on the ground by default, the zero of its model 0.38 m under the rail heads: the ground lies 0.35 m under them as Ie-102 draws it (Lx), the foot of the mast stands on the foundation 3 cm over it in the models of pctga, and the sceneries made by hand (Wrzosy, Baltyk) stand their signals 0.20 m under the rail foot so. It stood on the rail heads. signalindicatorswap and signalacross drive it in the self-tests. * fix(editor): the hand joints of a station without a record, of its ends and of another station; a dragged signal keeps its place across and its height - Edit the joints by hand on a station not described yet read the record of index -1: the hand joints are shown only for a station with one. - The joint between the station and a line out of it can't be taken: taken away, the circuit of the switch ran on over the tracks of the line. - A joint held is let go when another station opens, a move by less than half a metre lets it go, and a change no step of the history takes is undone, so the undo knows every change of the joints. - A signal dragged or snapped along its track keeps its distance from the axis and its height over the default, set by hand or standing so before. * fix(editor): a dragged signal carries what it had by its own track; As planned forgets the hand joints that change nothing The distance from the axis and the height of a dragged signal were taken against the track it was dropped onto: dropped on the next piece of its line, on a grade or by a parallel track it came out too far, in the gauge or off the ground. They are taken as it stood by its own track at the start of the drag. As planned clears the hand joints even where the circuits come out the same. * fix(editor): a signal stands as high over the rail heads as its include gives, lowered only where its bottom would hang over the ground The default height of a signal was 0.38 m under the rail heads for every model. It is now read from the description of its include, `//$e signal: {..., height: <m>, depth: <m>}`: height is where the zero of the model stands over the rail heads (by Ie-117 § 15 the top of the foundation of a mast 0.10 m under them, of a dwarf 0.20 m), depth how far the model reaches under its zero. With a depth, a signal whose bottom would hang over the ground, down an embankment, goes down onto it, by at most 3 m (more is taken for a bridge). Without a height the zero stands at the rail heads. "Raised" in the panel, a signal moved across or dragged, all count from that default height. * fix(editor): a signal flipped, given another template or its variant for the other side stays as raised as it was The default height now depends on the template and on the ground under the signal, so keeping the height as it was no longer keeps the raise. Flipped to the other side of the track, the signal is raised over the default there as it was over the default on its own side. Given another template (Swap), or the variant of its template for the other side when moved or placed, it goes up or down by how much the default height of the new template differs from the old one. * fix(editor): As planned forgetting hand joints that change nothing is a step of undo of its own With nothing in the circuits to change no step of the history took the forgotten joints, so they went with no undo for it: Ctrl+Z took back the step before. The anchor of the station as it is now carries them in a step of their own. The signalmove selftest gets its carry indented with the block it is in. * feat(editor): an indicator under the lights goes in its place by Ie-117, from the top W21, W24, W20, W19, W26 Put on a signal, an indicator under its lights was put below the ones there. It now goes in its place by Ie-117 section 12.1 among them, under the last one it doesn't go above, the others (W18 and the rest) below these; the ones under it move a place down, in the same step of undo. * fix(editor): the signal card and the move of a signal keep no pointer across a refresh of the signals - The card of the selected signal went on after "To the other side" or "Turn around" with found pointing into the list of the signals standing, which their refresh had just replaced: the indicators and the gauge of the card read freed memory. It now ends that frame there. - signal_move_to read the mount of the template after the refresh, which may scan the templates again; it is taken before it. signal_place takes a copy of the template given for the same reason. - The fouling test counts its metres with an int, and the search of the middle point of the radius is a while loop (no floating loop counter). * fix(editor): the dimension line to the danger point counts its metres with an int (Sonar S2193) The line drawn by the track from a signal to the switch or fouling point ahead stepped a double by 1 m. It now counts the whole metres with an int from the same first one: the points are the same, since adding 1 to a whole double and adding a whole int to it give the same values. --------- Co-authored-by: maj00r <maj00r@host> * feat(editor): ride the camera along the tracks, and a minimap with stations by their W4 (#317) * feat(editor): the camera rides along the tracks, over the joints and switches and over to the tracks alongside Y puts the camera onto the track under the cursor (or the nearest one), looking along it 3 m over the rails. W/S drive it ahead and back the way the camera looks, Shift and Ctrl faster (20, 60, 250 m/s); A/D take it over to the track alongside, a click to any track; E/Q and the wheel raise and lower it; the mouse looks around as when flying. At a switch entered from its blades it goes straight on, Z picks the turnout for the camera alone: no switch is thrown, no track learns of the ride. The bar over the view shows the track, the km, the speed, the height and the switch ahead. Y or Esc ends it. Self-test commands ride, ridewalk, ridejump, rideahead, rideprobe and rideleave. * feat(editor): a minimap of the tracks with the camera on them, and the stations found by the names of their W4 View / Minimap and stations (W4), Ctrl+M: a window with the rail tracks seen from above, the camera as a triangle the way it looks, the track ridden along in orange and the stops of passenger trains as dots with the names of their stations. It follows the camera, or is dragged and zoomed apart from it; a click takes the camera there, riding along the track onto the track there. Above it the stations the PassengerStopPoint memory cells and events name, searched by a part of the name with or without the polish letters; a click (or Enter for the first found) flies the camera over to the stop looking along the track, riding it rides on from there, each click to the next W4 of the station. Self-test commands minimap, stations, station and minimapclick. * fix(editor): the ride and the minimap after the review, with fewer words on the screen - Ctrl+S, Ctrl+Z and the other shortcuts reach the editor while riding; Esc closes an open popup first - no key stays held when a window takes the keyboard, the place is kept within a path that got shorter, a release of the mouse goes where its press went - the minimap keeps under the vertex limit of a draw list, Enter in the search goes round the stops of the station, the marked station stays marked - the bar of the ride is one line: the track, km, speed and height; the switch ahead under it, the keys only while standing - the minimap in the Map menu, opening over the view, with short texts; the context menu of a track rides along it * feat(editor): the ride drives with the right button held, as the camera flies, and the editor works on along it - W/S, A/D and Q/E drive the ride only with the right button held; without it they're the editor's keys again (Q/W/E the gizmo) - the left button and Esc go to the tools while riding: tracks and objects are laid and selected from where the ride took the camera; Y leaves, a flight of the camera to a framing leaves too - after the review: the help names Ctrl+W/Ctrl+Down as the much faster drive, the stops of the minimap stay within the vertex limit, the search field lets the keys go after Enter * fix(editor): the tools keep their wheel and the menu of a track its click while riding, a pan or the view from above ends the ride --------- Co-authored-by: maj00r <maj00r@host> * feat(editor): signals placed by the editor get a name plate drawn by python (#316) * feat: Elf emergency brake position in the master controller (eu07/maszyna#413) The Elf's master controller (EIMCtrlType 2) gets an optional emergency brake position below its position 0, turned on by the new .fiz key EIMCtrlMainEmergency=Yes in Cntrl (default No, no change without it). With it the old positions move up by one (MCPN 5, neutral at 4): the emergency position brakes fully at once and vents the brake pipe, like the alarm chain or the Impuls's EIMCtrlEmergency. The loader raises a too small MCPN to 5 and logs it. The Elf code with hard-coded positions (CheckEIMIC, the MED full braking, the AI) takes the shift into account. SVN data to change afterwards (dynamic/pkp/elf_v1, needs this exe): - every .fiz with EIMCtrlType=2: EIMCtrlMainEmergency=Yes, MCPN=5, DirChangeMaxPos=4 where present; - the cab .mmd mainctrl entries: offset one notch lower (-0.06 -> -0.09), sounds shifted one index up, new sound0 with 26284_elf_nastawnik_nagle_*.wav. Issue: (eu07/maszyna#413) * fix: Elf emergency brake position vents the pipe only from the driven vehicle, coupled units agree on the controller position The emergency position of the master controller vented the brake pipe from every vehicle whose controller stood there, and "MainCtrl" reached the coupled vehicles raw, so an Elf with EIMCtrlMainEmergency and one without it disagreed by one notch (the full braking of one was the emergency brake of the other, neutral of one a power position of the other). The pipe is now vented only from the vehicle driven from (IsCabMaster()), and the position goes to the coupled vehicles in the positions without the key (MainCtrlPosForCoupled(), the emergency one as the full braking), each adding its own shift on receiving it (MainCtrlPosFromCoupled()). The loader's fix-up for the old MCPN=4 raises DirChangeMaxPos by the same shift, so the reverser keeps working at the new neutral. * feat(editor): the signals the editor places get a plate with their name, drawn by python A signal placed with the signal tool used to get the plate texture of textures/tabl named like it, or none at all. Now, unless a texture is picked, its plate is made by python/local/signal_plate.py: "make:signal_plate?name=<name>", a light plate with a dark edge, four screws and the name in black, the way the plates of textures/tabl look. Renaming the signal in its properties renames a drawn plate with it; a picked texture stays. The templates put the plate after a folder, "tabl/(p6)", so material_data::assign() takes the folder off a skin which names a texture made by a script. * fix(editor): a drawn signal plate keeps following a cleared name, and isn't made for a name it can't carry Clearing the name of a signal in its properties made its plate the drawn plate of no name, which then never followed the name again. A drawn plate now follows any rename to a name, and keeps the last one while the name is cleared. A name with '|', '&' or '?', or one longer than 64 characters, gets no plate (0_nothing) instead of a broken one: '|' splits the skin, '&' and '?' the query of the script, and a very long name made a path too long for the file system when the skin was looked for on the disk. * fix(editor): a signal plate keeps its last name through a name it can't carry, and a plate named by hand stays Renaming a signal to a name its plate can't carry turned the drawn plate into 0_nothing, and it stopped following the name for good. Such a name now leaves the plate with the last usable one, like a cleared name does, and the plate follows again once a usable name is typed. A drawn plate whose name was given by hand, different from the name of the signal, is no longer replaced on a rename: only the drawn plate of the signal's own name follows it. * feat(editor): the drawn signal plates come in three looks, plain, toned and aged The plate drawn by python/local/signal_plate.py looked too clean. It now takes a look in its query, "make:signal_plate?look=toned&name=Tm12": plain is the bright plate it was, toned a greyish field with a little grain and dust towards the bottom and the sides, a thinner edge, smaller screws and graphite letters, aged a darker, grainier and dustier one. Toned is drawn when no look is given. The signal tool picks the look under the plate, kept in the settings of the editor. A rename of the signal in its properties keeps the look of its plate. * perf(editor): the grain and the dust of a drawn signal plate are made on whole images The toned and aged plates shaded their field a pixel at a time in python, about 34 ms a plate with the interpreter held, so a station of a hundred signals in view kept the python queue, and the screens of the cabs, waiting for seconds. The dust is now made once per look, and the grain from random bytes of the name, both put on the field with ImageChops: about 2 ms a plate. The mean colour of the plates stays the same; only the grain falls differently. * fix(editor): the station signalling draws the plates of its signals as their schematic names them The plates the station signalling places and renames say what its schematic shows (Tm3, F1, ToA, a block signal without the stem), and a template swapped in for a signal without a plate draws that text too rather than the small letters of the name. A signal left for removal gets a plate of no text again, not one saying "_old". No plate, 0_nothing, or the texture named like the signal, what the editor gave before the plates were drawn, become the drawn plate when the signal is renamed, in the properties panel as by the station signalling, in the look set in the editor. * fix(editor): a plate of a scenery named like the end of the name of its signal stays through a rename in the properties A texture pzs_a was given by its scenery as a, its real plate: a rename in the properties panel keeps it. Only the station signalling, which looked its plates up that way, takes such a one for its own. * feat(editor): the drawn signal plates are 256 pixels across, sharp up close The edge, the screws and the blur are drawn bigger by as much as the plate is, and the grain is as coarse as before, so the three looks stay as they were. The smallest letters tried grow with the plate too. * feat(editor): a drawn signal plate takes a speed index and the m of shunting signals, typed in the signal tool signal_plate.py draws the speed index after the name, one digit up at its right or two as a fraction across the height of the letters (index=4, index=12 for 1/2), and with m=1 an "m" on a strip of its own under the name, as Ie-1 marks a semaphore giving shunting signals and as the textures/tabl a-12m plates show it. The signal tool has a field for the index and a box for the m under the look of the plate; the hint of the plate names them (B 1/2 m). The style of a drawn plate, its look with the index and the m, stays with it through a rename, in the properties panel and by the station signalling, which sets neither. The signal selftest takes index= and m=. * fix(editor): the speed index of a plate takes only digits as they are typed The decimal field let in signs and dots, which stayed shown while the index held only the digits, and filled the two places before a second digit could go in. * fix(sonar): the remarks on the drawn signal plates, to pass the quality gate The new code of the plates was 5.2% technical debt against the 5% of the gate. Fixed the small remarks; the big functions stay as they are: - the speed index field and the plate looks are std::arrays, the index is copied without snprintf, the combo of the looks has a function of its own - ranges algorithms, a string_view for signal_plate_drawn, emplace_back - signal_plate.py: dict literals, a cache of fonts not named like FONTS, no unused local, the name and the m drawn by methods of their own; the plates drawn are byte for byte the same as before --------- Co-authored-by: jerrrrycho <jurek.pakula@gmail.com> Co-authored-by: maj00r <maj00r@host> * fix(editor): the tutorial and the hints tell of the kilometrage, and the first lesson takes O either way The kilometrage (X) was in no hint, no shortcut list and no lesson, though the hectometre posts and the block signals are numbered after it. The row of the track tools now reads L T G N U I X B P V J, the turntable with it, and F1 lists I / X / B. The lesson of the signals and the posts says what X does and where the posts take their numbers from, the km of the line or the km typed in their panel for the place clicked, and it opens with the kilometrage tool too. The first lesson asked to switch to the view from above, which a scenery made in the wizard opens in already: O either way does it now. * fix(editor): master's road lifting texts translated, and the panning by the wheel told of in 3D too The merge of master left the status and the label of the lifting of the road points in English: both go through the translations now. Master pans the 3D view by the wheel as well, so the lesson, the hint row and its line say it works in both views. <cstring>, dropped from the road tool before, came back in the merge and is gone again. * fix(editor): the tools of a plain line in sight, the km of a line set once, a lesson of a whole line and of the ride along a track What a layman building a line with signals and posts couldn't find: - The Signals, Kilometrage and Posts tools are in the main row of Tracks, after the tools of laying; the stations, their signals, the line block, the turntable, the trainset and the checks stay behind More. - "Objects" was where the hectometre posts are: the tool is Posts now (Słupki), its hints say the line the posts go along. - The km of a line could be typed in three places that didn't lead to each other. The panel of the posts and the one of a station, where the line has no km set, say the typed km is theirs alone and have Set the km of the line (X), opening the Kilometrage tool; that tool says first that one known point serves the posts, the stations and the block signals. - The hint of the Signals tool says to pick a signal in the list, then click beside a track; with no templates the panel says so in plain words. - A new lesson, A whole line, step by step: the tracks and switches, the km, the station, its signals, the line block, the posts and the drive, with a button to the station tool, and opened with the station tools. - The first lesson shows the ride of the camera along a track (Y, then W S A D and Z) and has it as a step to try. - lang/editor_pl.po: "Restore the terrain" and "Drag an end" were there twice, the second copies are gone. Checked: MSVC build, unit tests 459/459; editor run on a small scenery, screenshots of the toolbar, the new lesson, the first lesson with the ride ticked after Y, the panels of the posts, the kilometrage and the signals. The station panel with no km of the line wasn't seen, the scenery had no station. * fix(editor): the posts open expanded from the trainset, and the Polish of the whole-line lesson reads right B or the Posts button pressed while the trainset tab is shown opens the hectometre posts with their panel expanded. The Tracks area tooltip names the kilometrage and the posts. The station step names the shunting signals, the station button says Narzędzie Stacja, and the ride rows and the lesson list read smoother in Polish. * fix(editor): a bent model is lengthened along the tracks joined to its own, laid along another track after the bending, and set by fewer settings The ends of a bent model have handles in the view: dragged, the model goes on along the tracks joined there, at a switch the way it's dragged to. Its length, a drag of the whole model and a drag of an end all follow the joined tracks; before, they went on straight past the end of the track under the model. The panel of a bent model picks its track: another one picked, the model stays where it stands, a platform turns its edge to the new track and keeps its length. On top stay the track, the length, the offset and the height, bent or repeated, and the platform edge; the reference point, the position along, turned, mirrored, the cant and the gauge widening went under More settings. The buttons of the model's own length and of the whole track are gone: the length field and the handles do it. The links of a model to its tracks are counted anew when its pieces change, undo and redo included. * fix(editor): the bends of straights laid from the end of a curve begin with a straight, not a compound curve In the mode of straights the curve of a plain track's free end no longer goes on into the curve of the first bend as a compound curve. The line comes out of the end's curve by a transition onto a straight, and each bend gets a curve of its own. Only a curve traced in the mode of a curve goes on from the curve of the end, as it already did at a switch. * fix(editor): the bent model keeps its links and its line to what it reaches, and drags without rebuilding at each track - the links of a bent model are matched anew whenever any of its pieces change, not only the first - the line is lengthened by the plan lengths of the joined tracks and built once a round; a drag reuses the line made at its start while it doesn't grow - the tracks of one name are told apart in the track lists, and a deleted track leaves them - the tracks at the ends the copies no longer reach are left out of the line after an edit or a drag * fix(editor): a click on a bent model's handles changes nothing, and the track picked stays picked - the line is trimmed on a drag's release only when the drag changed the model, and an edit that trimming undoes makes no undo step - the track picked for the bending is kept by the track, not its place in the list, when the list is gathered anew * fix(lang): a stray line taken out of editor_pl.po A single "r" between two entries, left by an edit of the switch texts: msgfmt refuses the file with it. * feat(launcher): the range of the aerial photos of a new real scenery given on the map, changed later in the editor (#328) * feat(launcher): the new real scenery gets the range of its aerial photos on the map, changed later in the editor The wizard of a new scenery asked only for the centre; the editor then downloaded the photos around the camera wherever it went, and a scenery had no range of them until one was drawn in the orthophoto settings. The realistic scenery is made in three steps: the name, the place (a click on the map or the place typed, degrees or PUWG 1992), and the range of the aerial photos: a square of 1, 2, 5 or 10 km around the centre, or an area of the user's, its corners clicked on the map. The range is drawn on the map with its size and the number of the tiles, and it's written to the scenery as the download area (//$z), so the editor downloads the photos and the terrain model inside it only. What a beginner gets wrong is told before the scenery is made: the button stays off with the reason under it (no name, the name taken, no centre, the centre outside Poland, an area being drawn or crossing itself), and a warning comes with the centre outside the area, a large area and a centre clicked on the map of the whole country (the map zooms to the place after the first click). In the editor the download area says in plain words what it does, a square around the camera replaces it in one click, and with the camera outside it a note at the bottom of the view says there are no photos there, with the way to the range. * fix(launcher): the range of the photos asked for after the centre, the drawing given up as with Cancel, the square named by its sides The review of the range of the aerial photos found: - with My own area chosen before the centre, the clicks meant for the centre went to the corners of the area: step 3 waits for the centre; - switching to Fictional while drawing dropped the area there was before, and an unfinished one of three corners counted as done: it's given up as with Cancel now, also with Esc; Enter ends it, Backspace takes the last corner back, as in the editor; - the error of a place mistyped stayed after a click on the map; - the largest square was told to be large or not by the rounding: the warning comes from 50 sq km on; - "2 km" read as a radius: the squares say "2 x 2 km", the tooltip how far each edge is; - a place typed with an area of the user's fitted the map to the area, not to the place. In the editor the note of the camera outside the range says the terrain model isn't there either, its button says it opens the settings, it stands above the strip of the profile and the keys of the tools, and it can be closed until the camera is back inside. The squares around the camera want the place of the scenery on the map, and replace an area there is, or start one of 10 x 10 km, only with a yes. * fix(editor): one note of the empty scenery in the middle of the view, the warnings of an area told once it's drawn A new scenery opened in the editor showed two notes of the same over each other in the middle of the view: the panel of the track tools ("The scenery has no tracks yet") and the line of the terrain ("This scenery is still empty"). The line gives way to the panel now. In the wizard the centre outside the area and the crossing edges were told while the area was still being drawn; they're told once it's done. * fix(editor): the note of the camera outside the range of the photos hidden while the camera rides a track Its lines at the bottom of the view are where the camera riding a track writes the next switch and its keys. --------- Co-authored-by: maj00r <maj00r@host> --------- Co-authored-by: maj00r <maj00r@host> Co-authored-by: Hirek193 <polomarket73@gmail.com> Co-authored-by: jerrrrycho <jurek.pakula@gmail.com>
4295 lines
163 KiB
C++
4295 lines
163 KiB
C++
/*
|
|
This Source Code Form is subject to the
|
|
terms of the Mozilla Public License, v.
|
|
2.0. If a copy of the MPL was not
|
|
distributed with this file, You can
|
|
obtain one at
|
|
http://mozilla.org/MPL/2.0/.
|
|
*/
|
|
|
|
#include "stdafx.h"
|
|
#include "world/Road.h"
|
|
|
|
#include "world/RoadOrder.h"
|
|
#include "world/Track.h"
|
|
#include "vehicle/DynObj.h"
|
|
#include "simulation/simulation.h"
|
|
#include "scene/scene.h"
|
|
#include "rendering/renderer.h"
|
|
#include "utilities/Globals.h"
|
|
#include "utilities/Logs.h"
|
|
#include "utilities/parser.h"
|
|
#include "utilities/utilities.h"
|
|
|
|
namespace
|
|
{
|
|
|
|
// dimensions of the markings, in metres
|
|
// NOTE: these give a layout resembling an ordinary polish road, they weren't taken from the regulations
|
|
constexpr double line_width{0.12};
|
|
constexpr double line_spacing{0.12}; // gap between two lines painted side by side
|
|
constexpr double line_lift{0.02}; // the markings are raised over the surface, so the two don't fight for depth
|
|
constexpr double edge_inset{0.15}; // distance between the edge of the surface and the line running along it
|
|
constexpr double dash_period{12.0}; // a third of it is painted, the rest is the gap
|
|
constexpr double dash_step{2.0}; // longest straight piece of a painted line
|
|
// speed and reach of the paths made to turn the vehicles back at a loose end of the road
|
|
constexpr float turn_velocity{10.f};
|
|
constexpr double turn_reach{6.0};
|
|
// length of the paths left of the lanes at the ends of a piece which gains or loses lanes
|
|
constexpr double lane_lead{2.0};
|
|
|
|
glm::dvec3 const up{0.0, 1.0, 0.0};
|
|
|
|
// placement of a cross-section of the road
|
|
struct axis_frame
|
|
{
|
|
glm::dvec3 position;
|
|
glm::dvec3 tangent; // direction of the axis
|
|
glm::dvec3 left; // direction across the road, tilted by the roll
|
|
double roll{0.0};
|
|
};
|
|
|
|
// the axis of a road piece; a cubic bezier curve, the same thing the paths of the tracks are made of
|
|
class road_axis
|
|
{
|
|
|
|
public:
|
|
explicit road_axis(segment_data const &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]};
|
|
m_curved = (control1 != glm::dvec3{0.0}) || (control2 != glm::dvec3{0.0});
|
|
m_points[0] = start;
|
|
m_points[3] = end;
|
|
if (m_curved)
|
|
{
|
|
m_points[1] = start + control1;
|
|
m_points[2] = end + control2;
|
|
}
|
|
else
|
|
{
|
|
// a straight gets its control points in thirds of the length, the way the tracks do it
|
|
m_points[1] = start + (end - start) / 3.0;
|
|
m_points[2] = end - (end - start) / 3.0;
|
|
}
|
|
m_rolls = {glm::radians(static_cast<double>(Path.rolls[0])), glm::radians(static_cast<double>(Path.rolls[1]))};
|
|
m_radius = std::abs(Path.radius);
|
|
// distances along the curve for evenly spaced values of its parameter, to convert the former into the latter
|
|
m_stations.resize(samples + 1);
|
|
m_stations[0] = 0.0;
|
|
auto previous{m_points[0]};
|
|
for (int idx = 1; idx <= samples; ++idx)
|
|
{
|
|
auto const current{point(static_cast<double>(idx) / samples)};
|
|
m_stations[idx] = m_stations[idx - 1] + glm::distance(previous, current);
|
|
previous = current;
|
|
}
|
|
}
|
|
bool curved() const
|
|
{
|
|
return m_curved;
|
|
}
|
|
double length() const
|
|
{
|
|
return m_stations.back();
|
|
}
|
|
// control vector of specified end of the curve, relative to that end
|
|
glm::dvec3 control(int const End) const
|
|
{
|
|
return End == 0 ? m_points[1] - m_points[0] : m_points[2] - m_points[3];
|
|
}
|
|
glm::dvec3 point(double const T) const
|
|
{
|
|
auto const u{1.0 - T};
|
|
return u * u * u * m_points[0] + 3.0 * u * u * T * m_points[1] + 3.0 * u * T * T * m_points[2] + T * T * T * m_points[3];
|
|
}
|
|
// curvature of the axis seen from above, positive when it bends to the left
|
|
double curvature(double const T) const
|
|
{
|
|
auto const first{derivative(T)};
|
|
auto const second{6.0 * (1.0 - T) * (m_points[2] - 2.0 * m_points[1] + m_points[0]) + 6.0 * T * (m_points[3] - 2.0 * m_points[2] + m_points[1])};
|
|
auto const speedsquared{first.x * first.x + first.z * first.z};
|
|
if (speedsquared < 1e-9)
|
|
{
|
|
return 0.0;
|
|
}
|
|
return (second.x * first.z - second.z * first.x) / (speedsquared * std::sqrt(speedsquared));
|
|
}
|
|
// cross-section at specified value of the curve parameter
|
|
axis_frame frame(double const T) const
|
|
{
|
|
axis_frame frame;
|
|
frame.position = point(T);
|
|
auto direction{derivative(T)};
|
|
if (glm::length2(direction) < 1e-9)
|
|
{
|
|
// a control point placed right at the end of the curve
|
|
direction = derivative(std::clamp(T, 0.01, 0.99));
|
|
}
|
|
if (glm::length2(direction) < 1e-9)
|
|
{
|
|
direction = m_points[3] - m_points[0];
|
|
}
|
|
if (glm::length2(direction) < 1e-9)
|
|
{
|
|
direction = glm::dvec3{0.0, 0.0, 1.0};
|
|
}
|
|
frame.tangent = glm::normalize(direction);
|
|
// with the y axis up and the vehicle facing along z its left side is at positive x
|
|
glm::dvec3 across{frame.tangent.z, 0.0, -frame.tangent.x};
|
|
across = (glm::length2(across) < 1e-9 ? glm::dvec3{1.0, 0.0, 0.0} : glm::normalize(across));
|
|
// positive roll lowers the right side of the road, same as it does for the tracks
|
|
frame.roll = glm::mix(m_rolls[0], m_rolls[1], T);
|
|
frame.left = across * std::cos(frame.roll) + up * std::sin(frame.roll);
|
|
return frame;
|
|
}
|
|
// cross-section at specified distance from the start of the axis
|
|
axis_frame at(double const Station) const
|
|
{
|
|
return frame(parameter(Station));
|
|
}
|
|
// control vector of specified end of a part of the curve, relative to that end
|
|
glm::dvec3 control(int const End, double const From, double const To) const
|
|
{
|
|
if (From <= 0.0 && To >= 1.0)
|
|
{
|
|
return control(End);
|
|
}
|
|
// a part of a cubic curve is a cubic curve, with the tangents scaled to the part of the parameter range it takes
|
|
return End == 0 ? derivative(From) * ((To - From) / 3.0) : derivative(To) * (-(To - From) / 3.0);
|
|
}
|
|
// value of the curve parameter at specified distance from the start of the axis
|
|
double parameter(double const Station) const
|
|
{
|
|
if (Station <= 0.0)
|
|
{
|
|
return 0.0;
|
|
}
|
|
if (Station >= length())
|
|
{
|
|
return 1.0;
|
|
}
|
|
// first of the sampled distances past the requested one; it's never the very first sample
|
|
auto const idx{std::distance(m_stations.begin(), std::upper_bound(m_stations.begin(), m_stations.end(), Station))};
|
|
auto const span{m_stations[idx] - m_stations[idx - 1]};
|
|
auto const fraction{span > 0.0 ? (Station - m_stations[idx - 1]) / span : 0.0};
|
|
return (static_cast<double>(idx - 1) + fraction) / samples;
|
|
}
|
|
// part of the length of the axis which lies before specified value of the curve parameter
|
|
double fraction(double const T) const
|
|
{
|
|
if (T <= 0.0 || length() <= 0.0)
|
|
{
|
|
return 0.0;
|
|
}
|
|
if (T >= 1.0)
|
|
{
|
|
return 1.0;
|
|
}
|
|
auto const position{T * samples};
|
|
auto const idx{std::min(samples - 1, static_cast<int>(position))};
|
|
return glm::mix(m_stations[idx], m_stations[idx + 1], position - idx) / length();
|
|
}
|
|
// length of pieces the road is cut into along the axis; follows the rules the tracks use
|
|
double step() const
|
|
{
|
|
if (false == m_curved)
|
|
{
|
|
return 10.0;
|
|
}
|
|
auto const fidelity{std::max(1.0, static_cast<double>(Global.SplineFidelity))};
|
|
return std::clamp(m_radius != 0.0 ? m_radius * 0.02 / fidelity : length() * 0.1, 2.0 / fidelity, 10.0 / fidelity);
|
|
}
|
|
|
|
private:
|
|
static constexpr int samples{64};
|
|
|
|
glm::dvec3 derivative(double const T) const
|
|
{
|
|
auto const u{1.0 - T};
|
|
return 3.0 * u * u * (m_points[1] - m_points[0]) + 6.0 * u * T * (m_points[2] - m_points[1]) + 3.0 * T * T * (m_points[3] - m_points[2]);
|
|
}
|
|
|
|
std::array<glm::dvec3, 4> m_points;
|
|
std::array<double, 2> m_rolls{};
|
|
double m_radius{0.0};
|
|
bool m_curved{false};
|
|
std::vector<double> m_stations;
|
|
};
|
|
|
|
// lines of a road a corner of a cross-section can be measured from. on a piece which gains or loses lanes the edges
|
|
// and the line the directions meet at move across the axis along the way, each on its own
|
|
enum profile_anchor : int
|
|
{
|
|
anchor_axis = 0,
|
|
anchor_left = 1, // left edge of the lanes
|
|
anchor_right = 2, // right edge of the lanes
|
|
anchor_middle = 3 // the line the two directions meet at
|
|
};
|
|
|
|
// corner of the cross-section of something laid along the road
|
|
struct profile_point
|
|
{
|
|
double offset; // distance from the axis, positive to the left. this part of it follows the taper of the road
|
|
double height; // above the surface
|
|
float texture; // texture coordinate across the road
|
|
double shift{0.0}; // further distance from the axis, which the taper leaves alone
|
|
double spread{0.0}; // how much of the gap between the two directions of the road it's moved by: 0.5 for their left edge, -0.5 for the right one
|
|
double grow{0.0}; // what the shift changes by along the axis, evenly
|
|
double sink{0.0}; // what the height changes by along the axis, evenly
|
|
int anchor{anchor_axis}; // line of the road the corner is measured from, one of profile_anchor
|
|
double tile{0.0}; // if set the image is laid across the road by where the corner is: its coordinate grows by one for each that many metres from the axis
|
|
};
|
|
|
|
// how far the taper of a road has got at specified part of its length. it starts and ends level, so the pieces of a road
|
|
// meet without a bend in their edges, and it's what a lane running from one width to another comes to on a straight
|
|
double taper_progress(double const Fraction)
|
|
{
|
|
auto const t{std::clamp(Fraction, 0.0, 1.0)};
|
|
return t * t * (3.0 - 2.0 * t);
|
|
}
|
|
|
|
// stretches provided profile along a part of the axis. the profile points go left to right, each two neighbours make a band of triangles.
|
|
// Road: the road it's done for, which says how the offsets of the profile change along the axis
|
|
void loft(std::vector<world_vertex> &Output, road_axis const &Axis, std::vector<profile_point> const &Profile, double const From, double const To, double const Step, double const Texturelength,
|
|
road_node::state const &Road)
|
|
{
|
|
auto const &Taper{Road.taper};
|
|
auto const &median{Road.median.width};
|
|
auto const divided{Road.divided()};
|
|
if (Profile.size() < 2 || To <= From || Step <= 0.0)
|
|
{
|
|
return;
|
|
}
|
|
auto const count{std::max(1, static_cast<int>(std::ceil((To - From) / Step - 0.001)))};
|
|
auto const pointcount{Profile.size()};
|
|
// each band is flat across the road, and follows its bends along it
|
|
auto const normal = [](glm::dvec3 const &Tangent, glm::dvec3 const &Across) {
|
|
auto const result{glm::cross(Tangent, Across)};
|
|
return glm::vec3{glm::length2(result) < 1e-12 ? up : glm::normalize(result)};
|
|
};
|
|
std::vector<glm::dvec3> previous(pointcount), current(pointcount);
|
|
std::vector<float> previoustexture(pointcount), currenttexture(pointcount);
|
|
auto const anchored{std::any_of(Profile.begin(), Profile.end(), [](profile_point const &Point) { return Point.anchor != anchor_axis; })};
|
|
axis_frame previousframe;
|
|
double previousstation{From};
|
|
|
|
for (int section = 0; section <= count; ++section)
|
|
{
|
|
auto const station{From + (To - From) * section / count};
|
|
auto const frame{Axis.at(station)};
|
|
auto const fraction{Axis.length() > 0.0 ? station / Axis.length() : 0.0};
|
|
auto const scale{Taper[0] == Taper[1] ? static_cast<double>(Taper[0]) : glm::mix(static_cast<double>(Taper[0]), static_cast<double>(Taper[1]), taper_progress(fraction))};
|
|
auto const gap{false == divided ? 0.0 : glm::mix(static_cast<double>(median[0]), static_cast<double>(median[1]), taper_progress(fraction))};
|
|
// where the lines the corners are measured from are at this section
|
|
std::array<double, 4> lead{0.0, 0.0, 0.0, 0.0};
|
|
if (anchored)
|
|
{
|
|
auto const half{0.5 * Road.breadth(fraction)};
|
|
lead = {0.0, half, -half, Road.middle(fraction)};
|
|
}
|
|
for (std::size_t idx = 0; idx < pointcount; ++idx)
|
|
{
|
|
auto const &point{Profile[idx]};
|
|
auto const across{lead[point.anchor] + (point.offset * scale + point.shift + point.spread * gap + point.grow * fraction)};
|
|
current[idx] = frame.position + frame.left * across + up * (point.height + point.sink * fraction);
|
|
currenttexture[idx] = (point.tile > 0.0 ? static_cast<float>(point.texture + across / point.tile) : point.texture);
|
|
}
|
|
if (section > 0)
|
|
{
|
|
auto const texturestart{static_cast<float>(previousstation / Texturelength)};
|
|
auto const textureend{static_cast<float>(station / Texturelength)};
|
|
for (std::size_t idx = 0; idx + 1 < pointcount; ++idx)
|
|
{
|
|
auto const normalstart{normal(previousframe.tangent, previous[idx] - previous[idx + 1])};
|
|
auto const normalend{normal(frame.tangent, current[idx] - current[idx + 1])};
|
|
world_vertex const leftstart{previous[idx], normalstart, {previoustexture[idx], texturestart}};
|
|
world_vertex const rightstart{previous[idx + 1], normalstart, {previoustexture[idx + 1], texturestart}};
|
|
world_vertex const leftend{current[idx], normalend, {currenttexture[idx], textureend}};
|
|
world_vertex const rightend{current[idx + 1], normalend, {currenttexture[idx + 1], textureend}};
|
|
Output.push_back(leftstart);
|
|
Output.push_back(rightstart);
|
|
Output.push_back(leftend);
|
|
|
|
Output.push_back(rightstart);
|
|
Output.push_back(rightend);
|
|
Output.push_back(leftend);
|
|
}
|
|
}
|
|
previous.swap(current);
|
|
previoustexture.swap(currenttexture);
|
|
previousframe = frame;
|
|
previousstation = station;
|
|
}
|
|
}
|
|
|
|
// shape of a line running beside a part of the axis of a road, from one distance from the axis to another, positive being to the left.
|
|
// From, To: values of the curve parameter of the axis. the line is laid out the way the axis goes
|
|
segment_data offset_path(segment_data const &Axis, road_axis const &Centre, double const From, double const To, double const Fromoffset, double const Tooffset)
|
|
{
|
|
auto const begin{Centre.frame(From)};
|
|
auto const end{Centre.frame(To)};
|
|
|
|
segment_data path;
|
|
path.points[segment_data::point::start] = begin.position + begin.left * Fromoffset;
|
|
path.points[segment_data::point::end] = end.position + end.left * Tooffset;
|
|
if (Centre.curved() || Fromoffset != Tooffset)
|
|
{
|
|
// a line running beside a bend is shorter or longer than the bend itself, and so are its control vectors.
|
|
// the control vectors go along the axis at both ends, which is what makes the lane meet the next piece without a bend
|
|
path.points[segment_data::point::control1] = Centre.control(0, From, To) * std::max(0.05, 1.0 - Fromoffset * std::cos(begin.roll) * Centre.curvature(From));
|
|
path.points[segment_data::point::control2] = Centre.control(1, From, To) * std::max(0.05, 1.0 - Tooffset * std::cos(end.roll) * Centre.curvature(To));
|
|
// if the roll changes along the road its sides rise or fall relative to the axis
|
|
auto const climb{(Tooffset * std::sin(end.roll) - Fromoffset * std::sin(begin.roll)) / 3.0};
|
|
path.points[segment_data::point::control1].y += climb;
|
|
path.points[segment_data::point::control2].y -= climb;
|
|
}
|
|
path.rolls = {From <= 0.0 ? Axis.rolls[0] : glm::mix(Axis.rolls[0], Axis.rolls[1], static_cast<float>(From)),
|
|
To >= 1.0 ? Axis.rolls[1] : glm::mix(Axis.rolls[0], Axis.rolls[1], static_cast<float>(To))};
|
|
if (Axis.radius != 0.f)
|
|
{
|
|
// the lanes on the inner side of the bend have it tighter
|
|
auto const turn{Centre.curvature(0.5 * (From + To)) >= 0.0 ? 1.0 : -1.0};
|
|
path.radius = static_cast<float>(std::max(1.0, std::abs(Axis.radius) - turn * 0.5 * (Fromoffset + Tooffset)));
|
|
}
|
|
return path;
|
|
}
|
|
|
|
// turns a line laid out along the axis of a road into the path of a lane. Against: the lane goes against the axis
|
|
segment_data lane_shape(segment_data Path, bool const Against)
|
|
{
|
|
if (Against)
|
|
{
|
|
std::swap(Path.points[segment_data::point::start], Path.points[segment_data::point::end]);
|
|
std::swap(Path.points[segment_data::point::control1], Path.points[segment_data::point::control2]);
|
|
Path.rolls = {-Path.rolls[1], -Path.rolls[0]};
|
|
}
|
|
if (Global.bRollFix)
|
|
{
|
|
// with this setting on a rolled path gets raised when it's set up, by an amount fit for a railway track.
|
|
// the surface of the road stays where it is, so the lane is lowered beforehand to make up for it
|
|
Path.points[segment_data::point::start].y -= std::abs(std::sin(glm::radians(static_cast<double>(Path.rolls[0])))) * 0.75;
|
|
Path.points[segment_data::point::end].y -= std::abs(std::sin(glm::radians(static_cast<double>(Path.rolls[1])))) * 0.75;
|
|
}
|
|
return Path;
|
|
}
|
|
|
|
// corner of a cross-section which changes along the road
|
|
struct section_corner
|
|
{
|
|
double offset; // distance from the axis, positive to the left
|
|
double height;
|
|
float texture;
|
|
};
|
|
|
|
// stretches a profile whose corners move from one cross-section to the next along the axis.
|
|
// Shape: fills in the corners, left to right, for specified distance from the start of the axis; it has to give the same number of them each time
|
|
template <class Shape_>
|
|
void sweep(std::vector<world_vertex> &Output, road_axis const &Axis, std::vector<double> const &Stations, double const Texturelength, Shape_ Shape)
|
|
{
|
|
auto const normal = [](glm::dvec3 const &Tangent, glm::dvec3 const &Across) {
|
|
auto const result{glm::cross(Tangent, Across)};
|
|
return glm::vec3{glm::length2(result) < 1e-12 ? up : glm::normalize(result)};
|
|
};
|
|
std::vector<section_corner> corners, previouscorners;
|
|
std::vector<glm::dvec3> previous, current;
|
|
axis_frame previousframe;
|
|
double previousstation{0.0};
|
|
for (std::size_t section = 0; section < Stations.size(); ++section)
|
|
{
|
|
auto const station{Stations[section]};
|
|
auto const frame{Axis.at(station)};
|
|
corners.clear();
|
|
Shape(station, corners);
|
|
current.resize(corners.size());
|
|
for (std::size_t idx = 0; idx < corners.size(); ++idx)
|
|
{
|
|
current[idx] = frame.position + frame.left * corners[idx].offset + up * corners[idx].height;
|
|
}
|
|
if (section > 0 && previous.size() == current.size())
|
|
{
|
|
auto const texturestart{static_cast<float>(previousstation / Texturelength)};
|
|
auto const textureend{static_cast<float>(station / Texturelength)};
|
|
for (std::size_t idx = 0; idx + 1 < current.size(); ++idx)
|
|
{
|
|
auto const normalstart{normal(previousframe.tangent, previous[idx] - previous[idx + 1])};
|
|
auto const normalend{normal(frame.tangent, current[idx] - current[idx + 1])};
|
|
world_vertex const leftstart{previous[idx], normalstart, {previouscorners[idx].texture, texturestart}};
|
|
world_vertex const rightstart{previous[idx + 1], normalstart, {previouscorners[idx + 1].texture, texturestart}};
|
|
world_vertex const leftend{current[idx], normalend, {corners[idx].texture, textureend}};
|
|
world_vertex const rightend{current[idx + 1], normalend, {corners[idx + 1].texture, textureend}};
|
|
Output.push_back(leftstart);
|
|
Output.push_back(rightstart);
|
|
Output.push_back(leftend);
|
|
|
|
Output.push_back(rightstart);
|
|
Output.push_back(rightend);
|
|
Output.push_back(leftend);
|
|
}
|
|
}
|
|
previous.swap(current);
|
|
previouscorners = corners;
|
|
previousframe = frame;
|
|
previousstation = station;
|
|
}
|
|
}
|
|
|
|
// closes the end of something raised over the surface with a flat face.
|
|
// Corners: outline of the face; Forward: the face looks the way the axis goes rather than back along it
|
|
void cap(std::vector<world_vertex> &Output, axis_frame const &Frame, std::vector<section_corner> const &Corners, bool const Forward, double const Tile)
|
|
{
|
|
if (Corners.size() < 3)
|
|
{
|
|
return;
|
|
}
|
|
auto const facing{Forward ? Frame.tangent : -Frame.tangent};
|
|
auto const point = [&Frame](section_corner const &Corner) { return Frame.position + Frame.left * Corner.offset + up * Corner.height; };
|
|
for (std::size_t idx = 1; idx + 1 < Corners.size(); ++idx)
|
|
{
|
|
std::array<std::size_t, 3> order{0, idx, idx + 1};
|
|
if (glm::dot(glm::cross(point(Corners[idx]) - point(Corners[0]), point(Corners[idx + 1]) - point(Corners[0])), facing) < 0.0)
|
|
{
|
|
std::swap(order[1], order[2]);
|
|
}
|
|
for (auto const corner : order)
|
|
{
|
|
Output.push_back({point(Corners[corner]), glm::vec3{facing}, {static_cast<float>(Corners[corner].offset / Tile), static_cast<float>(Corners[corner].height / Tile)}});
|
|
}
|
|
}
|
|
}
|
|
|
|
// proportions of the image specified material is painted with
|
|
float texture_ratio(std::string const &Material)
|
|
{
|
|
auto const material{GfxRenderer->Fetch_Material(Material)};
|
|
if (material == null_handle)
|
|
{
|
|
return 1.f;
|
|
}
|
|
auto const texture{GfxRenderer->Material(material)->GetTexture(0)};
|
|
if (texture == null_handle)
|
|
{
|
|
return 1.f;
|
|
}
|
|
auto const &image{GfxRenderer->Texture(texture)};
|
|
return image.get_height() > 0 ? static_cast<float>(image.get_width()) / static_cast<float>(image.get_height()) : 1.f;
|
|
}
|
|
|
|
} // namespace
|
|
|
|
// brings the content to a usable form: values within their limits, an entry for each lane and for each pair of neighbours
|
|
void road_node::state::normalize()
|
|
{
|
|
forward = std::clamp(forward, 0, 8);
|
|
backward = std::clamp(backward, 0, 8);
|
|
for (int direction = 0; direction < 2; ++direction)
|
|
{
|
|
auto &count{direction == 0 ? forward : backward};
|
|
for (auto &end : missing)
|
|
{
|
|
end[direction] = std::clamp(end[direction], 0, count);
|
|
}
|
|
// lanes the piece has at neither of its ends aren't there at all
|
|
auto const both{std::min(missing[0][direction], missing[1][direction])};
|
|
count -= both;
|
|
missing[0][direction] -= both;
|
|
missing[1][direction] -= both;
|
|
}
|
|
if (forward + backward == 0)
|
|
{
|
|
forward = 1;
|
|
}
|
|
for (auto &end : missing)
|
|
{
|
|
// there has to be a lane at each end
|
|
if (forward - end[0] + backward - end[1] < 1)
|
|
{
|
|
(forward > 0 ? end[0] : end[1]) = (forward > 0 ? forward : backward) - 1;
|
|
}
|
|
}
|
|
lanewidth = std::max(1.f, lanewidth);
|
|
weight = std::clamp(weight, 0.f, 10000.f);
|
|
for (auto &width : median.width)
|
|
{
|
|
width = std::clamp(width, 0.f, 100.f);
|
|
}
|
|
if (median.material.empty())
|
|
{
|
|
median.material = "none";
|
|
}
|
|
for (auto &round : median.round)
|
|
{
|
|
round = std::clamp(round, 0.f, 100.f);
|
|
}
|
|
kerbwidth = std::clamp(kerbwidth, 0.05f, 2.f);
|
|
if (kerbmaterial.empty())
|
|
{
|
|
kerbmaterial = "none";
|
|
}
|
|
if (bankmaterial.empty())
|
|
{
|
|
bankmaterial = "none";
|
|
}
|
|
for (auto &bank : banks)
|
|
{
|
|
for (auto &width : bank.width)
|
|
{
|
|
width = std::clamp(width, 0.f, 100.f);
|
|
}
|
|
for (auto &drop : bank.drop)
|
|
{
|
|
drop = std::clamp(drop, -100.f, 100.f);
|
|
}
|
|
}
|
|
for (auto &end : taper)
|
|
{
|
|
end = std::clamp(end, 0.25f, 4.f);
|
|
}
|
|
if (texturelength < 0.01f)
|
|
{
|
|
texturelength = 4.f;
|
|
}
|
|
if (surface.empty())
|
|
{
|
|
surface = "none";
|
|
}
|
|
// the paths of the lanes are loaded from text, so what goes into it has to be something they understand
|
|
static std::array<std::string, 7> const environments{"flat", "mountains", "mountain", "canyon", "tunnel", "bridge", "bank"};
|
|
if (std::find(environments.begin(), environments.end(), environment) == environments.end())
|
|
{
|
|
environment = "flat";
|
|
}
|
|
auto const count{static_cast<std::size_t>(forward + backward)};
|
|
if (lanes.size() != count)
|
|
{
|
|
lane_data fresh;
|
|
fresh.width = lanewidth;
|
|
fresh.velocity = velocity;
|
|
lanes.assign(count, fresh);
|
|
}
|
|
for (auto &lane : lanes)
|
|
{
|
|
lane.width = std::max(1.f, lane.width);
|
|
}
|
|
if (changes.size() != count - 1)
|
|
{
|
|
changes.resize(count - 1);
|
|
for (std::size_t boundary = 0; boundary < changes.size(); ++boundary)
|
|
{
|
|
changes[boundary] = default_change(boundary);
|
|
}
|
|
}
|
|
for (auto &change : changes)
|
|
{
|
|
change = std::clamp(change, static_cast<int>(change_none), static_cast<int>(change_both));
|
|
}
|
|
}
|
|
|
|
// identifier of a lane: f1..fn go along the axis and b1..bn against it, both counted outwards from where the directions meet
|
|
std::string road_node::state::lane_id(std::size_t const Lane) const
|
|
{
|
|
auto const against{static_cast<std::size_t>(backward)};
|
|
return Lane < against ? "b" + std::to_string(against - Lane) : "f" + std::to_string(Lane - against + 1);
|
|
}
|
|
|
|
// number of a lane in the left to right order, -1 if there's no lane with such identifier
|
|
int road_node::state::lane_index(std::string const &Id) const
|
|
{
|
|
if (Id.size() < 2 || Id.size() > 3 || (Id[0] != 'f' && Id[0] != 'b'))
|
|
{
|
|
return -1;
|
|
}
|
|
int number{0};
|
|
for (std::size_t idx = 1; idx < Id.size(); ++idx)
|
|
{
|
|
if (Id[idx] < '0' || Id[idx] > '9')
|
|
{
|
|
return -1;
|
|
}
|
|
number = number * 10 + (Id[idx] - '0');
|
|
}
|
|
if (number < 1 || number > (Id[0] == 'f' ? forward : backward))
|
|
{
|
|
return -1;
|
|
}
|
|
return Id[0] == 'f' ? backward + number - 1 : backward - number;
|
|
}
|
|
|
|
// true if the piece has other lanes at its end than at its start
|
|
bool road_node::state::changing() const
|
|
{
|
|
return missing[0][0] != 0 || missing[0][1] != 0 || missing[1][0] != 0 || missing[1][1] != 0;
|
|
}
|
|
|
|
// sets the lanes the piece has at the start and at the end of its axis
|
|
void road_node::state::lanes_between(int const Startforward, int const Startbackward, int const Endforward, int const Endbackward)
|
|
{
|
|
auto const along{std::clamp(std::max(Startforward, Endforward), 0, 8)};
|
|
auto const against{std::clamp(std::max(Startbackward, Endbackward), 0, 8)};
|
|
if (along != forward || against != backward)
|
|
{
|
|
// a different set of lanes starts with the common width and speed limit, and the default rules for changing lanes
|
|
forward = along;
|
|
backward = against;
|
|
lanes.clear();
|
|
changes.clear();
|
|
}
|
|
missing[0] = {forward - std::max(0, Startforward), backward - std::max(0, Startbackward)};
|
|
missing[1] = {forward - std::max(0, Endforward), backward - std::max(0, Endbackward)};
|
|
normalize();
|
|
}
|
|
|
|
// number of lanes at an end of the axis: of the ones going along it, or of the ones going against it
|
|
int road_node::state::lanes_at(int const End, bool const Along) const
|
|
{
|
|
return Along ? forward - missing[End][0] : backward - missing[End][1];
|
|
}
|
|
|
|
// true if the piece has the lane at specified end of the axis
|
|
bool road_node::state::lane_at(std::size_t const Lane, int const End) const
|
|
{
|
|
// the lanes of each direction are counted outwards from where the directions meet, and it's the outermost ones a piece is short of
|
|
auto const against{static_cast<std::size_t>(backward)};
|
|
return Lane < against ? Lane >= static_cast<std::size_t>(missing[End][1]) : Lane - against < static_cast<std::size_t>(forward - missing[End][0]);
|
|
}
|
|
|
|
// the same road with the lanes it has at specified end of the axis all the way
|
|
road_node::state road_node::state::section(int const End) const
|
|
{
|
|
auto result{*this};
|
|
result.lanes.clear();
|
|
result.changes.clear();
|
|
for (std::size_t lane = 0; lane < lanes.size(); ++lane)
|
|
{
|
|
if (false == lane_at(lane, End))
|
|
{
|
|
continue;
|
|
}
|
|
// the lanes a piece has at an end lie side by side, so the one before this one is its neighbour there as well
|
|
if (false == result.lanes.empty() && lane - 1 < changes.size())
|
|
{
|
|
result.changes.emplace_back(changes[lane - 1]);
|
|
}
|
|
result.lanes.emplace_back(lanes[lane]);
|
|
}
|
|
result.forward = lanes_at(End, true);
|
|
result.backward = lanes_at(End, false);
|
|
result.missing = {};
|
|
return result;
|
|
}
|
|
|
|
// permission to change the lane a pair of neighbouring lanes gets if the scenery doesn't say otherwise
|
|
int road_node::state::default_change(std::size_t const Boundary) const
|
|
{
|
|
auto const opposite{backward > 0 && forward > 0 && Boundary + 1 == static_cast<std::size_t>(backward)};
|
|
if (false == opposite)
|
|
{
|
|
return change_both;
|
|
}
|
|
// overtaking across the oncoming lane is left for the simple two lane roads
|
|
return (forward == 1 && backward == 1) ? change_both : change_none;
|
|
}
|
|
|
|
// distance of the middle of a lane from the axis, positive to the left when facing along the axis
|
|
double road_node::state::lane_offset(std::size_t const Lane) const
|
|
{
|
|
auto offset{0.5 * width()};
|
|
for (std::size_t idx = 0; idx < Lane && idx < lanes.size(); ++idx)
|
|
{
|
|
offset -= lanes[idx].width;
|
|
}
|
|
return Lane < lanes.size() ? offset - 0.5 * lanes[Lane].width : offset;
|
|
}
|
|
|
|
// the same at an end of the axis, where the road is centred on the axis with the lanes it has there
|
|
double road_node::state::lane_offset(std::size_t const Lane, int const End) const
|
|
{
|
|
auto const against{static_cast<std::size_t>(backward)};
|
|
auto lane{Lane};
|
|
if (Lane < lanes.size() && false == lane_at(Lane, End))
|
|
{
|
|
// a lane the road is short of there comes out of the outermost lane its direction has at that end, or goes into it.
|
|
// with no such lane it starts, or ends, at the line the directions meet at
|
|
if (lanes_at(End, Lane >= against) < 1)
|
|
{
|
|
return divide(End);
|
|
}
|
|
lane = (Lane < against ? static_cast<std::size_t>(missing[End][1]) : against + static_cast<std::size_t>(lanes_at(End, true) - 1));
|
|
}
|
|
auto offset{0.5 * width(End)};
|
|
for (std::size_t idx = 0; idx < lane && idx < lanes.size(); ++idx)
|
|
{
|
|
if (lane_at(idx, End))
|
|
{
|
|
offset -= lanes[idx].width;
|
|
}
|
|
}
|
|
return lane < lanes.size() ? offset - 0.5 * lanes[lane].width : offset;
|
|
}
|
|
|
|
// distance of the middle of a lane from the axis at specified part of the length of the axis, with the taper and what's between the directions counted in
|
|
double road_node::state::lane_position(std::size_t const Lane, double const Fraction) const
|
|
{
|
|
auto const side{Lane < static_cast<std::size_t>(backward) ? 0.5 : -0.5};
|
|
auto const beginoffset{lane_offset(Lane, 0) * taper[0] + side * median_width(0.0)};
|
|
auto const endoffset{lane_offset(Lane, 1) * taper[1] + side * median_width(1.0)};
|
|
return glm::mix(beginoffset, endoffset, taper_progress(Fraction));
|
|
}
|
|
|
|
// combined width of the lanes, before the taper
|
|
double road_node::state::width() const
|
|
{
|
|
double total{0.0};
|
|
for (auto const &lane : lanes)
|
|
{
|
|
total += lane.width;
|
|
}
|
|
return total;
|
|
}
|
|
|
|
// the same for the lanes the piece has at an end of the axis
|
|
double road_node::state::width(int const End) const
|
|
{
|
|
double total{0.0};
|
|
for (std::size_t lane = 0; lane < lanes.size(); ++lane)
|
|
{
|
|
if (lane_at(lane, End))
|
|
{
|
|
total += lanes[lane].width;
|
|
}
|
|
}
|
|
return total;
|
|
}
|
|
|
|
// combined width of the lanes at specified part of the length of the axis, with the taper counted in
|
|
double road_node::state::breadth(double const Fraction) const
|
|
{
|
|
return glm::mix(width(0) * taper[0], width(1) * taper[1], taper_progress(Fraction));
|
|
}
|
|
|
|
// what the widths of the lanes are multiplied by at specified value of the curve parameter
|
|
double road_node::state::scale(double const T) const
|
|
{
|
|
return glm::mix(static_cast<double>(taper[0]), static_cast<double>(taper[1]), taper_progress(T));
|
|
}
|
|
|
|
// true if the two directions of the road are kept apart anywhere along it
|
|
bool road_node::state::divided() const
|
|
{
|
|
return forward > 0 && backward > 0 && (median.width[0] > 0.f || median.width[1] > 0.f);
|
|
}
|
|
|
|
// how far apart the two directions are at specified value of the curve parameter
|
|
double road_node::state::median_width(double const T) const
|
|
{
|
|
return divided() ? glm::mix(static_cast<double>(median.width[0]), static_cast<double>(median.width[1]), taper_progress(T)) : 0.0;
|
|
}
|
|
|
|
// distance from the axis of the line the two directions meet at, on a road which doesn't keep them apart
|
|
double road_node::state::divide() const
|
|
{
|
|
auto offset{0.5 * width()};
|
|
for (std::size_t idx = 0; idx < static_cast<std::size_t>(backward) && idx < lanes.size(); ++idx)
|
|
{
|
|
offset -= lanes[idx].width;
|
|
}
|
|
return offset;
|
|
}
|
|
|
|
// the same for the lanes the piece has at an end of the axis
|
|
double road_node::state::divide(int const End) const
|
|
{
|
|
auto offset{0.5 * width(End)};
|
|
for (std::size_t idx = 0; idx < static_cast<std::size_t>(backward) && idx < lanes.size(); ++idx)
|
|
{
|
|
if (lane_at(idx, End))
|
|
{
|
|
offset -= lanes[idx].width;
|
|
}
|
|
}
|
|
return offset;
|
|
}
|
|
|
|
// the same at specified part of the length of the axis, with the taper counted in
|
|
double road_node::state::middle(double const Fraction) const
|
|
{
|
|
return glm::mix(divide(0) * taper[0], divide(1) * taper[1], taper_progress(Fraction));
|
|
}
|
|
|
|
// width of the whole roadway at specified value of the curve parameter
|
|
double road_node::state::span(double const T) const
|
|
{
|
|
return (changing() ? breadth(T) : width() * scale(T)) + median_width(T);
|
|
}
|
|
|
|
// shape of the middle of a lane, laid out in the direction of travel
|
|
segment_data road_node::state::lane_path(std::size_t const Lane) const
|
|
{
|
|
road_axis const centre{axis};
|
|
// on a road which gets wider or narrower the lane moves away from the axis or towards it along the way,
|
|
// and so it does where the two directions are led apart, or where the road gains or loses lanes
|
|
auto const side{Lane < static_cast<std::size_t>(backward) ? 0.5 : -0.5};
|
|
auto const beginoffset{lane_offset(Lane, 0) * taper[0] + side * median_width(0.0)};
|
|
auto const endoffset{lane_offset(Lane, 1) * taper[1] + side * median_width(1.0)};
|
|
return lane_shape(offset_path(axis, centre, 0.0, 1.0, beginoffset, endoffset), Lane < static_cast<std::size_t>(backward));
|
|
}
|
|
|
|
// shape of the way from the middle of a lane to the middle of another over a part of the axis, laid out in the direction of travel
|
|
segment_data road_node::state::lane_path(std::size_t const Lane, std::size_t const Tolane, double const From, double const To) const
|
|
{
|
|
road_axis const centre{axis};
|
|
auto const against{Lane < static_cast<std::size_t>(backward)};
|
|
// the traffic going against the axis gets to the part by its far end
|
|
auto const fromoffset{lane_position(against ? Tolane : Lane, centre.fraction(From))};
|
|
auto const tooffset{lane_position(against ? Lane : Tolane, centre.fraction(To))};
|
|
return lane_shape(offset_path(axis, centre, From, To, fromoffset, tooffset), against);
|
|
}
|
|
|
|
// part of the axis over which a piece which gains or loses lanes leads the lanes it has at one end to the lanes it has at the other
|
|
std::array<double, 2> road_node::state::change_range() const
|
|
{
|
|
road_axis const centre{axis};
|
|
auto const lead{std::min(lane_lead, 0.2 * centre.length())};
|
|
return {centre.parameter(lead), centre.parameter(centre.length() - lead)};
|
|
}
|
|
|
|
// length of the axis
|
|
double road_node::state::length() const
|
|
{
|
|
return road_axis{axis}.length();
|
|
}
|
|
|
|
// position on the axis and direction of the axis, for specified value of the curve parameter
|
|
glm::dvec3 road_node::state::point(double const T) const
|
|
{
|
|
return road_axis{axis}.point(T);
|
|
}
|
|
|
|
glm::dvec3 road_node::state::tangent(double const T) const
|
|
{
|
|
return road_axis{axis}.frame(T).tangent;
|
|
}
|
|
|
|
road_node::road_node(scene::node_data const &Nodedata) : basic_node(Nodedata) {}
|
|
|
|
// restores content of the node from provided input stream; reads up to and including the closing 'endroad'
|
|
void road_node::import(cParser &Input, glm::dvec3 const &Offset)
|
|
{
|
|
auto const label{m_name.empty() ? std::string{"unnamed road"} : "road \"" + m_name + "\""};
|
|
|
|
m_state = state{};
|
|
m_state.axis.deserialize(Input, Offset);
|
|
|
|
// properties of the lanes can precede the statement which sets how many of them there are, so they wait until everything is read
|
|
struct lane_property
|
|
{
|
|
std::string lane;
|
|
std::string property;
|
|
float value;
|
|
};
|
|
struct change_property
|
|
{
|
|
std::string first;
|
|
std::string second;
|
|
std::string mode;
|
|
};
|
|
std::vector<lane_property> laneproperties;
|
|
std::vector<change_property> changeproperties;
|
|
// lanes at the end of the axis, if these are other than the ones at its start
|
|
std::array<int, 2> endlanes{-1, -1};
|
|
|
|
auto token{Input.getToken<std::string>()};
|
|
while (false == token.empty() && token != "endroad")
|
|
{
|
|
if (token == "lanes")
|
|
{
|
|
// lanes <along the axis> <against the axis>
|
|
Input.getTokens(2);
|
|
Input >> m_state.forward >> m_state.backward;
|
|
}
|
|
else if (token == "lanesto")
|
|
{
|
|
// lanesto <along the axis> <against the axis>
|
|
Input.getTokens(2);
|
|
Input >> endlanes[0] >> endlanes[1];
|
|
}
|
|
else if (token == "width")
|
|
{
|
|
Input.getTokens();
|
|
Input >> m_state.lanewidth;
|
|
}
|
|
else if (token == "velocity")
|
|
{
|
|
Input.getTokens();
|
|
Input >> m_state.velocity;
|
|
}
|
|
else if (token == "taper")
|
|
{
|
|
// taper <at the start> <at the end>
|
|
Input.getTokens(2);
|
|
Input >> m_state.taper[0] >> m_state.taper[1];
|
|
}
|
|
else if (token == "lane")
|
|
{
|
|
// lane <lane> <width|velocity> <value>
|
|
lane_property property;
|
|
property.lane = Input.getToken<std::string>();
|
|
property.property = Input.getToken<std::string>();
|
|
property.value = 0.f;
|
|
Input.getTokens();
|
|
Input >> property.value;
|
|
laneproperties.emplace_back(property);
|
|
}
|
|
else if (token == "change")
|
|
{
|
|
// change <lane> <neighbouring lane> <both|none|ab|ba>
|
|
change_property property;
|
|
property.first = Input.getToken<std::string>();
|
|
property.second = Input.getToken<std::string>();
|
|
property.mode = Input.getToken<std::string>();
|
|
changeproperties.emplace_back(property);
|
|
}
|
|
else if (token == "surface")
|
|
{
|
|
m_state.surface = Input.getToken<std::string>();
|
|
replace_slashes(m_state.surface);
|
|
}
|
|
else if (token == "texlength")
|
|
{
|
|
Input.getTokens();
|
|
Input >> m_state.texturelength;
|
|
}
|
|
else if (token == "side")
|
|
{
|
|
// side <left|right|both> <none|shoulder|sidewalk> <width> <material>
|
|
auto const where{Input.getToken<std::string>()};
|
|
auto const type{Input.getToken<std::string>()};
|
|
side_data side;
|
|
Input.getTokens();
|
|
Input >> side.width;
|
|
side.material = Input.getToken<std::string>();
|
|
replace_slashes(side.material);
|
|
side.type = (type == "shoulder" ? side_type::shoulder : type == "sidewalk" ? side_type::sidewalk : side_type::none);
|
|
if (type != "shoulder" && type != "sidewalk" && type != "none")
|
|
{
|
|
ErrorLog("Bad road: unknown kind of side \"" + type + "\" defined for " + label);
|
|
}
|
|
if (where == "left" || where == "both")
|
|
{
|
|
m_state.sides[0] = side;
|
|
}
|
|
if (where == "right" || where == "both")
|
|
{
|
|
m_state.sides[1] = side;
|
|
}
|
|
if (where != "left" && where != "right" && where != "both")
|
|
{
|
|
ErrorLog("Bad road: unknown side \"" + where + "\" defined for " + label);
|
|
}
|
|
}
|
|
else if (token == "kerb")
|
|
{
|
|
Input.getTokens();
|
|
Input >> m_state.kerbheight;
|
|
}
|
|
else if (token == "slope")
|
|
{
|
|
// slope <width> <drop>
|
|
Input.getTokens(2);
|
|
Input >> m_state.slope.x >> m_state.slope.y;
|
|
}
|
|
else if (token == "markings")
|
|
{
|
|
auto const colour{Input.getToken<std::string>()};
|
|
m_state.markings = (colour == "white" ? marking_colour::white : colour == "orange" ? marking_colour::orange : marking_colour::none);
|
|
if (colour != "white" && colour != "orange" && colour != "none")
|
|
{
|
|
ErrorLog("Bad road: unknown colour of markings \"" + colour + "\" defined for " + label);
|
|
}
|
|
}
|
|
else if (token == "friction")
|
|
{
|
|
Input.getTokens();
|
|
Input >> m_state.friction;
|
|
}
|
|
else if (token == "environment")
|
|
{
|
|
m_state.environment = Input.getToken<std::string>();
|
|
}
|
|
else if (token == "weight")
|
|
{
|
|
Input.getTokens();
|
|
Input >> m_state.weight;
|
|
}
|
|
else if (token == "median")
|
|
{
|
|
// median <gap|painted|island> <width at the start> <width at the end> <material>
|
|
auto const type{Input.getToken<std::string>()};
|
|
m_state.median.type = (type == "gap" ? median_type::gap : type == "island" ? median_type::island : median_type::painted);
|
|
if (type != "gap" && type != "island" && type != "painted")
|
|
{
|
|
ErrorLog("Bad road: unknown kind of median \"" + type + "\" defined for " + label);
|
|
}
|
|
Input.getTokens(2);
|
|
Input >> m_state.median.width[0] >> m_state.median.width[1];
|
|
m_state.median.material = Input.getToken<std::string>();
|
|
replace_slashes(m_state.median.material);
|
|
}
|
|
else if (token == "medianround")
|
|
{
|
|
// medianround <at the start> <at the end>
|
|
Input.getTokens(2);
|
|
Input >> m_state.median.round[0] >> m_state.median.round[1];
|
|
}
|
|
else if (token == "kerbs")
|
|
{
|
|
// kerbs <left|right|both> <width> <material>
|
|
auto const where{Input.getToken<std::string>()};
|
|
m_state.kerbs = {where == "left" || where == "both", where == "right" || where == "both"};
|
|
if (where != "left" && where != "right" && where != "both")
|
|
{
|
|
ErrorLog("Bad road: unknown side \"" + where + "\" defined for the kerbs of " + label);
|
|
}
|
|
Input.getTokens();
|
|
Input >> m_state.kerbwidth;
|
|
m_state.kerbmaterial = Input.getToken<std::string>();
|
|
replace_slashes(m_state.kerbmaterial);
|
|
}
|
|
else if (token == "bank")
|
|
{
|
|
// bank <left|right|both> <width at the start> <drop at the start> <width at the end> <drop at the end>
|
|
auto const where{Input.getToken<std::string>()};
|
|
bank_data bank;
|
|
bank.set = true;
|
|
Input.getTokens(4);
|
|
Input >> bank.width[0] >> bank.drop[0] >> bank.width[1] >> bank.drop[1];
|
|
if (where == "left" || where == "both")
|
|
{
|
|
m_state.banks[0] = bank;
|
|
}
|
|
if (where == "right" || where == "both")
|
|
{
|
|
m_state.banks[1] = bank;
|
|
}
|
|
if (where != "left" && where != "right" && where != "both")
|
|
{
|
|
ErrorLog("Bad road: unknown side \"" + where + "\" defined for a bank of " + label);
|
|
}
|
|
}
|
|
else if (token == "bankmaterial")
|
|
{
|
|
m_state.bankmaterial = Input.getToken<std::string>();
|
|
replace_slashes(m_state.bankmaterial);
|
|
}
|
|
else if (token == "roundabout")
|
|
{
|
|
m_state.roundabout = true;
|
|
}
|
|
else
|
|
{
|
|
ErrorLog("Bad road: unknown property: \"" + token + "\" defined for " + label);
|
|
}
|
|
token = Input.getToken<std::string>();
|
|
}
|
|
|
|
if (m_state.forward + m_state.backward <= 0)
|
|
{
|
|
ErrorLog("Bad road: " + label + " has no lanes, a single one is used instead");
|
|
}
|
|
auto const environment{m_state.environment};
|
|
if (endlanes[0] >= 0 || endlanes[1] >= 0)
|
|
{
|
|
if (std::max(0, endlanes[0]) + std::max(0, endlanes[1]) <= 0)
|
|
{
|
|
ErrorLog("Bad road: " + label + " has no lanes at its end, a single one is used instead");
|
|
}
|
|
m_state.lanes_between(m_state.forward, m_state.backward, endlanes[0], endlanes[1]);
|
|
// the traffic going along the axis gets on the piece at its start, the one going against it at its end
|
|
int const gains[]{m_state.lanes_at(1, true) - m_state.lanes_at(0, true), m_state.lanes_at(0, false) - m_state.lanes_at(1, false)};
|
|
int const leaving[]{m_state.lanes_at(1, true), m_state.lanes_at(0, false)};
|
|
int const arriving[]{m_state.lanes_at(0, true), m_state.lanes_at(1, false)};
|
|
for (int direction = 0; direction < 2; ++direction)
|
|
{
|
|
if (arriving[direction] > 0 && gains[direction] > 2)
|
|
{
|
|
ErrorLog("Bad road: " + label + " gains more than two lanes at once, the ones past the second can't be got on");
|
|
}
|
|
if (arriving[direction] > 0 && leaving[direction] == 0)
|
|
{
|
|
ErrorLog("Bad road: " + label + " has lanes which lead nowhere, as their direction ends within it");
|
|
}
|
|
}
|
|
}
|
|
m_state.normalize();
|
|
if (environment != m_state.environment)
|
|
{
|
|
ErrorLog("Bad road: unknown environment \"" + environment + "\" defined for " + label);
|
|
}
|
|
|
|
for (auto const &property : laneproperties)
|
|
{
|
|
auto const lane{m_state.lane_index(property.lane)};
|
|
if (lane < 0)
|
|
{
|
|
ErrorLog("Bad road: " + label + " has no lane \"" + property.lane + "\"");
|
|
continue;
|
|
}
|
|
if (property.property == "width")
|
|
{
|
|
m_state.lanes[lane].width = std::max(1.f, property.value);
|
|
}
|
|
else if (property.property == "velocity")
|
|
{
|
|
m_state.lanes[lane].velocity = property.value;
|
|
}
|
|
else
|
|
{
|
|
ErrorLog("Bad road: unknown lane property: \"" + property.property + "\" defined for " + label);
|
|
}
|
|
}
|
|
for (auto const &property : changeproperties)
|
|
{
|
|
auto const first{m_state.lane_index(property.first)};
|
|
auto const second{m_state.lane_index(property.second)};
|
|
if (first < 0 || second < 0 || std::abs(first - second) != 1)
|
|
{
|
|
ErrorLog("Bad road: lanes \"" + property.first + "\" and \"" + property.second + "\" aren't neighbours on " + label);
|
|
continue;
|
|
}
|
|
// the permissions are stored for the pair taken left to right
|
|
auto const firstonleft{first < second};
|
|
auto &change{m_state.changes[std::min(first, second)]};
|
|
if (property.mode == "both")
|
|
{
|
|
change = change_both;
|
|
}
|
|
else if (property.mode == "none")
|
|
{
|
|
change = change_none;
|
|
}
|
|
else if (property.mode == "ab")
|
|
{
|
|
change = (firstonleft ? change_toright : change_toleft);
|
|
}
|
|
else if (property.mode == "ba")
|
|
{
|
|
change = (firstonleft ? change_toleft : change_toright);
|
|
}
|
|
else
|
|
{
|
|
ErrorLog("Bad road: unknown lane change mode: \"" + property.mode + "\" defined for " + label);
|
|
}
|
|
}
|
|
|
|
location(m_state.point(0.5));
|
|
}
|
|
|
|
// replaces what the node knows about the road
|
|
void road_node::define(state const &State)
|
|
{
|
|
m_state = State;
|
|
m_state.normalize();
|
|
location(m_state.point(0.5));
|
|
m_area.radius = -1.f;
|
|
}
|
|
|
|
// creates paths of the lanes and hands them over to the simulation
|
|
void road_node::create_lanes()
|
|
{
|
|
auto const count{m_state.lanes.size()};
|
|
m_tracks.clear();
|
|
for (auto &tracks : m_lanetracks)
|
|
{
|
|
tracks.assign(count, nullptr);
|
|
}
|
|
auto const range{m_state.change_range()};
|
|
for (std::size_t lane = 0; lane < count; ++lane)
|
|
{
|
|
auto const along{lane >= static_cast<std::size_t>(m_state.backward)};
|
|
auto const name{m_name.empty() ? std::string{} : m_name + ":" + m_state.lane_id(lane)};
|
|
auto const &data{m_state.lanes[lane]};
|
|
if (m_state.missing[0][along ? 0 : 1] == 0 && m_state.missing[1][along ? 0 : 1] == 0)
|
|
{
|
|
// the direction keeps its lanes all the way, and so each of them is a single path
|
|
auto *track{create_track(name, m_state.lane_path(lane), data.width, data.velocity)};
|
|
m_lanetracks[0][lane] = track;
|
|
m_lanetracks[1][lane] = track;
|
|
m_tracks.emplace_back(track);
|
|
continue;
|
|
}
|
|
// the direction gains or loses lanes along the way. a lane gets a short path at each end the piece has it at, which is what
|
|
// the neighbours and the junctions join; what leads from the ones at one end to the ones at the other is made by create_links()
|
|
for (int end = 0; end < 2; ++end)
|
|
{
|
|
if (false == m_state.lane_at(lane, end))
|
|
{
|
|
continue;
|
|
}
|
|
// the traffic going along the axis gets on the piece at its start
|
|
auto const entry{(end == 0) == along};
|
|
auto *track{create_track(name.empty() || entry ? name : name + ":out", m_state.lane_path(lane, lane, end == 0 ? 0.0 : range[1], end == 0 ? range[0] : 1.0), data.width, data.velocity)};
|
|
m_lanetracks[end][lane] = track;
|
|
m_tracks.emplace_back(track);
|
|
}
|
|
}
|
|
}
|
|
|
|
// makes the paths which lead the lanes the piece has at one end to the lanes it has at the other, where these differ
|
|
void road_node::create_links()
|
|
{
|
|
if (false == m_links.empty() || false == m_state.changing() || m_lanetracks[0].size() != m_state.lanes.size())
|
|
{
|
|
return;
|
|
}
|
|
auto const range{m_state.change_range()};
|
|
std::ostringstream text;
|
|
text.precision(std::numeric_limits<double>::digits10);
|
|
auto const write_point = [&text](glm::dvec3 const &Point) { text << Point.x << ' ' << Point.y << ' ' << Point.z << ' '; };
|
|
for (int direction = 0; direction < 2; ++direction)
|
|
{
|
|
if (m_state.missing[0][direction] == 0 && m_state.missing[1][direction] == 0)
|
|
{
|
|
continue;
|
|
}
|
|
auto const along{direction == 0};
|
|
// ends of the axis the traffic of the direction gets on the piece and leaves it by
|
|
auto const entry{along ? 0 : 1};
|
|
auto const exit{1 - entry};
|
|
auto const arriving{m_state.lanes_at(entry, along)};
|
|
auto const leaving{m_state.lanes_at(exit, along)};
|
|
// place of a lane of the direction, counted from where the directions meet, in the left to right order
|
|
auto const index = [&](int const Number) { return static_cast<std::size_t>(along ? m_state.backward + Number - 1 : m_state.backward - Number); };
|
|
for (int number = 1; number <= arriving && leaving > 0; ++number)
|
|
{
|
|
auto const lane{index(number)};
|
|
auto *head{m_lanetracks[entry][lane]};
|
|
if (head == nullptr)
|
|
{
|
|
continue;
|
|
}
|
|
// a lane leads to itself; one the road loses leads to the outermost lane left, and the outermost lane of a road
|
|
// which gains lanes leads to these as well. a path has up to three ways out, so that's two lanes gained at most
|
|
std::vector<std::size_t> targets{index(std::min(number, leaving))};
|
|
for (int extra = arriving + 1; number == arriving && extra <= leaving && targets.size() < 3; ++extra)
|
|
{
|
|
targets.emplace_back(index(extra));
|
|
}
|
|
std::vector<TTrack *> tails;
|
|
std::vector<segment_data> ways;
|
|
for (auto const target : targets)
|
|
{
|
|
if (m_lanetracks[exit][target] != nullptr)
|
|
{
|
|
tails.emplace_back(m_lanetracks[exit][target]);
|
|
ways.emplace_back(m_state.lane_path(lane, target, range[0], range[1]));
|
|
}
|
|
}
|
|
if (tails.empty())
|
|
{
|
|
continue;
|
|
}
|
|
m_ways.insert(m_ways.end(), ways.begin(), ways.end());
|
|
auto const name{m_name.empty() ? std::string{} : m_name + ":" + m_state.lane_id(lane) + ":way"};
|
|
auto const &data{m_state.lanes[lane]};
|
|
if (tails.size() == 1)
|
|
{
|
|
auto *link{create_track(name, ways[0], data.width, data.velocity)};
|
|
// tied by hand: lanes the road loses end where the one they lead to carries on, which is more than joining path ends can express
|
|
head->ConnectNextPrev(link, 0);
|
|
link->trNext = tails[0];
|
|
link->iNextDirection = 0;
|
|
if (tails[0]->trPrev == nullptr)
|
|
{
|
|
tails[0]->trPrev = link;
|
|
tails[0]->iPrevDirection = 1;
|
|
}
|
|
m_links.emplace_back(link);
|
|
continue;
|
|
}
|
|
// a fork is a crossroads, which is what the drivers know how to pick a way through. the ways leave the lane
|
|
// the way it goes, and each joins its lane the way that one goes
|
|
// NOTE: a crossroads isn't set up the way a rolled path is, so its points are given as they are and it's level across
|
|
auto const raise = [](glm::dvec3 Point, float const Roll) {
|
|
if (Global.bRollFix)
|
|
{
|
|
Point.y += std::abs(std::sin(glm::radians(static_cast<double>(Roll)))) * 0.75;
|
|
}
|
|
return Point;
|
|
};
|
|
auto const start{raise(ways[0].points[segment_data::point::start], ways[0].rolls[0])};
|
|
auto const startcontrol{ways[0].points[segment_data::point::control1]};
|
|
std::vector<glm::dvec3> ends;
|
|
std::vector<glm::dvec3> endcontrols;
|
|
for (auto const &way : ways)
|
|
{
|
|
ends.emplace_back(raise(way.points[segment_data::point::end], way.rolls[1]));
|
|
endcontrols.emplace_back(way.points[segment_data::point::control2]);
|
|
}
|
|
text.str("");
|
|
text << "cross " << glm::distance(start, ends[0]) << ' ' << data.width << ' ' << m_state.friction << ' ' << m_state.sounddistance << ' ' << m_state.quality << " 0 " << m_state.environment
|
|
<< " unvis ";
|
|
// first path: from the lane to itself
|
|
write_point(start);
|
|
text << "0 ";
|
|
write_point(startcontrol);
|
|
write_point(endcontrols[0]);
|
|
write_point(ends[0]);
|
|
text << "0 0 ";
|
|
if (ways.size() == 2)
|
|
{
|
|
// second path of a crossroads of three roads starts where the first one does
|
|
write_point(start);
|
|
text << "0 ";
|
|
write_point(startcontrol);
|
|
write_point(endcontrols[1]);
|
|
write_point(ends[1]);
|
|
text << "0 0 ";
|
|
}
|
|
else
|
|
{
|
|
// second path of a crossroads of four roads runs between its third and fourth point
|
|
write_point(ends[1]);
|
|
text << "0 ";
|
|
write_point(endcontrols[1]);
|
|
write_point(endcontrols[2]);
|
|
write_point(ends[2]);
|
|
text << "0 0 ";
|
|
}
|
|
if (data.velocity > 0.f)
|
|
{
|
|
text << "velocity " << data.velocity << ' ';
|
|
}
|
|
text << "endtrack";
|
|
auto *link{create_track(name, text.str())};
|
|
if (link->SwitchExtension != nullptr)
|
|
{
|
|
auto &extension{*link->SwitchExtension};
|
|
// the points of the crossroads are stored as: first, second, fourth, third
|
|
extension.pPrevs[0] = head;
|
|
extension.iPrevDirection[0] = 1;
|
|
extension.pNexts[0] = tails[0];
|
|
extension.iNextDirection[0] = 0;
|
|
extension.pPrevs[1] = (tails.size() == 3 ? tails[2] : tails[1]);
|
|
extension.iPrevDirection[1] = 0;
|
|
extension.pNexts[1] = (tails.size() == 3 ? tails[1] : nullptr);
|
|
extension.iNextDirection[1] = 0;
|
|
link->Switch(0);
|
|
head->trNext = link;
|
|
head->iNextDirection = 0;
|
|
// the drivers take each of the lanes as readily as any other
|
|
link->m_routeweights = {100.f, 100.f, tails.size() == 3 ? 100.f : 0.f};
|
|
// the lanes get to know the path leading to them, for whatever goes backwards and for those who look who's coming
|
|
int const ends2[]{1, 2};
|
|
int const ends3[]{1, 3, 2};
|
|
for (std::size_t idx = 0; idx < tails.size(); ++idx)
|
|
{
|
|
if (tails[idx]->trPrev == nullptr)
|
|
{
|
|
tails[idx]->trPrev = link;
|
|
tails[idx]->iPrevDirection = (tails.size() == 3 ? ends3[idx] : ends2[idx]);
|
|
}
|
|
}
|
|
}
|
|
m_links.emplace_back(link);
|
|
}
|
|
}
|
|
}
|
|
|
|
// links lanes of opposite directions at an end of the road which leads nowhere, so the vehicles can turn back
|
|
void road_node::close_ends()
|
|
{
|
|
// NOTE: without the link a vehicle reaching the end would be sent back on the lane it came by, against its direction
|
|
if (m_lanetracks[0].size() != m_state.lanes.size())
|
|
{
|
|
return;
|
|
}
|
|
road_axis const axis{m_state.axis};
|
|
for (int end = 0; end < 2; ++end)
|
|
{
|
|
// the lanes going along the axis leave the road at its end, the ones going against it leave at its start
|
|
auto const outwards{end == 1 ? axis.frame(1.0).tangent : -axis.frame(0.0).tangent};
|
|
for (int pair = 1; pair <= std::min(m_state.lanes_at(end, true), m_state.lanes_at(end, false)); ++pair)
|
|
{
|
|
auto const forward{static_cast<std::size_t>(m_state.backward + pair - 1)};
|
|
auto const backward{static_cast<std::size_t>(m_state.backward - pair)};
|
|
auto *exit{m_lanetracks[end][end == 1 ? forward : backward]};
|
|
auto *entry{m_lanetracks[end][end == 1 ? backward : forward]};
|
|
if (exit == nullptr || entry == nullptr || exit->trNext != nullptr || entry->trPrev != nullptr)
|
|
{
|
|
continue;
|
|
}
|
|
segment_data path;
|
|
path.points[segment_data::point::start] = exit->CurrentSegment()->FastGetPoint_1();
|
|
path.points[segment_data::point::end] = entry->CurrentSegment()->FastGetPoint_0();
|
|
auto const span{glm::distance(path.points[segment_data::point::start], path.points[segment_data::point::end])};
|
|
path.points[segment_data::point::control1] = outwards * std::max(turn_reach, 1.5 * span);
|
|
path.points[segment_data::point::control2] = outwards * std::max(turn_reach, 1.5 * span);
|
|
path.radius = static_cast<float>(std::max(2.0, 0.5 * span));
|
|
auto *turn{create_track(m_name.empty() ? std::string{} : m_name + ":" + (end == 1 ? "endturn" : "startturn") + std::to_string(pair), path, m_state.lanes[forward].width, turn_velocity)};
|
|
exit->ConnectNextPrev(turn, 0);
|
|
turn->ConnectNextPrev(entry, 0);
|
|
m_turns.emplace_back(turn);
|
|
}
|
|
}
|
|
}
|
|
|
|
// gives up the paths of the lanes
|
|
std::vector<TTrack *> road_node::release_lanes()
|
|
{
|
|
std::vector<TTrack *> released;
|
|
released.swap(m_tracks);
|
|
released.insert(released.end(), m_links.begin(), m_links.end());
|
|
m_links.clear();
|
|
m_ways.clear();
|
|
for (auto &tracks : m_lanetracks)
|
|
{
|
|
tracks.clear();
|
|
}
|
|
released.erase(std::remove(released.begin(), released.end(), nullptr), released.end());
|
|
return released;
|
|
}
|
|
|
|
// gives up the paths made to close the loose ends
|
|
std::vector<TTrack *> road_node::release_turns()
|
|
{
|
|
std::vector<TTrack *> released;
|
|
released.swap(m_turns);
|
|
return released;
|
|
}
|
|
|
|
// true if there's a vehicle on any path of the road
|
|
bool road_node::occupied() const
|
|
{
|
|
for (auto const *tracks : {&m_tracks, &m_links, &m_turns})
|
|
{
|
|
for (auto const *track : *tracks)
|
|
{
|
|
if (track != nullptr && false == track->Dynamics.empty())
|
|
{
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
// generates geometry of the surface, the sides and the markings
|
|
std::vector<scene::shape_node> road_node::create_shapes() const
|
|
{
|
|
// triangles are gathered separately for each look, so the lot can be drawn with as few shapes as possible
|
|
struct batch
|
|
{
|
|
std::string material;
|
|
lighting_data lighting;
|
|
std::vector<world_vertex> vertices;
|
|
};
|
|
std::vector<batch> batches;
|
|
auto const vertices = [&batches](std::string const &Material, lighting_data const &Lighting) -> std::vector<world_vertex> & {
|
|
for (auto &entry : batches)
|
|
{
|
|
if (entry.material == Material && entry.lighting == Lighting)
|
|
{
|
|
return entry.vertices;
|
|
}
|
|
}
|
|
batches.emplace_back();
|
|
batches.back().material = Material;
|
|
batches.back().lighting = Lighting;
|
|
return batches.back().vertices;
|
|
};
|
|
|
|
auto const &road{m_state};
|
|
road_axis const axis{road.axis};
|
|
auto const length{axis.length()};
|
|
auto const step{axis.step()};
|
|
auto const halfwidth{0.5 * road.width()};
|
|
double const texturelength{road.texturelength};
|
|
// where the two directions are kept apart there's a roadway for each, moved away from the axis by half of what's between them
|
|
auto const divided{road.divided()};
|
|
auto const divide{road.divide()};
|
|
auto const widest{static_cast<double>(std::max(road.median.width[0], road.median.width[1]))};
|
|
auto const height{static_cast<double>(road.kerbheight)};
|
|
auto const usable = [](std::string const &Material) { return false == Material.empty() && Material != "none"; };
|
|
// on a piece which gains or loses lanes the edges and the line the directions meet at move across the axis along the way,
|
|
// so what's laid along them is measured from them. elsewhere they keep their distance from the axis, and it's measured from the axis
|
|
auto const changing{road.changing()};
|
|
// distance of one of these lines from the axis, on a road as wide as its lanes say
|
|
auto const distance = [&](int const Line) { return Line == anchor_left ? halfwidth : Line == anchor_right ? -halfwidth : Line == anchor_middle ? divide : 0.0; };
|
|
// where the line the directions meet at is, for specified distance from the start of the axis
|
|
auto const meeting = [&](double const Station) {
|
|
return changing ? road.middle(Station / length) : divide * glm::mix(static_cast<double>(road.taper[0]), static_cast<double>(road.taper[1]), taper_progress(Station / length));
|
|
};
|
|
|
|
// surface. the image is centered on the axis, and repeated if the road is wider
|
|
if (road.surface != "none")
|
|
{
|
|
auto const tile{static_cast<double>(texture_ratio(road.surface)) * texturelength};
|
|
auto const corner = [&](int const Line, double const Spread) {
|
|
if (changing)
|
|
{
|
|
return profile_point{0.0, 0.0, 0.5f, 0.0, Spread, 0.0, 0.0, Line, tile};
|
|
}
|
|
auto const offset{distance(Line)};
|
|
return profile_point{offset, 0.0, static_cast<float>(0.5 + (offset + Spread * widest) / tile), 0.0, Spread};
|
|
};
|
|
auto &surface{vertices(road.surface, lighting_data{})};
|
|
if (false == divided)
|
|
{
|
|
loft(surface, axis, {corner(anchor_left, 0.0), corner(anchor_right, 0.0)}, 0.0, length, step, texturelength, road);
|
|
}
|
|
else
|
|
{
|
|
loft(surface, axis, {corner(anchor_left, 0.5), corner(anchor_middle, 0.5)}, 0.0, length, step, texturelength, road);
|
|
if (road.median.type != median_type::gap)
|
|
{
|
|
// the surface carries on between the roadways; an island stands on it, so there's something under its rounded ends
|
|
loft(surface, axis, {corner(anchor_middle, 0.5), corner(anchor_middle, -0.5)}, 0.0, length, step, texturelength, road);
|
|
}
|
|
loft(surface, axis, {corner(anchor_middle, -0.5), corner(anchor_right, -0.5)}, 0.0, length, step, texturelength, road);
|
|
}
|
|
}
|
|
|
|
// an island between the roadways: a kerb facing each of them, and what's between the kerbs
|
|
if (divided && road.median.type == median_type::island && length > 0.0)
|
|
{
|
|
auto const kerbed{usable(road.kerbmaterial)};
|
|
auto const covered{usable(road.median.material)};
|
|
// the ends of the island can be rounded; it gets narrower there along a quarter of an ellipse
|
|
std::array<double, 2> const nose{std::min(static_cast<double>(road.median.round[0]), 0.5 * length), std::min(static_cast<double>(road.median.round[1]), 0.5 * length)};
|
|
int const nosesteps{8};
|
|
double const quarter{1.5707963267948966};
|
|
std::vector<double> stations;
|
|
for (int idx = 0; idx < nosesteps && nose[0] > 0.0; ++idx)
|
|
{
|
|
stations.emplace_back(nose[0] * (1.0 - std::cos(quarter * idx / nosesteps)));
|
|
}
|
|
auto const body{length - nose[0] - nose[1]};
|
|
auto const bodysteps{std::max(1, static_cast<int>(std::ceil(body / step - 0.001)))};
|
|
for (int idx = 0; idx <= bodysteps; ++idx)
|
|
{
|
|
stations.emplace_back(nose[0] + body * idx / bodysteps);
|
|
}
|
|
for (int idx = 1; idx <= nosesteps && nose[1] > 0.0; ++idx)
|
|
{
|
|
stations.emplace_back(length - nose[1] * (1.0 - std::sin(quarter * idx / nosesteps)));
|
|
}
|
|
// middle of the island and half of its width, for specified distance from the start of the axis
|
|
auto const &middle{meeting};
|
|
auto const half = [&](double const Station) {
|
|
auto result{0.5 * glm::mix(static_cast<double>(road.median.width[0]), static_cast<double>(road.median.width[1]), taper_progress(Station / length))};
|
|
if (Station < nose[0])
|
|
{
|
|
auto const along{(nose[0] - Station) / nose[0]};
|
|
result *= std::sqrt(std::max(0.0, 1.0 - along * along));
|
|
}
|
|
else if (Station > length - nose[1])
|
|
{
|
|
auto const along{(Station - (length - nose[1])) / nose[1]};
|
|
result *= std::sqrt(std::max(0.0, 1.0 - along * along));
|
|
}
|
|
return result;
|
|
};
|
|
if (kerbed)
|
|
{
|
|
auto const tile{static_cast<double>(texture_ratio(road.kerbmaterial)) * texturelength};
|
|
auto const top{static_cast<float>(height / tile)};
|
|
auto const inner{static_cast<float>((height + road.kerbwidth) / tile)};
|
|
auto &kerbs{vertices(road.kerbmaterial, lighting_data{})};
|
|
sweep(kerbs, axis, stations, texturelength, [&](double const Station, std::vector<section_corner> &Corners) {
|
|
auto const edge{middle(Station) + half(Station)};
|
|
Corners = {{edge, 0.0, 0.f}, {edge, height, top}, {edge - std::min(static_cast<double>(road.kerbwidth), half(Station)), height, inner}};
|
|
});
|
|
sweep(kerbs, axis, stations, texturelength, [&](double const Station, std::vector<section_corner> &Corners) {
|
|
auto const edge{middle(Station) - half(Station)};
|
|
Corners = {{edge + std::min(static_cast<double>(road.kerbwidth), half(Station)), height, inner}, {edge, height, top}, {edge, 0.0, 0.f}};
|
|
});
|
|
}
|
|
if (covered)
|
|
{
|
|
auto const tile{static_cast<double>(texture_ratio(road.median.material)) * texturelength};
|
|
sweep(vertices(road.median.material, lighting_data{}), axis, stations, texturelength, [&](double const Station, std::vector<section_corner> &Corners) {
|
|
auto const centre{middle(Station)};
|
|
auto const reach{half(Station)};
|
|
auto const inset{kerbed ? std::min(static_cast<double>(road.kerbwidth), reach) : 0.0};
|
|
Corners.clear();
|
|
if (false == kerbed)
|
|
{
|
|
// without kerbs of their own material the sides of the island are covered with what its top is
|
|
Corners.push_back({centre + reach, 0.0, 0.f});
|
|
}
|
|
Corners.push_back({centre + reach - inset, height, static_cast<float>(height / tile)});
|
|
Corners.push_back({centre - reach + inset, height, static_cast<float>((height + 2.0 * reach) / tile)});
|
|
if (false == kerbed)
|
|
{
|
|
Corners.push_back({centre - reach, 0.0, static_cast<float>((2.0 * height + 2.0 * reach) / tile)});
|
|
}
|
|
});
|
|
}
|
|
// an end which isn't rounded gets a face, so the island isn't hollow where the next piece has none
|
|
if (kerbed || covered)
|
|
{
|
|
auto const &material{covered ? road.median.material : road.kerbmaterial};
|
|
auto const tile{static_cast<double>(texture_ratio(material)) * texturelength};
|
|
for (int end = 0; end < 2; ++end)
|
|
{
|
|
auto const station{end == 0 ? 0.0 : length};
|
|
auto const reach{half(station)};
|
|
if (nose[end] > 0.0 || reach < 0.025)
|
|
{
|
|
continue;
|
|
}
|
|
auto const centre{middle(station)};
|
|
std::vector<section_corner> const face{{centre + reach, 0.0, 0.f}, {centre + reach, height, 0.f}, {centre - reach, height, 0.f}, {centre - reach, 0.0, 0.f}};
|
|
cap(vertices(material, lighting_data{}), axis.at(station), face, end == 1, tile);
|
|
}
|
|
}
|
|
}
|
|
|
|
// sides: a kerb, then a shoulder or a sidewalk, then a bank leading to the ground; each of them optional
|
|
for (int side = 0; side < 2; ++side)
|
|
{
|
|
auto const &data{road.sides[side]};
|
|
auto const direction{side == 0 ? 1.0 : -1.0};
|
|
auto const sided{data.type != side_type::none && data.width > 0.f && usable(data.material)};
|
|
auto const kerbed{road.kerbs[side] && usable(road.kerbmaterial)};
|
|
// the profiles are given from the edge of the surface outwards, as distances from that edge
|
|
auto const emit = [&](std::string const &Material, std::vector<profile_point> Profile) {
|
|
for (auto &point : Profile)
|
|
{
|
|
point.offset = (changing ? 0.0 : direction * halfwidth);
|
|
point.anchor = (changing ? (side == 0 ? anchor_left : anchor_right) : anchor_axis);
|
|
point.spread = (divided ? direction * 0.5 : 0.0);
|
|
point.shift *= direction;
|
|
point.grow *= direction;
|
|
}
|
|
if (side == 0)
|
|
{
|
|
// the loft takes the corners left to right
|
|
std::reverse(Profile.begin(), Profile.end());
|
|
}
|
|
loft(vertices(Material, lighting_data{}), axis, Profile, 0.0, length, step, texturelength, road);
|
|
};
|
|
// faces closing what's raised over the surface at both ends of the piece, so it isn't hollow where the next piece has none.
|
|
// From, To: distances from the edge of the surface
|
|
auto const close = [&](std::string const &Material, double const From, double const To) {
|
|
auto const tile{static_cast<double>(texture_ratio(Material)) * texturelength};
|
|
for (int end = 0; end < 2; ++end)
|
|
{
|
|
auto const edge{direction * (0.5 * road.width(end) * road.taper[end] + (divided ? 0.5 * road.median.width[end] : 0.0))};
|
|
cap(vertices(Material, lighting_data{}), axis.at(end == 0 ? 0.0 : length),
|
|
{{edge + direction * From, 0.0, 0.f}, {edge + direction * From, height, 0.f}, {edge + direction * To, height, 0.f}, {edge + direction * To, 0.0, 0.f}}, end == 1, tile);
|
|
}
|
|
};
|
|
double reach{0.0}; // how far from the edge of the surface the next thing starts
|
|
double level{0.0}; // and how high
|
|
if (kerbed)
|
|
{
|
|
auto const tile{static_cast<double>(texture_ratio(road.kerbmaterial)) * texturelength};
|
|
double const width{road.kerbwidth};
|
|
close(road.kerbmaterial, 0.0, width);
|
|
std::vector<profile_point> kerb{{0.0, 0.0, 0.f, 0.0}, {0.0, height, static_cast<float>(height / tile), 0.0}, {0.0, height, static_cast<float>((height + width) / tile), width}};
|
|
if (false == sided || data.type != side_type::sidewalk)
|
|
{
|
|
// with nothing raised behind it the kerb has a back
|
|
kerb.push_back({0.0, 0.0, static_cast<float>((2.0 * height + width) / tile), width});
|
|
}
|
|
emit(road.kerbmaterial, kerb);
|
|
reach = width;
|
|
}
|
|
if (sided && data.type == side_type::shoulder)
|
|
{
|
|
// the image is laid out like the one of the legacy roads: the edge of the surface on its right, the bank on its left half
|
|
std::vector<profile_point> profile{{0.0, 0.0, 1.f, reach}, {0.0, 0.0, 0.5f, reach + data.width}};
|
|
reach += data.width;
|
|
auto const &bank{road.banks[side]};
|
|
glm::dvec2 const start{bank.set ? bank.width[0] : road.slope.x, bank.set ? bank.drop[0] : road.slope.y};
|
|
glm::dvec2 const end{bank.set ? bank.width[1] : road.slope.x, bank.set ? bank.drop[1] : road.slope.y};
|
|
if (start.x > 0.0 || end.x > 0.0)
|
|
{
|
|
profile.push_back({0.0, -start.y, 0.f, reach + start.x, 0.0, end.x - start.x, start.y - end.y});
|
|
}
|
|
emit(data.material, profile);
|
|
}
|
|
else if (sided)
|
|
{
|
|
// the image starts at the foot of the kerb, and is laid out in its own proportions
|
|
auto const tile{static_cast<double>(texture_ratio(data.material)) * texturelength};
|
|
std::vector<profile_point> profile;
|
|
if (false == kerbed)
|
|
{
|
|
profile.push_back({0.0, 0.0, 0.f, 0.0});
|
|
}
|
|
profile.push_back({0.0, height, static_cast<float>(height / tile), reach});
|
|
profile.push_back({0.0, height, static_cast<float>((height + data.width) / tile), reach + data.width});
|
|
emit(data.material, profile);
|
|
close(data.material, reach, reach + data.width);
|
|
reach += data.width;
|
|
level = height;
|
|
}
|
|
// a bank next to something other than a shoulder is covered with a material of its own
|
|
auto const &bank{road.banks[side]};
|
|
if ((false == sided || data.type != side_type::shoulder) && bank.set && usable(road.bankmaterial) && (bank.width[0] > 0.f || bank.width[1] > 0.f))
|
|
{
|
|
auto const tile{static_cast<double>(texture_ratio(road.bankmaterial)) * texturelength};
|
|
profile_point foot{0.0, level - bank.drop[0], static_cast<float>(std::max(bank.width[0], bank.width[1]) / tile), reach + bank.width[0]};
|
|
foot.grow = static_cast<double>(bank.width[1]) - bank.width[0];
|
|
foot.sink = static_cast<double>(bank.drop[0]) - bank.drop[1];
|
|
emit(road.bankmaterial, {{0.0, level, 0.f, reach}, foot});
|
|
}
|
|
}
|
|
|
|
// markings. these are painted with plain colour instead of an image
|
|
if (road.markings != marking_colour::none)
|
|
{
|
|
lighting_data paint;
|
|
paint.diffuse = (road.markings == marking_colour::white ? glm::vec4{0.92f, 0.92f, 0.92f, 1.f} : glm::vec4{0.95f, 0.5f, 0.08f, 1.f});
|
|
paint.ambient = paint.diffuse;
|
|
auto &lines{vertices("colored", paint)};
|
|
|
|
// Line, Offset: where the line runs on a road as wide as its lanes say, as a distance from one of the lines of the road,
|
|
// Shift: how far from there it's kept whatever the width, Spread: which of the roadways it goes with, where the road has two,
|
|
// From, To: part of the piece it's painted on
|
|
auto const solid = [&](int const Line, double const Offset, double const Shift, double const Spread, double const From, double const To) {
|
|
std::vector<profile_point> const line{{Offset, line_lift, 0.f, Shift + 0.5 * line_width, Spread, 0.0, 0.0, Line},
|
|
{Offset, line_lift, 1.f, Shift - 0.5 * line_width, Spread, 0.0, 0.0, Line}};
|
|
loft(lines, axis, line, From, To, std::min(step, dash_step), texturelength, road);
|
|
};
|
|
// the dashes are fitted so the gaps at both ends of the road are a half of the regular one, which makes them match the next piece
|
|
auto const dashed = [&](int const Line, double const Offset, double const Shift, double const Spread, double const From, double const To) {
|
|
auto const count{std::max(1, static_cast<int>(std::lround(length / dash_period)))};
|
|
auto const period{length / count};
|
|
std::vector<profile_point> const line{{Offset, line_lift, 0.f, Shift + 0.5 * line_width, Spread, 0.0, 0.0, Line},
|
|
{Offset, line_lift, 1.f, Shift - 0.5 * line_width, Spread, 0.0, 0.0, Line}};
|
|
for (int dash = 0; dash < count; ++dash)
|
|
{
|
|
auto const from{(dash + 1.0 / 3.0) * period};
|
|
if (from < From || from + period / 3.0 > To)
|
|
{
|
|
continue;
|
|
}
|
|
loft(lines, axis, line, from, from + period / 3.0, dash_step, texturelength, road);
|
|
}
|
|
};
|
|
// part of the piece the line between two lanes is painted on. a lane the road gains or loses along the piece
|
|
// gets its line where there's room for a half of it
|
|
auto const stretch = [&](std::size_t const Boundary) {
|
|
auto const against{static_cast<std::size_t>(road.backward)};
|
|
std::pair<double, double> result{0.0, length};
|
|
if (false == changing || Boundary + 1 == against)
|
|
{
|
|
return result;
|
|
}
|
|
// the one of the two which is further from where the directions meet
|
|
auto const outer{Boundary + 1 < against ? Boundary : Boundary + 1};
|
|
if (road.lane_at(outer, 0) && road.lane_at(outer, 1))
|
|
{
|
|
return result;
|
|
}
|
|
// what the direction needs to be as wide as for the line, on a road as wide as its lanes say
|
|
auto needed{0.5 * road.lanes[outer].width};
|
|
for (auto lane{outer < against ? outer + 1 : against}; lane < (outer < against ? against : outer); ++lane)
|
|
{
|
|
needed += road.lanes[lane].width;
|
|
}
|
|
int const samples{64};
|
|
auto const room = [&](int const Sample) {
|
|
auto const fraction{static_cast<double>(Sample) / samples};
|
|
auto const half{0.5 * road.breadth(fraction)};
|
|
auto const middle{road.middle(fraction)};
|
|
auto const scale{glm::mix(static_cast<double>(road.taper[0]), static_cast<double>(road.taper[1]), taper_progress(fraction))};
|
|
return (outer < against ? half - middle : half + middle) >= needed * scale;
|
|
};
|
|
auto first{0};
|
|
while (first <= samples && false == room(first))
|
|
{
|
|
++first;
|
|
}
|
|
auto last{samples};
|
|
while (last >= first && false == room(last))
|
|
{
|
|
--last;
|
|
}
|
|
result = {length * first / samples, length * last / samples};
|
|
return result;
|
|
};
|
|
|
|
// edges of the surface
|
|
auto const inset{edge_inset + 0.5 * line_width};
|
|
if (0.5 * std::min(road.width(0) * road.taper[0], road.width(1) * road.taper[1]) - inset > 0.5)
|
|
{
|
|
solid(changing ? anchor_left : anchor_axis, changing ? 0.0 : halfwidth, -inset, divided ? 0.5 : 0.0, 0.0, length);
|
|
solid(changing ? anchor_right : anchor_axis, changing ? 0.0 : -halfwidth, inset, divided ? -0.5 : 0.0, 0.0, length);
|
|
}
|
|
// lines between the lanes. a lane can be left across a dashed line, or across a pair of lines if the dashed one is on its side
|
|
auto offset{halfwidth};
|
|
for (std::size_t boundary = 0; boundary < road.changes.size() && boundary < road.lanes.size(); ++boundary)
|
|
{
|
|
offset -= road.lanes[boundary].width;
|
|
auto const opposite{road.backward > 0 && boundary + 1 == static_cast<std::size_t>(road.backward)};
|
|
auto const pair{0.5 * (line_width + line_spacing)};
|
|
// the lanes keep their widths, and so the lines between them keep their distance from where the directions meet
|
|
auto const from{changing ? anchor_middle : anchor_axis};
|
|
auto const place{changing ? offset - divide : offset};
|
|
auto const range{stretch(boundary)};
|
|
if (changing && range.second - range.first < 1.0)
|
|
{
|
|
continue;
|
|
}
|
|
if (opposite && divided)
|
|
{
|
|
// each of the two roadways gets its edge line
|
|
solid(from, place, inset, 0.5, range.first, range.second);
|
|
solid(from, place, -inset, -0.5, range.first, range.second);
|
|
continue;
|
|
}
|
|
auto const spread{false == divided ? 0.0 : boundary + 1 < static_cast<std::size_t>(road.backward) ? 0.5 : -0.5};
|
|
switch (road.changes[boundary])
|
|
{
|
|
case change_both:
|
|
{
|
|
dashed(from, place, 0.0, spread, range.first, range.second);
|
|
break;
|
|
}
|
|
case change_toright:
|
|
{
|
|
dashed(from, place, pair, spread, range.first, range.second);
|
|
solid(from, place, -pair, spread, range.first, range.second);
|
|
break;
|
|
}
|
|
case change_toleft:
|
|
{
|
|
solid(from, place, pair, spread, range.first, range.second);
|
|
dashed(from, place, -pair, spread, range.first, range.second);
|
|
break;
|
|
}
|
|
default:
|
|
{
|
|
if (opposite)
|
|
{
|
|
// traffic going opposite ways is kept apart with a double line
|
|
solid(from, place, pair, spread, range.first, range.second);
|
|
solid(from, place, -pair, spread, range.first, range.second);
|
|
}
|
|
else
|
|
{
|
|
solid(from, place, 0.0, spread, range.first, range.second);
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
if (divided && road.median.type == median_type::painted && length > 0.0)
|
|
{
|
|
// what's between the roadways is closed to the traffic: slanted stripes are led from one edge line to the other
|
|
double const period{3.0};
|
|
double const stripe{0.5};
|
|
glm::vec3 const upwards{0.f, 1.f, 0.f};
|
|
auto const gap_at = [&](double const Station) { return glm::mix(static_cast<double>(road.median.width[0]), static_cast<double>(road.median.width[1]), taper_progress(Station / length)); };
|
|
// point of the edge of one of the roadways, a bit into what's between them. Side: 1 for the left one, -1 for the right one
|
|
auto const edge = [&](double const Station, double const Side) {
|
|
auto const station{std::clamp(Station, 0.0, length)};
|
|
auto const frame{axis.at(station)};
|
|
return frame.position + frame.left * (meeting(station) + Side * std::max(0.0, 0.5 * gap_at(station) - 2.0 * inset)) + up * line_lift;
|
|
};
|
|
// the stripes are spread evenly over the piece, and none of them reaches past its ends
|
|
auto const count{std::max(1, static_cast<int>(std::lround(length / period)))};
|
|
auto const spacing{length / count};
|
|
for (int index = 0; index < count; ++index)
|
|
{
|
|
auto const centre{(index + 0.5) * spacing};
|
|
auto const gap{gap_at(centre)};
|
|
if (gap < 1.0)
|
|
{
|
|
continue;
|
|
}
|
|
// a stripe gets as far along the road as it gets across it, as long as that leaves room for the next one
|
|
auto const slant{std::clamp(gap, 0.0, std::max(0.0, spacing - stripe - 0.25))};
|
|
auto const station{centre - 0.5 * (slant + stripe)};
|
|
auto const leftstart{edge(station, 1.0)};
|
|
auto const leftend{edge(station + stripe, 1.0)};
|
|
auto const rightstart{edge(station + slant, -1.0)};
|
|
auto const rightend{edge(station + slant + stripe, -1.0)};
|
|
lines.push_back({leftstart, upwards, {0.f, 0.f}});
|
|
lines.push_back({rightstart, upwards, {1.f, 0.f}});
|
|
lines.push_back({leftend, upwards, {0.f, 1.f}});
|
|
lines.push_back({rightstart, upwards, {1.f, 0.f}});
|
|
lines.push_back({rightend, upwards, {1.f, 1.f}});
|
|
lines.push_back({leftend, upwards, {0.f, 1.f}});
|
|
}
|
|
}
|
|
}
|
|
|
|
std::vector<scene::shape_node> shapes;
|
|
for (auto &entry : batches)
|
|
{
|
|
if (entry.vertices.empty())
|
|
{
|
|
continue;
|
|
}
|
|
scene::shape_node shape;
|
|
shape.make_terrain(GfxRenderer->Fetch_Material(entry.material), std::move(entry.vertices), glm::dvec3{0.0});
|
|
shape.lighting(entry.lighting);
|
|
shapes.emplace_back(std::move(shape));
|
|
}
|
|
return shapes;
|
|
}
|
|
|
|
namespace
|
|
{
|
|
|
|
// banks holding geometry put in the scene by the owned shapes
|
|
std::unordered_set<std::uint32_t> ownedbanks;
|
|
|
|
double const junction_reach{0.25}; // an end of a road this close to an arm is attached to it
|
|
double const junction_fit{0.05}; // a lane has to end this close to where the junction expects it
|
|
int const corner_steps{6}; // pieces a rounded corner is made of
|
|
double const stopline_width{0.5};
|
|
double const stopline_inset{0.2}; // distance of a stop line from the end of its road
|
|
double const gate_period{0.2}; // seconds between looks at the traffic around a junction
|
|
double const gate_reach{120.0}; // how far back along the lanes leading to a junction the vehicles are looked for
|
|
double const gate_gap{6.0}; // a vehicle this many seconds from a junction starts to matter to the others, and is told about them
|
|
double const gate_zone{15.0}; // and so does one this close, however slow it goes
|
|
double const gate_commit{8.0}; // a vehicle let through this close to the junction is on its way, the others wait for it
|
|
double const gate_patience{6.0}; // seconds a vehicle let through can stand still before the others stop waiting for it
|
|
double const way_clearance{2.2}; // ways through a junction which pass this close to each other can't be taken at the same time
|
|
|
|
double const crosswalk_inset{1.0}; // distance of a pedestrian crossing from the end of its road, which leaves room for a stop line
|
|
|
|
// corner of the cross-section of what lines the edge of a junction
|
|
struct edge_point
|
|
{
|
|
double offset; // distance from the edge of the surface
|
|
double height;
|
|
float texture;
|
|
double grow{0.0}; // what the offset changes by along the edge, evenly
|
|
double sink{0.0}; // what the height changes by along the edge, evenly
|
|
};
|
|
|
|
// something which lines the edge of a junction: a kerb, a shoulder with its bank, a sidewalk, a bank
|
|
struct edge_lining
|
|
{
|
|
std::string material;
|
|
std::vector<edge_point> profile;
|
|
};
|
|
|
|
// what the edge of a junction is lined with, from the edge outwards. Bank: slope leading to the ground from that edge
|
|
std::vector<edge_lining> edge_linings(junction_node::state const &State, road_node::bank_data const &Bank)
|
|
{
|
|
std::vector<edge_lining> linings;
|
|
auto const usable = [](std::string const &Material) { return false == Material.empty() && Material != "none"; };
|
|
auto const &side{State.side};
|
|
auto const sided{side.type != road_node::side_type::none && side.width > 0.f && usable(side.material)};
|
|
auto const kerbed{State.kerbs && usable(State.kerbmaterial)};
|
|
double const height{State.kerbheight};
|
|
double reach{0.0}; // how far from the edge of the surface the next thing starts
|
|
double level{0.0}; // and how high
|
|
if (kerbed)
|
|
{
|
|
auto const tile{static_cast<double>(texture_ratio(State.kerbmaterial)) * State.texturelength};
|
|
double const width{State.kerbwidth};
|
|
edge_lining kerb;
|
|
kerb.material = State.kerbmaterial;
|
|
kerb.profile = {{0.0, 0.0, 0.f}, {0.0, height, static_cast<float>(height / tile)}, {width, height, static_cast<float>((height + width) / tile)}};
|
|
if (false == sided || side.type != road_node::side_type::sidewalk)
|
|
{
|
|
// with nothing raised behind it the kerb has a back
|
|
kerb.profile.push_back({width, 0.0, static_cast<float>((2.0 * height + width) / tile)});
|
|
}
|
|
linings.emplace_back(kerb);
|
|
reach = width;
|
|
}
|
|
if (sided && side.type == road_node::side_type::shoulder)
|
|
{
|
|
edge_lining shoulder;
|
|
shoulder.material = side.material;
|
|
shoulder.profile = {{reach, 0.0, 1.f}, {reach + side.width, 0.0, 0.5f}};
|
|
reach += side.width;
|
|
glm::dvec2 const start{Bank.set ? Bank.width[0] : State.slope.x, Bank.set ? Bank.drop[0] : State.slope.y};
|
|
glm::dvec2 const end{Bank.set ? Bank.width[1] : State.slope.x, Bank.set ? Bank.drop[1] : State.slope.y};
|
|
if (start.x > 0.0 || end.x > 0.0)
|
|
{
|
|
shoulder.profile.push_back({reach + start.x, -start.y, 0.f, end.x - start.x, start.y - end.y});
|
|
}
|
|
linings.emplace_back(shoulder);
|
|
}
|
|
else if (sided)
|
|
{
|
|
auto const tile{static_cast<double>(texture_ratio(side.material)) * State.texturelength};
|
|
edge_lining sidewalk;
|
|
sidewalk.material = side.material;
|
|
if (false == kerbed)
|
|
{
|
|
sidewalk.profile.push_back({0.0, 0.0, 0.f});
|
|
}
|
|
sidewalk.profile.push_back({reach, height, static_cast<float>(height / tile)});
|
|
sidewalk.profile.push_back({reach + side.width, height, static_cast<float>((height + side.width) / tile)});
|
|
linings.emplace_back(sidewalk);
|
|
reach += side.width;
|
|
level = height;
|
|
}
|
|
// a bank next to something other than a shoulder is covered with a material of its own
|
|
if ((false == sided || side.type != road_node::side_type::shoulder) && Bank.set && usable(State.bankmaterial) && (Bank.width[0] > 0.f || Bank.width[1] > 0.f))
|
|
{
|
|
auto const tile{static_cast<double>(texture_ratio(State.bankmaterial)) * State.texturelength};
|
|
edge_lining bank;
|
|
bank.material = State.bankmaterial;
|
|
bank.profile = {{reach, level, 0.f}, {reach + Bank.width[0], level - Bank.drop[0], static_cast<float>(std::max(Bank.width[0], Bank.width[1]) / tile)}};
|
|
bank.profile.back().grow = static_cast<double>(Bank.width[1]) - Bank.width[0];
|
|
bank.profile.back().sink = static_cast<double>(Bank.drop[0]) - Bank.drop[1];
|
|
linings.emplace_back(bank);
|
|
}
|
|
return linings;
|
|
}
|
|
|
|
// direction on the ground as a vector in space
|
|
glm::dvec3 flat(glm::dvec2 const &Direction)
|
|
{
|
|
return glm::dvec3{Direction.x, 0.0, Direction.y};
|
|
}
|
|
|
|
// direction to the left of the provided one, on the ground
|
|
glm::dvec2 left_of(glm::dvec2 const &Direction)
|
|
{
|
|
return glm::dvec2{Direction.y, -Direction.x};
|
|
}
|
|
|
|
// angle of the turn from one direction to another, positive to the left
|
|
double turn_angle(glm::dvec2 const &From, glm::dvec2 const &To)
|
|
{
|
|
return std::atan2(glm::dot(To, left_of(From)), glm::dot(To, From));
|
|
}
|
|
|
|
// slope a lane has at one of its ends, in the direction of travel
|
|
double lane_grade(TTrack const &Lane, bool const Atend)
|
|
{
|
|
if (Lane.m_paths.empty())
|
|
{
|
|
return 0.0;
|
|
}
|
|
auto const &path{Lane.m_paths.front()};
|
|
auto const &control{path.points[Atend ? segment_data::point::control2 : segment_data::point::control1]};
|
|
auto const direction{control != glm::dvec3{0.0} ? (Atend ? -control : control) : path.points[segment_data::point::end] - path.points[segment_data::point::start]};
|
|
auto const run{glm::length(glm::dvec2{direction.x, direction.z})};
|
|
return run > 1e-6 ? direction.y / run : 0.0;
|
|
}
|
|
|
|
// what a driver calls the way of a fork which leads to specified lane: the number of the path of the crossroads it's on,
|
|
// negative if it's taken against the path. 0 if the fork doesn't lead to the lane
|
|
int fork_code(TTrack const &Fork, TTrack const *Lane)
|
|
{
|
|
if (Fork.SwitchExtension == nullptr || Lane == nullptr)
|
|
{
|
|
return 0;
|
|
}
|
|
auto const &extension{*Fork.SwitchExtension};
|
|
if (extension.pNexts[0] == Lane)
|
|
{
|
|
return 1;
|
|
}
|
|
if (extension.pNexts[1] != nullptr)
|
|
{
|
|
// three ways out
|
|
return extension.pNexts[1] == Lane ? 5 : extension.pPrevs[1] == Lane ? -4 : 0;
|
|
}
|
|
return extension.pPrevs[1] == Lane ? -2 : 0;
|
|
}
|
|
|
|
} // namespace
|
|
|
|
// puts provided shapes in the section of the scene holding specified point
|
|
void owned_shapes::show(std::vector<scene::shape_node> Shapes, glm::dvec3 const &Location)
|
|
{
|
|
if (m_section != nullptr || Shapes.empty() || simulation::Region == nullptr || false == simulation::Region->point_inside(Location))
|
|
{
|
|
return;
|
|
}
|
|
auto §ion{simulation::Region->section(Location)};
|
|
// the rest of the section has to be built by now, or it'd count our shapes as waiting for it too
|
|
section.create_geometry();
|
|
if (m_bank.bank == 0 && m_bank.chunk == 0)
|
|
{
|
|
m_bank = GfxRenderer->Create_Bank();
|
|
ownedbanks.emplace(m_bank.bank);
|
|
}
|
|
for (auto &shape : Shapes)
|
|
{
|
|
// shapes held by a section are drawn relative to its centre
|
|
shape.origin(section.m_area.center);
|
|
auto const centre{shape.data().area.center};
|
|
auto const radius{shape.radius()};
|
|
shape.create_geometry(m_bank);
|
|
m_geometry.emplace_back(shape.data().geometry);
|
|
section.m_shapes.emplace_back(std::move(shape));
|
|
// the section may need to reach further to keep the shape from being culled at its edges
|
|
section.m_area.radius = std::max(section.m_area.radius, static_cast<float>(glm::length(section.m_area.center - centre) + radius));
|
|
}
|
|
m_section = §ion;
|
|
}
|
|
|
|
// takes the shapes back
|
|
void owned_shapes::hide()
|
|
{
|
|
if (m_section == nullptr)
|
|
{
|
|
return;
|
|
}
|
|
// our shapes are told from the others by their geometry. the renderer reclaims the chunks once they're no longer drawn
|
|
auto &shapes{m_section->m_shapes};
|
|
shapes.erase(std::remove_if(shapes.begin(), shapes.end(),
|
|
[this](scene::shape_node const &Shape) {
|
|
auto const handle{Shape.data().geometry};
|
|
return std::any_of(m_geometry.begin(), m_geometry.end(), [&handle](gfx::geometry_handle const &Own) { return Own.bank == handle.bank && Own.chunk == handle.chunk; });
|
|
}),
|
|
shapes.end());
|
|
m_geometry.clear();
|
|
m_section = nullptr;
|
|
}
|
|
|
|
// true if specified geometry was put in the scene by any object of this class
|
|
bool owned_shapes::owns(gfx::geometry_handle const &Geometry)
|
|
{
|
|
return Geometry.bank != 0 && ownedbanks.count(Geometry.bank) != 0;
|
|
}
|
|
|
|
// puts geometry of the road in the scene as shapes of its own, which can be taken back
|
|
void road_node::show()
|
|
{
|
|
if (m_merged || m_shapes.shown())
|
|
{
|
|
return;
|
|
}
|
|
m_shapes.show(create_shapes(), location());
|
|
}
|
|
|
|
// takes back geometry put in the scene by show()
|
|
void road_node::hide()
|
|
{
|
|
m_shapes.hide();
|
|
}
|
|
|
|
// brings the content to a usable form
|
|
void junction_node::state::normalize()
|
|
{
|
|
for (auto &arm : arms)
|
|
{
|
|
arm.incoming = std::clamp(arm.incoming, 0, 8);
|
|
arm.outgoing = std::clamp(arm.outgoing, 0, 8);
|
|
arm.width = std::max(1.f, arm.width);
|
|
arm.median = (arm.incoming > 0 && arm.outgoing > 0 ? std::clamp(arm.median, 0.f, 100.f) : 0.f);
|
|
arm.crosswalk = std::clamp(arm.crosswalk, 0.f, 20.f);
|
|
for (int end = 0; end < 2; ++end)
|
|
{
|
|
arm.bank.width[end] = std::clamp(arm.bank.width[end], 0.f, 100.f);
|
|
arm.bank.drop[end] = std::clamp(arm.bank.drop[end], -100.f, 100.f);
|
|
}
|
|
arm.direction = (glm::length(arm.direction) > 1e-6 ? glm::normalize(arm.direction) : glm::dvec2{0.0, 1.0});
|
|
if (arm.turns.size() > static_cast<std::size_t>(arm.incoming))
|
|
{
|
|
arm.turns.resize(static_cast<std::size_t>(arm.incoming));
|
|
}
|
|
for (auto &turns : arm.turns)
|
|
{
|
|
turns &= (turn_left | turn_straight | turn_right);
|
|
}
|
|
}
|
|
side.width = std::max(0.f, side.width);
|
|
kerbheight = std::max(0.f, kerbheight);
|
|
kerbwidth = std::clamp(kerbwidth, 0.05f, 2.f);
|
|
if (kerbmaterial.empty())
|
|
{
|
|
kerbmaterial = "none";
|
|
}
|
|
if (bankmaterial.empty())
|
|
{
|
|
bankmaterial = "none";
|
|
}
|
|
if (medianmaterial.empty())
|
|
{
|
|
medianmaterial = "none";
|
|
}
|
|
slope = glm::max(slope, glm::vec2{0.f});
|
|
if (texturelength < 0.01f)
|
|
{
|
|
texturelength = 4.f;
|
|
}
|
|
if (surface.empty())
|
|
{
|
|
surface = "none";
|
|
}
|
|
static std::array<std::string, 7> const environments{"flat", "mountains", "mountain", "canyon", "tunnel", "bridge", "bank"};
|
|
if (std::find(environments.begin(), environments.end(), environment) == environments.end())
|
|
{
|
|
environment = "flat";
|
|
}
|
|
}
|
|
|
|
// width of the road at specified arm
|
|
double junction_node::state::arm_width(std::size_t const Arm) const
|
|
{
|
|
return Arm < arms.size() ? static_cast<double>(arms[Arm].incoming + arms[Arm].outgoing) * arms[Arm].width + arms[Arm].median : 0.0;
|
|
}
|
|
|
|
// where a lane of an arm meets the junction; the lanes of each kind are counted from the middle of the road, starting with 1
|
|
glm::dvec3 junction_node::state::lane_point(std::size_t const Arm, bool const Incoming, int const Lane) const
|
|
{
|
|
auto const &arm{arms[Arm]};
|
|
// seen from the junction the traffic coming in is on the left side of the road, and the one going out on the right
|
|
auto const divide{0.5 * arm_width(Arm) - static_cast<double>(arm.incoming) * arm.width};
|
|
// what keeps the two directions apart lies past the lanes coming in
|
|
auto const offset{Incoming ? divide + (Lane - 0.5) * arm.width : divide - arm.median - (Lane - 0.5) * arm.width};
|
|
return arm.position + flat(left_of(arm.direction)) * offset;
|
|
}
|
|
|
|
// arms in the order they're met going around the junction
|
|
std::vector<std::size_t> junction_node::state::arm_order() const
|
|
{
|
|
std::vector<std::size_t> order(arms.size());
|
|
for (std::size_t idx = 0; idx < order.size(); ++idx)
|
|
{
|
|
order[idx] = idx;
|
|
}
|
|
// the order goes from the z axis towards the x axis, which makes triangles spanned from the centre face up
|
|
std::sort(order.begin(), order.end(), [this](std::size_t const Left, std::size_t const Right) { return std::atan2(arms[Left].direction.x, arms[Left].direction.y) < std::atan2(arms[Right].direction.x, arms[Right].direction.y); });
|
|
return order;
|
|
}
|
|
|
|
// edge of the surface: ends of the arms joined with rounded corners, going around the junction
|
|
std::vector<glm::dvec3> junction_node::state::outline(std::vector<std::vector<glm::dvec3>> *Corners) const
|
|
{
|
|
std::vector<glm::dvec3> points;
|
|
auto const order{arm_order()};
|
|
for (std::size_t idx = 0; idx < order.size(); ++idx)
|
|
{
|
|
auto const &arm{arms[order[idx]]};
|
|
auto const &next{arms[order[(idx + 1) % order.size()]]};
|
|
auto const halfwidth{0.5 * arm_width(order[idx])};
|
|
auto const nexthalfwidth{0.5 * arm_width(order[(idx + 1) % order.size()])};
|
|
// the end of the arm, then the corner leading to the next one
|
|
auto const right{arm.position - flat(left_of(arm.direction)) * halfwidth};
|
|
auto const left{arm.position + flat(left_of(arm.direction)) * halfwidth};
|
|
auto const nextright{next.position - flat(left_of(next.direction)) * nexthalfwidth};
|
|
points.emplace_back(right);
|
|
points.emplace_back(left);
|
|
// the corner is bent towards the point where the edges of both roads would meet, if there's a reasonable one
|
|
auto control{0.5 * (left + nextright)};
|
|
auto const cross{arm.direction.x * next.direction.y - arm.direction.y * next.direction.x};
|
|
if (std::abs(cross) > 0.05)
|
|
{
|
|
// left - arm.direction * t == nextright - next.direction * s
|
|
glm::dvec2 const delta{nextright.x - left.x, nextright.z - left.z};
|
|
auto const t{-(delta.x * next.direction.y - delta.y * next.direction.x) / cross};
|
|
auto const s{-(delta.x * arm.direction.y - delta.y * arm.direction.x) / cross};
|
|
if (t > 0.0 && s > 0.0 && t < 100.0 && s < 100.0)
|
|
{
|
|
control = left - flat(arm.direction) * t;
|
|
control.y = 0.5 * (left.y + nextright.y);
|
|
}
|
|
}
|
|
std::vector<glm::dvec3> corner{left};
|
|
for (int step = 1; step < corner_steps; ++step)
|
|
{
|
|
auto const t{static_cast<double>(step) / corner_steps};
|
|
auto const point{(1.0 - t) * (1.0 - t) * left + 2.0 * (1.0 - t) * t * control + t * t * nextright};
|
|
points.emplace_back(point);
|
|
corner.emplace_back(point);
|
|
}
|
|
corner.emplace_back(nextright);
|
|
if (Corners != nullptr)
|
|
{
|
|
Corners->emplace_back(std::move(corner));
|
|
}
|
|
}
|
|
return points;
|
|
}
|
|
|
|
junction_node::junction_node(scene::node_data const &Nodedata) : basic_node(Nodedata) {}
|
|
|
|
// restores content of the node from provided input stream; reads up to and including the closing 'endjunction'
|
|
void junction_node::import(cParser &Input, glm::dvec3 const &Offset)
|
|
{
|
|
auto const label{m_name.empty() ? std::string{"unnamed junction"} : "junction \"" + m_name + "\""};
|
|
|
|
m_state = state{};
|
|
Input.getTokens(3);
|
|
Input >> m_state.centre.x >> m_state.centre.y >> m_state.centre.z;
|
|
m_state.centre += Offset;
|
|
std::vector<int> stoplines;
|
|
// what's said about the arms may come ahead of them, so it waits until all is read
|
|
std::vector<std::pair<int, std::string>> priorities;
|
|
std::vector<std::pair<int, float>> medians;
|
|
std::vector<std::pair<int, float>> crosswalks;
|
|
std::vector<std::pair<int, road_node::bank_data>> banks;
|
|
struct turn_property
|
|
{
|
|
int arm;
|
|
int lane;
|
|
std::string ways;
|
|
};
|
|
std::vector<turn_property> turns;
|
|
|
|
auto token{Input.getToken<std::string>()};
|
|
while (false == token.empty() && token != "endjunction")
|
|
{
|
|
if (token == "arm")
|
|
{
|
|
// arm <position> <direction x z> <lanes in> <lanes out> <lane width>
|
|
arm_data arm;
|
|
Input.getTokens(3);
|
|
Input >> arm.position.x >> arm.position.y >> arm.position.z;
|
|
arm.position += Offset;
|
|
Input.getTokens(2);
|
|
Input >> arm.direction.x >> arm.direction.y;
|
|
Input.getTokens(3);
|
|
Input >> arm.incoming >> arm.outgoing >> arm.width;
|
|
m_state.arms.emplace_back(arm);
|
|
}
|
|
else if (token == "surface")
|
|
{
|
|
m_state.surface = Input.getToken<std::string>();
|
|
replace_slashes(m_state.surface);
|
|
}
|
|
else if (token == "texlength")
|
|
{
|
|
Input.getTokens();
|
|
Input >> m_state.texturelength;
|
|
}
|
|
else if (token == "markings")
|
|
{
|
|
auto const colour{Input.getToken<std::string>()};
|
|
m_state.markings = (colour == "white" ? road_node::marking_colour::white : colour == "orange" ? road_node::marking_colour::orange : road_node::marking_colour::none);
|
|
}
|
|
else if (token == "side")
|
|
{
|
|
// side <none|shoulder|sidewalk> <width> <material>
|
|
auto const type{Input.getToken<std::string>()};
|
|
Input.getTokens();
|
|
Input >> m_state.side.width;
|
|
m_state.side.material = Input.getToken<std::string>();
|
|
replace_slashes(m_state.side.material);
|
|
m_state.side.type = (type == "shoulder" ? road_node::side_type::shoulder : type == "sidewalk" ? road_node::side_type::sidewalk : road_node::side_type::none);
|
|
if (type != "shoulder" && type != "sidewalk" && type != "none")
|
|
{
|
|
ErrorLog("Bad junction: unknown kind of side \"" + type + "\" defined for " + label);
|
|
}
|
|
}
|
|
else if (token == "kerb")
|
|
{
|
|
Input.getTokens();
|
|
Input >> m_state.kerbheight;
|
|
}
|
|
else if (token == "slope")
|
|
{
|
|
// slope <width> <drop>
|
|
Input.getTokens(2);
|
|
Input >> m_state.slope.x >> m_state.slope.y;
|
|
}
|
|
else if (token == "kerbs")
|
|
{
|
|
// kerbs <width> <material>
|
|
m_state.kerbs = true;
|
|
Input.getTokens();
|
|
Input >> m_state.kerbwidth;
|
|
m_state.kerbmaterial = Input.getToken<std::string>();
|
|
replace_slashes(m_state.kerbmaterial);
|
|
}
|
|
else if (token == "stopline")
|
|
{
|
|
// stopline <number of an arm, counted from 1>; the arms it's for may come later, so the numbers wait
|
|
int number{0};
|
|
Input.getTokens();
|
|
Input >> number;
|
|
stoplines.emplace_back(number);
|
|
}
|
|
else if (token == "priority")
|
|
{
|
|
// priority <number of an arm, counted from 1> <none|main|yield|stop>
|
|
int number{0};
|
|
Input.getTokens();
|
|
Input >> number;
|
|
priorities.emplace_back(number, Input.getToken<std::string>());
|
|
}
|
|
else if (token == "crosswalk")
|
|
{
|
|
// crosswalk <number of an arm, counted from 1> <length>
|
|
int number{0};
|
|
float length{0.f};
|
|
Input.getTokens(2);
|
|
Input >> number >> length;
|
|
crosswalks.emplace_back(number, length);
|
|
}
|
|
else if (token == "cornerbank")
|
|
{
|
|
// cornerbank <number of an arm> <width at that road> <drop at that road> <width at the next road> <drop at the next road>
|
|
int number{0};
|
|
road_node::bank_data bank;
|
|
bank.set = true;
|
|
Input.getTokens(5);
|
|
Input >> number >> bank.width[0] >> bank.drop[0] >> bank.width[1] >> bank.drop[1];
|
|
banks.emplace_back(number, bank);
|
|
}
|
|
else if (token == "bankmaterial")
|
|
{
|
|
m_state.bankmaterial = Input.getToken<std::string>();
|
|
replace_slashes(m_state.bankmaterial);
|
|
}
|
|
else if (token == "median")
|
|
{
|
|
// median <gap|painted|island> <material>
|
|
auto const type{Input.getToken<std::string>()};
|
|
m_state.median = (type == "gap" ? road_node::median_type::gap : type == "island" ? road_node::median_type::island : road_node::median_type::painted);
|
|
m_state.medianmaterial = Input.getToken<std::string>();
|
|
replace_slashes(m_state.medianmaterial);
|
|
}
|
|
else if (token == "armmedian")
|
|
{
|
|
// armmedian <number of an arm, counted from 1> <width>
|
|
int number{0};
|
|
float width{0.f};
|
|
Input.getTokens(2);
|
|
Input >> number >> width;
|
|
medians.emplace_back(number, width);
|
|
}
|
|
else if (token == "turns")
|
|
{
|
|
// turns <number of an arm> <lane leading in, counted from the middle of the road> <letters out of l, s, r>
|
|
turn_property property;
|
|
property.arm = 0;
|
|
property.lane = 0;
|
|
Input.getTokens(2);
|
|
Input >> property.arm >> property.lane;
|
|
property.ways = Input.getToken<std::string>();
|
|
turns.emplace_back(property);
|
|
}
|
|
else if (token == "velocity")
|
|
{
|
|
Input.getTokens();
|
|
Input >> m_state.velocity;
|
|
}
|
|
else if (token == "friction")
|
|
{
|
|
Input.getTokens();
|
|
Input >> m_state.friction;
|
|
}
|
|
else if (token == "environment")
|
|
{
|
|
m_state.environment = Input.getToken<std::string>();
|
|
}
|
|
else
|
|
{
|
|
ErrorLog("Bad junction: unknown property: \"" + token + "\" defined for " + label);
|
|
}
|
|
token = Input.getToken<std::string>();
|
|
}
|
|
for (auto const number : stoplines)
|
|
{
|
|
if (number < 1 || number > static_cast<int>(m_state.arms.size()))
|
|
{
|
|
ErrorLog("Bad junction: " + label + " has no arm " + std::to_string(number) + " to put a stop line at");
|
|
continue;
|
|
}
|
|
m_state.arms[number - 1].stopline = true;
|
|
}
|
|
for (auto const &entry : medians)
|
|
{
|
|
if (entry.first < 1 || entry.first > static_cast<int>(m_state.arms.size()))
|
|
{
|
|
ErrorLog("Bad junction: " + label + " has no arm " + std::to_string(entry.first) + " to set the median for");
|
|
continue;
|
|
}
|
|
m_state.arms[entry.first - 1].median = entry.second;
|
|
}
|
|
for (auto const &entry : crosswalks)
|
|
{
|
|
if (entry.first < 1 || entry.first > static_cast<int>(m_state.arms.size()))
|
|
{
|
|
ErrorLog("Bad junction: " + label + " has no arm " + std::to_string(entry.first) + " to paint a pedestrian crossing at");
|
|
continue;
|
|
}
|
|
m_state.arms[entry.first - 1].crosswalk = entry.second;
|
|
}
|
|
for (auto const &entry : banks)
|
|
{
|
|
if (entry.first < 1 || entry.first > static_cast<int>(m_state.arms.size()))
|
|
{
|
|
ErrorLog("Bad junction: " + label + " has no arm " + std::to_string(entry.first) + " to set the bank for");
|
|
continue;
|
|
}
|
|
m_state.arms[entry.first - 1].bank = entry.second;
|
|
}
|
|
for (auto const &entry : priorities)
|
|
{
|
|
if (entry.first < 1 || entry.first > static_cast<int>(m_state.arms.size()))
|
|
{
|
|
ErrorLog("Bad junction: " + label + " has no arm " + std::to_string(entry.first) + " to set the right of way for");
|
|
continue;
|
|
}
|
|
auto &priority{m_state.arms[entry.first - 1].priority};
|
|
priority = (entry.second == "main" ? right_of_way::priority : entry.second == "yield" ? right_of_way::yield : entry.second == "stop" ? right_of_way::stop : right_of_way::none);
|
|
if (entry.second != "main" && entry.second != "yield" && entry.second != "stop" && entry.second != "none")
|
|
{
|
|
ErrorLog("Bad junction: unknown right of way \"" + entry.second + "\" defined for " + label);
|
|
}
|
|
}
|
|
for (auto const &entry : turns)
|
|
{
|
|
if (entry.arm < 1 || entry.arm > static_cast<int>(m_state.arms.size()) || entry.lane < 1 || entry.lane > m_state.arms[entry.arm - 1].incoming)
|
|
{
|
|
ErrorLog("Bad junction: " + label + " has no lane " + std::to_string(entry.lane) + " leading in at arm " + std::to_string(entry.arm));
|
|
continue;
|
|
}
|
|
auto &lanes{m_state.arms[entry.arm - 1].turns};
|
|
lanes.resize(std::max(lanes.size(), static_cast<std::size_t>(entry.lane)), 0);
|
|
auto const has = [&entry](char const Way) { return entry.ways.find(Way) != std::string::npos; };
|
|
lanes[entry.lane - 1] = (has('l') ? turn_left : 0) | (has('s') ? turn_straight : 0) | (has('r') ? turn_right : 0);
|
|
}
|
|
if (m_state.arms.size() < 2 || m_state.arms.size() > 4)
|
|
{
|
|
ErrorLog("Bad junction: " + label + " has " + std::to_string(m_state.arms.size()) + " arms, it takes 2 to 4");
|
|
if (m_state.arms.size() > 4)
|
|
{
|
|
m_state.arms.resize(4);
|
|
}
|
|
}
|
|
m_state.normalize();
|
|
location(m_state.centre);
|
|
}
|
|
|
|
void junction_node::define(state const &State)
|
|
{
|
|
m_state = State;
|
|
m_state.normalize();
|
|
location(m_state.centre);
|
|
m_area.radius = -1.f;
|
|
}
|
|
|
|
// a junction of two roads is a stretch where a road changes its lanes, which a road can do by itself
|
|
bool junction_node::as_road(road_node::state &Road) const
|
|
{
|
|
auto const &arms{m_state.arms};
|
|
if (arms.size() != 2)
|
|
{
|
|
return false;
|
|
}
|
|
auto const &from{arms[0]};
|
|
auto const &to{arms[1]};
|
|
auto const span{glm::distance(from.position, to.position)};
|
|
if (span < 0.1)
|
|
{
|
|
return false;
|
|
}
|
|
road_node::state road;
|
|
// the axis is the way from the first road to the second, which leaves and joins them the way they go
|
|
road.axis.points[segment_data::point::start] = from.position;
|
|
road.axis.points[segment_data::point::control1] = glm::dvec3{0.0} - flat(from.direction) * (0.39 * span);
|
|
road.axis.points[segment_data::point::control2] = glm::dvec3{0.0} - flat(to.direction) * (0.39 * span);
|
|
road.axis.points[segment_data::point::end] = to.position;
|
|
// at the first road the lanes leading into the junction go the way the axis does, at the second one it's the lanes leading out of it
|
|
road.lanewidth = from.width;
|
|
road.velocity = m_state.velocity;
|
|
road.lanes_between(from.incoming, from.outgoing, to.outgoing, to.incoming);
|
|
road.taper = {1.f, from.width > 0.f ? to.width / from.width : 1.f};
|
|
road.median.type = m_state.median;
|
|
road.median.material = m_state.medianmaterial;
|
|
road.median.width = {from.median, to.median};
|
|
road.surface = m_state.surface;
|
|
road.texturelength = m_state.texturelength;
|
|
road.markings = m_state.markings;
|
|
road.sides = {m_state.side, m_state.side};
|
|
road.kerbs = {m_state.kerbs, m_state.kerbs};
|
|
road.kerbwidth = m_state.kerbwidth;
|
|
road.kerbmaterial = m_state.kerbmaterial;
|
|
road.kerbheight = m_state.kerbheight;
|
|
road.slope = m_state.slope;
|
|
// the bank of the corner which starts at the first road runs along the right edge. the one which starts at the second road
|
|
// runs along the left edge, the other way
|
|
road.banks[1] = from.bank;
|
|
road.banks[0] = to.bank;
|
|
std::swap(road.banks[0].width[0], road.banks[0].width[1]);
|
|
std::swap(road.banks[0].drop[0], road.banks[0].drop[1]);
|
|
road.bankmaterial = m_state.bankmaterial;
|
|
road.friction = m_state.friction;
|
|
road.sounddistance = m_state.sounddistance;
|
|
road.quality = m_state.quality;
|
|
road.environment = m_state.environment;
|
|
road.normalize();
|
|
Road = road;
|
|
return true;
|
|
}
|
|
|
|
// makes paths leading through the junction, between the lanes of the roads attached to it at the moment
|
|
void junction_node::create_links()
|
|
{
|
|
m_movements.clear();
|
|
auto const &arms{m_state.arms};
|
|
// lanes of the roads attached to the arms; a road is attached if one of its ends is where the arm is
|
|
struct arm_lanes
|
|
{
|
|
std::vector<TTrack *> incoming;
|
|
std::vector<TTrack *> outgoing;
|
|
float weight{100.f}; // how willing the drivers are to leave by the road
|
|
};
|
|
std::vector<arm_lanes> lanes(arms.size());
|
|
for (std::size_t arm = 0; arm < arms.size(); ++arm)
|
|
{
|
|
lanes[arm].incoming.assign(static_cast<std::size_t>(arms[arm].incoming), nullptr);
|
|
lanes[arm].outgoing.assign(static_cast<std::size_t>(arms[arm].outgoing), nullptr);
|
|
for (auto const *road : simulation::Roads.sequence())
|
|
{
|
|
if (road == nullptr || road->m_editorremoved)
|
|
{
|
|
continue;
|
|
}
|
|
auto const &layout{road->definition()};
|
|
for (auto const atend : {false, true})
|
|
{
|
|
if (glm::distance(layout.axis.points[atend ? segment_data::point::end : segment_data::point::start], arms[arm].position) > junction_reach)
|
|
{
|
|
continue;
|
|
}
|
|
lanes[arm].weight = layout.weight;
|
|
// the lanes heading for this end of the road lead into the junction, the others lead out of it
|
|
for (int lane = 1; lane <= arms[arm].incoming; ++lane)
|
|
{
|
|
// the road may have other lanes at its other end; it's the ones it has here which count
|
|
auto const index{layout.lane_index((atend ? "f" : "b") + std::to_string(lane))};
|
|
auto *track{index >= 0 ? road->lane_track(static_cast<std::size_t>(index), atend ? 1 : 0) : nullptr};
|
|
if (track != nullptr && glm::distance(glm::dvec3{track->CurrentSegment()->FastGetPoint_1()}, m_state.lane_point(arm, true, lane)) < junction_fit)
|
|
{
|
|
lanes[arm].incoming[lane - 1] = track;
|
|
}
|
|
}
|
|
for (int lane = 1; lane <= arms[arm].outgoing; ++lane)
|
|
{
|
|
auto const index{layout.lane_index((atend ? "b" : "f") + std::to_string(lane))};
|
|
auto *track{index >= 0 ? road->lane_track(static_cast<std::size_t>(index), atend ? 1 : 0) : nullptr};
|
|
if (track != nullptr && glm::distance(glm::dvec3{track->CurrentSegment()->FastGetPoint_0()}, m_state.lane_point(arm, false, lane)) < junction_fit)
|
|
{
|
|
lanes[arm].outgoing[lane - 1] = track;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
enum class way
|
|
{
|
|
left,
|
|
straight,
|
|
right
|
|
};
|
|
struct exit_data
|
|
{
|
|
std::size_t arm;
|
|
double turn;
|
|
way kind;
|
|
TTrack *track;
|
|
};
|
|
std::ostringstream text;
|
|
text.precision(std::numeric_limits<double>::digits10);
|
|
auto const write_point = [&text](glm::dvec3 const &Point) { text << Point.x << ' ' << Point.y << ' ' << Point.z << ' '; };
|
|
|
|
for (std::size_t arm = 0; arm < arms.size(); ++arm)
|
|
{
|
|
auto const heading{-arms[arm].direction};
|
|
// the other arms with a road to leave by, from the leftmost to the rightmost
|
|
std::vector<exit_data> exits;
|
|
for (std::size_t other = 0; other < arms.size(); ++other)
|
|
{
|
|
if (other == arm || std::all_of(lanes[other].outgoing.begin(), lanes[other].outgoing.end(), [](TTrack const *Track) { return Track == nullptr; }))
|
|
{
|
|
continue;
|
|
}
|
|
exits.push_back({other, turn_angle(heading, arms[other].direction), way::straight, nullptr});
|
|
}
|
|
std::sort(exits.begin(), exits.end(), [](exit_data const &Left, exit_data const &Right) { return Left.turn > Right.turn; });
|
|
if (exits.size() == 3)
|
|
{
|
|
exits[0].kind = way::left;
|
|
exits[2].kind = way::right;
|
|
}
|
|
else
|
|
{
|
|
auto const sideways{glm::radians(50.0)};
|
|
for (auto &exit : exits)
|
|
{
|
|
exit.kind = (exit.turn > sideways ? way::left : exit.turn < -sideways ? way::right : way::straight);
|
|
}
|
|
if (exits.size() == 2 && exits[0].kind == exits[1].kind)
|
|
{
|
|
// two ways of the same kind are told apart by which one is more to the left
|
|
if (exits[0].kind == way::right)
|
|
{
|
|
exits[0].kind = way::straight;
|
|
}
|
|
else if (exits[0].kind == way::left)
|
|
{
|
|
exits[1].kind = way::straight;
|
|
}
|
|
else
|
|
{
|
|
exits[0].kind = way::left;
|
|
exits[1].kind = way::right;
|
|
}
|
|
}
|
|
}
|
|
auto const lanecount{static_cast<int>(lanes[arm].incoming.size())};
|
|
for (int lane = 1; lane <= lanecount; ++lane)
|
|
{
|
|
auto *entry{lanes[arm].incoming[lane - 1]};
|
|
if (entry == nullptr)
|
|
{
|
|
continue;
|
|
}
|
|
// with more lanes than one the inner lane takes the left turns, the outer one the right turns, and all go straight;
|
|
// unless the scenery says which ways the lane can be left by
|
|
auto const turns{static_cast<std::size_t>(lane - 1) < arms[arm].turns.size() ? arms[arm].turns[lane - 1] : 0};
|
|
std::vector<exit_data> ways;
|
|
for (auto const &exit : exits)
|
|
{
|
|
auto const allowed{turns != 0 ? (turns & (exit.kind == way::left ? turn_left : exit.kind == way::right ? turn_right : turn_straight)) != 0 :
|
|
lanecount == 1 || exit.kind == way::straight || (exit.kind == way::left && lane == 1) || (exit.kind == way::right && lane == lanecount)};
|
|
if (allowed)
|
|
{
|
|
ways.emplace_back(exit);
|
|
}
|
|
}
|
|
if (ways.empty())
|
|
{
|
|
ways = exits;
|
|
}
|
|
for (auto &exit : ways)
|
|
{
|
|
// the lane of the same number on the road to leave by, or the nearest one there is
|
|
auto const &candidates{lanes[exit.arm].outgoing};
|
|
for (int shift = 0; shift < static_cast<int>(candidates.size()) && exit.track == nullptr; ++shift)
|
|
{
|
|
for (auto const index : {lane - 1 - shift, lane - 1 + shift})
|
|
{
|
|
if (index >= 0 && index < static_cast<int>(candidates.size()) && candidates[index] != nullptr)
|
|
{
|
|
exit.track = candidates[index];
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
if (exit.track == nullptr)
|
|
{
|
|
exit.track = candidates.back();
|
|
}
|
|
}
|
|
ways.erase(std::remove_if(ways.begin(), ways.end(), [](exit_data const &Exit) { return Exit.track == nullptr; }), ways.end());
|
|
if (ways.empty())
|
|
{
|
|
continue;
|
|
}
|
|
if (ways.size() == 3)
|
|
{
|
|
// the legacy crossroads has the way straight ahead at its second point, the left one at the third and the right one at the fourth
|
|
std::swap(ways[0], ways[1]);
|
|
}
|
|
if (exits.size() == 1 && lane == lanecount)
|
|
{
|
|
// where the only road to leave by has more lanes than the one coming in, the road gets wider: the lanes it gains
|
|
// are entered from the outermost lane. a path has up to three ways out, so that's two lanes gained at most
|
|
auto const &candidates{lanes[exits[0].arm].outgoing};
|
|
for (auto extra = static_cast<std::size_t>(lanecount); extra < candidates.size() && ways.size() < 3; ++extra)
|
|
{
|
|
if (candidates[extra] != nullptr && candidates[extra] != ways.front().track)
|
|
{
|
|
auto way{ways.front()};
|
|
way.track = candidates[extra];
|
|
ways.emplace_back(way);
|
|
}
|
|
}
|
|
}
|
|
|
|
// shape of the ways: each leaves the lane coming in the way that lane goes, and joins the lane going out the way that one goes
|
|
glm::dvec3 const start{entry->CurrentSegment()->FastGetPoint_1()};
|
|
std::vector<glm::dvec3> ends;
|
|
std::vector<glm::dvec3> endcontrols;
|
|
double reach{0.0};
|
|
for (auto const &exit : ways)
|
|
{
|
|
glm::dvec3 const end{exit.track->CurrentSegment()->FastGetPoint_0()};
|
|
auto const span{glm::distance(start, end)};
|
|
ends.emplace_back(end);
|
|
// the slopes of the lanes are carried on, so a junction on a hill doesn't make a step
|
|
endcontrols.emplace_back(-(flat(arms[exit.arm].direction) + up * lane_grade(*exit.track, false)) * (0.39 * span));
|
|
reach += 0.39 * span / ways.size();
|
|
}
|
|
auto const startcontrol{(flat(heading) + up * lane_grade(*entry, true)) * reach};
|
|
gate_data gate;
|
|
gate.arm = arm;
|
|
gate.lane = lane;
|
|
gate.entry = entry;
|
|
gate.line = start;
|
|
// what a driver calls each way, once they picked it: the number of the path of the crossroads it's on, negative if it's taken against the path
|
|
int const codes2[]{1, -2};
|
|
int const codes3[]{1, 5, -4};
|
|
for (std::size_t idx = 0; idx < ways.size(); ++idx)
|
|
{
|
|
segment_data movement;
|
|
movement.points[segment_data::point::start] = start;
|
|
movement.points[segment_data::point::control1] = startcontrol;
|
|
movement.points[segment_data::point::control2] = endcontrols[idx];
|
|
movement.points[segment_data::point::end] = ends[idx];
|
|
m_movements.emplace_back(movement);
|
|
way_data route;
|
|
route.exit = ways[idx].arm;
|
|
route.kind = (ways[idx].kind == way::left ? turn_left : ways[idx].kind == way::right ? turn_right : turn_straight);
|
|
route.code = (ways.size() == 3 ? codes3[idx] : ways.size() == 2 ? codes2[idx] : 0);
|
|
route.track = ways[idx].track;
|
|
route.path = movement;
|
|
gate.ways.emplace_back(route);
|
|
}
|
|
|
|
text.str("");
|
|
text << (ways.size() == 1 ? "road " : "cross ") << glm::distance(start, ends[0]) << ' ' << arms[arm].width << ' ' << m_state.friction << ' ' << m_state.sounddistance << ' ' << m_state.quality << " 0 " << m_state.environment << " unvis ";
|
|
// first path: from the lane coming in to the first way out
|
|
write_point(start);
|
|
text << "0 ";
|
|
write_point(startcontrol);
|
|
write_point(endcontrols[0]);
|
|
write_point(ends[0]);
|
|
text << "0 0 ";
|
|
if (ways.size() == 2)
|
|
{
|
|
// second path of a crossroads of three roads starts where the first one does
|
|
write_point(start);
|
|
text << "0 ";
|
|
write_point(startcontrol);
|
|
write_point(endcontrols[1]);
|
|
write_point(ends[1]);
|
|
text << "0 0 ";
|
|
}
|
|
else if (ways.size() == 3)
|
|
{
|
|
// second path of a crossroads of four roads runs between its third and fourth point
|
|
write_point(ends[1]);
|
|
text << "0 ";
|
|
write_point(endcontrols[1]);
|
|
write_point(endcontrols[2]);
|
|
write_point(ends[2]);
|
|
text << "0 0 ";
|
|
}
|
|
if (m_state.velocity > 0.f)
|
|
{
|
|
text << "velocity " << m_state.velocity << ' ';
|
|
}
|
|
text << "endtrack";
|
|
auto *link{create_track(text.str(), m_links.size())};
|
|
|
|
// the path is tied to the lanes by hand: the lanes going out are shared by the paths from all the other arms,
|
|
// which is more than the automatic joining of path ends can express
|
|
if (ways.size() == 1)
|
|
{
|
|
entry->ConnectNextPrev(link, 0);
|
|
link->trNext = ways[0].track;
|
|
link->iNextDirection = 0;
|
|
if (ways[0].track->trPrev == nullptr)
|
|
{
|
|
ways[0].track->trPrev = link;
|
|
ways[0].track->iPrevDirection = 1;
|
|
}
|
|
}
|
|
else if (link->SwitchExtension != nullptr)
|
|
{
|
|
auto &extension{*link->SwitchExtension};
|
|
// the points of the crossroads are stored as: first, second, fourth, third
|
|
extension.pPrevs[0] = entry;
|
|
extension.iPrevDirection[0] = 1;
|
|
extension.pNexts[0] = ways[0].track;
|
|
extension.iNextDirection[0] = 0;
|
|
extension.pPrevs[1] = (ways.size() == 3 ? ways[2].track : ways[1].track);
|
|
extension.iPrevDirection[1] = 0;
|
|
extension.pNexts[1] = (ways.size() == 3 ? ways[1].track : nullptr);
|
|
extension.iNextDirection[1] = 0;
|
|
link->Switch(0);
|
|
entry->trNext = link;
|
|
entry->iNextDirection = 0;
|
|
// odds of each way being picked go by how willing the drivers are to take the road it leads to.
|
|
// the routes of a crossroads are numbered: left, right, straight ahead
|
|
if (ways.size() == 3)
|
|
{
|
|
link->m_routeweights = {lanes[ways[1].arm].weight, lanes[ways[2].arm].weight, lanes[ways[0].arm].weight};
|
|
}
|
|
else
|
|
{
|
|
link->m_routeweights = {lanes[ways[0].arm].weight, lanes[ways[1].arm].weight, 0.f};
|
|
}
|
|
// the lanes going out get to know one of the paths leading to them, for whatever goes backwards
|
|
int const ends2[]{1, 2};
|
|
int const ends3[]{1, 3, 2};
|
|
for (std::size_t idx = 0; idx < ways.size(); ++idx)
|
|
{
|
|
if (ways[idx].track->trPrev == nullptr)
|
|
{
|
|
ways[idx].track->trPrev = link;
|
|
ways[idx].track->iPrevDirection = (ways.size() == 3 ? ends3[idx] : ends2[idx]);
|
|
}
|
|
}
|
|
}
|
|
m_links.emplace_back(link);
|
|
gate.link = link;
|
|
m_gates.emplace_back(std::move(gate));
|
|
}
|
|
}
|
|
create_gates();
|
|
}
|
|
|
|
// sets up what the traffic of each lane leading in is told, once the ways through are made
|
|
void junction_node::create_gates()
|
|
{
|
|
if (m_state.arms.size() < 3)
|
|
{
|
|
// where a road only changes its lanes nobody gets in the way of anybody
|
|
m_gates.clear();
|
|
return;
|
|
}
|
|
auto const point = [](segment_data const &Path, double const T) {
|
|
auto const &p0{Path.points[segment_data::point::start]};
|
|
auto const &p3{Path.points[segment_data::point::end]};
|
|
auto const p1{p0 + Path.points[segment_data::point::control1]};
|
|
auto const p2{p3 + Path.points[segment_data::point::control2]};
|
|
auto const u{1.0 - T};
|
|
auto const result{u * u * u * p0 + 3.0 * u * u * T * p1 + 3.0 * u * T * T * p2 + T * T * T * p3};
|
|
return glm::dvec2{result.x, result.z};
|
|
};
|
|
int const samples{10};
|
|
for (std::size_t index = 0; index < m_gates.size(); ++index)
|
|
{
|
|
auto &gate{m_gates[index]};
|
|
// lanes the vehicles heading for the junction are on: the one leading in, and the same lane of the pieces before it
|
|
gate.approach.emplace_back(gate.entry);
|
|
gate.wishes.emplace_back(0);
|
|
auto reach{glm::distance(glm::dvec3{gate.entry->CurrentSegment()->FastGetPoint_0()}, glm::dvec3{gate.entry->CurrentSegment()->FastGetPoint_1()})};
|
|
for (auto *lane{gate.entry}; reach < gate_reach && gate.approach.size() < 16;)
|
|
{
|
|
auto *previous{lane->trPrev};
|
|
// lanes a road loses join the one which is left: the vehicles on the paths leading them here are coming this way too
|
|
if (auto const *owner{dynamic_cast<road_node const *>(lane->m_road)}; owner != nullptr)
|
|
{
|
|
for (auto *link : owner->links())
|
|
{
|
|
if (link != previous && link->trNext == lane && link->m_paths.size() == 1)
|
|
{
|
|
gate.approach.emplace_back(link);
|
|
gate.wishes.emplace_back(0);
|
|
}
|
|
}
|
|
}
|
|
auto wish{0};
|
|
if (previous != nullptr && previous->m_paths.size() > 1 && dynamic_cast<road_node const *>(previous->m_road) != nullptr)
|
|
{
|
|
// a path on which a road forks into more lanes: of the vehicles on it the ones which picked the way leading here count
|
|
wish = fork_code(*previous, lane);
|
|
if (wish == 0)
|
|
{
|
|
break;
|
|
}
|
|
}
|
|
else if (previous == nullptr || previous->trNext != lane || dynamic_cast<road_node const *>(previous->m_road) == nullptr || previous->m_paths.size() != 1)
|
|
{
|
|
break;
|
|
}
|
|
gate.approach.emplace_back(previous);
|
|
gate.wishes.emplace_back(wish);
|
|
reach += glm::distance(glm::dvec3{previous->CurrentSegment()->FastGetPoint_0()}, glm::dvec3{previous->CurrentSegment()->FastGetPoint_1()});
|
|
lane = previous;
|
|
}
|
|
// the order, found by the drivers a bit ahead of where the lane ends
|
|
if (index >= m_orders.size())
|
|
{
|
|
m_orders.emplace_back(new road_order());
|
|
m_orders.back()->m_name = m_name + ":gate" + std::to_string(m_orders.size());
|
|
}
|
|
gate.order = m_orders[index];
|
|
gate.order->m_velocity = -1.0;
|
|
gate.order->m_location = gate.line;
|
|
gate.entry->m_events2.emplace_back(gate.order->m_name, gate.order);
|
|
// ways which get in the way of each other: the ones from other roads which cross it, or lead to the same lane
|
|
for (std::size_t way = 0; way < gate.ways.size(); ++way)
|
|
{
|
|
for (std::size_t other = 0; other < m_gates.size(); ++other)
|
|
{
|
|
if (m_gates[other].arm == gate.arm)
|
|
{
|
|
continue;
|
|
}
|
|
for (std::size_t otherway = 0; otherway < m_gates[other].ways.size(); ++otherway)
|
|
{
|
|
auto const &path{gate.ways[way].path};
|
|
auto const &otherpath{m_gates[other].ways[otherway].path};
|
|
auto nearest{std::numeric_limits<double>::max()};
|
|
for (int first = 0; first <= samples; ++first)
|
|
{
|
|
for (int second = 0; second <= samples; ++second)
|
|
{
|
|
nearest = std::min(nearest, glm::distance(point(path, static_cast<double>(first) / samples), point(otherpath, static_cast<double>(second) / samples)));
|
|
}
|
|
}
|
|
if (nearest < way_clearance)
|
|
{
|
|
gate.ways[way].conflicts.emplace_back(other, otherway);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
m_scan = 0.0;
|
|
m_quiet = false;
|
|
}
|
|
|
|
// gives up the paths leading through the junction
|
|
std::vector<TTrack *> junction_node::release_links()
|
|
{
|
|
// the lanes leading in are let go of. a driver who has one of the orders in sight keeps it; it's not to hold anyone anymore
|
|
for (auto const &gate : m_gates)
|
|
{
|
|
if (gate.entry == nullptr || gate.order == nullptr)
|
|
{
|
|
continue;
|
|
}
|
|
auto &events{gate.entry->m_events2};
|
|
auto const *order{static_cast<basic_event const *>(gate.order)};
|
|
events.erase(std::remove_if(events.begin(), events.end(), [order](std::pair<std::string, basic_event *> const &Entry) { return Entry.second == order; }), events.end());
|
|
}
|
|
for (auto *order : m_orders)
|
|
{
|
|
order->m_velocity = -1.0;
|
|
}
|
|
m_gates.clear();
|
|
std::vector<TTrack *> released;
|
|
released.swap(m_links);
|
|
m_movements.clear();
|
|
return released;
|
|
}
|
|
|
|
// tells the vehicles heading for the junction whether they can drive on
|
|
void junction_node::update(double const Deltatime)
|
|
{
|
|
if (m_gates.empty())
|
|
{
|
|
return;
|
|
}
|
|
m_scan -= Deltatime;
|
|
if (m_scan > 0.0)
|
|
{
|
|
return;
|
|
}
|
|
auto const elapsed{gate_period - m_scan};
|
|
m_scan = gate_period;
|
|
|
|
// ways a vehicle is going to take, or is on: the one its driver picked, or any of them if the driver didn't pick yet
|
|
auto const ways_of = [](gate_data const &Gate, TDynamicObject *Vehicle) {
|
|
auto const all{(1u << Gate.ways.size()) - 1u};
|
|
if (Gate.ways.size() < 2)
|
|
{
|
|
return all;
|
|
}
|
|
auto const code{Vehicle->RouteWish(Gate.link)};
|
|
for (std::size_t way = 0; way < Gate.ways.size(); ++way)
|
|
{
|
|
if (Gate.ways[way].code == code)
|
|
{
|
|
return 1u << way;
|
|
}
|
|
}
|
|
return all;
|
|
};
|
|
// who's first in line on each lane leading in, and who's on the ways through
|
|
auto traffic{false};
|
|
for (auto &gate : m_gates)
|
|
{
|
|
TDynamicObject *first{nullptr};
|
|
auto nearest{std::numeric_limits<double>::max()};
|
|
for (std::size_t idx = 0; idx < gate.approach.size(); ++idx)
|
|
{
|
|
auto *lane{gate.approach[idx]};
|
|
auto const wish{idx < gate.wishes.size() ? gate.wishes[idx] : 0};
|
|
for (auto *vehicle : lane->Dynamics)
|
|
{
|
|
if (vehicle == nullptr)
|
|
{
|
|
continue;
|
|
}
|
|
if (wish != 0)
|
|
{
|
|
// on a fork: the ones which picked another lane aren't coming this way
|
|
auto const picked{vehicle->RouteWish(lane)};
|
|
if (picked != 0 && picked != wish)
|
|
{
|
|
continue;
|
|
}
|
|
}
|
|
auto const position{vehicle->GetPosition()};
|
|
auto const distance{glm::distance(glm::dvec2{position.x, position.z}, glm::dvec2{gate.line.x, gate.line.z})};
|
|
if (distance < nearest)
|
|
{
|
|
nearest = distance;
|
|
first = vehicle;
|
|
}
|
|
}
|
|
}
|
|
if (first != gate.first)
|
|
{
|
|
gate.first = first;
|
|
gate.committed = false;
|
|
gate.stopped = false;
|
|
gate.waited = 0.0;
|
|
gate.idle = 0.0;
|
|
}
|
|
gate.inside = 0;
|
|
for (auto *vehicle : gate.link->Dynamics)
|
|
{
|
|
if (vehicle != nullptr)
|
|
{
|
|
gate.inside |= ways_of(gate, vehicle);
|
|
}
|
|
}
|
|
if (first != nullptr)
|
|
{
|
|
gate.distance = nearest;
|
|
gate.speed = std::abs(first->MoverParameters->V);
|
|
gate.halflength = 0.5 * first->MoverParameters->Dim.L;
|
|
gate.taken = ways_of(gate, first);
|
|
gate.active = gate.distance < std::max(gate_zone, gate.speed * gate_gap) + gate.halflength;
|
|
}
|
|
else
|
|
{
|
|
gate.taken = 0;
|
|
gate.active = false;
|
|
gate.blocked = false;
|
|
}
|
|
traffic = traffic || first != nullptr || gate.inside != 0;
|
|
}
|
|
if (false == traffic)
|
|
{
|
|
if (false == m_quiet)
|
|
{
|
|
for (auto &gate : m_gates)
|
|
{
|
|
gate.order->m_velocity = -1.0;
|
|
}
|
|
m_quiet = true;
|
|
}
|
|
return;
|
|
}
|
|
m_quiet = false;
|
|
|
|
auto const &arms{m_state.arms};
|
|
auto const rank = [&arms](gate_data const &Gate) { return arms[Gate.arm].priority == right_of_way::priority ? 2 : arms[Gate.arm].priority == right_of_way::none ? 1 : 0; };
|
|
// true if any of the ways marked for one lane gets in the way of any marked for another
|
|
auto const clash = [this](std::size_t const Gate, unsigned const Ways, std::size_t const Other, unsigned const Otherways) {
|
|
auto const &gate{m_gates[Gate]};
|
|
for (std::size_t way = 0; way < gate.ways.size(); ++way)
|
|
{
|
|
if ((Ways & (1u << way)) == 0)
|
|
{
|
|
continue;
|
|
}
|
|
for (auto const &conflict : gate.ways[way].conflicts)
|
|
{
|
|
if (conflict.first == Other && (Otherways & (1u << conflict.second)) != 0)
|
|
{
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
return false;
|
|
};
|
|
auto const turns_left = [](gate_data const &Gate) {
|
|
if (Gate.taken == 0)
|
|
{
|
|
return false;
|
|
}
|
|
for (std::size_t way = 0; way < Gate.ways.size(); ++way)
|
|
{
|
|
if ((Gate.taken & (1u << way)) != 0 && Gate.ways[way].kind != turn_left)
|
|
{
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
};
|
|
// true if the first vehicle of one lane goes ahead of the first vehicle of another
|
|
auto const precedes = [&](gate_data const &Rival, gate_data const &Gate) {
|
|
if (rank(Rival) != rank(Gate))
|
|
{
|
|
return rank(Rival) > rank(Gate);
|
|
}
|
|
// neither has the right of way over the other: the one coming from the right goes first,
|
|
// and so does the one coming from the opposite side, if its way is turned across
|
|
auto const bearing{turn_angle(-arms[Gate.arm].direction, arms[Rival.arm].direction)};
|
|
if (bearing < -glm::radians(20.0) && bearing > -glm::radians(160.0))
|
|
{
|
|
return true;
|
|
}
|
|
return std::abs(bearing) <= glm::radians(20.0) && turns_left(Gate) && false == turns_left(Rival);
|
|
};
|
|
// the lanes are gone through from the ones with the right of way, and among these from the one waiting the longest
|
|
std::vector<std::size_t> order(m_gates.size());
|
|
for (std::size_t index = 0; index < order.size(); ++index)
|
|
{
|
|
order[index] = index;
|
|
}
|
|
std::stable_sort(order.begin(), order.end(), [&](std::size_t const Left, std::size_t const Right) {
|
|
return rank(m_gates[Left]) != rank(m_gates[Right]) ? rank(m_gates[Left]) > rank(m_gates[Right]) : m_gates[Left].waited > m_gates[Right].waited;
|
|
});
|
|
for (auto const index : order)
|
|
{
|
|
auto &gate{m_gates[index]};
|
|
if (gate.first == nullptr || false == gate.active)
|
|
{
|
|
// nobody to tell anything, or too far to be bothered
|
|
gate.blocked = false;
|
|
gate.committed = false;
|
|
gate.order->m_velocity = -1.0;
|
|
continue;
|
|
}
|
|
auto blocked{false};
|
|
for (std::size_t other = 0; other < m_gates.size() && false == blocked; ++other)
|
|
{
|
|
auto const &rival{m_gates[other]};
|
|
if (rival.arm == gate.arm)
|
|
{
|
|
continue;
|
|
}
|
|
// the ones driving through the junction, and the ones which were let in
|
|
if (rival.inside != 0 && clash(index, gate.taken, other, rival.inside))
|
|
{
|
|
blocked = true;
|
|
}
|
|
if (rival.first == nullptr || false == rival.active || false == clash(index, gate.taken, other, rival.taken))
|
|
{
|
|
continue;
|
|
}
|
|
if (rival.committed)
|
|
{
|
|
blocked = true;
|
|
}
|
|
// the ones to give way to. one which stands waiting for somebody else isn't waited for:
|
|
// it'll be told to wait for this one in turn, once this one is let in
|
|
else if (precedes(rival, gate) && false == (rival.blocked && rival.speed < 0.5))
|
|
{
|
|
blocked = true;
|
|
}
|
|
}
|
|
if (arms[gate.arm].priority == right_of_way::stop && false == gate.stopped)
|
|
{
|
|
// the stop has to be made, whatever the traffic
|
|
if (gate.speed < 0.3 && gate.distance < gate.halflength + 6.0)
|
|
{
|
|
gate.stopped = true;
|
|
}
|
|
else
|
|
{
|
|
blocked = true;
|
|
}
|
|
}
|
|
if (blocked)
|
|
{
|
|
gate.committed = false;
|
|
if (gate.speed < 0.5)
|
|
{
|
|
gate.waited += elapsed;
|
|
}
|
|
}
|
|
else if (gate.committed)
|
|
{
|
|
// a vehicle which was let in and doesn't go, for whatever reason, isn't waited for forever
|
|
gate.idle = (gate.speed < 0.5 ? gate.idle + elapsed : 0.0);
|
|
if (gate.idle > gate_patience)
|
|
{
|
|
gate.committed = false;
|
|
gate.idle = 0.0;
|
|
}
|
|
}
|
|
else if (gate.distance < gate.halflength + gate_commit)
|
|
{
|
|
gate.committed = true;
|
|
gate.idle = 0.0;
|
|
}
|
|
gate.blocked = blocked;
|
|
gate.order->m_velocity = (blocked ? 0.0 : -1.0);
|
|
}
|
|
}
|
|
|
|
// true if there's a vehicle on any path of the junction
|
|
bool junction_node::occupied() const
|
|
{
|
|
return std::any_of(m_links.begin(), m_links.end(), [](TTrack const *Track) { return Track != nullptr && false == Track->Dynamics.empty(); });
|
|
}
|
|
|
|
// geometry of a junction of two roads: a stretch of road, on which the lanes of one are led to the lanes of the other
|
|
std::vector<scene::shape_node> junction_node::create_transition_shapes() const
|
|
{
|
|
std::vector<scene::shape_node> shapes;
|
|
auto const &arms{m_state.arms};
|
|
auto const &from{arms[0]};
|
|
auto const &to{arms[1]};
|
|
// the way from the first road to the second, which leaves and joins them the way they go
|
|
auto const p0{from.position};
|
|
auto const p3{to.position};
|
|
auto const span{glm::distance(p0, p3)};
|
|
if (span < 0.1)
|
|
{
|
|
return shapes;
|
|
}
|
|
auto const p1{p0 - flat(from.direction) * (0.39 * span)};
|
|
auto const p2{p3 - flat(to.direction) * (0.39 * span)};
|
|
// edges of the two roadways as distances from that way, positive to the left of it. at the first road the lanes
|
|
// leading into the junction go the way the stretch does, at the second one it's the lanes leading out of it
|
|
struct edges
|
|
{
|
|
double right;
|
|
double forward; // edge of the roadway going along the way, on the side of the other one
|
|
double backward; // edge of the roadway going against it, on the side of the other one
|
|
double left;
|
|
double lanewidth;
|
|
};
|
|
auto const width0{m_state.arm_width(0)};
|
|
auto const width1{m_state.arm_width(1)};
|
|
edges const start{-0.5 * width0, -0.5 * width0 + from.incoming * from.width, 0.5 * width0 - from.outgoing * from.width, 0.5 * width0, from.width};
|
|
edges const end{-0.5 * width1, -0.5 * width1 + to.outgoing * to.width, 0.5 * width1 - to.incoming * to.width, 0.5 * width1, to.width};
|
|
struct section
|
|
{
|
|
glm::dvec3 position;
|
|
glm::dvec3 left;
|
|
glm::dvec3 tangent;
|
|
double station;
|
|
double fraction;
|
|
edges offsets;
|
|
};
|
|
auto const at = [&](double const T) {
|
|
section result;
|
|
auto const u{1.0 - T};
|
|
result.position = u * u * u * p0 + 3.0 * u * u * T * p1 + 3.0 * u * T * T * p2 + T * T * T * p3;
|
|
auto const direction{3.0 * u * u * (p1 - p0) + 6.0 * u * T * (p2 - p1) + 3.0 * T * T * (p3 - p2)};
|
|
glm::dvec2 const heading{direction.x, direction.z};
|
|
result.tangent = (glm::length2(direction) > 1e-12 ? glm::normalize(direction) : flat(to.direction));
|
|
result.left = flat(left_of(glm::length(heading) > 1e-9 ? glm::normalize(heading) : to.direction));
|
|
// the edges get from where they are at one road to where they are at the other the way the edges of a road which changes its width do
|
|
auto const blend{taper_progress(T)};
|
|
result.offsets = {glm::mix(start.right, end.right, blend), glm::mix(start.forward, end.forward, blend), glm::mix(start.backward, end.backward, blend), glm::mix(start.left, end.left, blend),
|
|
glm::mix(start.lanewidth, end.lanewidth, blend)};
|
|
result.station = 0.0;
|
|
result.fraction = T;
|
|
return result;
|
|
};
|
|
auto const steps{std::clamp(static_cast<int>(span / 2.0), 8, 32)};
|
|
std::vector<section> sections;
|
|
for (int idx = 0; idx <= steps; ++idx)
|
|
{
|
|
sections.emplace_back(at(static_cast<double>(idx) / steps));
|
|
if (idx > 0)
|
|
{
|
|
sections[idx].station = sections[idx - 1].station + glm::distance(sections[idx - 1].position, sections[idx].position);
|
|
}
|
|
}
|
|
auto const length{sections.back().station};
|
|
|
|
// triangles are gathered separately for each look
|
|
struct batch
|
|
{
|
|
std::string material;
|
|
lighting_data lighting;
|
|
std::vector<world_vertex> vertices;
|
|
};
|
|
std::vector<batch> batches;
|
|
auto const vertices = [&batches](std::string const &Material, lighting_data const &Lighting) -> std::vector<world_vertex> & {
|
|
for (auto &entry : batches)
|
|
{
|
|
if (entry.material == Material && entry.lighting == Lighting)
|
|
{
|
|
return entry.vertices;
|
|
}
|
|
}
|
|
batches.emplace_back();
|
|
batches.back().material = Material;
|
|
batches.back().lighting = Lighting;
|
|
return batches.back().vertices;
|
|
};
|
|
auto const usable = [](std::string const &Material) { return false == Material.empty() && Material != "none"; };
|
|
auto const place = [](section const &Section, section_corner const &Corner) { return Section.position + Section.left * Corner.offset + up * Corner.height; };
|
|
// a band of triangles between two lines running along the stretch, from a section to another.
|
|
// Left, Right: give the distance from the way, the height and the texture coordinate of each line at a section
|
|
auto const strip = [&](std::vector<world_vertex> &Output, auto const &Left, auto const &Right, std::size_t const First, std::size_t const Last) {
|
|
for (auto idx{First}; idx < Last && idx + 1 < sections.size(); ++idx)
|
|
{
|
|
auto const &here{sections[idx]};
|
|
auto const &there{sections[idx + 1]};
|
|
section_corner const left0{Left(here)};
|
|
section_corner const right0{Right(here)};
|
|
section_corner const left1{Left(there)};
|
|
section_corner const right1{Right(there)};
|
|
auto const leftstart{place(here, left0)};
|
|
auto const rightstart{place(here, right0)};
|
|
auto const leftend{place(there, left1)};
|
|
auto const rightend{place(there, right1)};
|
|
auto const facing{glm::cross(here.tangent, leftstart - rightstart)};
|
|
glm::vec3 const normal{glm::length2(facing) < 1e-12 ? up : glm::normalize(facing)};
|
|
auto const texturestart{static_cast<float>(here.station / m_state.texturelength)};
|
|
auto const textureend{static_cast<float>(there.station / m_state.texturelength)};
|
|
Output.push_back({leftstart, normal, {left0.texture, texturestart}});
|
|
Output.push_back({rightstart, normal, {right0.texture, texturestart}});
|
|
Output.push_back({leftend, normal, {left1.texture, textureend}});
|
|
Output.push_back({rightstart, normal, {right0.texture, texturestart}});
|
|
Output.push_back({rightend, normal, {right1.texture, textureend}});
|
|
Output.push_back({leftend, normal, {left1.texture, textureend}});
|
|
}
|
|
};
|
|
auto const whole{sections.size() - 1};
|
|
// the two directions are apart at either road
|
|
auto const apart{from.median > 0.f || to.median > 0.f};
|
|
auto const forth{from.incoming > 0 || to.outgoing > 0};
|
|
auto const back{from.outgoing > 0 || to.incoming > 0};
|
|
double const height{m_state.kerbheight};
|
|
|
|
// surface. the image is centered on the way, like it is on a road
|
|
if (m_state.surface != "none")
|
|
{
|
|
auto const tile{static_cast<double>(texture_ratio(m_state.surface)) * m_state.texturelength};
|
|
auto const along = [tile](double edges::*Edge) {
|
|
return [tile, Edge](section const &Section) { return section_corner{Section.offsets.*Edge, 0.0, static_cast<float>(0.5 + Section.offsets.*Edge / tile)}; };
|
|
};
|
|
auto &surface{vertices(m_state.surface, lighting_data{})};
|
|
if (apart && m_state.median == road_node::median_type::gap)
|
|
{
|
|
// a roadway for each direction, with the ground showing between them
|
|
strip(surface, along(&edges::forward), along(&edges::right), 0, whole);
|
|
strip(surface, along(&edges::left), along(&edges::backward), 0, whole);
|
|
}
|
|
else
|
|
{
|
|
strip(surface, along(&edges::left), along(&edges::right), 0, whole);
|
|
}
|
|
}
|
|
// an island where the two directions part
|
|
if (apart && m_state.median == road_node::median_type::island && (usable(m_state.medianmaterial) || (m_state.kerbs && usable(m_state.kerbmaterial))))
|
|
{
|
|
auto const &material{usable(m_state.medianmaterial) ? m_state.medianmaterial : m_state.kerbmaterial};
|
|
auto const tile{static_cast<double>(texture_ratio(material)) * m_state.texturelength};
|
|
auto const widest{std::max(from.median, to.median)};
|
|
auto &island{vertices(material, lighting_data{})};
|
|
auto const corner = [](double edges::*Edge, double const Height, float const Texture) {
|
|
return [Edge, Height, Texture](section const &Section) { return section_corner{Section.offsets.*Edge, Height, Texture}; };
|
|
};
|
|
auto const top{static_cast<float>(height / tile)};
|
|
auto const across{static_cast<float>((height + widest) / tile)};
|
|
strip(island, corner(&edges::backward, 0.0, 0.f), corner(&edges::backward, height, top), 0, whole);
|
|
strip(island, corner(&edges::backward, height, top), corner(&edges::forward, height, across), 0, whole);
|
|
strip(island, corner(&edges::forward, height, across), corner(&edges::forward, 0.0, static_cast<float>((2.0 * height + widest) / tile)), 0, whole);
|
|
}
|
|
// what lines the edges: the same the corners of a junction of more roads get. the right edge is the corner which starts
|
|
// at the first road, the left one is the corner which starts at the second road, so it's gone along backwards
|
|
for (int side = 0; side < 2; ++side)
|
|
{
|
|
auto const sign{side == 0 ? -1.0 : 1.0};
|
|
for (auto const &lining : edge_linings(m_state, arms[side].bank))
|
|
{
|
|
auto &output{vertices(lining.material, lighting_data{})};
|
|
for (std::size_t band = 0; band + 1 < lining.profile.size(); ++band)
|
|
{
|
|
auto const corner = [side, sign](edge_point const &Point) {
|
|
return [sign, &Point, side](section const &Section) {
|
|
auto const fraction{side == 0 ? Section.fraction : 1.0 - Section.fraction};
|
|
auto const edge{side == 0 ? Section.offsets.right : Section.offsets.left};
|
|
return section_corner{edge + sign * (Point.offset + Point.grow * fraction), Point.height + Point.sink * fraction, Point.texture};
|
|
};
|
|
};
|
|
auto const inner{corner(lining.profile[band])};
|
|
auto const outer{corner(lining.profile[band + 1])};
|
|
if (side == 0)
|
|
{
|
|
strip(output, inner, outer, 0, whole);
|
|
}
|
|
else
|
|
{
|
|
strip(output, outer, inner, 0, whole);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// markings
|
|
if (m_state.markings != road_node::marking_colour::none)
|
|
{
|
|
lighting_data paint;
|
|
paint.diffuse = (m_state.markings == road_node::marking_colour::white ? glm::vec4{0.92f, 0.92f, 0.92f, 1.f} : glm::vec4{0.95f, 0.5f, 0.08f, 1.f});
|
|
paint.ambient = paint.diffuse;
|
|
auto &lines{vertices("colored", paint)};
|
|
// a line running at some distance from one of the edges
|
|
auto const line = [&](double edges::*Edge, double const Shift, double const Lanes, std::size_t const First, std::size_t const Last) {
|
|
auto const side = [Edge, Shift, Lanes](double const Half, float const Texture) {
|
|
return [Edge, Shift, Lanes, Half, Texture](section const &Section) {
|
|
return section_corner{Section.offsets.*Edge + Shift + Lanes * Section.offsets.lanewidth + Half, line_lift, Texture};
|
|
};
|
|
};
|
|
strip(lines, side(0.5 * line_width, 0.f), side(-0.5 * line_width, 1.f), First, Last);
|
|
};
|
|
auto const inset{edge_inset + 0.5 * line_width};
|
|
line(&edges::right, inset, 0.0, 0, whole);
|
|
line(&edges::left, -inset, 0.0, 0, whole);
|
|
if (forth && back)
|
|
{
|
|
if (apart)
|
|
{
|
|
// each of the two roadways gets its edge line
|
|
line(&edges::forward, -inset, 0.0, 0, whole);
|
|
line(&edges::backward, inset, 0.0, 0, whole);
|
|
}
|
|
else
|
|
{
|
|
// traffic going opposite ways is kept apart with a double line
|
|
auto const pair{0.5 * (line_width + line_spacing)};
|
|
line(&edges::forward, pair, 0.0, 0, whole);
|
|
line(&edges::forward, -pair, 0.0, 0, whole);
|
|
}
|
|
}
|
|
// lines between the lanes of each direction, dashed. the lanes are counted from the middle of the road, so the ones
|
|
// both roads have run all the way; a line of a lane only one of them has starts where the roadway got wide enough for the lane
|
|
for (int direction = 0; direction < 2; ++direction)
|
|
{
|
|
auto const lanes{direction == 0 ? std::max(from.incoming, to.outgoing) : std::max(from.outgoing, to.incoming)};
|
|
for (int lane = 1; lane < lanes; ++lane)
|
|
{
|
|
for (std::size_t idx = 0; idx < whole; ++idx)
|
|
{
|
|
if (std::fmod(sections[idx].station, dash_period) >= dash_period / 3.0)
|
|
{
|
|
continue;
|
|
}
|
|
auto const room = [&](section const &Section) {
|
|
auto const &offsets{Section.offsets};
|
|
return (direction == 0 ? offsets.forward - offsets.right : offsets.left - offsets.backward) >= (lane + 0.5) * offsets.lanewidth;
|
|
};
|
|
if (room(sections[idx]) && room(sections[idx + 1]))
|
|
{
|
|
line(direction == 0 ? &edges::forward : &edges::backward, 0.0, direction == 0 ? -lane : lane, idx, idx + 1);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if (apart && m_state.median == road_node::median_type::painted && length > 0.0)
|
|
{
|
|
// what's between the roadways is closed to the traffic: slanted stripes are led from one edge line to the other
|
|
double const period{3.0};
|
|
double const stripe{0.5};
|
|
glm::vec3 const upwards{0.f, 1.f, 0.f};
|
|
// point of the edge of one of the roadways, a bit into what's between them
|
|
auto const edge = [&](double const Station, bool const Left) {
|
|
auto const where{at(std::clamp(Station / length, 0.0, 1.0))};
|
|
auto const gap{where.offsets.backward - where.offsets.forward};
|
|
auto const margin{std::min(2.0 * inset, 0.5 * gap)};
|
|
return where.position + where.left * (Left ? where.offsets.backward - margin : where.offsets.forward + margin) + up * line_lift;
|
|
};
|
|
auto const count{std::max(1, static_cast<int>(std::lround(length / period)))};
|
|
auto const spacing{length / count};
|
|
for (int index = 0; index < count; ++index)
|
|
{
|
|
auto const centre{(index + 0.5) * spacing};
|
|
auto const middle{at(std::clamp(centre / length, 0.0, 1.0))};
|
|
auto const gap{middle.offsets.backward - middle.offsets.forward};
|
|
if (gap < 1.0)
|
|
{
|
|
continue;
|
|
}
|
|
auto const slant{std::clamp(gap, 0.0, std::max(0.0, spacing - stripe - 0.25))};
|
|
auto const station{centre - 0.5 * (slant + stripe)};
|
|
auto const leftstart{edge(station, true)};
|
|
auto const leftend{edge(station + stripe, true)};
|
|
auto const rightstart{edge(station + slant, false)};
|
|
auto const rightend{edge(station + slant + stripe, false)};
|
|
lines.push_back({leftstart, upwards, {0.f, 0.f}});
|
|
lines.push_back({rightstart, upwards, {1.f, 0.f}});
|
|
lines.push_back({leftend, upwards, {0.f, 1.f}});
|
|
lines.push_back({rightstart, upwards, {1.f, 0.f}});
|
|
lines.push_back({rightend, upwards, {1.f, 1.f}});
|
|
lines.push_back({leftend, upwards, {0.f, 1.f}});
|
|
}
|
|
}
|
|
}
|
|
|
|
for (auto &entry : batches)
|
|
{
|
|
if (entry.vertices.empty())
|
|
{
|
|
continue;
|
|
}
|
|
scene::shape_node shape;
|
|
shape.make_terrain(GfxRenderer->Fetch_Material(entry.material), std::move(entry.vertices), glm::dvec3{0.0});
|
|
shape.lighting(entry.lighting);
|
|
shapes.emplace_back(std::move(shape));
|
|
}
|
|
return shapes;
|
|
}
|
|
|
|
// generates geometry of the surface
|
|
std::vector<scene::shape_node> junction_node::create_shapes() const
|
|
{
|
|
if (m_state.arms.size() == 2)
|
|
{
|
|
// where a road changes its lanes it's drawn as a stretch of that road
|
|
return create_transition_shapes();
|
|
}
|
|
std::vector<scene::shape_node> shapes;
|
|
std::vector<std::vector<glm::dvec3>> corners;
|
|
auto const points{m_state.outline(&corners)};
|
|
if (points.size() < 3)
|
|
{
|
|
return shapes;
|
|
}
|
|
auto const ¢re{m_state.centre};
|
|
if (m_state.surface != "none")
|
|
{
|
|
// a fan of triangles spanned from the centre, with the image laid out flat over the ground
|
|
auto const tile{static_cast<double>(texture_ratio(m_state.surface)) * m_state.texturelength};
|
|
auto const vertex = [&](glm::dvec3 const &Point, glm::vec3 const &Normal) {
|
|
return world_vertex{Point, Normal, {static_cast<float>(0.5 + (Point.x - centre.x) / tile), static_cast<float>(0.5 + (Point.z - centre.z) / m_state.texturelength)}};
|
|
};
|
|
std::vector<world_vertex> vertices;
|
|
for (std::size_t idx = 0; idx < points.size(); ++idx)
|
|
{
|
|
auto const ¤t{points[idx]};
|
|
auto const &next{points[(idx + 1) % points.size()]};
|
|
auto normal{glm::cross(current - centre, next - centre)};
|
|
if (glm::length2(normal) < 1e-12)
|
|
{
|
|
continue;
|
|
}
|
|
glm::vec3 const facing{glm::normalize(normal)};
|
|
vertices.emplace_back(vertex(centre, facing));
|
|
vertices.emplace_back(vertex(current, facing));
|
|
vertices.emplace_back(vertex(next, facing));
|
|
}
|
|
if (false == vertices.empty())
|
|
{
|
|
scene::shape_node shape;
|
|
shape.make_terrain(GfxRenderer->Fetch_Material(m_state.surface), std::move(vertices), glm::dvec3{0.0});
|
|
shapes.emplace_back(std::move(shape));
|
|
}
|
|
}
|
|
// the corners are lined the way the edges of a road are, so the kerbs, the shoulders, the sidewalks and the banks of the roads carry on around the junction
|
|
{
|
|
auto const order{m_state.arm_order()};
|
|
// triangles are gathered for each material, in the order the materials come up
|
|
std::vector<std::pair<std::string, std::vector<world_vertex>>> lined;
|
|
auto const batch = [&lined](std::string const &Material) -> std::vector<world_vertex> & {
|
|
for (auto &entry : lined)
|
|
{
|
|
if (entry.first == Material)
|
|
{
|
|
return entry.second;
|
|
}
|
|
}
|
|
lined.emplace_back(Material, std::vector<world_vertex>{});
|
|
return lined.back().second;
|
|
};
|
|
for (std::size_t idx = 0; idx < corners.size() && idx < order.size(); ++idx)
|
|
{
|
|
auto const &corner{corners[idx]};
|
|
if (corner.size() < 2)
|
|
{
|
|
continue;
|
|
}
|
|
// the way out of the surface at each point of the corner. at its ends it's the way across the roads there,
|
|
// so what lines the corner meets what the roads have along their edges
|
|
std::vector<glm::dvec3> outwards(corner.size());
|
|
outwards.front() = flat(left_of(m_state.arms[order[idx]].direction));
|
|
outwards.back() = -flat(left_of(m_state.arms[order[(idx + 1) % order.size()]].direction));
|
|
for (std::size_t point = 1; point + 1 < corner.size(); ++point)
|
|
{
|
|
// going around the junction the surface is on the left, and the way out of it on the right
|
|
glm::dvec2 const along{corner[point + 1].x - corner[point - 1].x, corner[point + 1].z - corner[point - 1].z};
|
|
outwards[point] = (glm::length(along) > 1e-9 ? -flat(left_of(glm::normalize(along))) : outwards[point - 1]);
|
|
}
|
|
double total{0.0};
|
|
for (std::size_t point = 0; point + 1 < corner.size(); ++point)
|
|
{
|
|
total += glm::distance(corner[point], corner[point + 1]);
|
|
}
|
|
// the bank of the corner is the one set for the road the corner starts at
|
|
for (auto const &lining : edge_linings(m_state, m_state.arms[order[idx]].bank))
|
|
{
|
|
auto &vertices{batch(lining.material)};
|
|
auto const &profile{lining.profile};
|
|
double station{0.0};
|
|
for (std::size_t point = 0; point + 1 < corner.size(); ++point)
|
|
{
|
|
auto const length{glm::distance(corner[point], corner[point + 1])};
|
|
auto const tangent{corner[point + 1] - corner[point]};
|
|
auto const texturestart{static_cast<float>(station / m_state.texturelength)};
|
|
auto const textureend{static_cast<float>((station + length) / m_state.texturelength)};
|
|
auto const fractionstart{total > 0.0 ? station / total : 0.0};
|
|
auto const fractionend{total > 0.0 ? (station + length) / total : 0.0};
|
|
for (std::size_t band = 0; band + 1 < profile.size(); ++band)
|
|
{
|
|
auto const &inner{profile[band]};
|
|
auto const &outer{profile[band + 1]};
|
|
auto const leftstart{corner[point] + outwards[point] * (inner.offset + inner.grow * fractionstart) + up * (inner.height + inner.sink * fractionstart)};
|
|
auto const rightstart{corner[point] + outwards[point] * (outer.offset + outer.grow * fractionstart) + up * (outer.height + outer.sink * fractionstart)};
|
|
auto const leftend{corner[point + 1] + outwards[point + 1] * (inner.offset + inner.grow * fractionend) + up * (inner.height + inner.sink * fractionend)};
|
|
auto const rightend{corner[point + 1] + outwards[point + 1] * (outer.offset + outer.grow * fractionend) + up * (outer.height + outer.sink * fractionend)};
|
|
auto facing{glm::cross(tangent, leftstart - rightstart)};
|
|
glm::vec3 const normal{glm::length2(facing) < 1e-12 ? up : glm::normalize(facing)};
|
|
vertices.push_back({leftstart, normal, {inner.texture, texturestart}});
|
|
vertices.push_back({rightstart, normal, {outer.texture, texturestart}});
|
|
vertices.push_back({leftend, normal, {inner.texture, textureend}});
|
|
vertices.push_back({rightstart, normal, {outer.texture, texturestart}});
|
|
vertices.push_back({rightend, normal, {outer.texture, textureend}});
|
|
vertices.push_back({leftend, normal, {inner.texture, textureend}});
|
|
}
|
|
station += length;
|
|
}
|
|
}
|
|
}
|
|
for (auto &entry : lined)
|
|
{
|
|
if (entry.second.empty())
|
|
{
|
|
continue;
|
|
}
|
|
scene::shape_node shape;
|
|
shape.make_terrain(GfxRenderer->Fetch_Material(entry.first), std::move(entry.second), glm::dvec3{0.0});
|
|
shapes.emplace_back(std::move(shape));
|
|
}
|
|
}
|
|
if (m_state.markings != road_node::marking_colour::none)
|
|
{
|
|
// edge lines carried around the corners
|
|
std::vector<world_vertex> vertices;
|
|
glm::dvec3 const lift{0.0, line_lift, 0.0};
|
|
glm::vec3 const upwards{0.f, 1.f, 0.f};
|
|
auto const &arms{m_state.arms};
|
|
for (std::size_t arm = 0; arm < arms.size(); ++arm)
|
|
{
|
|
if (false == arms[arm].stopline || arms[arm].incoming < 1)
|
|
{
|
|
continue;
|
|
}
|
|
// a stop line: across the lanes leading into the junction, right where the road ends
|
|
auto const across{flat(left_of(arms[arm].direction))};
|
|
auto const inwards{-flat(arms[arm].direction)};
|
|
auto const halfwidth{0.5 * m_state.arm_width(arm)};
|
|
auto const from{arms[arm].position + across * (halfwidth - static_cast<double>(arms[arm].incoming) * arms[arm].width + 0.5 * line_width) + lift};
|
|
auto const to{arms[arm].position + across * (halfwidth - edge_inset - line_width) + lift};
|
|
auto const leftstart{from + inwards * (stopline_inset + stopline_width)};
|
|
auto const rightstart{from + inwards * stopline_inset};
|
|
auto const leftend{to + inwards * (stopline_inset + stopline_width)};
|
|
auto const rightend{to + inwards * stopline_inset};
|
|
vertices.push_back({leftstart, upwards, {0.f, 0.f}});
|
|
vertices.push_back({rightstart, upwards, {1.f, 0.f}});
|
|
vertices.push_back({leftend, upwards, {0.f, 1.f}});
|
|
vertices.push_back({rightstart, upwards, {1.f, 0.f}});
|
|
vertices.push_back({rightend, upwards, {1.f, 1.f}});
|
|
vertices.push_back({leftend, upwards, {0.f, 1.f}});
|
|
}
|
|
for (std::size_t arm = 0; arm < arms.size(); ++arm)
|
|
{
|
|
if (arms[arm].crosswalk <= 0.f)
|
|
{
|
|
continue;
|
|
}
|
|
// a pedestrian crossing: stripes laid the way the road goes, side by side across it, past the place for a stop line
|
|
auto const across{flat(left_of(arms[arm].direction))};
|
|
auto const inwards{-flat(arms[arm].direction)};
|
|
auto const reach{0.5 * m_state.arm_width(arm) - edge_inset};
|
|
auto const stripes{std::max(1, static_cast<int>(std::floor((2.0 * reach + stopline_width) / (2.0 * stopline_width))))};
|
|
auto const first{-0.5 * (stripes * 2 - 1) * stopline_width};
|
|
for (int stripe = 0; stripe < stripes; ++stripe)
|
|
{
|
|
auto const offset{first + stripe * 2.0 * stopline_width};
|
|
auto const from{arms[arm].position + across * offset + lift};
|
|
auto const to{arms[arm].position + across * (offset + stopline_width) + lift};
|
|
auto const leftstart{from + inwards * (crosswalk_inset + arms[arm].crosswalk)};
|
|
auto const rightstart{from + inwards * crosswalk_inset};
|
|
auto const leftend{to + inwards * (crosswalk_inset + arms[arm].crosswalk)};
|
|
auto const rightend{to + inwards * crosswalk_inset};
|
|
vertices.push_back({leftstart, upwards, {0.f, 0.f}});
|
|
vertices.push_back({rightstart, upwards, {1.f, 0.f}});
|
|
vertices.push_back({leftend, upwards, {0.f, 1.f}});
|
|
vertices.push_back({rightstart, upwards, {1.f, 0.f}});
|
|
vertices.push_back({rightend, upwards, {1.f, 1.f}});
|
|
vertices.push_back({leftend, upwards, {0.f, 1.f}});
|
|
}
|
|
}
|
|
if (arms.size() == 2 && arms[0].incoming > 0 && arms[0].outgoing > 0 && arms[1].incoming > 0 && arms[1].outgoing > 0)
|
|
{
|
|
// a junction of two roads is where a road changes its lanes. the double line keeping the directions apart is led through it
|
|
auto const divide = [&](std::size_t const Arm) { return arms[Arm].position + flat(left_of(arms[Arm].direction)) * (0.5 * m_state.arm_width(Arm) - static_cast<double>(arms[Arm].incoming) * arms[Arm].width); };
|
|
auto const p0{divide(0)};
|
|
auto const p3{divide(1)};
|
|
auto const reach{0.39 * glm::distance(p0, p3)};
|
|
auto const p1{p0 - flat(arms[0].direction) * reach};
|
|
auto const p2{p3 - flat(arms[1].direction) * reach};
|
|
auto const pair{0.5 * (line_width + line_spacing)};
|
|
int const steps{12};
|
|
glm::dvec3 previous{p0};
|
|
glm::dvec3 previousleft{flat(left_of(-arms[0].direction))};
|
|
for (int step = 1; step <= steps; ++step)
|
|
{
|
|
auto const t{static_cast<double>(step) / steps};
|
|
auto const u{1.0 - t};
|
|
auto const current{u * u * u * p0 + 3.0 * u * u * t * p1 + 3.0 * u * t * t * p2 + t * t * t * p3};
|
|
auto const direction{3.0 * u * u * (p1 - p0) + 6.0 * u * t * (p2 - p1) + 3.0 * t * t * (p3 - p2)};
|
|
glm::dvec2 const heading{direction.x, direction.z};
|
|
auto const left{glm::length(heading) > 1e-9 ? flat(left_of(glm::normalize(heading))) : previousleft};
|
|
for (auto const side : {-1.0, 1.0})
|
|
{
|
|
auto const leftstart{previous + previousleft * (side * pair + 0.5 * line_width) + lift};
|
|
auto const rightstart{previous + previousleft * (side * pair - 0.5 * line_width) + lift};
|
|
auto const leftend{current + left * (side * pair + 0.5 * line_width) + lift};
|
|
auto const rightend{current + left * (side * pair - 0.5 * line_width) + lift};
|
|
vertices.push_back({leftstart, upwards, {0.f, 0.f}});
|
|
vertices.push_back({rightstart, upwards, {1.f, 0.f}});
|
|
vertices.push_back({leftend, upwards, {0.f, 1.f}});
|
|
vertices.push_back({rightstart, upwards, {1.f, 0.f}});
|
|
vertices.push_back({rightend, upwards, {1.f, 1.f}});
|
|
vertices.push_back({leftend, upwards, {0.f, 1.f}});
|
|
}
|
|
previous = current;
|
|
previousleft = left;
|
|
}
|
|
}
|
|
for (auto const &corner : corners)
|
|
{
|
|
for (std::size_t idx = 0; idx + 1 < corner.size(); ++idx)
|
|
{
|
|
// the line keeps its distance from the edge, on the side of the centre
|
|
auto const inwards = [&](glm::dvec3 const &Point) {
|
|
auto direction{centre - Point};
|
|
direction.y = 0.0;
|
|
return glm::length2(direction) > 1e-12 ? glm::normalize(direction) : glm::dvec3{0.0};
|
|
};
|
|
auto const outer0{corner[idx] + inwards(corner[idx]) * edge_inset + lift};
|
|
auto const inner0{corner[idx] + inwards(corner[idx]) * (edge_inset + line_width) + lift};
|
|
auto const outer1{corner[idx + 1] + inwards(corner[idx + 1]) * edge_inset + lift};
|
|
auto const inner1{corner[idx + 1] + inwards(corner[idx + 1]) * (edge_inset + line_width) + lift};
|
|
// the corners are listed going around the junction the way which makes these face up
|
|
vertices.push_back({inner0, upwards, {0.f, 0.f}});
|
|
vertices.push_back({outer0, upwards, {1.f, 0.f}});
|
|
vertices.push_back({outer1, upwards, {1.f, 1.f}});
|
|
vertices.push_back({inner0, upwards, {0.f, 0.f}});
|
|
vertices.push_back({outer1, upwards, {1.f, 1.f}});
|
|
vertices.push_back({inner1, upwards, {0.f, 1.f}});
|
|
}
|
|
}
|
|
if (false == vertices.empty())
|
|
{
|
|
lighting_data paint;
|
|
paint.diffuse = (m_state.markings == road_node::marking_colour::white ? glm::vec4{0.92f, 0.92f, 0.92f, 1.f} : glm::vec4{0.95f, 0.5f, 0.08f, 1.f});
|
|
paint.ambient = paint.diffuse;
|
|
scene::shape_node shape;
|
|
shape.make_terrain(GfxRenderer->Fetch_Material("colored"), std::move(vertices), glm::dvec3{0.0});
|
|
shape.lighting(paint);
|
|
shapes.emplace_back(std::move(shape));
|
|
}
|
|
}
|
|
return shapes;
|
|
}
|
|
|
|
void junction_node::show()
|
|
{
|
|
if (m_merged || m_shapes.shown())
|
|
{
|
|
return;
|
|
}
|
|
m_shapes.show(create_shapes(), location());
|
|
}
|
|
|
|
void junction_node::hide()
|
|
{
|
|
m_shapes.hide();
|
|
}
|
|
|
|
// creates a path through the junction from provided definition and registers it with the simulation
|
|
TTrack *junction_node::create_track(std::string const &Definition, std::size_t const Index)
|
|
{
|
|
cParser parser(Definition, cParser::buffer_TEXT);
|
|
scene::node_data nodedata;
|
|
nodedata.range_max = -1.0;
|
|
nodedata.name = (m_name.empty() ? std::string{} : m_name + ":way" + std::to_string(Index + 1));
|
|
nodedata.type = "track";
|
|
auto *track{new TTrack(nodedata)};
|
|
track->Load(&parser, glm::dvec3{0.0});
|
|
track->m_road = this;
|
|
// NOTE: the table points the name at the newest path, which is what a junction made anew in the editor needs
|
|
simulation::Paths.insert(track);
|
|
simulation::Region->insert_and_register(track);
|
|
return track;
|
|
}
|
|
|
|
float junction_node::radius_() const
|
|
{
|
|
float radius{0.f};
|
|
for (std::size_t arm = 0; arm < m_state.arms.size(); ++arm)
|
|
{
|
|
radius = std::max(radius, static_cast<float>(glm::distance(m_state.arms[arm].position, m_state.centre) + 0.5 * m_state.arm_width(arm)));
|
|
}
|
|
return radius;
|
|
}
|
|
|
|
void junction_node::serialize_(std::ostream &Output) const
|
|
{
|
|
// TODO: implement
|
|
}
|
|
|
|
void junction_node::deserialize_(std::istream &Input)
|
|
{
|
|
// TODO: implement
|
|
}
|
|
|
|
// export() subclass details, sends basic content of the class in legacy (text) format to provided stream
|
|
void junction_node::export_as_text_(std::ostream &Output) const
|
|
{
|
|
Output << "junction ";
|
|
auto const precision{Output.precision(std::numeric_limits<double>::digits10)};
|
|
Output << m_state.centre.x << ' ' << m_state.centre.y << ' ' << m_state.centre.z << ' ';
|
|
for (auto const &arm : m_state.arms)
|
|
{
|
|
Output << "arm " << arm.position.x << ' ' << arm.position.y << ' ' << arm.position.z << ' ' << arm.direction.x << ' ' << arm.direction.y << ' ' << arm.incoming << ' ' << arm.outgoing << ' ' << arm.width << ' ';
|
|
}
|
|
Output.precision(precision);
|
|
Output << "surface " << m_state.surface << ' ' << "texlength " << m_state.texturelength << ' ' << "markings "
|
|
<< (m_state.markings == road_node::marking_colour::white ? "white" : m_state.markings == road_node::marking_colour::orange ? "orange" : "none") << ' ';
|
|
if (m_state.side.type != road_node::side_type::none)
|
|
{
|
|
Output << "side " << (m_state.side.type == road_node::side_type::shoulder ? "shoulder" : "sidewalk") << ' ' << m_state.side.width << ' ' << (m_state.side.material.empty() ? "none" : m_state.side.material) << ' ' << "kerb " << m_state.kerbheight << ' '
|
|
<< "slope " << m_state.slope.x << ' ' << m_state.slope.y << ' ';
|
|
}
|
|
if (m_state.kerbs)
|
|
{
|
|
Output << "kerbs " << m_state.kerbwidth << ' ' << m_state.kerbmaterial << ' ';
|
|
if (m_state.side.type == road_node::side_type::none)
|
|
{
|
|
Output << "kerb " << m_state.kerbheight << ' ';
|
|
}
|
|
}
|
|
for (std::size_t arm = 0; arm < m_state.arms.size(); ++arm)
|
|
{
|
|
if (m_state.arms[arm].stopline)
|
|
{
|
|
Output << "stopline " << arm + 1 << ' ';
|
|
}
|
|
if (m_state.arms[arm].median > 0.f)
|
|
{
|
|
Output << "armmedian " << arm + 1 << ' ' << m_state.arms[arm].median << ' ';
|
|
}
|
|
if (m_state.arms[arm].crosswalk > 0.f)
|
|
{
|
|
Output << "crosswalk " << arm + 1 << ' ' << m_state.arms[arm].crosswalk << ' ';
|
|
}
|
|
auto const &bank{m_state.arms[arm].bank};
|
|
if (bank.set)
|
|
{
|
|
Output << "cornerbank " << arm + 1 << ' ' << bank.width[0] << ' ' << bank.drop[0] << ' ' << bank.width[1] << ' ' << bank.drop[1] << ' ';
|
|
}
|
|
auto const priority{m_state.arms[arm].priority};
|
|
if (priority != right_of_way::none)
|
|
{
|
|
Output << "priority " << arm + 1 << ' ' << (priority == right_of_way::priority ? "main" : priority == right_of_way::yield ? "yield" : "stop") << ' ';
|
|
}
|
|
for (std::size_t lane = 0; lane < m_state.arms[arm].turns.size(); ++lane)
|
|
{
|
|
auto const turns{m_state.arms[arm].turns[lane]};
|
|
if (turns != 0)
|
|
{
|
|
Output << "turns " << arm + 1 << ' ' << lane + 1 << ' ';
|
|
Output << ((turns & turn_left) != 0 ? "l" : "") << ((turns & turn_straight) != 0 ? "s" : "") << ((turns & turn_right) != 0 ? "r" : "") << ' ';
|
|
}
|
|
}
|
|
}
|
|
if (m_state.bankmaterial != "none")
|
|
{
|
|
Output << "bankmaterial " << m_state.bankmaterial << ' ';
|
|
}
|
|
if (m_state.arms.size() == 2 && (m_state.arms[0].median > 0.f || m_state.arms[1].median > 0.f))
|
|
{
|
|
Output << "median " << (m_state.median == road_node::median_type::gap ? "gap" : m_state.median == road_node::median_type::island ? "island" : "painted") << ' ';
|
|
Output << m_state.medianmaterial << ' ';
|
|
}
|
|
Output << "velocity " << m_state.velocity << ' ' << "friction " << m_state.friction << ' ' << "environment " << m_state.environment << ' ';
|
|
Output << "endjunction"
|
|
<< "\n";
|
|
}
|
|
|
|
// creates a path for the vehicles and registers it with the simulation
|
|
TTrack *road_node::create_track(std::string const &Name, segment_data const &Path, float const Width, float const Velocity)
|
|
{
|
|
auto const &start{Path.points[segment_data::point::start]};
|
|
auto const &control1{Path.points[segment_data::point::control1]};
|
|
auto const &control2{Path.points[segment_data::point::control2]};
|
|
auto const &end{Path.points[segment_data::point::end]};
|
|
// the path is put together the way the scenery defines an invisible road, to have it set up by the code which loads these
|
|
std::ostringstream text;
|
|
text.precision(std::numeric_limits<double>::digits10);
|
|
text << "road " << glm::distance(start, end) << ' ' << Width << ' ' << m_state.friction << ' ' << m_state.sounddistance << ' ' << m_state.quality << " 0 " << m_state.environment << " unvis " << start.x << ' ' << start.y << ' ' << start.z << ' ' << Path.rolls[0] << ' '
|
|
<< control1.x << ' ' << control1.y << ' ' << control1.z << ' ' << control2.x << ' ' << control2.y << ' ' << control2.z << ' ' << end.x << ' ' << end.y << ' ' << end.z << ' ' << Path.rolls[1] << ' ' << Path.radius << ' ';
|
|
if (Velocity > 0.f)
|
|
{
|
|
text << "velocity " << Velocity << ' ';
|
|
}
|
|
text << "endtrack";
|
|
|
|
return create_track(Name, text.str());
|
|
}
|
|
|
|
// creates a path for the vehicles from its definition and registers it with the simulation
|
|
TTrack *road_node::create_track(std::string const &Name, std::string const &Definition)
|
|
{
|
|
cParser parser(Definition, cParser::buffer_TEXT);
|
|
scene::node_data nodedata;
|
|
nodedata.range_max = -1.0;
|
|
nodedata.name = Name;
|
|
nodedata.type = "track";
|
|
auto *track{new TTrack(nodedata)};
|
|
track->Load(&parser, glm::dvec3{0.0});
|
|
track->m_road = this;
|
|
if (false == simulation::Paths.insert(track))
|
|
{
|
|
// NOTE: the table points the name at the newest path, which is what a road made anew in the editor needs
|
|
if (false == m_editorremoved && false == dirty())
|
|
{
|
|
ErrorLog("Bad scenario: duplicate track name \"" + track->name() + "\" generated for a road");
|
|
}
|
|
}
|
|
simulation::Region->insert_and_register(track);
|
|
return track;
|
|
}
|
|
|
|
// radius() subclass details, calculates node's bounding radius
|
|
float road_node::radius_() const
|
|
{
|
|
auto reach{static_cast<double>(m_state.slope.x)};
|
|
for (auto const &bank : m_state.banks)
|
|
{
|
|
if (bank.set)
|
|
{
|
|
reach = std::max(reach, static_cast<double>(std::max(bank.width[0], bank.width[1])));
|
|
}
|
|
}
|
|
return static_cast<float>(0.5 * m_state.length() + 0.5 * std::max(m_state.span(0.0), m_state.span(1.0)) + m_state.kerbwidth + std::max(m_state.sides[0].width, m_state.sides[1].width) + reach);
|
|
}
|
|
|
|
// serialize() subclass details, sends content of the subclass to provided stream
|
|
void road_node::serialize_(std::ostream &Output) const
|
|
{
|
|
// TODO: implement
|
|
}
|
|
|
|
// deserialize() subclass details, restores content of the subclass from provided stream
|
|
void road_node::deserialize_(std::istream &Input)
|
|
{
|
|
// TODO: implement
|
|
}
|
|
|
|
// export() subclass details, sends basic content of the class in legacy (text) format to provided stream
|
|
void road_node::export_as_text_(std::ostream &Output) const
|
|
{
|
|
auto const &road{m_state};
|
|
Output << "road ";
|
|
// axis
|
|
auto const precision{Output.precision(std::numeric_limits<double>::digits10)};
|
|
Output << road.axis.points[segment_data::point::start].x << ' ' << road.axis.points[segment_data::point::start].y << ' ' << road.axis.points[segment_data::point::start].z << ' ' << road.axis.rolls[0] << ' '
|
|
<< road.axis.points[segment_data::point::control1].x << ' ' << road.axis.points[segment_data::point::control1].y << ' ' << road.axis.points[segment_data::point::control1].z << ' '
|
|
<< road.axis.points[segment_data::point::control2].x << ' ' << road.axis.points[segment_data::point::control2].y << ' ' << road.axis.points[segment_data::point::control2].z << ' '
|
|
<< road.axis.points[segment_data::point::end].x << ' ' << road.axis.points[segment_data::point::end].y << ' ' << road.axis.points[segment_data::point::end].z << ' ' << road.axis.rolls[1] << ' '
|
|
<< road.axis.radius << ' ';
|
|
Output.precision(precision);
|
|
// lanes
|
|
Output << "lanes " << road.lanes_at(0, true) << ' ' << road.lanes_at(0, false) << ' ';
|
|
if (road.changing())
|
|
{
|
|
Output << "lanesto " << road.lanes_at(1, true) << ' ' << road.lanes_at(1, false) << ' ';
|
|
}
|
|
Output << "width " << road.lanewidth << ' ';
|
|
if (road.taper[0] != 1.f || road.taper[1] != 1.f)
|
|
{
|
|
Output << "taper " << road.taper[0] << ' ' << road.taper[1] << ' ';
|
|
}
|
|
if (road.velocity > 0.f)
|
|
{
|
|
Output << "velocity " << road.velocity << ' ';
|
|
}
|
|
for (std::size_t lane = 0; lane < road.lanes.size(); ++lane)
|
|
{
|
|
if (road.lanes[lane].width != road.lanewidth)
|
|
{
|
|
Output << "lane " << road.lane_id(lane) << " width " << road.lanes[lane].width << ' ';
|
|
}
|
|
if (road.lanes[lane].velocity != road.velocity)
|
|
{
|
|
Output << "lane " << road.lane_id(lane) << " velocity " << road.lanes[lane].velocity << ' ';
|
|
}
|
|
}
|
|
for (std::size_t boundary = 0; boundary < road.changes.size(); ++boundary)
|
|
{
|
|
if (road.changes[boundary] == road.default_change(boundary))
|
|
{
|
|
continue;
|
|
}
|
|
Output << "change " << road.lane_id(boundary) << ' ' << road.lane_id(boundary + 1) << ' ' << (road.changes[boundary] == change_both ? "both" : road.changes[boundary] == change_toright ? "ab" : road.changes[boundary] == change_toleft ? "ba" : "none") << ' ';
|
|
}
|
|
// appearance
|
|
Output << "surface " << road.surface << ' ' << "texlength " << road.texturelength << ' ';
|
|
char const *sidenames[]{"left", "right"};
|
|
for (int side = 0; side < 2; ++side)
|
|
{
|
|
auto const &data{road.sides[side]};
|
|
if (data.type == side_type::none)
|
|
{
|
|
continue;
|
|
}
|
|
Output << "side " << sidenames[side] << ' ' << (data.type == side_type::shoulder ? "shoulder" : "sidewalk") << ' ' << data.width << ' ' << (data.material.empty() ? "none" : data.material) << ' ';
|
|
}
|
|
Output << "kerb " << road.kerbheight << ' ' << "slope " << road.slope.x << ' ' << road.slope.y << ' ' << "markings " << (road.markings == marking_colour::white ? "white" : road.markings == marking_colour::orange ? "orange" : "none") << ' ';
|
|
// properties passed on to the lanes
|
|
Output << "friction " << road.friction << ' ' << "environment " << road.environment << ' ';
|
|
if (road.weight != 100.f)
|
|
{
|
|
Output << "weight " << road.weight << ' ';
|
|
}
|
|
if (road.median.width[0] > 0.f || road.median.width[1] > 0.f)
|
|
{
|
|
Output << "median " << (road.median.type == median_type::gap ? "gap" : road.median.type == median_type::island ? "island" : "painted") << ' ';
|
|
Output << road.median.width[0] << ' ' << road.median.width[1] << ' ' << road.median.material << ' ';
|
|
if (road.median.round[0] > 0.f || road.median.round[1] > 0.f)
|
|
{
|
|
Output << "medianround " << road.median.round[0] << ' ' << road.median.round[1] << ' ';
|
|
}
|
|
}
|
|
if (road.kerbs[0] || road.kerbs[1])
|
|
{
|
|
Output << "kerbs " << (road.kerbs[0] && road.kerbs[1] ? "both" : road.kerbs[0] ? "left" : "right") << ' ' << road.kerbwidth << ' ' << road.kerbmaterial << ' ';
|
|
}
|
|
for (int side = 0; side < 2; ++side)
|
|
{
|
|
auto const &bank{road.banks[side]};
|
|
if (bank.set)
|
|
{
|
|
Output << "bank " << sidenames[side] << ' ' << bank.width[0] << ' ' << bank.drop[0] << ' ' << bank.width[1] << ' ' << bank.drop[1] << ' ';
|
|
}
|
|
}
|
|
if (road.bankmaterial != "none")
|
|
{
|
|
Output << "bankmaterial " << road.bankmaterial << ' ';
|
|
}
|
|
if (road.roundabout)
|
|
{
|
|
Output << "roundabout ";
|
|
}
|
|
// footer
|
|
Output << "endroad"
|
|
<< "\n";
|
|
}
|
|
|
|
// legacy style initialization, to be performed when the tracks are already joined
|
|
void road_table::InitLanes()
|
|
{
|
|
// the pieces which gain or lose lanes lead the ones they have at one end to the ones they have at the other
|
|
for (auto *road : m_items)
|
|
{
|
|
if (road != nullptr)
|
|
{
|
|
road->create_links();
|
|
}
|
|
}
|
|
}
|
|
|
|
// legacy style initialization, to be performed when the junctions are done
|
|
void road_table::InitRoads()
|
|
{
|
|
for (auto *road : m_items)
|
|
{
|
|
if (road != nullptr)
|
|
{
|
|
road->close_ends();
|
|
}
|
|
}
|
|
}
|
|
|
|
// generates geometry of the roads and puts it in the scene
|
|
void road_table::create_geometry(scene::scratch_data &Scratchpad)
|
|
{
|
|
if (simulation::Region == nullptr)
|
|
{
|
|
return;
|
|
}
|
|
for (auto *road : m_items)
|
|
{
|
|
if (road == nullptr)
|
|
{
|
|
continue;
|
|
}
|
|
if (Global.editor_session && false == Global.NvRenderer)
|
|
{
|
|
// scenery opened for editing: the road keeps its geometry apart, so it can be changed later.
|
|
// NOTE: the experimental renderer draws only what the scenery had when it was loaded
|
|
road->show();
|
|
continue;
|
|
}
|
|
// otherwise the geometry joins the rest of the scenery, which lets it be drawn along with it at no extra cost
|
|
for (auto &shape : road->create_shapes())
|
|
{
|
|
// it's already where it belongs, so the placement set by the scenery isn't to be applied to it
|
|
simulation::Region->insert(shape, Scratchpad, false);
|
|
}
|
|
road->merged(true);
|
|
}
|
|
}
|
|
|
|
// legacy style initialization, to be performed when the tracks are joined, ahead of the roads
|
|
void junction_table::InitJunctions()
|
|
{
|
|
for (auto *junction : m_items)
|
|
{
|
|
if (junction != nullptr)
|
|
{
|
|
junction->create_links();
|
|
}
|
|
}
|
|
}
|
|
|
|
// to be called with each step of the simulation
|
|
void junction_table::update(double const Deltatime)
|
|
{
|
|
for (auto *junction : m_items)
|
|
{
|
|
if (junction != nullptr && false == junction->m_editorremoved)
|
|
{
|
|
junction->update(Deltatime);
|
|
}
|
|
}
|
|
}
|
|
|
|
// generates geometry of the junctions and puts it in the scene
|
|
void junction_table::create_geometry(scene::scratch_data &Scratchpad)
|
|
{
|
|
if (simulation::Region == nullptr)
|
|
{
|
|
return;
|
|
}
|
|
for (auto *junction : m_items)
|
|
{
|
|
if (junction == nullptr)
|
|
{
|
|
continue;
|
|
}
|
|
if (Global.editor_session && false == Global.NvRenderer)
|
|
{
|
|
junction->show();
|
|
continue;
|
|
}
|
|
for (auto &shape : junction->create_shapes())
|
|
{
|
|
simulation::Region->insert(shape, Scratchpad, false);
|
|
}
|
|
junction->merged(true);
|
|
}
|
|
}
|
|
|
|
//---------------------------------------------------------------------------
|