Thursday, October 22, 2009

Thinner Builder, Smaller Stardust

Stardust project homepage
Stardust Manual (PDF)

I should have done this long time ago.

As listed in the feature list, Stardust supports XML serialization. The XMLBuilder class is in charge of converting a particle system to XML representation and reconstructing a particle system from a give XML representation.

How does the XMLBuilder class know the mapping from an XML tag's name to an actual Stardust class? The answer is the registerClass(), registerClasses(), and registerClassesFromClassPackage() methods. The XMLBuilder relies on these methods to acquire the knowledge of which XML tag name maps to which actual class.

These methods have to be called by the programmer: the more classes you wish the builder to build from XML data, the more classes you must register. The more classes you register, the larger the compiled file size, since more classes are linked together.

The registerClassesFromClassPackage() method is worth mentioning in particular. Subclasses of the ClassPackage class, which is essentially a collection of classes for convenience, all override the populateClasses() method to populate the classes (an array) property with class references. The registerClassesFromClassPackage() would register all the classes in a ClassPackage object in just one line of code. There are already several build-in class packages at your disposal: CommonClassPackage, TwoDClassPacakge, ThreeDClassPackage, ZBClassPackage, PV3DClassPackage, and ND3DClassPackage. All these class packages provide a getInstance() method to return a singleton object, since it's not necessary to instantiate a collection with a fixed set of elements yourself.

Class packages are convenient. But please beware: it's very likely that you would not use all the classes in a class package during XML deserialization, thus wasting some file size. It doesn't matter when the file size is of no concern; however, when you are working with a file-size-sensitive project, such as banner, file size becomes critically. In such circumstances, I would highly recommend you register classes one by one through the registerClass() method, just registering the class you would like to use when deserializing from XML data.

Originally, the XMLBuilder class registers the CommonClassPackage, TwoDClassPacakge, and ThreeDClassPackage by default. I've removed this default action in the latest revision (1.0.110 Beta), which I should have done long time ago.

You can see this class registering process in action in the 6th step of the XML reconstruction example in the Stardust Manual on page 41, which I just updated today.

No comments: