Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize a tree structure in C++?

I'm trying to serialize/deserialize a game scene for network sending/receiving and saving/loading from/to disk.

My game engine uses Nodes and Components and as such those are the only objects that need serializing. A scene might look like this:

Root Node
  - Node
    - SpecializedComponent
    - SpecializedComponent
    - Node 
      - Node
  - Node
    - Node
    - Node
      - Node
        - Node
          - SpecializedComponent
  - Node

A Node is basically this:

class Node {
    map<String, Node> mChildren;
    map<String, Component> mComponents;
    uuid_t mId;
    Node* mParent;
};

A SpecializedComponent is basically this:

class SpecializedComponent : public Component {
    uuid_t mId;
    Node* mNode;
};

I'd like to either use YAML or JSON for my text representation of this. I have Qt, Boost and any other library I'd like at my disposal so dependencies are not an issue. In fact, nodes are already Q_OBJECTS so I have reflection.

Despite reflection, deserializing this properly back to a C++ tree structure seems to be a problem.

Optimally, I'd like an elegant and efficient solution to serializing/deserializing a structure like this into either binary or text format.

like image 717
svenstaro Avatar asked Oct 23 '11 12:10

svenstaro


1 Answers

A descent recursive parser usually it's the simpler and sufficiently powerful option to handle the reconstruction part. I could try to setup some code to show in concrete, in pseudocode some thing like this:

 Node *parse(stream s) {
  content = new Node;
  s >> content >> nsons;
  for (int c = 0; c < nsons; ++c)
   content->addChild(parse(s));
  return content; 
 }

Of course when a component is read we must check the type.

like image 80
CapelliC Avatar answered Oct 19 '22 23:10

CapelliC