Asset Pipeline
Eclipsed Engine
Every texture, shader, sound and scene in Eclipsed Engine goes through the asset pipeline I built. In the editor it imports source files, keeps them up to date as you edit them, and frees them when nothing uses them. I've also written the format for cooking everything into one file for game builds.

At a glance

GUIDs instead of paths

If a scene refers to a texture by its path, renaming or moving the file breaks the scene. So every asset gets a 128-bit GUID the first time the engine sees it, saved in a .meta file next to the source. Scenes, materials and prefabs only store GUIDs.

The meta file also holds per-asset settings, like the sprite rectangles for a sprite sheet. The imported binary is written to an artifacts folder named after the GUID, split by its first two characters so no single folder gets too large:
AssetMeta MetaSerializer::LoadOrCreateMeta(const std::filesystem::path& assetPath)
{
    AssetMeta meta;

    if (MetaFileExists(assetPath)) meta = LoadMeta(assetPath);
    else meta = CreateMeta(assetPath);

    std::filesystem::path path = PathManager::GetArtifactsPath();

    std::string guidStr = meta.guid.ToString();
    path /= guidStr.substr(0, 2);
    path /= guidStr;

    meta.exportedPath = path;
    return meta;
}

One interface per asset type

Every asset type implements the same small interface. Importing reads the source file, an optional processing step transforms it, and serializing writes the engine-ready binary. Loading reads that binary back into memory.
class IAssetType
{
public:
    virtual ImportedData Import(const AssetMeta& file) = 0;
    virtual ProcessedData Process(const ImportedData& file) { return file; }
    virtual void Serialize(BinaryWriter& writer, const ProcessedData& data) = 0;

    virtual void Load(BinaryReader& reader, const AssetMeta& meta, AssetData* data) = 0;
    virtual void LoadFromBinary(BinaryReader& reader, const AssetMeta& meta, AssetData* data) {}

    virtual bool NeedsProcessing() const { return false; }
};
For a texture, Import decodes the image with stb_image and Serialize writes the width, height, channel count, raw pixels and sprite rectangles. At load time the pixels go straight to the GPU, with no image decoding at runtime.

The importer skips any file whose binary is already newer than the source, so opening the editor only re-imports what actually changed:
if (std::filesystem::exists(meta.exportedPath) &&
    std::filesystem::last_write_time(meta.fullPath) < std::filesystem::last_write_time(meta.exportedPath))
    return;

ImportedData imported = type->Import(meta);
BinaryWriter writer(meta.guid);

if (type->NeedsProcessing())
    type->Serialize(writer, type->Process(imported));
else
    type->Serialize(writer, imported);
Adding a new kind of asset means writing one class and registering it. The rest of the pipeline doesn't change.

Reference counting and deferred deletion

Game code never holds raw asset data. It holds a small handle, like Texture or AudioClip, that points into a shared cache. Copying a handle increases the reference count, destroying one decreases it, and moving one just transfers the pointer.

Loading checks the cache first, so any number of components can use the same texture while it's only loaded once:
AssetData* data = AssetCache::Get(guid);
if (data == nullptr)
{
    BinaryReader reader(guid);
    const AssetMeta& meta = database.GetProcessedFile(guid);

    data = AssetCache::Store(guid, T::CreateNewData());
    AssetTypeRegistry::GetType(meta.type)->Load(reader, meta, data);
}
return data;
When the count reaches zero, the asset isn't deleted right away. It's put in a queue that is processed at the end of the frame, and only assets that are still unused get freed. If a scene drops a texture and picks it up again in the same frame, which happens a lot when objects are destroyed and recreated, the texture stays in memory and isn't loaded twice.
void AssetDeletionQueue::ProcessPendingForDelete()
{
    for (GUID& guid : pendingForDelete)
    {
        AssetData* data = AssetCache::Get(guid);
        if (data == nullptr) continue;

        if (data->refCount <= 0)
            AssetCache::Delete(guid);
    }
    pendingForDelete.clear();
}

Hot-reloading assets

In the editor, a file watcher runs on its own thread and reports every change in the project's folders. That thread must not touch the asset cache, since the main thread is using it to render. So it only pushes events into a list guarded by a mutex:
void AssetManager::AddFileChanged(const Editor::FileWatcherEvent& e)
{
    std::lock_guard<std::mutex> lock(fileChangesMutex);
    fileChanges.push_back(e);
}
At the end of each frame the main thread takes the whole list in one short lock and processes it with the lock released, so the watcher thread is never blocked while files are re-imported:
std::vector<Editor::FileWatcherEvent> localChanges;
{
    std::lock_guard<std::mutex> lock(fileChangesMutex);
    localChanges = std::move(fileChanges);
    fileChanges.clear();
}

for (auto& e : localChanges)
{
    const AssetMeta& meta = database.ProcessFile(e.path, e.root);
    AssetImporter::ImportFile(meta);
    AssetCache::MarkForReload(meta.guid);
}
The reload writes the new data into the existing cache entry instead of creating a new one. Every handle already points at that entry, so every sprite, material and sound using the asset shows the new version immediately, without anyone having to look it up again.

Cooking for game builds (in progress)

A shipped game shouldn't carry thousands of loose files. So I've written a cooking step that packs every imported asset into a single bundle: first the number of assets, then a table of fixed-size headers, then all the asset data back to back. Hooking it into the editor's build process is the next step.
struct Header {
    Assets::GUID guid;
    size_t size;
    size_t offset;
    AssetType type;
    char name[32];
};
The game only needs to read the header table into its asset database at startup. When an asset is needed, the reader jumps straight to that asset's offset in the bundle, using the same load code the editor uses:
void TextureAssetType::LoadFromBinary(BinaryReader& reader, const AssetMeta& meta, AssetData* data)
{
    reader.SetRead(meta.offset);
    Load(reader, meta, data);
}

Trade-offs and next steps

  • Bundles aren't part of the build yet. The cooking and bundle-reading code exists, but the game build still needs to call it and agree on the bundle's file name.
  • Meta file edits don't trigger a re-import. The file watcher ignores .meta files, so changing an asset's settings needs the source file to be touched too.
  • The bundle format isn't versioned. Headers are written straight from memory, so the layout depends on the compiler and platform. A version number and explicit field-by-field writing would make bundles portable and safe to change.
  • Nothing is compressed. Textures are stored as raw pixels. Compressing the bundle, or using GPU texture formats, would make builds much smaller.
  • Loading is synchronous. Assets load on the main thread the first time they're asked for. Loading on a worker thread, with a placeholder until it's done, would remove hitches when a scene opens.

The source code for the asset module is on GitHub.