From 2edf9c410da9ef4961626a07370d2f75f7fc86f9 Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Tue, 1 Dec 2026 18:11:17 +0100 Subject: [PATCH] feat(render): Vulkan keeps the compact vertex streams of EU07M models; E4D renamed EU07M (#537) * 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. * refactor(model): the new model format is EU07M (.eu07m), not E4D E4D read as the next version of E3D, which the format isn't meant to be tied to; EU07M goes with the world format .eu07. The format isn't released, so nothing reads the old name. - The extension .eu07m, the magic EU7M (the four bytes of the header), model/eu07m/ with eu07m_*.{h,cpp}, namespace eu07m, docs/eu07m-format.md, tests/unit/test_eu07m.cpp. - The command line -eu07m convert|dump|validate|diff, TModel3d::LoadFromEU07M, and the key modelformat eu07m|legacy of eu07.ini (Global.modelformat_eu07m). - Nothing else changes: the sections, the records and the components are the same, so a converted file needs only its magic and its extension changed. Unit tests 1189/1189. * fix(render): EU07M review of #537: no whole vertices kept for the bounds, the compact variant checked by CI and given up when it fails - The bounding radius, offset() and MaxY() read the positions of a chunk alone (Positions(), geometry_bank::positions()): on Vulkan the compact streams are no longer decoded into basic_vertex and kept for the life of the bank as every model loads, so the host memory of EU07M models stays below that of E3D. What still needs whole vertices (the editor, the picking, the export) decodes them on first use as before. - A COMPACT_VERTEX variant which doesn't compile is told once in the log and the banks of EU07M models go back to basic_vertex (compact_layout_failed()), those built already when they are drawn next, instead of the models being left out for the session. - The shader validator compiles the vk14 shaders which have COMPACT_VERTEX with it, alone and with MODEL_DRAWS, as the renderer makes the variants. * feat(model): the EU07M model files take the .r3a extension, the switch is modelformat r3a The model files of the format are named .r3a in place of .eu07m, and eu07.ini selects them with modelformat r3a in place of modelformat eu07m. The format keeps its name (EU07M), its magic and the -eu07m command line tool. Neither the extension nor the key has been released, so nothing reads the old ones. * feat(model): the EU07M model files take the .ng3d extension, the switch is modelformat ng3d In place of .r3a (2fe1064f9): the model files are .ng3d and eu07.ini selects them with modelformat ng3d. The format keeps its name (EU07M), its magic and the -eu07m command line tool. Neither name has been released. --- CMakeLists.txt | 14 +- EU07.cpp | 8 +- ci_shadervalidator/main.cpp | 11 + docs/{e4d-format.md => eu07m-format.md} | 37 +- model/MdlMngr.cpp | 6 +- model/Model3d.cpp | 54 ++- model/Model3d.h | 7 +- .../e4d_build.cpp => eu07m/eu07m_build.cpp} | 6 +- .../{e4d/e4d_build.h => eu07m/eu07m_build.h} | 8 +- .../eu07m_convert.cpp} | 30 +- .../e4d_convert.h => eu07m/eu07m_convert.h} | 12 +- .../e4d_dump.cpp => eu07m/eu07m_dump.cpp} | 6 +- model/{e4d/e4d_dump.h => eu07m/eu07m_dump.h} | 8 +- .../e4d_format.h => eu07m/eu07m_format.h} | 10 +- model/{e4d/e4d_io.cpp => eu07m/eu07m_io.cpp} | 10 +- model/{e4d/e4d_io.h => eu07m/eu07m_io.h} | 8 +- .../e4d_load.cpp => eu07m/eu07m_load.cpp} | 128 ++++--- .../{e4d/e4d_model.h => eu07m/eu07m_model.h} | 8 +- rendering/geometrybank.cpp | 107 +++++- rendering/geometrybank.h | 39 +- rendering/renderer.h | 16 + rendering/vulkan14/vulkan14context.h | 9 +- rendering/vulkan14/vulkan14geometry.cpp | 151 +++++--- rendering/vulkan14/vulkan14geometry.h | 23 ++ rendering/vulkan14/vulkan14indirect.cpp | 92 +++-- rendering/vulkan14/vulkan14raytracing.cpp | 15 +- rendering/vulkan14/vulkan14renderer.h | 11 + rendering/vulkan14/vulkan14scene.cpp | 75 +++- 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 +- tests/unit/{test_e4d.cpp => test_eu07m.cpp} | 340 +++++++++--------- utilities/Globals.cpp | 6 +- utilities/Globals.h | 2 +- 37 files changed, 924 insertions(+), 423 deletions(-) rename docs/{e4d-format.md => eu07m-format.md} (88%) rename model/{e4d/e4d_build.cpp => eu07m/eu07m_build.cpp} (99%) rename model/{e4d/e4d_build.h => eu07m/eu07m_build.h} (89%) rename model/{e4d/e4d_convert.cpp => eu07m/eu07m_convert.cpp} (97%) rename model/{e4d/e4d_convert.h => eu07m/eu07m_convert.h} (59%) rename model/{e4d/e4d_dump.cpp => eu07m/eu07m_dump.cpp} (98%) rename model/{e4d/e4d_dump.h => eu07m/eu07m_dump.h} (67%) rename model/{e4d/e4d_format.h => eu07m/eu07m_format.h} (98%) rename model/{e4d/e4d_io.cpp => eu07m/eu07m_io.cpp} (99%) rename model/{e4d/e4d_io.h => eu07m/eu07m_io.h} (92%) rename model/{e4d/e4d_load.cpp => eu07m/eu07m_load.cpp} (73%) rename model/{e4d/e4d_model.h => eu07m/eu07m_model.h} (95%) rename tests/unit/{test_e4d.cpp => test_eu07m.cpp} (60%) diff --git a/CMakeLists.txt b/CMakeLists.txt index 37cdd0164..4cbf05057 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -225,8 +225,8 @@ set(SOURCES "vehicle/dynamic/visual.cpp" "EU07.cpp" "export_e3d_standalone.cpp" -"model/e4d/e4d_convert.cpp" -"model/e4d/e4d_load.cpp" +"model/eu07m/eu07m_convert.cpp" +"model/eu07m/eu07m_load.cpp" "export_btf_standalone.cpp" "nodebank_previews_standalone.cpp" "world/Event.cpp" @@ -862,12 +862,12 @@ set(CORE_SOURCES "world/stationnames.cpp" "world/eventconditions.cpp" "utilities/wholefile.cpp" -# the E4D model format: the files, their checks and the data they carry, which the unit tests read and write too -"model/e4d/e4d_io.cpp" -"model/e4d/e4d_build.cpp" -"model/e4d/e4d_dump.cpp" +# the EU07M model format: the files, their checks and the data they carry, which the unit tests read and write too +"model/eu07m/eu07m_io.cpp" +"model/eu07m/eu07m_build.cpp" +"model/eu07m/eu07m_dump.cpp" "${DEPS_DIR}/zstd/zstd.c" -# the codecs of the vertex and index streams of E4D +# the codecs of the vertex and index streams of EU07M "${DEPS_DIR}/meshoptimizer/src/vertexcodec.cpp" "${DEPS_DIR}/meshoptimizer/src/indexcodec.cpp" ) diff --git a/EU07.cpp b/EU07.cpp index da94e78c9..b02843c22 100644 --- a/EU07.cpp +++ b/EU07.cpp @@ -50,7 +50,7 @@ Stele, firleju, szociu, hunter, ZiomalCl, OLI_EU and others void export_e3d_standalone(std::string in, std::string out, int flags, bool dynamic); int export_btf_standalone(std::string in, std::string out); -namespace e4d { +namespace eu07m { int run_command_line(int Argc, char *Argv[]); } int generate_nodebank_previews(int Argc, char *Argv[]); @@ -149,10 +149,10 @@ int main(int argc, char *argv[]) int dynamic = std::stoi(std::string(argv[5])); export_e3d_standalone(in, out, flags, dynamic); } - // standalone conversion, listing and checking of E4D models: -e4d convert|dump|validate ... - else if (argc >= 2 && std::string(argv[1]) == "-e4d") + // standalone conversion, listing and checking of EU07M models: -eu07m convert|dump|validate ... + else if (argc >= 2 && std::string(argv[1]) == "-eu07m") { - auto const result{e4d::run_command_line(argc, argv)}; + auto const result{eu07m::run_command_line(argc, argv)}; fflush(stdout); fflush(stderr); std::_Exit(result); diff --git a/ci_shadervalidator/main.cpp b/ci_shadervalidator/main.cpp index 96af5c0ed..1bb1bbafb 100644 --- a/ci_shadervalidator/main.cpp +++ b/ci_shadervalidator/main.cpp @@ -226,6 +226,17 @@ bool check_vk14(std::string const &Name) if (!check_text(gfx::preprocess_shader(gfx::shader_api::vulkan14, Name, "#define NO_MOTION_OUTPUT 1\n", {}, false, vk14_dir), "-V --target-env " + vulkan_env)) suc = false; } + // the compact vertex layout of EU07M models (vk14::vertex_kind::scene_compact), alone and with the multi draws, as the + // renderer puts the definitions before the sources (compact_kind and multidraw_kind of vulkan14indirect.cpp) + if (source.text.find("COMPACT_VERTEX") != std::string::npos) + { + std::cout << "done, compact vertices..." << std::flush; + for (std::string_view const defines : {"#define COMPACT_VERTEX\n", "#define MODEL_DRAWS\n#define COMPACT_VERTEX\n"}) + { + if (!check_text(gfx::preprocess_shader(gfx::shader_api::vulkan14, Name, std::string{defines}, {}, false, vk14_dir), "-V --target-env " + vulkan_env)) + suc = false; + } + } // the ray traced reflections (gfx.raytracing): the renderer puts the extensions and REFLECTION_RAYS before the sources // (vk14::binding_preamble()), the shaders which shade with light_common.glsl trace the rays if (source.text.find("REFLECTION_RAYS_ACTIVE") != std::string::npos) diff --git a/docs/e4d-format.md b/docs/eu07m-format.md similarity index 88% rename from docs/e4d-format.md rename to docs/eu07m-format.md index 990fb14a7..3104b7927 100644 --- a/docs/e4d-format.md +++ b/docs/eu07m-format.md @@ -1,11 +1,12 @@ -# Format modeli E4D (`.e4d`) +# Format modeli EU07M (`.ng3d`) Następca E3D: w pełni binarny format modeli. Plik czyta się prawie bez przetwarzania, prosto do buforów OpenGL 4.6 i Vulkana 1.4. Niesie węzły TRS, skinning, typowane komponenty i metadane węzłów oraz grup wierzchołków. Rozszerza się bez -podnoszenia wersji. Rekordy, rozmiary i offsety są w `model/e4d/e4d_format.h`, a `static_assert` pilnują, żeby kod i ten +podnoszenia wersji. Rekordy, rozmiary i offsety są w `model/eu07m/eu07m_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 @@ -19,7 +20,7 @@ Stan: wersja 1.0, etap 1 (format, czytnik, pisarz, konwersja z E3D/T3D). Gra jes - **Wersja.** Wersja główna zmienia się tylko przy zmianie niezgodnej; czytnik odrzuca plik o wyższej wersji głównej. Wersja poboczna oznacza nowe pola i sekcje, które starszy czytnik pomija. - **Plik to dane niezaufane.** Czytnik sprawdza każdy offset, rozmiar, indeks, rodzica, joint i odwołanie, zanim - cokolwiek zostanie użyte (`e4d::validate`). + cokolwiek zostanie użyte (`eu07m::validate`). - **Semantyka w danych, nie w nazwach.** Role, strony pojazdu, warianty i sloty świateł są polami komponentów. Nazwy zostają, żeby dzisiejsze `.mmd` i eventy działały bez zmian. @@ -27,7 +28,7 @@ Stan: wersja 1.0, etap 1 (format, czytnik, pisarz, konwersja z E3D/T3D). Gra jes | Offset | Typ | Pole | |---|---|---| -| 0 | char × 4 | magic `E4D\0` | +| 0 | char × 4 | magic `EU7M`, nazwa formatu w czterech bajtach | | 4 | u16 × 2 | wersja główna (1), poboczna (0) | | 8 | u32 | flagi: bit 0 = kolejność indeksów zoptymalizowana | | 12 | u32 | liczba sekcji | @@ -129,7 +130,7 @@ węzła to T · R · S, chyba że ma flagę `XFRM`. ### Prymitywy scalone Dziś każda ruchoma część i każda lampa (`Light_On##` / `Light_Off##`) to osobny submodel, a więc osobny draw call w -każdym przebiegu. Model scenerii ze światłem albo animacją nie jest przy tym instancjonowany. E4D pozwala złożyć części +każdym przebiegu. Model scenerii ze światłem albo animacją nie jest przy tym instancjonowany. EU07M pozwala złożyć części kilku węzłów o tym samym materiale w jeden prymityw: - **Sztywne jointy (0x200).** Każdy wierzchołek wskazuje w `VBND` joint skóry prymitywu (`skin` ≥ 0), z wagą 1. @@ -214,8 +215,8 @@ Odwołania wewnątrz danych to indeksy: string, węzeł albo komponent; `0xFFFFF ## Konwersja z E3D i T3D -`eu07 -e4d convert [dynamic]` wczytuje model istniejącym loaderem (jak `-e3d`) i zapisuje -go w E4D: +`eu07 -eu07m convert [dynamic]` wczytuje model istniejącym loaderem (jak `-e3d`) i zapisuje +go w EU07M: - Submodel staje się węzłem. Kolejność dzieci i nazwy zostają, więc `GetFromName`, `.mmd` i eventy działają po staremu. - Macierz submodelu jest rozkładana na TRS. Gdy TRS jej nie odtwarza (ścinanie), pełna macierz idzie do `XFRM`. @@ -227,10 +228,24 @@ go w E4D: zgaduje je na nowo gra, z prawdziwym materiałem. Model pojazdu konwertuje się z `.e3d`, który robi z niego gra, nie z `.t3d`. - Wymienna skóra `-k` w przebiegu przezroczystym (bit k−1 flag E3D) ma w `MATL` flagę `translucent`. -Pozostałe polecenia: `eu07 -e4d dump ` (zawartość jako tekst) i `eu07 -e4d validate ` (sprawdzenie +Pozostałe polecenia: `eu07 -eu07m dump ` (zawartość jako tekst) i `eu07 -eu07m validate ` (sprawdzenie pliku wraz z hashem zawartości). +## W grze + +Z `modelformat ng3d` w `eu07.ini` model z plikiem `.ng3d` obok `.e3d` / `.t3d` jest wczytywany z niego (`TModel3d::LoadFromEU07M`). +Domyślne `modelformat legacy` zostawia pliki `.ng3d` w spokoju. + +- **Renderer Vulkan** trzyma strumienie modelu EU07M 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 `.ng3d` jest wczytywany tylko wtedy, gdy istnieje, za przełącznikiem `modelformat ng3d` +w `eu07.ini`. Obecne wydanie nie czyta `.ng3d`. diff --git a/model/MdlMngr.cpp b/model/MdlMngr.cpp index 71822523a..44c3a1669 100644 --- a/model/MdlMngr.cpp +++ b/model/MdlMngr.cpp @@ -166,9 +166,9 @@ std::string TModelsManager::find_on_disk( std::string const &Name ) { std::vector extensions { { ".e3d" }, { ".t3d" } }; - if( Global.modelformat_e4d ) { - // a model may come as an .e4d alone - extensions.emplace_back( ".e4d" ); + if( Global.modelformat_eu07m ) { + // a model may come as an .ng3d alone + extensions.emplace_back( ".ng3d" ); } for( auto const &extension : extensions ) { diff --git a/model/Model3d.cpp b/model/Model3d.cpp index 791146795..37ac9a523 100644 --- a/model/Model3d.cpp +++ b/model/Model3d.cpp @@ -1486,9 +1486,10 @@ void TSubModel::create_geometry(std::size_t &Indexoffset, std::size_t &Vertexoff // since we're comparing squared radii, we need to square it back for correct results m_boundingradius *= m_boundingradius; auto const submodeloffset{offset(std::numeric_limits::max())}; - for (auto const &vertex : GfxRenderer->Vertices(m_geometry.handle)) + // the positions alone: the vertices of an EU07M model on Vulkan would be made and kept whole for it + for (auto const &position : GfxRenderer->Positions(m_geometry.handle)) { - squaredradius = glm::length2(submodeloffset + vertex.position); + squaredradius = glm::length2(submodeloffset + position); if (squaredradius > m_boundingradius) { m_boundingradius = squaredradius; @@ -1612,9 +1613,9 @@ float TSubModel::MaxY(float4x4 const &m) if (m_geometry.handle != null_handle) { - for (auto const &vertex : GfxRenderer->Vertices(m_geometry.handle)) + for (auto const &position : GfxRenderer->Positions(m_geometry.handle)) { - maxy = std::max(maxy, m[0][1] * vertex.position.x + m[1][1] * vertex.position.y + m[2][1] * vertex.position.z + m[3][1]); + maxy = std::max(maxy, m[0][1] * position.x + m[1][1] * position.y + m[2][1] * position.z + m[3][1]); } } else if (false == Vertices.empty()) @@ -1756,17 +1757,30 @@ glm::vec3 TSubModel::offset(float const Geometrytestoffsetthreshold) const // offset of zero generally means the submodel has optimized identity matrix // for such cases we resort to an estimate from submodel geometry // TODO: do proper bounding area calculation for submodel when loading mesh and grab the centre point from it here - auto const &vertices{(m_geometry.handle != null_handle ? GfxRenderer->Vertices(m_geometry.handle) : Vertices)}; - if (false == vertices.empty()) + // the positions alone: the vertices of an EU07M model on Vulkan would be made and kept whole for them + gfx::position_array positions; + if (m_geometry.handle != null_handle) + { + positions = GfxRenderer->Positions(m_geometry.handle); + } + else + { + positions.reserve(Vertices.size()); + for (auto const &vertex : Vertices) + { + positions.push_back(vertex.position); + } + } + if (false == positions.empty()) { // transformation matrix for the submodel can still contain rotation and/or scaling, // so we pass the vertex positions through it rather than just grab them directly offset = glm::vec3(); - auto const vertexfactor{1.f / vertices.size()}; + auto const vertexfactor{1.f / positions.size()}; auto const transformationmatrix{glm::make_mat4(parentmatrix.readArray())}; - for (auto const &vertex : vertices) + for (auto const &position : positions) { - offset += glm::vec3{transformationmatrix * glm::vec4{vertex.position, 1}} * vertexfactor; + offset += glm::vec3{transformationmatrix * glm::vec4{position, 1}} * vertexfactor; } } } @@ -1776,12 +1790,12 @@ glm::vec3 TSubModel::offset(float const Geometrytestoffsetthreshold) const namespace { -// modelformat e4d: an .e4d older than the .e3d / .t3d it was made from isn't used, the model was changed after it was +// modelformat ng3d: an .ng3d older than the .e3d / .t3d it was made from isn't used, the model was changed after it was // converted (the hash of the source in its header would need the source read whole to be compared) -bool e4d_up_to_date(std::string const &E4d, std::initializer_list const Sources) +bool eu07m_up_to_date(std::string const &Eu07m, std::initializer_list const Sources) { std::error_code error; - auto const made{std::filesystem::last_write_time(E4d, error)}; + auto const made{std::filesystem::last_write_time(Eu07m, error)}; if (error) return false; for (auto const &source : Sources) @@ -1790,7 +1804,7 @@ bool e4d_up_to_date(std::string const &E4d, std::initializer_list c continue; if (auto const changed{std::filesystem::last_write_time(source, error)}; (false == bool(error)) && (changed > made)) { - WriteLog("Model \"" + source + "\" is newer than its \"" + E4d + "\", which isn't used", logtype::model); + WriteLog("Model \"" + source + "\" is newer than its \"" + Eu07m + "\", which isn't used", logtype::model); return false; } } @@ -1898,10 +1912,10 @@ bool TModel3d::LoadFromFile(std::string const &FileName, bool dynamic) Init(); assign_lod_ranges(Root, name); } - else if (auto const e4dfile{Global.modelformat_e4d ? FileCased(name + ".e4d") : std::string{}}; - (false == e4dfile.empty()) && e4d_up_to_date(e4dfile, {binaryfile, textfile}) && LoadFromE4D(e4dfile, dynamic)) + else if (auto const eu07mfile{Global.modelformat_eu07m ? FileCased(name + ".ng3d") : std::string{}}; + (false == eu07mfile.empty()) && eu07m_up_to_date(eu07mfile, {binaryfile, textfile}) && LoadFromEU07M(eu07mfile, dynamic)) { - // modelformat e4d: the .e4d made from the model takes its place; one which doesn't load leaves the .e3d / .t3d to go on + // modelformat ng3d: the .ng3d made from the model takes its place; one which doesn't load leaves the .e3d / .t3d to go on asBinary = ""; Init(); assign_lod_ranges(Root, name); @@ -2675,7 +2689,7 @@ void TModel3d::deserialize(std::istream &s, size_t size, bool dynamic) finish_binary(dynamic, hastangents); } -// the submodels read from a file (E3D or E4D) tied together, their materials looked up and their geometry handed to the renderer +// the submodels read from a file (E3D or EU07M) tied together, their materials looked up and their geometry handed to the renderer void TModel3d::finish_binary(bool const dynamic, bool const hastangents) { for (size_t i = 0; (int)i < iSubModelsCount; ++i) @@ -2703,6 +2717,12 @@ void TModel3d::finish_binary(bool const dynamic, bool const hastangents) break; } } + if (false == Root[i].CompactPositions.empty()) + { + // a submodel of an EU07M 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 db021004b..62341cdfc 100644 --- a/model/Model3d.h +++ b/model/Model3d.h @@ -161,6 +161,9 @@ public: // chwilowo gfx::vertex_array Vertices; gfx::userdata_array Userdata; gfx::index_array Indices; + // the compact streams of a submodel loaded from EU07M, 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 @@ -339,9 +342,9 @@ public: void AddTo(TSubModel *tmp, TSubModel *SubModel); void LoadFromTextFile(std::string const &FileName, bool dynamic); void LoadFromBinFile(std::string const &FileName, bool dynamic); - // the model from an E4D file (model/e4d/e4d_load.cpp), as LoadFromBinFile builds it from E3D. returns false, with the reason + // the model from an EU07M file (model/eu07m/eu07m_load.cpp), as LoadFromBinFile builds it from E3D. returns false, with the reason // in the log and nothing loaded, when the file can't be read or isn't valid - bool LoadFromE4D(std::string const &FileName, bool dynamic); + bool LoadFromEU07M(std::string const &FileName, bool dynamic); bool LoadFromFile(std::string const &FileName, bool dynamic); TSubModel *AppendChildFromGeometry(const std::string &name, const std::string &parent, const gfx::vertex_array &vertices, const gfx::index_array &indices); void SaveToBinFile(std::string const &FileName); diff --git a/model/e4d/e4d_build.cpp b/model/eu07m/eu07m_build.cpp similarity index 99% rename from model/e4d/e4d_build.cpp rename to model/eu07m/eu07m_build.cpp index 23254066e..09d725a2a 100644 --- a/model/e4d/e4d_build.cpp +++ b/model/eu07m/eu07m_build.cpp @@ -9,7 +9,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" -#include "model/e4d/e4d_build.h" +#include "model/eu07m/eu07m_build.h" #include #include @@ -17,7 +17,7 @@ http://mozilla.org/MPL/2.0/. #include #include -namespace e4d { +namespace eu07m { namespace { @@ -269,4 +269,4 @@ void compute_bounds(model &Model) { Model.bounds.push_back(to_bounds(whole, whole.empty() ? 0.f : glm::length(whole.max - whole.centre()))); } -} // namespace e4d +} // namespace eu07m diff --git a/model/e4d/e4d_build.h b/model/eu07m/eu07m_build.h similarity index 89% rename from model/e4d/e4d_build.h rename to model/eu07m/eu07m_build.h index e7bd1f9ee..38c485488 100644 --- a/model/e4d/e4d_build.h +++ b/model/eu07m/eu07m_build.h @@ -9,14 +9,14 @@ http://mozilla.org/MPL/2.0/. #pragma once -// the helpers which make and read the data of an E4D model: the tangent frames, the transforms of the nodes, the index of +// the helpers which make and read the data of an EU07M model: the tangent frames, the transforms of the nodes, the index of // the names and the bounds -#include "model/e4d/e4d_model.h" +#include "model/eu07m/eu07m_model.h" #include -namespace e4d { +namespace eu07m { struct tangent_frame { glm::vec3 normal{0.f, 0.f, 1.f}; @@ -47,4 +47,4 @@ std::vector find_nodes(model const &Model, std::string_view Name) // the bounds of every node (its own geometry, in its space) and of the whole model, and the spheres of the primitives void compute_bounds(model &Model); -} // namespace e4d +} // namespace eu07m diff --git a/model/e4d/e4d_convert.cpp b/model/eu07m/eu07m_convert.cpp similarity index 97% rename from model/e4d/e4d_convert.cpp rename to model/eu07m/eu07m_convert.cpp index 76d90fa62..f52c3acf2 100644 --- a/model/e4d/e4d_convert.cpp +++ b/model/eu07m/eu07m_convert.cpp @@ -9,11 +9,11 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" -#include "model/e4d/e4d_convert.h" +#include "model/eu07m/eu07m_convert.h" -#include "model/e4d/e4d_build.h" -#include "model/e4d/e4d_dump.h" -#include "model/e4d/e4d_io.h" +#include "model/eu07m/eu07m_build.h" +#include "model/eu07m/eu07m_dump.h" +#include "model/eu07m/eu07m_io.h" #include "model/Model3d.h" #include "rendering/renderer.h" #include "utilities/Globals.h" @@ -30,11 +30,11 @@ http://mozilla.org/MPL/2.0/. #include #include -namespace e4d { +namespace eu07m { namespace { -// the E3D kinds of geometry are the primitive types of OpenGL, which the topologies of E4D take over +// the E3D kinds of geometry are the primitive types of OpenGL, which the topologies of EU07M take over constexpr int gl_primitive_last{6}; std::uint32_t pack_colour(glm::vec3 const &Colour) { @@ -315,8 +315,8 @@ bool load_source(std::string const &Input, bool const Dynamic, TModel3d &Source, auto const start{std::chrono::steady_clock::now()}; if (extension_of(Input) == ".e3d") Source.LoadFromBinFile(Input, Dynamic); - else if (extension_of(Input) == ".e4d") - Source.LoadFromE4D(Input, Dynamic); + else if (extension_of(Input) == ".ng3d") + Source.LoadFromEU07M(Input, Dynamic); else Source.LoadFromTextFile(Input, Dynamic); if (Milliseconds != nullptr) @@ -476,7 +476,7 @@ void model_diff::geometry(TSubModel const &Left, TSubModel const &Right) { int command_diff(int const Argc, char *Argv[]) { if (Argc < 5) { - std::cerr << "usage: -e4d diff [dynamic 0|1]\n"; + std::cerr << "usage: -eu07m diff [dynamic 0|1]\n"; return 2; } if (false == start_tools(Argc, Argv)) @@ -495,13 +495,13 @@ int command_diff(int const Argc, char *Argv[]) { std::cout << std::format("{}: {} submodels, {} vertices, {} differences; transforms within {:.2g}, normals within {:.3f} deg ({} past 0.5 deg), tangents within {:.3f} deg\n", Argv[4], diff.submodels, diff.vertices, diff.differences.size(), diff.matrix, diff.normal, diff.bent, diff.tangent); // with the files in the system's cache or not, as they came: a run right after another one of the same files finds them there - std::cout << std::format("load: source {:.2f} ms, e4d {:.2f} ms\n", sourcetime, convertedtime); + std::cout << std::format("load: source {:.2f} ms, eu07m {:.2f} ms\n", sourcetime, convertedtime); return diff.differences.empty() ? 0 : 1; } int command_convert(int const Argc, char *Argv[]) { if (Argc < 5) { - std::cerr << "usage: -e4d convert [dynamic 0|1] [convertmodels flags]\n"; + std::cerr << "usage: -eu07m convert [dynamic 0|1] [convertmodels flags]\n"; return 2; } std::string const input{Argv[3]}; @@ -524,7 +524,7 @@ int command_convert(int const Argc, char *Argv[]) { std::cerr << std::format("{}: {}\n", input, fault); auto const file{read_whole_file(input)}; converted.source_hash = hash_bytes(std::as_bytes(std::span{file.data.get(), file.size})); - converted.edit.push_back({converted.intern(input), converted.intern("eu07 -e4d convert"), {}}); + converted.edit.push_back({converted.intern(input), converted.intern("eu07 -eu07m convert"), {}}); if (auto const problems{validate(converted)}; false == problems.empty()) { for (auto const &problem : problems) std::cerr << std::format("the converted model is invalid: {}\n", problem); @@ -543,7 +543,7 @@ int command_convert(int const Argc, char *Argv[]) { int command_read(int const Argc, char *Argv[], bool const Dump) { if (Argc < 4) { - std::cerr << std::format("usage: -e4d {} \n", Dump ? "dump" : "validate"); + std::cerr << std::format("usage: -eu07m {} \n", Dump ? "dump" : "validate"); return 2; } auto const file{read_whole_file(Argv[3])}; @@ -580,8 +580,8 @@ int run_command_line(int const Argc, char *Argv[]) { return command_read(Argc, Argv, false); if (command == "diff") return command_diff(Argc, Argv); - std::cerr << "usage: -e4d convert|dump|validate|diff ...\n"; + std::cerr << "usage: -eu07m convert|dump|validate|diff ...\n"; return 2; } -} // namespace e4d +} // namespace eu07m diff --git a/model/e4d/e4d_convert.h b/model/eu07m/eu07m_convert.h similarity index 59% rename from model/e4d/e4d_convert.h rename to model/eu07m/eu07m_convert.h index 9dc8499fc..904bc8372 100644 --- a/model/e4d/e4d_convert.h +++ b/model/eu07m/eu07m_convert.h @@ -9,23 +9,23 @@ http://mozilla.org/MPL/2.0/. #pragma once -// the conversion of a model loaded from E3D or T3D into E4D, and the -e4d commands of the program +// the conversion of a model loaded from E3D or T3D into EU07M, and the -eu07m commands of the program -#include "model/e4d/e4d_model.h" +#include "model/eu07m/eu07m_model.h" #include #include class TModel3d; -namespace e4d { +namespace eu07m { -// the E4D form of the loaded model, its geometry taken from the renderer's banks (as SaveToBinFile does). the name index +// the EU07M form of the loaded model, its geometry taken from the renderer's banks (as SaveToBinFile does). the name index // and the bounds are filled in; the source hash is left to the caller. the faults of the source found on the way, which // leave the result invalid, are added to Faults, each naming its submodel model convert(TModel3d &Source, std::vector &Faults); -// the -e4d commands: convert, dump, validate. returns the exit code of the program +// the -eu07m commands: convert, dump, validate. returns the exit code of the program int run_command_line(int Argc, char *Argv[]); -} // namespace e4d +} // namespace eu07m diff --git a/model/e4d/e4d_dump.cpp b/model/eu07m/eu07m_dump.cpp similarity index 98% rename from model/e4d/e4d_dump.cpp rename to model/eu07m/eu07m_dump.cpp index 8dcd0925e..5e192e65a 100644 --- a/model/e4d/e4d_dump.cpp +++ b/model/eu07m/eu07m_dump.cpp @@ -9,11 +9,11 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" -#include "model/e4d/e4d_dump.h" +#include "model/eu07m/eu07m_dump.h" #include -namespace e4d { +namespace eu07m { std::string fourcc_name(std::uint32_t const Id) { std::string text(4, ' '); @@ -113,4 +113,4 @@ std::string dump(model const &Model) { return output; } -} // namespace e4d +} // namespace eu07m diff --git a/model/e4d/e4d_dump.h b/model/eu07m/eu07m_dump.h similarity index 67% rename from model/e4d/e4d_dump.h rename to model/eu07m/eu07m_dump.h index 73acab2ab..8219e12f5 100644 --- a/model/e4d/e4d_dump.h +++ b/model/eu07m/eu07m_dump.h @@ -9,16 +9,16 @@ http://mozilla.org/MPL/2.0/. #pragma once -// the content of an E4D model as text, for people and for comparing two files +// the content of an EU07M model as text, for people and for comparing two files -#include "model/e4d/e4d_model.h" +#include "model/eu07m/eu07m_model.h" #include -namespace e4d { +namespace eu07m { std::string dump(model const &Model); std::string fourcc_name(std::uint32_t Id); -} // namespace e4d +} // namespace eu07m diff --git a/model/e4d/e4d_format.h b/model/eu07m/eu07m_format.h similarity index 98% rename from model/e4d/e4d_format.h rename to model/eu07m/eu07m_format.h index e52985a15..51219f31b 100644 --- a/model/e4d/e4d_format.h +++ b/model/eu07m/eu07m_format.h @@ -9,7 +9,7 @@ http://mozilla.org/MPL/2.0/. #pragma once -// the records of the E4D model format, as they lie in the file. docs/e4d-format.md describes them; the sizes and offsets +// the records of the EU07M model format, as they lie in the file. docs/eu07m-format.md describes them; the sizes and offsets // below are the format, and the static_asserts keep the two the same #include @@ -18,9 +18,9 @@ http://mozilla.org/MPL/2.0/. #include #include -namespace e4d { +namespace eu07m { -static_assert(std::endian::native == std::endian::little, "the E4D records are read and uploaded to the gpu as they lie in the file, little-endian"); +static_assert(std::endian::native == std::endian::little, "the EU07M records are read and uploaded to the gpu as they lie in the file, little-endian"); constexpr std::uint32_t fourcc(std::string_view const Code) { return static_cast(static_cast(Code[0])) | (static_cast(static_cast(Code[1])) << 8) | @@ -82,7 +82,7 @@ constexpr std::uint32_t legacy_material{fourcc("LMAT")}; } // namespace component struct file_header { - std::array magic{'E', '4', 'D', '\0'}; + std::array magic{'E', 'U', '7', 'M'}; // the name of the format, EU07M, in four bytes std::uint16_t major{version_major}; std::uint16_t minor{version_minor}; std::uint32_t flags{0}; @@ -575,4 +575,4 @@ static_assert(sizeof(legacy_material) == 4); } // namespace payload -} // namespace e4d +} // namespace eu07m diff --git a/model/e4d/e4d_io.cpp b/model/eu07m/eu07m_io.cpp similarity index 99% rename from model/e4d/e4d_io.cpp rename to model/eu07m/eu07m_io.cpp index 782f472ec..cbef66292 100644 --- a/model/e4d/e4d_io.cpp +++ b/model/eu07m/eu07m_io.cpp @@ -9,8 +9,8 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" -#include "model/e4d/e4d_io.h" -#include "model/e4d/e4d_dump.h" +#include "model/eu07m/eu07m_io.h" +#include "model/eu07m/eu07m_dump.h" #include "meshoptimizer.h" #include "zstd.h" @@ -24,7 +24,7 @@ http://mozilla.org/MPL/2.0/. #include #include -namespace e4d { +namespace eu07m { std::uint32_t model::intern(std::string_view const Text) { if (m_stringids.size() != strings.size()) { @@ -374,7 +374,7 @@ bool file_reader::read_header(file_header &Header) { return fail("the file is shorter than the header"); std::memcpy(&Header, m_file.data(), sizeof(file_header)); if (Header.magic != file_header{}.magic) - return fail("the file isn't an E4D model"); + return fail("the file isn't an EU07M model"); if (Header.major != version_major) return fail(std::format("the model has version {}.{}, this program reads version {}", Header.major, Header.minor, version_major)); if (Header.file_size > m_file.size()) @@ -1171,4 +1171,4 @@ std::vector validate(model const &Model, std::size_t const Limit) { return validator{Model, Limit}.run(); } -} // namespace e4d +} // namespace eu07m diff --git a/model/e4d/e4d_io.h b/model/eu07m/eu07m_io.h similarity index 92% rename from model/e4d/e4d_io.h rename to model/eu07m/eu07m_io.h index 74a963c0b..1296a1f53 100644 --- a/model/e4d/e4d_io.h +++ b/model/eu07m/eu07m_io.h @@ -9,14 +9,14 @@ http://mozilla.org/MPL/2.0/. #pragma once -// writing, reading and checking of E4D files +// writing, reading and checking of EU07M files -#include "model/e4d/e4d_model.h" +#include "model/eu07m/eu07m_model.h" #include #include -namespace e4d { +namespace eu07m { struct write_options { bool compress{true}; // zstd for the sections where it saves at least an eighth @@ -46,4 +46,4 @@ read_result read(std::span File, model &Model, read_options con // the faults of the model, each a line of text; empty when it can be used. stops after Limit faults std::vector validate(model const &Model, std::size_t Limit = 16); -} // namespace e4d +} // namespace eu07m diff --git a/model/e4d/e4d_load.cpp b/model/eu07m/eu07m_load.cpp similarity index 73% rename from model/e4d/e4d_load.cpp rename to model/eu07m/eu07m_load.cpp index 475face2b..1595eb2e8 100644 --- a/model/e4d/e4d_load.cpp +++ b/model/eu07m/eu07m_load.cpp @@ -11,8 +11,8 @@ http://mozilla.org/MPL/2.0/. #include "model/Model3d.h" -#include "model/e4d/e4d_build.h" -#include "model/e4d/e4d_io.h" +#include "model/eu07m/eu07m_build.h" +#include "model/eu07m/eu07m_io.h" #include "rendering/renderer.h" #include "utilities/Logs.h" #include "utilities/utilities.h" @@ -22,6 +22,7 @@ http://mozilla.org/MPL/2.0/. #include #include +#include #include #include #include @@ -29,43 +30,49 @@ http://mozilla.org/MPL/2.0/. #include #include -// the loading of an E4D model into the tree of submodels the rest of the game works with: each node becomes a submodel, with +// the loading of an EU07M model into the tree of submodels the rest of the game works with: each node becomes a submodel, with // what E3D keeps in the submodel taken from the node, its material, its primitive and its components. the result is what // TModel3d::LoadFromBinFile() makes of the E3D the model was converted from namespace { -// what E3D keeps in the submodel and E4D in the components of the node +// the vertex streams of the file are the compact layout of the renderer, byte for byte +static_assert(sizeof(eu07m::position) == sizeof(glm::vec3)); +static_assert(sizeof(eu07m::attributes) == sizeof(gfx::compact_attributes)); +static_assert(offsetof(eu07m::attributes, qtangent) == offsetof(gfx::compact_attributes, qtangent)); +static_assert(offsetof(eu07m::attributes, uv) == offsetof(gfx::compact_attributes, texture)); + +// what E3D keeps in the submodel and EU07M in the components of the node struct legacy_parts { - std::optional light; - std::uint32_t material{e4d::no_index}; // of a node without geometry + std::optional light; + std::uint32_t material{eu07m::no_index}; // of a node without geometry TAnimType animation{TAnimType::at_None}; bool text{false}; std::span stars; // the packed colours, one for each vertex of the mesh }; -legacy_parts parts_of(e4d::model const &Model, e4d::node_record const &Node) { +legacy_parts parts_of(eu07m::model const &Model, eu07m::node_record const &Node) { legacy_parts parts; for (auto idx = Node.component_first; idx < Node.component_first + Node.component_count; ++idx) { auto const type{Model.components[idx].type}; auto const data{Model.component_payload(idx)}; - e4d::payload_reader reader{data}; - if (type == e4d::component::light) { - if (e4d::payload::light light; reader.get(light)) + eu07m::payload_reader reader{data}; + if (type == eu07m::component::light) { + if (eu07m::payload::light light; reader.get(light)) parts.light = light; } - else if (type == e4d::component::legacy_animation) { - if (e4d::payload::legacy_animation animation; reader.get(animation)) + else if (type == eu07m::component::legacy_animation) { + if (eu07m::payload::legacy_animation animation; reader.get(animation)) parts.animation = static_cast(animation.type); } - else if (type == e4d::component::legacy_text) + else if (type == eu07m::component::legacy_text) parts.text = true; - else if (type == e4d::component::legacy_material) { - if (e4d::payload::legacy_material material; reader.get(material)) + else if (type == eu07m::component::legacy_material) { + if (eu07m::payload::legacy_material material; reader.get(material)) parts.material = material.material; } - else if (type == e4d::component::legacy_stars && data.size() >= sizeof(e4d::payload::legacy_stars)) - parts.stars = data.subspan(sizeof(e4d::payload::legacy_stars)); + else if (type == eu07m::component::legacy_stars && data.size() >= sizeof(eu07m::payload::legacy_stars)) + parts.stars = data.subspan(sizeof(eu07m::payload::legacy_stars)); } return parts; } @@ -83,7 +90,7 @@ glm::vec4 to_vec4(std::array const &Value) { // the vertices and the indices of a submodel, filled once the submodels are set up struct geometry_job { - e4d::primitive_record const *primitive{nullptr}; + eu07m::primitive_record const *primitive{nullptr}; std::span stars; TSubModel *submodel{nullptr}; }; @@ -95,8 +102,8 @@ constexpr unsigned parallel_thread_limit{8}; // fills the submodels from the nodes of the model class submodel_builder { public: - submodel_builder(e4d::model const &Model, std::vector &Textures, std::vector &Names, std::vector &Matrices) - : m_model(Model), m_textures(Textures), m_names(Names), m_matrices(Matrices), m_transforms(e4d::local_transforms(Model)) { + submodel_builder(eu07m::model const &Model, std::vector &Textures, std::vector &Names, std::vector &Matrices) + : m_model(Model), m_textures(Textures), m_names(Names), m_matrices(Matrices), m_transforms(eu07m::local_transforms(Model)) { // texture 0 is "none" in the submodels m_textures.emplace_back(); } @@ -108,13 +115,13 @@ class submodel_builder { void links(std::uint32_t Index, TSubModel &Submodel) const; void transform(std::uint32_t Index, TSubModel &Submodel); void material(std::uint32_t Material, TSubModel &Submodel); - static void light(e4d::payload::light const &Light, TSubModel &Submodel); - void geometry(e4d::primitive_record const &Primitive, legacy_parts const &Parts, TSubModel &Submodel); + static void light(eu07m::payload::light const &Light, TSubModel &Submodel); + void geometry(eu07m::primitive_record const &Primitive, legacy_parts const &Parts, TSubModel &Submodel); void fill(geometry_job const &Job) const; - void indices(e4d::primitive_record const &Primitive, TSubModel &Submodel) const; + void indices(eu07m::primitive_record const &Primitive, TSubModel &Submodel) const; int texture(std::string_view Name); - e4d::model const &m_model; + eu07m::model const &m_model; std::vector &m_textures; std::vector &m_names; std::vector &m_matrices; @@ -131,7 +138,7 @@ class submodel_builder { void submodel_builder::build(std::uint32_t const Index, TSubModel &Submodel) { auto const &node{m_model.nodes[Index]}; links(Index, Submodel); - if (node.name != e4d::no_index) { + if (node.name != eu07m::no_index) { Submodel.iName = static_cast(m_names.size()); m_names.emplace_back(m_model.string(node.name)); } @@ -168,7 +175,7 @@ void submodel_builder::links(std::uint32_t const Index, TSubModel &Submodel) con } void submodel_builder::transform(std::uint32_t const Index, TSubModel &Submodel) { - if ((m_model.nodes[Index].flags & e4d::node_flags::no_transform) != 0) { + if ((m_model.nodes[Index].flags & eu07m::node_flags::no_transform) != 0) { Submodel.iMatrix = -1; return; } @@ -189,7 +196,7 @@ void submodel_builder::material(std::uint32_t const Material, TSubModel &Submode auto const &material{m_model.materials[Material]}; if (material.replaceable != 0) Submodel.iTexture = material.replaceable; - else if (material.name != e4d::no_index) + else if (material.name != eu07m::no_index) Submodel.iTexture = texture(m_model.string(material.name)); Submodel.fLight = material.selfillum; Submodel.f4Ambient = to_vec4(material.ambient); @@ -198,8 +205,8 @@ void submodel_builder::material(std::uint32_t const Material, TSubModel &Submode Submodel.f4Emision = to_vec4(material.emission); } -void submodel_builder::light(e4d::payload::light const &Light, TSubModel &Submodel) { - namespace light_flags = e4d::payload::light_flags; +void submodel_builder::light(eu07m::payload::light const &Light, TSubModel &Submodel) { + namespace light_flags = eu07m::payload::light_flags; Submodel.f4Diffuse = to_vec4(Light.color); Submodel.fHotspotPower = Light.hotspot_power; Submodel.fLightRadius = Light.radius; @@ -217,10 +224,10 @@ void submodel_builder::light(e4d::payload::light const &Light, TSubModel &Submod } // what the submodel knows of its geometry; the vertices and the indices come later, in fill_geometry() -void submodel_builder::geometry(e4d::primitive_record const &Primitive, legacy_parts const &Parts, TSubModel &Submodel) { - Submodel.eType = Parts.stars.empty() ? static_cast(Primitive.flags & e4d::primitive_flags::topology_mask) : TP_STARS; +void submodel_builder::geometry(eu07m::primitive_record const &Primitive, legacy_parts const &Parts, TSubModel &Submodel) { + Submodel.eType = Parts.stars.empty() ? static_cast(Primitive.flags & eu07m::primitive_flags::topology_mask) : TP_STARS; material(Primitive.material, Submodel); - auto const indexed{(Primitive.flags & e4d::primitive_flags::indexed) != 0}; + auto const indexed{(Primitive.flags & eu07m::primitive_flags::indexed) != 0}; Submodel.m_geometry.vertex_count = static_cast(Primitive.vertex_count); Submodel.m_geometry.vertex_offset = m_vertexoffset; Submodel.m_geometry.index_count = indexed ? static_cast(Primitive.index_count) : 0; @@ -237,21 +244,6 @@ 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 - submodel.Vertices.clear(); - submodel.Vertices.reserve(primitive.vertex_count); - for (std::uint32_t idx = 0; idx < primitive.vertex_count; ++idx) { - auto const source{std::size_t{primitive.base_vertex} + idx}; - auto const &position{m_model.positions[source]}; - auto const &attribute{m_model.vertex_attributes[source]}; - 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.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); @@ -259,12 +251,36 @@ void submodel_builder::fill(geometry_job const &Job) const { 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) { + auto const source{std::size_t{primitive.base_vertex} + idx}; + auto const &position{m_model.positions[source]}; + auto const &attribute{m_model.vertex_attributes[source]}; + auto const frame{eu07m::decode_qtangent(attribute.qtangent)}; + gfx::basic_vertex vertex; + vertex.position = {position[0], position[1], position[2]}; + 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); + } } -void submodel_builder::indices(e4d::primitive_record const &Primitive, TSubModel &Submodel) const { - if ((Primitive.flags & e4d::primitive_flags::indexed) == 0) +void submodel_builder::indices(eu07m::primitive_record const &Primitive, TSubModel &Submodel) const { + if ((Primitive.flags & eu07m::primitive_flags::indexed) == 0) return; - if ((Primitive.flags & e4d::primitive_flags::index32) != 0) { + if ((Primitive.flags & eu07m::primitive_flags::index32) != 0) { auto const source{std::span{m_model.indices32}.subspan(Primitive.first_index, Primitive.index_count)}; Submodel.Indices.assign(source.begin(), source.end()); } @@ -317,18 +333,18 @@ void submodel_builder::fill_geometry() { } // namespace -bool TModel3d::LoadFromE4D(std::string const &FileName, bool const dynamic) { - WriteLog("Loading E4D model data from \"" + FileName + "\"...", logtype::model); +bool TModel3d::LoadFromEU07M(std::string const &FileName, bool const dynamic) { + WriteLog("Loading EU07M model data from \"" + FileName + "\"...", logtype::model); auto const file{read_whole_file(FileName)}; if (file.data == nullptr) { ErrorLog("Bad model: can't read \"" + FileName + "\"", logtype::model); return false; } - e4d::model model; + eu07m::model model; // the game has no use for the sections it doesn't know try { - if (auto const result{e4d::read(std::as_bytes(std::span{file.data.get(), file.size}), model, {false, false})}; false == result.ok) { - ErrorLog("Bad model: \"" + FileName + "\" isn't a valid E4D file: " + result.error, logtype::model); + if (auto const result{eu07m::read(std::as_bytes(std::span{file.data.get(), file.size}), model, {false, false})}; false == result.ok) { + ErrorLog("Bad model: \"" + FileName + "\" isn't a valid EU07M file: " + result.error, logtype::model); return false; } } @@ -370,6 +386,6 @@ bool TModel3d::LoadFromE4D(std::string const &FileName, bool const dynamic) { m_indexcount += builder.index_count; // the tangents come with the vertices finish_binary(dynamic, true); - WriteLog("Finished loading E4D model data from \"" + FileName + "\"", logtype::model); + WriteLog("Finished loading EU07M model data from \"" + FileName + "\"", logtype::model); return true; } diff --git a/model/e4d/e4d_model.h b/model/eu07m/eu07m_model.h similarity index 95% rename from model/e4d/e4d_model.h rename to model/eu07m/eu07m_model.h index da3228e87..82567ab33 100644 --- a/model/e4d/e4d_model.h +++ b/model/eu07m/eu07m_model.h @@ -9,9 +9,9 @@ http://mozilla.org/MPL/2.0/. #pragma once -// an E4D model in memory: the tables of the file, as the writer takes them and the reader gives them back +// an EU07M model in memory: the tables of the file, as the writer takes them and the reader gives them back -#include "model/e4d/e4d_format.h" +#include "model/eu07m/eu07m_format.h" #include #include @@ -22,7 +22,7 @@ http://mozilla.org/MPL/2.0/. #include #include -namespace e4d { +namespace eu07m { // a section the reader didn't know, kept so the tools write it back unchanged struct unknown_section { @@ -139,4 +139,4 @@ std::uint64_t hash_bytes(std::span Data, std::uint64_t Seed = 0 // FNV-1a 64 of the name in ASCII lowercase, the key of the name index std::uint64_t hash_name(std::string_view Name); -} // namespace e4d +} // namespace eu07m diff --git a/rendering/geometrybank.cpp b/rendering/geometrybank.cpp index 4b12ec65e..ce84c9be1 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 (eu07m::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 ); @@ -436,11 +496,36 @@ geometry_bank::indices( gfx::geometry_handle const &Geometry ) const { return geometry_bank::chunk( Geometry ).indices; } +// the positions of the vertices of specified chunk: of a chunk of the compact layout its stream as it is, without making the +// basic_vertex of it which vertices() keeps for good +position_array +geometry_bank::positions( gfx::geometry_handle const &Geometry ) const { + + auto const &chunk { geometry_bank::chunk( Geometry ) }; + std::scoped_lock lock { m_decodemutex }; + if( chunk.compact() ) { + return chunk.positions; + } + position_array positions; + positions.reserve( chunk.vertices.size() ); + for( auto const &vertex : chunk.vertices ) { + positions.push_back( vertex.position ); + } + return positions; +} + // provides direct access to vertex data of specfied chunk 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 +561,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 +616,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 ) { @@ -674,6 +769,12 @@ geometrybank_manager::indices( gfx::geometry_handle const &Geometry ) const { } // provides direct access to vertex data of specfied chunk +gfx::position_array +geometrybank_manager::positions( gfx::geometry_handle const &Geometry ) const { + + return bank( Geometry ).first->positions( Geometry ); +} + gfx::vertex_array const & geometrybank_manager::vertices( gfx::geometry_handle const &Geometry ) const { diff --git a/rendering/geometrybank.h b/rendering/geometrybank.h index 366ea339d..b44ee7f4b 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 EU07M 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 @@ -161,6 +181,8 @@ public: void release(); // provides direct access to index data of specfied chunk auto indices( gfx::geometry_handle const &Geometry ) const -> gfx::index_array const &; + // the positions of the vertices of specified chunk, without the basic_vertex of a chunk of the compact layout being made + auto positions( gfx::geometry_handle const &Geometry ) const -> gfx::position_array; // provides direct access to vertex data of specfied chunk auto vertices( gfx::geometry_handle const &Geometry ) const -> gfx::vertex_array const &; // provides direct access to vertex user data of specfied chunk @@ -178,9 +200,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 +236,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 +290,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 @@ -291,6 +326,8 @@ public: ++First; } } // provides direct access to index data of specfied chunk auto indices( gfx::geometry_handle const &Geometry ) const -> gfx::index_array const &; + // the positions of the vertices of specified chunk (geometry_bank::positions()) + auto positions( gfx::geometry_handle const &Geometry ) const -> gfx::position_array; // provides direct access to vertex data of specfied chunk auto vertices( gfx::geometry_handle const &Geometry ) const -> gfx::vertex_array const &; // what the banks keep in the process, for the debug panel: banks, chunks with their vertex bytes, index bytes and user data bytes diff --git a/rendering/renderer.h b/rendering/renderer.h index d84035b68..5021e9992 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 EU07M 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. @@ -116,6 +123,15 @@ public: virtual auto Indices( gfx::geometry_handle const &Geometry ) const->gfx::index_array const & = 0; // provides direct access to vertex data of specfied chunk virtual auto Vertices( gfx::geometry_handle const &Geometry ) const ->gfx::vertex_array const & = 0; + // the positions of the vertices of specified chunk, for what needs no more of them (the bounds of a model as it loads): a renderer + // keeping the compact streams of an EU07M model gives them without making and keeping the basic_vertex Vertices() would + virtual auto Positions( gfx::geometry_handle const &Geometry ) const -> gfx::position_array { + auto const &vertices { Vertices( Geometry ) }; + gfx::position_array positions; + positions.reserve( vertices.size() ); + for( auto const &vertex : vertices ) { + positions.push_back( vertex.position ); } + return positions; } // provides direct access to vertex user data of specfied chunk virtual auto UserData( gfx::geometry_handle const &Geometry ) const ->gfx::userdata_array const & = 0; // kind of geometry of specified chunk, -1 when the renderer doesn't tell diff --git a/rendering/vulkan14/vulkan14context.h b/rendering/vulkan14/vulkan14context.h index 26010523c..6bef028aa 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 EU07M 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 @@ -791,6 +797,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..b1f9f59b8 100644 --- a/rendering/vulkan14/vulkan14geometry.cpp +++ b/rendering/vulkan14/vulkan14geometry.cpp @@ -12,6 +12,7 @@ http://mozilla.org/MPL/2.0/. #include "rendering/vulkan14/vulkan14texture.h" #include +#include namespace vk14 { @@ -25,8 +26,24 @@ gfx::vertex_userdata const no_userdata{glm::vec4{0.f, 0.f, 0.f, 1.f}}; // the numbers the data of the banks get, unique across the banks (a bank made where another one was gets a new one) std::atomic g_generation{0}; +// set when a variant of a program for the compact layout didn't compile (compact_layout_failed()) +std::atomic g_compactfailed{false}; + } // namespace +void compact_layout_failed(std::string_view const Program) +{ + if (false == g_compactfailed.exchange(true)) + { + log_error(std::format("the compact vertex variant of \"{}\" didn't compile; EU07M models are drawn from basic_vertex from now on", Program)); + } +} + +bool compact_layout_usable() +{ + return false == g_compactfailed.load(); +} + VkPrimitiveTopology topology_of(unsigned int const Type) { switch (Type) @@ -61,8 +78,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 +109,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 +124,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 +143,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 +166,18 @@ bool vulkan14_geometrybank::build() } release_(); + // the compact layout when every chunk of the bank is of it (an EU07M model); otherwise its chunks go as basic_vertex + m_compact = compact_layout_usable() && (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 +185,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 +207,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 +230,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; } @@ -249,7 +314,8 @@ bool vulkan14_geometrybank::source(gfx::geometry_handle const &Geometry, chunk_s return false; } std::lock_guard lock(m_mutex); - if (m_layoutdirty) + // a bank of the compact layout whose programs can't be had is made anew of basic_vertex + if (m_layoutdirty || (m_compact && (false == compact_layout_usable()))) { build(); } @@ -265,6 +331,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 +340,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..7ad767074 100644 --- a/rendering/vulkan14/vulkan14geometry.h +++ b/rendering/vulkan14/vulkan14geometry.h @@ -22,6 +22,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include namespace vk14 { @@ -31,8 +32,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 +49,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}; }; @@ -50,6 +57,12 @@ struct chunk_source // the vulkan primitive of a primitive of opengl (GL_TRIANGLES ...) VkPrimitiveTopology topology_of(unsigned int Type); +// a variant of a scene program for the compact layout didn't compile: the banks of EU07M models are made of basic_vertex +// from then on, those made already when they are drawn next, so the models stay in sight. told once in the log +void compact_layout_failed(std::string_view Program); +// false once compact_layout_failed() was called +bool compact_layout_usable(); + class vulkan14_geometrybank : public gfx::geometry_bank { public: @@ -91,10 +104,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 d47428fe7..e6536bd84 100644 --- a/rendering/vulkan14/vulkan14indirect.cpp +++ b/rendering/vulkan14/vulkan14indirect.cpp @@ -279,43 +279,72 @@ 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) { vk14::log_error(Exception.what()); + if (Kind.compact) + { + // without the variant the chunks of the compact layout would be left out for good: their banks go back to basic_vertex + vk14::compact_layout_failed(Name); + } } return nullptr; } } // 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 +354,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 +402,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 +478,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..5d31a8fda 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 EU07M 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 0c2cf8e26..d0f97e154 100644 --- a/rendering/vulkan14/vulkan14renderer.h +++ b/rendering/vulkan14/vulkan14renderer.h @@ -80,12 +80,15 @@ 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 EU07M 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; void Erase(gfx::geometry_handle const &Geometry) override; gfx::index_array const &Indices(gfx::geometry_handle const &Geometry) const override; gfx::vertex_array const &Vertices(gfx::geometry_handle const &Geometry) const override; + gfx::position_array Positions(gfx::geometry_handle const &Geometry) const override; gfx::userdata_array const &UserData(gfx::geometry_handle const &Geometry) const override; int Primitive(gfx::geometry_handle const &Geometry) const override; // the sleepers and timbers are drawn by the walk of the scene (gfx::scene_walk), as in the opengl renderer @@ -263,6 +266,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 0e221446a..6ca017514 100644 --- a/rendering/vulkan14/vulkan14scene.cpp +++ b/rendering/vulkan14/vulkan14scene.cpp @@ -92,6 +92,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}}; @@ -1288,6 +1299,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) @@ -1337,6 +1356,11 @@ gfx::vertex_array const &vulkan14_renderer::Vertices(gfx::geometry_handle const return m_geometry.vertices(Geometry); } +gfx::position_array vulkan14_renderer::Positions(gfx::geometry_handle const &Geometry) const +{ + return m_geometry.positions(Geometry); +} + gfx::userdata_array const &vulkan14_renderer::UserData(gfx::geometry_handle const &Geometry) const { return m_geometry.userdata(Geometry); @@ -2148,6 +2172,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}; @@ -2190,9 +2249,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; @@ -2229,14 +2289,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) { @@ -2341,7 +2394,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 6c0884dc1..6d070d7fd 100644 --- a/shaders/vk14/common.glsl +++ b/shaders/vk14/common.glsl @@ -476,6 +476,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 EU07M 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..68a5f5193 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 EU07M 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); diff --git a/tests/unit/test_e4d.cpp b/tests/unit/test_eu07m.cpp similarity index 60% rename from tests/unit/test_e4d.cpp rename to tests/unit/test_eu07m.cpp index 6166e8ea8..5fac0167e 100644 --- a/tests/unit/test_e4d.cpp +++ b/tests/unit/test_eu07m.cpp @@ -2,9 +2,9 @@ #include "doctest.h" -#include "model/e4d/e4d_build.h" -#include "model/e4d/e4d_dump.h" -#include "model/e4d/e4d_io.h" +#include "model/eu07m/eu07m_build.h" +#include "model/eu07m/eu07m_dump.h" +#include "model/eu07m/eu07m_io.h" #include @@ -15,10 +15,10 @@ namespace { // a small model with something in every section: a root, a body with a quad and a light, a hose skinned to two joints -e4d::model sample_model() { - e4d::model model; +eu07m::model sample_model() { + eu07m::model model; auto const node{[&model](std::string_view const Name, std::int32_t const Parent) { - e4d::node_record record; + eu07m::node_record record; record.name = model.intern(Name); record.parent = Parent; model.nodes.push_back(record); @@ -35,29 +35,29 @@ e4d::model sample_model() { model.nodes[hose].subtree_end = 5; model.nodes[body].translation = {1.f, 2.f, 3.f}; - e4d::material_record material; + eu07m::material_record material; material.name = model.intern("pkp/body.mat"); model.materials.push_back(material); - e4d::material_record skin; + eu07m::material_record skin; skin.replaceable = -1; model.materials.push_back(skin); // the quad of the body, indexed for (auto const &corner : std::array{glm::vec2{0.f, 0.f}, {1.f, 0.f}, {1.f, 1.f}, {0.f, 1.f}}) { model.positions.push_back({corner.x, corner.y, 0.f}); - e4d::attributes attribute; - attribute.qtangent = e4d::encode_qtangent({{0.f, 0.f, 1.f}, {1.f, 0.f, 0.f}, 1.f}); + eu07m::attributes attribute; + attribute.qtangent = eu07m::encode_qtangent({{0.f, 0.f, 1.f}, {1.f, 0.f, 0.f}, 1.f}); attribute.uv = {corner.x, corner.y}; model.vertex_attributes.push_back(attribute); model.weights.push_back({}); } model.indices16 = {0, 1, 2, 0, 2, 3}; - e4d::primitive_record quad; + eu07m::primitive_record quad; quad.index_count = 6; quad.vertex_count = 4; quad.node = body; quad.material = 0; - quad.flags = static_cast(e4d::topology::triangles) | e4d::primitive_flags::indexed | e4d::primitive_flags::opaque; + quad.flags = static_cast(eu07m::topology::triangles) | eu07m::primitive_flags::indexed | eu07m::primitive_flags::opaque; model.primitives.push_back(quad); model.meshes.push_back({0, 1, -1, 0}); model.nodes[body].mesh = 0; @@ -67,24 +67,24 @@ e4d::model sample_model() { for (int idx = 0; idx < 3; ++idx) { model.positions.push_back({0.f, 0.f, static_cast(idx)}); model.vertex_attributes.push_back({}); - e4d::skin_weights weights; + eu07m::skin_weights weights; weights.joints = {0, 1, 0, 0}; weights.weights = hoseweights[idx]; model.weights.push_back(weights); } - e4d::primitive_record line; + eu07m::primitive_record line; line.base_vertex = 4; line.vertex_count = 3; line.index_count = 3; line.node = hose; line.material = 1; line.skin = 0; - line.flags = static_cast(e4d::topology::line_strip); + line.flags = static_cast(eu07m::topology::line_strip); model.primitives.push_back(line); model.meshes.push_back({1, 1, 0, 0}); model.nodes[hose].mesh = 1; model.skins.push_back({0, 2, static_cast(hose), 0}); - e4d::skin_joint_record first; + eu07m::skin_joint_record first; first.node = joint0; first.inverse_bind = {1.f, 0.f, 0.f, 0.f, 1.f, 0.f, 0.f, 0.f, 1.f, 0.f, 0.f, 0.f}; auto second{first}; @@ -93,46 +93,46 @@ e4d::model sample_model() { // the components of the body (a socket and a light), then the chain of the hose, then a light slot of the model model.nodes[body].component_first = 0; - e4d::payload::socket socket; + eu07m::payload::socket socket; socket.role = model.intern("hook"); - socket.end = e4d::payload::side::front; - model.add_component(e4d::component::socket, e4d::target_kind::node, body, e4d::payload_writer{}.put(socket).data()); - auto const light{model.add_component(e4d::component::light, e4d::target_kind::node, body, e4d::payload_writer{}.put(e4d::payload::light{}).data())}; + socket.end = eu07m::payload::side::front; + model.add_component(eu07m::component::socket, eu07m::target_kind::node, body, eu07m::payload_writer{}.put(socket).data()); + auto const light{model.add_component(eu07m::component::light, eu07m::target_kind::node, body, eu07m::payload_writer{}.put(eu07m::payload::light{}).data())}; model.nodes[body].component_count = 2; model.nodes[hose].component_first = 2; - e4d::payload::chain chain; - chain.kind = e4d::payload::chain_kind::hose_brake; + eu07m::payload::chain chain; + chain.kind = eu07m::payload::chain_kind::hose_brake; chain.joint_count = 2; chain.skin = 0; chain.end_a = 0; - model.add_component(e4d::component::chain, e4d::target_kind::node, hose, e4d::payload_writer{}.put(chain).put(joint0).put(joint1).put(0.5f).data()); + model.add_component(eu07m::component::chain, eu07m::target_kind::node, hose, eu07m::payload_writer{}.put(chain).put(joint0).put(joint1).put(0.5f).data()); model.nodes[hose].component_count = 1; - e4d::payload::light_slot slot; + eu07m::payload::light_slot slot; slot.on_count = 1; slot.light_count = 1; - model.add_component(e4d::component::light_slot, e4d::target_kind::model, 0, e4d::payload_writer{}.put(slot).put(body).put(light).data()); + model.add_component(eu07m::component::light_slot, eu07m::target_kind::model, 0, eu07m::payload_writer{}.put(slot).put(body).put(light).data()); // a vertex group of the hose with metadata, and an unknown section of a later version model.vertex_group_items = {4, 2}; - model.vertex_groups.push_back({model.intern("rigid head"), 1, 0, 1, e4d::vertex_group_flags::ranges, 4, 1, 0}); - e4d::payload::property property; + model.vertex_groups.push_back({model.intern("rigid head"), 1, 0, 1, eu07m::vertex_group_flags::ranges, 4, 1, 0}); + eu07m::payload::property property; property.key = model.intern("rigid"); - property.type = e4d::payload::value_type::boolean; + property.type = eu07m::payload::value_type::boolean; property.value[0] = 1; - model.add_component(e4d::component::properties, e4d::target_kind::vertex_group, 0, e4d::payload_writer{}.put(std::uint32_t{1}).put(property).data()); - model.unknown.push_back({e4d::fourcc("ZZZZ"), 0, {std::byte{1}, std::byte{2}, std::byte{3}}}); + model.add_component(eu07m::component::properties, eu07m::target_kind::vertex_group, 0, eu07m::payload_writer{}.put(std::uint32_t{1}).put(property).data()); + model.unknown.push_back({eu07m::fourcc("ZZZZ"), 0, {std::byte{1}, std::byte{2}, std::byte{3}}}); - e4d::build_name_index(model); - e4d::compute_bounds(model); + eu07m::build_name_index(model); + eu07m::compute_bounds(model); return model; } std::vector sample_file(bool const Compress = true) { - return e4d::write(sample_model(), {Compress, 9}); + return eu07m::write(sample_model(), {Compress, 9}); } -e4d::read_result read_file(std::vector const &File, e4d::model &Model) { - return e4d::read(File, Model, {true, true}); +eu07m::read_result read_file(std::vector const &File, eu07m::model &Model) { + return eu07m::read(File, Model, {true, true}); } template Type_ get_at(std::vector const &File, std::size_t const Offset) { @@ -147,10 +147,10 @@ template void put_at(std::vector &File, std::size_t // the entry of the section in the list of the file std::size_t entry_offset(std::vector const &File, std::uint32_t const Id) { - auto const header{get_at(File, 0)}; + auto const header{get_at(File, 0)}; for (std::size_t idx = 0; idx < header.section_count; ++idx) { - auto const offset{header.toc_offset + idx * sizeof(e4d::section_entry)}; - if (get_at(File, offset).id == Id) + auto const offset{header.toc_offset + idx * sizeof(eu07m::section_entry)}; + if (get_at(File, offset).id == Id) return offset; } FAIL("no such section"); @@ -159,82 +159,82 @@ std::size_t entry_offset(std::vector const &File, std::uint32_t const // the hash of the content made right again after a change, so the reader looks at the change itself void rehash(std::vector &File) { - auto header{get_at(File, 0)}; - header.content_hash = e4d::hash_bytes(std::span{File}.subspan(sizeof(e4d::file_header))); + auto header{get_at(File, 0)}; + header.content_hash = eu07m::hash_bytes(std::span{File}.subspan(sizeof(eu07m::file_header))); put_at(File, 0, header); } } // namespace -TEST_CASE("e4d: a model written and read back is the same") +TEST_CASE("eu07m: a model written and read back is the same") { auto const original{sample_model()}; - REQUIRE(e4d::validate(original).empty()); + REQUIRE(eu07m::validate(original).empty()); for (auto const compress : {false, true}) { CAPTURE(compress); - auto const file{e4d::write(original, {compress, 9})}; - e4d::model loaded; + auto const file{eu07m::write(original, {compress, 9})}; + eu07m::model loaded; auto const result{read_file(file, loaded)}; REQUIRE_MESSAGE(result.ok, result.error); - CHECK(e4d::dump(loaded) == e4d::dump(original)); + CHECK(eu07m::dump(loaded) == eu07m::dump(original)); CHECK(loaded.strings == original.strings); CHECK(loaded.component_data == original.component_data); CHECK(loaded.indices16 == original.indices16); CHECK(loaded.weights.size() == original.weights.size()); - CHECK(std::memcmp(loaded.nodes.data(), original.nodes.data(), original.nodes.size() * sizeof(e4d::node_record)) == 0); + CHECK(std::memcmp(loaded.nodes.data(), original.nodes.data(), original.nodes.size() * sizeof(eu07m::node_record)) == 0); REQUIRE(loaded.unknown.size() == 1); CHECK(loaded.unknown.front().data == original.unknown.front().data); } } -TEST_CASE("e4d: the sections lie where the format says") +TEST_CASE("eu07m: the sections lie where the format says") { auto const file{sample_file(false)}; - auto const header{get_at(file, 0)}; + auto const header{get_at(file, 0)}; CHECK(header.file_size == file.size()); - CHECK(header.toc_offset == sizeof(e4d::file_header)); + CHECK(header.toc_offset == sizeof(eu07m::file_header)); for (std::size_t idx = 0; idx < header.section_count; ++idx) { - auto const entry{get_at(file, header.toc_offset + idx * sizeof(e4d::section_entry))}; - auto const stream{entry.id == e4d::section::positions || entry.id == e4d::section::attributes || entry.id == e4d::section::indices16}; - CHECK(entry.offset % (stream ? e4d::gpu_alignment : e4d::section_alignment) == 0); + auto const entry{get_at(file, header.toc_offset + idx * sizeof(eu07m::section_entry))}; + auto const stream{entry.id == eu07m::section::positions || entry.id == eu07m::section::attributes || entry.id == eu07m::section::indices16}; + CHECK(entry.offset % (stream ? eu07m::gpu_alignment : eu07m::section_alignment) == 0); } // the strings of the model - auto const strings{get_at(file, entry_offset(file, e4d::section::strings))}; - CHECK((strings.flags & e4d::section_flags::required) != 0); + auto const strings{get_at(file, entry_offset(file, eu07m::section::strings))}; + CHECK((strings.flags & eu07m::section_flags::required) != 0); CHECK(get_at(file, strings.offset) == sample_model().strings.size()); } -TEST_CASE("e4d: a table with longer records of a later version is read by its known part") +TEST_CASE("eu07m: a table with longer records of a later version is read by its known part") { auto const model{sample_model()}; - auto file{e4d::write(model, {false, 0})}; + auto file{eu07m::write(model, {false, 0})}; // the nodes written again with 16 more bytes each, in a new section at the end of the file std::vector table; - auto const header{e4d::table_header{static_cast(model.nodes.size()), static_cast(sizeof(e4d::node_record) + 16)}}; + auto const header{eu07m::table_header{static_cast(model.nodes.size()), static_cast(sizeof(eu07m::node_record) + 16)}}; table.resize(sizeof(header) + header.count * header.stride, std::byte{0x5A}); std::memcpy(table.data(), &header, sizeof(header)); for (std::size_t idx = 0; idx < model.nodes.size(); ++idx) - std::memcpy(table.data() + sizeof(header) + idx * header.stride, &model.nodes[idx], sizeof(e4d::node_record)); - auto const entryoffset{entry_offset(file, e4d::section::nodes)}; - auto entry{get_at(file, entryoffset)}; - while (file.size() % e4d::section_alignment != 0) + std::memcpy(table.data() + sizeof(header) + idx * header.stride, &model.nodes[idx], sizeof(eu07m::node_record)); + auto const entryoffset{entry_offset(file, eu07m::section::nodes)}; + auto entry{get_at(file, entryoffset)}; + while (file.size() % eu07m::section_alignment != 0) file.push_back(std::byte{0}); entry.offset = file.size(); entry.size = entry.stored_size = table.size(); file.insert(file.end(), table.begin(), table.end()); put_at(file, entryoffset, entry); - auto fileheader{get_at(file, 0)}; + auto fileheader{get_at(file, 0)}; fileheader.file_size = file.size(); put_at(file, 0, fileheader); rehash(file); - e4d::model loaded; + eu07m::model loaded; auto const result{read_file(file, loaded)}; REQUIRE_MESSAGE(result.ok, result.error); - CHECK(std::memcmp(loaded.nodes.data(), model.nodes.data(), model.nodes.size() * sizeof(e4d::node_record)) == 0); + CHECK(std::memcmp(loaded.nodes.data(), model.nodes.data(), model.nodes.size() * sizeof(eu07m::node_record)) == 0); } -TEST_CASE("e4d: broken files are refused with a reason, and leave the model empty") +TEST_CASE("eu07m: broken files are refused with a reason, and leave the model empty") { auto const good{sample_file(false)}; struct breakage { @@ -242,16 +242,16 @@ TEST_CASE("e4d: broken files are refused with a reason, and leave the model empt std::function &)> apply; std::string_view reason; }; - auto const section{[&good](std::uint32_t const Id) { return get_at(good, entry_offset(good, Id)); }}; + auto const section{[&good](std::uint32_t const Id) { return get_at(good, entry_offset(good, Id)); }}; std::vector const breakages{ {"cut short", [](std::vector &File) { File.resize(File.size() / 2); }, "cut short"}, - {"no magic", [](std::vector &File) { File[0] = std::byte{'X'}; }, "isn't an E4D"}, + {"no magic", [](std::vector &File) { File[0] = std::byte{'X'}; }, "isn't an EU07M"}, {"a later major version", [](std::vector &File) { put_at(File, 4, std::uint16_t{2}); }, "version 2"}, {"the content changed", [](std::vector &File) { File.back() ^= std::byte{0xFF}; }, "hash"}, {"a section past the end", [&good](std::vector &File) { - auto const offset{entry_offset(good, e4d::section::nodes)}; - auto entry{get_at(File, offset)}; + auto const offset{entry_offset(good, eu07m::section::nodes)}; + auto entry{get_at(File, offset)}; entry.offset = File.size(); put_at(File, offset, entry); rehash(File); @@ -259,61 +259,61 @@ TEST_CASE("e4d: broken files are refused with a reason, and leave the model empt "outside the file"}, {"a section twice", [&good](std::vector &File) { - put_at(File, entry_offset(good, e4d::section::bounds), get_at(File, entry_offset(good, e4d::section::nodes))); + put_at(File, entry_offset(good, eu07m::section::bounds), get_at(File, entry_offset(good, eu07m::section::nodes))); rehash(File); }, "twice"}, {"an unknown required section", [&good](std::vector &File) { - auto const offset{entry_offset(good, e4d::fourcc("ZZZZ"))}; - auto entry{get_at(File, offset)}; - entry.flags |= e4d::section_flags::required; + auto const offset{entry_offset(good, eu07m::fourcc("ZZZZ"))}; + auto entry{get_at(File, offset)}; + entry.flags |= eu07m::section_flags::required; put_at(File, offset, entry); rehash(File); }, "doesn't know"}, {"an index past the vertices", [§ion](std::vector &File) { - put_at(File, section(e4d::section::indices16).offset, std::uint16_t{9}); + put_at(File, section(eu07m::section::indices16).offset, std::uint16_t{9}); rehash(File); }, "past its 4 vertices"}, {"a parent after its child", [§ion](std::vector &File) { - put_at(File, section(e4d::section::nodes).offset + sizeof(e4d::table_header) + offsetof(e4d::node_record, parent), std::int32_t{3}); + put_at(File, section(eu07m::section::nodes).offset + sizeof(eu07m::table_header) + offsetof(eu07m::node_record, parent), std::int32_t{3}); rehash(File); }, "isn't before it"}, {"a joint the skin doesn't have", [§ion](std::vector &File) { - put_at(File, section(e4d::section::skin_weights).offset + 4 * sizeof(e4d::skin_weights), std::uint8_t{7}); + put_at(File, section(eu07m::section::skin_weights).offset + 4 * sizeof(eu07m::skin_weights), std::uint8_t{7}); rehash(File); }, "joint its skin doesn't have"}, {"a light slot naming a node which isn't there", [§ion](std::vector &File) { // the slot is the last but one component; its node list follows the fixed part - auto const table{section(e4d::section::components).offset + sizeof(e4d::table_header)}; - auto const record{get_at(File, table + 3 * sizeof(e4d::component_record))}; - REQUIRE(record.type == e4d::component::light_slot); - put_at(File, section(e4d::section::component_data).offset + record.data_offset + sizeof(e4d::payload::light_slot), std::uint32_t{99}); + auto const table{section(eu07m::section::components).offset + sizeof(eu07m::table_header)}; + auto const record{get_at(File, table + 3 * sizeof(eu07m::component_record))}; + REQUIRE(record.type == eu07m::component::light_slot); + put_at(File, section(eu07m::section::component_data).offset + record.data_offset + sizeof(eu07m::payload::light_slot), std::uint32_t{99}); rehash(File); }, "don't hold together"}, {"a header that claims fewer bytes than itself", - [](std::vector &File) { put_at(File, offsetof(e4d::file_header, file_size), std::uint64_t{32}); }, + [](std::vector &File) { put_at(File, offsetof(eu07m::file_header, file_size), std::uint64_t{32}); }, "less than its header"}, {"a node in the subtree of another node than its parent", [§ion](std::vector &File) { // the body (node 1) reaches over the hose (node 2), whose parent is the root - put_at(File, section(e4d::section::nodes).offset + sizeof(e4d::table_header) + sizeof(e4d::node_record) + offsetof(e4d::node_record, subtree_end), + put_at(File, section(eu07m::section::nodes).offset + sizeof(eu07m::table_header) + sizeof(eu07m::node_record) + offsetof(eu07m::node_record, subtree_end), std::uint32_t{5}); rehash(File); }, "lies in the subtree of node 1"}, {"a record too short for its table", [§ion](std::vector &File) { - put_at(File, section(e4d::section::primitives).offset + 4, std::uint32_t{20}); + put_at(File, section(eu07m::section::primitives).offset + 4, std::uint32_t{20}); rehash(File); }, "records of 20 bytes"}, @@ -333,7 +333,7 @@ TEST_CASE("e4d: broken files are refused with a reason, and leave the model empt namespace { // the sample with one more primitive: two quads of two nodes merged into one draw, the second a lamp of light slot 3 -e4d::model merged_model() { +eu07m::model merged_model() { auto model{sample_model()}; auto const first{static_cast(model.positions.size())}; for (std::uint8_t part = 0; part < 2; ++part) { @@ -345,12 +345,12 @@ e4d::model merged_model() { } model.bindings.resize(model.positions.size()); for (std::uint32_t idx = first + 4; idx < first + 8; ++idx) - model.bindings[idx] = {1, 3, e4d::slot_role::lit, 0}; + model.bindings[idx] = {1, 3, eu07m::slot_role::lit, 0}; for (std::uint16_t part = 0; part < 2; ++part) { for (std::uint16_t const corner : {0, 1, 2, 0, 2, 3}) model.indices16.push_back(static_cast(part * 4 + corner)); } - e4d::primitive_record merged; + eu07m::primitive_record merged; merged.first_index = 6; // past the quad of the sample; its hose has no indices merged.index_count = 12; merged.base_vertex = first; @@ -358,8 +358,8 @@ e4d::model merged_model() { merged.material = 0; merged.node = 0; merged.skin = 1; - merged.flags = static_cast(e4d::topology::triangles) | e4d::primitive_flags::indexed | e4d::primitive_flags::opaque | - e4d::primitive_flags::rigid_joints | e4d::primitive_flags::light_slots; + merged.flags = static_cast(eu07m::topology::triangles) | eu07m::primitive_flags::indexed | eu07m::primitive_flags::opaque | + eu07m::primitive_flags::rigid_joints | eu07m::primitive_flags::light_slots; model.primitives.push_back(merged); model.meshes.push_back({2, 1, 1, 0}); model.nodes[0].mesh = 2; @@ -371,47 +371,47 @@ e4d::model merged_model() { hose.node = 2; model.skin_joints.push_back(body); model.skin_joints.push_back(hose); - e4d::compute_bounds(model); + eu07m::compute_bounds(model); return model; } } // namespace -TEST_CASE("e4d: parts of several nodes and light slots merged into one primitive") +TEST_CASE("eu07m: parts of several nodes and light slots merged into one primitive") { auto const original{merged_model()}; - auto const faults{e4d::validate(original)}; + auto const faults{eu07m::validate(original)}; REQUIRE_MESSAGE(faults.empty(), (faults.empty() ? std::string{} : faults.front())); REQUIRE(original.indices16.size() == 18); - auto const file{e4d::write(original, {false, 0})}; + auto const file{eu07m::write(original, {false, 0})}; // the merged primitive draws wrong without VBND, so a reader which doesn't know it refuses the file - auto const bindings{get_at(file, entry_offset(file, e4d::section::bindings))}; - CHECK((bindings.flags & e4d::section_flags::required) != 0); - CHECK(bindings.offset % e4d::gpu_alignment == 0); - e4d::model loaded; + auto const bindings{get_at(file, entry_offset(file, eu07m::section::bindings))}; + CHECK((bindings.flags & eu07m::section_flags::required) != 0); + CHECK(bindings.offset % eu07m::gpu_alignment == 0); + eu07m::model loaded; auto const result{read_file(file, loaded)}; REQUIRE_MESSAGE(result.ok, result.error); REQUIRE(loaded.bindings.size() == original.bindings.size()); - CHECK(std::memcmp(loaded.bindings.data(), original.bindings.data(), original.bindings.size() * sizeof(e4d::vertex_binding)) == 0); - CHECK(e4d::dump(loaded) == e4d::dump(original)); + CHECK(std::memcmp(loaded.bindings.data(), original.bindings.data(), original.bindings.size() * sizeof(eu07m::vertex_binding)) == 0); + CHECK(eu07m::dump(loaded) == eu07m::dump(original)); struct breakage { std::string_view what; - std::function apply; + std::function apply; std::string_view reason; }; std::vector const breakages{ - {"a joint the skin doesn't have", [](e4d::model &Model) { Model.bindings.back().joint = 2; }, "joint its skin doesn't have"}, - {"an unknown role", [](e4d::model &Model) { Model.bindings.back().role = static_cast(3); }, "unknown light slot role"}, - {"no skin", [](e4d::model &Model) { Model.primitives.back().skin = -1; }, "no skin naming them"}, - {"no VBND", [](e4d::model &Model) { Model.bindings.clear(); }, "no VBND"}, - {"VBND of other length", [](e4d::model &Model) { Model.bindings.pop_back(); }, "VBND has"}, + {"a joint the skin doesn't have", [](eu07m::model &Model) { Model.bindings.back().joint = 2; }, "joint its skin doesn't have"}, + {"an unknown role", [](eu07m::model &Model) { Model.bindings.back().role = static_cast(3); }, "unknown light slot role"}, + {"no skin", [](eu07m::model &Model) { Model.primitives.back().skin = -1; }, "no skin naming them"}, + {"no VBND", [](eu07m::model &Model) { Model.bindings.clear(); }, "no VBND"}, + {"VBND of other length", [](eu07m::model &Model) { Model.bindings.pop_back(); }, "VBND has"}, }; for (auto const &breakage : breakages) { CAPTURE(breakage.what); auto model{original}; breakage.apply(model); - auto const problems{e4d::validate(model)}; + auto const problems{eu07m::validate(model)}; REQUIRE_FALSE(problems.empty()); CHECK(std::ranges::any_of(problems, [&breakage](std::string const &Problem) { return Problem.find(breakage.reason) != std::string::npos; })); } @@ -420,7 +420,7 @@ TEST_CASE("e4d: parts of several nodes and light slots merged into one primitive namespace { // the sample with a grid of 64 x 64 vertices on the body: streams big enough for the codecs -e4d::model grid_model() { +eu07m::model grid_model() { auto model{sample_model()}; auto const first{static_cast(model.positions.size())}; constexpr std::uint32_t side{64}; @@ -429,14 +429,14 @@ e4d::model grid_model() { auto const x{static_cast(column) * 0.1f}; auto const z{static_cast(row) * 0.1f}; model.positions.push_back({x, std::sin(x) * std::cos(z), z}); - e4d::attributes attribute; - attribute.qtangent = e4d::encode_qtangent({glm::normalize(glm::vec3{std::sin(x), 1.f, std::cos(z)}), {1.f, 0.f, 0.f}, 1.f}); + eu07m::attributes attribute; + attribute.qtangent = eu07m::encode_qtangent({glm::normalize(glm::vec3{std::sin(x), 1.f, std::cos(z)}), {1.f, 0.f, 0.f}, 1.f}); attribute.uv = {x, z}; model.vertex_attributes.push_back(attribute); model.weights.push_back({}); } } - e4d::primitive_record grid; + eu07m::primitive_record grid; grid.first_index = static_cast(model.indices16.size()); for (std::uint32_t row = 0; row + 1 < side; ++row) { for (std::uint32_t column = 0; column + 1 < side; ++column) { @@ -451,114 +451,114 @@ e4d::model grid_model() { grid.vertex_count = side * side; grid.material = 0; grid.node = 0; - grid.flags = static_cast(e4d::topology::triangles) | e4d::primitive_flags::indexed | e4d::primitive_flags::opaque; + grid.flags = static_cast(eu07m::topology::triangles) | eu07m::primitive_flags::indexed | eu07m::primitive_flags::opaque; model.primitives.push_back(grid); model.meshes.push_back({2, 1, -1, 0}); model.nodes[0].mesh = 2; - e4d::compute_bounds(model); + eu07m::compute_bounds(model); return model; } } // namespace -TEST_CASE("e4d: the streams in the codecs of meshoptimizer, with and without zstd") +TEST_CASE("eu07m: the streams in the codecs of meshoptimizer, with and without zstd") { auto const original{grid_model()}; - REQUIRE(e4d::validate(original).empty()); + REQUIRE(eu07m::validate(original).empty()); for (auto const compress : {false, true}) { for (auto const codec : {false, true}) { CAPTURE(compress); CAPTURE(codec); - auto const file{e4d::write(original, {compress, 9, codec})}; - auto const positions{get_at(file, entry_offset(file, e4d::section::positions))}; - auto const indices{get_at(file, entry_offset(file, e4d::section::indices16))}; - CHECK(((positions.flags & e4d::section_flags::meshopt) != 0) == codec); - CHECK(((indices.flags & e4d::section_flags::meshopt) != 0) == codec); - e4d::model loaded; + auto const file{eu07m::write(original, {compress, 9, codec})}; + auto const positions{get_at(file, entry_offset(file, eu07m::section::positions))}; + auto const indices{get_at(file, entry_offset(file, eu07m::section::indices16))}; + CHECK(((positions.flags & eu07m::section_flags::meshopt) != 0) == codec); + CHECK(((indices.flags & eu07m::section_flags::meshopt) != 0) == codec); + eu07m::model loaded; auto const result{read_file(file, loaded)}; REQUIRE_MESSAGE(result.ok, result.error); CHECK(loaded.positions == original.positions); CHECK(loaded.indices16 == original.indices16); - CHECK(std::memcmp(loaded.vertex_attributes.data(), original.vertex_attributes.data(), original.vertex_attributes.size() * sizeof(e4d::attributes)) == 0); - CHECK(e4d::dump(loaded) == e4d::dump(original)); + CHECK(std::memcmp(loaded.vertex_attributes.data(), original.vertex_attributes.data(), original.vertex_attributes.size() * sizeof(eu07m::attributes)) == 0); + CHECK(eu07m::dump(loaded) == eu07m::dump(original)); } } // zstd over the codec, for an archive { - auto const file{e4d::write(original, {true, 9, true, true})}; - auto const positions{get_at(file, entry_offset(file, e4d::section::positions))}; - CHECK((positions.flags & e4d::section_flags::meshopt) != 0); - e4d::model loaded; + auto const file{eu07m::write(original, {true, 9, true, true})}; + auto const positions{get_at(file, entry_offset(file, eu07m::section::positions))}; + CHECK((positions.flags & eu07m::section_flags::meshopt) != 0); + eu07m::model loaded; auto const result{read_file(file, loaded)}; REQUIRE_MESSAGE(result.ok, result.error); CHECK(loaded.positions == original.positions); - CHECK(e4d::dump(loaded) == e4d::dump(original)); + CHECK(eu07m::dump(loaded) == eu07m::dump(original)); } // the codec on a section which isn't a stream, and a stream whose encoded bytes don't decode - auto const good{e4d::write(original, {false, 0, true})}; + auto const good{eu07m::write(original, {false, 0, true})}; auto onnodes{good}; - auto const nodesoffset{entry_offset(onnodes, e4d::section::nodes)}; - auto nodes{get_at(onnodes, nodesoffset)}; - nodes.flags |= e4d::section_flags::meshopt; + auto const nodesoffset{entry_offset(onnodes, eu07m::section::nodes)}; + auto nodes{get_at(onnodes, nodesoffset)}; + nodes.flags |= eu07m::section_flags::meshopt; put_at(onnodes, nodesoffset, nodes); - e4d::model loaded; - auto const wrongsection{e4d::read(onnodes, loaded, {false, true})}; + eu07m::model loaded; + auto const wrongsection{eu07m::read(onnodes, loaded, {false, true})}; CHECK_FALSE(wrongsection.ok); CHECK(wrongsection.error.find("only the vertex and index streams") != std::string::npos); auto broken{good}; - auto const positions{get_at(broken, entry_offset(broken, e4d::section::positions))}; + auto const positions{get_at(broken, entry_offset(broken, eu07m::section::positions))}; // the stream cut in the middle by a stored size of half of it auto shortened{positions}; shortened.stored_size /= 2; - put_at(broken, entry_offset(broken, e4d::section::positions), shortened); - auto const cut{e4d::read(broken, loaded, {false, true})}; + put_at(broken, entry_offset(broken, eu07m::section::positions), shortened); + auto const cut{eu07m::read(broken, loaded, {false, true})}; CHECK_FALSE(cut.ok); CHECK(cut.error.find("doesn't decode") != std::string::npos); CHECK(loaded.nodes.empty()); } -TEST_CASE("e4d: a section the reader doesn't know is passed over unless the tools keep it") +TEST_CASE("eu07m: a section the reader doesn't know is passed over unless the tools keep it") { auto const file{sample_file()}; - e4d::model kept; - REQUIRE(e4d::read(file, kept, {true, true}).ok); + eu07m::model kept; + REQUIRE(eu07m::read(file, kept, {true, true}).ok); CHECK(kept.unknown.size() == 1); - e4d::model skipped; - auto const result{e4d::read(file, skipped, {true, false})}; + eu07m::model skipped; + auto const result{eu07m::read(file, skipped, {true, false})}; REQUIRE_MESSAGE(result.ok, result.error); CHECK(skipped.unknown.empty()); kept.unknown.clear(); - CHECK(e4d::dump(skipped) == e4d::dump(kept)); + CHECK(eu07m::dump(skipped) == eu07m::dump(kept)); } -TEST_CASE("e4d: an unknown section in the codec of the streams doesn't stop the reading, unless the model needs it") +TEST_CASE("eu07m: an unknown section in the codec of the streams doesn't stop the reading, unless the model needs it") { // a later version may put a new optional stream in the codec; this one passes it over, the tools too auto file{sample_file(false)}; - auto const offset{entry_offset(file, e4d::fourcc("ZZZZ"))}; - auto entry{get_at(file, offset)}; - entry.flags |= e4d::section_flags::meshopt; + auto const offset{entry_offset(file, eu07m::fourcc("ZZZZ"))}; + auto entry{get_at(file, offset)}; + entry.flags |= eu07m::section_flags::meshopt; put_at(file, offset, entry); rehash(file); - e4d::model loaded; - auto const result{e4d::read(file, loaded, {true, true})}; + eu07m::model loaded; + auto const result{eu07m::read(file, loaded, {true, true})}; REQUIRE_MESSAGE(result.ok, result.error); CHECK(loaded.unknown.empty()); // one the model needs is refused as unknown, not for its codec - entry.flags |= e4d::section_flags::required; + entry.flags |= eu07m::section_flags::required; put_at(file, offset, entry); rehash(file); - auto const required{e4d::read(file, loaded, {true, true})}; + auto const required{eu07m::read(file, loaded, {true, true})}; CHECK_FALSE(required.ok); CHECK(required.error.find("doesn't know") != std::string::npos); } -TEST_CASE("e4d: a file with random bytes changed is read or refused, never more") +TEST_CASE("eu07m: a file with random bytes changed is read or refused, never more") { // the sample, too small for the codecs, and the grid, in them for (auto const variant : {0, 1, 2}) { auto const compress{variant == 1}; - auto const good{variant < 2 ? sample_file(compress) : e4d::write(grid_model(), {true, 9, true})}; + auto const good{variant < 2 ? sample_file(compress) : eu07m::write(grid_model(), {true, 9, true})}; std::mt19937 random{static_cast(7 + variant * 4)}; // NOSONAR: seeded on purpose, the test changes the same bytes every run; nothing secret std::uniform_int_distribution position{0, good.size() - 1}; std::uniform_int_distribution value{0, 255}; @@ -568,17 +568,17 @@ TEST_CASE("e4d: a file with random bytes changed is read or refused, never more" for (int change = 0; change < changes; ++change) file[position(random)] = static_cast(value(random)); // without the hash, so the changes reach the sections - e4d::model model; - auto const result{e4d::read(file, model, {false, true})}; + eu07m::model model; + auto const result{eu07m::read(file, model, {false, true})}; if (result.ok) - CHECK(e4d::validate(model).empty()); + CHECK(eu07m::validate(model).empty()); else CHECK(model.nodes.empty()); } } } -TEST_CASE("e4d: the tangent frame survives its packing") +TEST_CASE("eu07m: the tangent frame survives its packing") { std::mt19937 random{3}; // NOSONAR: seeded on purpose, the test packs the same frames every run; nothing secret std::uniform_real_distribution coordinate{-1.f, 1.f}; @@ -590,58 +590,58 @@ TEST_CASE("e4d: the tangent frame survives its packing") normal = glm::normalize(normal); tangent = glm::normalize(tangent - normal * glm::dot(normal, tangent)); auto const handedness{attempt % 2 == 0 ? 1.f : -1.f}; - auto const frame{e4d::decode_qtangent(e4d::encode_qtangent({normal, tangent, handedness}))}; + auto const frame{eu07m::decode_qtangent(eu07m::encode_qtangent({normal, tangent, handedness}))}; CHECK(glm::dot(frame.normal, normal) > 0.99999f); CHECK(glm::dot(frame.tangent, tangent) > 0.99999f); CHECK(frame.handedness == handedness); } // the frames where w of the quaternion is near zero (a half turn) keep their handedness too for (auto const handedness : {1.f, -1.f}) { - auto const frame{e4d::decode_qtangent(e4d::encode_qtangent({{0.f, 0.f, -1.f}, {-1.f, 0.f, 0.f}, handedness}))}; + auto const frame{eu07m::decode_qtangent(eu07m::encode_qtangent({{0.f, 0.f, -1.f}, {-1.f, 0.f, 0.f}, handedness}))}; CHECK(frame.handedness == handedness); CHECK(glm::dot(frame.normal, glm::vec3{0.f, 0.f, -1.f}) > 0.9999f); } // a degenerate frame (no normal, a tangent along it) gets a valid one - auto const frame{e4d::decode_qtangent(e4d::encode_qtangent({{0.f, 0.f, 0.f}, {0.f, 0.f, 1.f}, 1.f}))}; + auto const frame{eu07m::decode_qtangent(eu07m::encode_qtangent({{0.f, 0.f, 0.f}, {0.f, 0.f, 1.f}, 1.f}))}; CHECK(std::abs(glm::dot(frame.normal, frame.tangent)) < 1e-3f); } -TEST_CASE("e4d: a transform becomes TRS, a sheared one stays a matrix") +TEST_CASE("eu07m: a transform becomes TRS, a sheared one stays a matrix") { - e4d::node_record node; + eu07m::node_record node; auto const trs{glm::translate(glm::mat4{1.f}, glm::vec3{1.f, -2.f, 3.f}) * glm::mat4_cast(glm::angleAxis(0.7f, glm::normalize(glm::vec3{1.f, 2.f, 3.f}))) * glm::scale(glm::mat4{1.f}, glm::vec3{2.f, 0.5f, 1.f})}; - CHECK(e4d::set_transform(node, trs)); + CHECK(eu07m::set_transform(node, trs)); CHECK(node.translation[1] == doctest::Approx(-2.f)); // a mirror is kept as a negative scale - CHECK(e4d::set_transform(node, glm::scale(glm::mat4{1.f}, glm::vec3{-1.f, 1.f, 1.f}))); + CHECK(eu07m::set_transform(node, glm::scale(glm::mat4{1.f}, glm::vec3{-1.f, 1.f, 1.f}))); CHECK(node.scale[0] == doctest::Approx(-1.f)); auto shear{glm::mat4{1.f}}; shear[1][0] = 0.5f; - CHECK_FALSE(e4d::set_transform(node, shear)); + CHECK_FALSE(eu07m::set_transform(node, shear)); // the transforms of the model follow the parents auto model{sample_model()}; - auto const transforms{e4d::model_transforms(model)}; + auto const transforms{eu07m::model_transforms(model)}; CHECK(transforms[1][3].x == doctest::Approx(1.f)); CHECK(transforms[3] == glm::mat4{1.f}); } -TEST_CASE("e4d: the nodes are found by name regardless of case") +TEST_CASE("eu07m: the nodes are found by name regardless of case") { auto const model{sample_model()}; - auto const found{e4d::find_nodes(model, "BODY")}; + auto const found{eu07m::find_nodes(model, "BODY")}; REQUIRE(found.size() == 1); CHECK(found.front() == 1); - CHECK(e4d::find_nodes(model, "hose_J1") == std::vector{4}); - CHECK(e4d::find_nodes(model, "nothing").empty()); + CHECK(eu07m::find_nodes(model, "hose_J1") == std::vector{4}); + CHECK(eu07m::find_nodes(model, "nothing").empty()); // without the index the same, by a pass over the nodes auto unindexed{model}; unindexed.name_index.clear(); - CHECK(e4d::find_nodes(unindexed, "Hose") == std::vector{2}); + CHECK(eu07m::find_nodes(unindexed, "Hose") == std::vector{2}); } -TEST_CASE("e4d: the bounds hold the geometry of each node and of the whole model") +TEST_CASE("eu07m: the bounds hold the geometry of each node and of the whole model") { auto const model{sample_model()}; REQUIRE(model.bounds.size() == model.nodes.size() + 1); diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index ea8b879af..158ef4877 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -1001,10 +1001,10 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& if (token == "modelformat") { - // e4d: a model with an .e4d file beside its .e3d / .t3d is loaded from it; legacy: the .e4d files are left alone + // ng3d: a model with an .ng3d file beside its .e3d / .t3d is loaded from it; legacy: the .ng3d files are left alone std::string value; ParseOne(Parser, value, 1); - modelformat_e4d = value == "e4d"; + modelformat_eu07m = value == "ng3d"; return true; } @@ -2690,7 +2690,7 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "hiddenevents", iHiddenEvents ); export_as_text( Output, "pause", ( iPause & 1 ) != 0 ); export_as_text(Output, "priorityLoadText3D", priorityLoadText3D); - export_as_text(Output, "modelformat", std::string{modelformat_e4d ? "e4d" : "legacy"}); + export_as_text(Output, "modelformat", std::string{modelformat_eu07m ? "ng3d" : "legacy"}); export_as_text( Output, "lang", asLang ); export_as_text( Output, "python.updatetime", PythonScreenUpdateRate ); Output diff --git a/utilities/Globals.h b/utilities/Globals.h index 29b521b99..e21731062 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -121,7 +121,7 @@ struct global_settings { int file_binary_terrain_skipped{0}; // number of terrain includes left out by the parser during the current scenery load // logs bool priorityLoadText3D{false}; // ladowanie T3D priorytetowo - bool modelformat_e4d{false}; // modelformat e4d: models are loaded from their .e4d files where there are some + bool modelformat_eu07m{false}; // modelformat ng3d: models are loaded from their .ng3d files where there are some int iWriteLogEnabled{ 3 }; // maska bitowa: 1-zapis do pliku, 2-okienko, 4-nazwy torów bool MultipleLogs{ false }; bool crashdump_full{ false }; // crash dump with the whole memory of the process instead of the small one