TExcelTAD

Hot Reload

An artist tweaks a texture, a designer changes a jump height in a config file, a graphics programmer edits a shader. Without hot reload, each change means quit, rebuild data, relaunch, walk back to the spot. With it, the change appears in the running game within a second. Over a project's life, hot reload is one of the best productivity investments an engine team can make.

Hot reload has three parts:

  1. Detect that a source file changed.
  2. Reload the asset, ideally on a background thread.
  3. Swap the new data in so that everything holding the old asset sees the new one, without dangling pointers.

Detect by version stamps

The portable way to detect changes is to poll: remember each file's version stamp (its last-write time, a size + hash, or a counter from the asset pipeline) and compare it every so often. The model below fakes the file system with a map so the run is deterministic; the real call is shown afterwards.

The key design choice is indirection: game code holds a Handle (an index into the cache's table), never a Texture*. Reloading replaces the table entry, and every holder sees the new data on its next lookup.

cpp · try it yourself
#include <cstdint>
#include <iostream>
#include <map>
#include <string>
#include <vector>

// Fake file system: path -> (version stamp, contents).
struct FakeFile { std::uint64_t version; std::string contents; };
std::map<std::string, FakeFile> disk = {
    {"player.cfg", {1, "jump=4.0"}},
    {"enemy.cfg",  {1, "speed=2.5"}},
};

struct Config { std::string text; };
struct Handle { std::uint32_t index; };

class ConfigCache {
public:
    Handle load(const std::string& path) {
        entries_.push_back({path, disk.at(path).version, Config{disk.at(path).contents}});
        return Handle{std::uint32_t(entries_.size() - 1)};
    }
    const Config& get(Handle h) const { return entries_[h.index].data; }

    // Called once per frame (or every N frames): compare stamps, reload what changed.
    int poll() {
        int reloaded = 0;
        for (Entry& e : entries_) {
            const FakeFile& f = disk.at(e.path);
            if (f.version != e.loadedVersion) {
                e.data = Config{f.contents};                 // swap in place: handles stay valid
                std::cout << "  reloaded " << e.path << " v" << e.loadedVersion << " -> v" << f.version << "\n";
                e.loadedVersion = f.version;
                reloaded++;
            }
        }
        return reloaded;
    }

private:
    struct Entry { std::string path; std::uint64_t loadedVersion; Config data; };
    std::vector<Entry> entries_;
};

int main() {
    ConfigCache cache;
    Handle player = cache.load("player.cfg");
    Handle enemy = cache.load("enemy.cfg");

    for (int frame = 1; frame <= 4; frame++) {
        if (frame == 2) disk["player.cfg"] = {2, "jump=5.5"};      // the designer saves a change
        if (frame == 4) { disk["player.cfg"] = {3, "jump=5.0"}; disk["enemy.cfg"] = {2, "speed=3.0"}; }
        std::cout << "frame " << frame << ":\n";
        int n = cache.poll();
        std::cout << "  " << n << " reloaded; player " << cache.get(player).text << ", enemy " << cache.get(enemy).text << "\n";
    }
}
frame 1:
  0 reloaded; player jump=4.0, enemy speed=2.5
frame 2:
  reloaded player.cfg v1 -> v2
  1 reloaded; player jump=5.5, enemy speed=2.5
frame 3:
  0 reloaded; player jump=5.5, enemy speed=2.5
frame 4:
  reloaded player.cfg v2 -> v3
  reloaded enemy.cfg v1 -> v2
  2 reloaded; player jump=5.0, enemy speed=3.0

On a real disk, std::filesystem::last_write_time gives the stamp. Polling a few hundred files every half second is cheap; for thousands, use the OS's change notifications (ReadDirectoryChangesW on Windows, inotify on Linux, FSEvents on macOS), or a wrapper library such as efsw.

cpp
#include <filesystem>
namespace fs = std::filesystem;

fs::file_time_type stamp = fs::last_write_time("assets/player.cfg");
if (stamp != entry.loadedStamp) { /* reload */ }

Tip: Editors often save a file in several steps (write a temp file, delete, rename) and you may see the change while the file is half-written. Wait until the stamp has been stable for ~100 ms, and treat a failed open or parse as "try again next poll", not as an error.

Dependencies and failed reloads

Assets depend on each other: a material uses a shader and two textures; a prefab uses a mesh and a material. When a shader changes, every material built from it must be rebuilt too. And when a reload fails (a shader with a syntax error, a truncated texture), the game must keep running with the old version and report the error, not crash.

cpp · try it yourself
#include <iostream>
#include <map>
#include <set>
#include <string>
#include <vector>

struct Asset {
    std::string source;          // what's "on disk"
    int diskVersion = 1;
    int loadedVersion = 0;
    std::string compiled;        // the live, last good version
    std::vector<std::string> deps;
};

std::map<std::string, Asset> assets;

bool compile(const std::string& name) {
    Asset& a = assets[name];
    if (a.source.find("ERROR") != std::string::npos) {
        std::cout << "  " << name << ": reload failed, keeping v" << a.loadedVersion << "\n";
        a.loadedVersion = a.diskVersion;         // don't retry until the file changes again
        return false;
    }
    std::string built = a.source;
    for (auto& d : a.deps) built += "+" + assets[d].compiled;
    a.compiled = built;
    a.loadedVersion = a.diskVersion;
    std::cout << "  " << name << " rebuilt: " << a.compiled << "\n";
    return true;
}

void poll() {
    std::set<std::string> dirty;
    for (auto& [name, a] : assets) if (a.diskVersion != a.loadedVersion) dirty.insert(name);
    // Propagate to dependents until nothing new is added.
    bool grew = true;
    while (grew) {
        grew = false;
        for (auto& [name, a] : assets)
            for (auto& d : a.deps)
                if (dirty.count(d) && !dirty.count(name)) { dirty.insert(name); grew = true; }
    }
    // Rebuild dependencies before dependents (a tiny topological order: depth first).
    std::set<std::string> done;
    auto visit = [&](auto&& self, const std::string& n) -> void {
        if (done.count(n) || !dirty.count(n)) return;
        for (auto& d : assets[n].deps) self(self, d);
        done.insert(n);
        if (!compile(n)) return;
    };
    for (auto& n : dirty) visit(visit, n);
}

int main() {
    assets["lit.shader"]   = {"lit1", 1, 0, "", {}};
    assets["rock.png"]     = {"rock1", 1, 0, "", {}};
    assets["rock.mat"]     = {"mat1", 1, 0, "", {"lit.shader", "rock.png"}};
    assets["boulder.prefab"] = {"pre1", 1, 0, "", {"rock.mat"}};

    std::cout << "initial load\n"; poll();

    std::cout << "edit shader\n";
    assets["lit.shader"].source = "lit2"; assets["lit.shader"].diskVersion = 2;
    poll();

    std::cout << "save shader with a typo\n";
    assets["lit.shader"].source = "lit3 ERROR"; assets["lit.shader"].diskVersion = 3;
    poll();
    std::cout << "boulder still uses: " << assets["boulder.prefab"].compiled << "\n";
}
initial load
  lit.shader rebuilt: lit1
  rock.png rebuilt: rock1
  rock.mat rebuilt: mat1+lit1+rock1
  boulder.prefab rebuilt: pre1+mat1+lit1+rock1
edit shader
  lit.shader rebuilt: lit2
  rock.mat rebuilt: mat1+lit2+rock1
  boulder.prefab rebuilt: pre1+mat1+lit2+rock1
save shader with a typo
  lit.shader: reload failed, keeping v2
  rock.mat rebuilt: mat1+lit2+rock1
  boulder.prefab rebuilt: pre1+mat1+lit2+rock1
boulder still uses: pre1+mat1+lit2+rock1

The shader edit rebuilt the material and the prefab that use it, in dependency order. The broken shader left everything on the last good version. (The dependents were still rebuilt from the old shader, which is harmless; a smarter version would skip them when a dependency fails.)

What can be reloaded

Kind Difficulty Notes
Config/tuning values easy reload the file, re-read values each frame or on a "changed" event
Textures, sounds easy re-create the GPU texture / audio buffer, swap behind the handle
Shaders medium recompile, rebuild pipelines that use them; keep the old one on errors
Meshes, materials, prefabs medium dependencies; live instances may need re-spawning
Scripts (Lua, etc.) medium reload the chunk; keep state in tables that survive the reload. See Scripting with Lua and sol2
C++ code hard load gameplay from a DLL/shared library and swap it, or use a tool like Live++; state layout changes break it

Note: Ship builds usually compile hot reload out. Assets are packed into archives, file watching costs a thread, and the indirection is only needed in development. Keep the handle indirection, though: it is also what makes streaming and memory defragmentation possible.

Test yourself

Why does the cache hand out handles instead of raw pointers to assets?

  1. Handles are smaller
  2. Reloading can replace the data behind a handle without leaving holders with dangling pointers
  3. Pointers cannot be stored in vectors
  4. Handles load faster

A shader with a syntax error is saved. What should hot reload do?

  1. Crash so the error is noticed
  2. Unload the shader and draw nothing
  3. Report the error and keep using the last good version
  4. Reload the whole level

When lit.shader changes, which assets need rebuilding?

  1. Only the shader
  2. The shader and every asset that depends on it, directly or indirectly
  3. All assets
  4. Only the textures