MeshSerializer2

Author: Aras Pranckevicius

Description
A set of scrtipts for saving/loading meshes to a simple compact binary format. Possible use case is saving them to files, uploading them somewhere and then using WWW interface to download meshes dynamically.

Of course since Unity 2.1 Asset Bundles provide a superset of this functionality (but they are only available in Unity Pro). This script itself is an improvement from MeshSerializer script, with 5x-6x reduction in file size.

The package contains an example scene; where one mesh is saved to file and the other is downloaded.

Usage

 * MeshSerializer.js is an utility class to do the actual mesh serialization. Has comments inside.
 * SaveMeshForWeb.js and LoadMeshFromWeb.js are example usage scripts.

The package
Zipped Unity package: [[Media:MeshSerializer2.zip]] (for Unity 2.x)

File format used
Note that such a file format is pretty fragile to changes - it does not have any concept of "format version" built in. It's fully enough if you save and load meshes yourself (you know which format are you using), but if you want a generic mesh-loading-format, you'd have to implement something more complex.

The file format used now:
 * 2 bytes vertex count
 * 2 bytes triangle count
 * 1 bytes vertex format (bits: 0=vertices, 1=normals, 2=tangents, 3=uvs)
 * After that come vertex component arrays, each optional except for positions. Which ones are present depends on vertex format:
 * Positions. 3D bounding box, followed by vertices encoded as two bytes per vertex component (so it's 6 bytes/vertex, plus 24 bytes for the bounding box).
 * Normals. 3 bytes per normal.
 * Tangents. 4 bytes per tangent.
 * UVs. 2D bounding box, followed by UVs encoded as two bytes per UV component (so it's 4 bytes/UV, plus 16 bytes for the bounding box).
 * Finally the triangle indices array: 6 bytes per triangle (3 two byte indices)

Notes and ideas
If bump-mapping is not used, then storing tangents is a waste of space. By default tangents are not stored.

There is a related article about saving unity meshes in .obj format: ObjExporter.

Like mentioned above, this incorporates some of size reduction ideas from MeshSerializer article. Positions and UVs are encoded as 16 bit integers, quantized over the bounding box range. Normals and tangents are encoded at one byte per component, under assumption that components will always be in -1..1 range.

The encoding is not exactly right, I think; proper way would be to round to integers instead of truncate. An exercise for the reader!

Changelog

 * 2009 Feb 24 - Initial version.

Source code
All the source code is included in the provided Unity Package above. This is only for easy-browsing purposes.