diff --git a/src/assets/TextureFile.cpp b/src/assets/TextureFile.cpp index 09b6faa..58f162b 100644 --- a/src/assets/TextureFile.cpp +++ b/src/assets/TextureFile.cpp @@ -57,7 +57,7 @@ double TextureData::metresPerTexel() const { return 0.5 * (perX + perY); } -TextureData loadTextureFile(const std::string& path) { +TextureData loadTextureFileHeader(const std::string& path) { std::ifstream file(path, std::ios::binary); if (!file) { throw std::runtime_error("Texture : fichier introuvable ou illisible : " + path); @@ -148,13 +148,6 @@ TextureData loadTextureFile(const std::string& path) { ". Fichier tronque ou en-tete incoherent."); } - file.seekg(static_cast(kHeaderSize), std::ios::beg); - texture.pixels.resize(static_cast(total)); - if (!file.read(reinterpret_cast(texture.pixels.data()), - static_cast(total))) { - throw std::runtime_error("Texture : lecture interrompue dans " + path + "."); - } - logInfo("Texture : " + texture.label + " " + std::to_string(texture.width) + "x" + std::to_string(texture.height) + ", " + std::to_string(mipLevels) + " mipmaps, " + @@ -164,4 +157,33 @@ TextureData loadTextureFile(const std::string& path) { return texture; } +void readTexturePayload(std::istream& file, uint64_t offset, uint64_t bytes, + void* destination) { + file.seekg(static_cast(kHeaderSize + offset), std::ios::beg); + if (!file.read(static_cast(destination), static_cast(bytes))) { + throw std::runtime_error("Texture : lecture interrompue (" + std::to_string(bytes) + + " octets a l'offset " + std::to_string(offset) + ")."); + } +} + +void readTexturePayload(const std::string& path, const TextureData& header, + void* destination) { + std::ifstream file(path, std::ios::binary); + if (!file) { + throw std::runtime_error("Texture : fichier introuvable ou illisible : " + path); + } + try { + readTexturePayload(file, 0, header.payloadSize(), destination); + } catch (const std::exception&) { + throw std::runtime_error("Texture : lecture interrompue dans " + path + "."); + } +} + +TextureData loadTextureFile(const std::string& path) { + TextureData texture = loadTextureFileHeader(path); + texture.pixels.resize(static_cast(texture.payloadSize())); + readTexturePayload(path, texture, texture.pixels.data()); + return texture; +} + } // namespace vercora diff --git a/src/assets/TextureFile.hpp b/src/assets/TextureFile.hpp index 56cd911..3f0fac7 100644 --- a/src/assets/TextureFile.hpp +++ b/src/assets/TextureFile.hpp @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include @@ -57,6 +58,12 @@ struct TextureData { // journal de demarrage : c'est le chiffre qui dit si la texture est a la // hauteur du niveau de detail du terrain. double metresPerTexel() const; + + // PHASE 30. Octets de TOUTE la chaine de mipmaps, deduits des niveaux : + // c'est la taille de `pixels` une fois charge, et celle du staging. + uint64_t payloadSize() const { + return mips.empty() ? 0 : mips.back().offset + mips.back().size; + } }; // Charge un .vcto. Lance std::runtime_error avec un message exploitable si le @@ -65,6 +72,20 @@ struct TextureData { // annonces, ...). TextureData loadTextureFile(const std::string& path); +// PHASE 30. Les deux moities de loadTextureFile, pour ne jamais tenir la +// charge utile en RAM : l'en-tete d'abord (memes controles, taille du fichier +// comprise, `pixels` reste VIDE), puis la lecture des `payloadSize()` octets +// directement la ou l'appelant les veut - en pratique le staging mappe de la +// texture GPU (Renderer::setTerrainTextureFromFile). Sur l'orthophoto de la +// zone, c'est une copie de 42 Mo de moins au chargement, et autant de pic RAM. +TextureData loadTextureFileHeader(const std::string& path); +void readTexturePayload(const std::string& path, const TextureData& header, void* destination); + +// Variante par TRANCHE, sur un fichier deja ouvert : `bytes` octets de la +// charge utile a partir de son octet `offset`. Sert au televersement par +// bandes de Texture (staging de 4 Mo au plus). +void readTexturePayload(std::istream& file, uint64_t offset, uint64_t bytes, void* destination); + // Nombre d'octets d'un niveau de mipmap pour un format donne. Expose parce que // c'est la seule formule qui lie les deux formats a leur taille, et que le // chargeur ET les tests s'en servent. diff --git a/src/main.cpp b/src/main.cpp index 300a926..dfbc034 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1351,9 +1351,12 @@ int main(int argc, char** argv) { " -i data/ortho -o " + orthoPath); } else { try { - const TextureData ortho = loadTextureFile(orthoPath); + // PHASE 30 : l'en-tete seul d'abord (controle d'emprise), puis + // les 42 Mo de texels lus directement dans le staging de la + // texture - jamais tenus en RAM a cote. + const TextureData ortho = loadTextureFileHeader(orthoPath); if (orthoMatchesTerrain(ortho, *heightmap)) { - renderer.setTerrainTexture(ortho); + renderer.setTerrainTextureFromFile(ortho, orthoPath); renderer.setOrthoMix(1.0f); groundDetailPattern = ortho.metresPerTexel(); logInfo("Orthophoto : " + diff --git a/src/renderer/Renderer.cpp b/src/renderer/Renderer.cpp index ce7a9c4..dd1a4ac 100644 --- a/src/renderer/Renderer.cpp +++ b/src/renderer/Renderer.cpp @@ -1,6 +1,7 @@ #include "renderer/Renderer.hpp" #include "assets/DetailNoise.hpp" +#include "assets/TextureFile.hpp" #include "core/Camera.hpp" #include "core/Logger.hpp" @@ -20,6 +21,7 @@ #include #include #include +#include #include namespace vercora { @@ -609,6 +611,26 @@ void Renderer::setTerrainTexture(const TextureData& data) { " Mo sur le GPU."); } +void Renderer::setTerrainTextureFromFile(const TextureData& header, const std::string& path) { + waitIdle(); + + std::ifstream file(path, std::ios::binary); + if (!file) { + throw std::runtime_error("Texture : fichier introuvable ou illisible : " + path); + } + terrainTexture_ = std::make_unique( + context_, commandPool_, context_.graphicsQueue(), header, + [&file](void* destination, uint64_t offset, uint64_t bytes) { + readTexturePayload(file, offset, bytes, destination); + }); + writeTextureDescriptors(); + + logInfo("Orthophoto reliee au terrain : " + std::to_string(header.width) + "x" + + std::to_string(header.height) + ", " + + std::to_string(terrainTexture_->deviceSize() / (1024 * 1024)) + + " Mo sur le GPU, lue par tranches directement dans le staging."); +} + void Renderer::setOrthoMix(float mix) { options_.orthoMix = std::clamp(mix, 0.0f, 1.0f); } diff --git a/src/renderer/Renderer.hpp b/src/renderer/Renderer.hpp index 4e65c54..799691f 100644 --- a/src/renderer/Renderer.hpp +++ b/src/renderer/Renderer.hpp @@ -163,6 +163,12 @@ public: // coloration procedurale est visible. void setTerrainTexture(const TextureData& data); + // PHASE 30. Meme chose, mais les texels sont lus dans `path` DIRECTEMENT + // vers le staging de la texture : `header` vient de loadTextureFileHeader + // et ne porte aucun texel. Evite de tenir l'orthophoto (42 Mo) en RAM en + // plus du staging et de l'image GPU pendant le chargement. + void setTerrainTextureFromFile(const TextureData& header, const std::string& path); + // Bascule coloration procedurale <-> orthophoto (voir RenderOptions). // Sans effet visible si aucune texture n'a ete chargee. void setOrthoMix(float mix); diff --git a/src/renderer/Texture.cpp b/src/renderer/Texture.cpp index 6acf046..700d9a7 100644 --- a/src/renderer/Texture.cpp +++ b/src/renderer/Texture.cpp @@ -72,8 +72,19 @@ TextureData Texture::whitePixelData() { Texture::Texture(VulkanContext& context, VkCommandPool commandPool, VkQueue queue, const TextureData& data, bool repeat) + : Texture(context, commandPool, queue, data, + [&data](void* destination, uint64_t offset, uint64_t bytes) { + std::memcpy(destination, data.pixels.data() + offset, + static_cast(bytes)); + }, + repeat) { +} + +Texture::Texture(VulkanContext& context, VkCommandPool commandPool, VkQueue queue, + const TextureData& data, const PixelSource& source, bool repeat) : context_(context) { - if (data.pixels.empty() || data.mips.empty()) { + if (data.mips.empty() || data.payloadSize() == 0 || + (!data.pixels.empty() && data.pixels.size() < data.payloadSize())) { throw std::runtime_error("Texture : donnees vides."); } @@ -95,7 +106,7 @@ Texture::Texture(VulkanContext& context, VkCommandPool commandPool, VkQueue queu const uint32_t mipLevels = static_cast(data.mips.size()); createImage(data.width, data.height, mipLevels, format); - uploadAndTransition(commandPool, queue, data); + uploadAndTransition(commandPool, queue, data, source); createView(format, mipLevels); createSampler(mipLevels, repeat); } @@ -144,18 +155,59 @@ void Texture::createImage(uint32_t width, uint32_t height, uint32_t mipLevels, } void Texture::uploadAndTransition(VkCommandPool commandPool, VkQueue queue, - const TextureData& data) { + const TextureData& data, const PixelSource& source) { VkDevice device = context_.device(); - const VkDeviceSize total = static_cast(data.pixels.size()); + const VkDeviceSize total = static_cast(data.payloadSize()); + const uint32_t mipLevels = static_cast(data.mips.size()); - // Un seul buffer de staging pour toute la chaine : les niveaux sont deja - // contigus dans le fichier, donc les offsets de copie sont ceux du .vcto. - VulkanBuffer staging(context_, total, + // PHASE 30 : un staging de 4 Mo au plus, REUTILISE tranche apres tranche, + // au lieu d'un staging de la taille de toute la chaine. Pour l'orthophoto + // de la zone, c'etait 42 Mo de memoire GPU transitoire en plus de l'image + // elle-meme : le pic de memoire GPU de TOUTE la partie se situait la, au + // chargement. Les texels sont ecrits dans le staging par `source` - + // directement depuis le fichier pour l'orthophoto. + constexpr VkDeviceSize kStagingChunk = 4ull * 1024 * 1024; + const VkDeviceSize stagingSize = std::min(total, kStagingChunk); + VulkanBuffer staging(context_, stagingSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); - staging.writeToBuffer(data.pixels.data(), total); - staging.unmap(); + staging.map(); + auto* stagingBytes = static_cast(staging.mapped()); + + // --- Decoupe en BANDES de rangees de blocs ------------------------------ + // Une bande = des rangees completes d'un niveau, assez peu pour tenir dans + // le staging. BC1 se range par rangees de blocs de 4 texels de haut ; une + // bande qui n'atteint pas le bas d'un niveau a donc une hauteur multiple de + // 4, comme l'exige une copie vers un format compresse. + struct Band { + uint32_t level = 0; + uint32_t y = 0; + uint32_t height = 0; + uint64_t payloadOffset = 0; + uint64_t bytes = 0; + }; + std::vector bands; + const bool blocks = (data.format == TextureFormat::BC1); + const uint32_t texelsPerRow = blocks ? 4u : 1u; + for (uint32_t level = 0; level < mipLevels; ++level) { + const TextureMipLevel& mip = data.mips[level]; + const uint64_t rowBytes = blocks ? static_cast((mip.width + 3u) / 4u) * 8u + : static_cast(mip.width) * 4u; + const uint32_t rows = (mip.height + texelsPerRow - 1u) / texelsPerRow; + const uint32_t rowsPerBand = static_cast( + std::max(1u, stagingSize / rowBytes)); + for (uint32_t row = 0; row < rows; row += rowsPerBand) { + const uint32_t count = std::min(rowsPerBand, rows - row); + Band band; + band.level = level; + band.y = row * texelsPerRow; + band.height = std::min(count * texelsPerRow, mip.height - band.y); + band.payloadOffset = mip.offset + static_cast(row) * rowBytes; + band.bytes = static_cast(count) * rowBytes; + bands.push_back(band); + } + } VkCommandBufferAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; @@ -166,60 +218,74 @@ void Texture::uploadAndTransition(VkCommandPool commandPool, VkQueue queue, VkCommandBuffer commandBuffer = VK_NULL_HANDLE; vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer); - VkCommandBufferBeginInfo beginInfo{}; - beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; - beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; - vkBeginCommandBuffer(commandBuffer, &beginInfo); - - const uint32_t mipLevels = static_cast(data.mips.size()); - - transitionLayout(commandBuffer, image_, mipLevels, - VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - 0, VK_ACCESS_TRANSFER_WRITE_BIT, - VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); - + // --- Un lot de bandes par remplissage du staging ------------------------ std::vector regions; - regions.reserve(mipLevels); - for (uint32_t level = 0; level < mipLevels; ++level) { - const TextureMipLevel& mip = data.mips[level]; - VkBufferImageCopy region{}; - region.bufferOffset = mip.offset; - // 0 = "serre sur l'extent de l'image". Indispensable pour un format - // compresse, ou bufferRowLength se compterait en TEXELS et non en blocs : - // le calculer a la main serait une occasion d'erreur gratuite. - region.bufferRowLength = 0; - region.bufferImageHeight = 0; - region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - region.imageSubresource.mipLevel = level; - region.imageSubresource.baseArrayLayer = 0; - region.imageSubresource.layerCount = 1; - region.imageOffset = { 0, 0, 0 }; - region.imageExtent = { mip.width, mip.height, 1 }; - regions.push_back(region); + std::size_t next = 0; + bool first = true; + while (next < bands.size()) { + regions.clear(); + VkDeviceSize used = 0; + while (next < bands.size() && used + bands[next].bytes <= stagingSize) { + const Band& band = bands[next]; + source(stagingBytes + used, band.payloadOffset, band.bytes); + + VkBufferImageCopy region{}; + region.bufferOffset = used; + // 0 = "serre sur l'extent de la copie". Indispensable pour un format + // compresse, ou bufferRowLength se compterait en TEXELS et non en + // blocs : le calculer a la main serait une occasion d'erreur + // gratuite. + region.bufferRowLength = 0; + region.bufferImageHeight = 0; + region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + region.imageSubresource.mipLevel = band.level; + region.imageSubresource.baseArrayLayer = 0; + region.imageSubresource.layerCount = 1; + region.imageOffset = { 0, static_cast(band.y), 0 }; + region.imageExtent = { data.mips[band.level].width, band.height, 1 }; + regions.push_back(region); + + used += band.bytes; + ++next; + } + const bool last = (next == bands.size()); + + VkCommandBufferBeginInfo beginInfo{}; + beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; + beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + vkBeginCommandBuffer(commandBuffer, &beginInfo); + + if (first) { + transitionLayout(commandBuffer, image_, mipLevels, + VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + 0, VK_ACCESS_TRANSFER_WRITE_BIT, + VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); + } + vkCmdCopyBufferToImage(commandBuffer, staging.handle(), image_, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + static_cast(regions.size()), regions.data()); + if (last) { + transitionLayout(commandBuffer, image_, mipLevels, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, + VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT); + } + vkEndCommandBuffer(commandBuffer); + + VkSubmitInfo submitInfo{}; + submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + submitInfo.commandBufferCount = 1; + submitInfo.pCommandBuffers = &commandBuffer; + vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE); + // Transfert a l'initialisation : attendre est simple et sans + // consequence sur la boucle de rendu, qui n'a pas encore demarre - et + // c'est ce qui rend le staging reutilisable pour la tranche suivante. + vkQueueWaitIdle(queue); + first = false; } - vkCmdCopyBufferToImage(commandBuffer, staging.handle(), image_, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - static_cast(regions.size()), regions.data()); - - transitionLayout(commandBuffer, image_, mipLevels, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, - VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT); - - vkEndCommandBuffer(commandBuffer); - - VkSubmitInfo submitInfo{}; - submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; - submitInfo.commandBufferCount = 1; - submitInfo.pCommandBuffers = &commandBuffer; - vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE); - // Transfert unique a l'initialisation : attendre est simple et sans - // consequence sur la boucle de rendu, qui n'a pas encore demarre. - vkQueueWaitIdle(queue); - vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer); } diff --git a/src/renderer/Texture.hpp b/src/renderer/Texture.hpp index c609500..56a7e1d 100644 --- a/src/renderer/Texture.hpp +++ b/src/renderer/Texture.hpp @@ -9,6 +9,7 @@ #include #include +#include namespace vercora { @@ -44,6 +45,19 @@ public: // l'orthophoto - voir createSampler. Texture(VulkanContext& context, VkCommandPool commandPool, VkQueue queue, const TextureData& data, bool repeat = false); + + // PHASE 30. Source des texels : ecrit `bytes` octets de la charge utile, a + // partir de l'octet `offset` (0 = debut du niveau 0, meme rangement que + // TextureData::pixels), dans `destination` - le staging mappe. + using PixelSource = + std::function; + + // PHASE 30. Meme texture, mais les texels ne sont PAS dans `layout` (son + // `pixels` peut etre vide) : `source` les ecrit directement dans le + // staging, tranche par tranche. C'est ce qui permet de lire l'orthophoto + // depuis son fichier sans jamais la tenir en RAM. + Texture(VulkanContext& context, VkCommandPool commandPool, VkQueue queue, + const TextureData& layout, const PixelSource& source, bool repeat = false); ~Texture(); Texture(const Texture&) = delete; @@ -69,7 +83,7 @@ public: private: void createImage(uint32_t width, uint32_t height, uint32_t mipLevels, VkFormat format); void uploadAndTransition(VkCommandPool commandPool, VkQueue queue, - const TextureData& data); + const TextureData& data, const PixelSource& source); void createView(VkFormat format, uint32_t mipLevels); void createSampler(uint32_t mipLevels, bool repeat); diff --git a/tests/logic_tests.cpp b/tests/logic_tests.cpp index 0fcc4c2..55dfd49 100644 --- a/tests/logic_tests.cpp +++ b/tests/logic_tests.cpp @@ -3199,6 +3199,62 @@ void testTextureFile() { threw = true; } check(threw, "Refus : fichier .vcto absent"); + + // --- PHASE 30 : en-tete seul, puis charge utile lue a la demande -------- + // Le chargement de l'orthophoto ne tient plus la charge utile en RAM : il + // lit l'en-tete, puis des TRANCHES directement dans le staging. Les deux + // chemins doivent rendre exactement les memes octets que loadTextureFile. + { + const std::string path = + (std::filesystem::temp_directory_path() / "vercora_phase30_test.vcto").string(); + std::vector payload; + const uint32_t width = 8; + const uint32_t height = 4; + uint32_t levels = 0; + for (uint32_t w = width, h = height;; w = std::max(1u, w / 2), h = std::max(1u, h / 2)) { + for (uint32_t k = 0; k < w * h * 4; ++k) { + payload.push_back(static_cast((payload.size() * 37u + 11u) & 0xFFu)); + } + ++levels; + if (w == 1 && h == 1) { + break; + } + } + unsigned char header[128] = {}; + std::memcpy(header, "VCTO", 4); + const uint32_t fields[5] = { 1u, width, height, levels, 0u /* RGBA8 */ }; + std::memcpy(header + 4, fields, sizeof(fields)); + const double extent[4] = { 899000.0, 6435000.0, 904000.0, 6440000.0 }; + std::memcpy(header + 24, extent, sizeof(extent)); + const uint32_t epsg = 2154u; + std::memcpy(header + 56, &epsg, sizeof(epsg)); + { + std::ofstream out(path, std::ios::binary); + out.write(reinterpret_cast(header), sizeof(header)); + out.write(reinterpret_cast(payload.data()), + static_cast(payload.size())); + } + + const TextureData full = loadTextureFile(path); + const TextureData headerOnly = loadTextureFileHeader(path); + check(full.pixels == payload && full.payloadSize() == payload.size(), + "Phase 30 : loadTextureFile rend la charge utile complete"); + check(headerOnly.pixels.empty() && headerOnly.payloadSize() == payload.size() && + headerOnly.mips.size() == full.mips.size(), + "Phase 30 : l'en-tete seul decrit la meme chaine, sans aucun texel"); + + std::vector whole(payload.size()); + readTexturePayload(path, headerOnly, whole.data()); + std::vector banded(payload.size()); + std::ifstream in(path, std::ios::binary); + for (uint64_t offset = 0; offset < payload.size(); offset += 24) { + const uint64_t bytes = std::min(24, payload.size() - offset); + readTexturePayload(in, offset, bytes, banded.data() + offset); + } + check(whole == payload && banded == payload, + "Phase 30 : lecture directe et lecture par tranches = memes octets"); + std::filesystem::remove(path); + } } void testGrassMesh() {