Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
An example of how an AssetFactory for Starling's new AssetManager can process zip files.
package starling.assets
{
import deng.fzip.FZip;
import deng.fzip.FZipEvent;
import deng.fzip.FZipFile;
import flash.events.Event;
import flash.utils.ByteArray;
import starling.assets.AssetFactory;
import starling.assets.AssetFactoryHelper;
import starling.assets.AssetReference;
import starling.assets.AtfTextureFactory;
import starling.assets.BitmapTextureFactory;
import starling.assets.DataLoader;
import starling.assets.JsonFactory;
import starling.assets.SoundFactory;
import starling.assets.XmlFactory;
public class ZipAssetFactory extends AssetFactory
{
private var _subFactories:Array;
public function ZipAssetFactory()
{
addExtensions("zip");
addMimeTypes("application/zip", "application/zip-compressed");
_subFactories = [
new BitmapTextureFactory(), new AtfTextureFactory(),
new SoundFactory(), new JsonFactory(), new XmlFactory()
];
}
override public function create(reference:AssetReference, helper:AssetFactoryHelper,
onComplete:Function, onError:Function):void
{
// get the FZip library here: https://github.com/claus/fzip
var numProcessing:int = 0;
var aborted:Boolean = false;
var fzip:FZip = new FZip();
fzip.addEventListener(Event.COMPLETE, onZipComplete);
fzip.addEventListener(FZipEvent.FILE_LOADED, onZipFileLoaded);
fzip.loadBytes(reference.data as ByteArray);
function onZipComplete(event:Event):void
{
fzip.close();
finishIfReady();
}
function onZipFileLoaded(event:FZipEvent):void
{
if (aborted) return;
var file:FZipFile = event.file;
if (file.sizeUncompressed == 0 || file.filename.indexOf("__MACOSX") != -1) return;
var subAsset:AssetReference = new AssetReference(file.content);
subAsset.url = file.filename;
subAsset.name = helper.getNameFromUrl(file.filename);
subAsset.extension = helper.getExtensionFromUrl(file.filename);
subAsset.textureOptions = reference.textureOptions;
var subFactory:AssetFactory = getFactoryFor(subAsset);
if (subFactory)
{
numProcessing++;
subFactory.create(subAsset, helper, onFactoryComplete, onFactoryError);
}
else
helper.log("No suitable factory found for " + subAsset.url);
}
function onFactoryComplete(name:String, asset:Object):void
{
helper.addComplementaryAsset(name, asset);
numProcessing--;
finishIfReady();
}
function onFactoryError(error:String):void
{
aborted = true;
fzip.close();
onError(error);
}
function finishIfReady():void
{
if (!aborted && numProcessing == 0 && !fzip.active) onComplete();
}
}
private function getFactoryFor(asset:AssetReference):AssetFactory
{
for each (var factory:AssetFactory in _subFactories)
if (factory.canHandle(asset)) return factory;
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.