Introduction
Objective
The objective of the saving system is, given a node, any node, serialize it completely and automatically without having to go through the mistake prone method of each time we add a member, having to remember to update the load and save functions.
To this aim, we will use the IntermediateSerializer class, with a few auxiliary classes to handle logical exceptions in our design and in the IntermediateSerializer class.
Considered options
There are several options when saving the game in XNA, the 3 more common ones are serializing using the XmlSerializer class, serializing using the IntermediateSerializer class, and finally, saving with a BinaryWriter class.
The reasons why I won’t use the XmlSerializer are explained in the conclusion in this post, so I won’t expand on it. The BinaryWriter, on the other hand, requires knowing the data you are going to read beforehand, as it’s in binary format and you need to select “chunks” of specific lengths to be interpreted as variables. This does not work well with the initial objective of the saving being automatic or not having to make custom save / load functions for each class. This leaves us with the IntermediateSerializer.
Serialization
Serializing with the IntermediateSerializer
The use of the IntermediateSerializer is best documented in these 2 articles by Shawn Hargraves: Teaching a man to fish, and Everything you ever wanted to know about IntermediateSerializer.
On the positive side, it’s simple (doesn’t require the multithreading gymnastics for the container that the XmlSerializer needs), and highly customizable (adding private members, excluding public members, setting members as references, dealing with collections, etc…). On the negative side, it only works on windows, but that’s an acceptable inconvenient, and it needs the full .Net Framework 4.0 instead of the client version (explanation).
Working with the Node
For our specific situation, we want to serialize a subtree of nodes, this nodes being any class that might derive from node. For example, we might have a situation like this:
This diagram represents that there is a root node “Scene” with two added child nodes “Camera” and “Map” (ignore the UML notation, it was the only editor at hand). We want to serialize Scene without caring about what hangs from it and have everything serialized to XML.
The first attempt at serializing this launched an error of cyclic reference, as each Node has a pointer to it’s parent. To solve this we declared the parent member of a node as a ContentSerializerAttribute.SharedResource so instead of storing the parent, it just stored a reference to this. This serialized, but upon closer investigation of the XML code it became apparent that this generated “shadow” parents, as we had both the original parent that called the serialization, and the one each child was referencing, resulting in something like this:
That’s because the children of each node are not references themselves, if they were we’d just have a very slim XML tree with just references, no content, and then the references at the bottom. Something like this:
- <?xml version="1.0" encoding="utf-8"?>
- <XnaContent xmlns:Utils="Baddies.Utils"
- xmlns:Scenes="Baddies.Scenes"
- xmlns:Nodes="Baddies.Nodes">
- <!-- Root of the tree-->
- <Asset Type="Utils:NodeSerializer">
- <root>#Resource1</root>
- </Asset>
- <!-- References-->
- <Resources>
- <!-- Scene node-->
- <Resource ID="#Resource1" Type="Scenes:Scene">
- <Name>Node</Name>
- <ParentRelativePos>false</ParentRelativePos>
- <Children Type="Utils:SharedResourceDictionary[int,Nodes:Node]">
- <Item>
- <Key>0</Key>
- <Value>#Resource2</Value>
- </Item>
- <Item>
- <Key>1</Key>
- <Value>#Resource3</Value>
- </Item>
- </Children>
- <Visible>true</Visible>
- <Position>-0 -0 -0</Position>
- <Parent />
- </Resource>
- <!-- Camera node -->
- <Resource ID="#Resource2" Type="Baddies.Camera">
- <Name>Cam</Name>
- <ParentRelativePos>false</ParentRelativePos>
- <Children Type="Utils:SharedResourceDictionary[int,Nodes:Node]" />
- <Visible>true</Visible>
- <Position>0 0 0</Position>
- <Parent>#Resource1</Parent>
- <W>673</W>
- <H>442</H>
- <DisplayBorder>true</DisplayBorder>
- </Resource>
- <!-- Map node -->
- <Resource ID="#Resource3" Type="Baddies.Map.MapGrid">
- <Name>Map</Name>
- <ParentRelativePos>true</ParentRelativePos>
- <Children Type="Utils:SharedResourceDictionary[int,Nodes:Node]" />
- <Visible>true</Visible>
- <Position>0 0 0</Position>
- <Parent>#Resource1</Parent>
- <DisplayTerrain>true</DisplayTerrain>
- <DisplayGrid>true</DisplayGrid>
- <DisplayCollisionMap>false</DisplayCollisionMap>
- <MapWidth>16</MapWidth>
- <MapHeight>16</MapHeight>
- <TileSize>16</TileSize>
- <Tiles>
- <!-- Map tiles excuded for brevity -->
- </Tiles>
- <tileSetTex>
- <Name>TileMap/tileset1</Name>
- <contentRef>#Resource3</contentRef>
- </tileSetTex>
- </Resource>
- </Resources>
- </XnaContent>
To achieve that structure we need to set the children of the Node as references as well. The children of each node are kept in a dictionary, so to solve this “dictionary of shared resources” dilemma, I wrote a class to handle it, explained in this article. This is one of the few exceptions to the “not writing custom code for saving different data” but only because the IntermediateSerializer doesn’t support these type of dictionaries out of the box.
Another exception is that even if we mark everything as references, the first node to be serialized is not considered a reference because it’s the starting point of the serializer. To solve this I made a wrapper class to serialize that only contains the root node, as a reference.
- /// <summary>
- /// Auxiliary class that takes care of
- /// the serialization of a Node tree.
- /// <remarks>
- /// Works by having a reference to the
- /// node and serializing itself, so the root
- /// node is also regarded as a reference.
- /// </remarks>
- /// </summary>
- public class NodeSerializer
- {
- /// <summary>
- /// Root node to serialize.
- /// </summary>
- [ContentSerializerAttribute(SharedResource = true)]
- private Node root;
- /// <summary>
- /// Serializes a node to XML.
- /// </summary>
- /// <param name="node">Node to
- /// serialize.</param>
- /// <param name="name">Name of the
- /// file to serialize to.</param>
- public void Serialize(Node node, string name)
- {
- this.root = node;
- XmlWriterSettings settings =
- new XmlWriterSettings();
- settings.Indent = true;
- using (XmlWriter writer =
- XmlWriter.Create(name, settings))
- {
- IntermediateSerializer.
- Serialize(writer, this, null);
- }
- }
- /// <summary>
- /// Deserializes the XML file provided
- /// and returns the created node.
- /// </summary>
- /// <param name="name">Name of the xml file.</param>
- /// <returns>Node serialized in that file.</returns>
- public Node Deserialize(string name)
- {
- Node node = null;
- XmlReaderSettings settings =
- new XmlReaderSettings();
- using (XmlReader reader =
- XmlReader.Create(name, settings))
- {
- NodeSerializer serial =
- IntermediateSerializer.
- Deserialize<NodeSerializer>(reader, null);
- node = serial.root;
- }
- return node;
- }
- }
The last exception comes with the Texture2D class. I wanted that the serializing of a tree included the actual textures used, as not to have to do a “second” step when loading. This has 2 problems. First, the texture is binary data, so kind of difficult to serialize in xml. Second, the texture has a reference to the ContentManager that loaded it, so it creates a circular dependency that there is no way to solve, short of dumping the use of the ContentManager all together.
To work around these 2 issues I created a Texture2D proxy class, as shown here:
- public class Texture2DProxy
- {
- /// <summary>
- /// Reference to the the parent class
- /// that holds a ContentManager to load
- /// this texture.
- /// </summary>
- [ContentSerializerAttribute(SharedResource = true)]
- private IContentHolder contentRef;
- /// <summary>
- /// Texture we wrap.
- /// </summary>
- private Texture2D texture;
- /// <summary>
- /// Name of the texture in the
- /// ContentManager.
- /// </summary>
- private string name;
- /// <summary>
- /// Initializes a new instance of
- /// the Texture2DProxy class.
- /// </summary>
- /// <param name="contentRef">
- /// Content manager that will be
- /// used for loading.</param>
- public Texture2DProxy(IContentHolder contentRef)
- {
- this.contentRef = contentRef;
- this.name = string.Empty;
- this.texture = null;
- }
- /// <summary>
- /// Initializes a new instance of
- /// the Texture2DProxy class.
- /// </summary>
- public Texture2DProxy()
- {
- this.contentRef = null;
- this.name = string.Empty;
- this.texture = null;
- }
- /// <summary>
- /// Gets or sets the name of the texture.
- /// </summary>
- /// <value>Name of the texture.</value>
- public string Name
- {
- set { this.name = value; }
- get { return this.name; }
- }
- /// <summary>
- /// Gets or sets the texture of the proxy.
- /// <remarks>
- /// The Get method has lazy
- /// initialization of the texture,
- /// in the sense that if we have the
- /// texture name and not the texture,
- /// it loads it when we request the
- /// texture. This is useful for when
- /// we load a texture via serialization.
- /// </remarks>
- /// </summary>
- /// <value>Texture that we wrap.</value>
- [ContentSerializerIgnore]
- public Texture2D Texture
- {
- get
- {
- if (this.texture == null &&
- this.name != string.Empty)
- {
- ContentManager man =
- this.contentRef.GetContent();
- this.texture =
- this.contentRef.GetContent().
- Load<Texture2D>(this.name);
- }
- return this.texture;
- }
- set
- {
- this.texture = value;
- }
- }
- /// <summary>
- /// Loads the selected texture.
- /// </summary>
- /// <param name="name">
- /// Name of the texture to
- /// load.</param>
- public void Load(string name)
- {
- this.name = name;
- this.texture =
- this.contentRef.GetContent().
- Load<Texture2D>(name);
- }
- }
What is serialized in the texture is the actual name of the texture, so afterwards we can load the name, and load the actual texture by request in the “get” field. This makes for a simple method of loading the textures from xml, the only problem is a project can have many ContentManagers running, and we have no way of knowing which one is the one the texture is associated to. To get around this we create a IContentHolder interface.
- /// <summary>
- /// Class that has a content manager.
- /// </summary>
- public interface IContentHolder
- {
- /// <summary>
- /// Returns the ContentManager
- /// associated to this class.
- /// </summary>
- /// <returns>A ContentManager object.</returns>
- ContentManager GetContent();
- }
The parent class that owns the texture implements this interface, and is required to pass itself to the texture as a reference upon creation. That way the steps when deserializing are as follows:
- When the serializer creates the parent class, the parent class creates the Texture2DProxy object and assigns itself as the ContentHolder.
- The deserializer fills the serialized data of the Texture2DProxy (the name of the texture),
- At some point, the game requests the texture for the first time, in the “get” field we see it’s not loaded yet, so we create it using the ContentManager of our parent, and we’re ready to go.