mirror of
https://github.com/MaSzyna-EU07/maszyna.git
synced 2026-11-27 23:57:09 +01:00
* Enhance Windows build matrix with AVX2 variants * fix(lang): the two Polish lines of the download area written with \n, so they match the tooltip and the hint * fix(files): data named in another case is found on Linux, folders included The parser and the loaders lowercase every name they read, while the data made on Windows has files and folders named in any case (scenery/Braniewo, textures/siec_trakcyjna_ph/.../STS_*.tga, sounds/sip/Gorki.wav). FileCased matched the file name only, so a folder in another case wasn't found. - FileCased walks every part of the path on Linux, the folder listings kept by their lowercase and read again once the folder changed; Windows as it was - FileExists finds the file in any case on Linux, and the variant with names and extensions gives back the name as it's on the disk, so textures, materials, sounds, station announcements and scripts open that name - models, sound captions, timetables and nodebank previews open the file as it's named on the disk; the texture format is told by the extension in any case * fix(files): the banks keep the names asked for, only the opening takes the case of the disk The textures, materials and sounds are kept by the names they're asked for. Given back as named on the disk, a file in another case missed the bank and was loaded again on every request. - FileExists with names and extensions finds the file in any case but gives back the name asked for; FileOnDisk gives the file to open, used where textures, sounds and scripts are opened - FileExists of a single name is a plain check again, the places checking it and opening the same name stay as they were - the texture format is told by the extension asked for again - a folder changed shortly before it was read is read again for a name missing from it, the time of a change being as coarse as the clock of the file system; a listing cut short isn't kept * fix(files): a folder changed in the future isn't read again on every name missing from it * perf(files): a file missing costs a single check, as before Measured in a case sensitive folder (3000 textures, every 20th in mixed case, looked up the way Texture.cpp does), the walk over every part of the path made a texture lookup 4-5 times slower than master: each name tried and missing checked every folder of its path. - the folders found are kept by the name they're given with, the missing ones for a second, so a missing file checks its folder alone - a folder named as it is on the disk is taken without its listing - the time a folder was changed is looked at once a second at most The lookup is now as fast as master's (about 180 us per texture on NTFS in both) while finding the files named in another case too. * fix(files): terrain files named in another case are found on Linux The terrain directive names .txtf/.btf files in lowercase, as the parser gives every token. The name is now taken as it is on disk, from the text file first, so the binary file is made next to the text and the editor's references and layers keep one name. * fix(files): models named in another case are found on Linux The manager of the models looked for the file with FileExists of a single name, a plain check again since the banks keep the names asked for, so a model named in another case (models/przejazdy/plyty3_L, dynamic/pkp/st44_v2/main/2M62-0685-A) was reported missing before TModel3d::LoadFromFile() could open it as it's named on the disk. find_on_disk() finds the file in any case and gives back the name asked for, the key of the bank. * refactor(files): named functions instead of the lambdas of the folder cache (Sonar S2259, S3608, S6004) Sonar took the folder captured by the lambda reading it for a reference to null, failing the quality gate on reliability. The folder is read and the path kept by functions in the anonymous namespace, the age of the listing declared in its if. * fix: the simulator opens more than 512 files at once, and a shader it can't open says why With "physicslog yes" every driver keeps its .dat open, and a large scenery (Tomaszewo: some 500 vehicles, cars of the roads included) took all 512 streams the MSVC runtime gives: the next fopen failed and the simulator stopped at "cannot read shader: shaders/map.vert" on opening the map. The limit is raised to 8192 at the start (the soft limit of open files up to the hard one on Linux), and a shader file that doesn't open is told as such, with the system's reason, rather than as one that can't be read. * feat(blackbox): the black box on its own, writing the tapes of the user's vehicles at the end "blackbox yes" in eu07.ini records the black box with the physics logs on or off, "blackbox no" never; with no entry it goes with "physicslog yes" as before. With the physics logs off, the recorder keeps the line of the physics log of the driver the user is with, every 0.05 s, and writes it to physicslog/<vehicle>.dat when the recording closes: the speed recorder's tape of the vehicles the user was in, without every vehicle keeping a log open and written twenty times a second. The line and the header of the log are made by one function of the driver, which its own log writes too, and the file is opened the same way, so the two are the same to the byte: the readers of these logs (the old Hasler tape viewer, the starter) read them as before. * feat(physicslog): the logs written every two seconds by a thread of their own, no file kept open; the black box's tapes as it goes "physicslog yes" kept the .dat of every vehicle with a driver open for the whole run and flushed it twenty times a second from the simulation's thread: some 580 open files on Tomaszewo. The lines are kept now and a thread of their own writes them every two seconds, each file opened only for the moment it is written to. The files, their lines and their text mode stay as they were. - The black box, with the physics logs off, writes the tapes of the user's vehicles through the same writer as it goes, not at the end. A log begins when the user is first in the vehicle and goes on while the user looks around outside, until another vehicle is taken; back in it, the log goes on after the gap. The vehicle's own driver keeps the log only if it is the primary one, as a passive one's clock stands still; otherwise the driver of its train does. - What is kept is written when the simulator closes, after the black box, at the end of a test run, and when the test watchdog ends a run. A crash loses the last two seconds. - On Tomaszewo with the black box alone, the one tape grows every two seconds. With "physicslog yes", the 581 logs grow and the simulator holds as many handles as without them; writing them takes the thread about 1.9 s, which the closing waits for once. * feat(blackbox): the cab record holds the speed of the wheels, apart from the vehicle's when they slip The speed of the cab record is the vehicle's. The speedometer, and a speed recorder's tape with it, shows the speed of the wheels as they turn, which runs away from it while they slip and drops to 0 while they are locked in a skid. It is added at the end of the record (194 bytes), where the readers skip what they don't know; the .dat tapes have it already, in their second column. * fix(ci): build OpenAL Soft with the PipeWire, PulseAudio and ALSA backends, so the Linux game has sound The Linux job builds OpenAL Soft 1.24.2 from source, but the runner had none of the headers of its audio backends, and OpenAL Soft's CMake leaves out every backend it can't find. The bundled libopenal.so.1 had only OSS, Null, Wave and Loopback. Modern distributions and the Steam Linux Runtime have no /dev/dsp, so the game logged "Failed to obtain audio device" and played nothing, with any Steam Linux Runtime and without one. - install libasound2-dev, libpulse-dev and libpipewire-0.3-dev before building OpenAL Soft - configure it with ALSOFT_REQUIRE_PIPEWIRE/PULSEAUDIO/ALSA, so a missing header fails the build instead of shipping a library without sound The backends are loaded with dlopen at run time (ALSOFT_DLOPEN is on by default), so the bundled library gains no new dependency. Tested by putting an OpenAL Soft 1.24.2 with these backends next to the game from the Steam depot: under Steam Linux Runtime 4.0 the sound works. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(editor): the certificates of https looked for where the distribution keeps them The Linux game bundles the libcurl of Ubuntu, which knows only Ubuntu's /etc/ssl/certs/ca-certificates.crt. Fedora, RHEL and openSUSE keep the certificates elsewhere, so every download of the editor (orthophoto, terrain model, topo map) failed there with a certificate error. The file is taken from SSL_CERT_FILE or CURL_CA_BUNDLE when set, else the first of the files the distributions keep, and passed as CURLOPT_CAINFO. With none found libcurl keeps its own. * fix(editor): an https proxy checked with the same certificates CURLOPT_PROXY_CAINFO gets the file found for CURLOPT_CAINFO, so a download through an https:// proxy on Fedora or RHEL doesn't fail on the proxy's certificate. * fix(ci): the no-AVX2 Windows build has its own concurrency group and its own public download After master was merged the two Windows variants shared one concurrency group with cancel-in-progress, so one cancelled the other, and the publish job looked for an artifact name the matrix no longer produces. Each variant now has its own group, the publish job downloads both, and the release carries maszyna-windows-x64.zip (AVX2, the old name, so the links already handed out still work) and maszyna-windows-x64-noavx2.zip. The AVX2 variant passes -DENABLE_AVX2=ON explicitly instead of an empty flag. * build: a build without AVX2 has _noavx2 at the end of its executable name With ENABLE_AVX2=OFF the executable is eu07-x64_<date>_<hash>_noavx2.exe (eu07-x64_noavx2.exe without ADD_VERSION_SUFFIX), so a starter can tell the two builds apart by the name alone and pick this one on a CPU without AVX2. The AVX2 build keeps its name. * ci: Linux is built without AVX2 too, published as maszyna-linux-x64-noavx2.tar.gz The Linux job becomes the same two-variant matrix as Windows (ENABLE_AVX2=ON/OFF), each variant with a concurrency group of its own. The publish job downloads both Linux artifacts, restores the executable bits in both and releases maszyna-linux-x64.tar.gz (AVX2, the old name) next to maszyna-linux-x64-noavx2.tar.gz. The no-AVX2 executable is eu07_<date>_<hash>_noavx2. * fix(renderer): the legacy renderer clears the arrays the scene left before it draws the ui The legacy renderer drew the ui with the client arrays of the last scene draw still enabled: the texture coordinates of the normal map unit and the normals, pointing into the vertex buffer of whatever was drawn last, 48 bytes a vertex. The ImGui backend sets up the vertex, colour and texture coordinates of the active unit only, so the driver read the stale arrays with the indices of the ui. Once the ui had more vertices than that buffer, the NVIDIA driver read past its end and the game crashed; a crash dump of the editor (an area selected, a track being laid) shows the read of vertex 15113 at a 48-byte stride in ImGui_ImplOpenGL2_RenderDrawData. The arrays are now disabled on every texture unit the geometry uses, with the normal and colour arrays, inside the glPushClientAttrib already there, so the scene gets its state back after the ui. The default and the experimental renderers don't go through this code. * fix(app): a renderer this build doesn't have starts the full one, not the legacy one The starter writes "gfxrenderer vulkan" for the Vulkan renderer of the builds that have it. This exe doesn't know the word, and every word other than default/experimental fell to the legacy renderer: a player who picked Vulkan got the slowest renderer, the one whose ui crashes on NVIDIA (the arrays left by the scene). "experimental" in a build without the NVRHI renderer ended with "no renderer found!" and no game at all. After the settings are read, a gfxrenderer word this build has no renderer for becomes "default", with a line in the log saying so. The words it knows stay as they were: full/default, legacy, simple, null, the older starters' simpleshader and off (legacy as before), and experimental where it is built. * fix(settings): the gfxrenderer word read in any case, as the starter reads it A hand-written "gfxrenderer Legacy" started the legacy renderer only because every unknown word did; with unknown words going to the full renderer it would have changed. The word is lowercased when read, as StarterNG's RenderEngineOf does, so Legacy, Simple or Full mean what they say. * fix(physicslog): a log whose file can't be written keeps its lines and header, and the writer is stopped once on every way out A failed write put its lines back, ahead of those since, so a file held by another program for a while gets its header and every line once it can be written; up to 4 MB kept per log. Stopping is joined once, and not from the writer's own thread. main stops the logs after an error it caught too, and the test watchdog flushes with a time limit, so a disk that doesn't answer doesn't keep the run from ending. * fix(blackbox): the wheels of the powered vehicle, as the speedometer has them, and the logs described as the drivers' they are In a unit driven from an unpowered car, the speed of the wheels was of the car the user is in, whose wheels never slip; now of the motor car, signed as the occupied vehicle's speed. The doc tells of a log per driver, and of the two seconds of real time a crash loses. * fix(physicslog): failed logs kept within 64 MB in all, cut outside the lock, never written twice; the writer knows itself when stopped The lines kept while files can't be written are cut to their share of 64 MB before the lock the simulation waits on. A log written in part is cut back to its length, so the next try doesn't write its start twice. A stop from the writer itself is told by its id even after another thread took it to join, and the watchdog's flush waits at most its time, the writing on a thread of its own. * feat(physicslog): the logs of the trains only, physicslog.trains "physicslog.trains yes" in eu07.ini writes the .dat log of each driver who drives rail vehicles, not of the passengers nor of the road vehicles that make "physicslog yes" hundreds of files on a big scenery: the tape of every train. A driver made primary later begins its log then, and isn't counted while it doesn't log. The black box goes with it when the ini says nothing of its own, and doesn't write a second log of a driver writing its own. The doc tells the doors' sides are the vehicle's, the driver's swapped in the rear cab. * fix(physicslog): a train's log begun at its first line, so passive crews get no file Every crew is primary in the constructor and the drivers but one of a train with crews in more vehicles are made passive only before it starts, so a log begun there left files with only the header. With physicslog on all logs begin at once as before; one of a train waits for update_logs. * fix(editor): the texture pickers let go of the images scrolled past, the memory no longer runs out The picker of the textures of a track offers every texture of the textures folder, and each tile that came into sight read its texture full size, into the graphics card and the memory, and kept it there for good. Scrolling through the list for a trackbed texture took about 2.5 MB a tile: some 900 tiles made 3.5 GB, the whole folder 28 GB, and the game went down once the memory ran out. An image out of sight for 3 seconds is now taken out of both again (texture_manager::unload, Unload_Texture of the renderers) and read anew when it's shown once more, a few a frame as before. Only a texture the scene has never drawn is let go; those of the scene stay to the resource sweep. The texture browser lets go of its images on Refresh too. The picker no longer lists textures/previews: the 4100 previews of the node bank are images of models, not textures of anything. Checked on td.scn by a scripted run: 8000 images of the picker read one batch a few frames after another held the game at 2-3 GB, where it went to 28 GB and fell before; images shown again after they were let go come back; a trackbed texture picked from the folder is drawn on the track after its image was let go. * fix(physicslog): the writer's destructor throws nothing, its wait a plain condition variable woken to stop; a driver of no vehicle controls nothing * fix(editor): the images of the materials let go of with all their textures, the browser's Refresh a frame later An image of a material read the material with all its textures, the normal and specular maps and the variants, and only the first one was let go of: those stayed in the memory for every material scrolled past. They are let go of together now (Unload_Material). texture_manager::unload also takes the textures read and not made yet, waiting for a worker still reading one, and deletes the gl texture itself: release() would read it back from the card with gfx.resource.move only for it to be dropped. The Refresh of the texture browser let go of the images in the middle of the frame, while panels drawn before it could still refer to them; it now marks them, and they go at the start of the next frame. Checked on td.scn by a scripted run: 8040 images of the picker read a batch every few frames end at 2.0 GB, against 2.3-2.6 GB before this and 1.1 GB at the start; a trackbed material picked from the folder is drawn on the track after its image was let go. * fix(physicslog): every stop asked wakes the writer, the one from itself too; no psyche for a driver of no vehicle * fix(editor): the image of a material with no texture in its first slot is let go of too Its normal and specular maps were read with it and stayed in the memory: the trim passed over every image with no texture of its own, the material along with it. * fix(physicslog): nothing that goes wrong in the writing ends the simulator; a name in 1250 makes a path on a Windows set to UTF-8 The writer's thread called flush() with nothing around it, so an exception leaving write() ended the process with std::terminate, with no message. One that happens: the file of a log was made a std::filesystem::path of the vehicle's name, which MSVC converts in the code page of the system and throws for bytes not of it; on a Windows with "Use Unicode UTF-8 for worldwide language support" a vehicle named in 1250, as the sceneries have them (0xB3 for ł), isn't UTF-8. - the file of a log is made of the name with MultiByteToWideChar without MB_ERR_INVALID_CHARS: the same file as before for every name of the code page, U+FFFD for the bytes not of it instead of a throw. Elsewhere the bytes are the name of the file as they were - a log whose writing throws for any other reason (memory) is kept for the next try as one whose file can't be written, and the other logs are written still - the thread, flush_for() and stop() write through flush_safely(), which lets nothing out: what was taken for a writing failing as a whole is lost and told in the log, the next writing goes on - the messages name the file by the bytes of the name, not by path::string(), which converts back Tests: a log which can't be written doesn't keep the others from theirs; a vehicle named in 1250 has its log, read back by physicslog_writer::file(). Reported in the review of #385. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(blackbox): the tapes go on after the editor, with the physics logs off The tapes of the user's vehicles were written by update() after the check for the writer of the recording, which close() drops on entering the editor (F11). With "physicslog no", the speed recorder's tape ended at F11 while the drivers' own logs of "physicslog yes" went on. The tapes are files of their own: they are kept from the moment the recording was to be made, the file made or not, closed or not, until the simulator closes, after the gap of the time in the editor. Only the recording itself stops at F11, as before. Reported in the review of #385. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(physicslog): what no file name may have on Windows is replaced in the name of a log, on every system A spawned vehicle is named <spawn>:<number>, and its log went to physicslog/<spawn>:<number>.dat. On NTFS that isn't even an error: it is the stream <number>.dat of the file <spawn>, which nothing lists, so the log was written and no one could find it. On Linux the file was there, under a name Windows can't open. The name of the file of a log has < > : " / \ | ? * and the control characters replaced by _, on every system, so the logs are named alike everywhere (spawn_ezt:12 is spawn_ezt_12.dat), and a _ before a name Windows keeps for a device (con, nul, com1..., with an extension too). The bytes of 1250 stay. The black box tells the log it begins by the same name. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(renderer): a material's textures let go of in one place, for every backend Unload_Material walked the textures of a material and of its variants the same way in both opengl renderers, and Sonar counted its declarations, set into the long run of overrides the two headers share, as duplicated: 5.2% of the new code, 3% allowed. The walk is gfx_renderer's now, over IMaterial::GetAllTextures and the backend's Unload_Texture. Materials that don't tell their textures, the Vulkan renderer's, give none, and are left alone as before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(physicslog): road vehicles keep no log, the lines are made into text by the writer, and a slow disk gets them less often On a big scenery "physicslog yes" wrote a log for every driver, the hundreds of cars of the roads too: Tomaszewo gives over a thousand. A player with an i7-3770 and a hard disk had 1 fps there and 90 fps paused; with the physics log off the frame rate came back. The disk was busy with the logs all the time, and the simulation formatted 26 values a line, twenty lines a second, for each of them. - "physicslog yes" writes the logs of all drivers but those of road vehicles. Nobody reads those, and the starter's tapes are of rail vehicles. The black box writes the tape of a car the user drives, as it does with the physics logs off. On Tomaszewo a 120 s test run gives 20 logs instead of 579. - The simulation hands the writer the values of a line; the writer's thread makes them into text, with the same stream as before. The logs of a fixed-seed run of Tomaszewo come out byte for byte the same as before. - The writer's thread does its disk work at background priority (Windows THREAD_MODE_BACKGROUND_BEGIN, Linux the lowest best-effort I/O priority), so the simulation's own reading doesn't wait behind the logs. - A writing that takes over a third of the 2 s interval makes the next wait three times as long as it took: the disk is busy with the logs a quarter of the time at most. The log of the simulator says so once. - A log is written with one write, the header of a log begun with its lines, and a log added to is opened at its end rather than asked for its length first. What changes for the data: with "physicslog yes" no .dat files of road vehicles appear in physicslog/. Nothing in the SVN needs to change; the comment of physicslog in the shipped eu07.ini ("for all vehicles manned by AI or a human") is now a little wide of it. * fix(physicslog): the wait after a slow writing is ten seconds at most, a log whose lines can't be made into text is kept - The wait after a slow writing grew with what it left to the next one, with no end once the formatting and the bytes took a quarter of the time: it is five intervals at most now, so a crash loses ten seconds at most. - The lines given as values are made into text within the try of each log, aside and added at once: out of memory there keeps that log for the next try and the others are written, as the comment said. - The Windows background mode is described as it is: very low I/O priority, the memory pages let go of first. - The black box doc says a car the user drives has no log with the black box off. * fix(physicslog): the closing waits for the logs a second at most, the rest is dropped stop() gives the writing one second (a constructor parameter, ClosingWait). The writer thread's batch under way and the final writing check the time before each log and drop the logs past it, telling how many in the log. The final writing runs on a thread of its own, left behind when it isn't done in time, so a disk that doesn't answer in the middle of a file doesn't hold the closing either; the simulator ends with _Exit, and a writer object that goes waits for those writings in its destructor. At the closing the writer thread's disk priority is put back to normal, so that second goes to the logs. A flush() after the stop is not cut short. * fix(physicslog): a second stop keeps the time of a closing under way, and a stop lets out no exception The simulator stops the logs twice on a normal exit (Application.exit() and main). A stop while an earlier closing is still writing now keeps that closing's time instead of giving it another second, and doesn't tell it again. The thread of the closing is begun in a noexcept helper: with no memory or no thread to be had the rest is written on the calling thread, the logs past the time dropped still, so stop() doesn't throw on the way out of an out-of-memory error. * fix(physicslog): a closing whose thread is begun isn't written again by the stop when its log line fails std::format of the timeout line can throw (out of memory) after the closing's thread was started; close_aside returned false then, and stop() wrote on the calling thread too, waiting on the files the closing holds with no time limit. A thread begun counts now. * fix(physicslog): a failed log keeps its values in order, and the user's log goes first at the closing A log whose file couldn't be written kept the values the writing failed to make into text (out of memory) only until the next line came: keeping it put the values given since in their place. They're made into text again now, and the values given since go after them, added at once. Values which still can't be made into text are dropped when text was given after them, as the order can't be kept otherwise. What a writing needs before it takes the lines (the names put first, the order) is had before it takes them, so without the memory for it the lines are left for the next writing. The closing, which waits a second for the writing, dropped the logs past it by the order of their names: the user's train could lose its last seconds while a log nobody reads was written. Now: - the logs put first (put_first) are written before the others at each writing: the one of the driver the black box follows, of the vehicle the user is in (the black box goes with the physics logs unless "blackbox no"), and those of the drivers of the tested trains (test.vehicle); - a stop ends a writing of the thread under way at the log at hand, and the thread begins none after it. The logs it hasn't come to are left to the closing's writing, which has them with the lines given since, those put first first. Before, the thread went on through them and the closing's writing, coming after, had no time left for the newest lines. They go back as they were taken: their values are made into text by the closing's writing, not on the way to it unless text was given since, and they don't count toward the 64 MB kept of the logs whose file can't be written. The closing drops the logs past its time as before, the user's too: none is begun once the time is over, only the one at hand may still be written while the process ends. The thread no longer raises its disk priority at a closing, as it no longer writes there. --------- Co-authored-by: maj00r <maj00r@host> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Hirek193 <polomarket73@gmail.com>
1694 lines
46 KiB
C++
1694 lines
46 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 "application/application.h"
|
|
#include "application/drivermode.h"
|
|
#include "application/editormode.h"
|
|
#include "application/scenarioloadermode.h"
|
|
#include "launcher/launchermode.h"
|
|
|
|
#include "utilities/Globals.h"
|
|
#include "utilities/utilities.h"
|
|
#include "simulation/simulation.h"
|
|
#include "simulation/simulationsounds.h"
|
|
#include "simulation/blackboxrecorder.h"
|
|
#include "vehicle/Train.h"
|
|
#include "utilities/dictionary.h"
|
|
#include "scene/sceneeditor.h"
|
|
#include "rendering/renderer.h"
|
|
#include "application/uilayer.h"
|
|
#include "utilities/Logs.h"
|
|
#include "world/SleeperWorker.h"
|
|
#include "rendering/screenshot.h"
|
|
#include "utilities/translation.h"
|
|
#include "vehicle/Train.h"
|
|
#include "utilities/Timer.h"
|
|
#include "utilities/framepacer.h"
|
|
#include "utilities/dictionary.h"
|
|
#include "version_info.h"
|
|
#include "simulation/simulationtest.h"
|
|
#include "utilities/physicslog.h"
|
|
#include <chrono>
|
|
#include <format>
|
|
#include <vector>
|
|
#include "utilities/translation.h"
|
|
|
|
#if WITH_DISCORD_RPC
|
|
#include "ref/discord-rpc/include/discord_rpc.h"
|
|
#include <discord_rpc.h>
|
|
#endif
|
|
|
|
#include <chrono>
|
|
#include "utilities/translation.h"
|
|
|
|
#ifdef _WIN32
|
|
#pragma comment(lib, "dsound.lib")
|
|
#pragma comment(lib, "winmm.lib")
|
|
#pragma comment(lib, "setupapi.lib")
|
|
#pragma comment(lib, "dbghelp.lib")
|
|
#pragma comment(lib, "version.lib")
|
|
#endif
|
|
|
|
#ifdef __unix__
|
|
#include <unistd.h>
|
|
#include <sys/stat.h>
|
|
#endif
|
|
|
|
eu07_application Application;
|
|
screenshot_manager screenshot_man;
|
|
ui_layer uilayerstaticinitializer;
|
|
|
|
#ifdef _WIN32
|
|
extern "C"
|
|
{
|
|
GLFWAPI HWND glfwGetWin32Window(GLFWwindow *window);
|
|
}
|
|
|
|
LRESULT APIENTRY WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
|
|
extern HWND Hwnd;
|
|
extern WNDPROC BaseWindowProc;
|
|
#endif
|
|
|
|
// user input callbacks
|
|
|
|
void focus_callback(GLFWwindow *window, int focus)
|
|
{
|
|
ui_layer::focus_callback(focus);
|
|
Application.on_focus_change(focus != 0);
|
|
}
|
|
|
|
void cursor_enter_callback(GLFWwindow *window, int entered)
|
|
{
|
|
if (scripted_input::driving())
|
|
return;
|
|
ui_layer::cursor_enter_callback(entered);
|
|
}
|
|
|
|
void framebuffer_resize_callback(GLFWwindow *, int w, int h)
|
|
{
|
|
Global.fb_size = glm::ivec2(w, h);
|
|
}
|
|
|
|
void window_resize_callback(GLFWwindow *, int w, int h)
|
|
{
|
|
Global.window_size = glm::ivec2(w, h);
|
|
Application.on_window_resize(w, h);
|
|
}
|
|
|
|
void cursor_pos_callback(GLFWwindow *window, double x, double y)
|
|
{
|
|
if (scripted_input::driving())
|
|
return;
|
|
ui_layer::cursor_pos_callback(x, y);
|
|
Global.cursor_pos = glm::ivec2(x, y);
|
|
Application.on_cursor_pos(x, y);
|
|
}
|
|
|
|
void mouse_button_callback(GLFWwindow *window, int button, int action, int mods)
|
|
{
|
|
if (scripted_input::driving())
|
|
return;
|
|
Application.on_mouse_button(button, action, mods);
|
|
}
|
|
|
|
void scroll_callback(GLFWwindow *window, double xoffset, double yoffset)
|
|
{
|
|
if (scripted_input::driving())
|
|
return;
|
|
Application.on_scroll(xoffset, yoffset);
|
|
}
|
|
|
|
void key_callback(GLFWwindow *window, int key, int scancode, int action, int mods)
|
|
{
|
|
if (scripted_input::driving())
|
|
return;
|
|
|
|
Application.on_key(key, scancode, action, mods);
|
|
}
|
|
|
|
void char_callback(GLFWwindow *window, unsigned int c)
|
|
{
|
|
if (scripted_input::driving())
|
|
return;
|
|
Application.on_char(c);
|
|
}
|
|
|
|
// public:
|
|
|
|
void eu07_application::queue_screenshot()
|
|
{
|
|
m_screenshot_queued = true;
|
|
}
|
|
|
|
int eu07_application::run_crashgui()
|
|
{
|
|
bool autoup = false;
|
|
|
|
while (!glfwWindowShouldClose(m_windows.front()))
|
|
{
|
|
glfwPollEvents();
|
|
|
|
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
|
|
ui_layer::begin_ui_frame_internal();
|
|
|
|
bool y, n;
|
|
|
|
if (Global.asLang == "pl")
|
|
{
|
|
ImGui::Begin("Raportowanie błędów", nullptr, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize);
|
|
ImGui::TextUnformatted("Podczas ostatniego uruchomienia symulatora wystąpił błąd.\nWysłać raport o błędzie do deweloperów?\n");
|
|
ImGui::TextUnformatted(("Usługa udostępniana przez " + crashreport_get_provider() + "\n").c_str());
|
|
y = ImGui::Button("Tak", ImVec2S(60, 0));
|
|
ImGui::SameLine();
|
|
ImGui::Checkbox("W przyszłości przesyłaj raporty o błędach automatycznie", &autoup);
|
|
|
|
ImGui::SameLine();
|
|
ImGui::TextDisabled("(?)");
|
|
if (ImGui::IsItemHovered())
|
|
{
|
|
ImGui::BeginTooltip();
|
|
ImGui::TextUnformatted("W celu wyłączenia tej funkcji będzie trzeba skasować plik crashdumps/autoupload_enabled.conf");
|
|
ImGui::EndTooltip();
|
|
}
|
|
|
|
ImGui::NewLine();
|
|
n = ImGui::Button("Nie", ImVec2S(60, 0));
|
|
ImGui::End();
|
|
}
|
|
else
|
|
{
|
|
ImGui::Begin("Crash reporting", nullptr, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize);
|
|
ImGui::TextUnformatted("Crash occurred during last launch of the simulator.\nSend crash report to developers?\n");
|
|
ImGui::TextUnformatted(("Service provided by " + crashreport_get_provider() + "\n").c_str());
|
|
y = ImGui::Button("Yes", ImVec2S(60, 0));
|
|
ImGui::SameLine();
|
|
ImGui::Checkbox("In future send crash reports automatically", &autoup);
|
|
|
|
ImGui::SameLine();
|
|
ImGui::TextDisabled("(?)");
|
|
if (ImGui::IsItemHovered())
|
|
{
|
|
ImGui::BeginTooltip();
|
|
ImGui::TextUnformatted("To disable this feature remove file crashdumps/autoupload_enabled.conf");
|
|
ImGui::EndTooltip();
|
|
}
|
|
|
|
ImGui::NewLine();
|
|
n = ImGui::Button("No", ImVec2S(60, 0));
|
|
ImGui::End();
|
|
}
|
|
|
|
ui_layer::render_internal();
|
|
glfwSwapBuffers(m_windows.front());
|
|
|
|
if (y)
|
|
{
|
|
crashreport_upload_accept();
|
|
if (autoup)
|
|
crashreport_set_autoupload();
|
|
return 0;
|
|
}
|
|
|
|
if (n)
|
|
{
|
|
crashreport_upload_reject();
|
|
return 0;
|
|
}
|
|
}
|
|
return -1;
|
|
}
|
|
#if WITH_DISCORD_RPC
|
|
void eu07_application::DiscordRPCService()
|
|
{
|
|
// initialize discord-rpc
|
|
WriteLog("Initializing Discord Rich Presence...");
|
|
static const char *discord_app_id = "1343662664504840222";
|
|
DiscordEventHandlers handlers;
|
|
memset(&handlers, 0, sizeof(handlers));
|
|
Discord_Initialize(discord_app_id, &handlers, 1, nullptr);
|
|
|
|
// calculate startup timestamp
|
|
auto now = std::chrono::system_clock::now();
|
|
auto now_c = std::chrono::system_clock::to_time_t(now);
|
|
|
|
// Init RPC object
|
|
static DiscordRichPresence discord_rpc;
|
|
memset(&discord_rpc, 0, sizeof(discord_rpc));
|
|
discord_rpc.startTimestamp = static_cast<int64_t>(now_c);
|
|
discord_rpc.largeImageText = "MaSzyna";
|
|
|
|
// run loop
|
|
while (!glfwWindowShouldClose(m_windows.front()) && !m_modestack.empty() && !Global.applicationQuitOrder)
|
|
{
|
|
auto currentMode = m_modestack.top();
|
|
if (currentMode == mode::launcher)
|
|
{
|
|
// in launcher mode
|
|
|
|
discord_rpc.state = Translations.lookup_c("In main menu");
|
|
discord_rpc.details = Translations.lookup_c("Browsing scenarios...");
|
|
discord_rpc.largeImageKey = "";
|
|
discord_rpc.largeImageText = "MaSzyna";
|
|
// RPC upload
|
|
Discord_UpdatePresence(&discord_rpc);
|
|
|
|
std::this_thread::sleep_for(std::chrono::milliseconds(5000)); // update RPC every 5 secs
|
|
continue;
|
|
}
|
|
else if (currentMode == mode::scenarioloader)
|
|
{
|
|
std::string rpcScnName = Global.SceneryFile;
|
|
if (rpcScnName[0] == '$')
|
|
rpcScnName.erase(0, 1);
|
|
rpcScnName.erase(rpcScnName.size() - 4, 4);
|
|
if (rpcScnName.find('_') != std::string::npos)
|
|
{
|
|
std::replace(rpcScnName.begin(), rpcScnName.end(), '_', ' ');
|
|
}
|
|
|
|
// realworld timestamp from datetime
|
|
static std::string state = Translations.lookup_s("Scenery: ") + rpcScnName;
|
|
discord_rpc.state = state.c_str();
|
|
discord_rpc.details = Translations.lookup_c("Loading scenery...");
|
|
discord_rpc.largeImageKey = "logo";
|
|
discord_rpc.largeImageText = "MaSzyna";
|
|
|
|
// RPC upload
|
|
Discord_UpdatePresence(&discord_rpc);
|
|
|
|
std::this_thread::sleep_for(std::chrono::milliseconds(5000)); // update RPC every 5 secs
|
|
continue;
|
|
}
|
|
|
|
if (currentMode != mode::driver)
|
|
{
|
|
// the editor and the other modes: nothing to tell, without spinning a core on it
|
|
std::this_thread::sleep_for(std::chrono::milliseconds(250));
|
|
continue;
|
|
}
|
|
|
|
// Discord RPC updater
|
|
if (simulation::is_ready)
|
|
{
|
|
std::string PlayerVehicle;
|
|
if (simulation::Train != nullptr)
|
|
{
|
|
PlayerVehicle = simulation::Train->name();
|
|
// make to upper
|
|
for (auto &c : PlayerVehicle)
|
|
c = toupper(c);
|
|
|
|
PlayerVehicle = Translations.lookup_s("Driving: ") + PlayerVehicle;
|
|
discord_rpc.details = PlayerVehicle.c_str();
|
|
|
|
uint16_t playerTrainVelocity = simulation::Train->Dynamic()->GetVelocity();
|
|
if (playerTrainVelocity > 1)
|
|
{
|
|
// ikonka ze jedziemy i nie spimy
|
|
discord_rpc.smallImageKey = "driving";
|
|
std::string smallText = Translations.lookup_s("Speed: ") + std::to_string(playerTrainVelocity) + " km/h";
|
|
discord_rpc.smallImageText = smallText.c_str();
|
|
}
|
|
else
|
|
{
|
|
// krecimy postoj
|
|
discord_rpc.smallImageKey = "halt";
|
|
discord_rpc.smallImageText = Translations.lookup_c("Stopped");
|
|
}
|
|
}
|
|
|
|
Discord_UpdatePresence(&discord_rpc);
|
|
}
|
|
std::this_thread::sleep_for(std::chrono::milliseconds(5000)); // update RPC every 5 secs
|
|
}
|
|
|
|
Discord_Shutdown();
|
|
|
|
}
|
|
#endif
|
|
|
|
int eu07_application::init(int Argc, char *Argv[])
|
|
{
|
|
|
|
int result{0};
|
|
// a test run is known before anything is logged: whoever started it reads its result on the standard output,
|
|
// which the log isn't written to then (eu07/maszyna#541)
|
|
Global.test.enabled = simulation::parse_test_command_line(std::vector<char const *>(Argv, Argv + Argc)).enabled;
|
|
// start logging service
|
|
std::thread sLoggingService(LogService);
|
|
Global.threads.emplace("LogService", std::move(sLoggingService));
|
|
|
|
init_debug();
|
|
init_files();
|
|
if ((result = init_settings(Argc, Argv)) != 0)
|
|
{
|
|
ErrorLog("Failed to initialize settings! Maybe you're missing eu07.ini file?");
|
|
return result;
|
|
}
|
|
|
|
// the run's seed, settled once and kept in Globals: the engines come out of it.
|
|
// narrowed on purpose - mt19937 and seed_of() both work on 32 bits, and that is
|
|
// the seed somebody can write down and pass on
|
|
if (!Global.random_seed)
|
|
Global.random_seed = static_cast<std::uint32_t>(true_random_seed());
|
|
Global.random_engine.seed(Global.random_seed);
|
|
Global.local_random_engine.seed(Global.random_seed);
|
|
|
|
// configure the OS console according to Globals.ShowSystemConsole.
|
|
// must run AFTER init_settings (so the ini-loaded value is honoured) and
|
|
// BEFORE the first WriteLog below (so colored \033[...] sequences emitted
|
|
// by utilities/Logs.cpp land in a console with VT processing enabled).
|
|
init_console();
|
|
|
|
WriteLog("Starting MaSzyna rail vehicle simulator (release: " + Global.asVersion + ")");
|
|
WriteLog("For online documentation and additional files refer to: http://eu07.pl");
|
|
WriteLog("Authors: Marcin_EU, McZapkie, ABu, Winger, Tolaris, nbmx, OLO_EU, Bart, Quark-t, "
|
|
"ShaXbee, Oli_EU, youBy, KURS90, Ra, hunter, szociu, Stele, Q, firleju and others");
|
|
|
|
if (!crashreport_get_provider().empty())
|
|
WriteLog("Crashdump analysis provided by " + crashreport_get_provider() + "\n");
|
|
|
|
{
|
|
WriteLog("// settings");
|
|
std::stringstream settingspipe;
|
|
Global.export_as_text(settingspipe);
|
|
WriteLog(settingspipe.str());
|
|
}
|
|
|
|
// cruel way to prevent crashes because of threaded upload from python
|
|
if (Global.NvRenderer)
|
|
Global.python_threadedupload = false;
|
|
|
|
WriteLog("// startup");
|
|
|
|
if ((result = init_glfw()) != 0)
|
|
{
|
|
ErrorLog("Failed to initialize glfw!");
|
|
return result;
|
|
}
|
|
if (needs_ogl() && (result = init_ogl()) != 0)
|
|
{
|
|
ErrorLog("Failed to initialize ogl!");
|
|
return result;
|
|
}
|
|
|
|
if (crashreport_is_pending() && false == Global.test.enabled)
|
|
{ // run crashgui as early as possible
|
|
if ((result = run_crashgui()) != 0)
|
|
{
|
|
ErrorLog("Failed to run crash gui!");
|
|
return result;
|
|
}
|
|
}
|
|
|
|
if ((result = init_locale()) != 0)
|
|
{
|
|
ErrorLog("Failed to initialize locales! Maybe you're missing lang directory?");
|
|
return result;
|
|
}
|
|
|
|
if ((result = init_gfx()) != 0)
|
|
{
|
|
ErrorLog("Failed to initialize GFX!");
|
|
return result;
|
|
}
|
|
|
|
if ((result = init_ui()) != 0)
|
|
{ // ui now depends on activated renderer
|
|
ErrorLog("Failed to init UI!");
|
|
return result;
|
|
}
|
|
if ((result = init_audio()) != 0)
|
|
{
|
|
ErrorLog("Failed to initialize OpenAL");
|
|
return result;
|
|
}
|
|
if ((result = init_data()) != 0)
|
|
{
|
|
ErrorLog("Failed to load data/ contents! Maybe your installation is broken?");
|
|
return result;
|
|
}
|
|
crashreport_add_info("python_enabled", Global.python_enabled ? "yes" : "no");
|
|
if (Global.python_enabled)
|
|
{
|
|
m_taskqueue.init();
|
|
}
|
|
crashreport_add_info("luascreens_enabled", Global.luascreens_enabled ? "yes" : "no");
|
|
crashreport_add_info("wasm_enabled", Global.wasm_enabled ? "yes" : "no");
|
|
if (Global.luascreens_enabled || Global.wasm_enabled)
|
|
{
|
|
m_screenqueue.init();
|
|
if (Global.screens_gpupost)
|
|
{
|
|
m_screenqueue.set_post_processor(GfxRenderer->Screen_post_processor());
|
|
}
|
|
}
|
|
if ((result = init_modes()) != 0)
|
|
{
|
|
ErrorLog("Failed to initialize game modes");
|
|
return result;
|
|
}
|
|
|
|
|
|
#if WITH_DISCORD_RPC
|
|
// Run DiscordRPC service
|
|
// not for a test run: it would show the test scenery as the player's presence, and hold up the closing
|
|
if (false == Global.test.enabled)
|
|
{
|
|
std::thread sDiscordRPC(&eu07_application::DiscordRPCService, this);
|
|
Global.threads.emplace("DiscordRPC", std::move(sDiscordRPC));
|
|
}
|
|
#endif
|
|
|
|
if (!init_network())
|
|
return -1;
|
|
|
|
return result;
|
|
}
|
|
|
|
double eu07_application::generate_sync()
|
|
{
|
|
if (Timer::GetDeltaTime() == 0.0)
|
|
return 0.0;
|
|
double sync = 0.0;
|
|
for (const TDynamicObject *vehicle : simulation::Vehicles.sequence())
|
|
{
|
|
auto const pos{vehicle->GetPosition()};
|
|
sync += pos.x + pos.y + pos.z;
|
|
}
|
|
sync += Random(1.0, 100.0);
|
|
return sync;
|
|
}
|
|
|
|
void eu07_application::queue_quit(bool direct)
|
|
{
|
|
if (direct || !m_modes[m_modestack.top()]->is_command_processor())
|
|
{
|
|
glfwSetWindowShouldClose(m_windows[0], GLFW_TRUE);
|
|
return;
|
|
}
|
|
|
|
command_relay relay;
|
|
relay.post(user_command::quitsimulation, 0.0, 0.0, GLFW_PRESS, 0);
|
|
}
|
|
|
|
bool eu07_application::is_server() const
|
|
{
|
|
|
|
return m_network && m_network->servers;
|
|
}
|
|
|
|
bool eu07_application::is_client() const
|
|
{
|
|
|
|
return m_network && m_network->client;
|
|
}
|
|
|
|
int eu07_application::run()
|
|
{
|
|
auto frame{0};
|
|
frame_pacer framepacer;
|
|
Timer::subsystem.mainloop_period.start();
|
|
// main application loop
|
|
while (!glfwWindowShouldClose(m_windows.front()) && !m_modestack.empty())
|
|
{
|
|
// the time from one frame's start to the next, the wait for fpslimit included
|
|
Timer::subsystem.mainloop_period.stop();
|
|
Timer::subsystem.mainloop_period.start();
|
|
Timer::subsystem.mainloop_total.start();
|
|
glfwPollEvents();
|
|
|
|
if (m_headtrack)
|
|
m_headtrack->update();
|
|
|
|
begin_ui_frame();
|
|
|
|
// -------------------------------------------------------------------
|
|
// multiplayer command relaying logic can seem a bit complex
|
|
//
|
|
// we are simultaneously:
|
|
// => master (not client) OR slave (client)
|
|
// => server OR not
|
|
//
|
|
// trivia: being client and server is possible
|
|
|
|
double frameStartTime = Timer::GetTime();
|
|
|
|
if (m_modes[m_modestack.top()]->is_command_processor())
|
|
{
|
|
// active mode is doing real calculations (e.g. drivermode)
|
|
int loop_remaining = MAX_NETWORK_PER_FRAME;
|
|
while (--loop_remaining > 0)
|
|
{
|
|
command_queue::commands_map commands_to_exec;
|
|
command_queue::commands_map local_commands = simulation::Commands.pop_intercept_queue();
|
|
double slave_sync{0.0};
|
|
|
|
// if we're the server
|
|
if (m_network && m_network->servers)
|
|
{
|
|
// fetch from network layer command requests received from clients
|
|
command_queue::commands_map remote_commands = m_network->servers->pop_commands();
|
|
|
|
// push these into local queue
|
|
add_to_dequemap(local_commands, remote_commands);
|
|
}
|
|
|
|
// if we're slave
|
|
if (m_network && m_network->client)
|
|
{
|
|
// fetch frame info from network layer,
|
|
auto frame_info = m_network->client->get_next_delta(MAX_NETWORK_PER_FRAME - loop_remaining);
|
|
|
|
// use delta and commands received from master
|
|
double delta = std::get<0>(frame_info);
|
|
Timer::set_delta_override(delta);
|
|
slave_sync = std::get<1>(frame_info);
|
|
add_to_dequemap(commands_to_exec, std::get<2>(frame_info));
|
|
|
|
// and send our local commands to master
|
|
m_network->client->send_commands(local_commands);
|
|
|
|
if (delta == 0.0)
|
|
loop_remaining = -1;
|
|
}
|
|
// if we're master
|
|
else
|
|
{
|
|
// just push local commands to execution
|
|
add_to_dequemap(commands_to_exec, local_commands);
|
|
|
|
loop_remaining = -1;
|
|
}
|
|
|
|
// send commands to command queue
|
|
simulation::Commands.push_commands(commands_to_exec);
|
|
|
|
// do actual frame processing (depending on mode)
|
|
if (!m_modes[m_modestack.top()]->update())
|
|
return 0;
|
|
|
|
// update continuous commands
|
|
simulation::Commands.update();
|
|
|
|
double sync = generate_sync();
|
|
|
|
// if we're the server
|
|
if (m_network && m_network->servers)
|
|
{
|
|
// send delta, sync, and commands we just executed to clients
|
|
double delta = Timer::GetDeltaTime();
|
|
double render = Timer::GetDeltaRenderTime();
|
|
m_network->servers->push_delta(render, delta, sync, commands_to_exec);
|
|
}
|
|
|
|
// if we're slave
|
|
if (m_network && m_network->client)
|
|
{
|
|
// verify sync
|
|
if (sync != slave_sync) // NOSONAR slave_sync is initialised, the PR analysis keeps a stale report of the old declaration
|
|
{
|
|
WriteLog("net: desync! calculated: " + std::to_string(sync) + ", received: " + std::to_string(slave_sync), logtype::net);
|
|
|
|
Global.desync = slave_sync - sync;
|
|
}
|
|
|
|
// set total delta for rendering code
|
|
double totalDelta = Timer::GetTime() - frameStartTime;
|
|
Timer::set_delta_override(totalDelta);
|
|
}
|
|
}
|
|
|
|
if (!loop_remaining)
|
|
{
|
|
// loop break forced by counter
|
|
float received = m_network->client->get_frame_counter();
|
|
float awaiting = m_network->client->get_awaiting_frames();
|
|
|
|
// TODO: don't meddle with mode progresbar
|
|
m_modes[m_modestack.top()]->set_progress(100.0f * (received - awaiting) / received);
|
|
}
|
|
else
|
|
{
|
|
m_modes[m_modestack.top()]->set_progress(0.0f, 0.0f);
|
|
}
|
|
}
|
|
else
|
|
{
|
|
// active mode is loader
|
|
|
|
// clear local command queue
|
|
simulation::Commands.pop_intercept_queue();
|
|
|
|
// do actual frame processing
|
|
if (!m_modes[m_modestack.top()]->update())
|
|
return 0;
|
|
}
|
|
|
|
// -------------------------------------------------------------------
|
|
|
|
// keep streamed terrain loaded around the active camera in every mode (editor + driver),
|
|
// once the simulation is live (avoid streaming while the scenery is still loading)
|
|
if (simulation::is_ready && EditorTerrain.active())
|
|
EditorTerrain.update(Global.pCamera.Pos);
|
|
|
|
m_taskqueue.update();
|
|
m_screenqueue.update();
|
|
opengl_texture::reset_unit_cache();
|
|
|
|
if (!GfxRenderer->Render())
|
|
break;
|
|
|
|
GfxRenderer->SwapBuffers();
|
|
|
|
if (m_modestack.empty())
|
|
break;
|
|
|
|
m_modes[m_modestack.top()]->on_event_poll();
|
|
|
|
if (m_screenshot_queued)
|
|
{
|
|
m_screenshot_queued = false;
|
|
GfxRenderer->MakeScreenshot();
|
|
}
|
|
|
|
if (m_network)
|
|
m_network->update();
|
|
|
|
Timer::subsystem.mainloop_total.stop();
|
|
// fpslimit: wait for the next frame's slot (eu07/maszyna#416)
|
|
if (auto const nextframe{framepacer.next_frame(frame_pacer::clock::now(), Global.minframetime)})
|
|
{
|
|
std::this_thread::sleep_until(*nextframe);
|
|
}
|
|
}
|
|
// Handled by application.exit
|
|
// Global.applicationQuitOrder = true;
|
|
// auto it = Global.threads.find("LogService");
|
|
// if (it != Global.threads.end())
|
|
// {
|
|
// if (it->second.joinable())
|
|
// it->second.join();
|
|
// }
|
|
//
|
|
// it = Global.threads.find("DiscordRPC");
|
|
// if (it != Global.threads.end())
|
|
// {
|
|
// if (it->second.joinable())
|
|
// it->second.join();
|
|
// }
|
|
return 0;
|
|
}
|
|
|
|
// issues request for a worker thread to perform specified task. returns: true if task was scheduled
|
|
bool eu07_application::request(python_taskqueue::task_request const &Task)
|
|
{
|
|
|
|
auto const result{m_taskqueue.insert(Task)};
|
|
if (false == result && Task.input != nullptr)
|
|
{
|
|
// clean up allocated resources since the worker won't
|
|
}
|
|
return result;
|
|
}
|
|
|
|
// ensures the main thread holds the python gil and can safely execute python calls
|
|
void eu07_application::acquire_python_lock()
|
|
{
|
|
|
|
m_taskqueue.acquire_lock();
|
|
}
|
|
|
|
// frees the python gil and swaps out the main thread
|
|
void eu07_application::release_python_lock()
|
|
{
|
|
|
|
m_taskqueue.release_lock();
|
|
}
|
|
|
|
void eu07_application::exit()
|
|
{
|
|
Global.applicationQuitOrder = true;
|
|
// each step of the closing in the log, to tell from it where a closing that hangs stops
|
|
auto const closing{std::chrono::steady_clock::now()};
|
|
auto const step = [closing](char const *What) {
|
|
WriteLog(std::format("Closing: {} at {} ms", What, std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - closing).count()));
|
|
};
|
|
step("the sleepers laid in the background");
|
|
// the sleepers laid in the background read the scenery, which goes below
|
|
track_sleepers::stop_background();
|
|
step("the black box");
|
|
simulation::Blackbox.close();
|
|
step("the physics logs");
|
|
// what is kept of them, the black box's written last, waited for a second at most: the rest is dropped
|
|
PhysicsLogs.stop();
|
|
step("the modes");
|
|
for (auto &mode : m_modes)
|
|
mode.reset();
|
|
|
|
step("the renderer");
|
|
// the screens' post-processing goes with the renderer
|
|
m_screenqueue.set_post_processor(nullptr);
|
|
GfxRenderer->Shutdown();
|
|
m_network.reset();
|
|
|
|
// SafeDelete( simulation::Train );
|
|
step("the odometers");
|
|
simulation::Vehicles.save_odometers();
|
|
step("the scenery");
|
|
SafeDelete(simulation::Region);
|
|
|
|
step("the ui and the python workers");
|
|
ui_layer::shutdown();
|
|
|
|
// the python workers detach their GL context on the way out, so they have to be done before the windows they use are destroyed
|
|
m_taskqueue.exit();
|
|
m_screenqueue.exit();
|
|
step("the windows");
|
|
for (auto *window : m_windows)
|
|
{
|
|
glfwDestroyWindow(window);
|
|
}
|
|
glfwPollEvents(); // TODO: This fixes a segfault on Wayland when closing. Remove after updating glfw to 3.5.
|
|
glfwTerminate();
|
|
|
|
if (!Global.exec_on_exit.empty())
|
|
system(Global.exec_on_exit.c_str());
|
|
|
|
step("done");
|
|
StopLogService();
|
|
auto it = Global.threads.find("LogService");
|
|
if (it != Global.threads.end())
|
|
{
|
|
if (it->second.joinable())
|
|
it->second.join();
|
|
}
|
|
|
|
#if WITH_DISCORD_RPC
|
|
it = Global.threads.find("DiscordRPC");
|
|
if (it != Global.threads.end())
|
|
{
|
|
if (it->second.joinable())
|
|
it->second.join();
|
|
}
|
|
#endif
|
|
}
|
|
|
|
void eu07_application::render_ui()
|
|
{
|
|
|
|
if (m_modestack.empty())
|
|
{
|
|
return;
|
|
}
|
|
|
|
m_modes[m_modestack.top()]->render_ui();
|
|
}
|
|
|
|
void eu07_application::begin_ui_frame()
|
|
{
|
|
|
|
if (m_modestack.empty())
|
|
{
|
|
return;
|
|
}
|
|
|
|
m_modes[m_modestack.top()]->begin_ui_frame();
|
|
}
|
|
|
|
bool eu07_application::pop_mode()
|
|
{
|
|
if (m_modestack.empty())
|
|
{
|
|
return false;
|
|
}
|
|
|
|
m_modes[m_modestack.top()]->exit();
|
|
m_modestack.pop();
|
|
return true;
|
|
}
|
|
|
|
bool eu07_application::push_mode(mode const Mode)
|
|
{
|
|
|
|
if (Mode >= count_)
|
|
return false;
|
|
|
|
if (!m_modes[Mode])
|
|
{
|
|
if (Mode == launcher)
|
|
m_modes[Mode] = std::make_shared<launcher_mode>();
|
|
if (Mode == scenarioloader)
|
|
m_modes[Mode] = std::make_shared<scenarioloader_mode>();
|
|
if (Mode == driver)
|
|
m_modes[Mode] = std::make_shared<driver_mode>();
|
|
if (Mode == editor)
|
|
m_modes[Mode] = std::make_shared<editor_mode>();
|
|
|
|
if (!m_modes[Mode]->init())
|
|
return false;
|
|
}
|
|
|
|
m_modes[Mode]->enter();
|
|
m_modestack.push(Mode);
|
|
|
|
return true;
|
|
}
|
|
|
|
void eu07_application::set_title(std::string const &Title)
|
|
{
|
|
|
|
glfwSetWindowTitle(m_windows.front(), Title.c_str());
|
|
}
|
|
|
|
void eu07_application::set_progress(float const Progress, float const Subtaskprogress)
|
|
{
|
|
|
|
if (m_modestack.empty())
|
|
{
|
|
return;
|
|
}
|
|
|
|
m_modes[m_modestack.top()]->set_progress(Progress, Subtaskprogress);
|
|
}
|
|
|
|
void eu07_application::set_tooltip(std::string const &Tooltip)
|
|
{
|
|
|
|
if (m_modestack.empty())
|
|
{
|
|
return;
|
|
}
|
|
|
|
m_modes[m_modestack.top()]->set_tooltip(Tooltip);
|
|
}
|
|
|
|
void eu07_application::set_cursor(int const Mode)
|
|
{
|
|
|
|
ui_layer::set_cursor(Mode);
|
|
}
|
|
|
|
void eu07_application::set_cursor_pos(double const Horizontal, double const Vertical)
|
|
{
|
|
|
|
glfwSetCursorPos(m_windows.front(), Horizontal, Vertical);
|
|
}
|
|
|
|
/*
|
|
// provides keyboard mapping associated with specified control item
|
|
std::string
|
|
eu07_application::get_input_hint( user_command const Command ) const {
|
|
|
|
if( m_modestack.empty() ) { return ""; }
|
|
|
|
return m_modes[ m_modestack.top() ]->get_input_hint( Command );
|
|
}
|
|
*/
|
|
|
|
void eu07_application::on_key(int const Key, int const Scancode, int const Action, int const Mods)
|
|
{
|
|
|
|
if (ui_layer::key_callback(Key, Scancode, Action, Mods))
|
|
return;
|
|
|
|
if (m_modestack.empty())
|
|
{
|
|
return;
|
|
}
|
|
|
|
#ifdef __unix__
|
|
if (Key == GLFW_KEY_LEFT_SHIFT || Key == GLFW_KEY_RIGHT_SHIFT)
|
|
Global.shiftState = Action == GLFW_PRESS;
|
|
if (Key == GLFW_KEY_LEFT_CONTROL || Key == GLFW_KEY_RIGHT_CONTROL)
|
|
Global.ctrlState = Action == GLFW_PRESS;
|
|
if (Key == GLFW_KEY_LEFT_ALT || Key == GLFW_KEY_RIGHT_ALT)
|
|
Global.altState = Action == GLFW_PRESS;
|
|
#endif
|
|
|
|
m_modes[m_modestack.top()]->on_key(Key, Scancode, Action, Mods);
|
|
}
|
|
|
|
void eu07_application::on_cursor_pos(double const Horizontal, double const Vertical)
|
|
{
|
|
|
|
if (m_modestack.empty())
|
|
{
|
|
return;
|
|
}
|
|
|
|
m_modes[m_modestack.top()]->on_cursor_pos(Horizontal, Vertical);
|
|
}
|
|
|
|
void eu07_application::on_mouse_button(int const Button, int const Action, int const Mods)
|
|
{
|
|
|
|
if (ui_layer::mouse_button_callback(Button, Action, Mods))
|
|
return;
|
|
|
|
if (m_modestack.empty())
|
|
{
|
|
return;
|
|
}
|
|
|
|
m_modes[m_modestack.top()]->on_mouse_button(Button, Action, Mods);
|
|
}
|
|
|
|
void eu07_application::on_scroll(double const Xoffset, double const Yoffset)
|
|
{
|
|
|
|
if (ui_layer::scroll_callback(Xoffset, Yoffset))
|
|
return;
|
|
|
|
if (m_modestack.empty())
|
|
{
|
|
return;
|
|
}
|
|
|
|
m_modes[m_modestack.top()]->on_scroll(Xoffset, Yoffset);
|
|
}
|
|
|
|
void eu07_application::on_char(unsigned int c)
|
|
{
|
|
if (ui_layer::char_callback(c))
|
|
return;
|
|
}
|
|
|
|
void eu07_application::on_focus_change(bool focus)
|
|
{
|
|
if (Global.bInactivePause && m_network.has_value() && !m_network->client)
|
|
{ // jeśli ma być pauzowanie okna w tle
|
|
command_relay relay;
|
|
relay.post(user_command::focuspauseset, focus ? 1.0 : 0.0, 0.0, GLFW_PRESS, 0);
|
|
}
|
|
}
|
|
|
|
void eu07_application::on_window_resize(int w, int h)
|
|
{
|
|
if (m_modestack.empty())
|
|
return;
|
|
m_modes[m_modestack.top()]->on_window_resize(w, h);
|
|
}
|
|
|
|
GLFWwindow *eu07_application::window(int const Windowindex, bool visible, int width, int height, GLFWmonitor *monitor, bool keep_ownership, bool share_ctx)
|
|
{
|
|
|
|
if (Windowindex >= 0)
|
|
{
|
|
return Windowindex < m_windows.size() ? m_windows[Windowindex] : nullptr;
|
|
}
|
|
// for index -1 create a new child window
|
|
|
|
auto *videomonitor{monitor ? monitor : glfwGetPrimaryMonitor()};
|
|
// a machine without a display (e.g. a test runner) has no monitor to match
|
|
if (auto const *vmode{videomonitor ? glfwGetVideoMode(videomonitor) : nullptr})
|
|
{
|
|
// match requested video mode to current to allow for
|
|
// fullwindow creation when resolution is the same
|
|
glfwWindowHint(GLFW_RED_BITS, vmode->redBits);
|
|
glfwWindowHint(GLFW_GREEN_BITS, vmode->greenBits);
|
|
glfwWindowHint(GLFW_BLUE_BITS, vmode->blueBits);
|
|
glfwWindowHint(GLFW_REFRESH_RATE, vmode->refreshRate);
|
|
}
|
|
|
|
glfwWindowHint(GLFW_VISIBLE, visible);
|
|
|
|
auto *childwindow = glfwCreateWindow(width, height, "eu07window", monitor, share_ctx ? m_windows.front() : nullptr);
|
|
if (!childwindow)
|
|
return nullptr;
|
|
|
|
if (keep_ownership)
|
|
m_windows.emplace_back(childwindow);
|
|
|
|
if (glfwGetWindowAttrib(m_windows.front(), GLFW_VISIBLE))
|
|
glfwFocusWindow(m_windows.front()); // restore focus to main window
|
|
|
|
return childwindow;
|
|
}
|
|
|
|
// private:
|
|
GLFWmonitor *eu07_application::find_monitor(const std::string &str) const
|
|
{
|
|
int monitor_count;
|
|
GLFWmonitor **monitors = glfwGetMonitors(&monitor_count);
|
|
|
|
for (size_t i = 0; i < monitor_count; i++)
|
|
{
|
|
if (describe_monitor(monitors[i]) == str)
|
|
return monitors[i];
|
|
}
|
|
|
|
return nullptr;
|
|
}
|
|
|
|
std::string eu07_application::describe_monitor(GLFWmonitor *monitor) const
|
|
{
|
|
std::string name(glfwGetMonitorName(monitor));
|
|
std::replace(std::begin(name), std::end(name), ' ', '_');
|
|
|
|
int x, y;
|
|
glfwGetMonitorPos(monitor, &x, &y);
|
|
|
|
return name + ":" + std::to_string(x) + "," + std::to_string(y);
|
|
}
|
|
|
|
// private:
|
|
|
|
bool eu07_application::needs_ogl() const
|
|
{
|
|
return !Global.NvRenderer;
|
|
}
|
|
|
|
void eu07_application::init_debug()
|
|
{
|
|
|
|
#if defined(_MSC_VER) && defined(_DEBUG)
|
|
// memory leaks
|
|
_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
|
|
/*
|
|
// floating point operation errors
|
|
auto state { _clearfp() };
|
|
state = _control87( 0, 0 );
|
|
// this will turn on FPE for #IND and zerodiv
|
|
state = _control87( state & ~( _EM_ZERODIVIDE | _EM_INVALID ), _MCW_EM );
|
|
*/
|
|
#endif
|
|
}
|
|
|
|
// Honours Globals.ShowSystemConsole (default: true).
|
|
//
|
|
// Windows: if the toggle is on, ensure a console is attached (allocate one when
|
|
// the binary was linked as the WINDOWS subsystem and none is inherited), then
|
|
// reopen the C stdio streams onto it and turn on ENABLE_VIRTUAL_TERMINAL_PROCESSING
|
|
// so the ANSI colour escapes used by utilities/Logs.cpp render correctly.
|
|
// If the toggle is off, hide the console window (or free an allocated one) so
|
|
// the GUI launches without a stray cmd window.
|
|
//
|
|
// Other platforms: no-op. stdout is the launching terminal (or already detached);
|
|
// hiding it on Linux/macOS would mean redirecting to /dev/null and is left to the
|
|
// user's shell (e.g. "./eu07 >/dev/null 2>&1").
|
|
void eu07_application::init_console()
|
|
{
|
|
#ifdef _WIN32
|
|
if (Global.test.enabled)
|
|
{
|
|
// a test is started by whoever waits for its result, often reading its output: no console of its own
|
|
// (showsystemconsole) pops up and takes stdout away from them, and a console it was started from isn't hidden
|
|
return;
|
|
}
|
|
|
|
HWND consoleWnd = ::GetConsoleWindow();
|
|
const bool hadConsole = consoleWnd != nullptr;
|
|
|
|
if (Global.ShowSystemConsole)
|
|
{
|
|
if (!hadConsole)
|
|
{
|
|
// no console inherited (e.g. WINDOWS subsystem build, or launched
|
|
// detached) -- create one and wire stdio to it so printf in
|
|
// utilities/Logs.cpp actually reaches the user
|
|
if (::AllocConsole())
|
|
{
|
|
FILE *fp = nullptr;
|
|
freopen_s(&fp, "CONOUT$", "w", stdout);
|
|
freopen_s(&fp, "CONOUT$", "w", stderr);
|
|
freopen_s(&fp, "CONIN$", "r", stdin);
|
|
// keep C++ streams in sync with the redirected C streams
|
|
std::ios::sync_with_stdio(true);
|
|
std::cout.clear();
|
|
std::cerr.clear();
|
|
std::clog.clear();
|
|
std::cin.clear();
|
|
consoleWnd = ::GetConsoleWindow();
|
|
}
|
|
}
|
|
|
|
// enable ANSI virtual-terminal processing so the colour escapes in
|
|
// utilities/Logs.cpp ("\033[1;37;41m...", "\033[32m...") render as
|
|
// colours instead of literal garbage on the conhost.
|
|
//
|
|
// IMPORTANT: do NOT rely on GetStdHandle(STD_OUTPUT_HANDLE). After
|
|
// AllocConsole + freopen_s the CRT may have rewired things, and on a
|
|
// console-subsystem build the std handle can also point to a redirected
|
|
// pipe/file rather than the actual console screen buffer -- in either
|
|
// case SetConsoleMode silently fails and the escape bytes leak through
|
|
// as text ("←[32m" etc). Open CONOUT$ directly to get the real screen
|
|
// buffer handle, then flip VT on it.
|
|
auto enable_vt = [](const char *devName) {
|
|
HANDLE h = ::CreateFileA(
|
|
devName,
|
|
GENERIC_READ | GENERIC_WRITE,
|
|
FILE_SHARE_READ | FILE_SHARE_WRITE,
|
|
nullptr,
|
|
OPEN_EXISTING,
|
|
0,
|
|
nullptr);
|
|
if (h == INVALID_HANDLE_VALUE)
|
|
return;
|
|
DWORD mode = 0;
|
|
if (::GetConsoleMode(h, &mode))
|
|
{
|
|
::SetConsoleMode(h, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING | ENABLE_PROCESSED_OUTPUT);
|
|
}
|
|
::CloseHandle(h);
|
|
};
|
|
// CONOUT$ is the console's active screen buffer; enabling VT on it
|
|
// affects everything that ends up being written there, regardless of
|
|
// which FILE* / std handle the writer used
|
|
enable_vt("CONOUT$");
|
|
|
|
if (consoleWnd)
|
|
{
|
|
::ShowWindow(consoleWnd, SW_SHOW);
|
|
// give the console a recognisable title
|
|
::SetConsoleTitleA("MaSzyna log");
|
|
}
|
|
}
|
|
else
|
|
{
|
|
// user wants no console window -- hide whatever we have
|
|
if (consoleWnd)
|
|
{
|
|
::ShowWindow(consoleWnd, SW_HIDE);
|
|
}
|
|
// if we'd allocated one ourselves on a previous run path we'd FreeConsole here,
|
|
// but on first init the console (if any) was inherited from the launcher and
|
|
// belongs to it -- just hiding the window is the least-surprising behaviour
|
|
}
|
|
#endif
|
|
}
|
|
|
|
void eu07_application::init_files()
|
|
{
|
|
|
|
#ifdef _WIN32
|
|
DeleteFile("log.txt");
|
|
DeleteFile("errors.txt");
|
|
CreateDirectory("logs", nullptr);
|
|
#elif __unix__
|
|
unlink("log.txt");
|
|
unlink("errors.txt");
|
|
mkdir("logs", 0750);
|
|
#endif
|
|
}
|
|
namespace fs = std::filesystem;
|
|
|
|
int eu07_application::init_settings(int Argc, char *Argv[])
|
|
{
|
|
Global.asVersion = VERSION_INFO;
|
|
|
|
// a test run is known before the rest of the command line is read (Global.test.enabled, see init()), so a
|
|
// command line it can't take ends with the error code of the test, not with 0, which would pass it
|
|
auto const testcommandline{simulation::parse_test_command_line(std::vector<char const *>(Argv, Argv + Argc))};
|
|
if (false == testcommandline.error.empty())
|
|
{
|
|
simulation::test().conclude(simulation::test_result::error, testcommandline.error);
|
|
return -1;
|
|
}
|
|
if (testcommandline.timeout.has_value())
|
|
{
|
|
Global.test.timeout = *testcommandline.timeout;
|
|
Global.test.timeout_from_command_line = true;
|
|
}
|
|
if (testcommandline.wall_timeout.has_value())
|
|
{
|
|
Global.test.wall_timeout = testcommandline.wall_timeout;
|
|
Global.test.wall_timeout_from_command_line = true;
|
|
}
|
|
|
|
fs::path iniPath = user_config_path("eu07.ini");
|
|
|
|
// a test reads the settings of the game folder only (and those given with -ini), not the player's own
|
|
// (%APPDATA%/MaSzyna, ~/.config/MaSzyna), so it runs the same for whoever runs it
|
|
if (false == Global.test.enabled && !iniPath.empty() && fs::exists(iniPath))
|
|
{
|
|
Global.LoadIniFile(iniPath.string().c_str());
|
|
}
|
|
else
|
|
{
|
|
Global.LoadIniFile("eu07.ini");
|
|
}
|
|
|
|
// process command line arguments
|
|
bool sceneryfromcommandline{false};
|
|
bool editwithoutscenery{false};
|
|
for (int i = 1; i < Argc; ++i)
|
|
{
|
|
|
|
std::string token{Argv[i]};
|
|
|
|
if (token == "-s")
|
|
{
|
|
if (i + 1 < Argc)
|
|
{
|
|
Global.SceneryFile = ToLower(Argv[++i]);
|
|
sceneryfromcommandline = true;
|
|
}
|
|
}
|
|
else if (token == "-v")
|
|
{
|
|
if (i + 1 < Argc)
|
|
{
|
|
Global.local_start_vehicle = ToLower(Argv[++i]);
|
|
}
|
|
}
|
|
else if (token == "-edit")
|
|
{
|
|
// edit session: the scenery is loaded without player vehicle, straight into the editor
|
|
Global.editor_session = true;
|
|
Global.local_start_vehicle = "ghostview";
|
|
if (i + 1 < Argc && Argv[i + 1][0] != '-')
|
|
{
|
|
Global.SceneryFile = ToLower(Argv[++i]);
|
|
sceneryfromcommandline = true;
|
|
}
|
|
else
|
|
editwithoutscenery = true;
|
|
}
|
|
else if (token == "-seed")
|
|
{
|
|
// a number is the seed; anything else is a word that stands for one. said in the
|
|
// log as it was given, because that is what gets passed on to somebody else
|
|
if (i + 1 < Argc)
|
|
{
|
|
Global.random_seed = seed_of(Argv[++i]);
|
|
WriteLog(std::format("seed given on the command line: {} -> {}", Argv[i], Global.random_seed));
|
|
}
|
|
}
|
|
else if (token == "--test")
|
|
{
|
|
// integration test: the scenery runs unattended and the exit code is the result (eu07/maszyna#541),
|
|
// taken from the command line above
|
|
}
|
|
else if (token == "--test-timeout" || token == "--test-wall-timeout")
|
|
{
|
|
// taken from the command line above, with its value
|
|
++i;
|
|
}
|
|
else if (token == "-ini")
|
|
{
|
|
// extra settings file read on top of eu07.ini, so a run can override a few keys
|
|
// (window size, physicslog...) without touching the user's own config
|
|
if (i + 1 < Argc)
|
|
{
|
|
Global.LoadIniFile(Argv[++i]);
|
|
}
|
|
}
|
|
else
|
|
{
|
|
// a test's standard output carries its result only
|
|
(Global.test.enabled ? std::cerr : std::cout) << "usage: " << std::string(Argv[0]) << " [-s sceneryfilepath]"
|
|
<< " [-v vehiclename]"
|
|
<< " [-edit [sceneryfilepath]]"
|
|
<< " [-seed number|word]"
|
|
<< " [-ini settingsfile]"
|
|
<< " [--test [--test-timeout seconds] [--test-wall-timeout seconds]]" << std::endl;
|
|
simulation::test().conclude(simulation::test_result::error, std::format("unknown command line argument {}", token));
|
|
return -1;
|
|
}
|
|
}
|
|
if (editwithoutscenery && false == sceneryfromcommandline)
|
|
Global.SceneryFile.clear();
|
|
|
|
if (Global.test.enabled)
|
|
{
|
|
if (false == sceneryfromcommandline || Global.SceneryFile.empty())
|
|
{
|
|
simulation::test().conclude(simulation::test_result::error, "--test needs a scenery given with -s");
|
|
return -1;
|
|
}
|
|
simulation::apply_test_mode_settings();
|
|
}
|
|
|
|
// a renderer this build doesn't have gets the full one: the starter writes the words of every build it knows
|
|
// ("vulkan" for the vulkan builds), and any word not known here used to start the legacy renderer.
|
|
// "simpleshader" and "off" of the older starters keep the legacy one they always had
|
|
auto const &renderer{Global.GfxRenderer};
|
|
auto const known{renderer == "default" || renderer == "legacy" || renderer == "simple" || renderer == "null" || renderer == "simpleshader" ||
|
|
renderer == "off" || (renderer == "experimental" && gfx_renderer_factory::get_instance()->has_backend(renderer))};
|
|
if (false == known)
|
|
{
|
|
WriteLog("gfxrenderer \"" + renderer + "\" isn't in this build, the full renderer is used instead");
|
|
Global.GfxRenderer = "default";
|
|
Global.NvRenderer = false;
|
|
Global.LegacyRenderer = false;
|
|
Global.BasicRenderer = false;
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|
|
int eu07_application::init_locale()
|
|
{
|
|
|
|
Translations.init();
|
|
|
|
return 0;
|
|
}
|
|
|
|
int eu07_application::init_glfw()
|
|
{
|
|
{
|
|
int glfw_major, glfw_minor, glfw_rev;
|
|
glfwGetVersion(&glfw_major, &glfw_minor, &glfw_rev);
|
|
m_glfwversion = glfw_major * 10000 + glfw_minor * 100 + glfw_minor;
|
|
}
|
|
|
|
#ifdef GLFW_ANGLE_PLATFORM_TYPE
|
|
if (m_glfwversion >= 30400)
|
|
{
|
|
int platform = GLFW_ANGLE_PLATFORM_TYPE_NONE;
|
|
if (Global.gfx_angleplatform == "opengl")
|
|
platform = GLFW_ANGLE_PLATFORM_TYPE_OPENGL;
|
|
else if (Global.gfx_angleplatform == "opengles")
|
|
platform = GLFW_ANGLE_PLATFORM_TYPE_OPENGLES;
|
|
else if (Global.gfx_angleplatform == "d3d9")
|
|
platform = GLFW_ANGLE_PLATFORM_TYPE_D3D9;
|
|
else if (Global.gfx_angleplatform == "d3d11")
|
|
platform = GLFW_ANGLE_PLATFORM_TYPE_D3D11;
|
|
else if (Global.gfx_angleplatform == "vulkan")
|
|
platform = GLFW_ANGLE_PLATFORM_TYPE_VULKAN;
|
|
else if (Global.gfx_angleplatform == "metal")
|
|
platform = GLFW_ANGLE_PLATFORM_TYPE_METAL;
|
|
|
|
glfwInitHint(GLFW_ANGLE_PLATFORM_TYPE, platform);
|
|
}
|
|
#endif
|
|
|
|
if (glfwInit() == GLFW_FALSE)
|
|
{
|
|
ErrorLog("Bad init: failed to initialize glfw");
|
|
return -1;
|
|
}
|
|
|
|
{
|
|
int monitor_count;
|
|
GLFWmonitor **monitors = glfwGetMonitors(&monitor_count);
|
|
|
|
WriteLog("available monitors:");
|
|
for (size_t i = 0; i < monitor_count; i++)
|
|
{
|
|
WriteLog(describe_monitor(monitors[i]));
|
|
}
|
|
}
|
|
|
|
auto *monitor{find_monitor(Global.fullscreen_monitor)};
|
|
if (!monitor)
|
|
monitor = glfwGetPrimaryMonitor();
|
|
|
|
glfwWindowHint(GLFW_AUTO_ICONIFY, GLFW_FALSE);
|
|
if ((Global.gfx_skippipeline || Global.LegacyRenderer) && Global.iMultisampling > 0)
|
|
{
|
|
glfwWindowHint(GLFW_SAMPLES, 1 << Global.iMultisampling);
|
|
}
|
|
|
|
crashreport_add_info("gfxrenderer", Global.GfxRenderer);
|
|
|
|
if (!needs_ogl())
|
|
{
|
|
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
|
|
}
|
|
else if (Global.test.enabled)
|
|
{
|
|
// the null renderer draws nothing, but parts of the ui make textures with gl calls of their own.
|
|
// any context will do for them, so none is asked for in particular: a machine without a graphics
|
|
// driver (a test runner) has only the basic one of the system
|
|
}
|
|
else
|
|
{
|
|
if (!Global.LegacyRenderer)
|
|
{
|
|
Global.bUseVBO = true;
|
|
// activate core profile for opengl 3.3 renderer
|
|
if (!Global.gfx_usegles)
|
|
{
|
|
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
|
|
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE);
|
|
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
|
|
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
|
|
}
|
|
else
|
|
{
|
|
#ifdef GLFW_CONTEXT_CREATION_API
|
|
if (m_glfwversion >= 30200)
|
|
glfwWindowHint(GLFW_CONTEXT_CREATION_API, GLFW_EGL_CONTEXT_API);
|
|
#endif
|
|
glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API);
|
|
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
|
|
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
|
|
}
|
|
}
|
|
else
|
|
{
|
|
if (Global.gfx_usegles)
|
|
{
|
|
ErrorLog("legacy renderer not supported in gles mode");
|
|
return -1;
|
|
}
|
|
Global.gfx_shadergamma = false;
|
|
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_ANY_PROFILE);
|
|
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
|
|
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
|
|
}
|
|
|
|
if (Global.gfx_gldebug)
|
|
glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE);
|
|
}
|
|
|
|
glfwWindowHint(GLFW_SRGB_CAPABLE, !Global.gfx_shadergamma);
|
|
|
|
if (Global.fullscreen_windowed)
|
|
{
|
|
auto const mode = glfwGetVideoMode(monitor);
|
|
Global.window_size.x = mode->width;
|
|
Global.window_size.y = mode->height;
|
|
Global.bFullScreen = true;
|
|
}
|
|
|
|
// test mode keeps its window hidden: glfw, the ui and the input still need one, but nothing is shown in it.
|
|
// so does a selftest of the editor run while the computer is in use for something else: never shown nor focused
|
|
bool const shown{false == Global.test.enabled && selftest_script("EU07_EDITOR_SELFTEST_HIDDEN") == nullptr};
|
|
auto *mainwindow = window(-1, shown, Global.window_size.x, Global.window_size.y, Global.bFullScreen && shown ? monitor : nullptr, true, false);
|
|
|
|
if (mainwindow == nullptr)
|
|
{
|
|
ErrorLog("Bad init: failed to create glfw window");
|
|
return -1;
|
|
}
|
|
|
|
glfwMakeContextCurrent(mainwindow);
|
|
glfwSwapInterval(Global.VSync ? 1 : 0); // vsync
|
|
|
|
{
|
|
int width, height;
|
|
|
|
glfwGetFramebufferSize(mainwindow, &width, &height);
|
|
framebuffer_resize_callback(mainwindow, width, height);
|
|
|
|
glfwGetWindowSize(mainwindow, &width, &height);
|
|
window_resize_callback(mainwindow, width, height);
|
|
}
|
|
|
|
#ifdef _WIN32
|
|
// setup wrapper for base glfw window proc, to handle copydata messages
|
|
Hwnd = glfwGetWin32Window(mainwindow);
|
|
// commands sent by other programs are input from outside, which a test doesn't take
|
|
if (false == Global.test.enabled)
|
|
BaseWindowProc = (WNDPROC)::SetWindowLongPtr(Hwnd, GWLP_WNDPROC, (LONG_PTR)WndProc);
|
|
// switch off the topmost flag
|
|
::SetWindowPos(Hwnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
|
|
#endif
|
|
|
|
return 0;
|
|
}
|
|
|
|
void eu07_application::init_callbacks()
|
|
{
|
|
|
|
auto *window{m_windows.front()};
|
|
glfwSetWindowSizeCallback(window, window_resize_callback);
|
|
glfwSetFramebufferSizeCallback(window, framebuffer_resize_callback);
|
|
glfwSetWindowFocusCallback(window, focus_callback);
|
|
glfwSetCursorEnterCallback(window, cursor_enter_callback);
|
|
if (Global.test.enabled)
|
|
{
|
|
// a test takes no input: keys and clicks sent to its hidden window would change the run
|
|
return;
|
|
}
|
|
glfwSetCursorPosCallback(window, cursor_pos_callback);
|
|
glfwSetMouseButtonCallback(window, mouse_button_callback);
|
|
glfwSetKeyCallback(window, key_callback);
|
|
glfwSetScrollCallback(window, scroll_callback);
|
|
glfwSetCharCallback(window, char_callback);
|
|
}
|
|
|
|
int eu07_application::init_ogl()
|
|
{
|
|
if (!Global.gfx_usegles)
|
|
{
|
|
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
|
|
{
|
|
ErrorLog("Bad init: failed to initialize glad");
|
|
return -1;
|
|
}
|
|
}
|
|
else
|
|
{
|
|
if (!gladLoadGLES2Loader((GLADloadproc)glfwGetProcAddress))
|
|
{
|
|
ErrorLog("Bad init: failed to initialize glad");
|
|
return -1;
|
|
}
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|
|
int eu07_application::init_ui()
|
|
{
|
|
if (false == ui_layer::init(m_windows.front()))
|
|
{
|
|
return -1;
|
|
}
|
|
init_callbacks();
|
|
return 0;
|
|
}
|
|
|
|
int eu07_application::init_gfx()
|
|
{
|
|
|
|
if (Global.GfxRenderer == "default")
|
|
{
|
|
// default render path
|
|
GfxRenderer = gfx_renderer_factory::get_instance()->create("modern");
|
|
}
|
|
else if (Global.GfxRenderer == "null")
|
|
{
|
|
// draws nothing and loads no textures (test mode)
|
|
GfxRenderer = gfx_renderer_factory::get_instance()->create("null");
|
|
}
|
|
else if (Global.GfxRenderer == "experimental")
|
|
{
|
|
GfxRenderer = gfx_renderer_factory::get_instance()->create(Global.GfxRenderer);
|
|
}
|
|
else
|
|
{
|
|
// legacy render path
|
|
GfxRenderer = gfx_renderer_factory::get_instance()->create("legacy");
|
|
Global.DisabledLogTypes |= static_cast<unsigned int>(logtype::material);
|
|
}
|
|
|
|
if (!GfxRenderer)
|
|
{
|
|
ErrorLog("no renderer found!");
|
|
return -1;
|
|
}
|
|
|
|
if (false == GfxRenderer->Init(m_windows.front()))
|
|
{
|
|
return -1;
|
|
}
|
|
|
|
for (const global_settings::extraviewport_config &conf : Global.extra_viewports)
|
|
if (!GfxRenderer->AddViewport(conf))
|
|
return -1;
|
|
|
|
if (!Global.headtrack_conf.joy.empty())
|
|
m_headtrack.emplace();
|
|
|
|
return 0;
|
|
}
|
|
|
|
int eu07_application::init_audio()
|
|
{
|
|
|
|
if (Global.bSoundEnabled)
|
|
{
|
|
Global.bSoundEnabled &= audio::renderer.init();
|
|
}
|
|
// NOTE: lack of audio isn't deemed a failure serious enough to throw in the towel
|
|
return 0;
|
|
}
|
|
|
|
int eu07_application::init_data()
|
|
{
|
|
|
|
// HACK: grab content of the first {} block in load_unit_weights using temporary parser, then parse it normally. on any error our weight list will be empty string
|
|
auto loadweights{cParser(cParser("data/load_weights.txt", cParser::buffer_FILE).getToken<std::string>(true, "{}"), cParser::buffer_TEXT)};
|
|
while (true == loadweights.getTokens(2))
|
|
{
|
|
std::pair<std::string, float> weightpair;
|
|
loadweights >> weightpair.first >> weightpair.second;
|
|
weightpair.first.erase(weightpair.first.end() - 1); // trim trailing ':' from the key
|
|
simulation::Weights.emplace(weightpair.first, weightpair.second);
|
|
}
|
|
cParser override_parser("data/sound_overrides.txt", cParser::buffer_FILE);
|
|
deserialize_map(simulation::Sound_overrides, override_parser);
|
|
|
|
return 0;
|
|
}
|
|
|
|
int eu07_application::init_modes()
|
|
{
|
|
// local cosmetics only (sound pitch, editor placement), never security related
|
|
Global.local_random_engine.seed(static_cast<std::mt19937::result_type>(true_random_seed())); // NOSONAR
|
|
|
|
if ((!Global.network_servers.empty() || Global.network_client) && Global.SceneryFile.empty())
|
|
{
|
|
ErrorLog("launcher mode is currently not supported in network mode");
|
|
return -1;
|
|
}
|
|
|
|
// activate the default mode
|
|
if (Global.SceneryFile.empty())
|
|
push_mode(mode::launcher);
|
|
else
|
|
push_mode(mode::scenarioloader);
|
|
|
|
return 0;
|
|
}
|
|
|
|
bool eu07_application::init_network()
|
|
{
|
|
if (!Global.network_servers.empty() || Global.network_client)
|
|
{
|
|
// create network manager
|
|
m_network.emplace();
|
|
}
|
|
|
|
for (auto const &pair : Global.network_servers)
|
|
{
|
|
// create all servers
|
|
m_network->create_server(pair.first, pair.second);
|
|
}
|
|
|
|
if (Global.network_client)
|
|
{
|
|
// create client
|
|
m_network->connect(Global.network_client->first, Global.network_client->second);
|
|
}
|
|
else
|
|
{
|
|
// we're simulation master
|
|
// TODO: sort out this timezone mess
|
|
std::time_t utc_now = std::time(nullptr);
|
|
|
|
std::tm const tm_local = local_tm(utc_now);
|
|
std::tm const tm_utc = utc_tm(utc_now);
|
|
|
|
int64_t offset = tm_local.tm_hour * 3600 + tm_local.tm_min * 60 + tm_local.tm_sec - (tm_utc.tm_hour * 3600 + tm_utc.tm_min * 60 + tm_utc.tm_sec);
|
|
|
|
Global.starting_timestamp = utc_now + offset;
|
|
Global.ready_to_load = true;
|
|
}
|
|
|
|
return true;
|
|
}
|