-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathconvertToBinary.js
93 lines (78 loc) · 2.18 KB
/
convertToBinary.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
93
/**
* This file generates binary files for https://github.com/anvaka/allnpmviz3d:
*
* + links.bin
* + positions.bin
* + labels.json
*/
var fs = require('fs');
var posFileName = process.argv[2];
var graphFileName = process.argv[3];
if (!posFileName) {
console.log('I need positition file `*.pos3d as second argument`');
return -1;
}
if (!graphFileName) {
console.log('I need graph file, produced by convertToGraph.js file');
return -2;
}
var nodes = JSON.parse(fs.readFileSync(posFileName, 'utf8'));
savePositions(nodes);
saveLinks(nodes);
saveLabels(nodes);
function savePositions(nodes) {
var buf = new Buffer(nodes.length * 4 * 3);
nodes.forEach(function(element, i) {
var idx = i * 4 * 3;
buf.writeInt32LE(element.pos.x, idx);
buf.writeInt32LE(element.pos.y, idx + 4);
buf.writeInt32LE(element.pos.z, idx + 8);
});
fs.writeFileSync('positions.bin', buf);
}
function saveLabels(nodes) {
var labels = [];
nodes.forEach(function(element, i) {
labels.push(element.node);
});
fs.writeFileSync('labels.json', JSON.stringify(labels), 'utf8');
}
function saveLinks(nodes) {
var graph = JSON.parse(fs.readFileSync(graphFileName, 'utf8'));
var nodeMap = Object.create(null);
nodes.forEach(function(element, i) {
nodeMap[element.node] = i;
});
var linkMap = Object.create(null);
graph.links.forEach(function (link) {
if (typeof nodeMap[link.fromId] !== 'number') {
console.log('skipping', link);
return;
}
var store = linkMap[link.fromId];
if (!store) {
store = linkMap[link.fromId] = [];
}
var nodeIdx = nodeMap[link.toId];
if (typeof nodeIdx !== 'number') {
console.log('skipping', link);
return;
}
store.push(nodeIdx);
});
var buf = new Buffer((nodes.length + graph.links.length) * 4);
var idx = 0;
nodes.forEach(function(element, i) {
var nodeId = nodeMap[element.node] + 1; // + 1 so that we avoid 0
buf.writeInt32LE(-nodeId, idx);
idx += 4;
var adjacent = linkMap[element.node];
if (adjacent) {
adjacent.forEach(function (element) {
buf.writeInt32LE(element, idx);
idx += 4;
});
}
});
fs.writeFileSync('links.bin', buf);
}