-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathindex.js
362 lines (308 loc) · 9.47 KB
/
index.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
var express = require('express');
var Canvas = require('canvas');
var Image = Canvas.Image;
var app = express();
var moment = require('moment');
var fs = require('fs');
var util = require('util');
var mkdirp = require('mkdirp');
var getDirName = require('path').dirname;
var enableCache = false;
var cp = require('child_process').exec;
var bodyParser = require('body-parser');
var imgCache = {};
app.set('port', (process.env.PORT || 5000));
app.use('/public', express.static('public'));
app.use('/editor', express.static('public'));
app.use('/region-raw-img', express.static('region-raw-img'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
app.get('/', function(req,res) {
res.redirect('/editor/');
})
app.get('/images', function(req, res) {
var images = fs.readdirSync('./region-raw-img/');
res.send(images);
})
app.get('/overlay/:region', function(req, res) {
try {
var region = req.params.region;
var img = JSON.parse(fs.readFileSync('./regions/' + region + '.json')).image;
var overlay = process.cwd() + '/region-raw-img/' + img;
res.sendFile(overlay);
}
catch(err) {
console.log(err.stack);
}
})
app.put('/regions/:name', function(req, res) {
var name = req.params.name;
var body = req.body;
console.log(name, body);
try {
fs.writeFileSync('./regions/'+name+'.json', JSON.stringify(body));
}
catch(err) {
console.log(err.stack);
res.sendStatus(500);
}
res.sendStatus(200);
})
app.post('/regions/:name', function(req, res) {
var name = req.params.name;
var body = req.body;
console.log(name, body);
try {
fs.writeFileSync('./regions/'+name+'.json', JSON.stringify(body));
}
catch(err) {
console.log(err.stack);
res.sendStatus(500);
}
res.sendStatus(200);
})
app.get('/regions', function(req, res) {
try {
var regions = fs.readdir('./regions/', function(err, files) {
console.log(files)
var results = [];
for(var i in files) {
if(/\.json$/i.test(files[i])) {
var meta = './regions/'+files[i];
console.log('read region meta :', meta);
var region = JSON.parse(fs.readFileSync(meta));
region.name = String(files[i]).replace(/\.json$/i,'');
results.push(region);
}
}
res.send(results);
})
// res.send(files)
}catch(err) {
console.log(err.stack);
}
})
app.post('/bounds/:region', function(req, res) {
var region = req.params.region;
console.log(region,req.body)
try {
fs.writeFileSync('./regions/'+region+'.json', JSON.stringify(req.body));
}catch(err) {
console.log(err.stack);
}
res.sendStatus(200);
})
app.get('/bounds/:region', function(req, res) {
var region = req.params.region;
try {
var data = fs.readFileSync('./regions/' + region + '.json');
res.send(data);
} catch(err) {
console.log(err.stack);
}
})
app.delete('/tiles/:region', function(req,res) {
var region = req.params.region;
try {
deleteFolderRecursive('./regions/'+region+'/debug/', function() {
res.send(200)
});
} catch(err) {
console.log(err.stack);
}
})
app.get('/cache/:enable', function(req, res) {
if(req.params.enable == '1') {
enableCache = true;
}
else
enableCache = false;
res.send(200);
})
app.get('/lookup/:z/:x/:y', function(req, res) {
var x = req.params.x,
y = req.params.y,
z = req.params.z;
res.send(tileToLatLng(x,y,z));
});
app.get('/tiles/debug/:region/:z/:x/:y/', handleTileRequestDebug);
app.get('/tiles/:region/:z/:x/:y/', handleTileRequest);
function handleTileRequestDebug(req, res) {
req.params.debug = true;
handleTileRequest(req,res);
}
function handleTileRequest(req, res) {
try {
var {x, y, z, region, debug} = req.params;
console.log(`make tile: ${region}/${z}/${x}/${y}`);
let tilePath = `./regions/${region}/${debug ? 'debug/' : ''}${z}/${x}${y}.png`;
fs.exists(tilePath, (ext) => {
if(ext) {
console.log('found tile', tilePath);
fs.readFile(tilePath, (err, data) => {
res.type('image/png').send(data);
});
}
else {
createTileFromRawImage(region, x, y, z, debug, function(bytes) {
console.log('send tile')
res.type('image/png').send(bytes);
});
}
});
} catch(err) {
console.log(err.stack)
}
}
app.get('/base/:z/:x/:y', function(req,res) {
var request = require('request');
var x = req.params.x;
var y = req.params.y;
var z = req.params.z;
var pipe = req.pipe(request.post('http://mt1.google.com/vt/lyrs=m@110&hl=pl&x='+x+'&y='+y+'&z='+ z));
var response = [];
pipe.on('data',function(chunk) {
response.push(chunk);
});
pipe.on('end',function() {
var res2 = Buffer.concat(response);
res.send(res2);
});
})
function tileToLatLng(x,y,z) {
let result = { lat : tileToLat(y,z), lng : tileToLong(x,z) };;
return result;
}
function tileToLong(x,z) { return (x/Math.pow(2,z)*360-180); }
function tileToLat(y,z) {
var n = Math.PI-2*Math.PI*y/Math.pow(2,z);
return (180/Math.PI*Math.atan(0.5*(Math.exp(n)-Math.exp(-n))));
}
function createTileFromRawImage(region, x, y, z, debug, cb) {
console.log('create tile :', region, x, y, z)
console.log('debug=',debug)
x = Math.floor(x);
y = Math.floor(y);
z = Math.floor(z);
fs.readFile(`./regions/${region}.json`, (err, data) => {
let bounds = [];
let img = '';
try {
bounds = JSON.parse(data).bounds;
img = JSON.parse(data).image;
console.log(bounds);
}
catch(err) {
console.log(err.stack);
return;
}
let sign = bounds[0].lat < 0 ? 1 : -1;
let tileBounds = [
tileToLatLng(x,y,z),
tileToLatLng(x+1,y,z),
tileToLatLng(x+1,y+1,z),
tileToLatLng(x,y+1,z)
];
if(imgCache[region]) {
render(null, imgCache);
}
else {
fs.readFile(`./region-raw-img/${img}`, render);
}
function render(err, data) {
if(err)
throw err;
let img = new Image;
img.src = data;
console.log(data.length)
console.log(img.width, 'x', img.height)
console.log(util.inspect(img, false, null))
console.log('mag bounds:',bounds);
console.log('tile bounds:', tileBounds);
let regionWidth = Math.abs(Math.abs(bounds[0].lng) - Math.abs(bounds[1].lng)),
regionHeight = Math.abs(Math.abs(bounds[1].lat) - Math.abs(bounds[2].lat));
console.log(`regionWidth=${regionWidth}, regionHeight=${regionHeight}`);
let tileWidth = Math.abs(tileBounds[0].lng - tileBounds[1].lng) * img.width /regionWidth,
tileHeight = Math.abs(tileBounds[1].lat - tileBounds[2].lat) * img.height /regionHeight;
console.log(`tileWidth=${tileWidth}, tileHeight=${tileHeight}`);
let tileImg = new Canvas(256, 256);
let originX = (Math.abs(tileBounds[0].lng) - Math.abs(bounds[0].lng))/regionWidth * img.width;
let originY = (Math.abs(tileBounds[0].lat) - Math.abs(bounds[0].lat))/regionHeight * img.height;
if(sign<0) {
originY = img.height - originY - 512 - img.height%256;
}
let ctx = tileImg.getContext('2d');
if( originX > img.width + tileWidth ||
originY > img.height + tileHeight ||
originY < -tileHeight -1 || originX < -tileWidth -1 ) {
console.log('OUTBOUND')
ctx.rect(0, 0, 256, 256);
ctx.fillStyle = '#F0F0F0';
ctx.fill();
ctx.fillStyle = '#222';
ctx.font = '16px Arial';
ctx.fillText('OUT OF BOUND', 128, 128);
var bytes = tileImg.toBuffer(undefined, 3, ctx.PNG_FILTER_NONE);
cb([])
return
}
else {
console.log(`fill size (${tileWidth}, ${tileHeight})`);
console.log(`project (${originX}, ${originY}, ${originX + tileWidth}, ${originY + tileHeight})`);
ctx.drawImage(img, originX, originY, tileWidth, tileHeight, 0, 0, 256, 256);
if(debug) {
drawText(ctx,{x,y,z}, originX,originY,tileWidth, tileHeight, z);
}
ctx.strokeRect(0, 0, 256, 256);
ctx.fillStyle = '#DDD';
}
var bytes = tileImg.toBuffer(undefined, 3, ctx.PNG_FILTER_NONE);
console.log('size', bytes.length);
var dir = `./regions/debug/${region}/${z}/${x}${y}.png`;
mkdirp(getDirName(dir), function (err) {
if (err)
console.log(err);
if(enableCache) {
fs.writeFile(dir, bytes, function(err) {
if(err)
console.log(err)
cb(bytes);
});
}
else {
cb(bytes);
}
});
}
});
}
function drawText(ctx,param, ox,oy, dx, dy, z) {
var {region,x,y,z} = param;
var info = `${region}: ${z}/${x}/${y}`;
var coords = 'from (' + [Math.round(ox), Math.floor(oy)].join(', ') + ')';
var coords2 = 'to (' + [Math.round(ox+dx), Math.floor(oy + dy)].join(', ') + ')';
ctx.font = '16px Arial';
ctx.fillStyle = '#333';
ctx.fillText(info, 8, 24);
ctx.fillText(coords, 8, 48);
ctx.fillText(coords2, 8, 64);
ctx.font = '64px Arial';
ctx.fillText(z + 'x', 144, 255);
}
var deleteFolderRecursive = function(path, cb) {
if( fs.existsSync(path) ) {
fs.readdirSync(path).forEach(function(file,index){
var curPath = path + "/" + file;
if(fs.lstatSync(curPath).isDirectory()) { // recurse
deleteFolderRecursive(curPath);
} else { // delete file
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(path);
}
cb()
};