-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.mjs
415 lines (386 loc) · 13.9 KB
/
index.mjs
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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
import fs from 'fs/promises';
import path from 'path';
import { availableParallelism } from 'os';
import readline from 'readline';
import sharp from 'sharp';
import ora from 'ora';
import dotenv from 'dotenv';
import { DateTime } from 'luxon';
import WorkerPromise, { activeWorkerCount, workerEvents } from './worker-promise.mjs';
dotenv.config();
const prompt = (textPrompt, defaultValue) => {
return new Promise((resolve) => {
const input = readline.createInterface({
input: process.stdin,
output: process.stdout
});
input.question(textPrompt, response => {
input.close();
if (response === '') {
response = undefined;
}
resolve(response ?? String(defaultValue));
});
});
};
let imagePath = process.env.IMAGE_PATH || process.argv[2];
if (!imagePath) {
imagePath = '../tarkov-dev-src-maps/interactive';
console.log(`IMAGE_PATH not set, defaulting to ${imagePath}`);
}
const minTileSize = process.env.MIN_TILE_SIZE || 100;
const maxTileSize = process.env.MAX_TILE_SIZE || 400;
const threadLimit = isNaN(process.env.THREAD_LIMIT) ? availableParallelism() : parseInt(process.env.THREAD_LIMIT);
const testOutput = Boolean(process.env.TEST_OUTPUT || false);
async function getTileSettings() {
const tileSettings = {
imagePath,
};
if ((await fs.lstat(imagePath)).isDirectory()) {
const imageExtensions = ['jpg', 'jpeg', 'png', 'webp'];
const files = await fs
.readdir(imagePath)
.then(files =>
files.filter(filename =>
imageExtensions.some(ext =>
filename.toLocaleLowerCase().endsWith(`.${ext}`)
)
)
);
if (files.length < 1) {
return Promise.reject(new Error(`The folder ${imagePath} does not contain any images`));
}
console.log('Select input image:');
for (let i = 0; i < files.length; i++) {
console.log(`${i + 1}. ${files[i]}`);
}
const index = await prompt(`[1-${files.length}]: `);
if (isNaN(index) || index < 1 || index > files.length) {
return Promise.reject(new Error(`${index} is an invalid input image selection`));
}
tileSettings.imagePath = path.join(imagePath, files[parseInt(index - 1)]);
}
tileSettings.mapName =
process.env.MAP_NAME ||
tileSettings.imagePath.substring(
tileSettings.imagePath.lastIndexOf(path.sep) + 1,
tileSettings.imagePath.lastIndexOf('.')
);
const newMapName = await prompt(`Output folder (${tileSettings.mapName}): `, tileSettings.mapName);
tileSettings.mapName = newMapName.replace(' ', '_');
let inputImage = sharp(tileSettings.imagePath, {
unlimited: true,
limitInputPixels: false
}).png();
let metadata = await inputImage.metadata();
console.log(`Image size: ${metadata.width}x${metadata.height}`);
tileSettings.rotation = await prompt('Rotate image 90, 180, or 270 degrees (0): ', 0);
if (tileSettings.rotation) {
tileSettings.rotation = tileSettings.rotation.trim();
if (!['0', '90', '180', '270'].includes(tileSettings.rotation)) {
return Promise.reject(new Error(`${tileSettings.rotation} is not a valid rotation`));
}
tileSettings.rotation = parseInt(tileSettings.rotation);
}
let fullSize = Math.max(metadata.width, metadata.height);
let tileSize = 0;
let tileConfig = {difference: Number.MAX_SAFE_INTEGER};
let tileResize = false;
tileLoop: for (let i = minTileSize; i <= maxTileSize; i++) {
for (let pow = 0; pow < 100; pow++) {
if (i * Math.pow(2, pow) === fullSize) {
tileConfig.size = i;
tileConfig.pow = pow;
tileConfig.difference = 0;
tileSize = i;
if (i > 200) {
break tileLoop;
}
}
}
}
if (!tileSize) {
tileResize = {
grow: {difference: Number.MAX_SAFE_INTEGER},
shrink: {difference: Number.MAX_SAFE_INTEGER}
};
for (let i = minTileSize; i <= maxTileSize; i++) {
for (let pow = 0; pow < 100; pow++) {
const resized = i * Math.pow(2, pow);
let resizeType = tileResize.grow;
if (resized < fullSize) {
resizeType = tileResize.shrink;
}
const diff = Math.abs(resized - fullSize);
if (diff < resizeType.difference) {
resizeType.size = i;
resizeType.pow = pow;
resizeType.difference = diff;
}
}
}
if (tileResize.grow.difference <= tileResize.grow.size) {
tileConfig = tileResize.grow;
} else {
tileConfig =
tileResize.grow.difference <= tileResize.shrink.difference
? tileResize.grow
: tileResize.shrink;
}
if (tileConfig.difference < Number.MAX_SAFE_INTEGER) {
tileSize = tileConfig.size;
} else {
tileSize = isNaN(process.env.TILE_SIZE)
? 256
: parseInt(process.env.TILE_SIZE);
}
}
if (tileResize) {
console.log(
`Image must be resized. Closest grow and shrink sizes for tiles ${minTileSize}-${maxTileSize}px:`
);
console.log(
`Grow: ${tileResize.grow.size}px tiles with ${
tileResize.grow.size * Math.pow(2, tileResize.grow.pow)
}px total size (+${
tileResize.grow.size * Math.pow(2, tileResize.grow.pow) -
fullSize
}px padding)`
);
console.log(
`Shrink: ${tileResize.shrink.size}px tiles with ${
tileResize.shrink.size * Math.pow(2, tileResize.shrink.pow)
}px total size (${
tileResize.shrink.size * Math.pow(2, tileResize.shrink.pow) -
fullSize
}px)`
);
}
const newTileSize = await prompt(`Tile size (${tileSize}): `, tileSize);
if (isNaN(newTileSize)) {
return Promise.reject(new Error(`${newTileSize} is not a valid tile size`));
}
if (parseInt(newTileSize) !== tileConfig.size) {
tileConfig.size = parseInt(newTileSize);
tileConfig.difference = Number.MAX_SAFE_INTEGER;
tileConfig.pow = 0;
for (let pow = 0; pow < 100; pow++) {
const diff = Math.abs(
tileConfig.size * Math.pow(2, pow) - fullSize
);
if (diff < tileConfig.difference) {
tileConfig.pow = pow;
tileConfig.difference = diff;
}
}
}
tileSettings.tileSize = tileConfig.size;
if (tileConfig.difference) {
tileSettings.resize = tileSize * Math.pow(2, tileConfig.pow);
}
let zoomLevels = 0;
for (let imageWidth = fullSize; imageWidth >= tileSize; imageWidth /= 2) {
zoomLevels++;
}
tileSettings.maxZoom = Math.min(
isNaN(process.env.MAX_ZOOM)
? zoomLevels
: parseInt(process.env.MAX_ZOOM),
zoomLevels - 1
);
tileSettings.minZoom = process.env.MIN_ZOOM || 0;
return tileSettings;
}
async function createTiles(options) {
const {
imagePath,
rotation,
resize,
tileSize,
minZoom,
maxZoom,
mapName,
} = options;
let inputImage = sharp(imagePath, {
unlimited: true,
limitInputPixels: false
}).png();
let metadata = await inputImage.metadata();
if (rotation) {
const rotateSpinner = ora(`Rotating image ${rotation} degrees`);
rotateSpinner.start();
inputImage = sharp(await inputImage.rotate(rotation).toBuffer(), {
unlimited: true,
limitInputPixels: false
});
if (testOutput) {
rotateSpinner.suffixText = 'saving test output...';
await inputImage.toFile('./output/test_rotated.jpg');
rotateSpinner.suffixText = '';
}
rotateSpinner.succeed();
if (rotation === 90 || rotation === 270) {
const h = metadata.height;
metadata.height = metadata.width;
metadata.width = h;
}
}
let fullSize = Math.max(metadata.width, metadata.height);
if (resize) {
const resizeSpinner = ora();
if (resize < fullSize) {
resizeSpinner.start(
`Shrinking source image to fit ${resize}x${resize}`
);
inputImage = sharp(
await inputImage
.resize({
width: resize,
height: resize,
fit: sharp.fit.contain,
position: sharp.gravity.northwest,
background: {r: 1, g: 0, b: 0, alpha: 0}
})
.toBuffer()
);
} else {
resizeSpinner.start(
`Padding source image to fit ${resize}x${resize}`
);
const xPadding = resize - metadata.width;
const yPadding = resize - metadata.height;
const top = Math.ceil(yPadding / 2);
const bottom = Math.floor(yPadding / 2);
const left = Math.ceil(xPadding / 2);
const right = Math.floor(xPadding / 2);
inputImage = sharp(
await inputImage
.extend({
top,
right,
bottom,
left,
background: {r: 1, g: 0, b: 0, alpha: 0}
})
.toBuffer(),
{
unlimited: true,
limitInputPixels: false
}
);
}
if (testOutput) {
resizeSpinner.suffixText = 'saving test output...';
await inputImage.toFile('./output/test_resized.jpg');
resizeSpinner.suffixText = '';
}
resizeSpinner.succeed();
fullSize = resize;
}
await fs.mkdir(`output/${mapName}`).catch(error => {
if (error.code !== 'EEXIST') {
console.log(error);
}
});
await fs.writeFile(
`output/${mapName}/config.json`,
JSON.stringify(
{
tileSize: tileSize,
minZoom: minZoom,
maxZoom: maxZoom
},
null,
4
)
);
let totalTiles = 0;
for (let z = minZoom; z <= maxZoom; z++) {
totalTiles += Math.pow((tileSize * Math.pow(2, z)) / tileSize, 2);
}
const tileCheck = async () => {
if (activeWorkerCount() >= threadLimit) {
return new Promise(resolve => {
workerEvents.once('workerEnded', resolve);
});
}
return Promise.resolve();
};
let completedTiles = 0;
const zoomSpinner = ora({text: mapName, prefixText: '0.00%'});
zoomSpinner.start();
const startTime = DateTime.now();
const inputImageBuffer = (await inputImage.toBuffer()).buffer;
for (let z = minZoom; z <= maxZoom; z++) {
const scaledSize = tileSize * Math.pow(2, z);
zoomSpinner.suffixText = `| z ${z}/${maxZoom} Resizing to ${scaledSize}`;
const workerResult = await new WorkerPromise('resize-worker.mjs').start({tileSize, z, image: inputImageBuffer});
await fs.mkdir(`output/${mapName}/${z}`).catch(error => {
if (error.code !== 'EEXIST') {
console.log(error);
}
});
for (let x = 0; x < scaledSize / tileSize; x++) {
await fs.mkdir(`output/${mapName}/${z}/${x}`).catch(error => {
if (error.code !== 'EEXIST') {
console.log(error);
}
});
for (let y = 0; y < scaledSize / tileSize; y++) {
new WorkerPromise('tile-worker.mjs').start({
mapName,
tileSize,
x,
y,
z,
image: workerResult.image,
}).then(() => {
zoomSpinner.suffixText = `| z ${z}/${maxZoom} | x ${x}/${
scaledSize / tileSize - 1
} | y ${y}/${scaledSize / tileSize - 1}`;
completedTiles++;
zoomSpinner.prefixText = `${(
Math.round(
(completedTiles / totalTiles) * 10000
) / 100
).toFixed(2)}%`;
});
await tileCheck();
}
}
zoomSpinner.suffixText = '';
zoomSpinner.prefixText = '';
}
zoomSpinner.suffixText = `completed ${DateTime.now().toRelative({ base: startTime})}`;
zoomSpinner.succeed();
}
(async () => {
await fs.mkdir('output').catch(error => {
if (error.code !== 'EEXIST') {
console.log(error);
}
});
const tileSettings = [];
while (true) {
try {
tileSettings.push(await getTileSettings());
} catch (error) {
console.log(error.message);
}
if (tileSettings.length > 0) {
console.log(`Queued tiles: ${tileSettings.map(setting => setting.mapName).join(', ')}`);
}
const again = (await prompt(`Do you want to queue another tileset? (n): `, 'n'))?.trim().toLocaleLowerCase();
if (!again?.startsWith('y')) {
break;
}
}
for (const settings of tileSettings) {
try {
await createTiles(settings);
} catch (error) {
console.log(`Error creating ${settings.mapName} tiles`);
console.log(error);
}
}
})();