18
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-12-02 02:42:46 +01:00
Files
maszyna/rendering/geometrystreamer.cpp
T
maj00r 89405a6eaf feat(render): the geometry of the scenery models and the data of the textures streamed, on by default
The streaming of the geometry of EU07M models (modelstreaming) and the streaming of the textures (gfx.textures.streaming) are now
both on by default; either is turned off in eu07.ini with "no", and turned off the game does what it did before.

Geometry (modelstreaming yes, with modelformat eu07m):
- A scenery model (node ... model) of an .eu07m file of at least modelstreaming.minsize KiB (256), without skins, stars and texts of
  E3D and with BNDS, has only its structure read at the load: one read of the beginning of the file (eu07m::read_file() with
  read_options::streams false, validate_scope::structure). Vehicles, cabs, loads and every other model load whole, as before; a
  streamed model asked for by anything else gets its geometry loaded and kept (TModelsManager::GetModel(..., Streamable)).
- Its geometry bank keeps its chunks empty (gfx::residency). A bank without its data draws nothing and is asked of the streamer
  (rendering/geometrystreamer.h): threads read and unpack the streams and the GREF blocks, nearest first, and the main thread hands
  them to the banks, 64 MB or 3 ms a frame. A bank unused for modelstreaming.evictafter s (30) lets go of its data in memory and on
  the GPU; above modelstreaming.budget MB (0, no limit) sooner. Whatever reads the vertices (picking, editor, sky occlusion) gets
  them loaded at once. The walks kept by the GPU culling are made anew when a bank got its data.
- The nodes, materials, components, clips and channels stay loaded: the walk goes through an instance without its geometry as
  through any other (RaAnimate(), RaPrepare()), only its draws are left out, so animations, lights and the events at their ends
  keep their timing. The radius of a streamed model and the bounds of its branches come from BNDS instead of the vertices.
- rendering/common/modelprefetch.h goes through the cells within the draw range and 500 m, 32 a frame, and asks for the geometry
  of the streamed models ahead of their drawing.

Textures (gfx.textures.streaming yes):
- The same pass has the data of the textures of the instances, shapes and tracks in reach read ahead by the texture workers in the
  Vulkan renderer (the OpenGL renderer has its own pass); the read-ahead data not drawn for 5 minutes or left behind is dropped.
- The loading screen waits, two minutes at most, for the geometry and the textures around the start and, in Vulkan, for their
  images made on the GPU (vulkan14_texture::request_background(false), made()).

Measured on Tomaszewo, Vulkan, editor self-test flight start to Kaletnik, four runs on an idle machine, alternated:
- peak committed memory 11.0 GB without streaming, 7.0 GB with textures, 6.2 GB with both; working set 9.0 / 4.8 / 4.2 GB
  (the copies of the texture data were 4.5 GB, the geometry banks 1.55 GB);
- scenario load 104-145 s without, 95-97 s with;
- frame time over the flight the same (11.8-12.5 ms), draws without their texture at the start the same as without streaming and
  fewer in the flight (380 against 636); the prefetch costs the main thread 0.1-0.2 ms a frame.

Also: the self-test commands "modelstream evict|wait|stats" and "memory <label>" (rendering/common/memoryreport.h, a breakdown of
the memory of the process), file_parts (utilities/wholefile.h) for reads of parts of a file, and the docs in docs/eu07m-format.md
("Streaming of the geometry"). The format doesn't change and no asset change is needed. Unit tests: test_eu07m_streaming.cpp.
2026-11-29 20:39:47 +01:00

