GPU data
Streaming assets in the background
Reading a model or a texture from disk can take hundreds of milliseconds. A frame has about 16. So an engine loads assets on other threads, while it keeps drawing, and brings each one in when it is ready. This page explains how that works: workers, the hand-off to the main thread, a time budget per frame, what to show until the data arrives, caching, failures, and when to free memory. The last part shows how RASM does it.
In short
- A load call returns a handle at once. The object is in the loading state until its data is in.
- Worker threads read and decode the file. They work on their own memory and never touch the renderer's state.
- The main thread picks up finished results at one fixed point in the frame. Only it creates GPU objects and makes the asset visible.
- A budget per frame (time or bytes) limits how much it picks up, so many loads that finish together do not make one long frame.
- Until the data is in, the engine shows nothing, a placeholder, or a low-detail version.
- Loads are cached by path, so one file is loaded once. A failure is a state, not a crash.
- After the upload, the CPU copy is usually not needed. Free it.
1Why not load on the main thread
The main thread runs the frame loop: input, game logic, and recording the GPU's work. If it stops to load a file, no new frame is made until the load is done. The picture freezes.
Not every part of a load can move to another thread, though. To see which parts can, split the load into its steps.
2What a load is made of
A load is five steps in a row. The first three are most of the time, and they only need the file and some memory.
- Readfile bytes from disk
- Parse, decodeJSON, PNG, JPEG…
- ProcessLODs, mips, tangents
- Uploadcopy to GPU memory
- Publishmark it ready
Can run on a worker: plain data in, plain data out
Read
Only a file name and a byte array. Any thread can do it.
Bottleneck: the disk
Parse, decode
A pure function of the bytes. Any thread can do it, if the library has no global state.
Bottleneck: the CPU
Process
Same as decode: plain data in, plain data out. It builds what the renderer wants: coarser versions of a mesh, the smaller mip levels of a texture, missing normals.
Bottleneck: the CPU
Usually the main thread: graphics API and engine state
Upload
It creates GPU objects and records copies. Graphics APIs let several threads do this, but each command buffer and pool belongs to one thread at a time. Many engines keep it on the main thread, which is simpler.
Bottleneck: the bus to the GPU
Publish
It changes the engine's tables, which the main thread reads all the time. Doing it at one fixed point avoids locks.
Bottleneck: nothing
3Worker threads and job queues
A worker is a thread that runs jobs given to it by another thread. A job here is "load this file": it gets a path and returns the decoded data. There are three common ways to run them.
One task per load
Start a new task (a thread, or a library task like a future) for each load. The task's result is the hand-off.
Good: very little code. No queue to write.
Bad: 100 loads at once start up to 100 threads, which fight for the CPU and the disk. No order, no priorities, hard to cancel.
Fixed thread pool with a job queue
A few threads (often the core count minus one or two) take jobs from a shared queue.
Good: the CPU is never oversubscribed. The queue can be sorted by priority (near objects first), and a job can be removed before it starts.
Bad: more code: the queue, its lock, and shutting the threads down.
Asynchronous I/O plus a pool
The OS reads the file in the background (overlapped I/O, io_uring); only decoding uses a worker.
Good: no thread waits on the disk.
Bad: platform-specific code.
A pool also lets one load split into smaller jobs (one per image of a model), and hold loads back when their decoded data would not fit in memory. Job systems and worker pools explains both, and how a job waits for its parts without blocking a worker.
4The hand-off between threads
The worker and the main thread run at the same time. If both touch the same data, the result depends on timing: a data race. The safe pattern is that data moves between threads and is never shared. The worker gets a copy of what it needs (a path, some options), builds its result in its own memory, and hands the whole result over in one step. Click through one load (or use the arrow keys).
1. The request returns at once
The caller can use the handle right away, for example to place the object in the scene. The renderer knows the object is not ready and skips it.
2. The worker decodes; frames go on
Each frame asks "is it done?" without waiting. That check must be cheap and must never block.
3. The result waits
Once it has handed over its result, the worker forgets it. Nothing in the engine has changed yet, so there is no race.
4. The main thread picks it up
This happens at one fixed point, usually the start of the frame, before anything reads the engine's tables. So the new asset is either fully in for the whole frame, or not at all.
5. The GPU copies it, then draws it
The copies are recorded before the draws that use them, with a barrier between, so the same frame can already draw the asset. See GPU memory and GPU synchronization.
What the worker may touch
Its inputs (copied in), its own memory, and thread-safe libraries.
What it must not touch
The engine's tables, the graphics device, or anything the main thread may change.
Careful with libraries that keep global settings: an image loader with a global "flip vertically" switch gives different results depending on which thread set it last.
When the program exits while a load runs, the worker still writes into memory that the program is about to free. So shutdown must first wait for (or cancel) every running job, and then free what the finished ones returned.
5A budget per frame
Workers finish at random times. Often many finish together, for example when a level starts. If the main thread picked them all up in one frame, that frame would be long again: the freeze from section 1, only shorter. So the main thread works under a budget: it picks up results until the budget is used, and leaves the rest for the next frame.
The budget can count different things:
Time
Stop when the clock passes the limit.
Follows the real cost. One big item can still go over, because work is not split.
Bytes
Stop after N MiB of uploads.
Predictable for the bus and the staging memory. Ignores CPU work such as building mips.
Count
Stop after N items.
Simplest. A large and a small texture count the same.
No budget
Take everything that is ready, and wait for the rest.
For a loading screen: the first frame shows the full scene.
Worked example
30 textures finish at the same moment. Finishing one on the main thread (creating it, copying it, building its mips) takes 3 ms. The frame rate is 60 Hz, so a frame is 16.7 ms.
No budget
30 × 3 = 90 ms of main-thread work, in one frame. One frame takes over 100 ms: a visible hitch of about 5 frames.
4 ms, checked before each texture
A texture starts at 0 ms and at 3 ms, so 2 textures = 6 ms per frame. Every frame stays smooth. All 30 are in after 15 frames, 0.25 s.
Play with it. The picture below loads 30 textures. Reading and decoding one takes 100 ms; finishing it on the main thread takes 3 ms, as above. A frame's own work takes 10 ms here, so 6.7 ms are free for loading.
A smaller budget gives smoother frames, but the scene fills in more slowly. A big item that cannot be split, such as one huge texture, needs to be split into pieces (one mip level or one tile at a time) to stay under the budget.
6What to show until the data arrives
Four ways to show an object that is still loading. The grid lines stand for texture detail: a placeholder has none, a small mip a little, the full texture all of it.
Hide it
Simple, and it never looks wrong. Things pop in late.
Placeholder
The shape is there at once. Its surface changes later.
Low detail first
Small mips or a coarse mesh first, sharper later.
Full
All data in.
Which one is right depends on the program. A game behind a loading screen hides things. An open world or a map viewer shows something early and refines it.
What is one unit?
An object often needs a mesh and several textures. Each part can appear on its own, or the object can wait until all parts are in:
Each part on its own
The object can show up with a wrong surface for a few frames, for example without its normal map.
All parts together
No half-loaded look, at the cost of a little more delay.
When a material points at a texture whose pixels are not there yet, and the renderer may sample it, the texture must hold something defined: a plain color, not uninitialized memory.
7Caching by path, and failures
The same file is often requested many times: a tree model used by a thousand trees, a texture shared by many materials. The loader keeps a cache: a map from the file's path to its handle. A second request returns the first handle, also while the first load still runs.
Errors come in two kinds, and they reach the caller in different ways:
Early
The file does not exist, the file type is not supported, bad arguments.
Found in the load call, before any job starts. The caller learns it from an invalid handle, at once.
Late
The file is corrupt, the decoder fails, there is no GPU memory left for it.
Found on the worker, or when the main thread picks it up. The caller learns it when the handle's state becomes failed; the caller can ask for it.
Should a failed path stay in the cache?
Keep it as "failed"
Every later request fails fast, which is cheap.
Let a request retry
A file that was fixed on disk loads on the next try.
Either way, a failure must never leave a half-made asset behind: check that everything fits (memory, table slots) before creating the first part, or undo the parts on failure.
8Freeing the CPU copy
During a load the same data exists several times. Most copies are only needed for a short time.
The decoded data is the big one:
Keep a CPU copy only when the CPU really reads it later:
| Keep | Because |
|---|---|
| positions and indices, as a separate copy | physics, ray picking, CPU culling of individual triangles |
| small metadata: sizes, bounds, ranges in the GPU buffers | the renderer needs them every frame |
| nothing else | if the GPU copy is lost, load the file again |
9File formats, just enough
Two common mesh formats need different work before the data is GPU-ready:
- glTF data is not aligned
- A float may start at any byte. Read it with a byte copy, not a pointer cast.
- A glTF buffer view has a stride
- Attributes can be interleaved. Element i starts at offset + i × stride, not i × element size.
- OBJ and glTF put the UV origin in different corners
- OBJ's v runs up from the bottom; images and glTF start at the top. Flip one of them (v' = 1 − v).
- Paths with non-ASCII characters
- Some C libraries open files in the system's code page. Open the file yourself (as UTF-8 or wide characters) and pass the bytes or a stream.
10In RASM
RASM loads meshes, textures and environments as jobs on one pool of worker threads, under a memory budget (job systems explains the pool). The main thread picks up the finished results at the start of each frame, inside a 4 ms budget. An entity is drawn only when its mesh and all its textures are in.
GLTFRaw. Everything that touches the renderer runs in the AssetLoader's finishLoads, which the renderer's beginFrame calls through LoadHooks before anything binds the geometry pool or the bindless set. The loader lives in the rasm library, the renderer in rasm::renderer: the renderer only knows the hooks, and an application without a loader links none of the file libraries.Where RASM follows the textbook, and where it differs
| Part | This page | RASM |
|---|---|---|
| Workers | a thread pool with a job queue, or one task per load | One WorkerPool per AssetLoader, of AssetLoaderConfig::loadThreads threads (0: the hardware threads minus one), FIFO, a glTF's images and LODs as child jobs that run first. A load starts only when its bytes fit AssetLoaderConfig::loadMemoryBudget (an Engine takes both from its EngineConfig). Destroying a loading object drops its load. No priorities (job systems). |
| Hand-off | a result slot, checked without blocking | A MeshLoadJob, TextureLoadJob or EnvironmentLoadJob that the jobs write and PendingMeshLoad or PendingTextureLoad holds; its LoadTicket state turns DONE, an atomic the main thread reads without blocking. A glTF's textures wait in PendingTextureLoad with their levels already made (levels), so they are ready at once. Job code (parseMeshFile, runImageWork, buildMeshLods, decodeTexture, buildTextureLevels) never touches the engine. |
| When results are picked up | one fixed point per frame | The start of beginFrame, before the minimized-window check, so loads also finish while the window is minimized. |
| Budget | time, bytes or count | Time: LOAD_BUDGET = 4 ms, checked before each result. Meshes, then environments, then textures, at least one part of a texture per frame. A glTF file's finishMeshLoad creates its textures and queues their fills as texture results of their own, so a big model's copies spread over frames (texture uploads), and a texture is filled in 4 MiB parts. One step is never split: a model's geometry goes in one finishMeshLoad (P24). waitForLoads takes everything, with no budget. The decoded data that waits holds part of the load workers' memory budget until it is used. |
| Upload | through staging memory | Geometry (vertices, indices, and the streams only some meshes have: colors, skin weights, morph deltas) and animation data: the pools are BufferDesc::staged, so on a discrete GPU fillBuffer puts the data into a 64 MiB staging ring (on an integrated GPU it writes straight into the pool), and the copies go out at once on the transfer queue, or on the graphics queue without one (see transfer queues). A mesh and a texture count as loaded only once their copies are on the GPU, so the frames never wait for them. Textures: fillTexturePart copies through the same staging ring, or on the host (host image copy) where that costs the GPU nothing. Every level comes from the worker: an image's mips are made there (buildTextureLevels), a KTX2 file brings its own (texture compression), so the main thread only copies. The longest frame while the Flight Helmet loads is 5 ms as KTX2 and 9 ms as PNG, against 28 and 206 ms when the mips were made on the main thread and a model's textures were copied in one frame (Release, RTX 3060; texture uploads). |
| Placeholders | hide, placeholder, low detail first | Hide: an entity waits in entitiesWaitingForMesh, then in entitiesWaitingForTextures, until its mesh and every texture of its materials are in. No low-detail-first. A texture whose decode fails is filled white, because a material may already use it. |
| Cache | normalized path → handle | resolveAssetPath joins the path to AssetLoaderConfig::assetRoot and normalizes it. Meshes: loadedMeshes, by path. Textures: loadedTextures, by path and format. glTF images: GltfImportCache, once per image, sampler and color space, per model. |
| Failures | early or late; fail fast or retry | Early (missing file, unsupported extension, out of handles): invalid handle. Late (decode fails, a pool is full): MeshState::FAILED. Loading a failed path again retries, on the same handle, and destroyMesh frees it. GeometryPool::allocate takes every range of every sub-mesh, and the animation pool's largest free range (EngineConfig::animationPoolBytes) is checked, before anything is created, so a mesh that does not fit takes nothing. |
| Freeing | free the CPU copy after upload | glTF buffers go on the worker, once every accessor is read. The vertex, index, LOD, skin and morph arrays, the animation keys and the glTF model go at the end of finishMeshLoad. The decoded pixels go on the worker once their mips are made (stbi_image_free in decodeTexture and runImageWork; a glTF's image file bytes in finishImageWork), and the levels when their texture is filled (P6). Nothing is kept for the CPU. |
| Formats | glTF and OBJ | glTF through tinygltf, OBJ through tinyobjloader. An OBJ file becomes one sub-mesh with one vertex per face corner and no material; buildMeshLods merges equal vertices later. OBJ's v is flipped. |
Textures: two ways in
loadTexture
The main thread reads only the image header (stbi_info) and creates the texture at full size at once, so a material can use the handle before the pixels exist. The worker runs decodeTexture (stbi_load, always 4 channels, then every mip with buildTextureLevels). finishTextureLoad copies the levels and sets texturesFinished, so syncGpuScene checks the waiting entities.
Images inside a glTF file
tinygltf keeps each image's file bytes. Each image a material reads is a job of its own (runImageWork): it decodes the image to RGBA once and makes its mips, once per kind of slot (a normal map's are renormalized), on any free worker. loadMaterial creates each texture inside finishMeshLoad and queues its fill in pendingTextures; isLoaded(mesh) waits for them.
Where it lives in code
| What | Where |
|---|---|
| Mesh loads | AssetLoader::Impl::loadMesh, finishMeshLoad in src/assets/meshLoad.cpp; Renderer::createMesh, isLoaded in src/assets/mesh.cpp |
| Texture loads | AssetLoader::Impl::loadTexture, decodeTexture, finishTextureLoad in src/assets/textureLoad.cpp; the renderer's loadingTextures, which Renderer::isLoaded and the waiting entities read |
| Worker pool | WorkerPool, LoadTicket in src/core/workerPool.cpp; the load jobs, runMeshImport in src/assets/meshLoad.cpp, MeshLoadJob in src/assets/loadJobs.h (job systems) |
| Worker import | parseMeshFile, importGltf, importObj, runImageWork, finishImageWork in src/assets/meshImport.cpp; animations, skins and morph targets in src/assets/animationImport.cpp, src/assets/skinImport.cpp, src/assets/morphImport.cpp |
| glTF materials and images | AssetLoader::Impl::loadMaterial in src/assets/materialImport.cpp; the images' work, planImageLevels and planKtxImages in src/assets/meshImport.cpp |
| Mips on the worker | buildTextureLevels in src/rhi/mipChain.cpp (texture uploads) |
| Budget and pick-up | finishLoads, finishReadyLoads, waitForLoads, LOAD_BUDGET, resolveAssetPath in src/assets/assetLoader.cpp; the hooks, LoadHooks in src/renderer/loadHooks.h |
| Pending loads | PendingMeshLoad, PendingTextureLoad, pendingMeshes, pendingTextures in AssetLoader::Impl, src/assets/assetLoaderImpl.h |
| Result types and states | GLTFRaw, ObjRaw in src/assets/meshData.h (private); MeshState in include/rasm/mesh.h; TextureRaw in include/rasm/types.h |
| Fit check and append | GeometryPool::fits, GeometryPool::upload in src/renderer/geometryPool.cpp; Renderer::uploadMeshAnimation in src/renderer/animation.cpp |
| Entities that wait | syncGpuScene in src/renderer/gpuScene.cpp |
| Staging ring | UploadManager in src/rhi/uploadManager.cpp |
| API | loadMesh, loadTexture, waitForLoads |
- Worker code gets a path and returns a plain result. It must not touch the renderer, the registry or the device.
- Anything that creates GPU objects, writes the registry or fills a buffer for a load runs in
finishLoads, on the main thread. - Check that the whole mesh fits (
GeometryPool::fits, the animation pool) before creating any part of it. - A texture a material may already use is always filled, even when its decode fails.
- Free the CPU copy after the upload (P6). Do not keep vertex arrays, the glTF model or pixels in the registry.
- Shutdown drops every pending load and joins the workers, in
~AssetLoader, which runs before the renderer goes (anEngineholds its loader as a member). A job holds its load's job struct byshared_ptr, never the engine. - Every byte a load takes from the budget goes back once: by the main thread when it uses or drops a done result, by the job when it ends dropped.
- The main thread makes no mips for a load: the worker hands over every level.
No priority per load: the queue is FIFO. A tile streamer ranks whole tiles instead, and keeps few loads in flight, so the FIFO matters little there. A model's geometry and each texture are finished in one step, however big (P24). A 16-bit image loads as 8 bits (D36). A texture, mesh or environment can be destroyed while it loads: its load is dropped (a queued job never runs), and a mesh's pool ranges come back (deferred destruction).
Further reading
- Jason Gregory, Game Engine Architecture, 3rd edition: the chapters on resources and the file system, and on parallelism.
- Christian Gyrling, Parallelizing the Naughty Dog Engine Using Fibers, GDC 2015: a job system for a whole engine.
- The Khronos Group, glTF 2.0 Specification: buffers, buffer views, accessors and the node tree.
- Anthony Williams, C++ Concurrency in Action, 2nd edition: futures, thread pools and data races.