18
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-11-27 22:55:16 +01:00
Files
maszyna/rendering/opengl33renderer.cpp
jerrrrycho 7ac2472c37 Merge master into staging (#514)
* 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 since ce87aa0e (#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 before
ce87aa0e and 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 since
e230d7b9 it 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.1

d1f16411 (#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; fa2ed089 swapped 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 (since 96f43e11 and 4d72d352), and the old clamp made that the headroom Vmax - (Vel + 0.32 Vmax),
negative above 68% of the top speed, capped from above only; d464628a and 03bfbb13 kept 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 before d1f16411.

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 of 8811ee5a:

- 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 of 939514ea:

- 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

Since d13c27a7 (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. Before d13c27a7 the 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 before d13c27a7: 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 commit 9ffed96ec1)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

From the review of the descriptions:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* refactor: the Sonar remarks on the tutorial

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

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

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

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

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

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

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

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

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

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

* refactor: the last Sonar remarks on the small fixes

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Also:

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

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

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

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

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

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

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

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

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

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

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

- editor/editorTrackTrace: the track followed the way a train runs, shared by the W17 markers and the signals. The fouling
  point of a switch (where the axes of its tracks are 3.5 m apart) moved here…

* 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 again

ee3af0bf (#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: ee3af0bf moved 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>

* fix(render): the free camera blurs with its own movement, the grass racing under it no longer strobes in rings (#441)

The motion blur took the movement of the vehicle the camera sits in and nothing else, so in freefly (and the
debug camera) the world got no blur from the camera at all. Low over grass the texture under the camera then
moved tens of pixels a frame and strobed: rings around the camera, at the distances its pattern repeats,
stronger with shift and ctrl, gone above about 20 m, worst on a 165 Hz screen.

* the camera with no vehicle of its own blurs the world with its movement since the frame before, as a vehicle
  does with get_future_movement(); a jump of 50 m or more (a camera preset) is no movement
* that movement is held to half a metre a frame: the blur takes the scene where the camera will be, and a
  camera faster than that passes the ground at the bottom of the screen within a frame, where its motion turned
  over into a bright band. with the shutter of the blur it still smears metres
* the blur shader skips samples off the picture instead of reading its edge row again and again

* fix(ai): an uphill start keeps the power on until the train brake is off (#396)

* fix(ai): an uphill start keeps the power on until the train brake is off

The uphill start of #265 ended as soon as the power held the train (or the head of the
train moved back 0.5 km/h). From then on the brake still on in the wagons made Ready false,
the power went off, the train rolled back, was braked again and the start began anew; only
the cylinders falling below 0.8 bar let the train get away.

- Once the power holds the train, the start goes on while the train brake is released:
  Ready holds, the power stays on, bounded to 1.5 x the grade force. It ends when the
  consist is released (the same test as Ready, without the hold) or after 60 s.
- A start is given up for rolling back on the mass-weighted speed of the consist, not on
  the speed of the locomotive, which runs back into the slack of the train held by its brake.
- A train slipping back uphill is not released by the rule for a train to go on.

* fix(ai): an uphill start begins only with the whole train at a stand

* fix(ai): an uphill start applies the train brake further while it doesn't hold the train without the locomotive brake

* fix(ai): the speed and the tractive force of an uphill start in the direction of travel also from cab 2

* fix(ai): an uphill start tops up the train brake a full application time a step, at most to full service, and keeps the power between 1.1 and 1.5 times the grade force while the brake releases

* fix(ai): an uphill start no longer takes a notch back in the release phase: the notch below doesn't hold the train

* refactor(ai): the train brake top-up of an uphill start in uphill_start::brake_top_up(), with unit tests

* fix(ai): a standing train starts only with its brakes charged, held on the locomotive brake while it charges (#444)

* fix(ai): a standing train starts only with its brakes charged, held on the locomotive brake while it charges

Prepared from cold, the AI filled the brake pipe at once with the locomotive brake off: the distributors
released while the auxiliary reservoirs were still empty, so the train had no air to brake with, and on
a gradient it rolled as it released. The train counted as ready as soon as it was released. A train placed
cold with its pipe below the lock of the FV4a driver's brake valve (2.75 bar) wasn't unlocked until the
order to go, and went on what its reservoirs got meanwhile (TMS77185 in linia_107_objazdy: 40 minutes at
1.2-1.9 bar, the last wagon at 4.3 bar at the start).

- Standing, PrepareEngine() applies the locomotive brake first, then fills the pipe. Where the locomotive
  brake alone doesn't hold the train (1.1 x the grade force), the train brake goes to the first service
  position instead, so the reservoirs charge with the train held. Multiple units with the
  electro-pneumatic brake are released as before.
- Standing to charge, the AI unlocks the pipe as it does to go (the releaser, or the unlock button). A
  handle which has to be moved to unlock is left where the light application holds the train.
- A train is ready only once the pipe and the auxiliary reservoir of every vehicle with a working brake
  are within 0.5 bar of the working pressure (4.5 of 5.0: the last wagon of a long train stays at about
  4.6-4.7 from what leaks along the pipe), with the pipe fed at the head of the train. Brakes cut out
  don't count.
- The locomotive brake comes off only once the train is charged, also against DecBrakeEIM(), which for a
  vehicle without the integrated handle releases it too; an uphill start begins only then.
- A human driver gets the same wait as a hint: "Wait for the train brakes to charge"
  (driver_hint::waitbrakecharge), and the hint to release the brakes waits with it once the train brake is
  off (brake_charge::release_waits()). The train brake may still come off: released, it fills the pipe.
- A charge that rises by less than 0.02 bar in 60 s lets the train go all the same, with a line in the
  log. The time counts only while there is air to charge with (the engine prepared, the main reservoir
  above what the pipe charges to, the pipe fed at the head): a train with its compressor not running yet
  or a locked pipe is waited out. Once let go, a train stays so until it is to stand again: otherwise the
  pipe refilling behind the release held it at a crawl (et22-1075 with 36 wagons, baltyk_interregio).
- The check applies to the pneumatic brake only, to the first start of a train that hasn't run (above
  1 km/h) since it was placed, and to a start with the pipe below 2.5 bar (near empty, after an emergency
  application). A start after an ordinary stop, a service stop (3.0-3.5 bar), a change of direction or a
  shunting move isn't held: waiting there only delayed the train, and the scenery set the routes of the
  others later.
- The release of the train brake in PrepareEngine() had a stray semicolon after its condition; the
  condition applies again in motion.
- Unit tests for the charge check (brake_charge::charged(), locomotive_brake_holds(), release_waits()).

Run on all 174 shipped sceneries (20 minutes each, against master): no train stuck that moved on master,
466 timetable departures compared, 459 within 15 s, mean -1.2 s. Waits for the charge: median 4 s, 90%
39 s, longest 106 s (a heavy freight train charged from 2.2 bar).

* test(ai): the brake charge test counts its looks in whole numbers, not in a floating-point time

SonarCloud took the loop of the test of a train with nothing to charge with yet for a bug (cpp:S2193, a
counter of type double). The same 120 looks, 5 s apart.

* fix(ai): the light application that holds a charging train stays on, and an empty pipe is no charge

Runs of a cold train on a gradient (P33000 at Lupkow in linia_107_objazdy, 13-16 per mille, with an SM42 and 32
wagons, 1556 t) showed three faults of the charged-brakes start:

- The locomotive brake was taken to hold the train with the force of its brake blocks alone, 1031 kN for an ST43:
  several times what its wheels pass on to the rails. It is limited to a quarter of the locomotive's weight
  (brake_charge::adhesion), so a light locomotive with a heavy train gets the light application of the train brake.
- That application was taken off again as soon as the order to go came, by the rule that puts the handle back to
  running with the main reservoir below 5 bar, and by DecBrake(). The train then stood on the locomotive brake
  that doesn't hold it, and moved as its wagons let go (to 0.3 km/h). It stays on until the train is charged
  (brake_charge::holds_application()).
- With the train brake applied the train counted as charged to what the head of the pipe has, which is nothing with
  the pipe empty: charged at 0.02 bar the moment the brake was applied. The pipe at the head counts no lower than a
  full service application leaves (brake_charge::reference()).

The SM42 with the 32 wagons now stands still while it charges and starts without rolling back, 2 min 30 s after it
was prepared (4 min 40 s before, with a start that rolled back at 0.3 km/h). An ST43 with 33 wagons and a 754 with
8 coaches there are as before, their locomotive brake holds them. In eight of the sceneries run before
(l053_poranek, calkowo_v2_cementa, calkowo_v2_ctl-wegiela, calkowo_v2_osoba_jar_poranek, calkowo_retro_zima,
linia61_towarowy2, l053-sluzba-brutto-posp, baltyk_interregio) the 60 timetable departures compared are the same,
within 15 s, mean 0.0 s. Unit tests for the two new decisions.

* fix(ai): the locomotive brake counted of the occupied vehicle alone

locomotive_brake_force() added the brake of every powered vehicle of the train. The locomotive brake handle acts on the
occupied vehicle only (LocalBrakePosA is set on mvOccupied and passed to no other vehicle), so a second locomotive, in
multiple control or hauled dead, made the brake count as holding a train it doesn't hold, and the train brake was
released on a gradient with the leading locomotive alone holding.

The estimate of one vehicle is brake_charge::locomotive_brake_force(), with a test.

brakecharge.h named TController::control_brake_charge(), which doesn't exist: the logic is in
determine_consist_state().

* fix(sky): the legacy renderer gets the sky, ambient and fog of 26.05 again (#415)

* fix(sky): the legacy renderer gets the sky, ambient and fog of 26.05 again

The colours of the sky dome were made for the full renderer, which
tonemaps them and draws to an sRGB framebuffer: the sRGB matrix, the
gamma put on the brightness, a lighter gradient and a band of light
at the horizon (40c21bd4, b46c8c76, 8df81eb4), and the fog no longer
dimmed by the diffuse level (#229). The legacy and simple renderers draw
these colours as they are, and the ambient light and the fog are taken
from them, so all three differed from 26.05 there.

With Global.LegacyRenderer the dome is computed as in 26.05: the Adobe
RGB matrix, the brightness knee at 0.85, the sky tone saturated as the
colour, the plain gradient and the gamma of 0.45 by day at the end; the
fog is lit by the key light at its diffuse level. The full renderer is
unchanged. The turbidity under overcast is a separate fix (#410).

* fix(test): a test run takes the legacy and the simple renderer flag off with the renderer

From the review of #415: apply_test_mode_settings() sets the null renderer
but left Global.LegacyRenderer and Global.BasicRenderer as the gfxrenderer
line of eu07.ini made them. With this PR the legacy flag picks the colours
of the sky dome, and their average is the light level the scenery lamps,
the AI's compartment lights and Python's light_level go by. The same --test
run on a machine with "gfxrenderer legacy" and on one with the default
renderer computed different skies and could switch those lights at other
times. A test run now always takes the sky of the full renderer, as on
master. The context of a test run doesn't depend on the flag (it asks for
none in particular), and its multisampling is off, so nothing else changes.

---------

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

* fix(python): the files a screen opens itself are found on Linux when named in another case (#449)

#362 made the simulator find the data named in another case of its letters, through FileOnDisk(), the
script of a screen included. What the script opens itself goes past it: Image.open(), ImageFont.truetype(),
open() and the openimage() of the screens go straight to the system. The data is made on Windows, so on
Linux a screen that asks for "WS_on.png" where the disk has "ws_on.png" doesn't start at all, e.g. the left
screens of the EN57AL/AKM (WS_gotowosc.png), EN57AKL and EN71AKS (WN_off.png, M1M2_on.png and more).

abstractscreenrenderer.py, run in __main__ before any screen, now finds those files as FileCased() does:
the name given when it's on the disk, otherwise the one differing from it only in case, of the file or of
its folders, a folder listed again for a name missing at most once a second. builtins.open() (which
Image.open() goes through) and ImageFont.truetype() take the name so found, and openimage() looks for it.
A file not there yet goes into its folder as named on the disk, so a screen writing its state for the first
time doesn't make a second folder. A name with no such file is passed on as given, so a file missing fails
as before.

On Windows, which finds the names in any case itself, nothing is wrapped and nothing changes. No change to
the game data is needed.

Checked on a case-sensitive folder (a Windows folder with the case-sensitive attribute) with the scripts as
they are in the data: with the file of master the EN57AL, EN57AKL and EN71AKS screens fail to start, with
this one they start and render; plus the cases of the lookup (folders, ./, .., backslashes, a new file, a
missing one, the module run twice, a screen's global named like the module's own).

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* fix(render): old assets drawn as 26.05 drew them; the headlight beam spread sideways (#481)

* fix(render): old assets drawn as 26.05 drew them: metal, sun highlight, tonemapping, sun scale, diffuse colour

The shader changes since 26.05.2 were made for PBR-authored assets; the assets in the game
data were tuned for 26.05, and none of them is authored for the new combine.

- Metal keeps its diffuse term as far as its reflection mask is low (metal_diffuse_loss =
  metalic * reflectivity). Assets marking metal in the specgloss with a low mask went
  almost black (the gold EN63A-031); a full mask is drawn as before.
- The direct sun highlight is tinted by the albedo again, for dielectrics too. Old assets
  tuned param_specular / specgloss R with that multiply; untinted, dark glossy plastic broke
  into white glints along edges (Impuls fronts) and speckles on cab desks (SA132).
- ACES instead of AgX: AgX with its look crushed the dark end, a night scene lost half its
  brightness and the ground beside the track went black.
- SUN_DIFFUSE_SCALE 2.5 again (1.5 dimmed the moon at night as well).
- The Diffuse colour of submodels and shapes scales the light as it is, as in 26.05, not
  raised to 2.2: that took a quarter off the default 0.8 of every scenery shape and more off
  the ~64 000 textured submodels with a darker Diffuse.

Checked on screenshots of 10 vehicles by day (Ultra preset) and from cabs at night against
the 26.05.2 shaders on the same executable. No game data changes.

* feat(render): the headlight beam spread sideways, gfx.headlights.beamwidth (default 1.7)

The projected beam texture lit the track and the ballast, and the ground beside them only
with its dark edge (24-45 against 116 on the ballast close ahead, nearly 0 further on), so at
night only the ballast showed. The beam is spread sideways around its middle by
gfx.headlights.beamwidth: at 1.7 the ground gets most of the light of the ballast, the
brightness along the track stays as it was. 1 draws the narrow beam of 26.05; range 1-4.

The value reaches the shaders as HEADLIGHT_BEAM_WIDTH, written with the classic locale so
that a decimal comma can't break the glsl; the shader validator compiles them with and
without the spread. The key is written to the log with the other settings.

* fix(render): the sunless specgloss shader combines metal as apply_lights does

* fix(render): an untextured submodel takes its linearised colour as the texture again, as 26.05 did

mat_colored.frag gave apply_lights() a white base, so the albedo of a Map: none submodel was its diffuse colour c,
where 26.05.2 drew c^2.2 * c. A dark grey came out tens of times lighter: on the road vehicles of pctga the tyres
(25-40 grey) 60-165x, the glass 23x, whole untextured cars (a4, golf, passat, ka, arosa) 1.5-3x. With the
linearised colour as the texture a grey matches 26.05 in the ambient and the sun; a saturated colour is up to
a third darker in the sun, as 26.05 scaled the sun by the value of the colour, not by the colour.

* fix(render): the sun highlight is tinted by the texture alone, as 26.05 drew it

---------

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>
Co-authored-by: pawelw <p.warszawski@gmail.com>
2026-11-27 04:05:40 +01:00

6916 lines
245 KiB
C++

/*
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
*/
#include "stdafx.h"
#include "rendering/opengl33renderer.h"
#include "utilities/color.h"
#include "utilities/Globals.h"
#include "utilities/Timer.h"
#include "vehicle/Train.h"
#include "vehicle/Camera.h"
#include "simulation/simulation.h"
#include "utilities/Logs.h"
#include "simulation/simulationtime.h"
#include "application/application.h"
#include "model/AnimModel.h"
#include "rendering/opengl33geometrybank.h"
#include "rendering/screenshot.h"
#include "rendering/editoroverlay.h"
#include <imgui/imgui_impl_opengl3.h>
//#define EU07_DEBUG_OPENGL
int constexpr EU07_PICKBUFFERSIZE{ 1024 }; // size of (square) textures bound with the pick framebuffer
int constexpr EU07_REFLECTIONFIDELITYOFFSET { 250 }; // artificial increase of range for reflection pass detail reduction
namespace {
// the top view of the editor shows everything this close to the camera, the corners of the screen included
float
editor_ortho_reach()
{
auto const aspect{Global.window_size.x / std::max(1.f, static_cast<float>(Global.window_size.y))};
return Global.EditorOrthoExtent * std::sqrt(1.f + aspect * aspect) + 500.f;
}
float
editor_track_view_range(float const Range, bool const Apply)
{
if (false == Apply || false == Global.editor_tracks)
return Range;
float extra = 50000.0f;
if (Global.EditorOrtho)
extra = editor_ortho_reach();
return Range > extra ? Range : extra;
}
// the top view of the editor may leave the ballast of the railway out, for the ground under the tracks to show
bool
editor_ballast_hidden(TTrack const *Track, bool const Colour)
{
return Colour && EditorModeFlag && Global.EditorOrtho && Global.EditorOrthoTracks > 0 && (Track->iCategoryFlag & 15) == 1;
}
// ...or the sleepers and the timbers of the switches too, the rails alone as on a plan
bool
editor_sleepers_hidden()
{
return EditorModeFlag && Global.EditorOrtho && Global.EditorOrthoTracks > 1;
}
// far off the camera the tracks of the editor are drawn alone, the terrain, the models and the rest only as far as the
// scenery reaches in the game; the top view measures it off its centre on the ground, its camera being high above it
bool
editor_far_tracks_only(bool const Apply, scene::bounding_area const &Area, glm::dvec3 const &Camera, double const SceneryLimit)
{
if (false == Apply)
return false;
auto offset{Area.center - Camera};
if (Global.EditorOrtho)
offset.y = 0.0;
double nearest = glm::length(offset) - static_cast<double>(Area.radius);
if (nearest < 0.0)
nearest = 0.0;
return nearest > SceneryLimit;
}
// returns material assigned to the submodel, resolving replacable skins. null_handle if no skin set is bound
material_handle
submodel_material( TSubModel const *Submodel ) {
if( Submodel->m_material >= 0 ) {
return Submodel->m_material;
}
return (
TSubModel::ReplacableSkinId != nullptr ?
TSubModel::ReplacableSkinId[ -Submodel->m_material ] :
null_handle );
}
} // namespace
void GLAPIENTRY
ErrorCallback( GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam ) {
/*
auto const typestring {
type == GL_DEBUG_TYPE_ERROR ? "error" :
type == GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR ? "deprecated behavior" :
type == GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR ? "undefined behavior" :
type == GL_DEBUG_TYPE_PORTABILITY ? "portability" :
type == GL_DEBUG_TYPE_PERFORMANCE ? "performance" :
type == GL_DEBUG_TYPE_OTHER ? "other" :
"unknown" };
*/
auto const severitystring {
severity == GL_DEBUG_SEVERITY_HIGH ? "high severity" :
severity == GL_DEBUG_SEVERITY_MEDIUM ? "medium severity" :
severity == GL_DEBUG_SEVERITY_LOW ? "low severity" :
severity == GL_DEBUG_SEVERITY_NOTIFICATION ? "notification" :
"unknown" };
ErrorLog(
"bad gfx code: " + std::string( type == GL_DEBUG_TYPE_ERROR ? "** GL ERROR ** " : "" )
+ to_hex_str( id )
+ " (" + severitystring + ") "
+ message );
}
bool opengl33_renderer::Init(GLFWwindow *Window)
{
if (Global.gfx_gldebug && GLAD_GL_KHR_debug) {
glEnable( GL_DEBUG_OUTPUT );
glEnable( GL_DEBUG_OUTPUT_SYNCHRONOUS );
glDebugMessageControl( GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_NOTIFICATION, 0, nullptr, GL_FALSE );
glDebugMessageControl( GL_DONT_CARE, GL_DEBUG_TYPE_PERFORMANCE, GL_DONT_CARE, 0, nullptr, GL_FALSE );
glDebugMessageCallback( ErrorCallback, 0 );
}
glClearColor( 0.f, 0.f, 0.f, 1.f );
glClear( GL_COLOR_BUFFER_BIT );
glfwSwapBuffers( Window );
if (!Init_caps())
return false;
WriteLog("preparing renderer..");
OpenGLMatrices.upload() = false; // set matrix stack in virtual mode
m_window = Window;
gl::glsl_common_setup();
if (true == Global.ScaleSpecularValues)
{
m_specularopaquescalefactor = 0.25f;
m_speculartranslucentscalefactor = 1.5f;
}
// rgb value for 5780 kelvin
Global.DayLight.diffuse[0] = 1.0f; // 255 / 255
Global.DayLight.diffuse[1] = 0.9490196f; // 242 / 255
Global.DayLight.diffuse[2] = 0.9058824f; // 231 / 255
Global.DayLight.is_directional = true;
m_sunlight.id = opengl33_renderer::sunlight;
// create dynamic light pool
for (int idx = 0; idx < Global.DynamicLightCount; ++idx)
{
opengl33_light light;
light.id = 1 + idx;
light.is_directional = false;
m_lights.emplace_back(light);
}
// preload some common textures
WriteLog("Loading common gfx data...");
m_glaretexture = Fetch_Texture("fx/lightglare");
m_suntexture = Fetch_Texture("fx/sun");
m_moontexture = Fetch_Texture("fx/moon");
m_smoketexture = Fetch_Texture("fx/smoke");
m_headlightstexture = Fetch_Texture("fx/headlights:st");
WriteLog("...gfx data pre-loading done");
// prepare basic geometry chunks
float const size = 2.5f / 2.0f;
auto const geometrybank = Create_Bank();
gfx::vertex_array billboard_array{
{{-size, size, 0.f}, glm::vec3(), {1.f, 1.f}}, {{size, size, 0.f}, glm::vec3(), {0.f, 1.f}}, {{-size, -size, 0.f}, glm::vec3(), {1.f, 0.f}}, {{size, -size, 0.f}, glm::vec3(), {0.f, 0.f}}};
gfx::userdata_array userdata{};
m_billboardgeometry = m_geometry.create_chunk(billboard_array, userdata, geometrybank, GL_TRIANGLE_STRIP);
m_empty_vao = std::make_unique<gl::vao>();
try
{
m_vertex_shader = std::make_unique<gl::shader>("vertex.vert");
m_line_shader = make_shader("traction.vert", "traction.frag");
m_freespot_shader = make_shader("freespot.vert", "freespot.frag");
m_shadow_shader = make_shader("simpleuv.vert", "shadowmap.frag");
m_alpha_shadow_shader = make_shader("simpleuv.vert", "alphashadowmap.frag");
m_pick_shader = make_shader("vertexonly.vert", "pick.frag");
m_pick_surface_shader = make_shader("simpleuv.vert", "pick_surface.frag");
m_billboard_shader = make_shader("simpleuv.vert", "billboard.frag");
m_celestial_shader = make_shader("celestial.vert", "celestial.frag");
m_hiddenarea_shader = make_shader("hiddenarea.vert", "hiddenarea.frag");
m_copy_shader = make_shader("quad.vert", "copy.frag");
if (Global.gfx_usegles)
m_depth_pointer_shader = make_shader("quad.vert", "gles_depthpointer.frag");
m_invalid_material = Fetch_Material("invalid");
}
catch (gl::shader_exception const &e)
{
ErrorLog("invalid shader: " + std::string(e.what()));
return false;
}
scene_ubo = std::make_unique<gl::ubo>(sizeof(gl::scene_ubs), 0);
model_ubo = std::make_unique<gl::ubo>(sizeof(gl::model_ubs), 1, GL_STREAM_DRAW);
light_ubo = std::make_unique<gl::ubo>(sizeof(gl::light_ubs), 2);
instance_ubo = std::make_unique<gl::ubo>(sizeof(gl::instance_ubs), 3, GL_STREAM_DRAW);
// better initialize with 0 to not crash driver/whole system
// when we forget
memset(&light_ubs, 0, sizeof(light_ubs));
memset(&model_ubs, 0, sizeof(model_ubs));
memset(&scene_ubs, 0, sizeof(scene_ubs));
light_ubo->update(light_ubs);
model_ubo->update(model_ubs);
scene_ubo->update(scene_ubs);
// initialize instance_ubo slot 0 to identity. This is the matrix sampled by
// gl_InstanceID==0 in non-instanced draws, so existing rendering paths
// continue to multiply effective_modelview = identity * modelview = modelview.
{
glm::mat4 identity( 1.0f );
instance_ubo->update( reinterpret_cast<uint8_t const*>(&identity), 0, sizeof(identity) );
}
int samples = 1 << Global.iMultisampling;
if (!Global.gfx_usegles && samples > 1)
glEnable(GL_MULTISAMPLE);
m_pfx_motionblur = std::make_unique<gl::postfx>("motionblur");
m_pfx_tonemapping = std::make_unique<gl::postfx>("tonemapping");
m_pfx_chromaticaberration = std::make_unique<gl::postfx>( "chromaticaberration" );
m_pfx_ssao = std::make_unique<gl::postfx>("ssao");
m_pfx_ssao_blur = std::make_unique<gl::postfx>("ssao_blur");
m_pfx_ssao_apply = std::make_unique<gl::postfx>("ssao_apply");
// Generate hemisphere kernel (z > 0 = toward surface normal)
std::uniform_real_distribution<float> rnd(0.0f, 1.0f);
std::default_random_engine gen(42); // NOSONAR fixed seed on purpose, SSAO kernel has to be identical every run
for (int i = 0; i < 32; i++) {
glm::vec3 s(rnd(gen)*2.0f-1.0f, rnd(gen)*2.0f-1.0f, rnd(gen));
s = glm::normalize(s) * rnd(gen);
float scale = float(i) / 32.0f;
scale = glm::mix(0.1f, 1.0f, scale * scale); // accelerating interpolant
m_ssao_kernel[i] = s * scale;
}
// Generate 4x4 noise texture (random rotation vectors in XY)
std::vector<glm::vec3> noise_data;
for (int i = 0; i < 16; i++)
noise_data.push_back(glm::normalize(glm::vec3(rnd(gen)*2.0f-1.0f, rnd(gen)*2.0f-1.0f, 0.0f)));
// noise texture (4x4 random rotation vectors in tangent space)
// noise texture (4x4 random rotation vectors in tangent space)
m_ssao_noise_tex = std::make_unique<opengl_texture>();
m_ssao_noise_tex->alloc_rendertarget(GL_RGB32F, GL_RGB, 4, 4, 1, 1, GL_REPEAT);
m_ssao_noise_tex->bind(0);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 4, 4, GL_RGB, GL_FLOAT, noise_data.data());
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
m_empty_cubemap = std::make_unique<gl::cubemap>();
m_empty_cubemap->alloc(Global.gfx_format_color, 16, 16, GL_RGB, GL_FLOAT);
m_viewports.push_back(std::make_unique<viewport_config>());
viewport_config &default_viewport = *m_viewports.front().get();
default_viewport.width = Global.gfx_framebuffer_width;
default_viewport.height = Global.gfx_framebuffer_height;
default_viewport.main = true;
default_viewport.shadow = true;
default_viewport.window = m_window;
default_viewport.draw_range = 1.0f;
if (Global.vr) {
vr = vr_interface_factory::get_instance()->create(Global.vr_backend);
crashreport_add_info("vr_backend", Global.vr_backend);
}
if (vr) {
glm::ivec2 target_size = vr->get_target_size();
WriteLog("using vr rendertarget: " + glm::to_string(target_size));
// hijack main window for left eye
default_viewport.width = target_size.x;
default_viewport.height = target_size.y;
default_viewport.custom_backbuffer = true;
default_viewport.proj_type = viewport_config::vr_left;
// create right eye viewport
m_viewports.push_back(std::make_unique<viewport_config>());
m_viewports.back()->width = target_size.x;
m_viewports.back()->height = target_size.y;
m_viewports.back()->window = m_window; // we can reuse context
m_viewports.back()->real_window = false; // but don't draw anything to it
m_viewports.back()->custom_backbuffer = true;
m_viewports.back()->proj_type = viewport_config::vr_right;
m_viewports.back()->draw_range = 1.0f;
m_viewports.back()->shadow = true;
if (!init_viewport(*m_viewports.back()))
return false;
}
if (!init_viewport(default_viewport))
return false;
glfwMakeContextCurrent(m_window);
if (Global.gfx_shadowmap_enabled)
{
m_shadow_fb = std::make_unique<gl::framebuffer>();
m_shadow_tex = std::make_unique<opengl_texture>();
m_shadow_tex->alloc_rendertarget(Global.gfx_format_depth, GL_DEPTH_COMPONENT, m_shadowbuffersize, m_shadowbuffersize, m_shadowpass.size());
m_shadow_fb->attach(*m_shadow_tex, GL_DEPTH_ATTACHMENT, 0);
m_shadow_fb->setup_drawing(0);
if( !m_shadow_fb->is_complete() ) {
ErrorLog( "shadow framebuffer setup failed" );
return false;
}
WriteLog("shadows enabled");
}
if (Global.gfx_envmap_enabled)
{
m_env_rb = std::make_unique<gl::renderbuffer>();
m_env_rb->alloc(Global.gfx_format_depth, gl::ENVMAP_SIZE, gl::ENVMAP_SIZE);
m_env_tex = std::make_unique<gl::cubemap>();
m_env_tex->alloc(Global.gfx_format_color, gl::ENVMAP_SIZE, gl::ENVMAP_SIZE, GL_RGB, GL_FLOAT);
m_env_fb = std::make_unique<gl::framebuffer>();
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
for (int i = 0; i < 6; i++)
{
m_env_fb->attach(*m_empty_cubemap, i, GL_COLOR_ATTACHMENT0);
m_env_fb->clear(GL_COLOR_BUFFER_BIT);
}
m_env_fb->detach(GL_COLOR_ATTACHMENT0);
m_env_fb->attach(*m_env_rb, GL_DEPTH_ATTACHMENT);
WriteLog("envmap enabled");
}
m_pick_tex = std::make_unique<opengl_texture>();
m_pick_tex->alloc_rendertarget(GL_RGB8, GL_RGB, EU07_PICKBUFFERSIZE, EU07_PICKBUFFERSIZE);
m_pick_rb = std::make_unique<gl::renderbuffer>();
m_pick_rb->alloc(Global.gfx_format_depth, EU07_PICKBUFFERSIZE, EU07_PICKBUFFERSIZE);
m_pick_fb = std::make_unique<gl::framebuffer>();
m_pick_fb->attach(*m_pick_tex, GL_COLOR_ATTACHMENT0);
m_pick_fb->attach(*m_pick_rb, GL_DEPTH_ATTACHMENT);
if( !m_pick_fb->is_complete() ) {
ErrorLog( "pick framebuffer setup failed" );
return false;
}
m_picking_pbo = std::make_unique<gl::pbo>();
m_picking_node_pbo = std::make_unique<gl::pbo>();
GLenum depth_pointer_format = Global.gfx_format_depth;
if (Global.gfx_skippipeline)
{
gl::framebuffer::unbind();
GLint bits, type;
glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER, GL_DEPTH, GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE, &bits);
glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER, GL_DEPTH, GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE, &type);
if (type == GL_FLOAT && bits == 32)
depth_pointer_format = GL_DEPTH_COMPONENT32F;
else if (bits == 16)
depth_pointer_format = GL_DEPTH_COMPONENT16;
else if (bits == 24)
depth_pointer_format = GL_DEPTH_COMPONENT24;
else if (bits == 32)
depth_pointer_format = GL_DEPTH_COMPONENT32;
}
m_depth_pointer_pbo = std::make_unique<gl::pbo>();
if (!Global.gfx_usegles && Global.iMultisampling)
{
m_depth_pointer_rb = std::make_unique<gl::renderbuffer>();
m_depth_pointer_rb->alloc(depth_pointer_format, 1, 1);
m_depth_pointer_fb = std::make_unique<gl::framebuffer>();
m_depth_pointer_fb->attach(*m_depth_pointer_rb, GL_DEPTH_ATTACHMENT);
m_depth_pointer_fb->setup_drawing(0);
if( !m_depth_pointer_fb->is_complete() ) {
ErrorLog( "depth pointer framebuffer setup failed" );
return false;
}
}
else if (Global.gfx_usegles)
{
m_depth_pointer_tex = std::make_unique<opengl_texture>();
m_depth_pointer_tex->alloc_rendertarget(depth_pointer_format, GL_DEPTH_COMPONENT, Global.gfx_framebuffer_width, Global.gfx_framebuffer_height);
m_depth_pointer_rb = std::make_unique<gl::renderbuffer>();
m_depth_pointer_rb->alloc(GL_R16UI, Global.gfx_framebuffer_width, Global.gfx_framebuffer_height);
m_depth_pointer_fb = std::make_unique<gl::framebuffer>();
m_depth_pointer_fb->attach(*m_depth_pointer_tex, GL_DEPTH_ATTACHMENT);
m_depth_pointer_fb2 = std::make_unique<gl::framebuffer>();
m_depth_pointer_fb2->attach(*m_depth_pointer_rb, GL_COLOR_ATTACHMENT0);
if( !m_depth_pointer_fb->is_complete() ) {
ErrorLog( "depth pointer framebuffer setup failed" );
return false;
}
if( !m_depth_pointer_fb2->is_complete() ) {
ErrorLog( "depth pointer framebuffer2 setup failed" );
return false;
}
}
if (!Global.gfx_usegles) {
m_timequery.emplace(gl::query::TIME_ELAPSED);
m_timequery->begin();
}
WriteLog("picking objects created");
WriteLog("Gfx Renderer: setup complete");
return true;
}
void opengl33_renderer::Shutdown()
{
vr.reset();
m_screen_post.reset();
}
script_screens::post_processor *opengl33_renderer::Screen_post_processor()
{
// GLES converts what's written into an sRGB texture, and the passes give the bytes as they are: the cpu does it there
if (Global.gfx_usegles)
{
return nullptr;
}
if (m_screen_post == nullptr)
{
m_screen_post = std::make_unique<opengl33_screen_post>();
}
return m_screen_post.get();
}
bool opengl33_renderer::AddViewport(const global_settings::extraviewport_config &conf)
{
viewport_config *vp;
if (conf.monitor == "MAIN") {
vp = m_viewports.front().get();
}
else {
m_viewports.push_back(std::make_unique<viewport_config>());
vp = m_viewports.back().get();
vp->window = Application.window(-1, true, conf.width, conf.height, Application.find_monitor(conf.monitor));
}
vp->width = conf.width;
vp->height = conf.height;
vp->projection = conf.projection;
vp->proj_type = viewport_config::custom;
vp->draw_range = conf.draw_range;
bool ret = init_viewport(*vp);
glfwMakeContextCurrent(m_window);
return ret;
}
bool opengl33_renderer::init_viewport(viewport_config &vp)
{
if (vp.initialized)
return true;
glfwMakeContextCurrent(vp.window);
WriteLog("init viewport: " + std::to_string(vp.width) + " x " + std::to_string(vp.height));
if (vp.real_window)
glfwSwapInterval( Global.VSync ? 1 : 0 );
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glClearColor( 51.0f / 255.f, 102.0f / 255.f, 85.0f / 255.f, 1.f ); // initial background Color
glFrontFace(GL_CCW);
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
if (!Global.gfx_usegles)
glClearDepth(0.0f);
else
glClearDepthf(0.0f);
glDepthFunc(GL_GEQUAL);
if (GLAD_GL_ARB_clip_control)
glClipControl(GL_LOWER_LEFT, GL_ZERO_TO_ONE);
else if (GLAD_GL_EXT_clip_control)
glClipControlEXT(GL_LOWER_LEFT_EXT, GL_ZERO_TO_ONE_EXT);
if (!Global.gfx_usegles)
glEnable(GL_PROGRAM_POINT_SIZE);
if (!gl::vao::use_vao)
{
GLuint v;
glGenVertexArrays(1, &v);
glBindVertexArray(v);
}
int samples = 1 << Global.iMultisampling;
model_ubo->bind_uniform();
scene_ubo->bind_uniform();
light_ubo->bind_uniform();
if (!Global.gfx_skippipeline)
{
vp.msaa_rbc = std::make_unique<gl::renderbuffer>();
vp.msaa_rbc->alloc(Global.gfx_format_color, vp.width, vp.height, samples);
vp.msaa_rbd = std::make_unique<gl::renderbuffer>();
vp.msaa_rbd->alloc(Global.gfx_format_depth, vp.width, vp.height, samples);
vp.msaa_fb = std::make_unique<gl::framebuffer>();
vp.msaa_fb->attach(*vp.msaa_rbc, GL_COLOR_ATTACHMENT0);
vp.msaa_fb->attach(*vp.msaa_rbd, GL_DEPTH_ATTACHMENT);
if (Global.gfx_postfx_chromaticaberration_enabled || Global.gfx_postfx_motionblur_enabled || Global.gfx_postfx_ssao_enabled)
{
vp.main_tex = std::make_unique<opengl_texture>();
vp.main_tex->alloc_rendertarget(Global.gfx_format_color, GL_RGB, vp.width, vp.height, 1, 1, GL_CLAMP_TO_EDGE);
vp.main_texd = std::make_unique<opengl_texture>();
vp.main_texd->alloc_rendertarget(Global.gfx_format_depth, GL_DEPTH_COMPONENT, vp.width, vp.height, 1, 1, GL_CLAMP_TO_EDGE);
vp.main_fb = std::make_unique<gl::framebuffer>();
vp.main_fb->attach(*vp.main_tex, GL_COLOR_ATTACHMENT0);
vp.main_fb->attach(*vp.main_texd, GL_DEPTH_ATTACHMENT);
if (Global.gfx_postfx_motionblur_enabled)
{
vp.main_texv = std::make_unique<opengl_texture>();
vp.main_texv->alloc_rendertarget(Global.gfx_postfx_motionblur_format, GL_RG, vp.width, vp.height);
vp.main_fb->attach(*vp.main_texv, GL_COLOR_ATTACHMENT1);
} else
if( !vp.main_fb->is_complete() ) {
ErrorLog( "main framebuffer setup failed" );
return false;
}
}
if (Global.gfx_postfx_motionblur_enabled)
{
vp.msaa_rbv = std::make_unique<gl::renderbuffer>();
vp.msaa_rbv->alloc(Global.gfx_postfx_motionblur_format, vp.width, vp.height, samples);
vp.msaa_fb->attach(*vp.msaa_rbv, GL_COLOR_ATTACHMENT1);
WriteLog("motion blur enabled");
}
if( !vp.msaa_fb->is_complete() ) {
ErrorLog( "msaa framebuffer setup failed" );
return false;
}
vp.main2_tex = std::make_unique<opengl_texture>();
vp.main2_tex->alloc_rendertarget(Global.gfx_format_color, GL_RGB, vp.width, vp.height);
vp.main2_fb = std::make_unique<gl::framebuffer>();
vp.main2_fb->attach(*vp.main2_tex, GL_COLOR_ATTACHMENT0);
if (Global.gfx_postfx_ssao_enabled)
{
int ssao_w = std::max(1, vp.width / 2);
int ssao_h = std::max(1, vp.height / 2);
vp.ssao_tex = std::make_unique<opengl_texture>();
vp.ssao_tex->alloc_rendertarget(GL_R8, GL_RED, ssao_w, ssao_h, 1, 1, GL_CLAMP_TO_EDGE);
vp.ssao_fb = std::make_unique<gl::framebuffer>();
vp.ssao_fb->attach(*vp.ssao_tex, GL_COLOR_ATTACHMENT0);
if (!vp.ssao_fb->is_complete()) { ErrorLog("ssao framebuffer setup failed"); return false; }
vp.ssao_blur_tex = std::make_unique<opengl_texture>();
vp.ssao_blur_tex->alloc_rendertarget(GL_R8, GL_RED, ssao_w, ssao_h, 1, 1, GL_CLAMP_TO_EDGE);
vp.ssao_blur_fb = std::make_unique<gl::framebuffer>();
vp.ssao_blur_fb->attach(*vp.ssao_blur_tex, GL_COLOR_ATTACHMENT0);
if (!vp.ssao_blur_fb->is_complete()) { ErrorLog("ssao blur framebuffer setup failed"); return false; }
}
if (!vp.main2_fb->is_complete())
return false;
}
if (vp.custom_backbuffer)
{
vp.backbuffer_tex = std::make_unique<opengl_texture>();
vp.backbuffer_tex->alloc_rendertarget(GL_SRGB8, GL_RGB, vp.width, vp.height);
vp.backbuffer_fb = std::make_unique<gl::framebuffer>();
vp.backbuffer_fb->attach(*vp.backbuffer_tex, GL_COLOR_ATTACHMENT0);
if (!vp.backbuffer_fb->is_complete())
return false;
}
vp.initialized = true;
return true;
}
std::unique_ptr<gl::program> opengl33_renderer::make_shader(std::string v, std::string f)
{
gl::shader vert(v);
gl::shader frag(f);
gl::program *prog = new gl::program({vert, frag});
return std::unique_ptr<gl::program>(prog);
}
bool opengl33_renderer::Render()
{
Timer::subsystem.gfx_total.start();
if (!Global.gfx_usegles)
{
std::optional<int64_t> result = m_timequery->result();
if (result) {
m_gllasttime = *result;
m_timequery->begin();
}
}
// fetch simulation data
if (simulation::is_ready)
{
m_sunlight = Global.DayLight;
// quantize sun angle to reduce shadow crawl
auto const quantizationstep{0.004f};
m_sunlight.direction = glm::normalize(quantizationstep * glm::roundEven(m_sunlight.direction * (1.f / quantizationstep)));
}
// generate new frame
opengl_texture::reset_unit_cache();
// textures of new heightmap terrain layers go to the arrays the terrain shader reads them from
m_terrainmaterials.update();
if( EditorModeFlag ) {
// the editor moves and resizes model instances in place, which leaves the copies of their bounds out of date
++m_instanceboundsversion;
}
m_renderpass.draw_mode = rendermode::none; // force setup anew
m_renderpass.draw_stats = debug_stats();
m_geometry.primitives_count() = 0;
if (vr)
vr->begin_frame();
for (auto &viewport : m_viewports) {
Render_pass(*viewport, rendermode::color);
}
glfwMakeContextCurrent(m_window);
gl::framebuffer::unbind();
m_current_viewport = &(*m_viewports.front());
/*
m_debugtimestext += "cpu: " + to_string(Timer::subsystem.gfx_color.average(), 2) + " ms (" + std::to_string(m_cellqueue.size()) + " sectors)\n" +=
"cpu swap: " + to_string(Timer::subsystem.gfx_swap.average(), 2) + " ms\n" += "uilayer: " + to_string(Timer::subsystem.gfx_gui.average(), 2) + "ms\n" +=
"mainloop total: " + to_string(Timer::subsystem.mainloop_total.average(), 2) + "ms\n";
*/
if (!Global.gfx_usegles)
{
m_timequery->end();
/*
if (m_gllasttime)
m_debugtimestext += "gpu: " + to_string((double)(m_gllasttime / 1000ULL) / 1000.0, 3) + "ms";
*/
}
++m_framestamp;
Timer::subsystem.gfx_total.stop();
// swapbuffers() could unbind current buffers so we prepare for it on our end
gfx::opengl33_vaogeometrybank::reset();
return true; // for now always succeed
}
void opengl33_renderer::SwapBuffers()
{
Timer::subsystem.gfx_swap.start();
for (auto &viewport : m_viewports) {
if (viewport->window && viewport->real_window)
glfwSwapBuffers(viewport->window);
}
if (vr)
vr->finish_frame();
Timer::subsystem.gfx_swap.stop();
m_debugtimestext.clear();
m_debugtimestext =
"cpu frame total: " + to_string( Timer::subsystem.gfx_color.average() + Timer::subsystem.gfx_shadows.average() + ( Global.gfx_envmap_enabled ? Timer::subsystem.gfx_reflections.average() : 0.f ) + Timer::subsystem.gfx_swap.average(), 2 ) + " ms\n"
+ " color: " + to_string( Timer::subsystem.gfx_color.average(), 2 ) + " ms (" + std::to_string( m_cellqueue.size() ) + " sectors)\n";
if( Global.gfx_shadowmap_enabled ) {
m_debugtimestext +=
" shadows: " + to_string( Timer::subsystem.gfx_shadows.average(), 2 ) + " ms\n";
}
if( Global.gfx_envmap_enabled ) {
m_debugtimestext +=
" reflections: " + to_string( Timer::subsystem.gfx_reflections.average(), 2 ) + " ms\n";
}
m_debugtimestext += " swap: " + to_string( Timer::subsystem.gfx_swap.average(), 2 ) + " ms\n";
if( !Global.gfx_usegles ) {
if (m_gllasttime)
m_debugtimestext += "gpu frame total: " + to_string((double)(m_gllasttime / 1000ULL) / 1000.0, 3) + " ms\n";
}
m_debugtimestext += "uilayer: " + to_string( Timer::subsystem.gfx_gui.average(), 2 ) + " ms\n";
if( DebugModeFlag )
m_debugtimestext += m_textures.info();
debug_stats shadowstats;
for( auto const &shadowpass : m_shadowpass ) {
shadowstats += shadowpass.draw_stats;
}
m_debugstatstext =
"triangles: " + to_string( static_cast<int>(m_geometry.primitives_count()), 7 ) + "\n"
+ "vehicles: " + to_string( m_colorpass.draw_stats.dynamics, 7 ) + " +" + to_string( shadowstats.dynamics, 7 )
+ " =" + to_string( m_colorpass.draw_stats.dynamics + shadowstats.dynamics, 7 ) + "\n"
+ "models: " + to_string( m_colorpass.draw_stats.models, 7 ) + " +" + to_string( shadowstats.models, 7 )
+ " =" + to_string( m_colorpass.draw_stats.models + shadowstats.models, 7 ) + "\n"
+ "drawcalls: " + to_string( m_colorpass.draw_stats.drawcalls, 7 ) + " +" + to_string( shadowstats.drawcalls, 7 )
+ " =" + to_string( m_colorpass.draw_stats.drawcalls + shadowstats.drawcalls, 7 ) + "\n"
+ " instanced:" + to_string( m_colorpass.draw_stats.instances, 7 ) + " +" + to_string( shadowstats.instances, 7 )
+ " =" + to_string( m_colorpass.draw_stats.instances + shadowstats.instances, 7 )
+ " (" + std::to_string( m_colorpass.draw_stats.instanced_drawcalls + shadowstats.instanced_drawcalls ) + " batches)\n"
+ " inst-pool:" + std::to_string( TAnimModel::s_instanceable_total )
+ "/" + std::to_string( TAnimModel::s_classified_total )
+ " rej(noModel/lights/anim/animSubM): "
+ std::to_string( TAnimModel::s_rejected_no_pmodel ) + "/"
+ std::to_string( TAnimModel::s_rejected_lights ) + "/"
+ std::to_string( TAnimModel::s_rejected_animlist ) + "/"
+ std::to_string( TAnimModel::s_rejected_animated_submodel ) + "\n"
+ " submodels:" + to_string( m_colorpass.draw_stats.submodels, 7 ) + " +" + to_string( shadowstats.submodels, 7 )
+ " =" + to_string( m_colorpass.draw_stats.submodels + shadowstats.submodels, 7 ) + "\n"
+ " paths: " + to_string( m_colorpass.draw_stats.paths, 7 ) + " +" + to_string( shadowstats.paths, 7 )
+ " =" + to_string( m_colorpass.draw_stats.paths + shadowstats.paths, 7 ) + "\n"
+ " shapes: " + to_string( m_colorpass.draw_stats.shapes, 7 ) + " +" + to_string( shadowstats.shapes, 7 )
+ " =" + to_string( m_colorpass.draw_stats.shapes + shadowstats.shapes, 7 ) + "\n"
+ " traction: " + to_string( m_colorpass.draw_stats.traction, 7 ) + "\n"
+ " lines: " + to_string( m_colorpass.draw_stats.lines, 7 ) + "\n"
+ "particles: " + to_string( m_colorpass.draw_stats.particles, 7 );
}
void opengl33_renderer::draw_debug_ui()
{
if (!debug_ui_active)
return;
if (ImGui::Begin("Headlight config", &debug_ui_active))
{
ImGui::SetWindowSize(ImVec2(0, 0));
headlight_config_s &conf = headlight_config;
ImGui::SliderFloat("in_cutoff", &conf.in_cutoff, 0.9f, 1.1f);
ImGui::SliderFloat("out_cutoff", &conf.out_cutoff, 0.9f, 1.1f);
ImGui::SliderFloat("falloff_linear", &conf.falloff_linear, 0.0f, 1.0f, "%.3f", ImGuiSliderFlags_Logarithmic);
ImGui::SliderFloat("falloff_quadratic", &conf.falloff_quadratic, 0.0f, 1.0f, "%.3f", ImGuiSliderFlags_Logarithmic);
ImGui::SliderFloat("ambient", &conf.ambient, 0.0f, 3.0f);
ImGui::SliderFloat("intensity", &conf.intensity, 0.0f, 10.0f);
}
ImGui::End();
ImGui::SetNextWindowSize(ImVec2S(400, 400));
if (ImGui::Begin("Pickbuffer") && m_pick_tex) {
ImGui::Image((ImTextureID)(intptr_t)(m_pick_tex->id), ImGui::GetContentRegionAvail(), ImVec2(0, 1.0), ImVec2(1.0, 0));
}
ImGui::End();
}
// runs jobs needed to generate graphics for specified render pass
void opengl33_renderer::Render_pass(viewport_config &vp, rendermode const Mode)
{
setup_pass(vp, m_renderpass, Mode);
switch (m_renderpass.draw_mode)
{
case rendermode::color:
{
glDebug("rendermode::color");
glDebug("context switch");
static bool was_made = false;
if (m_current_viewport != &vp)
{
glfwMakeContextCurrent(vp.window);
m_current_viewport = &vp;
}
if ((!simulation::is_ready) || (Global.gfx_skiprendering))
{
gl::framebuffer::unbind();
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if (vp.main) {
// clear state for ui
gl::program::unbind();
Application.render_ui();
}
break;
}
m_colorpass = m_renderpass; // cache pass data
scene_ubs.time = Timer::GetTime();
{
float percipitation_intensity = glm::saturate(Global.Overcast - 1.);
scene_ubs.rain_params.x = percipitation_intensity; // % amount of droplets
scene_ubs.rain_params.y = glm::mix(15., 1., percipitation_intensity); // Regeneration time
if (TDynamicObject const *owner = Global.pCamera.m_owner; owner && !!owner->MoverParameters->CabActive)
{
for (int i = 0; i < 4; ++i)
{
if (i < owner->dWiperPos.size())
{
int index = owner->MoverParameters->CabActive > 0 ? i : static_cast<int>(owner->dWiperPos.size() - 1) - i;
scene_ubs.wiper_pos[i] = owner->dWiperPos[index];
if (owner->dWiperPos[index] > 0. && owner->wiperDirection[index])
{
scene_ubs.wiper_pos[i] += 1.;
}
if (owner->dWiperPos[index] < .025)
{
scene_ubs.wiper_timer_out[i] = scene_ubs.time;
}
if (owner->dWiperPos[index] > .975)
{
scene_ubs.wiper_timer_return[i] = scene_ubs.time;
}
}
else
{
scene_ubs.wiper_pos[i] = 0.;
scene_ubs.wiper_timer_out[i] = -1000.;
scene_ubs.wiper_timer_return[i] = -1000.;
}
}
}
else
{
scene_ubs.wiper_pos = glm::vec4{0.};
scene_ubs.wiper_timer_out = glm::vec4{-1000.};
scene_ubs.wiper_timer_return = glm::vec4{-1000.};
}
}
scene_ubs.projection = OpenGLMatrices.data(GL_PROJECTION);
scene_ubs.inv_view = glm::inverse( glm::mat4{ glm::mat3{ m_colorpass.pass_camera.modelview() } } );
scene_ubo->update(scene_ubs);
scene_ubo->bind_uniform();
if (m_widelines_supported)
glLineWidth(1.0f);
if (!Global.gfx_usegles)
{
if (Global.bWireFrame)
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
else
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
setup_shadow_unbind_map();
setup_env_map(nullptr);
if (Global.gfx_shadowmap_enabled && vp.main)
{
glDebug("render shadowmap start");
Timer::subsystem.gfx_shadows.start();
m_renderpass.draw_stats = {};
Render_pass(vp, rendermode::shadows);
m_renderpass = m_colorpass; // restore draw mode. TBD, TODO: render mode stack
Timer::subsystem.gfx_shadows.stop();
glDebug("render shadowmap end");
}
if (Global.gfx_envmap_enabled && vp.main)
{
// potentially update environmental cube map
m_renderpass.draw_stats = {};
Timer::subsystem.gfx_reflections.start();
if (Render_reflections(vp))
m_renderpass = m_colorpass; // restore color pass settings
Timer::subsystem.gfx_reflections.stop();
setup_env_map(m_env_tex.get());
}
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
setup_drawing(false);
glm::ivec2 target_size(vp.width, vp.height);
if (vp.main && !vp.custom_backbuffer) // TODO: update window sizes also for extra viewports
target_size = Global.fb_size;
if (!Global.gfx_skippipeline)
{
vp.msaa_fb->bind();
if (Global.gfx_postfx_motionblur_enabled)
vp.msaa_fb->setup_drawing(2);
else
vp.msaa_fb->setup_drawing(1);
glViewport(0, 0, vp.width, vp.height);
vp.msaa_fb->clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
else
{
if (!Global.gfx_usegles && !Global.gfx_shadergamma)
glEnable(GL_FRAMEBUFFER_SRGB);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(0, 0, target_size.x, target_size.y);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
glEnable(GL_DEPTH_TEST);
Timer::subsystem.gfx_color.start();
if (vr && (vp.proj_type == viewport_config::vr_left || vp.proj_type == viewport_config::vr_right)) {
glDebug("vr hiddenarea");
TModel3d *mask = vr->get_hiddenarea_mesh((vp.proj_type == viewport_config::vr_left) ? vr_interface::eye_left : vr_interface::eye_right);
if (mask) {
glDisable(GL_CULL_FACE);
glDisable(GL_BLEND);
glDepthMask(GL_TRUE);
m_hiddenarea_shader->bind();
draw(mask->Root->m_geometry.handle);
glEnable(GL_CULL_FACE);
}
}
setup_matrices();
setup_drawing(true);
m_renderpass.draw_stats = {};
model_ubs.future = glm::mat4();
glm::mat4 future;
if (Global.pCamera.m_owner != nullptr)
{
auto const *vehicle = Global.pCamera.m_owner;
glm::mat4 mv = OpenGLMatrices.data(GL_MODELVIEW);
future = glm::translate(mv, -glm::vec3(vehicle->get_future_movement())) * glm::inverse(mv);
m_freecameraposition.reset();
}
else if (vp.main)
{
// the free camera (freefly, debug camera) blurs the world with its own movement, as a vehicle does with its:
// without it the ground racing under a low camera strobes in rings at the distances its texture repeats.
// the movement of the frame before stands for the one to come; a jump (a camera preset) is no movement
auto const position{Global.pCamera.Pos};
if (m_freecameraposition)
{
auto movement{glm::vec3(position - *m_freecameraposition)};
auto const length{glm::length(movement)};
if (length < 50.f)
{
// the blur takes the scene where the camera will be: a fast camera (shift, ctrl) moves past the ground
// at the bottom of the screen within a frame, it ends up behind it there and its motion turns over
// into a bright band. half a metre a frame still blurs metres with the shutter of the motion blur
auto const maxmovement{0.5f};
if (length > maxmovement)
movement *= maxmovement / length;
glm::mat4 mv = OpenGLMatrices.data(GL_MODELVIEW);
future = glm::translate(mv, -movement) * glm::inverse(mv);
}
}
m_freecameraposition = position;
}
Update_Lights( simulation::Lights );
glDebug("render environment");
scene_ubs.projection = OpenGLMatrices.data(GL_PROJECTION);
scene_ubo->update(scene_ubs);
Render(&simulation::Environment);
if( Global.gfx_shadowmap_enabled )
setup_shadow_bind_map();
// opaque parts...
setup_drawing(false);
// without rain/snow we can render the cab early to limit the overdraw
// precipitation happens when overcast is in 1-2 range
if (!FreeFlyModeFlag && Global.Overcast <= 1.0f && Global.render_cab)
{
glDebug("render opaque cab");
model_ubs.future = glm::mat4();
auto const *vehicle{ simulation::Train->Dynamic() };
if( vehicle->InteriorLightLevel > 0.f ) {
setup_shadow_color( glm::min( colors::white, m_shadowcolor + glm::vec4( vehicle->InteriorLight * vehicle->InteriorLightLevel, 1.f ) ) );
}
Render_cab( vehicle, vehicle->InteriorLightLevel, false );
}
setup_shadow_color( m_shadowcolor );
glDebug("render opaque region");
model_ubs.future = future;
Render(simulation::Region);
Render_vr_models();
// ...translucent parts
glDebug("render translucent region");
setup_drawing(true);
Render_Alpha(simulation::Region);
Render_editor_overlay();
// particles
Render_particles();
// precipitation; done at end, only before cab render
Render_precipitation();
// cab render
if (false == FreeFlyModeFlag && Global.render_cab)
{
model_ubs.future = glm::mat4();
auto *vehicle { simulation::Train->Dynamic() };
if( vehicle->InteriorLightLevel > 0.f ) {
setup_shadow_color( glm::min( colors::white, m_shadowcolor + glm::vec4( vehicle->InteriorLight * vehicle->InteriorLightLevel, 1.f ) ) );
}
if (Global.Overcast > 1.0f)
{
// with active precipitation draw the opaque cab parts here to mask rain/snow placed 'inside' the cab
glDebug( "render opaque cab" );
setup_drawing(false);
Render_cab(vehicle, vehicle->InteriorLightLevel, false);
Render_interior(false);
setup_drawing(true);
Render_interior(true);
}
glDebug( "render translucent cab" );
Render_cab(vehicle, vehicle->InteriorLightLevel, true);
setup_shadow_color( m_shadowcolor );
if( Global.Overcast > 1.0f ) {
// with the cab in place we can (finally) safely draw translucent part of the occupied vehicle
Render_Alpha( vehicle );
}
}
Timer::subsystem.gfx_color.stop();
// store draw stats
m_colorpass.draw_stats = m_renderpass.draw_stats;
setup_shadow_unbind_map();
setup_env_map(nullptr);
if (!Global.gfx_usegles)
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
if (!Global.gfx_skippipeline)
{
if (Global.gfx_postfx_motionblur_enabled)
{
vp.main_fb->clear(GL_COLOR_BUFFER_BIT);
vp.main_fb->setup_drawing(2);
vp.msaa_fb->blit_to(vp.main_fb.get(), vp.width, vp.height, GL_COLOR_BUFFER_BIT, GL_COLOR_ATTACHMENT0);
vp.msaa_fb->blit_to(vp.main_fb.get(), vp.width, vp.height, GL_COLOR_BUFFER_BIT, GL_COLOR_ATTACHMENT1);
vp.msaa_fb->blit_to(vp.main_fb.get(), vp.width, vp.height, GL_DEPTH_BUFFER_BIT, GL_DEPTH_ATTACHMENT);
model_ubs.param[0].x = m_framerate / (1.0 / Global.gfx_postfx_motionblur_shutter);
model_ubo->update(model_ubs);
m_pfx_motionblur->apply({vp.main_tex.get(), vp.main_texv.get(), vp.main_texd.get()}, vp.main2_fb.get());
}
else if (Global.gfx_postfx_ssao_enabled)
{
// resolve color+depth so SSAO can sample the depth texture
vp.main_fb->clear(GL_COLOR_BUFFER_BIT);
vp.main_fb->setup_drawing(1);
vp.msaa_fb->blit_to(vp.main_fb.get(), vp.width, vp.height, GL_COLOR_BUFFER_BIT, GL_COLOR_ATTACHMENT0);
vp.msaa_fb->blit_to(vp.main_fb.get(), vp.width, vp.height, GL_DEPTH_BUFFER_BIT, GL_DEPTH_ATTACHMENT);
}
else
{
vp.main2_fb->clear(GL_COLOR_BUFFER_BIT);
vp.msaa_fb->blit_to(vp.main2_fb.get(), vp.width, vp.height, GL_COLOR_BUFFER_BIT, GL_COLOR_ATTACHMENT0);
}
// SSAO: depth -> occlusion -> blur -> modulate color into main2_fb
if (Global.gfx_postfx_ssao_enabled && !Global.gfx_postfx_motionblur_enabled)
{
int ssao_w = std::max(1, vp.width / 2);
int ssao_h = std::max(1, vp.height / 2);
// (kernel is generated procedurally in the shader; no UBO upload needed)
glViewport(0, 0, ssao_w, ssao_h);
m_pfx_ssao ->apply({ vp.main_texd.get(), m_ssao_noise_tex.get() }, vp.ssao_fb.get());
m_pfx_ssao_blur->apply({ vp.ssao_tex.get() }, vp.ssao_blur_fb.get());
glViewport(0, 0, vp.width, vp.height);
vp.main2_fb->clear(GL_COLOR_BUFFER_BIT);
m_pfx_ssao_apply->apply({ vp.main_tex.get(), vp.ssao_blur_tex.get() }, vp.main2_fb.get());
}
if (!Global.gfx_usegles && !Global.gfx_shadergamma)
glEnable(GL_FRAMEBUFFER_SRGB);
gl::framebuffer *target = nullptr;
if (vp.custom_backbuffer)
target = vp.backbuffer_fb.get();
if( Global.gfx_postfx_chromaticaberration_enabled ) {
glViewport(0, 0, vp.width, vp.height);
vp.main_fb->setup_drawing(1);
m_pfx_tonemapping->apply( *vp.main2_tex, vp.main_fb.get() );
glViewport(0, 0, target_size.x, target_size.y);
m_pfx_chromaticaberration->apply( *vp.main_tex, target );
}
else {
glViewport(0, 0, target_size.x, target_size.y);
m_pfx_tonemapping->apply( *vp.main2_tex, target );
}
if (vr) {
if (vp.proj_type == viewport_config::vr_left)
vr->submit(vr_interface::eye_left, vp.backbuffer_tex.get());
if (vp.proj_type == viewport_config::vr_right)
vr->submit(vr_interface::eye_right, vp.backbuffer_tex.get());
}
if (vp.custom_backbuffer && vp.real_window) {
if (vp.main)
target_size = Global.fb_size;
glViewport(0, 0, target_size.x, target_size.y);
vp.backbuffer_tex->bind(0);
m_copy_shader->bind();
m_empty_vao->bind();
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
vp.backbuffer_tex->unbind(0);
}
opengl_texture::reset_unit_cache();
}
if (!Global.gfx_usegles && !Global.gfx_shadergamma)
glDisable(GL_FRAMEBUFFER_SRGB);
glDebug("uilayer render");
Timer::subsystem.gfx_gui.start();
if (vp.main) {
// clear state for ui
gl::program::unbind();
draw_debug_ui();
Application.render_ui();
}
Timer::subsystem.gfx_gui.stop();
// restore binding
scene_ubo->bind_uniform();
glDebug("rendermode::color end");
break;
}
case rendermode::shadows:
{
if (!simulation::is_ready)
break;
glDebug("rendermode::shadows");
glEnable(GL_DEPTH_TEST);
setup_drawing( false );
glViewport(0, 0, m_shadowbuffersize, m_shadowbuffersize);
float csmstageboundaries[] = {0.0f,
Global.shadowtune.range / 32,
Global.shadowtune.range / 8,
Global.shadowtune.range};
if( Global.shadowtune.map_size > 2048 ) {
// increase coverage if our shadow map is large enough to produce decent results
csmstageboundaries[1] *= Global.shadowtune.map_size / 2048;
csmstageboundaries[2] *= Global.shadowtune.map_size / 2048;
csmstageboundaries[3] *= Global.shadowtune.map_size / 2048;
}
for( auto idx = 0; idx < m_shadowpass.size(); ++idx ) {
m_shadow_fb->attach( *m_shadow_tex, GL_DEPTH_ATTACHMENT, idx );
m_shadow_fb->clear( GL_DEPTH_BUFFER_BIT );
setup_pass( vp, m_renderpass, rendermode::shadows, csmstageboundaries[ idx ], csmstageboundaries[ idx + 1 ] );
m_shadowpass[ idx ] = m_renderpass; // store pass config for reference in other stages
setup_matrices();
scene_ubs.projection = OpenGLMatrices.data( GL_PROJECTION );
auto const csmstagezfar {
(csmstageboundaries[ idx + 1 ])
+ ( m_shadowpass.size() - idx ) }; // we can fairly safely add some extra padding in the early stages
scene_ubs.cascade_end[ idx ] = csmstagezfar * csmstagezfar; // store squared to allow semi-optimized length2 comparisons in the shader
scene_ubo->update( scene_ubs );
if( m_shadowcolor != colors::white ) {
Render( simulation::Region );
if( idx > 0 ) { continue; } // render cab only in the closest csm stage
if( !FreeFlyModeFlag && Global.render_cab ) {
Render_cab( simulation::Train->Dynamic(), 0.0f, false );
Render_cab( simulation::Train->Dynamic(), 0.0f, true );
}
}
}
m_shadow_fb->unbind();
glDebug("rendermode::shadows end");
break;
}
case rendermode::reflections:
{
if (!simulation::is_ready)
break;
glDebug("rendermode::reflections");
// NOTE: buffer attachment and viewport setup in this mode is handled by the wrapper method
glEnable(GL_DEPTH_TEST);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
m_env_fb->clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
m_env_fb->bind();
setup_env_map(m_empty_cubemap.get());
setup_matrices();
// render
// environment...
setup_drawing(true);
setup_shadow_unbind_map();
scene_ubs.projection = OpenGLMatrices.data(GL_PROJECTION);
scene_ubo->update(scene_ubs);
Render(&simulation::Environment);
// opaque parts...
setup_drawing(false);
setup_shadow_bind_map();
scene_ubs.projection = OpenGLMatrices.data(GL_PROJECTION);
scene_ubo->update(scene_ubs);
Render(simulation::Region);
m_env_fb->unbind();
glDebug("rendermode::reflections end");
break;
}
case rendermode::pickcontrols:
{
if (!simulation::is_ready || !simulation::Train)
break;
glDebug("rendermode::pickcontrols");
glEnable(GL_DEPTH_TEST);
glViewport(0, 0, EU07_PICKBUFFERSIZE, EU07_PICKBUFFERSIZE);
m_pick_fb->bind();
m_pick_fb->clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
m_picksurfaceitems.clear();
m_pickcontrolsitems.clear();
setup_matrices();
setup_drawing(false);
scene_ubs.projection = OpenGLMatrices.data(GL_PROJECTION);
scene_ubo->update(scene_ubs);
if (simulation::Train != nullptr) {
Render_cab(simulation::Train->Dynamic(), 0.0f);
Render(simulation::Train->Dynamic());
}
m_pick_fb->unbind();
glDebug("rendermode::pickcontrols end");
break;
}
case rendermode::pickscenery:
{
if (!simulation::is_ready)
break;
glEnable(GL_DEPTH_TEST);
glViewport(0, 0, EU07_PICKBUFFERSIZE, EU07_PICKBUFFERSIZE);
m_pick_fb->bind();
m_pick_fb->clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
m_picksceneryitems.clear();
setup_matrices();
setup_drawing(false);
scene_ubs.projection = OpenGLMatrices.data(GL_PROJECTION);
scene_ubo->update(scene_ubs);
Render(simulation::Region);
break;
}
default:
{
break;
}
}
}
bool opengl33_renderer::Render_interior( bool const Alpha ) {
// TODO: early frustum based cull, camera might be pointing elsewhere
std::vector< std::pair<float, TDynamicObject *> > dynamics;
auto *dynamic { simulation::Train->Dynamic() };
// draw interiors of the occupied vehicle, and all vehicles behind it with permanent coupling, in case they're open-ended
while( dynamic != nullptr ) {
glm::dvec3 const originoffset { dynamic->vPosition - m_renderpass.pass_camera.position() };
float const squaredistance{ glm::length2( glm::vec3{ originoffset } / Global.ZoomFactor ) };
dynamics.emplace_back( squaredistance, dynamic );
dynamic = dynamic->Next( coupling::permanent );
}
// draw also interiors of permanently coupled vehicles in front, if there's any
dynamic = simulation::Train->Dynamic()->Prev( coupling::permanent );
while( dynamic != nullptr ) {
glm::dvec3 const originoffset { dynamic->vPosition - m_renderpass.pass_camera.position() };
float const squaredistance{ glm::length2( glm::vec3{ originoffset } / Global.ZoomFactor ) };
dynamics.emplace_back( squaredistance, dynamic );
dynamic = dynamic->Prev( coupling::permanent );
}
if( Alpha ) {
std::sort(
std::begin( dynamics ), std::end( dynamics ),
[]( std::pair<float, TDynamicObject *> const &Left, std::pair<float, TDynamicObject *> const &Right ) {
return ( Left.first ) > ( Right.first ); } );
}
for( auto &dynamic : dynamics ) {
Render_lowpoly( dynamic.second, dynamic.first, true, Alpha );
}
return true;
}
bool opengl33_renderer::Render_lowpoly( TDynamicObject *Dynamic, float const Squaredistance, bool const Setup, bool const Alpha ) {
if( Dynamic->mdLowPolyInt == nullptr ) { return false; }
// low poly interior
if( Setup ) {
TSubModel::iInstance = reinterpret_cast<std::uintptr_t>( Dynamic ); //żeby nie robić cudzych animacji
TSubModel::iVariantSeed = Dynamic->variant_seed();
glm::dvec3 const originoffset{ Dynamic->vPosition - m_renderpass.pass_camera.position() };
Dynamic->ABuLittleUpdate( Squaredistance ); // ustawianie zmiennych submodeli dla wspólnego modelu
glm::mat4 mv = OpenGLMatrices.data( GL_MODELVIEW );
::glPushMatrix();
::glTranslated( originoffset.x, originoffset.y, originoffset.z );
::glMultMatrixd( glm::value_ptr(Dynamic->mMatrix) );
}
// HACK: reduce light level for vehicle interior if there's strong global lighting source
if( false == Alpha ) {
/*
auto const luminance { static_cast<float>( std::min(
( Dynamic->fShade > 0.0 ? Dynamic->fShade * Global.fLuminance : Global.fLuminance ),
Global.fLuminance - 0.5 * ( std::max( 0.3, Global.fLuminance - Global.Overcast ) ) ) ) };
*/
auto const luminance{ static_cast<float>(
0.5
* ( std::max(
0.3,
( Global.fLuminance - Global.Overcast )
* ( Dynamic->fShade > 0.0 ?
Dynamic->fShade :
1.0 ) ) ) ) };
setup_sunlight_intensity(
std::clamp( (
Dynamic->fShade > 0.f ?
Dynamic->fShade :
1.f )
- luminance,
0.f, 1.f ) );
Render( Dynamic->mdLowPolyInt, Dynamic->Material(), Squaredistance );
// HACK: if the model has low poly interior, we presume the load is placed inside and also affected by reduced light level
if( Dynamic->mdLoad ) {
// renderowanie nieprzezroczystego ładunku
Render( Dynamic->mdLoad, Dynamic->Material(), Squaredistance, { 0.f, Dynamic->LoadOffset, 0.f }, {} );
}
setup_sunlight_intensity( Dynamic->fShade > 0.f ? Dynamic->fShade : 1.f );
}
else {
// Render_Alpha( Dynamic->mdLowPolyInt, Dynamic->Material(), Squaredistance );
// HACK: some models have windows included as part of the main model instead of lowpoly
if( Dynamic->mdModel ) {
// main model
Render_Alpha( Dynamic->mdModel, Dynamic->Material(), Squaredistance );
}
}
if( Setup ) {
if( Dynamic->fShade > 0.0f ) {
// restore regular light level
setup_sunlight_intensity();
}
::glPopMatrix();
// TODO: check if this reset is needed. In theory each object should render all parts based on its own instance data anyway?
if( Dynamic->btnOn ) {
Dynamic->TurnOff(); // przywrócenie domyślnych pozycji submodeli
}
}
return true;
}
bool opengl33_renderer::Render_coupler_adapter( TDynamicObject *Dynamic, float const Squaredistance, int const End, bool const Alpha ) {
if( Dynamic->m_coupleradapters[ End ] == nullptr ) { return false; }
auto const position { glm::dvec3 {
0.f,
Dynamic->MoverParameters->Couplers[ End ].adapter_height,
( Dynamic->MoverParameters->Couplers[ End ].adapter_length + Dynamic->MoverParameters->Dim.L * 0.5 ) * ( End == end::front ? 1 : -1 ) } };
auto const angle { glm::vec3{
0,
( End == end::front ? 0 : 180 ),
0 } };
if( Alpha ) {
Render_Alpha( Dynamic->m_coupleradapters[ End ], Dynamic->Material(), Squaredistance, position, angle );
}
else {
Render( Dynamic->m_coupleradapters[ End ], Dynamic->Material(), Squaredistance, position, angle );
}
return true;
}
// creates dynamic environment cubemap
bool opengl33_renderer::Render_reflections(viewport_config &vp)
{
if( Global.reflectiontune.update_interval == 0 ) { return false; }
// the top view of the editor shows nothing the reflections would be seen on: the cube map stays as it was
if( EditorModeFlag && Global.EditorOrtho ) { return false; }
if( m_environmentupdateface >= 6 ) {
// no update in progress, check whether it's time for another one
auto const timestamp{ Timer::GetRenderTime() };
if( ( timestamp - m_environmentupdatetime < Global.reflectiontune.update_interval )
&& ( glm::length2( m_renderpass.pass_camera.position() - m_environmentupdatelocation ) < sq(1000.0)) ) // length2 is better than length for comparing because it does not require sqrt function
{
// run update every 5+ mins of simulation time, or at least 1km from the last location
return false;
}
m_environmentupdatetime = timestamp;
m_environmentupdatelocation = m_renderpass.pass_camera.position();
m_environmentupdateface = 0;
}
// an update draws the scene six times, which is too much for a single frame. its cost is spread
// by drawing one face of the map per frame, all of them as seen from the place the update began at.
// the first update is done in one go, as there's nothing to show in the meantime
auto const lastface{ m_environmentready ? m_environmentupdateface : 5 };
glViewport(0, 0, gl::ENVMAP_SIZE, gl::ENVMAP_SIZE);
for (; m_environmentupdateface <= lastface; ++m_environmentupdateface)
{
m_environmentcubetextureface = m_environmentupdateface;
m_env_fb->attach(*m_env_tex, m_environmentcubetextureface, GL_COLOR_ATTACHMENT0);
if (m_env_fb->is_complete())
Render_pass(vp, rendermode::reflections);
}
if (m_environmentupdateface >= 6)
{
m_env_tex->generate_mipmaps();
m_environmentready = true;
}
m_env_fb->detach(GL_COLOR_ATTACHMENT0);
return true;
}
// based on
// https://csc.lsu.edu/~kooima/articles/genperspective/index.html
glm::mat4 opengl33_renderer::perspective_projection(const viewport_proj_config &c,
float n, float f, glm::mat4 &frustum)
{
glm::vec3 vr, vu, vn;
vr = glm::normalize(c.pb - c.pa);
vu = glm::normalize(c.pc - c.pa);
vn = glm::normalize(glm::cross(vr, vu));
glm::mat4 M;
M[0] = glm::vec4(vr, 0.0f);
M[1] = glm::vec4(vu, 0.0f);
M[2] = glm::vec4(vn, 0.0f);
M = glm::transpose(M);
glm::vec3 va, vb, vc;
va = c.pa - c.pe;
vb = c.pb - c.pe;
vc = c.pc - c.pe;
float l, r, b, t, d;
d = -glm::dot(va, vn);
l = glm::dot(vr, va) * n / d;
r = glm::dot(vr, vb) * n / d;
b = glm::dot(vu, va) * n / d;
t = glm::dot(vu, vc) * n / d;
frustum = glm::frustum(l, r, b, t, n, f);
glm::mat4 R = frustum;
frustum = glm::translate(frustum * M, -c.pe);
if (GLAD_GL_ARB_clip_control || GLAD_GL_EXT_clip_control) {
// when clip_control available, use projection matrix with 1..0 Z range and infinite zfar
R[2][2] = -1.0f;
R[3][2] = -2.0f * n;
R = glm::mat4( //
1.0f, 0.0f, 0.0f, 0.0f, //
0.0f, 1.0f, 0.0f, 0.0f, //
0.0f, 0.0f, -0.5f, 0.0f, //
0.0f, 0.0f, 0.5f, 1.0f //
) * R;
} else {
// or use standard matrix but with 1..-1 Z range
// (reverse Z don't give any extra precision without clip_control, but it is used anyway for consistency)
R = glm::mat4(
1.0f, 0.0f, 0.0f, 0.0f, //
0.0f, 1.0f, 0.0f, 0.0f, //
0.0f, 0.0f, -1.0f, 0.0f, //
0.0f, 0.0f, 0.0f, 1.0f //
) * R;
}
return glm::translate(R * M, -c.pe);
}
glm::mat4 opengl33_renderer::perspective_projection_raw(float fovy, float aspect, float znear, float zfar)
{
if (GLAD_GL_ARB_clip_control || GLAD_GL_EXT_clip_control)
{
const float f = 1.0f / std::tan(fovy / 2.0f);
// when clip_control available, use projection matrix with 1..0 Z range and infinite zfar
return glm::mat4( //
f / aspect, 0.0f, 0.0f, 0.0f, //
0.0f, f, 0.0f, 0.0f, //
0.0f, 0.0f, 0.0f, -1.0f, //
0.0f, 0.0f, znear, 0.0f //
);
}
else
// or use standard matrix but with 1..-1 Z range
// (reverse Z don't give any extra precision without clip_control, but it is used anyway for consistency)
return glm::mat4( //
1.0f, 0.0f, 0.0f, 0.0f, //
0.0f, 1.0f, 0.0f, 0.0f, //
0.0f, 0.0f, -1.0f, 0.0f, //
0.0f, 0.0f, 0.0f, 1.0f //
) *
glm::perspective(fovy, aspect, znear, zfar);
}
glm::mat4 opengl33_renderer::ortho_projection(float l, float r, float b, float t, float znear, float zfar)
{
glm::mat4 proj = glm::ortho(l, r, b, t, znear, zfar);
if (GLAD_GL_ARB_clip_control || GLAD_GL_EXT_clip_control)
// when clip_control available, use projection matrix with 1..0 Z range
return glm::mat4( //
1.0f, 0.0f, 0.0f, 0.0f, //
0.0f, 1.0f, 0.0f, 0.0f, //
0.0f, 0.0f, -0.5f, 0.0f, //
0.0f, 0.0f, 0.5f, 1.0f //
) *
proj;
else
// or use standard matrix but with 1..-1 Z range
// (reverse Z don't give any extra precision without clip_control, but it is used anyway for consistency)
return glm::mat4( //
1.0f, 0.0f, 0.0f, 0.0f, //
0.0f, 1.0f, 0.0f, 0.0f, //
0.0f, 0.0f, -1.0f, 0.0f, //
0.0f, 0.0f, 0.0f, 1.0f //
) *
proj;
}
glm::mat4 opengl33_renderer::ortho_frustumtest_projection(float l, float r, float b, float t, float znear, float zfar)
{
// for frustum calculation, use standard opengl matrix
return glm::ortho(l, r, b, t, znear, zfar);
}
// the main viewport of the editor in the orthographic view replaces the perspective projection
void opengl33_renderer::editor_ortho_projection(viewport_config const &Viewport, float const Zfar, glm::mat4 &Projection, glm::mat4 &Frustum)
{
if (false == (EditorModeFlag && Global.EditorOrtho && Viewport.main))
return;
auto const height{Global.EditorOrthoExtent};
auto const width{height * Global.window_size.x / std::max(1.f, static_cast<float>(Global.window_size.y))};
Projection = ortho_projection(-width, width, -height, height, -Zfar, Zfar);
Frustum = ortho_frustumtest_projection(-width, width, -height, height, -Zfar, Zfar);
}
void opengl33_renderer::setup_pass(viewport_config &Viewport, renderpass_config &Config, rendermode const Mode,
float const Znear, float const Zfar, bool const Ignoredebug)
{
Config.draw_mode = Mode;
if( false == simulation::is_ready ) { return; }
// setup draw range
switch( Mode ) {
case rendermode::color: { Config.draw_range = Global.BaseDrawRange * Global.fDistanceFactor * Viewport.draw_range; break; }
case rendermode::shadows: { Config.draw_range = Global.shadowtune.range; break; }
case rendermode::reflections: { Config.draw_range = Global.BaseDrawRange * Viewport.draw_range; break; }
case rendermode::pickcontrols: { Config.draw_range = 50.f; break; }
case rendermode::pickscenery: { Config.draw_range = Global.BaseDrawRange * Viewport.draw_range * 0.5f; break; }
default: { Config.draw_range = 0.f; break; }
}
// setup camera
auto &camera = Config.pass_camera;
glm::dmat4 viewmatrix(1.0);
glm::mat4 frustumtest_proj;
glm::ivec2 target_size(Viewport.width, Viewport.height);
if (Viewport.main) // TODO: update window sizes also for extra viewports
target_size = Global.fb_size;
Config.viewport_camera.position() = Global.pCamera.Pos;
switch (Mode)
{
case rendermode::color:
{
if (Viewport.proj_type == viewport_config::normal && Viewport.main) {
// TODO: update window sizes also for extra viewports
float const fovy = glm::radians(Global.FieldOfView / Global.ZoomFactor);
// setup virtual screen
glm::vec2 screen_h = glm::vec2(Global.window_size) / 2.0f;
float const dist = screen_h.y / glm::tan(fovy / 2.0f);
Viewport.projection.pa = glm::vec3(-screen_h.x, -screen_h.y, -dist);
Viewport.projection.pb = glm::vec3( screen_h.x, -screen_h.y, -dist);
Viewport.projection.pc = glm::vec3(-screen_h.x, screen_h.y, -dist);
Viewport.projection.pe = glm::vec3(0.0f, 0.0f, 0.0f);
}
if (vr && (Viewport.proj_type == viewport_config::vr_left || Viewport.proj_type == viewport_config::vr_right)) {
Viewport.projection = vr->get_proj_config(Viewport.proj_type == viewport_config::vr_left ? vr_interface::eye_left : vr_interface::eye_right);
Global.pCamera.Angle.x = 0.0;
Global.pCamera.Angle.z = 0.0;
}
if (Global.headtrack_conf.magic_window)
Viewport.projection.pe = Global.viewport_move;
TCamera *cam = ((false == DebugCameraFlag) || (true == Ignoredebug)) ? &Global.pCamera : &Global.pDebugCamera;
camera.position() = cam->Pos;
cam->SetMatrix(viewmatrix);
if (!Global.headtrack_conf.magic_window || vr) {
camera.position() += Global.viewport_move * glm::mat3(viewmatrix);
viewmatrix = glm::dmat4(glm::inverse(Global.viewport_rotate)) * viewmatrix;
}
// optimization: don't bother drawing things completely blended with the background
// but ensure at least 2 km range to account for signals and lights
Config.draw_range = std::min( Config.draw_range, m_fogrange * 2 );
Config.draw_range = std::max( 2000.f, Config.draw_range );
// projection
auto zfar = ( Zfar > 1.f ? Zfar : Config.draw_range * Zfar );
auto const znear = ( Znear > 1.f ? Znear : Znear > 0.f ? Znear * zfar : 0.1f * Global.ZoomFactor);
if (EditorModeFlag && Viewport.main)
zfar = editor_track_view_range(zfar, true);
camera.projection() = perspective_projection(Viewport.projection, znear, zfar, frustumtest_proj);
editor_ortho_projection(Viewport, zfar, camera.projection(), frustumtest_proj);
break;
}
case rendermode::shadows:
{
// calculate lightview boundaries based on relevant area of the world camera frustum:
// ...setup chunk of frustum we're interested in...
// auto const zfar = std::min(1.f, Global.shadowtune.range / (Global.BaseDrawRange * Global.fDistanceFactor) * std::max(1.f, Global.ZoomFactor * 0.5f));
// auto const zfar = ( Zfar > 1.f ? Zfar * std::max( 1.f, Global.ZoomFactor * 0.5f ) : Zfar );
auto const zfar = ( Zfar > 1.f ? Zfar : Zfar * Global.shadowtune.range * std::max( Zfar, Global.ZoomFactor * 0.5f ) );
size_t bounding_viewports_count = 0;
std::vector<glm::vec4> frustumchunkshapepoints;
glm::dvec3 pass_camera;
for (std::unique_ptr<viewport_config> &conf : m_viewports) {
if (!conf->shadow)
continue;
renderpass_config worldview;
setup_pass(*conf, worldview, rendermode::color, Znear, zfar, true);
auto &points = worldview.pass_camera.frustum_points();
frustumchunkshapepoints.insert(frustumchunkshapepoints.end(), points.begin(), points.end());
pass_camera += worldview.pass_camera.position();
bounding_viewports_count++;
}
pass_camera /= bounding_viewports_count;
// ...modelview matrix: determine the centre of frustum chunk in world space...
glm::vec3 frustumchunkmin, frustumchunkmax;
bounding_box(frustumchunkmin, frustumchunkmax, std::begin(frustumchunkshapepoints), std::end(frustumchunkshapepoints));
auto const frustumchunkcentre = (frustumchunkmin + frustumchunkmax) * 0.5f;
// ...cap the vertical angle to keep shadows from getting too long...
auto const lightvector = glm::normalize(glm::vec3{m_sunlight.direction.x, std::min(m_sunlight.direction.y, Global.gfx_shadow_angle_min), m_sunlight.direction.z});
// ...place the light source at the calculated centre and setup world space light view matrix...
camera.position() = pass_camera + glm::dvec3{frustumchunkcentre};
viewmatrix *= glm::lookAt(camera.position(), camera.position() + glm::dvec3{lightvector}, glm::dvec3{0.f, 1.f, 0.f});
// ...projection matrix: calculate boundaries of the frustum chunk in light space...
auto const lightviewmatrix = glm::translate(glm::mat4{glm::mat3{viewmatrix}}, -frustumchunkcentre);
for (auto &point : frustumchunkshapepoints)
{
point = lightviewmatrix * point;
}
bounding_box(frustumchunkmin, frustumchunkmax, std::begin(frustumchunkshapepoints), std::end(frustumchunkshapepoints));
// quantize the frustum points and add some padding, to reduce shadow shimmer on scale changes
auto const frustumchunkdepth { zfar - ( Znear > 1.f ? Znear : 0.f ) };
auto const quantizationstep{std::min(frustumchunkdepth, 50.f)};
frustumchunkmin = quantizationstep * glm::floor(frustumchunkmin * (1.f / quantizationstep));
frustumchunkmax = quantizationstep * glm::ceil(frustumchunkmax * (1.f / quantizationstep));
// ...use the dimensions to set up light projection boundaries...
// NOTE: since we only have one cascade map stage, we extend the chunk forward/back to catch areas normally covered by other stages
camera.projection() = ortho_projection(frustumchunkmin.x, frustumchunkmax.x, frustumchunkmin.y, frustumchunkmax.y, frustumchunkmin.z - 500.f, frustumchunkmax.z + 500.f);
frustumtest_proj = ortho_frustumtest_projection(frustumchunkmin.x, frustumchunkmax.x, frustumchunkmin.y, frustumchunkmax.y, frustumchunkmin.z - 500.f, frustumchunkmax.z + 500.f);
// ... and adjust the projection to sample complete shadow map texels:
// get coordinates for a sample texel...
auto shadowmaptexel = glm::vec2{camera.projection() * glm::mat4{viewmatrix} * glm::vec4{0.f, 0.f, 0.f, 1.f}};
// ...convert result from clip space to texture coordinates, and calculate adjustment...
shadowmaptexel *= m_shadowbuffersize * 0.5f;
auto shadowmapadjustment = glm::round(shadowmaptexel) - shadowmaptexel;
// ...transform coordinate change back to homogenous light space...
shadowmapadjustment /= m_shadowbuffersize * 0.5f;
// ... and bake the adjustment into the projection matrix
camera.projection() = glm::translate(glm::mat4{1.f}, glm::vec3{shadowmapadjustment, 0.f}) * camera.projection();
break;
}
case rendermode::pickcontrols:
case rendermode::pickscenery:
{
// modelview
camera.position() = Global.pCamera.Pos;
Global.pCamera.SetMatrix(viewmatrix);
viewport_proj_config proj = Viewport.projection;
// projection
float znear = 0.1f * Global.ZoomFactor;
float zfar = Config.draw_range * Global.fDistanceFactor;
if (EditorModeFlag && Viewport.main && Mode == rendermode::pickscenery)
zfar = editor_track_view_range(zfar, true);
if (vr) {
glm::mat4 transform = vr->get_pick_transform();
camera.position() += glm::vec3(transform[3]) * glm::mat3(viewmatrix);
viewmatrix = glm::dmat4(glm::inverse(glm::mat3(transform))) * viewmatrix;
znear = 0.01f;
zfar = 10.0f;
float const fovy = glm::radians(3.0f);
glm::vec2 screen_h = glm::vec2(1000.0f, 1000.0f) / 2.0f;
float const dist = screen_h.y / glm::tan(fovy / 2.0f);
proj.pa = glm::vec3(-screen_h.x, -screen_h.y, -dist);
proj.pb = glm::vec3( screen_h.x, -screen_h.y, -dist);
proj.pc = glm::vec3(-screen_h.x, screen_h.y, -dist);
proj.pe = glm::vec3(0.0f, 0.0f, 0.0f);
}
camera.projection() = perspective_projection(proj, znear, zfar, frustumtest_proj);
editor_ortho_projection(Viewport, zfar, camera.projection(), frustumtest_proj);
break;
}
case rendermode::reflections:
{
// modelview
// the faces of the map are drawn over a few frames. each is drawn from the place the camera was at
// when the update began, so they fit together along the edges when the camera moves in the meantime
camera.position() = m_environmentupdatelocation;
glm::dvec3 const cubefacetargetvectors[6] = {{1.0, 0.0, 0.0}, {-1.0, 0.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, -1.0, 0.0}, {0.0, 0.0, 1.0}, {0.0, 0.0, -1.0}};
glm::dvec3 const cubefaceupvectors[6] = {{0.0, -1.0, 0.0}, {0.0, -1.0, 0.0}, {0.0, 0.0, 1.0}, {0.0, 0.0, -1.0}, {0.0, -1.0, 0.0}, {0.0, -1.0, 0.0}};
auto const cubefaceindex = m_environmentcubetextureface;
viewmatrix *= glm::lookAt(camera.position(), camera.position() + cubefacetargetvectors[cubefaceindex], cubefaceupvectors[cubefaceindex]);
// projection
float znear = 0.1f * Global.ZoomFactor;
float zfar = Config.draw_range * Global.fDistanceFactor;
viewport_proj_config proj({{ -0.5f, -0.5f, -0.5f },
{ 0.5f, -0.5f, -0.5f },
{ -0.5f, 0.5f, -0.5f },
{ 0.0f, 0.0f, 0.0f }});
camera.projection() = perspective_projection(proj, znear, zfar, frustumtest_proj);
break;
}
default:
{
break;
}
}
camera.modelview() = viewmatrix;
camera.update_frustum(frustumtest_proj);
}
void opengl33_renderer::setup_matrices()
{
OpenGLMatrices.mode(GL_PROJECTION);
OpenGLMatrices.load_matrix(m_renderpass.pass_camera.projection());
// trim modelview matrix just to rotation, since rendering is done in camera-centric world space
OpenGLMatrices.mode(GL_MODELVIEW);
OpenGLMatrices.load_matrix(glm::mat4{glm::mat3{m_renderpass.pass_camera.modelview()}});
}
void opengl33_renderer::setup_alpha_to_coverage(bool const Enable)
{
// the shaders keep the plain alpha test unless told the coverage of their alpha is used;
// uploaded with the rest of the model block at the next draw
model_ubs.alpha_to_coverage = (Enable ? 1.f : 0.f);
if (Enable == m_alphatocoverageenabled)
return;
if (Enable)
glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE);
else
glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
m_alphatocoverageenabled = Enable;
}
void opengl33_renderer::setup_drawing(bool const Alpha)
{
if (Alpha)
{
glEnable(GL_BLEND);
glDepthMask(GL_FALSE);
m_blendingenabled = true;
}
else
{
glDisable(GL_BLEND);
glDepthMask(GL_TRUE);
m_blendingenabled = false;
}
// turned on again per material, by the ones which need it
setup_alpha_to_coverage(false);
switch (m_renderpass.draw_mode)
{
case rendermode::color:
case rendermode::reflections:
{
glCullFace(GL_BACK);
break;
}
case rendermode::shadows:
{
glCullFace(GL_FRONT);
break;
}
case rendermode::pickcontrols:
case rendermode::pickscenery:
{
glCullFace(GL_BACK);
break;
}
default:
{
break;
}
}
}
void opengl33_renderer::setup_shadow_unbind_map()
{
opengl_texture::unbind( gl::SHADOW_TEX );
}
// binds shadow map and updates shadow map uniform data
void opengl33_renderer::setup_shadow_bind_map()
{
if( false == Global.gfx_shadowmap_enabled ) { return; }
m_shadow_tex->bind(gl::SHADOW_TEX);
glm::mat4 coordmove;
if (GLAD_GL_ARB_clip_control || GLAD_GL_EXT_clip_control)
// transform 1..-1 NDC xy coordinates to 1..0
coordmove = glm::mat4( //
0.5, 0.0, 0.0, 0.0, //
0.0, 0.5, 0.0, 0.0, //
0.0, 0.0, 1.0, 0.0, //
0.5, 0.5, 0.0, 1.0 //
);
else
// without clip_control we also need to transform z
coordmove = glm::mat4( //
0.5, 0.0, 0.0, 0.0, //
0.0, 0.5, 0.0, 0.0, //
0.0, 0.0, 0.5, 0.0, //
0.5, 0.5, 0.5, 1.0 //
);
for( auto idx = 0; idx < m_shadowpass.size(); ++idx ) {
glm::mat4 depthproj = m_shadowpass[ idx ].pass_camera.projection();
// NOTE: we strip transformations from camera projections to remove jitter that occurs
// with large (and unneded as we only need the offset) transformations back and forth
auto const depthcam{ glm::mat3{ m_shadowpass[ idx ].pass_camera.modelview()} };
auto const worldcam{ glm::mat3{ m_renderpass.pass_camera.modelview()} };
scene_ubs.lightview[ idx ] =
coordmove
* depthproj
* glm::translate(
glm::mat4{ depthcam },
glm::vec3{ m_renderpass.pass_camera.position() - m_shadowpass[ idx ].pass_camera.position() } )
* glm::mat4{ glm::inverse( worldcam ) };
}
scene_ubo->update(scene_ubs);
}
void opengl33_renderer::setup_shadow_color( glm::vec4 const &Shadowcolor ) {
model_ubs.shadow_tone = glm::pow( Shadowcolor.x, 2.2f );
}
void opengl33_renderer::setup_env_map(gl::cubemap *tex)
{
if (tex)
{
tex->bind(GL_TEXTURE0 + gl::ENV_TEX);
glActiveTexture(GL_TEXTURE0);
}
else
{
glActiveTexture(GL_TEXTURE0 + gl::ENV_TEX);
glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
glActiveTexture(GL_TEXTURE0);
}
opengl_texture::reset_unit_cache();
}
void opengl33_renderer::setup_environment_light(TEnvironmentType const Environment)
{
switch (Environment)
{
case e_flat:
{
setup_sunlight_intensity();
// m_environment = Environment;
break;
}
case e_canyon:
{
setup_sunlight_intensity(0.4f);
// m_environment = Environment;
break;
}
case e_tunnel:
{
setup_sunlight_intensity(0.2f);
// m_environment = Environment;
break;
}
default:
{
break;
}
}
}
void opengl33_renderer::setup_sunlight_intensity( float const Factor ) {
m_sunlight.apply_intensity( Factor );
light_ubs.lights[ 0 ].intensity = m_sunlight.factor * (1.0f - Global.Overcast * 0.33f);
light_ubs.ambient = m_sunlight.ambient * m_sunlight.factor;
light_ubo->update( light_ubs );
}
bool opengl33_renderer::Render(world_environment *Environment)
{
m_shadowcolor = colors::white; // prevent shadow from affecting sky
setup_shadow_color( m_shadowcolor );
if (Global.bWireFrame)
{
// bez nieba w trybie rysowania linii
return false;
}
Bind_Material(null_handle);
::glPushMatrix();
// skydome
// drawn with 500m radius to blend in if the fog range is low
glPushMatrix();
{
glScalef( 500.0f, 500.0f, 500.0f );
model_ubs.set_modelview( OpenGLMatrices.data( GL_MODELVIEW ) );
model_ubo->update( model_ubs );
m_skydomerenderer.update();
m_skydomerenderer.render();
// skydome uses a custom vbo which could potentially confuse the main geometry system. hardly elegant but, eh
gfx::opengl33_vaogeometrybank::reset();
}
glPopMatrix();
::glBlendFunc( GL_SRC_ALPHA, GL_ONE );
// stars
if (Environment->m_stars.m_stars != nullptr && Global.fFogEnd > 500.f)
{
// setup
::glPushMatrix();
::glRotatef(Environment->m_stars.m_latitude, 1.f, 0.f, 0.f); // ustawienie osi OY na północ
::glRotatef(-std::fmod((float)Global.fTimeAngleDeg, 360.f), 0.f, 1.f, 0.f); // obrót dobowy osi OX
// render
Render(Environment->m_stars.m_stars, nullptr, 1.0);
// post-render cleanup
::glPopMatrix();
}
// celestial bodies
m_celestial_shader->bind();
m_empty_vao->bind();
auto const &modelview = OpenGLMatrices.data(GL_MODELVIEW);
auto const fogfactor{std::clamp(Global.fFogEnd / 2000.f, 0.f, 1.f)}; // stronger fog reduces opacity of the celestial bodies
float const duskfactor = 1.0f - std::clamp(std::abs(Environment->m_sun.getAngle()), 0.0f, 12.0f) / 12.0f;
glm::vec3 suncolor = glm::mix(glm::vec3(1.0f, 242.0f / 255.0f, 231.0f / 255.0f), glm::vec3(235.0f / 255.0f, 140.0f / 255.0f, 36.0f / 255.0f), duskfactor);
// sun
{
Bind_Texture(0, m_suntexture);
glm::vec4 color(suncolor.x, suncolor.y, suncolor.z, std::clamp(1.5f - Global.Overcast, 0.f, 1.f) * fogfactor);
auto const sunvector = Environment->m_sun.getDirection();
float const size = std::lerp( // TODO: expose distance/scale factor from the moon object
0.0325f,
0.0275f,
std::clamp( Environment->m_sun.getAngle(), 0.f, 90.f ) / 90.f );
model_ubs.param[0] = color;
model_ubs.param[1] = glm::vec4(glm::vec3(modelview * glm::vec4(sunvector, 1.0f)), size);
model_ubs.param[2] = glm::vec4(0.0f, 1.0f, 1.0f, 0.0f);
model_ubo->update(model_ubs);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
}
// moon
{
Bind_Texture(0, m_moontexture);
glm::vec3 mooncolor(1.0f, 0.9490196f, 0.9058824f);
glm::vec4 color(mooncolor.r, mooncolor.g, mooncolor.b,
// fade the moon if it's near the sun in the sky, especially during the day
std::max<float>(0.f, 1.0 - 0.5 * Global.fLuminance - 0.65 * std::max(0.f, glm::dot(Environment->m_sun.getDirection(), Environment->m_moon.getDirection()))) * fogfactor);
auto const moonvector = Environment->m_moon.getDirection();
// choose the moon appearance variant, based on current moon phase
// NOTE: implementation specific, 8 variants are laid out in 3x3 arrangement
// from new moon onwards, top left to right bottom (last spot is left for future use, if any)
auto const moonphase = Environment->m_moon.getPhase();
float moonu, moonv;
if (moonphase < 1.84566f)
{
moonv = 1.0f - 0.0f;
moonu = 0.0f;
}
else if (moonphase < 5.53699f)
{
moonv = 1.0f - 0.0f;
moonu = 0.333f;
}
else if (moonphase < 9.22831f)
{
moonv = 1.0f - 0.0f;
moonu = 0.667f;
}
else if (moonphase < 12.91963f)
{
moonv = 1.0f - 0.333f;
moonu = 0.0f;
}
else if (moonphase < 16.61096f)
{
moonv = 1.0f - 0.333f;
moonu = 0.333f;
}
else if (moonphase < 20.30228f)
{
moonv = 1.0f - 0.333f;
moonu = 0.667f;
}
else if (moonphase < 23.99361f)
{
moonv = 1.0f - 0.667f;
moonu = 0.0f;
}
else if (moonphase < 27.68493f)
{
moonv = 1.0f - 0.667f;
moonu = 0.333f;
}
else if (moonphase == 50) //9th slot used for easter egg
{
moonv = 1.0f - 0.667f;
moonu = 0.66f;
}
else
{
moonv = 1.0f - 0.0f;
moonu = 0.0f;
}
float const size = std::lerp( // TODO: expose distance/scale factor from the moon object
0.0160f,
0.0135f,
std::clamp( Environment->m_moon.getAngle(), 0.f, 90.f ) / 90.f );
model_ubs.param[0] = color;
model_ubs.param[1] = glm::vec4(glm::vec3(modelview * glm::vec4(moonvector, 1.0f)), size);
model_ubs.param[2] = glm::vec4(moonu, moonv, 0.333f, 0.0f);
model_ubo->update(model_ubs);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
}
::glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
// clouds
if (Environment->m_clouds.mdCloud)
{
// setup
auto const color {
glm::clamp(
( glm::vec3 { Global.DayLight.ambient }
+ 0.35f * glm::vec3{ Global.DayLight.diffuse } ) * simulation::Environment.light_intensity()
* 0.5f,
glm::vec3{ 0.f }, glm::vec3{ 1.f } ) };
// write cloud color into material
TSubModel *mdl = Environment->m_clouds.mdCloud->Root;
if (mdl->m_material != null_handle)
m_materials.material(mdl->m_material).params[0] = glm::vec4(color * 2.5f, 1.0f);
// render
Render(Environment->m_clouds.mdCloud, nullptr, 100.0);
Render_Alpha(Environment->m_clouds.mdCloud, nullptr, 100.0);
// post-render cleanup
}
gl::program::unbind();
gl::vao::unbind();
::glPopMatrix();
m_sunlight.apply_angle();
m_sunlight.apply_intensity();
// calculate shadow tone, based on positions of celestial bodies
m_shadowcolor = glm::mix(glm::vec4{colors::shadow}, glm::vec4{colors::white}, std::clamp(-Environment->m_sun.getAngle(), 0.f, 6.f) / 6.f);
if ((Environment->m_sun.getAngle() < -18.f) && (Environment->m_moon.getAngle() > 0.f))
{
// turn on moon shadows after nautical twilight, if the moon is actually up
m_shadowcolor = colors::shadow;
}
// soften shadows depending on sky overcast factor
m_shadowcolor = glm::min(colors::white, m_shadowcolor + ((colors::white - colors::shadow) * Global.Overcast));
setup_shadow_color( m_shadowcolor);
return true;
}
// geometry methods
// creates a new geometry bank. returns: handle to the bank or NULL
gfx::geometrybank_handle opengl33_renderer::Create_Bank()
{
return m_geometry.register_bank(std::make_unique<gfx::opengl33_vaogeometrybank>());
}
// creates a new indexed geometry chunk of specified type from supplied data, in specified bank. returns: handle to the chunk or NULL
gfx::geometry_handle opengl33_renderer::Insert(gfx::index_array &Indices, gfx::vertex_array &Vertices, gfx::userdata_array &Userdata, gfx::geometrybank_handle const &Geometry, int const Type)
{
// NOTE: we expect indexed geometry to come with calculated tangents
return m_geometry.create_chunk( Indices, Vertices, Userdata, Geometry, Type );
}
// creates a new geometry chunk of specified type from supplied data, in specified bank. returns: handle to the chunk or NULL
gfx::geometry_handle opengl33_renderer::Insert(gfx::vertex_array &Vertices, gfx::userdata_array &Userdata, gfx::geometrybank_handle const &Geometry, int const Type)
{
gfx::calculate_tangents(Vertices, gfx::index_array(), Type);
return m_geometry.create_chunk(Vertices, Userdata, Geometry, Type);
}
// replaces data of specified chunk with the supplied vertex data, starting from specified offset
bool opengl33_renderer::Replace(gfx::vertex_array &Vertices, gfx::userdata_array &Userdata, gfx::geometry_handle const &Geometry, int const Type, const std::size_t Offset)
{
gfx::calculate_tangents(Vertices, gfx::index_array(), Type);
return m_geometry.replace(Vertices, Userdata, Geometry, Offset);
}
// adds supplied vertex data at the end of specified chunk
bool opengl33_renderer::Append(gfx::vertex_array &Vertices, gfx::userdata_array &Userdata, gfx::geometry_handle const &Geometry, int const Type)
{
gfx::calculate_tangents(Vertices, gfx::index_array(), Type);
return m_geometry.append(Vertices, Userdata, Geometry);
}
void opengl33_renderer::Erase(gfx::geometry_handle const &Geometry)
{
m_geometry.erase(Geometry);
}
// provides direct access to index data of specfied chunk
gfx::index_array const & opengl33_renderer::Indices(gfx::geometry_handle const &Geometry) const
{
return m_geometry.indices(Geometry);
}
// provides direct access to vertex data of specfied chunk
gfx::vertex_array const &opengl33_renderer::Vertices(gfx::geometry_handle const &Geometry) const
{
return m_geometry.vertices(Geometry);
}
gfx::userdata_array const &opengl33_renderer::UserData(const gfx::geometry_handle &Geometry) const
{
return m_geometry.userdata(Geometry);
}
int opengl33_renderer::Primitive(gfx::geometry_handle const &Geometry) const
{
auto const primitive{m_geometry.primitive(Geometry)};
return primitive == gfx::geometry_bank::no_primitive ? -1 : static_cast<int>(primitive);
}
// material methods
material_handle opengl33_renderer::Fetch_Material(std::string const &Filename, bool const Loadnow)
{
return m_materials.create(Filename, Loadnow);
}
material_handle opengl33_renderer::Matte_Material(material_handle const Material)
{
return m_materials.create_matte(Material);
}
material_handle opengl33_renderer::Tinted_Material(material_handle const Material, glm::vec3 const &Colour)
{
return m_materials.create_tinted(Material, Colour);
}
std::shared_ptr<gl::program> opengl33_renderer::Fetch_Shader(const std::string &name)
{
auto it = m_shaders.find(name);
if (it == m_shaders.end())
{
gl::shader fragment("mat_" + name + ".frag");
gl::program *program = new gl::program({fragment, *m_vertex_shader.get()});
m_shaders.insert({name, std::shared_ptr<gl::program>(program)});
}
return m_shaders[name];
}
void opengl33_renderer::Bind_Material( material_handle const Material, TSubModel const *sm, lighting_data const *lighting )
{
if (Material != null_handle)
{
auto const &material { m_materials.material( Material ) };
if( false == material.is_good ) {
// use failure indicator instead
if( Material != m_invalid_material ) {
Bind_Material( m_invalid_material );
}
return;
}
memcpy(&model_ubs.param[0], &material.params[0], sizeof(model_ubs.param));
for( auto const &entry : material.params_state )
{
glm::vec4 src(1.0f);
// submodel-based parameters
if (sm)
{
switch( entry.defaultparam ) {
case gl::shader::defaultparam_e::ambient: {
src = sm->f4Ambient;
break;
}
case gl::shader::defaultparam_e::diffuse: {
src = sm->f4Diffuse;
break;
}
case gl::shader::defaultparam_e::specular: {
src = sm->f4Specular;
break;
}
default: {
break;
}
}
}
if( lighting )
{
switch( entry.defaultparam ) {
case gl::shader::defaultparam_e::ambient: {
src = lighting->ambient;
break;
}
case gl::shader::defaultparam_e::diffuse: {
src = lighting->diffuse;
break;
}
case gl::shader::defaultparam_e::specular: {
src = lighting->specular;
break;
}
default: {
break;
}
}
}
// material-based parameters
switch( entry.defaultparam ) {
case gl::shader::defaultparam_e::glossiness: {
src = glm::vec4 { material.glossiness };
}
default: {
break;
}
}
if( entry.size == 1 ) {
// HACK: convert color to luminosity, if it's passed as single value
src = glm::vec4 { colors::RGBtoHSV( glm::vec3 { src } ).z };
}
for (size_t j = 0; j < entry.size; j++)
model_ubs.param[entry.location][entry.offset + j] = src[j];
}
/*
if (m_blendingenabled)
{
model_ubs.opacity = -1.0f;
}
else
{
if (!std::isnan(material.opacity))
model_ubs.opacity = material.opacity;
else
model_ubs.opacity = 0.5f;
}
*/
if( material.opacity ) {
model_ubs.opacity = (
m_blendingenabled ?
-material.opacity.value() :
material.opacity.value() );
}
else {
model_ubs.opacity = (
m_blendingenabled ?
0.0f :
0.5f );
}
if (sm)
model_ubs.alpha_mult = sm->fVisible;
else
model_ubs.alpha_mult = 1.0f;
// the alpha test drops or keeps whole pixels, so multisampling alone leaves its edges (e.g. sides
// of the trackbed textures) jagged. the alpha tested materials of the opaque colour pass get them
// antialiased with alpha to coverage instead; their shaders give the coverage as the alpha.
// the model previews draw in colour mode too, but to a single-sampled framebuffer
setup_alpha_to_coverage(
Global.iMultisampling > 0
&& false == m_blendingenabled
&& m_renderpass.draw_mode == rendermode::color
&& false == m_previewing
&& model_ubs.opacity > 0.f
&& material.shader->alpha_to_coverage );
// materials which declare texture variants provide a different texture set per model instance,
// picked from the seed of the rendered instance and the variant group of the submodel
auto const &materialtextures{
material.texture_variants.empty() ?
material.textures :
material.GetTextures(TSubModel::VariantId(sm))};
if (GLAD_GL_ARB_multi_bind)
{
// the cache may have been marked stale by the python upload thread
opengl_texture::sync_unit_cache();
GLuint lastdiff = 0;
size_t i;
for (i = 0; i < gl::MAX_TEXTURES; i++)
if (materialtextures[i] != null_handle)
{
opengl_texture &tex = m_textures.mark_as_used(materialtextures[i]);
tex.create();
if (opengl_texture::units[i] != tex.id)
{
opengl_texture::units[i] = tex.id;
lastdiff = i + 1;
}
}
else
break;
if (lastdiff)
glBindTextures(0, lastdiff, &opengl_texture::units[0]);
}
else
{
size_t unit = 0;
for (auto &tex : materialtextures)
{
if (tex == null_handle)
break;
m_textures.bind(unit, tex);
unit++;
}
}
material.shader->bind();
}
else if (Material != m_invalid_material)
Bind_Material(m_invalid_material);
}
void opengl33_renderer::Bind_Material_Shadow(material_handle const Material)
{
if (Material != null_handle)
{
auto &material = m_materials.material(Material);
if (material.textures[0] != null_handle)
{
m_textures.bind(0, material.textures[0]);
m_alpha_shadow_shader->bind();
}
else {
m_shadow_shader->bind();
}
}
else {
m_shadow_shader->bind();
}
}
IMaterial const *opengl33_renderer::Material(material_handle const Material) const
{
return &m_materials.material(Material);
}
material_handle opengl33_renderer::Terrain_Material(material_handle const Reuse, std::vector<gfx::terrain_layer> const &Layers, int const Samples, std::uint8_t const *Weights, glm::vec3 const &Placement)
{
auto const material{m_terrainmaterials.make(Reuse, Layers, Samples, Weights, Placement)};
if (material != null_handle)
return material;
// the terrain shader can't be used, the chunk makes do with a plain material
return gfx_renderer::Terrain_Material(Reuse, Layers, Samples, Weights, Placement);
}
void opengl33_renderer::Terrain_Release(material_handle const Material)
{
m_terrainmaterials.release(Material);
}
opengl_material &opengl33_renderer::Material(material_handle const Material)
{
return m_materials.material(Material);
}
opengl_material const & opengl33_renderer::Material( TSubModel const * Submodel ) const {
return m_materials.material( submodel_material( Submodel ) );
}
texture_handle opengl33_renderer::Fetch_Texture(std::string const &Filename, bool const Loadnow, GLint format_hint)
{
return m_textures.create(Filename, Loadnow, format_hint);
}
void opengl33_renderer::Bind_Texture( texture_handle const Texture )
{
return Bind_Texture( 0, Texture );
}
void opengl33_renderer::Bind_Texture(std::size_t const Unit, texture_handle const Texture)
{
m_textures.bind(Unit, Texture);
}
ITexture &opengl33_renderer::Texture(texture_handle const Texture)
{
return m_textures.texture(Texture);
}
ITexture const &opengl33_renderer::Texture(texture_handle const Texture) const
{
return m_textures.texture(Texture);
}
void opengl33_renderer::Unload_Texture(texture_handle const Texture)
{
m_textures.unload(Texture);
}
void opengl33_renderer::Update_AnimModel(TAnimModel *model)
{
model->RaAnimate(m_framestamp);
}
void opengl33_renderer::Render(scene::basic_region *Region)
{
m_sectionqueue.clear();
m_cellqueue.clear();
// discard last pass's accumulated instance buckets before this pass starts.
// the vectors themselves are kept, so their allocations get reused by the following passes
for( auto &bucket : m_frame_instance_buckets ) {
bucket.second.clear();
}
// build a list of region sections to render
glm::vec3 const cameraposition{m_renderpass.pass_camera.position()};
auto const camerax = static_cast<int>(std::floor(cameraposition.x / scene::EU07_SECTIONSIZE + scene::EU07_REGIONSIDESECTIONCOUNT / 2));
auto const cameraz = static_cast<int>(std::floor(cameraposition.z / scene::EU07_SECTIONSIZE + scene::EU07_REGIONSIDESECTIONCOUNT / 2));
float section_range = m_renderpass.draw_range * Global.fDistanceFactor;
section_range = editor_track_view_range(section_range, EditorModeFlag && (m_renderpass.draw_mode == rendermode::color || m_renderpass.draw_mode == rendermode::pickscenery));
int const segmentcount = 2 * static_cast<int>(std::ceil(section_range / scene::EU07_SECTIONSIZE));
int const originx = camerax - segmentcount / 2;
int const originz = cameraz - segmentcount / 2;
for (int row = originz; row <= originz + segmentcount; ++row)
{
if (row < 0)
{
continue;
}
if (row >= scene::EU07_REGIONSIDESECTIONCOUNT)
{
break;
}
for (int column = originx; column <= originx + segmentcount; ++column)
{
if (column < 0)
{
continue;
}
if (column >= scene::EU07_REGIONSIDESECTIONCOUNT)
{
break;
}
auto *section{Region->m_sections[row * scene::EU07_REGIONSIDESECTIONCOUNT + column]};
if ((section != nullptr) && (m_renderpass.pass_camera.visible(section->m_area)))
{
m_sectionqueue.emplace_back(section);
}
}
}
switch (m_renderpass.draw_mode)
{
case rendermode::color:
{
Render(std::begin(m_sectionqueue), std::end(m_sectionqueue));
// draw queue is filled while rendering sections
if (EditorModeFlag && m_current_viewport->main)
{
// when editor mode is active calculate world position of the cursor
// at this stage the z-buffer is filled with only ground geometry
Update_Mouse_Position();
}
// draw opaque cells front-to-back: with the depth test enabled this
// lets the GPU reject hidden fragments early, before the (expensive)
// lit fragment shader runs on them. Order is irrelevant to the final
// image for opaque geometry, so this is purely a fill-rate win.
std::sort( std::begin( m_cellqueue ), std::end( m_cellqueue ),
[]( distancecell_pair const &Left, distancecell_pair const &Right ) { return Left.first < Right.first; } );
Render(std::begin(m_cellqueue), std::end(m_cellqueue));
break;
}
case rendermode::shadows:
case rendermode::pickscenery:
{
// these render modes don't bother with lights
Render(std::begin(m_sectionqueue), std::end(m_sectionqueue));
// they can also skip queue sorting, as they only deal with opaque geometry
// NOTE: there's benefit from rendering front-to-back, but is it significant enough? TODO: investigate
Render(std::begin(m_cellqueue), std::end(m_cellqueue));
break;
}
case rendermode::reflections:
{
Render(std::begin(m_sectionqueue), std::end(m_sectionqueue));
if( Global.reflectiontune.fidelity >= 1 ) {
Render(std::begin(m_cellqueue), std::end(m_cellqueue));
}
break;
}
case rendermode::pickcontrols:
default:
{
// no need to render anything ourside of the cab in control picking mode
break;
}
}
}
void opengl33_renderer::Render(section_sequence::iterator First, section_sequence::iterator Last)
{
switch (m_renderpass.draw_mode)
{
case rendermode::color:
case rendermode::reflections:
case rendermode::shadows:
break;
case rendermode::pickscenery:
{
// non-interactive scenery elements get neutral colour
model_ubs.param[0] = colors::none;
break;
}
default:
break;
}
// the ground of the sections far off, the terrain of the editor among it, isn't drawn with the tracks reaching there
auto const scenery_limit{static_cast<double>(Global.BaseDrawRange) * Global.fDistanceFactor + 250.0};
bool const far_paths{EditorModeFlag && Global.editor_tracks && (m_renderpass.draw_mode == rendermode::color || m_renderpass.draw_mode == rendermode::pickscenery)};
glm::dvec3 const camera{m_renderpass.pass_camera.position()};
while (First != Last)
{
auto *section = *First;
section->create_geometry();
// render shapes held by the section
switch (m_renderpass.draw_mode)
{
case rendermode::color:
case rendermode::reflections:
case rendermode::shadows:
case rendermode::pickscenery:
{
if (false == section->m_shapes.empty() && false == editor_far_tracks_only(far_paths, section->m_area, camera, scenery_limit))
{
// since all shapes of the section share center point we can optimize out a few calls here
::glPushMatrix();
auto const originoffset{section->m_area.center - m_renderpass.pass_camera.position()};
::glTranslated(originoffset.x, originoffset.y, originoffset.z);
// render
for (auto const &shape : section->m_shapes)
{
Render(shape, true);
}
// post-render cleanup
::glPopMatrix();
}
break;
}
case rendermode::pickcontrols:
default:
{
break;
}
}
// add the section's cells to the cell queue
switch (m_renderpass.draw_mode)
{
case rendermode::color:
case rendermode::shadows:
case rendermode::pickscenery:
{
// TBD, TODO: refactor into a method to reuse below?
for (auto &cell : section->m_cells)
{
if ((true == cell.m_active) && (m_renderpass.pass_camera.visible(cell.m_area)))
{
// a cell with nothing but instances too far to be drawn is left out of the color pass altogether
if( ( true == Prepare_Instances( cell ) )
&& ( m_renderpass.draw_mode == rendermode::color )
&& ( true == Cell_Out_Of_Range( cell ) ) ) {
continue;
}
// store visible cells with content as well as their current distance, for sorting later
m_cellqueue.emplace_back(glm::length2(m_renderpass.pass_camera.position() - cell.m_area.center), &cell);
}
}
break;
}
case rendermode::reflections:
{
// we can skip filling the cell queue if reflections pass isn't going to use it
if( Global.reflectiontune.fidelity == 0 ) { break; }
for (auto &cell : section->m_cells)
{
if ((true == cell.m_active) && (m_renderpass.pass_camera.visible(cell.m_area)))
{
Prepare_Instances( cell );
// store visible cells with content as well as their current distance, for sorting later
m_cellqueue.emplace_back(glm::length2(m_renderpass.pass_camera.position() - cell.m_area.center), &cell);
}
}
break;
}
case rendermode::pickcontrols:
default:
{
break;
}
}
// proceed to next section
++First;
}
switch (m_renderpass.draw_mode)
{
case rendermode::shadows:
{
break;
}
default:
{
break;
}
}
}
void opengl33_renderer::Render(cell_sequence::iterator First, cell_sequence::iterator Last)
{
// cache initial iterator for the second sweep
auto first{First};
auto const scenery_limit{static_cast<double>(Global.BaseDrawRange) * Global.fDistanceFactor + 250.0};
bool const far_paths{EditorModeFlag && Global.editor_tracks && (m_renderpass.draw_mode == rendermode::color || m_renderpass.draw_mode == rendermode::pickscenery)};
glm::dvec3 const camera{m_renderpass.pass_camera.position()};
// first pass draws elements which we know are located in section banks, to reduce vbo switching
while (First != Last)
{
auto *cell = First->second;
// przeliczenia animacji torów w sektorze
cell->RaAnimate(m_framestamp);
bool const tracks_only{editor_far_tracks_only(far_paths, cell->m_area, camera, scenery_limit)};
switch (m_renderpass.draw_mode)
{
case rendermode::color:
{
// since all shapes of the section share center point we can optimize out a few calls here
::glPushMatrix();
auto const originoffset{cell->m_area.center - m_renderpass.pass_camera.position()};
::glTranslated(originoffset.x, originoffset.y, originoffset.z);
// render
// opaque non-instanced shapes
if (false == tracks_only)
{
for (auto const &shape : cell->m_shapesopaque)
{
Render(shape, false);
}
}
// tracks
// TODO: update after path node refactoring
Render(std::begin(cell->m_paths), std::end(cell->m_paths));
// post-render cleanup
::glPopMatrix();
break;
}
case rendermode::reflections:
{
// since all shapes of the section share center point we can optimize out a few calls here
::glPushMatrix();
auto const originoffset{cell->m_area.center - m_renderpass.pass_camera.position()};
::glTranslated(originoffset.x, originoffset.y, originoffset.z);
// render
// opaque non-instanced shapes
for (auto const &shape : cell->m_shapesopaque)
Render(shape, false);
// post-render cleanup
::glPopMatrix();
break;
}
case rendermode::shadows:
{
// since all shapes of the section share center point we can optimize out a few calls here
::glPushMatrix();
auto const originoffset{cell->m_area.center - m_renderpass.pass_camera.position()};
::glTranslated(originoffset.x, originoffset.y, originoffset.z);
// render
// opaque non-instanced shapes
for (auto const &shape : cell->m_shapesopaque)
Render(shape, false);
// tracks
Render(std::begin(cell->m_paths), std::end(cell->m_paths));
// post-render cleanup
::glPopMatrix();
break;
}
case rendermode::pickscenery:
{
// same procedure like with regular render, but editor-enabled nodes receive custom colour used for picking
// since all shapes of the section share center point we can optimize out a few calls here
::glPushMatrix();
auto const originoffset{cell->m_area.center - m_renderpass.pass_camera.position()};
::glTranslated(originoffset.x, originoffset.y, originoffset.z);
// render
// opaque non-instanced shapes
// non-interactive scenery elements get neutral colour
if (false == tracks_only)
{
model_ubs.param[0] = colors::none;
for (auto const &shape : cell->m_shapesopaque)
Render(shape, false);
}
// tracks
for (auto *path : cell->m_paths)
{
model_ubs.param[0] = glm::vec4(pick_color(m_picksceneryitems.size() + 1), 1.0f);
Render(path);
}
// post-render cleanup
::glPopMatrix();
break;
}
case rendermode::pickcontrols:
default:
{
break;
}
}
++First;
}
// second pass draws elements with their own vbos
while (first != Last)
{
auto const *cell = first->second;
switch (m_renderpass.draw_mode)
{
case rendermode::color:
case rendermode::shadows:
{
if (editor_far_tracks_only(far_paths, cell->m_area, camera, scenery_limit))
break;
// TBD, TODO: refactor in to a method to reuse in branch below?
// opaque parts of instanced models -- accumulate this cell's buckets
// into the frame-level map; the actual Render_Instanced() calls are
// issued once per unique model after the cell loop (see flush below).
//
// Cell-level far-distance pre-cull: when the whole cell lies beyond
// the instance draw distance, every instance in it would fail the
// per-instance drawdistancethreshold test inside Render_Instanced(),
// so there is no point merging its buckets into the frame map. The
// test reproduces Render_Instanced()'s distance maths exactly -- same
// ZoomFactor / fDistanceFactor scaling, same +250 margin -- applied to
// the nearest point of the cell's bounding sphere. basic_cell::enclose_area
// guarantees m_area.radius >= |m_area.center - instance.location()| for
// every contained instance, so the nearest-point distance is a true
// lower bound on every instance's distance: the cull can never drop a
// cell that still holds a drawable instance. Shadows measure from the
// real (viewport) camera, matching Render_Instanced()'s shadow branch;
// every other gated mode measures from the pass camera. Non-instanced
// scenery and vehicles below keep their own per-node culling and are
// intentionally left untouched.
{
auto const &distancecamera = (
m_renderpass.draw_mode == rendermode::shadows
? m_renderpass.viewport_camera
: m_renderpass.pass_camera );
auto const cellcenterdistance { glm::length( cell->m_area.center - distancecamera.position() ) };
auto const cellnearestdistance { std::max( 0.0, cellcenterdistance - cell->m_area.radius ) };
auto const cellnearestdistancesquared {
( cellnearestdistance * cellnearestdistance )
/ ( static_cast<double>( Global.ZoomFactor ) * static_cast<double>( Global.ZoomFactor ) )
/ static_cast<double>( Global.fDistanceFactor ) };
if( cellnearestdistancesquared <= sq( static_cast<double>( m_renderpass.draw_range ) + 250.0 ) ) {
Queue_Instances( cell );
}
}
// remaining (non-instanceable) opaque instance nodes go through the per-node path. the list of them kept for
// the cell spares going through every instance of it only to skip the instanceable ones - with many of these
// (vegetation) that took more time than drawing everything else
for (auto *instance : ( Instance_Cache_Valid( *cell ) ? cell->m_instancecache.single : cell->m_instancesopaque ))
{
if( instance->m_instanceable ) { continue; } // already handled via bucket
Render(instance);
}
// opaque parts of vehicles
for (auto *path : cell->m_paths)
{
for (auto *dynamic : path->Dynamics)
{
Render(dynamic);
}
}
break;
}
case rendermode::reflections:
{
// a cell lying whole beyond the range the reflections draw model instances at is left out, as each
// of its instances would fail the range test done for it in Render_Instanced() and Render( TAnimModel * ).
// like the cull of the regular passes above, the test goes by the nearest point of the bounding sphere
// of the cell, which holds the locations of all its instances
auto const cellnearestdistance { std::max( 0.0, glm::length( cell->m_area.center - m_renderpass.pass_camera.position() ) - cell->m_area.radius ) };
if( ( Global.reflectiontune.fidelity >= 1 )
&& ( cellnearestdistance <= Global.reflectiontune.range_instances ) ) {
// opaque parts of instanced models -- accumulate into the
// frame-level map; flushed once per unique model after the loop.
Queue_Instances( cell );
for( auto *instance : cell->m_instancesopaque ) {
if( instance->m_instanceable ) { continue; }
Render( instance );
}
}
if( Global.reflectiontune.fidelity >= 2 ) {
// opaque parts of vehicles
for( auto *path : cell->m_paths ) {
for( auto *dynamic : path->Dynamics ) {
Render( dynamic );
}
}
}
break;
}
case rendermode::pickscenery:
{
if (editor_far_tracks_only(far_paths, cell->m_area, camera, scenery_limit))
break;
// opaque parts of instanced models
// same procedure like with regular render, but each node receives custom colour used for picking.
// picking always uses the per-instance path because each instance needs a unique pick colour;
// batching would assign the same colour to every instance in the bucket.
for (auto *instance : cell->m_instancesopaque)
{
model_ubs.param[0] = glm::vec4(pick_color(m_picksceneryitems.size() + 1), 1.0f);
Render(instance);
}
// vehicles aren't included in scenery picking for the time being
break;
}
case rendermode::pickcontrols:
default:
{
break;
}
}
++first;
}
// flush accumulated instance buckets: issue one Render_Instanced() per unique
// (TModel3d*, skins) key across every cell visited in this pass, instead of
// one call per cell. All per-instance frustum/distance/pixel-area culling
// still happens inside Render_Instanced(), so correctness is unchanged -- only
// the number of calls and glBufferSubData round-trips drops sharply.
// (For pickscenery/pickcontrols modes the map stays empty, so this is a no-op.)
for( auto &bucket : m_frame_instance_buckets ) {
if( bucket.second.empty() ) { continue; }
Render_Instanced( bucket.first.pModel, bucket.second );
bucket.second.clear();
}
}
void opengl33_renderer::Draw_Geometry(std::vector<gfx::geometrybank_handle>::iterator begin, std::vector<gfx::geometrybank_handle>::iterator end)
{
if (begin == end)
{
return;
}
// the handles are handed over as a whole, so chunks kept in the same bank can be drawn with fewer calls
auto const *first{&(*begin)};
m_geometry.draw_batch(first, first + std::distance(begin, end));
}
void opengl33_renderer::Draw_Geometry(const gfx::geometrybank_handle &handle)
{
m_geometry.draw(handle);
}
void opengl33_renderer::draw(const gfx::geometry_handle &handle)
{
model_ubs.set_modelview(OpenGLMatrices.data(GL_MODELVIEW));
model_ubo->update(model_ubs);
if( m_current_instance_count > 0 ) {
// inside Render_Instanced(): one GL instanced draw replaces what would
// otherwise be N regular draws (one per instance) at this submodel
m_geometry.draw_instanced( handle, m_current_instance_count );
}
else {
m_geometry.draw( handle );
}
}
void opengl33_renderer::draw(std::vector<gfx::geometrybank_handle>::iterator it, std::vector<gfx::geometrybank_handle>::iterator end)
{
model_ubs.set_modelview(OpenGLMatrices.data(GL_MODELVIEW));
model_ubo->update(model_ubs);
Draw_Geometry(it, end);
}
void opengl33_renderer::Render(scene::shape_node const &Shape, bool const Ignorerange)
{
auto const &data{Shape.data()};
if (false == Ignorerange)
{
double distancesquared;
switch (m_renderpass.draw_mode)
{
case rendermode::shadows:
{
// 'camera' for the light pass is the light source, but we need to draw what the 'real' camera sees
distancesquared = glm::length2((data.area.center - m_renderpass.viewport_camera.position()) / (double)Global.ZoomFactor) / Global.fDistanceFactor;
break;
}
case rendermode::reflections:
{
// reflection mode draws simplified version of the shapes, by artificially increasing view range
distancesquared =
// TBD, TODO: bind offset value with setting variable?
sq(EU07_REFLECTIONFIDELITYOFFSET)
+ glm::length2( ( data.area.center - m_renderpass.pass_camera.position() ) );
/*
// TBD: take into account distance multipliers?
/ Global.fDistanceFactor;
*/
break;
}
default:
{
distancesquared = glm::length2((data.area.center - m_renderpass.pass_camera.position()) / (double)Global.ZoomFactor) / Global.fDistanceFactor;
break;
}
}
if ((distancesquared < data.rangesquared_min) || (distancesquared >= data.rangesquared_max))
{
return;
}
}
// setup
switch (m_renderpass.draw_mode)
{
case rendermode::color:
case rendermode::reflections:
Bind_Material(data.material, nullptr, &Shape.data().lighting );
break;
case rendermode::shadows:
// skip if the shadow caster rank is too low for currently set threshold
if( Material( data.material ).shadow_rank > Global.gfx_shadow_rank_cutoff )
return;
Bind_Material_Shadow(data.material);
break;
case rendermode::pickscenery:
case rendermode::pickcontrols:
m_pick_shader->bind();
break;
default:
break;
}
// render
// a decal comes nearer the camera: the depth is reversed (GL_GEQUAL), so a positive offset. not in the shadows, it casts none
auto const decal{data.decal && m_renderpass.draw_mode != rendermode::shadows};
if (decal)
{
::glEnable(GL_POLYGON_OFFSET_FILL);
::glPolygonOffset(2.f, 8.f);
}
draw(data.geometry);
if (decal)
::glDisable(GL_POLYGON_OFFSET_FILL);
// debug data
++m_renderpass.draw_stats.shapes;
++m_renderpass.draw_stats.drawcalls;
}
void opengl33_renderer::Render(TAnimModel *Instance)
{
if (false == Instance->m_visible) { return; }
if( false == m_renderpass.pass_camera.visible( Instance->m_area ) ) { return; }
double distancesquared;
switch (m_renderpass.draw_mode)
{
case rendermode::shadows:
{
// 'camera' for the light pass is the light source, but we need to draw what the 'real' camera sees
distancesquared = glm::length2((Instance->location() - m_renderpass.viewport_camera.position()) / (double)Global.ZoomFactor) / Global.fDistanceFactor;
break;
}
case rendermode::reflections:
{
// reflection mode draws simplified version of the shapes, by artificially increasing view range
// it also ignores zoom settings and distance multipliers
// TBD: take into account distance multipliers?
distancesquared = glm::length2((Instance->location() - m_renderpass.pass_camera.position())) /* / Global.fDistanceFactor */;
// NOTE: arbitrary draw range limit
if( distancesquared > Global.reflectiontune.range_instances * Global.reflectiontune.range_instances ) {
return;
}
// TBD, TODO: bind offset value with setting variable?
distancesquared += sq(EU07_REFLECTIONFIDELITYOFFSET);
break;
}
default:
{
distancesquared = glm::length2((Instance->location() - m_renderpass.pass_camera.position()) / (double)Global.ZoomFactor) / Global.fDistanceFactor;
break;
}
}
if ((distancesquared < Instance->m_rangesquaredmin) || (distancesquared >= Instance->m_rangesquaredmax))
{
return;
}
// crude way to reject early items too far to affect the output (mostly relevant for shadow passes)
auto const drawdistancethreshold{ m_renderpass.draw_range + 250 };
if( distancesquared > sq(drawdistancethreshold) ) {
return;
}
// second stage visibility cull, reject modelstoo far away to be noticeable
auto const radiussquared { Instance->radius() * Instance->radius() };
if( radiussquared * Global.ZoomFactor / distancesquared < 0.003 * 0.003 ) {
return;
}
switch (m_renderpass.draw_mode)
{
case rendermode::pickscenery:
{
// add the node to the pick list
m_picksceneryitems.emplace_back(Instance);
break;
}
default:
{
break;
}
}
Instance->RaAnimate(m_framestamp); // jednorazowe przeliczenie animacji
Instance->RaPrepare();
if (Instance->pModel)
{
// per-instance uniform scale: applied between the rotation and the
// submodel-local transform chain. Pushing it on the matrix stack here
// means Render(TModel3d, ..., position, angle) doesn't need a new
// signature and the same scale flows naturally into Render_Alpha and
// any other recursive callers.
auto const &scale = Instance->Scale();
bool const scaled = ( scale.x != 1.0f || scale.y != 1.0f || scale.z != 1.0f );
if( scaled ) {
// Per-axis scale applied between rotation and the submodel-local
// chain: build the per-instance transform here so we can inject
// glScalef before the submodel walk.
::glPushMatrix();
auto const Position = Instance->location() - m_renderpass.pass_camera.position();
auto const Angle = Instance->vAngle;
::glTranslated( Position.x, Position.y, Position.z );
if( Angle.y != 0.0 ) ::glRotated( Angle.y, 0.f, 1.f, 0.f );
if( Angle.x != 0.0 ) ::glRotated( Angle.x, 1.f, 0.f, 0.f );
if( Angle.z != 0.0 ) ::glRotated( Angle.z, 0.f, 0.f, 1.f );
::glScalef( scale.x, scale.y, scale.z );
Render( Instance->pModel, Instance->Material(), distancesquared );
::glPopMatrix();
}
else {
// fast path for unscaled (the common case): existing behaviour
Render(Instance->pModel, Instance->Material(), distancesquared, Instance->location() - m_renderpass.pass_camera.position(), Instance->vAngle);
}
// debug data
++m_renderpass.draw_stats.models;
}
}
// adds the bucketed instances of a scene cell to the frame-level buckets, for Render_Instanced() to draw.
// Render_Instanced() culls each instance it's given. the tests it makes are repeated here on the copies of instance
// bounds kept by the buckets, with some slack for the single precision of the copies, and the instances which fail are
// left out: the instances themselves are fetched only when there's a chance for them to be drawn
void opengl33_renderer::Queue_Instances( scene::basic_cell const *Cell )
{
// the editor moves and resizes the instances in place, the copies can't be relied on while it's active
auto const usebounds { false == EditorModeFlag };
auto const reflections { m_renderpass.draw_mode == rendermode::reflections };
// same choices as in Render_Instanced(): shadows measure the distance from the real camera, reflections
// ignore zoom and distance factor, test the plain distance against their own range and add the fidelity offset
auto const &distancecamera { m_renderpass.draw_mode == rendermode::shadows ? m_renderpass.viewport_camera : m_renderpass.pass_camera };
glm::dvec3 const cameraposition { distancecamera.position() };
auto const distancescale { reflections ? 1.0 : 1.0 / ( static_cast<double>( Global.ZoomFactor ) * static_cast<double>( Global.ZoomFactor ) * static_cast<double>( Global.fDistanceFactor ) ) };
auto const distanceoffset { reflections ? sq( static_cast<double>( EU07_REFLECTIONFIDELITYOFFSET ) ) : 0.0 };
auto const slack { 1.001 };
auto const distancelimit { slack * ( reflections ? sq( static_cast<double>( Global.reflectiontune.range_instances ) ) : sq( static_cast<double>( m_renderpass.draw_range ) + 250.0 ) ) };
// up close the rounding of the copies is too large a part of the distance for the slack to cover it
auto const distancetested { sq( 64.0 ) };
// the nearest point of the bounding sphere of the cell, which holds the locations of all its instances. no instance
// of the cell is closer, so where this distance fails the range test below for the largest range in a bucket,
// it fails it for each instance of that bucket, and the bucket can be skipped without going through them
auto const cellnearestdistance { std::max( 0.0, glm::length( Cell->m_area.center - cameraposition ) - Cell->m_area.radius ) };
auto const cellnearestdistancesquared { cellnearestdistance * cellnearestdistance };
for( auto const &bucket : Cell->m_instancebuckets_opaque ) {
auto const &instances { bucket.second.instances };
if( false == usebounds ) {
auto &dest { m_frame_instance_buckets[ bucket.first ] };
dest.insert( dest.end(), instances.begin(), instances.end() );
continue;
}
if( ( bucket.second.boundsversion != m_instanceboundsversion )
|| ( bucket.second.bounds.size() != instances.size() ) ) {
Update_Instance_Bounds( bucket.first.pModel, bucket.second );
}
else if( ( bucket.second.rangeversion == m_instanceboundsversion )
&& ( cellnearestdistancesquared > distancetested )
&& ( cellnearestdistancesquared * distancescale + distanceoffset >= slack * bucket.second.rangesquaredmax ) ) {
continue;
}
auto const &bounds { bucket.second.bounds };
std::vector<TAnimModel *> *dest { nullptr }; // looked up when there's something to put in it
for( std::size_t idx = 0; idx < bounds.size(); ++idx ) {
auto const &instancebounds { bounds[ idx ] };
auto const center { glm::dvec3{ instancebounds.center } };
auto const distancesquared { glm::length2( center - cameraposition ) };
if( distancesquared > distancetested ) {
auto const scaleddistancesquared { distancesquared * distancescale };
if( scaleddistancesquared > distancelimit ) { continue; }
if( scaleddistancesquared + distanceoffset >= slack * instancebounds.rangesquaredmax ) { continue; }
}
if( false == m_renderpass.pass_camera.visible( scene::bounding_area{ center, instancebounds.radius } ) ) { continue; }
if( dest == nullptr ) {
dest = &m_frame_instance_buckets[ bucket.first ];
}
dest->emplace_back( instances[ idx ] );
}
}
}
// brings up to date what the renderer keeps of the instances of the cell: the copies of the bounds of the instances
// and the largest range in each bucket, the largest range in the cell, and the list of its instances drawn one by one.
// rebuilt after the content of the cell changed, or any instance lost its instanceable status (an event added an
// animation container, or changed a skin). returns: true if the cache can be used; it can't in the editor, which
// moves and resizes the instances in place, as with the copies of their bounds
bool opengl33_renderer::Prepare_Instances( scene::basic_cell &Cell )
{
if( EditorModeFlag ) { return false; }
if( Instance_Cache_Valid( Cell ) ) { return true; }
auto &cache { Cell.m_instancecache };
cache.rangesquaredmax = 0.f;
for( auto &[ key, bucket ] : Cell.m_instancebuckets_opaque ) {
if( ( bucket.boundsversion != m_instanceboundsversion )
|| ( bucket.bounds.size() != bucket.instances.size() ) ) {
Update_Instance_Bounds( key.pModel, bucket );
}
auto rangesquaredmax { 0.f };
for( auto const &instancebounds : bucket.bounds ) {
rangesquaredmax = std::max( rangesquaredmax, instancebounds.rangesquaredmax );
}
bucket.rangesquaredmax = rangesquaredmax;
bucket.rangeversion = m_instanceboundsversion;
cache.rangesquaredmax = std::max( cache.rangesquaredmax, rangesquaredmax );
}
cache.single.clear();
for( auto *instance : Cell.m_instancesopaque ) {
if( false == instance->m_instanceable ) {
cache.single.emplace_back( instance );
}
}
cache.instancedonly =
( false == Cell.m_instancebuckets_opaque.empty() )
&& Cell.m_paths.empty()
&& Cell.m_shapesopaque.empty()
&& Cell.m_shapestranslucent.empty()
&& Cell.m_lines.empty()
&& Cell.m_traction.empty()
&& Cell.m_instancetranslucent.empty()
&& cache.single.empty();
cache.boundsversion = m_instanceboundsversion;
cache.revoked = TAnimModel::s_instanceable_revoked;
return true;
}
bool opengl33_renderer::Instance_Cache_Valid( scene::basic_cell const &Cell ) const
{
return ( false == EditorModeFlag )
&& ( Cell.m_instancecache.boundsversion == m_instanceboundsversion )
&& ( Cell.m_instancecache.revoked == TAnimModel::s_instanceable_revoked );
}
// true if nothing of the cell would be drawn by the color pass: it holds only instances drawn with the instanced path,
// and the nearest point of the cell is past the largest range of them. the test is the one made for each bucket in
// Queue_Instances(), done before the cell is put in the cell queue: a scenery with many small instances of a short
// range has them in nearly every cell up to the draw range, and queueing, sorting and visiting these cells only
// to skip all their buckets took a good part of the frame
bool opengl33_renderer::Cell_Out_Of_Range( scene::basic_cell const &Cell ) const
{
if( ( false == Instance_Cache_Valid( Cell ) ) || ( false == Cell.m_instancecache.instancedonly ) ) { return false; }
// same measures as in Queue_Instances() for the color pass
auto const distancescale { 1.0 / ( static_cast<double>( Global.ZoomFactor ) * static_cast<double>( Global.ZoomFactor ) * static_cast<double>( Global.fDistanceFactor ) ) };
auto const slack { 1.001 };
auto const distancetested { sq( 64.0 ) };
auto const cellnearestdistance { std::max( 0.0, glm::length( Cell.m_area.center - m_renderpass.pass_camera.position() ) - Cell.m_area.radius ) };
auto const cellnearestdistancesquared { cellnearestdistance * cellnearestdistance };
return ( cellnearestdistancesquared > distancetested )
&& ( cellnearestdistancesquared * distancescale >= slack * Cell.m_instancecache.rangesquaredmax );
}
// makes the copies of the bounds of the instances held by a bucket of a scene cell
void opengl33_renderer::Update_Instance_Bounds( TModel3d const *Model, scene::basic_cell::instance_bucket const &Bucket )
{
// a submodel is drawn only closer than its fSquareMaxDist, see Render( TSubModel * ). past the largest of these
// there's nothing of the model left to draw, which makes it another limit of the range of its instances
auto lodrangesquared { ( Model != nullptr && Model->Root != nullptr ) ? 0.f : std::numeric_limits<float>::max() };
m_instance_lodpending.clear();
m_instance_lodpending.push_back( Model != nullptr ? Model->Root : nullptr );
while( false == m_instance_lodpending.empty() ) {
auto const *submodel = m_instance_lodpending.back();
m_instance_lodpending.pop_back();
if( submodel == nullptr ) { continue; }
lodrangesquared = std::max( lodrangesquared, submodel->fSquareMaxDist );
m_instance_lodpending.push_back( submodel->Child );
m_instance_lodpending.push_back( submodel->Next );
}
Bucket.bounds.clear();
Bucket.bounds.reserve( Bucket.instances.size() );
for( auto const *instance : Bucket.instances ) {
scene::basic_cell::instance_bounds instancebounds;
if( instance != nullptr ) {
instancebounds.center = glm::vec3{ instance->m_area.center };
instancebounds.radius = instance->m_area.radius;
instancebounds.rangesquaredmax = std::min( lodrangesquared, static_cast<float>( std::min( instance->m_rangesquaredmax, static_cast<double>( std::numeric_limits<float>::max() ) ) ) );
}
Bucket.bounds.emplace_back( instancebounds );
}
Bucket.boundsversion = m_instanceboundsversion;
}
// True GPU-instanced render path for a group of TAnimModel instances sharing the same
// TModel3d. The submodel tree is walked ONCE per batch; at every submodel that draws
// geometry we issue a single glDrawElementsInstancedBaseVertex(N) covering all visible
// instances. The vertex shader multiplies effective_modelview = instance_modelview[gl_InstanceID]
// * model_ubs.modelview, where instance_modelview[i] is the camera-space root transform
// of instance i (precomputed below) and model_ubs.modelview is the submodel-local chain
// (accumulated by the matrix stack starting from identity, NOT the camera/instance frame).
//
// Batch size is capped at MAX_INSTANCES_PER_BATCH (256). Larger groups are split.
void opengl33_renderer::Render_Instanced( TModel3d *Model, std::vector<TAnimModel *> const &Instances )
{
if( Model == nullptr ) { return; }
if( Instances.empty() ) { return; }
// LOD: a submodel is drawn only while fSquareDist lies inside its [fSquareMinDist, fSquareMaxDist)
// range, so the distinct range bounds split distance into bands with constant LOD. The bucket
// collects instances from every visible cell, so a single fSquareDist for all of them would draw
// far instances at the LOD of the nearest one. Each instance is assigned to its band and every
// band is drawn with its own fSquareDist, like in Render_Sleepers(). The grouping is a counting
// sort, linear in the instance count.
// the same walk also checks whether any piece of the model can get into the shadow map. Models
// whose materials are all excluded by the shadow rank cutoff (e.g. grass) would otherwise go through
// the whole per-instance culling and the batched draws in every shadow pass, only for every submodel
// to be skipped in Render(TSubModel*)
auto const *skins { Instances.front() != nullptr && Instances.front()->Material() != nullptr ? Instances.front()->Material()->replacable_skins : nullptr };
bool castsshadow { m_renderpass.draw_mode != rendermode::shadows };
m_instance_lodbounds.clear();
m_instance_lodpending.clear();
m_instance_lodpending.push_back( Model->Root );
while( false == m_instance_lodpending.empty() ) {
auto const *submodel = m_instance_lodpending.back();
m_instance_lodpending.pop_back();
if( submodel == nullptr ) { continue; }
if( submodel->fSquareMinDist > 0.f ) { m_instance_lodbounds.emplace_back( submodel->fSquareMinDist ); }
if( submodel->fSquareMaxDist < std::numeric_limits<float>::max() ) { m_instance_lodbounds.emplace_back( submodel->fSquareMaxDist ); }
if( ( false == castsshadow ) && ( submodel->eType < TP_ROTATOR ) ) {
auto const material { submodel->m_material >= 0 ? submodel->m_material : ( skins != nullptr ? skins[ -submodel->m_material ] : null_handle ) };
castsshadow = ( Material( material ).shadow_rank <= Global.gfx_shadow_rank_cutoff );
}
m_instance_lodpending.push_back( submodel->Child );
m_instance_lodpending.push_back( submodel->Next );
}
if( false == castsshadow ) { return; }
std::sort( m_instance_lodbounds.begin(), m_instance_lodbounds.end() );
m_instance_lodbounds.erase( std::unique( m_instance_lodbounds.begin(), m_instance_lodbounds.end() ), m_instance_lodbounds.end() );
auto const bandcount { m_instance_lodbounds.size() + 1 };
// 1. Visibility / distance cull. Collect surviving instances with their precomputed
// camera-space root modelview matrices and lod bands. m_instance_survivors and the other
// scratch vectors are persistent members reused across every Render_Instanced() call:
// clear() drops the contents but keeps the allocated capacity, so after the first few
// frames this stops calling malloc/free entirely.
m_instance_survivors.clear();
m_instance_survivors.reserve( Instances.size() );
// Pull the current pass camera/view transform once. We use the current GL
// modelview matrix as the view matrix because at the point Render_Instanced
// is called, OpenGLMatrices is set to the camera view (scene root) — no
// per-instance transform has been pushed yet.
glm::mat4 const view_matrix = OpenGLMatrices.data( GL_MODELVIEW );
bool prepared_shared_state = false; // RaPrepare() runs once per bucket
material_data const *batch_material { nullptr };
float farthest_distancesquared { 0.f };
for( auto *Instance : Instances ) {
if( Instance == nullptr ) { continue; }
// instances which lost their instanceable status after being bucketed (animation or skin
// assigned by an event) are drawn by the per-node path
if( false == Instance->m_instanceable ) { continue; }
if( false == Instance->m_visible ) { continue; }
if( false == m_renderpass.pass_camera.visible( Instance->m_area ) ) { continue; }
double distancesquared;
switch( m_renderpass.draw_mode ) {
case rendermode::shadows:
distancesquared = glm::length2( ( Instance->location() - m_renderpass.viewport_camera.position() ) / (double)Global.ZoomFactor ) / Global.fDistanceFactor;
break;
case rendermode::reflections:
distancesquared = glm::length2( ( Instance->location() - m_renderpass.pass_camera.position() ) );
if( distancesquared > Global.reflectiontune.range_instances * Global.reflectiontune.range_instances ) { continue; }
distancesquared += sq( EU07_REFLECTIONFIDELITYOFFSET );
break;
default:
distancesquared = glm::length2( ( Instance->location() - m_renderpass.pass_camera.position() ) / (double)Global.ZoomFactor ) / Global.fDistanceFactor;
break;
}
if( ( distancesquared < Instance->m_rangesquaredmin )
|| ( distancesquared >= Instance->m_rangesquaredmax ) ) { continue; }
auto const drawdistancethreshold { m_renderpass.draw_range + 250 };
if( distancesquared > sq( drawdistancethreshold ) ) { continue; }
auto const radiussquared { Instance->radius() * Instance->radius() };
if( radiussquared * Global.ZoomFactor / distancesquared < 0.003 * 0.003 ) { continue; }
if( !prepared_shared_state ) {
Instance->RaPrepare();
prepared_shared_state = true;
batch_material = Instance->Material();
}
Instance->m_framestamp = m_framestamp;
// Build the camera-relative root modelview for this instance:
// mv = view * translate(instance_pos - camera_pos) * rotate(instance_angles) * scale(m_scale)
// The rotation and scale part is cached by the instance, the translation goes into its last
// column. The scale is folded in so the GPU-instanced path produces visually identical output
// to the regular per-instance path; the shader applies it via effective_modelview = instance_mv * model_local.
glm::mat4 root { Instance->rotation_scale() };
root[ 3 ] = glm::vec4( glm::vec3( Instance->location() - m_renderpass.pass_camera.position() ), 1.f );
auto const distance { static_cast<float>( distancesquared ) };
farthest_distancesquared = std::max( farthest_distancesquared, distance );
m_instance_survivors.push_back( {
view_matrix * root,
distance,
static_cast<std::uint32_t>( std::upper_bound( m_instance_lodbounds.begin(), m_instance_lodbounds.end(), distance ) - m_instance_lodbounds.begin() ) } );
}
if( m_instance_survivors.empty() ) { return; }
// group the modelviews by lod band into a contiguous array, for the UBO upload. every distance in
// a band selects the same lod; the nearest one represents the band.
// within a band the instances are additionally ordered roughly near-to-far, in distance slots. dense
// alpha tested foliage then gets the most out of the early depth test, as the nearest instances fill
// the depth buffer first and hide the fragments of those behind them before they get shaded.
// both levels are done with a single counting sort, linear in the instance count
auto const distanceslots { 16 };
auto const keycount { bandcount * distanceslots };
auto const slotscale { distanceslots / std::sqrt( std::max( farthest_distancesquared, 1.f ) ) };
m_instance_bandstarts.assign( keycount + 1, 0 );
m_instance_banddistances.assign( bandcount, std::numeric_limits<float>::max() );
for( auto &survivor : m_instance_survivors ) {
m_instance_banddistances[ survivor.band ] = std::min( m_instance_banddistances[ survivor.band ], survivor.distancesquared );
auto const slot { std::min( distanceslots - 1, static_cast<int>( std::sqrt( survivor.distancesquared ) * slotscale ) ) };
survivor.band = static_cast<std::uint32_t>( survivor.band * distanceslots + slot ); // from now on it's the sort key
++m_instance_bandstarts[ survivor.band + 1 ];
}
for( std::size_t key = 1; key <= keycount; ++key ) {
m_instance_bandstarts[ key ] += m_instance_bandstarts[ key - 1 ];
}
m_instance_bandcursors.assign( m_instance_bandstarts.begin(), m_instance_bandstarts.end() - 1 );
m_instance_modelviews.resize( m_instance_survivors.size() );
for( auto const &survivor : m_instance_survivors ) {
m_instance_modelviews[ m_instance_bandcursors[ survivor.band ]++ ] = survivor.modelview;
}
auto alpha = ( batch_material != nullptr ? batch_material->textures_alpha : 0x30300030 );
alpha ^= 0x0F0F000F;
// 2. Walk the submodel tree once per sub-batch. The submodel-local matrix
// stack starts at identity; the per-instance camera transform comes from
// instance_modelview[gl_InstanceID] in the shader.
for( std::size_t band = 0; band < bandcount; ++band ) {
std::size_t offset_idx = m_instance_bandstarts[ band * distanceslots ];
std::size_t const band_end = m_instance_bandstarts[ ( band + 1 ) * distanceslots ];
while( offset_idx < band_end ) {
std::size_t const this_batch = std::min<std::size_t>( band_end - offset_idx, gl::MAX_INSTANCES_PER_BATCH );
// 2a. Upload N modelviews to instance_ubo[0..N-1].
instance_ubo->update(
reinterpret_cast<uint8_t const *>( m_instance_modelviews.data() + offset_idx ),
0,
static_cast<int>( this_batch * sizeof( glm::mat4 ) ) );
// 2b. Push identity onto the matrix stack so submodel transforms
// accumulate from identity, not from camera/instance space.
::glPushMatrix();
::glLoadIdentity();
// 2c. Configure the existing TModel3d/TSubModel render path. Setting
// m_current_instance_count routes draw(handle) calls to draw_instanced.
m_current_instance_count = this_batch;
Model->Root->fSquareDist = m_instance_banddistances[ band ]; // shared global, used by submodel LOD
Model->Root->ReplacableSet( ( batch_material != nullptr ? batch_material->replacable_skins : nullptr ), alpha );
Model->Root->pRoot = Model;
Render( Model->Root );
m_current_instance_count = 0;
::glPopMatrix();
offset_idx += this_batch;
++m_renderpass.draw_stats.instanced_drawcalls;
}
}
// 3. Restore instance_modelview[0] to identity so subsequent
// non-instanced draws continue to compute identity * modelview.
// done once the last batch is out, as everything drawn up to that point is instanced
{
glm::mat4 const identity( 1.0f );
instance_ubo->update( reinterpret_cast<uint8_t const *>( &identity ), 0, sizeof( identity ) );
}
m_renderpass.draw_stats.instances += static_cast<int>( m_instance_survivors.size() );
m_renderpass.draw_stats.models += static_cast<int>( m_instance_survivors.size() );
}
// Renders the per-track sleeper instances (TTrack::m_sleeper_local_transforms) using the
// existing GPU-instanced submodel pipeline. The track owns a vector of pre-baked
// local-space matrices; we compose each with `view * translate(track_origin - camera)`
// to get a camera-space modelview, then issue batched glDrawElementsInstancedBaseVertex
// calls -- one batch per MAX_INSTANCES_PER_BATCH sleepers.
//
// Skipped entirely when:
// - Global.SleeperDistance == 0 (sleeper rendering globally disabled)
// - the track has no sleepermodel
// - the track is farther than Global.SleeperDistance meters from the camera
// releases gl textures used only by vehicles farther than gfx.textures.releasedistance times the draw range
void opengl33_renderer::Update_Texture_Release()
{
if (m_colorpass.draw_range <= 0.f)
{
return;
}
auto const range{static_cast<double>(Global.gfx_texture_releasedistance) * m_colorpass.draw_range};
auto const camera{m_colorpass.pass_camera.position()};
m_textures.begin_release_scan();
for (auto *vehicle : simulation::Vehicles.sequence())
{
if (vehicle == nullptr)
{
continue;
}
bool const isnear{glm::length(vehicle->vPosition - camera) - vehicle->radius() <= range};
auto const mark_model = [&](TModel3d *Model) {
if (Model == nullptr)
{
return;
}
for (auto const texture : Model_Textures(Model))
{
m_textures.mark_as_needed(texture, isnear);
}
};
mark_model(vehicle->mdModel);
mark_model(vehicle->mdLowPolyInt);
mark_model(vehicle->mdLoad);
for (auto *attachment : vehicle->mdAttachments)
{
mark_model(attachment);
}
for (auto const skin : vehicle->m_materialdata.replacable_skins)
{
if (skin <= 0)
{
continue;
}
auto const &material{m_materials.material(skin)};
for (auto const texture : material.textures)
{
m_textures.mark_as_needed(texture, isnear);
}
for (auto const &variant : material.texture_variants)
{
for (auto const texture : variant)
{
m_textures.mark_as_needed(texture, isnear);
}
}
}
}
m_textures.release_unneeded();
}
// textures used by materials of the sub-models of specified model, replaceable skins excluded
std::vector<texture_handle> const &opengl33_renderer::Model_Textures(TModel3d *Model)
{
auto const lookup{m_modeltextures.find(Model)};
if (lookup != m_modeltextures.end())
{
return lookup->second;
}
auto &textures{m_modeltextures[Model]};
std::vector<TSubModel *> submodels;
if (Model->GetSMRoot() != nullptr)
{
submodels.emplace_back(Model->GetSMRoot());
}
while (false == submodels.empty())
{
auto *submodel{submodels.back()};
submodels.pop_back();
if (submodel->NextGet() != nullptr)
{
submodels.emplace_back(submodel->NextGet());
}
if (submodel->ChildGet() != nullptr)
{
submodels.emplace_back(submodel->ChildGet());
}
// negative material is one of replaceable skins of the vehicle, these are handled with the vehicle
if (submodel->GetMaterial() <= 0)
{
continue;
}
auto const &material{m_materials.material(submodel->GetMaterial())};
for (auto const texture : material.textures)
{
if (texture > 0)
{
textures.emplace_back(texture);
}
}
for (auto const &variant : material.texture_variants)
{
for (auto const texture : variant)
{
if (texture > 0)
{
textures.emplace_back(texture);
}
}
}
}
std::sort(std::begin(textures), std::end(textures));
textures.erase(std::unique(std::begin(textures), std::end(textures)), std::end(textures));
return textures;
}
void opengl33_renderer::Render_Sleepers( TTrack *Track )
{
if( Track == nullptr ) { return; }
if( false == Track->m_sleeper_enabled ) { return; }
if( Track->m_sleeper_model == nullptr ) { return; }
if( Track->m_sleeper_local_transforms.empty() ) { return; }
if( Global.SleeperDistance <= 0.f ) { return; }
// only the color and reflection passes draw sleepers; shadow/pick skip them on purpose
// (sleeper shadows would mostly fall back under the trackbed and pick already operates on
// the track itself).
switch( m_renderpass.draw_mode ) {
case rendermode::color:
case rendermode::reflections:
break;
default:
return;
}
// distance gate -- compare against Globals.SleeperDistance squared to avoid the sqrt
auto const camerapos = m_renderpass.pass_camera.position();
auto const trackpos = Track->location();
auto const distsq = glm::length2( trackpos - camerapos );
auto const cutoffsq = static_cast<double>( Global.SleeperDistance ) * static_cast<double>( Global.SleeperDistance );
if( distsq > cutoffsq ) { return; }
// build camera-space modelview matrices.
// each sleeper's stored matrix is in track-local space (relative to Track->m_origin).
// Render_Sleepers is called from inside the per-cell origin push -- the cell's center
// already equals Track->m_origin (see basic_cell::insert), so the current GL_MODELVIEW
// is already view * translate(m_origin - camera). We just need to compose with each
// per-sleeper local transform to get the final modelview.
glm::mat4 const origin_mv = OpenGLMatrices.data( GL_MODELVIEW );
// per-sleeper frustum cull + LOD selection. The whole-track SleeperDistance
// gate above keeps or drops the track as a unit; everything from here on
// operates on individual sleepers.
//
// Each m_sleeper_local_transforms entry is
// translate(world_pos - m_origin) * rotate(...) * translate(local_offset)
// so its translation column is the sleeper position relative to m_origin;
// adding m_origin back yields the sleeper's world-space position. The model's
// bounding radius (floored to a small minimum, in case it was never measured)
// serves both as the frustum test sphere and -- via the distance to that
// world position -- as the per-sleeper LOD distance.
auto const sleeperradius = std::max( Track->m_sleeper_model->bounding_radius(), 2.0f );
// Phase 1 -- frustum cull. For every sleeper that survives, store its
// camera-space modelview paired with the squared distance from the camera
// to ITS OWN world position (not the track / segment origin). That
// per-sleeper distance is what drives LOD selection below. A sleeper whose
// origin sits just off screen while its geometry still reaches into view is
// kept rather than wrongly culled.
std::vector<std::pair<float, glm::mat4>> survivors;
survivors.reserve( Track->m_sleeper_local_transforms.size() );
for( auto const &local : Track->m_sleeper_local_transforms ) {
glm::dvec3 const sleeperworldpos {
Track->m_origin + glm::dvec3( local[ 3 ].x, local[ 3 ].y, local[ 3 ].z ) };
if( false == m_renderpass.pass_camera.visible( scene::bounding_area{ sleeperworldpos, sleeperradius } ) ) {
continue;
}
auto const sleeperdistancesquared = static_cast<float>( glm::length2( sleeperworldpos - camerapos ) );
survivors.emplace_back( sleeperdistancesquared, origin_mv * local );
}
// every sleeper of this track was frustum-culled -- nothing left to draw
if( survivors.empty() ) { return; }
// Phase 2 -- sort survivors near-to-far. A submodel is drawn only while
// fSquareDist lies inside its [fSquareMinDist, fSquareMaxDist) range, so
// every distance between two consecutive range bounds selects an identical
// set of submodels -- i.e. the same LOD. Sorting turns each such LOD band
// into a contiguous run, letting the draw loop emit one instanced batch per
// band instead of one track-wide batch at a single distance.
std::sort( survivors.begin(), survivors.end(),
[]( std::pair<float, glm::mat4> const &Left, std::pair<float, glm::mat4> const &Right ) {
return Left.first < Right.first; } );
// contiguous copy of the sorted modelview matrices, for the UBO upload.
// Per-sleeper distances stay available as survivors[i].first, in lockstep.
std::vector<glm::mat4> instance_modelviews;
instance_modelviews.reserve( survivors.size() );
for( auto const &survivor : survivors ) {
instance_modelviews.emplace_back( survivor.second );
}
// collect the model's distinct LOD distance bounds. The sorted, de-duplicated
// set of every submodel's fSquareMinDist / fSquareMaxDist partitions distance
// into bands within which the selected LOD is constant. A model with no LOD
// yields a single band, and the draw loop below then behaves exactly like a
// single plain batched draw.
std::vector<float> lodbounds;
{
std::vector<TSubModel const *> pending;
if( Track->m_sleeper_model->Root != nullptr ) {
pending.push_back( Track->m_sleeper_model->Root );
}
while( false == pending.empty() ) {
auto const *submodel = pending.back();
pending.pop_back();
lodbounds.emplace_back( submodel->fSquareMinDist );
lodbounds.emplace_back( submodel->fSquareMaxDist );
if( submodel->Child != nullptr ) { pending.push_back( submodel->Child ); }
if( submodel->Next != nullptr ) { pending.push_back( submodel->Next ); }
}
}
std::sort( lodbounds.begin(), lodbounds.end() );
lodbounds.erase( std::unique( lodbounds.begin(), lodbounds.end() ), lodbounds.end() );
// optional replacable skin: build a transient material_data so we can drive ReplacableSet
// the same way Render_Instanced does. when no skin is set we fall back to the model defaults.
material_data sleeper_material {};
bool const has_skin = ( Track->m_sleeper_skin != null_handle );
if( has_skin ) {
sleeper_material.replacable_skins[ 1 ] = Track->m_sleeper_skin;
}
// Phase 3 -- draw. Walk the sorted survivors one LOD band at a time. Each
// band is submitted as one or more instanced draws (split only when it
// exceeds MAX_INSTANCES_PER_BATCH); every draw in the band uses an in-band
// fSquareDist, so each sleeper renders at the LOD its own distance selects
// while instancing stays fully in effect.
auto *Model = Track->m_sleeper_model;
std::size_t const total = instance_modelviews.size();
std::size_t band_start = 0;
while( band_start < total ) {
// the band ends at the first sleeper distance that reaches the next LOD
// bound above the band's starting distance.
auto const upperbound = std::upper_bound(
lodbounds.begin(), lodbounds.end(), survivors[ band_start ].first );
float const band_limit = ( upperbound == lodbounds.end()
? std::numeric_limits<float>::max()
: *upperbound );
std::size_t band_end = band_start;
while( ( band_end < total ) && ( survivors[ band_end ].first < band_limit ) ) {
++band_end;
}
// every distance in the band selects the same LOD; the band's nearest
// sleeper is used as the representative fSquareDist.
float const band_distancesquared = survivors[ band_start ].first;
std::size_t offset_idx = band_start;
while( offset_idx < band_end ) {
std::size_t const this_batch = std::min<std::size_t>( band_end - offset_idx, gl::MAX_INSTANCES_PER_BATCH );
instance_ubo->update(
reinterpret_cast<uint8_t const *>( instance_modelviews.data() + offset_idx ),
0,
static_cast<int>( this_batch * sizeof( glm::mat4 ) ) );
::glPushMatrix();
::glLoadIdentity();
m_current_instance_count = this_batch;
Model->Root->fSquareDist = band_distancesquared;
auto alpha = ( has_skin ? sleeper_material.textures_alpha : 0x30300030 );
alpha ^= 0x0F0F000F;
Model->Root->ReplacableSet( ( has_skin ? sleeper_material.replacable_skins : nullptr ), alpha );
Model->Root->pRoot = Model;
Render( Model->Root );
m_current_instance_count = 0;
::glPopMatrix();
// restore instance_modelview[0] to identity so subsequent non-instanced draws
// continue to compute identity * modelview (mirroring Render_Instanced).
{
glm::mat4 const identity( 1.0f );
instance_ubo->update( reinterpret_cast<uint8_t const *>( &identity ), 0, sizeof( identity ) );
}
offset_idx += this_batch;
++m_renderpass.draw_stats.instanced_drawcalls;
}
band_start = band_end;
}
m_renderpass.draw_stats.instances += static_cast<int>( total );
m_renderpass.draw_stats.models += static_cast<int>( total );
}
namespace {
// the level of detail of the whole model a run of beams is seen at, from its distance
float timber_band( track_sleepers::beam_model const &Model, double const Distance )
{
auto const squaredistance { static_cast<float>( Distance * Distance ) };
auto band { Model.bands.empty() ? 0.f : Model.bands.front() };
for( auto const start : Model.bands ) {
if( squaredistance >= start ) {
band = start;
}
}
return band;
}
// the transforms of a run of beams, relative to the origin of their track, put in the camera space of the modelview given
void append_timbers( std::vector<glm::mat4> &Instances, glm::mat4 const &Modelview, std::vector<glm::mat4> const &Transforms, std::size_t const First, std::size_t const Last )
{
for( auto index { First }; index < Last; ++index ) {
Instances.emplace_back( Modelview * Transforms[ index ] );
}
}
} // namespace
// Renders the sleepers and switch timbers of a run of tracks of a cell. Each beam is made of instances of the parts of a model or
// of a whole model, kept by its track relative to the origin of the track. The runs of beams in range and in sight are gathered
// for the whole run of tracks by the model and its part or its level of detail, and each is drawn in as few instanced batches
// as they fit in. In the shadow pass only those near the camera are drawn, their shadows falling where they can be seen.
void opengl33_renderer::Render_Timbers( scene::basic_cell::path_sequence::const_iterator First, scene::basic_cell::path_sequence::const_iterator Last )
{
if( Global.SleeperDistance <= 0.f ) { return; }
// a name alone, without looking the model up: the tracks it failed to load for aren't laid
if( Global.Sleepers3D.empty() ) { return; }
auto const shadows = ( m_renderpass.draw_mode == rendermode::shadows );
timber_view const view {
// the distance is taken from the camera of the view, the shadow pass culling against its own frustum
( shadows ? m_renderpass.viewport_camera.position() : m_renderpass.pass_camera.position() ),
static_cast<double>( shadows ? std::min( Global.SleeperDistance, 50.f ) : Global.SleeperDistance ),
shadows,
OpenGLMatrices.data( GL_MODELVIEW ) };
for( auto &bucket : m_timberbuckets ) {
bucket.instances.clear();
}
for( auto first { First }; first != Last; ++first ) {
gather_timbers( **first, view );
}
std::size_t total { 0 };
for( auto const &bucket : m_timberbuckets ) {
if( bucket.instances.empty() ) { continue; }
total += bucket.instances.size();
draw_timbers( bucket );
}
if( total == 0 ) { return; }
// instance_modelview[0] back to identity for the draws which aren't instanced
{
glm::mat4 const identity( 1.0f );
instance_ubo->update( std::as_bytes( std::span { &identity, 1 } ), 0 );
}
m_renderpass.draw_stats.instances += static_cast<int>( total );
}
// the camera-space transforms of the beams of a model and its part or its level of detail gathered for the frame, in a bucket of
// their own made for the first of them
std::vector<glm::mat4> &opengl33_renderer::timber_instances( track_sleepers::beam_model const *Model, int const Part, float const Band )
{
for( auto &bucket : m_timberbuckets ) {
if( bucket.model == Model && bucket.part == Part && bucket.band == Band ) {
return bucket.instances;
}
}
auto &bucket { m_timberbuckets.emplace_back() };
bucket.model = Model;
bucket.part = Part;
bucket.band = Band;
return bucket.instances;
}
// the beams of a track in range and in sight gathered into the buckets, laid first where they've changed; those of a track about to
// come in range laid ahead, in the background
void opengl33_renderer::gather_timbers( TTrack &Track, timber_view const &View )
{
if( false == Track.m_visible || false == Track.m_sleepers3d.active ) { return; }
if( glm::length( Track.location() - View.camera ) > View.reach + Track.radius() ) {
// worked out ahead, in the background, before it comes in range
if( false == View.shadows && Track.m_sleepers3d.dirty && glm::length( Track.location() - View.camera ) < View.reach + Track.radius() + 300.0 ) {
track_sleepers::prefetch( Track );
}
return;
}
if( Track.m_sleepers3d.dirty ) {
track_sleepers::lay( Track );
}
auto const &laid = Track.m_sleepers3d;
if( laid.timbers == nullptr ) { return; }
for( auto const &chunk : laid.chunks ) {
auto const centre = Track.m_origin + glm::dvec3( chunk.centre );
auto const distance = glm::length( centre - View.camera );
if( distance > View.reach + chunk.radius ) { continue; }
if( false == m_renderpass.pass_camera.visible( scene::bounding_area{ centre, chunk.radius } ) ) { continue; }
// the transforms of the beams are relative to the origin of the track, which the modelview is translated to already
gather_timber_chunk( laid, chunk, std::max( 0.0, distance - chunk.radius ), View.modelview );
}
}
// the beams of a run of them along a track gathered into the buckets: the parts of the timbers of a model made of them, the whole
// timbers and the plain sleepers at the level of detail they're seen at from the nearest of them
void opengl33_renderer::gather_timber_chunk( track_sleepers::laid const &Laid, track_sleepers::chunk const &Chunk, double const Nearest, glm::mat4 const &Modelview )
{
if( Laid.timbers->stretchable ) {
for( int part = 0; part < track_sleepers::part_count; ++part ) {
auto &instances { timber_instances( Laid.timbers, part, 0.f ) };
append_timbers( instances, Modelview, Laid.instances[ part ], Chunk.first[ part ], Chunk.last[ part ] );
}
}
if( Chunk.wholelast > Chunk.wholefirst ) {
auto &instances { timber_instances( Laid.timbers, -1, timber_band( *Laid.timbers, Nearest ) ) };
append_timbers( instances, Modelview, Laid.whole, Chunk.wholefirst, Chunk.wholelast );
}
if( Laid.plains != nullptr && Chunk.plainlast > Chunk.plainfirst ) {
auto &instances { timber_instances( Laid.plains, -1, timber_band( *Laid.plains, Nearest ) ) };
append_timbers( instances, Modelview, Laid.plain, Chunk.plainfirst, Chunk.plainlast );
}
}
// the beams of a bucket drawn in as few instanced batches as they fit in: of a part of a model with the rest of it hidden, or of a whole
// model at the level of detail of the bucket
void opengl33_renderer::draw_timbers( timber_bucket const &Bucket )
{
auto const &beammodel = *Bucket.model;
auto *model = beammodel.model;
if( Bucket.part >= 0 ) {
show_timber_part( beammodel, Bucket.part );
}
material_data skins {};
if( beammodel.skin != null_handle ) {
skins.replacable_skins[ 1 ] = beammodel.skin;
}
auto const alpha = ( 0x30300030 ^ 0x0F0F000F );
auto const &instances = Bucket.instances;
for( std::size_t offset = 0; offset < instances.size(); offset += gl::MAX_INSTANCES_PER_BATCH ) {
auto const batch = std::min<std::size_t>( instances.size() - offset, gl::MAX_INSTANCES_PER_BATCH );
instance_ubo->update( std::as_bytes( std::span { instances.data() + offset, batch } ), 0 );
::glPushMatrix();
::glLoadIdentity();
m_current_instance_count = batch;
// inside the range of the level of detail the beams are at
TSubModel::fSquareDist = ( Bucket.part >= 0 ? 0.f : Bucket.band + 1.f );
TSubModel::ReplacableSet( ( beammodel.skin != null_handle ? skins.replacable_skins : nullptr ), alpha );
TSubModel::pRoot = model;
Render( model->Root );
m_current_instance_count = 0;
::glPopMatrix();
++m_renderpass.draw_stats.instanced_drawcalls;
}
if( Bucket.part >= 0 ) {
restore_timber_parts( beammodel );
}
}
// only the given part of a timber model seen, its siblings skipped as the model is walked: the other parts, and what else the model
// holds, like the fastenings of the rails, which aren't laid. what each was is kept to put it back
void opengl33_renderer::show_timber_part( track_sleepers::beam_model const &Model, int const Part )
{
m_timbervisibility.clear();
for( int part = 0; part < track_sleepers::part_count; ++part ) {
m_timbervisibility.push_back( Model.parts[ part ]->iVisible );
Model.parts[ part ]->iVisible = ( part == Part ? 1 : 0 );
}
for( auto *other : Model.others ) {
m_timbervisibility.push_back( other->iVisible );
other->iVisible = 0;
}
}
// the parts of a timber model and its other submodels seen as they were, some hidden by the model itself, which may stand in the
// scenery too
void opengl33_renderer::restore_timber_parts( track_sleepers::beam_model const &Model )
{
auto visibility = m_timbervisibility.begin();
for( int part = 0; part < track_sleepers::part_count; ++part ) {
Model.parts[ part ]->iVisible = *visibility++;
}
for( auto *other : Model.others ) {
other->iVisible = *visibility++;
}
}
bool opengl33_renderer::Render(TDynamicObject *Dynamic)
{
glDebug("Render TDynamicObject");
if (!Global.render_cab && Global.pCamera.m_owner == Dynamic)
return false;
Dynamic->renderme = (
( Global.pCamera.m_owner == Dynamic && !FreeFlyModeFlag )
|| ( m_renderpass.pass_camera.visible( Dynamic ) ) );
if (false == Dynamic->renderme) { return false; }
// setup
TSubModel::iInstance = reinterpret_cast<std::uintptr_t>(Dynamic); //żeby nie robić cudzych animacji
TSubModel::iVariantSeed = Dynamic->variant_seed();
glm::dvec3 const originoffset = Dynamic->vPosition - m_renderpass.pass_camera.position();
// lod visibility ranges are defined for base (x 1.0) viewing distance. for render we adjust them for actual range multiplier and zoom
float squaredistance;
switch (m_renderpass.draw_mode)
{
case rendermode::shadows:
{
squaredistance = glm::length2(glm::vec3{glm::dvec3{Dynamic->vPosition - m_renderpass.viewport_camera.position()}} / Global.ZoomFactor);
if( false == FreeFlyModeFlag ) {
// filter out small details if we're in vehicle cab
squaredistance = std::max( 100.f * 100.f, squaredistance );
}
break;
}
case rendermode::reflections:
{
// reflection mode draws simplified version of the shapes, by artificially increasing view range
// it also ignores zoom settings and distance multipliers
squaredistance =
std::max(
100.f * 100.f,
// TBD: take into account distance multipliers?
glm::length2( glm::vec3{ originoffset } ) /* / Global.fDistanceFactor */ );
// NOTE: arbitrary draw range limit
if( squaredistance > Global.reflectiontune.range_vehicles * Global.reflectiontune.range_vehicles ) {
return false;
}
// TBD, TODO: bind offset value with setting variable?
// NOTE: combined 'squared' distance doesn't equal actual squared (distance + offset) but, eh
squaredistance += sq(EU07_REFLECTIONFIDELITYOFFSET);
break;
}
default:
{
squaredistance = glm::length2(glm::vec3{originoffset} / Global.ZoomFactor);
// TODO: filter out small details based on fidelity setting
break;
}
}
// crude way to reject early items too far to affect the output (mostly relevant for shadow and reflection passes)
auto const drawdistancethreshold{ m_renderpass.draw_range + 250 };
if( squaredistance > sq(drawdistancethreshold) ) {
return false;
}
// second stage visibility cull, reject vehicles too far away to be noticeable
auto const squareradius{ Dynamic->radius() * Dynamic->radius() };
Dynamic->renderme = ( squareradius * Global.ZoomFactor / squaredistance > 0.003 * 0.003 );
if( false == Dynamic->renderme ) {
return false;
}
// debug data
++m_renderpass.draw_stats.dynamics;
Dynamic->ABuLittleUpdate(squaredistance); // ustawianie zmiennych submodeli dla wspólnego modelu
glm::mat4 future_stack = model_ubs.future;
glm::mat4 mv = OpenGLMatrices.data(GL_MODELVIEW);
model_ubs.future *= glm::translate(mv, glm::vec3(Dynamic->get_future_movement())) * glm::inverse(mv);
::glPushMatrix();
::glTranslated(originoffset.x, originoffset.y, originoffset.z);
::glMultMatrixd(glm::value_ptr(Dynamic->mMatrix));
switch (m_renderpass.draw_mode)
{
case rendermode::color:
case rendermode::reflections:
{
if (Dynamic->fShade > 0.0f)
{
// change light level based on light level of the occupied track
setup_sunlight_intensity(Dynamic->fShade);
}
// render
if( Dynamic->mdLowPolyInt ) {
// low poly interior
Render_lowpoly( Dynamic, squaredistance, false );
}
else {
// HACK: if the model lacks low poly interior, we presume the load is placed outside
if( Dynamic->mdLoad ) {
// renderowanie nieprzezroczystego ładunku
Render( Dynamic->mdLoad, Dynamic->Material(), squaredistance, { 0.f, Dynamic->LoadOffset, 0.f }, {} );
}
}
if( Dynamic->mdModel ) {
// main model
Render( Dynamic->mdModel, Dynamic->Material(), squaredistance );
}
// optional attached models
for( auto *attachment : Dynamic->mdAttachments ) {
Render( attachment, Dynamic->Material(), squaredistance );
}
// optional coupling adapters
Render_coupler_adapter( Dynamic, squaredistance, end::front );
Render_coupler_adapter( Dynamic, squaredistance, end::rear );
// post-render cleanup
if (Dynamic->fShade > 0.0f)
{
// restore regular light level
setup_sunlight_intensity();
}
break;
}
case rendermode::shadows:
{
if( Dynamic->mdLowPolyInt ) {
// low poly interior
Render( Dynamic->mdLowPolyInt, Dynamic->Material(), squaredistance );
}
if( Dynamic->mdModel ) {
// main model
Render( Dynamic->mdModel, Dynamic->Material(), squaredistance );
}
// optional attached models
for( auto *attachment : Dynamic->mdAttachments ) {
Render( attachment, Dynamic->Material(), squaredistance );
}
// optional coupling adapters
Render_coupler_adapter( Dynamic, squaredistance, end::front );
Render_coupler_adapter( Dynamic, squaredistance, end::rear );
if( Dynamic->mdLoad ) {
// renderowanie nieprzezroczystego ładunku
Render( Dynamic->mdLoad, Dynamic->Material(), squaredistance, { 0.f, Dynamic->LoadOffset, 0.f }, {} );
}
// post-render cleanup
break;
}
case rendermode::pickcontrols:
{
if (Dynamic->mdLowPolyInt) {
// low poly interior
Render(Dynamic->mdLowPolyInt, Dynamic->Material(), squaredistance);
}
break;
}
case rendermode::pickscenery:
default:
{
break;
}
}
::glPopMatrix();
model_ubs.future = future_stack;
// TODO: check if this reset is needed. In theory each object should render all parts based on its own instance data anyway?
if (Dynamic->btnOn)
Dynamic->TurnOff(); // przywrócenie domyślnych pozycji submodeli
return true;
}
// rendering kabiny gdy jest oddzielnym modelem i ma byc wyswietlana
bool opengl33_renderer::Render_cab(TDynamicObject const *Dynamic, float const Lightlevel, bool const Alpha)
{
if (Dynamic == nullptr)
{
TSubModel::iInstance = 0;
TSubModel::iVariantSeed = 0;
return false;
}
TSubModel::iInstance = reinterpret_cast<std::uintptr_t>(Dynamic);
TSubModel::iVariantSeed = Dynamic->variant_seed();
if ((true == FreeFlyModeFlag) || (false == Dynamic->bDisplayCab) || (Dynamic->mdKabina == Dynamic->mdModel))
{
// ABu: Rendering kabiny jako ostatniej, zeby bylo widac przez szyby, tylko w widoku ze srodka
return false;
}
if (Dynamic->mdKabina)
{ // bo mogła zniknąć przy przechodzeniu do innego pojazdu
// setup shared by all render paths
::glPushMatrix();
auto const originoffset = Dynamic->GetPosition() - m_renderpass.pass_camera.position();
::glTranslated(originoffset.x, originoffset.y, originoffset.z);
::glMultMatrixd(glm::value_ptr(Dynamic->mMatrix));
switch (m_renderpass.draw_mode)
{
case rendermode::color:
{
// render path specific setup:
if (Dynamic->fShade > 0.0f)
{
// change light level based on light level of the occupied track
setup_sunlight_intensity(Dynamic->fShade);
}
auto const old_ambient { light_ubs.ambient };
auto const luminance { Global.fLuminance * ( Dynamic->fShade > 0.0f ? Dynamic->fShade : 1.0f ) };
if( Lightlevel > 0.f ) {
// crude way to light the cabin, until we have something more complete in place
light_ubs.ambient += packed_vec3( ( Dynamic->InteriorLight * Lightlevel ) * static_cast<float>( std::clamp( 1.25 - luminance, 0.0, 1.0 ) ) );
light_ubo->update( light_ubs );
}
// render
if (true == Alpha)
{
// translucent parts
Render_Alpha(Dynamic->mdKabina, Dynamic->Material(), 0.0);
}
else
{
// opaque parts
Render(Dynamic->mdKabina, Dynamic->Material(), 0.0);
}
// post-render restore
light_ubs.ambient = old_ambient;
setup_sunlight_intensity();
break;
}
case rendermode::shadows:
{
if( true == Alpha ) {
// translucent parts
Render_Alpha( Dynamic->mdKabina, Dynamic->Material(), 0.0 );
}
else {
// opaque parts
Render( Dynamic->mdKabina, Dynamic->Material(), 0.0 );
}
break;
}
case rendermode::pickcontrols:
{
Render(Dynamic->mdKabina, Dynamic->Material(), 0.0);
break;
}
default:
{
break;
}
}
// post-render restore
::glPopMatrix();
}
return true;
}
bool opengl33_renderer::Render(TModel3d *Model, material_data const *Material, float const Squaredistance)
{
auto alpha = (Material != nullptr ? Material->textures_alpha : 0x30300030);
alpha ^= 0x0F0F000F; // odwrócenie flag tekstur, aby wyłapać nieprzezroczyste
if (0 == (alpha & Model->iFlags & 0x1F1F001F))
{
// czy w ogóle jest co robić w tym cyklu?
return false;
}
Model->Root->fSquareDist = Squaredistance; // zmienna globalna!
// setup
Model->Root->ReplacableSet((Material != nullptr ? Material->replacable_skins : nullptr), alpha);
Model->Root->pRoot = Model;
// render
Render(Model->Root);
// post-render cleanup
return true;
}
bool opengl33_renderer::Render(TModel3d *Model, material_data const *Material, float const Squaredistance, glm::dvec3 const &Position, glm::vec3 const &Angle)
{
::glPushMatrix();
::glTranslated(Position.x, Position.y, Position.z);
if (Angle.y != 0.0)
::glRotated(Angle.y, 0.f, 1.f, 0.f);
if (Angle.x != 0.0)
::glRotated(Angle.x, 1.f, 0.f, 0.f);
if (Angle.z != 0.0)
::glRotated(Angle.z, 0.f, 0.f, 1.f);
auto const result = Render(Model, Material, Squaredistance);
::glPopMatrix();
return result;
}
// opaque characters of a text display, laid out in a row the same way as the translucent ones
void opengl33_renderer::Render_text(TSubModel *Submodel)
{
if (TSubModel::pasText == nullptr)
{
return;
}
::glPushMatrix();
for (auto *p : Submodel->text_letters(*TSubModel::pasText))
{
Render(p);
if (p->fMatrix)
::glMultMatrixf(p->fMatrix->readArray()); // move on to the place of the next character
}
::glPopMatrix();
}
void opengl33_renderer::Render(TSubModel *Submodel)
{
glDebug("Render TSubModel");
if ((Submodel->iVisible) && (TSubModel::fSquareDist >= Submodel->fSquareMinDist) && (TSubModel::fSquareDist < Submodel->fSquareMaxDist) && (false == m_previewing || Submodel->fVisible > 0.f))
{
glm::mat4 future_stack = model_ubs.future;
if (Submodel->iFlags & 0xC000)
{
::glPushMatrix();
if (Submodel->fMatrix)
::glMultMatrixf(Submodel->fMatrix->readArray());
if (Submodel->b_aAnim != TAnimType::at_None)
{
Submodel->RaAnimation(Submodel->b_aAnim);
glm::mat4 mv = OpenGLMatrices.data(GL_MODELVIEW);
model_ubs.future *= (mv * Submodel->future_transform) * glm::inverse(mv);
}
}
if (Submodel->eType < TP_ROTATOR)
{
// renderowanie obiektów OpenGL
if (Submodel->iAlpha & Submodel->iFlags & 0x1F)
{
// rysuj gdy element nieprzezroczysty
// debug data
++m_renderpass.draw_stats.submodels;
++m_renderpass.draw_stats.drawcalls;
switch (m_renderpass.draw_mode)
{
case rendermode::color:
case rendermode::reflections:
{
// material configuration:
// transparency hack
if (Submodel->fVisible < 1.0f)
setup_drawing(true);
// textures...
if (Submodel->m_material < 0)
{ // zmienialne skóry
Bind_Material(submodel_material(Submodel), Submodel);
}
else
{
// również 0
Bind_Material(Submodel->m_material, Submodel);
}
// ...luminance
auto const isemissive { ( Submodel->f4Emision.a > 0.f ) && ( Global.fLuminance < Submodel->fLight ) };
if (isemissive)
model_ubs.emission = Submodel->f4Emision.a;
// main draw call
draw(Submodel->m_geometry.handle);
// post-draw reset
model_ubs.emission = 0.0f;
if (Submodel->fVisible < 1.0f)
setup_drawing(false);
break;
}
case rendermode::shadows:
{
// skip if the shadow caster rank is too low for currently set threshold
// or if the submodel is hidden (colour pass only fades it out, e.g. inactive seasonal variant)
if( ( Material( Submodel ).shadow_rank > Global.gfx_shadow_rank_cutoff )
|| ( Submodel->fVisible <= 0.f ) )
{
--m_renderpass.draw_stats.submodels;
--m_renderpass.draw_stats.drawcalls;
break;
}
if (Submodel->m_material < 0)
{ // zmienialne skóry
Bind_Material_Shadow(submodel_material(Submodel));
}
else
{
// również 0
Bind_Material_Shadow(Submodel->m_material);
}
draw(Submodel->m_geometry.handle);
break;
}
case rendermode::pickscenery:
{
m_pick_shader->bind();
draw(Submodel->m_geometry.handle);
break;
}
case rendermode::pickcontrols:
{
if (Submodel->screen_touch_list) {
// touch screen gradient
m_pick_surface_shader->bind();
model_ubs.param[0] = glm::vec4(1.0f - m_picksurfaceitems.size() / 255.0f, 0.0f, 0.0f, 1.0f);
m_picksurfaceitems.emplace_back(Submodel);
}
else {
// control picking applies individual colour for each submodel
m_pick_shader->bind();
m_pickcontrolsitems.emplace_back(Submodel);
model_ubs.param[0] = glm::vec4(pick_color(m_pickcontrolsitems.size()), 1.0f);
}
draw(Submodel->m_geometry.handle);
break;
}
default:
{
break;
}
}
}
}
else if (Submodel->eType == TP_STARS)
{
switch (m_renderpass.draw_mode)
{
// colour points are only rendered in colour mode(s)
case rendermode::color:
case rendermode::reflections:
{
if (Global.fLuminance < Submodel->fLight)
{
Bind_Material(Submodel->m_material, Submodel);
// main draw call
model_ubs.param[1].x = 8.0f;
draw(Submodel->m_geometry.handle);
}
break;
}
default:
{
break;
}
}
}
if (Submodel->Child != nullptr && (TSubModel::iAlpha & Submodel->iFlags & 0x001F0000))
{
if (Submodel->eType == TP_TEXT)
{
Render_text(Submodel);
}
else
{
Render(Submodel->Child);
}
}
if (Submodel->iFlags & 0xC000)
{
model_ubs.future = future_stack;
::glPopMatrix();
}
}
/*
if( Submodel->b_Anim < at_SecondsJump )
Submodel->b_Anim = at_None; // wyłączenie animacji dla kolejnego użycia subm
*/
if (Submodel->Next)
if (Submodel->iAlpha & Submodel->iFlags & 0x1F000000)
Render(Submodel->Next); // dalsze rekurencyjnie
}
void opengl33_renderer::Render(TTrack *Track)
{
if ((Track->m_material1 == 0) && (Track->m_material2 == 0) && (Track->eType != tt_Switch || Track->SwitchExtension->m_material3 == 0))
{
return;
}
if (false == Track->m_visible)
{
return;
}
++m_renderpass.draw_stats.paths;
++m_renderpass.draw_stats.drawcalls;
switch (m_renderpass.draw_mode)
{
// single path pieces are rendererd in pick scenery mode only
case rendermode::pickscenery:
{
m_pick_shader->bind();
m_picksceneryitems.emplace_back( Track );
draw(std::begin(Track->Geometry1), std::end(Track->Geometry1));
draw(std::begin(Track->Geometry2), std::end(Track->Geometry2));
for (auto &tread : Track->GeometryTreads)
draw(std::begin(tread.geometry), std::end(tread.geometry));
if (Track->eType == tt_Switch)
draw(Track->SwitchExtension->Geometry3);
break;
}
default:
{
break;
}
}
}
// the cut faces of the rails of a track and the treads of the wheels on them, in the matte variants of the rail materials: batched with
// those of the other tracks, unless the track lies where the light differs
void opengl33_renderer::Render_cuts(TTrack *Track, material_handle &Batchmaterial)
{
// most tracks have none, the frogs and the blades off or the track plain: nothing to go through
if (Track->GeometryCut1.empty() && Track->GeometryCut2.empty() && Track->GeometryTreads.empty())
{
return;
}
auto const part = [this, Track, &Batchmaterial](material_handle const Material, TTrack::geometryhandle_sequence &Geometry) {
if ((Material == null_handle) || Geometry.empty())
{
return;
}
if (Track->eEnvironment != e_flat)
{
flush_path_batch(Batchmaterial);
setup_environment_light(Track->eEnvironment);
Bind_Material(Material);
draw(std::begin(Geometry), std::end(Geometry));
setup_environment_light();
return;
}
begin_path_batch(Batchmaterial, Material);
m_pathbatch.insert(std::end(m_pathbatch), std::begin(Geometry), std::end(Geometry));
};
part(Track->m_materialcut1, Track->GeometryCut1);
part(Track->m_materialcut2, Track->GeometryCut2);
for (auto &tread : Track->GeometryTreads)
{
part(tread.material, tread.geometry);
part(tread.matte, tread.cuts);
}
}
void opengl33_renderer::flush_path_batch(material_handle &Batchmaterial)
{
if (false == m_pathbatch.empty())
{
draw(std::begin(m_pathbatch), std::end(m_pathbatch));
m_pathbatch.clear();
}
Batchmaterial = null_handle;
}
bool opengl33_renderer::begin_path_batch(material_handle &Batchmaterial, material_handle const Material)
{
if (Material == Batchmaterial)
{
return false;
}
flush_path_batch(Batchmaterial);
Bind_Material(Material);
Batchmaterial = Material;
return true;
}
// experimental, does track rendering in two passes, to take advantage of reduced texture switching
void opengl33_renderer::Render(scene::basic_cell::path_sequence::const_iterator First, scene::basic_cell::path_sequence::const_iterator Last)
{
// setup
switch (m_renderpass.draw_mode)
{
case rendermode::shadows:
{
// NOTE: roads-based platforms tend to miss parts of shadows if rendered with either back or front culling
glDisable(GL_CULL_FACE);
break;
}
default:
{
break;
}
}
// geometry of neighbouring tracks which share the material is gathered and drawn together.
// only neighbours are combined, the tracks are still drawn in their order in the cell
material_handle batchmaterial{null_handle};
auto const flush_batch = [this, &batchmaterial]() { flush_path_batch(batchmaterial); };
// returns: true if the material starts a new batch, false if it continues the current one
auto const begin_batch = [this, &batchmaterial](material_handle const Material) { return begin_path_batch(batchmaterial, Material); };
// TODO: render auto generated trackbeds together with regular trackbeds in pass 1, and all rails in pass 2
// first pass, material 1
for (auto first{First}; first != Last; ++first)
{
auto const track{*first};
if (track->m_material1 == 0)
{
continue;
}
if (false == track->m_visible)
{
continue;
}
++m_renderpass.draw_stats.paths;
++m_renderpass.draw_stats.drawcalls;
switch (m_renderpass.draw_mode)
{
case rendermode::color:
case rendermode::reflections:
{
if (track->eEnvironment != e_flat)
{
// track with light level of its own is drawn on its own
flush_batch();
setup_environment_light(track->eEnvironment);
Bind_Material(track->m_material1);
draw(std::begin(track->Geometry1), std::end(track->Geometry1));
// restore default lighting
setup_environment_light();
break;
}
if (false == begin_batch(track->m_material1))
{
// the track is drawn with the call of its predecessor
--m_renderpass.draw_stats.drawcalls;
}
m_pathbatch.insert(std::end(m_pathbatch), std::begin(track->Geometry1), std::end(track->Geometry1));
break;
}
case rendermode::shadows:
{
if ((std::abs(track->fTexHeight1) < 0.35f) || (track->iCategoryFlag != 2))
{
// shadows are only calculated for high enough roads, typically meaning track platforms
--m_renderpass.draw_stats.paths;
--m_renderpass.draw_stats.drawcalls;
continue;
}
if( Material( track->m_material1 ).shadow_rank > Global.gfx_shadow_rank_cutoff ) {
// skip if the shadow caster rank is too low for currently set threshold
--m_renderpass.draw_stats.paths;
--m_renderpass.draw_stats.drawcalls;
continue;
}
Bind_Material_Shadow(track->m_material1);
draw(std::begin(track->Geometry1), std::end(track->Geometry1));
break;
}
case rendermode::pickscenery: // pick scenery mode uses piece-by-piece approach
case rendermode::pickcontrols:
default:
{
break;
}
}
}
flush_batch();
// second pass, material 2
for (auto first{First}; first != Last; ++first)
{
auto const track{*first};
if (track->m_material2 == 0)
{
continue;
}
if (false == track->m_visible)
{
continue;
}
if (track->eType == tt_Normal && editor_ballast_hidden(track, m_renderpass.draw_mode == rendermode::color))
{
continue;
}
switch (m_renderpass.draw_mode)
{
case rendermode::color:
case rendermode::reflections:
{
if (track->eEnvironment != e_flat)
{
flush_batch();
setup_environment_light(track->eEnvironment);
Bind_Material(track->m_material2);
draw(std::begin(track->Geometry2), std::end(track->Geometry2));
// restore default lighting
setup_environment_light();
break;
}
begin_batch(track->m_material2);
m_pathbatch.insert(std::end(m_pathbatch), std::begin(track->Geometry2), std::end(track->Geometry2));
break;
}
case rendermode::shadows:
{
if ((std::abs(track->fTexHeight1) < 0.35f) || ((track->iCategoryFlag == 1) && (track->eType != tt_Normal)))
{
// shadows are only calculated for high enough trackbeds
continue;
}
if( Material( track->m_material2 ).shadow_rank > Global.gfx_shadow_rank_cutoff ) {
// skip if the shadow caster rank is too low for currently set threshold
continue;
}
Bind_Material_Shadow(track->m_material2);
draw(std::begin(track->Geometry2), std::end(track->Geometry2));
break;
}
case rendermode::pickscenery: // pick scenery mode uses piece-by-piece approach
case rendermode::pickcontrols:
default:
{
break;
}
}
}
flush_batch();
// third pass, material 3
for (auto first{First}; first != Last; ++first)
{
auto const track{*first};
if (track->eType != tt_Switch)
{
continue;
}
if (track->SwitchExtension->m_material3 == 0)
{
continue;
}
if (false == track->m_visible)
{
continue;
}
if (editor_ballast_hidden(track, m_renderpass.draw_mode == rendermode::color))
{
continue;
}
switch (m_renderpass.draw_mode)
{
case rendermode::color:
case rendermode::reflections:
{
if (track->eEnvironment != e_flat)
{
flush_batch();
setup_environment_light(track->eEnvironment);
Bind_Material(track->SwitchExtension->m_material3);
draw(track->SwitchExtension->Geometry3);
// restore default lighting
setup_environment_light();
break;
}
begin_batch(track->SwitchExtension->m_material3);
m_pathbatch.emplace_back(track->SwitchExtension->Geometry3);
break;
}
case rendermode::shadows:
{
if ((std::abs(track->fTexHeight1) < 0.35f) || ((track->iCategoryFlag == 1) && (track->eType != tt_Normal)))
{
// shadows are only calculated for high enough trackbeds
continue;
}
if( Material( track->m_material2 ).shadow_rank > Global.gfx_shadow_rank_cutoff ) {
// skip if the shadow caster rank is too low for currently set threshold
continue;
}
Bind_Material_Shadow(track->SwitchExtension->m_material3);
draw(track->SwitchExtension->Geometry3);
break;
}
case rendermode::pickscenery: // pick scenery mode uses piece-by-piece approach
case rendermode::pickcontrols:
default:
{
break;
}
}
}
flush_batch();
// cut faces of rails, in matte variants of the rail materials
if ((m_renderpass.draw_mode == rendermode::color) || (m_renderpass.draw_mode == rendermode::reflections))
{
for (auto first{First}; first != Last; ++first)
{
auto const track{*first};
if (false == track->m_visible)
{
continue;
}
Render_cuts(track, batchmaterial);
}
flush_batch();
}
// fourth pass: per-track sleeper models (sleepermodel optional directive).
// drawn after rails/trackbeds so depth pre-pass culling is favourable, and only in passes
// where Render_Sleepers actually does work (it gates itself on draw mode / distance).
switch( m_renderpass.draw_mode ) {
case rendermode::color:
case rendermode::reflections: {
if( editor_sleepers_hidden() ) { break; }
for( auto first { First }; first != Last; ++first ) {
auto *track = *first;
if( false == track->m_visible ) { continue; }
if( false == track->m_sleeper_enabled ) { continue; }
// a track with the sleepers and timbers of eu07.ini lays its sleeper model there
if( track->m_sleepers3d.active ) { continue; }
Render_Sleepers( track );
}
if( m_renderpass.draw_mode == rendermode::color ) {
Render_Timbers( First, Last );
}
break;
}
case rendermode::shadows: {
Render_Timbers( First, Last );
break;
}
default:
break;
}
// post-render reset
switch (m_renderpass.draw_mode)
{
case rendermode::shadows:
{
// restore standard face cull mode
::glEnable(GL_CULL_FACE);
break;
}
default:
{
break;
}
}
}
void opengl33_renderer::Render(TMemCell *Memcell)
{
::glPushMatrix();
auto const position = Memcell->location() - m_renderpass.pass_camera.position();
::glTranslated(position.x, position.y + 0.5, position.z);
switch (m_renderpass.draw_mode)
{
case rendermode::color:
{
break;
}
case rendermode::shadows:
case rendermode::pickscenery:
{
break;
}
case rendermode::reflections:
case rendermode::pickcontrols:
{
break;
}
default:
{
break;
}
}
::glPopMatrix();
}
void opengl33_renderer::Render_particles()
{
model_ubs.set_modelview(OpenGLMatrices.data(GL_MODELVIEW));
model_ubo->update(model_ubs);
Bind_Texture(0, m_smoketexture);
m_particlerenderer.update(m_renderpass.pass_camera);
m_renderpass.draw_stats.particles = m_particlerenderer.render();
}
void opengl33_renderer::Render_vr_models()
{
if (!vr)
return;
glDebug("Render_vr_models");
::glPushMatrix();
glm::dmat4 tmpmat;
Global.pCamera.SetMatrix(tmpmat);
tmpmat = glm::dmat3(tmpmat);
glMultMatrixd(glm::value_ptr(glm::inverse(tmpmat)));
std::vector<TModel3d*> list = vr->get_render_models();
material_data data;
for (TModel3d *mdl : list)
Render(mdl, &data, 0.0);
::glPopMatrix();
}
void opengl33_renderer::Render_precipitation()
{
if (Global.Overcast <= 1.f)
{
return;
}
::glPushMatrix();
// tilt the precipitation cone against the velocity vector for crude motion blur
// include current wind vector while at it
auto const velocity {
simulation::Environment.m_precipitation.m_cameramove * -1.0
+ glm::dvec3{ simulation::Environment.wind() } * 0.5 };
if (glm::length2(velocity) > 0.0)
{
auto const forward{glm::normalize(velocity)};
auto left{glm::cross(forward, {0.0, 1.0, 0.0})};
auto const rotationangle{std::min(45.0, ((FreeFlyModeFlag || simulation::Train == nullptr) ?
5 * glm::length(velocity) : simulation::Train->Dynamic()->GetVelocity() * 0.2))};
::glRotated(rotationangle, left.x, 0.0, left.z);
}
if (false == FreeFlyModeFlag)
{
// counter potential vehicle roll
auto const roll{0.5 * glm::degrees(simulation::Train->Dynamic()->Roll())};
if (roll != 0.0)
{
auto const forward{simulation::Train->Dynamic()->VectorFront()};
auto const vehicledirection = simulation::Train->Dynamic()->DirectionGet();
::glRotated(roll, forward.x, 0.0, forward.z);
}
}
if (!Global.iPause)
{
if (Global.Weather == "rain:")
// oddly enough random streaks produce more natural looking rain than ones the eye can follow
m_precipitationrotation = LocalRandom() * 360;
else
m_precipitationrotation = 0.0;
}
::glRotated(m_precipitationrotation, 0.0, 1.0, 0.0);
model_ubs.set_modelview(OpenGLMatrices.data(GL_MODELVIEW));
model_ubs.param[0] = glm::mix(0.5f * (Global.DayLight.diffuse + Global.DayLight.ambient), colors::white, 0.5f * std::clamp((float)Global.fLuminance, 0.f, 1.f));
model_ubs.param[1].x = simulation::Environment.m_precipitation.get_textureoffset();
model_ubo->update(model_ubs);
m_precipitationrenderer.update();
m_precipitationrenderer.render();
::glPopMatrix();
}
void opengl33_renderer::Render_Alpha(scene::basic_region *Region)
{
// sort the nodes based on their distance to viewer
std::sort(std::begin(m_cellqueue), std::end(m_cellqueue), [](distancecell_pair const &Left, distancecell_pair const &Right) { return (Left.first) < (Right.first); });
Render_Alpha(std::rbegin(m_cellqueue), std::rend(m_cellqueue));
}
void opengl33_renderer::Render_Alpha(cell_sequence::reverse_iterator First, cell_sequence::reverse_iterator Last)
{
// NOTE: this method is launched only during color pass therefore we don't bother with mode test here
// the cells far off with the tracks alone drawn there have nothing translucent drawn either
auto const scenery_limit{static_cast<double>(Global.BaseDrawRange) * Global.fDistanceFactor + 250.0};
bool const far_paths{EditorModeFlag && Global.editor_tracks};
glm::dvec3 const camera{m_renderpass.pass_camera.position()};
auto const distant = [&](scene::basic_cell const *Cell) { return editor_far_tracks_only(far_paths, Cell->m_area, camera, scenery_limit); };
// first pass draws elements which we know are located in section banks, to reduce vbo switching
{
auto first{First};
while (first != Last)
{
auto const *cell = first->second;
if (false == cell->m_shapestranslucent.empty() && false == distant(cell))
{
// since all shapes of the cell share center point we can optimize out a few calls here
::glPushMatrix();
auto const originoffset{cell->m_area.center - m_renderpass.pass_camera.position()};
::glTranslated(originoffset.x, originoffset.y, originoffset.z);
// render
// NOTE: we can reuse the method used to draw opaque geometry
for (auto const &shape : cell->m_shapestranslucent)
{
Render(shape, false);
}
// post-render cleanup
::glPopMatrix();
}
++first;
}
}
// second pass draws elements with their own vbos
{
auto first{First};
while (first != Last)
{
auto const *cell = first->second;
if (distant(cell))
{
++first;
continue;
}
// translucent parts of instanced models
for (auto *instance : cell->m_instancetranslucent)
{
Render_Alpha(instance);
}
// translucent parts of vehicles
for (auto *path : cell->m_paths)
{
for (auto *dynamic : path->Dynamics)
{
Render_Alpha(dynamic);
}
}
++first;
}
}
// third pass draws the wires;
// wires use section vbos, but for the time being we want to draw them at the very end
{
auto first{First};
while (first != Last)
{
auto const *cell = first->second;
if ((false == cell->m_traction.empty() || (false == cell->m_lines.empty())) && false == distant(cell))
{
// since all shapes of the cell share center point we can optimize out a few calls here
::glPushMatrix();
auto const originoffset{cell->m_area.center - m_renderpass.pass_camera.position()};
::glTranslated(originoffset.x, originoffset.y, originoffset.z);
Bind_Material(null_handle);
// render
for (auto *traction : cell->m_traction)
{
Render_Alpha(traction);
}
for (auto &lines : cell->m_lines)
{
Render_Alpha(lines);
}
// post-render cleanup
::glPopMatrix();
}
++first;
}
}
}
void opengl33_renderer::Render_Alpha(TAnimModel *Instance)
{
if (false == Instance->m_visible) { return; }
if( false == m_renderpass.pass_camera.visible( Instance->m_area ) ) { return; }
double distancesquared;
switch (m_renderpass.draw_mode)
{
case rendermode::shadows:
{
// 'camera' for the light pass is the light source, but we need to draw what the 'real' camera sees
distancesquared = glm::length2((Instance->location() - m_renderpass.viewport_camera.position()) / (double)Global.ZoomFactor) / Global.fDistanceFactor;
break;
}
default:
{
distancesquared = glm::length2((Instance->location() - m_renderpass.pass_camera.position()) / (double)Global.ZoomFactor) / Global.fDistanceFactor;
break;
}
}
if ((distancesquared < Instance->m_rangesquaredmin) || (distancesquared >= Instance->m_rangesquaredmax))
{
return;
}
// crude way to reject early items too far to affect the output (mostly relevant for shadow passes)
auto const drawdistancethreshold{ m_renderpass.draw_range + 250 };
if( distancesquared > sq(drawdistancethreshold) ) {
return;
}
// second stage visibility cull, reject modelstoo far away to be noticeable
auto const radiussquared { Instance->radius() * Instance->radius() };
if( radiussquared * Global.ZoomFactor / distancesquared < 0.003 * 0.003 ) {
return;
}
Instance->RaPrepare();
if (Instance->pModel)
{
auto const &scale = Instance->Scale();
bool const scaled = ( scale.x != 1.0f || scale.y != 1.0f || scale.z != 1.0f );
if( scaled ) {
// scaled instance: build the per-instance transform locally and call
// the distance-only Render_Alpha so we can inject glScalef before
// the submodel walk. Mirror of the opaque path in Render(TAnimModel*).
::glPushMatrix();
auto const Position = Instance->location() - m_renderpass.pass_camera.position();
auto const Angle = Instance->vAngle;
::glTranslated( Position.x, Position.y, Position.z );
if( Angle.y != 0.0 ) ::glRotated( Angle.y, 0.f, 1.f, 0.f );
if( Angle.x != 0.0 ) ::glRotated( Angle.x, 1.f, 0.f, 0.f );
if( Angle.z != 0.0 ) ::glRotated( Angle.z, 0.f, 0.f, 1.f );
::glScalef( scale.x, scale.y, scale.z );
Render_Alpha( Instance->pModel, Instance->Material(), distancesquared );
::glPopMatrix();
}
else {
Render_Alpha(Instance->pModel, Instance->Material(), distancesquared, Instance->location() - m_renderpass.pass_camera.position(), Instance->vAngle);
}
}
}
void opengl33_renderer::Render_Alpha(TTraction *Traction)
{
glDebug("Render_Alpha TTraction");
auto const distancesquared { glm::length2( ( Traction->location() - m_renderpass.pass_camera.position() ) / (double)Global.ZoomFactor ) / Global.fDistanceFactor };
if ((distancesquared < Traction->m_rangesquaredmin) || (distancesquared >= Traction->m_rangesquaredmax))
{
return;
}
if (false == Traction->m_visible)
{
return;
}
// rysuj jesli sa druty i nie zerwana
if ((Traction->Wires == 0) || (true == TestFlag(Traction->DamageFlag, 128)))
{
return;
}
// setup
auto const distance{static_cast<float>(std::sqrt(distancesquared))};
auto const linealpha = 20.f * Traction->WireThickness / std::max(0.5f * Traction->radius() + 1.f, distance - (0.5f * Traction->radius()));
if (m_widelines_supported)
glLineWidth(std::clamp(0.5f * linealpha + Traction->WireThickness * Traction->radius() / 1000.f, 1.f, 1.75f));
// render
// McZapkie-261102: kolor zalezy od materialu i zasniedzenia
model_ubs.param[0] = glm::vec4(Traction->wire_color(), glm::min(1.0f, linealpha));
if (m_renderpass.draw_mode == rendermode::shadows)
Bind_Material_Shadow(null_handle);
else
m_line_shader->bind();
draw(Traction->m_geometry);
// debug data
++m_renderpass.draw_stats.traction;
++m_renderpass.draw_stats.drawcalls;
if (m_widelines_supported)
glLineWidth(1.0f);
}
void opengl33_renderer::Render_editor_overlay()
{
if (false == EditorModeFlag || EditorOverlay.batches.empty())
return;
glDebug("Render_editor_overlay");
if (m_editor_overlay_revision != EditorOverlay.revision)
{
m_editor_overlay_revision = EditorOverlay.revision;
if (m_editor_overlay_bank == null_handle)
m_editor_overlay_bank = Create_Bank();
auto const &batches{EditorOverlay.batches};
for (std::size_t i = 0; i < batches.size(); ++i)
{
gfx::vertex_array vertices;
vertices.reserve(batches[i].points.size());
for (auto const &point : batches[i].points)
vertices.emplace_back(point, glm::vec3(0.f, 1.f, 0.f), glm::vec2());
gfx::userdata_array userdata;
if (i >= m_editor_overlay_geometry.size())
m_editor_overlay_geometry.emplace_back();
auto &geometry{m_editor_overlay_geometry[i]};
if (geometry != null_handle)
m_geometry.replace(vertices, userdata, geometry);
else if (false == vertices.empty())
geometry = m_geometry.create_chunk(vertices, userdata, m_editor_overlay_bank, batches[i].type);
}
}
::glPushMatrix();
auto const origin{EditorOverlay.origin - m_renderpass.pass_camera.position()};
::glTranslated(origin.x, origin.y, origin.z);
::glDisable(GL_CULL_FACE);
::glDepthMask(GL_FALSE);
m_line_shader->bind();
auto const &batches{EditorOverlay.batches};
for (std::size_t i = 0; i < batches.size() && i < m_editor_overlay_geometry.size(); ++i)
{
if (batches[i].points.empty() || m_editor_overlay_geometry[i] == null_handle)
continue;
model_ubs.param[0] = batches[i].color;
draw(m_editor_overlay_geometry[i]);
++m_renderpass.draw_stats.drawcalls;
}
::glDepthMask(GL_TRUE);
::glEnable(GL_CULL_FACE);
::glPopMatrix();
}
void opengl33_renderer::Render_Alpha(scene::lines_node const &Lines)
{
glDebug("Render_Alpha scene::lines_node");
auto const &data{Lines.data()};
auto const distancesquared { glm::length2( ( data.area.center - m_renderpass.pass_camera.position() ) / (double)Global.ZoomFactor ) / Global.fDistanceFactor };
if ((distancesquared < data.rangesquared_min) || (distancesquared >= data.rangesquared_max))
{
return;
}
// setup
auto const distance{static_cast<float>(std::sqrt(distancesquared))};
auto const linealpha =
(data.line_width > 0.f ? 10.f * data.line_width / std::max(0.5f * data.area.radius + 1.f, distance - (0.5f * data.area.radius)) : 1.f); // negative width means the lines are always opague
if (m_widelines_supported)
glLineWidth(std::clamp(0.5f * linealpha + data.line_width * data.area.radius / 1000.f, 1.f, 8.f));
model_ubs.param[0] = glm::vec4(glm::vec3(data.lighting.diffuse * m_sunlight.ambient), glm::min(1.0f, linealpha));
if (m_renderpass.draw_mode == rendermode::shadows)
Bind_Material_Shadow(null_handle);
else
m_line_shader->bind();
draw(data.geometry);
++m_renderpass.draw_stats.lines;
++m_renderpass.draw_stats.drawcalls;
if (m_widelines_supported)
glLineWidth(1.0f);
}
bool opengl33_renderer::Render_Alpha(TDynamicObject *Dynamic)
{
if (!Global.render_cab && Global.pCamera.m_owner == Dynamic)
return false;
if (false == Dynamic->renderme)
{
return false;
}
// setup
TSubModel::iInstance = (size_t)Dynamic; //żeby nie robić cudzych animacji
TSubModel::iVariantSeed = Dynamic->variant_seed();
glm::dvec3 const originoffset = Dynamic->vPosition - m_renderpass.pass_camera.position();
// lod visibility ranges are defined for base (x 1.0) viewing distance. for render we adjust them for actual range multiplier and zoom
float squaredistance;
switch (m_renderpass.draw_mode)
{
case rendermode::shadows:
default:
{
squaredistance = glm::length2(glm::vec3{originoffset} / Global.ZoomFactor);
break;
}
}
Dynamic->ABuLittleUpdate(squaredistance); // ustawianie zmiennych submodeli dla wspólnego modelu
glm::mat4 future_stack = model_ubs.future;
glm::mat4 mv = OpenGLMatrices.data(GL_MODELVIEW);
model_ubs.future *= glm::translate(mv, glm::vec3(Dynamic->get_future_movement())) * glm::inverse(mv);
::glPushMatrix();
::glTranslated(originoffset.x, originoffset.y, originoffset.z);
::glMultMatrixd(glm::value_ptr(Dynamic->mMatrix));
if (Dynamic->fShade > 0.0f)
{
// change light level based on light level of the occupied track
setup_sunlight_intensity(Dynamic->fShade);
}
// render
if( Dynamic->mdLowPolyInt ) {
// low poly interior
Render_Alpha( Dynamic->mdLowPolyInt, Dynamic->Material(), squaredistance );
}
if( Dynamic->mdModel ) {
// main model
Render_Alpha( Dynamic->mdModel, Dynamic->Material(), squaredistance );
}
// optional attached models
for( auto *attachment : Dynamic->mdAttachments ) {
Render_Alpha( attachment, Dynamic->Material(), squaredistance );
}
// optional coupling adapters
Render_coupler_adapter( Dynamic, squaredistance, end::front, true );
Render_coupler_adapter( Dynamic, squaredistance, end::rear, true );
if( Dynamic->mdLoad ) {
// renderowanie nieprzezroczystego ładunku
Render_Alpha( Dynamic->mdLoad, Dynamic->Material(), squaredistance, { 0.f, Dynamic->LoadOffset, 0.f }, {} );
}
// post-render cleanup
if (Dynamic->fShade > 0.0f)
{
// restore regular light level
setup_sunlight_intensity();
}
::glPopMatrix();
model_ubs.future = future_stack;
if (Dynamic->btnOn)
Dynamic->TurnOff(); // przywrócenie domyślnych pozycji submodeli
return true;
}
bool opengl33_renderer::Render_Alpha(TModel3d *Model, material_data const *Material, float const Squaredistance)
{
auto alpha = (Material != nullptr ? Material->textures_alpha : 0x30300030);
if (0 == (alpha & Model->iFlags & 0x2F2F002F))
{
// nothing to render
return false;
}
Model->Root->fSquareDist = Squaredistance; // zmienna globalna!
// setup
Model->Root->ReplacableSet((Material != nullptr ? Material->replacable_skins : nullptr), alpha);
Model->Root->pRoot = Model;
// render
Render_Alpha(Model->Root);
// post-render cleanup
return true;
}
bool opengl33_renderer::Render_Alpha(TModel3d *Model, material_data const *Material, float const Squaredistance, glm::dvec3 const &Position, glm::vec3 const &Angle)
{
::glPushMatrix();
::glTranslated(Position.x, Position.y, Position.z);
if (Angle.y != 0.0)
::glRotated(Angle.y, 0.f, 1.f, 0.f);
if (Angle.x != 0.0)
::glRotated(Angle.x, 1.f, 0.f, 0.f);
if (Angle.z != 0.0)
::glRotated(Angle.z, 0.f, 0.f, 1.f);
auto const result = Render_Alpha(Model, Material, Squaredistance); // position is effectively camera offset
::glPopMatrix();
return result;
}
// characters of a text display, laid out in a row. the text can be encoded in utf-8 or in windows-1250
void opengl33_renderer::Render_Alpha_text(TSubModel *Submodel)
{
if (TSubModel::pasText == nullptr)
{
return;
}
for (auto *p : Submodel->text_letters(*TSubModel::pasText))
{ // translucent only, for the time being
Render_Alpha(p);
if (p->fMatrix)
::glMultMatrixf(p->fMatrix->readArray()); // move on to the place of the next character
}
}
void opengl33_renderer::Render_Alpha(TSubModel *Submodel)
{
// renderowanie przezroczystych przez DL
if ((Submodel->iVisible) && (TSubModel::fSquareDist >= Submodel->fSquareMinDist) && (TSubModel::fSquareDist < Submodel->fSquareMaxDist) && (false == m_previewing || Submodel->fVisible > 0.f))
{
glm::mat4 future_stack = model_ubs.future;
if (Submodel->iFlags & 0xC000)
{
::glPushMatrix();
if (Submodel->fMatrix)
::glMultMatrixf(Submodel->fMatrix->readArray());
if (Submodel->b_aAnim != TAnimType::at_None)
{
Submodel->RaAnimation(Submodel->b_aAnim);
glm::mat4 mv = OpenGLMatrices.data(GL_MODELVIEW);
model_ubs.future *= (mv * Submodel->future_transform) * glm::inverse(mv);
}
}
if (Submodel->eType < TP_ROTATOR)
{
// renderowanie obiektów OpenGL
if (Submodel->iAlpha & Submodel->iFlags & 0x2F)
{
// rysuj gdy element przezroczysty
// debug data
++m_renderpass.draw_stats.submodels;
++m_renderpass.draw_stats.drawcalls;
switch (m_renderpass.draw_mode)
{
case rendermode::color:
{
// material configuration:
// textures...
if (Submodel->m_material < 0)
{ // zmienialne skóry
Bind_Material(submodel_material(Submodel), Submodel);
}
else
{
Bind_Material(Submodel->m_material, Submodel);
}
// ...luminance
auto const isemissive { ( Submodel->f4Emision.a > 0.f ) && ( Global.fLuminance < Submodel->fLight ) };
if (isemissive)
model_ubs.emission = Submodel->f4Emision.a;
// main draw call
draw(Submodel->m_geometry.handle);
model_ubs.emission = 0.0f;
break;
}
case rendermode::shadows:
{
// skip if the shadow caster rank is too low for currently set threshold
// or if the submodel is hidden (colour pass only fades it out, e.g. inactive seasonal variant)
if( ( Material( Submodel ).shadow_rank > Global.gfx_shadow_rank_cutoff )
|| ( Submodel->fVisible <= 0.f ) )
{
--m_renderpass.draw_stats.submodels;
--m_renderpass.draw_stats.drawcalls;
break;
}
if (Submodel->m_material < 0)
{ // zmienialne skóry
Bind_Material_Shadow(submodel_material(Submodel));
}
else
{
Bind_Material_Shadow(Submodel->m_material);
}
draw(Submodel->m_geometry.handle);
break;
}
default:
{
break;
}
}
}
}
else if (Submodel->eType == TP_FREESPOTLIGHT)
{
// NOTE: we're forced here to redo view angle calculations etc, because this data isn't instanced but stored along with the single mesh
// TODO: separate instance data from reusable geometry
auto const &modelview = OpenGLMatrices.data(GL_MODELVIEW);
auto const lightcenter = modelview * glm::mix(glm::vec4(0.f, 0.f, -0.05f, 1.f), glm::vec4(0.f, 0.f, -0.25f, 1.f),
static_cast<float>(TSubModel::fSquareDist / Submodel->fSquareMaxDist)); // pozycja punktu świecącego względem kamery
Submodel->fCosViewAngle = glm::dot(glm::normalize(modelview * glm::vec4(0.f, 0.f, -1.f, 1.f) - lightcenter), glm::normalize(-lightcenter));
if (Global.fLuminance < Submodel->fLight || Global.Overcast > 1.0f)
{
if (Submodel->fCosViewAngle > Submodel->fCosFalloffAngle)
{
// only bother if the viewer is inside the visibility cone
// luminosity at night is at level of ~0.1, so the overall resulting transparency in clear conditions is ~0.5 at full 'brightness'
auto glarelevel{std::clamp(std::max<float>(0.6f - Global.fLuminance, // reduce the glare in bright daylight
Global.Overcast - 1.f), // ensure some glare in rainy/foggy conditions
0.f, 1.f)};
// view angle attenuation
float const anglefactor{std::clamp((Submodel->fCosViewAngle - Submodel->fCosFalloffAngle) / (Submodel->fCosHotspotAngle - Submodel->fCosFalloffAngle), 0.f, 1.f)};
glarelevel *= anglefactor;
if (glarelevel > 0.0f)
{
glDisable(GL_DEPTH_TEST);
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
::glPushMatrix();
::glLoadIdentity(); // macierz jedynkowa
::glTranslatef(lightcenter.x, lightcenter.y, lightcenter.z); // początek układu zostaje bez zmian
::glRotated(std::atan2(lightcenter.x, lightcenter.z) * 180.0 / M_PI, 0.0, 1.0, 0.0); // jedynie obracamy w pionie o kąt
auto const lightcolor = glm::vec3(Submodel->DiffuseOverride.r < 0.f ? // -1 indicates no override
Submodel->f4Diffuse :
Submodel->DiffuseOverride);
m_billboard_shader->bind();
Bind_Texture(0, m_glaretexture);
model_ubs.param[0] = glm::vec4(glm::vec3(lightcolor), Submodel->fVisible * glarelevel);
// main draw call
if (Submodel->occlusion_query) {
if (!Global.gfx_usegles) {
glBeginConditionalRender(*Submodel->occlusion_query, GL_QUERY_WAIT);
draw(m_billboardgeometry);
glEndConditionalRender();
}
else {
auto result = Submodel->occlusion_query->result();
if (result && *result)
draw(m_billboardgeometry);
}
}
else
draw(m_billboardgeometry);
glEnable(GL_DEPTH_TEST);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
::glPopMatrix();
}
}
}
if (Submodel->fCosViewAngle > Submodel->fCosFalloffAngle)
{
// kąt większy niż maksymalny stożek swiatła
float lightlevel = 1.f; // TODO, TBD: parameter to control light strength
// view angle attenuation
float const anglefactor = std::clamp((Submodel->fCosViewAngle - Submodel->fCosFalloffAngle) / (Submodel->fCosHotspotAngle - Submodel->fCosFalloffAngle), 0.f, 1.f);
lightlevel *= anglefactor;
// distance attenuation. NOTE: since it's fixed pipeline with built-in gamma correction we're using linear attenuation
// we're capping how much effect the distance attenuation can have, otherwise the lights get too tiny at regular distances
float const distancefactor{std::max(0.5f, (Submodel->fSquareMaxDist - TSubModel::fSquareDist) / Submodel->fSquareMaxDist)};
auto const pointsize{std::max(3.f, 5.f * distancefactor * anglefactor)};
// additionally reduce light strength for farther sources in rain or snow
if (Global.Overcast > 0.75f)
{
float const precipitationfactor{std::lerp(std::lerp(1.f, 0.25f, std::clamp(Global.Overcast * 0.75f - 0.5f, 0.f, 1.f)), 1.f, distancefactor)};
lightlevel *= precipitationfactor;
}
if (lightlevel > 0.f)
{
::glPushMatrix();
::glLoadIdentity();
::glTranslatef(lightcenter.x, lightcenter.y, lightcenter.z); // początek układu zostaje bez zmian
// material configuration:
// limit impact of dense fog on the lights
auto const lightrange { std::max<float>( 500, m_fogrange * 2 ) }; // arbitrary, visibility at least 500m
model_ubs.fog_density = 1.0 / lightrange;
// main draw call
model_ubs.emission = 1.0f;
auto lightcolor = glm::vec3(Submodel->DiffuseOverride.r < 0.f ? // -1 indicates no override
Submodel->f4Diffuse :
Submodel->DiffuseOverride);
m_freespot_shader->bind();
if (Global.Overcast > 1.0f)
{
// fake fog halo
float const fogfactor{std::lerp(1.5f, 1.f, std::clamp(Global.fFogEnd / 2000, 0.f, 1.f)) * std::max(1.f, Global.Overcast)};
model_ubs.param[1].x = pointsize * fogfactor * 4.0f;
model_ubs.param[0] = glm::vec4(glm::vec3(lightcolor), Submodel->fVisible * std::min(1.f, lightlevel) * 0.5f);
draw(Submodel->m_geometry.handle);
}
model_ubs.param[1].x = pointsize * 4.0f;
model_ubs.param[0] = glm::vec4(glm::vec3(lightcolor), Submodel->fVisible * std::min(1.f, lightlevel));
if (gl::vao::use_vao) {
if (!Submodel->occlusion_query)
Submodel->occlusion_query.emplace(gl::query::ANY_SAMPLES_PASSED);
Submodel->occlusion_query->begin();
}
draw(Submodel->m_geometry.handle);
if (gl::vao::use_vao)
Submodel->occlusion_query->end();
// post-draw reset
model_ubs.emission = 0.0f;
model_ubs.fog_density = 1.0f / m_fogrange;
::glPopMatrix();
}
}
}
if (Submodel->Child != nullptr)
{
if (Submodel->eType == TP_TEXT)
{ // tekst renderujemy w specjalny sposób, zamiast submodeli z łańcucha Child
Render_Alpha_text(Submodel);
}
else if (Submodel->iAlpha & Submodel->iFlags & 0x002F0000)
Render_Alpha(Submodel->Child);
}
if (Submodel->iFlags & 0xC000)
{
model_ubs.future = future_stack;
::glPopMatrix();
}
}
/*
if( Submodel->b_aAnim < at_SecondsJump )
Submodel->b_aAnim = at_None; // wyłączenie animacji dla kolejnego użycia submodelu
*/
if (Submodel->Next != nullptr)
if (Submodel->iAlpha & Submodel->iFlags & 0x2F000000)
Render_Alpha(Submodel->Next);
};
bool opengl33_renderer::Debug_Ui_State(std::optional<bool> param)
{
if (param) {
debug_ui_active = *param;
}
return debug_ui_active;
}
// utility methods
void opengl33_renderer::Update_Pick_Control()
{
if (!m_picking_pbo->is_busy())
{
unsigned char pickreadout[4];
if (m_picking_pbo->read_data(1, 1, pickreadout))
{
auto const controlindex = pick_index(glm::ivec3{pickreadout[0], pickreadout[1], pickreadout[2]});
TSubModel const *control{nullptr};
glm::vec2 position(0.0f);
if ((controlindex > 0) && (controlindex <= m_pickcontrolsitems.size())) {
control = m_pickcontrolsitems[controlindex - 1];
} else if (255 - pickreadout[0] < m_picksurfaceitems.size()) {
control = m_picksurfaceitems[255 - pickreadout[0]];
position.x = pickreadout[1] / 255.0f;
position.y = pickreadout[2] / 255.0f;
}
m_pickcontrolitem = control;
for (auto f : m_control_pick_requests)
f(m_pickcontrolitem, position);
m_control_pick_requests.clear();
}
if (!m_control_pick_requests.empty())
{
glm::vec2 mousepos = Global.cursor_pos;
mousepos.y = Global.window_size.y - mousepos.y; // cursor coordinates are flipped compared to opengl
glm::ivec2 pickbufferpos;
pickbufferpos = glm::ivec2(mousepos * glm::vec2(EU07_PICKBUFFERSIZE) / glm::vec2(Global.window_size));
if (vr)
pickbufferpos = glm::ivec2(EU07_PICKBUFFERSIZE / 2 + 1, EU07_PICKBUFFERSIZE / 2 + 1);
pickbufferpos = glm::clamp(pickbufferpos, glm::ivec2(0, 0), glm::ivec2(EU07_PICKBUFFERSIZE - 1, EU07_PICKBUFFERSIZE - 1));
Render_pass(*m_viewports.front().get(), rendermode::pickcontrols);
m_pick_fb->bind();
m_picking_pbo->request_read(pickbufferpos.x, pickbufferpos.y, 1, 1);
m_pick_fb->unbind();
}
}
}
void opengl33_renderer::Update_Pick_Node()
{
if (!m_picking_node_pbo->is_busy())
{
unsigned char pickreadout[4];
if (m_picking_node_pbo->read_data(1, 1, pickreadout))
{
auto const nodeindex = pick_index(glm::ivec3{pickreadout[0], pickreadout[1], pickreadout[2]});
scene::basic_node *node{nullptr};
if ((nodeindex > 0) && (nodeindex <= m_picksceneryitems.size()))
{
node = m_picksceneryitems[nodeindex - 1];
}
m_picksceneryitem = node;
for (auto f : m_node_pick_requests)
f(m_picksceneryitem);
m_node_pick_requests.clear();
}
if (!m_node_pick_requests.empty())
{
// determine point to examine
glm::vec2 mousepos = Global.cursor_pos;
mousepos.y = Global.window_size.y - mousepos.y; // cursor coordinates are flipped compared to opengl
glm::ivec2 pickbufferpos;
pickbufferpos = glm::ivec2(mousepos * glm::vec2(EU07_PICKBUFFERSIZE) / glm::vec2(Global.window_size));
pickbufferpos = glm::clamp(pickbufferpos, glm::ivec2(0, 0), glm::ivec2(EU07_PICKBUFFERSIZE - 1, EU07_PICKBUFFERSIZE - 1));
Render_pass(*m_viewports.front().get(), rendermode::pickscenery);
m_pick_fb->bind();
m_picking_node_pbo->request_read(pickbufferpos.x, pickbufferpos.y, 1, 1);
m_pick_fb->unbind();
}
}
}
void opengl33_renderer::Pick_Control_Callback(std::function<void(TSubModel const *, const glm::vec2 pos)> callback)
{
if (!Global.render_cab) {
callback(nullptr, glm::vec2());
return;
}
m_control_pick_requests.push_back(callback);
}
void opengl33_renderer::Pick_Node_Callback(std::function<void(scene::basic_node *)> callback)
{
m_node_pick_requests.push_back(callback);
}
void opengl33_renderer::Forget_Node(scene::basic_node const *Node)
{
if (m_picksceneryitem == Node)
m_picksceneryitem = nullptr;
std::ranges::replace_if(m_picksceneryitems, [Node](scene::basic_node const *Item) { return Item == Node; }, nullptr);
}
glm::dvec3 opengl33_renderer::Update_Mouse_Position()
{
if (!m_depth_pointer_pbo->is_busy())
{
// determine point to examine
glm::vec2 mousepos = Global.cursor_pos;
mousepos.y = Global.window_size.y - mousepos.y; // cursor coordinates are flipped compared to opengl
glm::ivec2 bufferpos;
bufferpos = glm::ivec2(mousepos * glm::vec2(Global.gfx_framebuffer_width, Global.gfx_framebuffer_height) / glm::vec2(Global.window_size));
bufferpos = glm::clamp(bufferpos, glm::ivec2(0, 0), glm::ivec2(Global.gfx_framebuffer_width - 1, Global.gfx_framebuffer_height - 1));
float pointdepth = std::numeric_limits<float>::max();
if (!Global.gfx_usegles)
{
m_depth_pointer_pbo->read_data(1, 1, &pointdepth, 4);
if (!Global.iMultisampling)
{
m_depth_pointer_pbo->request_read(bufferpos.x, bufferpos.y, 1, 1, 4, GL_DEPTH_COMPONENT, GL_FLOAT);
}
else if (Global.gfx_skippipeline)
{
gl::framebuffer::blit(nullptr, m_depth_pointer_fb.get(), bufferpos.x, bufferpos.y, 1, 1, GL_DEPTH_BUFFER_BIT, 0);
m_depth_pointer_fb->bind();
m_depth_pointer_pbo->request_read(0, 0, 1, 1, 4, GL_DEPTH_COMPONENT, GL_FLOAT);
m_depth_pointer_fb->unbind();
}
else
{
gl::framebuffer::blit(m_viewports.front()->msaa_fb.get(), m_depth_pointer_fb.get(), bufferpos.x, bufferpos.y, 1, 1, GL_DEPTH_BUFFER_BIT, 0);
m_depth_pointer_fb->bind();
m_depth_pointer_pbo->request_read(0, 0, 1, 1, 4, GL_DEPTH_COMPONENT, GL_FLOAT);
m_viewports.front()->msaa_fb->bind();
}
}
else
{
unsigned int data[4];
if (m_depth_pointer_pbo->read_data(1, 1, data, 16))
pointdepth = (double)data[0] / 65535.0;
if (Global.gfx_skippipeline)
{
gl::framebuffer::blit(nullptr, m_depth_pointer_fb.get(), 0, 0, Global.gfx_framebuffer_width, Global.gfx_framebuffer_height, GL_DEPTH_BUFFER_BIT, 0);
m_empty_vao->bind();
m_depth_pointer_tex->bind(0);
m_depth_pointer_shader->bind();
m_depth_pointer_fb2->bind();
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
m_depth_pointer_pbo->request_read(bufferpos.x, bufferpos.y, 1, 1, 16, GL_RGBA_INTEGER, GL_UNSIGNED_INT);
m_depth_pointer_shader->unbind();
m_empty_vao->unbind();
m_depth_pointer_fb2->unbind();
}
else
{
gl::framebuffer::blit(m_viewports.front()->msaa_fb.get(), m_depth_pointer_fb.get(), 0, 0, Global.gfx_framebuffer_width, Global.gfx_framebuffer_height, GL_DEPTH_BUFFER_BIT, 0);
m_empty_vao->bind();
m_depth_pointer_tex->bind(0);
m_depth_pointer_shader->bind();
m_depth_pointer_fb2->bind();
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
m_depth_pointer_pbo->request_read(bufferpos.x, bufferpos.y, 1, 1, 16, GL_RGBA_INTEGER, GL_UNSIGNED_INT);
m_depth_pointer_shader->unbind();
m_empty_vao->unbind();
m_viewports.front()->msaa_fb->bind();
}
}
if (pointdepth != std::numeric_limits<float>::max())
{
m_mousehit = (GLAD_GL_ARB_clip_control || GLAD_GL_EXT_clip_control) ? pointdepth > 0.0f : pointdepth < 1.0f;
if (GLAD_GL_ARB_clip_control || GLAD_GL_EXT_clip_control) {
if (pointdepth > 0.0f)
m_worldmousecoordinates = glm::unProjectZO(glm::vec3(bufferpos, pointdepth), glm::mat4(glm::mat3(m_colorpass.pass_camera.modelview())), m_colorpass.pass_camera.projection(),
glm::vec4(0, 0, Global.gfx_framebuffer_width, Global.gfx_framebuffer_height));
} else if (pointdepth < 1.0f)
m_worldmousecoordinates = glm::unProjectNO(glm::vec3(bufferpos, pointdepth), glm::mat4(glm::mat3(m_colorpass.pass_camera.modelview())), m_colorpass.pass_camera.projection(),
glm::vec4(0, 0, Global.gfx_framebuffer_width, Global.gfx_framebuffer_height));
}
}
return m_colorpass.pass_camera.position() + glm::dvec3{m_worldmousecoordinates};
}
void opengl33_renderer::Update(double const Deltatime)
{
Update_Pick_Control();
Update_Pick_Node();
m_updateaccumulator += Deltatime;
if (m_updateaccumulator < 1.0)
{
// too early for any work
return;
}
m_updateaccumulator = 0.0;
// the frames actually shown, the wait for fpslimit included (eu07/maszyna#416)
m_framerate = 1000.f / ( Timer::subsystem.mainloop_period.average() );
// the frames the work alone would allow, so a frame rate held down by fpslimit doesn't cut the draw ranges
auto const workframerate{1000.f / Timer::subsystem.mainloop_total.average()};
// adjust draw ranges etc, based on recent performance
if (Global.targetfps != 0.0f) {
float fps_diff = Global.targetfps - workframerate;
if (fps_diff > 0.0f)
Global.fDistanceFactor = std::max(0.5f, Global.fDistanceFactor - 0.05f);
else
Global.fDistanceFactor = std::min(Global.gfx_distance_factor_max, Global.fDistanceFactor + 0.05f);
}
// legacy framerate parameters
else if (Global.fFpsAverage != 0.f) {
auto const fps_diff = workframerate - Global.fFpsAverage;
if (fps_diff < -Global.fFpsDeviation) {
Global.fDistanceFactor = std::min(std::max(1.0f, Global.fDistanceFactor - 0.05f), Global.gfx_distance_factor_max);
}
else if (fps_diff > Global.fFpsDeviation) {
Global.fDistanceFactor = std::min(std::min(3.0f, Global.fDistanceFactor + 0.05f), Global.gfx_distance_factor_max);
}
}
if( Global.UpdateMaterials ) {
// update resources if there was environmental change
simulation_state simulationstate {
Global.Weather,
Global.Season
};
std::swap( m_simulationstate, simulationstate );
if( ( m_simulationstate.season != simulationstate.season ) && ( false == simulationstate.season.empty() ) ) {
m_materials.on_season_change();
}
if( ( m_simulationstate.weather != simulationstate.weather ) && ( false == simulationstate.weather.empty() ) ) {
m_materials.on_weather_change();
}
}
if ((true == Global.ResourceSweep) && (true == simulation::is_ready))
{
// garbage collection
m_geometry.update();
m_textures.update();
}
if ((Global.gfx_texture_releasedistance > 0.f) && (true == simulation::is_ready))
{
Update_Texture_Release();
}
if ((true == Global.ControlPicking) && (false == FreeFlyModeFlag))
Pick_Control_Callback([](const TSubModel *, const glm::vec2) {});
// temporary conditions for testing. eventually will be coupled with editor mode
if ((true == Global.ControlPicking) && (true == DebugModeFlag) && (true == FreeFlyModeFlag))
Pick_Node_Callback([](scene::basic_node *) {});
// dump last opengl error, if any
int glerror;
while ((glerror = glGetError()) != GL_NO_ERROR)
{
std::string glerrorstring;
if (glerror == GL_INVALID_ENUM)
glerrorstring = "GL_INVALID_ENUM";
else if (glerror == GL_INVALID_VALUE)
glerrorstring = "GL_INVALID_VALUE";
else if (glerror == GL_INVALID_OPERATION)
glerrorstring = "GL_INVALID_OPERATION";
else if (glerror == GL_OUT_OF_MEMORY)
glerrorstring = "GL_OUT_OF_MEMORY";
else if (glerror == GL_INVALID_FRAMEBUFFER_OPERATION)
glerrorstring = "GL_INVALID_FRAMEBUFFER_OPERATION";
Global.LastGLError = std::to_string(glerror) + " (" + glerrorstring + ")";
}
}
// debug performance string
std::string const &opengl33_renderer::info_times() const
{
return m_debugtimestext;
}
std::string const &opengl33_renderer::info_stats() const
{
return m_debugstatstext;
}
void opengl33_renderer::MakeScreenshot()
{
screenshot_manager::make_screenshot();
}
// model previews
namespace
{
// direction from the previewed model to the camera. models are made facing -z (the front view of 3ds max),
// so the camera looks at their front, right side and top
glm::dvec3 const preview_viewdirection{-0.6123724, 0.5, -0.6123724};
// vertical field of view of the preview camera, in degrees
float const preview_fieldofview{30.f};
// brightness of the hdr background, past the white point of the tonemapping, so translucent parts blend with white
float const preview_background{16.f};
} // namespace
void opengl33_renderer::Preview_Bounds(TSubModel const *Submodel, glm::dmat4 const &Transform, glm::dvec3 &Min, glm::dvec3 &Max) const
{
// same walk as the one of Render(TSubModel *) bar the range checks, which leave out parts only for the bounds to be smaller
for (auto const *submodel{Submodel}; submodel != nullptr; submodel = submodel->Next)
{
if ((submodel->iVisible == 0) || (submodel->fVisible <= 0.f))
{
continue;
}
auto transform{Transform};
if ((submodel->iFlags & 0xC000) && (submodel->fMatrix != nullptr))
{
transform *= glm::dmat4{glm::make_mat4(submodel->fMatrix->readArray())};
}
if ((submodel->eType < TP_ROTATOR) && (submodel->m_geometry.handle != null_handle))
{
for (auto const &vertex : m_geometry.vertices(submodel->m_geometry.handle))
{
auto const point{glm::dvec3{transform * glm::dvec4{glm::dvec3{vertex.position}, 1.0}}};
Min = glm::min(Min, point);
Max = glm::max(Max, point);
}
}
Preview_Bounds(submodel->Child, transform, Min, Max);
}
}
bool opengl33_renderer::Preview_Targets(int const Size)
{
if (m_preview.size == Size)
{
return true;
}
m_preview = preview_targets();
m_preview.hdr_tex = std::make_unique<opengl_texture>();
m_preview.hdr_tex->alloc_rendertarget(GL_RGBA16F, GL_RGBA, Size, Size, 1, 1, GL_CLAMP_TO_EDGE);
m_preview.hdr_rbds = std::make_unique<gl::renderbuffer>();
m_preview.hdr_rbds->alloc(GL_DEPTH32F_STENCIL8, Size, Size);
m_preview.hdr_fb = std::make_unique<gl::framebuffer>();
m_preview.hdr_fb->attach(*m_preview.hdr_tex, GL_COLOR_ATTACHMENT0);
m_preview.hdr_fb->attach(*m_preview.hdr_rbds, GL_DEPTH_STENCIL_ATTACHMENT);
m_preview.hdr_fb->setup_drawing(1);
if (false == m_preview.hdr_fb->is_complete())
{
ErrorLog("preview framebuffer setup failed");
m_preview = preview_targets();
return false;
}
// the tonemapping writes srgb values, either by itself or through the srgb target
m_preview.ldr_tex = std::make_unique<opengl_texture>();
m_preview.ldr_tex->alloc_rendertarget((Global.gfx_shadergamma ? GL_RGBA8 : GL_SRGB8_ALPHA8), GL_RGBA, Size, Size, 1, 1, GL_CLAMP_TO_EDGE);
m_preview.ldr_fb = std::make_unique<gl::framebuffer>();
m_preview.ldr_fb->attach(*m_preview.ldr_tex, GL_COLOR_ATTACHMENT0);
m_preview.ldr_fb->setup_drawing(1);
if (false == m_preview.ldr_fb->is_complete())
{
ErrorLog("preview framebuffer setup failed");
m_preview = preview_targets();
return false;
}
gl::framebuffer::unbind();
m_preview.size = Size;
return true;
}
void opengl33_renderer::Preview_Model(TAnimModel *Instance, float const Squaredistance, bool const Alpha)
{
// the placement of Render(TAnimModel *), without its range and visibility tests
::glPushMatrix();
auto const position{Instance->location() - m_renderpass.pass_camera.position()};
::glTranslated(position.x, position.y, position.z);
auto const &angle{Instance->vAngle};
if (angle.y != 0.0)
::glRotated(angle.y, 0.f, 1.f, 0.f);
if (angle.x != 0.0)
::glRotated(angle.x, 1.f, 0.f, 0.f);
if (angle.z != 0.0)
::glRotated(angle.z, 0.f, 0.f, 1.f);
auto const &scale{Instance->Scale()};
::glScalef(scale.x, scale.y, scale.z);
if (Alpha)
Render_Alpha(Instance->pModel, Instance->Material(), Squaredistance);
else
Render(Instance->pModel, Instance->Material(), Squaredistance);
::glPopMatrix();
}
void opengl33_renderer::Preview_Color(TAnimModel *Instance, float const Squaredistance, int const Size, glm::dvec3 const &Eye, glm::mat4 const &View, glm::mat4 const &Projection, bool const Shadows)
{
m_renderpass.draw_mode = rendermode::color;
m_renderpass.pass_camera.position() = Eye;
m_renderpass.pass_camera.modelview() = View;
m_renderpass.pass_camera.projection() = Projection;
m_renderpass.viewport_camera.position() = Eye;
setup_matrices();
scene_ubs.projection = OpenGLMatrices.data(GL_PROJECTION);
scene_ubs.inv_view = glm::inverse(glm::mat4{glm::mat3{View}});
scene_ubs.time = 0.f;
for (auto idx = 0; idx < m_shadowpass.size(); ++idx)
{
// everything is in the first cascade
scene_ubs.cascade_end[idx] = std::numeric_limits<float>::max();
}
scene_ubo->update(scene_ubs);
scene_ubo->bind_uniform();
// the sun is the only light, and there's no fog
auto const &modelview{OpenGLMatrices.data(GL_MODELVIEW)};
light_ubs.ambient = m_sunlight.ambient;
light_ubs.fog_color = glm::vec3{1.f};
light_ubs.lights_count = 1;
light_ubs.lights[0].type = gl::light_element_ubs::DIR;
light_ubs.lights[0].dir = modelview * glm::vec4(m_sunlight.direction, 0.0f);
light_ubs.lights[0].color = m_sunlight.diffuse;
light_ubs.lights[0].ambient = 0.0f;
light_ubs.lights[0].intensity = 1.0f;
light_ubo->update(light_ubs);
model_ubs.fog_density = 0.f;
model_ubs.future = glm::mat4();
model_ubs.emission = 0.f;
if (Shadows)
{
setup_shadow_bind_map();
setup_shadow_color(colors::shadow);
}
else
{
setup_shadow_unbind_map();
setup_shadow_color(colors::white);
}
setup_env_map(nullptr);
m_preview.hdr_fb->bind();
glViewport(0, 0, Size, Size);
glClearColor(preview_background, preview_background, preview_background, 1.f);
glClearStencil(0);
glStencilMask(0xFF);
m_preview.hdr_fb->clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
if (!Global.gfx_usegles)
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glEnable(GL_DEPTH_TEST);
// every fragment which made it past the alpha test marks the pixel as covered, translucent ones included
glEnable(GL_STENCIL_TEST);
glStencilFunc(GL_ALWAYS, 1, 0xFF);
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
setup_drawing(false);
Preview_Model(Instance, Squaredistance, false);
setup_drawing(true);
Preview_Model(Instance, Squaredistance, true);
setup_drawing(false);
glDisable(GL_STENCIL_TEST);
setup_shadow_unbind_map();
}
bool opengl33_renderer::Render_Preview(TAnimModel *Instance, int const Size, int const Margin, bool const Shadows, std::vector<std::uint8_t> &Image)
{
if ((Instance == nullptr) || (Instance->pModel == nullptr) || (Size <= 0) || (Margin < 0) || (Margin * 2 >= Size))
{
return false;
}
// the image is drawn at double size and scaled down, for antialiased edges which blend with the white background
GLint maxtexturesize{0}, maxrenderbuffersize{0};
GLint maxviewport[2]{0, 0};
glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxtexturesize);
glGetIntegerv(GL_MAX_RENDERBUFFER_SIZE, &maxrenderbuffersize);
glGetIntegerv(GL_MAX_VIEWPORT_DIMS, maxviewport);
auto const maxsize{std::min({maxtexturesize, maxrenderbuffersize, maxviewport[0], maxviewport[1]})};
if (Size > maxsize)
{
ErrorLog("preview size " + std::to_string(Size) + " exceeds the limit of the graphics driver, " + std::to_string(maxsize));
return false;
}
auto const supersampling{(Size * 2 <= maxsize ? 2 : 1)};
auto const targetsize{Size * supersampling};
if (false == Preview_Targets(targetsize))
{
return false;
}
glfwMakeContextCurrent(m_window);
opengl_texture::reset_unit_cache();
gfx::opengl33_vaogeometrybank::reset();
m_previewing = true;
// lights and visibility of the submodels, for this instance
Instance->RaAnimate(m_framestamp);
Instance->RaPrepare();
// bounding sphere of the model, which the camera is placed to fit in its view
glm::dvec3 boundsmin{std::numeric_limits<double>::max()};
glm::dvec3 boundsmax{std::numeric_limits<double>::lowest()};
Preview_Bounds(Instance->pModel->Root, glm::translate(glm::dmat4{1.0}, Instance->location()) * glm::dmat4{Instance->rotation_scale()}, boundsmin, boundsmax);
if (boundsmin.x > boundsmax.x)
{
m_previewing = false;
return false;
}
auto const centre{(boundsmin + boundsmax) * 0.5};
auto const radius{std::max(0.01, glm::length(boundsmax - boundsmin) * 0.5)};
auto const fieldofview{glm::radians(preview_fieldofview)};
auto const distance{radius / std::sin(fieldofview * 0.5)};
auto const eye{centre + glm::normalize(preview_viewdirection) * distance};
glm::mat4 const view{glm::lookAt(eye, centre, glm::dvec3{0.0, 1.0, 0.0})};
// the sphere is given some slack for parts which aren't where their vertices are, like billboards turning to the camera
auto const znear{static_cast<float>(std::max(distance - radius * 1.5, distance * 0.05))};
auto const zfar{static_cast<float>(distance + radius * 1.5)};
auto const projection{perspective_projection_raw(fieldofview, 1.f, znear, zfar)};
// level of detail as seen from the camera, like in Render(TAnimModel *)
auto const squaredistance{static_cast<float>(glm::length2(Instance->location() - eye) / Global.fDistanceFactor)};
// key light from above the left shoulder of the viewer, so the visible sides of the model differ in tone
auto const forward{glm::normalize(centre - eye)};
auto const right{glm::normalize(glm::cross(forward, glm::dvec3{0.0, 1.0, 0.0}))};
auto const tosun{glm::normalize(-forward * 0.4 + glm::dvec3{0.0, 1.0, 0.0} - right * 0.9)};
m_sunlight.direction = glm::vec3{-tosun};
m_sunlight.diffuse = glm::vec4{1.0f, 0.9686275f, 0.9411765f, 1.f};
m_sunlight.ambient = glm::vec4{0.65f, 0.66f, 0.68f, 1.f};
m_sunlight.factor = 1.f;
auto const shadows{Shadows && Global.gfx_shadowmap_enabled && (m_shadow_fb != nullptr)};
if (shadows)
{
// one map covering the whole model, seen from the sun
m_renderpass.draw_mode = rendermode::shadows;
m_renderpass.pass_camera.position() = centre;
m_renderpass.pass_camera.modelview() = glm::mat4{glm::lookAt(centre, centre + glm::dvec3{m_sunlight.direction}, glm::dvec3{0.0, 1.0, 0.0})};
auto const extent{static_cast<float>(radius * 1.5)};
m_renderpass.pass_camera.projection() = ortho_projection(-extent, extent, -extent, extent, -extent, extent);
m_renderpass.viewport_camera.position() = eye;
setup_matrices();
scene_ubs.projection = OpenGLMatrices.data(GL_PROJECTION);
scene_ubo->update(scene_ubs);
glViewport(0, 0, m_shadowbuffersize, m_shadowbuffersize);
m_shadow_fb->attach(*m_shadow_tex, GL_DEPTH_ATTACHMENT, 0);
m_shadow_fb->clear(GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
setup_drawing(false);
Preview_Model(Instance, squaredistance, false);
m_shadow_fb->unbind();
for (auto &pass : m_shadowpass)
{
pass = m_renderpass;
}
}
// the view is cropped to the part of the image the model covers: a look from a bit further first, to find it,
// then a closer one at the full size, as thin parts can show up only there, to refine the crop to a pixel.
// the crop maps the area to the image less the margins
std::vector<std::uint8_t> coverage;
auto const fitsize{targetsize};
auto const area{1.0 - 2.0 * Margin / Size}; // half of the extent of the area for the model, in normalized device coordinates
glm::dvec2 cropcentre{0.0};
auto cropscale{0.75};
auto tight{false}; // whether the crop was fitted to the model
auto const cropped = [&]() {
return glm::mat4{glm::scale(glm::dmat4{1.0}, glm::dvec3{cropscale, cropscale, 1.0}) * glm::translate(glm::dmat4{1.0}, glm::dvec3{-cropcentre, 0.0})} * projection;
};
for (auto attempt = 0; attempt < 6; ++attempt)
{
auto const passsize{(tight ? fitsize : std::min(fitsize, 512))};
Preview_Color(Instance, squaredistance, passsize, eye, view, cropped(), shadows);
coverage.resize(static_cast<std::size_t>(passsize) * passsize);
m_preview.hdr_fb->bind();
glReadPixels(0, 0, passsize, passsize, GL_STENCIL_INDEX, GL_UNSIGNED_BYTE, coverage.data());
glm::ivec2 pixelmin{passsize, passsize}, pixelmax{-1, -1};
for (auto y = 0; y < passsize; ++y)
{
auto const *row{coverage.data() + static_cast<std::size_t>(y) * passsize};
for (auto x = 0; x < passsize; ++x)
{
if (row[x] != 0)
{
pixelmin = glm::min(pixelmin, glm::ivec2{x, y});
pixelmax = glm::max(pixelmax, glm::ivec2{x, y});
}
}
}
if (pixelmax.x < 0)
{
if (attempt == 0)
{
// nothing to see
m_previewing = false;
m_renderpass.draw_mode = rendermode::none;
gl::framebuffer::unbind();
return false;
}
// the crop missed the model, start over with the plain view
cropcentre = glm::dvec2{0.0};
cropscale = 0.5;
tight = false;
continue;
}
// covered area in normalized device coordinates of the uncropped view
auto const tondc = [&](glm::ivec2 const &Pixel) { return (glm::dvec2{-1.0} + 2.0 * glm::dvec2{Pixel} / static_cast<double>(passsize)) / cropscale + cropcentre; };
auto const ndcmin{tondc(pixelmin)};
auto const ndcmax{tondc(pixelmax + 1)};
cropcentre = (ndcmin + ndcmax) * 0.5;
// a model fitted to the area keeps clear of the image edges, unless the margin is too thin to tell
auto const clipped{(pixelmin.x == 0) || (pixelmin.y == 0) || (pixelmax.x == passsize - 1) || (pixelmax.y == passsize - 1)};
if (clipped && ((false == tight) || (Margin * passsize / Size >= 2)))
{
// part of the model is out of the view, look again from further away
cropscale *= 0.5;
tight = false;
continue;
}
cropscale = 2.0 * area / std::max(ndcmax.x - ndcmin.x, ndcmax.y - ndcmin.y);
if (tight)
{
// measured through a fitted crop, which makes it accurate to a pixel of the fitting pass
break;
}
tight = true;
}
// the image itself
Preview_Color(Instance, squaredistance, targetsize, eye, view, cropped(), shadows);
glViewport(0, 0, targetsize, targetsize);
if (!Global.gfx_usegles && !Global.gfx_shadergamma)
glEnable(GL_FRAMEBUFFER_SRGB);
m_pfx_tonemapping->apply(*m_preview.hdr_tex, m_preview.ldr_fb.get());
if (!Global.gfx_usegles && !Global.gfx_shadergamma)
glDisable(GL_FRAMEBUFFER_SRGB);
opengl_texture::reset_unit_cache();
// the post processing binds its own vertex array, which the geometry banks don't know about
gfx::opengl33_vaogeometrybank::reset();
auto const targetpixels{static_cast<std::size_t>(targetsize) * targetsize};
std::vector<std::uint8_t> colors(targetpixels * 4);
m_preview.ldr_fb->bind();
glReadPixels(0, 0, targetsize, targetsize, GL_RGBA, GL_UNSIGNED_BYTE, colors.data());
coverage.resize(targetpixels);
m_preview.hdr_fb->bind();
glReadPixels(0, 0, targetsize, targetsize, GL_STENCIL_INDEX, GL_UNSIGNED_BYTE, coverage.data());
gl::framebuffer::unbind();
glDepthMask(GL_TRUE);
m_previewing = false;
m_renderpass.draw_mode = rendermode::none;
// uncovered pixels are white, the samples are averaged in linear space and the rows flipped to go from the top
static auto const tolinear{[]() {
std::array<float, 256> table;
for (auto idx = 0; idx < 256; ++idx)
{
auto const value{idx / 255.f};
table[idx] = (value <= 0.04045f ? value / 12.92f : std::pow((value + 0.055f) / 1.055f, 2.4f));
}
return table;
}()};
auto const tosrgb = [](float const Value) {
auto const value{std::clamp(Value, 0.f, 1.f)};
auto const encoded{(value <= 0.0031308f ? value * 12.92f : 1.055f * std::pow(value, 1.f / 2.4f) - 0.055f)};
return static_cast<std::uint8_t>(std::lround(encoded * 255.f));
};
auto const samplecount{static_cast<float>(supersampling * supersampling)};
Image.resize(static_cast<std::size_t>(Size) * Size * 3);
for (auto y = 0; y < Size; ++y)
{
auto *output{Image.data() + static_cast<std::size_t>(y) * Size * 3};
auto const sourcey{(Size - 1 - y) * supersampling};
for (auto x = 0; x < Size; ++x)
{
glm::vec3 color{0.f};
for (auto sy = 0; sy < supersampling; ++sy)
{
for (auto sx = 0; sx < supersampling; ++sx)
{
auto const sample{static_cast<std::size_t>(sourcey + sy) * targetsize + x * supersampling + sx};
if (coverage[sample] != 0)
{
auto const *rgba{colors.data() + sample * 4};
color += glm::vec3{tolinear[rgba[0]], tolinear[rgba[1]], tolinear[rgba[2]]};
}
else
{
color += glm::vec3{1.f};
}
}
}
color /= samplecount;
output[x * 3 + 0] = tosrgb(color.r);
output[x * 3 + 1] = tosrgb(color.g);
output[x * 3 + 2] = tosrgb(color.b);
}
}
return true;
}
void opengl33_renderer::Update_Lights(light_array &Lights)
{
glDebug("Update_Lights");
Bind_Texture( gl::HEADLIGHT_TEX, m_headlightstexture );
// arrange the light array from closest to farthest from current position of the camera
auto const camera = m_colorpass.pass_camera.position();
std::sort(
std::begin(Lights.data), std::end(Lights.data),
[&camera](light_array::light_record const &Left, light_array::light_record const &Right) {
// move lights which are off at the end...
if (Left.intensity == 0.f) { return false; }
if (Right.intensity == 0.f) { return true; }
// ...otherwise prefer closer and/or brigher light sources
return (glm::length2(camera - Left.position) / Left.intensity) < (glm::length2(camera - Right.position) / Right.intensity);
});
// set up helpers
glm::mat4 coordmove;
if (GLAD_GL_ARB_clip_control || GLAD_GL_EXT_clip_control)
// transform 1..-1 NDC xy coordinates to 1..0
coordmove = glm::mat4( //
0.5, 0.0, 0.0, 0.0, //
0.0, 0.5, 0.0, 0.0, //
0.0, 0.0, 1.0, 0.0, //
0.5, 0.5, 0.0, 1.0 //
);
else
// without clip_control we also need to transform z
coordmove = glm::mat4( //
0.5, 0.0, 0.0, 0.0, //
0.0, 0.5, 0.0, 0.0, //
0.0, 0.0, 0.5, 0.0, //
0.5, 0.5, 0.5, 1.0 //
);
glm::mat4 mv = OpenGLMatrices.data( GL_MODELVIEW );
// fill vehicle headlights data
auto renderlight = m_lights.begin();
size_t light_i = 1;
for (auto const &scenelight : Lights.data)
{
if (renderlight == m_lights.end()) {
// we ran out of lights to assign
break;
}
if (scenelight.intensity == 0.f) {
// all lights past this one are bound to be off
break;
}
auto const lightoffset = glm::vec3{scenelight.position - camera};
if (glm::length2(lightoffset) > sq(1000.f)) {
// we don't care about lights past arbitrary limit of 1 km.
// but there could still be weaker lights which are closer, so keep looking
continue;
}
// if the light passed tests so far, it's good enough
renderlight->position = lightoffset;
renderlight->direction = scenelight.direction;
auto luminance = static_cast<float>(Global.fLuminance);
// adjust luminance level based on vehicle's location, e.g. tunnels
auto const environment = scenelight.owner->fShade;
if (environment > 0.f)
{
luminance *= environment;
}
renderlight->diffuse = glm::vec4{glm::max(glm::vec3{colors::none}, scenelight.color - glm::vec3{luminance}), renderlight->diffuse[3]};
renderlight->ambient = glm::vec4{glm::max(glm::vec3{colors::none}, scenelight.color * glm::vec3{scenelight.intensity} - glm::vec3{luminance}), renderlight->ambient[3]};
renderlight->apply_intensity( ( scenelight.count * 0.5 ) * ( scenelight.owner->DimHeadlights ? 0.5 : 1.0 ) );
renderlight->apply_angle();
gl::light_element_ubs *light = &light_ubs.lights[light_i];
light->pos = mv * glm::vec4(renderlight->position, 1.0f);
light->dir = mv * glm::vec4(renderlight->direction, 0.0f);
light->type = gl::light_element_ubs::HEADLIGHTS;
light->in_cutoff = headlight_config.in_cutoff;
light->out_cutoff = headlight_config.out_cutoff;
light->color = renderlight->diffuse * renderlight->factor;
light->linear = headlight_config.falloff_linear / 10.0f;
light->quadratic = headlight_config.falloff_quadratic / 100.0f;
light->ambient = headlight_config.ambient;
light->intensity = headlight_config.intensity;
// headlights-to-world projection
{
// headlight projection is 1 km long box aligned with vehicle rotation and aimed slightly downwards
opengl_camera headlights;
auto const &ownerdimensions{ scenelight.owner->MoverParameters->Dim };
auto const up{ static_cast<glm::dvec3>( scenelight.owner->VectorUp() ) };
auto const size{ static_cast<float>( std::max( ownerdimensions.W, ownerdimensions.H ) * 1.0 ) }; // ensure square ratio
auto const cone{ 5.f };
auto const offset{ 75.f * ( 5.f / cone ) };
headlights.position() =
scenelight.owner->GetPosition()
- glm::dvec3(scenelight.direction * offset)
+ up * ( size * 0.5 );
/*
headlights.projection() = ortho_projection(
-size, size,
-size, size,
ownerdimensions.L * 0.5 - 0.5, 1000.0f );
*/
headlights.projection() = perspective_projection_raw(
glm::radians( cone ),
1.0,
ownerdimensions.L * 0.5 + offset - 0.25, 1000.0f );
glm::dmat4 viewmatrix{ 1.0 };
viewmatrix *=
glm::lookAt(
headlights.position(),
headlights.position()
- up * 1.0
+ glm::dvec3{ scenelight.direction * 1000.f },
glm::dvec3{ 0.f, 1.f, 0.f } );
headlights.modelview() = viewmatrix;
// calculate world->headlight space projection matrix
glm::mat4 const depthproj{ headlights.projection() };
// NOTE: we strip transformations from camera projections to remove jitter that occurs
// with large (and unneded as we only need the offset) transformations back and forth
auto const lightcam{ glm::mat3{ headlights.modelview() } };
auto const worldcam{ glm::mat3{ m_renderpass.pass_camera.modelview() } };
light->headlight_projection =
coordmove
* depthproj
* glm::translate(
glm::mat4{ lightcam },
glm::vec3{ m_renderpass.pass_camera.position() - headlights.position() } )
* glm::mat4{ glm::inverse( worldcam ) };
}
// headlights weights
light->headlight_weights = { scenelight.state, 0.f };
++light_i;
++renderlight;
}
light_ubs.lights_count = light_i;
// fill sunlight data
light_ubs.ambient = m_sunlight.ambient * m_sunlight.factor;// *simulation::Environment.light_intensity();
light_ubs.lights[0].type = gl::light_element_ubs::DIR;
light_ubs.lights[0].dir = mv * glm::vec4(m_sunlight.direction, 0.0f);
light_ubs.lights[0].color = m_sunlight.diffuse * m_sunlight.factor * simulation::Environment.light_intensity();
light_ubs.lights[0].ambient = 0.0f;
light_ubs.lights[0].intensity = 1.0f;
// fill fog data
light_ubs.fog_color = Global.FogColor;
if (Global.fFogEnd > 0)
{
m_fogrange = Global.fFogEnd / std::max(1.f, Global.Overcast * 2.f);
model_ubs.fog_density = 1.0f / m_fogrange;
}
else
{
model_ubs.fog_density = 0.0f;
}
// ship config data to the gpu
model_ubo->update(model_ubs);
light_ubo->update(light_ubs);
}
bool opengl33_renderer::Init_caps()
{
std::string gl_renderer((char *)glGetString(GL_RENDERER));
std::string gl_vendor((char *)glGetString(GL_VENDOR));
std::string gl_version((char *)glGetString(GL_VERSION));
crashreport_add_info("gl_renderer", gl_renderer);
crashreport_add_info("gl_vendor", gl_vendor);
crashreport_add_info("gl_version", gl_version);
crashreport_add_info("gl_use_vao", gl::vao::use_vao ? "yes" : "no");
crashreport_add_info("gfx.skippipeline", Global.gfx_skippipeline ? "yes" : "no");
WriteLog("MaSzyna OpenGL Renderer");
WriteLog("Renderer: " + gl_renderer);
WriteLog("Vendor: " + gl_vendor);
WriteLog("GL version: " + gl_version);
WriteLog("--------");
GLint extCount = 0;
glGetIntegerv(GL_NUM_EXTENSIONS, &extCount);
WriteLog("Supported extensions:");
for (int i = 0; i < extCount; i++)
{
const char *ext = (const char *)glGetStringi(GL_EXTENSIONS, i);
WriteLog(ext);
}
WriteLog("--------");
if (!Global.gfx_usegles)
{
crashreport_add_info("gl_family", "desktop");
if (!GLAD_GL_VERSION_3_3)
{
ErrorLog("requires OpenGL >= 3.3!");
return false;
}
if (!GLAD_GL_EXT_texture_sRGB)
ErrorLog("EXT_texture_sRGB not supported!");
if (!GLAD_GL_EXT_texture_compression_s3tc)
ErrorLog("EXT_texture_compression_s3tc not supported!");
if (GLAD_GL_ARB_texture_filter_anisotropic)
WriteLog("ARB_texture_filter_anisotropic supported!");
if (GLAD_GL_ARB_multi_bind)
WriteLog("ARB_multi_bind supported!");
if (GLAD_GL_ARB_direct_state_access)
WriteLog("ARB_direct_state_access supported!");
if (GLAD_GL_ARB_clip_control)
WriteLog("ARB_clip_control supported!");
}
else
{
crashreport_add_info("gl_family", "gles");
if (!GLAD_GL_ES_VERSION_3_0)
{
ErrorLog("requires OpenGL ES >= 3.0!");
return false;
}
if (GLAD_GL_EXT_texture_filter_anisotropic)
WriteLog("EXT_texture_filter_anisotropic supported!");
if (GLAD_GL_EXT_clip_control)
WriteLog("EXT_clip_control supported!");
if (GLAD_GL_EXT_geometry_shader)
WriteLog("EXT_geometry_shader supported!");
}
glGetError();
glLineWidth(2.0f);
if (!glGetError())
{
WriteLog("wide lines supported!");
m_widelines_supported = true;
}
else
WriteLog("warning: wide lines not supported");
WriteLog("--------");
// ograniczenie maksymalnego rozmiaru tekstur - parametr dla skalowania tekstur
{
GLint texturesize;
::glGetIntegerv(GL_MAX_TEXTURE_SIZE, &texturesize);
Global.iMaxTextureSize = std::min(Global.iMaxTextureSize, texturesize);
Global.iMaxCabTextureSize = std::min( Global.iMaxCabTextureSize, texturesize );
WriteLog( "texture sizes capped at " + std::to_string(Global.iMaxTextureSize) + "p (" + std::to_string( Global.iMaxCabTextureSize ) + "p for cab textures)" );
Global.CurrentMaxTextureSize = Global.iMaxTextureSize;
m_shadowbuffersize = Global.shadowtune.map_size;
m_shadowbuffersize = std::min(m_shadowbuffersize, texturesize);
WriteLog("shadows map size capped at " + std::to_string(m_shadowbuffersize) + "p");
}
Global.DynamicLightCount = std::min(Global.DynamicLightCount, (int)gl::MAX_LIGHTS - 1); // reserve 1 slot for sun
if (Global.iMultisampling)
{
WriteLog("using multisampling x" + std::to_string(1 << Global.iMultisampling));
}
if (Global.gfx_framebuffer_width == -1)
Global.gfx_framebuffer_width = Global.fb_size.x;
if (Global.gfx_framebuffer_height == -1)
Global.gfx_framebuffer_height = Global.fb_size.y;
WriteLog("main window size: " + std::to_string(Global.gfx_framebuffer_width) + "x" + std::to_string(Global.gfx_framebuffer_height));
return true;
}
glm::vec3 opengl33_renderer::pick_color(std::size_t const Index)
{
return glm::vec3{((Index & 0xff0000) >> 16) / 255.0f, ((Index & 0x00ff00) >> 8) / 255.0f, (Index & 0x0000ff) / 255.0f};
}
std::size_t opengl33_renderer::pick_index(glm::ivec3 const &Color)
{
return Color.b + (Color.g * 256) + (Color.r * 256 * 256);
}
std::unique_ptr<gfx_renderer> opengl33_renderer::create_func()
{
return std::unique_ptr<gfx_renderer>(new opengl33_renderer());
}
bool opengl33_renderer::renderer_register = gfx_renderer_factory::get_instance()->register_backend("modern", opengl33_renderer::create_func);
bool opengl33_renderer::opengl33_imgui_renderer::Init()
{
crashreport_add_info("imgui_ver", "gl3");
if (Global.gfx_usegles)
return ImGui_ImplOpenGL3_Init("#version 300 es\nprecision highp float;");
else
return ImGui_ImplOpenGL3_Init("#version 330 core");
}
void opengl33_renderer::opengl33_imgui_renderer::Shutdown()
{
ImGui_ImplOpenGL3_Shutdown();
}
void opengl33_renderer::opengl33_imgui_renderer::BeginFrame()
{
ImGui_ImplOpenGL3_NewFrame();
}
void opengl33_renderer::opengl33_imgui_renderer::Render()
{
gl::buffer::unbind(gl::buffer::ARRAY_BUFFER);
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
}
std::uint64_t opengl33_renderer::opengl33_imgui_renderer::Create_Image(std::uint8_t const *Rgba, int const Width, int const Height)
{
// the ui colours are made linear in its shaders, the image is too, by sampling it as srgb. the bindings the renderer
// keeps track of are put back as they were
GLint texture{0}, unpack{0}, alignment{4};
glGetIntegerv(GL_TEXTURE_BINDING_2D, &texture);
glGetIntegerv(GL_PIXEL_UNPACK_BUFFER_BINDING, &unpack);
glGetIntegerv(GL_UNPACK_ALIGNMENT, &alignment);
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
GLuint image{0};
glGenTextures(1, &image);
glBindTexture(GL_TEXTURE_2D, image);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_SRGB8_ALPHA8, Width, Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, Rgba);
glBindTexture(GL_TEXTURE_2D, static_cast<GLuint>(texture));
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, static_cast<GLuint>(unpack));
glPixelStorei(GL_UNPACK_ALIGNMENT, alignment);
return image;
}
void opengl33_renderer::opengl33_imgui_renderer::Release_Image(std::uint64_t const Image)
{
auto const image{static_cast<GLuint>(Image)};
glDeleteTextures(1, &image);
}