Robotica
GameDev

RoboEngine DevBlog#2

Time Travel for Game Worlds:
Making Every Edit Reversible

So we have the beginnings of a user interface, a facade to our castle, but we need to unlock the most essential superpower in any creation tool: full Undo and Redo.

Once an editor lets you delete lights, shuffle hierarchies, and tweak values on the fly, you desperately need a safety net when you accidentally nuke half your scene. Now, creating, deleting, re-parenting, adding or removing components, and dragging sliders in the Inspector are all completely reversible. Ctrl+Z, Ctrl+Y, and Ctrl+Shift+Z work right out of the box, and the Edit menu even tells you what you’re rewinding, like “Undo Delete Point Light 2”.

Best of all? The entire undo/redo engine took only about 300 new lines of C++. It stayed so lean because it piggybacks directly on the EnTT scene and component reflection table we built in the first commit. Let’s pop the hood on how that foundation works, and how we turned it into a time machine.

The Bedrock Underneath:
ReScene & Intrusive Lists

At the bottom of the stack, ReScene wraps an entt::registry. Entities are bare entt::entity handles, packing both an index and a version number so stale IDs immediately reveal themselves after an entity is destroyed, while components are plain data structs driven by systems:

ComponentWhat It HoldsSaved in Scene Files?
NameComponentDisplay nameYes
TransformComponentLocal translation,
rotation (Euler, radians),
scale
Yes
HierarchyParent,
first child,
next/prev sibling,
tree depth
No (owned by the scene)
WorldTransformWorld matrix and
normal matrix
No (recomputed every frame)
MeshComponentshared_ptr<ReModel> plus the model’s file pathYes (path only)
PointLightComponentColor,
intensity,
billboard radius
Yes
OrbitBehaviorCenter,
axis,
speed in rad/s
Yes

Every entity automatically receives the first four. Notice how Hierarchy forms an intrusive linked list woven directly across the entities themselves:

struct Hierarchy
{
    Entity   parent      = NullEntity;
    Entity   firstChild  = NullEntity;
    Entity   nextSibling = NullEntity;
    Entity   prevSibling = NullEntity;
    uint32_t depth       = 0; // The transform system sorts by this so parents update first
};

Only ReScene::setParent is allowed to touch these links, keeping the tree tangle-free. It blocks moves that would turn an entity into its own ancestor and can optionally adjust local transforms so a re-parented object stays visually pinned in place.

(For orientation trivia: RoboEngine’s world is +Z up, converting OBJ models from Y-up at import.)

Keeping track of nextSibling turns out to be crucial for time travel: when you undo a deletion, an entity shouldn’t just reappear under its old parent, it needs to slot right back into its exact original spot among its siblings.

The Secret Weapon:
The Component Table

Neither the Inspector UI nor the JSON serializer ever hardcodes component types. Instead, every user-facing component registers a single ComponentInfo entry containing its display name, type hash, removability flag, and a handful of function pointers:

struct ComponentInfo
{
    const char   *name;      // Display name and key in scene files
    entt::id_type type;      // entt::type_hash<T>::value()
    bool          removable; // False for components every entity must have

    bool (*has)   (const entt::registry &, Entity);
    void (*add)   (entt::registry &, Entity);
    void (*remove)(entt::registry &, Entity);
    void (*save)  (const entt::registry &, Entity, nlohmann::json &out);
    void (*load)  (entt::registry &, Entity, const nlohmann::json &in, ComponentLoadContext &);
};

A helper template, makeInfo<T, Save, Load>, generates all the boilerplate using capture-free lambdas, turning component registration into a clean, one-line table:

static const std::vector<ComponentInfo> table
{
    makeInfo<NameComponent,       saveName,       loadName      >("Name",        false),
    makeInfo<TransformComponent,  saveTransform,  loadTransform >("Transform",   false),
    makeInfo<MeshComponent,       saveMesh,       loadMesh      >("Mesh",        true),
    makeInfo<PointLightComponent, savePointLight, loadPointLight>("Point Light", true),
    makeInfo<OrbitBehavior,       saveOrbit,      loadOrbit     >("Orbit",       true),
};

The Inspector walks this table to draw headers and populate the Add Component menu, while the serializer walks it to read and write JSON. Loading is deliberately forgiving: missing or mistyped fields gracefully fall back to defaults instead of crashing, and meshes route through a per-load cache so multiple entities sharing a model share a single GPU copy.

Here is why this table made Undo/Redo a bargain:

By adding just two more function pointers to ComponentInfo, every single component type instantly learned how to clone and restore itself in memory:

// In-memory copies for undo snapshots
std::any (*copy) (const entt::registry &, Entity);
void     (*paste)(entt::registry &, Entity, const std::any &value); // Adds or replaces

// Inside makeInfo<T>:
[](const entt::registry &r, Entity e) { return std::any{r.get<T>(e)}; },
[](entt::registry &r, Entity e, const std::any &v) { r.emplace_or_replace<T>(e, std::any_cast<const T &>(v)); },