332 lines
10 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/geometrystreamer.h"
#include "rendering/common/walksync.h"
#include "utilities/Globals.h"
#include "utilities/Logs.h"
#include <algorithm>
#include <format>
namespace gfx {
namespace {
// what a frame hands to the banks at most: the bytes of their data (the vulkan renderer sends them to the gpu the next time it draws
// them) and the time
constexpr std::size_t frame_bytes { std::size_t { 64 } << 20 };
constexpr std::chrono::milliseconds frame_time { 3 };
// the banks with their data gone through by the sweep of a frame
constexpr std::size_t sweep_count { 256 };
// over the budget of the memory (modelstreaming.budget), a bank unused for this long is let go of before its time
constexpr std::uint32_t over_budget_unused_ms { 2000 };
} // namespace
geometry_streamer &
geometry_streamer::instance() {
static geometry_streamer streamer;
return streamer;
}
geometry_streamer::~geometry_streamer() {
stop();
}
std::uint32_t
geometry_streamer::now() {
return instance().m_now.load( std::memory_order_relaxed );
}
void
geometry_streamer::start_threads() {
if( ( false == m_threads.empty() ) || m_stopped ) { return; }
// the loads read the disk and unpack: a few threads, not to take the cores the frame needs
auto const count { std::clamp( std::thread::hardware_concurrency() / 4u, 1u, 3u ) };
for( unsigned idx = 0; idx < count; ++idx ) {
m_threads.emplace_back( [ this ]( std::stop_token const Stop ) { work( Stop ); } );
}
}
void
geometry_streamer::request( geometry_bank &Bank, float const Priority ) {
std::scoped_lock lock { m_mutex };
if( m_stopped ) { return; }
if( auto const queued { m_queued.find( &Bank ) }; queued != m_queued.end() ) {
// asked for sooner: put ahead
if( Priority < queued->second->first.first ) {
m_queue.erase( queued->second );
queued->second = m_queue.emplace( queue_key { Priority, m_order++ }, &Bank ).first;
}
return;
}
if( false == Bank.begin_load( Priority ) ) { return; }
m_queued.emplace( &Bank, m_queue.emplace( queue_key { Priority, m_order++ }, &Bank ).first );
start_threads();
m_wake.notify_one();
}
void
geometry_streamer::work( std::stop_token const Stop ) {
while( false == Stop.stop_requested() ) {
geometry_bank *bank { nullptr };
{
std::unique_lock lock { m_mutex };
if( false == m_wake.wait( lock, Stop, [ this ]() { return false == m_queue.empty(); } ) ) {
return; // stopped
}
auto const first { m_queue.begin() };
bank = first->second;
m_queued.erase( bank );
m_queue.erase( first );
++m_working;
}
// the epoch the load is of: a bank loaded or let go of meanwhile doesn't take it (geometry_bank::adopt())
result done;
done.bank = bank;
done.epoch = bank->epoch();
done.ok = bank->source()->load( done.data, bank->plain_layout(), done.error );
{
std::scoped_lock lock { m_mutex };
m_done.emplace_back( std::move( done ) );
--m_working;
}
m_idle.notify_all();
}
}
void
geometry_streamer::hand_over_one( result &Result ) {
auto &bank { *Result.bank };
if( false == Result.ok ) {
if( false == bank.fail_load( Result.epoch ) ) {
return; // loaded meanwhile by the thread which read it
}
++m_failed;
ErrorLog( std::format( "Bad model: the geometry of \"{}\" can't be loaded: {}", bank.source()->name(), Result.error ), logtype::model );
return;
}
if( false == bank.adopt( Result.data, Result.epoch ) ) {
// loaded meanwhile by the thread which read it, or let go of
return;
}
++m_loaded;
m_adoptions.fetch_add( 1, std::memory_order_acq_rel );
std::scoped_lock lock { m_mutex };
m_resident.push_back( &bank );
}
std::size_t
geometry_streamer::hand_over( std::size_t const Bytes, std::chrono::steady_clock::duration const Time ) {
auto const start { std::chrono::steady_clock::now() };
std::size_t handed { 0 };
while( true ) {
result done;
{
std::scoped_lock lock { m_mutex };
if( m_done.empty() ) { break; }
done = std::move( m_done.front() );
m_done.pop_front();
}
{
// the chunks of the bank change while no walk of the passes draws (gfx::walk_sync)
gfx::walk_sync::change change;
hand_over_one( done );
}
handed += done.bank->data_bytes();
if( ( Bytes > 0 ) && ( ( handed >= Bytes ) || ( std::chrono::steady_clock::now() - start >= Time ) ) ) {
break;
}
}
return handed;
}
void
geometry_streamer::update() {
m_now.store( static_cast<std::uint32_t>( std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::steady_clock::now() - m_start ).count() ), std::memory_order_relaxed );
hand_over( frame_bytes, frame_time );
report_failures();
sweep();
}
std::size_t
geometry_streamer::finish( std::chrono::milliseconds const Timeout ) {
auto const deadline { std::chrono::steady_clock::now() + Timeout };
while( true ) {
hand_over( 0, {} );
report_failures();
std::unique_lock lock { m_mutex };
auto const left { m_queue.size() + m_working + m_done.size() };
if( ( left == 0 ) || ( std::chrono::steady_clock::now() >= deadline ) ) {
return left;
}
m_idle.wait_for( lock, std::chrono::milliseconds { 50 } );
}
}
std::size_t
geometry_streamer::pending() const {
std::scoped_lock lock { m_mutex };
return m_queue.size() + m_working + m_done.size();
}
void
geometry_streamer::register_resident( geometry_bank &Bank ) {
m_adoptions.fetch_add( 1, std::memory_order_acq_rel );
std::scoped_lock lock { m_mutex };
++m_loaded;
m_resident.push_back( &Bank );
}
void
geometry_streamer::report_failure( std::string_view const Name, std::string_view const Error ) {
std::scoped_lock lock { m_mutex };
++m_failed;
m_failures.emplace_back( std::format( "Bad model: the geometry of \"{}\" can't be loaded: {}", Name, Error ) );
}
void
geometry_streamer::report_failures() {
std::vector<std::string> failures;
{
std::scoped_lock lock { m_mutex };
failures.swap( m_failures );
}
for( auto const &failure : failures ) {
ErrorLog( failure, logtype::model );
}
}
void
geometry_streamer::sweep() {
std::vector<geometry_bank *> unused;
{
std::scoped_lock lock { m_mutex };
if( m_resident.empty() ) { return; }
auto const clock { now() };
auto const lifetime { static_cast<std::uint32_t>( std::max( 0.f, Global.modelstreaming_evictafter ) * 1000.f ) };
std::size_t bytes { 0 };
if( Global.modelstreaming_budget > 0 ) {
for( auto const *bank : m_resident ) {
bytes += bank->data_bytes();
}
}
auto const overbudget { ( Global.modelstreaming_budget > 0 ) && ( bytes > ( static_cast<std::size_t>( Global.modelstreaming_budget ) << 20 ) ) };
auto const limit { overbudget ? std::min( lifetime, over_budget_unused_ms ) : lifetime };
for( std::size_t step = 0; ( step < sweep_count ) && ( false == m_resident.empty() ); ++step ) {
if( m_sweepcursor >= m_resident.size() ) {
m_sweepcursor = 0;
}
auto *bank { m_resident[ m_sweepcursor ] };
auto const gone { bank->state() != residency::resident };
auto const stale { ( false == gone ) && ( false == bank->pinned() ) && ( clock - bank->last_used() > limit ) };
if( false == ( gone || stale ) ) {
++m_sweepcursor;
continue;
}
if( stale ) {
unused.push_back( bank );
}
m_resident[ m_sweepcursor ] = m_resident.back();
m_resident.pop_back();
}
}
if( unused.empty() ) { return; }
// the chunks of the banks change while no walk of the passes draws (gfx::walk_sync)
gfx::walk_sync::change change;
for( auto *bank : unused ) {
bank->evict();
}
m_evicted += unused.size();
}
std::size_t
geometry_streamer::evict_all() {
std::vector<geometry_bank *> banks;
{
std::scoped_lock lock { m_mutex };
banks.swap( m_resident );
m_sweepcursor = 0;
}
std::size_t evicted { 0 };
gfx::walk_sync::change change;
for( auto *bank : banks ) {
if( bank->pinned() || ( bank->state() != residency::resident ) ) {
if( bank->state() == residency::resident ) {
std::scoped_lock lock { m_mutex };
m_resident.push_back( bank );
}
continue;
}
bank->evict();
++evicted;
}
m_evicted += evicted;
return evicted;
}
void
geometry_streamer::stop() {
std::vector<std::jthread> threads;
{
std::scoped_lock lock { m_mutex };
m_stopped = true;
threads.swap( m_threads );
}
for( auto &thread : threads ) {
thread.request_stop();
}
m_wake.notify_all();
threads.clear(); // joined here
std::scoped_lock lock { m_mutex };
m_queue.clear();
m_queued.clear();
m_done.clear();
m_resident.clear();
}
geometry_streamer::statistics
geometry_streamer::stats() const {
statistics values;
std::scoped_lock lock { m_mutex };
values.resident = m_resident.size();
for( auto const *bank : m_resident ) {
values.bytes += bank->data_bytes();
}
values.pending = m_queue.size() + m_working + m_done.size();
values.loaded = m_loaded;
values.evicted = m_evicted;
values.failed = m_failed;
return values;
}
} // namespace gfx