From 5185d69dc98a040e96b0ad194abdd2a0238b5f04 Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Sat, 28 Nov 2026 21:52:47 +0100 Subject: [PATCH] feat(render): the Vulkan renderer keeps the vertex streams of E4D models as they are, 28 bytes a vertex Stage 3 of the E4D model format. A model loaded from .e4d (modelformat e4d) reaches the Vulkan renderer as its compact streams: positions (12 B), attributes (QTangent snorm16x4 + uv f32x2, 16 B), user data and indices, without the 48-byte gfx::basic_vertex in between. - gfx: gfx::compact_attributes, geometry_bank::create_compact() and GfxRenderer->Insert_Compact(). The default of Insert_Compact decodes to basic_vertex, so the OpenGL 4.6 and the null renderers get the models as before. The CPU readers of a chunk (pantograph, bounds, picking, the editor) get basic_vertex made from the streams the first time they read it; a chunk which is changed (replace, append) turns into basic_vertex first. - Vulkan: a bank whose chunks are all compact keeps positions, user data, attributes and indices in buffers of their own; vertex_kind::scene_compact reads them (location 5 the quaternion as R16G16B16A16_SNORM). A program gets a COMPACT_VERTEX variant the first time a compact chunk is drawn with it, in the background with gfx.vulkan.asyncresources, as the MODEL_DRAWS one; the variant of the multi draws makes a compact one of its own. Only vertex.vert and cabprobe.vert decode the normal (compact_frame() in common.glsl); the shaders of shadows, prepass, picking and cube shadows read position and uv as before. - Ray tracing: the BLAS of a compact chunk reads the positions with a stride of 12, and the reflections read the normal and uv from the attributes (RT_FLAG_COMPACT in the record). Not tried with ray tracing on. - The loader hands the streams of the file to Insert_Compact as they are; the stars keep their colours in the normals of basic_vertex and go as before. Measured on Vulkan (self-test, 250 models of the game, runs alternating with legacy): device memory 1.60-1.64 GiB against 1.89 GiB, GPU time a frame 1.27-1.39 ms against 1.37-1.57 ms, the same frame time and load time, the picture within 1/255 of the legacy one, no errors of Vulkan in the log. Unit tests 1189/1189; -e4d diff gives the same results through the new decode. Not built with GCC here. --- docs/e4d-format.md | 21 +++- model/Model3d.cpp | 6 + model/Model3d.h | 3 + model/e4d/e4d_load.cpp | 34 ++++-- rendering/geometrybank.cpp | 83 +++++++++++++- rendering/geometrybank.h | 35 +++++- rendering/renderer.h | 7 ++ rendering/vulkan14/vulkan14context.h | 9 +- rendering/vulkan14/vulkan14geometry.cpp | 131 +++++++++++++++------- rendering/vulkan14/vulkan14geometry.h | 16 +++ rendering/vulkan14/vulkan14indirect.cpp | 87 +++++++++----- rendering/vulkan14/vulkan14raytracing.cpp | 15 ++- rendering/vulkan14/vulkan14renderer.h | 10 ++ rendering/vulkan14/vulkan14scene.cpp | 70 ++++++++++-- shaders/vk14/cabprobe.vert | 11 +- shaders/vk14/common.glsl | 17 +++ shaders/vk14/freespot.vert | 3 + shaders/vk14/rt_reflections.glsl | 36 ++++++ shaders/vk14/traction.vert | 3 + shaders/vk14/vertex.vert | 20 +++- 20 files changed, 510 insertions(+), 107 deletions(-) diff --git a/docs/e4d-format.md b/docs/e4d-format.md index 105b6375d..52cdd6112 100644 --- a/docs/e4d-format.md +++ b/docs/e4d-format.md @@ -5,7 +5,8 @@ Vulkana 1.4. Niesie węzły TRS, skinning, typowane komponenty i metadane węzł podnoszenia wersji. Rekordy, rozmiary i offsety są w `model/e4d/e4d_format.h`, a `static_assert` pilnują, żeby kod i ten opis się nie rozjechały. -Stan: wersja 1.0, etap 1 (format, czytnik, pisarz, konwersja z E3D/T3D). Gra jeszcze nie wczytuje `.e4d`; to etap 2. +Stan: wersja 1.0. Format, czytnik, pisarz i konwersja z E3D/T3D (etap 1), wczytywanie w grze za przełącznikiem (etap 2), +strumienie kompaktowe w rendererze Vulkan (etap 3, sekcja „W grze”). ## Zasady @@ -227,7 +228,21 @@ go w E4D: Pozostałe polecenia: `eu07 -e4d dump ` (zawartość jako tekst) i `eu07 -e4d validate ` (sprawdzenie pliku wraz z hashem zawartości). +## W grze + +Z `modelformat e4d` w `eu07.ini` model z plikiem `.e4d` obok `.e3d` / `.t3d` jest wczytywany z niego (`TModel3d::LoadFromE4D`). +Domyślne `modelformat legacy` zostawia pliki `.e4d` w spokoju. + +- **Renderer Vulkan** trzyma strumienie modelu E4D tak, jak leżą w pliku: pozycje (12 B), atrybuty z `VATT` (16 B), dane + użytkownika i indeksy, każde w osobnym buforze banku (`vertex_kind::scene_compact`). Shadery czytają pozycję i UV jak dotąd, + a normalną i tangens wyliczają z kwaternionu (`compact_frame()` w `shaders/vk14/common.glsl`, wariant `COMPACT_VERTEX` + programu). Ray tracing buduje BLAS z pozycji o kroku 12 B i czyta normalne oraz UV z atrybutów (`RT_FLAG_COMPACT`). +- **Renderer OpenGL 4.6** dostaje te same modele jako `gfx::basic_vertex` (48 B), jak modele E3D. +- Kod gry, który czyta wierzchołki modelu (pantograf, granice, picking, edytor), dostaje je jako `gfx::basic_vertex`, zrobione ze + strumieni przy pierwszym odczycie. +- Gwiazdy (`STAR`) trzymają kolor w normalnej, więc idą jako `gfx::basic_vertex` również w Vulkanie. + ## Zgodność wstecz -E3D i T3D są czytane jak dotąd. Gra zacznie wczytywać `.e4d` w etapie 2, i tylko wtedy, gdy plik istnieje, za -przełącznikiem w `eu07.ini`. Obecne wydanie nie czyta `.e4d`. +E3D i T3D są czytane jak dotąd. Plik `.e4d` jest wczytywany tylko wtedy, gdy istnieje, za przełącznikiem `modelformat e4d` +w `eu07.ini`. Obecne wydanie nie czyta `.e4d`. diff --git a/model/Model3d.cpp b/model/Model3d.cpp index a7d3d5cb3..6780086d4 100644 --- a/model/Model3d.cpp +++ b/model/Model3d.cpp @@ -2679,6 +2679,12 @@ void TModel3d::finish_binary(bool const dynamic, bool const hastangents) break; } } + if (false == Root[i].CompactPositions.empty()) + { + // a submodel of an E4D model: its compact streams as they are, the renderer keeps them or makes basic_vertex of them + Root[i].m_geometry.handle = GfxRenderer->Insert_Compact(Root[i].Indices, Root[i].CompactPositions, Root[i].CompactAttributes, Root[i].Userdata, m_geometrybank, type); + continue; + } if (false == hastangents) { gfx::calculate_tangents(Root[i].Vertices, Root[i].Indices, type); diff --git a/model/Model3d.h b/model/Model3d.h index 8e75ae274..14c9ddd88 100644 --- a/model/Model3d.h +++ b/model/Model3d.h @@ -159,6 +159,9 @@ public: // chwilowo gfx::vertex_array Vertices; gfx::userdata_array Userdata; gfx::index_array Indices; + // the compact streams of a submodel loaded from E4D, in place of Vertices till they go to the renderer (Insert_Compact()) + gfx::position_array CompactPositions; + gfx::compact_array CompactAttributes; float m_boundingradius { 0 }; std::uintptr_t iAnimOwner{ 0 }; // roboczy numer egzemplarza, który ustawił animację TAnimType b_aAnim{ TAnimType::at_None }; // kody animacji oddzielnie, bo zerowane diff --git a/model/e4d/e4d_load.cpp b/model/e4d/e4d_load.cpp index 204da371c..3decb055b 100644 --- a/model/e4d/e4d_load.cpp +++ b/model/e4d/e4d_load.cpp @@ -21,6 +21,7 @@ http://mozilla.org/MPL/2.0/. #include #include +#include #include #include #include @@ -32,6 +33,12 @@ http://mozilla.org/MPL/2.0/. namespace { +// the vertex streams of the file are the compact layout of the renderer, byte for byte +static_assert(sizeof(e4d::position) == sizeof(glm::vec3)); +static_assert(sizeof(e4d::attributes) == sizeof(gfx::compact_attributes)); +static_assert(offsetof(e4d::attributes, qtangent) == offsetof(gfx::compact_attributes, qtangent)); +static_assert(offsetof(e4d::attributes, uv) == offsetof(gfx::compact_attributes, texture)); + // what E3D keeps in the submodel and E4D in the components of the node struct legacy_parts { std::optional light; @@ -234,7 +241,23 @@ void submodel_builder::fill(geometry_job const &Job) const { auto &submodel{*Job.submodel}; auto const stars{false == Job.stars.empty()}; auto const userdata{m_model.vertex_userdata.size() == m_model.vertex_count()}; - // each vertex is written once: reserved and appended, without the zeroes resize() would write first + if (userdata) { + submodel.Userdata.clear(); + submodel.Userdata.reserve(primitive.vertex_count); + for (auto const &data : std::span{m_model.vertex_userdata}.subspan(primitive.base_vertex, primitive.vertex_count)) + submodel.Userdata.push_back({glm::vec4{data[0], data[1], data[2], data[3]}}); + } + indices(primitive, submodel); + if (false == stars) { + // the streams of the file are the compact layout of the renderer: copied as they are (Insert_Compact()) + submodel.CompactPositions.resize(primitive.vertex_count); + submodel.CompactAttributes.resize(primitive.vertex_count); + std::memcpy(submodel.CompactPositions.data(), m_model.positions.data() + primitive.base_vertex, primitive.vertex_count * sizeof(glm::vec3)); + std::memcpy(submodel.CompactAttributes.data(), m_model.vertex_attributes.data() + primitive.base_vertex, primitive.vertex_count * sizeof(gfx::compact_attributes)); + return; + } + // the stars keep their colours in the normals of basic_vertex. each vertex is written once: reserved and appended, without the + // zeroes resize() would write first submodel.Vertices.clear(); submodel.Vertices.reserve(primitive.vertex_count); for (std::uint32_t idx = 0; idx < primitive.vertex_count; ++idx) { @@ -244,18 +267,11 @@ void submodel_builder::fill(geometry_job const &Job) const { auto const frame{e4d::decode_qtangent(attribute.qtangent)}; gfx::basic_vertex vertex; vertex.position = {position[0], position[1], position[2]}; - vertex.normal = stars ? unpack_colour(Job.stars, idx) : frame.normal; + vertex.normal = unpack_colour(Job.stars, idx); vertex.tangent = glm::vec4{frame.tangent, frame.handedness}; vertex.texture = {attribute.uv[0], attribute.uv[1]}; submodel.Vertices.push_back(vertex); } - if (userdata) { - submodel.Userdata.clear(); - submodel.Userdata.reserve(primitive.vertex_count); - for (auto const &data : std::span{m_model.vertex_userdata}.subspan(primitive.base_vertex, primitive.vertex_count)) - submodel.Userdata.push_back({glm::vec4{data[0], data[1], data[2], data[3]}}); - } - indices(primitive, submodel); } void submodel_builder::indices(e4d::primitive_record const &Primitive, TSubModel &Submodel) const { diff --git a/rendering/geometrybank.cpp b/rendering/geometrybank.cpp index 4b12ec65e..79ce20604 100644 --- a/rendering/geometrybank.cpp +++ b/rendering/geometrybank.cpp @@ -300,6 +300,61 @@ geometry_bank::create( gfx::index_array &Indices, gfx::vertex_array &Vertices, u return chunkhandle; } +auto +decode_compact( position_array const &Positions, compact_array const &Attributes ) -> vertex_array { + + vertex_array vertices; + auto const count { std::min( Positions.size(), Attributes.size() ) }; + vertices.reserve( count ); + for( std::size_t idx = 0; idx < count; ++idx ) { + // the first and the third column of the rotation matrix of the quaternion, made unit by 2 / |q|^2 (e4d::decode_qtangent) + auto const &packed { Attributes[ idx ].qtangent }; + auto const x { packed[ 0 ] / 32767.f }; + auto const y { packed[ 1 ] / 32767.f }; + auto const z { packed[ 2 ] / 32767.f }; + auto const w { packed[ 3 ] / 32767.f }; + auto const norm { x * x + y * y + z * z + w * w }; + auto const s { norm > 1e-12f ? 2.f / norm : 0.f }; + basic_vertex vertex; + vertex.position = Positions[ idx ]; + vertex.normal = norm > 1e-12f ? glm::vec3 { s * ( x * z + w * y ), s * ( y * z - w * x ), 1.f - s * ( x * x + y * y ) } : glm::vec3 { 0.f, 0.f, 1.f }; + vertex.tangent = glm::vec4 { + norm > 1e-12f ? glm::vec3 { 1.f - s * ( y * y + z * z ), s * ( x * y + w * z ), s * ( x * z - w * y ) } : glm::vec3 { 1.f, 0.f, 0.f }, + w < 0.f ? -1.f : 1.f }; + vertex.texture = Attributes[ idx ].texture; + vertices.push_back( vertex ); + } + return vertices; +} + +// creates a new chunk of the compact layout +gfx::geometry_handle +geometry_bank::create_compact( gfx::index_array &Indices, gfx::position_array &Positions, gfx::compact_array &Attributes, gfx::userdata_array &Userdata, unsigned int const Type ) { + + if( Positions.empty() || ( Positions.size() != Attributes.size() ) ) { return { 0, 0 }; } + + gfx::vertex_array none; + m_chunks.emplace_back( Indices, none, Userdata, Type ); + auto &chunk { m_chunks.back() }; + chunk.positions.swap( Positions ); + chunk.attributes.swap( Attributes ); + gfx::geometry_handle chunkhandle { 0, static_cast( m_chunks.size() ) }; + create_( chunkhandle ); + return chunkhandle; +} + +void +geometry_bank::make_plain( geometry_chunk &Chunk ) const { + + if( false == Chunk.compact() ) { return; } + std::scoped_lock lock { m_decodemutex }; + if( Chunk.vertices.empty() ) { + Chunk.vertices = decode_compact( Chunk.positions, Chunk.attributes ); + } + gfx::position_array().swap( Chunk.positions ); + gfx::compact_array().swap( Chunk.attributes ); +} + // replaces data of specified chunk with the supplied vertex data, starting from specified offset bool geometry_bank::replace( gfx::vertex_array &Vertices, userdata_array &Userdata, gfx::geometry_handle const &Geometry, std::size_t const Offset ) { @@ -307,6 +362,7 @@ geometry_bank::replace( gfx::vertex_array &Vertices, userdata_array &Userdata, g if( ( Geometry.chunk == 0 ) || ( Geometry.chunk > m_chunks.size() ) ) { return false; } auto &chunk = gfx::geometry_bank::chunk( Geometry ); + make_plain( chunk ); if( ( Offset == 0 ) && ( Vertices.size() == chunk.vertices.size() ) ) { @@ -336,6 +392,7 @@ geometry_bank::replace( gfx::index_array &Indices, gfx::vertex_array &Vertices, if( ( Geometry.chunk == 0 ) || ( Geometry.chunk > m_chunks.size() ) ) { return false; } auto &chunk = gfx::geometry_bank::chunk( Geometry ); + make_plain( chunk ); // the place of the chunk in the buffers of the bank is kept, so the sizes have to stay if( ( Indices.size() != chunk.indices.size() ) || ( Vertices.size() != chunk.vertices.size() ) @@ -356,6 +413,7 @@ geometry_bank::append( gfx::vertex_array &Vertices, userdata_array &Userdata, gf if( ( Geometry.chunk == 0 ) || ( Geometry.chunk > m_chunks.size() ) ) { return false; } + make_plain( gfx::geometry_bank::chunk( Geometry ) ); return replace( Vertices, Userdata, Geometry, gfx::geometry_bank::chunk( Geometry ).vertices.size() ); } @@ -365,8 +423,10 @@ geometry_bank::erase( gfx::geometry_handle const &Geometry ) { if( ( Geometry.chunk == 0 ) || ( Geometry.chunk > m_chunks.size() ) ) { return; } auto &chunk = gfx::geometry_bank::chunk( Geometry ); - if( chunk.vertices.empty() && chunk.indices.empty() ) { return; } + if( chunk.vertices.empty() && chunk.indices.empty() && ( false == chunk.compact() ) ) { return; } + gfx::position_array().swap( chunk.positions ); + gfx::compact_array().swap( chunk.attributes ); gfx::vertex_array().swap( chunk.vertices ); gfx::index_array().swap( chunk.indices ); gfx::userdata_array().swap( chunk.userdata ); @@ -440,7 +500,14 @@ geometry_bank::indices( gfx::geometry_handle const &Geometry ) const { vertex_array const & geometry_bank::vertices( gfx::geometry_handle const &Geometry ) const { - return geometry_bank::chunk( Geometry ).vertices; + auto const &chunk { geometry_bank::chunk( Geometry ) }; + // made from the compact streams the first time something reads them (the simulation, the editor, the picking). under the lock + // also for a chunk which isn't compact (any more): make_plain() may be turning it into basic_vertex on a thread drawing the bank + std::scoped_lock lock { m_decodemutex }; + if( chunk.compact() && chunk.vertices.empty() ) { + chunk.vertices = decode_compact( chunk.positions, chunk.attributes ); + } + return chunk.vertices; } // primitive type of specified chunk, 0 if there's no such chunk @@ -476,7 +543,7 @@ geometry_bank::count_memory( memory_count &Vertices, memory_count &Indices, memo for( auto const &chunk : m_chunks ) { ++Vertices.count; - Vertices.bytes += memory_of( chunk.vertices ); + Vertices.bytes += memory_of( chunk.vertices ) + memory_of( chunk.positions ) + memory_of( chunk.attributes ); Indices.bytes += memory_of( chunk.indices ); Userdata.bytes += memory_of( chunk.userdata ); } @@ -531,6 +598,16 @@ geometrybank_manager::create_chunk( gfx::index_array &Indices, gfx::vertex_array else { return { 0, 0 }; } } +// creates a new chunk of the compact layout in specified bank. returns: handle to the chunk or NULL +gfx::geometry_handle +geometrybank_manager::create_chunk_compact( gfx::index_array &Indices, gfx::position_array &Positions, gfx::compact_array &Attributes, userdata_array &Userdata, gfx::geometrybank_handle const &Geometry, unsigned int const Type ) { + + auto const newchunkhandle = bank( Geometry ).first->create_compact( Indices, Positions, Attributes, Userdata, Type ); + + if( newchunkhandle.chunk != 0 ) { return { Geometry.bank, newchunkhandle.chunk }; } + else { return { 0, 0 }; } +} + // replaces data of specified chunk with the supplied vertex data, starting from specified offset bool geometrybank_manager::replace( gfx::vertex_array &Vertices, userdata_array &Userdata, gfx::geometry_handle const &Geometry, std::size_t const Offset ) { diff --git a/rendering/geometrybank.h b/rendering/geometrybank.h index 366ea339d..8b75557ac 100644 --- a/rendering/geometrybank.h +++ b/rendering/geometrybank.h @@ -12,6 +12,9 @@ http://mozilla.org/MPL/2.0/. #include "model/ResourceManager.h" #include "utilities/memorystats.h" +#include +#include + struct world_vertex; namespace gfx { @@ -76,6 +79,20 @@ using vertex_array = std::vector; using userdata_array = std::vector; using index_array = std::vector; +// the attributes of a vertex in the compact layout of the E4D models: the tangent frame as a snorm16 quaternion (its w is negative +// where the bitangent is flipped), then the texture coordinates. with the position in a stream of its own a vertex takes 28 bytes +// against the 48 of basic_vertex, and the depth and shadow passes read 12 of them +struct compact_attributes { + std::array qtangent { 0, 0, 0, 32767 }; + glm::vec2 texture { 0.f, 0.f }; +}; +static_assert( sizeof( compact_attributes ) == 16 ); +using position_array = std::vector; +using compact_array = std::vector; + +// the vertices the compact streams stand for (the normal and the tangent from the quaternion) +auto decode_compact( position_array const &Positions, compact_array const &Attributes ) -> vertex_array; + void calculate_tangents( vertex_array &vertices, index_array const &indices, int const type ); void calculate_indices( index_array &Indices, vertex_array &Vertices, userdata_array &Userdata, float tolerancescale = 1.0f ); @@ -124,6 +141,9 @@ public: auto create( gfx::vertex_array &Vertices, gfx::userdata_array& Userdata, unsigned int const Type ) -> gfx::geometry_handle; // creates a new indexed geometry chunk of specified type from supplied data. returns: handle to the chunk or NULL auto create( gfx::index_array &Indices, gfx::vertex_array &Vertices, gfx::userdata_array& Userdata, unsigned int const Type ) -> gfx::geometry_handle; + // creates a new chunk of the compact layout: positions and compact attributes, with indices or without. its vertices() are + // made from them when something reads them first. returns: handle to the chunk or NULL + auto create_compact( gfx::index_array &Indices, gfx::position_array &Positions, gfx::compact_array &Attributes, gfx::userdata_array &Userdata, unsigned int const Type ) -> gfx::geometry_handle; // replaces vertex data of specified chunk with the supplied data, starting from specified offset auto replace( gfx::vertex_array &Vertices, gfx::userdata_array& Userdata, gfx::geometry_handle const &Geometry, std::size_t const Offset = 0 ) -> bool; // replaces the index and the vertex data of specified indexed chunk with the supplied data of the same counts. returns: false if the counts differ @@ -178,9 +198,15 @@ protected: // types: struct geometry_chunk { unsigned int type; // kind of geometry used by the chunk - gfx::vertex_array vertices; // geometry data + // geometry data. for a chunk of the compact layout it's made from the compact streams when it's read first (vertices()) + mutable gfx::vertex_array vertices; gfx::index_array indices; // index data gfx::userdata_array userdata; + // the compact layout (create_compact()): the positions and the attributes, empty for a chunk of basic_vertex + gfx::position_array positions; + gfx::compact_array attributes; + auto compact() const -> bool { + return false == positions.empty(); } // NOTE: constructor doesn't copy provided geometry data, but moves it geometry_chunk( gfx::vertex_array &Vertices, gfx::userdata_array& Userdata, unsigned int Type ) : type( Type ) @@ -208,8 +234,13 @@ protected: auto chunk( gfx::geometry_handle const Geometry ) const -> geometry_chunk const & { return m_chunks[ Geometry.chunk - 1 ]; } + // a chunk of the compact layout turned into one of basic_vertex, before it's changed (replace(), append(), erase()) + void make_plain( geometry_chunk &Chunk ) const; + // members: geometrychunk_sequence m_chunks; + // the vertices of the compact chunks made when they're first read, by one of the threads reading them at a time + mutable std::mutex m_decodemutex; private: // methods: @@ -257,6 +288,8 @@ public: auto create_chunk( gfx::vertex_array &Vertices, gfx::userdata_array &Userdata, gfx::geometrybank_handle const &Geometry, int const Type ) -> gfx::geometry_handle; // creates a new indexed geometry chunk of specified type from supplied data, in specified bank. returns: handle to the chunk or NULL auto create_chunk( gfx::index_array &Indices, gfx::vertex_array &Vertices, gfx::userdata_array &Userdata, gfx::geometrybank_handle const &Geometry, unsigned int const Type ) -> gfx::geometry_handle; + // creates a new chunk of the compact layout in specified bank (geometry_bank::create_compact()). returns: handle to the chunk or NULL + auto create_chunk_compact( gfx::index_array &Indices, gfx::position_array &Positions, gfx::compact_array &Attributes, gfx::userdata_array &Userdata, gfx::geometrybank_handle const &Geometry, unsigned int const Type ) -> gfx::geometry_handle; // replaces data of specified chunk with the supplied vertex data, starting from specified offset auto replace( gfx::vertex_array &Vertices, gfx::userdata_array &Userdata, gfx::geometry_handle const &Geometry, std::size_t const Offset = 0 ) -> bool; // replaces the index and the vertex data of specified indexed chunk with the supplied data of the same counts. returns: false if the counts differ diff --git a/rendering/renderer.h b/rendering/renderer.h index d84035b68..700235361 100644 --- a/rendering/renderer.h +++ b/rendering/renderer.h @@ -101,6 +101,13 @@ public: virtual auto Insert(gfx::index_array &Indices, gfx::vertex_array &Vertices, gfx::userdata_array &Userdata, gfx::geometrybank_handle const &Geometry, int const Type) -> gfx::geometry_handle = 0; // creates a new geometry chunk of specified type from supplied data, in specified bank. returns: handle to the chunk or NULL virtual auto Insert(gfx::vertex_array &Vertices, gfx::userdata_array &Userdata, gfx::geometrybank_handle const &Geometry, int const Type) -> gfx::geometry_handle = 0; + // creates a new chunk from the compact streams of an E4D model (positions, tangent frames as quaternions and texture + // coordinates), with indices or without, in specified bank. a renderer which draws basic_vertex only gets them as such + virtual auto Insert_Compact(gfx::index_array &Indices, gfx::position_array &Positions, gfx::compact_array &Attributes, gfx::userdata_array &Userdata, gfx::geometrybank_handle const &Geometry, int const Type) -> gfx::geometry_handle { + auto vertices { gfx::decode_compact( Positions, Attributes ) }; + gfx::position_array().swap( Positions ); + gfx::compact_array().swap( Attributes ); + return Indices.empty() ? Insert( vertices, Userdata, Geometry, Type ) : Insert( Indices, vertices, Userdata, Geometry, Type ); } // replaces data of specified chunk with the supplied vertex data, starting from specified offset virtual auto Replace(gfx::vertex_array &Vertices, gfx::userdata_array &Userdata, gfx::geometry_handle const &Geometry, int const Type, const std::size_t Offset = 0) -> bool = 0; // replaces the index and the vertex data of specified indexed chunk with the supplied data of the same counts. diff --git a/rendering/vulkan14/vulkan14context.h b/rendering/vulkan14/vulkan14context.h index f3ef48acc..d460aee6c 100644 --- a/rendering/vulkan14/vulkan14context.h +++ b/rendering/vulkan14/vulkan14context.h @@ -65,7 +65,8 @@ enum class vertex_kind : std::uint8_t star, // direction with the magnitude and colour with the phase of the twinkling in one stream, the stars particle, // position, colour and texture coordinates in one stream, the smoke position_uv, // position and texture coordinates in two streams, the precipitation - particle_instance // three vec4 of gl::particle_draw for each instance, the particles of the gpu + particle_instance, // three vec4 of gl::particle_draw for each instance, the particles of the gpu + scene_compact // the compact streams of the E4D models: positions, user data, tangent quaternions with texture coordinates }; // the vertices of a particle of the smoke of the cpu (vertex_kind::particle, as opengl46_particles has them) @@ -104,6 +105,11 @@ struct scene_program : public gfx::shader_program bool multidraw_tried{false}; // its shaders are being compiled by the background threads, the draws it's for are left out till then bool multidraw_pending{false}; + // the variant for the chunks of the compact layout (COMPACT_VERTEX, vertex_kind::scene_compact), made when it's first needed, + // as the one of the multi draws + std::shared_ptr compact; + bool compact_tried{false}; + bool compact_pending{false}; vertex_kind vertices{vertex_kind::scene}; // the pipelines made, by the key of bind_scene_pipeline(), and the ones the background threads are making (M5). guarded by the // mutex, as are the variants above made when they're first needed: the walks of the passes and the background threads ask for @@ -788,6 +794,7 @@ struct vulkan14_renderer::draw_state VkPipeline pipeline{VK_NULL_HANDLE}; VkBuffer vertices{VK_NULL_HANDLE}; VkBuffer userdata{VK_NULL_HANDLE}; + VkBuffer attributes{VK_NULL_HANDLE}; // binding 2, the chunks of the compact layout (vk14::chunk_source::attributes) VkBuffer indices{VK_NULL_HANDLE}; VkPrimitiveTopology topology{VK_PRIMITIVE_TOPOLOGY_MAX_ENUM}; VkCullModeFlags cull{VK_CULL_MODE_FLAG_BITS_MAX_ENUM}; diff --git a/rendering/vulkan14/vulkan14geometry.cpp b/rendering/vulkan14/vulkan14geometry.cpp index efbc4f53d..4b59dac91 100644 --- a/rendering/vulkan14/vulkan14geometry.cpp +++ b/rendering/vulkan14/vulkan14geometry.cpp @@ -61,8 +61,11 @@ void vulkan14_geometrybank::create_(gfx::geometry_handle const &Geometry) void vulkan14_geometrybank::replace_(gfx::geometry_handle const &Geometry) { - if (m_layoutdirty) + // a chunk of the compact layout is changed as basic_vertex (geometry_bank::make_plain()): the bank isn't of the compact layout + // any more, its buffers are made anew + if (m_layoutdirty || m_compact) { + m_layoutdirty = true; return; } auto const index{Geometry.chunk - 1}; @@ -89,12 +92,14 @@ void vulkan14_geometrybank::replace_(gfx::geometry_handle const &Geometry) void vulkan14_geometrybank::release_() { auto *deletions{m_resources.deletions}; - if ((deletions != nullptr) && (m_resources.uploads != nullptr) && (m_vertices || m_userdata || m_indices)) + if ((deletions != nullptr) && (m_resources.uploads != nullptr) && (m_vertices || m_userdata || m_attributes || m_indices)) { - deletions->push(m_resources.uploads->current_value(), [vertices = std::move(m_vertices), userdata = std::move(m_userdata), indices = std::move(m_indices)]() {}); + deletions->push(m_resources.uploads->current_value(), + [vertices = std::move(m_vertices), userdata = std::move(m_userdata), attributes = std::move(m_attributes), indices = std::move(m_indices)]() {}); } m_vertices.reset(); m_userdata.reset(); + m_attributes.reset(); m_indices.reset(); m_places.clear(); m_bytes = 0; @@ -102,18 +107,17 @@ void vulkan14_geometrybank::release_() m_chunksdirty = false; } +void vulkan14_geometrybank::gpu_userdata(geometry_chunk const &Chunk, std::size_t const Count, std::vector &Userdata) +{ + auto const target{Userdata.size() + Count}; + Userdata.insert(Userdata.end(), Chunk.userdata.begin(), Chunk.userdata.begin() + std::min(Count, Chunk.userdata.size())); + Userdata.resize(target, no_userdata); +} + void vulkan14_geometrybank::gpu_vertices(geometry_chunk const &Chunk, std::vector &Vertices, std::vector &Userdata) const { Vertices.insert(Vertices.end(), Chunk.vertices.begin(), Chunk.vertices.end()); - if (Chunk.userdata.size() >= Chunk.vertices.size()) - { - Userdata.insert(Userdata.end(), Chunk.userdata.begin(), Chunk.userdata.begin() + Chunk.vertices.size()); - } - else - { - Userdata.insert(Userdata.end(), Chunk.userdata.begin(), Chunk.userdata.end()); - Userdata.resize(Vertices.size(), no_userdata); - } + gpu_userdata(Chunk, Chunk.vertices.size(), Userdata); if ((Chunk.type == GL_LINE_LOOP) && Chunk.indices.empty() && (false == Chunk.vertices.empty())) { // back to the first vertex @@ -122,6 +126,20 @@ void vulkan14_geometrybank::gpu_vertices(geometry_chunk const &Chunk, std::vecto } } +void vulkan14_geometrybank::gpu_compact(geometry_chunk const &Chunk, gfx::position_array &Positions, gfx::compact_array &Attributes, std::vector &Userdata) +{ + Positions.insert(Positions.end(), Chunk.positions.begin(), Chunk.positions.end()); + Attributes.insert(Attributes.end(), Chunk.attributes.begin(), Chunk.attributes.end()); + gpu_userdata(Chunk, Chunk.positions.size(), Userdata); + if ((Chunk.type == GL_LINE_LOOP) && Chunk.indices.empty()) + { + // back to the first vertex + Positions.push_back(Chunk.positions.front()); + Attributes.push_back(Chunk.attributes.front()); + Userdata.push_back(Chunk.userdata.empty() ? no_userdata : Chunk.userdata.front()); + } +} + bool vulkan14_geometrybank::build() { // there was no memory for the buffers a moment ago: tried again after a while, not by every draw of every chunk of the bank @@ -131,7 +149,18 @@ bool vulkan14_geometrybank::build() } release_(); + // the compact layout when every chunk of the bank is of it (an E4D model); otherwise its chunks go as basic_vertex + m_compact = (false == m_chunks.empty()) && std::ranges::all_of(m_chunks, [](geometry_chunk const &Chunk) { return Chunk.compact(); }); + if (false == m_compact) + { + for (auto &chunk : m_chunks) + { + make_plain(chunk); + } + } std::vector vertices; + gfx::position_array positions; + gfx::compact_array attributes; std::vector userdata; std::vector indices; m_places.resize(m_chunks.size()); @@ -139,10 +168,17 @@ bool vulkan14_geometrybank::build() { auto const &chunk{m_chunks[i]}; auto &place{m_places[i]}; - place.vertexfirst = static_cast(vertices.size()); + place.vertexfirst = static_cast(userdata.size()); place.indexfirst = static_cast(indices.size()); - gpu_vertices(chunk, vertices, userdata); - place.vertexcount = static_cast(vertices.size()) - place.vertexfirst; + if (m_compact) + { + gpu_compact(chunk, positions, attributes, userdata); + } + else + { + gpu_vertices(chunk, vertices, userdata); + } + place.vertexcount = static_cast(userdata.size()) - place.vertexfirst; indices.insert(indices.end(), chunk.indices.begin(), chunk.indices.end()); if ((chunk.type == GL_LINE_LOOP) && (false == chunk.indices.empty())) { @@ -154,36 +190,17 @@ bool vulkan14_geometrybank::build() } m_layoutdirty = false; m_chunksdirty = false; - if (vertices.empty()) + if (userdata.empty()) { return false; } - - auto &memory{*m_resources.memory}; - auto &uploads{*m_resources.uploads}; - // with the ray tracing the vertices and the indices are built into acceleration structures, and the shading reads them - auto const raytracing{m_resources.raytracing ? (VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR) : 0}; - auto const make = [&](std::shared_ptr &Buffer, void const *Data, VkDeviceSize const Size, VkBufferUsageFlags const Usage, char const *Name) { - Buffer = std::make_shared(); - if ((false == Buffer->create(memory, Size, Usage | VK_BUFFER_USAGE_TRANSFER_DST_BIT | raytracing, memory_kind::device, Name)) || (false == uploads.upload_buffer(Buffer, Data, Size))) - { - Buffer.reset(); - return false; - } - m_bytes += Size; - return true; - }; - auto ok{make(m_vertices, vertices.data(), vertices.size() * sizeof(gfx::basic_vertex), VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, "geometry vertices") && - make(m_userdata, userdata.data(), userdata.size() * sizeof(gfx::vertex_userdata), VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, "geometry user data")}; - if (ok && (false == indices.empty())) - { - ok = make(m_indices, indices.data(), indices.size() * sizeof(gfx::basic_index), VK_BUFFER_USAGE_INDEX_BUFFER_BIT, "geometry indices"); - } - if (false == ok) + auto const made{m_compact ? make_buffers(positions.data(), positions.size() * sizeof(glm::vec3), userdata, &attributes, indices) + : make_buffers(vertices.data(), vertices.size() * sizeof(gfx::basic_vertex), userdata, nullptr, indices)}; + if (false == made) { if (false == m_failed) { - log_error("no memory for the geometry of a bank of " + std::to_string(vertices.size()) + " vertices, trying again every second"); + log_error("no memory for the geometry of a bank of " + std::to_string(userdata.size()) + " vertices, trying again every second"); } release_(); // tried again when it's drawn after a while @@ -196,10 +213,41 @@ bool vulkan14_geometrybank::build() return true; } +bool vulkan14_geometrybank::make_buffers(void const *Vertices, VkDeviceSize const VertexBytes, std::vector const &Userdata, gfx::compact_array const *Attributes, + std::vector const &Indices) +{ + auto &memory{*m_resources.memory}; + auto &uploads{*m_resources.uploads}; + // with the ray tracing the vertices and the indices are built into acceleration structures, and the shading reads them + auto const raytracing{m_resources.raytracing ? (VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR) : 0}; + auto const make = [this, &memory, &uploads, raytracing](std::shared_ptr &Buffer, void const *Data, VkDeviceSize const Size, VkBufferUsageFlags const Usage, char const *Name) { + Buffer = std::make_shared(); + if ((false == Buffer->create(memory, Size, Usage | VK_BUFFER_USAGE_TRANSFER_DST_BIT | raytracing, memory_kind::device, Name)) || (false == uploads.upload_buffer(Buffer, Data, Size))) + { + Buffer.reset(); + return false; + } + m_bytes += Size; + return true; + }; + auto ok{make(m_vertices, Vertices, VertexBytes, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, Attributes != nullptr ? "geometry positions" : "geometry vertices") && + make(m_userdata, Userdata.data(), Userdata.size() * sizeof(gfx::vertex_userdata), VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, "geometry user data")}; + if (ok && (Attributes != nullptr)) + { + ok = make(m_attributes, Attributes->data(), Attributes->size() * sizeof(gfx::compact_attributes), VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, "geometry attributes"); + } + if (ok && (false == Indices.empty())) + { + ok = make(m_indices, Indices.data(), Indices.size() * sizeof(gfx::basic_index), VK_BUFFER_USAGE_INDEX_BUFFER_BIT, "geometry indices"); + } + return ok; +} + void vulkan14_geometrybank::update() { m_chunksdirty = false; - if ((false == bool(m_vertices)) || (false == bool(m_userdata))) + // a bank of the compact layout is made anew when a chunk changes (replace_()) + if ((false == bool(m_vertices)) || (false == bool(m_userdata)) || m_compact) { return; } @@ -265,6 +313,8 @@ bool vulkan14_geometrybank::source(gfx::geometry_handle const &Geometry, chunk_s auto const &place{m_places[index]}; Source.vertices = m_vertices->handle(); Source.userdata = m_userdata->handle(); + Source.compact = m_compact && m_attributes; + Source.attributes = Source.compact ? m_attributes->handle() : VK_NULL_HANDLE; Source.topology = topology_of(m_chunks[index].type); Source.vertexfirst = place.vertexfirst; Source.vertexcount = place.vertexcount; @@ -272,6 +322,7 @@ bool vulkan14_geometrybank::source(gfx::geometry_handle const &Geometry, chunk_s if (m_resources.raytracing) { Source.vertex_address = m_vertices->address(); + Source.attribute_address = (Source.compact ? m_attributes->address() : 0); Source.index_address = (m_indices ? m_indices->address() : 0); } if (place.indexcount > 0) diff --git a/rendering/vulkan14/vulkan14geometry.h b/rendering/vulkan14/vulkan14geometry.h index 487def7ce..daed8db8d 100644 --- a/rendering/vulkan14/vulkan14geometry.h +++ b/rendering/vulkan14/vulkan14geometry.h @@ -31,8 +31,13 @@ struct resources; // where the data of a chunk is in the buffers of its bank struct chunk_source { + // basic_vertex, or for a bank of the compact layout the positions alone (12 bytes a vertex) VkBuffer vertices{VK_NULL_HANDLE}; VkBuffer userdata{VK_NULL_HANDLE}; + // the compact layout: the tangent quaternions and the texture coordinates (gfx::compact_attributes), drawn with the + // vertex_kind::scene_compact variant of the program; null for basic_vertex + VkBuffer attributes{VK_NULL_HANDLE}; + bool compact{false}; VkBuffer indices{VK_NULL_HANDLE}; // null for a chunk without indices std::uint32_t count{0}; // vertices, or indices std::uint32_t first{0}; // first index, or vertex @@ -43,6 +48,7 @@ struct chunk_source std::uint32_t vertexfirst{0}; std::uint32_t vertexcount{0}; VkDeviceAddress vertex_address{0}; + VkDeviceAddress attribute_address{0}; // the compact layout VkDeviceAddress index_address{0}; std::uint64_t generation{0}; }; @@ -91,10 +97,20 @@ class vulkan14_geometrybank : public gfx::geometry_bank void update(); // the vertices of a chunk as they go to the gpu void gpu_vertices(geometry_chunk const &Chunk, std::vector &Vertices, std::vector &Userdata) const; + // the same for a chunk of the compact layout + static void gpu_compact(geometry_chunk const &Chunk, gfx::position_array &Positions, gfx::compact_array &Attributes, std::vector &Userdata); + // the user data of a chunk as it goes to the gpu, for its first Count vertices + static void gpu_userdata(geometry_chunk const &Chunk, std::size_t Count, std::vector &Userdata); + // the vertex streams of the gpu made of the chunks, in place of the buffers made before + bool make_buffers(void const *Vertices, VkDeviceSize VertexBytes, std::vector const &Userdata, gfx::compact_array const *Attributes, std::vector const &Indices); resources const &m_resources; + // basic_vertex, or the positions of the compact layout std::shared_ptr m_vertices; std::shared_ptr m_userdata; + // the compact layout (every chunk of the bank made with create_compact()): the tangent quaternions and the texture coordinates + std::shared_ptr m_attributes; + bool m_compact{false}; std::shared_ptr m_indices; std::vector m_places; bool m_layoutdirty{true}; // the buffers have to be made anew diff --git a/rendering/vulkan14/vulkan14indirect.cpp b/rendering/vulkan14/vulkan14indirect.cpp index c568306fd..611f139fb 100644 --- a/rendering/vulkan14/vulkan14indirect.cpp +++ b/rendering/vulkan14/vulkan14indirect.cpp @@ -279,20 +279,42 @@ void vulkan14_renderer::resume_rendering() namespace { -// the variant of a program of the scene for the multi draws (MODEL_DRAWS), null when its shaders can't be made. any thread -std::shared_ptr multidraw_variant(vk14::shader_library &Shaders, std::string const &Defines, std::string const &Vertex, std::string const &Fragment, std::string const &Name) +// a variant of a program of the scene, made of its shaders with a definition more: the multi draws (MODEL_DRAWS, of the same +// vertices), or the chunks of the compact layout (COMPACT_VERTEX, vertex_kind::scene_compact). null when its shaders can't be made. +// any thread +struct variant_kind +{ + char const *define; + char const *label; + bool compact; + std::shared_ptr vk14::scene_program::*slot; + bool vk14::scene_program::*tried; + bool vk14::scene_program::*pending; +}; + +variant_kind const multidraw_kind{"#define MODEL_DRAWS\n", " (multi draws)", false, &vk14::scene_program::multidraw, &vk14::scene_program::multidraw_tried, &vk14::scene_program::multidraw_pending}; +variant_kind const compact_kind{"#define COMPACT_VERTEX\n", " (compact)", true, &vk14::scene_program::compact, &vk14::scene_program::compact_tried, &vk14::scene_program::compact_pending}; + +std::shared_ptr make_variant(vk14::shader_library &Shaders, std::string const &Defines, std::string const &Vertex, std::string const &Fragment, std::string const &Name, + vk14::vertex_kind const Vertices, variant_kind const &Kind) { try { auto variant{std::make_shared()}; - variant->defines = Defines + "#define MODEL_DRAWS\n"; + variant->defines = Defines + Kind.define; variant->vertex = Shaders.get(Vertex, variant->defines); variant->fragment = Shaders.get(Fragment, variant->defines); variant->vertex_name = Vertex; variant->fragment_name = Fragment; - variant->vertices = vk14::vertex_kind::scene; - variant->name = Name + " (multi draws)"; - variant->multidraw_tried = true; + variant->vertices = Kind.compact ? vk14::vertex_kind::scene_compact : Vertices; + variant->name = Name + Kind.label; + // a variant has no variant of its own kind. the one of the multi draws makes a compact one of its own (both definitions), which + // the multi draws of the chunks of the compact layout take; the compact one makes none more + (*variant).*Kind.tried = true; + if (Kind.compact) + { + variant->multidraw_tried = true; + } return variant; } catch (gfx::shader_exception const &Exception) @@ -304,18 +326,20 @@ std::shared_ptr multidraw_variant(vk14::shader_library &Sha } // namespace -vk14::scene_program *vulkan14_renderer::multidraw_program(vk14::scene_program &Program, bool &Pending) +vk14::scene_program *vulkan14_renderer::program_variant(vk14::scene_program &Program, bool &Pending, bool const Compact) { + auto const &kind{Compact ? compact_kind : multidraw_kind}; // made by one of the threads walking the passes (M2) - std::lock_guard lock(Program.mutex); + std::scoped_lock lock(Program.mutex); Pending = false; - if (Program.multidraw_tried) + if (Program.*kind.tried) { - Pending = Program.multidraw_pending; - return Program.multidraw.get(); + Pending = Program.*kind.pending; + return (Program.*kind.slot).get(); } - Program.multidraw_tried = true; - if (Program.vertex_name.empty() || Program.fragment_name.empty() || (Program.vertices != vk14::vertex_kind::scene)) + Program.*kind.tried = true; + auto const scene{(Program.vertices == vk14::vertex_kind::scene) || ((false == Compact) && (Program.vertices == vk14::vertex_kind::scene_compact))}; + if (Program.vertex_name.empty() || Program.fragment_name.empty() || (false == scene)) { return nullptr; } @@ -325,18 +349,29 @@ vk14::scene_program *vulkan14_renderer::multidraw_program(vk14::scene_program &P // its shaders are compiled by the background threads (gfx.vulkan.asyncresources), the draws left out till they are, as the // ones without their pipeline are: the walk doesn't wait for the compiler, nor do the other threads binding the program for // its lock. the program outlives the threads (stopped first when the scene goes) - Program.multidraw_pending = true; + Program.*kind.pending = true; Pending = true; - ctx.background.add([&shaders = ctx.shaders, program = &Program, defines = Program.defines, vertex = Program.vertex_name, fragment = Program.fragment_name, name = Program.name]() { - auto variant{multidraw_variant(shaders, defines, vertex, fragment, name)}; + ctx.background.add([&shaders = ctx.shaders, program = &Program, defines = Program.defines, vertex = Program.vertex_name, fragment = Program.fragment_name, name = Program.name, + vertices = Program.vertices, &kind]() { + auto variant{make_variant(shaders, defines, vertex, fragment, name, vertices, kind)}; std::scoped_lock const made{program->mutex}; - program->multidraw = std::move(variant); - program->multidraw_pending = false; + (*program).*kind.slot = std::move(variant); + (*program).*kind.pending = false; }); return nullptr; } - Program.multidraw = multidraw_variant(ctx.shaders, Program.defines, Program.vertex_name, Program.fragment_name, Program.name); - return Program.multidraw.get(); + Program.*kind.slot = make_variant(ctx.shaders, Program.defines, Program.vertex_name, Program.fragment_name, Program.name, Program.vertices, kind); + return (Program.*kind.slot).get(); +} + +vk14::scene_program *vulkan14_renderer::multidraw_program(vk14::scene_program &Program, bool &Pending) +{ + return program_variant(Program, Pending, false); +} + +vk14::scene_program *vulkan14_renderer::compact_program(vk14::scene_program &Program, bool &Pending) +{ + return program_variant(Program, Pending, true); } bool vulkan14_renderer::draw_indirect(vk14::instance_cull &Cull, command_set const Set, std::size_t const First, std::uint32_t const Count, vk14::scene_program &Program, vk14::blend_mode const Blend) @@ -362,7 +397,8 @@ bool vulkan14_renderer::draw_indirect(vk14::instance_cull &Cull, command_set con m_prepassincomplete = (m_prepassincomplete || draw.depthpass); return false; } - if (false == bind_scene_pipeline(Program, *draw.targets, Blend, static_cast(chunk.topology))) + auto *program{program_for(Program, chunk)}; + if ((program == nullptr) || (false == bind_scene_pipeline(*program, *draw.targets, Blend, static_cast(chunk.topology)))) { m_prepassincomplete = (m_prepassincomplete || draw.depthpass); return false; @@ -437,14 +473,7 @@ bool vulkan14_renderer::draw_indirect(vk14::instance_cull &Cull, command_set con commands->push_constants2(&info); draw.pushed_draw = block; } - if ((chunk.vertices != draw.vertices) || (chunk.userdata != draw.userdata)) - { - VkBuffer const buffers[2]{chunk.vertices, chunk.userdata}; - VkDeviceSize const offsets[2]{0, 0}; - commands->bind_vertex_buffers(0, 2, buffers, offsets); - draw.vertices = chunk.vertices; - draw.userdata = chunk.userdata; - } + bind_chunk_buffers(chunk); auto const offset{static_cast(Cull.draw_command_offset(Set, First))}; if (chunk.indices != VK_NULL_HANDLE) { diff --git a/rendering/vulkan14/vulkan14raytracing.cpp b/rendering/vulkan14/vulkan14raytracing.cpp index d91a83746..2cc79401a 100644 --- a/rendering/vulkan14/vulkan14raytracing.cpp +++ b/rendering/vulkan14/vulkan14raytracing.cpp @@ -52,6 +52,11 @@ std::uint64_t constexpr bottom_lifetime{1800}; std::uint64_t constexpr texture_lifetime{600}; // the size of the vertices of the banks (gfx::basic_vertex) VkDeviceSize constexpr vertex_stride{48}; +// a bank of the compact layout (the E4D models): the positions apart (12 bytes), the attributes (gfx::compact_attributes, 16 bytes) +VkDeviceSize constexpr compact_position_stride{sizeof(glm::vec3)}; +VkDeviceSize constexpr compact_attribute_stride{sizeof(gfx::compact_attributes)}; +// the vertices of the record are the attributes of the compact layout (rt_reflections.glsl, RT_FLAG_COMPACT) +std::uint32_t constexpr record_compact{4}; VkDeviceSize grow(VkDeviceSize const Needed, VkDeviceSize const Current) { @@ -493,8 +498,9 @@ void ray_tracing::build(command_stream *Commands, std::uint32_t const Slot, std: auto &triangles_data{build.geometry.geometry.triangles}; triangles_data.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_TRIANGLES_DATA_KHR; triangles_data.vertexFormat = VK_FORMAT_R32G32B32_SFLOAT; - triangles_data.vertexData.deviceAddress = source.vertex_address + vertex_stride * source.vertexfirst; - triangles_data.vertexStride = vertex_stride; + auto const stride{source.compact ? compact_position_stride : vertex_stride}; + triangles_data.vertexData.deviceAddress = source.vertex_address + stride * source.vertexfirst; + triangles_data.vertexStride = stride; triangles_data.maxVertex = source.vertexcount - 1; triangles_data.indexType = ((indexed || generated) ? VK_INDEX_TYPE_UINT32 : VK_INDEX_TYPE_NONE_KHR); triangles_data.indexData.deviceAddress = (generated ? generated->address() : indexed ? source.index_address + sizeof(std::uint32_t) * source.first : 0); @@ -649,11 +655,12 @@ void ray_tracing::build(command_stream *Commands, std::uint32_t const Slot, std: // made here and copied whole: the buffers are write-combined memory of the upload heap, where setting the bit fields of // an instance in place reads the memory back, which takes a few microseconds for each draw record entry{}; - entry.vertices = source.vertex_address + vertex_stride * source.vertexfirst; + // the shading reads the normals and the texture coordinates: basic_vertex, or the attributes of the compact layout + entry.vertices = (source.compact ? source.attribute_address + compact_attribute_stride * source.vertexfirst : source.vertex_address + vertex_stride * source.vertexfirst); entry.indices = (built->index_address != 0 ? built->index_address : source.indices != VK_NULL_HANDLE ? source.index_address + sizeof(std::uint32_t) * source.first : 0); entry.texture = texture; auto const alpha{(false == terrain) && (texture != 0) && (draw.cutoff > 0.f)}; - entry.flags = (alpha ? record_alpha : 0); + entry.flags = (alpha ? record_alpha : 0) | (source.compact ? record_compact : 0); entry.cutoff = draw.cutoff; entry.glow = draw.glow; entry.colour = glm::vec4{draw.colour, 1.f}; diff --git a/rendering/vulkan14/vulkan14renderer.h b/rendering/vulkan14/vulkan14renderer.h index 7184e7ba5..f79e79438 100644 --- a/rendering/vulkan14/vulkan14renderer.h +++ b/rendering/vulkan14/vulkan14renderer.h @@ -80,6 +80,8 @@ class vulkan14_renderer : public gfx_renderer, public gfx::scene_walk gfx::geometrybank_handle Create_Bank() override; gfx::geometry_handle Insert(gfx::index_array &Indices, gfx::vertex_array &Vertices, gfx::userdata_array &Userdata, gfx::geometrybank_handle const &Geometry, int const Type) override; gfx::geometry_handle Insert(gfx::vertex_array &Vertices, gfx::userdata_array &Userdata, gfx::geometrybank_handle const &Geometry, int const Type) override; + // the compact streams stay as they are: the bank of an E4D model keeps them on the gpu, 28 bytes a vertex + gfx::geometry_handle Insert_Compact(gfx::index_array &Indices, gfx::position_array &Positions, gfx::compact_array &Attributes, gfx::userdata_array &Userdata, gfx::geometrybank_handle const &Geometry, int const Type) override; bool Replace(gfx::vertex_array &Vertices, gfx::userdata_array &Userdata, gfx::geometry_handle const &Geometry, int const Type, std::size_t const Offset = 0) override; bool Replace_Indexed(gfx::index_array &Indices, gfx::vertex_array &Vertices, gfx::userdata_array &Userdata, gfx::geometry_handle const &Geometry) override; bool Append(gfx::vertex_array &Vertices, gfx::userdata_array &Userdata, gfx::geometry_handle const &Geometry, int const Type) override; @@ -263,6 +265,14 @@ class vulkan14_renderer : public gfx_renderer, public gfx::scene_walk // the variant of a program for the multi draws, nullptr when there's none // Pending: its shaders are being compiled by the background threads, the draws it's for are left out till they're there vk14::scene_program *multidraw_program(vk14::scene_program &Program, bool &Pending); + // the variant of a program for the chunks of the compact layout (vertex_kind::scene_compact), nullptr when there's none + vk14::scene_program *compact_program(vk14::scene_program &Program, bool &Pending); + vk14::scene_program *program_variant(vk14::scene_program &Program, bool &Pending, bool Compact); + // the program a chunk is drawn with: the one given, or its compact variant for a chunk of the compact layout. nullptr: the + // chunk isn't drawn now (no variant, or its shaders are being made) + vk14::scene_program *program_for(vk14::scene_program &Program, vk14::chunk_source const &Chunk); + // the vertex buffers of the chunk bound, unless they are already + void bind_chunk_buffers(vk14::chunk_source const &Chunk); vk14::instance_cull &pass_cull(); // the shadow maps of the lamps (vulkan14lamps.cpp, the stage P4; opengl46_renderer::Render_local_shadows() and the rest): the cab // lamp, the scenery lamps, one of them, the headlights, one set of them; the culling of a map (nullptr when its instances go diff --git a/rendering/vulkan14/vulkan14scene.cpp b/rendering/vulkan14/vulkan14scene.cpp index 5f1b5d976..4ad5f432b 100644 --- a/rendering/vulkan14/vulkan14scene.cpp +++ b/rendering/vulkan14/vulkan14scene.cpp @@ -91,6 +91,17 @@ vk14::vertex_layout layout_of(vk14::vertex_kind const Kind) {3, 0, VK_FORMAT_R32G32B32A32_SFLOAT, static_cast(offsetof(gfx::basic_vertex, tangent))}, {4, 1, VK_FORMAT_R32G32B32A32_SFLOAT, static_cast(offsetof(gfx::vertex_userdata, data))}}; break; + case vk14::vertex_kind::scene_compact: + // the positions, the user data, the attributes (gfx::compact_attributes): the texture coordinates where basic_vertex has them, + // the tangent frame as a quaternion at a location of its own (5), which the COMPACT_VERTEX variants of the shaders read + layout.bindings = {{0, sizeof(glm::vec3), VK_VERTEX_INPUT_RATE_VERTEX}, + {1, sizeof(gfx::vertex_userdata), VK_VERTEX_INPUT_RATE_VERTEX}, + {2, sizeof(gfx::compact_attributes), VK_VERTEX_INPUT_RATE_VERTEX}}; + layout.attributes = {{0, 0, VK_FORMAT_R32G32B32_SFLOAT, 0}, + {2, 2, VK_FORMAT_R32G32_SFLOAT, static_cast(offsetof(gfx::compact_attributes, texture))}, + {4, 1, VK_FORMAT_R32G32B32A32_SFLOAT, static_cast(offsetof(gfx::vertex_userdata, data))}, + {5, 2, VK_FORMAT_R16G16B16A16_SNORM, static_cast(offsetof(gfx::compact_attributes, qtangent))}}; + break; case vk14::vertex_kind::colour: layout.bindings = {{0, sizeof(glm::vec3), VK_VERTEX_INPUT_RATE_VERTEX}, {1, sizeof(glm::vec3), VK_VERTEX_INPUT_RATE_VERTEX}}; layout.attributes = {{0, 0, VK_FORMAT_R32G32B32_SFLOAT, 0}, {1, 1, VK_FORMAT_R32G32B32_SFLOAT, 0}}; @@ -1284,6 +1295,14 @@ gfx::geometry_handle vulkan14_renderer::Insert(gfx::index_array &Indices, gfx::v return m_geometry.create_chunk(Indices, Vertices, Userdata, Geometry, Type); } +gfx::geometry_handle vulkan14_renderer::Insert_Compact(gfx::index_array &Indices, gfx::position_array &Positions, gfx::compact_array &Attributes, gfx::userdata_array &Userdata, gfx::geometrybank_handle const &Geometry, + int const Type) +{ + // made while no walk of the passes draws (gfx::walk_sync) + gfx::walk_sync::change change; + return m_geometry.create_chunk_compact(Indices, Positions, Attributes, Userdata, Geometry, Type); +} + gfx::geometry_handle vulkan14_renderer::Insert(gfx::vertex_array &Vertices, gfx::userdata_array &Userdata, gfx::geometrybank_handle const &Geometry, int const Type) { // made while no walk of the passes draws (gfx::walk_sync) @@ -2079,6 +2098,41 @@ void vulkan14_renderer::walk_draw(std::vector::iterato } } +vk14::scene_program *vulkan14_renderer::program_for(vk14::scene_program &Program, vk14::chunk_source const &Chunk) +{ + if (false == Chunk.compact) + { + return &Program; + } + if (Program.vertices == vk14::vertex_kind::scene_compact) + { + return &Program; + } + // the compact variant: compiled the first time a chunk of the compact layout is drawn with the program, in the background + // with gfx.vulkan.asyncresources (the chunk is left out till it's there, as a draw without its pipeline is) + bool pending{false}; + return compact_program(Program, pending); +} + +void vulkan14_renderer::bind_chunk_buffers(vk14::chunk_source const &Chunk) +{ + auto &draw{*m_draw}; + if ((Chunk.vertices == draw.vertices) && (Chunk.userdata == draw.userdata) && ((false == Chunk.compact) || (Chunk.attributes == draw.attributes))) + { + return; + } + // the compact layout takes a third binding, the attributes; basic_vertex leaves it as it was, its pipelines don't read it + VkBuffer const buffers[3]{Chunk.vertices, Chunk.userdata, Chunk.attributes}; + VkDeviceSize const offsets[3]{0, 0, 0}; + draw.commands->bind_vertex_buffers(0, Chunk.compact ? 3 : 2, buffers, offsets); + draw.vertices = Chunk.vertices; + draw.userdata = Chunk.userdata; + if (Chunk.compact) + { + draw.attributes = Chunk.attributes; + } +} + void vulkan14_renderer::draw_chunk(gfx::geometry_handle const &Geometry, bool const Newblock) { auto &draw{*m_draw}; @@ -2121,9 +2175,10 @@ void vulkan14_renderer::draw_chunk(gfx::geometry_handle const &Geometry, bool co auto &ctx{*m_context}; auto &scene{ctx.scene}; auto const commands{draw.commands}; - // the pipeline for the state of the walk + // the pipeline for the state of the walk, of the variant of the program for the vertices of the chunk auto const blend{draw.glare ? vk14::blend_mode::scene_additive : (draw.blending ? vk14::blend_mode::scene_alpha : vk14::blend_mode::none)}; - if (false == bind_scene_pipeline(*draw.program, *draw.targets, blend, static_cast(chunk.topology))) + auto *program{program_for(*draw.program, chunk)}; + if ((program == nullptr) || (false == bind_scene_pipeline(*program, *draw.targets, blend, static_cast(chunk.topology)))) { m_prepassincomplete = (m_prepassincomplete || draw.depthpass); return; @@ -2160,14 +2215,7 @@ void vulkan14_renderer::draw_chunk(gfx::geometry_handle const &Geometry, bool co commands->push_constants2(&info); draw.pushed_draw = draw.block; } - if ((chunk.vertices != draw.vertices) || (chunk.userdata != draw.userdata)) - { - VkBuffer const buffers[2]{chunk.vertices, chunk.userdata}; - VkDeviceSize const offsets[2]{0, 0}; - commands->bind_vertex_buffers(0, 2, buffers, offsets); - draw.vertices = chunk.vertices; - draw.userdata = chunk.userdata; - } + bind_chunk_buffers(chunk); auto const firstinstance{m_current_instance_count > 0 ? m_current_instance_base : 0u}; if (chunk.indices != VK_NULL_HANDLE) { @@ -2272,7 +2320,7 @@ bool pipeline_record_valid(vk14::scene_pipeline_record const &Record, std::uint3 // the formats of the core, which the targets of the passes are of return static_cast(Format) <= static_cast(VK_FORMAT_ASTC_12x12_SRGB_BLOCK); }; - return (Vertices <= static_cast(vk14::vertex_kind::particle_instance)) && (Topology <= static_cast(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN)) && + return (Vertices <= static_cast(vk14::vertex_kind::scene_compact)) && (Topology <= static_cast(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN)) && (Record.blending <= static_cast(vk14::blend_mode::no_colour)) && format(Record.colour[0]) && format(Record.colour[1]) && format(Record.depth) && std::has_single_bit(Record.samples) && (Record.samples <= 8) && (Record.view_mask <= 0x3fu) && (Record.settings < 64u); } diff --git a/shaders/vk14/cabprobe.vert b/shaders/vk14/cabprobe.vert index 40c47778a..c568296ae 100644 --- a/shaders/vk14/cabprobe.vert +++ b/shaders/vk14/cabprobe.vert @@ -8,7 +8,9 @@ // reach and reversed depth like the one of the scene: the depth is near / d, d the distance along the axis of the face #include "common.glsl" layout(location = 0) in vec3 v_vert; +#ifndef COMPACT_VERTEX layout(location = 1) in vec3 v_normal; +#endif layout(location = 2) in vec2 v_coord; layout(location = 0) out vec3 f_normal; @@ -28,7 +30,14 @@ void main() vec3 position = (effective_modelview() * vec4(v_vert, 1.0)).xyz; int face = int(gl_ViewIndex); gl_Position = vec4(dot(position, face_right[face]), dot(position, face_up[face]), PROBE_NEAR, dot(position, face_forward[face])); - f_normal = effective_modelviewnormal() * v_normal; +#ifdef COMPACT_VERTEX + vec3 vertex_normal; + vec4 vertex_tangent; + compact_frame(vertex_normal, vertex_tangent); +#else + vec3 vertex_normal = v_normal; +#endif + f_normal = effective_modelviewnormal() * vertex_normal; f_coord = v_coord; f_pos = vec4(position, 1.0); #ifdef MODEL_DRAWS diff --git a/shaders/vk14/common.glsl b/shaders/vk14/common.glsl index 3dc8df4b8..f2b07a10c 100644 --- a/shaders/vk14/common.glsl +++ b/shaders/vk14/common.glsl @@ -456,6 +456,23 @@ mat3 effective_modelviewnormal() mat3 instance_normal = transpose(inverse(instance_mv3)); return instance_normal * modelviewnormal; } + +#ifdef COMPACT_VERTEX +// the vertex of the compact layout of the E4D models (gfx::compact_attributes, vertex_kind::scene_compact): the tangent frame as a +// quaternion (x, y, z, w), read as snorm16 at location 5; its w is negative where the bitangent is flipped. the normal is the third +// column of its rotation matrix and the tangent the first, made unit by 2 / |q|^2 (gfx::decode_compact()) +layout(location = 5) in vec4 v_qtangent; + +void compact_frame(out vec3 Normal, out vec4 Tangent) +{ + vec4 q = v_qtangent; + float norm = dot(q, q); + float s = norm > 1e-12 ? 2.0 / norm : 0.0; + Normal = norm > 1e-12 ? vec3(s * (q.x * q.z + q.w * q.y), s * (q.y * q.z - q.w * q.x), 1.0 - s * (q.x * q.x + q.y * q.y)) : vec3(0.0, 0.0, 1.0); + vec3 tangent = norm > 1e-12 ? vec3(1.0 - s * (q.y * q.y + q.z * q.z), s * (q.x * q.y + q.w * q.z), s * (q.x * q.z - q.w * q.y)) : vec3(1.0, 0.0, 0.0); + Tangent = vec4(tangent, q.w < 0.0 ? -1.0 : 1.0); +} +#endif #endif #endif diff --git a/shaders/vk14/freespot.vert b/shaders/vk14/freespot.vert index 78b50f3f0..84e0c9d2b 100644 --- a/shaders/vk14/freespot.vert +++ b/shaders/vk14/freespot.vert @@ -2,7 +2,10 @@ #define STAGE_VERTEX 1 #include "common.glsl" layout(location = 0) in vec3 v_vert; +#ifndef COMPACT_VERTEX +// not read; the compact layout has no normal at this location layout(location = 1) in vec3 v_normal; +#endif layout(location = 2) in vec2 v_coord; diff --git a/shaders/vk14/rt_reflections.glsl b/shaders/vk14/rt_reflections.glsl index 414e92e5b..fc2ff3c6a 100644 --- a/shaders/vk14/rt_reflections.glsl +++ b/shaders/vk14/rt_reflections.glsl @@ -43,7 +43,33 @@ const uint RT_FLAG_ALPHA = 1U; // a chunk of the heightmap terrain: texindex its first weights, the bits of cutoff its second weights, the bits of glow the table // of its layers, colour its placement (param[2] of its material) const uint RT_FLAG_TERRAIN = 2U; +// the vertices of the record are the attributes of the compact layout of the E4D models (gfx::compact_attributes, 4 words: the tangent +// quaternion as snorm16 x 4, then the texture coordinates) +const uint RT_FLAG_COMPACT = 4U; const uint RT_VERTEX_FLOATS = 12U; +const uint RT_COMPACT_WORDS = 4U; + +layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer rt_compact_data +{ + uint rt_compact[]; +}; + +// the texture coordinates of a vertex of the compact layout +vec2 rt_compact_coords(rt_compact_data Vertices, uint Vertex) +{ + return vec2(uintBitsToFloat(Vertices.rt_compact[Vertex * RT_COMPACT_WORDS + 2U]), uintBitsToFloat(Vertices.rt_compact[Vertex * RT_COMPACT_WORDS + 3U])); +} + +// the normal of a vertex of the compact layout: the third column of the rotation of its quaternion (gfx::decode_compact()) +vec3 rt_compact_normal(rt_compact_data Vertices, uint Vertex) +{ + vec4 q = vec4(unpackSnorm2x16(Vertices.rt_compact[Vertex * RT_COMPACT_WORDS]), unpackSnorm2x16(Vertices.rt_compact[Vertex * RT_COMPACT_WORDS + 1U])); + float norm = dot(q, q); + if (norm <= 1e-12) + return vec3(0.0, 0.0, 1.0); + float s = 2.0 / norm; + return vec3(s * (q.x * q.z + q.w * q.y), s * (q.y * q.z - q.w * q.x), 1.0 - s * (q.x * q.x + q.y * q.y)); +} // the masks of the instances (vk14::ray_tracing): the opaque ones, the alpha tested ones (the foliage). the shadow rays take the // opaque ones only, and the reflections leave out the alpha tested ones when the renderer says so (env_params.y, 1) const uint RT_MASK_OPAQUE = 1U; @@ -63,6 +89,11 @@ uvec3 rt_triangle(rt_record record, uint primitive) // the texture coordinates of a point of a triangle, its barycentric coordinates Weights vec2 rt_coords(rt_record record, uvec3 triangle, vec2 weights) { + if ((record.flags & RT_FLAG_COMPACT) != 0U) + { + rt_compact_data compact = rt_compact_data(record.vertices); + return rt_compact_coords(compact, triangle.x) * (1.0 - weights.x - weights.y) + rt_compact_coords(compact, triangle.y) * weights.x + rt_compact_coords(compact, triangle.z) * weights.y; + } rt_vertex_data vertices = rt_vertex_data(record.vertices); vec2 a = vec2(vertices.rt_vertex[triangle.x * RT_VERTEX_FLOATS + 6U], vertices.rt_vertex[triangle.x * RT_VERTEX_FLOATS + 7U]); vec2 b = vec2(vertices.rt_vertex[triangle.y * RT_VERTEX_FLOATS + 6U], vertices.rt_vertex[triangle.y * RT_VERTEX_FLOATS + 7U]); @@ -72,6 +103,11 @@ vec2 rt_coords(rt_record record, uvec3 triangle, vec2 weights) vec3 rt_normal(rt_record record, uvec3 triangle, vec2 weights) { + if ((record.flags & RT_FLAG_COMPACT) != 0U) + { + rt_compact_data compact = rt_compact_data(record.vertices); + return rt_compact_normal(compact, triangle.x) * (1.0 - weights.x - weights.y) + rt_compact_normal(compact, triangle.y) * weights.x + rt_compact_normal(compact, triangle.z) * weights.y; + } rt_vertex_data vertices = rt_vertex_data(record.vertices); vec3 a = vec3(vertices.rt_vertex[triangle.x * RT_VERTEX_FLOATS + 3U], vertices.rt_vertex[triangle.x * RT_VERTEX_FLOATS + 4U], vertices.rt_vertex[triangle.x * RT_VERTEX_FLOATS + 5U]); vec3 b = vec3(vertices.rt_vertex[triangle.y * RT_VERTEX_FLOATS + 3U], vertices.rt_vertex[triangle.y * RT_VERTEX_FLOATS + 4U], vertices.rt_vertex[triangle.y * RT_VERTEX_FLOATS + 5U]); diff --git a/shaders/vk14/traction.vert b/shaders/vk14/traction.vert index 20ca8171c..87054ef25 100644 --- a/shaders/vk14/traction.vert +++ b/shaders/vk14/traction.vert @@ -2,7 +2,10 @@ #define STAGE_VERTEX 1 #include "common.glsl" layout(location = 0) in vec3 v_vert; +#ifndef COMPACT_VERTEX +// not read; the compact layout has no normal at this location layout(location = 1) in vec3 v_normal; +#endif layout(location = 2) in vec2 v_coord; diff --git a/shaders/vk14/vertex.vert b/shaders/vk14/vertex.vert index ddf02369a..a2d311aee 100644 --- a/shaders/vk14/vertex.vert +++ b/shaders/vk14/vertex.vert @@ -2,9 +2,11 @@ #define STAGE_VERTEX 1 #include "common.glsl" layout(location = 0) in vec3 v_vert; +#ifndef COMPACT_VERTEX layout(location = 1) in vec3 v_normal; -layout(location = 2) in vec2 v_coord; layout(location = 3) in vec4 v_tangent; +#endif +layout(location = 2) in vec2 v_coord; layout(location = 4) in vec4 v_userdata; @@ -30,8 +32,16 @@ void main() mat4 mv = effective_modelview(); mat3 mvn = effective_modelviewnormal(); - f_normal = normalize(mvn * v_normal); - f_normal_raw = v_normal; +#ifdef COMPACT_VERTEX + vec3 vertex_normal; + vec4 vertex_tangent; + compact_frame(vertex_normal, vertex_tangent); +#else + vec3 vertex_normal = v_normal; + vec4 vertex_tangent = v_tangent; +#endif + f_normal = normalize(mvn * vertex_normal); + f_normal_raw = vertex_normal; f_coord = v_coord; f_pos = mv * vec4(v_vert, 1.0); f_clip_pos = projection * f_pos; @@ -41,10 +51,10 @@ void main() gl_PointSize = param[1].x; vec3 N = f_normal; - vec3 T = mvn * v_tangent.xyz; + vec3 T = mvn * vertex_tangent.xyz; T = normalize(T - N * dot(N, T)); // w is -1 where the texture is mirrored (calculate_tangents()), the bitangent turns with it - vec3 B = cross(N, T) * (v_tangent.w < 0.0 ? -1.0 : 1.0); + vec3 B = cross(N, T) * (vertex_tangent.w < 0.0 ? -1.0 : 1.0); f_tbn = mat3(T, B, N); mat3 TBN = transpose(f_tbn);