Better yet, copying a MeshComponent copies its shared_ptr<ReModel>, keeping the GPU buffers alive inside the undo stack. Undoing a mesh deletion brings it back instantaneously, no disk reload required!

How the Time Machine Works

Instead of writing dozens of bespoke command classes (MoveCommand, DeleteCommand, TweakLightCommand), RoboEngine uses unified state snapshots. Every reversible action captures the affected entities before the change and after the change. Undo applies “before”; redo applies “after.”

1. Capturing EntitySnapshots

An EntitySnapshot freezes the complete state of one entity at a single moment in time:

struct EntitySnapshot
{
    Entity id          = NullEntity;
    bool   exists      = false;
    Entity parent      = NullEntity;
    Entity nextSibling = NullEntity; // Preserves exact sibling order
    std::vector<std::pair<const ComponentInfo *, std::any>> components;
};

captureEntity clones every component listed in our table. For hierarchies, captureSubtree walks depth-first so parents are always recorded ahead of their children, while asDestroyed flips a snapshot list into “these entities do not exist”, giving us the exact before-state of a creation and the after-state of a deletion.

2. Two-Pass Restoration

When you hit Ctrl+Z, restoreSnapshots rebuilds reality in two careful passes:

  1. Backwards pass (children first):
    • Destroy every entity whose target snapshot says exists == false.
  2. Forwards pass (parents first):
    • Resurrect any missing entity using its original ID, paste its exact snapshot components (stripping away any extras), and re-link it under its parent right in front of its old nextSibling.

Because the snapshot already stores the entity’s local transform, re-linking calls setParent with keepWorldTransform = false alongside a new insertBefore parameter so the entity drops neatly back into its original sibling slot.

3. The History Stacks

Each entry in ReUndoHistory bundles a human-readable label with its before/after states and the entity to highlight afterward:

struct Change
{
    std::string label;                  // e.g. "Delete Point Light 2"
    std::vector<EntitySnapshot> before; // Parents first
    std::vector<EntitySnapshot> after;  // Parents first
    Entity focus = NullEntity;          // Entity to select after undo / redo
};

Undo lives in a std::deque<Change> capped at 200 steps (dropping the oldest when full), while redo sits in a std::vector<Change> that clears whenever you perform a fresh edit.

Editor ActionRecorded Before StateRecorded After State
Create Entity{id, exists = false}captureEntity
Delete EntitycaptureSubtree (entire subtree)asDestroyed(before)
Re-parentcaptureEntitycaptureEntity (only if parent or sibling slot changed)
Add / Remove ComponentcaptureEntitycaptureEntity
Inspector EditSnapshot cached while no widget is activecaptureEntity the moment the widget is released

Traps & Mobs Along the Way

Building an undo stack sounds straightforward until you start clicking things in weird orders. Here are five traps we had to outsmart:

Resurrecting exact entity IDs

Older undo entries refer to entities by their entt::entity handle. If undoing a deletion brought an entity back with a new ID, every earlier history step touching it would point at thin air. ReScene::recreateEntity asks EnTT for that exact index and version, and gracefully backs out with a warning log if another entity somehow claimed the slot:

const Entity entity = registry_.create(id);
if (entity != id)
{
    registry_.destroy(entity); // Slot was taken by another entity
    return NullEntity;
}

One slider drag = one undo step

Dragging a float slider updates values every single frame. Recording on every frame would turn Ctrl+Z into a painful pixel-by-pixel crawl. Instead, the Inspector snapshots the entity only while no UI widget is active, and records the change once the widget is released:

editChanged |= changed;
editActive   = ImGui::IsAnyItemActive() &&
               ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows);
if (!editActive && editChanged)
{
    history.record({"Edit " + entityName(scene, selected), {editBefore}, {captureEntity(scene, selected)}, selected});
    editChanged = false;
}

Crucial detail:

  • ImGuiFocusedFlags_RootAndChildWindows ensures opening a color picker popup doesn’t count as “leaving” the Inspector, which would otherwise shatter a single color drag into dozens of tiny undo steps.

Don’t hijack Ctrl+Z from text boxes.

  • ImGui’s text inputs have their own built-in text undo. Our global shortcut steps aside whenever io.WantTextInput is active so pressing Ctrl+Z while renaming an entity fixes your typo instead of reverting your last scene edit.

Wait for the GPU before rewinding

  • Undo and redo can destroy entities whose meshes are still in flight on the GPU. Just like deleting an entity, both paths call vkDeviceWaitIdle before mutating the registry.

Wipe the slate on scene load

  • Loading a new scene file mints fresh entity IDs that mean completely different things than the old ones, so loading a file clears both undo and redo stacks cleanly.

Next Up on the Quest

Right now, our demo scene: two vases, a floor, and six orbiting lights, is still hardcoded inside FirstApp’s constructor. In our next DevBlog, we’ll tackle evicting that hardcoded setup into a proper JSON scene file and building a file picker so RoboEngine boots from data instead of C++!