GPU data
Texture uploads
A PNG on disk is a few megabytes. In video memory the same texture is a chain of mip levels, in a tiled order only the GPU knows. This page follows a texture through the four steps that get it there: decode, make the mips, reorder the texels, place them in memory. It compares the two ways to do the copy (a staging buffer, or host image copy), the places a program can make the mips, and how many textures share memory. The last part shows how RASM does it.
In short
- Four steps: decode the file, make the mips, reorder the texels into the GPU's tiling, put them in video memory. Only the last two need the GPU or its driver.
- Staging: the CPU writes rows into a buffer, and a GPU copy command tiles them into the image. It works everywhere.
- Host image copy (Vulkan 1.4): the driver tiles on the CPU, with no command buffer. It is good only where the image can live in the same memory as any other texture, and keeps the GPU's best layout. Ask the device both.
- Mips can come from the file, a CPU worker, GPU blits or a GPU compute pass. Filter color in linear light, weight it by alpha, and make normals unit length again.
- Thousands of textures should share a few large memory blocks (sub-allocation): a separate allocation per texture is slow to make and slow to free.
- A model's textures are many megabytes: copy them a few per frame, not all in one frame.
1Four steps from file to GPU
Follow one 2048 × 2048 color texture. Two steps are plain CPU work on bytes; two need to know the GPU.
2Two ways to reorder and place
The CPU cannot write the tiled order itself: it is the vendor's secret. Two paths hand the rows to someone who knows it.
Staging copy
Works on every GPU and every format. Costs a command buffer, barriers, a fence before the buffer is reused, and a little GPU copy time.
Host image copy
Vulkan 1.4 (VK_EXT_host_image_copy before). No staging memory, no commands. The CPU must be able to write the image's memory, which is the catch (next section).
3Where a host-copied image may live
The CPU writes a host-copied image directly. So the driver may allow such an image only in memory the CPU can reach. Each image asks for a set of memory types (a bit mask). Compare the set of an image filled by a copy with the set of the same image made for host copy. This is a real discrete GPU with resizable BAR:
vkGetDeviceImageMemoryRequirements with and without the host-transfer usage. On lavapipe there is one memory type, and both sets are that type.So a program should ask the device, per format, before it picks host copy:
- Featurethe device has host image copy
- Formatit lists host image transfer
- Best layoutthe GPU reads it as fast as any image
- Copy layoutthe shader-read layout is allowed
- Memorya device-local type both sets share
If any answer is no, the format uses staging. A device without the feature then still starts and draws: it only loses a shortcut. In Vulkan the checks are the hostImageCopy feature, the format's host-image-transfer feature bit, optimalDeviceAccess in VkHostImageCopyDevicePerformanceQuery, pCopyDstLayouts, and the memory type bits.
4Where to make the mips
A full mip chain adds a third to the texture. Each level is the one above, half the size, filtered. Four places can make it:
In the file
KTX2 and DDS store the levels, already block-compressed. Best quality and no load-time work.
Needs an offline tool step.
A CPU worker
Same code on every GPU and API. Any filter: linear light, alpha weighting, renormalized normals.
About 10 ms of CPU per 2048² texture; a third more bytes to copy.
GPU blits
A few commands, almost no GPU time. The filter is a fixed box; colors are not weighted by alpha, and normals are not renormalized.
Vulkan and Metal have blits; D3D12 and WebGPU do not.
GPU compute
Fast and any filter. The image needs storage usage, and an sRGB image a second, UNORM view.
Storage usage can turn off the GPU's texture compression (AFBC, DCC): slower reads for the texture's life.
Filter what the numbers mean
A mip is an average. What to average depends on the texture:
Color: linear light
Decode sRGB to light, average, encode again. Averaging the stored numbers darkens every edge.
Cut-outs: weight by alpha
A transparent texel's color is never seen, so it must not count. Without the weight, leaves get dark rims far away.
Normal maps: renormalize
Average the directions, then make each unit length again, so every level stores a direction. A two-channel map (z rebuilt from x and y) needs it most.
5Many textures, few allocations
A scene has hundreds of textures; a streaming map has thousands over its life. Giving each its own device allocation is simple, but each allocation is an OS call, drivers limit how many exist, and freeing one can take milliseconds.
One allocation per texture
Sub-allocated
Keep a dedicated allocation for the few large render targets that a driver asks to have one. The block size also changes what "memory in use" means: the OS counts whole blocks, so count the bytes of the textures inside them too.
6Pitfalls
- Far textures look too dark, edges have dark lines
- The mips averaged sRGB numbers, not light. Filter sRGB textures in linear light.
- Leaves and fences get dark or bright rims in the distance
- The mips averaged the hidden color of transparent texels. Weight color by alpha.
- Bumps look flat or bright far away
- Averaged normals are shorter than 1; a two-channel map rebuilds a wrong z from them. Renormalize each mip.
- Loading a level freezes one frame for 200 ms
- Mips are made on the main thread, or all of a model's textures are copied in one frame. Make mips on a worker, and copy a few textures per frame.
- Frames drop while textures load, the CPU is idle
- The GPU stalls on host-copied images in special memory. Use host copy only where the image can use the same memory types as a copied one.
- A GPU without host image copy cannot start the program
- The feature was required. Make it optional: the staging path serves every device.
- Destroying a big model makes one long frame
- Each texture had its own allocation, and each free is an OS call. Sub-allocate.
7In RASM
The worker decodes and makes every level; the main thread only creates the texture and copies the levels, in parts of 4 MiB under a budget per frame; the device copies through the staging ring, on the transfer queue where there is one, unless host copy is safe for the format. The texture counts as loaded once its copies are done (transfer queues).
finishMeshLoad and wait in pendingTextures with their levels; loadTexture's wait for their worker. finishLoads fills both kinds after the meshes, under the same budget.Where RASM follows the page, and where it differs
| Part | This page | RASM |
|---|---|---|
| Decode | a worker | decodeTexture (stb_image) for loadTexture; runImageWork for a glTF's images, one job per image, so a model's images decode and get their mips on several workers at once (job systems). Every job runs on the engine's WorkerPool. |
| Mips | file, CPU worker, GPU blits or compute | KTX2: from the file (or made on the worker for a Basis file without them). PNG and JPEG: buildTextureLevels on the worker, with stb_image_resize2's default filter (Mitchell), each level from the one above. GPU mip generation is not used: it would need storage usage on every texture, and blits have no alpha weighting. |
| Filtering | linear light, alpha, renormalize | R8G8B8A8_SRGB: linear light, alpha-weighted. R8G8B8A8_UNORM: the stored numbers. A glTF normal texture (KtxSlot::NORMAL): renormalized; loadTexture does not know the slot, so it does not renormalize. |
| Copy | staging or host copy | Host copy only for a format where VulkanDevice::queryFormatSupport found the feature, host transfer, optimalDeviceAccess, SHADER_READ_ONLY_OPTIMAL among the copy layouts, and a device-local type in both sets (getHostCopyMemoryTypes); the image is then made with only those types. Every other format, and every format with EngineConfig::hostImageCopy false, goes through the staging ring. The log says which: Host image copy: off on the RTX 3060, and on for 13 formats on lavapipe. |
| Per frame | a few textures per frame | Each texture is its own entry in pendingTextures, filled after the meshes inside LOAD_BUDGET, in parts of 4 MiB (RenderContext::fillTexturePart, TextureFillProgress), at least one part per frame, the textures begun first; a part stops at a full staging ring instead of waiting. The longest frame while the PNG Flight Helmet loads is 5 ms (9 ms with a texture in one go). A glTF texture whose fill fails is taken out of its materials, which then read their defaults. A texture is loaded once its last part's copies are done; isLoaded(mesh) is true once its glTF's textures are (transfer queues). |
| Memory | sub-allocate, dedicated for big targets | Sampled textures are sub-allocated by VMA, with no host-access flags. Attachments and storage textures keep a dedicated allocation. VRAMStats::vramAllocated counts the bytes of the allocations, vramUsage the whole blocks. |
| App-filled textures | — | RenderContext::fillTexture(texture, data) with one RGBA8 level still makes the mips in the caller's thread (buildMipChain), as the application asked for. |
Measured
examples/10_ktx2_textures --measure --model <file>, Release, headless, RTX 3060, the median of three runs. "Longest frame" is the longest frame while the model loads.
Each image of a model is a job of its own, so its decode and its mips run on every free worker at once: the whole PNG helmet loads in 191 ms and Sponza in 200 ms (23 workers; job systems).
Where it lives in code
| What | Where |
|---|---|
| Mips | buildTextureLevels, buildMipChain, getFullMipCount in src/rhi/mipChain.cpp |
| Worker: textures | decodeTexture, AssetLoader::loadTexture, finishTextureLoad in src/assets/texture.cpp |
| Worker: glTF images | planImageLevels, runImageWork, getImageLevelsKey in src/assets/meshImport.cpp; GLTFRaw::imageLevels in include/rasm/mesh.h |
| Queued fills | AssetLoader::Impl::loadMaterial in src/assets/material.cpp; PendingTextureLoad in src/assets/assetLoaderImpl.h; finishLoads in src/assets/assetLoader.cpp |
| Host copy or staging | VulkanDevice::queryFormatSupport, createTexture, fillTexture in src/rhi/vulkan/vulkanDevice.cpp; getHostCopyMemoryTypes in src/rhi/vulkan/vulkanUtils.cpp; UploadManager::uploadTexture in src/rhi/uploadManager.cpp |
| Measure | examples/10_ktx2_textures (--measure, --staging, --model) |
| Tests | tests/textureUploadTests.cpp |
- No image asks VMA for host access: a host-copied image uses only the memory types
queryFormatSupportfound. - The main thread never makes mips for a load. A worker hands over every level.
- Every texture fill of a load goes through
pendingTextures, so the budget sees it. - The worker's level count is the texture's mip count (
getFullMipCount), orfillTexturerefuses the levels.
Further reading
- Khronos, the Vulkan specification, "Host Image Copies" (
vkCopyMemoryToImage,VkHostImageCopyDevicePerformanceQuery, identicalMemoryTypeRequirements). - AMD GPUOpen, "Vulkan Memory Allocator" documentation: choosing memory types, dedicated allocations.
- GPU memory and uploads, Mipmaps and texture sampling, Color spaces, Streaming assets in the background, Texture compression.