-
Notifications
You must be signed in to change notification settings - Fork 31
/
Serializer.js
92 lines (78 loc) · 2.33 KB
/
Serializer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
"use strict";
/**
* An (experimental) tool for serializing matter.js worlds.
* @module Serializer
*/
const Serializer = module.exports = {};
const Resurrect = require('../../libs/resurrect-js/resurrect');
const Matter = require('matter-js');
const Common = Matter.Common;
const Engine = Matter.Engine;
/**
* Creates a serializer.
* @function Serializer.create
* @return {} A serializer
*/
Serializer.create = function() {
let serializer = new Resurrect({ prefix: '$', cleanup: true });
serializer.parse = serializer.resurrect;
return serializer;
};
/**
* Clones an object using a serializer and assigns it a new id
* @function Serializer.clone
* @param {object} serializer
* @param {object} object
* @return {} The clone
*/
Serializer.clone = function(serializer, object) {
var clone = serializer.parse(Serializer.serialise(serializer, object));
clone.id = Common.nextId();
return clone;
};
/**
* Saves world state to local storage
* @function Serializer.saveState
* @param {object} serializer
* @param {engine} engine
* @param {string} key
*/
Serializer.saveState = function(serializer, engine, key) {
localStorage.setItem(key, Serializer.serialise(serializer, engine.world));
};
/**
* Loads world state from local storage
* @function Serializer.loadState
* @param {object} serializer
* @param {engine} engine
* @param {string} key
*/
Serializer.loadState = function(serializer, engine, key) {
var loadedWorld = serializer.parse(localStorage.getItem(key));
if (loadedWorld) {
Engine.merge(engine, { world: loadedWorld });
}
};
/**
* Serialises the object using the given serializer and a Matter-specific replacer
* @function Serializer.serialise
* @param {object} serializer
* @param {object} object
* @param {number} indent
* @return {string} The serialised object
*/
Serializer.serialise = function(serializer, object, indent) {
indent = indent || 0;
return serializer.stringify(object, function(key, value) {
// limit precision of floats
if (!/^#/.exec(key) && typeof value === 'number') {
var fixed = parseFloat(value.toFixed(3));
// do not limit if limiting will cause value to zero
// TODO: this should ideally dynamically find the SF precision required
if (fixed === 0 && value !== 0)
return value;
return fixed;
}
return value;
}, indent);
};