piskel/js/utils/Serializer.js

88 lines
2.7 KiB
JavaScript
Raw Normal View History

(function () {
var ns = $.namespace('pskl.utils');
ns.Serializer = {
serializePiskel : function (piskel) {
var serializedLayers = piskel.getLayers().map(function (l) {
return pskl.utils.Serializer.serializeLayer(l);
});
return JSON.stringify({
modelVersion : Constants.MODEL_VERSION,
piskel : {
height : piskel.getHeight(),
width : piskel.getWidth(),
layers : serializedLayers
}
});
},
serializeLayer : function (layer) {
var serializedFrames = layer.getFrames().map(function (f) {
return f.serialize();
});
return JSON.stringify({
name : layer.getName(),
frames : serializedFrames
});
},
2013-10-09 22:06:11 +00:00
deserializePiskel : function (piskelString) {
var piskelData = JSON.parse(piskelString);
return this.createPiskelFromData(piskelData);
},
/**
* Similar to deserializePiskel, but dealing directly with a parsed piskel
* @param {Object} piskelData JSON.parse of a serialized piskel
* @return {pskl.model.Piskel} a piskel
2013-10-09 22:06:11 +00:00
*/
createPiskel : function (piskelData) {
var piskel = null;
2013-10-09 22:06:11 +00:00
if (piskelData.modelVersion == Constants.MODEL_VERSION) {
var pData = piskelData.piskel;
piskel = new pskl.model.Piskel(pData.width, pData.height);
pData.layers.forEach(function (serializedLayer) {
var layer = pskl.utils.Serializer.deserializeLayer(serializedLayer);
piskel.addLayer(layer);
});
} else {
2013-10-09 22:06:11 +00:00
piskel = pskl.utils.Serializer.backwardDeserializer_(piskelData);
}
return piskel;
},
2013-10-09 22:06:11 +00:00
deserializeLayer : function (layerString) {
var lData = JSON.parse(layerString);
var layer = new pskl.model.Layer(lData.name);
lData.frames.forEach(function (serializedFrame) {
var frame = pskl.utils.Serializer.deserializeFrame(serializedFrame);
layer.addFrame(frame);
});
return layer;
},
2013-10-09 22:06:11 +00:00
deserializeFrame : function (frameString) {
var framePixelGrid = JSON.parse(frameString);
return pskl.model.Frame.fromPixelGrid(framePixelGrid);
},
/**
* Deserialize old piskel framesheets. Initially piskels were stored as arrays of frames : "[[pixelGrid],[pixelGrid],[pixelGrid]]".
*/
2013-10-04 21:55:45 +00:00
backwardDeserializer_ : function (frames) {
var layer = new pskl.model.Layer('Layer 1');
frames.forEach(function (frame) {
layer.addFrame(pskl.model.Frame.fromPixelGrid(frame));
});
var width = layer.getFrameAt(0).getWidth(), height = layer.getFrameAt(0).getHeight();
var piskel = new pskl.model.Piskel(width, height);
piskel.addLayer(layer);
return piskel;
}
};
})();