mirror of
https://github.com/MaSzyna-EU07/maszyna.git
synced 2026-11-27 21:45:16 +01:00
* Enhance Windows build matrix with AVX2 variants * fix(lang): the two Polish lines of the download area written with \n, so they match the tooltip and the hint * fix(files): data named in another case is found on Linux, folders included The parser and the loaders lowercase every name they read, while the data made on Windows has files and folders named in any case (scenery/Braniewo, textures/siec_trakcyjna_ph/.../STS_*.tga, sounds/sip/Gorki.wav). FileCased matched the file name only, so a folder in another case wasn't found. - FileCased walks every part of the path on Linux, the folder listings kept by their lowercase and read again once the folder changed; Windows as it was - FileExists finds the file in any case on Linux, and the variant with names and extensions gives back the name as it's on the disk, so textures, materials, sounds, station announcements and scripts open that name - models, sound captions, timetables and nodebank previews open the file as it's named on the disk; the texture format is told by the extension in any case * fix(files): the banks keep the names asked for, only the opening takes the case of the disk The textures, materials and sounds are kept by the names they're asked for. Given back as named on the disk, a file in another case missed the bank and was loaded again on every request. - FileExists with names and extensions finds the file in any case but gives back the name asked for; FileOnDisk gives the file to open, used where textures, sounds and scripts are opened - FileExists of a single name is a plain check again, the places checking it and opening the same name stay as they were - the texture format is told by the extension asked for again - a folder changed shortly before it was read is read again for a name missing from it, the time of a change being as coarse as the clock of the file system; a listing cut short isn't kept * fix(files): a folder changed in the future isn't read again on every name missing from it * perf(files): a file missing costs a single check, as before Measured in a case sensitive folder (3000 textures, every 20th in mixed case, looked up the way Texture.cpp does), the walk over every part of the path made a texture lookup 4-5 times slower than master: each name tried and missing checked every folder of its path. - the folders found are kept by the name they're given with, the missing ones for a second, so a missing file checks its folder alone - a folder named as it is on the disk is taken without its listing - the time a folder was changed is looked at once a second at most The lookup is now as fast as master's (about 180 us per texture on NTFS in both) while finding the files named in another case too. * fix(files): terrain files named in another case are found on Linux The terrain directive names .txtf/.btf files in lowercase, as the parser gives every token. The name is now taken as it is on disk, from the text file first, so the binary file is made next to the text and the editor's references and layers keep one name. * fix(files): models named in another case are found on Linux The manager of the models looked for the file with FileExists of a single name, a plain check again since the banks keep the names asked for, so a model named in another case (models/przejazdy/plyty3_L, dynamic/pkp/st44_v2/main/2M62-0685-A) was reported missing before TModel3d::LoadFromFile() could open it as it's named on the disk. find_on_disk() finds the file in any case and gives back the name asked for, the key of the bank. * refactor(files): named functions instead of the lambdas of the folder cache (Sonar S2259, S3608, S6004) Sonar took the folder captured by the lambda reading it for a reference to null, failing the quality gate on reliability. The folder is read and the path kept by functions in the anonymous namespace, the age of the listing declared in its if. * fix: the simulator opens more than 512 files at once, and a shader it can't open says why With "physicslog yes" every driver keeps its .dat open, and a large scenery (Tomaszewo: some 500 vehicles, cars of the roads included) took all 512 streams the MSVC runtime gives: the next fopen failed and the simulator stopped at "cannot read shader: shaders/map.vert" on opening the map. The limit is raised to 8192 at the start (the soft limit of open files up to the hard one on Linux), and a shader file that doesn't open is told as such, with the system's reason, rather than as one that can't be read. * feat(blackbox): the black box on its own, writing the tapes of the user's vehicles at the end "blackbox yes" in eu07.ini records the black box with the physics logs on or off, "blackbox no" never; with no entry it goes with "physicslog yes" as before. With the physics logs off, the recorder keeps the line of the physics log of the driver the user is with, every 0.05 s, and writes it to physicslog/<vehicle>.dat when the recording closes: the speed recorder's tape of the vehicles the user was in, without every vehicle keeping a log open and written twenty times a second. The line and the header of the log are made by one function of the driver, which its own log writes too, and the file is opened the same way, so the two are the same to the byte: the readers of these logs (the old Hasler tape viewer, the starter) read them as before. * feat(physicslog): the logs written every two seconds by a thread of their own, no file kept open; the black box's tapes as it goes "physicslog yes" kept the .dat of every vehicle with a driver open for the whole run and flushed it twenty times a second from the simulation's thread: some 580 open files on Tomaszewo. The lines are kept now and a thread of their own writes them every two seconds, each file opened only for the moment it is written to. The files, their lines and their text mode stay as they were. - The black box, with the physics logs off, writes the tapes of the user's vehicles through the same writer as it goes, not at the end. A log begins when the user is first in the vehicle and goes on while the user looks around outside, until another vehicle is taken; back in it, the log goes on after the gap. The vehicle's own driver keeps the log only if it is the primary one, as a passive one's clock stands still; otherwise the driver of its train does. - What is kept is written when the simulator closes, after the black box, at the end of a test run, and when the test watchdog ends a run. A crash loses the last two seconds. - On Tomaszewo with the black box alone, the one tape grows every two seconds. With "physicslog yes", the 581 logs grow and the simulator holds as many handles as without them; writing them takes the thread about 1.9 s, which the closing waits for once. * feat(blackbox): the cab record holds the speed of the wheels, apart from the vehicle's when they slip The speed of the cab record is the vehicle's. The speedometer, and a speed recorder's tape with it, shows the speed of the wheels as they turn, which runs away from it while they slip and drops to 0 while they are locked in a skid. It is added at the end of the record (194 bytes), where the readers skip what they don't know; the .dat tapes have it already, in their second column. * fix(ci): build OpenAL Soft with the PipeWire, PulseAudio and ALSA backends, so the Linux game has sound The Linux job builds OpenAL Soft 1.24.2 from source, but the runner had none of the headers of its audio backends, and OpenAL Soft's CMake leaves out every backend it can't find. The bundled libopenal.so.1 had only OSS, Null, Wave and Loopback. Modern distributions and the Steam Linux Runtime have no /dev/dsp, so the game logged "Failed to obtain audio device" and played nothing, with any Steam Linux Runtime and without one. - install libasound2-dev, libpulse-dev and libpipewire-0.3-dev before building OpenAL Soft - configure it with ALSOFT_REQUIRE_PIPEWIRE/PULSEAUDIO/ALSA, so a missing header fails the build instead of shipping a library without sound The backends are loaded with dlopen at run time (ALSOFT_DLOPEN is on by default), so the bundled library gains no new dependency. Tested by putting an OpenAL Soft 1.24.2 with these backends next to the game from the Steam depot: under Steam Linux Runtime 4.0 the sound works. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(editor): the certificates of https looked for where the distribution keeps them The Linux game bundles the libcurl of Ubuntu, which knows only Ubuntu's /etc/ssl/certs/ca-certificates.crt. Fedora, RHEL and openSUSE keep the certificates elsewhere, so every download of the editor (orthophoto, terrain model, topo map) failed there with a certificate error. The file is taken from SSL_CERT_FILE or CURL_CA_BUNDLE when set, else the first of the files the distributions keep, and passed as CURLOPT_CAINFO. With none found libcurl keeps its own. * fix(editor): an https proxy checked with the same certificates CURLOPT_PROXY_CAINFO gets the file found for CURLOPT_CAINFO, so a download through an https:// proxy on Fedora or RHEL doesn't fail on the proxy's certificate. * fix(ci): the no-AVX2 Windows build has its own concurrency group and its own public download After master was merged the two Windows variants shared one concurrency group with cancel-in-progress, so one cancelled the other, and the publish job looked for an artifact name the matrix no longer produces. Each variant now has its own group, the publish job downloads both, and the release carries maszyna-windows-x64.zip (AVX2, the old name, so the links already handed out still work) and maszyna-windows-x64-noavx2.zip. The AVX2 variant passes -DENABLE_AVX2=ON explicitly instead of an empty flag. * build: a build without AVX2 has _noavx2 at the end of its executable name With ENABLE_AVX2=OFF the executable is eu07-x64_<date>_<hash>_noavx2.exe (eu07-x64_noavx2.exe without ADD_VERSION_SUFFIX), so a starter can tell the two builds apart by the name alone and pick this one on a CPU without AVX2. The AVX2 build keeps its name. * ci: Linux is built without AVX2 too, published as maszyna-linux-x64-noavx2.tar.gz The Linux job becomes the same two-variant matrix as Windows (ENABLE_AVX2=ON/OFF), each variant with a concurrency group of its own. The publish job downloads both Linux artifacts, restores the executable bits in both and releases maszyna-linux-x64.tar.gz (AVX2, the old name) next to maszyna-linux-x64-noavx2.tar.gz. The no-AVX2 executable is eu07_<date>_<hash>_noavx2. * fix(renderer): the legacy renderer clears the arrays the scene left before it draws the ui The legacy renderer drew the ui with the client arrays of the last scene draw still enabled: the texture coordinates of the normal map unit and the normals, pointing into the vertex buffer of whatever was drawn last, 48 bytes a vertex. The ImGui backend sets up the vertex, colour and texture coordinates of the active unit only, so the driver read the stale arrays with the indices of the ui. Once the ui had more vertices than that buffer, the NVIDIA driver read past its end and the game crashed; a crash dump of the editor (an area selected, a track being laid) shows the read of vertex 15113 at a 48-byte stride in ImGui_ImplOpenGL2_RenderDrawData. The arrays are now disabled on every texture unit the geometry uses, with the normal and colour arrays, inside the glPushClientAttrib already there, so the scene gets its state back after the ui. The default and the experimental renderers don't go through this code. * fix(app): a renderer this build doesn't have starts the full one, not the legacy one The starter writes "gfxrenderer vulkan" for the Vulkan renderer of the builds that have it. This exe doesn't know the word, and every word other than default/experimental fell to the legacy renderer: a player who picked Vulkan got the slowest renderer, the one whose ui crashes on NVIDIA (the arrays left by the scene). "experimental" in a build without the NVRHI renderer ended with "no renderer found!" and no game at all. After the settings are read, a gfxrenderer word this build has no renderer for becomes "default", with a line in the log saying so. The words it knows stay as they were: full/default, legacy, simple, null, the older starters' simpleshader and off (legacy as before), and experimental where it is built. * fix(settings): the gfxrenderer word read in any case, as the starter reads it A hand-written "gfxrenderer Legacy" started the legacy renderer only because every unknown word did; with unknown words going to the full renderer it would have changed. The word is lowercased when read, as StarterNG's RenderEngineOf does, so Legacy, Simple or Full mean what they say. * fix(physicslog): a log whose file can't be written keeps its lines and header, and the writer is stopped once on every way out A failed write put its lines back, ahead of those since, so a file held by another program for a while gets its header and every line once it can be written; up to 4 MB kept per log. Stopping is joined once, and not from the writer's own thread. main stops the logs after an error it caught too, and the test watchdog flushes with a time limit, so a disk that doesn't answer doesn't keep the run from ending. * fix(blackbox): the wheels of the powered vehicle, as the speedometer has them, and the logs described as the drivers' they are In a unit driven from an unpowered car, the speed of the wheels was of the car the user is in, whose wheels never slip; now of the motor car, signed as the occupied vehicle's speed. The doc tells of a log per driver, and of the two seconds of real time a crash loses. * fix(physicslog): failed logs kept within 64 MB in all, cut outside the lock, never written twice; the writer knows itself when stopped The lines kept while files can't be written are cut to their share of 64 MB before the lock the simulation waits on. A log written in part is cut back to its length, so the next try doesn't write its start twice. A stop from the writer itself is told by its id even after another thread took it to join, and the watchdog's flush waits at most its time, the writing on a thread of its own. * feat(physicslog): the logs of the trains only, physicslog.trains "physicslog.trains yes" in eu07.ini writes the .dat log of each driver who drives rail vehicles, not of the passengers nor of the road vehicles that make "physicslog yes" hundreds of files on a big scenery: the tape of every train. A driver made primary later begins its log then, and isn't counted while it doesn't log. The black box goes with it when the ini says nothing of its own, and doesn't write a second log of a driver writing its own. The doc tells the doors' sides are the vehicle's, the driver's swapped in the rear cab. * fix(physicslog): a train's log begun at its first line, so passive crews get no file Every crew is primary in the constructor and the drivers but one of a train with crews in more vehicles are made passive only before it starts, so a log begun there left files with only the header. With physicslog on all logs begin at once as before; one of a train waits for update_logs. * fix(editor): the texture pickers let go of the images scrolled past, the memory no longer runs out The picker of the textures of a track offers every texture of the textures folder, and each tile that came into sight read its texture full size, into the graphics card and the memory, and kept it there for good. Scrolling through the list for a trackbed texture took about 2.5 MB a tile: some 900 tiles made 3.5 GB, the whole folder 28 GB, and the game went down once the memory ran out. An image out of sight for 3 seconds is now taken out of both again (texture_manager::unload, Unload_Texture of the renderers) and read anew when it's shown once more, a few a frame as before. Only a texture the scene has never drawn is let go; those of the scene stay to the resource sweep. The texture browser lets go of its images on Refresh too. The picker no longer lists textures/previews: the 4100 previews of the node bank are images of models, not textures of anything. Checked on td.scn by a scripted run: 8000 images of the picker read one batch a few frames after another held the game at 2-3 GB, where it went to 28 GB and fell before; images shown again after they were let go come back; a trackbed texture picked from the folder is drawn on the track after its image was let go. * fix(physicslog): the writer's destructor throws nothing, its wait a plain condition variable woken to stop; a driver of no vehicle controls nothing * fix(editor): the images of the materials let go of with all their textures, the browser's Refresh a frame later An image of a material read the material with all its textures, the normal and specular maps and the variants, and only the first one was let go of: those stayed in the memory for every material scrolled past. They are let go of together now (Unload_Material). texture_manager::unload also takes the textures read and not made yet, waiting for a worker still reading one, and deletes the gl texture itself: release() would read it back from the card with gfx.resource.move only for it to be dropped. The Refresh of the texture browser let go of the images in the middle of the frame, while panels drawn before it could still refer to them; it now marks them, and they go at the start of the next frame. Checked on td.scn by a scripted run: 8040 images of the picker read a batch every few frames end at 2.0 GB, against 2.3-2.6 GB before this and 1.1 GB at the start; a trackbed material picked from the folder is drawn on the track after its image was let go. * fix(physicslog): every stop asked wakes the writer, the one from itself too; no psyche for a driver of no vehicle * fix(editor): the image of a material with no texture in its first slot is let go of too Its normal and specular maps were read with it and stayed in the memory: the trim passed over every image with no texture of its own, the material along with it. * fix(physicslog): nothing that goes wrong in the writing ends the simulator; a name in 1250 makes a path on a Windows set to UTF-8 The writer's thread called flush() with nothing around it, so an exception leaving write() ended the process with std::terminate, with no message. One that happens: the file of a log was made a std::filesystem::path of the vehicle's name, which MSVC converts in the code page of the system and throws for bytes not of it; on a Windows with "Use Unicode UTF-8 for worldwide language support" a vehicle named in 1250, as the sceneries have them (0xB3 for ł), isn't UTF-8. - the file of a log is made of the name with MultiByteToWideChar without MB_ERR_INVALID_CHARS: the same file as before for every name of the code page, U+FFFD for the bytes not of it instead of a throw. Elsewhere the bytes are the name of the file as they were - a log whose writing throws for any other reason (memory) is kept for the next try as one whose file can't be written, and the other logs are written still - the thread, flush_for() and stop() write through flush_safely(), which lets nothing out: what was taken for a writing failing as a whole is lost and told in the log, the next writing goes on - the messages name the file by the bytes of the name, not by path::string(), which converts back Tests: a log which can't be written doesn't keep the others from theirs; a vehicle named in 1250 has its log, read back by physicslog_writer::file(). Reported in the review of #385. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(blackbox): the tapes go on after the editor, with the physics logs off The tapes of the user's vehicles were written by update() after the check for the writer of the recording, which close() drops on entering the editor (F11). With "physicslog no", the speed recorder's tape ended at F11 while the drivers' own logs of "physicslog yes" went on. The tapes are files of their own: they are kept from the moment the recording was to be made, the file made or not, closed or not, until the simulator closes, after the gap of the time in the editor. Only the recording itself stops at F11, as before. Reported in the review of #385. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(physicslog): what no file name may have on Windows is replaced in the name of a log, on every system A spawned vehicle is named <spawn>:<number>, and its log went to physicslog/<spawn>:<number>.dat. On NTFS that isn't even an error: it is the stream <number>.dat of the file <spawn>, which nothing lists, so the log was written and no one could find it. On Linux the file was there, under a name Windows can't open. The name of the file of a log has < > : " / \ | ? * and the control characters replaced by _, on every system, so the logs are named alike everywhere (spawn_ezt:12 is spawn_ezt_12.dat), and a _ before a name Windows keeps for a device (con, nul, com1..., with an extension too). The bytes of 1250 stay. The black box tells the log it begins by the same name. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(renderer): a material's textures let go of in one place, for every backend Unload_Material walked the textures of a material and of its variants the same way in both opengl renderers, and Sonar counted its declarations, set into the long run of overrides the two headers share, as duplicated: 5.2% of the new code, 3% allowed. The walk is gfx_renderer's now, over IMaterial::GetAllTextures and the backend's Unload_Texture. Materials that don't tell their textures, the Vulkan renderer's, give none, and are left alone as before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * AI: shunting brakes for a stop point again; test mode: no false SPAD for a train set across a signal (#409) * fix(ai): shunting AI brakes for a stop point again, the braking curve doesn't plan from a brake table left at zero The braking curve outside the final approach plans from the consist brake table sincece87aa0e(#187, merged with #264) whenever the brake is pneumatic. That table is worked out only for train running (Obey_train, Bank); in shunting it stays at zero, the planned full braking falls to its floor of 0.01 m/s2, and the demand comes out at a few hundredths of a m/s2, above the shunting brake threshold of -0.2. A shunting engine then rolled on without braking until the final approach, too late, and ran through the signal it was to stop at (seed 480873929 of l053_poranek: ep07p-2003 at sandomierz_g4_sem_info, sm42-1096, et22-654). With no worked out table the curve is again the constant deceleration over the distance left, as it was beforece87aa0eand as #187 meant to keep it for shunting. Train running is unchanged. The curve moves out of TController into vehicle/brakingcurve.{h,cpp} so that it is unit tested: tests/unit/test_braking_curve.cpp checks a shunting engine braking to a stop point with the zeroed table, and that a train with a worked out table gets the same demand as before. * test(ai): pin the train braking-curve demand to the results of the code before the move A brake table that grips harder as the train slows and a gradient, so that a wrong gravity sign, table index or a dropped term in the shaped demand shows; the expected values were worked out with the code removed from TController::adjust_desired_speed_for_braking_curve. * fix(test): a train set across a signal doesn't pass it at danger the moment the AI first looks at it The speed table takes in events up to a train length behind the head, so a signal the train stands across at the start of a scenario is found already behind the head, becomes elapsed on its first update, and the test mode reported it as passed at danger (calkowo_lotos: st43-189 at mac_daleko3_sem_info, manewrowo3: st43-100 at suw_szopa_a02_sem_info, both at 13.6 s with the train at a stand, the signal 20 m behind the head). A point now counts as passed only when the head of the train had it ahead once; the blackbox record of passed signals follows the same rule. * fix(test): a signal found up to 5 m behind the head still counts as seen ahead The distance to an event is found in steps of a metre from the position of its memory cell, so a signal just ahead of the head (a train stopped short of it when the autopilot takes over, or set right at it at the start) could come out slightly behind it, and passing it would not be reported. The trains set across a signal that the previous commit is about stood 20 m past it. Still not reported: a signal crossed while the speed table is being traced anew in motion (a Timetable: command to a running train, the autopilot taking over in motion), as it is found behind the head when the trace is made. * docs(test): say what the seen-ahead tolerance gives up A train set less than 5 m past a signal at stop is still reported to pass it at danger: standing that close it can't be told from a train stopped just short of the signal, which the tolerance is there for. --------- Co-authored-by: maj00r <maj00r@host> * fix(camera): the roll of the cab shake tilts the view about the line of sight again (#414)623c4f82(#97, in 26.05.1) changed the order of the camera rotations from Z, X, Y to X, Y, Z. The order matters only with a roll, which the cab shake gives (Angle.z, set in drivermode.cpp), or a camera entry of the scenery with a roll. Applied last, in the space of the cab, the roll nodded the view up and down when looking out of a side window instead of tilting it. The roll is multiplied in first again, as in 26.05. Co-authored-by: maj00r <maj00r@host> * fix(particles): the smoke of a cold diesel keeps the colour of its template (#413)bcb9e644(#109) turned a comparison into an assignment: the smoke of a vehicle in air at 5 degrees or less, or with its engine under 45 degrees, got the colour 128,128,128. The emitter colour is on a 0-1 scale, so the smoke turned pure white, glowing at night, and stayed so once the engine warmed up. Up to 26.05 the line compared and did nothing; the smoke keeps the colour of its template again, as it did then. Co-authored-by: maj00r <maj00r@host> * Fix stutter with fpslimit on Windows and a texture unit cache race with threaded Python screens (#399) * fix(render): the python upload thread only marks the texture unit cache stale, the drawing thread clears it update_from_memory() runs on the python upload thread with python.threadedupload (the default), and sincee230d7b9it cleared opengl_texture::units there outright. That raced Bind_Material filling the same array for its multi-bind: a unit reset between the fill and glBindTextures() made the bind of that unit fail, and the object was drawn with the texture of the one drawn before it, for a frame, at the rate of the screens. The thread now sets an atomic flag, and the drawing thread clears the cache when it next binds textures (bind() and the multi-bind of Bind_Material), so a screen texture given a new gl name is still rebound. * fix(app): fpslimit asks Windows for the 1 ms timer, the frames no longer come in turns long and short The wait of fpslimit sleeps, and Windows wakes a process which didn't ask for a finer timer in steps of up to ~15.6 ms. A 10 ms slot of fpslimit 100 ended ~15.6 ms later, the pacer made it up with no wait in the next frame, and with vsync on the frames were shown for one or two refreshes in turn: visible stutter at a steady FPS. timeBeginPeriod(1) is held from the settings to the exit, only when fpslimit is set. * fix: the 1 ms timer also for an fpslimit set by the scenery, the stale unit cache checked with a plain load first A config block of the scenery is parsed after the settings and can set fpslimit, so the timer period is asked for at the first wait of the pacer too, once. bind() checks the stale flag of the unit cache with a relaxed load before the exchange, which it does for every texture. * fix(textures): the stale flag of the unit cache uses the default memory order (Sonar S8417) On x86 a sequentially consistent load and exchange cost the same as the relaxed and acq_rel ones; only the store in invalidate_unit_cache() becomes an xchg, and it runs rarely. --------- Co-authored-by: maj00r <maj00r@host> * fix(camera): the cab shake taken at the frame's moment between its fixed steps, it no longer moves in steps (#403) The shake of the cab camera (ShakeState) is stepped by update_shake at a fixed 1/50 s, while the camera read the raw state every frame. At any frame rate other than 50 the shake moved in steps: some frames showed the same state as the one before, others jumped one or two steps at once. Players with 144/165 Hz screens saw the cab jump around the camera. The vehicle now keeps the state from before the last step (ShakeStateBefore), and the camera takes the state between the two at the share of the step the simulation time has reached (shake_between). The offset and the velocity are blended, the angles worked out from the blended velocity. The shake itself is computed as before, with the same fixed step and the same springs; only what the camera shows of it changes. It lags the vehicle by a constant 1/50 s instead of 0 to 1/50 s. Measured with the same build and the blending switched off by a temporary environment variable (not in this commit), the EU07 on td.scn driven by the AI, frames over 30 km/h, two runs of each: - 60 fps: frames with the shake standing still 25% -> 0%, the change in its speed frame to frame 4-5 times smaller for the offset, a third smaller for the angles - ~144 fps: 65% -> 0%, 10-18 times smaller for the offset, 4 times for the angles - no fps limit (~520 fps): 90% -> 0% Co-authored-by: maj00r <maj00r@host> * fix: inverted clamp bounds give the upper bound again, as the old clamp did (#412) * fix: inverted clamp bounds give the upper bound again, as the old clamp did The project's own clamp() of 26.05 applied the lower bound first and the upper one last, so bounds given the wrong way round always gave the upper one. Its calls became std::clamp (undefined for such bounds) and, where the bounds can cross, safe_clamp, which swapped them instead. Neither gives the old result. - safe_clamp is the old clamp again, min(max(value, lo), hi). This restores 26.05 at every place it is used, among them the AI's dynamic brake test (its demand was fAccThreshold x1.21, the swap made it x1.01), the generator voltage, the heavy cargo acceleration of the AI and the EP correction of the brake. - The cab camera is kept inside the cab with safe_clamp. The bounds come from the .mmd as written and some cabs have them reversed (the B cars of SA134 and 21xM, ET40, 754); with std::clamp the camera jumped between the two bounds every frame on MSVC, as its result is fed back. * fix: every call of the old clamp gives what it gave up to 26.05.1d1f16411(#99) made every call of the project's clamp() std::clamp. Where the bounds come from the data or are computed at runtime they can cross, and then std::clamp gives another result (undefined behaviour; MSVC gives the lower bound unless the value is above the upper one) where the old clamp gave the upper bound. These calls use safe_clamp, the old clamp, too: - Mover: the pantograph pressure (MaxPress), the compressor switch (CompressorListPosNo), the coupler distance (DmaxB, DmaxC), the engine revolutions, the eimic ramp (CtrlDelay), the eimic limit (eimic_max), the speed control ramp (PowerUpSpeed, PowerDownSpeed), the load (MaxLoad), the magnet of the security system (Dim.L); - DynObj: the coupler distance of the buffers (DmaxB), the axle distance (Dim.L); - Train: the brake handle positions (BrakeCtrlPosNo, the range of the handle); - the legacy renderer: the mouse pick (the window size). With the bounds in order nothing changes. Calls whose bounds the code keeps in order (constants, SplineFidelity 1-4, the season table, the guarded output calibration) give the same result with std::clamp and stay as they are. The load offset takes its arguments in the 26.05.1 order again;fa2ed089swapped them, which with the old clamp differs only for a negative load. The bump at a rail joint gives the old result again. Up to 26.05.1 its clamps had 0 in place of the value (since96f43e11and4d72d352), and the old clamp made that the headroom Vmax - (Vel + 0.32 Vmax), negative above 68% of the top speed, capped from above only;d464628aand03bfbb13kept it at 0 or above. Only damaged track has the bump: a damage flag in the .scn, a derailer set by an event, a track made on a derailment. The interior light of the cab in the 3.3 renderer is computed in double again, as befored1f16411. The call added since (stepped_uc_value,00955513) keeps what master does: bounds given the other way round are put in order. * fix: the alpha of a particle in the legacy renderer as up to 26.05.1, the NaN cases of the clamp tested Up to 26.05.1 the alpha was clamp<std::uint8_t>( particle.opacity * 255, 0, 255 ): the float was made a byte first, so the clamp did nothing and an opacity over 1 (a smoke max_opacity over 1) wrapped round, 1.2 giving 50. The move to std::clamp made it 255. It's made a byte as then again, through int: the byte the x86-64 compilers gave, without the undefined behaviour of that conversion (MSVC makes the same two instructions of both). openglparticles.cpp goes with feat/gl46-migration; its opengl33 counterpart, std::clamp( opacity, 0, 1 ), already gives what 26.05.1 gave. The tests pin what the old clamp gave with NaN: a NaN value stays NaN, a NaN bound doesn't clamp. The checks named after the AI braking test and the bump at a rail joint say they test the helper with the arguments of those calls, not the calls. * test: the includes of the clamp tests before the project's headers <cmath> and <limits> go up, after the test headers, so the change no longer touches the lines #416 adds its includes after. With both merged <cmath> is included twice, which is harmless. --------- Co-authored-by: maj00r <maj00r@host> * Python screens: the worker's image goes in place only after its fence, not a bare glFlush (#411) * fix(python): a screen uploaded by the worker goes into a texture of its own, put in place after a fence With python.threadedupload (the default) the worker wrote the image into the texture the drawing thread draws from, with glTexImage2D and glGenerateMipmap from its own context, and only a glFlush after. Nothing ordered the two contexts: the drawing one could sample the texture while its storage was being made anew, its level 0 half written or its mipmaps not made yet, and on a change of size the worker deleted the texture and wrote a new name into `id` with no synchronisation. The worker now uploads each image into a new texture, sets a fence after it and flushes. The drawing thread, once per frame in python_taskqueue::update(), waits for that fence on the gpu (glWaitSync, the cpu goes on), deletes the old texture and puts the new one in place. The worker no longer touches the texture drawn from, nor `id`. An image the drawing thread didn't take yet is dropped by the next one. Without sync objects the worker waits for the upload with glFinish. The windows of python.displaywindows with python.sharectx bound the texture once; they now bind the name of the last image put in place, which python_rt keeps for them. Uploads on the drawing thread (python.threadedupload no, the Lua and WebAssembly screens, the editor) are as they were. * fix(python): the image of the worker goes in place once its fence is signalled, the viewer binds it each frame From the review of8811ee5a: - glWaitSync ordered only the context of the main window. The extra viewports and the windows of python.displaywindows draw in contexts of their own and could bind the new texture before the upload was done. commit_thread_upload() now asks the fence without waiting (glClientWaitSync, timeout 0) and puts the image in place only once it is signalled, so every context binding it afterwards has it whole. Until then the task stays in the upload queue and is asked again the next frame. - The drawing thread chose between upload and commit by python.threadedupload, the worker by whether it got a context. With python.threadedupload on and no context made for the worker, the screens were no longer updated. The task now records that a worker uploaded it. - The viewer of python.displaywindows told a new image by its texture name, but a deleted name comes back for a later texture. It binds the name of the last image each frame, read under the lock of the render target, and the name it starts with is read on the drawing thread when it is made. * fix(python): the old texture deleted under the lock the viewers bind under, a fence not made waited for with glFinish From the review of #411: - finish_upload() deleted the old texture before it took the lock of the render target, and the windows of python.displaywindows read the name under that lock but bound it after letting go of it. A window could bind a name already deleted, or already given to the next upload. In a compatibility context (the legacy renderer) that makes a new empty texture: a black frame and a texture never deleted. The commit and the publishing of the new name now go under the lock, and the viewer binds under it too. A name bound before the deletion stays alive in that window's context while bound. - A glFenceSync that returns no fence was taken for a signalled one: the image went in place at once, with nothing ordering the contexts. The worker now waits for its upload with glFinish then, as without sync objects. * fix(python): the worker waits for the lock of the screen without the gil, no flush after a finish From the review of939514ea: - The drawing thread now holds the lock of the render target for a whole upload with python.threadedupload off. The worker, copying the next image under that lock, waited for it holding the gil. It now lets the gil go around the lock and the copy: the bytes it copies stay valid, the object is immutable and held by the reference the worker has. - glFlush after glFinish did nothing; the worker flushes only when it made a fence. --------- Co-authored-by: maj00r <maj00r@host> * fix(models): a scenery light that is off no longer shows lit for a moment the first time it comes into view (#407) * fix(models): a scenery light that is off no longer shows lit for a moment the first time it comes into view Sinced13c27a7(the light blinking rework) the opacity of a light changes step by step from its last value, and the opacities start at 1. RaAnimate runs only for the instances that are drawn, so a model with "lights 0" (a W24 LED indicator, for one) was drawn lit when it first came into range and faded out over 0.45 s. Befored13c27a7the opacity of a plain on/off light was worked out anew from a timer starting at 0, so a light that is off was off from the first frame. Now the first time an instance is animated its lights take their current state at once, whether it came from the definition or from an event since. Every later change fades as before. The light threshold modes (ls_Dark, ls_Home) are untouched. The only other difference from befored13c27a7: a light that is on no longer fades in the first time it is drawn. * fix(models): the light opacity step written without an implicit double to float conversion (Sonar S5276) The sum is still worked out in double and rounded to float once, as the compound assignment did, so the result is the same to the bit. --------- Co-authored-by: maj00r <maj00r@host> * Editor: switch drives with no switch listed and marked; a deleted switch takes its drives and ballast along (#330) * 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… * fix: a failed start says why and ends with an error code; a small crash dump by default (#425) * fix: a failed start says why in the log and ends with an error code When the window could not be made, the log only said "Bad init: failed to create glfw window", without the reason glfw knows (no OpenGL driver, no pixel format that fits, no EGL). Sometimes it did not even say that: the log thread writes every 50 ms, and main() ended the process with std::_Exit(0) without stopping it, so a start that failed within that time left a log that ends at "// startup". - glfw's errors go to the log and errors.txt through glfwSetErrorCallback, set before glfwInit(); each distinct message once. - after a failed start (or an exception caught in main) the log thread is stopped and waited for, as the test runs already do, so nothing logged last is lost. - a failed start ends with exit code 1 instead of 0, so the starter can tell it from a closing. A start that worked ends as before. * fix: glfw's errors told during the start only, a closed crash dialog is no failed start After review of the previous commit: - the glfw error callback is taken off at the end of init(). Once the simulator runs, glfw would only repeat what the platform can't do (glfwSetCursorPos on Wayland, on every mouse-look) or what a scenery asks for in vain (launcher key codes below GLFW_KEY_SPACE, checked on every update), which would put new lines in errors.txt of existing sceneries and cost a format and a lock per call. - closing the crash-report window ends the simulator as before, but init() now returns 1 for it (above 0: closed by the player), and only a result below 0 gives exit code 1. - a start that throws from init() (bad_alloc, or a runtime_error on Windows) ends with exit code 1 too; an exception after a start that worked ends with 0 as before. * feat: a small crash dump by default, the full one with "crashdump.full yes" The dump written by the crash handler (Windows, WITHDUMPGEN) held all the memory of the simulator (MiniDumpWithFullMemory), so it was as large as the memory the simulator took: gigabytes on a large scenery, written to the game folder at the moment of the crash, on machines with 8 GB of RAM too. By default it now holds the stacks with the memory they point to, the threads, the modules, the handles, the memory map and the modules' data segments (MiniDumpWithDataSegs in place of MiniDumpWithFullMemory, the rest of the flags as before). The globals, Global among them, stay readable. "crashdump.full yes" in eu07.ini writes the full dump as before. Measured on td.scn with a ghostview camera (1.2 GB committed): the small dump 44 MB in 2 s, the full one 1.6 GB in 19 s. The key is new and optional: eu07.ini files without it read as before, and the setting is listed in the log at start. * fix: the small crash dump keeps the process and thread blocks MiniDumpWithProcessThreadData adds the PEB and the TEBs, a few KB: the command line (the scenery and the vehicle), the environment and the last error of each thread, which the small dump otherwise lacks, since the heap behind Global's longer strings is not in it. * fix: an exception that ends the simulator says what it was in the log After review of #425: - the exceptions main() catches are logged ("Critical error: ..."): on Windows the runtime_error that only showed a message box, and on the other systems any std::exception, which used to end the simulator through std::terminate with no word in the log. On Windows the others are still left to CrashHandler, whose dump shows where they were thrown. - every exception caught there ends with exit code 1, in the start or later, as a crash; it used to be 0 when caught, the abort code when not. - closing the crash-report window logs "Crash report window closed, closing" instead of the error "Failed to run crash gui!", which stays for a result below 0. * feat: the stack of a crash on Linux in the log and on the standard error On Linux no dump is written (the crash handler is Windows only, crashpad is off), so a crash left a log that just stopped. A handler of SIGSEGV, SIGBUS, SIGFPE, SIGILL and SIGABRT (installed at the start of main) now writes, with write() only: Crash: signal 11 (SIGSEGV) at address 0x... Version: EU07 (cmake), <hash> (...) Stack (addr2line -f -C -e <the eu07 file of this version> <offset>): <backtrace_symbols_fd> to the end of the log file (its whole path, set when the log opens it) and to the standard error, which StarterNG shows first. The Linux builds carry their symbols (GENERATE_PDB adds -g, nothing strips them), so addr2line on the eu07 file of the same version gives the files and lines. Then the signal ends the process as before (SA_RESETHAND, raise): the same exit status, and a core dump where the system makes one. The handler runs on an alternate stack, so an overflow of the main thread's stack is reported too; backtrace() is warmed up at install so it doesn't allocate in the handler, and alarm(5) ends a handler that hangs (a crash in the allocator or the loader). WAMR is built without its hardware bound checks, so it installs no SIGSEGV handler of its own. Elsewhere crash_signals does nothing. A unit test (Linux only) crashes a child process and checks the report on its standard error and in the log, and that the child still ended by SIGSEGV. * fix: the crash report can't be cut by a second crash signal or end with SIGALRM After review: - the five crash signals are blocked while a report is written, so a second one waits rather than starting a second report in its middle (a fault that comes while blocked still ends the process). - a report that hangs past alarm(5) ends the process by the signal of the crash, not by SIGALRM: a SIGALRM handler, set only in the crash handler, raises the crash signal and unblocks it. - the child of the unit test calls alarm(10) first, so a child stuck before the crash can't hang the build. --------- Co-authored-by: maj00r <maj00r@host> * feat(track): unevenness waves shaped by the track spectra of FRA and ORE B176 (#426) * feat(track): unevenness waves shaped by the track spectra of FRA and ORE B176 The waves were 5-42 m sideways and 8-83 m vertically, with the long ones cut down, so a short wavelength carried a large share and the ride and the rails looked busy. They are now 7-90 m sideways and 8-110 m vertically, about the bands D1-D3 of EN 13848, each wave standing for a band of the spectrum S ~ Wc^2 / (W^2 (W^2 + Wc^2)), Wc = 0.8245 rad/m, the shape the FRA and the ORE B176 (German) spectra share: the longer a wave, the higher it is. The "uneven" value keeps its meaning, the peak deviation of a rail on a 10 m chord as PLK Id-14 measures it, so the values in sceneries stay as they are. Since the chord sees the long waves less, the amplitudes are calibrated again, and apart for the vertical and the sideways waves: stray_per_mm becomes stray_up_per_mm 0.00229 and stray_side_per_mm 0.0031, and cross_share 0.35. A track at "uneven 18" measures 18 mm vertically, 17 sideways, 15 of twist, +-10 of gauge, 21 of cross level and J 5.7 against the Id-14 limits for 80 km/h. A rail now goes up to about 5 cm off its design over the long waves, so the bound of the test goes from 40 to 60 mm; the short waves the cab shakes on are smaller, the sideways bend under the axles about 30% less. Every scenery with unevenness looks and rides differently after this. No release has unevenness yet. The grading tool follows the vertical waves; on Baltyk the pantograph keeps within 0.6 cm of the wire up to the product 1150 of the vertical value and the speed (925 before). * test(track): bound the sideways offset of an uneven track off its design The longer waves move the track about 4.5 cm sideways off its design at "uneven 18" (2 cm before), and nothing checked or stated it. The Id-14 test now bounds the peak sideways offset of the middle of the track below 5 cm, next to the vertical one, so a later change of the shares can't double it unnoticed. The doc gives the figure, and names platform edges and level crossing panels among what a rail moves away from. --------- Co-authored-by: maj00r <maj00r@host> * feat(editor): ~ shows or hides the orthophoto, Ctrl+~ downloads what the camera sees first; the speed of the camera in the View menu (#312) * feat(editor): ~ shows or hides the orthophoto, Ctrl+~ downloads what the camera sees first; the speed of the camera in the View menu ~ (the key left of 1) turns the orthophoto on and off. Ctrl+~ finds what of the ground the camera sees (rays through a grid over the screen down to the level of the ground under the camera, or as far as 2.5 km where they don't come down to it) and puts those tiles at the front of the queue of the downloads, the ones which failed tried again at once; the status line tells how many. Tab is not used, the laying and the switches have it. View > Camera speed: the speed of the free camera of the editor (x0.05 to x10, 1 as it was), how many times faster Ctrl makes it (1 to 30, 30 as it was), and in the top view as fast as the view is zoomed, so the map crosses the screen at the same pace zoomed in or out. Kept in the settings of the editor; the camera of the cab and of the free fly outside the editor unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DDcMn1Q7wdYkbxDUWscNHZ * fix(editor): Ctrl+~ in the top view, over a scenery with no terrain under the camera and with the orthophoto off; "As it was" without the speed going with the zoom In the top view the box is the view itself, its corners on the ground. The ground under the camera is the terrain, else the scenery, else the rays go as far as the reach. The tile of the camera is taken anew by hurry(), it isn't followed while the layer is off. The top view is as fast zoomed in as out by default, as before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DDcMn1Q7wdYkbxDUWscNHZ * fix(editor): the corners of the top view on the ground put where the camera is (the view matrix is camera-relative) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DDcMn1Q7wdYkbxDUWscNHZ * i18n(editor): Polish for the orthophoto keys and the camera speed, on top of the master's own translations Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DDcMn1Q7wdYkbxDUWscNHZ * fix(editor): Ctrl+~ asks only for the tiles update() would ask for; the tooltip of "Track colours" back in its place After the reviews of #312: - hurry() skips the tiles outside the download area set and marks the ones outside the area the service covers as empty, as update() does, so Ctrl+~ no longer queues downloads update() drops at once (and the workers took anyway, into the disk cache, against the area set), nor requests the service can't answer. - A blank tile hurried takes the standard image first, as in update(); first_level() and outside_area() are shared by both loops, and the body of the loop of hurry() is hurry_tile(). - orthophoto_hurry() takes the level of the terrain only when it's below the camera, as the branch of the scenery already did: a camera under the terrain (a tunnel, under the heightmap) no longer flips the box of the view behind it. - The "Camera speed" menu goes after the tooltip of "Track colours", which it had taken. - #include <set> once in editorOrthophoto.hpp. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QRgQ1K1Qu7TCsa74zsNURd --------- Co-authored-by: Claude <noreply@anthropic.com> * fix: whole-number bounds of Random() give a real number again (#416) * fix: whole-number bounds of Random() give a real number againee3af0bf(#99, in 26.05.2) renamed RandomInt to an overload, Random(int, int). The calls with whole-number bounds that expect a real number in between took the overload and draw whole numbers since: - wheel flats given with P0 happen to 1 vehicle in 101 (before: none), the random part of a flat is a whole number of millimetres; - the chance of truck hunting is h/101 instead of h/100; - the wind starts with a whole azimuth, speed and rates of change, and its direction changes in whole degrees per second; - the tachometer below 5 km/h jumps to whole numbers. The whole-number draw is RandomInt again, keeping the shared engine and the swap of inverted bounds; the loading screen's trivia use it. Those calls take the real Random() again, as up to 26.05.1. * RandomInt: the comment says what it draws and why it has a name of its own The comment put the bug on the overloading. It was in the calls that pass whole-number bounds and expect a real number; the separate name keeps them on Random(double, double). * fix: RandomInt draws from the local engine, as up to 26.05.1 from one of its own From the review of #416:ee3af0bfmoved RandomInt from an engine of its own (std::mt19937 seeded by std::random_device) to Global.random_engine, the engine of the run's seed, and only the name was taken back here. Its one caller draws the trivia of the loading screen, in init_modes, before a network client gets the seed of the session in server_hello: the server's engine was then one draw ahead of the client's, and with a fixed randomseed the trivia was the same on every start. It is drawn from Global.local_random_engine now, the engine of what one machine shows, seeded from a true random source in init_modes before the loader is made. The test of the same seed checks the shared engine with Random() and the local one with RandomInt(); a new test checks that RandomInt() doesn't move the engine of the run's seed. --------- Co-authored-by: maj00r <maj00r@host> * fix(editor): the orthophoto only on the chunks of the heightmap terrain in memory, and laid onto the ground again once it comes (#417) * fix(editor): the orthophoto only on the chunks of the heightmap terrain in memory, and laid onto the ground again once it comes Right after the editor started, the tiles of the orthophoto came from the disk cache at once and were fitted to the ground before the chunks of the heightmap terrain had come (on IRT the orthophoto was on at 24.5 s, the first chunk came at 24.5 s, the last one at 85 s). A tile with no ground under it, and none beside, stayed flat at the height of the layer (0 m, some 230 m under IRT); one partly over the ground had its holes filled from the points beside. Neither was fitted again when the ground came: only the guessed tiles were, by their middle and corners alone, and a tile with no chunk under it at all never got any. The overlay, drawn over everything, then slid with the camera (WASD, turning) instead of lying on the ground. Turning the orthophoto off and on hid it: by then the terrain was in and the tiles took their heights from it or from the edges of the tiles beside. - With the heightmap terrain (the terrain streamer active), a tile of the orthophoto, of the WMS layers and of Ctrl+~ is asked for and shown only where its chunks are in memory (terrain_streamer::ground_under): it waits while one is still to come, and where no chunk is nor will be there's no imagery at all. A scenery without the heightmap terrain is as before. - A tile remembers the points of its grid the ground didn't answer and is fitted again once the ground comes under any of them (every second point and the edges), not only the guessed tiles. No asset changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(editor): the orthophoto waits only for the chunks that will come at this distance, and lies on the other ground or the guess elsewhere After the reviews of maj00r and jerrrrycho on #417: - A tile is no longer dropped where no chunk of the heightmap terrain is nor will be. There it lies on whatever ground there is (terrain models) or on the NMT guess, as on master; a scenery with a few chunks, or with chunks removed, keeps its imagery around them. - A chunk counts as still to come only while it's being loaded or lies within the circle the streamer walks around the camera. The corners of the imagery in the 3D view, beyond that circle, no longer wait for chunks that won't load there: they lie on the guess and are sampled again when the camera comes near and the chunk loads. - terrain_streamer::ground_under() (true / false / empty) became ground_coming() (bool), the cover source of the orthophoto the coming source, and on_ground() waits_for_ground(), which only holds back a new tile. - In the scene (in_scene), the points a steep triangle leaves without a height but the heightmap terrain answers aren't kept as unanswered, so the tile isn't sampled again on every chunk that comes. The holes are counted from the heights again, as on master. --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> * fix(editor): the closing doesn't wait for a geoportal service that doesn't answer (#432) * fix(editor): the closing doesn't wait for a geoportal service that doesn't answer When geoportal.gov.pl took the connection and never answered, the editor's closing stood still for tens of seconds and was killed: the WinHTTP client was synchronous and looked at the stop only between the reads of a body, so a request waiting for the answer held the closing for the timeouts (up to 20 s for the answer, a few tries a square), and the map of the place-picker downloaded with no stop at all, its std::async future waited for to the end. On Windows the client now uses WinHTTP asynchronously: each step is waited for while the stop is looked at every 50 ms, and a stop closes the request at once. The timeouts, the user agent, the size limit, the errors and the body of a response with an error status stay as they were. The map of the place-picker is given up when it goes. libcurl looked at the stop during the whole transfer already. The unit tests run the client against a local server that never answers (given up within 0.4 s of the stop), one with a body of 100 kB and one with an error status. * fix(editor): the capabilities of a WMS service being added don't hold the closing either The reading of the layers of a WMS service the user adds ran on a std::async future of the editor with no stop: closing the editor while such a service didn't answer waited for its three tries. The reading is given up when the editor goes, as the other downloads now are, and editor_http_get, left with no callers, goes. The unit test's silent server no longer waits for the client to close its connection, and the requests to the local server are skipped when the environment names a proxy, which couldn't reach it. * fix(editor): the stop of the WMS reading outlives the future waiting for it The flag was declared after the future of the reading, so it was destroyed first while the future's destructor still waited for the task reading it. --------- Co-authored-by: maj00r <maj00r@host> * revert(environment): the turbidity of the sky as it was before #227 (#410) #227 (842b7688) raised the turbidity of the sky dome for most cloud covers (3 -> 4 for a clear sky, 5 -> 6 at 0.41-0.60, one more from 0.61 up to 0.90). In the Preetham model a higher turbidity darkens the sky a lot once the sun is below the horizon: with a cover of 0.47 the zenith is about a third darker 1.4 degrees below it and half as bright 3 degrees below, the stars come out right after the sunset and the ambient light taken from the sky dome drops with it. Players report the dusk as too dark since the update. The values are put back as they were before #227, in the turbidity_of() that #323 made of the old chain of conditionals. A clear sky gets the turbidity 3 again, which #227 said breaks the model at night. Co-authored-by: maj00r <maj00r@host> * Revert "fix(physicslog): no road-vehicle logs, formatting on the writer, a slow disk and the closing kept short (#408)" This reverts commitd6c3593520. --------- Co-authored-by: maj00r <73280030+maj00r@users.noreply.github.com> Co-authored-by: maj00r <maj00r@host> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Hirek193 <polomarket73@gmail.com> Co-authored-by: pol102 <mindak.m@icloud.com>
9333 lines
421 KiB
C++
9333 lines
421 KiB
C++
/*
|
|
This Source Code Form is subject to the
|
|
terms of the Mozilla Public License, v.
|
|
2.0. If a copy of the MPL was not
|
|
distributed with this file, You can
|
|
obtain one at
|
|
http://mozilla.org/MPL/2.0/.
|
|
*/
|
|
/*
|
|
MaSzyna EU07 locomotive simulator
|
|
Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others
|
|
|
|
*/
|
|
|
|
#include "stdafx.h"
|
|
#include "vehicle/Driver.h"
|
|
|
|
#include "utilities/Globals.h"
|
|
#include "utilities/translation.h"
|
|
#include "utilities/Logs.h"
|
|
#include "utilities/physicslog.h"
|
|
#include "vehicle/Train.h"
|
|
#include "vehicle/brakesetting.h"
|
|
#include "vehicle/brakingcurve.h"
|
|
#include "vehicle/handover.h"
|
|
#include "vehicle/timetableservice.h"
|
|
#include "world/mtable.h"
|
|
#include "world/stationnames.h"
|
|
#include "vehicle/DynObj.h"
|
|
#include "world/Event.h"
|
|
#include "world/MemCell.h"
|
|
#include "simulation/simulation.h"
|
|
#include "simulation/blackboxrecorder.h"
|
|
#include "simulation/simulationtime.h"
|
|
#include "simulation/simulationtest.h"
|
|
#include "world/Track.h"
|
|
#include "world/station.h"
|
|
#include "input/keyboardinput.h"
|
|
|
|
#include <algorithm>
|
|
#include <format>
|
|
#include <ranges>
|
|
|
|
#define LOGVELOCITY 0
|
|
#define LOGORDERS 1
|
|
#define LOGSTOPS 1
|
|
#define LOGBACKSCAN 0
|
|
#define LOGPRESS 0
|
|
|
|
// finds point of specified track nearest to specified event. returns: distance to that point from the specified end of the track
|
|
// TODO: move this to file with all generic routines, too easy to forget it's here and it may come useful
|
|
double
|
|
ProjectEventOnTrack( basic_event const *Event, TTrack const *Track, double const Direction ) {
|
|
|
|
auto const segment = Track->CurrentSegment();
|
|
auto const nearestpoint = segment->find_nearest_point( Event->input_location() );
|
|
return Direction > 0 ? nearestpoint * segment->GetLength() : // measure from point1
|
|
(1.0 - nearestpoint) * segment->GetLength(); // measure from point2
|
|
};
|
|
|
|
double GetDistanceToEvent(TTrack const *track, basic_event const *event, double scan_dir, double start_dist, int iter = 0, bool back = false)
|
|
{
|
|
if( track == nullptr ) { return start_dist; }
|
|
|
|
auto const segment = track->CurrentSegment();
|
|
auto const pos_event = event->input_location();
|
|
double len1, len2;
|
|
double sd = scan_dir;
|
|
double seg_len = scan_dir > 0 ? 0.0 : 1.0;
|
|
double const dzielnik = 1.0 / segment->GetLength();// rozdzielczosc mniej wiecej 1m
|
|
int krok = 0; // krok obliczeniowy do sprawdzania czy odwracamy
|
|
len2 = glm::length2(pos_event - segment->FastGetPoint(seg_len));
|
|
do
|
|
{
|
|
len1 = len2;
|
|
seg_len += scan_dir > 0 ? dzielnik : -dzielnik;
|
|
len2 = glm::length2(pos_event - segment->FastGetPoint(seg_len));
|
|
++krok;
|
|
} while (len1 > len2 && seg_len >= dzielnik && seg_len <= 1.0 - dzielnik);
|
|
//trzeba sprawdzić czy seg_len nie osiągnął skrajnych wartości, bo wtedy
|
|
// trzeba sprawdzić tor obok
|
|
if (1 == krok)
|
|
sd = -sd; // jeśli tylko jeden krok tzn, że event przy poprzednim sprawdzaym torze
|
|
if ((1 == krok || seg_len <= dzielnik || seg_len > 1.0 - dzielnik) && iter < 3)
|
|
{ // przejście na inny tor
|
|
track = track->Connected(int(sd), sd);
|
|
start_dist += 1 == krok ? 0 : back ? -segment->GetLength() : segment->GetLength();
|
|
if( track != nullptr
|
|
&& track->eType == tt_Cross ) {
|
|
// NOTE: tracing through crossroads currently poses risk of tracing through wrong segment
|
|
// as it's possible to be performerd before setting a route through the crossroads
|
|
// as a stop-gap measure we don't trace through crossroads which should be reasonable in most cases
|
|
// TODO: establish route before the scan, or a way for the function to know which route to pick
|
|
return start_dist;
|
|
}
|
|
else {
|
|
return GetDistanceToEvent( track, event, sd, start_dist, ++iter, 1 == krok ? true : false );
|
|
}
|
|
}
|
|
else
|
|
{ // obliczenie mojego toru
|
|
seg_len -= scan_dir > 0 ? dzielnik : -dzielnik; //trzeba wrócić do pozycji len1
|
|
seg_len = scan_dir < 0 ? 1 - seg_len : seg_len;
|
|
seg_len = back ? 1 - seg_len : seg_len; // odwracamy jeśli idzie do tyłu
|
|
start_dist -= back ? segment->GetLength() : 0;
|
|
return start_dist + segment->GetLength() * seg_len;
|
|
}
|
|
};
|
|
|
|
/*
|
|
|
|
Moduł obsługujący sterowanie pojazdami (składami pociągów, samochodami).
|
|
Ma działać zarówno jako AI oraz przy prowadzeniu przez człowieka. W tym
|
|
drugim przypadku jedynie informuje za pomocą napisów o tym, co by zrobił
|
|
w tym pierwszym. Obejmuje zarówno maszynistę jak i kierownika pociągu
|
|
(dawanie sygnału do odjazdu).
|
|
|
|
Przeniesiona tutaj została zawartość ai_driver.pas przerobiona na C++.
|
|
Również niektóre funkcje dotyczące składów z DynObj.cpp.
|
|
|
|
Teoria jest wtedy kiedy wszystko wiemy, ale nic nie działa.
|
|
Praktyka jest wtedy, kiedy wszystko działa, ale nikt nie wie dlaczego.
|
|
Tutaj łączymy teorię z praktyką - tu nic nie działa i nikt nie wie dlaczego…
|
|
|
|
*/
|
|
|
|
// zrobione:
|
|
// 0. pobieranie komend z dwoma parametrami
|
|
// 1. przyspieszanie do zadanej predkosci, ew. hamowanie jesli przekroczona
|
|
// 2. hamowanie na zadanym odcinku do zadanej predkosci (ze stabilizacja przyspieszenia)
|
|
// 3. wychodzenie z sytuacji awaryjnych: bezpiecznik nadmiarowy, poslizg
|
|
// 4. przygotowanie pojazdu do drogi, zmiana kierunku ruchu
|
|
// 5. dwa sposoby jazdy - manewrowy i pociagowy
|
|
// 6. dwa zestawy psychiki: spokojny i agresywny
|
|
// 7. przejscie na zestaw spokojny jesli wystepuje duzo poslizgow lub wybic nadmiarowego.
|
|
// 8. lagodne ruszanie (przedluzony czas reakcji na 2 pierwszych nastawnikach)
|
|
// 9. unikanie jazdy na oporach rozruchowych
|
|
// 10. logowanie fizyki //Ra: nie przeniesione do C++
|
|
// 11. kasowanie czuwaka/SHP
|
|
// 12. procedury wspomagajace "patrzenie" na odlegle semafory
|
|
// 13. ulepszone procedury sterowania
|
|
// 14. zglaszanie problemow z dlugim staniem na sygnale S1
|
|
// 15. sterowanie EN57
|
|
// 16. zmiana kierunku //Ra: z przesiadką po ukrotnieniu
|
|
// 17. otwieranie/zamykanie drzwi
|
|
// 18. Ra: odczepianie z zahamowaniem i podczepianie
|
|
// 19. dla Humandriver: tasma szybkosciomierza - zapis do pliku!
|
|
// 20. wybór pozycji zaworu maszynisty w oparciu o zadane opoznienie hamowania
|
|
|
|
|
|
// do zrobienia:
|
|
// 1. kierownik pociagu
|
|
// 2. madrzejsze unikanie grzania oporow rozruchowych i silnika
|
|
// 3. unikanie szarpniec, zerwania pociagu itp
|
|
// 4. obsluga innych awarii
|
|
// 5. raportowanie problemow, usterek nie do rozwiazania
|
|
// 7. samouczacy sie algorytm hamowania
|
|
|
|
// stałe
|
|
const double EasyReactionTime = 0.5; //[s] przebłyski świadomości dla zwykłej jazdy
|
|
const double HardReactionTime = 0.2;
|
|
const double EasyAcceleration = 0.85; //[m/ss]
|
|
const double HardAcceleration = 9.81;
|
|
const double PassengetTrainAcceleration = 0.40;
|
|
const double HeavyPassengetTrainAcceleration = 0.20;
|
|
const double CargoTrainAcceleration = 0.25;
|
|
const double HeavyCargoTrainAcceleration = 0.10;
|
|
const double PrepareTime = 2.0; //[s] przebłyski świadomości przy odpalaniu
|
|
const double FSOverchargePipePress = 5.2;
|
|
const double FSOverchargeTime = 2.0;
|
|
const double FSOverchargeCRP = 0.05;
|
|
const double FSMaxTime = 10.0;
|
|
const double DepartBlockedFSDelay = 10.0;
|
|
bool WriteLogFlag = false;
|
|
bool WriteTrainLogFlag = false;
|
|
double const deltalog = 0.05; // przyrost czasu
|
|
|
|
std::string StopReasonTable[] = {
|
|
// przyczyny zatrzymania ruchu AI
|
|
"", // stopNone, //nie ma powodu - powinien jechać
|
|
"Off", // stopSleep, //nie został odpalony, to nie pojedzie
|
|
"Semaphore", // stopSem, //semafor zamknięty
|
|
"Time", // stopTime, //czekanie na godzinę odjazdu
|
|
"End of track", // stopEnd, //brak dalszej części toru
|
|
"Change direction", // stopDir, //trzeba stanąć, by zmienić kierunek jazdy
|
|
"Joining", // stopJoin, //zatrzymanie przy (p)odczepianiu
|
|
"Block", // stopBlock, //przeszkoda na drodze ruchu
|
|
"A command", // stopComm, //otrzymano taką komendę (niewiadomego pochodzenia)
|
|
"Out of station", // stopOut, //komenda wyjazdu poza stację (raczej nie powinna zatrzymywać!)
|
|
"Radiostop", // stopRadio, //komunikat przekazany radiem (Radiostop)
|
|
"External", // stopExt, //przesłany z zewnątrz
|
|
"Error", // stopError //z powodu błędu w obliczeniu drogi hamowania
|
|
};
|
|
|
|
//---------------------------------------------------------------------------
|
|
//---------------------------------------------------------------------------
|
|
//---------------------------------------------------------------------------
|
|
|
|
TSpeedPos::TSpeedPos(TTrack *track, double dist, int flag)
|
|
{
|
|
Set(track, dist, flag);
|
|
};
|
|
|
|
TSpeedPos::TSpeedPos(basic_event *event, double dist, double length, TOrders order)
|
|
{
|
|
Set(event, dist, length, order);
|
|
};
|
|
|
|
void TSpeedPos::Clear()
|
|
{
|
|
iFlags = 0; // brak flag to brak reakcji
|
|
fVelNext = -1.0; // prędkość bez ograniczeń
|
|
fSectionVelocityDist = 0.0; //brak długości
|
|
fPointDist = 0.0;
|
|
fDist = 0.0;
|
|
bSeenAhead = false;
|
|
vPos = glm::dvec3(0, 0, 0);
|
|
trTrack = nullptr; // brak wskaźnika
|
|
};
|
|
|
|
void TSpeedPos::CommandCheck()
|
|
{ // sprawdzenie typu komendy w evencie i określenie prędkości
|
|
TCommandType command = evEvent->input_command();
|
|
double value1 = evEvent->input_value(1);
|
|
double value2 = evEvent->input_value(2);
|
|
// the point of a PointVelocity limit is taken anew from the current command
|
|
iFlags &= ~spPointVelocity;
|
|
fPointDist = 0.0;
|
|
switch (command)
|
|
{
|
|
case TCommandType::cm_ShuntVelocity:
|
|
// prędkość manewrową zapisać, najwyżej AI zignoruje przy analizie tabelki
|
|
fVelNext = value1; // powinno być value2, bo druga określa "za"?
|
|
iFlags |= spShuntSemaphor;
|
|
break;
|
|
case TCommandType::cm_SetVelocity:
|
|
// w semaforze typu "m" jest ShuntVelocity dla Ms2 i SetVelocity dla S1
|
|
// SetVelocity * 0 -> można jechać, ale stanąć przed
|
|
// SetVelocity 0 20 -> stanąć przed, potem można jechać 20 (SBL)
|
|
// SetVelocity -1 100 -> można jechać, przy następnym ograniczenie (SBL)
|
|
// SetVelocity 40 -1 -> PutValues: jechać 40 aż do minięcia (koniec ograniczenia(
|
|
fVelNext = value1;
|
|
iFlags &= ~(spShuntSemaphor | spPassengerStopPoint | spStopOnSBL);
|
|
iFlags |= spSemaphor;// nie manewrowa, nie przystanek, nie zatrzymać na SBL, ale semafor
|
|
if (value1 == 0.0 && value2 != 0.0) // jeśli pierwsza zerowa
|
|
// a druga nie
|
|
{ // S1 na SBL, można przejechać po zatrzymaniu (tu nie mamy prędkości ani odległości)
|
|
fVelNext = value2; // normalnie będzie zezwolenie na jazdę, aby się usunął z tabelki
|
|
iFlags |= spStopOnSBL; // flaga, że ma zatrzymać; na pewno nie zezwoli na manewry
|
|
}
|
|
break;
|
|
case TCommandType::cm_SectionVelocity:
|
|
// odcinek z ograniczeniem prędkości
|
|
fVelNext = value1;
|
|
fSectionVelocityDist = value2;
|
|
iFlags |= spSectionVel;
|
|
break;
|
|
case TCommandType::cm_RoadVelocity:
|
|
// prędkość drogowa (od tej pory będzie jako domyślna najwyższa)
|
|
fVelNext = value1;
|
|
iFlags |= spRoadVel;
|
|
break;
|
|
case TCommandType::cm_PassengerStopPoint:
|
|
// nie ma dostępu do rozkładu
|
|
// przystanek, najwyżej AI zignoruje przy analizie tabelki
|
|
fVelNext = 0.0;
|
|
iFlags |= spPassengerStopPoint; // niestety nie da się w tym miejscu współpracować z rozkładem
|
|
/*
|
|
// NOTE: not used for now as it might be unnecessary
|
|
// special case, potentially override any set speed limits if requested
|
|
// NOTE: we test it here because for the time being it's only used for passenger stops
|
|
if( TestFlag( iFlags, spDontApplySpeedLimit ) ) {
|
|
fVelNext = -1;
|
|
}
|
|
*/
|
|
break;
|
|
case TCommandType::cm_SetProximityVelocity:
|
|
// musi zostać gdyż inaczej nie działają manewry
|
|
fVelNext = -1;
|
|
iFlags |= spProximityVelocity;
|
|
// fSectionVelocityDist = value2;
|
|
break;
|
|
case TCommandType::cm_PointVelocity:
|
|
// PointVelocity v d: the head has to be at v (-1: no limit) at the point d metres beyond the cell,
|
|
// the limit ends when the head passes that point. the cell is read until the head passes the cell,
|
|
// what it says then holds for the point (the warning disc of a level crossing, Osp1/Osp2)
|
|
fVelNext = value1;
|
|
fPointDist = std::max( value2, 0.0 );
|
|
iFlags &= ~(spShuntSemaphor | spPassengerStopPoint | spStopOnSBL | spSemaphor); // not a signal, even if the cell was one before
|
|
iFlags |= spPointVelocity;
|
|
break;
|
|
case TCommandType::cm_OutsideStation:
|
|
// w trybie manewrowym: skanować od niej wstecz i stanąć po wyjechaniu za sygnalizator i
|
|
// zmienić kierunek
|
|
// w trybie pociągowym: można przyspieszyć do wskazanej prędkości (po zjechaniu z rozjazdów)
|
|
fVelNext = -1;
|
|
iFlags |= spOutsideStation; // W5
|
|
break;
|
|
case TCommandType::cm_EmergencyBrake:
|
|
fVelNext = -1;
|
|
break;
|
|
case TCommandType::cm_SecuritySystemMagnet:
|
|
fVelNext = -1;
|
|
break;
|
|
case TCommandType::cm_SignalAreaEnd:
|
|
// imposes no speed of its own, it only ends the reduced speed of the signal passed last
|
|
fVelNext = -1;
|
|
iFlags |= spSignalAreaEnd;
|
|
break;
|
|
default:
|
|
// inna komenda w evencie skanowanym powoduje zatrzymanie i wysłanie tej komendy
|
|
// nie manewrowa, nie przystanek, nie zatrzymać na SBL
|
|
// jak nieznana komenda w komórce sygnałowej, to zatrzymujemy
|
|
fVelNext = 0.0;
|
|
/*
|
|
fVelNext = (
|
|
evEvent->is_command() ? 0.0 : // ask for a stop if we have a command for the vehicle
|
|
( iFlags & ( spSemaphor | spShuntSemaphor )) != 0 ? fVelNext : // don't change semafor velocity
|
|
-1.0 ); // otherwise don't be a bother
|
|
*/
|
|
// TODO: check whether clearing spShuntSemaphor flag doesn't cause problems
|
|
// potentially it can invalidate shunt semaphor used to transmit timetable or similar command
|
|
iFlags &= ~(spShuntSemaphor | spPassengerStopPoint | spStopOnSBL);
|
|
}
|
|
};
|
|
|
|
bool TSpeedPos::Update()
|
|
{
|
|
if( fDist < 0.0 ) {
|
|
// trzeba zazanaczyć, że minięty
|
|
iFlags |= spElapsed;
|
|
}
|
|
else {
|
|
bSeenAhead = true;
|
|
}
|
|
if (iFlags & spTrack) {
|
|
// road/track
|
|
if (trTrack) {
|
|
// może być NULL, jeśli koniec toru (???)
|
|
fVelNext = trTrack->VelocityGet(); // aktualizacja prędkości (może być zmieniana eventem)
|
|
|
|
if( trTrack->iCategoryFlag & 1 ) {
|
|
// railways
|
|
if( iFlags & spSwitch && (trTrack->GetSwitchState() & 1) != 0 != ((iFlags & spSwitchStatus) != 0) ) {
|
|
// jeśli odcinek zmienny
|
|
// czy stan się zmienił?
|
|
// Ra: zakładam, że są tylko 2 możliwe stany
|
|
iFlags ^= spSwitchStatus;
|
|
if ((iFlags & spElapsed) == 0)
|
|
{
|
|
// jeszcze trzeba skanowanie wykonać od tego toru
|
|
// problem jest chyba, jeśli zwrotnica się przełoży zaraz po zjechaniu z niej
|
|
// na Mydelniczce potrafi skanować na wprost mimo pojechania na bok
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
else {
|
|
// roads and others
|
|
if( iFlags & 0xF0000000 && (iFlags & 0xF0000000) > 0x10000000 ) {
|
|
// jeśli skrzyżowanie, ograniczyć prędkość przy skręcaniu
|
|
// ±1 to jazda na wprost, ±2 nieby też, ale z przecięciem głównej drogi - chyba że jest równorzędne...
|
|
// TODO: uzależnić prędkość od promienia;
|
|
// albo niech będzie ograniczona w skrzyżowaniu (velocity z ujemną wartością)
|
|
fVelNext = 30.0;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
else if (iFlags & spEvent && ((iFlags & spElapsed) == 0 || fVelNext == 0.0)) {
|
|
// jeśli event
|
|
// ignore already passed signals, but keep an eye on overrun stops
|
|
// (a PointVelocity cell is latched when the head passes it, except at 0, which has to be released by the cell)
|
|
// odczyt komórki pamięci najlepiej by było zrobić jako notyfikację,
|
|
// czyli zmiana komórki wywoła jakąś podaną funkcję
|
|
CommandCheck(); // sprawdzenie typu komendy w evencie i określenie prędkości
|
|
}
|
|
return false;
|
|
};
|
|
|
|
std::string TSpeedPos::GetName() const
|
|
{
|
|
if( iFlags & spTrack ) // jeśli tor
|
|
return trTrack->name();
|
|
else if( iFlags & spEvent ) // jeśli event
|
|
return
|
|
evEvent->m_name
|
|
+ " [" + std::to_string( static_cast<int>( evEvent->input_value( 1 ) ) )
|
|
+ ", " + std::to_string( static_cast<int>( evEvent->input_value( 2 ) ) )
|
|
+ "]";
|
|
else
|
|
return "";
|
|
}
|
|
|
|
std::string TSpeedPos::TableText() const
|
|
{ // pozycja tabelki pr?dko?ci
|
|
if (iFlags & spEnabled)
|
|
{ // o ile pozycja istotna
|
|
return to_hex_str(iFlags, 8) + " " + to_string(fDist, 1, 6) +
|
|
" " + (fVelNext == -1.0 ? " -" : to_string(static_cast<int>(fVelNext), 0, 3)) + " " + GetName();
|
|
}
|
|
return "Empty";
|
|
}
|
|
|
|
bool TSpeedPos::IsProperSemaphor(TOrders order)
|
|
{ // sprawdzenie czy semafor jest zgodny z trybem jazdy
|
|
if (order < Obey_train) // Wait_for_orders, Prepare_engine, Change_direction, Connect, Disconnect, Shunt
|
|
{
|
|
if (iFlags & (spSemaphor | spShuntSemaphor))
|
|
return true;
|
|
else if (iFlags & spOutsideStation)
|
|
return true;
|
|
}
|
|
else if (order & Obey_train && iFlags & spSemaphor)
|
|
{
|
|
return true;
|
|
}
|
|
return false; // true gdy zatrzymanie, wtedy nie ma po co skanować dalej
|
|
}
|
|
|
|
// how far behind the head an event found in the scan may lie and still count as one the head had ahead [m]
|
|
constexpr double SeenAheadTolerance { 5.0 };
|
|
|
|
bool TSpeedPos::Set(basic_event *event, double dist, double length, TOrders order)
|
|
{ // zapamiętanie zdarzenia
|
|
fDist = dist;
|
|
// an event already behind the head when found (under a train set across a signal) wasn't passed by it. the
|
|
// distance is found in steps of a metre from the position of the memory cell, so a signal just ahead of the head
|
|
// may come out a few metres behind it: those still count as seen ahead. the price is that a train set less than
|
|
// the tolerance past a signal at stop is still reported to pass it; a train standing that close to a signal can't
|
|
// be told from one stopped just short of it, which really passes the signal if it goes on
|
|
bSeenAhead = ( dist >= -SeenAheadTolerance );
|
|
iFlags = spEvent;
|
|
evEvent = event;
|
|
vPos = event->input_location(); // współrzędne eventu albo komórki pamięci (zrzutować na tor?)
|
|
// ignore events located behind the consist, but with exception of stop points which may be needed to update freshly received timetable
|
|
if( dist + length < 0
|
|
&& event->input_command() != TCommandType::cm_PassengerStopPoint ) {
|
|
return false;
|
|
}
|
|
iFlags |= spEnabled;
|
|
CommandCheck(); // sprawdzenie typu komendy w evencie i określenie prędkości
|
|
// zależnie od trybu sprawdzenie czy jest tutaj gdzieś semafor lub tarcza manewrowa
|
|
// jeśli wskazuje stop wtedy wystawiamy true jako koniec sprawdzania
|
|
// WriteLog("EventSet: Vel=" + AnsiString(fVelNext) + " iFlags=" + AnsiString(iFlags) + " order="+AnsiString(order));
|
|
if (order < Obey_train) // Wait_for_orders, Prepare_engine, Change_direction, Connect, Disconnect, Shunt
|
|
{
|
|
if (iFlags & (spSemaphor | spShuntSemaphor) && fVelNext == 0.0)
|
|
return true;
|
|
else if (iFlags & spOutsideStation)
|
|
return true;
|
|
}
|
|
else if (order & Obey_train && iFlags & spSemaphor && fVelNext == 0.0)
|
|
{
|
|
return true;
|
|
}
|
|
return false; // true gdy zatrzymanie, wtedy nie ma po co skanować dalej
|
|
};
|
|
|
|
void TSpeedPos::Set(TTrack *track, double dist, int flag)
|
|
{ // zapamiętanie zmiany prędkości w torze
|
|
fDist = dist; // odległość do początku toru
|
|
trTrack = track; // TODO: (t) może być NULL i nie odczytamy końca poprzedniego :/
|
|
if (trTrack)
|
|
{
|
|
iFlags = flag | (trTrack->eType == tt_Normal ? spTrack : spTrack | spSwitch ); // zapamiętanie kierunku wraz z typem
|
|
if (iFlags & spSwitch && trTrack->GetSwitchState() & 1)
|
|
iFlags |= spSwitchStatus;
|
|
fVelNext = trTrack->VelocityGet();
|
|
if (trTrack->iDamageFlag & 128)
|
|
fVelNext = 0.0; // jeśli uszkodzony, to też stój
|
|
if (iFlags & spEnd)
|
|
fVelNext = trTrack->iCategoryFlag & 1 ?
|
|
0.0 :
|
|
20.0; // jeśli koniec, to pociąg stój, a samochód zwolnij
|
|
vPos =
|
|
iFlags & spReverse ?
|
|
trTrack->CurrentSegment()->FastGetPoint_1() :
|
|
trTrack->CurrentSegment()->FastGetPoint_0();
|
|
}
|
|
};
|
|
|
|
//---------------------------------------------------------------------------
|
|
|
|
void TController::TableClear()
|
|
{ // wyczyszczenie tablicy
|
|
sSpeedTable.clear();
|
|
iLast = -1;
|
|
iTableDirection = 0; // nieznany
|
|
tLast = nullptr;
|
|
fLastVel = -1.0;
|
|
SemNextIndex = npos;
|
|
SemNextStopIndex = npos;
|
|
eSignSkip = nullptr; // nic nie pomijamy
|
|
};
|
|
|
|
std::vector<basic_event *> TController::CheckTrackEvent( TTrack *Track, double const fDirection ) const
|
|
{ // sprawdzanie eventów na podanym torze do podstawowego skanowania
|
|
std::vector<basic_event *> events;
|
|
auto const &eventsequence { ( fDirection > 0 ? Track->m_events2 : Track->m_events1 ) };
|
|
for( auto const &event : eventsequence ) {
|
|
if( event.second != nullptr
|
|
&& event.second->m_passive ) {
|
|
events.emplace_back( event.second );
|
|
}
|
|
}
|
|
return events;
|
|
}
|
|
|
|
bool TController::TableAddNew()
|
|
{ // zwiększenie użytej tabelki o jeden rekord
|
|
sSpeedTable.emplace_back(); // add a new slot
|
|
iLast = sSpeedTable.size() - 1;
|
|
return true; // false gdy się nałoży
|
|
};
|
|
|
|
bool TController::TableNotFound(basic_event const *Event, double const Distance ) const
|
|
{ // sprawdzenie, czy nie został już dodany do tabelki (np. podwójne W4 robi problemy)
|
|
auto lookup =
|
|
std::find_if(
|
|
sSpeedTable.begin(),
|
|
sSpeedTable.end(),
|
|
[Event]( TSpeedPos const &speedpoint ){
|
|
return true == TestFlag(speedpoint.iFlags, spEnabled | spEvent) && speedpoint.evEvent == Event; } );
|
|
|
|
if (Global.iWriteLogEnabled & 8
|
|
&& lookup != sSpeedTable.end() ) {
|
|
WriteLog( "Speed table for " + OwnerName() + " already contains event " + lookup->evEvent->m_name );
|
|
}
|
|
|
|
// ignore duplicates which seem to be reasonably apart from each other, on account of looping tracks
|
|
// NOTE: since supplied distance is only rough approximation of distance to the event, we're using large safety margin
|
|
return lookup == sSpeedTable.end() || Distance - lookup->fDist > 100.0;
|
|
};
|
|
|
|
void TController::TableTraceRoute(double fDistance, TDynamicObject *pVehicle)
|
|
{ // skanowanie trajektorii na odległość (fDistance) od (pVehicle) w kierunku przodu składu i
|
|
// uzupełnianie tabelki
|
|
// WriteLog("Starting TableTraceRoute");
|
|
|
|
TTrack *pTrack{ nullptr }; // zaczynamy od ostatniego analizowanego toru
|
|
double fTrackLength{ 0.0 }; // długość aktualnego toru (krótsza dla pierwszego)
|
|
double fCurrentDistance{ 0.0 }; // aktualna przeskanowana długość
|
|
double fLastDir{ 0.0 };
|
|
|
|
if (iTableDirection != iDirection ) {
|
|
// jeśli zmiana kierunku, zaczynamy od toru ze wskazanym pojazdem
|
|
TableClear();
|
|
/*
|
|
// aktualna prędkość // changed to -1 to recognize speed limit, if any
|
|
fLastVel = -1.0;
|
|
sSpeedTable.clear();
|
|
iLast = -1;
|
|
tLast = nullptr; //żaden nie sprawdzony
|
|
SemNextIndex = npos;
|
|
SemNextStopIndex = npos;
|
|
*/
|
|
if( VelSignalLast == 0.0 ) {
|
|
// don't allow potential red light overrun keep us from reversing
|
|
VelSignalLast = -1.0;
|
|
}
|
|
iTableDirection = iDirection; // ustalenie w jakim kierunku jest wypełniana tabelka względem pojazdu
|
|
pTrack = pVehicle->GetTrack(); // odcinek, na którym stoi
|
|
fTrackLength = pVehicle->RaTranslationGet(); // pozycja na tym torze (odległość od Point1)
|
|
fLastDir = pVehicle->DirectionGet() * pVehicle->RaDirectionGet(); // ustalenie kierunku skanowania na torze
|
|
if( fLastDir < 0.0 ) {
|
|
// jeśli w kierunku Point2 toru
|
|
fTrackLength = pTrack->Length() - fTrackLength; // przeskanowana zostanie odległość do Point2
|
|
}
|
|
// account for the fact tracing begins from active axle, not the actual front of the vehicle
|
|
// NOTE: position of the couplers is modified by track offset, but the axles ain't, so we need to account for this as well
|
|
fTrackLength -= glm::length(
|
|
pVehicle->AxlePositionGet()
|
|
- pVehicle->RearPosition()
|
|
+ pVehicle->VectorLeft() * pVehicle->MoverParameters->OffsetTrackH );
|
|
// aktualna odległość ma być ujemna gdyż jesteśmy na końcu składu
|
|
fCurrentDistance = -fLength - fTrackLength;
|
|
fTrackLength = pTrack->Length(); //skasowanie zmian w zmiennej żeby poprawnie liczyło w dalszych krokach
|
|
MoveDistanceReset(); // AI startuje 1s po zaczęciu jazdy i mógł już coś przejechać
|
|
}
|
|
else {
|
|
if( iTableDirection == 0 ) { return; }
|
|
// NOTE: belt and braces; TablePurger() used to leave these pointing past the end of the table
|
|
if( SemNextIndex != npos
|
|
&& SemNextIndex >= sSpeedTable.size() ) {
|
|
SemNextIndex = npos;
|
|
}
|
|
if( SemNextStopIndex != npos
|
|
&& SemNextStopIndex >= sSpeedTable.size() ) {
|
|
SemNextStopIndex = npos;
|
|
}
|
|
// kontynuacja skanowania od ostatnio sprawdzonego toru (w ostatniej pozycji zawsze jest tor)
|
|
if( SemNextStopIndex != npos
|
|
&& sSpeedTable[SemNextStopIndex].fVelNext == 0.0 ) {
|
|
// znaleziono semafor lub tarczę lub tor z prędkością zero, trzeba sprawdzić czy to nadał semafor
|
|
// jeśli jest następny semafor to sprawdzamy czy to on nadał zero
|
|
if( OrderCurrentGet() & Obey_train
|
|
&& sSpeedTable[SemNextStopIndex].iFlags & spSemaphor ) {
|
|
return;
|
|
}
|
|
else {
|
|
if( OrderCurrentGet() < Obey_train
|
|
&& sSpeedTable[SemNextStopIndex].iFlags & (spSemaphor | spShuntSemaphor | spOutsideStation) ) {
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
|
|
auto const &lastspeedpoint = sSpeedTable[ iLast ];
|
|
pTrack = lastspeedpoint.trTrack;
|
|
assert( pTrack != nullptr );
|
|
// flaga ustawiona, gdy Point2 toru jest blizej
|
|
fLastDir = (lastspeedpoint.iFlags & spReverse) != 0 ? -1.0 : 1.0;
|
|
fCurrentDistance = lastspeedpoint.fDist; // aktualna odleglosc do jego Point1
|
|
fTrackLength = pTrack->Length();
|
|
}
|
|
|
|
if( iTableDirection == 0 ) {
|
|
// don't bother
|
|
return;
|
|
}
|
|
|
|
while (fCurrentDistance < fDistance)
|
|
{
|
|
if (pTrack != tLast) // ostatni zapisany w tabelce nie był jeszcze sprawdzony
|
|
{ // jeśli tor nie był jeszcze sprawdzany
|
|
if( Global.iWriteLogEnabled & 8 ) {
|
|
WriteLog( "Speed table for " + OwnerName() + " tracing through track " + pTrack->name() );
|
|
}
|
|
|
|
auto const events { CheckTrackEvent( pTrack, fLastDir ) };
|
|
for( auto *pEvent : events ) {
|
|
if( pEvent != nullptr && TableNotFound(pEvent, fCurrentDistance) ) // jeśli jest semafor na tym torze
|
|
{ // trzeba sprawdzić tabelkę, bo dodawanie drugi raz tego samego przystanku nie jest korzystne
|
|
// jeśli nie ma
|
|
TableAddNew(); // zawsze jest true
|
|
|
|
if (Global.iWriteLogEnabled & 8)
|
|
{
|
|
WriteLog("Speed table for " + OwnerName() + " found new event, " + pEvent->m_name);
|
|
}
|
|
auto &newspeedpoint = sSpeedTable[iLast];
|
|
/*
|
|
if( newspeedpoint.Set(
|
|
pEvent,
|
|
fCurrentDistance + ProjectEventOnTrack( pEvent, pTrack, fLastDir ),
|
|
OrderCurrentGet() ) ) {
|
|
*/
|
|
if (newspeedpoint.Set(pEvent, GetDistanceToEvent(pTrack, pEvent, fLastDir, fCurrentDistance), fLength, OrderCurrentGet()))
|
|
{
|
|
|
|
fDistance = newspeedpoint.fDist; // jeśli sygnał stop, to nie ma potrzeby dalej skanować
|
|
SemNextStopIndex = iLast;
|
|
if (SemNextIndex == npos)
|
|
{
|
|
SemNextIndex = iLast;
|
|
}
|
|
if (Global.iWriteLogEnabled & 8)
|
|
{
|
|
WriteLog("(stop signal from " + (SemNextStopIndex != npos ? sSpeedTable[SemNextStopIndex].GetName() : "unknown semaphor") + ")");
|
|
}
|
|
}
|
|
else
|
|
{
|
|
if (true == newspeedpoint.IsProperSemaphor(OrderCurrentGet()) && SemNextIndex == npos)
|
|
{
|
|
SemNextIndex = iLast; // sprawdzamy czy pierwszy na drodze
|
|
}
|
|
if (Global.iWriteLogEnabled & 8)
|
|
{
|
|
WriteLog("(forward signal for " + (SemNextIndex != npos ? sSpeedTable[SemNextIndex].GetName() : "unknown semaphor") + ")");
|
|
}
|
|
}
|
|
}
|
|
} // event dodajemy najpierw, żeby móc sprawdzić, czy tor został dodany po odczytaniu prędkości następnego
|
|
|
|
if( pTrack->VelocityGet() == 0.0 // zatrzymanie
|
|
|| pTrack->iAction // jeśli tor ma własności istotne dla skanowania
|
|
|| pTrack->VelocityGet() != fLastVel ) // następuje zmiana prędkości
|
|
{ // odcinek dodajemy do tabelki, gdy jest istotny dla ruchu
|
|
TableAddNew();
|
|
sSpeedTable[ iLast ].Set(
|
|
pTrack, fCurrentDistance,
|
|
fLastDir < 0 ? spEnabled | spReverse : spEnabled ); // dodanie odcinka do tabelki z flagą kierunku wejścia
|
|
if (pTrack->eType == tt_Cross) {
|
|
// na skrzyżowaniach trzeba wybrać segment, po którym pojedzie pojazd
|
|
// dopiero tutaj jest ustalany kierunek segmentu na skrzyżowaniu
|
|
/*
|
|
// NOTE: manual selection disabled due to multiplayer
|
|
int routewanted;
|
|
if( false == AIControllFlag ) {
|
|
routewanted = (
|
|
input::keys[ GLFW_KEY_LEFT ] != GLFW_RELEASE ? 1 :
|
|
input::keys[ GLFW_KEY_RIGHT ] != GLFW_RELEASE ? 2 :
|
|
3 );
|
|
}
|
|
else {
|
|
routewanted = 1 + std::floor( Random( static_cast<double>( pTrack->RouteCount() ) - 0.001 ) );
|
|
}
|
|
*/
|
|
auto const routewanted { pTrack->RouteDraw() };
|
|
sSpeedTable[iLast].iFlags |=
|
|
(pTrack->CrossSegment(fLastDir < 0 ? tLast->iPrevDirection : tLast->iNextDirection,
|
|
/*
|
|
iRouteWanted )
|
|
*/
|
|
routewanted) &
|
|
0xf)
|
|
<< 28; // ostatnie 4 bity pola flag
|
|
sSpeedTable[iLast].iFlags &= ~spReverse; // usunięcie flagi kierunku, bo może być błędna
|
|
if (sSpeedTable[iLast].iFlags < 0) {
|
|
sSpeedTable[iLast].iFlags |= spReverse; // ustawienie flagi kierunku na podstawie wybranego segmentu
|
|
}
|
|
if (int(fLastDir) * sSpeedTable[iLast].iFlags < 0) {
|
|
fLastDir = -fLastDir;
|
|
}
|
|
/*
|
|
if (AIControllFlag) {
|
|
// dla AI na razie losujemy kierunek na kolejnym skrzyżowaniu
|
|
iRouteWanted = 1 + Random(3);
|
|
}
|
|
*/
|
|
}
|
|
}
|
|
else if ( (pTrack->fRadius != 0.0 // odległość na łuku lepiej aproksymować cięciwami
|
|
|| tLast != nullptr && tLast->fRadius != 0.0) &&
|
|
TableAddNew()) // koniec łuku też jest istotny
|
|
{ // albo dla liczenia odległości przy pomocy cięciw - te usuwać po przejechaniu
|
|
// dodanie odcinka do tabelki
|
|
sSpeedTable[iLast].Set(pTrack, fCurrentDistance, fLastDir < 0 ? spEnabled | spCurve | spReverse : spEnabled | spCurve);
|
|
}
|
|
}
|
|
|
|
fCurrentDistance += fTrackLength; // doliczenie kolejnego odcinka do przeskanowanej długości
|
|
tLast = pTrack; // odhaczenie, że sprawdzony
|
|
fLastVel = pTrack->VelocityGet(); // prędkość na poprzednio sprawdzonym odcinku
|
|
pTrack = pTrack->Connected(
|
|
pTrack->eType == tt_Cross ? sSpeedTable[iLast].iFlags >> 28 : static_cast<int>(fLastDir),
|
|
fLastDir); // może być NULL
|
|
|
|
if (pTrack != nullptr )
|
|
{ // jeśli kolejny istnieje
|
|
if( tLast != nullptr && tLast->VelocityGet() > 0 && (tLast->VelocityGet() < pTrack->VelocityGet() || pTrack->VelocityGet() < 0) ) {
|
|
|
|
if (iLast != -1 && sSpeedTable[iLast].trTrack == tLast)
|
|
{
|
|
// if the track is already in the table we only need to mark it as relevant
|
|
sSpeedTable[iLast].iFlags |= spEnabled;
|
|
}
|
|
else
|
|
{
|
|
// otherwise add it
|
|
TableAddNew();
|
|
sSpeedTable[iLast].Set(tLast,
|
|
fCurrentDistance - fTrackLength, // by now the current distance points to beginning of next track
|
|
(fLastDir > 0 ? pTrack->iPrevDirection : pTrack->iNextDirection) ? spEnabled : spEnabled | spReverse);
|
|
}
|
|
}
|
|
// zwiększenie skanowanej odległości tylko jeśli istnieje dalszy tor
|
|
fTrackLength = pTrack->Length();
|
|
}
|
|
else
|
|
{ // definitywny koniec skanowania, chyba że dalej puszczamy samochód po gruncie...
|
|
if( iLast == -1
|
|
|| ( false == TestFlag(sSpeedTable[iLast].iFlags, spEnabled | spEnd)
|
|
&& sSpeedTable[iLast].trTrack != tLast ) ) {
|
|
// only if we haven't already marked end of the track and if the new track doesn't duplicate last one
|
|
if( TableAddNew() ) {
|
|
// zapisanie ostatniego sprawdzonego toru
|
|
sSpeedTable[iLast].Set(
|
|
tLast, fCurrentDistance - fTrackLength, // by now the current distance points to beginning of next track,
|
|
fLastDir < 0 ? spEnabled | spEnd | spReverse : spEnabled | spEnd);
|
|
}
|
|
}
|
|
else if( sSpeedTable[iLast].trTrack == tLast && false == TestFlag(sSpeedTable[iLast].trTrack->iCategoryFlag, 0x100) ) {
|
|
// otherwise just mark the last added track as the final one
|
|
// TODO: investigate exactly how we can wind up not marking the last existing track as actual end
|
|
// don't mark portals, as these aren't exactly track ends, but teleport devices
|
|
sSpeedTable[iLast].iFlags |= spEnabled | spEnd;
|
|
}
|
|
// to ostatnia pozycja, bo NULL nic nie da, a może się podpiąć obrotnica, czy jakieś transportery
|
|
return;
|
|
}
|
|
}
|
|
if( TableAddNew() ) {
|
|
// zapisanie ostatniego sprawdzonego toru
|
|
sSpeedTable[ iLast ].Set(
|
|
pTrack, fCurrentDistance,
|
|
fLastDir < 0 ? spNone | spReverse : spNone );
|
|
}
|
|
};
|
|
|
|
void TController::TableCheck(double fDistance)
|
|
{ // przeliczenie odległości w tabelce, ewentualnie doskanowanie (bez analizy prędkości itp.)
|
|
if( iTableDirection != iDirection ) {
|
|
// jak zmiana kierunku, to skanujemy od końca składu
|
|
TableTraceRoute( fDistance, pVehicles[ end::rear ] );
|
|
TableSort();
|
|
}
|
|
else if (iTableDirection)
|
|
{ // trzeba sprawdzić, czy coś się zmieniło
|
|
auto const distance = MoveDistanceGet();
|
|
for (auto &sp : sSpeedTable) {
|
|
// aktualizacja odległości dla wszystkich pozycji tabeli
|
|
sp.UpdateDistance(distance);
|
|
}
|
|
MoveDistanceReset(); // kasowanie odległości po aktualizacji tabelki
|
|
for( int i = 0; i < iLast; ++i )
|
|
{ // aktualizacja rekordów z wyjątkiem ostatniego
|
|
if (sSpeedTable[i].iFlags & spEnabled) // jeśli pozycja istotna
|
|
{
|
|
auto const passedbefore { TestFlag( sSpeedTable[ i ].iFlags, spElapsed ) };
|
|
if (sSpeedTable[i].Update())
|
|
{
|
|
if( Global.iWriteLogEnabled & 8 ) {
|
|
WriteLog( "Speed table for " + OwnerName() + " detected switch change at " + sSpeedTable[ i ].trTrack->name() + " (generating fresh trace)" );
|
|
}
|
|
// usuwamy wszystko za tym torem
|
|
while (sSpeedTable.back().trTrack != sSpeedTable[i].trTrack)
|
|
{ // usuwamy wszystko dopóki nie trafimy na tą zwrotnicę
|
|
sSpeedTable.pop_back();
|
|
--iLast;
|
|
}
|
|
// a semaphor recorded beyond the switch went away with the discarded entries
|
|
if( SemNextIndex != npos
|
|
&& SemNextIndex >= sSpeedTable.size() ) {
|
|
SemNextIndex = npos;
|
|
}
|
|
if( SemNextStopIndex != npos
|
|
&& SemNextStopIndex >= sSpeedTable.size() ) {
|
|
SemNextStopIndex = npos;
|
|
}
|
|
tLast = sSpeedTable[ i ].trTrack;
|
|
TableTraceRoute( fDistance, pVehicles[ end::rear ] );
|
|
TableSort();
|
|
// nie kontynuujemy pętli, trzeba doskanować ciąg dalszy
|
|
break;
|
|
}
|
|
// a switch is a track, the update of a signal never ends the loop above
|
|
CheckSignalPassed( sSpeedTable[ i ], passedbefore );
|
|
if (sSpeedTable[i].iFlags & spTrack) // jeśli odcinek
|
|
{
|
|
if( sSpeedTable[ i ].fDist + sSpeedTable[ i ].trTrack->Length() < -fLength ) // a skład wyjechał całą długością poza
|
|
{ // degradacja pozycji
|
|
sSpeedTable[i].iFlags &= ~spEnabled; // nie liczy się
|
|
}
|
|
else if( (sSpeedTable[i].iFlags & 0xF0000028) == spElapsed && sSpeedTable[i].fVelNext < 0 ) {
|
|
// jest z tyłu (najechany) i nie jest zwrotnicą ani skrzyżowaniem
|
|
// a nie ma ograniczenia prędkości
|
|
sSpeedTable[i].iFlags = 0; // to nie ma go po co trzymać (odtykacz usunie ze środka)
|
|
}
|
|
}
|
|
else if (sSpeedTable[i].iFlags & spEvent && (sSpeedTable[i].iFlags & spPointVelocity) == 0 && sSpeedTable[i].fDist < (typeid(*sSpeedTable[i].evEvent) == typeid(putvalues_event) ? -fLength : 0) && mvOccupied->CategoryFlag == 2 &&
|
|
sSpeedTable[i].fDist < -0.75) // jeśli event
|
|
{
|
|
// jeśli jest z tyłu
|
|
// pociąg staje zawsze, a samochód tylko jeśli nie przejedzie całą długością (może być zaskoczony zmianą)
|
|
// WriteLog("TableCheck: Event is behind. Delete from table: " + sSpeedTable[i].evEvent->asName);
|
|
sSpeedTable[i].iFlags &= ~spEnabled; // degradacja pozycji dla samochodu;
|
|
// semafory usuwane tylko przy sprawdzaniu, bo wysyłają komendy
|
|
}
|
|
}
|
|
}
|
|
auto const lastpassedbefore { TestFlag( sSpeedTable[ iLast ].iFlags, spElapsed ) };
|
|
sSpeedTable[iLast].Update(); // aktualizacja ostatniego
|
|
// a signal at stop often is the last, the scan doesn't go past it
|
|
CheckSignalPassed( sSpeedTable[ iLast ], lastpassedbefore );
|
|
// WriteLog("TableCheck: Upate last track. Dist=" + AnsiString(sSpeedTable[iLast].fDist));
|
|
if( sSpeedTable[ iLast ].fDist < fDistance ) {
|
|
TableTraceRoute( fDistance, pVehicles[ end::rear ] ); // doskanowanie dalszego odcinka
|
|
TableSort();
|
|
}
|
|
// garbage collection
|
|
TablePurger();
|
|
}
|
|
};
|
|
|
|
namespace {
|
|
|
|
// the position is a signal showing stop (SetVelocity 0 0). SetVelocity 0 x on automatic block isn't: it may be passed after a stop
|
|
bool is_signal_at_stop( TSpeedPos const &Point )
|
|
{
|
|
return TestFlag( Point.iFlags, spEvent )
|
|
&& TestFlag( Point.iFlags, spSemaphor )
|
|
&& false == TestFlag( Point.iFlags, spStopOnSBL )
|
|
&& std::abs( Point.fVelNext ) <= 0.0
|
|
&& Point.evEvent != nullptr;
|
|
}
|
|
|
|
void clear_signal_area_end( TSpeedPos &Point )
|
|
{
|
|
if( TestFlag( Point.iFlags, spSignalAreaEnd ) ) {
|
|
Point.Clear();
|
|
}
|
|
}
|
|
|
|
// the position is a signal, a main or a shunting one: the aspect comes from its memory cell. putvalues events
|
|
// set speed limits by the track, and the flags they get don't make them signals
|
|
bool is_signal( TSpeedPos const &Point )
|
|
{
|
|
return TestFlag( Point.iFlags, spEvent )
|
|
&& ( TestFlag( Point.iFlags, spSemaphor ) || TestFlag( Point.iFlags, spShuntSemaphor ) )
|
|
&& Point.evEvent != nullptr
|
|
&& typeid( *Point.evEvent ) == typeid( getvalues_event );
|
|
}
|
|
|
|
std::uint8_t passing_flags_of( TSpeedPos const &Point, double const Speedatsignal, bool const Trainmovement )
|
|
{
|
|
std::uint8_t flags { 0 };
|
|
auto const shunting { TestFlag( Point.iFlags, spShuntSemaphor ) };
|
|
if( shunting ) {
|
|
flags |= blackbox::passing_flags::shunt;
|
|
}
|
|
// the speeds of the aspects are whole km/h, -1 for no limit; a shunting signal binds only the shunting
|
|
if( std::abs( Speedatsignal ) < 0.5 && ( false == shunting || false == Trainmovement ) ) {
|
|
flags |= ( TestFlag( Point.iFlags, spStopOnSBL ) ? blackbox::passing_flags::automatic_block : blackbox::passing_flags::at_stop );
|
|
}
|
|
return flags;
|
|
}
|
|
|
|
} // namespace
|
|
|
|
void TController::CheckSignalPassed( TSpeedPos const &Point, bool const Passedbefore ) const
|
|
{
|
|
if( Passedbefore
|
|
|| false == TestFlag( Point.iFlags, spElapsed )
|
|
|| false == Point.bSeenAhead // found already behind the head: the train stood across it, it didn't pass it
|
|
|| ( mvOccupied->CategoryFlag & 1 ) == 0 ) { // railway only
|
|
return;
|
|
}
|
|
if( is_signal_at_stop( Point ) ) {
|
|
simulation::test().signal_passed_at_danger( OwnerName(), Point.evEvent->m_name );
|
|
}
|
|
if( is_signal( Point ) ) {
|
|
// the aspect the train had of it: the table keeps it once the signal is behind, while the memory cell
|
|
// may already show stop for the train itself, past the signal on the track it guards. the stop of an
|
|
// automatic block signal is kept as the speed allowed after it, with a flag of its own
|
|
auto const speedatsignal { TestFlag( Point.iFlags, spStopOnSBL ) ? 0.0 : Point.fVelNext };
|
|
simulation::Blackbox.signal_passed(
|
|
pVehicles[ end::front ], *Point.evEvent,
|
|
speedatsignal, Point.evEvent->input_value( 2 ),
|
|
mvOccupied->Vel, -Point.fDist,
|
|
passing_flags_of( Point, speedatsignal, ( OrderCurrentGet() & ( Shunt | Loose_shunt ) ) == 0 ) );
|
|
}
|
|
}
|
|
|
|
auto const passengerstopmaxdistance { 400.0 }; // maximum allowed distance between passenger stop point and consist head
|
|
|
|
// the margins of the final approach of a train [m], closer than the first of which it stops at once and within the
|
|
// second of which it makes its final approach: at a passenger stop, or at a signal and anything else it stops at
|
|
std::pair<double, double>
|
|
TController::train_proximity_margins( bool const Passengerstop ) const {
|
|
|
|
auto minproximity { 0.0 };
|
|
auto maxproximity { 0.0 };
|
|
if( Passengerstop ) {
|
|
// a stop point keeps the margins its W4 parameters (head or middle of the consist,
|
|
// platform length) were set up against
|
|
minproximity = std::clamp( 5 + iVehicles, 10, 15 ) + ( IsCargoTrain ? 10.0 : 0.0 );
|
|
maxproximity = std::clamp( 10 + iVehicles, 15, 40 );
|
|
}
|
|
else {
|
|
// a train stops 8-15 m short of the signal whatever its length; closer than the lower
|
|
// edge it stops at once, the braking aims at the middle of the window, 3.5 m further out
|
|
minproximity = 8.0;
|
|
// the final approach begins far enough out to slow from the coasting speed down to the window,
|
|
// and at the same distance whether the train is moving or standing, so it does not flip
|
|
// between creeping closer and holding still when it comes to a stand short of the window
|
|
maxproximity = 50.0;
|
|
}
|
|
if( IsCargoTrain ) {
|
|
// start the final approach earlier for cargo trains, their brakes react more slowly
|
|
maxproximity += 10.0;
|
|
}
|
|
if( ( Global.FrictionWeatherFactor < 1.f )
|
|
&& ( iVehicles > 1 ) ) {
|
|
// take into account weather conditions
|
|
minproximity += 5.0;
|
|
maxproximity += 5.0;
|
|
}
|
|
if( mvOccupied->Vel < 0.1 ) {
|
|
// jak stanie za daleko, to niech nie dociąga paru metrów
|
|
maxproximity = std::max( maxproximity, 50.0 );
|
|
}
|
|
return { minproximity, maxproximity };
|
|
}
|
|
|
|
TCommandType TController::TableUpdate(double &fVelDes, double &fDist, double &fNext, double &fAcc)
|
|
{ // ustalenie parametrów, zwraca typ komendy, jeśli sygnał podaje prędkość do jazdy
|
|
// fVelDes - prędkość zadana
|
|
// fDist - dystans w jakim należy rozważyć ruch
|
|
// fNext - prędkość na końcu tego dystansu
|
|
// fAcc - zalecane przyspieszenie w chwili obecnej - kryterium wyboru dystansu
|
|
auto a { 0.0 }; // przyspieszenie
|
|
auto v { 0.0 }; // prędkość
|
|
auto d { 0.0 }; // droga
|
|
auto d_to_next_sem { 10000.0 }; //ustaiwamy na pewno dalej niż widzi AI
|
|
auto go { TCommandType::cm_Unknown };
|
|
auto speedlimitiscontinuous { true }; // stays true if potential active speed limit is unbroken to the last (relevant) point in scan table
|
|
eSignNext = nullptr;
|
|
IsAtPassengerStop = false;
|
|
bStopTargetIsPassengerStop = false;
|
|
IsScheduledPassengerStopVisible = false;
|
|
mvOccupied->SecuritySystem.set_cabsignal_lock(false);
|
|
// te flagi są ustawiane tutaj, w razie potrzeby
|
|
iDrivigFlags &= ~(moveTrackEnd | moveSwitchFound | moveSignalFound | /*moveSpeedLimitFound*/ moveStopPointFound );
|
|
SignalAreaEndDist = -1.0;
|
|
update_point_limits();
|
|
|
|
for( std::size_t idx = 0; idx < sSpeedTable.size(); ++idx ) {
|
|
// o ile dana pozycja tabelki jest istotna
|
|
if( ( sSpeedTable[ idx ].iFlags & spEnabled ) == 0 ) { continue; }
|
|
|
|
auto &point { sSpeedTable[ idx ] };
|
|
|
|
if( TestFlag( point.iFlags, spPassengerStopPoint ) ) {
|
|
if( TableUpdateStopPoint( go, point, d_to_next_sem ) ) { continue; };
|
|
}
|
|
v = point.fVelNext; // odczyt prędkości do zmiennej pomocniczej
|
|
if( TestFlag( point.iFlags, spSwitch ) ) {
|
|
// zwrotnice są usuwane z tabelki dopiero po zjechaniu z nich
|
|
iDrivigFlags |= moveSwitchFound; // rozjazd z przodu/pod ogranicza np. sens skanowania wstecz
|
|
SwitchClearDist = point.fDist + point.trTrack->Length() + fLength;
|
|
}
|
|
else if ( TestFlag(point.iFlags, spEvent) && TableUpdateEvent(v, go, point, d_to_next_sem, idx) ) // W4 może się deaktywować
|
|
{ // jeżeli event, może być potrzeba wysłania komendy, aby ruszył
|
|
continue;
|
|
}
|
|
|
|
auto const railwaytrackend { true == TestFlag(point.iFlags, spEnd) && is_train() };
|
|
if( v >= 0.0 // pozycje z prędkością -1 można spokojnie pomijać
|
|
|| railwaytrackend ) {
|
|
|
|
// a PointVelocity limit lies fPointDist beyond its entry and stays ahead of us until the head passes it
|
|
auto const ispointlimit { TestFlag( point.iFlags, spPointVelocity ) };
|
|
d = point.fDist + point.fPointDist;
|
|
|
|
if( v >= 0.0 ) {
|
|
// points located in front of us can potentially affect our acceleration and target speed
|
|
if( d > 0.0
|
|
&& ( false == TestFlag(point.iFlags, spElapsed) || ispointlimit ) ) {
|
|
// sygnał lub ograniczenie z przodu (+32=przejechane)
|
|
// 2014-02: jeśli stoi, a ma do przejechania kawałek, to niech jedzie
|
|
if( mvOccupied->Vel < 0.01
|
|
&& true == TestFlag(point.iFlags, spEnabled | spEvent | spPassengerStopPoint)
|
|
&& false == IsAtPassengerStop ) {
|
|
// ma podjechać bliżej - czy na pewno w tym miejscu taki warunek?
|
|
a = d > passengerstopmaxdistance || (iDrivigFlags & moveStopCloser) != 0 ? fAcc : 0.0;
|
|
}
|
|
else {
|
|
// przyspieszenie: ujemne, gdy trzeba hamować
|
|
if( v >= 0.0 ) {
|
|
a = ( v * v - mvOccupied->Vel * mvOccupied->Vel ) / ( 25.92 * d );
|
|
if( mvOccupied->Vel < v
|
|
|| v == 0.0 ) {
|
|
// if we're going slower than the target velocity and there's enough room for safe stop, speed up
|
|
auto const brakingdistance { 1.2 * fBrakeDist * braking_distance_multiplier( v ) };
|
|
if( brakingdistance > 0.0 ) {
|
|
// maintain desired acc while we have enough room to brake safely, when close enough start paying attention
|
|
// try to make a smooth transition instead of sharp change
|
|
a = std::lerp( a, AccPreferred, std::clamp( ( d - brakingdistance ) / brakingdistance, 0.0, 1.0 ) );
|
|
}
|
|
}
|
|
if( d < ( ispointlimit && v > 0.0 ? point_limit_approach() : fMinProximityDist )
|
|
&& v < fVelDes ) {
|
|
// jak jest już blisko, ograniczenie aktualnej prędkości
|
|
fVelDes = v;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
// points located behind can affect our current speed, but little else
|
|
else if ( point.iFlags & spTrack) // jeśli tor
|
|
{ // tor ogranicza prędkość, dopóki cały skład nie przejedzie,
|
|
if( v >= 1.0 && d + point.trTrack->Length() < -fLength && false == railwaytrackend ) { // EU06 się zawieszało po dojechaniu na koniec toru postojowego
|
|
// zapętlenie, jeśli już wyjechał za ten odcinek
|
|
continue;
|
|
}
|
|
if( v < fVelDes ) {
|
|
// ograniczenie aktualnej prędkości aż do wyjechania za ograniczenie
|
|
fVelDes = v;
|
|
}
|
|
if( v < VelLimitLastDist.first ) {
|
|
VelLimitLastDist.second = d + point.trTrack->Length() + fLength;
|
|
}
|
|
else if( VelLimitLastDist.second > 0 && (point.iFlags & (spSwitch | spPassengerStopPoint)) == 0 ) { // the speed limit can potentially start afterwards, so don't mark it as broken too soon
|
|
speedlimitiscontinuous = false;
|
|
}
|
|
if( false == railwaytrackend ) {
|
|
continue; // i tyle wystarczy
|
|
}
|
|
}
|
|
else {
|
|
// event trzyma tylko jeśli VelNext=0, nawet po przejechaniu (nie powinno dotyczyć samochodów?)
|
|
a = v > 0.0 ?
|
|
fAcc :
|
|
mvOccupied->Vel < 0.01 ?
|
|
0.0 : // already standing still so no need to bother with brakes
|
|
-2.0; // ruszanie albo hamowanie
|
|
}
|
|
}
|
|
// track can potentially end, which creates another virtual point of interest with speed limit of 0 at the end of it
|
|
// TBD, TODO: when tracing the route create a dedicated table entry for it, to simplify the code?
|
|
if( railwaytrackend ) {
|
|
// if the railway track ends here set the velnext accordingly as well
|
|
// TODO: test this with turntables and such
|
|
auto const stopatendacceleration = -1.0 * mvOccupied->Vel * mvOccupied->Vel / ( 25.92 * ( d + point.trTrack->Length() ) );
|
|
if( stopatendacceleration < a ) {
|
|
a = stopatendacceleration;
|
|
v = 0.0;
|
|
d += point.trTrack->Length();
|
|
if( d < fMinProximityDist ) {
|
|
// jak jest już blisko, ograniczenie aktualnej prędkości
|
|
fVelDes = v;
|
|
}
|
|
}
|
|
}
|
|
|
|
if( a <= fAcc
|
|
&& ( v < fNext || fNext < 0 ) ) { // filter out consecutive, farther out blocks with the same speed limit; they'd make us accelerate slower due to their lower a value
|
|
// mniejsze przyspieszenie to mniejsza możliwość rozpędzenia się albo konieczność hamowania
|
|
// jeśli droga wolna, to może być a>1.0 i się tu nie załapuje
|
|
fAcc = a; // zalecane przyspieszenie (nie musi być uwzględniane przez AI)
|
|
fNext = v; // istotna jest prędkość na końcu tego odcinka
|
|
fDist = d; // dlugość odcinka
|
|
bStopTargetIsPassengerStop = ( v == 0.0 ) && ( ( point.iFlags & spPassengerStopPoint ) != 0 );
|
|
}
|
|
/*
|
|
else if ((fAcc > 0) && (v >= 0) && (v > fNext)) {
|
|
// jeśli nie ma wskazań do hamowania, można podać drogę i prędkość na jej końcu
|
|
fNext = v; // istotna jest prędkość na końcu tego odcinka
|
|
fDist = d; // dlugość odcinka (kolejne pozycje mogą wydłużać drogę, jeśli prędkość jest stała)
|
|
}
|
|
*/
|
|
// we'll pick first scanned target speed as our goal
|
|
// farther scan table points can override it through previous clause, if they require lower acceleration or speed reduction
|
|
else if( a > 0 && a <= fAcc && v >= 0 && fNext < 0 ) {
|
|
fAcc = a;
|
|
fNext = v;
|
|
fDist = d;
|
|
bStopTargetIsPassengerStop = ( v == 0.0 ) && ( ( point.iFlags & spPassengerStopPoint ) != 0 );
|
|
}
|
|
// potentially update our current speed limit
|
|
// a point limit binds only the head at its point, it neither extends nor breaks a limit over a stretch of the line
|
|
if( false == ispointlimit
|
|
&& v < VelLimitLastDist.first
|
|
&& ( d < 0 // the point counts as part of last speed limit either if it's behind us
|
|
|| VelLimitLastDist.second > 0 ) ) { // or if we already have the last limit ongoing
|
|
VelLimitLastDist.second = d + fLength;
|
|
if( ( point.iFlags & spTrack ) != 0 ) {
|
|
VelLimitLastDist.second += point.trTrack->Length();
|
|
}
|
|
}
|
|
else if( ( point.iFlags & ( spSwitch | spPassengerStopPoint | spPointVelocity ) ) == 0 ) {
|
|
// if we found a point which isn't part of the current speed limit mark the limit as broken
|
|
// NOTE: we exclude switches from this rule, as speed limits generally extend through these
|
|
speedlimitiscontinuous = false;
|
|
}
|
|
} // if (v>=0.0)
|
|
// finding a point which doesn't impose speed limit means any potential active speed limit can't extend through entire scan table
|
|
// NOTE: we test actual speed value for the given point, as events may receive (v = -1) as a way to disable them in irrelevant modes
|
|
if( point.fVelNext < 0 && (point.iFlags & (spSwitch | spPassengerStopPoint | spPointVelocity)) == 0 ) {
|
|
// NOTE: we exclude switches from this rule, as speed limits generally extend through these
|
|
// and point limits, which say nothing of the line they lie on
|
|
speedlimitiscontinuous = false;
|
|
}
|
|
if (fNext >= 0.0)
|
|
{ // jeśli ograniczenie
|
|
if( (point.iFlags & (spEnabled | spEvent)) == (spEnabled | spEvent) && (point.iFlags & spPointVelocity) == 0 && eSignNext == nullptr ) { // tylko sygnał przypisujemy (a point limit isn't one)
|
|
// jeśli jeszcze nic nie zapisane tam
|
|
eSignNext = point.evEvent; // dla informacji
|
|
}
|
|
if( fNext == 0.0 ) {
|
|
break; // nie ma sensu analizować tabelki dalej
|
|
}
|
|
}
|
|
}
|
|
|
|
// the point limits latched before, which aren't in the table any more
|
|
apply_point_limits( fVelDes, fDist, fNext, fAcc );
|
|
|
|
// jeśli mieliśmy ograniczenie z semafora i nie ma przed nami
|
|
if( VelSignalLast >= 0.0
|
|
&& (iDrivigFlags & (moveSignalFound | moveSwitchFound | moveStopPointFound)) == 0
|
|
&& true == TestFlag(OrderCurrentGet(), Obey_train) ) {
|
|
VelSignalLast = -1.0;
|
|
}
|
|
// if there's unbroken speed limit through our scan table take a note of it
|
|
if( VelLimitLastDist.second > 0
|
|
&& speedlimitiscontinuous ) {
|
|
VelLimitLastDist.second = EU07_AI_SPEEDLIMITEXTENDSBEYONDSCANRANGE;
|
|
}
|
|
// take into account the effect switches have on duration of signal-imposed speed limit, in calculation of speed limit end point
|
|
// a reduced speed ends where the interlocking area does, if that is marked, and not past the switches farther on
|
|
if( auto const signallimitend { VelSignalLast > 0.0 && SignalAreaEndDist >= 0.0 ? SignalAreaEndDist : SwitchClearDist };
|
|
VelSignalLast >= 0.0 && signallimitend >= 0.0 ) {
|
|
VelLimitLastDist.second = std::max( VelLimitLastDist.second, signallimitend );
|
|
}
|
|
|
|
//analiza spisanych z tabelki ograniczeń i nadpisanie aktualnego
|
|
// if stopped at a valid passenger stop, hold there
|
|
if( true == IsAtPassengerStop && mvOccupied->Vel < 0.01 ) {
|
|
fVelDes = 0.0;
|
|
}
|
|
else {
|
|
fVelDes = min_speed( fVelDes, VelSignalLast );
|
|
fVelDes = min_speed( fVelDes, VelLimitLast );
|
|
fVelDes = min_speed( fVelDes, VelRoad );
|
|
fVelDes = min_speed( fVelDes, VelRestricted );
|
|
}
|
|
// nastepnego semafora albo zwrotnicy to uznajemy, że mijamy W5
|
|
FirstSemaphorDist = d_to_next_sem; // przepisanie znalezionej wartosci do zmiennej
|
|
return go;
|
|
};
|
|
|
|
bool
|
|
TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, double const Signaldistance ) {
|
|
// stop points are irrelevant when not in one of the basic modes
|
|
if( ( OrderCurrentGet() & ( Shunt | Loose_shunt | Obey_train | Bank ) ) == 0 ) { return true; }
|
|
// jeśli przystanek, trzeba obsłużyć wg rozkładu
|
|
iDrivigFlags |= moveStopPointFound;
|
|
// the W4 and the timetable name the station each in its own file, so the two spellings are compared by their key:
|
|
// with or without the polish letters, in any case, with spaces or underscores
|
|
if( false == timetable::stop_point_is_for( Point.evEvent->input_text(), asNextStop ) )
|
|
{ // jeśli nazwa nie jest zgodna
|
|
if( false == IsScheduledPassengerStopVisible // check if our next scheduled stop didn't show up earlier in the scan
|
|
&& Point.fDist < 1.15 * fBrakeDist + 300
|
|
&& Point.fDist > 0 ) // tylko jeśli W4 jest blisko, przy dwóch może zaczać szaleć
|
|
{
|
|
// porównuje do następnej stacji, więc trzeba przewinąć do poprzedniej
|
|
// nastepnie ustawić następną na aktualną tak żeby prawidłowo ją obsłużył w następnym kroku
|
|
if( true == TrainParams.RewindTimeTable( Point.evEvent->input_text() ) ) {
|
|
asNextStop = TrainParams.NextStop();
|
|
TrainParams.StationStart = TrainParams.StationIndex;
|
|
}
|
|
}
|
|
else if( Point.fDist < -fLength ) {
|
|
// jeśli został przejechany
|
|
Point.iFlags = 0; // to można usunąć (nie mogą być usuwane w skanowaniu)
|
|
}
|
|
return true; // ignorowanie jakby nie było tej pozycji
|
|
}
|
|
else if (iDrivigFlags & moveStopPoint) // jeśli pomijanie W4, to nie sprawdza czasu odjazdu
|
|
{ // tylko gdy nazwa zatrzymania się zgadza
|
|
if( ( OrderCurrentGet() & ( Obey_train | Bank ) ) != 0 ) {
|
|
// check whether the station specifies radio channel change
|
|
// NOTE: we don't do it in shunt mode, as shunting operations tend to use dedicated radio channel
|
|
// NOTE: there's a risk radio channel change was specified by a station which we skipped during timetable rewind
|
|
// we ignore this for the time being as it's not a high priority error
|
|
auto const radiochannel { TrainParams.radio_channel() };
|
|
if( radiochannel > 0 ) {
|
|
if( iGuardRadio != 0 ) {
|
|
iGuardRadio = radiochannel;
|
|
}
|
|
if( iRadioChannel != radiochannel ) {
|
|
cue_action( driver_hint::radiochannel, radiochannel );
|
|
}
|
|
}
|
|
}
|
|
IsScheduledPassengerStopVisible = true; // block potential timetable rewind if the next stop shows up later in the scan
|
|
if (false == TrainParams.IsStop())
|
|
{ // jeśli nie ma tu postoju
|
|
Point.fVelNext = -1; // maksymalna prędkość w tym miejscu
|
|
// przy 160km/h jedzie 44m/s, to da dokładność rzędu 5 sekund
|
|
if (Point.fDist < passengerstopmaxdistance * 0.5 ) {
|
|
// zaliczamy posterunek w pewnej odległości przed (choć W4 nie zasłania już semafora)
|
|
#if LOGSTOPS
|
|
WriteLog(std::format(
|
|
"{} as {}: at {}:{} passed {}",
|
|
pVehicle->asName, TrainParams.TrainName, simulation::Time.data().wHour, simulation::Time.data().wMinute, asNextStop)); // informacja
|
|
#endif
|
|
// przy jakim dystansie (stanie licznika) ma przesunąć na następny postój
|
|
fLastStopExpDist = mvOccupied->DistCounter + 0.250 + 0.001 * fLength;
|
|
TrainParams.UpdateMTable( simulation::Time, asNextStop );
|
|
record_station( Point, blackbox::station_kinds::passed );
|
|
UpdateDelayFlag();
|
|
TrainParams.StationIndexInc(); // przejście do następnej
|
|
asNextStop = TrainParams.NextStop(); // pobranie kolejnego miejsca zatrzymania
|
|
Point.iFlags = 0; // nie liczy się już
|
|
return true; // table entry recognized and handled
|
|
}
|
|
} // koniec obsługi przelotu na W4
|
|
else {
|
|
// zatrzymanie na W4
|
|
// the margins of a passenger stop, whether the train is already making for it or not: the present ones
|
|
// depend on this very flag, and a check against them would turn it on and off every other scan
|
|
auto const [ stopminproximity, stopmaxproximity ] {
|
|
is_train() ?
|
|
train_proximity_margins( true ) :
|
|
std::pair{ fMinProximityDist, fMaxProximityDist } };
|
|
if ( false == Point.bMoved ) {
|
|
// potentially shift the stop point in accordance with its defined parameters
|
|
/*
|
|
// https://rainsted.com/pl/Wersja/18.2.133#Okr.C4.99gi_dla_W4_i_W32
|
|
Pierwszy parametr ujemny - preferowane zatrzymanie czoła składu (np. przed przejściem).
|
|
Pierwszy parametr dodatni - preferowane zatrzymanie środka składu (np. przy wiacie, przejściu podziemnym).
|
|
Drugi parametr ujemny - wskazanie zatrzymania dla krótszych składów (W32).
|
|
Drugi paramer dodatni - długość peronu (W4).
|
|
*/
|
|
auto L = 0.0;
|
|
auto Par1 = Point.evEvent->input_value(1);
|
|
auto Par2 = Point.evEvent->input_value(2);
|
|
if (Par2 >= 0 || fLength < -Par2) { //użyj tego W4
|
|
if (Par1 < 0) {
|
|
L = -Par1;
|
|
}
|
|
else {
|
|
//środek
|
|
L = Par1 - stopminproximity - fLength * 0.5;
|
|
}
|
|
// the train comes to a stand anywhere up to the margin of a passenger stop short of this point, not
|
|
// that of the signals it may be making for when it first sees the W4, so the tail is to keep that far
|
|
// inside the platform
|
|
L = std::max(0.0, std::min(L, std::abs(Par2) - stopminproximity - fLength));
|
|
Point.UpdateDistance(L);
|
|
Point.bMoved = true;
|
|
Point.fMoved = L;
|
|
}
|
|
else {
|
|
Point.iFlags = 0;
|
|
}
|
|
}
|
|
// for human-driven vehicles discard the stop point if they leave it far enough behind
|
|
if( false == AIControllFlag
|
|
&& Point.fDist < -1 * std::max(fLength + 100, 250.0) - Point.fMoved ) {
|
|
record_station( Point, blackbox::station_kinds::missed );
|
|
Point.iFlags = 0; // nie liczy się już zupełnie (nie wyśle SetVelocity)
|
|
Point.fVelNext = -1; // można jechać za W4
|
|
if( Point.fDist <= 0.0 && eSignNext == Point.evEvent ) {
|
|
// sanity check, if we're held by this stop point, let us go
|
|
VelSignalLast = -1;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
IsAtPassengerStop = Point.fDist <= passengerstopmaxdistance
|
|
// Ra 2F1I: odległość plus długość pociągu musi być mniejsza od długości
|
|
// peronu, chyba że pociąg jest dłuższy, to wtedy minimalna.
|
|
// jeśli długość peronu ((sSpeedTable[i].evEvent->ValueGet(2)) nie podana,
|
|
// przyjąć odległość fMinProximityDist
|
|
&& ((iDrivigFlags & moveStopCloser) != 0 ?
|
|
Point.fDist + fLength + (Point.fMoved - stopminproximity * 0.5f) <= std::max(std::abs(Point.evEvent->input_value(2)),
|
|
2.0 * stopmaxproximity + fLength) :
|
|
Point.fDist < Signaldistance);
|
|
|
|
if( !eSignNext ) {
|
|
//jeśli nie widzi następnego sygnału ustawia dotychczasową
|
|
eSignNext = Point.evEvent;
|
|
}
|
|
if( mvOccupied->Vel > EU07_AI_MOVEMENT ) {
|
|
// jeśli jedzie (nie trzeba czekać, aż się drgania wytłumią - drzwi zamykane od 1.0) to będzie zatrzymanie
|
|
Point.fVelNext = 0;
|
|
// potentially announce pending stop
|
|
if( m_lastannouncement != announcement_t::approaching
|
|
&& Point.fDist < 750
|
|
&& Point.fDist > 250 ) {
|
|
announce( announcement_t::approaching );
|
|
}
|
|
} else if( true == IsAtPassengerStop ) {
|
|
// jeśli się zatrzymał przy W4, albo stał w momencie zobaczenia W4
|
|
if( !AIControllFlag ) {
|
|
// w razie przełączenia na AI ma nie podciągać do W4, gdy użytkownik zatrzymał za daleko
|
|
iDrivigFlags &= ~moveStopCloser;
|
|
}
|
|
if (TrainParams.UpdateMTable( simulation::Time, asNextStop) ) {
|
|
// to się wykona tylko raz po zatrzymaniu na W4
|
|
record_station( Point, blackbox::station_kinds::stopped );
|
|
// the service flags of this stop hold for its doors and departure
|
|
m_stopflags = TrainParams.stop_flags();
|
|
if( TrainParams.StationIndex < TrainParams.StationCount ) {
|
|
// jeśli są dalsze stacje, bez trąbienia przed odjazdem
|
|
// also ignore any horn cue that may be potentially set below 1 km/h and before the actual full stop
|
|
iDrivigFlags &= ~( moveStartHorn | moveStartHornNow );
|
|
}
|
|
UpdateDelayFlag();
|
|
|
|
// perform loading/unloading
|
|
// HACK: manual check if we didn't already do load exchange at this stop
|
|
// TODO: remove the check once the station system is in place
|
|
if( m_lastexchangestop != asNextStop ) {
|
|
m_lastexchangestop = asNextStop;
|
|
m_lastexchangedirection = pVehicle->DirectionGet();
|
|
m_lastexchangeplatforms = static_cast<int>( std::floor( std::abs( Point.evEvent->input_value( 2 ) ) ) ) % 10;
|
|
auto const exchangetime { simulation::Station.update_load( pVehicles[ end::front ], TrainParams, m_lastexchangeplatforms ) };
|
|
WaitingSet( exchangetime );
|
|
// announce the stop name while at it
|
|
announce( announcement_t::current );
|
|
m_makenextstopannouncement = true;
|
|
}
|
|
|
|
if (TrainParams.DirectionChange()) {
|
|
// jeśli "@" w rozkładzie, to wykonanie dalszych komend
|
|
// wykonanie kolejnej komendy, nie dotyczy ostatniej stacji
|
|
if (iDrivigFlags & movePushPull) {
|
|
// SN61 ma się też nie ruszać, chyba że ma wagony
|
|
iDrivigFlags |= moveStopHere; // EZT ma stać przy peronie
|
|
if (OrderNextGet() != Change_direction) {
|
|
OrderPush(Change_direction); // zmiana kierunku
|
|
OrderPush(
|
|
TrainParams.StationIndex < TrainParams.StationCount ?
|
|
Obey_train :
|
|
Shunt); // to dalej wg rozkładu
|
|
}
|
|
}
|
|
else {
|
|
// a dla lokomotyw...
|
|
// pozwolenie na przejechanie za W4 przed czasem i nie ma stać
|
|
iDrivigFlags &= ~( moveStopPoint | moveStopHere );
|
|
}
|
|
// przejście do kolejnego rozkazu (zmiana kierunku, odczepianie)
|
|
JumpToNextOrder();
|
|
// ma nie podjeżdżać pod W4 po przeciwnej stronie
|
|
iDrivigFlags &= ~moveStopCloser;
|
|
// ten W4 nie liczy się już zupełnie (nie wyśle SetVelocity)
|
|
Point.iFlags = 0;
|
|
// jechać
|
|
Point.fVelNext = -1;
|
|
// nie analizować prędkości
|
|
return true;
|
|
}
|
|
}
|
|
|
|
if (OrderCurrentGet() & ( Shunt | Loose_shunt )) {
|
|
OrderNext(Obey_train); // uruchomić jazdę pociągową
|
|
CheckVehicles(); // zmienić światła
|
|
}
|
|
|
|
if (TrainParams.StationIndex < TrainParams.StationCount) {
|
|
// jeśli są dalsze stacje, czekamy do godziny odjazdu
|
|
if ( true == IsCargoTrain
|
|
|| true == TrainParams.IsMaintenance()
|
|
|| TrainParams.IsTimeToGo(simulation::Time.data().wHour, simulation::Time.data().wMinute + simulation::Time.data().wSecond * 0.0167) ) {
|
|
// z dalszą akcją czekamy do godziny odjazdu
|
|
// cargo trains and passenger trains at maintenance stop don't need to wait
|
|
IsAtPassengerStop = false;
|
|
record_station( Point, blackbox::station_kinds::ready );
|
|
// przy jakim dystansie (stanie licznika) ma przesunąć na następny postój
|
|
fLastStopExpDist = mvOccupied->DistCounter + 0.050 + 0.001 * fLength;
|
|
TrainParams.StationIndexInc(); // przejście do następnej
|
|
asNextStop = TrainParams.NextStop(); // pobranie kolejnego miejsca zatrzymania
|
|
#if LOGSTOPS
|
|
WriteLog(std::format(
|
|
"{} as {}: at {}:{} next {}",
|
|
pVehicle->asName, TrainParams.TrainName, simulation::Time.data().wHour, simulation::Time.data().wMinute, asNextStop)); // informacja
|
|
#endif
|
|
// update consist weight, brake settings and ai braking tables
|
|
// NOTE: this calculation is expected to run after completing loading/unloading
|
|
CheckVehicles(); // nastawianie hamulca do jazdy pociągowej
|
|
|
|
if( static_cast<int>( std::floor( std::abs( Point.evEvent->input_value( 1 ) ) ) ) % 2 ) {
|
|
// nie podjeżdżać do semafora, jeśli droga nie jest wolna
|
|
iDrivigFlags |= moveStopHere;
|
|
}
|
|
else {
|
|
//po czasie jedź dalej
|
|
iDrivigFlags &= ~moveStopHere;
|
|
}
|
|
iDrivigFlags |= moveStopCloser; // do następnego W4 podjechać blisko (z dociąganiem)
|
|
Point.iFlags = 0; // nie liczy się już zupełnie (nie wyśle SetVelocity)
|
|
Point.fVelNext = -1; // można jechać za W4
|
|
if( Point.fDist <= 0.0 && eSignNext == Point.evEvent ) {
|
|
// sanity check, if we're held by this stop point, let us go
|
|
VelSignalLast = -1;
|
|
}
|
|
if( Command == TCommandType::cm_Unknown ) { // jeśli nie było komendy wcześniej
|
|
Command = TCommandType::cm_Ready; // gotów do odjazdu z W4 (semafor może zatrzymać)
|
|
}
|
|
if( false == tsGuardSignal.empty()
|
|
&& true == timetable::has_conductor( m_stopflags ) ) {
|
|
// jeśli mamy głos kierownika, to odegrać
|
|
iDrivigFlags |= moveGuardSignal;
|
|
}
|
|
return true; // nie analizować prędkości
|
|
} // koniec startu z zatrzymania
|
|
else {
|
|
cue_action(driver_hint::waitdeparturetime);
|
|
if (timetable::has_conductor(m_stopflags) // no conductor, no door kept open for him
|
|
&& TrainParams.IsTimeToGo(simulation::Time.data().wHour, simulation::Time.data().wMinute + simulation::Time.data().wSecond*0.0167 + 0.1)) { //if is less than 6 sec to departure
|
|
iDrivigFlags |= moveGuardOpenDoor;
|
|
GuardOpenDoor();
|
|
}
|
|
}
|
|
} // koniec obsługi początkowych stacji
|
|
else {
|
|
// jeśli dojechaliśmy do końca rozkładu
|
|
#if LOGSTOPS
|
|
WriteLog(std::format(
|
|
"{} as {}: at {}:{} end of route.",
|
|
pVehicle->asName, TrainParams.TrainName, simulation::Time.data().wHour, simulation::Time.data().wMinute)); // informacja
|
|
#endif
|
|
asNextStop = TrainParams.NextStop(); // informacja o końcu trasy
|
|
TrainParams.NewName("none"); // czyszczenie nieaktualnego rozkładu
|
|
// koniec kursu, gasimy wyświetlacze relacji (tablice blaszane zostają)
|
|
for( auto *vehicle { pVehicles[ end::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) {
|
|
vehicle->DestinationClear();
|
|
}
|
|
// ma nie podjeżdżać pod W4 i ma je pomijać
|
|
iDrivigFlags &= ~moveStopCloser;
|
|
if( false == TestFlag( iDrivigFlags, movePushPull ) ) {
|
|
// if the consist can change direction through a simple cab change it doesn't need fiddling with recognition of passenger stops
|
|
iDrivigFlags &= ~moveStopPoint;
|
|
}
|
|
fLastStopExpDist = -1.0f; // nie ma rozkładu, nie ma usuwania stacji
|
|
Point.iFlags = 0; // W4 nie liczy się już (nie wyśle SetVelocity)
|
|
Point.fVelNext = -1; // można jechać za W4
|
|
if( Point.fDist <= 0.0 && eSignNext == Point.evEvent ) {
|
|
// sanity check, if we're held by this stop point, let us go
|
|
VelSignalLast = -1;
|
|
}
|
|
// wykonanie kolejnego rozkazu (Change_direction albo Shunt)
|
|
JumpToNextOrder();
|
|
// ma się nie ruszać aż do momentu podania sygnału
|
|
iDrivigFlags |= moveStopHere | moveStartHorn;
|
|
return true; // nie analizować prędkości
|
|
} // koniec obsługi ostatniej stacji
|
|
} // vel 0, at passenger stop
|
|
else {
|
|
// HACK: momentarily deactivate W4 to trick the controller into moving closer
|
|
Point.fVelNext = -1;
|
|
} // vel 0, outside of passenger stop
|
|
} // koniec obsługi zatrzymania na W4
|
|
} // koniec warunku pomijania W4 podczas zmiany czoła
|
|
else
|
|
{ // skoro pomijanie, to jechać i ignorować W4
|
|
Point.iFlags = 0; // W4 nie liczy się już (nie zatrzymuje jazdy)
|
|
Point.fVelNext = -1;
|
|
return true; // nie analizować prędkości
|
|
}
|
|
|
|
return false; //
|
|
}
|
|
|
|
// a road speed sign (W27/W27a) passed by the head stays in the table until the rear is past it too. not for cars: their
|
|
// passed events leave the table at the latest when the rear passes them (TableCheck), before the table update sees that
|
|
bool
|
|
TController::is_road_velocity_held( TSpeedPos const &Point ) const {
|
|
|
|
return TestFlag( Point.iFlags, spRoadVel )
|
|
&& mvOccupied->CategoryFlag != 2
|
|
&& Point.fDist >= -fLength;
|
|
}
|
|
|
|
// a passed event is handled once and then dropped from the table, except a road speed sign held for the rear
|
|
void
|
|
TController::TableDropPassedEvent( TSpeedPos &Point ) const {
|
|
|
|
if( is_road_velocity_held( Point ) ) {
|
|
Point.iFlags |= spRoadVelHeld;
|
|
return;
|
|
}
|
|
Point.Clear();
|
|
}
|
|
|
|
// the lowest road speed of the signs past the given one that the head has passed: held until the rear is past them too,
|
|
// or passed in this very tick and not marked as held yet; -1 if there's none
|
|
double
|
|
TController::held_road_velocity_beyond( TSpeedPos const &Point ) const {
|
|
|
|
auto lowest { -1.0 };
|
|
for( auto const &held : sSpeedTable ) {
|
|
if( ( held.iFlags & ( spEnabled | spRoadVel ) ) != ( spEnabled | spRoadVel )
|
|
|| held.fDist >= 0.0
|
|
|| held.fDist <= Point.fDist ) {
|
|
continue;
|
|
}
|
|
lowest = min_speed( lowest, held.fVelNext );
|
|
}
|
|
return lowest;
|
|
}
|
|
|
|
// a road speed (W27/W27a) lower than the one in force holds once the head passes the sign, a higher one only once the
|
|
// whole train is past it (a car takes it from the head). the first pass after the head handles the sign as before, the
|
|
// entry is then only held for the rear: returns true for it, so the rest of the table update leaves it out
|
|
bool
|
|
TController::TableUpdateRoadVelocity( TSpeedPos &Point ) {
|
|
|
|
if( Point.fDist >= 0.0 ) { return false; }
|
|
|
|
if( mvOccupied->CategoryFlag == 2 ) {
|
|
VelRoad = Point.fVelNext;
|
|
return false;
|
|
}
|
|
|
|
auto const isrearpast { Point.fDist < -fLength };
|
|
if( isrearpast ) {
|
|
// the rear past it, but not past a sign after it the head has passed too: none of those may be exceeded, so a
|
|
// lower one (W27a 60 within a train's length after a 120) stays in force
|
|
VelRoad = min_speed( Point.fVelNext, held_road_velocity_beyond( Point ) );
|
|
}
|
|
else if( Point.fVelNext == min_speed( Point.fVelNext, VelRoad ) ) {
|
|
VelRoad = Point.fVelNext;
|
|
}
|
|
if( false == TestFlag( Point.iFlags, spRoadVelHeld ) ) {
|
|
return false;
|
|
}
|
|
if( isrearpast ) {
|
|
Point.Clear();
|
|
}
|
|
return true;
|
|
}
|
|
|
|
// a reduced speed shown by a signal holds to the end of the interlocking area the signal guards (Ie-1), and that end is
|
|
// marked on the main track with a SignalAreaEnd event. on a track without the marker the speed holds as it did before:
|
|
// until the next signal, or until no signal, switch or stop point is left in the scan
|
|
void
|
|
TController::TableUpdateSignalAreaEnd( TSpeedPos &Point ) {
|
|
|
|
// the switches lie in front of the marker, so the whole train has left them once its rear end is past it
|
|
if( Point.fDist >= -fLength ) {
|
|
if( SignalAreaEndDist < 0.0
|
|
&& TestFlag( OrderCurrentGet(), Obey_train ) ) {
|
|
// the table is sorted by distance, so the first marker is the nearest one
|
|
SignalAreaEndDist = Point.fDist + fLength;
|
|
}
|
|
return;
|
|
}
|
|
|
|
// in shunting the marker stays, a train order given before the next signal still finds it
|
|
if( false == TestFlag( OrderCurrentGet(), Obey_train ) ) { return; }
|
|
|
|
// a passed signal at stop (0) keeps holding the train, only a reduced speed ends here
|
|
if( VelSignalLast > 0.0 ) {
|
|
if( Global.iWriteLogEnabled & 8 ) {
|
|
WriteLog( "Speed table update for " + OwnerName() + ", left the interlocking area at " + Point.evEvent->m_name );
|
|
}
|
|
VelSignalLast = -1.0;
|
|
}
|
|
Point.Clear();
|
|
}
|
|
|
|
bool TController::point_limit_latched( basic_event const *Cell ) const {
|
|
|
|
return std::any_of(
|
|
m_pointlimits.begin(), m_pointlimits.end(),
|
|
[&]( point_limit const &Limit ) { return Limit.source == Cell; } );
|
|
}
|
|
|
|
double TController::point_limit_end( glm::dvec3 const &Heading ) const {
|
|
|
|
auto const origin { pVehicle->GetPosition() };
|
|
auto result { 0.0 };
|
|
auto first { true };
|
|
for( auto const *vehicle : { pVehicles[ end::front ], pVehicles[ end::rear ] } ) {
|
|
if( vehicle == nullptr ) { continue; }
|
|
for( auto const side : { end::front, end::rear } ) {
|
|
auto const along { glm::dot( vehicle->CouplerPosition( side ) - origin, Heading ) };
|
|
result = ( first ? along : std::max( result, along ) );
|
|
first = false;
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
|
|
void TController::latch_point_limit( TSpeedPos const &Point ) {
|
|
|
|
if( point_limit_latched( Point.evEvent ) ) { return; }
|
|
m_pointlimits.push_back(
|
|
point_limit { Point.evEvent, Point.fVelNext, Point.fDist + Point.fPointDist, Point.fPointDist, travel_direction() } );
|
|
if( Global.iWriteLogEnabled & 8 ) {
|
|
WriteLog( "Speed table update for " + OwnerName() + ", latched point limit of " + Point.evEvent->m_name
|
|
+ ": " + to_string( Point.fVelNext, 0 ) + " in " + to_string( m_pointlimits.back().distance, 0 ) + " m" );
|
|
}
|
|
}
|
|
|
|
void TController::update_point_limits() {
|
|
|
|
if( pVehicle == nullptr ) { return; }
|
|
auto const position { pVehicle->GetPosition() };
|
|
if( m_pointlimitsvehicle == pVehicle ) {
|
|
auto const movement { position - m_pointlimitsposition };
|
|
auto const length { glm::length( movement ) };
|
|
if( length >= 200.0 ) {
|
|
// a longer jump between two updates isn't driving: the consist was moved elsewhere
|
|
m_pointlimits.clear();
|
|
}
|
|
else if( length > 0.0 ) {
|
|
auto const step { movement / length };
|
|
for( auto &limit : m_pointlimits ) {
|
|
if( glm::length( limit.heading ) < 0.5 ) {
|
|
// the way wasn't known when the limit was latched, the head was passing the cell
|
|
limit.heading = step;
|
|
}
|
|
auto const along { glm::dot( step, limit.heading ) };
|
|
limit.distance += ( along >= 0.0 ? -length : length );
|
|
// the way towards the point follows the line, step by step; a step far off it
|
|
// (a jolt of a standing vehicle) doesn't turn it
|
|
if( std::abs( along ) > 0.5 ) {
|
|
limit.heading = ( along >= 0.0 ? step : -step );
|
|
}
|
|
}
|
|
}
|
|
}
|
|
// a change of the vehicle (another cab) starts the measure from its place
|
|
auto const vehiclechanged { m_pointlimitsvehicle != pVehicle };
|
|
auto const previousposition { m_pointlimitsposition };
|
|
m_pointlimitsvehicle = pVehicle;
|
|
m_pointlimitsposition = position;
|
|
// the consist, as its end vehicles and its length
|
|
auto const *front { pVehicles[ end::front ] };
|
|
auto const *rear { pVehicles[ end::rear ] };
|
|
auto const consistchanged {
|
|
false == ( ( front == m_pointlimitsends[ 0 ] && rear == m_pointlimitsends[ 1 ] )
|
|
|| ( front == m_pointlimitsends[ 1 ] && rear == m_pointlimitsends[ 0 ] ) )
|
|
|| std::abs( fLength - m_pointlimitslength ) > 0.5 };
|
|
m_pointlimitsends[ 0 ] = front;
|
|
m_pointlimitsends[ 1 ] = rear;
|
|
m_pointlimitslength = fLength;
|
|
// vehicles coupled or uncoupled at the end towards the point move the head towards it or away. only a change of
|
|
// the consist counts, as the end measured from the vehicle shifts on curves. another vehicle measured from (a cab
|
|
// change, which may come with a coupling in the same order) moves the end measured before to its place
|
|
for( auto &limit : m_pointlimits ) {
|
|
if( glm::length( limit.heading ) < 0.5 ) { continue; }
|
|
auto const consistend { point_limit_end( limit.heading ) };
|
|
if( limit.endknown && consistchanged ) {
|
|
auto const previousend {
|
|
vehiclechanged ?
|
|
limit.end + glm::dot( previousposition - position, limit.heading ) :
|
|
limit.end };
|
|
limit.distance -= consistend - previousend;
|
|
}
|
|
limit.end = consistend;
|
|
limit.endknown = true;
|
|
}
|
|
|
|
auto const travel { travel_direction() };
|
|
std::erase_if(
|
|
m_pointlimits,
|
|
[&]( point_limit const &Limit ) {
|
|
// passed by the head
|
|
if( Limit.distance < 0.0 ) {
|
|
if( Global.iWriteLogEnabled & 8 ) {
|
|
WriteLog( "Speed table update for " + OwnerName() + ", passed point limit of " + Limit.source->m_name );
|
|
}
|
|
return true;
|
|
}
|
|
// the head backed up behind the cell: the speed table reads it again if it is ahead
|
|
if( Limit.distance > Limit.celldistance + 1.0 ) {
|
|
if( Global.iWriteLogEnabled & 8 ) {
|
|
WriteLog( "Speed table update for " + OwnerName() + ", left behind point limit of " + Limit.source->m_name );
|
|
}
|
|
return true;
|
|
}
|
|
// the cell ahead of the head again, going towards the point after backing up past the cell: it is read anew
|
|
// (not while backing up: the cell may as well be scanned from the other side)
|
|
return glm::dot( travel, Limit.heading ) > 0.0
|
|
&& std::any_of(
|
|
sSpeedTable.begin(), sSpeedTable.end(),
|
|
[&]( TSpeedPos const &Point ) {
|
|
return Point.evEvent == Limit.source
|
|
&& TestFlag( Point.iFlags, spEnabled | spEvent | spPointVelocity )
|
|
&& Point.fDist > 0.0; } ); } );
|
|
}
|
|
|
|
void TController::apply_point_limits( double &Velocity, double &Distance, double &Next, double &Acceleration ) {
|
|
|
|
auto const travel { travel_direction() };
|
|
for( auto const &limit : m_pointlimits ) {
|
|
// latched with no limit, or passed (dropped at the next update)
|
|
if( limit.velocity < 0.0 || limit.distance <= 0.0 ) { continue; }
|
|
// going away from the point, or the way isn't known
|
|
if( glm::dot( travel, limit.heading ) <= 0.0 ) { continue; }
|
|
// the same as for a point of the speed table ahead
|
|
auto const v { limit.velocity };
|
|
auto const d { limit.distance };
|
|
auto a { ( v * v - mvOccupied->Vel * mvOccupied->Vel ) / ( 25.92 * d ) };
|
|
if( mvOccupied->Vel < v ) {
|
|
auto const brakingdistance { 1.2 * fBrakeDist * braking_distance_multiplier( v ) };
|
|
if( brakingdistance > 0.0 ) {
|
|
a = std::lerp( a, AccPreferred, std::clamp( ( d - brakingdistance ) / brakingdistance, 0.0, 1.0 ) );
|
|
}
|
|
}
|
|
if( d < point_limit_approach() && v < Velocity ) {
|
|
Velocity = v;
|
|
}
|
|
if( a <= Acceleration
|
|
&& ( v < Next || Next < 0 ) ) {
|
|
Acceleration = a;
|
|
Next = v;
|
|
Distance = d;
|
|
bStopTargetIsPassengerStop = false;
|
|
}
|
|
}
|
|
}
|
|
|
|
double TController::point_limit_approach() const {
|
|
// a point limit holds at its point and not a metre beyond, so the braking curve alone leaves a slow consist
|
|
// coasting above it (the deceleration asked for is below what makes the driver brake). within the final
|
|
// approach, and five seconds of the present speed before it, the speed is held down to it already
|
|
return fMaxProximityDist + mvOccupied->Vel / 3.6 * 5.0;
|
|
}
|
|
|
|
glm::dvec3 TController::travel_direction() const {
|
|
|
|
if( pVehicle == nullptr || iDirection == 0 ) { return glm::dvec3 { 0.0 }; }
|
|
// the direction is given against the couplers of the vehicle the driver is in, which is the vehicle measured;
|
|
// along its own length it follows the track, where the chord of a long consist on a curve doesn't
|
|
auto const along { pVehicle->CouplerPosition( end::front ) - pVehicle->CouplerPosition( end::rear ) };
|
|
auto const length { glm::length( along ) };
|
|
if( length < 0.001 ) { return glm::dvec3 { 0.0 }; }
|
|
return ( iDirection > 0 ? along : -along ) / length;
|
|
}
|
|
|
|
bool
|
|
TController::TableUpdateEvent( double &Velocity, TCommandType &Command, TSpeedPos &Point, double &Signaldistance, int const Pointindex ) {
|
|
|
|
if( TestFlag( Point.iFlags, spSignalAreaEnd ) ) {
|
|
// not a signal: it neither sends a command nor counts as the end of a speed limit in the scan
|
|
TableUpdateSignalAreaEnd( Point );
|
|
return true;
|
|
}
|
|
|
|
if( TestFlag( Point.iFlags, spPointVelocity ) ) {
|
|
// PointVelocity: no signal, no command, only the limit at its point
|
|
// done once the head passes the point
|
|
if( Point.fDist + Point.fPointDist < 0.0 ) {
|
|
if( Global.iWriteLogEnabled & 8 ) {
|
|
WriteLog( "Speed table update for " + OwnerName() + ", passed point limit of " + Point.GetName() );
|
|
}
|
|
Point.Clear();
|
|
return true;
|
|
}
|
|
if( Point.fDist < 0.0 ) {
|
|
if( point_limit_latched( Point.evEvent ) ) {
|
|
// a table built anew found under the consist a cell whose state holds already
|
|
Point.Clear();
|
|
return true;
|
|
}
|
|
if( Point.fVelNext != 0.0 ) {
|
|
// the head passed the cell: what it says now holds at the point, whatever happens to the table.
|
|
// a stop at 0 stays in the table, where the cell can still release it
|
|
latch_point_limit( Point );
|
|
Point.Clear();
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
// sprawdzanie eventów pasywnych miniętych
|
|
if( Point.fDist < 0.0 ) {
|
|
if( SemNextIndex == Pointindex ) {
|
|
if( Global.iWriteLogEnabled & 8 ) {
|
|
WriteLog( "Speed table update for " + OwnerName() + ", passed semaphor " + sSpeedTable[ SemNextIndex ].GetName() );
|
|
}
|
|
SemNextIndex = npos; // jeśli minęliśmy semafor od ograniczenia to go kasujemy ze zmiennej sprawdzającej dla skanowania w przód
|
|
}
|
|
if( SemNextStopIndex == Pointindex ) {
|
|
if( Global.iWriteLogEnabled & 8 ) {
|
|
WriteLog( "Speed table update for " + OwnerName() + ", passed semaphor " + sSpeedTable[ SemNextStopIndex ].GetName() );
|
|
}
|
|
SemNextStopIndex = npos; // jeśli minęliśmy semafor od ograniczenia to go kasujemy ze zmiennej sprawdzającej dla skanowania w przód
|
|
}
|
|
switch( Point.evEvent->input_command() ) {
|
|
// TBD, TODO: expand emergency_brake handling to a more generic security system signal
|
|
case TCommandType::cm_EmergencyBrake: {
|
|
pVehicle->RadioStop();
|
|
Point.Clear(); // signal received, deactivate
|
|
return true;
|
|
}
|
|
case TCommandType::cm_SecuritySystemMagnet: {
|
|
// NOTE: magnet induction calculation presumes the driver is located in the front vehicle
|
|
// TBD, TODO: take into account actual position of controlled/occupied vehicle in the consist, whichever comes first
|
|
auto const magnetlocation { pVehicles[ end::front ]->MoverParameters->SecuritySystem.MagnetLocation };
|
|
auto const magnetrange { 1.0 };
|
|
auto const ismagnetpassed { Point.fDist < -( magnetlocation + magnetrange ) };
|
|
if( Point.fDist < -magnetlocation && (mvOccupied->Vel > EU07_AI_NOMOVEMENT || false == ismagnetpassed) ) {
|
|
// NOTE: normally we'd activate the magnet once the leading vehicle passes it
|
|
// but on a fresh scan after direction change it would be detected as long as it's under consist, and meet the (simple) activation condition
|
|
// thus we're doing a more precise check in such situation (we presume direction change takes place only if the vehicle is standing still)
|
|
mvOccupied->SecuritySystem.set_cabsignal_lock(!AIControllFlag); // don't make life difficult for the ai, but a human driver is a fair game
|
|
PutCommand(Point.evEvent->input_text(), Point.evEvent->input_value(1), Point.evEvent->input_value(2), nullptr);
|
|
}
|
|
if( ismagnetpassed ) {
|
|
Point.Clear();
|
|
mvOccupied->SecuritySystem.set_cabsignal_lock(false);
|
|
}
|
|
return true;
|
|
}
|
|
default: {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
// check signals ahead
|
|
if( Point.fDist > 0.0 ) {
|
|
// bail out early for signals which activate when passed
|
|
// TBD: make it an event method?
|
|
switch( Point.evEvent->input_command() ) {
|
|
case TCommandType::cm_EmergencyBrake: {
|
|
return true;
|
|
}
|
|
case TCommandType::cm_SecuritySystemMagnet: {
|
|
return true;
|
|
}
|
|
default: {
|
|
break;
|
|
}
|
|
}
|
|
|
|
if( Point.IsProperSemaphor( OrderCurrentGet() ) ) {
|
|
// special rule for cars: ignore stop signals at distance too short to come to a stop
|
|
// as trying to stop in such situation is likely to place the car on train tracks
|
|
if( is_car()
|
|
&& Point.fVelNext != -1.0
|
|
&& Point.fVelNext < 1.0
|
|
&& Point.fDist < -0.5 + std::min(fBrakeDist * 0.2, mvOccupied->Vel * 0.2) ) {
|
|
Point.Clear();
|
|
return true;
|
|
}
|
|
// jeśli jest mienięty poprzedni semafor a wcześniej
|
|
// byl nowy to go dorzucamy do zmiennej, żeby cały czas widział najbliższy
|
|
if( SemNextIndex == npos ) { // NOSONAR
|
|
SemNextIndex = Pointindex;
|
|
if( Global.iWriteLogEnabled & 8 ) {
|
|
WriteLog( "Speed table update for " + OwnerName() + ", next semaphor is " + sSpeedTable[ SemNextIndex ].GetName() );
|
|
}
|
|
}
|
|
if( SemNextStopIndex == npos
|
|
|| ( sSpeedTable[SemNextStopIndex].fVelNext != 0
|
|
&& Point.fVelNext == 0 ) ) {
|
|
SemNextStopIndex = Pointindex;
|
|
}
|
|
}
|
|
}
|
|
if (Point.iFlags & spOutsideStation)
|
|
{ // jeśli W5, to reakcja zależna od trybu jazdy
|
|
if (OrderCurrentGet() & Obey_train)
|
|
{ // w trybie pociągowym: można przyspieszyć do wskazanej prędkości (po zjechaniu z rozjazdów)
|
|
Velocity = -1.0; // ignorować?
|
|
if ( Point.fDist < 0.0) { // jeśli wskaźnik został minięty
|
|
VelSignalLast = Velocity; //ustawienie prędkości na -1
|
|
}
|
|
else if( ( iDrivigFlags & moveSwitchFound ) == 0 ) { // jeśli rozjazdy już minięte
|
|
VelSignalLast = Velocity; //!!! to też koniec ograniczenia
|
|
}
|
|
}
|
|
else
|
|
{ // w trybie manewrowym: skanować od niego wstecz, stanąć po wyjechaniu za sygnalizator i zmienić kierunek
|
|
Velocity = 0.0; // zmiana kierunku może być podanym sygnałem, ale wypadało by zmienić światło wcześniej
|
|
if( ( iDrivigFlags & moveSwitchFound ) == 0 ) { // jeśli nie ma rozjazdu
|
|
// check for presence of a signal facing the opposite direction
|
|
// if there's one, we'll want to pass it before changing direction
|
|
basic_event *foundevent = nullptr;
|
|
if( Point.fDist - fMaxProximityDist > 0 ) {
|
|
auto scandistance{ Point.fDist + fLength - fMaxProximityDist };
|
|
auto *scanvehicle{ pVehicles[ end::rear ] };
|
|
auto scandirection{ scanvehicle->DirectionGet() * scanvehicle->RaDirectionGet() };
|
|
auto *foundtrack = BackwardTraceRoute( scandistance, scandirection, scanvehicle, foundevent, -1, end::front, false );
|
|
}
|
|
if( foundevent == nullptr ) {
|
|
iDrivigFlags |= moveTrackEnd; // to dalsza jazda trwale ograniczona (W5, koniec toru)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
else if ( Point.iFlags & spStopOnSBL) {
|
|
// jeśli S1 na SBL
|
|
if( mvOccupied->Vel < 2.0 && Point.fDist < fMaxProximityDist && Obstacle.distance > 1000 ) {
|
|
// stanąć nie musi, ale zwolnić przynajmniej
|
|
// jest w maksymalnym zasięgu to można go pominąć (wziąć drugą prędkosć)
|
|
// as long as there isn't any obstacle in arbitrary view range
|
|
eSignSkip = Point.evEvent;
|
|
// jazda na widoczność - skanować możliwość kolizji i nie podjeżdżać zbyt blisko
|
|
// usunąć flagę po podjechaniu blisko semafora zezwalającego na jazdę
|
|
// ostrożnie interpretować sygnały - semafor może zezwalać na jazdę pociągu z przodu!
|
|
iDrivigFlags |= moveVisibility;
|
|
// store the ordered restricted speed and don't exceed it until the flag is cleared
|
|
VelRestricted = Point.evEvent->input_value(2);
|
|
}
|
|
if( eSignSkip != Point.evEvent ) {
|
|
// jeśli ten SBL nie jest do pominięcia to ma 0 odczytywać
|
|
Velocity = Point.evEvent->input_value( 1 );
|
|
// TODO sprawdzić do której zmiennej jest przypisywane v i zmienić to tutaj
|
|
}
|
|
}
|
|
else if ( Point.IsProperSemaphor(OrderCurrentGet()))
|
|
{ // to semaphor
|
|
if( Point.fDist < 0 ) {
|
|
// for human-driven vehicles ignore the signal if it was passed by sufficient distance
|
|
if( false == AIControllFlag
|
|
&& Point.fDist < -1 * std::max(fLength + 100, 250.0) ) {
|
|
VelSignal = -1.0;
|
|
Point.Clear();
|
|
return true;
|
|
}
|
|
// for ai-driven vehicles always play by the rules
|
|
else {
|
|
VelSignalLast = Point.fVelNext; //minięty daje prędkość obowiązującą
|
|
// a marker before this signal ends the interlocking area of an earlier signal, not the area of this one
|
|
// (a train longer than the way between the two, or one which started standing over the marker)
|
|
std::ranges::for_each( sSpeedTable | std::views::take( Pointindex ), clear_signal_area_end );
|
|
}
|
|
}
|
|
else {
|
|
//jeśli z przodu to dajemy flagę, że jest
|
|
iDrivigFlags |= moveSignalFound;
|
|
Signaldistance = std::min( Point.fDist, Signaldistance );
|
|
// if there's another vehicle closer to the signal, then it's likely its intended recipient
|
|
// HACK: if so, make it a stop point, to prevent non-signals farther down affect us
|
|
auto const isforsomeoneelse { is_train() && Obstacle.distance < Point.fDist };
|
|
if( Point.fDist <= Signaldistance ) {
|
|
if( isforsomeoneelse ) {
|
|
VelSignalNext = 0.0;
|
|
Velocity = 0.0;
|
|
}
|
|
else {
|
|
VelSignalNext = Point.fVelNext;
|
|
if( Velocity < 0 ) {
|
|
Velocity = fVelMax;
|
|
VelSignal = fVelMax;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
else if ( Point.iFlags & spRoadVel)
|
|
{ // to W27/W27a
|
|
if( TableUpdateRoadVelocity( Point ) ) {
|
|
return true;
|
|
}
|
|
}
|
|
else if ( Point.iFlags & spSectionVel && Point.fDist < 0)
|
|
{ // to W9
|
|
// teraz trzeba sprawdzić inne warunki
|
|
if (Point.fSectionVelocityDist == 0.0)
|
|
{
|
|
if (Global.iWriteLogEnabled & 8)
|
|
{
|
|
WriteLog("TableUpdate: Event is behind. SVD = 0: " + Point.evEvent->m_name);
|
|
}
|
|
Point.Clear(); // jeśli punktowy to kasujemy i nie dajemy ograniczenia na stałe
|
|
}
|
|
else if (Point.fSectionVelocityDist < 0.0)
|
|
{
|
|
// ograniczenie obowiązujące do następnego
|
|
if (Point.fVelNext == min_speed(Point.fVelNext, VelLimitLast) && Point.fVelNext != VelLimitLast)
|
|
{
|
|
// jeśli ograniczenie jest mniejsze niż obecne to obowiązuje od zaraz
|
|
VelLimitLast = Point.fVelNext;
|
|
}
|
|
else if (Point.fDist < -fLength)
|
|
{
|
|
// jeśli większe to musi wyjechać za poprzednie
|
|
VelLimitLast = Point.fVelNext;
|
|
if (Global.iWriteLogEnabled & 8)
|
|
{
|
|
WriteLog("TableUpdate: Event is behind. SVD < 0: " + Point.evEvent->m_name);
|
|
}
|
|
Point.Clear(); // wyjechaliśmy poza poprzednie, można skasować
|
|
}
|
|
}
|
|
else
|
|
{ // jeśli większe to ograniczenie ma swoją długość
|
|
if (Point.fVelNext == min_speed(Point.fVelNext, VelLimitLast) && Point.fVelNext != VelLimitLast)
|
|
{
|
|
// jeśli ograniczenie jest mniejsze niż obecne to obowiązuje od zaraz
|
|
VelLimitLast = Point.fVelNext;
|
|
}
|
|
else if (Point.fDist < -fLength && Point.fVelNext != VelLimitLast)
|
|
{
|
|
// jeśli większe to musi wyjechać za poprzednie
|
|
VelLimitLast = Point.fVelNext;
|
|
}
|
|
else if (Point.fDist < -fLength - Point.fSectionVelocityDist)
|
|
{
|
|
VelLimitLast = -1.0;
|
|
if (Global.iWriteLogEnabled & 8)
|
|
{
|
|
WriteLog("TableUpdate: Event is behind. SVD > 0: " + Point.evEvent->m_name);
|
|
}
|
|
Point.Clear(); // wyjechaliśmy poza poprzednie, można skasować
|
|
}
|
|
}
|
|
}
|
|
|
|
//sprawdzenie eventów pasywnych przed nami
|
|
{ // zawalidrogi nie ma (albo pojazd jest samochodem), sprawdzić sygnał
|
|
if ( Point.iFlags & spShuntSemaphor) // jeśli Tm - w zasadzie to sprawdzić komendę!
|
|
{ // jeśli podana prędkość manewrowa
|
|
if( Velocity == 0.0
|
|
&& true == TestFlag(OrderCurrentGet(), Obey_train) ) {
|
|
// jeśli tryb pociągowy a tarcze ma ShuntVelocity 0 0
|
|
Velocity = -1; // ignorować, chyba że prędkość stanie się niezerowa
|
|
if( true == TestFlag( Point.iFlags, spElapsed ) ) {
|
|
// a jak przejechana to można usunąć, bo podstawowy automat usuwa tylko niezerowe
|
|
Point.Clear();
|
|
}
|
|
}
|
|
else if( Command == TCommandType::cm_Unknown && Velocity != 0.0 ) {
|
|
// jeśli jeszcze nie ma komendy
|
|
// komenda jest tylko gdy ma jechać, bo stoi na podstawie tabelki
|
|
// jeśli nie było komendy wcześniej - pierwsza się liczy - ustawianie VelSignal
|
|
Command = TCommandType::cm_ShuntVelocity; // w trybie pociągowym tylko jeśli włącza tryb manewrowy (v!=0.0)
|
|
// Ra 2014-06: (VelSignal) nie może być tu ustawiane, bo Tm może być daleko
|
|
if (VelSignal == 0.0)
|
|
{
|
|
// aby stojący ruszył
|
|
VelSignal = Velocity;
|
|
}
|
|
if (Point.fDist < 0.0)
|
|
{
|
|
// jeśli przejechany
|
|
//!!! ustawienie, gdy przejechany jest lepsze niż wcale, ale to jeszcze nie to
|
|
VelSignal = Velocity;
|
|
// to można usunąć (nie mogą być usuwane w skanowaniu)
|
|
Point.Clear();
|
|
}
|
|
}
|
|
}
|
|
else if( ( Point.iFlags & spSectionVel ) == 0 ) {
|
|
//jeśli jakiś event pasywny ale nie ograniczenie
|
|
if( Command != TCommandType::cm_Unknown )
|
|
{
|
|
}
|
|
else
|
|
{
|
|
// jeśli nie było komendy wcześniej - pierwsza się liczy - ustawianie VelSignal
|
|
if (Velocity < 0.0 || Velocity >= 1.0)
|
|
{
|
|
// bo wartość 0.1 służy do hamowania tylko
|
|
Command = TCommandType::cm_SetVelocity; // może odjechać
|
|
// Ra 2014-06: (VelSignal) nie może być tu ustawiane, bo semafor może być daleko
|
|
// VelSignal=v; //nie do końca tak, to jest druga prędkość; -1 nie wpisywać...
|
|
if (VelSignal == 0.0)
|
|
{
|
|
// aby stojący ruszył
|
|
VelSignal = -1.0;
|
|
}
|
|
if (Point.fDist < 0.0)
|
|
{
|
|
// jeśli przejechany
|
|
VelSignal = Velocity == 0.0 ? 0.0 : -1.0;
|
|
// ustawienie, gdy przejechany jest lepsze niż wcale, ale to jeszcze nie to
|
|
if (Point.iFlags & spEvent && (Point.evEvent != eSignSkip || Point.fVelNext != VelRestricted))
|
|
{
|
|
// jeśli event
|
|
// ale inny niż ten, na którym minięto S1, chyba że się już zmieniło
|
|
// sygnał zezwalający na jazdę wyłącza jazdę na widoczność (po S1 na SBL)
|
|
iDrivigFlags &= ~moveVisibility;
|
|
// remove restricted speed
|
|
VelRestricted = -1.0;
|
|
}
|
|
// jeśli nie jest ograniczeniem prędkości to można usunąć
|
|
// (nie mogą być usuwane w skanowaniu)
|
|
TableDropPassedEvent( Point );
|
|
}
|
|
}
|
|
else if (Point.evEvent->is_command())
|
|
{
|
|
// jeśli prędkość jest zerowa, a komórka zawiera komendę
|
|
eSignNext = Point.evEvent; // dla informacji
|
|
// make sure the command isn't for someone else
|
|
// TBD, TODO: revise this check for bank/loose_shunt; we might want to ignore obstacles with no owner in these modes
|
|
if (Point.fDist < Obstacle.distance)
|
|
{
|
|
if (true == TestFlag(iDrivigFlags, moveStopHere))
|
|
{
|
|
// jeśli ma stać, dostaje komendę od razu
|
|
Command = TCommandType::cm_Command; // komenda z komórki, do wykonania po zatrzymaniu
|
|
}
|
|
// NOTE: human drivers are likely to stop wherever and expect things to still work, so we give them more leeway
|
|
else if (Point.fDist <= (AIControllFlag ? fMaxProximityDist : std::max(250.0, fMaxProximityDist)))
|
|
{
|
|
// jeśli ma dociągnąć, to niech dociąga
|
|
// (moveStopCloser dotyczy dociągania do W4, nie semafora)
|
|
Command = TCommandType::cm_Command; // komenda z komórki, do wykonania po zatrzymaniu
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
} // jeśli nie ma zawalidrogi
|
|
|
|
return false;
|
|
}
|
|
|
|
// modifies brake distance for low target speeds, to ease braking rate in such situations
|
|
float
|
|
TController::braking_distance_multiplier( float const Targetvelocity ) const {
|
|
|
|
auto const frictionmultiplier { 1.f / Global.FrictionWeatherFactor };
|
|
|
|
if( Targetvelocity > 65.f ) { return 1.f * frictionmultiplier; }
|
|
if( Targetvelocity < 5.f ) {
|
|
// HACK: engaged automatic transmission means extra/earlier braking effort is needed for the last leg before full stop
|
|
if( is_dmu()
|
|
&& mvOccupied->Vel < 40.0
|
|
&& Targetvelocity == 0.f ) {
|
|
auto const multiplier { std::clamp( 1.f + iVehicles * 0.5f, 2.f, 4.f ) };
|
|
return std::lerp(multiplier, 1.f, static_cast<float>(mvOccupied->Vel / 40.0)) * frictionmultiplier;
|
|
}
|
|
// HACK: cargo trains or trains going downhill with high braking threshold need more distance to come to a full stop
|
|
if( fBrake_a0[1] > 0.2
|
|
&& ( true == IsCargoTrain
|
|
|| fAccGravity > 0.025 ) ) {
|
|
return std::lerp(1.f, 2.f, std::clamp((fBrake_a0[1] - 0.2) / 0.2, 0.0, 1.0)) * frictionmultiplier;
|
|
}
|
|
|
|
return 1.f * frictionmultiplier;
|
|
}
|
|
// stretch the braking distance up to 3 times; the lower the speed, the greater the stretch
|
|
return std::lerp(3.f, 1.f, (Targetvelocity - 5.f) / 60.f) * frictionmultiplier;
|
|
}
|
|
|
|
void TController::TablePurger()
|
|
{ // odtykacz: usuwa mniej istotne pozycje ze środka tabelki, aby uniknąć zatkania
|
|
//(np. brak ograniczenia pomiędzy zwrotnicami, usunięte sygnały, minięte odcinki łuku)
|
|
if( sSpeedTable.size() < 2 ) {
|
|
return;
|
|
}
|
|
// simplest approach should be good enough for start -- just copy whatever is still relevant, then swap
|
|
auto const isexpendable = []( TSpeedPos const &Speedpoint ) {
|
|
return
|
|
0 == ( Speedpoint.iFlags & spEnabled )
|
|
|| ( ( Speedpoint.iFlags & ( spElapsed | spTrack | spCurve | spSwitch ) ) == ( spElapsed | spTrack | spCurve )
|
|
&& Speedpoint.fVelNext < 0.0 ); };
|
|
// do a trial run first, to see if we need to bother at all
|
|
std::size_t trimcount{ 0 };
|
|
for( std::size_t idx = 0; idx < sSpeedTable.size() - 1; ++idx ) {
|
|
// NOTE: we could break out early here, but running through entire thing gives us exact size needed for new table
|
|
if( isexpendable( sSpeedTable[ idx ] ) ) {
|
|
++trimcount;
|
|
}
|
|
}
|
|
if( trimcount == 0 ) {
|
|
// there'd be no gain, may as well bail
|
|
return;
|
|
}
|
|
std::vector<TSpeedPos> trimmedtable; trimmedtable.reserve( sSpeedTable.size() - trimcount );
|
|
// the indices are only valid for the old table, so the new placements are recorded separately
|
|
// and assigned once the new table is complete
|
|
auto semnextindex { std::size_t( -1 ) };
|
|
auto semnextstopindex { std::size_t( -1 ) };
|
|
auto const trackplacement = [&]( std::size_t const Index, bool const Kept ) {
|
|
// a trimmed point leaves the index invalid, a kept one lands where the new table ends
|
|
if( Index == SemNextIndex ) {
|
|
semnextindex = ( Kept ? trimmedtable.size() : std::size_t( -1 ) );
|
|
}
|
|
if( Index == SemNextStopIndex ) {
|
|
semnextstopindex = ( Kept ? trimmedtable.size() : std::size_t( -1 ) );
|
|
} };
|
|
|
|
for( std::size_t idx = 0; idx < sSpeedTable.size() - 1; ++idx ) {
|
|
auto const &speedpoint = sSpeedTable[ idx ];
|
|
auto const kept { false == isexpendable( speedpoint ) };
|
|
trackplacement( idx, kept );
|
|
if( false == kept ) { continue; }
|
|
// we're left with useful speed point record we should copy
|
|
trimmedtable.emplace_back( speedpoint );
|
|
}
|
|
// always copy the last entry; an index pointing at it has to follow it as well
|
|
trackplacement( sSpeedTable.size() - 1, true );
|
|
trimmedtable.emplace_back( sSpeedTable.back() );
|
|
|
|
SemNextIndex = semnextindex;
|
|
SemNextStopIndex = semnextstopindex;
|
|
|
|
if( Global.iWriteLogEnabled & 8 ) {
|
|
WriteLog( "Speed table garbage collection for " + OwnerName() + " cut away " + std::to_string( trimcount ) + ( trimcount == 1 ? " record" : " records" ) );
|
|
}
|
|
// update the data
|
|
std::swap( sSpeedTable, trimmedtable );
|
|
iLast = sSpeedTable.size() - 1;
|
|
};
|
|
|
|
void TController::TableSort() {
|
|
|
|
if( sSpeedTable.size() < 3 ) {
|
|
// we skip last slot and no point in checking if there's only one other entry
|
|
return;
|
|
}
|
|
// the last slot holds the track the scan stopped at and stays where it is.
|
|
// a single bubble pass is not enough: TableTraceRoute() adds the events of a track before the
|
|
// track itself, so a track with k scanned events lands k places too far and needs k passes
|
|
auto const sortedcount { static_cast<std::size_t>( iLast ) };
|
|
auto const inrange = [&]( std::size_t const Index ) {
|
|
return Index < sortedcount; };
|
|
// the placements point at semaphor entries; remember which ones, the sort moves them around
|
|
auto const *semnextevent { inrange( SemNextIndex ) ? sSpeedTable[ SemNextIndex ].evEvent : nullptr };
|
|
auto const *semnextstopevent { inrange( SemNextStopIndex ) ? sSpeedTable[ SemNextStopIndex ].evEvent : nullptr };
|
|
|
|
std::stable_sort(
|
|
std::begin( sSpeedTable ), std::begin( sSpeedTable ) + sortedcount,
|
|
[]( TSpeedPos const &Left, TSpeedPos const &Right ) {
|
|
return Left.fDist < Right.fDist; } );
|
|
|
|
auto const relocate = [&]( basic_event const *Event, std::size_t &Index ) {
|
|
if( Event == nullptr ) { return; }
|
|
auto const lookup {
|
|
std::find_if(
|
|
std::begin( sSpeedTable ), std::begin( sSpeedTable ) + sortedcount,
|
|
[Event]( TSpeedPos const &Point ) {
|
|
return Point.evEvent == Event; } ) };
|
|
Index = (
|
|
lookup != std::begin( sSpeedTable ) + sortedcount ?
|
|
static_cast<std::size_t>( std::distance( std::begin( sSpeedTable ), lookup ) ) :
|
|
std::size_t( -1 ) );
|
|
};
|
|
relocate( semnextevent, SemNextIndex );
|
|
relocate( semnextstopevent, SemNextStopIndex );
|
|
}
|
|
|
|
//---------------------------------------------------------------------------
|
|
|
|
TController::TController(bool AI, TDynamicObject *NewControll, bool InitPsyche, bool Primary) :// czy ma aktywnie prowadzić?
|
|
AIControllFlag( AI ), pVehicle( NewControll )
|
|
{
|
|
if( pVehicle != nullptr ) {
|
|
pVehicles[ end::front ] = pVehicle->GetFirstDynamic( end::front ); // pierwszy w kierunku jazdy (Np. Pc1)
|
|
pVehicles[ end::rear ] = pVehicle->GetFirstDynamic( end::rear ); // ostatni w kierunku jazdy (końcówki)
|
|
}
|
|
else {
|
|
pVehicles[ end::front ] = nullptr;
|
|
pVehicles[ end::rear ] = nullptr;
|
|
}
|
|
ControllingSet(); // utworzenie połączenia do sterowanego pojazdu
|
|
if( mvOccupied != nullptr ) {
|
|
iDirectionOrder = mvOccupied->CabActive; // 1=do przodu (w kierunku sprzęgu 0)
|
|
VehicleName = mvOccupied->Name;
|
|
|
|
if( is_car() ) { // samochody: na podst. http://www.prawko-kwartnik.info/hamowanie.html
|
|
// fDriverBraking=0.0065; //mnożone przez (v^2+40*v) [km/h] daje prawie drogę hamowania [m]
|
|
fDriverBraking = 0.03; // coś nie hamują te samochody zbyt dobrze
|
|
fDriverDist = 5.0; // 5m - zachowywany odstęp przed kolizją
|
|
fVelPlus = 10.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania
|
|
fVelMinus = 2.0; // margines prędkości powodujący załączenie napędu
|
|
}
|
|
else { // pociągi i statki
|
|
fDriverBraking = 0.06; // mnożone przez (v^2+40*v) [km/h] daje prawie drogę hamowania [m]
|
|
fDriverDist = 50.0; // 50m - zachowywany odstęp przed kolizją
|
|
fVelPlus = 5.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania
|
|
fVelMinus = 5.0; // margines prędkości powodujący załączenie napędu
|
|
}
|
|
|
|
// fAccThreshold może podlegać uczeniu się - hamowanie powinno być rejestrowane, a potem analizowane
|
|
// próg opóźnienia dla zadziałania hamulca
|
|
fAccThreshold = is_emu() ? -0.55 : is_dmu() ? -0.45 : -0.2;
|
|
/*
|
|
// HACK: emu with induction motors need to start their braking a bit sooner than the ones with series motors
|
|
if( ( mvOccupied->TrainType == dt_EZT )
|
|
&& ( mvControlling->EngineType == TEngineType::ElectricInductionMotor ) ) {
|
|
fAccThreshold += 0.10;
|
|
}
|
|
*/
|
|
}
|
|
// TrainParams=NewTrainParams;
|
|
// if (TrainParams)
|
|
// asNextStop=TrainParams.NextStop();
|
|
// else
|
|
TrainParams = TTrainParameters("none"); // rozkład jazdy
|
|
// OrderCommand="";
|
|
// OrderValue=0;
|
|
OrdersClear();
|
|
|
|
if( true == Primary ) {
|
|
iDrivigFlags |= movePrimary; // aktywnie prowadzące pojazd
|
|
}
|
|
|
|
if( mvOccupied != nullptr ) {
|
|
SetDriverPsyche(); // na końcu, bo wymaga ustawienia zmiennych
|
|
}
|
|
TableClear();
|
|
|
|
// the logs of all, begun at once as they always were. one of a train only at its first line (update_logs): every
|
|
// crew is made primary here, and the drivers but one of a train with crews in more vehicles are made passive
|
|
// before it starts, so they get no file with only the header
|
|
if( WriteLogFlag ) {
|
|
begin_physicslog();
|
|
}
|
|
|
|
// HACK: give the simulation a small window to potentially replace the AI with a human driver
|
|
fActionTime = -5.0;
|
|
};
|
|
|
|
TController::~TController()
|
|
{ // wykopanie mechanika z roboty
|
|
};
|
|
|
|
// zamiana kodu rozkazu na opis
|
|
std::string TController::Order2Str(TOrders Order) const {
|
|
|
|
if( (Order & Change_direction) != 0
|
|
&& Order != Change_direction ) {
|
|
// może być nałożona na inną i wtedy ma priorytet
|
|
return
|
|
Order2Str( Change_direction )
|
|
+ " + "
|
|
+ Order2Str( static_cast<TOrders>( Order & ~Change_direction ) );
|
|
}
|
|
switch( Order ) {
|
|
case Wait_for_orders: return "Wait_for_orders";
|
|
case Prepare_engine: return "Prepare_engine";
|
|
case Release_engine: return "Release_engine";
|
|
case Change_direction: return "Change_direction";
|
|
case Connect: return "Connect";
|
|
case Disconnect: return "Disconnect";
|
|
case Shunt: return "Shunt";
|
|
case Loose_shunt: return "Loose_shunt";
|
|
case Obey_train: return "Obey_train";
|
|
case Bank: return "Bank";
|
|
case Jump_to_first_order: return "Jump_to_first_order";
|
|
default: return "Undefined";
|
|
}
|
|
}
|
|
|
|
std::array<char, 64> orderbuffer;
|
|
|
|
std::string TController::OrderCurrent() const
|
|
{ // pobranie aktualnego rozkazu celem wyświetlenia
|
|
auto const order { OrderCurrentGet() };
|
|
// generally prioritize direction change...
|
|
if( order & Change_direction && false == TestFlag(iDrivigFlags, moveConnect) ) {
|
|
// ...but not in the middle of coupling operation
|
|
return STR("Change direction");
|
|
}
|
|
|
|
switch( static_cast<TOrders>( order & ~Change_direction ) ) {
|
|
case Wait_for_orders: { return STR("Wait for orders"); }
|
|
case Prepare_engine: { return STR("Start the engine"); }
|
|
case Release_engine: { return STR("Shut down the engine"); }
|
|
case Change_direction: { return STR("Change direction"); }
|
|
case Connect: { return STR("Couple to consist ahead"); }
|
|
case Disconnect: {
|
|
if( iVehicleCount < 0 ) {
|
|
// done with uncoupling, order should update shortly
|
|
return STR("Wait for orders");
|
|
}
|
|
// try to provide some task details
|
|
auto const count { iVehicleCount };
|
|
|
|
if( iVehicleCount > 1 ) {
|
|
std::snprintf(
|
|
orderbuffer.data(), orderbuffer.size(),
|
|
STR_C("the engine plus %d next vehicles"), // TODO: implement plural forms
|
|
count );
|
|
}
|
|
auto const countstring { (
|
|
count == 0 ? STR("the engine") :
|
|
count == 1 ? STR("the engine plus the next vehicle") :
|
|
orderbuffer.data() ) };
|
|
|
|
std::snprintf(
|
|
orderbuffer.data(), orderbuffer.size(),
|
|
STR_C("Uncouple %s"),
|
|
countstring.c_str() );
|
|
return orderbuffer.data();
|
|
}
|
|
case Shunt: { return STR("Shunt according to signals"); }
|
|
case Loose_shunt: { return STR("Loose shunt according to signals"); }
|
|
case Obey_train: { return STR("Drive according to signals and timetable"); }
|
|
case Bank: { return STR("Bank consist ahead"); }
|
|
default: { return{}; }
|
|
}
|
|
};
|
|
|
|
void TController::OrdersClear()
|
|
{ // czyszczenie tabeli rozkazów na starcie albo po dojściu do końca
|
|
OrderPos = 0;
|
|
OrderTop = 1; // szczyt stosu rozkazów
|
|
for (int b = 0; b < maxorders; b++)
|
|
OrderList[b] = Wait_for_orders;
|
|
#if LOGORDERS
|
|
OrdersDump("OrdersClear", false);
|
|
#endif
|
|
};
|
|
|
|
void TController::Activation()
|
|
{ // umieszczenie obsady w odpowiednim członie, wykonywane wyłącznie gdy steruje AI
|
|
iDirection = iDirectionOrder; // kierunek (względem sprzęgów pojazdu z AI) właśnie został ustalony (zmieniony)
|
|
if (iDirection)
|
|
{ // jeśli jest ustalony kierunek
|
|
auto *initialvehicle { pVehicle };
|
|
/*
|
|
auto const initiallocalbrakelevel { mvOccupied->LocalBrakePosA };
|
|
*/
|
|
auto const initialspringbrakestate { mvOccupied->SpringBrake.Activate };
|
|
// switch off tempomat
|
|
SpeedCntrl( 0.0 );
|
|
mvControlling->DecScndCtrl( 2 );
|
|
// reset controls
|
|
ZeroSpeed();
|
|
ZeroDirection();
|
|
mvOccupied->CabOccupied = mvOccupied->CabActive; // użytkownik moze zmienić CabOccupied wychodząc
|
|
mvOccupied->CabDeactivisation(); // tak jest w Train.cpp
|
|
if (TestFlag(pVehicle->MoverParameters->Couplers[iDirectionOrder < 0 ? end::rear : end::front].CouplingFlag, coupling::control)) {
|
|
ZeroLocalBrake();
|
|
if( initialspringbrakestate ) {
|
|
mvOccupied->SpringBrakeActivate( false );
|
|
}
|
|
// odcięcie na zaworze maszynisty, FVel6 po drugiej stronie nie luzuje
|
|
mvOccupied->BrakeLevelSet( mvOccupied->Handle->GetPos(bh_NP) ); // odcięcie na zaworze maszynisty
|
|
BrakeLevelSet( mvOccupied->BrakeCtrlPos ); //ustawienie zmiennej GBH
|
|
}
|
|
// przejście AI na drugą stronę EN57, ET41 itp.
|
|
// TODO: clean this up, there's lot of redundancy with TMoverParameters::ChangeCab() and TTrain::MoveToVehicle()
|
|
{
|
|
int movedirection { ( iDirection < 0 ? end::rear : end::front ) };
|
|
auto *targetvehicle { pVehicle->FirstFind( movedirection, coupling::control ) };
|
|
if( pVehicle != targetvehicle ) {
|
|
auto *targetvehicledriver { targetvehicle->Mechanik }; // zapamiętanie tego, co ewentualnie tam siedzi, żeby w razie dwóch zamienić miejscami
|
|
// move to the new vehicle
|
|
targetvehicle->Mechanik = this; // na razie bilokacja
|
|
targetvehicle->MoverParameters->SetInternalCommand("", 0, 0); // usunięcie ewentualnie zalegającej komendy (Change_direction?)
|
|
if( targetvehicle->DirectionGet() != pVehicle->DirectionGet() ) {
|
|
// jeśli są przeciwne do siebie to będziemy jechać w drugą stronę względem zasiedzianego pojazdu
|
|
iDirection = -iDirection;
|
|
}
|
|
// move the other driver to our old vehicle
|
|
pVehicle->Mechanik = targetvehicledriver; // wsadzamy tego, co ewentualnie był (podwójna trakcja)
|
|
// NOTE: having caboccupied != 0 (by swapping in the driver from the target vehicle) may lead to dysfunctional brake
|
|
// TODO: investigate and resolve if necessary
|
|
pVehicle->MoverParameters->CabOccupied = targetvehicle->MoverParameters->CabOccupied;
|
|
if( pVehicle->Mechanik ) { // not guaranteed, as target vehicle can be empty
|
|
pVehicle->Mechanik->BrakeLevelSet( pVehicle->MoverParameters->BrakeCtrlPos );
|
|
}
|
|
// finish driver swap
|
|
pVehicle = targetvehicle;
|
|
}
|
|
}
|
|
if (pVehicle != initialvehicle)
|
|
{ // jeśli zmieniony został pojazd prowadzony
|
|
ControllingSet(); // utworzenie połączenia do sterowanego pojazdu (może się zmienić) - silnikowy dla EZT
|
|
if( mvOccupied->BrakeCtrlPosNo > 0
|
|
&& ( BrakeSystem == TBrakeSystem::Pneumatic
|
|
|| BrakeSystem == TBrakeSystem::ElectroPneumatic ) ) {
|
|
mvOccupied->LimPipePress = mvOccupied->PipePress;
|
|
mvOccupied->ActFlowSpeed = 0;
|
|
}
|
|
BrakeLevelSet( mvOccupied->BrakeCtrlPos );
|
|
}
|
|
if( mvControlling->EngineType == TEngineType::DieselEngine && mvControlling->ShuntModeAllow ) {
|
|
// dla 2Ls150 - przed ustawieniem kierunku - można zmienić tryb pracy
|
|
mvControlling->CurrentSwitch((OrderCurrentGet() & (Shunt | Loose_shunt)) != 0 || fMass > 224000.0); // do tego na wzniesieniu może nie dać rady na liniowym
|
|
}
|
|
// Ra: to przełączanie poniżej jest tu bez sensu
|
|
mvOccupied->CabOccupied = iDirection; // aktywacja kabiny w prowadzonym pojeżdzie (silnikowy może być odwrotnie?)
|
|
mvOccupied->CabActivisation(); // uruchomienie kabin w członach
|
|
DirectionForward(true); // nawrotnik do przodu
|
|
mvOccupied->SpringBrakeActivate( initialspringbrakestate );
|
|
/*
|
|
// NOTE: this won't restore local brake if the vehicle has integrated local brake control
|
|
// TBD, TODO: fix or let the ai activate the brake again as part of its standard logic?
|
|
if (initiallocalbrakelevel > 0.0) // hamowanie tylko jeśli był wcześniej zahamowany (bo możliwe, że jedzie!)
|
|
mvOccupied->LocalBrakePosA = initiallocalbrakelevel; // zahamuj jak wcześniej
|
|
*/
|
|
if( pVehicle != initialvehicle ) {
|
|
auto *train { simulation::Trains.find( initialvehicle->name() ) };
|
|
if( train ) {
|
|
train->MoveToVehicle( pVehicle );
|
|
}
|
|
}
|
|
|
|
CheckVehicles(); // sprawdzenie składu, AI zapali światła
|
|
TableClear(); // resetowanie tabelki skanowania torów
|
|
}
|
|
};
|
|
|
|
void TController::AutoRewident()
|
|
{ // autorewident: nastawianie hamulców w składzie
|
|
// 1. Zebranie informacji o składzie pociągu, od czoła do końca
|
|
std::vector<brake_setting::vehicle> consist;
|
|
for (auto const *d = pVehicles[0]; d != nullptr; d = d->Next()) {
|
|
consist.emplace_back(brake_setting::describe(*d->MoverParameters, d == pVehicle));
|
|
}
|
|
// 2. Określenie typu pociągu i nastaw: by the brake instruction Cw-1 (eu07/maszyna#350), or as the releases before it did.
|
|
// brakes are cut out (Cw-1 §19.9) only in a train (a bank engine's run included), not in a consist being shunted
|
|
auto const train{brake_setting::runs_as_train(OrderCurrentGet())};
|
|
auto const settings{Global.AIBrakeSettingCw1 ? brake_setting::choose(consist, train) : brake_setting::choose_legacy(consist)};
|
|
// and only at a standstill, the train creeping to a stop included: a check on the run (the order changed mid-run, or
|
|
// the train was just formed by coupling, which the AI does above that speed) leaves them to reinspect_brakes()
|
|
auto const standstill{brake_setting::at_standstill(mvOccupied->Vel)};
|
|
auto reinspect{false};
|
|
// a light engine counts as a passenger train for the braking below
|
|
auto const passengertrain{brake_setting::passenger(brake_setting::choose_train_setting(consist))};
|
|
// 3. Nastawianie
|
|
auto setting{settings.begin()};
|
|
for (auto *d = pVehicles[0]; d != nullptr && setting != settings.end(); d = d->Next(), ++setting) {
|
|
if (false == AIControllFlag && d == pVehicle) {
|
|
// don't touch human-controlled vehicle, but others are free game
|
|
continue;
|
|
}
|
|
// the setting, a brake cut out in a train on G (Cw-1 §19.9) or put back when the train no longer needs it cut out
|
|
if (brake_setting::apply(*d->MoverParameters, *setting, standstill)) {
|
|
// a brake to cut out, with the train moving: left for the next standstill
|
|
reinspect = true;
|
|
}
|
|
// potentially release manual brake
|
|
d->MoverParameters->DecManualBrakeLevel( ManualBrakePosNo );
|
|
d->MoverParameters->SpringBrake.Activate = false;
|
|
}
|
|
BrakeReinspectionPending = reinspect;
|
|
//ustawianie trybu pracy zadajnika hamulca, wystarczy raz po inicjalizacji AI
|
|
if( true == AIControllFlag ) {
|
|
// if a human is in charge leave the brake mode up to them, otherwise do as you like
|
|
for( int i = 1; i <= 8; i *= 2 ) {
|
|
if( ( mvOccupied->BrakeOpModes & i ) > 0 ) {
|
|
mvOccupied->BrakeOpModeFlag = i;
|
|
}
|
|
}
|
|
}
|
|
|
|
// teraz zerujemy tabelkę opóźnienia hamowania
|
|
for (int i = 0; i < BrakeAccTableSize; ++i)
|
|
{
|
|
fBrake_a0[i+1] = 0;
|
|
fBrake_a1[i+1] = 0;
|
|
}
|
|
|
|
if( OrderCurrentGet() & ( Shunt | Loose_shunt ) ) {
|
|
// for uniform behaviour and compatibility with older scenarios set default acceleration table values for shunting
|
|
fAccThreshold = is_emu() ? -0.55 : is_dmu() ? -0.45 : -0.2;
|
|
// HACK: emu with induction motors need to start their braking a bit sooner than the ones with series motors
|
|
if( is_emu()
|
|
&& mvControlling->EngineType == TEngineType::ElectricInductionMotor ) {
|
|
fAccThreshold += 0.10;
|
|
}
|
|
fNominalAccThreshold = fAccThreshold;
|
|
}
|
|
|
|
BrakeSystem = consist_brake_system();
|
|
// Change the EP fuse state only when AI is in charge, don't fiddle with controls when the user is controlling the vehicle
|
|
if (AIControllFlag) {
|
|
mvOccupied->EpFuseSwitch(BrakeSystem == TBrakeSystem::ElectroPneumatic);
|
|
}
|
|
|
|
if( OrderCurrentGet() & ( Obey_train | Bank ) ) {
|
|
// 4. Przeliczanie siły hamowania
|
|
double const velstep = mvOccupied->Vmax * 0.5 / BrakeAccTableSize;
|
|
auto *d = pVehicles[0]; // pojazd na czele składu
|
|
while (d) {
|
|
// a vehicle with its brake cut out (by the inspector above or for a reason of its own) adds its mass only;
|
|
// the inspector of the earlier releases counted its brake in
|
|
auto const brakes{false == Global.AIBrakeSettingCw1 || false == brake_setting::is_cut_out(*d->MoverParameters)};
|
|
for( int i = 0; i < BrakeAccTableSize && brakes; ++i ) {
|
|
fBrake_a0[ i + 1 ] += d->MoverParameters->BrakeForceR( 0.25, velstep*( 1 + 2 * i ) );
|
|
fBrake_a1[ i + 1 ] += d->MoverParameters->BrakeForceR( 1.00, velstep*( 1 + 2 * i ) );
|
|
}
|
|
d = d->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła)
|
|
}
|
|
for (int i = 0; i < BrakeAccTableSize; ++i)
|
|
{
|
|
fBrake_a1[i+1] -= fBrake_a0[i+1];
|
|
fBrake_a0[i+1] /= fMass;
|
|
fBrake_a0[i + 1] += 0.001*velstep*(1 + 2 * i);
|
|
fBrake_a1[i+1] /= 12 * fMass;
|
|
}
|
|
|
|
IsPassengerTrain = is_train() && false == is_emu() && false == is_dmu() && (mvOccupied->BrakeDelayFlag & bdelay_G) == 0;
|
|
IsCargoTrain = is_train() && (mvOccupied->BrakeDelayFlag & bdelay_G) != 0;
|
|
IsHeavyCargoTrain = true == IsCargoTrain && fBrake_a0[1] > 0.4 && iVehicles - ControlledEnginesCount > 0 && fMass / iVehicles > 50000;
|
|
|
|
BrakingInitialLevel = IsHeavyCargoTrain ? 1.25 : IsCargoTrain ? 1.25 : 1.00;
|
|
|
|
BrakingLevelIncrease = 0.25;
|
|
|
|
if( is_emu() ) {
|
|
auto ep_factor { ( BrakeSystem == TBrakeSystem::ElectroPneumatic ? 8 : 4 ) };
|
|
if( mvControlling->EngineType == TEngineType::ElectricInductionMotor ) {
|
|
// HACK: emu with induction motors need to start their braking a bit sooner than the ones with series motors
|
|
fNominalAccThreshold = std::max( -0.60, -fBrake_a0[ BrakeAccTableSize ] - ep_factor * fBrake_a1[ BrakeAccTableSize ] );
|
|
}
|
|
else {
|
|
fNominalAccThreshold = std::max( -0.75, -fBrake_a0[ BrakeAccTableSize ] - ep_factor * fBrake_a1[ BrakeAccTableSize ] );
|
|
}
|
|
fBrakeReaction = 0.25;
|
|
}
|
|
else if( is_dmu() ) {
|
|
fNominalAccThreshold = std::max( -0.75, -fBrake_a0[ BrakeAccTableSize ] - 8 * fBrake_a1[ BrakeAccTableSize ] );
|
|
fBrakeReaction = 0.25;
|
|
}
|
|
else if (passengertrain) {
|
|
fNominalAccThreshold = -fBrake_a0[ BrakeAccTableSize ] - 4 * fBrake_a1[ BrakeAccTableSize ];
|
|
fBrakeReaction = 1.00 + fLength*0.004;
|
|
}
|
|
else {
|
|
fNominalAccThreshold = -fBrake_a0[ BrakeAccTableSize ] - 1 * fBrake_a1[ BrakeAccTableSize ];
|
|
fBrakeReaction = 1.00 + fLength*0.005;
|
|
}
|
|
fAccThreshold = fNominalAccThreshold;
|
|
}
|
|
|
|
}
|
|
|
|
// a brake the inspector had to cut out (Cw-1 §19.9) while the train was moving gets cut out once the train stands.
|
|
// a train formed by coupling is looked at as the buffers meet, above the speed the inspector takes for a standstill,
|
|
// and with no stop ahead nothing would look at it standing again (eu07/maszyna#350)
|
|
void TController::reinspect_brakes()
|
|
{
|
|
if (false == BrakeReinspectionPending) {
|
|
return;
|
|
}
|
|
if (false == brake_setting::runs_as_train(OrderCurrentGet())) {
|
|
// no longer a train: nothing is cut out in a consist being shunted
|
|
BrakeReinspectionPending = false;
|
|
return;
|
|
}
|
|
if (brake_setting::at_standstill(mvOccupied->Vel)) {
|
|
// standing, the inspector leaves nothing for later: this clears the flag
|
|
AutoRewident();
|
|
}
|
|
}
|
|
|
|
double TController::ESMVelocity(bool Main)
|
|
{
|
|
double fCurrentCoeff = 0.9;
|
|
double fFrictionCoeff = 0.85;
|
|
double ESMVel = 9999;
|
|
int MCPN = mvControlling->MainCtrlActualPos;
|
|
int SCPN = mvControlling->ScndCtrlActualPos;
|
|
if (Main)
|
|
MCPN += 1;
|
|
else
|
|
SCPN += 1;
|
|
if (mvControlling->RList[MCPN].ScndAct < 255 && mvControlling->ScndCtrlActualPos == 0)
|
|
SCPN = mvControlling->RList[MCPN].ScndAct;
|
|
double FrictionMax = mvControlling->Mass*9.81*mvControlling->Adhesive(mvControlling->RunningTrack.friction)*fFrictionCoeff;
|
|
double IF = mvControlling->Imax;
|
|
double MS = 0;
|
|
double Fmax = 0;
|
|
for (int i = 0; i < 5; i++)
|
|
{
|
|
MS = mvControlling->MomentumF(IF, IF, SCPN);
|
|
Fmax = MS * mvControlling->RList[MCPN].Bn * mvControlling->RList[MCPN].Mn * 2 / mvControlling->WheelDiameter * mvControlling->Transmision.Ratio;
|
|
if( Fmax != 0.0 ) {
|
|
IF = 0.5 * IF * ( 1 + FrictionMax / Fmax );
|
|
}
|
|
else {
|
|
// NOTE: gets trimmed to actual highest acceptable value after the loop
|
|
IF = std::numeric_limits<double>::max();
|
|
break;
|
|
}
|
|
}
|
|
IF = std::min(IF, mvControlling->Imax*fCurrentCoeff);
|
|
double R = mvControlling->RList[MCPN].R + mvControlling->CircuitRes + mvControlling->RList[MCPN].Mn*mvControlling->WindingRes;
|
|
double pole = mvControlling->MotorParam[SCPN].fi *
|
|
std::max(abs(IF) / (abs(IF) + mvControlling->MotorParam[SCPN].Isat) - mvControlling->MotorParam[SCPN].fi0, 0.0);
|
|
double Us = abs(mvControlling->EngineVoltage) - IF*R;
|
|
double ns = std::max(0.0, Us / (pole*mvControlling->RList[MCPN].Mn));
|
|
ESMVel = ns * mvControlling->WheelDiameter*M_PI*3.6/mvControlling->Transmision.Ratio;
|
|
return ESMVel;
|
|
}
|
|
|
|
int TController::CheckDirection() {
|
|
|
|
int d = mvOccupied->DirAbsolute; // który sprzęg jest z przodu
|
|
if( !d ) {
|
|
// jeśli nie ma ustalonego kierunku to jedziemy wg aktualnej kabiny
|
|
d = mvOccupied->CabActive;
|
|
}
|
|
return d;
|
|
}
|
|
|
|
bool TController::CheckVehicles(TOrders user)
|
|
{ // sprawdzenie stanu posiadanych pojazdów w składzie i zapalenie świateł
|
|
TDynamicObject *p; // roboczy wskaźnik na pojazd
|
|
iVehicles = 0; // ilość pojazdów w składzie
|
|
auto d = CheckDirection();
|
|
d = d >= 0 ? 0 : 1; // kierunek szukania czoła (numer sprzęgu)
|
|
p = pVehicle->FirstFind(d); // pojazd na czele składu
|
|
if (!p)
|
|
p = pVehicle;
|
|
auto *const frontvehicle { p }; // stays the consist head for the rest of this check
|
|
pVehicles[end::front] = frontvehicle;
|
|
// liczenie pojazdów w składzie i ustalenie parametrów
|
|
auto dir = d = 1 - d; // a dalej będziemy zliczać od czoła do tyłu
|
|
fLength = 0.0; // długość składu do badania wyjechania za ograniczenie
|
|
fMass = 0.0; // całkowita masa do liczenia stycznej składowej grawitacji
|
|
fVelMax = -1; // ustalenie prędkości dla składu
|
|
bool main = true; // czy jest głównym sterującym
|
|
iDrivigFlags |= moveOerlikons; // zakładamy, że są same Oerlikony
|
|
// Ra 2014-09: ustawić moveMultiControl, jeśli wszystkie są w ukrotnieniu (i skrajne mają kabinę?)
|
|
while (p)
|
|
{ // sprawdzanie, czy jest głównym sterującym, żeby nie było konfliktu
|
|
if( p->Mechanik // jeśli ma obsadę
|
|
&& p->Mechanik != this && p->Mechanik->iDrivigFlags & movePrimary ) { // ale chodzi o inny pojazd, niż aktualnie sprawdzający
|
|
// a tamten ma priorytet
|
|
// TODO: take into account drivers' operating modes, one or more of them might be on banking duty
|
|
if (iDrivigFlags & movePrimary && mvOccupied->DirAbsolute && mvOccupied->BrakeCtrlPos >= -1)
|
|
{
|
|
// jeśli rządzi i ma kierunek
|
|
p->Mechanik->primary(false); // dezaktywuje tamtego
|
|
p->Mechanik->ZeroLocalBrake();
|
|
p->MoverParameters->BrakeLevelSet(p->MoverParameters->Handle->GetPos(bh_NP)); // odcięcie na zaworze maszynisty
|
|
p->Mechanik->BrakeLevelSet(p->MoverParameters->BrakeCtrlPos); // ustawienie zmiennej GBH
|
|
}
|
|
else
|
|
{
|
|
main = false; // nici z rządzenia
|
|
}
|
|
}
|
|
++iVehicles; // jest jeden pojazd więcej
|
|
pVehicles[end::rear] = p; // zapamiętanie ostatniego
|
|
fLength += p->MoverParameters->Dim.L; // dodanie długości pojazdu
|
|
fMass += p->MoverParameters->TotalMass; // dodanie masy łącznie z ładunkiem
|
|
fVelMax = min_speed( fVelMax, p->MoverParameters->Vmax ); // ustalenie maksymalnej prędkości dla składu
|
|
// reset oerlikon brakes consist flag as different type was detected
|
|
if( p->MoverParameters->BrakeSubsystem != TBrakeSubSystem::ss_ESt
|
|
&& p->MoverParameters->BrakeSubsystem != TBrakeSubSystem::ss_LSt ) {
|
|
iDrivigFlags &= ~moveOerlikons;
|
|
}
|
|
p = p->Neighbour(dir); // pojazd podłączony od wskazanej strony
|
|
}
|
|
if( main ) {
|
|
iDrivigFlags |= movePrimary; // nie znaleziono innego, można się porządzić
|
|
}
|
|
|
|
ControllingSet(); // ustalenie członu do sterowania (może być inny niż zasiedziany)
|
|
|
|
if (iDrivigFlags & movePrimary)
|
|
{ // jeśli jest aktywnie prowadzącym pojazd, może zrobić własny porządek
|
|
auto pantmask = 1;
|
|
p = frontvehicle;
|
|
// establish ownership and vehicle order
|
|
while (p)
|
|
{
|
|
if (p->MoverParameters->EnginePowerSource.SourceType == TPowerSource::CurrentCollector)
|
|
{ // jeśli pojazd posiada pantograf, to przydzielamy mu maskę, którą będzie informował o jeździe bezprądowej
|
|
p->iOverheadMask = pantmask;
|
|
pantmask = pantmask << 1; // przesunięcie bitów, max. 32 pojazdy z pantografami w składzie
|
|
}
|
|
|
|
d = p->DirectionSet(d ? 1 : -1); // zwraca położenie następnego (1=zgodny,0=odwrócony - względem czoła składu)
|
|
p->ctOwner = this; // dominator oznacza swoje terytorium
|
|
p = p->Next(); // pojazd podłączony od tyłu (licząc od czoła)
|
|
}
|
|
// with the order established the virtual train manager can do their work
|
|
p = frontvehicle;
|
|
ControlledEnginesCount = p->MoverParameters->Power > 1.0 ? 1 : 0;
|
|
auto hasheaters { false };
|
|
while (p)
|
|
{
|
|
if( p != pVehicle ) {
|
|
if( false == p->is_connected( pVehicle, coupling::control ) ) {
|
|
// NOTE: don't set battery in controllable vehicles, let the user/ai do it explicitly
|
|
// HACK: wagony muszą mieć baterię załączoną do otwarcia drzwi...
|
|
p->MoverParameters->BatterySwitch( true );
|
|
// enable heating and converter in carriages with can be heated
|
|
if( p->MoverParameters->HeatingPower > 0 ) {
|
|
p->MoverParameters->HeatingAllow = true;
|
|
p->MoverParameters->ConverterSwitch( true, range_t::local );
|
|
hasheaters = true;
|
|
}
|
|
}
|
|
else {
|
|
if( p->MoverParameters->Power > 1.0 ) {
|
|
++ControlledEnginesCount;
|
|
}
|
|
}
|
|
}
|
|
|
|
if( p->asDestination == "none" ) {
|
|
p->DestinationSet( TrainParams.Relation2, TrainParams.TrainName ); // relacja docelowa, jeśli nie było
|
|
}
|
|
if( AIControllFlag ) { // jeśli prowadzi komputer
|
|
p->RaLightsSet( 0, 0 ); // gasimy światła
|
|
}
|
|
p = p->Next(); // pojazd podłączony od tyłu (licząc od czoła)
|
|
}
|
|
|
|
if( user == Connect && true == main ) {
|
|
// HACK: with additional vehicles in the consist ensure all linked vehicles are set to move in the same direction
|
|
if( pVehicle->Prev(coupling::control) != nullptr
|
|
|| pVehicle->Next(coupling::control) != nullptr ) {
|
|
sync_consist_reversers();
|
|
}
|
|
// potentially sync compartment lighting state for the newly connected vehicles
|
|
if( mvOccupied->CompartmentLights.start_type == start_t::manual ) {
|
|
mvOccupied->CompartmentLightsSwitchOff( mvOccupied->CompartmentLights.is_disabled );
|
|
mvOccupied->CompartmentLightsSwitch( mvOccupied->CompartmentLights.is_enabled );
|
|
}
|
|
}
|
|
|
|
// kasowanie pamieci hamowania kontrolnego
|
|
if (OrderCurrentGet() & (Shunt | Loose_shunt | Disconnect | Connect | Change_direction)) {
|
|
DynamicBrakeTest = 0;
|
|
DBT_VelocityBrake
|
|
= DBT_VelocityRelease
|
|
= DBT_VelocityFinish
|
|
= DBT_BrakingTime
|
|
= DBT_ReleasingTime
|
|
= DBT_MidPointAcc
|
|
= 0;
|
|
}
|
|
|
|
if( brake_setting::inspects_train( OrderCurrentGet(), user == Connect ) ) {
|
|
// nastawianie hamulca do jazdy pociągowej
|
|
AutoRewident();
|
|
/*
|
|
if( ( true == TestFlag( iDrivigFlags, moveConnect ) )
|
|
&& ( true == TestFlag( OrderCurrentGet(), Connect ) ) ) {
|
|
iCoupler = 0; // dalsza jazda manewrowa już bez łączenia
|
|
iDrivigFlags &= ~moveConnect; // zdjęcie flagi doczepiania
|
|
SetVelocity( 0, 0, stopJoin ); // wyłączyć przyspieszanie
|
|
JumpToNextOrder(); // wykonanie następnej komendy
|
|
}
|
|
*/
|
|
}
|
|
|
|
// detect push-pull train configurations and mark them accordingly
|
|
if( frontvehicle->is_connected( pVehicles[ end::rear ], coupling::control ) ) {
|
|
// zmiana czoła przez zmianę kabiny
|
|
iDrivigFlags |= movePushPull;
|
|
}
|
|
else {
|
|
// zmiana czoła przez manewry
|
|
iDrivigFlags &= ~movePushPull;
|
|
}
|
|
|
|
// HACK: ensure vehicle lights are active from the beginning, if it had pre-activated battery
|
|
if( mvOccupied->LightsPosNo > 0 ) {
|
|
pVehicle->SetLights();
|
|
}
|
|
if( iEngineActive ) {
|
|
// potentially adjust light state
|
|
control_lights();
|
|
// custom ai action for disconnect mode: switch off lights on disconnected vehicle(s)
|
|
if( is_train() && true == TestFlag(OrderCurrentGet(), Disconnect) && AIControllFlag ) {
|
|
// światła manewrowe (Tb1) tylko z przodu, aby nie pozostawić odczepionego ze światłem
|
|
if (mvOccupied->DirActive >= 0)
|
|
{ // jak ma kierunek do przodu
|
|
pVehicles[end::rear]->RaLightsSet(-1, 0);
|
|
}
|
|
else
|
|
{ // jak dociska
|
|
frontvehicle->RaLightsSet(0, -1);
|
|
}
|
|
}
|
|
// enable door locks
|
|
cue_action( driver_hint::consistdoorlockson );
|
|
// potentially enable train heating
|
|
{
|
|
auto const ispassengertrain { IsPassengerTrain && iVehicles - ControlledEnginesCount > 0 };
|
|
// TODO: replace connection test with connection check between last engine and first car, specifically
|
|
auto const isheatingcouplingactive { (
|
|
ControlledEnginesCount == 1 ?
|
|
frontvehicle->is_connected( pVehicles[ end::rear ], coupling::heating ) :
|
|
true ) };
|
|
auto const isheatingneeded {
|
|
(is_emu() || is_dmu() ? true :
|
|
(OrderCurrentGet() & (Obey_train | Bank)) == 0 ? false :
|
|
false == isheatingcouplingactive ? false :
|
|
ispassengertrain ? hasheaters :
|
|
false) };
|
|
if( mvControlling->HeatingAllow != isheatingneeded ) {
|
|
cue_action(
|
|
isheatingneeded ?
|
|
driver_hint::consistheatingon :
|
|
driver_hint::consistheatingoff );
|
|
}
|
|
}
|
|
}
|
|
|
|
if( user == Connect
|
|
|| user == Disconnect ) {
|
|
// HACK: force route table update on consist change, new consist length means distances to points of interest are now wrong
|
|
iTableDirection = 0;
|
|
}
|
|
} // blok wykonywany, gdy aktywnie prowadzi
|
|
return true;
|
|
}
|
|
|
|
void TController::Lights(int head, int rear)
|
|
{ // zapalenie świateł w skłądzie
|
|
pVehicles[ end::front ]->RaLightsSet(head, -1); // zapalenie przednich w pierwszym
|
|
pVehicles[ end::rear ]->RaLightsSet(-1, rear); // zapalenie końcówek w ostatnim
|
|
}
|
|
|
|
void TController::DirectionInitial()
|
|
{ // ustawienie kierunku po wczytaniu trainset (może jechać na wstecznym
|
|
mvOccupied->CabActivisationAuto(); // załączenie rozrządu (wirtualne kabiny)
|
|
if (mvOccupied->Vel > EU07_AI_NOMOVEMENT)
|
|
{ // jeśli na starcie jedzie
|
|
iDirection = iDirectionOrder =
|
|
mvOccupied->V > 0 ? 1 : -1; // początkowa prędkość wymusza kierunek jazdy
|
|
DirectionForward(mvOccupied->V * mvOccupied->CabActive >= 0.0); // a dalej ustawienie nawrotnika
|
|
}
|
|
CheckVehicles(); // sprawdzenie świateł oraz skrajnych pojazdów do skanowania
|
|
};
|
|
|
|
void TController::DirectionChange() {
|
|
|
|
auto const initialstate { iDirection };
|
|
iDirection = CheckDirection();
|
|
if( iDirection != initialstate ) {
|
|
CheckVehicles( Change_direction );
|
|
}
|
|
}
|
|
|
|
TBrakeSystem TController::consist_brake_system() const {
|
|
|
|
if( mvOccupied->BrakeSystem != TBrakeSystem::ElectroPneumatic ) { return mvOccupied->BrakeSystem; }
|
|
|
|
auto isepcapable = true;
|
|
if( pVehicles[ end::front ] != pVehicles[ end::rear ] ) {
|
|
// more detailed version, will use manual braking also for coupled sets of controlled vehicles
|
|
auto *vehicle = pVehicles[ end::front ]; // start from first
|
|
while( true == isepcapable
|
|
&& vehicle != nullptr ) {
|
|
// NOTE: we could simplify this by doing only check of the rear coupler, but this can be quite tricky in itself
|
|
// TODO: add easier ways to access front/rear coupler taking into account vehicle's direction
|
|
isepcapable = (vehicle->MoverParameters->Couplers[end::front].Connected == nullptr ||
|
|
(vehicle->MoverParameters->Couplers[end::front].CouplingFlag & coupling::control && vehicle->MoverParameters->Couplers[end::front].Connected->Power > -1)) &&
|
|
(vehicle->MoverParameters->Couplers[end::rear].Connected == nullptr ||
|
|
(vehicle->MoverParameters->Couplers[end::rear].CouplingFlag & coupling::control && vehicle->MoverParameters->Couplers[end::rear].Connected->Power > -1));
|
|
vehicle = vehicle->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła)
|
|
}
|
|
}
|
|
return isepcapable ? TBrakeSystem::ElectroPneumatic : TBrakeSystem::Pneumatic;
|
|
}
|
|
|
|
std::pair<int, double> TController::next_speed_limit() const {
|
|
|
|
auto const speedlimit { static_cast<int>( VelDesired ) };
|
|
auto nextspeedlimit { speedlimit };
|
|
auto nextspeedlimitdistance { std::numeric_limits<double>::max() };
|
|
if( speedlimit == 0 ) {
|
|
// if we aren't allowed to move then any next speed limit is irrelevant
|
|
return { nextspeedlimit, nextspeedlimitdistance };
|
|
}
|
|
// nie przekraczać rozkladowej
|
|
auto const schedulespeedlimit { (
|
|
( OrderCurrentGet() & ( Obey_train | Bank ) ) != 0 && TrainParams.TTVmax > 0.0 ? static_cast<int>( TrainParams.TTVmax ) :
|
|
( OrderCurrentGet() & ( Obey_train | Bank ) ) == 0 ? static_cast<int>( fShuntVelocity ) :
|
|
-1 ) };
|
|
// first take note of any speed change which should occur after passing potential current speed limit
|
|
if( VelLimitLastDist.second > 0 ) {
|
|
nextspeedlimit = min_speed( schedulespeedlimit, static_cast<int>( VelLimitLastDist.first ) );
|
|
nextspeedlimitdistance = VelLimitLastDist.second;
|
|
}
|
|
// then take into account speed change ahead, compare it with speed after potentially clearing last limit
|
|
// lower of these two takes priority; otherwise limit lasts at least until potential last limit is cleared
|
|
auto const noactivespeedlimit { VelLimitLastDist.second < 0 };
|
|
if( auto const speedatproximitydistance { min_speed( schedulespeedlimit, static_cast<int>( VelNext ) ) }; speedatproximitydistance == nextspeedlimit ) {
|
|
if( noactivespeedlimit ) {
|
|
nextspeedlimit = speedatproximitydistance;
|
|
nextspeedlimitdistance = ActualProximityDist;
|
|
}
|
|
}
|
|
else if( speedatproximitydistance < nextspeedlimit ) {
|
|
// if the speed limit ahead is more strict than our current limit, it's important enough to report
|
|
if( speedatproximitydistance < VelDesired ) {
|
|
nextspeedlimit = speedatproximitydistance;
|
|
nextspeedlimitdistance = ActualProximityDist;
|
|
}
|
|
// otherwise report it only if it's located after our current (lower) limit ends
|
|
else if( ActualProximityDist > nextspeedlimitdistance ) {
|
|
nextspeedlimit = speedatproximitydistance;
|
|
nextspeedlimitdistance = ActualProximityDist;
|
|
}
|
|
}
|
|
else if( noactivespeedlimit ) { // implicit proximity > last, report only if last limit isn't present
|
|
nextspeedlimit = speedatproximitydistance;
|
|
nextspeedlimitdistance = ActualProximityDist;
|
|
}
|
|
// HACK: if our current speed limit extends beyond our scan range don't display potentially misleading information about its length
|
|
if( nextspeedlimitdistance >= EU07_AI_SPEEDLIMITEXTENDSBEYONDSCANRANGE ) {
|
|
nextspeedlimit = speedlimit;
|
|
}
|
|
// HACK: hide next speed limit if the 'limit' is a vehicle in front of us
|
|
else if( ActualProximityDist == std::abs( TrackObstacle() ) ) {
|
|
nextspeedlimit = speedlimit;
|
|
}
|
|
return { nextspeedlimit, nextspeedlimitdistance };
|
|
}
|
|
|
|
blackbox::ai_reference TController::ai_reference() const {
|
|
|
|
blackbox::ai_reference ai;
|
|
ai.target_kmh = static_cast<float>( VelDesired );
|
|
if( auto const [ limit, distance ] { next_speed_limit() }; limit != static_cast<int>( VelDesired ) ) {
|
|
ai.next_limit_kmh = static_cast<float>( limit );
|
|
ai.next_limit_distance = static_cast<float>( distance );
|
|
}
|
|
ai.acceleration = static_cast<float>( AccDesired );
|
|
ai.braking_distance = static_cast<float>( fBrakeDist );
|
|
ai.timetable_vmax_kmh = ( TrainParams.TTVmax > 0.0 ? static_cast<float>( TrainParams.TTVmax ) : -1.0f );
|
|
ai.track_vmax_kmh = static_cast<float>( mvOccupied->RunningTrack.Velmax );
|
|
return ai;
|
|
}
|
|
|
|
void TController::record_station( TSpeedPos const &Point, std::uint8_t const Kind ) const {
|
|
|
|
if( Point.evEvent == nullptr ) { return; }
|
|
blackbox::station_event entry;
|
|
entry.kind = Kind;
|
|
auto const row { TrainParams.StationIndex };
|
|
entry.row = static_cast<std::uint16_t>( std::max( 0, row ) );
|
|
entry.station = asNextStop;
|
|
entry.position = Point.evEvent->input_location();
|
|
// the stop point may be moved back from the indicator, to where the head of the train is to stop
|
|
entry.distance = static_cast<float>( Point.fDist + Point.fMoved );
|
|
entry.stop_at = static_cast<float>( Point.fMoved );
|
|
entry.train_length = static_cast<float>( fLength );
|
|
entry.platform = static_cast<float>( Point.evEvent->input_value( 2 ) );
|
|
if( row >= 0 && row <= TrainParams.StationCount ) {
|
|
auto const &line { TrainParams.TimeTable[ row ] };
|
|
entry.arrival = ( line.Ah >= 0 ? static_cast<float>( line.Ah * 60 ) + line.Am : -1.0f );
|
|
entry.departure = ( line.Dh >= 0 ? static_cast<float>( line.Dh * 60 ) + line.Dm : -1.0f );
|
|
}
|
|
simulation::Blackbox.station( pVehicles[ end::front ], std::move( entry ) );
|
|
}
|
|
|
|
int TController::OrderDirectionChange(int newdir, TMoverParameters *Vehicle)
|
|
{ // zmiana kierunku jazdy, niezależnie od kabiny
|
|
int testd = newdir;
|
|
if (Vehicle->Vel < 0.5)
|
|
{ // jeśli prawie stoi, można zmienić kierunek, musi być wykonane dwukrotnie, bo za pierwszym razem daje na zero
|
|
switch (newdir * Vehicle->CabActive)
|
|
{ // DirectionBackward() i DirectionForward() to zmiany względem kabiny
|
|
case -1: // if (!Vehicle->DirectionBackward()) testd=0; break;
|
|
DirectionForward(false);
|
|
break;
|
|
case 1: // if (!Vehicle->DirectionForward()) testd=0; break;
|
|
DirectionForward(true);
|
|
break;
|
|
}
|
|
if (testd == 0)
|
|
VelforDriver = -1; // kierunek został zmieniony na żądany, można jechać
|
|
}
|
|
else // jeśli jedzie
|
|
VelforDriver = 0; // ma się zatrzymać w celu zmiany kierunku
|
|
if (Vehicle->DirActive == 0 && VelforDriver < Vehicle->Vel) // Ra: to jest chyba bez sensu
|
|
IncBrake(); // niech hamuje
|
|
if (Vehicle->DirActive == testd * Vehicle->CabActive)
|
|
VelforDriver = -1; // można jechać, bo kierunek jest zgodny z żądanym
|
|
if (is_emu() && Vehicle->DirActive > 0)
|
|
// if () //tylko jeśli jazda pociągowa (tego nie wiemy w momencie odpalania silnika)
|
|
Vehicle->DirectionForward();
|
|
// Ra: z przekazaniem do silnikowego
|
|
return (int)VelforDriver; // zwraca prędkość mechanika
|
|
}
|
|
|
|
void TController::WaitingSet(double Seconds)
|
|
{ // ustawienie odczekania po zatrzymaniu (ustawienie w trakcie jazdy zatrzyma)
|
|
fStopTime = -Seconds; // ujemna wartość oznacza oczekiwanie (potem >=0.0)
|
|
}
|
|
|
|
void TController::SetVelocity(double NewVel, double NewVelNext, TStopReason r)
|
|
{ // ustawienie nowej prędkości
|
|
WaitingTime = -WaitingExpireTime; // przypisujemy -WaitingExpireTime, a potem porównujemy z zerem
|
|
if (NewVel == 0.0) { // jeśli ma stanąć
|
|
if (r != stopNone) // a jest powód podany
|
|
eStopReason = r; // to zapamiętać nowy powód
|
|
}
|
|
else {
|
|
eStopReason = stopNone; // podana prędkość, to nie ma powodów do stania
|
|
// to całe poniżej to warunki zatrąbienia przed ruszeniem
|
|
if( is_train() // tylko pociągi trąbią (unimogi tylko na torach, więc trzeba raczej sprawdzać tor)
|
|
&& (OrderCurrentGet() & (Shunt | Loose_shunt | Obey_train | Bank | Connect | Prepare_engine)) != 0 // jeśli jedzie w dowolnym trybie
|
|
&& (iDrivigFlags & moveStartHorn) != 0 // jezeli trąbienie włączone
|
|
&& (iDrivigFlags & (moveStartHornDone | moveConnect)) == 0 // jeśli nie zatrąbione i nie jest to moment podłączania składu
|
|
&& mvOccupied->Vel < 1.0 // jesli stoi (na razie, bo chyba powinien też, gdy hamuje przed semaforem)
|
|
&& ( NewVel >= 1.0 || NewVel < 0.0 ) ) { // o ile prędkość jest znacząca zatrąb po odhamowaniu
|
|
iDrivigFlags |= moveStartHornNow;
|
|
}
|
|
}
|
|
VelSignal = NewVel; // prędkość zezwolona na aktualnym odcinku
|
|
VelNext = NewVelNext; // prędkość przy następnym obiekcie
|
|
}
|
|
|
|
double TController::BrakeAccFactor() const
|
|
{
|
|
double Factor = 1.0;
|
|
|
|
if( fAccThreshold != 0.0
|
|
&& AccDesired < 0.0
|
|
&& ( ActualProximityDist > fMinProximityDist
|
|
|| mvOccupied->Vel > VelDesired + fVelPlus ) ) {
|
|
Factor += fBrakeReaction * (/*mvOccupied->BrakeCtrlPosR*/ BrakeCtrlPosition < 0.5 ? 1.5 : 1) * mvOccupied->Vel / ( std::max( 0.0, ActualProximityDist ) + 1 ) * ( ( AccDesired - AbsAccS ) / fAccThreshold );
|
|
}
|
|
/*
|
|
if (mvOccupied->TrainType == dt_DMU && mvOccupied->Vel > 40 && VelNext<40)
|
|
Factor *= 1 + 0.25 * ( (1600 - VelNext * VelNext) / (mvOccupied->Vel * mvOccupied->Vel) );
|
|
*/
|
|
return Factor;
|
|
}
|
|
|
|
void TController::SetDriverPsyche() {
|
|
|
|
if (Psyche == Aggressive && OrderCurrentGet() == Obey_train) {
|
|
ReactionTime = HardReactionTime; // w zaleznosci od charakteru maszynisty
|
|
if (is_car()) {
|
|
WaitingExpireTime = 1; // tyle ma czekać samochód, zanim się ruszy
|
|
AccPreferred = 3.0; //[m/ss] agresywny
|
|
}
|
|
else {
|
|
WaitingExpireTime = 61; // tyle ma czekać, zanim się ruszy
|
|
AccPreferred = HardAcceleration; // agresywny
|
|
}
|
|
}
|
|
else {
|
|
ReactionTime = EasyReactionTime; // spokojny
|
|
if (is_car()) {
|
|
WaitingExpireTime = 3; // tyle ma czekać samochód, zanim się ruszy
|
|
AccPreferred = 2.0; //[m/ss]
|
|
}
|
|
else {
|
|
WaitingExpireTime = 65; // tyle ma czekać, zanim się ruszy
|
|
AccPreferred = EasyAcceleration;
|
|
}
|
|
}
|
|
}
|
|
|
|
// closes the line breaker, or starts the engine, the relays reset first
|
|
void TController::close_line_breaker()
|
|
{
|
|
cue_action( driver_hint::mastercontrollersetzerospeed );
|
|
// consist-wide ground relay reset
|
|
cue_action( driver_hint::maincircuitgroundreset );
|
|
cue_action( driver_hint::tractionnmotoroverloadreset );
|
|
if( mvOccupied->EngineType == TEngineType::DieselEngine ) {
|
|
// specjalnie dla SN61 żeby nie zgasł
|
|
cue_action( driver_hint::mastercontrollersetidle );
|
|
}
|
|
cue_action( driver_hint::linebreakerclose );
|
|
}
|
|
|
|
bool TController::PrepareEngine()
|
|
{ // odpalanie silnika
|
|
// HACK: don't immediately activate inert vehicle in case the simulation is about to replace us with human driver
|
|
if( mvOccupied->Vel < 1.0 && fActionTime < 0.0 ) { return false; }
|
|
|
|
LastReactionTime = 0.0;
|
|
ReactionTime = mvOccupied->Vel < 5 ? PrepareTime : EasyReactionTime; // react faster with rolling start
|
|
|
|
cue_action( driver_hint::batteryon );
|
|
cue_action( driver_hint::cabactivation);
|
|
cue_action( driver_hint::radiofuseon );
|
|
cue_action( driver_hint::radioon );
|
|
|
|
if( has_diesel_engine() ) {
|
|
cue_action( driver_hint::oilpumpon );
|
|
PrepareHeating();
|
|
if( true == IsHeatingTemperatureOK ) {
|
|
cue_action( driver_hint::fuelpumpon );
|
|
}
|
|
else {
|
|
cue_action( driver_hint::waittemperaturetoolow );
|
|
}
|
|
}
|
|
|
|
if( mvControlling->PantographsRequireMains
|
|
&& IsAnyLineBreakerOpen ) {
|
|
// the pantographs rise only through the closed line breaker, which closes without their voltage
|
|
PrepareDirection();
|
|
close_line_breaker();
|
|
}
|
|
|
|
if( mvPantographUnit->EnginePowerSource.SourceType == TPowerSource::CurrentCollector
|
|
&& mvPantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo > 0 ) {
|
|
// if our pantograph unit isn't a pantograph-devoid fallback
|
|
auto const sufficientpantographpressure { (
|
|
is_emu() ?
|
|
2.5 : // Ra 2013-12: Niebugocław mówi, że w EZT podnoszą się przy 2.5
|
|
3.5 )
|
|
+ 0.1 }; // leeway margin
|
|
|
|
if (mvPantographUnit->PantPress < sufficientpantographpressure) {
|
|
// załączenie małej sprężarki
|
|
if( false == mvPantographUnit->PantAutoValve ) {
|
|
// odłączenie zbiornika głównego, bo z nim nie da rady napompować
|
|
cue_action( driver_hint::pantographairsourcesetauxiliary );
|
|
}
|
|
cue_action( driver_hint::pantographcompressoron ); // załączenie sprężarki pantografów
|
|
if( mvPantographUnit->PantCompFlag ) {
|
|
cue_action( driver_hint::waitpantographpressuretoolow );
|
|
}
|
|
}
|
|
else {
|
|
// jeżeli jest wystarczające ciśnienie w pantografach
|
|
if( false == mvPantographUnit->bPantKurek3
|
|
|| mvPantographUnit->PantPress <= mvPantographUnit->ScndPipePress ) { // kurek przełączony albo główna już pompuje
|
|
cue_action( driver_hint::pantographcompressoroff ); // sprężarkę pantografów można już wyłączyć
|
|
}
|
|
}
|
|
// TODO: make pantograph setup a part of control_pantographs() and call it here instead
|
|
if( fOverhead2 == -1.0 && iOverheadDown == 0 ) {
|
|
cue_action( driver_hint::pantographsvalveon );
|
|
cue_action( driver_hint::frontpantographvalveon, iDirection >= 0 ? 5 : 0 );
|
|
cue_action( driver_hint::rearpantographvalveon, iDirection >= 0 ? 0 : 5 );
|
|
}
|
|
}
|
|
|
|
auto const ispoweravailable =
|
|
mvControlling->EnginePowerSource.SourceType != TPowerSource::CurrentCollector
|
|
|| std::max(mvControlling->GetTrainsetHighVoltage(), mvControlling->PantographVoltage) > mvControlling->EnginePowerSource.CollectorParameters.MinV;
|
|
|
|
bool isready = false;
|
|
|
|
if( IsHeatingTemperatureOK
|
|
&& ispoweravailable ) {
|
|
// najpierw ustalamy kierunek, jeśli nie został ustalony
|
|
PrepareDirection();
|
|
|
|
if( IsAnyConverterOverloadRelayOpen ) {
|
|
// wywalił bezpiecznik nadmiarowy przetwornicy
|
|
cue_action( driver_hint::compressoroff ); // TODO: discern whether compressor needs converter to operate
|
|
cue_action( driver_hint::converteroff );
|
|
cue_action( driver_hint::primaryconverteroverloadreset ); // reset nadmiarowego
|
|
}
|
|
if( IsAnyLineBreakerOpen ) {
|
|
// activate main circuit or engine
|
|
close_line_breaker();
|
|
}
|
|
else {
|
|
// main circuit or engine is on, set up vehicle devices and controls
|
|
if( false == IsAnyConverterOverloadRelayOpen ) {
|
|
if( IsAnyConverterPresent ) {
|
|
cue_action( driver_hint::converteron );
|
|
}
|
|
// w EN57 sprężarka w ra jest zasilana z silnikowego
|
|
// TODO: change condition to presence of required voltage type
|
|
if( IsAnyCompressorPresent && IsAnyConverterEnabled ) {
|
|
cue_action( driver_hint::compressoron );
|
|
}
|
|
if( mvControlling->ScndPipePress < 4.5 && mvControlling->VeselVolume > 0.0 ) {
|
|
cue_action( driver_hint::waitpressuretoolow );
|
|
}
|
|
// enable motor blowers
|
|
if( mvOccupied->MotorBlowers[ end::front ].speed != 0 ) {
|
|
cue_action( driver_hint::frontmotorblowerson );
|
|
}
|
|
if( mvOccupied->MotorBlowers[ end::rear ].speed != 0 ) {
|
|
cue_action( driver_hint::rearmotorblowerson );
|
|
}
|
|
}
|
|
// sync virtual brake state with the 'real' one
|
|
if( mvOccupied->BrakeHandle != TBrakeHandle::NoHandle ) {
|
|
std::unordered_map<int, int> const brakepositions{
|
|
{ static_cast<int>( mvOccupied->Handle->GetPos( bh_RP ) ), gbh_RP },
|
|
{ static_cast<int>( mvOccupied->Handle->GetPos( bh_NP ) ), gbh_NP },
|
|
{ static_cast<int>( mvOccupied->Handle->GetPos( bh_FS ) ), gbh_FS } };
|
|
auto const lookup{ brakepositions.find( static_cast<int>( mvOccupied->fBrakeCtrlPos ) ) };
|
|
if( lookup != brakepositions.end() ) {
|
|
BrakeLevelSet( lookup->second ); // GBH
|
|
}
|
|
}
|
|
// set up train brake
|
|
if( mvOccupied->fBrakeCtrlPos != mvOccupied->Handle->GetPos( bh_RP ) ) {
|
|
if ( !mvOccupied->Handle->Time
|
|
|| mvOccupied->Handle->GetCP() < mvOccupied->HighPipePress - 0.05 );
|
|
cue_action( driver_hint::trainbrakerelease );
|
|
}
|
|
// sync spring brake state across consist
|
|
cue_action(
|
|
mvOccupied->SpringBrake.Activate ?
|
|
driver_hint::springbrakeon :
|
|
driver_hint::springbrakeoff );
|
|
}
|
|
isready = false == IsAnyConverterOverloadRelayOpen
|
|
&& mvOccupied->DirActive != 0
|
|
&& false == IsAnyLineBreakerOpen
|
|
&& ( false == IsAnyConverterPresent || true == IsAnyConverterEnabled )
|
|
&& ( false == IsAnyCompressorPresent || true == IsAnyCompressorEnabled )
|
|
&& ( mvControlling->ScndPipePress > 4.5 || mvControlling->VeselVolume == 0.0 );
|
|
}
|
|
|
|
if( true == isready ) {
|
|
// jeśli dotychczas spał teraz nie ma powodu do stania
|
|
eAction = TAction::actUnknown;
|
|
if( eStopReason == stopSleep ) {
|
|
eStopReason = stopNone;
|
|
}
|
|
// może skanować sygnały i reagować na komendy
|
|
iDrivigFlags |= moveActive;
|
|
}
|
|
|
|
iEngineActive = isready;
|
|
|
|
return iEngineActive;
|
|
}
|
|
|
|
// wyłączanie silnika (test wyłączenia, a część wykonawcza tylko jeśli steruje komputer)
|
|
bool TController::ReleaseEngine() {
|
|
/*
|
|
if( mvOccupied->Vel > 0.01 ) {
|
|
VelDesired = 0.0;
|
|
AccDesired = std::min( AccDesired, -1.25 ); // hamuj solidnie
|
|
if( true == AIControllFlag ) {
|
|
// TBD, TODO: make a dedicated braking procedure out of it for potential reuse
|
|
ZeroSpeed();
|
|
IncBrake();
|
|
ReactionTime = 0.1;
|
|
}
|
|
// don't bother with the rest until we're standing still
|
|
return false;
|
|
}
|
|
*/
|
|
// don't bother with the rest until we're standing still
|
|
if( mvOccupied->Vel > EU07_AI_NOMOVEMENT ) { return false; }
|
|
|
|
LastReactionTime = 0.0;
|
|
ReactionTime = PrepareTime;
|
|
|
|
cue_action( driver_hint::releaseroff );
|
|
// release train brake if on flats...
|
|
if( std::abs( fAccGravity ) < 0.01 ) {
|
|
apply_independent_brake_only();
|
|
}
|
|
// ... but on slopes engage train brake
|
|
else {
|
|
// AccDesired = std::min( AccDesired, -0.9 );
|
|
cue_action( driver_hint::trainbrakeapply );
|
|
}
|
|
|
|
cue_action( driver_hint::mastercontrollersetreverserunlock );
|
|
cue_action( driver_hint::directionnone );
|
|
// zamykanie drzwi
|
|
cue_action( driver_hint::doorrightclose );
|
|
cue_action( driver_hint::doorleftclose );
|
|
// heating
|
|
cue_action( driver_hint::consistheatingoff );
|
|
// devices
|
|
cue_action( driver_hint::compressoroff );
|
|
cue_action( driver_hint::converteroff );
|
|
// line breaker/engine
|
|
cue_action( driver_hint::linebreakeropen );
|
|
// pantographs
|
|
cue_action( driver_hint::frontpantographvalveoff );
|
|
cue_action( driver_hint::rearpantographvalveoff );
|
|
|
|
if( false == mvControlling->Mains ) {
|
|
// finish vehicle shutdown
|
|
if( has_diesel_engine() ) {
|
|
// heating/cooling subsystem
|
|
cue_action( driver_hint::waterheateroff );
|
|
// optionally turn off the water pump as well
|
|
if( mvControlling->WaterPump.start_type != start_t::battery ) {
|
|
cue_action( driver_hint::waterpumpoff );
|
|
}
|
|
// fuel and oil subsystems
|
|
cue_action( driver_hint::fuelpumpoff );
|
|
cue_action( driver_hint::oilpumpoff );
|
|
}
|
|
// gasimy światła
|
|
cue_action( driver_hint::lightsoff );
|
|
// activate parking brake
|
|
// TBD: do it earlier?
|
|
cue_action( driver_hint::springbrakeon );
|
|
if( mvOccupied->LocalBrake == TLocalBrake::ManualBrake
|
|
|| mvOccupied->MBrake == true ) {
|
|
cue_action( driver_hint::manualbrakon );
|
|
}
|
|
// switch off remaining power
|
|
cue_action( driver_hint::radiooff );
|
|
cue_action( driver_hint::batteryoff );
|
|
}
|
|
|
|
auto const OK {
|
|
mvOccupied->DirActive == 0
|
|
// && ( false == IsAnyCompressorEnabled )
|
|
// && ( false == IsAnyConverterEnabled )
|
|
&& false == mvControlling->Mains
|
|
&& false == mvOccupied->Power24vIsAvailable };
|
|
|
|
if (OK) {
|
|
// jeśli się zatrzymał
|
|
iEngineActive = false;
|
|
eStopReason = stopSleep; // stoimy z powodu wyłączenia
|
|
eAction = TAction::actSleep; //śpi (wygaszony)
|
|
|
|
OrderNext(Wait_for_orders); //żeby nie próbował coś robić dalej
|
|
iDrivigFlags &= ~moveActive; // ma nie skanować sygnałów i nie reagować na komendy
|
|
TableClear(); // zapominamy ograniczenia
|
|
VelSignalLast = -1.0;
|
|
}
|
|
return OK;
|
|
}
|
|
|
|
// defined further down, with the braking demand it is used for
|
|
static double brake_response_horizon( TMoverParameters const *Vehicle, TBrakeSystem const Brakesystem, double const Acceleration, double const Brakea0 );
|
|
|
|
// one step more of the train brake, sized from the consist brake table against the deceleration asked for
|
|
bool
|
|
TController::increase_train_brake() {
|
|
|
|
// dodane dla towarowego
|
|
float pos_corr = 0;
|
|
|
|
TDynamicObject *d;
|
|
d = pVehicles[0]; // pojazd na czele składu
|
|
while (d)
|
|
{ // przeliczanie dodatkowego potrzebnego spadku ciśnienia
|
|
if( ( d->MoverParameters->Hamulec->GetBrakeStatus() & b_dmg ) == 0 ) {
|
|
pos_corr -= ( std::min( 5.0, d->MoverParameters->Hamulec->GetCRP() ) - 5.0 ) * d->MoverParameters->TotalMass;
|
|
}
|
|
d = d->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła)
|
|
}
|
|
pos_corr = pos_corr / fMass * 2.5;
|
|
|
|
if (mvOccupied->BrakeHandle == TBrakeHandle::FV4a)
|
|
{
|
|
pos_corr += mvOccupied->Handle->GetCP()*0.2;
|
|
|
|
}
|
|
if( double const deltaAcc = -AccDesired*BrakeAccFactor() - (fBrake_a0[0] + 4.0 * (/*GBH mvOccupied->BrakeCtrlPosR*/BrakeCtrlPosition - 1 - pos_corr)*fBrake_a1[0]);
|
|
deltaAcc > brake_increase_margin() )
|
|
{
|
|
if( /*GBH mvOccupied->BrakeCtrlPosR*/BrakeCtrlPosition < 0.1 ) {
|
|
auto const OK { /*mvOccupied->*/BrakeLevelAdd( BrakingInitialLevel ) }; //GBH
|
|
// HACK: stronger braking to overcome SA134 engine behaviour
|
|
if( is_dmu()
|
|
&& VelNext == 0.0
|
|
&& fBrakeDist < 200.0 ) {
|
|
BrakeLevelAdd(
|
|
fBrakeDist / ActualProximityDist < 0.8 ?
|
|
0.5 :
|
|
1.0 );
|
|
}
|
|
return OK;
|
|
}
|
|
auto const OK { /*mvOccupied->*/BrakeLevelAdd( BrakingLevelIncrease ) }; //GBH
|
|
// brake harder if the acceleration is much higher than desired
|
|
/*if( ( deltaAcc > 2 * fBrake_a1[ 0 ] )
|
|
&& ( mvOccupied->BrakeCtrlPosR + BrakingLevelIncrease <= 5.0 ) ) {
|
|
mvOccupied->BrakeLevelAdd( BrakingLevelIncrease );
|
|
} GBH */
|
|
if( deltaAcc > 2 * fBrake_a1[0]
|
|
&& BrakeCtrlPosition + BrakingLevelIncrease <= 5.0 ) {
|
|
/*mvOccupied->*/BrakeLevelAdd( BrakingLevelIncrease );
|
|
}
|
|
return OK;
|
|
}
|
|
if( BrakeCtrlPosition > 0.0
|
|
&& AccDesired < 0.0 // only while braking is asked for, not when called for a train slipping back while starting
|
|
&& ( fBrakeHeldTime > (
|
|
mvOccupied->BrakeDelayFlag > bdelay_G ?
|
|
mvOccupied->BrakeDelay[ 1 ] :
|
|
mvOccupied->BrakeDelay[ 3 ] )
|
|
// a train falling further behind needs no full fill time to be seen not to get enough
|
|
|| ( ( fShortfall > 0.02 )
|
|
&& ( fBrakeHeldTime > brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) ) ) {
|
|
// the table says the present position is enough, but the brake has had its full fill
|
|
// time since the handle last moved and the train is still not slowing down as asked:
|
|
// believe the train rather than the table
|
|
return BrakeLevelAdd( BrakingLevelIncrease );
|
|
}
|
|
return false;
|
|
}
|
|
|
|
bool TController::IncBrake()
|
|
{ // zwiększenie hamowania
|
|
auto OK { false };
|
|
auto const bs {
|
|
BrakeSystem == TBrakeSystem::ElectroPneumatic && ForcePNBrake ?
|
|
TBrakeSystem::Pneumatic :
|
|
BrakeSystem };
|
|
switch( bs ) {
|
|
case TBrakeSystem::Individual: {
|
|
if( mvOccupied->LocalBrake == TLocalBrake::ManualBrake ) {
|
|
OK = mvOccupied->IncManualBrakeLevel( 1 + static_cast<int>( std::floor( 0.5 + std::fabs( AccDesired ) ) ) );
|
|
}
|
|
else {
|
|
OK = mvOccupied->IncLocalBrakeLevel( std::floor( 1.5 + std::abs( AccDesired ) ) );
|
|
}
|
|
break;
|
|
}
|
|
case TBrakeSystem::Pneumatic: {
|
|
if (bs != mvOccupied->BrakeSystem)
|
|
{
|
|
while (mvOccupied->BrakeOpModeFlag > bom_PN)
|
|
{
|
|
mvOccupied->BrakeOpModeFlag >>= 1;
|
|
}
|
|
}
|
|
// NOTE: can't perform just test whether connected vehicle == nullptr, due to virtual couplers formed with nearby vehicles
|
|
auto standalone { true };
|
|
if( mvOccupied->TrainType == dt_ET41
|
|
|| mvOccupied->TrainType == dt_ET42 ) {
|
|
// NOTE: we're doing simplified checks full of presuptions here.
|
|
// they'll break if someone does strange thing like turning around the second unit
|
|
if( mvOccupied->Couplers[end::rear].CouplingFlag & coupling::permanent
|
|
&& mvOccupied->Couplers[end::rear].Connected->Couplers[end::rear].Connected != nullptr ) {
|
|
standalone = false;
|
|
}
|
|
if( mvOccupied->Couplers[end::front].CouplingFlag & coupling::permanent
|
|
&& mvOccupied->Couplers[end::front].Connected->Couplers[end::front].Connected != nullptr ) {
|
|
standalone = false;
|
|
}
|
|
}
|
|
else if( is_dmu() ) {
|
|
// enforce use of train brake for DMUs
|
|
standalone = false;
|
|
}
|
|
else if( (OrderCurrentGet() & Loose_shunt) != 0
|
|
&& mvOccupied->Vel - VelDesired < fVelPlus + fVelMinus ) {
|
|
// try to reduce train brake use in loose shunting mode
|
|
standalone = true;
|
|
}
|
|
else {
|
|
/*
|
|
standalone =
|
|
( ( mvOccupied->Couplers[ 0 ].CouplingFlag == 0 )
|
|
&& ( mvOccupied->Couplers[ 1 ].CouplingFlag == 0 ) );
|
|
*/
|
|
if( pVehicles[ end::front ] != pVehicles[ end::rear ] ) {
|
|
// more detailed version, will use manual braking also for coupled sets of controlled vehicles
|
|
auto *vehicle = pVehicles[ end::front ]; // start from first
|
|
while( true == standalone
|
|
&& vehicle != nullptr ) {
|
|
// NOTE: we could simplify this by doing only check of the rear coupler, but this can be quite tricky in itself
|
|
// TODO: add easier ways to access front/rear coupler taking into account vehicle's direction
|
|
standalone =
|
|
(vehicle->MoverParameters->Couplers[end::front].Connected == nullptr ||
|
|
(vehicle->MoverParameters->Couplers[end::front].CouplingFlag & coupling::control && vehicle->MoverParameters->Couplers[end::front].Connected->Power > 1)) &&
|
|
(vehicle->MoverParameters->Couplers[end::rear].Connected == nullptr ||
|
|
(vehicle->MoverParameters->Couplers[end::rear].CouplingFlag & coupling::control && vehicle->MoverParameters->Couplers[end::rear].Connected->Power > 1));
|
|
vehicle = vehicle->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła)
|
|
}
|
|
}
|
|
}
|
|
|
|
//standalone = standalone && ( mvControlling->EIMCtrlType == 0 );
|
|
|
|
if( true == standalone && false == ForcePNBrake ) {
|
|
if( mvControlling->EIMCtrlType > 0 ) {
|
|
OK = IncBrakeEIM();
|
|
}
|
|
else {
|
|
OK = mvOccupied->IncLocalBrakeLevel(
|
|
1 + static_cast<int>( std::floor( 0.5 + std::fabs( AccDesired ) ) ) ); // hamowanie lokalnym bo luzem jedzie
|
|
}
|
|
}
|
|
else {
|
|
if( /*GBH mvOccupied->BrakeCtrlPos*/ BrakeCtrlPosition + 1 == gbh_MAX ) {
|
|
if (AccDesired < -1.5) // hamowanie nagle
|
|
OK = /*mvOccupied->*/BrakeLevelAdd(1.0); //GBH
|
|
else
|
|
OK = false;
|
|
}
|
|
else {
|
|
OK = increase_train_brake();
|
|
}
|
|
}
|
|
if( /*GBH mvOccupied->BrakeCtrlPos*/
|
|
/*GBH mvOccupied->BrakeCtrlPos*/ BrakeCtrlPosition > 0 && mvOccupied->Hamulec->Releaser() ) {
|
|
mvOccupied->BrakeReleaser(0);
|
|
}
|
|
break;
|
|
}
|
|
case TBrakeSystem::ElectroPneumatic: {
|
|
while( mvOccupied->BrakeOpModeFlag << 1 <= mvOccupied->BrakeOpModes ) {
|
|
mvOccupied->BrakeOpModeFlag <<= 1;
|
|
}
|
|
if( mvOccupied->EngineType == TEngineType::ElectricInductionMotor ) {
|
|
if (mvOccupied->BrakeHandle == TBrakeHandle::MHZ_EN57) {
|
|
if (mvOccupied->BrakeCtrlPos < mvOccupied->Handle->GetPos(bh_FB))
|
|
OK = mvOccupied->BrakeLevelAdd(1.0);
|
|
}
|
|
else {
|
|
OK = IncBrakeEIM();
|
|
}
|
|
}
|
|
else if( mvOccupied->Handle->TimeEP == false ) {
|
|
auto const initialbrakeposition { mvOccupied->fBrakeCtrlPos };
|
|
auto const AccMax { std::min( fBrake_a0[ 0 ] + 12 * fBrake_a1[ 0 ], mvOccupied->MED_amax ) };
|
|
mvOccupied->BrakeLevelSet(
|
|
std::lerp(
|
|
mvOccupied->Handle->GetPos( bh_EPR ),
|
|
mvOccupied->Handle->GetPos( bh_EPB ),
|
|
std::clamp( -AccDesired / AccMax * mvOccupied->AIHintLocalBrakeAccFactor, 0.0, 1.0 ) ) );
|
|
OK = mvOccupied->fBrakeCtrlPos != initialbrakeposition;
|
|
}
|
|
else if( mvOccupied->fBrakeCtrlPos != mvOccupied->Handle->GetPos( bh_EPB ) ) {
|
|
mvOccupied->BrakeLevelSet( mvOccupied->Handle->GetPos( bh_EPB ) );
|
|
if( mvOccupied->Handle->GetPos( bh_EPR ) - mvOccupied->Handle->GetPos( bh_EPN ) < 0.1 )
|
|
mvOccupied->SwitchEPBrake( 1 ); // to nie chce działać
|
|
OK = true;
|
|
}
|
|
else if( ( mvOccupied->Handle->GetPos( bh_EPR ) - mvOccupied->Handle->GetPos( bh_EPN ) < 0.1 )
|
|
&& ( mvOccupied->EpForce <= 0.0 )
|
|
&& ( mvOccupied->EPBrakeControlPowered() ) ) {
|
|
// the handle already in the EP brake position, but the EP brake dropped out with the control's
|
|
// supply (e.g. the EP fuse off in the running brake test): switch it on again
|
|
mvOccupied->SwitchEPBrake( 1 );
|
|
OK = ( mvOccupied->EpForce > 0.0 );
|
|
}
|
|
else
|
|
OK = false;
|
|
break;
|
|
}
|
|
default: { break; }
|
|
}
|
|
return OK;
|
|
}
|
|
|
|
bool TController::IncBrakeEIM()
|
|
{ // zwiększenie hamowania
|
|
bool OK = false;
|
|
switch (mvOccupied->EIMCtrlType)
|
|
{
|
|
case 0: {
|
|
if( mvOccupied->MED_amax != 9.81 ) {
|
|
auto const maxpos{mvOccupied->EIMCtrlEmergency ? 0.9 : 1.0 };
|
|
auto const brakelimit{ -2.2 * AccDesired / fMedAmax - 1.0}; //additional limit when hinted is too low
|
|
auto const brakehinted{ -1.0 * mvOccupied->AIHintLocalBrakeAccFactor * AccDesired / fMedAmax }; //preffered by AI
|
|
auto const brakeposition{ maxpos * std::clamp(std::max(brakelimit, brakehinted), 0.0, 1.0)};
|
|
OK = brakeposition != mvOccupied->LocalBrakePosA;
|
|
mvOccupied->LocalBrakePosA = brakeposition;
|
|
}
|
|
else {
|
|
OK = mvOccupied->IncLocalBrakeLevel( 1 );
|
|
}
|
|
break;
|
|
}
|
|
case 1: {
|
|
OK = mvOccupied->MainCtrlPos > 0;
|
|
if( OK )
|
|
mvOccupied->MainCtrlPos = 0;
|
|
break;
|
|
}
|
|
case 2: {
|
|
// the braking position, above the emergency brake one where the controller has it
|
|
auto const brakepos{1 + mvOccupied->EIMCtrlEmergencyPositions()};
|
|
OK = mvOccupied->MainCtrlPos > brakepos;
|
|
if( OK )
|
|
mvOccupied->MainCtrlPos = brakepos;
|
|
break;
|
|
}
|
|
case 3: {
|
|
if( mvOccupied->UniCtrlIntegratedLocalBrakeCtrl ) {
|
|
OK = mvOccupied->MainCtrlPos > 0;
|
|
if( OK )
|
|
mvOccupied->MainCtrlPos = 0;
|
|
}
|
|
else {
|
|
OK = mvOccupied->IncLocalBrakeLevel( 1 );
|
|
}
|
|
break;
|
|
}
|
|
default: {
|
|
break;
|
|
}
|
|
}
|
|
return OK;
|
|
}
|
|
|
|
// zmniejszenie siły hamowania
|
|
bool TController::DecBrake() {
|
|
|
|
auto OK { false };
|
|
auto const bs {
|
|
BrakeSystem == TBrakeSystem::ElectroPneumatic && ForcePNBrake ?
|
|
TBrakeSystem::Pneumatic :
|
|
BrakeSystem };
|
|
switch( bs ) {
|
|
case TBrakeSystem::Individual: {
|
|
auto const positionchange { 1 + std::floor( 0.5 + std::abs( AccDesired ) ) };
|
|
OK = mvOccupied->LocalBrake == TLocalBrake::ManualBrake ? mvOccupied->DecManualBrakeLevel(positionchange) : mvOccupied->DecLocalBrakeLevel(positionchange);
|
|
break;
|
|
}
|
|
case TBrakeSystem::Pneumatic: {
|
|
auto deltaAcc { -1.0 };
|
|
if( fBrake_a0[0] != 0.0
|
|
|| fBrake_a1[0] != 0.0 ) {
|
|
auto const pos_diff { ( is_dmu() ? 0.25 : 1.0 ) };
|
|
// a distributor applied at all gives at least its minimum stage, about what the first position does, so
|
|
// a position short of the first one brakes no weaker than that
|
|
deltaAcc = -AccDesired * BrakeAccFactor() - ( fBrake_a0[ 0 ] + 4 * std::max( 0.0, BrakeCtrlPosition - pos_diff ) * fBrake_a1[ 0 ] );
|
|
}
|
|
if( bUphillStart ) {
|
|
// starting uphill the train brake holds the train until the power does
|
|
break;
|
|
}
|
|
if( ( BrakeCtrlPosition > 0.0 )
|
|
&& ( uphill_stop_hold() ) ) {
|
|
// any release now raises the pipe, and a long train releases more than the handle is moved back, too late
|
|
// to apply again before the train stands: keep the brake as it is, and the locomotive brake with it
|
|
break;
|
|
}
|
|
if (deltaAcc < 0 && /*GBH mvOccupied->BrakeCtrlPosR*/ BrakeCtrlPosition > 0) {
|
|
OK = /*mvOccupied->*/ BrakeLevelAdd(-0.25);
|
|
// if ((deltaAcc < 5 * fBrake_a1[0]) && (mvOccupied->BrakeCtrlPosR >= 1.2))
|
|
// mvOccupied->BrakeLevelAdd(-1.0);
|
|
/* if (mvOccupied->BrakeCtrlPosR < 0.74) GBH */
|
|
if (BrakeCtrlPosition < 0.74)
|
|
/*mvOccupied->*/ BrakeLevelSet(gbh_RP);
|
|
}
|
|
if( !OK ) {
|
|
OK = mvOccupied->DecLocalBrakeLevel(2);
|
|
}
|
|
if( !OK ) {
|
|
OK = DecBrakeEIM();
|
|
}
|
|
/*
|
|
// NOTE: disabled, duplicate of AI's behaviour in UpdateSituation()
|
|
if (mvOccupied->PipePress < 3.0)
|
|
Need_BrakeRelease = true;
|
|
*/
|
|
break;
|
|
}
|
|
case TBrakeSystem::ElectroPneumatic: {
|
|
if( mvOccupied->EngineType == TEngineType::ElectricInductionMotor ) {
|
|
if( mvOccupied->BrakeHandle == TBrakeHandle::MHZ_EN57 ) {
|
|
if( mvOccupied->BrakeCtrlPos > mvOccupied->Handle->GetPos( bh_RP ) ) {
|
|
OK = mvOccupied->BrakeLevelAdd( -1.0 );
|
|
}
|
|
}
|
|
else {
|
|
OK = DecBrakeEIM();
|
|
}
|
|
}
|
|
else if( mvOccupied->Handle->TimeEP == false ) {
|
|
auto const initialbrakeposition { mvOccupied->fBrakeCtrlPos };
|
|
auto const AccMax { std::min( fBrake_a0[ 0 ] + 12 * fBrake_a1[ 0 ], mvOccupied->MED_amax ) };
|
|
mvOccupied->BrakeLevelSet(
|
|
std::lerp(
|
|
mvOccupied->Handle->GetPos( bh_EPR ),
|
|
mvOccupied->Handle->GetPos( bh_EPB ),
|
|
std::clamp( -AccDesired / AccMax * mvOccupied->AIHintLocalBrakeAccFactor, 0.0, 1.0 ) ) );
|
|
OK = mvOccupied->fBrakeCtrlPos != initialbrakeposition;
|
|
}
|
|
else {
|
|
OK = false;
|
|
if (mvOccupied->fBrakeCtrlPos != mvOccupied->Handle->GetPos(bh_EPR)) {
|
|
mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_EPR));
|
|
OK = true;
|
|
}
|
|
if (mvOccupied->Handle->GetPos(bh_EPR) - mvOccupied->Handle->GetPos(bh_EPN) < 0.1) {
|
|
OK = OK || mvOccupied->SwitchEPBrake(1);
|
|
}
|
|
}
|
|
if( !OK ) {
|
|
OK = mvOccupied->DecLocalBrakeLevel( 2 );
|
|
}
|
|
break;
|
|
}
|
|
default: {
|
|
break;
|
|
}
|
|
}
|
|
return OK;
|
|
}
|
|
|
|
void TController::LapBrake() {
|
|
|
|
if( mvOccupied->Handle->TimeEP ) {
|
|
if( mvOccupied->Handle->GetPos( bh_EPR ) - mvOccupied->Handle->GetPos( bh_EPN ) < 0.1 ) {
|
|
mvOccupied->SwitchEPBrake( 0 );
|
|
}
|
|
else {
|
|
mvOccupied->BrakeLevelSet( mvOccupied->Handle->GetPos( bh_EPN ) );
|
|
}
|
|
}
|
|
}
|
|
|
|
void TController::ZeroLocalBrake() {
|
|
|
|
if( mvOccupied->UniCtrlIntegratedLocalBrakeCtrl ) {
|
|
while( DecBrakeEIM() ) {
|
|
;
|
|
}
|
|
}
|
|
else {
|
|
mvOccupied->DecLocalBrakeLevel( LocalBrakePosNo );
|
|
}
|
|
}
|
|
|
|
bool TController::DecBrakeEIM()
|
|
{ // zmniejszenie siły hamowania
|
|
bool OK = false;
|
|
switch (mvOccupied->EIMCtrlType)
|
|
{
|
|
case 0: {
|
|
if( mvOccupied->MED_amax != 9.81 ) {
|
|
auto const desiredacceleration { ( mvOccupied->Vel > EU07_AI_NOMOVEMENT ? AccDesired : std::max( 0.0, AccDesired ) ) };
|
|
auto const brakeposition { std::clamp( -1.0 * mvOccupied->AIHintLocalBrakeAccFactor * desiredacceleration / mvOccupied->MED_amax, 0.0, 1.0 ) };
|
|
OK = brakeposition != mvOccupied->LocalBrakePosA;
|
|
mvOccupied->LocalBrakePosA = brakeposition;
|
|
}
|
|
else {
|
|
OK = mvOccupied->DecLocalBrakeLevel( 1 );
|
|
}
|
|
break;
|
|
}
|
|
case 1: {
|
|
OK = mvOccupied->MainCtrlPos < 2;
|
|
if( OK )
|
|
mvOccupied->MainCtrlPos = 2;
|
|
break;
|
|
}
|
|
case 2: {
|
|
auto const neutralpos{mvOccupied->MainCtrlNoPowerPos()};
|
|
OK = mvOccupied->MainCtrlPos < neutralpos;
|
|
if( OK )
|
|
mvOccupied->MainCtrlPos = neutralpos;
|
|
break;
|
|
}
|
|
case 3: {
|
|
OK = mvOccupied->MainCtrlPos < mvOccupied->MainCtrlMaxDirChangePos;
|
|
if( OK )
|
|
mvOccupied->MainCtrlPos = mvOccupied->MainCtrlMaxDirChangePos;
|
|
break;
|
|
}
|
|
}
|
|
return OK;
|
|
}
|
|
|
|
bool TController::IncSpeed()
|
|
{ // zwiększenie prędkości; zwraca false, jeśli dalej się nie da zwiększać
|
|
auto OK { false };
|
|
switch (mvOccupied->EngineType)
|
|
{
|
|
case TEngineType::None: // McZapkie-041003: wagon sterowniczy
|
|
if (mvControlling->MainCtrlPosNo > 0) // jeśli ma czym kręcić
|
|
iDrivigFlags |= moveIncSpeed; // ustawienie flagi jazdy
|
|
return false;
|
|
case TEngineType::ElectricSeriesMotor:
|
|
if (mvPantographUnit->EnginePowerSource.SourceType == TPowerSource::CurrentCollector) // jeśli pantografujący
|
|
{
|
|
if (fOverhead2 >= 0.0) // a jazda bezprądowa ustawiana eventami (albo opuszczenie)
|
|
return false; // to nici z ruszania
|
|
if (iOverheadZero) // jazda bezprądowa z poziomu toru ustawia bity
|
|
return false; // to nici z ruszania
|
|
}
|
|
// TODO: move all fVoltage assignments to a single, more generic place
|
|
if( mvControlling->EnginePowerSource.SourceType == TPowerSource::Accumulator ) {
|
|
fVoltage = mvControlling->BatteryVoltage;
|
|
}
|
|
if (!IsAnyMotorOverloadRelayOpen && !mvControlling->ControlPressureSwitch && (mvControlling->IsMainCtrlNoPowerPos() || mvControlling->StLinFlag) && (Ready || iDrivigFlags & movePress)) {
|
|
// youBy polecił dodać 2012-09-08 v367
|
|
// na pozycji 0 przejdzie, a na pozostałych będzie czekać, aż się załączą liniowe (zgaśnie DelayCtrlFlag)
|
|
auto const usehighoverloadrelaythreshold{mvControlling->TrainType != dt_ET42 // ET42 uses these variables for different purpose. TODO: fix this
|
|
&& mvControlling->ImaxHi > mvControlling->ImaxLo && mvOccupied->Vel < (mvControlling->IsMotorOverloadRelayHighThresholdOn() ? 30.0 : 20.0) &&
|
|
iVehicles - ControlledEnginesCount > 0
|
|
// && ( std::fabs( mvControlling->Im ) > 0.85 * mvControlling->Imax )
|
|
&& mvControlling->Imax * mvControlling->EngineVoltage * ControlledEnginesCount /
|
|
(fMass * (fAccGravity == 0.025 ? -0.01 : // prevent div/0
|
|
fAccGravity - 0.025)) <
|
|
-2.8};
|
|
// use series mode:
|
|
// if high threshold is set for motor overload relay,
|
|
// if the power station is heavily burdened,
|
|
// if it generates enough traction force
|
|
// to build up speed to 30/40 km/h for passenger/cargo train (10 km/h less if going uphill)
|
|
auto const sufficienttractionforce{std::abs(mvControlling->Ft) * ControlledEnginesCount > (IsHeavyCargoTrain ? 75 : 50) * 1000.0};
|
|
auto const sufficientacceleration{AbsAccS >= (IsHeavyCargoTrain ? 0.03 : IsCargoTrain ? 0.06 : 0.09)};
|
|
auto const seriesmodefieldshunting{mvControlling->ScndCtrlPos > 0 && mvControlling->RList[mvControlling->MainCtrlPos].Bn == 1};
|
|
auto const parallelmodefieldshunting{mvControlling->ScndCtrlPos > 0 && mvControlling->RList[mvControlling->MainCtrlPos].Bn > 1};
|
|
auto const minvoltage{(mvPantographUnit->EnginePowerSource.SourceType == TPowerSource::CurrentCollector ? mvPantographUnit->EnginePowerSource.CollectorParameters.MinV : 0.0)};
|
|
auto const maxvoltage{(mvPantographUnit->EnginePowerSource.SourceType == TPowerSource::CurrentCollector ? mvPantographUnit->EnginePowerSource.CollectorParameters.MaxV : 0.0)};
|
|
auto const seriesmodevoltage{std::lerp(minvoltage, maxvoltage, IsHeavyCargoTrain ? 0.35 : 0.40)};
|
|
auto const useseriesmode = mvControlling->Imax > mvControlling->ImaxLo || true == usehighoverloadrelaythreshold || fVoltage < seriesmodevoltage ||
|
|
(true == sufficientacceleration && true == sufficienttractionforce &&
|
|
mvOccupied->Vel <= (IsCargoTrain ? 40 : 30) + (seriesmodefieldshunting ? 5 : 0) - (fAccGravity < -0.025 ? 10 : 0));
|
|
// when not in series mode use the first available parallel mode configuration until 50/60 km/h for passenger/cargo train
|
|
// (if there's only one parallel mode configuration it'll be used regardless of current speed)
|
|
auto const usefieldshunting = mvControlling->StLinFlag && mvControlling->RList[mvControlling->MainCtrlPos].R < 0.01 && false == mvControlling->IsScndCtrlLockedByMainCtrl() &&
|
|
(useseriesmode ? mvControlling->RList[mvControlling->MainCtrlPos].Bn == 1 :
|
|
true == sufficientacceleration && true == sufficienttractionforce && mvOccupied->Vel <= (IsCargoTrain ? 60 : 50) + (parallelmodefieldshunting ? 5 : 0) ?
|
|
mvControlling->RList[mvControlling->MainCtrlPos].Bn > 1 :
|
|
mvControlling->MainCtrlPos == mvControlling->MainCtrlPosNo);
|
|
|
|
// if needed enable high threshold for overload relay...
|
|
if (mvControlling->TrainType != dt_ET42)
|
|
{ // ET42 uses these variables for different purpose. TODO: fix this
|
|
if (usehighoverloadrelaythreshold)
|
|
{
|
|
if (mvControlling->Imax < mvControlling->ImaxHi)
|
|
{
|
|
// to enable this setting we'll typically need the main controller in series mode (which is not guaranteed)
|
|
if (mvControlling->RList[mvControlling->MainCtrlPos].Bn > 1)
|
|
{
|
|
if (false == mvControlling->IsScndCtrlNoPowerPos())
|
|
{
|
|
mvControlling->DecScndCtrl(2);
|
|
}
|
|
while (false == mvControlling->IsMainCtrlNoPowerPos() && mvControlling->RList[mvControlling->MainCtrlPos].Bn > 1)
|
|
{
|
|
mvControlling->DecMainCtrl(1); // kręcimy nastawnik jazdy o 1 wstecz
|
|
}
|
|
}
|
|
mvControlling->CurrentSwitch(true); // rozruch wysoki (za to może się ślizgać)
|
|
}
|
|
}
|
|
// ...or disable high threshold for overload relay if no longer needed
|
|
else
|
|
{
|
|
if (mvControlling->IsMotorOverloadRelayHighThresholdOn() && std::fabs(mvControlling->Im) < mvControlling->ImaxLo)
|
|
{
|
|
mvControlling->CurrentSwitch(false); // rozruch wysoki wyłącz
|
|
}
|
|
}
|
|
}
|
|
|
|
double Vs = 99999;
|
|
if (usefieldshunting ? mvControlling->ScndCtrlPos < mvControlling->ScndCtrlPosNo : mvControlling->MainCtrlPos < mvControlling->MainCtrlPosNo)
|
|
{
|
|
Vs = ESMVelocity(!usefieldshunting);
|
|
}
|
|
|
|
if (std::abs(mvControlling->Im) < (fReady < 0.4 ? mvControlling->Imin : mvControlling->IminLo) || mvControlling->Vel > Vs)
|
|
{
|
|
// Ra: wywalał nadmiarowy, bo Im może być ujemne; jak nie odhamowany, to nie przesadzać z prądem
|
|
if (usefieldshunting)
|
|
{
|
|
// to dać bocznik
|
|
// engage the shuntfield only if there's sufficient power margin to draw from
|
|
auto const sufficientpowermargin{fVoltage - seriesmodevoltage > (IsHeavyCargoTrain ? 100.0 : 75.0) * ControlledEnginesCount};
|
|
|
|
OK = sufficientpowermargin ? mvControlling->IncScndCtrl(1) : true;
|
|
}
|
|
else
|
|
{
|
|
// jeśli ustawiony bocznik to bocznik na zero po chamsku
|
|
if (mvControlling->ScndCtrlPos)
|
|
{
|
|
mvControlling->DecScndCtrl(2);
|
|
}
|
|
// kręcimy nastawnik jazdy
|
|
// don't draw too much power;
|
|
// keep from dropping into series mode when entering/using parallel mode, and from shutting down in the series mode
|
|
auto const sufficientpowermargin{fVoltage -
|
|
(mvControlling->RList[std::min(mvControlling->MainCtrlPos + 1, mvControlling->MainCtrlPosNo)].Bn == 1 ? minvoltage : seriesmodevoltage) >
|
|
(IsHeavyCargoTrain ? 100.0 : 75.0) * ControlledEnginesCount};
|
|
|
|
OK = sufficientpowermargin && false == mvControlling->DelayCtrlFlag ? mvControlling->IncMainCtrl(1) : true;
|
|
// czekaj na 1 pozycji, zanim się nie włączą liniowe
|
|
if (true == mvControlling->StLinFlag)
|
|
{
|
|
iDrivigFlags |= moveIncSpeed;
|
|
}
|
|
else
|
|
{
|
|
iDrivigFlags &= ~moveIncSpeed;
|
|
}
|
|
|
|
if (mvControlling->Im == 0 && mvControlling->MainCtrlPowerPos() > 1)
|
|
{
|
|
// brak prądu na dalszych pozycjach
|
|
// nie załączona lokomotywa albo wywalił nadmiarowy
|
|
Need_TryAgain = true;
|
|
}
|
|
}
|
|
}
|
|
else
|
|
{
|
|
OK = false;
|
|
}
|
|
}
|
|
// mvControlling->AutoRelayCheck(); // sprawdzenie logiki sterowania
|
|
break;
|
|
case TEngineType::Dumb:
|
|
if (!IsAnyMotorOverloadRelayOpen && (Ready || iDrivigFlags & movePress))
|
|
//{(BrakePress<=0.01*MaxBrakePress)}
|
|
{
|
|
OK = IncSpeedEIM();
|
|
if (!OK)
|
|
OK = mvControlling->IncMainCtrl(1);
|
|
if (!OK)
|
|
OK = mvControlling->IncScndCtrl(1);
|
|
}
|
|
break;
|
|
case TEngineType::DieselElectric:
|
|
if (!IsAnyMotorOverloadRelayOpen && !mvControlling->ControlPressureSwitch && (mvControlling->IsMainCtrlNoPowerPos() || mvControlling->StLinFlag) && (Ready || iDrivigFlags & movePress)) {
|
|
// youBy polecił dodać 2012-09-08 v367
|
|
// na pozycji 0 przejdzie, a na pozostałych będzie czekać, aż się załączą liniowe (zgaśnie DelayCtrlFlag)
|
|
//{(BrakePress<=0.01*MaxBrakePress)}
|
|
OK = IncSpeedEIM();
|
|
if (!OK)
|
|
OK = mvControlling->IncMainCtrl(1);
|
|
if (!OK)
|
|
OK = mvControlling->IncScndCtrl(1);
|
|
}
|
|
break;
|
|
case TEngineType::ElectricInductionMotor:
|
|
if( !IsAnyMotorOverloadRelayOpen && (Ready || iDrivigFlags & movePress || mvOccupied->ShuntMode) ) {
|
|
//{(BrakePress<=0.01*MaxBrakePress)}
|
|
OK = IncSpeedEIM();
|
|
if (mvControlling->SpeedCtrl && mvControlling->Mains)
|
|
{
|
|
// cruise control
|
|
auto const couplinginprogress{true == TestFlag(iDrivigFlags, moveConnect) && true == TestFlag(OrderCurrentGet(), Connect)};
|
|
auto const SpeedCntrlVel{(ActualProximityDist > std::max(50.0, fMaxProximityDist) || couplinginprogress ? VelDesired : min_speed(VelDesired, VelNext))};
|
|
if (SpeedCntrlVel >= mvControlling->SpeedCtrlUnit.MinVelocity &&
|
|
SpeedCntrlVel - mvControlling->SpeedCtrlUnit.MinVelocity == quantize(SpeedCntrlVel - mvControlling->SpeedCtrlUnit.MinVelocity, mvControlling->SpeedCtrlUnit.VelocityStep))
|
|
{
|
|
SpeedCntrl(SpeedCntrlVel);
|
|
}
|
|
else if (SpeedCntrlVel > 0.1)
|
|
{
|
|
SpeedCntrl(0.0);
|
|
mvControlling->DecScndCtrl(2);
|
|
}
|
|
}
|
|
}
|
|
break;
|
|
case TEngineType::WheelsDriven:
|
|
if (!mvControlling->CabActive)
|
|
mvControlling->CabActivisation();
|
|
if (sin(mvControlling->eAngle) > 0)
|
|
mvControlling->IncMainCtrl(3 + 3 * floor(0.5 + fabs(AccDesired)));
|
|
else
|
|
mvControlling->DecMainCtrl(3 + 3 * floor(0.5 + fabs(AccDesired)));
|
|
break;
|
|
case TEngineType::DieselEngine:
|
|
if (mvControlling->ShuntModeAllow)
|
|
{ // dla 2Ls150 można zmienić tryb pracy, jeśli jest w liniowym i nie daje rady (wymaga zerowania kierunku)
|
|
// mvControlling->ShuntMode=(OrderList[OrderPos]&Shunt)||(fMass>224000.0);
|
|
}
|
|
if (mvControlling->SpeedCtrl && mvControlling->Mains) {// cruise control
|
|
auto const couplinginprogress { true == TestFlag(iDrivigFlags, moveConnect) && true == TestFlag(OrderCurrentGet(), Connect) };
|
|
auto const SpeedCntrlVel { (
|
|
ActualProximityDist > std::max(50.0, fMaxProximityDist) || couplinginprogress ?
|
|
VelDesired :
|
|
min_speed( VelDesired, VelNext ) ) };
|
|
if( SpeedCntrlVel >= mvControlling->SpeedCtrlUnit.MinVelocity
|
|
&& SpeedCntrlVel - mvControlling->SpeedCtrlUnit.MinVelocity == quantize(SpeedCntrlVel - mvControlling->SpeedCtrlUnit.MinVelocity, mvControlling->SpeedCtrlUnit.VelocityStep) ) {
|
|
SpeedCntrl(SpeedCntrlVel);
|
|
}
|
|
else if (SpeedCntrlVel > 0.1) {
|
|
SpeedCntrl(0.0);
|
|
mvControlling->DecScndCtrl( 2 );
|
|
}
|
|
}
|
|
if (mvControlling->EIMCtrlType > 0) {
|
|
if (true == Ready)
|
|
{
|
|
bool max = mvControlling->Vel > mvControlling->dizel_minVelfullengage
|
|
|| (mvControlling->SpeedCtrl && mvControlling->ScndCtrlPos > 0);
|
|
DizelPercentage = max ? 100 : 1;
|
|
}
|
|
break;
|
|
}
|
|
else {
|
|
if( true == Ready ) {
|
|
if( mvControlling->Vel > mvControlling->dizel_minVelfullengage
|
|
&& mvControlling->RList[mvControlling->MainCtrlPos].Mn > 0 ) {
|
|
OK = mvControlling->IncMainCtrl( 1 );
|
|
}
|
|
if( mvControlling->RList[ mvControlling->MainCtrlPos ].Mn == 0 ) {
|
|
OK = mvControlling->IncMainCtrl( 1 );
|
|
}
|
|
}
|
|
}
|
|
// TODO: move this check to a more suitable place, or scrap it
|
|
if( false == mvControlling->Mains ) {
|
|
SpeedCntrl(0.0);
|
|
mvControlling->DecScndCtrl( 2 );
|
|
cue_action( driver_hint::linebreakerclose );
|
|
cue_action( driver_hint::converteron );
|
|
cue_action( driver_hint::compressoron );
|
|
}
|
|
break;
|
|
}
|
|
return OK;
|
|
}
|
|
|
|
void TController::ZeroSpeed( bool const Enforce ) {
|
|
|
|
while( DecSpeed( Enforce ) ) {
|
|
;
|
|
}
|
|
}
|
|
|
|
bool TController::DecSpeed(bool force)
|
|
{ // zmniejszenie prędkości (ale nie hamowanie)
|
|
bool OK = false; // domyślnie false, aby wyszło z pętli while
|
|
switch (mvOccupied->EngineType)
|
|
{
|
|
case TEngineType::None: // McZapkie-041003: wagon sterowniczy
|
|
iDrivigFlags &= ~moveIncSpeed; // usunięcie flagi jazdy
|
|
if (force && mvControlling->MainCtrlPosNo > 0) // przy aktywacji kabiny jest potrzeba natychmiastowego wyzerowania
|
|
// McZapkie-041003: wagon sterowniczy, np. EZT
|
|
mvControlling->DecMainCtrl(std::min(mvControlling->MainCtrlPowerPos(), 2));
|
|
// mvControlling->AutoRelayCheck(); // sprawdzenie logiki sterowania
|
|
return false;
|
|
case TEngineType::ElectricSeriesMotor:
|
|
OK = mvControlling->DecScndCtrl(2); // najpierw bocznik na zero
|
|
if (!OK)
|
|
OK = mvControlling->DecMainCtrl( std::min( mvControlling->MainCtrlPowerPos(), 2 ) );
|
|
// mvControlling->AutoRelayCheck(); // sprawdzenie logiki sterowania
|
|
break;
|
|
case TEngineType::Dumb:
|
|
case TEngineType::DieselElectric:
|
|
OK = mvControlling->DecScndCtrl(2);
|
|
if (!OK)
|
|
OK = mvControlling->DecMainCtrl( std::min( mvControlling->MainCtrlPowerPos(), 2 + mvControlling->MainCtrlPowerPos() / 2 ) );
|
|
break;
|
|
case TEngineType::ElectricInductionMotor:
|
|
OK = DecSpeedEIM();
|
|
break;
|
|
case TEngineType::WheelsDriven:
|
|
if (!mvControlling->CabActive)
|
|
mvControlling->CabActivisation();
|
|
if (sin(mvControlling->eAngle) < 0)
|
|
mvControlling->IncMainCtrl(3 + 3 * floor(0.5 + fabs(AccDesired)));
|
|
else
|
|
mvControlling->DecMainCtrl(3 + 3 * floor(0.5 + fabs(AccDesired)));
|
|
break;
|
|
case TEngineType::DieselEngine:
|
|
if (mvControlling->EIMCtrlType > 0)
|
|
{
|
|
DizelPercentage = 0;
|
|
if (force) {
|
|
SpeedCntrl(0.0); //wylacz od razu tempomat
|
|
mvControlling->DecScndCtrl(2);
|
|
}
|
|
if (VelDesired > 0.1 && mvControlling->SpeedCtrlUnit.MinVelocity > VelDesired) {
|
|
SpeedCntrl(0.0); //wylacz od razu tempomat
|
|
mvControlling->DecScndCtrl(2);
|
|
}
|
|
break;
|
|
}
|
|
|
|
if (mvControlling->Vel > mvControlling->dizel_minVelfullengage)
|
|
{
|
|
if (mvControlling->RList[mvControlling->MainCtrlPos].Mn > 0)
|
|
OK = mvControlling->DecMainCtrl(1);
|
|
}
|
|
else {
|
|
while( mvControlling->RList[mvControlling->MainCtrlPos].Mn > 0
|
|
&& mvControlling->MainCtrlPowerPos() > 1 ) {
|
|
OK = mvControlling->DecMainCtrl( 1 );
|
|
}
|
|
}
|
|
if (force) { // przy aktywacji kabiny jest potrzeba natychmiastowego wyzerowania
|
|
OK = mvControlling->DecMainCtrl(mvControlling->MainCtrlPowerPos() > 2 ? 2 : 1);
|
|
SpeedCntrl(0.0); //wylacz od razu tempomat
|
|
mvControlling->DecScndCtrl( 2 );
|
|
}
|
|
break;
|
|
}
|
|
return OK;
|
|
};
|
|
|
|
bool TController::IncSpeedEIM() {
|
|
|
|
bool OK = false; // domyślnie false, aby wyszło z pętli while
|
|
switch( mvControlling->EIMCtrlType ) {
|
|
case 0:
|
|
OK = mvControlling->IncMainCtrl( 1 );
|
|
break;
|
|
case 1:
|
|
OK = mvControlling->MainCtrlPos < 6;
|
|
if( OK ) {
|
|
mvControlling->MainCtrlPos = 6;
|
|
}
|
|
/*
|
|
// TBD, TODO: set position based on desired acceleration?
|
|
OK = mvControlling->MainCtrlPos < mvControlling->MainCtrlPosNo;
|
|
if( OK ) {
|
|
mvControlling->MainCtrlPos = safe_clamp( mvControlling->MainCtrlPos + 1, 6, mvControlling->MainCtrlPosNo );
|
|
}
|
|
*/
|
|
break;
|
|
case 2: {
|
|
auto const powerpos{4 + mvControlling->EIMCtrlEmergencyPositions()};
|
|
OK = mvControlling->MainCtrlPos < powerpos;
|
|
if( OK ) {
|
|
mvControlling->MainCtrlPos = powerpos;
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
return OK;
|
|
}
|
|
|
|
bool TController::DecSpeedEIM( int const Amount )
|
|
{ // zmniejszenie prędkości (ale nie hamowanie)
|
|
bool OK = false; // domyślnie false, aby wyszło z pętli while
|
|
switch( mvControlling->EIMCtrlType ) {
|
|
case 0: {
|
|
OK = mvControlling->DecMainCtrl( Amount );
|
|
break;
|
|
}
|
|
case 1: {
|
|
OK = mvControlling->MainCtrlPos > 4;
|
|
if( OK ) {
|
|
mvControlling->MainCtrlPos = 4;
|
|
}
|
|
break;
|
|
}
|
|
case 2: {
|
|
if( AccDesired > 0
|
|
&& mvControlling->SpeedCtrlUnit.IsActive
|
|
&& mvControlling->SpeedCtrlUnit.PowerStep > 0
|
|
&& mvControlling->SpeedCtrlUnit.DesiredPower > mvControlling->SpeedCtrlUnit.MinPower ) {
|
|
mvControlling->SpeedCtrlPowerDec();
|
|
}
|
|
else {
|
|
auto const holdpos{2 + mvControlling->EIMCtrlEmergencyPositions()};
|
|
OK = mvControlling->MainCtrlPos > holdpos;
|
|
if( OK ) {
|
|
mvControlling->MainCtrlPos = holdpos;
|
|
}
|
|
}
|
|
break;
|
|
}
|
|
default: {
|
|
break;
|
|
}
|
|
}
|
|
return OK;
|
|
}
|
|
|
|
void TController::BrakeLevelSet(double b)
|
|
{ // ustawienie pozycji hamulca na wartość (b) w zakresie od -2 do BrakeCtrlPosNo
|
|
// jedyny dopuszczalny sposób przestawienia hamulca zasadniczego
|
|
if (BrakeCtrlPosition == b)
|
|
return; // nie przeliczać, jak nie ma zmiany
|
|
BrakeCtrlPosition = std::clamp(b, (double)gbh_MIN, (double)gbh_MAX);
|
|
fBrakeHeldTime = 0.0;
|
|
}
|
|
|
|
bool TController::BrakeLevelAdd(double b)
|
|
{ // dodanie wartości (b) do pozycji hamulca (w tym ujemnej)
|
|
// zwraca false, gdy po dodaniu było by poza zakresem
|
|
BrakeLevelSet(BrakeCtrlPosition + b);
|
|
return b > 0.0 ? BrakeCtrlPosition < gbh_MAX :
|
|
BrakeCtrlPosition > -1.0; // true, jeśli można kontynuować
|
|
}
|
|
|
|
// Ra: regulacja prędkości, wykonywana w każdym przebłysku świadomości AI
|
|
// ma dokręcać do bezoporowych i zdejmować pozycje w przypadku przekroczenia prądu
|
|
void TController::SpeedSet() {
|
|
|
|
if( false == AIControllFlag ) { return; }
|
|
|
|
switch (mvOccupied->EngineType)
|
|
{
|
|
case TEngineType::None: { // McZapkie-041003: wagon sterowniczy
|
|
if (mvControlling->MainCtrlPosNo > 0)
|
|
{ // jeśli ma czym kręcić
|
|
// TODO: sprawdzanie innego czlonu //if (!FuseFlagCheck())
|
|
if( ( iDrivigFlags & moveIncSpeed ) == 0 ) {
|
|
// przetok rozłączać od razu (no dependency on fActionTime)
|
|
while( mvControlling->MainCtrlPos
|
|
&& mvControlling->DecMainCtrl(1) ) {
|
|
; // na zero
|
|
}
|
|
if( fActionTime >= 0.0 ) {
|
|
fActionTime = -5.0; // niech trochę potrzyma
|
|
}
|
|
// mvControlling->AutoRelayCheck(); // sprawdzenie logiki sterowania
|
|
}
|
|
else {
|
|
// jak ma jechać
|
|
if( fActionTime < 0.0 ) { break; }
|
|
if( false == Ready ) { break; }
|
|
|
|
if( mvOccupied->DirActive > 0 ) {
|
|
mvOccupied->DirectionForward(); //żeby EN57 jechały na drugiej nastawie
|
|
}
|
|
|
|
if( mvControlling->MainCtrlPos > 0
|
|
&& false == mvControlling->StLinFlag ) {
|
|
// jak niby jedzie, ale ma rozłączone liniowe to na zero i czekać na przewalenie kułakowego
|
|
mvControlling->DecMainCtrl( 2 );
|
|
}
|
|
else {
|
|
// ruch nastawnika uzależniony jest od aktualnie ustawionej pozycji
|
|
switch( mvControlling->MainCtrlPos ) {
|
|
case 0:
|
|
if( mvControlling->MainCtrlActualPos ) {
|
|
// jeśli kułakowy nie jest wyzerowany to czekać na wyzerowanie
|
|
break;
|
|
}
|
|
mvControlling->IncMainCtrl( 1 ); // przetok; bez "break", bo nie ma czekania na 1. pozycji
|
|
case 1:
|
|
if( VelDesired >= 20 )
|
|
mvControlling->IncMainCtrl( 1 ); // szeregowa
|
|
case 2:
|
|
if( VelDesired >= 50 )
|
|
mvControlling->IncMainCtrl( 1 ); // równoległa
|
|
case 3:
|
|
if( VelDesired >= 80 )
|
|
mvControlling->IncMainCtrl( 1 ); // bocznik 1
|
|
case 4:
|
|
if( VelDesired >= 90 )
|
|
mvControlling->IncMainCtrl( 1 ); // bocznik 2
|
|
case 5:
|
|
if( VelDesired >= 100 )
|
|
mvControlling->IncMainCtrl( 1 ); // bocznik 3
|
|
}
|
|
}
|
|
if( mvControlling->MainCtrlPos ) // jak załączył pozycję
|
|
{
|
|
fActionTime = -5.0; // niech trochę potrzyma
|
|
// mvControlling->AutoRelayCheck(); // sprawdzenie logiki sterowania
|
|
}
|
|
}
|
|
}
|
|
break;
|
|
}
|
|
case TEngineType::ElectricSeriesMotor: {
|
|
/*
|
|
if (Ready || (iDrivigFlags & movePress)) { // o ile może jechać
|
|
// if (fAccGravity < -0.10) // i jedzie pod górę większą niż 10 promil
|
|
{ // procedura wjeżdżania na ekstremalne wzniesienia
|
|
if( std::fabs( mvControlling->Im ) > 0.85 * mvControlling->Imax ) { // a prąd jest większy niż 85% nadmiarowego
|
|
if( mvControlling->Imax * mvControlling->EngineVoltage / ( fMass * fAccGravity ) < -2.8 ) // a na niskim się za szybko nie pojedzie
|
|
{ // włączenie wysokiego rozruchu;
|
|
// (I*U)[A*V=W=kg*m*m/sss]/(m[kg]*a[m/ss])=v[m/s]; 2.8m/ss=10km/h
|
|
if( mvControlling->RList[ mvControlling->MainCtrlPos ].Bn > 1 ) { // jeśli jedzie na równoległym, to zbijamy do szeregowego, aby włączyć wysoki rozruch
|
|
if( mvControlling->ScndCtrlPos > 0 ) { // jeżeli jest bocznik
|
|
mvControlling->DecScndCtrl( 2 ); // wyłączyć bocznik, bo może blokować skręcenie NJ
|
|
}
|
|
do { // skręcanie do bezoporowej na szeregowym
|
|
mvControlling->DecMainCtrl( 1 ); // kręcimy nastawnik jazdy o 1 wstecz
|
|
}
|
|
while( ( false == mvControlling->IsMainCtrlNoPowerPos() )
|
|
&& ( mvControlling->RList[ mvControlling->MainCtrlPos ].Bn > 1 ) ); // oporowa zapętla
|
|
}
|
|
if( mvControlling->Imax < mvControlling->ImaxHi ) { // jeśli da się na wysokim
|
|
mvControlling->CurrentSwitch( true ); // rozruch wysoki (za to może się ślizgać)
|
|
}
|
|
if( ReactionTime > 0.1 ) {
|
|
ReactionTime = 0.1; // orientuj się szybciej
|
|
}
|
|
} // if (Im>Imin)
|
|
}
|
|
if( std::fabs( mvControlling->Im ) > 0.96 * mvControlling->Imax ) {// jeśli prąd jest duży (można 690 na 750)
|
|
if( mvControlling->ScndCtrlPos > 0 ) { // jeżeli jest bocznik
|
|
mvControlling->DecScndCtrl( 2 ); // zmniejszyć bocznik
|
|
}
|
|
else {
|
|
mvControlling->DecMainCtrl( 1 ); // kręcimy nastawnik jazdy o 1 wstecz
|
|
}
|
|
}
|
|
}
|
|
// else // gdy nie jedzie ambitnie pod górę
|
|
{ // sprawdzenie, czy rozruch wysoki jest potrzebny
|
|
if( ( mvControlling->Imax > mvControlling->ImaxLo )
|
|
&& ( mvOccupied->Vel >= 30.0 ) ) { // jak się rozpędził
|
|
// if (fAccGravity > -0.02) // a i pochylenie mnijsze niż 2‰
|
|
mvControlling->CurrentSwitch( false ); // rozruch wysoki wyłącz
|
|
}
|
|
}
|
|
}
|
|
*/
|
|
break;
|
|
}
|
|
case TEngineType::Dumb: {
|
|
break;
|
|
}
|
|
case TEngineType::DieselElectric: {
|
|
break;
|
|
}
|
|
case TEngineType::ElectricInductionMotor: {
|
|
break;
|
|
}
|
|
case TEngineType::DieselEngine: {
|
|
// Ra 2014-06: "automatyczna" skrzynia biegów...
|
|
auto const &motorparams { mvControlling->MotorParam[ mvControlling->ScndCtrlPos ] };
|
|
auto const velocity { ( mvControlling->ShuntMode ? mvControlling->AnPos : 1.0 ) * mvControlling->Vel };
|
|
if( false == motorparams.AutoSwitch ) {
|
|
// gdy biegi ręczne
|
|
// jak prędkość większa niż procent maksymalnej na danym biegu, wrzucić wyższy
|
|
if( velocity > 0.75 * motorparams.mfi ) {
|
|
// ...presuming there is a higher gear
|
|
if( mvControlling->ScndCtrlPos < mvControlling->ScndCtrlPosNo ) {
|
|
mvControlling->DecMainCtrl( 2 );
|
|
while( mvControlling->IncScndCtrl(1)
|
|
&& mvControlling->MotorParam[mvControlling->ScndCtrlPos].mIsat == 0.0 ) { // jeśli bieg jałowy to kolejny
|
|
;
|
|
}
|
|
}
|
|
}
|
|
// jak prędkość mniejsza niż minimalna na danym biegu, wrzucić niższy
|
|
else if( velocity < motorparams.fi && mvControlling->ScndCtrlPos > 1 ) {
|
|
// ... but ensure we don't switch all way down to 0
|
|
mvControlling->DecMainCtrl(2);
|
|
while (mvControlling->ScndCtrlPos > 1 // repeat the entry check as we're working in a loop
|
|
&& mvControlling->DecScndCtrl(1) && mvControlling->MotorParam[mvControlling->ScndCtrlPos].mIsat == 0.0)
|
|
{ // jeśli bieg jałowy to kolejny
|
|
;
|
|
}
|
|
}
|
|
}
|
|
break;
|
|
}
|
|
default: {
|
|
break;
|
|
}
|
|
} // enginetype
|
|
};
|
|
|
|
void TController::SpeedCntrl(double DesiredSpeed)
|
|
{
|
|
if( false == mvControlling->SpeedCtrl ) { return; }
|
|
|
|
if (mvControlling->IsSpeedCtrlSeparate())
|
|
{
|
|
// a switch of its own, the secondary controller left to the field shunting (eu07/maszyna#69)
|
|
if (DesiredSpeed < 0.1) {
|
|
DesiredSpeed = 0;
|
|
}
|
|
mvControlling->SpeedCtrlSwitch(DesiredSpeed > 0);
|
|
mvControlling->RunCommand("SpeedCntrl", DesiredSpeed, mvControlling->CabActive);
|
|
}
|
|
else if (mvControlling->EngineType == TEngineType::DieselEngine)
|
|
{
|
|
if (DesiredSpeed < 0.1) {
|
|
mvControlling->DecScndCtrl(2);
|
|
DesiredSpeed = 0;
|
|
}
|
|
else if (mvControlling->ScndCtrlPos < 1) {
|
|
mvControlling->IncScndCtrl(1);
|
|
}
|
|
mvControlling->RunCommand("SpeedCntrl", DesiredSpeed, mvControlling->CabActive);
|
|
}
|
|
else
|
|
if (mvControlling->ScndCtrlPosNo == 1)
|
|
{
|
|
mvControlling->IncScndCtrl(1);
|
|
mvControlling->RunCommand("SpeedCntrl", DesiredSpeed, mvControlling->CabActive);
|
|
}
|
|
else if (mvControlling->ScndCtrlPosNo > 1 && !mvOccupied->SpeedCtrlTypeTime)
|
|
{
|
|
int DesiredPos = 1 + mvControlling->ScndCtrlPosNo * ((DesiredSpeed - 1.0) / mvControlling->Vmax);
|
|
while( mvControlling->ScndCtrlPos > DesiredPos && true == mvControlling->DecScndCtrl(1) ) { ; } // all work is done in the condition loop
|
|
while( mvControlling->ScndCtrlPos < DesiredPos && true == mvControlling->IncScndCtrl(1) ) { ; } // all work is done in the condition loop
|
|
}
|
|
|
|
if( mvControlling->SpeedCtrlUnit.PowerStep > 0 && mvControlling->IsSpeedCtrlEngaged() ) {
|
|
while (mvControlling->SpeedCtrlUnit.DesiredPower < mvControlling->SpeedCtrlUnit.MaxPower)
|
|
{
|
|
mvControlling->SpeedCtrlPowerInc();
|
|
}
|
|
}
|
|
};
|
|
|
|
void TController::SetTimeControllers()
|
|
{
|
|
// TBD, TODO: rework this method to use hint system and regardless of driver type
|
|
if( false == AIControllFlag || 0 == mvOccupied->CabActive ) { return; }
|
|
|
|
//1. Check the type of Main Brake Handle
|
|
if( BrakeSystem == TBrakeSystem::Pneumatic || ForcePNBrake )
|
|
{
|
|
if (mvOccupied->Handle->Time)
|
|
{
|
|
auto const pressuredifference { mvOccupied->Handle->GetCP() - ( mvOccupied->HighPipePress - BrakeCtrlPosition * 0.25*mvOccupied->DeltaPipePress ) };
|
|
if (BrakeCtrlPosition > 0 && pressuredifference > 0.05)
|
|
mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_FB));
|
|
else if (BrakeCtrlPosition > 0 && pressuredifference < -0.05)
|
|
mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_RP));
|
|
else if (BrakeCtrlPosition == 0)
|
|
mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_RP));
|
|
else if (BrakeCtrlPosition == -1)
|
|
mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_FS));
|
|
else if (BrakeCtrlPosition == -2)
|
|
mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_NP));
|
|
}
|
|
if( mvOccupied->BrakeHandle == TBrakeHandle::FV4a ) {
|
|
mvOccupied->BrakeLevelSet( BrakeCtrlPosition );
|
|
}
|
|
if( mvOccupied->BrakeHandle == TBrakeHandle::MHZ_K8P
|
|
|| mvOccupied->BrakeHandle == TBrakeHandle::MHZ_EN57 ) {
|
|
if( BrakeCtrlPosition == 0 ) {
|
|
mvOccupied->BrakeLevelSet( mvOccupied->Handle->GetPos( bh_RP ) );
|
|
}
|
|
else if( BrakeCtrlPosition == -1 ) {
|
|
mvOccupied->BrakeLevelSet( mvOccupied->Handle->GetPos( bh_FS ) );
|
|
}
|
|
else if( BrakeCtrlPosition == -2 ) {
|
|
mvOccupied->BrakeLevelSet( mvOccupied->Handle->GetPos( bh_NP ) );
|
|
}
|
|
else if( BrakeCtrlPosition > 4.5 ) {
|
|
mvOccupied->BrakeLevelSet( 10 );
|
|
}
|
|
else if( BrakeCtrlPosition > 3.70 ) {
|
|
mvOccupied->BrakeLevelSet( 9 );
|
|
}
|
|
else {
|
|
mvOccupied->BrakeLevelSet( round( ( BrakeCtrlPosition * 0.4 - 0.1 ) / 0.15 ) );
|
|
}
|
|
}
|
|
}
|
|
//2. Check the type of Secondary Brake Handle
|
|
|
|
//3. Check the type od EIMCtrlType
|
|
/*
|
|
if (mvOccupied->EIMCtrlType > 0)
|
|
{
|
|
if (mvOccupied->EIMCtrlType == 1) //traxx
|
|
{
|
|
if (mvOccupied->LocalBrakePosA > 0.95) mvOccupied->MainCtrlPos = 0;
|
|
}
|
|
else if (mvOccupied->EIMCtrlType == 2) //elf
|
|
{
|
|
if (mvOccupied->LocalBrakePosA > 0.95) mvOccupied->MainCtrlPos = 1;
|
|
}
|
|
}
|
|
*/
|
|
if( mvOccupied->UniCtrlIntegratedLocalBrakeCtrl
|
|
&& mvOccupied->LocalBrakePosA > 0.95 ) {
|
|
while( IncBrakeEIM() ) { ; }
|
|
}
|
|
|
|
//4. Check Speed Control System
|
|
if (mvOccupied->EngineType == TEngineType::ElectricInductionMotor && mvOccupied->ScndCtrlPosNo > 1 && mvOccupied->SpeedCtrlTypeTime)
|
|
{
|
|
double SpeedCntrlVel =
|
|
ActualProximityDist > std::max(50.0, fMaxProximityDist) ?
|
|
VelDesired :
|
|
min_speed(VelDesired, VelNext);
|
|
SpeedCntrlVel = 10 * std::floor(SpeedCntrlVel*0.1);
|
|
if (mvOccupied->ScndCtrlPosNo == 4)
|
|
{
|
|
if (mvOccupied->NewSpeed + 0.1 < SpeedCntrlVel)
|
|
mvOccupied->ScndCtrlPos = 3;
|
|
if (mvOccupied->NewSpeed - 0.1 > SpeedCntrlVel)
|
|
mvOccupied->ScndCtrlPos = 1;
|
|
}
|
|
}
|
|
//5. Check Main Controller in Dizels
|
|
//5.1. Digital controller in DMUs with hydro
|
|
if (mvControlling->EngineType == TEngineType::DieselEngine && mvControlling->EIMCtrlType == 3)
|
|
{
|
|
|
|
DizelPercentage_Speed = DizelPercentage; //wstepnie procenty
|
|
auto MinVel{ std::min(mvControlling->hydro_TC_LockupSpeed, mvControlling->Vmax / 6) }; //minimal velocity
|
|
//when speed controll unit is active - start with the procedure
|
|
if (mvControlling->SpeedCtrl && mvControlling->ScndCtrlPos > 0) {
|
|
if (mvControlling->ScndCtrlPos > 0 && mvControlling->Vel < 1 + mvControlling->SpeedCtrlUnit.StartVelocity && DizelPercentage > 0)
|
|
DizelPercentage_Speed = 101; //keep last position to start
|
|
}
|
|
else if (VelDesired > MinVel) //more power for faster ride
|
|
{
|
|
auto const Factor{ 10 * mvControlling->Vmax / (mvControlling->Vmax + 3 * mvControlling->Vel) };
|
|
auto DesiredPercentage{ std::clamp(
|
|
VelDesired > mvControlling->Vel ? (VelDesired - mvControlling->Vel) / Factor : 0,
|
|
0.0, 1.0) }; //correction for reaching desired velocity
|
|
if (VelDesired < 0.5 * mvControlling->Vmax //low velocity and reaching desired
|
|
&& VelDesired - mvControlling->Vel < 10) {
|
|
DesiredPercentage = std::min(DesiredPercentage, 0.75);
|
|
}
|
|
DizelPercentage_Speed = std::round(DesiredPercentage * DizelPercentage);
|
|
}
|
|
else //slow acceleration during shunting wth minimal velocity
|
|
{
|
|
DizelPercentage_Speed = std::min(DizelPercentage, mvControlling->Vel < 0.99 * VelDesired ? 1 : 0);
|
|
}
|
|
|
|
auto const DizelActualPercentage { int(100.4 * mvControlling->eimic_real) };
|
|
|
|
auto const PosInc { mvControlling->MainCtrlPosNo };
|
|
auto PosDec { 0 };
|
|
for( int i = PosInc; i >= 0; --i ) {
|
|
if( mvControlling->UniCtrlList[i].SetCtrlVal <= 0
|
|
&& mvControlling->UniCtrlList[i].SpeedDown > 0.01 ) {
|
|
PosDec = i;
|
|
break;
|
|
}
|
|
}
|
|
|
|
if( std::abs( DizelPercentage_Speed - DizelActualPercentage ) > 0 ) {
|
|
|
|
if( PosDec > 0
|
|
&& ( DizelActualPercentage - DizelPercentage_Speed > 50
|
|
|| ( DizelPercentage_Speed == 0
|
|
&& DizelActualPercentage > 10 ) ) ) {
|
|
//one position earlier should be fast decreasing
|
|
PosDec -= 1;
|
|
}
|
|
auto const DesiredPos { (
|
|
DizelPercentage_Speed > DizelActualPercentage ?
|
|
PosInc :
|
|
PosDec ) };
|
|
while( mvControlling->MainCtrlPos > DesiredPos ) { mvControlling->DecMainCtrl( 1 ); }
|
|
while( mvControlling->MainCtrlPos < DesiredPos ) { mvControlling->IncMainCtrl( 1 ); }
|
|
}
|
|
if (BrakeCtrlPosition < 0.1) //jesli nie hamuje
|
|
mvOccupied->BrakeLevelSet(mvControlling->UniCtrlList[mvControlling->MainCtrlPos].mode); //zeby nie bruzdzilo machanie zespolonym
|
|
}
|
|
else
|
|
//5.2. Analog direct controller
|
|
if (mvControlling->EngineType == TEngineType::DieselEngine && mvControlling->Vmax > 30)
|
|
{
|
|
int MaxPos = mvControlling->MainCtrlPosNo;
|
|
int MinPos = MaxPos;
|
|
for (int i = MaxPos; i > 1 && mvControlling->RList[i].Mn > 0; i--) MinPos = i;
|
|
if (MaxPos > MinPos && mvControlling->MainCtrlPos > 0 && AccDesired > 0)
|
|
{
|
|
double Factor = 5 * mvControlling->Vmax / (mvControlling->Vmax + mvControlling->Vel);
|
|
int DesiredPos = MinPos + (MaxPos - MinPos)*(VelDesired > mvControlling->Vel ? (VelDesired - mvControlling->Vel) / Factor : 0);
|
|
if (DesiredPos > MaxPos) DesiredPos = MaxPos;
|
|
if (DesiredPos < MinPos) DesiredPos = MinPos;
|
|
if (!mvControlling->SlippingWheels)
|
|
{
|
|
while (mvControlling->MainCtrlPos > DesiredPos) mvControlling->DecMainCtrl(1);
|
|
if (mvControlling->Vel>mvControlling->dizel_minVelfullengage)
|
|
while (mvControlling->MainCtrlPos < DesiredPos) mvControlling->IncMainCtrl(1);
|
|
}
|
|
}
|
|
}
|
|
// 5.5 universal control for diesel electric vehicles
|
|
if (mvControlling->EngineType == TEngineType::DieselElectric && mvControlling->EIMCtrlType == 3 && AccDesired >= 0.0 && mvControlling->StLinFlag)
|
|
{
|
|
// NOTE: partial implementation for speedinc/dec
|
|
// TBD, TODO: implement fully?
|
|
auto const PosInc{mvControlling->MainCtrlPosNo};
|
|
auto PosKeep{0};
|
|
auto PosDec{0};
|
|
for (int i = PosInc; i >= 0; --i)
|
|
{
|
|
if (mvControlling->UniCtrlList[i].SetCtrlVal <= 0)
|
|
{
|
|
if (mvControlling->UniCtrlList[i].SpeedDown == 0.0)
|
|
{
|
|
PosKeep = i;
|
|
}
|
|
if (mvControlling->UniCtrlList[i].SpeedDown > 0.01)
|
|
{
|
|
PosDec = i;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
auto const DesiredPos{(AccDesired > AbsAccS + 0.05 ? PosInc : AccDesired < AbsAccS - 0.05 ? PosDec : PosKeep)};
|
|
|
|
while (mvControlling->MainCtrlPos > DesiredPos && mvControlling->DecMainCtrl(1))
|
|
{
|
|
;
|
|
}
|
|
while (mvControlling->MainCtrlPos < DesiredPos && mvControlling->IncMainCtrl(1))
|
|
{
|
|
;
|
|
}
|
|
}
|
|
//6. UniversalBrakeButtons
|
|
//6.1. Checking flags for Over pressure
|
|
if (std::abs(BrakeCtrlPosition - gbh_FS)<0.5) {
|
|
UniversalBrakeButtons |= TUniversalBrake::ub_HighPressure | TUniversalBrake::ub_Overload;
|
|
}
|
|
else {
|
|
UniversalBrakeButtons &= ~(TUniversalBrake::ub_HighPressure | TUniversalBrake::ub_Overload);
|
|
}
|
|
//6.2. Setting buttons
|
|
for (int i = 0; i < 3; i++) {
|
|
mvOccupied->UniversalBrakeButton(i, UniversalBrakeButtons & mvOccupied->UniversalBrakeButtonFlag[i]);
|
|
}
|
|
};
|
|
|
|
void TController::CheckTimeControllers()
|
|
{
|
|
// TODO: rework this method to use hint system and regardless of driver type
|
|
if( false == AIControllFlag || 0 == mvControlling->CabActive ) { return; }
|
|
|
|
//1. Check the type of Main Brake Handle
|
|
if( BrakeSystem == TBrakeSystem::ElectroPneumatic && mvOccupied->Handle->TimeEP && !ForcePNBrake )
|
|
{
|
|
mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_EPN));
|
|
}
|
|
if( ( BrakeSystem == TBrakeSystem::Pneumatic || ForcePNBrake ) && mvOccupied->Handle->Time )
|
|
{
|
|
if (BrakeCtrlPosition > 0)
|
|
mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_MB));
|
|
else
|
|
mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_RP));
|
|
}
|
|
//2. Check the type of Secondary Brake Handle
|
|
|
|
//3. Check the type od EIMCtrlType
|
|
if (mvOccupied->EIMCtrlType > 0)
|
|
{
|
|
if (mvOccupied->EIMCtrlType == 1) //traxx
|
|
{
|
|
if (mvOccupied->MainCtrlPos > 3) mvOccupied->MainCtrlPos = 5;
|
|
if (mvOccupied->MainCtrlPos < 3) mvOccupied->MainCtrlPos = 1;
|
|
}
|
|
else if (mvOccupied->EIMCtrlType == 2) //elf
|
|
{
|
|
auto const emergencypositions{mvOccupied->EIMCtrlEmergencyPositions()};
|
|
if (mvOccupied->eimic > 0) mvOccupied->MainCtrlPos = 3 + emergencypositions;
|
|
if (mvOccupied->eimic < 0) mvOccupied->MainCtrlPos = 2 + emergencypositions;
|
|
}
|
|
}
|
|
//4. Check Speed Control System
|
|
if (mvOccupied->EngineType == TEngineType::ElectricInductionMotor && mvOccupied->ScndCtrlPosNo > 1 && mvOccupied->SpeedCtrlTypeTime && mvOccupied->ScndCtrlPosNo == 4)
|
|
{
|
|
mvOccupied->ScndCtrlPos = 2;
|
|
}
|
|
|
|
//5. Check Main Controller in Dizels
|
|
//5.1. Digital controller in DMUs with hydro
|
|
if (mvControlling->EngineType == TEngineType::DieselEngine && mvControlling->EIMCtrlType == 3)
|
|
{
|
|
int DizelActualPercentage = 100.4 * mvControlling->eimic_real;
|
|
int NeutralPos = mvControlling->MainCtrlPosNo - 1; //przedostatnia powinna wstrzymywać - hipoteza robocza
|
|
for (int i = mvControlling->MainCtrlPosNo; i >= 0; i--)
|
|
if (mvControlling->UniCtrlList[i].SetCtrlVal <= 0 && mvControlling->UniCtrlList[i].SpeedDown < 0.01) //niby zero, ale nie zmniejsza procentów
|
|
{
|
|
NeutralPos = i;
|
|
break;
|
|
}
|
|
if (BrakeCtrlPosition < 0.1) //jesli nie hamuje
|
|
{
|
|
if (DizelActualPercentage >= DizelPercentage_Speed && mvControlling->MainCtrlPos > NeutralPos)
|
|
while (mvControlling->MainCtrlPos > NeutralPos) mvControlling->DecMainCtrl(1);
|
|
if (DizelActualPercentage <= DizelPercentage_Speed && mvControlling->MainCtrlPos < NeutralPos)
|
|
while (mvControlling->MainCtrlPos < NeutralPos) mvControlling->IncMainCtrl(1);
|
|
mvOccupied->BrakeLevelSet(mvControlling->UniCtrlList[mvControlling->MainCtrlPos].mode); //zeby nie bruzdzilo machanie zespolonym
|
|
}
|
|
}
|
|
};
|
|
|
|
// otwieranie/zamykanie drzwi w składzie albo (tylko AI) EZT
|
|
void TController::Doors( bool const Open, int const Side ) {
|
|
// otwieranie drzwi
|
|
if( true == Open ) {
|
|
|
|
auto const lewe = pVehicle->DirectionGet() > 0 ? 1 : 2;
|
|
auto const prawe = 3 - lewe;
|
|
// doorsteps as the timetable asks, before the doors open (eu07/maszyna#95)
|
|
if( auto const doorstep { timetable::doorstep( m_stopflags ) };
|
|
doorstep.has_value() && mvOccupied->Doors.step_enabled != *doorstep ) {
|
|
cue_action( *doorstep ? driver_hint::doorstepon : driver_hint::doorstepoff );
|
|
}
|
|
// grant door control permission if it's not automatic
|
|
// TBD: stricter requirements?
|
|
if( true == pVehicle->MoverParameters->Doors.permit_needed ) {
|
|
if( Side & prawe ) {
|
|
cue_action( driver_hint::doorrightpermiton );
|
|
}
|
|
if( Side & lewe ) {
|
|
cue_action( driver_hint::doorleftpermiton );
|
|
}
|
|
}
|
|
// consist-wide remote signals to open doors doors
|
|
// NOTE: mixed controls are left up to passengers to open doors by themselves, unless the timetable has
|
|
// the driver open all the doors
|
|
if( true == timetable::opens_doors( *pVehicle->MoverParameters, m_stopflags ) ) {
|
|
if( Side & prawe ) {
|
|
cue_action( driver_hint::doorrightopen );
|
|
}
|
|
if( Side & lewe ) {
|
|
cue_action( driver_hint::doorleftopen );
|
|
}
|
|
}
|
|
}
|
|
// zamykanie drzwi
|
|
else {
|
|
// if the doors are already closed and locked then there's nothing to do
|
|
if( false == doors_permit_active()
|
|
&& false == doors_open() ) {
|
|
iDrivigFlags &= ~moveDoorOpened;
|
|
iDrivigFlags &= ~moveDepartureWarned;
|
|
return;
|
|
}
|
|
|
|
if (mvOccupied->Doors.has_warning && !TestFlag(iDrivigFlags, moveDepartureWarned))
|
|
{
|
|
if (!mvOccupied->DepartureSignal)
|
|
{
|
|
// Not warned yet, not warning yet - start the warning signal.
|
|
cue_action( driver_hint::departuresignalon ); // załącenie bzyczka
|
|
fActionTime = Random( -0.8, -0.3 ); // 0.3-0.8 second buzzer
|
|
return;
|
|
}
|
|
// Not warned yet, warning now - stop the warning signal and mark it as done.
|
|
cue_action( driver_hint::departuresignaloff );
|
|
fActionTime = Random( -0.2, 0.0 ); // Wait just a bit more before departing
|
|
iDrivigFlags |= moveDepartureWarned;
|
|
return;
|
|
}
|
|
|
|
if( true == doors_open() && (pVehicle->MoverParameters->Doors.close_control == control_t::conductor || pVehicle->MoverParameters->Doors.close_control == control_t::driver ||
|
|
pVehicle->MoverParameters->Doors.close_control == control_t::mixed) ) {
|
|
// consist-wide remote signals to close doors
|
|
cue_action(driver_hint::doorrightclose);
|
|
cue_action(driver_hint::doorleftclose);
|
|
}
|
|
if( true == doors_permit_active() ) {
|
|
cue_action( driver_hint::doorrightpermitoff );
|
|
cue_action( driver_hint::doorleftpermitoff );
|
|
}
|
|
// if applicable close manually-operated doors in vehicles which may ignore remote signals
|
|
{
|
|
const auto *vehicle = pVehicles[ end::front ]; // pojazd na czole składu
|
|
while( vehicle != nullptr ) {
|
|
// zamykanie drzwi w pojazdach - flaga zezwolenia była by lepsza
|
|
auto const ismanualdoor {
|
|
vehicle->MoverParameters->Doors.auto_velocity == -1.f
|
|
&& ( vehicle->MoverParameters->Doors.close_control == control_t::passenger
|
|
|| vehicle->MoverParameters->Doors.close_control == control_t::mixed ) };
|
|
|
|
if( true == ismanualdoor
|
|
&& ( vehicle->LoadExchangeTime() == 0.f
|
|
|| vehicle->MoverParameters->Vel > EU07_AI_MOVEMENT ) ) {
|
|
vehicle->MoverParameters->OperateDoors( side::right, false, range_t::local );
|
|
vehicle->MoverParameters->OperateDoors( side::left, false, range_t::local );
|
|
}
|
|
vehicle = vehicle->Next(); // pojazd podłączony z tyłu (patrząc od czoła)
|
|
}
|
|
}
|
|
fActionTime = Random(-3.5, -1.0); // 1.0-3.5 sec wait
|
|
iDrivigFlags &= ~moveDoorOpened; // zostały zamknięte - nie wykonywać drugi raz
|
|
iDrivigFlags &= ~moveDepartureWarned;
|
|
}
|
|
}
|
|
|
|
// returns true if any vehicle in the consist has open doors
|
|
bool
|
|
TController::doors_open() const {
|
|
|
|
return IsAnyDoorOpen[side::right] || IsAnyDoorOpen[side::left];
|
|
}
|
|
|
|
bool
|
|
TController::doors_permit_active() const {
|
|
|
|
return IsAnyDoorPermitActive[side::right] || IsAnyDoorPermitActive[side::left];
|
|
}
|
|
|
|
void
|
|
TController::announce( announcement_t const Announcement ) {
|
|
|
|
m_lastannouncement = Announcement;
|
|
|
|
if( IsCargoTrain ) {
|
|
// cargo trains aren't likely to have announcement systems, so we can skip the procedure altogether
|
|
return;
|
|
}
|
|
|
|
auto *vehicle { pVehicles[ end::front ] };
|
|
while( vehicle ) {
|
|
vehicle->announce( Announcement );
|
|
vehicle = vehicle->Next();
|
|
}
|
|
}
|
|
|
|
void TController::RecognizeCommand()
|
|
{ // odczytuje i wykonuje komendę przekazaną lokomotywie
|
|
TCommand *c = &mvOccupied->CommandIn;
|
|
PutCommand(c->Command, c->Value1, c->Value2, c->Location, stopComm);
|
|
c->Command = ""; // usunięcie obsłużonej komendy
|
|
}
|
|
|
|
void TController::PutCommand(std::string NewCommand, double NewValue1, double NewValue2, const TLocation &NewLocation, TStopReason reason)
|
|
{ // wysłanie komendy przez event PutValues, jak pojazd ma obsadę, to wysyła tutaj, a nie do pojazdu bezpośrednio
|
|
// zamiana na współrzędne scenerii
|
|
glm::dvec3 sl { -NewLocation.X, NewLocation.Z, NewLocation.Y };
|
|
if (!PutCommand(NewCommand, NewValue1, NewValue2, &sl, reason))
|
|
mvOccupied->PutCommand(NewCommand, NewValue1, NewValue2, NewLocation);
|
|
}
|
|
|
|
bool TController::PutCommand( std::string NewCommand, double NewValue1, double NewValue2, glm::dvec3 const *NewLocation, TStopReason reason )
|
|
{ // analiza komendy
|
|
if (NewCommand == "CabSignal")
|
|
{ // SHP wyzwalane jest przez człon z obsadą, ale obsługiwane przez silnikowy
|
|
// nie jest to najlepiej zrobione, ale bez symulacji obwodów lepiej nie będzie
|
|
// Ra 2014-04: jednak przeniosłem do rozrządczego
|
|
mvOccupied->PutCommand(NewCommand, NewValue1, NewValue2, mvOccupied->Loc);
|
|
mvOccupied->RunInternalCommand(); // rozpoznaj komende bo lokomotywa jej nie rozpoznaje
|
|
return true; // załatwione
|
|
}
|
|
|
|
if (NewCommand == "Overhead")
|
|
{ // informacja o stanie sieci trakcyjnej
|
|
fOverhead1 = NewValue1; // informacja o napięciu w sieci trakcyjnej (0=brak drutu, zatrzymaj!)
|
|
fOverhead2 = NewValue2; // informacja o sposobie jazdy (-1=normalnie, 0=bez prądu, >0=z
|
|
// opuszczonym i ograniczeniem prędkości)
|
|
return true; // załatwione
|
|
}
|
|
|
|
if (NewCommand == "Emergency_brake") // wymuszenie zatrzymania, niezależnie kto prowadzi
|
|
{ // Ra: no nadal nie jest zbyt pięknie
|
|
// SetVelocity(0, 0, reason);
|
|
mvOccupied->PutCommand("Emergency_brake", 1.0, 1.0, mvOccupied->Loc);
|
|
return true; // załatwione
|
|
}
|
|
|
|
if (NewCommand.compare(0, 10, "Timetable:") == 0)
|
|
{ // przypisanie nowego rozkładu jazdy, również prowadzonemu przez użytkownika
|
|
NewCommand.erase(0, 10); // zostanie nazwa pliku z rozkładem
|
|
#if LOGSTOPS
|
|
WriteLog("New timetable for " + pVehicle->asName + ": " + NewCommand); // informacja
|
|
#endif
|
|
TrainParams = TTrainParameters(NewCommand); // rozkład jazdy
|
|
tsGuardSignal = sound_source { sound_placement::internal, 2 * EU07_SOUND_CABCONTROLSCUTOFFRANGE }; // wywalenie kierownika
|
|
m_lastexchangestop.clear();
|
|
m_stopflags = {};
|
|
if (NewCommand != "none")
|
|
{
|
|
if (false == TrainParams.LoadTTfile(
|
|
std::string(Global.asCurrentSceneryPath.c_str()), floor(NewValue2 + 0.5),
|
|
NewValue1)) // pierwszy parametr to przesunięcie rozkładu w czasie
|
|
{
|
|
if (ConversionError == -8)
|
|
ErrorLog("Missed timetable: " + NewCommand);
|
|
WriteLog("Cannot load timetable file " + NewCommand + "\r\nError " +
|
|
std::to_string(ConversionError) + " in position " + std::to_string(TrainParams.StationCount));
|
|
NewCommand = ""; // puste, dla wymiennej tekstury
|
|
}
|
|
else
|
|
{ // inicjacja pierwszego przystanku i pobranie jego nazwy
|
|
// HACK: clear the potentially set door state flag to ensure door get opened if applicable
|
|
if( true == AIControllFlag ) {
|
|
// simplified door closing procedure, to sync actual door state with the door state flag
|
|
// NOTE: this may result in visually ugly quick switch between closing and opening the doors, but eh
|
|
if( pVehicle->MoverParameters->Doors.close_control == control_t::driver
|
|
|| pVehicle->MoverParameters->Doors.close_control == control_t::mixed ) {
|
|
pVehicle->MoverParameters->OperateDoors( side::right, false );
|
|
pVehicle->MoverParameters->OperateDoors( side::left, false );
|
|
}
|
|
if( pVehicle->MoverParameters->Doors.permit_needed ) {
|
|
pVehicle->MoverParameters->PermitDoors( side::right, false );
|
|
pVehicle->MoverParameters->PermitDoors( side::left, false );
|
|
}
|
|
}
|
|
iDrivigFlags &= ~moveDoorOpened;
|
|
|
|
TrainParams.UpdateMTable( simulation::Time, TrainParams.NextStationName );
|
|
TrainParams.StationIndexInc(); // przejście do następnej
|
|
TrainParams.StationStart = TrainParams.StationIndex;
|
|
asNextStop = TrainParams.NextStop();
|
|
// the flags of the first station until the train stops there
|
|
m_stopflags = TrainParams.stop_flags();
|
|
m_lastannouncement = announcement_t::idle;
|
|
iDrivigFlags |= movePrimary; // skoro dostał rozkład, to jest teraz głównym
|
|
// NewCommand = Global.asCurrentSceneryPath + NewCommand;
|
|
auto lookup =
|
|
FileExists(
|
|
{ Global.asCurrentSceneryPath + NewCommand, paths::sounds + NewCommand },
|
|
{ ".ogg", ".flac", ".wav" } );
|
|
if( false == lookup.first.empty() ) {
|
|
// wczytanie dźwięku odjazdu podawanego bezpośrenido
|
|
tsGuardSignal = sound_source( sound_placement::external, 75.f ).deserialize( lookup.first + lookup.second, sound_type::single );
|
|
iGuardRadio = 0; // nie przez radio
|
|
}
|
|
else {
|
|
NewCommand += "radio";
|
|
lookup =
|
|
FileExists(
|
|
{ Global.asCurrentSceneryPath + NewCommand, paths::sounds + NewCommand },
|
|
{ ".ogg", ".flac", ".wav" } );
|
|
if( false == lookup.first.empty() ) {
|
|
// wczytanie dźwięku odjazdu w wersji radiowej (słychać tylko w kabinie)
|
|
tsGuardSignal = sound_source( sound_placement::internal, EU07_SOUND_HANDHELDRADIORANGE ).deserialize( lookup.first + lookup.second, sound_type::single );
|
|
iGuardRadio = iRadioChannel;
|
|
}
|
|
}
|
|
NewCommand = TrainParams.Relation2; // relacja docelowa z rozkładu
|
|
}
|
|
// jeszcze poustawiać tekstury na wyświetlaczach
|
|
TDynamicObject *p = pVehicles[end::front];
|
|
while (p)
|
|
{
|
|
p->DestinationSet(NewCommand, TrainParams.TrainName); // relacja docelowa
|
|
p = p->Next(); // pojazd podłączony od tyłu (licząc od czoła)
|
|
}
|
|
}
|
|
if (NewLocation) // jeśli podane współrzędne eventu/komórki ustawiającej rozkład (trainset
|
|
// nie podaje)
|
|
{
|
|
auto v = *NewLocation - pVehicle->GetPosition(); // wektor do punktu sterującego
|
|
auto d = pVehicle->VectorFront(); // wektor wskazujący przód
|
|
iDirectionOrder = (v.x * d.x + v.z * d.z) * NewValue1 > 0 ?
|
|
1 :
|
|
-1; // do przodu, gdy iloczyn skalarny i prędkość dodatnie
|
|
/*
|
|
if (NewValue1!=0.0) //jeśli ma jechać
|
|
if (iDirectionOrder==0) //a kierunek nie był określony (normalnie określany przez
|
|
reardriver/headdriver)
|
|
iDirectionOrder=NewValue1>0?1:-1; //ustalenie kierunku jazdy względem sprzęgów
|
|
else
|
|
if (NewValue1<0) //dla ujemnej prędkości
|
|
iDirectionOrder=-iDirectionOrder; //ma jechać w drugą stronę
|
|
*/
|
|
if (AIControllFlag) // jeśli prowadzi komputer
|
|
Activation(); // umieszczenie obsługi we właściwym członie, ustawienie nawrotnika w
|
|
// przód
|
|
}
|
|
/*
|
|
else
|
|
if (!iDirectionOrder)
|
|
{//jeśli nie ma kierunku, trzeba ustalić
|
|
if (mvOccupied->V!=0.0)
|
|
iDirectionOrder=mvOccupied->V>0?1:-1;
|
|
else
|
|
iDirectionOrder=mvOccupied->CabOccupied;
|
|
if (!iDirectionOrder) iDirectionOrder=1;
|
|
}
|
|
*/
|
|
// jeśli wysyłane z Trainset, to wszystko jest już odpowiednio ustawione
|
|
// if (!NewLocation) //jeśli wysyłane z Trainset
|
|
// if (mvOccupied->CabActive*mvOccupied->V*NewValue1<0) //jeśli zadana prędkość niezgodna z
|
|
// aktualnym kierunkiem jazdy
|
|
// DirectionForward(false); //jedziemy do tyłu (nawrotnik do tyłu)
|
|
// CheckVehicles(); //sprawdzenie składu, AI zapali światła
|
|
TableClear(); // wyczyszczenie tabelki prędkości, bo na nowo trzeba określić kierunek i
|
|
// sprawdzić przystanki
|
|
OrdersInit(fabs(NewValue1)); // ustalenie tabelki komend wg rozkładu oraz prędkości początkowej
|
|
// if (NewValue1!=0.0) if (!AIControllFlag) DirectionForward(NewValue1>0.0); //ustawienie
|
|
// nawrotnika użytkownikowi (propaguje się do członów)
|
|
// if (NewValue1>0)
|
|
// TrainNumber=floor(NewValue1); //i co potem ???
|
|
return true; // załatwione
|
|
}
|
|
|
|
if (NewCommand == "SetVelocity")
|
|
{
|
|
if (NewLocation)
|
|
vCommandLocation = *NewLocation;
|
|
if (NewValue1 != 0.0 && OrderCurrentGet() != Obey_train)
|
|
{ // o ile jazda
|
|
if( false == iEngineActive ) {
|
|
// trzeba odpalić silnik najpierw, światła ustawi
|
|
OrderNext( Prepare_engine );
|
|
}
|
|
OrderNext(Obey_train); // to uruchomić jazdę pociągową (od razu albo po odpaleniu silnika
|
|
OrderCheck(); // jeśli jazda pociągowa teraz, to wykonać niezbędne operacje
|
|
}
|
|
if (NewValue1 != 0.0) // jeśli jechać
|
|
iDrivigFlags &= ~moveStopHere; // podjeżanie do semaforów zezwolone
|
|
else
|
|
iDrivigFlags |= moveStopHere; // stać do momentu podania komendy jazdy
|
|
SetVelocity(NewValue1, NewValue2, reason); // bylo: nic nie rob bo SetVelocity zewnetrznie
|
|
// jest wywolywane przez dynobj.cpp
|
|
return true;
|
|
}
|
|
|
|
if( NewCommand == "PointVelocity" ) {
|
|
// read by the speed table scan only; when the cell's event runs, there is nothing to do
|
|
return true;
|
|
}
|
|
|
|
if (NewCommand == "SetProximityVelocity")
|
|
{
|
|
/*
|
|
if (SetProximityVelocity(NewValue1,NewValue2))
|
|
if (NewLocation)
|
|
vCommandLocation=*NewLocation;
|
|
*/
|
|
return true;
|
|
}
|
|
|
|
if (NewCommand == "ShuntVelocity")
|
|
{ // uruchomienie jazdy manewrowej bądź zmiana prędkości
|
|
if (NewLocation)
|
|
vCommandLocation = *NewLocation;
|
|
// if (OrderList[OrderPos]=Obey_train) and (NewValue1<>0))
|
|
if (false == iEngineActive)
|
|
OrderNext(Prepare_engine); // trzeba odpalić silnik najpierw
|
|
OrderNext(Shunt); // zamieniamy w aktualnej pozycji, albo dodajey za odpaleniem silnika
|
|
if (NewValue1 != 0.0)
|
|
{
|
|
// if (iVehicleCount>=0) WriteLog("Skasowano ilosć wagonów w ShuntVelocity!");
|
|
iVehicleCount = -2; // wartość neutralna
|
|
CheckVehicles(); // zabrać to do OrderCheck()
|
|
}
|
|
// dla prędkości ujemnej przestawić nawrotnik do tyłu? ale -1=brak ograniczenia !!!!
|
|
iDrivigFlags &= ~movePress; // bez dociskania
|
|
SetVelocity(NewValue1, NewValue2, reason);
|
|
if (NewValue1 != 0.0)
|
|
iDrivigFlags &= ~moveStopHere; // podjeżanie do semaforów zezwolone
|
|
else
|
|
iDrivigFlags |= moveStopHere; // ma stać w miejscu
|
|
if (fabs(NewValue1) > 2.0) // o ile wartość jest sensowna (-1 nie jest konkretną wartością)
|
|
fShuntVelocity = fabs(NewValue1); // zapamiętanie obowiązującej prędkości dla manewrów
|
|
|
|
return true;
|
|
}
|
|
|
|
if (NewCommand == "Wait_for_orders")
|
|
{ // oczekiwanie; NewValue1 - czas oczekiwania, -1 = na inną komendę
|
|
if (NewValue1 > 0.0 ? NewValue1 > fStopTime : false)
|
|
fStopTime = NewValue1; // Ra: włączenie czekania bez zmiany komendy
|
|
else
|
|
OrderCurrentSet( Wait_for_orders ); // czekanie na komendę (albo dać OrderPos=0)
|
|
|
|
return true;
|
|
}
|
|
|
|
if (NewCommand == "Prepare_engine")
|
|
{ // włączenie albo wyłączenie silnika (w szerokim sensie)
|
|
OrdersClear(); // czyszczenie tabelki rozkazów, aby nic dalej nie robił
|
|
if (NewValue1 == 0.0)
|
|
OrderNext(Release_engine); // wyłączyć silnik (przygotować pojazd do jazdy)
|
|
else if (NewValue1 > 0.0)
|
|
OrderNext(Prepare_engine); // odpalić silnik (wyłączyć wszystko, co się da)
|
|
// po załączeniu przejdzie do kolejnej komendy, po wyłączeniu na Wait_for_orders
|
|
return true;
|
|
}
|
|
|
|
if (NewCommand == "Change_direction")
|
|
{
|
|
TOrders o = OrderCurrentGet(); // co robił przed zmianą kierunku
|
|
if (false == iEngineActive)
|
|
OrderNext(Prepare_engine); // trzeba odpalić silnik najpierw
|
|
if (NewValue1 == 0.0)
|
|
iDirectionOrder = -iDirection; // zmiana na przeciwny niż obecny
|
|
else if (NewLocation) // jeśli podane współrzędne eventu/komórki ustawiającej rozkład
|
|
// (trainset nie podaje)
|
|
{
|
|
auto v = *NewLocation - pVehicle->GetPosition(); // wektor do punktu sterującego
|
|
auto d = pVehicle->VectorFront(); // wektor wskazujący przód
|
|
iDirectionOrder = (v.x * d.x + v.z * d.z) * NewValue1 > 0 ?
|
|
1 :
|
|
-1; // do przodu, gdy iloczyn skalarny i prędkość dodatnie
|
|
// iDirectionOrder=1; else if (NewValue1<0.0) iDirectionOrder=-1;
|
|
}
|
|
if (
|
|
|
|
iDirectionOrder != iDirection)
|
|
OrderNext(Change_direction); // zadanie komendy do wykonania
|
|
if (o >= Shunt) // jeśli jazda manewrowa albo pociągowa
|
|
OrderNext(o); // to samo robić po zmianie
|
|
else if (!o) // jeśli wcześniej było czekanie
|
|
OrderNext(Shunt); // to dalej jazda manewrowa
|
|
if (mvOccupied->Vel >= EU07_AI_MOVEMENT) // jeśli jedzie
|
|
iDrivigFlags &= ~moveStartHorn; // to bez trąbienia po ruszeniu z zatrzymania
|
|
// Change_direction wykona się samo i następnie przejdzie do kolejnej komendy
|
|
return true;
|
|
}
|
|
|
|
if (NewCommand == "Obey_train") {
|
|
if( false == iEngineActive ) {
|
|
OrderNext( Prepare_engine ); // trzeba odpalić silnik najpierw
|
|
}
|
|
OrderNext( Obey_train );
|
|
// if (NewValue1>0) TrainNumber=floor(NewValue1); //i co potem ???
|
|
OrderCheck(); // jeśli jazda pociągowa teraz, to wykonać niezbędne operacje
|
|
|
|
return true;
|
|
}
|
|
|
|
if (NewCommand == "Bank") {
|
|
if( false == iEngineActive ) {
|
|
OrderNext( Prepare_engine ); // trzeba odpalić silnik najpierw
|
|
}
|
|
OrderNext( Bank );
|
|
// if (NewValue1>0) TrainNumber=floor(NewValue1); //i co potem ???
|
|
OrderCheck(); // jeśli jazda pociągowa teraz, to wykonać niezbędne operacje
|
|
|
|
return true;
|
|
}
|
|
|
|
if( NewCommand == "Shunt" || NewCommand == "Loose_shunt" )
|
|
{ // NewValue1 - ilość wagonów (-1=wszystkie); NewValue2: 0=odczep, 1..63=dołącz, -1=bez zmian
|
|
//-3,-y - podłączyć do całego stojącego składu (sprzęgiem y>=1), zmienić kierunek i czekać w trybie pociągowym
|
|
//-2,-y - podłączyć do całego stojącego składu (sprzęgiem y>=1), zmienić kierunek i czekać
|
|
//-2, y - podłączyć do całego stojącego składu (sprzęgiem y>=1) i czekać
|
|
//-1,-y - podłączyć do całego stojącego składu (sprzęgiem y>=1) i jechać w powrotną stronę
|
|
//-1, y - podłączyć do całego stojącego składu (sprzęgiem y>=1) i jechać dalej
|
|
//-1, 0 - tryb manewrowy bez zmian (odczepianie z pozostawieniem wagonów nie ma sensu)
|
|
// 0, 0 - odczepienie lokomotywy
|
|
// x,-y - podłączyć się do składu (sprzęgiem y>=1), a następnie odczepić i zabrać (x) wagonów
|
|
// 1, 0 - odczepienie lokomotywy z jednym wagonem
|
|
iDrivigFlags &= ~moveStopHere; // podjeżanie do semaforów zezwolone
|
|
if( false == iEngineActive ) {
|
|
OrderNext( Prepare_engine ); // trzeba odpalić silnik najpierw
|
|
}
|
|
if (NewValue2 != 0) // jeśli podany jest sprzęg
|
|
{
|
|
iCoupler = std::floor( std::abs( NewValue2 ) ); // jakim sprzęgiem
|
|
OrderNext(Connect); // najpierw połącz pojazdy
|
|
if (NewValue1 >= 0.0) // jeśli ilość wagonów inna niż wszystkie
|
|
{ // to po podpięciu należy się odczepić
|
|
iDirectionOrder = -iDirection; // zmiana na ciągnięcie
|
|
OrderPush(Change_direction); // najpierw zmień kierunek, bo odczepiamy z tyłu
|
|
OrderPush(Disconnect); // a odczep już po zmianie kierunku
|
|
if( NewValue2 > 0.0
|
|
&& NewCommand == "Loose_shunt" ) {
|
|
// after decoupling continue pushing in the original direction
|
|
// NOTE: for backward compatibility this option isn't supported for basic shunting mode
|
|
iDirectionOrder = iDirection; // back to pushing
|
|
OrderPush( Change_direction );
|
|
}
|
|
}
|
|
else if (NewValue2 < 0.0) // jeśli wszystkie, a sprzęg ujemny, to tylko zmiana kierunku po podczepieniu
|
|
{ // np. Shunt -1 -3
|
|
iDirectionOrder = -iDirection; // jak się podczepi, to jazda w przeciwną stronę
|
|
OrderNext(Change_direction);
|
|
}
|
|
WaitingTime = 0.0; // nie ma co dalej czekać, można zatrąbić i jechać, chyba że już jedzie
|
|
}
|
|
else { // if (NewValue2==0.0) //zerowy sprzęg
|
|
if( NewValue1 >= 0.0 ) {
|
|
// jeśli ilość wagonów inna niż wszystkie będzie odczepianie,
|
|
// ale jeśli wagony są z przodu, to trzeba najpierw zmienić kierunek
|
|
if( mvOccupied->Couplers[mvOccupied->DirAbsolute > 0 ? end::rear : end::front].Connected == nullptr // z tyłu nic
|
|
&& mvOccupied->Couplers[mvOccupied->DirAbsolute > 0 ? end::front : end::rear].Connected != nullptr ) { // a z przodu skład
|
|
iDirectionOrder = -iDirection; // zmiana na ciągnięcie
|
|
OrderNext( Change_direction ); // najpierw zmień kierunek (zastąpi Disconnect)
|
|
OrderPush( Disconnect ); // a odczep już po zmianie kierunku
|
|
}
|
|
else if( mvOccupied->Couplers[ mvOccupied->DirAbsolute > 0 ? end::rear : end::front ].Connected != nullptr ) { // z tyłu coś
|
|
OrderNext( Disconnect ); // jak ciągnie, to tylko odczep (NewValue1) wagonów
|
|
}
|
|
else {
|
|
// both couplers empty
|
|
// NOTE: this condition implements legacy behavior (mis)used by some scenarios to keep vehicle idling without moving
|
|
SetVelocity( 0, 0, stopJoin );
|
|
iDrivigFlags |= moveStopHere; // nie podjeżdżać do semafora, jeśli droga nie jest wolna
|
|
}
|
|
WaitingTime = 0.0; // nie ma co dalej czekać, można zatrąbić i jechać, chyba że już jedzie
|
|
}
|
|
}
|
|
if (NewValue1 == -1.0) {
|
|
iDrivigFlags &= ~moveStopHere; // ma jechać
|
|
WaitingTime = 0.0; // nie ma co dalej czekać, można zatrąbić i jechać
|
|
}
|
|
if( NewValue1 < -1.5 ) { // jeśli -2/-3, czyli czekanie z ruszeniem na sygnał
|
|
iDrivigFlags |= moveStopHere; // nie podjeżdżać do semafora, jeśli droga nie jest wolna
|
|
}
|
|
// (nie dotyczy Connect)
|
|
if( NewValue1 < -2.5 ) { // jeśli -3 to potem jazda pociągowa
|
|
OrderNext( NewCommand == "Shunt" ? Obey_train : Bank );
|
|
}
|
|
else { // otherwise continue shunting
|
|
OrderNext( NewCommand == "Shunt" ? Shunt : Loose_shunt );
|
|
}
|
|
CheckVehicles(); // sprawdzić światła
|
|
iVehicleCount = std::floor( NewValue1 );
|
|
|
|
return true;
|
|
}
|
|
|
|
if( NewCommand == "Jump_to_first_order" ) {
|
|
JumpToFirstOrder();
|
|
return true;
|
|
}
|
|
|
|
if (NewCommand == "Jump_to_order")
|
|
{
|
|
if( NewValue1 == -1.0 ) {
|
|
JumpToNextOrder();
|
|
}
|
|
else if (NewValue1 >= 0 && NewValue1 < maxorders)
|
|
{
|
|
OrderPos = floor(NewValue1);
|
|
if( !OrderPos ) {
|
|
// zgodność wstecz: dopiero pierwsza uruchamia
|
|
OrderPos = 1;
|
|
}
|
|
#if LOGORDERS
|
|
OrdersDump("Jump_to_order");
|
|
#endif
|
|
}
|
|
return true;
|
|
}
|
|
|
|
if (NewCommand == "Warning_signal")
|
|
{
|
|
if( NewValue1 > 0 && NewValue2 > 0 ) {
|
|
fWarningDuration = NewValue1; // czas trąbienia
|
|
cue_action( driver_hint::hornon, NewValue2 ); // horn combination flag
|
|
simulation::Blackbox.horn_requested(
|
|
pVehicles[ end::front ], NewValue1, NewValue2, NewLocation != nullptr ? *NewLocation : pVehicles[ end::front ]->GetPosition() );
|
|
}
|
|
return true;
|
|
}
|
|
|
|
if (NewCommand == "Radio_channel") {
|
|
// wybór kanału radiowego (którego powinien używać AI, ręczny maszynista musi go ustawić sam)
|
|
if (NewValue1 >= 0) {
|
|
// wartości ujemne są zarezerwowane, -1 = nie zmieniać kanału
|
|
if( AIControllFlag ) {
|
|
iRadioChannel = NewValue1;
|
|
}
|
|
if( iGuardRadio ) {
|
|
// kierownikowi też zmienić
|
|
iGuardRadio = NewValue1;
|
|
}
|
|
}
|
|
// NewValue2 może zawierać dodatkowo oczekiwany kod odpowiedzi, np. dla W29 "nawiązać
|
|
// łączność radiową z dyżurnym ruchu odcinkowym"
|
|
return true;
|
|
}
|
|
|
|
if( NewCommand == "SetLights" ) {
|
|
// set consist lights pattern hints
|
|
m_lighthints[ end::front ] = static_cast<int>( NewValue1 );
|
|
m_lighthints[ end::rear ] = static_cast<int>( NewValue2 );
|
|
if( true == TestFlag( OrderCurrentGet(), Obey_train ) ) {
|
|
// light hints only apply in the obey_train mode
|
|
CheckVehicles();
|
|
}
|
|
return true;
|
|
}
|
|
|
|
if (NewCommand == "SetSignal") {
|
|
TSignals signal = (TSignals)std::lrint(NewValue1);
|
|
|
|
for (int i = Signal_START; i <= Signal_MAX; i++)
|
|
iDrivigFlags &= ~(1 << i);
|
|
|
|
if (NewValue2 > 0.5)
|
|
iDrivigFlags |= 1 << (uint32_t)signal;
|
|
else
|
|
CheckVehicles(); // restore light state
|
|
}
|
|
|
|
return false; // nierozpoznana - wysłać bezpośrednio do pojazdu
|
|
};
|
|
|
|
std::string_view TController::physicslog_header() {
|
|
// the columns of the readers of these logs, the Hasler tape of the starter among them, stay where they are:
|
|
// a new one goes at the end
|
|
return "Time[s] Velocity[m/s] Acceleration[m/ss] "
|
|
"Coupler.Dist[m] Coupler.Force[N] TractionForce[kN] FrictionForce[kN] BrakeForce[kN] "
|
|
"BrakePress[MPa] PipePress[MPa] MotorCurrent[A] "
|
|
"MCP SCP BCP LBP Direction Command CVal1 CVal2 "
|
|
"Security Wheelslip "
|
|
"EngineTemp[Deg] OilTemp[Deg] WaterTemp[Deg] WaterAuxTemp[Deg] "
|
|
"VehicleVelocity[km/h]"
|
|
"\r\n";
|
|
}
|
|
|
|
std::string TController::physicslog_line() const {
|
|
std::ostringstream line;
|
|
line << std::fixed << std::setprecision( 4 )
|
|
<< ElapsedTime << " "
|
|
<< fabs(11.31 * mvOccupied->WheelDiameter * mvOccupied->nrot) << " "
|
|
<< mvControlling->AccS << " "
|
|
<< mvOccupied->Couplers[1].Dist << " "
|
|
<< mvOccupied->Couplers[1].CForce << " "
|
|
<< mvOccupied->Ft << " "
|
|
<< mvOccupied->Ff << " "
|
|
<< mvOccupied->Fb << " "
|
|
<< mvOccupied->BrakePress << " "
|
|
<< mvOccupied->PipePress << " "
|
|
<< mvControlling->Im << " "
|
|
<< int(mvControlling->MainCtrlPos) << " "
|
|
<< int(mvControlling->ScndCtrlPos) << " "
|
|
<< mvOccupied->fBrakeCtrlPos << " "
|
|
<< mvOccupied->LocalBrakePosA << " "
|
|
<< int(mvControlling->DirActive) << " "
|
|
<< ( mvOccupied->CommandIn.Command.empty() ? "none" : mvOccupied->CommandIn.Command.c_str() ) << " "
|
|
<< mvOccupied->CommandIn.Value1 << " "
|
|
<< mvOccupied->CommandIn.Value2 << " "
|
|
<< int(mvControlling->SecuritySystem.is_blinking()) << " "
|
|
<< int(mvControlling->SlippingWheels) << " "
|
|
<< mvControlling->dizel_heat.Ts << " "
|
|
<< mvControlling->dizel_heat.To << " "
|
|
<< mvControlling->dizel_heat.temperatura1 << " "
|
|
<< mvControlling->dizel_heat.temperatura2 << " "
|
|
// vehicle speed [km/h], the second column is the wheel speed, which stays at 0 while the wheels are locked in a skid
|
|
<< mvOccupied->V * 3.6
|
|
<< "\r\n";
|
|
return line.str();
|
|
}
|
|
|
|
void TController::begin_physicslog()
|
|
{
|
|
// physicslog/<vehicle>.dat, written every two seconds along with the logs of the other drivers
|
|
#if LOGPRESS == 0
|
|
PhysicsLogs.begin( VehicleName, physicslog_header() );
|
|
#endif
|
|
#if LOGPRESS == 1
|
|
PhysicsLogs.begin( VehicleName, "t\tVel\tAcc\tPP\tVVP\tBP\tBVP\tCVP\n" );
|
|
#endif
|
|
PhysicsLogBegun = true;
|
|
}
|
|
|
|
void TController::PhysicsLog()
|
|
{ // zapis logu - na razie tylko wypisanie parametrów
|
|
#if LOGPRESS == 0
|
|
PhysicsLogs.append( VehicleName, physicslog_line() );
|
|
#endif
|
|
#if LOGPRESS == 1
|
|
std::ostringstream line;
|
|
line << ElapsedTime << "\t" << fabs(11.31 * mvOccupied->WheelDiameter * mvOccupied->nrot)
|
|
<< "\t";
|
|
line << mvControlling->AccS << "\t";
|
|
line << mvOccupied->PipePress << "\t" << mvOccupied->CntrlPipePress << "\t"
|
|
<< mvOccupied->BrakePress << "\t";
|
|
line << mvOccupied->Volume << "\t" << mvOccupied->Hamulec->GetCRP() << "\n";
|
|
PhysicsLogs.append( VehicleName, line.str() );
|
|
#endif
|
|
};
|
|
|
|
void
|
|
TController::Update( double const Timedelta ) {
|
|
// uruchamiać przynajmniej raz na sekundę
|
|
if( ( iDrivigFlags & movePrimary ) == 0 ) { return; } // pasywny nic nie robi
|
|
if( false == simulation::is_ready ) { return; }
|
|
|
|
update_timers( Timedelta );
|
|
update_logs( Timedelta );
|
|
|
|
auto const reactiontime { std::min( ReactionTime, 2.0 ) };
|
|
|
|
if( LastReactionTime < reactiontime ) { return; }
|
|
LastReactionTime -= reactiontime;
|
|
/*
|
|
// TBD, TODO: put this in an appropriate place, or get rid of it
|
|
// NOTE: this section moved all cars to the edge of their respective roads
|
|
// it may have some use eventually for collision avoidance,
|
|
// but when enabled all the time it produces silly effect
|
|
if( mvOccupied->Vel > 1.0 ) {
|
|
// przy prowadzeniu samochodu trzeba każdą oś odsuwać oddzielnie, inaczej kicha wychodzi
|
|
if (mvOccupied->CategoryFlag & 2) // jeśli samochód
|
|
// if (fabs(mvOccupied->OffsetTrackH)<mvOccupied->Dim.W) //Ra: szerokość drogi tu powinna być?
|
|
if (!mvOccupied->ChangeOffsetH(-0.01 * mvOccupied->Vel * dt)) // ruch w poprzek drogi
|
|
mvOccupied->ChangeOffsetH(0.01 * mvOccupied->Vel * dt); // Ra: co to miało być, to nie wiem
|
|
}
|
|
*/
|
|
update_hints();
|
|
// main ai update routine
|
|
determine_consist_state();
|
|
determine_braking_distance();
|
|
determine_proximity_ranges();
|
|
// vicinity check
|
|
auto const awarenessrange {
|
|
std::max(
|
|
750.0,
|
|
mvOccupied->Vel > EU07_AI_MOVEMENT ?
|
|
400 + fBrakeDist :
|
|
30.0 * fDriverDist ) }; // 1500m dla stojących pociągów;
|
|
if( is_active() ) {
|
|
scan_route( awarenessrange );
|
|
}
|
|
scan_obstacles( awarenessrange );
|
|
// generic actions
|
|
control_security_system( reactiontime );
|
|
if( iEngineActive ) {
|
|
control_wheelslip();
|
|
control_horns( reactiontime );
|
|
control_pantographs();
|
|
if( fActionTime > 0.0 ) {
|
|
// potentially delayed and/or low priority actions
|
|
control_lights();
|
|
control_doors();
|
|
control_compartment_lights();
|
|
}
|
|
}
|
|
CheckTimeControllers();
|
|
// external command actions
|
|
UpdateCommand();
|
|
// mode specific actions
|
|
handle_engine();
|
|
handle_orders();
|
|
// a brake the wagon inspector left to cut out while the train was moving
|
|
reinspect_brakes();
|
|
// situational velocity and acceleration adjustments
|
|
pick_optimal_speed( awarenessrange );
|
|
if( iEngineActive ) {
|
|
control_tractive_and_braking_force();
|
|
}
|
|
SetTimeControllers();
|
|
}
|
|
|
|
// configures vehicle heating given current situation; returns: true if vehicle can be operated normally, false otherwise
|
|
bool
|
|
TController::PrepareHeating() {
|
|
|
|
switch( mvControlling->EngineType ) {
|
|
|
|
case TEngineType::DieselElectric:
|
|
case TEngineType::DieselEngine: {
|
|
|
|
auto const &heat { mvControlling->dizel_heat };
|
|
|
|
// determine whether there's need to enable the water heater
|
|
// if the heater has configured maximum temperature, it'll disable itself automatically, so we can leave it always running
|
|
// otherwise enable the heater only to maintain minimum required temperature
|
|
auto const lowtemperature { (
|
|
( heat.water.config.temp_min > 0 && heat.temperatura1 < heat.water.config.temp_min + (mvControlling->WaterHeater.is_active ? 5 : 0) )
|
|
|| ( heat.water_aux.config.temp_min > 0 && heat.temperatura2 < heat.water_aux.config.temp_min + (mvControlling->WaterHeater.is_active ? 5 : 0) )
|
|
|| ( heat.oil.config.temp_min > 0 && heat.To < heat.oil.config.temp_min + (mvControlling->WaterHeater.is_active ? 5 : 0) ) ) };
|
|
auto const heateron { (
|
|
mvControlling->WaterHeater.config.temp_max > 0
|
|
|| true == lowtemperature ) };
|
|
if( true == heateron ) {
|
|
// make sure the water pump is running before enabling the heater
|
|
if( false == mvControlling->WaterPump.is_active ) {
|
|
cue_action( driver_hint::waterpumpbreakeron );
|
|
cue_action( driver_hint::waterpumpon );
|
|
}
|
|
if( true == mvControlling->WaterPump.is_active ) {
|
|
cue_action( driver_hint::waterheaterbreakeron );
|
|
cue_action( driver_hint::waterheateron );
|
|
cue_action( driver_hint::watercircuitslinkon );
|
|
}
|
|
}
|
|
else {
|
|
// no need to heat anything up, switch the heater off
|
|
cue_action( driver_hint::watercircuitslinkoff );
|
|
cue_action( driver_hint::waterheateroff );
|
|
cue_action( driver_hint::waterheaterbreakeroff );
|
|
// optionally turn off the water pump as well
|
|
if( mvControlling->WaterPump.start_type != start_t::battery ) {
|
|
cue_action( driver_hint::waterpumpoff );
|
|
cue_action( driver_hint::waterpumpbreakeroff );
|
|
}
|
|
}
|
|
|
|
IsHeatingTemperatureTooLow = lowtemperature;
|
|
break;
|
|
}
|
|
default: {
|
|
IsHeatingTemperatureTooLow = false;
|
|
break;
|
|
}
|
|
}
|
|
// TBD, TODO: potentially pay attention to too high temperature as well?
|
|
IsHeatingTemperatureOK = false == IsHeatingTemperatureTooLow;
|
|
|
|
return IsHeatingTemperatureOK;
|
|
}
|
|
|
|
void
|
|
TController::PrepareDirection() {
|
|
|
|
if( iDirection == 0 ) {
|
|
// jeśli nie ma ustalonego kierunku
|
|
if( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) { // ustalenie kierunku, gdy stoi
|
|
iDirection = mvOccupied->CabActive; // wg wybranej kabiny
|
|
/*
|
|
if( iDirection == 0 ) {
|
|
// jeśli nie ma ustalonego kierunku
|
|
if( mvOccupied->Couplers[ end::rear ].Connected == nullptr ) {
|
|
// jeśli z tyłu nie ma nic
|
|
iDirection = -1; // jazda w kierunku sprzęgu 1
|
|
}
|
|
if( mvOccupied->Couplers[ end::front ].Connected == nullptr ) {
|
|
// jeśli z przodu nie ma nic
|
|
iDirection = 1; // jazda w kierunku sprzęgu 0
|
|
}
|
|
}
|
|
*/
|
|
}
|
|
else {
|
|
// ustalenie kierunku, gdy jedzie
|
|
iDirection = mvOccupied->V >= 0 ? 1 : // jazda w kierunku sprzęgu 0
|
|
-1; // jazda w kierunku sprzęgu 1
|
|
}
|
|
}
|
|
cue_action( driver_hint::mastercontrollersetreverserunlock );
|
|
cue_action(
|
|
iDirection > 0 ?
|
|
driver_hint::directionforward :
|
|
driver_hint::directionbackward );
|
|
}
|
|
|
|
void TController::JumpToNextOrder( bool const Ignoremergedchangedirection )
|
|
{ // wykonanie kolejnej komendy z tablicy rozkazów
|
|
if (auto const currentorder { OrderCurrentGet() }; currentorder != Wait_for_orders)
|
|
{
|
|
if( (currentorder & Change_direction) != 0 // jeśli zmiana kierunku
|
|
&& currentorder != Change_direction && false == Ignoremergedchangedirection ) { // ale nałożona na coś
|
|
|
|
// usunięcie zmiany kierunku z innej komendy
|
|
OrderCurrentSet( TOrders(currentorder & ~Change_direction) );
|
|
OrderCheck();
|
|
return;
|
|
}
|
|
if (OrderPos < maxorders - 1)
|
|
++OrderPos;
|
|
else
|
|
OrderPos = 0;
|
|
}
|
|
OrderCheck();
|
|
#if LOGORDERS
|
|
OrdersDump("JumpToNextOrder"); // normalnie nie ma po co tego wypisywać
|
|
#endif
|
|
};
|
|
|
|
void TController::JumpToFirstOrder()
|
|
{ // taki relikt
|
|
OrderPos = 1;
|
|
if (OrderTop == 0)
|
|
OrderTop = 1;
|
|
OrderCheck();
|
|
#if LOGORDERS
|
|
OrdersDump("JumpToFirstOrder"); // normalnie nie ma po co tego wypisywać
|
|
#endif
|
|
};
|
|
|
|
void TController::OrderCheck()
|
|
{ // reakcja na zmianę rozkazu
|
|
|
|
if( OrderCurrentGet() != Obey_train ) {
|
|
// reset light hints
|
|
m_lighthints[ end::front ] = m_lighthints[ end::rear ] = -1;
|
|
}
|
|
if( OrderCurrentGet() & ( Shunt | Loose_shunt | Connect | Obey_train | Bank ) ) {
|
|
CheckVehicles(); // sprawdzić światła
|
|
}
|
|
if( OrderCurrentGet() & ( Shunt | Loose_shunt | Connect ) ) {
|
|
// HACK: ensure consist doors will be closed on departure
|
|
iDrivigFlags |= moveDoorOpened;
|
|
}
|
|
auto const currentorder { OrderCurrentGet() };
|
|
if (currentorder & Change_direction) // może być nałożona na inną i wtedy ma priorytet
|
|
iDirectionOrder = -iDirection; // trzeba zmienić jawnie, bo się nie domyśli
|
|
else if (currentorder == Obey_train)
|
|
iDrivigFlags |= moveStopPoint; // W4 są widziane
|
|
else if (currentorder == Disconnect)
|
|
iVehicleCount = iVehicleCount < 0 ? 0 : iVehicleCount; // odczepianie lokomotywy
|
|
else if (currentorder == Connect)
|
|
iDrivigFlags &= ~moveStopPoint; // podczas jazdy na połączenie nie zwracać uwagi na W4
|
|
else if (currentorder == Wait_for_orders)
|
|
OrdersClear(); // czyszczenie rozkazów i przeskok do zerowej pozycji
|
|
}
|
|
|
|
void TController::OrderNext(TOrders NewOrder)
|
|
{ // ustawienie rozkazu do wykonania jako następny
|
|
if (OrderCurrentGet() == NewOrder)
|
|
return; // jeśli robi to, co trzeba, to koniec
|
|
if (!OrderPos)
|
|
OrderPos = 1; // na pozycji zerowej pozostaje czekanie
|
|
OrderTop = OrderPos; // ale może jest czymś zajęty na razie
|
|
if (NewOrder >= Shunt) // jeśli ma jechać
|
|
{ // ale może być zajęty chwilowymi operacjami
|
|
while (OrderTop >= 0 && OrderTop < maxorders - 1
|
|
&& OrderList[OrderTop] != Wait_for_orders && OrderList[OrderTop] < Shunt) // jeśli coś robi
|
|
++OrderTop; // pomijamy wszystkie tymczasowe prace
|
|
}
|
|
else
|
|
{ // jeśli ma ustawioną jazdę, to wyłączamy na rzecz operacji
|
|
while (OrderTop >= 0 && OrderTop < maxorders - 1
|
|
&& OrderList[OrderTop] != Wait_for_orders && OrderList[OrderTop] < Shunt && OrderList[OrderTop] != NewOrder) // jeśli coś robi
|
|
++OrderTop; // pomijamy wszystkie tymczasowe prace
|
|
}
|
|
if (OrderTop < 0 || OrderTop >= maxorders)
|
|
{
|
|
ErrorLog("Commands overflow: order \"" + Order2Str(NewOrder) + "\" dropped");
|
|
return;
|
|
}
|
|
OrderList[OrderTop++] = NewOrder; // dodanie rozkazu jako następnego
|
|
#if LOGORDERS
|
|
OrdersDump( "OrderNext" ); // normalnie nie ma po co tego wypisywać
|
|
#endif
|
|
}
|
|
|
|
void TController::OrderPush(TOrders NewOrder)
|
|
{ // zapisanie na stosie kolejnego rozkazu do wykonania
|
|
if (OrderPos == OrderTop && OrderCurrentGet() < Shunt) // jeśli miałby być zapis na aktalnej pozycji
|
|
// ale nie jedzie
|
|
++OrderTop;
|
|
// niektóre operacje muszą zostać najpierw dokończone => zapis na kolejnej
|
|
if (OrderTop < 0 || OrderTop >= maxorders)
|
|
{
|
|
ErrorLog("Commands overflow: order \"" + Order2Str(NewOrder) + "\" dropped");
|
|
return;
|
|
}
|
|
if (OrderList[OrderTop] != NewOrder) // jeśli jest to samo, to nie dodajemy
|
|
OrderList[OrderTop++] = NewOrder; // dodanie rozkazu na stos
|
|
#if LOGORDERS
|
|
OrdersDump( "OrderPush: [" + Order2Str( NewOrder ) + "]" ); // normalnie nie ma po co tego wypisywać
|
|
#endif
|
|
}
|
|
|
|
void TController::OrdersDump( std::string const Neworder, bool const Verbose )
|
|
{ // wypisanie kolejnych rozkazów do logu
|
|
WriteLog( "New order for [" + pVehicle->asName + "]: " + Neworder );
|
|
if( false == Verbose ) { return; }
|
|
for (int b = 0; b < maxorders; ++b)
|
|
{
|
|
WriteLog( ( OrderPos == b ? ">" : " " ) + (std::to_string(b) + ": " + Order2Str(OrderList[b])));
|
|
if (b && OrderList[b] == Wait_for_orders) // z wyjątkiem pierwszej pozycji
|
|
// jeśli końcowa komenda
|
|
break;
|
|
// dalej nie trzeba
|
|
}
|
|
};
|
|
|
|
void TController::OrdersInit(double fVel)
|
|
{ // wypełnianie tabelki rozkazów na podstawie rozkładu
|
|
// ustawienie kolejności komend, niezależnie kto prowadzi
|
|
OrdersClear(); // usunięcie poprzedniej tabeli
|
|
OrderPush(Prepare_engine); // najpierw odpalenie silnika
|
|
if (TrainParams.StationCount == 0)
|
|
{ // brak rozkładu to jazda manewrowa
|
|
// if (fVel > 0.05) // typowo 0.1 oznacza gotowość do jazdy, 0.01 tylko załączenie silnika
|
|
OrderPush(Shunt); // jeśli nie ma rozkładu, to manewruje
|
|
}
|
|
else
|
|
{ // jeśli z rozkładem, to jedzie na szlak
|
|
if (fVel > 0.0 && fVel < 0.02)
|
|
OrderPush(Shunt); // dla prędkości 0.01 włączamy jazdę manewrową
|
|
else if (TrainParams.DirectionChange() ? // jeśli obrót na pierwszym przystanku
|
|
(iDrivigFlags & movePushPull ? // SZT również! SN61 zależnie od wagonów...
|
|
TrainParams.TimeTable[1].StationName == TrainParams.Relation1 :
|
|
false) :
|
|
false)
|
|
OrderPush(Shunt); // a teraz start będzie w manewrowym, a tryb pociągowy włączy W4
|
|
else
|
|
// jeśli start z pierwszej stacji i jednocześnie jest na niej zmiana kierunku, to EZT ma mieć Shunt
|
|
OrderPush(Obey_train); // dla starych scenerii start w trybie pociagowym
|
|
if (DebugModeFlag) // normalnie nie ma po co tego wypisywać
|
|
WriteLog("/* Timetable: " + TrainParams.ShowRelation());
|
|
TMTableLine *t;
|
|
for (int i = 0; i <= TrainParams.StationCount; ++i)
|
|
{
|
|
t = TrainParams.TimeTable + i;
|
|
if (DebugModeFlag) {
|
|
// normalnie nie ma po co tego wypisywa?
|
|
WriteLog(
|
|
t->StationName
|
|
+ " " + std::to_string(t->Ah) + ":" + std::to_string(t->Am)
|
|
+ ", " + std::to_string(t->Dh) + ":" + std::to_string(t->Dm)
|
|
+ " " + t->StationWare);
|
|
}
|
|
if ( contains( t->StationWare, '@' ) )
|
|
{ // zmiana kierunku i dalsza jazda wg rozk?adu
|
|
if (iDrivigFlags & movePushPull) // SZT również! SN61 zależnie od wagonów...
|
|
{ // jeśli skład zespolony, wystarczy zmienić kierunek jazdy
|
|
OrderPush(Change_direction); // zmiana kierunku
|
|
}
|
|
else
|
|
{ // dla zwykłego składu wagonowego odczepiamy lokomotywę
|
|
OrderPush(Disconnect); // odczepienie lokomotywy
|
|
OrderPush(Shunt); // a dalej manewry
|
|
}
|
|
if (i < TrainParams.StationCount) // jak nie ostatnia stacja
|
|
OrderPush(Obey_train); // to dalej wg rozkładu
|
|
}
|
|
}
|
|
if( DebugModeFlag ) {
|
|
// normalnie nie ma po co tego wypisywać
|
|
WriteLog( "*/" );
|
|
}
|
|
OrderPush(Shunt); // po wykonaniu rozkładu przełączy się na manewry
|
|
}
|
|
// McZapkie-100302 - to ma byc wyzwalane ze scenerii
|
|
if( fVel == 0.0 ) {
|
|
// jeśli nie ma prędkości początkowej, to śpi
|
|
SetVelocity( 0, 0, stopSleep );
|
|
}
|
|
else {
|
|
// jeśli podana niezerowa prędkość
|
|
if( fVel >= 1.0
|
|
|| fVel < 0.02 ) {
|
|
// jeśli ma jechać - dla 0.01 ma podjechać manewrowo po podaniu sygnału
|
|
// to do następnego W4 ma podjechać blisko
|
|
iDrivigFlags = iDrivigFlags & ~moveStopHere | moveStopCloser;
|
|
}
|
|
else {
|
|
// czekać na sygnał
|
|
iDrivigFlags |= moveStopHere;
|
|
}
|
|
JumpToFirstOrder();
|
|
if (fVel >= 1.0) // jeśli ma jechać
|
|
SetVelocity(fVel, -1); // ma ustawić żądaną prędkość
|
|
else
|
|
SetVelocity(0, 0, stopSleep); // prędkość w przedziale (0;1) oznacza, że ma stać
|
|
}
|
|
#if LOGORDERS
|
|
OrdersDump( "OrdersInit", DebugModeFlag ); // wypisanie kontrolne tabelki rozkazów
|
|
#endif
|
|
// McZapkie! - zeby w ogole AI ruszyl to musi wykonac powyzsze rozkazy
|
|
// Ale mozna by je zapodac ze scenerii
|
|
};
|
|
|
|
std::string TController::StopReasonText() const
|
|
{ // informacja tekstowa o przyczynie zatrzymania
|
|
if (eStopReason != 7) // zawalidroga będzie inaczej
|
|
return StopReasonTable[eStopReason];
|
|
else
|
|
return "Blocked by " + pVehicles[0]->PrevAny()->name();
|
|
};
|
|
|
|
//----------------------------------------------------------------------------------------------------------------------
|
|
// McZapkie: skanowanie semaforów
|
|
// Ra: stare funkcje skanujące, używane podczas manewrów do szukania sygnalizatora z tyłu
|
|
//- nie reagują na PutValues, bo nie ma takiej potrzeby
|
|
//- rozpoznają tylko zerową prędkość (jako koniec toru i brak podstaw do dalszego skanowania)
|
|
//----------------------------------------------------------------------------------------------------------------------
|
|
|
|
bool TController::IsOccupiedByAnotherConsist( TTrack *Track, double const Distance = 0 )
|
|
{ // najpierw sprawdzamy, czy na danym torze są pojazdy z innego składu
|
|
if( false == Track->Dynamics.empty() ) {
|
|
for( auto dynamic : Track->Dynamics ) {
|
|
if( dynamic->ctOwner != this ) {
|
|
// jeśli jest jakiś cudzy to tor jest zajęty i skanowanie nie obowiązuje
|
|
if( Distance == 0 ) {
|
|
return true;
|
|
}
|
|
else {
|
|
// based on provided position of scanning vehicle and scan direction, filter out vehicles on irrelevant end
|
|
auto const scandirection { Distance > 0 ? 1 : -1 }; // positive value means scan towards point2 end of the track
|
|
auto const obstaclelocation { scandirection > 0 ? Track->Length() - dynamic->RaTranslationGet() : dynamic->RaTranslationGet() };
|
|
// if detected vehicle is closer to the end of the track in scanned direction than we are, it means it's blocking our way
|
|
if( obstaclelocation < std::abs( Distance ) ) {
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return false; // wolny
|
|
};
|
|
|
|
basic_event * TController::CheckTrackEventBackward(double fDirection, TTrack *Track, TDynamicObject *Vehicle, int const Eventdirection, end const End)
|
|
{ // sprawdzanie eventu w torze, czy jest sygnałowym - skanowanie do tyłu
|
|
// NOTE: this method returns only one event which meets the conditions, due to limitations in the caller
|
|
// TBD, TODO: clean up the caller and return all suitable events, as in theory things will go awry if the track has more than one signal
|
|
auto const dir{ Vehicle->VectorFront() * (double)Vehicle->DirectionGet() };
|
|
auto const pos{ End == end::front ? Vehicle->RearPosition() : Vehicle->HeadPosition() };
|
|
auto const &eventsequence { ( fDirection * Eventdirection > 0 ? Track->m_events2 : Track->m_events1 ) };
|
|
for( auto const &event : eventsequence ) {
|
|
if( event.second != nullptr
|
|
&& event.second->m_passive
|
|
&& typeid(*event.second) == typeid(getvalues_event) ) {
|
|
// since we're checking for events behind us discard the sources in front of the scanning vehicle
|
|
auto const sl{ event.second->input_location() }; // położenie komórki pamięci
|
|
auto const sem{ sl - pos }; // wektor do komórki pamięci od końca składu
|
|
auto const isahead { dir.x * sem.x + dir.z * sem.z > 0 };
|
|
if( End == end::front ? isahead : !isahead ) {
|
|
// iloczyn skalarny jest ujemny, gdy sygnał stoi z tyłu
|
|
return event.second;
|
|
}
|
|
}
|
|
}
|
|
return nullptr;
|
|
};
|
|
|
|
TTrack * TController::BackwardTraceRoute(double &fDistance, double &fDirection, TDynamicObject *Vehicle, basic_event *&Event, int const Eventdirection, end const End, bool const Untiloccupied )
|
|
{ // szukanie sygnalizatora w kierunku przeciwnym jazdy (eventu odczytu komórki pamięci)
|
|
auto *Track = Vehicle->GetTrack();
|
|
double fCurrentDistance = Vehicle->RaTranslationGet(); // aktualna pozycja na torze
|
|
if (fDirection > 0) // jeśli w kierunku Point2 toru
|
|
fCurrentDistance = Track->Length() - fCurrentDistance;
|
|
double s = 0;
|
|
|
|
if( Track->VelocityGet() == 0.0 ) { // jak prędkosć 0 albo uszkadza, to nie ma po co skanować
|
|
fDistance = s; // to na tym torze stoimy
|
|
return nullptr; // stop, skanowanie nie dało sensownych rezultatów
|
|
}
|
|
// jak tor zajęty innym składem, to nie ma po co skanować
|
|
if( Untiloccupied && IsOccupiedByAnotherConsist( Track, fCurrentDistance * fDirection ) ) {
|
|
fDistance = s; // to na tym torze stoimy
|
|
return nullptr; // stop, skanowanie nie dało sensownych rezultatów
|
|
}
|
|
if ((Event = CheckTrackEventBackward(fDirection, Track, Vehicle, Eventdirection, End)) != nullptr)
|
|
{ // jeśli jest semafor na tym torze
|
|
fDistance = s; // to na tym torze stoimy
|
|
return Track;
|
|
}
|
|
TTrack *pTrackFrom; // odcinek poprzedni, do znajdywania końca dróg
|
|
while (s < fDistance)
|
|
{
|
|
// Track->ScannedFlag=true; //do pokazywania przeskanowanych torów
|
|
pTrackFrom = Track; // zapamiętanie aktualnego odcinka
|
|
s += fCurrentDistance; // doliczenie kolejnego odcinka do przeskanowanej długości
|
|
if (fDirection > 0)
|
|
{ // jeśli szukanie od Point1 w kierunku Point2
|
|
if (Track->iNextDirection)
|
|
fDirection = -fDirection;
|
|
Track = Track->CurrentNext(); // może być NULL
|
|
}
|
|
else // if (fDirection<0)
|
|
{ // jeśli szukanie od Point2 w kierunku Point1
|
|
if (!Track->iPrevDirection)
|
|
fDirection = -fDirection;
|
|
Track = Track->CurrentPrev(); // może być NULL
|
|
}
|
|
if (Track == pTrackFrom)
|
|
Track = nullptr; // koniec, tak jak dla torów
|
|
|
|
// gdy dalej toru nie ma albo zerowa prędkość, albo uszkadza pojazd
|
|
// zwraca NULL, że skanowanie nie dało sensownych rezultatów
|
|
if( Track == nullptr ) {
|
|
fDistance = s;
|
|
return nullptr;
|
|
}
|
|
if( Track->VelocityGet() == 0.0 )
|
|
{
|
|
fDistance = s;
|
|
return nullptr;
|
|
}
|
|
if( Untiloccupied && IsOccupiedByAnotherConsist( Track ) ) {
|
|
fDistance = s;
|
|
return nullptr;
|
|
}
|
|
fCurrentDistance = Track->Length();
|
|
if ((Event = CheckTrackEventBackward(fDirection, Track, Vehicle, Eventdirection, End)) != nullptr)
|
|
{ // znaleziony tor z eventem
|
|
fDistance = s;
|
|
return Track;
|
|
}
|
|
}
|
|
Event = nullptr; // jak dojdzie tu, to nie ma semafora
|
|
// zwraca ostatni sprawdzony tor
|
|
fDistance = s;
|
|
return Track;
|
|
}
|
|
|
|
// sprawdzanie zdarzeń semaforów i ograniczeń szlakowych
|
|
void TController::SetProximityVelocity( double dist, double vel, glm::dvec3 const *pos )
|
|
{ // Ra:przeslanie do AI prędkości
|
|
/*
|
|
//!!!! zastąpić prawidłową reakcją AI na SetProximityVelocity !!!!
|
|
if (vel==0)
|
|
{//jeśli zatrzymanie, to zmniejszamy dystans o 10m
|
|
dist-=10.0;
|
|
};
|
|
if (dist<0.0) dist=0.0;
|
|
if ((vel<0)?true:dist>0.1*(MoverParameters->Vel*MoverParameters->Vel-vel*vel)+50)
|
|
{//jeśli jest dalej od umownej drogi hamowania
|
|
*/
|
|
PutCommand( "SetProximityVelocity", dist, vel, pos );
|
|
/*
|
|
}
|
|
else
|
|
{//jeśli jest zagrożenie, że przekroczy
|
|
Mechanik->SetVelocity(floor(0.2*sqrt(dist)+vel),vel,stopError);
|
|
}
|
|
*/
|
|
}
|
|
|
|
TCommandType TController::BackwardScan( double const Range )
|
|
{ // sprawdzanie zdarzeń semaforów z tyłu pojazdu, zwraca komendę
|
|
// dzięki temu będzie można stawać za wskazanym sygnalizatorem, a zwłaszcza jeśli będzie jazda na kozioł
|
|
// ograniczenia prędkości nie są wtedy istotne, również koniec toru jest do niczego nie przydatny
|
|
// zwraca true, jeśli należy odwrócić kierunek jazdy pojazdu
|
|
if( OrderCurrentGet() & ~(Shunt | Loose_shunt | Connect) ) {
|
|
// skanowanie sygnałów tylko gdy jedzie w trybie manewrowym albo czeka na rozkazy
|
|
return TCommandType::cm_Unknown;
|
|
}
|
|
// kierunek jazdy względem sprzęgów pojazdu na czele
|
|
int const startdir = -pVehicles[0]->DirectionGet();
|
|
if( startdir == 0 ) {
|
|
// jeśli kabina i kierunek nie jest określony nie robimy nic
|
|
return TCommandType::cm_Unknown;
|
|
}
|
|
// szukamy od pierwszej osi w wybranym kierunku
|
|
double scandir = startdir * pVehicles[0]->RaDirectionGet();
|
|
|
|
if( scandir == 0.0 ) { return TCommandType::cm_Unknown; }
|
|
|
|
// skanowanie toru w poszukiwaniu eventów GetValues (PutValues nie są przydatne)
|
|
// Ra: przy wstecznym skanowaniu prędkość nie ma znaczenia
|
|
double scandist = Range; // zmodyfikuje na rzeczywiście przeskanowane
|
|
basic_event *e = nullptr; // event potencjalnie od semafora
|
|
// opcjonalnie może być skanowanie od "wskaźnika" z przodu, np. W5, Tm=Ms1, koniec toru wg
|
|
// drugiej osi w kierunku ruchu
|
|
auto const *scantrack{BackwardTraceRoute(scandist, scandir, pVehicles[end::front], e)};
|
|
auto const dir{(double)startdir *
|
|
pVehicles[end::front]->VectorFront()}; // wektor w kierunku jazdy/szukania
|
|
|
|
// jeśli wstecz wykryto koniec toru to raczej nic się nie da w takiej sytuacji zrobić
|
|
if (e == nullptr)
|
|
{
|
|
return TCommandType::cm_Unknown;
|
|
}
|
|
if (typeid(*e) != typeid(getvalues_event))
|
|
{
|
|
return TCommandType::cm_Unknown;
|
|
}
|
|
|
|
// jeśli jest jakiś sygnał na widoku
|
|
double scanvel; // prędkość ustawiona semaforem
|
|
#if LOGBACKSCAN
|
|
std::string edir{"Backward scan by " + pVehicle->asName + " - " +
|
|
((scandir > 0) ? "Event2 " : "Event1 ")};
|
|
edir += "(" + (e->name()) + ")";
|
|
#endif
|
|
{
|
|
// najpierw sprawdzamy, czy semafor czy inny znak został przejechany
|
|
auto const sl{e->input_location()}; // położenie komórki pamięci
|
|
auto const pos{pVehicles[end::rear]->RearPosition()}; // pozycja tyłu
|
|
if (auto const sem{sl - pos}; dir.x * sem.x + dir.z * sem.z < 0) // wektor do komórki pamięci od końca składu
|
|
{
|
|
// jeśli został minięty
|
|
// iloczyn skalarny jest ujemny, gdy sygnał stoi z tyłu
|
|
#if LOGBACKSCAN
|
|
WriteLog(edir + " - ignored as not passed yet");
|
|
#endif
|
|
return TCommandType::cm_Unknown; // nic
|
|
}
|
|
scanvel = e->input_value(1); // prędkość przy tym semaforze
|
|
#if LOGBACKSCAN
|
|
// przeliczamy odległość od semafora - potrzebne by były współrzędne początku składu
|
|
scandist = std::max(glm::length(sl - pos) - 2.0, 0.0); // 2m luzu przy manewrach wystarczy, ujemnych nie ma po co wysyłać
|
|
#endif
|
|
}
|
|
|
|
auto move{false}; // czy AI w trybie manewerowym ma dociągnąć pod S1
|
|
if (e->input_command() == TCommandType::cm_SetVelocity)
|
|
{
|
|
if (scanvel == 0.0 ? OrderCurrentGet() & (Shunt | Loose_shunt | Connect) :
|
|
OrderCurrentGet() & Connect)
|
|
{ // przy podczepianiu ignorować wyjazd?
|
|
move = true; // AI w trybie manewerowym ma dociągnąć pod S1
|
|
}
|
|
else
|
|
{
|
|
// jeśli semafor jest daleko, a pojazd jedzie, to informujemy o zmianie prędkości
|
|
// jeśli jedzie manewrowo, musi dostać SetVelocity, żeby sie na pociągowy przełączył
|
|
// w przeciwnym razie ustawiamy prędkość tylko wtedy, gdy ma ruszyć, stanąć albo ma stać
|
|
// ruszać stop trzeba powtarzać, bo inaczej zatrąbi i pojedzie sam
|
|
#if LOGBACKSCAN
|
|
if (scandist > fMinProximityDist &&
|
|
mvOccupied->Vel > EU07_AI_NOMOVEMENT && (OrderCurrentGet() & (Shunt | Loose_shunt)) == 0)
|
|
{
|
|
WriteLog(edir);
|
|
}
|
|
else
|
|
{
|
|
WriteLog(edir + " - [SetVelocity] [" + to_string(scanvel, 2) + "] [" +
|
|
to_string(e->input_value(2), 2) + "]");
|
|
}
|
|
#endif
|
|
return scanvel > 0 ? TCommandType::cm_SetVelocity : TCommandType::cm_Unknown;
|
|
}
|
|
}
|
|
// reakcja AI w trybie manewrowym dodatkowo na sygnały manewrowe
|
|
if ((OrderCurrentGet() ? OrderCurrentGet() & (Shunt | Loose_shunt | Connect) : true) && (move || e->input_command() == TCommandType::cm_ShuntVelocity)) // w Wait_for_orders też widzi tarcze
|
|
{
|
|
// jeśli powyżej było SetVelocity 0 0, to dociągamy pod S1
|
|
/*
|
|
if ((scandist > fMinProximityDist) &&
|
|
((mvOccupied->Vel > EU07_AI_NOMOVEMENT) || (scanvel == 0.0)))
|
|
{
|
|
// jeśli tarcza jest daleko, to:
|
|
//- jesli pojazd jedzie, to informujemy o zmianie prędkości
|
|
//- jeśli stoi, to z własnej inicjatywy może podjechać pod zamkniętą tarczę
|
|
if (mvOccupied->Vel > EU07_AI_NOMOVEMENT) // tylko jeśli jedzie
|
|
{ // Mechanik->PutCommand("SetProximityVelocity",scandist,scanvel,sl);
|
|
#if LOGBACKSCAN
|
|
// WriteLog(edir+"SetProximityVelocity "+AnsiString(scandist)+"
|
|
// "+AnsiString(scanvel));
|
|
WriteLog(edir);
|
|
#endif
|
|
// SetProximityVelocity(scandist,scanvel,&sl);
|
|
// jeśli jedzie na W5 albo koniec toru, to można zmienić kierunek
|
|
return (iDrivigFlags & moveTrackEnd) ? TCommandType::cm_ChangeDirection :
|
|
TCommandType::cm_Unknown;
|
|
// TBD: request direction change also if VelNext in current direction is 0,
|
|
// while signal behind requests movement?
|
|
}
|
|
}
|
|
else
|
|
{
|
|
// ustawiamy prędkość tylko wtedy, gdy ma ruszyć, albo stanąć albo ma stać pod
|
|
// tarczą stop trzeba powtarzać, bo inaczej zatrąbi i pojedzie sam if
|
|
// ((MoverParameters->Vel==0.0)||(scanvel==0.0)) //jeśli jedzie lub ma stanąć/stać
|
|
{ // nie dostanie komendy jeśli jedzie i ma jechać
|
|
// PutCommand("ShuntVelocity",scanvel,e->Params[9].asMemCell->Value2(),&sl,stopSem);
|
|
#if LOGBACKSCAN
|
|
WriteLog(edir + " - [ShuntVelocity] [" + to_string(scanvel, 2) + "] [" +
|
|
to_string(e->input_value(2), 2) + "]");
|
|
#endif
|
|
return (scanvel > 0 ? TCommandType::cm_ShuntVelocity :
|
|
TCommandType::cm_Unknown);
|
|
}
|
|
}
|
|
// NOTE: dead code due to returns in branching above
|
|
if ((scanvel != 0.0) && (scandist < 100.0))
|
|
{
|
|
// jeśli Tm w odległości do 100m podaje zezwolenie na jazdę, to od razu ją
|
|
// ignorujemy, aby móc szukać kolejnej eSignSkip=e; //wtedy uznajemy ignorowaną przy
|
|
// poszukiwaniu nowej
|
|
#if LOGBACKSCAN
|
|
WriteLog(edir + " - will be ignored due to Ms2");
|
|
#endif
|
|
return (scanvel > 0 ? TCommandType::cm_ShuntVelocity : TCommandType::cm_Unknown);
|
|
}
|
|
*/
|
|
return VelNext > 0 ?
|
|
TCommandType::cm_Unknown : // no need to bother if we can continue in current direction
|
|
scanvel == 0 ?
|
|
TCommandType::cm_Unknown : // no need to bother with a stop signal
|
|
TCommandType::cm_ShuntVelocity; // otherwise report a relevant shunt signal behind
|
|
// if (move?...
|
|
} // if (OrderCurrentGet()==Shunt)
|
|
|
|
return e->m_passive && e->is_command() ? TCommandType::cm_Command : TCommandType::cm_Unknown;
|
|
};
|
|
|
|
std::string TController::NextStop() const
|
|
{ // informacja o następnym zatrzymaniu, wyświetlane pod [F1]
|
|
if (asNextStop == "[End of route]")
|
|
return ""; // nie zawiera nazwy stacji, gdy dojechał do końca
|
|
// dodać godzinę odjazdu
|
|
// the name the way the timetable spells it, in utf-8 as the user interface takes it
|
|
auto nextstop{ TrainParams.station_caption( asNextStop ) };
|
|
auto const *t{ TrainParams.TimeTable + TrainParams.StationIndex };
|
|
if( t->Ah >= 0 ) {
|
|
// przyjazd
|
|
nextstop += " przyj." + std::to_string( t->Ah ) + ":"
|
|
+ to_minutes_str( t->Am, true, 3 );
|
|
|
|
}
|
|
if( t->Dh >= 0 ) {
|
|
// jeśli jest godzina odjazdu
|
|
nextstop += " odj." + std::to_string( t->Dh ) + ":"
|
|
+ to_minutes_str( t->Dm, true, 3 );
|
|
}
|
|
return nextstop;
|
|
};
|
|
|
|
void TController::UpdateDelayFlag() {
|
|
|
|
if( TrainParams.CheckTrainLatency() < 0.0 ) {
|
|
// odnotowano spóźnienie
|
|
iDrivigFlags |= moveLate;
|
|
}
|
|
else {
|
|
// przyjazd o czasie
|
|
iDrivigFlags &= ~moveLate;
|
|
}
|
|
}
|
|
|
|
//-----------koniec skanowania semaforow
|
|
|
|
void TController::TakeControl( bool const Aidriver, bool const Forcevehiclecheck )
|
|
{ // przejęcie kontroli przez AI albo oddanie
|
|
if (AIControllFlag == Aidriver && !Forcevehiclecheck)
|
|
return; // już jest jak ma być
|
|
if( AIControllFlag != Aidriver ) {
|
|
// the autopilot switched on or off
|
|
simulation::Blackbox.driver_changed( pVehicle, Aidriver );
|
|
}
|
|
if (Aidriver) //żeby nie wykonywać dwa razy
|
|
{ // teraz AI prowadzi
|
|
AIControllFlag = AIdriver;
|
|
pVehicle->Controller = AIdriver;
|
|
// the AI doesn't operate the headlight dimmer, drop the state left by the human driver
|
|
// so the lights set by the AI aren't hidden (dimmer in off position) or dimmed
|
|
pVehicle->HeadlightsAoff = false;
|
|
pVehicle->HeadlightsBoff = false;
|
|
pVehicle->DimHeadlights = false;
|
|
pVehicle->HighBeamLights = false;
|
|
control_lights(); // reinicjalizacja swiatel
|
|
mvOccupied->CabActivisation(true);
|
|
iDirection = 0; // kierunek jazdy trzeba dopiero zgadnąć
|
|
TableClear(); // ponowne utworzenie tabelki, bo człowiek mógł pojechać niezgodnie z sygnałami
|
|
if( action() != TAction::actSleep ) {
|
|
// gdy zgaszone światła, flaga podjeżdżania pod semafory pozostaje bez zmiany
|
|
// conditional below disabled to get around the situation where the AI train does nothing ever
|
|
// because it is waiting for orders which don't come until the engine is engaged, i.e. effectively never
|
|
if( OrderCurrentGet() ) {
|
|
// jeśli coś robi
|
|
PrepareEngine(); // niech sprawdzi stan silnika
|
|
}
|
|
else {
|
|
// jeśli nic nie robi
|
|
OrderNext( Prepare_engine );
|
|
if( pVehicle->MoverParameters->iLights[ ( mvOccupied->CabActive < 0 ?
|
|
end::rear :
|
|
end::front ) ]
|
|
& ( light::headlight_left | light::headlight_right | light::headlight_upper ) ) // któreś ze świateł zapalone?
|
|
{ // od wersji 357 oczekujemy podania komend dla AI przez scenerię
|
|
/*
|
|
if( pVehicle->MoverParameters->iLights[ mvOccupied->CabActive < 0 ? end::rear : end::front ] & light::headlight_upper ) // górne światło zapalone
|
|
OrderNext( Obey_train ); // jazda pociągowa
|
|
else
|
|
OrderNext( Shunt ); // jazda manewrowa
|
|
*/
|
|
if( mvOccupied->Vel >= 1.0 ) // jeśli jedzie (dla 0.1 ma stać)
|
|
iDrivigFlags &= ~moveStopHere; // to ma nie czekać na sygnał, tylko jechać
|
|
else
|
|
iDrivigFlags |= moveStopHere; // a jak stoi, to niech czeka
|
|
}
|
|
}
|
|
CheckVehicles(); // ustawienie świateł
|
|
}
|
|
}
|
|
else
|
|
{ // a teraz użytkownik
|
|
if (eAction == TAction::actSleep || OrderCurrentGet() == Wait_for_orders) // gasimy swiatla jesli przejmujemy odstawione
|
|
pVehicle->RaLightsSet(0, 0);
|
|
auto const aiwasdriving { AIControllFlag == AIdriver };
|
|
if( aiwasdriving ) {
|
|
// the horn, sandbox, departure signal and brake releaser the AI may have latched are momentary for the human driver
|
|
handover::release_ai_controls( *mvOccupied, *mvControlling );
|
|
fWarningDuration = 0.0;
|
|
remove_hint( driver_hint::hornon );
|
|
// the AI sets the lights directly, leave the selector in matching position so it doesn't revert them later
|
|
sync_lights_selector();
|
|
}
|
|
AIControllFlag = Humandriver;
|
|
pVehicle->Controller = Humandriver;
|
|
if( aiwasdriving ) {
|
|
// same with the headlight dimmer, which is only applied for the human driver
|
|
sync_lights_dimmer();
|
|
}
|
|
if( eAction == TAction::actSleep ) {
|
|
eAction = TAction::actUnknown;
|
|
}
|
|
if( Forcevehiclecheck ) {
|
|
// update consist ownership and other consist data
|
|
CheckVehicles();
|
|
}
|
|
}
|
|
};
|
|
|
|
void TController::DirectionForward(bool forward)
|
|
{ // ustawienie jazdy do przodu dla true i do tyłu dla false (zależy od kabiny)
|
|
ZeroSpeed( true ); // TODO: check if force switch is needed anymore here
|
|
// HACK: make sure the master controller isn't set in position which prevents direction change
|
|
mvControlling->MainCtrlPos = std::min( mvControlling->MainCtrlPos, mvControlling->MainCtrlMaxDirChangePos );
|
|
|
|
if( forward ) {
|
|
// do przodu w obecnej kabinie
|
|
while( mvOccupied->DirActive <= 0
|
|
&& mvOccupied->DirectionForward() ) {
|
|
// force scan table update
|
|
iTableDirection = 0;
|
|
}
|
|
}
|
|
else {
|
|
// do tyłu w obecnej kabinie
|
|
while( mvOccupied->DirActive >= 0
|
|
&& mvOccupied->DirectionBackward() ) {
|
|
// force scan table update
|
|
iTableDirection = 0;
|
|
}
|
|
}
|
|
if( mvOccupied->TrainType == dt_SN61 ) {
|
|
// specjalnie dla SN61 żeby nie zgasł
|
|
while( mvControlling->RList[mvControlling->MainCtrlPos].Mn == 0
|
|
&& mvControlling->IncMainCtrl(1) ) {
|
|
; // all work is done in the header
|
|
}
|
|
}
|
|
}
|
|
|
|
void TController::ZeroDirection() {
|
|
|
|
while( mvOccupied->DirActive > 0 && mvOccupied->DirectionBackward() ) { ; }
|
|
while( mvOccupied->DirActive < 0 && mvOccupied->DirectionForward() ) { ; }
|
|
}
|
|
|
|
void TController::sync_consist_reversers() {
|
|
|
|
auto const currentdirection { mvOccupied->DirActive };
|
|
auto const fastforward { is_emu() && mvOccupied->EngineType != TEngineType::ElectricInductionMotor
|
|
&& mvOccupied->Imin == mvOccupied->IminHi };
|
|
|
|
// move reverser all way in the opposite direction...
|
|
for( auto idx = 0; idx < 3; ++idx ) {
|
|
if( currentdirection >= 0 ) {
|
|
mvOccupied->DirectionBackward();
|
|
}
|
|
else {
|
|
mvOccupied->DirectionForward();
|
|
|
|
}
|
|
}
|
|
// ...then restore original setting
|
|
while( mvOccupied->DirActive != currentdirection ) {
|
|
if( false == (
|
|
currentdirection >= 0 ?
|
|
mvOccupied->DirectionForward() :
|
|
mvOccupied->DirectionBackward() ) ) {
|
|
// sanity check for potential endless loop
|
|
break;
|
|
}
|
|
}
|
|
// potentially restore 'fast forward' setting
|
|
if( currentdirection > 0 && true == fastforward ) {
|
|
mvOccupied->DirectionForward();
|
|
}
|
|
}
|
|
|
|
Mtable::TTrainParameters const &
|
|
TController::TrainTimetable() const {
|
|
return TrainParams;
|
|
}
|
|
|
|
std::string TController::Relation() const
|
|
{ // zwraca relację pociągu
|
|
return TrainParams.ShowRelation();
|
|
};
|
|
|
|
const std::string& TController::TrainName() const
|
|
{ // zwraca numer pociągu
|
|
return TrainParams.TrainName;
|
|
};
|
|
|
|
int TController::StationCount() const
|
|
{ // zwraca ilość stacji (miejsc zatrzymania)
|
|
return TrainParams.StationCount;
|
|
};
|
|
|
|
int TController::StationIndex() const
|
|
{ // zwraca indeks aktualnej stacji (miejsca zatrzymania)
|
|
return TrainParams.StationIndex;
|
|
};
|
|
|
|
bool TController::IsStop() const
|
|
{ // informuje, czy jest zatrzymanie na najbliższej stacji
|
|
return TrainParams.IsStop();
|
|
};
|
|
|
|
// returns most recently calculated distance to potential obstacle ahead
|
|
double
|
|
TController::TrackObstacle() const {
|
|
|
|
return Obstacle.distance;
|
|
}
|
|
|
|
void TController::MoveTo(TDynamicObject *to)
|
|
{ // przesunięcie AI do innego pojazdu (przy zmianie kabiny)
|
|
if( to->Mechanik != nullptr
|
|
&& to->Mechanik != this ) {
|
|
// ai controller thunderdome, there can be only one
|
|
if( to->Mechanik->AIControllFlag ) {
|
|
if( to->Mechanik->primary() ) {
|
|
// take over boss duties
|
|
primary( true );
|
|
}
|
|
SafeDelete( to->Mechanik );
|
|
}
|
|
else {
|
|
// can't quite delete a human
|
|
if( AIControllFlag ) {
|
|
delete this;
|
|
}
|
|
return;
|
|
}
|
|
}
|
|
pVehicle->Mechanik = nullptr;
|
|
pVehicle = to;
|
|
ControllingSet(); // utworzenie połączenia do sterowanego pojazdu
|
|
pVehicle->Mechanik = this;
|
|
|
|
};
|
|
|
|
void TController::ControllingSet()
|
|
{ // znajduje człon do sterowania w EZT będzie to silnikowy
|
|
// problematyczne jest sterowanie z członu biernego, dlatego damy AI silnikowy
|
|
// dzięki temu będzie wirtualna kabina w silnikowym, działająca w rozrządczym
|
|
// w plikach FIZ zostały zgubione ujemne maski sprzęgów, stąd problemy z EZT
|
|
if( pVehicle == nullptr ) {
|
|
// a driver of no vehicle has nothing to control
|
|
return;
|
|
}
|
|
mvOccupied = pVehicle->MoverParameters; // domyślny skrót do obiektu parametrów
|
|
BrakeSystem = mvOccupied->BrakeSystem; // domyślny sposób hamowania
|
|
mvControlling = pVehicle->FindPowered()->MoverParameters; // poszukiwanie członu sterowanego
|
|
{
|
|
auto *lookup { pVehicle->FindPantographCarrier() };
|
|
mvPantographUnit = lookup != nullptr ? lookup->MoverParameters : mvControlling;
|
|
}
|
|
BrakeSystem = consist_brake_system();
|
|
};
|
|
|
|
std::string TController::TableText( std::size_t const Index ) const
|
|
{ // pozycja tabelki prędkości
|
|
if( Index < sSpeedTable.size() ) {
|
|
return sSpeedTable[ Index ].TableText();
|
|
}
|
|
else {
|
|
return "";
|
|
}
|
|
};
|
|
|
|
int TController::CrossRoute(TTrack *tr)
|
|
{ // zwraca numer segmentu dla skrzyżowania (tr)
|
|
// pożądany numer segmentu jest określany podczas skanowania drogi
|
|
// droga powinna być określona sposobem przejazdu przez skrzyżowania albo współrzędnymi miejsca
|
|
// docelowego
|
|
for( std::size_t i = 0; i < sSpeedTable.size(); ++i )
|
|
{ // trzeba przejrzeć tabelę skanowania w poszukiwaniu (tr)
|
|
// i jak się znajdzie, to zwrócić zapamiętany numer segmentu i kierunek przejazdu
|
|
// (-6..-1,1..6)
|
|
if( true == TestFlag(sSpeedTable[i].iFlags, spEnabled | spTrack)
|
|
&& sSpeedTable[i].trTrack == tr ) {
|
|
// jeśli pozycja odpowiadająca skrzyżowaniu (tr)
|
|
return sSpeedTable[i].iFlags >> 28; // najstarsze 4 bity jako liczba -8..7
|
|
}
|
|
}
|
|
return 0; // nic nie znaleziono?
|
|
};
|
|
/*
|
|
void TController::RouteSwitch(int d)
|
|
{ // ustawienie kierunku jazdy z kabiny
|
|
d &= 3;
|
|
if( ( d != 0 )
|
|
&& ( iRouteWanted != d ) ) { // nowy kierunek
|
|
iRouteWanted = d; // zapamiętanie
|
|
if( mvOccupied->CategoryFlag & 2 ) {
|
|
// jeśli samochód
|
|
for( std::size_t i = 0; i < sSpeedTable.size(); ++i ) {
|
|
// szukanie pierwszego skrzyżowania i resetowanie kierunku na nim
|
|
if( true == TestFlag( sSpeedTable[ i ].iFlags, spEnabled | spTrack ) ) {
|
|
// jeśli pozycja istotna (1) oraz odcinek (2)
|
|
if( false == TestFlag( sSpeedTable[ i ].iFlags, spElapsed ) ) {
|
|
// odcinek nie może być miniętym
|
|
if( sSpeedTable[ i ].trTrack->eType == tt_Cross ) // jeśli skrzyżowanie
|
|
{
|
|
while( sSpeedTable.size() >= i ) {
|
|
// NOTE: we're ignoring semaphor flags and not resetting them like we do for train route trimming
|
|
// but what if there's street lights?
|
|
// TODO: investigate
|
|
sSpeedTable.pop_back();
|
|
}
|
|
iLast = sSpeedTable.size();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
};
|
|
*/
|
|
std::string TController::OwnerName() const
|
|
{
|
|
return pVehicle ? pVehicle->MoverParameters->Name : "none";
|
|
};
|
|
|
|
void
|
|
TController::update_timers( double dt ) {
|
|
|
|
ElapsedTime += dt;
|
|
WaitingTime += dt;
|
|
fBrakeTime -= dt; // wpisana wartość jest zmniejszana do 0, gdy ujemna należy zmienić nastawę hamulca
|
|
fBrakeHeldTime += dt;
|
|
if( mvOccupied->fBrakeCtrlPos != mvOccupied->Handle->GetPos( bh_FS ) ) {
|
|
// brake charging timeout starts after charging ends
|
|
BrakeChargingCooldown += dt;
|
|
}
|
|
fStopTime += dt; // zliczanie czasu postoju, nie ruszy dopóki ujemne
|
|
fActionTime += dt; // czas używany przy regulacji prędkości i zamykaniu drzwi
|
|
LastReactionTime += dt;
|
|
if( mvOccupied->Vel < 0.05
|
|
&& (OrderCurrentGet() & (Shunt | Loose_shunt | Obey_train | Bank)) != 0 ) {
|
|
IdleTime += dt;
|
|
}
|
|
else {
|
|
IdleTime = 0.0;
|
|
}
|
|
fWarningDuration -= dt; // horn activation while the value is positive
|
|
}
|
|
|
|
void
|
|
TController::update_logs( double const dt ) {
|
|
// log vehicle data
|
|
if( false == writes_physicslog() ) {
|
|
// not counted while it isn't logged (the driver of a road vehicle, or no logs on): were the logs turned on,
|
|
// it would write a line every 0.05 s from then on, not one each update to make up for the time before
|
|
LastUpdatedTime = 0.0;
|
|
return;
|
|
}
|
|
LastUpdatedTime += dt;
|
|
if( LastUpdatedTime > deltalog ) {
|
|
// zapis do pliku DAT
|
|
if( false == PhysicsLogBegun ) {
|
|
begin_physicslog();
|
|
}
|
|
PhysicsLog();
|
|
LastUpdatedTime -= deltalog;
|
|
}
|
|
}
|
|
|
|
void
|
|
TController::determine_consist_state() {
|
|
// ABu-160305 testowanie gotowości do jazdy
|
|
// Ra: przeniesione z DynObj, skład użytkownika też jest testowany, żeby mu przekazać, że ma odhamować
|
|
|
|
if (mvOccupied->CabActive == 0 && mvOccupied->Power24vIsAvailable)
|
|
{
|
|
cue_action( driver_hint::cabactivation );
|
|
}
|
|
else if (!mvOccupied->AutomaticCabActivation
|
|
&& ( mvOccupied->CabActive == -mvOccupied->CabOccupied || !mvOccupied->CabMaster || !mvOccupied->Power24vIsAvailable ) )
|
|
{
|
|
cue_action( driver_hint::cabdeactivation );
|
|
}
|
|
|
|
int index = double(BrakeAccTableSize) * (mvOccupied->Vel / mvOccupied->Vmax);
|
|
index = std::min(BrakeAccTableSize, std::max(1, index));
|
|
fBrake_a0[0] = fBrake_a0[index];
|
|
fBrake_a1[0] = fBrake_a1[index];
|
|
|
|
if (is_emu() || is_dmu()) {
|
|
auto Coeff = std::clamp( mvOccupied->Vel*0.015 , 0.5 , 1.0);
|
|
fAccThreshold = fNominalAccThreshold * Coeff - fBrake_a0[BrakeAccTableSize] * (1.0 - Coeff);
|
|
}
|
|
|
|
Ready = true; // wstępnie gotowy
|
|
fReady = 0.0; // założenie, że odhamowany
|
|
IsConsistBraked = mvOccupied->BrakeSystem == TBrakeSystem::ElectroPneumatic && false == ForcePNBrake ? mvOccupied->BrakePress > 2.0 :
|
|
mvOccupied->PipePress < std::max(3.9, mvOccupied->BrakePressureActual.PipePressureVal) + 0.1;
|
|
fAccGravity = 0.0; // przyspieszenie wynikające z pochylenia
|
|
IsAnyCouplerStretched = false;
|
|
IsAnyDoorOnlyOpen[ side::right ] = IsAnyDoorOnlyOpen[ side::left ] = false;
|
|
IsAnyDoorOpen[ side::right ] = IsAnyDoorOpen[ side::left ] = false;
|
|
IsAnyDoorPermitActive[ side::right ] = IsAnyDoorPermitActive[ side::left ] = false;
|
|
auto doorclosure { door_closure_t::none };
|
|
ConsistShade = 0.0;
|
|
auto *p { pVehicles[ end::front ] }; // pojazd na czole składu
|
|
double dy; // składowa styczna grawitacji, w przedziale <0,1>
|
|
while (p)
|
|
{ // sprawdzenie odhamowania wszystkich połączonych pojazdów
|
|
auto *vehicle { p->MoverParameters };
|
|
auto const bp { std::max( 0.0, vehicle->BrakePress - ( vehicle->SpeedCtrlUnit.Parking ? vehicle->MaxBrakePress[ 0 ] * vehicle->StopBrakeDecc : 0.0 ) ) };
|
|
// starting uphill the power is applied against the train brake on purpose, until the power holds the train
|
|
auto const heldforstart { bUphillStart };
|
|
if (Ready) {
|
|
// bo jak coś nie odhamowane, to dalej nie ma co sprawdzać
|
|
if( auto const isbraking { TestFlagAny( vehicle->Hamulec->GetBrakeStatus(), b_hld | b_on ) };
|
|
vehicle->Vel < 1.0 ?
|
|
isbraking || bp > 0.4 : // ensure the brakes are sufficiently released when starting to move
|
|
// once in motion a brake down to 0.4 bar counts as released (UIC), even if its distributor
|
|
// is still in the lap position while the brake pipe recharges
|
|
( isbraking && bp > 0.4 ) || vehicle->Fb > 10000.0 ) { // 10 kN
|
|
// ready all the same only at a standstill with the power going on against the brake on purpose;
|
|
// in motion a braking force left anywhere in the train (a hand brake) stops it as before
|
|
Ready = heldforstart && ( vehicle->Vel < 1.0 );
|
|
}
|
|
// Ra: odluźnianie przeładowanych lokomotyw, ciągniętych na zimno - prowizorka...
|
|
if( bp >= 0.4 && (AIControllFlag || Global.AITrainman && mvOccupied->Vel < EU07_AI_NOMOVEMENT && !is_emu() && !is_dmu()) && BrakeCtrlPosition == gbh_RP // jest pozycja jazdy
|
|
&& false == TestFlag(vehicle->Hamulec->GetBrakeStatus(), b_dmg) // brake isn't broken
|
|
&& vehicle->PipePress - mvOccupied->Handle->GetRP() > -0.1 // jeśli ciśnienie jak dla jazdy
|
|
&& vehicle->Hamulec->GetCRP() > vehicle->PipePress + 0.12 ) { // wg UIC określone sztywno na 0.04
|
|
// za dużo w zbiorniku
|
|
// indywidualne luzowanko
|
|
vehicle->BrakeReleaser(1);
|
|
}
|
|
if (bp < 0.1 && (AIControllFlag || Global.AITrainman) && false == TestFlag(vehicle->Hamulec->GetBrakeStatus(), b_dmg) // brake isn't broken
|
|
&& vehicle->Hamulec->GetCRP() < vehicle->PipePress - 0.1) {
|
|
// już nie jest za dużo w zbiorniku
|
|
// koniec indywidualnego luzowanka
|
|
vehicle->BrakeReleaser(0);
|
|
}
|
|
}
|
|
fReady = std::max( heldforstart ? 0.0 : bp, fReady ); // szukanie najbardziej zahamowanego
|
|
if( ( dy = p->VectorFront().y ) != 0.0 ) {
|
|
// istotne tylko dla pojazdów na pochyleniu
|
|
// ciężar razy składowa styczna grawitacji
|
|
fAccGravity -= vehicle->TotalMassxg * dy * ( p->DirectionGet() == iDirection ? 1 : -1 );
|
|
}
|
|
// check coupler state
|
|
IsAnyCouplerStretched =
|
|
IsAnyCouplerStretched
|
|
|| vehicle->Couplers[end::front].stretch_duration > 0.0
|
|
|| vehicle->Couplers[end::rear].stretch_duration > 0.0;
|
|
// check door state
|
|
{
|
|
auto const switchsides{ p->DirectionGet() != (iDirection == 0 ? mvOccupied->CabOccupied : iDirection) };
|
|
auto const &rightdoor { vehicle->Doors.instances[ ( switchsides ? side::left : side::right ) ] };
|
|
auto const &leftdoor { vehicle->Doors.instances[ ( switchsides ? side::right : side::left ) ] };
|
|
if( vehicle->Doors.close_control != control_t::autonomous ) {
|
|
IsAnyDoorOpen[ side::right ] |= false == rightdoor.is_closed;
|
|
IsAnyDoorOpen[ side::left ] |= false == leftdoor.is_closed;
|
|
}
|
|
if (vehicle->Doors.close_control != control_t::autonomous) {
|
|
IsAnyDoorOnlyOpen[ side::right ] |= false == rightdoor.is_door_closed;
|
|
IsAnyDoorOnlyOpen[ side::left ] |= false == leftdoor.is_door_closed;
|
|
}
|
|
if( vehicle->Doors.permit_needed ) {
|
|
IsAnyDoorPermitActive[ side::right ] |= rightdoor.open_permit;
|
|
IsAnyDoorPermitActive[ side::left ] |= leftdoor.open_permit;
|
|
}
|
|
doorclosure = std::max( doorclosure, vehicle->door_closure() );
|
|
}
|
|
// measure lighting level
|
|
// TBD: apply weight (multiplier) to partially lit vehicles?
|
|
ConsistShade += p->fShade > 0.0 ? p->fShade : 1.0;
|
|
p = p->Next(); // pojazd podłączony z tyłu (patrząc od czoła)
|
|
}
|
|
DoorClosure = doorclosure;
|
|
// calculate average amount of received sunlight
|
|
ConsistShade /= iVehicles;
|
|
|
|
// test state of main devices in all vehicles under control
|
|
IsAnyConverterOverloadRelayOpen = false;
|
|
IsAnyMotorOverloadRelayOpen = false;
|
|
IsAnyGroundRelayOpen = false;
|
|
IsAnyLineBreakerOpen = false;
|
|
IsAnyCompressorPresent = false;
|
|
IsAnyCompressorEnabled = false;
|
|
IsAnyCompressorExplicitlyEnabled = false;
|
|
IsAnyConverterPresent = false;
|
|
IsAnyConverterEnabled = false;
|
|
IsAnyConverterExplicitlyEnabled = false;
|
|
// whether the line contactors of a vehicle wait for its own converter (LineContactorsInterlock), off with its local switch
|
|
auto islocalconverterswitchoff { false };
|
|
|
|
pVehicle->for_each(
|
|
coupling::control,
|
|
[this, &islocalconverterswitchoff]( TDynamicObject * Vehicle ) {
|
|
auto const *vehicle { Vehicle->MoverParameters };
|
|
islocalconverterswitchoff |= vehicle->LineContactorsHeldByLocalConverterSwitch();
|
|
IsAnyConverterOverloadRelayOpen |= vehicle->ConvOvldFlag;
|
|
IsAnyMotorOverloadRelayOpen |= vehicle->FuseFlag;
|
|
IsAnyGroundRelayOpen |= !vehicle->GroundRelay;
|
|
IsAnyCompressorPresent |= vehicle->CompressorSpeed > 0.0;
|
|
IsAnyCompressorEnabled |= vehicle->CompressorSpeed > 0.0 ? (vehicle->CompressorAllow || vehicle->CompressorStart == start_t::automatic) && vehicle->CompressorAllowLocal : false;
|
|
IsAnyCompressorExplicitlyEnabled |= vehicle->CompressorSpeed > 0.0 ? vehicle->CompressorAllow && vehicle->CompressorAllowLocal : false;
|
|
IsAnyConverterPresent |= vehicle->ConverterStart != start_t::disabled;
|
|
IsAnyConverterEnabled |= ( vehicle->ConverterAllow || vehicle->ConverterStart == start_t::automatic ) && vehicle->ConverterAllowLocal;
|
|
IsAnyConverterExplicitlyEnabled |= vehicle->ConverterAllow && vehicle->ConverterAllowLocal;
|
|
if( vehicle->Power > 0.01 ) {
|
|
IsAnyLineBreakerOpen |= !vehicle->Mains; } } );
|
|
|
|
// siłę generują pojazdy na pochyleniu ale działa ona całość składu, więc a=F/m
|
|
fAccGravity *= iDirection >= 0 ? 1 : -1;
|
|
fAccGravity /= fMass;
|
|
{
|
|
auto absaccs { fAccGravity }; // Ra 2014-03: jesli skład stoi, to działa na niego składowa styczna grawitacji
|
|
if( mvOccupied->Vel > EU07_AI_NOMOVEMENT ) {
|
|
absaccs = 0;
|
|
auto *d = pVehicles[ end::front ]; // pojazd na czele składu
|
|
while( d ) {
|
|
absaccs += d->MoverParameters->TotalMass * d->MoverParameters->AccS * ( d->DirectionGet() == iDirection ? 1 : -1 );
|
|
d = d->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła)
|
|
}
|
|
absaccs *= iDirection >= 0 ? 1 : -1;
|
|
absaccs /= fMass;
|
|
}
|
|
AbsAccS = absaccs;
|
|
}
|
|
#if LOGVELOCITY
|
|
WriteLog( "Vel=" + to_string( DirectionalVel() ) + ", AbsAccS=" + to_string( AbsAccS ) + ", AccGrav=" + to_string( fAccGravity ) );
|
|
#endif
|
|
|
|
if( !Ready // v367: jeśli wg powyższych warunków skład nie jest odhamowany
|
|
&& fAccGravity < -0.05 // jeśli ma pod górę na tyle, by się stoczyć
|
|
&& fReady < 0.8 ) { // delikatniejszy warunek, obejmuje wszystkie wagony
|
|
Ready = true; //żeby uznać za odhamowany
|
|
}
|
|
auto const departblocked {
|
|
AIControllFlag
|
|
&& mvOccupied->Vel < EU07_AI_NOMOVEMENT
|
|
&& VelDesired > 0.0
|
|
&& ( false == Ready || fReady > 0.4 ) };
|
|
if( false == departblocked ) {
|
|
DepartBlockedStart = -1.0;
|
|
}
|
|
else if( DepartBlockedStart < 0.0 ) {
|
|
DepartBlockedStart = ElapsedTime;
|
|
}
|
|
// second pass, for diesel engines verify the (live) engines are fully started
|
|
// TODO: cache presence of diesel engines in the consist, to skip this test if there isn't any
|
|
p = pVehicles[ end::front ]; // pojazd na czole składu
|
|
while( true == Ready
|
|
&& p != nullptr ) {
|
|
|
|
auto const *vehicle { p->MoverParameters };
|
|
|
|
if( has_diesel_engine() ) {
|
|
|
|
Ready = vehicle->Vel > EU07_AI_MOVEMENT // already moving
|
|
|| false == vehicle->Mains // deadweight vehicle
|
|
|| vehicle->enrot > 0.8 * (vehicle->EngineType == TEngineType::DieselEngine ? vehicle->dizel_nmin : vehicle->DElist[0].RPM / 60.0);
|
|
}
|
|
p = p->Next(); // pojazd podłączony z tyłu (patrząc od czoła)
|
|
}
|
|
// test consist state for external events and/or weird things human user could've done
|
|
iEngineActive &=
|
|
false == IsAnyConverterOverloadRelayOpen
|
|
&& false == IsAnyLineBreakerOpen
|
|
&& ( false == IsAnyConverterPresent || true == IsAnyConverterEnabled )
|
|
&& ( false == IsAnyCompressorPresent || true == IsAnyCompressorEnabled )
|
|
// the ai goes back to preparing the engine and switches that converter on, the human driver may run with it off
|
|
&& ( false == AIControllFlag || false == islocalconverterswitchoff );
|
|
}
|
|
|
|
void
|
|
TController::control_wheelslip() {
|
|
// wheel slip
|
|
if( mvControlling->SlippingWheels ) {
|
|
cue_action( driver_hint::sandingon ); // piasku!
|
|
cue_action( driver_hint::tractiveforcedecrease );
|
|
cue_action( driver_hint::brakingforcedecrease );
|
|
cue_action( driver_hint::antislip );
|
|
++iDriverFailCount;
|
|
}
|
|
else if( std::fabs( mvControlling->Im ) > 0.75 * mvControlling->ImaxHi ) {
|
|
cue_action( driver_hint::sandingon ); // piaskujemy tory, coby się nie ślizgać
|
|
}
|
|
else {
|
|
// deactivate sandbox if we aren't slipping
|
|
if( mvControlling->SandDose ) {
|
|
cue_action( driver_hint::sandingoff );
|
|
}
|
|
}
|
|
}
|
|
|
|
void
|
|
TController::control_pantographs() {
|
|
|
|
if( mvPantographUnit->EnginePowerSource.SourceType != TPowerSource::CurrentCollector ) { return; }
|
|
|
|
if( false == mvPantographUnit->PantAutoValve
|
|
&& mvOccupied->ScndPipePress > 4.3 ) {
|
|
// gdy główna sprężarka bezpiecznie nabije ciśnienie to można przestawić kurek na zasilanie pantografów z głównej pneumatyki
|
|
cue_action( driver_hint::pantographairsourcesetmain );
|
|
}
|
|
|
|
// uśrednione napięcie sieci: przy spadku poniżej wartości minimalnej opóźnić rozruch o losowy czas
|
|
fVoltage = 0.5 * (fVoltage + std::max( mvControlling->GetTrainsetHighVoltage(), mvControlling->PantographVoltage ) );
|
|
if( fVoltage < mvControlling->EnginePowerSource.CollectorParameters.MinV && fActionTime >= PrepareTime ) {
|
|
// gdy rozłączenie WS z powodu niskiego napięcia
|
|
// jeśli czas oczekiwania nie został ustawiony, losowy czas oczekiwania przed ponownym załączeniem jazdy
|
|
fActionTime = -2.0 - Random(10);
|
|
}
|
|
|
|
// the pantograph setup the .fiz suggests for shunting (AI: ShuntPantstate=, eu07/maszyna#461), 0 when there's none
|
|
// or the vehicle isn't shunting
|
|
auto const shuntpantographsetup {
|
|
( OrderCurrentGet() & ( Shunt | Loose_shunt ) ) != 0 ?
|
|
mvOccupied->AIHintShuntPantstate :
|
|
0 };
|
|
|
|
// raise/lower pantographs as needed
|
|
auto const useregularpantographlayout {
|
|
pVehicle->Next(coupling::control) == nullptr // standalone
|
|
|| is_emu() // special case
|
|
|| mvControlling->TrainType == dt_ET41 }; // special case
|
|
|
|
if( mvOccupied->Vel > EU07_AI_NOMOVEMENT ) {
|
|
|
|
if( fOverhead2 >= 0.0 || iOverheadZero ) {
|
|
// jeśli jazda bezprądowa albo z opuszczonym pantografem
|
|
cue_action( driver_hint::mastercontrollersetzerospeed );
|
|
}
|
|
|
|
if( fOverhead2 > 0.0 || iOverheadDown ) {
|
|
// jazda z opuszczonymi pantografami
|
|
if( mvPantographUnit->Pantographs[ end::front ].is_active ) {
|
|
cue_action( driver_hint::frontpantographvalveoff );
|
|
}
|
|
if( mvPantographUnit->Pantographs[ end::rear ].is_active ) {
|
|
cue_action( driver_hint::rearpantographvalveoff );
|
|
}
|
|
}
|
|
else {
|
|
// jeśli nie trzeba opuszczać pantografów
|
|
// TODO: check if faction alone reduces frequency enough
|
|
if( fActionTime > 0.0 ) {
|
|
if( shuntpantographsetup != 0 ) {
|
|
// shunting with the pantograph setup the .fiz suggests for it
|
|
control_pantographs_setup( shuntpantographsetup );
|
|
}
|
|
else if( mvOccupied->AIHintPantstate == 0 ) {
|
|
// jazda na tylnym
|
|
if( iDirection >= 0 && useregularpantographlayout ) {
|
|
// jak jedzie w kierunku sprzęgu 0
|
|
if( mvPantographUnit->PantRearVolt == 0.0
|
|
// filter out cases with single _other_ working pantograph so we don't try to raise something we can't
|
|
&& ( mvPantographUnit->PantographVoltage == 0.0
|
|
|| mvPantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo > 1 ) ) {
|
|
cue_action( driver_hint::rearpantographvalveon );
|
|
}
|
|
}
|
|
else {
|
|
// jak jedzie w kierunku sprzęgu 0
|
|
if( mvPantographUnit->PantFrontVolt == 0.0
|
|
// filter out cases with single _other_ working pantograph so we don't try to raise something we can't
|
|
&& ( mvPantographUnit->PantographVoltage == 0.0
|
|
|| mvPantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo > 1 ) ) {
|
|
cue_action( driver_hint::frontpantographvalveon );
|
|
}
|
|
}
|
|
|
|
if( mvOccupied->Vel > 5 && mvPantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo > 1 ) {
|
|
// opuszczenie przedniego po rozpędzeniu się o ile jest więcej niż jeden
|
|
if (iDirection >= 0 && useregularpantographlayout) // jak jedzie w kierunku sprzęgu 0
|
|
{ // poczekać na podniesienie tylnego
|
|
if (mvPantographUnit->PantFrontVolt != 0.0 && mvPantographUnit->PantRearVolt != 0.0)
|
|
{ // czy jest napięcie zasilające na tylnym?
|
|
cue_action(driver_hint::frontpantographvalveoff); // opuszcza od sprzęgu 0
|
|
}
|
|
}
|
|
else
|
|
{ // poczekać na podniesienie przedniego
|
|
if (mvPantographUnit->PantRearVolt != 0.0 && mvPantographUnit->PantFrontVolt != 0.0)
|
|
{ // czy jest napięcie zasilające na przednim?
|
|
cue_action(driver_hint::rearpantographvalveoff); // opuszcza od sprzęgu 1
|
|
}
|
|
}
|
|
}
|
|
|
|
}
|
|
else {
|
|
// use suggested pantograph setup
|
|
if( mvOccupied->Vel > 5 ) {
|
|
auto const pantographsetup{ mvOccupied->AIHintPantstate };
|
|
cue_action(
|
|
pantographsetup & 1 << 0 ? driver_hint::frontpantographvalveon : driver_hint::frontpantographvalveoff );
|
|
cue_action(
|
|
pantographsetup & 1 << 1 ? driver_hint::rearpantographvalveon : driver_hint::rearpantographvalveoff );
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
else if( shuntpantographsetup != 0 ) {
|
|
// shunting with the suggested setup, also while standing, and without raising more pantographs when idling
|
|
if( fOverhead2 <= 0.0 && iOverheadDown == 0 ) {
|
|
control_pantographs_setup( shuntpantographsetup );
|
|
}
|
|
}
|
|
else {
|
|
if( !mvOccupied->AIHintPantUpIfIdle || IdleTime <= 45.0 || std::abs(fStopTime) <= 15.0 || mvPantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo <= 1 )
|
|
{
|
|
}
|
|
else
|
|
{
|
|
// spending a longer at a stop, raise also front pantograph
|
|
if (iDirection >= 0 && useregularpantographlayout)
|
|
{
|
|
// jak jedzie w kierunku sprzęgu 0
|
|
if (mvPantographUnit->PantFrontVolt == 0.0)
|
|
{
|
|
cue_action(driver_hint::frontpantographvalveon, 5); // discard the hint if speed exceeds 5 km/h
|
|
}
|
|
}
|
|
else
|
|
{
|
|
if (mvPantographUnit->PantRearVolt == 0.0)
|
|
{
|
|
cue_action(driver_hint::rearpantographvalveon, 5); // discard the hint if speed exceeds 5 km/h
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// raises the pantographs of the suggested setup (bit 0: front, bit 1: rear) and lowers the others, these only once
|
|
// a pantograph of the setup collects the voltage, so the vehicle doesn't lose its power on the way
|
|
void
|
|
TController::control_pantographs_setup( int const Setup ) {
|
|
|
|
auto const front { ( Setup & 1 << 0 ) != 0 };
|
|
auto const rear { ( Setup & 1 << 1 ) != 0 };
|
|
if( front ) {
|
|
cue_action( driver_hint::frontpantographvalveon );
|
|
}
|
|
if( rear ) {
|
|
cue_action( driver_hint::rearpantographvalveon );
|
|
}
|
|
if( auto const setuplive { ( front && mvPantographUnit->PantFrontVolt != 0.0 ) || ( rear && mvPantographUnit->PantRearVolt != 0.0 ) };
|
|
false == setuplive ) {
|
|
return;
|
|
}
|
|
if( false == front ) {
|
|
cue_action( driver_hint::frontpantographvalveoff );
|
|
}
|
|
if( false == rear ) {
|
|
cue_action( driver_hint::rearpantographvalveoff );
|
|
}
|
|
}
|
|
|
|
void
|
|
TController::control_horns( double const Timedelta ) {
|
|
// horn control
|
|
if( fWarningDuration > 0.0 ) {
|
|
// jeśli pozostało coś do wytrąbienia trąbienie trwa nadal
|
|
if( mvOccupied->WarningSignal == 0 ) {
|
|
cue_action( driver_hint::hornon, 1 ); // low tone horn by default
|
|
}
|
|
}
|
|
else {
|
|
if( mvOccupied->WarningSignal != 0 ) {
|
|
cue_action( driver_hint::hornoff ); // a tu się kończy
|
|
}
|
|
}
|
|
if( mvOccupied->Vel > EU07_AI_MOVEMENT ) {
|
|
// jesli jedzie, można odblokować trąbienie, bo się wtedy nie włączy
|
|
iDrivigFlags &= ~moveStartHornDone; // zatrąbi dopiero jak następnym razem stanie
|
|
iDrivigFlags |= moveStartHorn; // i trąbić przed następnym ruszeniem
|
|
}
|
|
|
|
if( true == TestFlag(iDrivigFlags, moveStartHornNow)
|
|
&& true == Ready
|
|
&& true == iEngineActive
|
|
&& mvControlling->MainCtrlPowerPos() > 0 ) {
|
|
// uruchomienie trąbienia przed ruszeniem
|
|
fWarningDuration = 0.3; // czas trąbienia
|
|
cue_action( driver_hint::hornon, pVehicle->iHornWarning ); // wysokość tonu (2=wysoki)
|
|
iDrivigFlags |= moveStartHornDone; // nie trąbić aż do ruszenia
|
|
iDrivigFlags &= ~moveStartHornNow; // trąbienie zostało zorganizowane
|
|
}
|
|
}
|
|
|
|
void
|
|
TController::control_security_system( double const Timedelta ) {
|
|
if( mvOccupied->SecuritySystem.is_cabsignal_blinking() && mvOccupied->SecuritySystem.has_separate_acknowledge()) {
|
|
// jak zadziałało SHP
|
|
if( false == is_emu()
|
|
&& mvOccupied->DirActive == 0 ) {
|
|
cue_action( driver_hint::directionforward );
|
|
}
|
|
cue_action( driver_hint::shpsystemreset ); // to skasuj
|
|
if( BrakeCtrlPosition == 0 // TODO: verify whether it's 0 in all vehicle types
|
|
&& AccDesired > 0.0
|
|
&& mvOccupied->SecuritySystem.is_braking() ) {
|
|
cue_action( driver_hint::trainbrakerelease );
|
|
}
|
|
}
|
|
|
|
if( mvOccupied->SecuritySystem.is_blinking() ) {
|
|
// jak zadziałało CA/SHP
|
|
if( false == is_emu()
|
|
&& mvOccupied->DirActive == 0 ) {
|
|
cue_action( driver_hint::directionforward );
|
|
}
|
|
cue_action( driver_hint::securitysystemreset ); // to skasuj
|
|
if( BrakeCtrlPosition == 0 // TODO: verify whether it's 0 in all vehicle types
|
|
&& AccDesired > 0.0
|
|
&& mvOccupied->SecuritySystem.is_braking() ) {
|
|
cue_action( driver_hint::trainbrakerelease );
|
|
}
|
|
}
|
|
// basic emergency stop handling, while at it
|
|
if( true == mvOccupied->RadioStopFlag // radio-stop
|
|
&& mvOccupied->Vel < 0.01 // and actual stop
|
|
&& true == mvOccupied->Radio ) { // and we didn't touch the radio yet
|
|
// turning off the radio should reset the flag, during security system check
|
|
if( m_radiocontroltime > 5.0 ) { // arbitrary delay between stop and disabling the radio
|
|
cue_action( driver_hint::radiooff );
|
|
}
|
|
else {
|
|
m_radiocontroltime += Timedelta;
|
|
}
|
|
}
|
|
if( iEngineActive
|
|
&& ( false == mvOccupied->Radio || false == mvOccupied->RadioFuse )
|
|
&& false == mvOccupied->RadioStopFlag ) {
|
|
// otherwise if it's safe to do so, turn the radio back on
|
|
// arbitrary 5 sec delay before switching radio back on
|
|
m_radiocontroltime = std::min( m_radiocontroltime, 5.0 );
|
|
if( m_radiocontroltime < 0.0 ) {
|
|
// hint at whichever of the two is open, the radio's switch or the cut-off in its power supply
|
|
if( false == mvOccupied->RadioFuse ) {
|
|
cue_action( driver_hint::radiofuseon );
|
|
}
|
|
if( false == mvOccupied->Radio ) {
|
|
cue_action( driver_hint::radioon );
|
|
}
|
|
}
|
|
else {
|
|
m_radiocontroltime -= Timedelta;
|
|
}
|
|
}
|
|
}
|
|
|
|
void
|
|
TController::control_handles() {
|
|
|
|
switch( mvControlling->EngineType ) {
|
|
case TEngineType::ElectricSeriesMotor: {
|
|
// styczniki liniowe rozłączone yBARC
|
|
if( false == mvControlling->StLinFlag
|
|
&& false == mvControlling->DelayCtrlFlag
|
|
&& mvControlling->MainCtrlPowerPos() > 1 ) {
|
|
cue_action( driver_hint::mastercontrollersetzerospeed );
|
|
}
|
|
// if the power station is heavily burdened drop down to series mode to reduce the load
|
|
auto const useseriesmodevoltage {
|
|
std::lerp(
|
|
mvControlling->EnginePowerSource.CollectorParameters.MinV,
|
|
mvControlling->EnginePowerSource.CollectorParameters.MaxV,
|
|
IsHeavyCargoTrain ? 0.35 : 0.40 ) };
|
|
|
|
if( fVoltage <= useseriesmodevoltage ) {
|
|
cue_action( driver_hint::mastercontrollersetseriesmode );
|
|
}
|
|
// sanity check
|
|
if( false == Ready
|
|
&& mvControlling->MainCtrlPowerPos() > 1 ) {
|
|
cue_action( driver_hint::mastercontrollersetzerospeed );
|
|
}
|
|
break;
|
|
}
|
|
case TEngineType::DieselElectric: {
|
|
// styczniki liniowe rozłączone yBARC
|
|
if( false == mvControlling->StLinFlag
|
|
&& false == mvControlling->DelayCtrlFlag
|
|
&& mvControlling->MainCtrlPowerPos() > 1 ) {
|
|
cue_action( driver_hint::mastercontrollersetzerospeed );
|
|
}
|
|
// sanity check
|
|
if( false == Ready
|
|
&& mvControlling->MainCtrlPowerPos() > 1 ) {
|
|
cue_action( driver_hint::mastercontrollersetzerospeed );
|
|
}
|
|
break;
|
|
}
|
|
default: {
|
|
break;
|
|
} } // enginetype
|
|
}
|
|
|
|
// moves the light preset selector to the position matching the lights set directly by the AI,
|
|
// otherwise the next SetLights() call (e.g. from CheckVehicles()) reverts them to the untouched selector position
|
|
void
|
|
TController::sync_lights_selector() {
|
|
|
|
if( mvOccupied->LightsPosNo <= 0 ) { return; }
|
|
|
|
auto const *headvehicle { pVehicles[ end::front ] };
|
|
if( headvehicle == nullptr ) { return; }
|
|
// same choice of the light table as in TDynamicObject::SetLights()
|
|
auto const lightstable { ( mvOccupied->CabOccupied * pVehicle->DirectionGet() >= 0 ? end::front : end::rear ) };
|
|
// same choice of the lit vehicle end as in TDynamicObject::RaLightsSet()
|
|
auto const headend { ( headvehicle->iDirection > 0 ? end::front : end::rear ) };
|
|
auto const position { handover::light_selector_position(
|
|
*mvOccupied, lightstable, headvehicle->MoverParameters->iLights[ headend ], headvehicle->LightList( headend ) ) };
|
|
if( position == mvOccupied->LightsPos ) { return; }
|
|
|
|
mvOccupied->LightsPos = position;
|
|
// visual feedback
|
|
auto *train { simulation::Trains.find( pVehicle->name() ) };
|
|
if( train != nullptr ) {
|
|
train->ggLightsButton.PutValue( static_cast<float>( position - 1 ) );
|
|
}
|
|
}
|
|
|
|
// re-applies the headlight dimmer state after the AI handed the vehicle over to the human driver,
|
|
// moving the dimmer out of the off position if it'd hide the head lights set by the AI
|
|
void
|
|
TController::sync_lights_dimmer() {
|
|
|
|
if( mvOccupied->dimPositions.empty() ) { return; }
|
|
|
|
auto const *headvehicle { pVehicles[ end::front ] };
|
|
auto const headend { ( headvehicle != nullptr && headvehicle->iDirection > 0 ? end::front : end::rear ) };
|
|
auto const headlightson {
|
|
headvehicle != nullptr
|
|
&& ( headvehicle->MoverParameters->iLights[ headend ] & ( light::headlight_left | light::headlight_right | light::headlight_upper ) ) != 0 };
|
|
|
|
auto const position { handover::dimmer_position( *mvOccupied, headlightson ) };
|
|
if( position != mvOccupied->modernDimmerPosition ) {
|
|
mvOccupied->modernDimmerPosition = position;
|
|
// visual feedback
|
|
auto *train { simulation::Trains.find( pVehicle->name() ) };
|
|
if( train != nullptr ) {
|
|
train->ggModernLightDimSw.PutValue( static_cast<float>( position ) );
|
|
}
|
|
}
|
|
if( position < 0 || position >= static_cast<int>( mvOccupied->dimPositions.size() ) ) { return; } // SetLightDimmings() doesn't check the range
|
|
pVehicle->SetLightDimmings();
|
|
}
|
|
|
|
// activate consist lamp codes
|
|
void
|
|
TController::control_lights() {
|
|
|
|
if( is_train() ) {
|
|
// jeśli jazda pociągowa
|
|
if( true == TestFlag( OrderCurrentGet(), Obey_train ) ) {
|
|
// head lights
|
|
if( m_lighthints[ end::front ] == -1 ) {
|
|
cue_action( driver_hint::headcodepc1 );
|
|
}
|
|
else if( m_lighthints[ end::front ] == ( light::redmarker_left | light::headlight_right | light::headlight_upper ) ) {
|
|
cue_action( driver_hint::headcodepc2 );
|
|
}
|
|
else {
|
|
// custom light pattern
|
|
if( AIControllFlag ) {
|
|
pVehicles[ end::front ]->RaLightsSet( m_lighthints[ end::front ], -1 );
|
|
}
|
|
}
|
|
// tail lights
|
|
if( m_lighthints[ end::rear ] == -1 ) {
|
|
cue_action( driver_hint::headcodepc5 );
|
|
}
|
|
else {
|
|
if( AIControllFlag ) {
|
|
pVehicles[ end::rear ]->RaLightsSet( -1, m_lighthints[ end::rear ] );
|
|
}
|
|
}
|
|
}
|
|
// for shunting mode
|
|
else if( OrderCurrentGet() & ( Shunt | Loose_shunt | Connect ) ) {
|
|
cue_action( driver_hint::headcodetb1 );
|
|
}
|
|
}
|
|
else if( is_car() ) {
|
|
Lights(
|
|
light::headlight_left | light::headlight_right,
|
|
light::redmarker_left | light::redmarker_right );
|
|
}
|
|
}
|
|
|
|
void
|
|
TController::control_compartment_lights() {
|
|
// compartment lights
|
|
if( mvOccupied->CompartmentLights.start_type != start_t::manual ) { return; }
|
|
|
|
auto const currentlightstate { mvOccupied->CompartmentLights.is_enabled };
|
|
auto const lightlevel { Global.fLuminance * ConsistShade };
|
|
auto const desiredlightstate{ (
|
|
currentlightstate ?
|
|
lightlevel < 0.40 : // turn off if lighting level goes above 0.4
|
|
lightlevel < 0.35 ) }; // turn on if lighting level goes below 0.35
|
|
if( desiredlightstate != currentlightstate ) {
|
|
cue_action( desiredlightstate ? driver_hint::consistlightson : driver_hint::consistlightsoff );
|
|
}
|
|
}
|
|
|
|
void
|
|
TController::control_doors() {
|
|
|
|
if( false == doors_open() ) { return; }
|
|
// jeżeli jedzie
|
|
// nie zamykać drzwi przy drganiach, bo zatrzymanie na W4 akceptuje niewielkie prędkości
|
|
if( mvOccupied->Vel > EU07_AI_MOVEMENT ) {
|
|
Doors( false );
|
|
return;
|
|
}
|
|
// HACK: crude way to deal with automatic door opening on W4 preventing further ride
|
|
// for human-controlled vehicles with no door control and dynamic brake auto-activating with door open
|
|
// TODO: check if this situation still happens and the hack is still needed
|
|
if( false == AIControllFlag && (mvControlling->EngineType == TEngineType::DieselEngine ? mvControlling->RList[mvControlling->MainCtrlPos].Mn > 0 : mvControlling->MainCtrlPowerPos() > 0) ) {
|
|
// for diesel engines react when engine is put past idle revolutions
|
|
// for others straightforward master controller check
|
|
Doors(false);
|
|
return;
|
|
}
|
|
}
|
|
|
|
void
|
|
TController::UpdateCommand() {
|
|
|
|
if( false == mvOccupied->CommandIn.Command.empty() && false == mvOccupied->RunInternalCommand() ) {
|
|
// rozpoznaj komende bo lokomotywa jej nie rozpoznaje
|
|
RecognizeCommand(); // samo czyta komendę wstawioną do pojazdu?
|
|
}
|
|
}
|
|
|
|
void
|
|
TController::UpdateNextStop() {
|
|
|
|
if( fLastStopExpDist > 0.0
|
|
&& mvOccupied->DistCounter > fLastStopExpDist ) {
|
|
// zaktualizować wyświetlanie rozkładu
|
|
TrainParams.StationStart = TrainParams.StationIndex;
|
|
fLastStopExpDist = -1.0; // usunąć licznik
|
|
if( true == m_makenextstopannouncement ) {
|
|
announce( announcement_t::next );
|
|
m_makenextstopannouncement = false; // keep next stop announcements suppressed until another scheduled stop
|
|
}
|
|
}
|
|
}
|
|
|
|
void
|
|
TController::determine_braking_distance() {
|
|
// przybliżona droga hamowania
|
|
// NOTE: we're ensuring some minimal braking distance to reduce ai flipping states between starting and braking
|
|
auto const velceil { std::max( 2.0, std::ceil( mvOccupied->Vel ) ) };
|
|
fBrakeDist = fDriverBraking * velceil * ( 40.0 + velceil );
|
|
if( fMass > 1000000.0 ) {
|
|
// korekta dla ciężkich, bo przeżynają - da to coś?
|
|
fBrakeDist *= 2.0;
|
|
}
|
|
if( -fAccThreshold > 0.05
|
|
&& mvOccupied->CategoryFlag == 1 ) {
|
|
fBrakeDist = velceil * velceil / 25.92 / -fAccThreshold;
|
|
}
|
|
if( mvOccupied->BrakeDelayFlag == bdelay_G ) {
|
|
// dla nastawienia G koniecznie należy wydłużyć drogę na czas reakcji
|
|
fBrakeDist += 2 * velceil;
|
|
}
|
|
if( mvOccupied->Vel > 15.0
|
|
&& mvControlling->EngineType == TEngineType::ElectricInductionMotor
|
|
&& is_emu() ) {
|
|
// HACK: make the induction motor powered EMUs start braking slightly earlier
|
|
fBrakeDist += 10.0;
|
|
}
|
|
/*
|
|
// take into account effect of gravity (but to stay on safe side of calculations, only downhill)
|
|
if( fAccGravity > 0.025 ) {
|
|
fBrakeDist *= ( 1.0 + fAccGravity );
|
|
// TBD: use version which shortens route going uphill, too
|
|
//fBrakeDist = std::max( fBrakeDist, fBrakeDist * ( 1.0 + fAccGravity ) );
|
|
}
|
|
*/
|
|
}
|
|
|
|
void
|
|
TController::scan_route( double const Range ) {
|
|
|
|
TableCheck( Range );
|
|
}
|
|
|
|
// check for potential collisions
|
|
void
|
|
TController::scan_obstacles( double const Range ) {
|
|
// HACK: vehicle order in the consist is based on intended travel direction
|
|
// if our actual travel direction doesn't match that, we should be scanning from the other end of the consist
|
|
// we cast to int to avoid getting confused by microstutters
|
|
auto *frontvehicle { pVehicles[ ( static_cast<int>( mvOccupied->V ) * iDirection >= 0 ? end::front : end::rear ) ] };
|
|
|
|
int routescandirection;
|
|
// for moving vehicle determine heading from velocity; for standing fall back on the set direction
|
|
if( std::abs(frontvehicle->MoverParameters->V) > 0.5 ? // ignore potential micro-stutters in oposite direction during "almost stop"
|
|
frontvehicle->MoverParameters->V > 0.0 :
|
|
pVehicle->DirectionGet() == frontvehicle->DirectionGet() ? iDirection >= 0 : iDirection <= 0 ) {
|
|
// towards coupler 0
|
|
routescandirection = end::front;
|
|
}
|
|
else {
|
|
// towards coupler 1
|
|
routescandirection = end::rear;
|
|
}
|
|
/*
|
|
if( pVehicle->MoverParameters->CabOccupied < 0 ) {
|
|
// flip the scan direction in the rear cab
|
|
routescandirection ^= routescandirection;
|
|
}
|
|
*/
|
|
Obstacle = neighbour_data();
|
|
auto const obstaclescanrange { std::max( is_car() ? 250.0 : 1000.0, Range ) };
|
|
auto const lookup { frontvehicle->find_vehicle( routescandirection, obstaclescanrange ) };
|
|
|
|
if( std::get<bool>( lookup ) == true ) {
|
|
|
|
Obstacle.vehicle = std::get<TDynamicObject *>( lookup );
|
|
Obstacle.vehicle_end = std::get<int>( lookup );
|
|
Obstacle.distance = std::get<double>( lookup );
|
|
|
|
if( Obstacle.distance < ( is_car() ? 50 : 100 ) ) {
|
|
// at short distances (re)calculate range between couplers directly
|
|
Obstacle.distance = TMoverParameters::CouplerDist( frontvehicle->MoverParameters, Obstacle.vehicle->MoverParameters );
|
|
}
|
|
}
|
|
}
|
|
|
|
void
|
|
TController::determine_proximity_ranges() {
|
|
// ustalenie dystansów w pozostałych przypadkach
|
|
switch (OrderCurrentGet())
|
|
{
|
|
case Connect: {
|
|
// podłączanie do składu
|
|
if (iDrivigFlags & moveConnect) {
|
|
// jeśli stanął już blisko, unikając zderzenia i można próbować podłączyć
|
|
fMinProximityDist = -1.0;
|
|
fMaxProximityDist = 0.0; //[m] dojechać maksymalnie
|
|
fVelPlus = 1.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania
|
|
fVelMinus = 0.5; // margines prędkości powodujący załączenie napędu
|
|
}
|
|
else {
|
|
// jak daleko, to jazda jak dla Shunt na kolizję
|
|
fMinProximityDist = 2.0;
|
|
fMaxProximityDist = 5.0; //[m] w takim przedziale odległości powinien stanąć
|
|
fVelPlus = 2.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania
|
|
fVelMinus = 1.0; // margines prędkości powodujący załączenie napędu
|
|
}
|
|
break;
|
|
}
|
|
case Disconnect: {
|
|
// 20.07.03 - manewrowanie wagonami
|
|
fMinProximityDist = 1.0;
|
|
fMaxProximityDist = 10.0; //[m]
|
|
fVelPlus = 1.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania
|
|
fVelMinus = 0.5; // margines prędkości powodujący załączenie napędu
|
|
break;
|
|
}
|
|
case Shunt: {
|
|
// na jaką odleglość i z jaką predkością ma podjechać
|
|
// TODO: test if we can use the distances calculation from obey_train
|
|
fMinProximityDist = std::min( 5 + iVehicles, 25 );
|
|
fMaxProximityDist = std::min( 10 + iVehicles, 50 );
|
|
// HACK: modern vehicles might brake slower at low speeds, increase safety margin as crude counter
|
|
if( mvControlling->EIMCtrlType > 0 ) {
|
|
fMinProximityDist += 5.0;
|
|
fMaxProximityDist += 5.0;
|
|
}
|
|
// take into account weather conditions
|
|
if (Global.FrictionWeatherFactor < 1.f
|
|
&& iVehicles > 1 ) {
|
|
fMinProximityDist += 5.0;
|
|
fMaxProximityDist += 5.0;
|
|
}
|
|
fVelPlus = 2.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania
|
|
// margines prędkości powodujący załączenie napędu
|
|
// były problemy z jazdą np. 3km/h podczas ładowania wagonów
|
|
fVelMinus = std::min( 0.1 * fShuntVelocity, 3.0 );
|
|
break;
|
|
}
|
|
case Loose_shunt: {
|
|
fMinProximityDist = -1.0;
|
|
fMaxProximityDist = 0.0; //[m] dojechać maksymalnie
|
|
fVelPlus = 2.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania
|
|
fVelMinus = 0.5; // margines prędkości powodujący załączenie napędu
|
|
break;
|
|
}
|
|
case Obey_train: {
|
|
// na jaka odleglosc i z jaka predkoscia ma podjechac do przeszkody
|
|
// jeśli pociąg
|
|
if( is_train() ) {
|
|
auto const [ minproximity, maxproximity ] { train_proximity_margins( IsAtPassengerStop ) };
|
|
fMinProximityDist = minproximity;
|
|
fMaxProximityDist = maxproximity;
|
|
|
|
if( iDrivigFlags & moveLate ) {
|
|
// jeśli spóźniony, to gna
|
|
fVelMinus = 1.0;
|
|
// dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania
|
|
fVelPlus = 5.0;
|
|
}
|
|
else {
|
|
// gdy nie musi się sprężać
|
|
// margines prędkości powodujący załączenie napędu; min 1.0 żeby nie ruszał przy 0.1
|
|
fVelMinus = std::clamp( std::round( 0.05 * VelDesired ), 1.0, 5.0 );
|
|
// normalnie dopuszczalne przekroczenie to 5% prędkości ale nie więcej niż 5km/h
|
|
// bottom margin raised to 2 km/h to give the AI more leeway at low speed limits
|
|
fVelPlus = std::clamp( std::ceil( 0.05 * VelDesired ), 2.0, 5.0 );
|
|
}
|
|
}
|
|
// samochod (sokista też)
|
|
else {
|
|
fMinProximityDist = std::max( 3.5, mvOccupied->Vel * 0.2 );
|
|
fMaxProximityDist = std::max( 9.5, mvOccupied->Vel * 0.375 ); //[m]
|
|
if( Global.FrictionWeatherFactor < 1.f ) {
|
|
// take into account weather conditions
|
|
fMinProximityDist += 0.75;
|
|
fMaxProximityDist += 0.75;
|
|
}
|
|
// margines prędkości powodujący załączenie napędu
|
|
fVelMinus = 2.0;
|
|
// dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania
|
|
fVelPlus = std::min( 10.0, mvOccupied->Vel * 0.1 );
|
|
}
|
|
break;
|
|
}
|
|
case Bank: {
|
|
// TODO: implement
|
|
break;
|
|
}
|
|
default: {
|
|
fMinProximityDist = 5.0;
|
|
fMaxProximityDist = 10.0; //[m]
|
|
fVelPlus = 2.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania
|
|
fVelMinus = 5.0; // margines prędkości powodujący załączenie napędu
|
|
}
|
|
} // switch OrderList[OrderPos]
|
|
}
|
|
|
|
void
|
|
TController::check_departure() {
|
|
|
|
if(( OrderCurrentGet() & ( Shunt | Loose_shunt | Obey_train | Bank | Connect ) ) == 0 ) { return; }
|
|
// odjechać sam może tylko jeśli jest w trybie jazdy
|
|
// automatyczne ruszanie po odstaniu albo spod SBL
|
|
if( VelSignal == 0.0
|
|
&& WaitingTime > 0.0
|
|
&& mvOccupied->RunningTrack.Velmax != 0.0 ) {
|
|
// jeśli stoi, a upłynął czas oczekiwania i tor ma niezerową prędkość
|
|
if( OrderCurrentGet() & (Shunt | Loose_shunt | Obey_train | Bank)
|
|
&& iDrivigFlags & moveStopHere ) {
|
|
// zakaz ruszania z miejsca bez otrzymania wolnej drogi
|
|
WaitingTime = -WaitingExpireTime;
|
|
}
|
|
else {
|
|
if( mvOccupied->CategoryFlag & 1 ) { // jeśli pociąg
|
|
PrepareDirection(); // zmieni ustawiony kierunek
|
|
SetVelocity( 20, 20 ); // jak się nastał, to niech jedzie 20km/h
|
|
WaitingTime = 0.0;
|
|
fWarningDuration = 1.5; // a zatrąbić trochę
|
|
}
|
|
else { // samochód ma stać, aż dostanie odjazd, chyba że stoi przez kolizję
|
|
if( eStopReason == stopBlock
|
|
&& Obstacle.distance > fDriverDist ) {
|
|
PrepareDirection(); // zmieni ustawiony kierunek
|
|
SetVelocity( -1, -1 ); // jak się nastał, to niech jedzie
|
|
WaitingTime = 0.0;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
else if( VelSignal == 0.0 && VelNext > 0.0 && mvOccupied->Vel < 1.0 && (iCoupler > 0 || (iDrivigFlags & moveStopHere) == 0) ) {
|
|
// Ra: tu jest coś nie tak, bo bez tego warunku ruszało w manewrowym !!!!
|
|
SetVelocity(VelNext, VelNext, stopSem); // omijanie SBL
|
|
}
|
|
}
|
|
|
|
// verify progress of load exchange
|
|
void
|
|
TController::check_load_exchange() {
|
|
|
|
ExchangeTime = 0.f;
|
|
DoesAnyDoorNeedOpening = false;
|
|
|
|
if( fStopTime > 0 ) { return; }
|
|
|
|
// czas postoju przed dalszą jazdą (np. na przystanku)
|
|
auto *vehicle { pVehicles[ end::front ] };
|
|
while( vehicle != nullptr ) {
|
|
auto const vehicleexchangetime { vehicle->LoadExchangeTime() };
|
|
DoesAnyDoorNeedOpening |= vehicleexchangetime > 0 && vehicle->LoadExchangeSpeed() == 0;
|
|
ExchangeTime = std::max( ExchangeTime, vehicleexchangetime );
|
|
vehicle = vehicle->Next();
|
|
}
|
|
|
|
if( pVehicle->DirectionGet() != m_lastexchangedirection ) {
|
|
// generally means the ai driver moved to the opposite end of the consist
|
|
// TODO: investigate whether user playing with the reverser can mess this up
|
|
auto const left { m_lastexchangedirection > 0 ? 1 : 2 };
|
|
auto const right { 3 - left };
|
|
m_lastexchangeplatforms =
|
|
( ( m_lastexchangeplatforms & left ) != 0 ? right : 0 )
|
|
+ ( ( m_lastexchangeplatforms & right ) != 0 ? left : 0 );
|
|
m_lastexchangedirection = pVehicle->DirectionGet();
|
|
}
|
|
if( false == TrainParams.IsMaintenance()
|
|
&& ( false == TestFlag(iDrivigFlags, moveDoorOpened)
|
|
|| true == DoesAnyDoorNeedOpening ) ) {
|
|
iDrivigFlags |= moveDoorOpened; // nie wykonywać drugi raz
|
|
remove_hint( driver_hint::doorleftopen );
|
|
remove_hint( driver_hint::doorrightopen );
|
|
Doors( true, m_lastexchangeplatforms );
|
|
}
|
|
}
|
|
|
|
void
|
|
TController::UpdateChangeDirection() {
|
|
// TODO: rework into driver mode independent routine
|
|
if( false == TestFlag( OrderCurrentGet(), Change_direction ) ) { return; }
|
|
|
|
if( true == AIControllFlag && mvOccupied->Vel < EU07_AI_NOMOVEMENT ) {
|
|
// sprobuj zmienic kierunek (może być zmieszane z jeszcze jakąś komendą)
|
|
// jeśli się zatrzymał, to zmieniamy kierunek jazdy, a nawet kabinę/człon
|
|
Activation(); // ustawienie zadanego wcześniej kierunku i ewentualne przemieszczenie AI
|
|
// Change_direction (tylko dla AI)
|
|
}
|
|
// shared part of the routine, implement if direction matches what was requested
|
|
if( mvOccupied->Vel < EU07_AI_NOMOVEMENT
|
|
&& iDirection == iDirectionOrder ) {
|
|
// NOTE: we can't be sure there's a visible signal within scan range after direction change
|
|
// which would normally overwrite the old limit, so we reset signal value manually here
|
|
VelSignal = -1;
|
|
VelSignalNext = -1;
|
|
PrepareEngine();
|
|
JumpToNextOrder(); // następnie robimy, co jest do zrobienia (Shunt albo Obey_train)
|
|
if( OrderCurrentGet() & (Shunt | Loose_shunt | Connect) && false == TestFlag(iDrivigFlags, moveStopHere) ) {
|
|
// jeśli dalej mamy manewry
|
|
// o ile nie ma stać w miejscu,
|
|
// jechać od razu w przeciwną stronę i nie trąbić z tego tytułu:
|
|
iDrivigFlags &= ~moveStartHorn;
|
|
SetVelocity(fShuntVelocity, fShuntVelocity);
|
|
}
|
|
}
|
|
}
|
|
|
|
void
|
|
TController::UpdateLooseShunt() {
|
|
// when loose shunting try to detect situations where engaged brakes in a consist to be pushed prevent movement
|
|
// TODO: run also for potential settings-based virtual assistant
|
|
auto const autobrakerelease { ( true == AIControllFlag ) };
|
|
|
|
if( autobrakerelease
|
|
&& Obstacle.distance < 1.0
|
|
&& AccDesired > 0.1
|
|
&& mvOccupied->Vel < 1.0 ) {
|
|
|
|
auto *vehicle { Obstacle.vehicle };
|
|
auto const direction { ( vehicle->Prev() != nullptr ? end::front : end::rear ) };
|
|
while( vehicle != nullptr ) {
|
|
if( vehicle->MoverParameters->BrakePress > 0.2 ) {
|
|
vehicle->MoverParameters->BrakeLevelSet( 0 ); // hamulec na zero, aby nie hamował
|
|
vehicle->MoverParameters->BrakeReleaser( 1 ); // wyluzuj pojazd, aby dało się dopychać
|
|
}
|
|
// NOTE: we trust the consist to be arranged in a valid chain
|
|
// TBD, TODO: traversal direction validation?
|
|
vehicle = direction == end::front ? vehicle->Prev() : vehicle->Next();
|
|
}
|
|
}
|
|
}
|
|
|
|
void
|
|
TController::UpdateObeyTrain() {
|
|
|
|
UpdateNextStop();
|
|
|
|
if( (iDrivigFlags & moveGuardSignal) != 0
|
|
&& VelDesired > 0.0 ) {
|
|
// komunikat od kierownika tu, bo musi być wolna droga i odczekany czas stania
|
|
iDrivigFlags &= ~moveGuardSignal; // tylko raz nadać
|
|
iDrivigFlags &= ~moveGuardOpenDoor; // nie trzeba już otwierać drzwi
|
|
if( false == tsGuardSignal.empty() ) {
|
|
tsGuardSignal.stop();
|
|
// w zasadzie to powinien mieć flagę, czy jest dźwiękiem radiowym, czy bezpośrednim
|
|
// albo trzeba zrobić dwa dźwięki, jeden bezpośredni, słyszalny w
|
|
// pobliżu, a drugi radiowy, słyszalny w innych lokomotywach
|
|
// na razie zakładam, że to nie jest dźwięk radiowy, bo trzeba by zrobić
|
|
// obsługę kanałów radiowych itd.
|
|
if( iGuardRadio == 0 ) {
|
|
// jeśli nie przez radio
|
|
tsGuardSignal.owner( pVehicle );
|
|
// place virtual conductor some distance away
|
|
tsGuardSignal.offset( { pVehicle->MoverParameters->Dim.W * -0.75f, 1.7f, std::min( -20.0, -0.2 * fLength ) } );
|
|
tsGuardSignal.play( sound_flags::exclusive );
|
|
// NOTE: we can't rely on is_playing() check as sound playback is based on distance from local camera
|
|
fActionTime = -5.0; // niech trochę potrzyma
|
|
}
|
|
else {
|
|
// radio message
|
|
tsGuardSignal.owner( pVehicle );
|
|
/*
|
|
tsGuardSignal.offset( { 0.f, 2.f, pVehicle->MoverParameters->Dim.L * 0.4f * ( pVehicle->MoverParameters->CabOccupied < 0 ? -1 : 1 ) } );
|
|
tsGuardSignal.play( sound_flags::exclusive );
|
|
*/
|
|
simulation::radio_message( &tsGuardSignal, iGuardRadio );
|
|
// NOTE: we can't rely on is_playing() check as sound playback is based on distance from local camera
|
|
fActionTime = -5.0; // niech trochę potrzyma
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
void
|
|
TController::UpdateConnect() {
|
|
// podłączanie do składu
|
|
if (iDrivigFlags & moveConnect) {
|
|
// sprzęgi sprawdzamy w pierwszej kolejności, bo jak połączony, to koniec
|
|
auto *vehicle { iCouplingVehicle.value().first };
|
|
auto const couplingend { iCouplingVehicle.value().second };
|
|
auto *vehicleparameters { vehicle->MoverParameters };
|
|
auto const &neighbour { vehicleparameters->Neighbours[ couplingend ] };
|
|
// vehicles which can't share their control get coupled without the control connection (eu07/maszyna#520)
|
|
auto expectedcoupling { iCoupler };
|
|
if( neighbour.vehicle != nullptr ) {
|
|
auto const neighbourend { neighbour.vehicle_end != 2 ? neighbour.vehicle_end : vehicleparameters->Couplers[ couplingend ].ConnectedNr };
|
|
expectedcoupling = vehicleparameters->CompatibleCoupling( couplingend, *neighbour.vehicle->MoverParameters, neighbourend, iCoupler );
|
|
}
|
|
if( vehicleparameters->Couplers[ couplingend ].CouplingFlag != expectedcoupling ) {
|
|
if( neighbour.vehicle != nullptr && neighbour.distance < 10 ) {
|
|
// check whether we need to attach coupler adapter
|
|
auto coupleriscompatible{true};
|
|
auto const &coupler{vehicleparameters->Couplers[couplingend]};
|
|
if (coupler.type() != TCouplerType::Automatic)
|
|
{
|
|
auto const &othercoupler = neighbour.vehicle->MoverParameters->Couplers[(neighbour.vehicle_end != 2 ? neighbour.vehicle_end : coupler.ConnectedNr)];
|
|
if (othercoupler.type() == TCouplerType::Automatic)
|
|
{
|
|
coupleriscompatible = false;
|
|
cue_action(driver_hint::couplingadapterattach, couplingend);
|
|
}
|
|
}
|
|
// próba podczepienia
|
|
if ((AIControllFlag || Global.AITrainman) && coupleriscompatible && neighbour.distance < 2)
|
|
{
|
|
vehicleparameters->Attach(couplingend, neighbour.vehicle_end, neighbour.vehicle->MoverParameters, iCoupler);
|
|
}
|
|
}
|
|
}
|
|
// NOTE: no else as the preceeding block can potentially establish expected connection
|
|
if( vehicleparameters->Couplers[ couplingend ].CouplingFlag == expectedcoupling ) {
|
|
// jeżeli został podłączony
|
|
CheckVehicles( Connect ); // sprawdzić światła nowego składu
|
|
|
|
iCoupler = 0; // dalsza jazda manewrowa już bez łączenia
|
|
iCouplingVehicle.reset();
|
|
iDrivigFlags &= ~moveConnect; // zdjęcie flagi doczepiania
|
|
JumpToNextOrder( true ); // wykonanie następnej komendy
|
|
}
|
|
} // moveConnect
|
|
else {
|
|
// początek podczepiania, z wyłączeniem sprawdzania fTrackBlock
|
|
if( Obstacle.distance <= 20.0 && !iCouplingVehicle ) {
|
|
// write down which vehicle should be coupled with the target consist,
|
|
// so we don't lose track of it if the user does something unexpected
|
|
iCouplingVehicle = {pVehicles[end::front], (pVehicles[end::front]->DirectionGet() > 0 ? end::front : end::rear)};
|
|
iDrivigFlags |= moveConnect;
|
|
}
|
|
}
|
|
}
|
|
|
|
void
|
|
TController::GuardOpenDoor() {
|
|
if ((iDrivigFlags & moveGuardOpenDoor) != 0) {
|
|
auto *vehicle{ pVehicles[end::front] };
|
|
while (vehicle != nullptr && vehicle->MoverParameters->Doors.range == 0) {
|
|
vehicle = vehicle->Next();
|
|
}
|
|
if (vehicle != nullptr && vehicle->MoverParameters->Doors.range > 0) {
|
|
auto const lewe = vehicle->DirectionGet() > 0 ? 1 : 2;
|
|
auto const prawe = 3 - lewe;
|
|
if (m_lastexchangeplatforms & lewe) {
|
|
vehicle->MoverParameters->OperateDoors(side::left, true, range_t::local);
|
|
}
|
|
if (m_lastexchangeplatforms & prawe) {
|
|
vehicle->MoverParameters->OperateDoors(side::right, true, range_t::local);
|
|
}
|
|
}
|
|
else {
|
|
iDrivigFlags &= ~moveGuardOpenDoor;
|
|
}
|
|
}
|
|
}
|
|
|
|
int
|
|
TController::unit_count( int const Threshold ) const {
|
|
|
|
auto *vehicle { pVehicle };
|
|
auto unitcount { 1 };
|
|
do {
|
|
auto const decoupledend{ ( vehicle->DirectionGet() > 0 ? // numer sprzęgu od strony czoła składu
|
|
end::rear :
|
|
end::front ) };
|
|
auto const coupling { vehicle->MoverParameters->Couplers[ decoupledend ].CouplingFlag };
|
|
if( coupling == coupling::faux ) {
|
|
break;
|
|
}
|
|
// jeżeli sprzęg zablokowany to liczymy człony jako jeden
|
|
if( ( coupling & coupling::permanent ) == 0 ) {
|
|
++unitcount;
|
|
}
|
|
vehicle = vehicle->Next();
|
|
} while( unitcount < Threshold );
|
|
|
|
return unitcount;
|
|
}
|
|
|
|
void
|
|
TController::UpdateDisconnect() {
|
|
|
|
if( iVehicleCount >= 0 ) {
|
|
// early test for human drivers, who might disregard the proper procedure, or perform it before they receive the order to
|
|
if( false == AIControllFlag && unit_count(iVehicleCount + 2) <= iVehicleCount + 1 ) {
|
|
// iVehicleCount = 0 means the consist should be reduced to (1) leading unit, thus we increase our test values by 1
|
|
iVehicleCount = -2; // odczepiono, co było do odczepienia
|
|
return; // we'll wrap up the procedure on the next update beat
|
|
}
|
|
// regular uncoupling procedure, performed by ai and naively expected from the human drivers
|
|
// 3rd stage: change direction, compress buffers and uncouple
|
|
if( iDirection != iDirectionOrder ) {
|
|
cue_action( driver_hint::mastercontrollersetreverserunlock );
|
|
cue_action( driver_hint::directionother );
|
|
}
|
|
if( (iDrivigFlags & movePress) != 0 && iDirection == iDirectionOrder ) {
|
|
if( iVehicleCount >= 0 ) {
|
|
// zmieni się po odczepieniu
|
|
WriteLog( "Uncoupling [" + mvOccupied->Name + "]: actuating and compressing buffers..." );
|
|
cue_action( driver_hint::independentbrakerelease );
|
|
cue_action( driver_hint::bufferscompress );
|
|
}
|
|
|
|
WriteLog( "Uncoupling [" + mvOccupied->Name + "]: from " + ( mvOccupied->DirAbsolute > 0 ? "front" : "rear" ) );
|
|
auto *decoupledvehicle { pVehicle }; // pojazd do odczepienia, w (pVehicle) siedzi AI
|
|
int decoupledend; // numer sprzęgu, który sprawdzamy albo odczepiamy
|
|
auto vehiclecount { iVehicleCount }; // ile wagonów ma zostać
|
|
// szukanie pojazdu do odczepienia
|
|
do {
|
|
decoupledend = decoupledvehicle->DirectionGet() > 0 ? // numer sprzęgu od strony czoła składu
|
|
end::front :
|
|
end::rear;
|
|
// jeżeli sprzęg zablokowany to liczymy człony jako jeden
|
|
if( decoupledvehicle->MoverParameters->Couplers[ decoupledend ].CouplingFlag & coupling::permanent ) {
|
|
++vehiclecount;
|
|
}
|
|
if( decoupledvehicle != pVehicle ) {
|
|
decoupledvehicle->MoverParameters->BrakeReleaser( 1 ); // wyluzuj pojazd, aby dało się dopychać
|
|
}
|
|
if( vehiclecount ) { // jeśli jeszcze nie koniec
|
|
decoupledvehicle = decoupledvehicle->Prev(); // kolejny w stronę czoła składu (licząc od tyłu), bo dociskamy
|
|
if( decoupledvehicle == nullptr ) {
|
|
vehiclecount = 0; // nie ma co dalej sprawdzać, odczepianie zakończone
|
|
}
|
|
}
|
|
} while( vehiclecount-- );
|
|
if( decoupledvehicle == nullptr ) {
|
|
// no target, or already just virtual coupling
|
|
WriteLog( "Uncoupling [" + mvOccupied->Name + "]: didn't find anything to disconnect" );
|
|
iVehicleCount = -2; // odczepiono, co było do odczepienia
|
|
}
|
|
else {
|
|
if( AIControllFlag || Global.AITrainman ) {
|
|
decoupledvehicle->Dettach( decoupledend );
|
|
}
|
|
// tylko jeśli odepnie
|
|
if( decoupledvehicle->MoverParameters->Couplers[ decoupledend ].CouplingFlag == coupling::faux ) {
|
|
WriteLog( "Uncoupling [" + mvOccupied->Name + "]: uncoupled" );
|
|
iVehicleCount = -2;
|
|
// update trainset state
|
|
CheckVehicles( Disconnect );
|
|
// potentially remove coupler adapter
|
|
/*
|
|
if( decoupledvehicle->MoverParameters->Couplers[ decoupledend ].has_adapter() ) {
|
|
decoupledvehicle->remove_coupler_adapter( decoupledend );
|
|
}
|
|
*/
|
|
if( pVehicles[ end::front ]->MoverParameters->Couplers[ decoupledend ].has_adapter() ) {
|
|
cue_action( driver_hint::couplingadapterremove, decoupledend );
|
|
}
|
|
}
|
|
} // a jak nie, to dociskać dalej
|
|
}
|
|
// 2nd stage: apply consist brakes and change direction
|
|
if( ( iDrivigFlags & movePress ) == 0 ) {
|
|
// store initial consist direction
|
|
if( !iDirectionBackup ) {
|
|
iDirectionBackup = iDirection;
|
|
}
|
|
if( false == IsConsistBraked ) {
|
|
WriteLog( "Uncoupling [" + mvOccupied->Name + "]: applying consist brakes..." );
|
|
cue_action( driver_hint::trainbrakeapply );
|
|
}
|
|
// jeśli w miarę został zahamowany (ciśnienie mniejsze niż podane na pozycji 3, zwyle 0.37)
|
|
else {
|
|
WriteLog( "Uncoupling [" + mvOccupied->Name + "]: direction change" );
|
|
/* // TODO: test if this block is needed
|
|
if( BrakeSystem == TBrakeSystem::ElectroPneumatic ) {
|
|
// wyłączenie EP, gdy wystarczy (może nie być potrzebne, bo na początku jest)
|
|
mvOccupied->BrakeLevelSet( 0 );
|
|
}
|
|
*/
|
|
iDirectionOrder = -iDirection; // zmiana kierunku jazdy na przeciwny (dociskanie)
|
|
iDrivigFlags |= movePress; // następnie będzie dociskanie
|
|
}
|
|
}
|
|
} // odczepianie
|
|
if( iVehicleCount < 0 ) {
|
|
// 4th stage: restore initial direction
|
|
if( iDirectionBackup ) {
|
|
iDirectionOrder = iDirectionBackup.value();
|
|
iDirectionBackup.reset();
|
|
}
|
|
if( iDirection != iDirectionOrder ) {
|
|
WriteLog( "Uncoupling [" + mvOccupied->Name + "]: second direction change" );
|
|
cue_action( driver_hint::mastercontrollersetreverserunlock );
|
|
cue_action( driver_hint::directionother ); // zmiana kierunku jazdy na właściwy
|
|
}
|
|
// 5th stage: clean up and move on to next order
|
|
if( iDirection == iDirectionOrder ) {
|
|
iDrivigFlags &= ~movePress; // koniec dociskania
|
|
JumpToNextOrder( true ); // zmieni światła
|
|
TableClear(); // skanowanie od nowa
|
|
iDrivigFlags &= ~moveStartHorn; // bez trąbienia przed ruszeniem
|
|
}
|
|
}
|
|
}
|
|
|
|
void
|
|
TController::handle_engine() {
|
|
// HACK: activate route scanning if an idling vehicle is activated by a human user
|
|
if( OrderCurrentGet() == Wait_for_orders
|
|
&& false == iEngineActive
|
|
// && ( false == AIControllFlag )
|
|
&& true == mvOccupied->Power24vIsAvailable ) {
|
|
OrderNext( Prepare_engine );
|
|
}
|
|
// basic engine preparation
|
|
if( OrderCurrentGet() == Prepare_engine && PrepareEngine() ) {
|
|
// gotowy do drogi?
|
|
JumpToNextOrder();
|
|
}
|
|
// engine state can potentially deteriorate in one of usual driving modes
|
|
if( OrderCurrentGet() & (Change_direction | Connect | Disconnect | Shunt | Loose_shunt | Obey_train | Bank)
|
|
&& false == iEngineActive ) {
|
|
// jeśli coś ma robić to niech odpala do skutku
|
|
PrepareEngine();
|
|
}
|
|
}
|
|
|
|
void
|
|
TController::handle_orders() {
|
|
|
|
switch (OrderCurrentGet())
|
|
{
|
|
case Release_engine: {
|
|
if( ReleaseEngine() ) { // zdana maszyna?
|
|
JumpToNextOrder();
|
|
}
|
|
break;
|
|
}
|
|
case Obey_train: {
|
|
UpdateObeyTrain();
|
|
break;
|
|
}
|
|
case Loose_shunt: {
|
|
UpdateLooseShunt();
|
|
break;
|
|
}
|
|
case Connect: {
|
|
UpdateConnect();
|
|
break;
|
|
}
|
|
case Disconnect: {
|
|
UpdateDisconnect();
|
|
break;
|
|
}
|
|
case Jump_to_first_order: {
|
|
if( OrderPos > 1 ) {
|
|
OrderPos = 1; // w zerowym zawsze jest czekanie
|
|
}
|
|
else {
|
|
++OrderPos;
|
|
}
|
|
#if LOGORDERS
|
|
OrdersDump("Jump_to_first_order");
|
|
#endif
|
|
break;
|
|
}
|
|
default: {
|
|
// special case, change_direction potentially received during partially completed coupling operation
|
|
// this is unlikely to happen for the AI, but can happen for a (slower) human user
|
|
if( TestFlag( iDrivigFlags, moveConnect ) ) {
|
|
UpdateConnect();
|
|
}
|
|
break;
|
|
}
|
|
} // switch OrderList[OrderPos]
|
|
UpdateChangeDirection();
|
|
}
|
|
|
|
// the stages of uncoupling: each one sets the speed for the next
|
|
void
|
|
TController::set_velocity_for_uncoupling() {
|
|
|
|
if( iVehicleCount < 0 ) {
|
|
// 4th stage: restore initial direction
|
|
if( ( iDrivigFlags & movePress ) != 0 ) {
|
|
SetVelocity( 0, 0, stopJoin );
|
|
}
|
|
return;
|
|
}
|
|
// 3rd stage: compress buffers and uncouple
|
|
if( ( iDrivigFlags & movePress ) != 0 && iDirection == iDirectionOrder ) {
|
|
SetVelocity( 2, 0 ); // jazda w ustawionym kierunku z prędkością 2
|
|
return;
|
|
}
|
|
// 1st stage: bring it to stop
|
|
// 2nd stage: apply consist brakes and change direction
|
|
SetVelocity( 0, 0, stopJoin );
|
|
}
|
|
|
|
// uphill, the gradient alone brings a slow train to a stand within metres, far sooner than a released
|
|
// brake applies; so the train brake goes on while the train is coming to a stand, stays on while it
|
|
// stands, and is applied for real if the train has started to roll back
|
|
void
|
|
TController::hold_train_coming_to_stand_uphill() {
|
|
|
|
if( ( false == is_train() )
|
|
|| ( ( OrderCurrentGet() & Obey_train ) == 0 )
|
|
|| ( VelNext != 0.0 )
|
|
|| ( ActualProximityDist > fMaxProximityDist )
|
|
|| ( fAccGravity >= EU07_AI_UPHILLGRAVITY ) ) {
|
|
return;
|
|
}
|
|
auto const vel { DirectionalVel() };
|
|
if( std::abs( vel ) < EU07_AI_NOMOVEMENT ) {
|
|
VelDesired = 0.0;
|
|
AccDesired = std::min( AccDesired, EU07_AI_NOACCELERATION );
|
|
return;
|
|
}
|
|
if( ( vel < 0.0 )
|
|
|| ( ( vel < 5.0 ) && ( AccDesired < 0.0 ) )
|
|
// rolling to a stand on the gradient alone, the brake has to be on its way before the train stops:
|
|
// once the time left to the stand is no longer than half of what the brake takes to apply, apply it; any
|
|
// sooner and the brake takes off more of the distance than the stop was planned with
|
|
|| ( ( BrakeSystem == TBrakeSystem::Pneumatic )
|
|
// not for a train that is short of where it is to stop and is to pull up further
|
|
&& ( AccDesired <= 0.0 )
|
|
&& ( vel / 3.6 / -fAccGravity <= 0.5 * brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) ) {
|
|
// the gradient alone already slows the train down nearly this much; ask for enough on top of it that
|
|
// the brake is applied for sure, not held back by the margin against small corrections
|
|
AccDesired = std::min( AccDesired, fAccGravity - std::max( 0.15, fBrake_a0[ 0 ] ) - brake_increase_margin() );
|
|
}
|
|
}
|
|
|
|
void
|
|
TController::pick_optimal_speed( double const Range ) {
|
|
|
|
// if( ( OrderCurrentGet() & ( Shunt | Loose_shunt | Obey_train | Bank | Connect | Disconnect | Change_direction ) ) == 0 ) { return; }
|
|
|
|
// set initial velocity and acceleration values
|
|
SetDriverPsyche(); // ustawia AccPreferred (potrzebne tu?)
|
|
VelDesired = fVelMax; // wstępnie prędkość maksymalna dla pojazdu(-ów), będzie następnie ograniczana
|
|
AccDesired = AccPreferred; // AccPreferred wynika z osobowości mechanika
|
|
|
|
// nie przekraczać rozkladowej
|
|
if( (OrderCurrentGet() & Obey_train) != 0
|
|
&& TrainParams.TTVmax > 0.0 ) {
|
|
VelDesired =
|
|
min_speed(
|
|
VelDesired,
|
|
TrainParams.TTVmax );
|
|
}
|
|
|
|
// VelNext = VelDesired; // maksymalna prędkość wynikająca z innych czynników niż trajektoria ruchu
|
|
// HACK: -1 means we can pick up 0 speed limits in ( point.velnext > velnext ) tests aimed to find highest next speed,
|
|
// but also doubles as 'max speed' in min_speed tests, so it shouldn't interfere if we don't find any speed limits
|
|
VelNext = -1.0;
|
|
|
|
// basic velocity and acceleration adjustments
|
|
// jeśli manewry, to ograniczamy prędkość
|
|
if( ( OrderCurrentGet() & ( Obey_train | Bank ) ) == 0 ) { // spokojne manewry
|
|
SetVelocity( fShuntVelocity, fShuntVelocity );
|
|
VelDesired =
|
|
min_speed(
|
|
VelDesired,
|
|
fShuntVelocity );
|
|
}
|
|
// uncoupling mode changes velocity/acceleration between stages
|
|
if( ( OrderCurrentGet() & Disconnect ) != 0 ) {
|
|
set_velocity_for_uncoupling();
|
|
}
|
|
|
|
VelLimitLastDist = { VelDesired, -1 };
|
|
SwitchClearDist = -1;
|
|
ActualProximityDist = Range; // funkcja Update() może pozostawić wartości bez zmian
|
|
|
|
// if we're idling bail out early
|
|
if( false == is_active() ) {
|
|
VelDesired = 0.0;
|
|
VelNext = 0.0;
|
|
AccDesired = std::min( AccDesired, EU07_AI_NOACCELERATION );
|
|
return;
|
|
}
|
|
|
|
// Ra: odczyt (ActualProximityDist), (VelNext) i (AccPreferred) z tabelki prędkosci
|
|
check_route_ahead( Range );
|
|
|
|
check_departure();
|
|
|
|
// if ordered to turn off the vehicle, try to stop
|
|
if( true == TestFlag( OrderCurrentGet(), Release_engine ) ) {
|
|
SetVelocity( 0, 0, stopSleep );
|
|
}
|
|
// if ordered to change direction, try to stop
|
|
if( true == TestFlag( OrderCurrentGet(), Change_direction ) ) {
|
|
SetVelocity( 0, 0, stopDir );
|
|
}
|
|
|
|
adjust_desired_speed_for_obstacles();
|
|
adjust_desired_speed_for_limits();
|
|
adjust_desired_speed_for_target_speed( Range );
|
|
adjust_desired_speed_for_current_speed();
|
|
adjust_desired_speed_for_braking_test();
|
|
|
|
// Ra 2F1I: wyłączyć kiedyś to uśrednianie i przeanalizować skanowanie, czemu migocze
|
|
if( AccDesired > EU07_AI_NOACCELERATION ) { // hamowania lepeiej nie uśredniać
|
|
AccDesired = fAccDesiredAv =
|
|
0.2 * AccDesired +
|
|
0.8 * fAccDesiredAv; // uśrednione, żeby ograniczyć migotanie
|
|
}
|
|
if( VelDesired == 0.0 ) {
|
|
// Ra 2F1J: jeszcze jedna prowizoryczna łatka
|
|
AccDesired = std::min( AccDesired, EU07_AI_NOACCELERATION );
|
|
}
|
|
|
|
// last step sanity check, until the whole calculation is straightened out
|
|
AccDesired = std::min( AccDesired, AccPreferred );
|
|
AccDesired = std::clamp(
|
|
AccDesired,
|
|
is_car() ? -2.0 : -0.9,
|
|
is_car() ? 2.0 : 0.9 );
|
|
|
|
// done last, so that none of the adjustments above, made for a train moving forward, can undo it
|
|
hold_train_coming_to_stand_uphill();
|
|
|
|
// if the route ahead is blocked we might need to head the other way
|
|
check_route_behind( 1000 ); // NOTE: legacy scan range value
|
|
}
|
|
|
|
void
|
|
TController::adjust_desired_speed_for_obstacles() {
|
|
// prędkość w kierunku jazdy, ujemna gdy jedzie w przeciwną stronę niż powinien
|
|
auto const vel { DirectionalVel() };
|
|
|
|
if (VelDesired < 0.0)
|
|
VelDesired = fVelMax; // bo VelDesired<0 oznacza prędkość maksymalną
|
|
|
|
// Ra: jazda na widoczność
|
|
if( Obstacle.distance < 5000 ) {
|
|
// mamy coś z przodu
|
|
// prędkość pojazdu z przodu (zakładając, że jedzie w tę samą stronę!!!)
|
|
auto const k { Obstacle.vehicle->MoverParameters->Vel };
|
|
|
|
if( k - vel < 5 ) {
|
|
// porównanie modułów prędkości [km/h]
|
|
// zatroszczyć się trzeba, jeśli tamten nie jedzie znacząco szybciej
|
|
if( Obstacle.distance < ActualProximityDist ) {
|
|
// the vehicle ahead, not the stop found by the scan, is what the train is now to stop short of
|
|
bStopTargetIsPassengerStop = false;
|
|
}
|
|
ActualProximityDist = std::min<double>(
|
|
ActualProximityDist,
|
|
Obstacle.distance );
|
|
|
|
if( Obstacle.distance <= (
|
|
mvOccupied->CategoryFlag & 2 ?
|
|
100.0 : // cars
|
|
250.0 ) ) { // others
|
|
// regardless of driving mode at close distance take precaution measures:
|
|
// match the other vehicle's speed or slow down if the other vehicle is stopped
|
|
VelDesired =
|
|
min_speed(
|
|
VelDesired,
|
|
std::max(
|
|
k,
|
|
mvOccupied->CategoryFlag & 2 ?
|
|
40.0 : // cars
|
|
20.0 ) ); // others
|
|
if( vel > VelDesired + fVelPlus ) {
|
|
// if going too fast force some prompt braking
|
|
AccPreferred = std::min(
|
|
mvOccupied->CategoryFlag & 2 ? -0.65 : // cars
|
|
-0.30, // others
|
|
AccPreferred );
|
|
}
|
|
}
|
|
|
|
double const distance = Obstacle.distance - fMaxProximityDist - fBrakeDist * 1.15; // odległość bezpieczna zależy od prędkości
|
|
if( distance < 0.0 ) {
|
|
// jeśli odległość jest zbyt mała
|
|
if( k < 10.0 ) // k - prędkość tego z przodu
|
|
{ // jeśli tamten porusza się z niewielką prędkością albo stoi
|
|
// keep speed difference within a safer margin
|
|
VelDesired = std::floor(
|
|
min_speed(
|
|
VelDesired,
|
|
Obstacle.distance > 100 ? k + 20.0 : std::min(8.0, k + 4.0) ) );
|
|
|
|
if( ( OrderCurrentGet() & ( Connect | Loose_shunt ) ) != 0 ) {
|
|
// jeśli spinanie, to jechać dalej
|
|
AccPreferred = std::min( 0.35, AccPreferred ); // nie hamuj
|
|
VelNext = std::floor( std::min( 8.0, k + 2.0 ) ); // i pakuj się na tamtego
|
|
}
|
|
else {
|
|
// a normalnie to hamować
|
|
VelNext = 0.0;
|
|
if( Obstacle.distance <= fMinProximityDist ) {
|
|
VelDesired = 0.0;
|
|
}
|
|
|
|
if( mvOccupied->CategoryFlag & 1
|
|
&& OrderCurrentGet() & Obey_train ) {
|
|
// trains which move normally should try to stop at safe margin
|
|
ActualProximityDist -= fDriverDist;
|
|
}
|
|
}
|
|
}
|
|
else {
|
|
// jeśli oba jadą, to przyhamuj lekko i ogranicz prędkość
|
|
if( Obstacle.distance < (
|
|
mvOccupied->CategoryFlag & 2 ?
|
|
fMaxProximityDist + 0.5 * vel : // cars
|
|
2.0 * fMaxProximityDist + 2.0 * vel ) ) { //others
|
|
// jak tamten jedzie wolniej a jest w drodze hamowania
|
|
AccPreferred = std::min( -0.9, AccPreferred );
|
|
VelNext = min_speed( std::round( k ) - 5.0, VelDesired );
|
|
if( Obstacle.distance <= (
|
|
mvOccupied->CategoryFlag & 2 ?
|
|
fMaxProximityDist : // cars
|
|
2.0 * fMaxProximityDist ) ) { //others
|
|
// try to force speed change if obstacle is really close
|
|
VelDesired = VelNext;
|
|
}
|
|
}
|
|
}
|
|
ReactionTime = mvOccupied->Vel > EU07_AI_NOMOVEMENT ? 0.1 : // orientuj się, bo jest goraco
|
|
2.0; // we're already standing still, so take it easy
|
|
}
|
|
else {
|
|
if( OrderCurrentGet() & Connect ) {
|
|
// if there's something nearby in the connect mode don't speed up too much
|
|
VelDesired =
|
|
min_speed(
|
|
VelDesired,
|
|
Obstacle.distance > 100 ? 20.0 : 4.0 );
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
void
|
|
TController::adjust_desired_speed_for_limits() {
|
|
// speed caps checks
|
|
// sprawdzamy możliwe ograniczenia prędkości
|
|
if( VelSignal >= 0 ) {
|
|
// jeśli skład był zatrzymany na początku i teraz już może jechać
|
|
VelDesired =
|
|
min_speed(
|
|
VelDesired,
|
|
VelSignal );
|
|
}
|
|
if( mvOccupied->RunningTrack.Velmax >= 0 ) {
|
|
// ograniczenie prędkości z trajektorii ruchu
|
|
VelDesired =
|
|
min_speed(
|
|
VelDesired,
|
|
mvOccupied->RunningTrack.Velmax ); // uwaga na ograniczenia szlakowej!
|
|
}
|
|
if( VelforDriver >= 0 ) {
|
|
// tu jest zero przy zmianie kierunku jazdy
|
|
// Ra: tu może być 40, jeśli mechanik nie ma znajomości szlaaku, albo kierowca jeździ 70
|
|
VelDesired =
|
|
min_speed(
|
|
VelDesired,
|
|
VelforDriver );
|
|
}
|
|
|
|
// recalculate potential load exchange duration
|
|
check_load_exchange();
|
|
if( ExchangeTime > 0
|
|
|| mvOccupied->Vel > 2.0 ) { // HACK: force timer reset if the load exchange is cancelled due to departure
|
|
WaitingSet( ExchangeTime );
|
|
}
|
|
if( fStopTime < 0 ) {
|
|
VelDesired = 0.0; // jak ma czekać, to nie ma jazdy
|
|
cue_action( driver_hint::waitloadexchange );
|
|
return; // speed limit can't get any lower
|
|
}
|
|
|
|
if( (OrderCurrentGet() & (Shunt | Loose_shunt | Obey_train | Bank)) != 0 && (iDrivigFlags & moveStopHere) != 0 && mvOccupied->Vel < 0.01 && VelSignalNext == 0.0 ) {
|
|
// w Connect nie, bo moveStopHere odnosi się do stanu po połączeniu
|
|
// jeśli ma czekać na wolną drogę, stoi a wyjazdu nie ma, to ma stać
|
|
VelDesired = 0.0;
|
|
return; // speed limit can't get any lower
|
|
}
|
|
|
|
if( OrderCurrentGet() == Wait_for_orders ) {
|
|
// wait means sit and wait
|
|
VelDesired = 0.0;
|
|
return; // speed limit can't get any lower
|
|
}
|
|
}
|
|
|
|
// how long the present acceleration of a consist lasts whatever is done with the handle now: half the time
|
|
// its pneumatic brake takes to apply (while speeding up) or to release (while slowing down), which in G
|
|
// is tens of seconds; never shorter than the look-ahead the AI has always used
|
|
static double
|
|
brake_response_horizon( TMoverParameters const *Vehicle, TBrakeSystem const Brakesystem, double const Acceleration, double const Brakea0 ) {
|
|
|
|
auto horizon { ( 1.0 - Brakea0 ) * 30.0 / 3.6 };
|
|
if( Brakesystem == TBrakeSystem::Pneumatic ) {
|
|
// BrakeDelay holds the release and the application time in G, then the same two in P
|
|
auto const delays { Vehicle->BrakeDelayFlag > bdelay_G ? 0 : 2 };
|
|
auto const isrelease { Acceleration < 0.0 };
|
|
horizon = std::max( horizon, 0.5 * Vehicle->BrakeDelay[ delays + ( isrelease ? 0 : 1 ) ] );
|
|
}
|
|
return horizon;
|
|
}
|
|
|
|
// distance [m] in which the gradient alone, with no brake and no power, brings a train rolling uphill at Velocity [km/h] to a stand
|
|
static double
|
|
uphill_stopping_distance( double const Velocity, double const Gravity ) {
|
|
return ( Velocity / 3.6 ) * ( Velocity / 3.6 ) / ( 2.0 * std::max( 0.01, -Gravity ) );
|
|
}
|
|
|
|
// speed [km/h] from which the gradient alone brings a train rolling uphill to a stand in Distance [m]
|
|
static double
|
|
uphill_coasting_speed( double const Distance, double const Gravity ) {
|
|
return 3.6 * std::sqrt( 2.0 * std::max( 0.01, -Gravity ) * std::max( 0.0, Distance ) );
|
|
}
|
|
|
|
// outside of max safe range: follow the braking curve down to the speed ahead, Vel is the present speed in the
|
|
// direction of travel
|
|
void
|
|
TController::adjust_desired_speed_for_braking_curve( double const Vel ) {
|
|
|
|
AccDesired = AccPreferred;
|
|
if( Vel <= min_speed( ActualProximityDist > 10.0 ? 10.0 : 5.0, VelDesired ) ) {
|
|
return;
|
|
}
|
|
// allow to coast at reasonably low speed
|
|
auto const brakingdistance { fBrakeDist * braking_distance_multiplier( VelNext ) };
|
|
if( auto const slowdowndistance { (
|
|
mvOccupied->CategoryFlag == 2 ? // cars can stop on a dime, for bigger vehicles we enforce some minimal braking distance
|
|
brakingdistance :
|
|
std::max(
|
|
(OrderCurrentGet() & Connect) == 0 ? 100.0 : 25.0,
|
|
brakingdistance ) ) };
|
|
brakingdistance + std::max(slowdowndistance, fMaxProximityDist) < ActualProximityDist - fMaxProximityDist ) {
|
|
// don't slow down prematurely; as long as we have room to come to a full stop at a safe distance, we're good
|
|
return;
|
|
}
|
|
// ensure some minimal coasting speed, otherwise a vehicle entering this zone at very low speed will be crawling forever
|
|
auto const brakingpointoffset = (
|
|
( VelNext == 0.0 ) && is_train() && ( OrderCurrentGet() & Obey_train ) ?
|
|
stopping_margin() : // the same stopping point as the final approach
|
|
VelNext * braking_distance_multiplier( static_cast<float>( VelNext ) ) );
|
|
// both plans of a pneumatic brake are made from the brake table of the consist; with none (in shunting it isn't
|
|
// worked out) the braking curve is the constant deceleration over the distance left, as before them
|
|
braking_curve::brake_table const braketable { fBrake_a0, fBrake_a1, BrakeAccTableSize, mvOccupied->Vmax };
|
|
// making for a passenger stop only the time the brake takes to fill: the look-ahead the horizon
|
|
// keeps as its floor was set for the stops at a signal, and a vehicle that brakes with its
|
|
// independent brake, which leaves the train brake handle where it is, kept braking earlier
|
|
// and earlier the whole way in, to crawl the last tens of metres to the stop point
|
|
auto const fillbrakea0 { bStopTargetIsPassengerStop ? 1.0 : fBrake_a0[ 0 ] };
|
|
braking_curve::approach const approach {
|
|
Vel, VelNext, ActualProximityDist, brakingpointoffset, fAccGravity, AbsAccS, BrakeCtrlPosition > 0.0,
|
|
brake_response_horizon( mvOccupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ),
|
|
brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fillbrakea0 ) };
|
|
auto const deceleration { braking_curve::demand( approach, BrakeSystem == TBrakeSystem::Pneumatic ? &braketable : nullptr ) };
|
|
AccDesired = std::min( AccDesired, deceleration ); // najpierw hamuje mocniej, potem zluzuje
|
|
if( Vel <= VelNext ) {
|
|
return;
|
|
}
|
|
if( deceleration < fAccGravity - 0.001 ) {
|
|
// no power while still above the speed being braked for
|
|
AccDesired = std::min( AccDesired, EU07_AI_NOACCELERATION );
|
|
}
|
|
else if( ( fAccGravity < -0.025 )
|
|
&& ( ( OrderCurrentGet() & Obey_train ) != 0 )
|
|
&& ( false == uphill_brake_committed( Vel ) )
|
|
&& ( ActualProximityDist - uphill_stopping_distance( Vel, fAccGravity ) > brakingpointoffset ) ) {
|
|
// uphill the gradient alone slows the train down more than it is asked to;
|
|
// keep it rolling at the present speed until that changes
|
|
AccDesired = std::min( 0.0, AccPreferred );
|
|
VelDesired = min_speed( VelDesired, uphill_coasting_speed( ActualProximityDist - brakingpointoffset, fAccGravity ) );
|
|
}
|
|
}
|
|
|
|
// the final approach to a stop, inside the proximity range: Vel is the present speed in the direction of travel
|
|
void
|
|
TController::adjust_desired_speed_for_final_approach( double const Vel ) {
|
|
|
|
if( ( mvOccupied->CategoryFlag & 1 ) == 0 ) {
|
|
// for cars (and others) coast at low speed until we hit min proximity range
|
|
VelDesired = min_speed( VelDesired, 5.0 );
|
|
return;
|
|
}
|
|
// trains
|
|
if( ( OrderCurrentGet() & ( Shunt | Connect ) )
|
|
&& ( Obstacle.distance < 50 ) ) {
|
|
// crude detection of edge case, if approaching another vehicle coast slowly until min distance
|
|
// this should allow to bunch up trainsets more on sidings
|
|
VelDesired = min_speed( 5.0, VelDesired );
|
|
return;
|
|
}
|
|
// hamowanie tak, aby stanąć
|
|
if( ( OrderCurrentGet() & Obey_train ) == 0 ) {
|
|
VelDesired = VelNext;
|
|
AccDesired = ( VelNext * VelNext - Vel * Vel ) / ( 25.92 * ( ActualProximityDist + 0.1 - 0.5*fMinProximityDist ) );
|
|
AccDesired = std::min( AccDesired, fAccThreshold );
|
|
return;
|
|
}
|
|
// a train keeps its desired speed until the lower edge of the stopping window (a desired
|
|
// speed of 0 here asks for hard braking whatever the distance left), aims at the middle
|
|
// of the window, and asks only for what that takes
|
|
auto const stoppingroom { std::max( 0.5, ActualProximityDist - stopping_margin() ) };
|
|
AccDesired = (
|
|
BrakeSystem == TBrakeSystem::Pneumatic ?
|
|
// cast iron blocks grip harder as the train comes to a stand
|
|
braking_curve::shaped_demand(
|
|
Vel, VelNext, stoppingroom, fAccGravity,
|
|
{ fBrake_a0, fBrake_a1, BrakeAccTableSize, mvOccupied->Vmax } ) :
|
|
( VelNext * VelNext - Vel * Vel ) / ( 25.92 * stoppingroom ) );
|
|
if( ( fAccGravity < -0.025 )
|
|
&& ( AccDesired >= fAccGravity - 0.001 ) // no brake needed at all
|
|
&& ( false == uphill_brake_committed( Vel ) )
|
|
&& ( ActualProximityDist - uphill_stopping_distance( Vel, fAccGravity ) > stopping_margin() ) ) {
|
|
// uphill the gradient alone would bring the train to a stand short of the
|
|
// middle of the stopping window; keep it rolling at the present speed until that changes,
|
|
// but no faster than the gradient alone can take off by the middle of the window
|
|
AccDesired = std::min( 0.0, AccPreferred );
|
|
VelDesired = min_speed( VelDesired, uphill_coasting_speed( ActualProximityDist - stopping_margin(), fAccGravity ) );
|
|
}
|
|
}
|
|
|
|
void
|
|
TController::adjust_desired_speed_for_target_speed( double const Range ) {
|
|
// ustalanie zadanego przyspieszenia
|
|
//(ActualProximityDist) - odległość do miejsca zmniejszenia prędkości
|
|
//(AccPreferred) - wynika z psychyki oraz uwzglęnia już ewentualne zderzenie z pojazdem z przodu, ujemne gdy należy hamować
|
|
//(AccDesired) - uwzględnia sygnały na drodze ruchu, ujemne gdy należy hamować
|
|
//(fAccGravity) - chwilowe przspieszenie grawitacyjne, ujemne działa przeciwnie do zadanego kierunku jazdy
|
|
//(AbsAccS) - chwilowe przyspieszenie pojazu (uwzględnia grawitację), ujemne działa przeciwnie do zadanego kierunku jazdy
|
|
//(AccDesired) porównujemy z (fAccGravity) albo (AbsAccS)
|
|
|
|
// gdy jedzie wolniej niż potrzeba, albo nie ma przeszkód na drodze
|
|
// normalna jazda
|
|
AccDesired = VelDesired != 0.0 ? AccPreferred : -0.01;
|
|
fAccDesiredGravity = 0.0;
|
|
|
|
auto const vel { DirectionalVel() };
|
|
|
|
if( VelNext >= 0.0
|
|
&& ActualProximityDist <= Range
|
|
&& vel >= VelNext ) {
|
|
// gdy zbliża się i jest za szybki do nowej prędkości, albo stoi na zatrzymaniu
|
|
if (vel > EU07_AI_NOMOVEMENT) {
|
|
// jeśli jedzie
|
|
if( vel < VelNext
|
|
&& ActualProximityDist > fMaxProximityDist * (1.0 + 0.1 * vel) ) {
|
|
// jeśli jedzie wolniej niż można i jest wystarczająco daleko, to można przyspieszyć
|
|
if( AccPreferred > 0.0 ) {
|
|
// jeśli nie ma zawalidrogi dojedz do semafora/przeszkody
|
|
AccDesired = AccPreferred;
|
|
}
|
|
}
|
|
else if( ( ActualProximityDist > fMinProximityDist )
|
|
// only a stop has a final approach of its own inside the proximity range; a lower speed ahead
|
|
// keeps the braking curve below right up to where it begins, or the train would stop braking
|
|
// (and even take power) that far out
|
|
&& ( VelNext == 0.0 )
|
|
&& ( ActualProximityDist < fMaxProximityDist ) ) {
|
|
// jedzie szybciej, niż trzeba na końcu ActualProximityDist, ale jeszcze jest daleko
|
|
// jak minął już maksymalny dystans po prostu hamuj (niski stopień)
|
|
// ma stanąć, a jest w drodze hamowania albo ma jechać
|
|
adjust_desired_speed_for_final_approach( vel );
|
|
AccDesired = std::min( AccDesired, AccPreferred );
|
|
}
|
|
else if (ActualProximityDist > fMinProximityDist) {
|
|
// jedzie szybciej, niż trzeba na końcu ActualProximityDist, ale jeszcze jest daleko
|
|
adjust_desired_speed_for_braking_curve( vel );
|
|
AccDesired = std::min( AccDesired, AccPreferred );
|
|
}
|
|
else {
|
|
// jest bliżej niż fMinProximityDist
|
|
// utrzymuj predkosc bo juz blisko
|
|
/*
|
|
VelDesired = min_speed( VelDesired, VelNext );
|
|
*/
|
|
if( VelNext == 0.0 ) {
|
|
VelDesired = VelNext;
|
|
}
|
|
else {
|
|
if( vel <= VelNext + fVelPlus ) {
|
|
// jeśli niewielkie przekroczenie, ale ma jechać
|
|
AccDesired = std::max( 0.0, AccPreferred ); // to olej (zacznij luzować)
|
|
}
|
|
}
|
|
ReactionTime = 0.1; // i orientuj się szybciej
|
|
}
|
|
}
|
|
else {
|
|
// zatrzymany (vel==0.0)
|
|
if( VelNext > 0.0 ) {
|
|
// można jechać
|
|
AccDesired = AccPreferred;
|
|
}
|
|
else {
|
|
// jeśli daleko jechać nie można
|
|
if( ActualProximityDist > (
|
|
mvOccupied->CategoryFlag & 2 ?
|
|
fMinProximityDist : // cars
|
|
fMaxProximityDist ) ) { // trains and others
|
|
// ale ma kawałek do sygnalizatora
|
|
if( AccPreferred > 0.0 ) {
|
|
// dociagnij do semafora;
|
|
AccDesired = AccPreferred;
|
|
}
|
|
else {
|
|
//stoj
|
|
VelDesired = 0.0;
|
|
}
|
|
}
|
|
else {
|
|
// VelNext=0 i stoi bliżej niż fMaxProximityDist
|
|
VelDesired = 0.0;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
void
|
|
TController::adjust_desired_speed_for_current_speed() {
|
|
// decisions based on current speed
|
|
auto const vel { DirectionalVel() };
|
|
|
|
if( is_train() ) {
|
|
// on flats or uphill we can be less careful
|
|
if( vel > VelDesired ) {
|
|
// jesli jedzie za szybko do AKTUALNEGO
|
|
if( VelDesired == 0.0 ) {
|
|
// jesli stoj, to hamuj, ale i tak juz za pozno :)
|
|
AccDesired = std::min( AccDesired, -0.85 ); // hamuj solidnie
|
|
}
|
|
else {
|
|
// slow down, not full stop
|
|
if( vel > VelDesired + fVelPlus ) {
|
|
// hamuj tak średnio
|
|
AccDesired = std::min( AccDesired, -0.05 + fAccThreshold );
|
|
}
|
|
else {
|
|
// o 5 km/h to olej (zacznij luzować)
|
|
AccDesired = std::min(
|
|
AccDesired, // but don't override decceleration for VelNext
|
|
std::max( 0.0, AccPreferred ) );
|
|
}
|
|
}
|
|
}
|
|
|
|
if( fAccGravity > 0.025 ) {
|
|
// going sharply downhill we may need to start braking sooner than usual
|
|
// try to estimate increase of current velocity before engaged brakes start working
|
|
// look ahead for as long as the brake takes to respond, since that is how long the
|
|
// present acceleration will last whatever is done with the handle now; a pneumatic
|
|
// brake applies and releases on its own time scale, which in G is tens of seconds
|
|
auto const horizon { brake_response_horizon( mvOccupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ) };
|
|
auto const speedestimate = vel + 3.6 * horizon * AbsAccS;
|
|
// already below a lower limit ahead, the train has no business speeding up towards it
|
|
auto holdlimit { VelDesired };
|
|
if( ( VelNext > 0.0 )
|
|
&& ( VelNext < holdlimit )
|
|
&& ( vel <= VelNext + fVelPlus )
|
|
&& ( ActualProximityDist < std::max( 2.0 * fBrakeDist, 500.0 ) ) ) {
|
|
holdlimit = VelNext;
|
|
}
|
|
// hold a band just below the limit; the steeper the descent the harder the train pulls
|
|
// away once the brake eases, so the band widens with the gradient (about 3 km/h at 20 per mille)
|
|
// an electro-pneumatic or electric brake responds at once and needs far less room
|
|
auto const holdspeed { holdlimit - (
|
|
BrakeSystem == TBrakeSystem::Pneumatic ?
|
|
std::clamp( fAccGravity * 15.0, 1.0, 3.0 ) :
|
|
std::clamp( fAccGravity * 7.5, 1.0, 1.5 ) ) };
|
|
// the predicted difference is to be made up over the time the brake takes to respond, not at once: with a
|
|
// slow brake, a demand sized to remove it at once comes on as a deep application, which then takes as
|
|
// long to let go, and the train ends up well below the speed it was to hold
|
|
auto const holdgain { std::min( 0.04, 1.0 / ( 3.6 * std::max( 1.0, horizon ) ) ) };
|
|
if( ( speedestimate > VelDesired )
|
|
&& ( VelDesired == 0.0 ) ) {
|
|
// jesli stoj, to hamuj, ale i tak juz za pozno :)
|
|
AccDesired = std::min( AccDesired, -0.85 ); // hamuj solidnie
|
|
}
|
|
else {
|
|
// one continuous law on both sides of the target, proportional to the predicted
|
|
// difference: a demand that jumps to the braking threshold above the target and to
|
|
// full acceleration below it alternates, with a brake that responds in seconds,
|
|
// between a hard application and a full release
|
|
AccDesired = std::min(
|
|
AccDesired, // but don't override decceleration for VelNext
|
|
std::clamp(
|
|
EU07_AI_NOACCELERATION - holdgain * ( speedestimate - holdspeed ),
|
|
-0.05 + fAccThreshold,
|
|
std::max( EU07_AI_NOACCELERATION, AccPreferred ) ) );
|
|
// HACK: for cargo trains with high braking threshold ensure we cross that threshold
|
|
auto const crossthreshold { IsCargoTrain && fBrake_a0[ 0 ] > 0.2 && speedestimate > holdlimit };
|
|
AccDesired -= ( crossthreshold ? std::clamp( fBrake_a0[ 0 ] - 0.2, 0.0, 0.15 ) : 0.0 );
|
|
}
|
|
// final tweaks
|
|
if( vel > EU07_AI_NOMOVEMENT ) {
|
|
// going downhill also take into account impact of gravity
|
|
AccDesired -= fAccGravity;
|
|
// from here on AccDesired is what the brake alone has to deliver, which is what
|
|
// IncBrake() sizes the handle position for; AbsAccS already contains the gravity,
|
|
// so the comparisons with it have to add this part back
|
|
fAccDesiredGravity = fAccGravity;
|
|
// HACK: if the max allowed speed was exceeded something went wrong; brake harder
|
|
AccDesired -= 0.15 * std::clamp( vel - VelDesired, 0.0, 5.0 );
|
|
}
|
|
}
|
|
// HACK: limit acceleration for cargo trains, to reduce probability of breaking couplers on sudden jolts
|
|
auto MaxAcc{ 0.5 * mvOccupied->Couplers[(mvOccupied->DirAbsolute >= 0 ? end::rear : end::front)].FmaxC / fMass };
|
|
if( iVehicles - ControlledEnginesCount > 0 ) {
|
|
MaxAcc *= std::clamp( vel * 0.025, 0.2, 1.0 );
|
|
}
|
|
AccDesired = std::min(AccDesired, safe_clamp(MaxAcc, HeavyCargoTrainAcceleration, AccPreferred));
|
|
// TBD: expand this behaviour to all trains with car(s) exceeding certain weight?
|
|
/*
|
|
if( ( IsPassengerTrain ) && ( iVehicles - ControlledEnginesCount > 0 ) ) {
|
|
AccDesired = std::min( AccDesired, ( iVehicles - ControlledEnginesCount > 8 ? HeavyPassengetTrainAcceleration : PassengetTrainAcceleration ) );
|
|
}
|
|
if( ( IsCargoTrain ) && ( iVehicles - ControlledEnginesCount > 0 ) ) {
|
|
AccDesired = std::min( AccDesired, CargoTrainAcceleration );
|
|
}
|
|
if( ( IsHeavyCargoTrain ) && ( iVehicles - ControlledEnginesCount > 0 ) ) {
|
|
AccDesired = std::min( AccDesired, HeavyCargoTrainAcceleration );
|
|
} */
|
|
}
|
|
else {
|
|
// for cars the older version works better
|
|
if( vel > VelDesired ) {
|
|
// jesli jedzie za szybko do AKTUALNEGO
|
|
if( VelDesired == 0.0 ) {
|
|
// jesli stoj, to hamuj, ale i tak juz za pozno :)
|
|
AccDesired = std::min( AccDesired, -0.9 ); // hamuj solidnie
|
|
}
|
|
else {
|
|
// slow down, not full stop
|
|
if( vel > VelDesired + fVelPlus ) {
|
|
// hamuj tak średnio
|
|
AccDesired = std::min( AccDesired, -fBrake_a0[ 0 ] * 0.5 );
|
|
}
|
|
else {
|
|
// o 5 km/h to olej (zacznij luzować)
|
|
AccDesired = std::min(
|
|
AccDesired, // but don't override decceleration for VelNext
|
|
std::max( 0.0, AccPreferred ) );
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// NOTE: as a stop-gap measure the routine is limited to trains only while car calculations seem off
|
|
if( is_train() && vel < VelDesired &&
|
|
-AccDesired * BrakeAccFactor() < (false == Ready || VelNext > vel - 40.0 ? fBrake_a0[0] * 0.8 : -fAccThreshold) / (1.2 * braking_distance_multiplier(VelNext)) ) {
|
|
// don't adjust acceleration when going above current target speed
|
|
AccDesired = std::max(EU07_AI_NOACCELERATION, AccDesired);
|
|
}
|
|
}
|
|
|
|
// hamowanie kontrolne
|
|
void
|
|
TController::adjust_desired_speed_for_braking_test() {
|
|
|
|
// if( false == Global.DynamicBrakeTest ) { return; }
|
|
if( DynamicBrakeTest >= 5 ) { return; } // all done
|
|
if( ( DynamicBrakeTest == 0 )
|
|
&& ( false == timetable::makes_brake_test( TrainParams.run_flags() ) ) ) { return; } // the timetable says there's none (eu07/maszyna#95)
|
|
if( false == is_train() ) { return; } // not applicable
|
|
if( mvOccupied->BrakeHandle == TBrakeHandle::FVel6 ) { return; } // leads to bugs in DecBrake, disable for now
|
|
if( false == TestFlag( OrderCurrentGet(), Obey_train ) ) { return; } // not applicable
|
|
if( false == AIControllFlag ) { return; } // TBD: add notification about braking test and enable it for human driver as well?
|
|
|
|
auto const vel { DirectionalVel() };
|
|
// what the route ahead asks for; the test may brake harder than that, never softer
|
|
auto const routeaccdesired { AccDesired };
|
|
auto const routeaccdesiredgravity { fAccDesiredGravity };
|
|
auto const routeveldesired { VelDesired };
|
|
|
|
switch( DynamicBrakeTest ) {
|
|
case 0: {
|
|
if( primary()
|
|
&& vel < VelDesired
|
|
&& fAccGravity >= 0.0 // not if going uphill
|
|
&& AccDesired >= EU07_AI_ACCELERATION
|
|
&& TrainParams.TTVmax >= 10.0
|
|
&& vel > std::min(TrainParams.TTVmax, 60.0) - 2.0 ) {
|
|
DynamicBrakeTest = 1;
|
|
DBT_BrakingTime = ElapsedTime;
|
|
DBT_VelocityBrake = vel;
|
|
}
|
|
break;
|
|
}
|
|
case 1: {
|
|
AccDesired = EU07_AI_BRAKINGTESTACCELERATION;
|
|
fAccDesiredGravity = 0.0;
|
|
VelDesired = DBT_VelocityBrake;
|
|
if( ElapsedTime - DBT_BrakingTime > 1 ) {
|
|
ForcePNBrake = true;
|
|
mvOccupied->EpFuseSwitch( false );
|
|
DynamicBrakeTest = 2;
|
|
}
|
|
break;
|
|
}
|
|
case 2: {
|
|
AccDesired = EU07_AI_BRAKINGTESTACCELERATION;
|
|
fAccDesiredGravity = 0.0;
|
|
VelDesired = DBT_VelocityBrake;
|
|
if( ElapsedTime - DBT_BrakingTime > 2 ) {
|
|
DBT_BrakingTime = ElapsedTime;
|
|
DBT_VelocityBrake = vel;
|
|
DBT_VelocityRelease = vel - 8.0;
|
|
DynamicBrakeTest = 3;
|
|
}
|
|
break;
|
|
}
|
|
case 3: {
|
|
AccDesired = safe_clamp( -AbsAccS, fAccThreshold * 1.01, fAccThreshold * 1.21 );
|
|
fAccDesiredGravity = 0.0;
|
|
VelDesired = DBT_VelocityBrake;
|
|
if( vel <= DBT_VelocityRelease ) {
|
|
DynamicBrakeTest = 4;
|
|
DBT_BrakingTime = ElapsedTime - DBT_BrakingTime;
|
|
DBT_MidPointAcc = AbsAccS;
|
|
DBT_ReleasingTime = ElapsedTime;
|
|
}
|
|
break;
|
|
}
|
|
case 4: {
|
|
if( Ready ) {
|
|
if( BrakeSystem == TBrakeSystem::ElectroPneumatic ) {
|
|
mvOccupied->EpFuseSwitch( true );
|
|
}
|
|
ForcePNBrake = false;
|
|
DynamicBrakeTest = 5;
|
|
DBT_ReleasingTime = ElapsedTime - DBT_ReleasingTime;
|
|
DBT_VelocityFinish = vel;
|
|
}
|
|
break;
|
|
}
|
|
default: {
|
|
break;
|
|
}
|
|
}
|
|
// a stop or a restriction coming up while the test runs takes precedence
|
|
if( ( DynamicBrakeTest >= 1 )
|
|
&& ( DynamicBrakeTest <= 3 )
|
|
&& ( routeaccdesired < AccDesired ) ) {
|
|
AccDesired = routeaccdesired;
|
|
fAccDesiredGravity = routeaccdesiredgravity;
|
|
VelDesired = std::min( VelDesired, routeveldesired );
|
|
}
|
|
}
|
|
|
|
void
|
|
TController::control_tractive_and_braking_force() {
|
|
|
|
#if LOGVELOCITY
|
|
WriteLog("Dist=" + FloatToStrF(ActualProximityDist, ffFixed, 7, 1) +
|
|
", VelDesired=" + FloatToStrF(VelDesired, ffFixed, 7, 1) +
|
|
", AccDesired=" + FloatToStrF(AccDesired, ffFixed, 7, 3) +
|
|
", VelSignal=" + AnsiString(VelSignal) + ", VelNext=" +
|
|
AnsiString(VelNext));
|
|
#endif
|
|
|
|
if (iDriverFailCount > maxdriverfails) {
|
|
Psyche = Easyman;
|
|
if (iDriverFailCount > maxdriverfails * 2)
|
|
SetDriverPsyche();
|
|
}
|
|
|
|
control_relays();
|
|
control_motor_connectors();
|
|
|
|
// if the radio-stop was issued don't waste effort trying to fight it
|
|
if( true == mvOccupied->RadioStopFlag // radio-stop
|
|
&& mvOccupied->Vel > EU07_AI_NOMOVEMENT ) { // and still moving
|
|
cue_action( driver_hint::mastercontrollersetzerospeed ); // just throttle down...
|
|
return; // ...and don't touch any other controls
|
|
}
|
|
// if we're slipping leave the controls alone, there's a separate logic section trying to deal with it
|
|
if( true == mvControlling->SlippingWheels ) {
|
|
return;
|
|
}
|
|
|
|
// ensure train brake isn't locked
|
|
if( BrakeCtrlPosition == gbh_NP ) {
|
|
cue_action( driver_hint::trainbrakerelease );
|
|
}
|
|
control_releaser();
|
|
control_main_pipe();
|
|
|
|
control_tractive_force();
|
|
control_braking_force();
|
|
|
|
#if LOGVELOCITY
|
|
WriteLog("BrakePos=" + AnsiString(mvOccupied->BrakeCtrlPos) + ", MainCtrl=" +
|
|
AnsiString(mvControlling->MainCtrlPos));
|
|
#endif
|
|
}
|
|
|
|
// ensure relays are active
|
|
void TController::control_relays() {
|
|
|
|
if( fActionTime < 0.0 ) { return; }
|
|
|
|
if( IsAnyMotorOverloadRelayOpen ) {
|
|
cue_action( driver_hint::mastercontrollersetzerospeed );
|
|
cue_action( driver_hint::tractionnmotoroverloadreset );
|
|
++iDriverFailCount;
|
|
}
|
|
if( IsAnyGroundRelayOpen ) {
|
|
cue_action( driver_hint::mastercontrollersetzerospeed );
|
|
cue_action( driver_hint::maincircuitgroundreset );
|
|
++iDriverFailCount;
|
|
}
|
|
}
|
|
|
|
void TController::control_motor_connectors() {
|
|
// ensure motor connectors are active
|
|
if( (mvControlling->EngineType == TEngineType::ElectricSeriesMotor || mvControlling->EngineType == TEngineType::DieselElectric || is_emu()) && Need_TryAgain ) {
|
|
// true, jeśli druga pozycja w elektryku nie załapała
|
|
cue_action(driver_hint::mastercontrollersetzerospeed);
|
|
Need_TryAgain = false;
|
|
}
|
|
}
|
|
|
|
void TController::control_tractive_force() {
|
|
|
|
control_uphill_start();
|
|
|
|
auto const velocity { DirectionalVel() };
|
|
// jeśli przyspieszenie pojazdu jest mniejsze niż żądane oraz...
|
|
if( AccDesired > EU07_AI_NOACCELERATION // don't add power if not asked for actual speed-up
|
|
&& (AbsAccS < AccDesired /*- std::min( 0.05, 0.01 * iDriverFailCount )*/ || mvOccupied->SpeedCtrlUnit.IsActive && velocity < mvOccupied->SpeedCtrlUnit.FullPowerVelocity) &&
|
|
false == TestFlag(iDrivigFlags, movePress) &&
|
|
velocity < (VelDesired == 1.0 ? // work around for trains getting stuck on tracks with speed limit = 1
|
|
VelDesired :
|
|
VelDesired - fVelMinus) &&
|
|
(ActualProximityDist > (is_car() ? fMinProximityDist : // cars are allowed to move within min proximity distance
|
|
fMaxProximityDist) ? // other vehicle types keep wider margin
|
|
true :
|
|
velocity + 1.0 < VelNext
|
|
// uphill, a train told to hold its speed on the way to a stop needs the power to do it
|
|
|| VelNext == 0.0 && (OrderCurrentGet() & Obey_train) != 0 && AccDesired >= 0.0 && fAccGravity < -0.025 && ActualProximityDist > fMinProximityDist) ) {
|
|
// ...jeśli prędkość w kierunku czoła jest mniejsza od dozwolonej o margines...
|
|
// within proximity margin don't exceed next scheduled speed, outside of the margin accelerate as you like
|
|
// ...to można przyspieszyć
|
|
increase_tractive_force();
|
|
}
|
|
// zmniejszanie predkosci
|
|
// margines dla prędkości jest doliczany tylko jeśli oczekiwana prędkość jest większa od 5km/h
|
|
if( false == TestFlag( iDrivigFlags, movePress ) ) {
|
|
double SpeedCtrlMargin = mvControlling->SpeedCtrlUnit.IsActive && VelDesired > 5 ? 3 : 0;
|
|
// jeśli nie dociskanie
|
|
if( AccDesired <= EU07_AI_NOACCELERATION ) {
|
|
cue_action( driver_hint::mastercontrollersetzerospeed );
|
|
}
|
|
else if( velocity > VelDesired + SpeedCtrlMargin
|
|
|| ( fAccGravity < -0.01 ? is_too_fast_uphill() : AbsAccS > AccDesired + 10.05 )
|
|
|| IsAnyCouplerStretched ) {
|
|
// jak za bardzo przyspiesza albo prędkość przekroczona
|
|
// dodany wyjatek na "pelna w przod"
|
|
cue_action( driver_hint::tractiveforcedecrease );
|
|
}
|
|
}
|
|
|
|
control_handles();
|
|
SpeedSet(); // ciągla regulacja prędkości
|
|
}
|
|
|
|
bool TController::is_too_fast_uphill() const {
|
|
|
|
if( AccDesired < 0.0 ) { return true; }
|
|
// holding the speed uphill on the way to a stop asks for no speeding up
|
|
return ( VelNext == 0.0 && ActualProximityDist <= fMaxProximityDist && AbsAccS > AccDesired + 0.05 );
|
|
}
|
|
|
|
// starting uphill a driver of a heavy train keeps the train brake applied, lets the locomotive's own brake off (the
|
|
// independent brake, and its share of the train brake with the releaser), applies the power, and releases the train
|
|
// brake only once the power holds the train. releasing everything first lets the train roll back before the power is
|
|
// there, and holding the train on the locomotive brake is no way out where that brake cuts the power (asynchronous
|
|
// drives, the control pressure switch)
|
|
void TController::control_uphill_start() {
|
|
|
|
auto const velocity { DirectionalVel() };
|
|
if( auto const uphill {
|
|
( BrakeSystem == TBrakeSystem::Pneumatic )
|
|
&& is_train()
|
|
&& ( false == is_emu() ) && ( false == is_dmu() ) // a multiple unit has no locomotive to hold a train behind it
|
|
&& ( fAccGravity < EU07_AI_UPHILLGRAVITY ) };
|
|
false == uphill ) {
|
|
bUphillStart = false;
|
|
return;
|
|
}
|
|
if( false == bUphillStart ) {
|
|
if( ( std::abs( velocity ) < EU07_AI_NOMOVEMENT )
|
|
&& ( AccDesired > EU07_AI_NOACCELERATION )
|
|
&& ( VelDesired > 0.0 )
|
|
&& ( BrakeCtrlPosition > 0.0 ) ) { // only with the train brake still applied to hold the train
|
|
bUphillStart = true;
|
|
fUphillStartTime = ElapsedTime;
|
|
}
|
|
else {
|
|
return;
|
|
}
|
|
}
|
|
if( AccDesired <= EU07_AI_NOACCELERATION ) {
|
|
// no longer to start: the standing rules take over
|
|
bUphillStart = false;
|
|
return;
|
|
}
|
|
if( velocity < -0.5 ) {
|
|
// rolling back all the same: the rules for a train slipping back take over and apply the brakes
|
|
bUphillStart = false;
|
|
return;
|
|
}
|
|
if( ( mvOccupied->LocalBrake != TLocalBrake::ManualBrake )
|
|
&& ( mvOccupied->LocalBrakePosA > 0.0 ) ) {
|
|
cue_action( driver_hint::independentbrakerelease );
|
|
}
|
|
auto tractiveforce { 0.0 };
|
|
for( auto const *vehicle { pVehicles[ end::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) {
|
|
// Ft is signed in the vehicle's own frame
|
|
tractiveforce += std::max( 0.0, vehicle->MoverParameters->Ft * ( vehicle->DirectionGet() == iDirection ? 1 : -1 ) );
|
|
}
|
|
auto const holdingforce { fMass * -fAccGravity };
|
|
if( ( velocity > 1.0 )
|
|
|| ( tractiveforce > 1.1 * holdingforce )
|
|
// a locomotive that can't hold the train on its own power gets the brake off in the end all the same
|
|
|| ( ElapsedTime - fUphillStartTime > 45.0 ) ) {
|
|
// the power holds the train: the train brake can be released
|
|
bUphillStart = false;
|
|
}
|
|
}
|
|
|
|
void TController::increase_tractive_force() {
|
|
|
|
if( fActionTime < 0.0 ) { return; } // gdy jest nakaz poczekać z jazdą, to nie ruszać
|
|
if( IsAnyCouplerStretched ) { return; } // train is already stretched past its limits, don't pull even harder
|
|
|
|
if( mvOccupied->SpringBrake.Activate ) {
|
|
cue_action( driver_hint::springbrakeoff );
|
|
}
|
|
if( VelDesired > 0.0 // to prevent door shuffle on stop
|
|
&& ( doors_open() || doors_permit_active() ) ) {
|
|
// zamykanie drzwi - tutaj wykonuje tylko AI (zmienia fActionTime)
|
|
Doors( false );
|
|
// Doors() call can potentially adjust fActionTime
|
|
if( fActionTime < 0.0 ) { return; }
|
|
}
|
|
if( true == mvOccupied->DepartureSignal ) {
|
|
cue_action( driver_hint::departuresignaloff );
|
|
}
|
|
|
|
cue_action( driver_hint::tractiveforceincrease );
|
|
}
|
|
|
|
// how far the deceleration may fall short of the demand before the brake is applied harder. approaching a lower
|
|
// speed, a pneumatic brake given a full step only once that much is missing acts too late: the demand
|
|
// creeps up meanwhile, and in a long G train the next step takes many seconds to act, so half a step is enough
|
|
double
|
|
TController::brake_increase_margin() const {
|
|
|
|
if( ( BrakeSystem == TBrakeSystem::Pneumatic )
|
|
&& ( VelNext > 0.0 )
|
|
&& ( VelNext < DirectionalVel() ) ) {
|
|
return 0.5 * fBrake_a1[ 0 ];
|
|
}
|
|
return fBrake_a1[ 0 ];
|
|
}
|
|
|
|
// a train coming to a stand with at least part of it on an up gradient: a long train brake released now cannot be
|
|
// applied again before the train stops and starts to roll back, so the train brake is not released any further, and the
|
|
// locomotive brake, which acts at once, helps to hold the train
|
|
bool
|
|
TController::uphill_stop_hold() const {
|
|
|
|
return (
|
|
( BrakeSystem == TBrakeSystem::Pneumatic ) && is_train() && ( ( OrderCurrentGet() & Obey_train ) != 0 )
|
|
&& ( VelNext == 0.0 )
|
|
&& ( ActualProximityDist <= fMaxProximityDist )
|
|
&& ( fAccGravity < EU07_AI_UPHILLGRAVITY )
|
|
&& ( std::abs( DirectionalVel() ) < 10.0 )
|
|
// not while the train is to be driven on
|
|
&& ( AccDesired <= 0.0 ) );
|
|
}
|
|
|
|
// uphill with the train brake applied, the gradient brings a slow train to a stand sooner than the brake of the consist
|
|
// can be released: letting the train roll on (or pulling up) at this speed only releases the brake for nothing, and the
|
|
// train stands with the brake on its way off instead
|
|
bool
|
|
TController::uphill_brake_committed( double const Velocity ) const {
|
|
|
|
return (
|
|
( BrakeSystem == TBrakeSystem::Pneumatic )
|
|
&& ( BrakeCtrlPosition > 0.0 )
|
|
&& ( fAccGravity < EU07_AI_UPHILLGRAVITY )
|
|
&& ( Velocity / 3.6 / -fAccGravity < brake_response_horizon( mvOccupied, BrakeSystem, -1.0, fBrake_a0[ 0 ] ) ) );
|
|
}
|
|
|
|
void TController::control_braking_force() {
|
|
|
|
// don't touch the brakes when compressing buffers during coupling/uncoupling
|
|
if( TestFlag( iDrivigFlags, movePress ) ) { return; }
|
|
|
|
auto const velocity { DirectionalVel() };
|
|
|
|
// jeśli przyspieszamy, to nie hamujemy
|
|
if( AccDesired > 0.0 && OrderCurrentGet() != Disconnect // przy odłączaniu nie zwalniamy tu hamulca
|
|
&& false == TestFlag(iDrivigFlags, movePress) ) {
|
|
cue_action(driver_hint::brakingforcesetzero);
|
|
}
|
|
|
|
// AbsAccS is the resultant acceleration, gravity included, so it is compared with the
|
|
// resultant the AI asks for, not with the brake-only demand AccDesired holds on a descent
|
|
auto const accdesiredresultant { AccDesired + fAccDesiredGravity };
|
|
|
|
// every few seconds, note how far the train falls short of the demand and whether that is getting worse: a brake
|
|
// still filling, or blocks gripping harder as the train slows down, make up a shortfall on their own, but a
|
|
// shortfall that keeps growing at a constant handle means the train is falling further behind its braking curve
|
|
if( ElapsedTime - fShortfallTime >= 3.0 ) {
|
|
auto const shortfall { AbsAccS - accdesiredresultant };
|
|
iShortfallGrowth = (
|
|
( ( AccDesired < 0.0 ) && ( shortfall > fShortfall + 0.005 ) ) ?
|
|
iShortfallGrowth + 1 :
|
|
0 );
|
|
fShortfall = shortfall;
|
|
fShortfallTime = ElapsedTime;
|
|
}
|
|
|
|
if( is_emu() && !ForcePNBrake ) {
|
|
// właściwie, to warunek powinien być na działający EP
|
|
// Ra: to dobrze hamuje EP w EZT
|
|
auto const accthreshold { (
|
|
fAccGravity < 0.025 ? // HACK: when going downhill be more responsive to desired deceleration
|
|
fAccThreshold :
|
|
std::max( -0.2, fAccThreshold ) ) };
|
|
auto const AccMax{ std::min(fBrake_a0[0] + 12 * fBrake_a1[0], mvOccupied->MED_amax) };
|
|
auto const accmargin = AccMax > 1.1 * AccDesired && fAccGravity < 0.025 ?
|
|
0.05 : 0.0;
|
|
if( ( AccDesired < accthreshold // jeśli hamować - u góry ustawia się hamowanie na fAccThreshold
|
|
&& ( AbsAccS > accdesiredresultant + accmargin
|
|
|| BrakeCtrlPosition < 0 ) )
|
|
|| ( fAccGravity < -0.05 && velocity < -0.1 && AccDesired < 0.0 ) ) { // also brake if uphill and slipping back
|
|
// hamować bardziej, gdy aktualne opóźnienie hamowania mniejsze niż (AccDesired)
|
|
cue_action( driver_hint::brakingforceincrease );
|
|
}
|
|
else if( OrderCurrentGet() != Disconnect ) { // przy odłączaniu nie zwalniamy tu hamulca
|
|
if( AbsAccS < accdesiredresultant - 0.05 ) {
|
|
// jeśli opóźnienie większe od wymaganego (z histerezą) luzowanie, gdy za dużo
|
|
// TBD: check if the condition isn't redundant with the DecBrake() code
|
|
if( BrakeCtrlPosition >= 0 && VelDesired > 0.0 ) {
|
|
// sanity check to prevent unintended brake release on sharp slopes
|
|
cue_action(driver_hint::brakingforcedecrease);
|
|
}
|
|
}
|
|
else {
|
|
cue_action( driver_hint::brakingforcelap );
|
|
}
|
|
}
|
|
} // type & dt_ezt
|
|
else {
|
|
// a stara wersja w miarę dobrze działa na składy wagonowe
|
|
if( (accdesiredresultant < fAccGravity - 0.1 && AbsAccS > accdesiredresultant + brake_increase_margin() // regular braking
|
|
|| fAccGravity < -0.05 && velocity < -0.1 && false == bUphillStart) && // also brake if uphill and slipping back
|
|
(fBrakeTime < 0.0
|
|
// the size of the brake demand decides whether to skip the reaction time, so the brake-only part
|
|
// (on a descent a heavy train needs its brake built up at once, the gravity does not help it slow)
|
|
|| AccDesired < fAccGravity - 0.5 || BrakeCtrlPosition <= 0) ) {
|
|
// u góry ustawia się hamowanie na fAccThreshold
|
|
// jeśli upłynął czas reakcji hamulca, chyba że nagłe albo luzował
|
|
// TODO: check whether brake delay variable still has any purpose
|
|
cue_action(driver_hint::brakingforceincrease,
|
|
// Ra: ten czas należy zmniejszyć, jeśli czas dojazdu do zatrzymania jest mniejszy
|
|
(3.0 + 0.5 * ((mvOccupied->BrakeDelayFlag > bdelay_G ? mvOccupied->BrakeDelay[1] : mvOccupied->BrakeDelay[3]) - 3.0)) * 0.5); // Ra: tymczasowo, bo przeżyna S1
|
|
}
|
|
else if( ( BrakeSystem == TBrakeSystem::Pneumatic )
|
|
&& ( AccDesired < 0.0 )
|
|
&& ( BrakeCtrlPosition > 0.0 )
|
|
&& ( fShortfall > 0.02 )
|
|
&& ( iShortfallGrowth >= 2 )
|
|
&& ( fBrakeHeldTime > brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) {
|
|
// the train has been falling further behind the demand for a while at a handle left alone for longer than
|
|
// the brake takes to respond: a small step now, while it still is small, rather than the deep one the
|
|
// margin above would allow only once the train is far behind
|
|
cue_action( driver_hint::brakingforceincrease );
|
|
iShortfallGrowth = 0;
|
|
}
|
|
if ( (accdesiredresultant < fAccGravity - 0.05
|
|
|| AccDesired >= EU07_AI_NOACCELERATION) // no braking asked for, yet the train is slowing down more than that
|
|
&& accdesiredresultant - fBrake_a1[0] * 0.51 - AbsAccS > 0.05 && OrderCurrentGet() != Disconnect && VelDesired > 0.0 ) {
|
|
// jak hamuje, to nie tykaj kranu za często
|
|
// yB: luzuje hamulec dopiero przy różnicy opóźnień rzędu 0.2
|
|
// przy odłączaniu nie zwalniamy tu hamulca
|
|
// sanity check to prevent unintended brake release on sharp slopes
|
|
// TODO: check whether brake delay variable still has any purpose
|
|
cue_action(driver_hint::brakingforcedecrease,
|
|
(mvOccupied->BrakeDelayFlag > bdelay_G ? mvOccupied->BrakeDelay[0] : mvOccupied->BrakeDelay[2]) / 3.0 * 0.5); // Ra: tymczasowo, bo przeżyna S1
|
|
}
|
|
// uphill, the locomotive brake acts at once while the train brake of a long train takes many seconds to apply:
|
|
// put it on as the train comes to a stand, and at once if the train has started to roll back
|
|
if( ( mvOccupied->LocalBrake != TLocalBrake::ManualBrake )
|
|
&& ( mvOccupied->LocalBrakePosA < 1.0 )
|
|
&& ( ( uphill_stop_hold() && ( std::abs( velocity ) < 3.0 )
|
|
// a train that has slowed down short of where it is to stop and is to pull up further does not get it
|
|
&& ( VelDesired <= std::abs( velocity ) + 0.5 )
|
|
&& ( ActualProximityDist - uphill_stopping_distance( std::abs( velocity ), fAccGravity ) <= stopping_margin() ) )
|
|
|| ( ( BrakeSystem == TBrakeSystem::Pneumatic ) && ( fAccGravity < EU07_AI_UPHILLGRAVITY ) && ( velocity < -0.1 ) && ( AccDesired <= 0.0 ) ) ) ) {
|
|
cue_action( driver_hint::independentbrakeapply );
|
|
}
|
|
// stop-gap measure to ensure cars actually brake to stop even when above calculactions go awry
|
|
// instead of releasing the brakes and creeping into obstacle at 1-2 km/h
|
|
if( is_car() && VelDesired == 0.0 && velocity > VelDesired && ActualProximityDist <= fMinProximityDist && mvOccupied->LocalBrakePosA < 0.01 ) {
|
|
cue_action(driver_hint::brakingforceincrease);
|
|
}
|
|
}
|
|
|
|
// odhamowywanie składu po zatrzymaniu i zabezpieczanie lokomotywy
|
|
if( mvOccupied->Vel < EU07_AI_NOMOVEMENT
|
|
&& ( VelDesired == 0.0
|
|
|| AccDesired <= EU07_AI_NOACCELERATION ) ) {
|
|
|
|
if( (OrderCurrentGet() & (Disconnect | Connect | Change_direction)) == 0 // przy (p)odłączaniu nie zwalniamy tu hamulca
|
|
&& std::abs(fAccGravity) < 0.01 ) { // only do this on flats, on slopes keep applied the train brake
|
|
apply_independent_brake_only();
|
|
}
|
|
// if told to change direction don't confuse human driver with request to leave applied brake in the cab they're about to leave
|
|
if( ( OrderCurrentGet() & Change_direction ) != 0 ) {
|
|
cue_action( driver_hint::independentbrakerelease );
|
|
}
|
|
}
|
|
}
|
|
|
|
void TController::apply_independent_brake_only() {
|
|
|
|
if( mvOccupied->LocalBrake != TLocalBrake::ManualBrake ) {
|
|
if( false == mvOccupied->ShuntMode // no need for independent brake if autobrake is active
|
|
&& is_equal(mvOccupied->fBrakeCtrlPos, mvOccupied->Handle->GetPos(bh_RP), 0.2) ) {
|
|
cue_action( driver_hint::independentbrakeapply );
|
|
}
|
|
else {
|
|
cue_action( driver_hint::trainbrakerelease );
|
|
}
|
|
}
|
|
}
|
|
|
|
void TController::control_releaser() {
|
|
// HACK: don't immediately touch releaser in inert vehicle, in case the simulation is about to replace us with human driver
|
|
if( mvOccupied->Vel < 1.0 && fActionTime < 0.0 ) { return; }
|
|
// TODO: combine all releaser handling in single decision tree instead of having bits all over the place
|
|
// TODO: replace handle and system conditions with flag indicating releaser presence
|
|
if( BrakeSystem != TBrakeSystem::Pneumatic ) { return; }
|
|
|
|
auto const hasreleaser {
|
|
false == (is_dmu() || is_emu()) // TODO: a more refined test than rejecting these types wholesale
|
|
&& ( mvOccupied->BrakeHandle == TBrakeHandle::FV4a
|
|
|| mvOccupied->BrakeHandle == TBrakeHandle::MHZ_6P
|
|
|| mvOccupied->BrakeHandle == TBrakeHandle::MHZ_K5P
|
|
|| mvOccupied->BrakeHandle == TBrakeHandle::MHZ_K8P
|
|
|| mvOccupied->BrakeHandle == TBrakeHandle::M394 ) };
|
|
|
|
if( false == hasreleaser ) { return; }
|
|
|
|
auto actuate { false };
|
|
auto isbrakehandleinrightposition { true };
|
|
|
|
if( AccDesired > EU07_AI_NOACCELERATION ) {
|
|
// fill up brake pipe if needed
|
|
if( mvOccupied->PipePress < 3.0 ) {
|
|
actuate = true;
|
|
// some vehicles require brake handle to be moved to specific position
|
|
if( mvOccupied->HandleUnlock != -3 ) {
|
|
cue_action( driver_hint::trainbrakesetpipeunlock );
|
|
isbrakehandleinrightposition &= BrakeCtrlPosition == mvOccupied->HandleUnlock;
|
|
}
|
|
}
|
|
// wyluzuj lokomotywę, to szybciej ruszymy
|
|
// this rule is for starting off, so only below 1 km/h: at speed, just after an application, it would vent
|
|
// the control reservoir of a locomotive that may have to brake again before the pipe has refilled it
|
|
if( mvOccupied->BrakePress > 0.4
|
|
&& ( mvOccupied->Hamulec->GetCRP() > 4.9
|
|
// starting uphill the train brake stays applied on purpose, and the locomotive's own share of it has to go
|
|
// for the power to come on (asynchronous drives and the pressure switch cut the power while it is applied)
|
|
|| bUphillStart )
|
|
&& mvOccupied->Vel < 1.0 ) {
|
|
actuate = true;
|
|
}
|
|
// keep engine brakes released during coupling/uncoupling
|
|
if( true == TestFlag(iDrivigFlags, movePress)
|
|
&& mvOccupied->BrakePress > 0.1 ) {
|
|
actuate = true;
|
|
}
|
|
}
|
|
// don't overcharge train brake pipe
|
|
if( mvOccupied->PipePress > 5.2 ) {
|
|
actuate = false;
|
|
}
|
|
|
|
if( actuate ) {
|
|
// some vehicles may require master controller in neutral position
|
|
cue_action( driver_hint::mastercontrollersetzerospeed );
|
|
if( false == mvOccupied->Hamulec->Releaser()
|
|
&& isbrakehandleinrightposition ) {
|
|
cue_action( driver_hint::releaseron );
|
|
}
|
|
}
|
|
else {
|
|
if( true == mvOccupied->Hamulec->Releaser() ) {
|
|
cue_action( driver_hint::releaseroff );
|
|
}
|
|
}
|
|
}
|
|
|
|
void TController::control_main_pipe() {
|
|
|
|
// unlocking main pipe
|
|
if( AccDesired > -0.03
|
|
&& true == mvOccupied->LockPipe ) {
|
|
UniversalBrakeButtons |= TUniversalBrake::ub_UnlockPipe;
|
|
}
|
|
else if (false == mvOccupied->LockPipe ) {
|
|
UniversalBrakeButtons &= ~TUniversalBrake::ub_UnlockPipe;
|
|
}
|
|
|
|
// napełnianie uderzeniowe
|
|
if( BrakeSystem != TBrakeSystem::Pneumatic ) { return; }
|
|
|
|
if( mvOccupied->BrakeHandle == TBrakeHandle::FV4a
|
|
|| mvOccupied->BrakeHandle == TBrakeHandle::MHZ_6P
|
|
|| mvOccupied->BrakeHandle == TBrakeHandle::MHZ_K5P
|
|
|| mvOccupied->BrakeHandle == TBrakeHandle::MHZ_K8P
|
|
|| mvOccupied->BrakeHandle == TBrakeHandle::M394 ) {
|
|
|
|
auto const departblocked { is_departure_blocked( DepartBlockedFSDelay ) };
|
|
if( (iDrivigFlags & moveOerlikons || true == IsCargoTrain || departblocked) && BrakeCtrlPosition == gbh_RP && AbsAccS < 0.03 && AccDesired > -0.03 && VelDesired - mvOccupied->Vel > 2.0 && fReady > 0.35 &&
|
|
( mvOccupied->EqvtPipePress < 4.5 || departblocked ) // don't charge with a risk of overcharging the main pipe
|
|
&& mvOccupied->Compressor >= 7.5 // don't charge without sufficient pressure in the tank
|
|
&& BrakeChargingCooldown >= 0.0 // don't charge while cooldown is active
|
|
&& (ActualProximityDist > 100.0 // don't charge if we're about to be braking soon
|
|
|| min_speed(mvOccupied->Vel, VelNext) >= mvOccupied->Vel) ) {
|
|
|
|
BrakeLevelSet(gbh_FS);
|
|
// don't charge the brakes too often, or we risk overcharging
|
|
BrakeChargingCooldown = -1 * std::clamp(iVehicles * 3, 30, 90);
|
|
}
|
|
|
|
update_brake_charging();
|
|
|
|
if( mvOccupied->Compressor < 5.0
|
|
|| ( BrakeCtrlPosition < gbh_RP
|
|
&& ( mvOccupied->EqvtPipePress > (fReady < 0.25 ? 5.1 : 5.2) || is_brake_charging_done() ) ) ) {
|
|
cue_action( driver_hint::trainbrakerelease );
|
|
}
|
|
}
|
|
}
|
|
|
|
void TController::update_brake_charging() {
|
|
|
|
if( std::abs( BrakeCtrlPosition - gbh_FS ) >= 0.5 ) {
|
|
BrakeChargingStart = -1.0;
|
|
BrakeChargingPipeOverchargeStart.clear();
|
|
return;
|
|
}
|
|
if( BrakeChargingStart < 0.0 ) {
|
|
BrakeChargingStart = ElapsedTime;
|
|
}
|
|
for( auto const *vehicle { pVehicles[ end::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) {
|
|
auto const isovercharged {
|
|
vehicle->MoverParameters != mvOccupied
|
|
&& vehicle->MoverParameters->PipePress > FSOverchargePipePress };
|
|
if( isovercharged ) {
|
|
BrakeChargingPipeOverchargeStart.try_emplace( vehicle, ElapsedTime );
|
|
}
|
|
else {
|
|
BrakeChargingPipeOverchargeStart.erase( vehicle );
|
|
}
|
|
}
|
|
}
|
|
|
|
bool TController::is_departure_blocked( double const Delay ) const {
|
|
|
|
return DepartBlockedStart >= 0.0
|
|
&& ElapsedTime - DepartBlockedStart > Delay;
|
|
}
|
|
|
|
double TController::consist_max_crp() const {
|
|
|
|
auto result { 0.0 };
|
|
for( auto const *vehicle { pVehicles[ end::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) {
|
|
result = std::max( result, vehicle->MoverParameters->Hamulec->GetCRP() );
|
|
}
|
|
return result;
|
|
}
|
|
|
|
bool TController::is_brake_charging_done() const {
|
|
|
|
if( BrakeChargingStart < 0.0 ) {
|
|
return false;
|
|
}
|
|
return ElapsedTime - BrakeChargingStart > FSMaxTime
|
|
|| consist_max_crp() > mvOccupied->HighPipePress + FSOverchargeCRP
|
|
|| std::ranges::any_of(
|
|
BrakeChargingPipeOverchargeStart,
|
|
[this]( auto const &Vehicle ) { return ElapsedTime - Vehicle.second > FSOverchargeTime; } );
|
|
}
|
|
|
|
void
|
|
TController::check_route_ahead( double const Range ) {
|
|
|
|
auto const comm { TableUpdate( VelDesired, ActualProximityDist, VelNext, AccDesired ) };
|
|
|
|
switch (comm) {
|
|
// ustawienie VelSignal - trochę proteza = do przemyślenia
|
|
case TCommandType::cm_Ready: { // W4 zezwolił na jazdę
|
|
// ewentualne doskanowanie trasy za W4, który zezwolił na jazdę
|
|
TableCheck( Range );
|
|
TableUpdate( VelDesired, ActualProximityDist, VelNext, AccDesired ); // aktualizacja po skanowaniu
|
|
if( VelNext == 0.0 ) {
|
|
break; // ale jak coś z przodu zamyka, to ma stać
|
|
}
|
|
if( iDrivigFlags & moveStopCloser ) {
|
|
VelSignal = -1.0; // ma czekać na sygnał z sygnalizatora!
|
|
}
|
|
break;
|
|
}
|
|
case TCommandType::cm_SetVelocity: { // od wersji 357 semafor nie budzi wyłączonej lokomotywy
|
|
if( (OrderCurrentGet() & ~(Shunt | Loose_shunt | Obey_train | Bank)) == 0 && std::fabs(VelSignal) >= 1.0 ) { // jedzie w dowolnym trybie albo Wait_for_orders
|
|
// 0.1 nie wysyła się do samochodow, bo potem nie ruszą
|
|
PutCommand("SetVelocity", VelSignal, VelNext, nullptr); // komenda robi dodatkowe operacje
|
|
}
|
|
break;
|
|
}
|
|
case TCommandType::cm_ShuntVelocity: { // od wersji 357 Tm nie budzi wyłączonej lokomotywy
|
|
if( ( OrderCurrentGet() & ~( Shunt | Loose_shunt | Obey_train | Bank ) ) == 0 ) { // jedzie w dowolnym trybie albo Wait_for_orders
|
|
PutCommand( "ShuntVelocity", VelSignal, VelNext, nullptr );
|
|
}
|
|
else if( iCoupler ) { // jeśli jedzie w celu połączenia
|
|
SetVelocity( VelSignal, VelNext );
|
|
}
|
|
break;
|
|
}
|
|
case TCommandType::cm_Command: { // komenda z komórki
|
|
if( (OrderCurrentGet() & ~(Shunt | Loose_shunt | Obey_train | Bank)) == 0 && mvOccupied->Vel < 0.1 ) {
|
|
// jedzie w dowolnym trybie albo Wait_for_orders
|
|
// dopiero jak stanie
|
|
/*
|
|
PutCommand( eSignNext->text(), eSignNext->value( 1 ), eSignNext->value( 2 ), nullptr );
|
|
eSignNext->StopCommandSent(); // się wykonało już
|
|
*/ // replacement of the above
|
|
eSignNext->send_command(*this);
|
|
}
|
|
break;
|
|
}
|
|
default: {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
void
|
|
TController::check_route_behind( double const Range ) {
|
|
|
|
if( VelNext != 0.0 ) { return; } // not if we can move ahead
|
|
if( TestFlag( iDrivigFlags, moveConnect ) ) { return; } // not if we're in middle of coupling operation
|
|
|
|
if( ( OrderCurrentGet() & ~( Shunt | Loose_shunt | Connect ) ) == 0 ) {
|
|
// jedzie w Shunt albo Connect, albo Wait_for_orders
|
|
// w trybie Connect skanować do tyłu tylko jeśli przed kolejnym sygnałem nie ma taboru do podłączenia
|
|
auto const couplinginprogress {
|
|
TestFlag(OrderCurrentGet(), Connect)
|
|
&& ( Obstacle.distance < std::min(2000.0, FirstSemaphorDist)
|
|
|| TestFlag(iDrivigFlags, moveConnect) ) };
|
|
if( couplinginprogress ) { return; }
|
|
|
|
auto const commandbehind { BackwardScan( Range ) };
|
|
if( commandbehind != TCommandType::cm_Unknown ) {
|
|
// jeśli w drugą można jechać
|
|
// należy sprawdzać odległość od znalezionego sygnalizatora,
|
|
// aby w przypadku prędkości 0.1 wyciągnąć najpierw skład za sygnalizator
|
|
// i dopiero wtedy zmienić kierunek jazdy, oczekując podania prędkości >0.5
|
|
if( commandbehind == TCommandType::cm_Command ) {
|
|
// jeśli komenda Shunt to ją odbierz bez przemieszczania się (np. odczep wagony po dopchnięciu do końca toru)
|
|
iDrivigFlags |= moveStopHere;
|
|
}
|
|
iDirectionOrder = -iDirection; // zmiana kierunku jazdy
|
|
// zmiana kierunku bez psucia kolejnych komend
|
|
OrderCurrentSet( TOrders( OrderCurrentGet() | Change_direction ) );
|
|
}
|
|
}
|
|
}
|
|
|
|
void
|
|
TController::UpdateBrakingHelper() {
|
|
|
|
if (HelperState > 0 && -AccDesired < fBrake_a0[0] + 2 * fBrake_a1[0] && mvOccupied->Vel > EU07_AI_NOMOVEMENT) {
|
|
HelperState = 0;
|
|
}
|
|
|
|
switch( HelperState ) {
|
|
case 0: {
|
|
if( -AccDesired > fBrake_a0[0] + 8 * fBrake_a1[0] ) {
|
|
HelperState = 1;
|
|
}
|
|
break;
|
|
}
|
|
case 1: {
|
|
if( -AccDesired > fBrake_a0[0] + 12 * fBrake_a1[0] ) {
|
|
HelperState = 2;
|
|
}
|
|
break;
|
|
}
|
|
case 2: {
|
|
if( -AccDesired > 0 && -ActualProximityDist > 5 ) {
|
|
HelperState = 3;
|
|
}
|
|
break;
|
|
}
|
|
default: {
|
|
break;
|
|
}
|
|
}
|
|
}
|