-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathomegga.plugin.ts
More file actions
executable file
·602 lines (527 loc) · 16.9 KB
/
omegga.plugin.ts
File metadata and controls
executable file
·602 lines (527 loc) · 16.9 KB
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
import OmeggaPlugin, { OL, PC, PS } from 'omegga';
import fs from 'fs';
import fetch from 'node-fetch';
import path from 'path';
import util from 'util';
const exec = util.promisify(require('child_process').exec);
import { PNG } from 'pngjs';
// path in which images are downloaded
const DOWNLOAD_FOLDER = path.join(__dirname, '../downloads');
// path to the heightmap binary
const HEIGHTMAP_BIN = path.join(__dirname, '../lib/heightmap');
const yellow = str => `<color=\\"ffff00\\">${str}</>`;
type Config = {
'only-authorized': boolean;
'authorized-users': { id: string; name: string }[];
cooldown: number;
'max-size': number;
'max-filesize': number;
'quilt-mode': boolean;
'quilt-size': number;
};
type Quilt =
| {
version: 1;
init: boolean;
size: number;
owners: {
images: number;
name: string;
id: string;
tiles: number;
index: number;
}[];
images: {
owner: number;
index: number;
area: [number, number][];
}[];
image_count: number;
owner_count: number;
grid: Record<string, number>;
}
| Record<string, never>;
type Storage = {
quilt: Quilt;
[key: string]: any;
};
export default class Img2Brick implements OmeggaPlugin<Config, Storage> {
omegga: OL;
config: PC<Config>;
store: PS<Storage>;
constructor(omegga: OL, config: PC<Config>, store: PS<Storage>) {
this.omegga = omegga;
this.config = config;
this.store = store;
}
quilt: Quilt;
async init() {
this.omegga
.on('chatcmd:img', (name, ...args) => {
const url = args.join(' ');
this.convert(name, url);
})
.on('chatcmd:img:tile', (name, ...args) => {
const url = args.join(' ');
this.convert(name, url, { tile: true });
})
.on('chatcmd:img:micro', (name, ...args) => {
// micro mode not enabled when quilt mode is enabled
if (this.config['quilt-mode']) return;
const url = args.join(' ');
this.convert(name, url, { micro: true });
})
.on('chatcmd:img:quilt-reset', async name => {
if (!this.omegga.getPlayer(name).isHost) return;
try {
const confSize = Math.max(8, this.config['quilt-size']);
this.quilt = {
version: 1,
init: true,
size: confSize,
owners: [],
images: [],
image_count: 0,
owner_count: 0,
grid: {},
};
this.saveQuilt();
this.omegga.broadcast(
'"reset quilt - make sure all bricks are cleared"'
);
} catch (e) {
this.omegga.broadcast('"error resetting quilt"');
}
})
.on('chatcmd:img:quilt-fix', async (name, all) => {
if (!this.isAuthorized(name)) return;
try {
const pos = await this.omegga.getPlayer(name).getPosition();
this.omegga.broadcast(
`"${this.fixQuilt([pos[0], pos[1]], all === 'all')}"`
);
} catch (e) {
console.log('err', e);
// player probably doesn't exist
}
})
.on('chatcmd:img:quilt-info', this.cmdQuiltInfo.bind(this))
.on('chatcmd:img:quilt-preview', this.cmdQuiltPreview.bind(this));
this.quilt = (await this.store.get('quilt')) || {};
}
async stop() {
try {
await this.store.set('quilt', this.quilt);
} catch (e) {
console.log(e, this.quilt);
}
}
// check if a name is authorized
isAuthorized(name) {
const player = this.omegga.getPlayer(name);
return (
player.isHost() ||
this.config['authorized-users'].some(p => player.id === p.id)
);
}
// get quilt info for the below image
cmdQuiltInfo(name, all) {
if (!this.quilt.init || !this.config['quilt-mode']) return;
const isAll = all === 'all' && this.isAuthorized(name);
const percent = n => yellow(Math.round(n * 100) + '%');
if (isAll) {
for (const owner of this.quilt.owners) {
this.omegga.broadcast(
`"<color=\\"ccccff\\">${owner.name}</>: ${yellow(
owner.images
)} images (${percent(
owner.images / this.quilt.images.length
)}), ${yellow(owner.tiles)} tiles (${percent(
owner.tiles / Object.keys(this.quilt.grid).length
)})"`
);
}
} else {
const owner = this.quilt.owners.find(o => o.name === name);
if (!owner) return;
this.omegga.broadcast(
`"You've contributed ${yellow(owner.images)} images (${percent(
owner.images / this.quilt.images.length
)}), ${yellow(owner.tiles)} tiles (${percent(
owner.tiles / Object.keys(this.quilt.grid).length
)})"`
);
}
}
// load bricks in over images owned by this player
async cmdQuiltPreview(name, arg) {
try {
if (!this.quilt.init || !this.config['quilt-mode']) return;
if (!this.isAuthorized(name)) return;
const say = msg => this.omegga.broadcast(`"${msg}"`);
const isAll = arg === 'all';
const isBroken = arg === 'broken';
// align to quilt grid
const quiltSize = this.quilt.size;
const load = (positions, owner?) => {
owner = owner || this.omegga.getPlayer(name);
this.omegga.loadSaveData({
brick_owners: [owner],
brick_assets: ['PB_DefaultTile'],
bricks: positions.map(([x, y]) => ({
owner_index: 1,
size: [quiltSize * 5, quiltSize * 5, 2],
position: [
(x * 2 + 1) * quiltSize * 5,
(y * 2 + 1) * quiltSize * 5,
200,
],
})),
});
};
let [x, y] = await this.omegga.getPlayer(name).getPosition();
x = Math.floor(x / quiltSize / 10);
y = Math.floor(y / quiltSize / 10);
const imageIndex = this.quilt.grid[[x, y].join(',')];
if (typeof imageIndex === 'undefined')
return say('not over an existing image');
if (isBroken) {
load(
Object.keys(this.quilt.grid)
.filter(i => this.quilt.grid[i] === -1)
.map(i => i.split(',').map(Number))
);
return say('loading all single cells');
}
const image = this.quilt.images.find(i => i.index === imageIndex);
if (imageIndex === -1 || !image) {
load([[x, y]]);
return say('ownerless tile ' + imageIndex);
}
const owner = this.quilt.owners.find(o => o.index === image.owner);
if (isAll) {
console.log(
this.quilt.images
.filter(i => i.owner === owner.index)
.flatMap(i => i.area)
);
load(
this.quilt.images
.filter(i => i.owner === owner.index)
.flatMap(i => i.area),
owner
);
} else {
load(image.area, owner);
return say('tile ' + imageIndex);
}
} catch (e) {
console.error(e);
}
}
// debounced update of quilt data
saveQuilt() {
this.store.set('quilt', this.quilt);
}
// check if the entry is valid for this quilt
checkQuilt(x, y, w, h) {
const confSize = Math.max(8, this.config['quilt-size']);
if (!this.quilt.init) {
this.quilt = {
version: 1,
init: true,
size: confSize,
owners: [],
images: [],
image_count: 0,
owner_count: 0,
grid: {},
};
}
// check if current quilt size can divide old quilt size
// (you can decrease quilt size by multiples but not increase)
if (this.quilt.size % confSize !== 0)
throw 'new quilt size does not match existing quilt - please reset';
// build quilt area and check if there's overlap
const area = [];
for (let i = 0; i < w; i++) {
for (let j = 0; j < h; j++) {
// add the cell to the area array
area.push([x + i, y + j]);
// check if there's an owner in this grid section
if (typeof this.quilt.grid[[x + i, y + j].join(',')] !== 'undefined')
throw 'image overlaps with another section of quilt';
}
}
return area;
}
// get an image's position adjusted for quilt size
// error if there is quilt overlap
async getSaveOffset(
[x, y, z],
[width, height],
player,
{ micro = false } = {}
) {
// if it's not quilt mode - use default behavior
if (!this.config['quilt-mode']) {
return [
{
offX: x - width * (micro ? 1 : 5),
offY: y - height * (micro ? 1 : 5),
offZ: Math.max(z - 26, 0),
},
{},
];
}
// align to quilt grid
const quiltSize = this.quilt.size;
x = Math.floor(x / quiltSize / 10);
y = Math.floor(y / quiltSize / 10);
// check image dimensions
if (width % quiltSize !== 0 || height % quiltSize !== 0)
throw `image does not fit ${quiltSize}x quilt grid (${width}x${height})`;
// get width/height in quilt units
width = Math.floor(width / quiltSize);
height = Math.floor(height / quiltSize);
// check for overlap, initialize quilt
const area = this.checkQuilt(x, y, width, height);
// return position snapped to grid
return [
{
offX: x * quiltSize * 10,
offY: y * quiltSize * 10,
offZ: 1,
},
{
owner: player,
area,
},
] as [
{ offX: number; offY: number; offZ: number },
{ owner: any; area: any }
];
}
// update the quilt
updateQuilt({ owner, area }) {
// find the quilt owner
let quiltOwner = this.quilt.owners.find(o => o.id === owner.id);
// add a new one
if (!quiltOwner) {
quiltOwner = {
...owner,
index: this.quilt.owner_count++,
tiles: 0,
images: 0,
};
this.quilt.owners.push(quiltOwner);
}
// update owner stats
quiltOwner.tiles += area.length;
quiltOwner.images++;
const ownerIndex = quiltOwner.index;
const imageIndex = this.quilt.image_count++;
// add the image data to the quilt
const image = {
owner: ownerIndex,
index: imageIndex,
area,
};
this.quilt.images.push(image);
// tell the quilt that this area is occupied by this image
for (const cell of area) {
this.quilt.grid[cell] = imageIndex;
}
// save the quilt
this.saveQuilt();
}
// remove entries from the quilt
fixQuilt([x, y], all) {
if (!this.quilt.init) return 'quilt not initialized';
// align to quilt grid
const quiltSize = this.quilt.size;
x = Math.floor(x / quiltSize / 10);
y = Math.floor(y / quiltSize / 10);
const imageIndex = this.quilt.grid[[x, y].join(',')];
if (typeof imageIndex === 'undefined') return 'not over an existing image';
const image = this.quilt.images.find(i => i.index === imageIndex);
if (imageIndex === -1 || !image) {
delete this.quilt.grid[[x, y].join(',')];
return 'cleared single tile';
}
const { owner: ownerIndex, area } = image;
const owner = this.quilt.owners.find(o => o.index === ownerIndex);
// remove every cell and image owned by this owner
if (all) {
for (const cell in this.quilt.grid) {
if (this.quilt.grid[cell] === ownerIndex) delete this.quilt.grid[cell];
}
// remove all images from this quilt
this.quilt.images = this.quilt.images.filter(i => i.owner !== ownerIndex);
return `Removed ${yellow(owner.tiles)} tiles, ${yellow(
owner.images
)} images by ${owner.name}`;
} else {
// remove just the cells in the image area
for (const cell of area) {
if (this.quilt.grid[cell.join(',')])
delete this.quilt.grid[cell.join(',')];
}
// remove the image from the images list
this.quilt.images.splice(imageIndex, 1);
// remove the metrics from the owner
owner.tiles -= area.length;
owner.images--;
return `Removed ${yellow(area.length)} tiles by ${owner.name}`;
}
}
// convert an image url into an in-game save at the player with a specified name's position
async convert(name, url, { tile = false, micro = false } = {}) {
if (url.length < 3) return;
if (this.config['quilt-mode']) {
tile = false;
micro = false;
}
// authorization check
const isAuthorized = this.isAuthorized(name);
if (this.config['only-authorized'] && !isAuthorized) return;
// check if player exists
const player = this.omegga.getPlayer(name);
if (!player) return;
// cooldown check for unauthorized players
if (!isAuthorized) {
const now = Date.now();
if (
((await this.store.get('cooldown_' + player.id)) || 0) +
Math.max(this.config['cooldown'], 0) * 1000 >
now
) {
return;
}
await this.store.set('cooldown_' + player.id, now);
}
// get player position
const pos = await player.getPosition();
// file output settings
const filename = name + '.png';
const filepath = path.join(DOWNLOAD_FOLDER, filename);
const savename = `img2brick_${name}`;
const destpath = path.join(this.omegga.savePath, savename + '.brs');
// download and run the heightmap
try {
// download the png
console.info(name, 'DL =>', url);
await this.downloadFile(url, filepath);
// check if it's a valid png
const [width, height] = await this.checkPNG(filepath, isAuthorized);
console.info(name, 'OK =>', filename, `(${width} x ${height})`);
// get the image's position (or quilt position)
const [savePos, quiltInsert] = await this.getSaveOffset(
pos,
[width, height],
player,
{ micro }
);
// convert the heightmap
await this.runHeightmap(filepath, destpath, {
tile,
micro,
name,
id: player.id,
});
console.log('[debug]', this.config['quilt-mode'], savePos);
// if quilt mode is enabled, update the quilt
if (this.config['quilt-mode']) {
this.omegga.loadBricks(savename, { ...savePos, quiet: true });
this.updateQuilt(quiltInsert as any);
} else {
// load the bricks
this.omegga.loadBricksOnPlayer(savename, player);
}
} catch (e) {
this.omegga.broadcast(`"error: ${e}"`);
console.error(e);
}
}
// download a png at a url to a file
async downloadFile(uri, filename) {
const headRes = await fetch(uri, { method: 'HEAD' });
if (headRes.headers.get('content-type') !== 'image/png')
throw 'wrong response format (expected image/png)';
const maxFileSize = this.config['max-filesize'];
// check file size
if (
headRes.headers.has('content-length') &&
!(Number(headRes.headers.get('content-length')) < maxFileSize)
)
throw `image file too large (${headRes.headers.get(
'content-length'
)}B > ${maxFileSize}B)`;
// go ahead and download the image.. we're really hoping they didn't lie in the content-type
const req = await fetch(uri, { size: maxFileSize });
const dest = fs.createWriteStream(filename);
const promise = new Promise((resolve, reject) => {
dest.on('close', resolve);
dest.on('error', err => {
console.error(err);
reject('error writing file');
});
});
req.body.pipe(dest);
await promise;
}
// check if a png file has a valid size
checkPNG(filename, ignore = false) {
const maxSize = this.config['max-size'];
return new Promise<[number, number]>((resolve, reject) => {
fs.createReadStream(filename)
.pipe(new PNG())
.on('error', () => reject('error parsing png'))
.on('parsed', function () {
if (!ignore && (this.width > maxSize || this.height > maxSize))
return reject(
`image dimensions too large (${Math.max(
this.height,
this.width
)}px > ${maxSize}px)`
);
return resolve([this.width, this.height]);
});
});
}
// run the heightmap binary given an input file
async runHeightmap(
filename: string,
destpath: string,
{
tile = false,
micro = false,
id,
name,
}: { tile?: boolean; micro?: boolean; id: string; name: string }
) {
try {
const command =
HEIGHTMAP_BIN +
` -o "${destpath}" --cull --owner_id "${id}" --owner "${name}" --img "${filename}"${
tile ? ' --tile' : micro ? ' --micro' : ''
}`;
if (this.omegga.verbose) console.info(command);
const { stdout } = await exec(command, {});
if (this.omegga.verbose) console.log(stdout);
const result = stdout.match(/Reduced (\d+) to (\d+) /);
if (!stdout.match(/Done!/) || !result)
throw 'could not finish conversion';
// potentially check reduction size
const original = Number(result[1]);
const reduced = Number(result[2]);
console.log('Reduced', original, 'to', reduced);
return true;
} catch (err) {
const { cmd, stderr } = err;
console.error('command: ' + cmd);
console.error(stderr);
throw 'conversion software failed';
}
}
}