-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathCDDA_Map_extension.mjs
4349 lines (4026 loc) · 208 KB
/
CDDA_Map_extension.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
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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/// <reference types="@mapeditor/tiled-api" />import_map
//ChibiUltica
//0x400 | 0x2000 | 0x4000 qdir filter for dir no dot and dotdot
//0x002 | 0x2000 | 0x4000 qdir filter for file no dot and dotdot
//JSON.stringify(m, null, 2) sringify with formatting
if(tiled.versionLessThan(`1.10.00`)){
tiled.log(`WARNING: version less than 1.10.00`)
}
var verbose = false
var use_pretty_symbols = false
var pathToExtras = `${tiled.extensionsPath}/cdda_map_extension_extras`
var pathToProjectTilesets = `${FileInfo.path(tiled.projectFilePath)}/tilesets`
var pathToProjectMaps = `${FileInfo.path(tiled.projectFilePath)}/maps`
const configfilename = "cdda_tiled_extension_config.json";
const mapLayerTypes = ["terrain", "furniture", "traps", "vehicles"] // , "items"
const entityLayerTypes = ["place_items", "place_item", "place_loot", "place_monsters", "place_vehicles", "place_fields", "place_zones"]
const flags = ["ERASE_ALL_BEFORE_PLACING_TERRAIN", "ALLOW_TERRAIN_UNDER_OTHER_DATA", "NO_UNDERLYING_ROTATE", "AVOID_CREATURES"]
const utf_ramps = {
"utf8_shortlist" : `#$%&'()*+,-.:;<=>@ABCDEFGHIJKLMNOPQRSTUVWXYZ^_abcdefghijklmnopqrstuvwxyz{|}~¡¢£¤¥¦§©ª«¬®¯°±²³µ¶·¹º»¼½¾¿0123456789`,
"greyscale_ramp" : `$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/|()1{}[]?-_+~<>i!lI;:,^'.`,
"us_keyboard" : {
"groundcover": ` ._,':-;`,
"soil": `, ._':-;`,
"floor" : ` ._,':-;`,
"sidewalk" : `s.,='_`,
"pavement" : `_.~=',`,
"pavement_y": `y:,`,
"thconc_y": `y:,`,
"column" : `I1`,
"pillar" : `I1`,
"solid" : `#@|-I!`,
"wall_wood" : `wW|I`,
"wall_log" : `wW|I`,
"wall" : `|#-I!`,
"mound" : `DO#()%`,
"fence" : `fF%#Ŧ`,
"door_glass" : `gG:+D`,
"door_locked" : `*L+D`,
"door" : `+D-`,
"open": `-'o`,
"gate": `gG+-`,
"t_door_metal_locked": `=M`,
"window_open" : `oO'wW`,
"window" : `wWoOvV`,
"downspout" : `^4`,
"_up" : `<^`,
"_down" : `>v`,
"water" : `Ww~≈`,
"sewage" : `~wW`,
"box" : `xX`,
"f_crate_o" : `oO`,
"f_crate_c" : `xX`,
"sand" : `s~`,
"telep" : `o`,
"toilet" : `tT`,
"table" : `ntT`,
"locker" : `lL`,
"rack" : `rRH`,
"sink" : `Ss`,
"chair" : `hc`,
"sofa" : `H?`,
"bench" : `bB`,
"bookcase" : `BR{`,
"dresser" : `dD`,
"flower" : `!i`,
"tree" : `7/T!`,
"bush" : `$#%/&`,
"underbrush" : `$#%/&`,
"shrub" : `$#%/&`,
"rubble" : `rRzZ^&#`,
"console" : `6X`,
"t_null" : `│`
},
"pretty": {
"t_soil": `░`,
"wall": `▓▒░$@B%&WM#/|(){}[]!I`,
"fence": `‡ǂ#H`,
"door": `D`,
"window": `o◦`,
"pavement": `'^,:;_-+`,
"sidewalk": `'^,:;_-+`,
"floor": `'^,:;_-+`,
"_up": `<Λ↑⇑⇡⇧`,
"_down": `>V↓⇓⇣⇩`,
"ladder": `ʭΞ`,
"water": `~≈w`,
"box": `□▫⬞`,
"sandbag": `⬝▪■`,
"trap": `♣♠♦*ϗ`,
"telep": `◌●◙`,
"table": `πΠ`,
"chair": `h`,
"others": `⧫ᒤᒦᒌᕈҐᖗᖙᖘᖚ⅄♪♫ʬ♥♣♠♦`
}
}
const no_id_objects = ["rows", "palettes", "fill_ter", "//", "id", "type"]
// let checkmarkImage = new Image();
// checkmarkImage.loadFromData(Base64.decode("PHN2ZyB3aWR0aD0iMTkuMjEzMTUiIGhlaWdodD0iMTguMjk0OTk0IiB2ZXJzaW9uPSIxLjAiPjxnIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0xOTIuOTA1LC01MTYuMDIwNjQpIj48cGF0aCBzdHlsZT0iZmlsbDojMDBmZjAwIiBkPSJNIDE5Ny42Nzk2OCw1MzQuMzE1NjMgQyAxOTcuNDA0NjgsNTM0LjMxMjA4IDE5Ni4yMTc4OCw1MzIuNTM3MTkgMTk1LjA0MjM0LDUzMC4zNzE0MyBMIDE5Mi45MDUsNTI2LjQzMzY4IEwgMTkzLjQ1OTAxLDUyNS44Nzk2OCBDIDE5My43NjM3MSw1MjUuNTc0OTcgMTk0LjU4MjY5LDUyNS4zMjU2NyAxOTUuMjc4OTYsNTI1LjMyNTY3IEwgMTk2LjU0NDksNTI1LjMyNTY3IEwgMTk3LjE4MTI5LDUyNy4zMzA3NiBMIDE5Ny44MTc2OCw1MjkuMzM1ODQgTCAyMDIuODgyMTUsNTIzLjc5NDUxIEMgMjA1LjY2NzYxLDUyMC43NDY3OCAyMDguODg1MjIsNTE3Ljc1MDg1IDIxMC4wMzIzOSw1MTcuMTM2OTEgTCAyMTIuMTE4MTUsNTE2LjAyMDY0IEwgMjA3LjkwODcxLDUyMC44MDI4MiBDIDIwNS41OTM1MSw1MjMuNDMzMDIgMjAyLjQ1NzM1LDUyNy41NTA4NSAyMDAuOTM5NDcsNTI5Ljk1MzU1IEMgMTk5LjQyMTU5LDUzMi4zNTYyNSAxOTcuOTU0NjgsNTM0LjMxOTE5IDE5Ny42Nzk2OCw1MzQuMzE1NjMgeiIvPjwvZz48L3N2Zz4="), "svg");
// let checkMark = dialog.addImage('', checkmarkImage);
var skipOverwrite = true;
var overwriteExisting = true;
var config = {};
// var imageCache = {};
var cache = {};
const timers = {};
function startTimer(name) {
if (!name) {
tiled.error('Timer name is required');
return;
}
timers[name] = new Date().getTime();
}
function stopTimer(name) {
if (!timers[name]) {
tiled.error(`Timer "${name}" not found`);
return;
}
const duration = new Date().getTime() - timers[name];
tiled.log(`Timer "${name}": ${duration} ms`);
delete timers[name];
}
// // Usage example:
// startTimer('part1');
// // Your script part 1
// stopTimer('part1');
// startTimer('part2');
// // Your script part 2
// startTimer('nested');
// // Your nested script part
// stopTimer('nested');
// stopTimer('part2');
const cte = { // helper functions
adjustTSJ: (filepath) => {
let json = JSONread(filepath);
json.tileheight = 32
json.tilewidth = 32
var update_json = new TextFile(filepath, TextFile.WriteOnly);
update_json.write(JSON.stringify(json, null, 2));
update_json.commit();
},
replaceNewlines: function replaceNewlines(str) {
// Use the regular expression to find objects with 4 or fewer entries
var regex = /\[\n(?:.*?,(\n)){0,4}(?:.*?(\n)).*?],?/gm;
var matches = str.match(regex);
// Replace newlines in each match with spaces
if (matches) {
matches.forEach((match) => {
str = str.replace(match, match.replace(/\n\t*/g, " ")).trim();
});
}
// Use the regular expression to find objects with 4 or fewer entries
regex = /\{\n(?:.*?,(\n)){0,4}(?:.*?(\n)).*?},?/gm;
matches = str.match(regex);
// Replace newlines in each match with spaces
if (matches) {
matches.forEach((match) => {
str = str.replace(match, match.replace(/\n\t*/g, " ")).trim();
});
}
// Return the updated string
return str;
},
folderPicker: (filepath, title) => {
let dialog = new Dialog();
title ? dialog.windowTitle = title : dialog.windowTitle;
dialog.addLabel(`Select any file within the desired folder.`)
dialog.addNewRow()
let cont = false;
// if(dialog===undefined){dialog = new Dialog();}
filepath === undefined ? filepath = FileInfo.fromNativeSeparators(FileInfo.path(tiled.projectFilePath)) : filepath = FileInfo.fromNativeSeparators(filepath);
let newFilepath;
let fileEdit = dialog.addFilePicker();
dialog.addNewRow();
fileEdit.fileUrl = filepath;
let acceptButton = dialog.addButton(`Accept`);
let cancelButton = dialog.addButton(`Cancel`);
fileEdit.fileUrlChanged.connect(() => {
fileEdit.fileUrl = FileInfo.path(fileEdit.fileUrl)
})
acceptButton.clicked.connect(function () {
dialog.accept();
});
cancelButton.clicked.connect(function () {
dialog.reject();
});
dialog.accepted.connect(() => {
if (tiled.platform === "windows") {
newFilepath = fileEdit.fileUrl.toString().replace(/^file\:\/\/\//, "");
} else {
newFilepath = fileEdit.fileUrl.toString().replace(/^file\:\//, "");
}
cont = true;
});
if(verbose){tiled.log(newFilepath)}
dialog.show();
dialog.exec();
return cont ? newFilepath : false;
},
filePicker: (filepath, title) => {
let dialog = new Dialog();
title ? dialog.windowTitle = title : dialog.windowTitle;
let cont = false;
filepath === undefined ? filepath = FileInfo.fromNativeSeparators(FileInfo.path(tiled.projectFilePath)) : filepath = FileInfo.fromNativeSeparators(filepath);
let newFilepath;
let fileEdit = dialog.addFilePicker();
dialog.addNewRow();
fileEdit.fileUrl = filepath;
let cancelButton = dialog.addButton(`Cancel`);
let acceptButton = dialog.addButton(`Accept`);
acceptButton.clicked.connect(function () {
dialog.accept();
});
cancelButton.clicked.connect(function () {
dialog.reject();
});
dialog.accepted.connect(() => {
newFilepath = cte.removeFileStringFromFileUrl(fileEdit.fileUrl.toString());
cont = true;
});
dialog.show();
dialog.exec();
return cont ? newFilepath : false;
},
getTileXY: function getTileXY(tile) {
let tileset = tile.asset;
if (tileset.isCollection) { return [[0, tile.width], 0, tile.height]; }
let x = [parseInt(((tile.id * tileset.tileWidth) % tileset.imageWidth), 10), parseInt((tile.id * tileset.tileWidth) % tileset.imageWidth + tileset.tileWidth, 10)]
let y = [parseInt(Math.floor((tile.id * tileset.tileWidth) / tileset.imageWidth) * tileset.tileHeight, 10), parseInt(Math.floor((tile.id * tileset.tileWidth) / tileset.imageWidth) * tileset.tileHeight + tileset.tileHeight, 10)]
tileset = undefined;
return [x, y];
},
cropImage: function cropImage(image, importX, importY) {
if (!cache.hasOwnProperty(image)) {
cache[image] = new Image(image);
}
// let originalImage = new Image(image);
let croppedImage = new Image(importX[1] - importX[0], importY[1] - importY[0]);
if (verbose >= 2) { tiled.log(`'${originalImage}, ${croppedImage}'`); }
if (verbose >= 2) { tiled.log(`'${importX}, ${importY}'`); }
for (let py = importY[0]; py < importY[1]; py++) {
let y = py - importY[0];
for (let px = importX[0]; px < importX[1]; px++) {
let x = px - importX[0];
if (verbose >= 2) { tiled.log(`'${x},${y}'`); }
if (verbose >= 4) { tiled.log(`'${cache[image].pixel(px, py)}'`); }
// if(verbose >= 1){tiled.log(`'${px}, ${py}'`);}
croppedImage.setPixel(x, y, cache[image].pixel(px, py))
};
};
// originalImage = undefined;
return croppedImage;
},
getSortedKeys: function getSortedKeys(dict) {
var sorted = [];
for (var key in dict) {
sorted[sorted.length] = key;
}
return sorted.sort((a, b) => a.length - b.length);
},
goToTile: function goToTile(id, filepath) {
let asset = ""
if (tiled.activeAsset.isTileMap) {
let map = tiled.activeAsset
for (let tileset of tiled.activeAsset.tilesets.concat(tiled.openAssets)) {
if (tileset.fileName == FileInfo.fromNativeSeparators(filepath)) {
asset = tileset
break
}
}
if (asset === "") {
let mapasset = tiled.activeAsset
let mappath = tiled.activeAsset.fileName
asset = tiled.open(filepath)
let map = tiled.open(mappath)
tiled.mapEditor.currentBrush.addTileset(asset)
}
tiled.mapEditor.tilesetsView.currentTileset = asset
tiled.mapEditor.tilesetsView.selectedTiles = [asset.findTile(id)]
} else {
asset = tiled.open(filepath)
asset.selectedTiles = [asset.findTile(id)]
}
},
load_config: () => {
let loaded_config;
var pathToConfig = `${FileInfo.path(tiled.projectFilePath)}/${configfilename}`
if(File.exists(pathToConfig)){
config = JSONread(pathToConfig)
} else {
config = {
chosen_tileset: `ChibiUltica`,
snaptogrid: true
} // new extensionConfig(FileInfo.path(tiled.projectFilePath));
}
add_config_properties()
// for(let key in loaded_config){
// config[key] = loaded_config[key]
// tiled.log(`'${key} (${typeof key})': '${config[key]} (${typeof config[key]})'`)
// // config[`set_${key}`] = loaded_config[key]
// }
// tiled.log(config.path_to_cdda_palettes)
},
/**
* Update config file with contents of config object.
*/
updateConfig: function updateConfig() {
var pathToConfig = `${FileInfo.path(tiled.projectFilePath)}/${configfilename}`
var configfile = new TextFile(pathToConfig, TextFile.WriteOnly);
for(let key in config){
if(key.match(/(?:\"get|\"set)/)){delete config[key]()}
}
configfile.write(JSON.stringify(config, null, 2));
configfile.commit();
},
getFilesInPath: function getFilesInPath(path) { return File.directoryEntries(path, 0x002 | 0x2000 | 0x4000); },
getFoldersInPath: function getFoldersInPath(path) { return File.directoryEntries(path, 0x400 | 0x2000 | 0x4000); },
flattenDict: function flattenDict(dict, result) {
if (typeof result === "undefined") {
result = [];
}
for (let i in dict) {
if ((dict[i].constructor == Object)) {
cte.flattenDict(dict[i], result);
} else {
if (Array.isArray(dict[i])) {
let flat = cte.flattenArray(dict[i])
for (var a = 0; a < flat.length; a++) {
result.push(flat[a]);
}
}
}
}
return result;
},
/**
* Check if path is a file (true) or directory (false).\
* @param {string} path - path to check
* @returns {boolean} - true if path is a file, false if path is a directory.
*/
isFile: (path) => {
return File.directoryEntries(`${FileInfo.path(cte.removeFileStringFromFileUrl(path))}/..`, 0x002 | 0x2000 | 0x4000).includes(path)
},
/**
*
* @param {*} dict
* @param {*} result
* @returns
*/
/**
*
* @param {object} dict - a dictionary with nested objects
* @returns {array} - a flat array of all the values in the dictionary
*/
flattenDictKeys: function flattenDictKeys(dict, result) {
if (typeof result === "undefined") {
result = [];
}
for (let i in dict) {
if ((dict[i].constructor == Object)) {
result.push(i);
cte.flattenDictKeys(Object.keys(dict[i]), result);
}
}
return result;
},
/**
*
* @param {array} arr - an array with nested arrays.
* @returns {array} - a flat array with all the values from the nested arrays.
*/
flattenArray: (arr, result) => {
if (typeof result === "undefined") {
result = [];
}
for (var i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
cte.flattenArray(arr[i], result);
} else {
result.push(arr[i]);
}
}
return result;
},
isTilesetInstalled: (tileset) => {
if(File.exists(`${FileInfo.path(tiled.projectFilePath)}/tilesets/${tileset}`)){
return true
} else {
return false
}
},
/**
*
* @param {string} tileset
* @returns Boolean - true if the tileset is the active tileset, false if it is not.
*/
isTilesetActive: (tileset) => {
if(config && config.chosen_tileset && config.chosen_tileset == tileset){
return true
} else {
return false
}
},
/**
* Checks if the path to the CDDA directory is valid.
*
* @param {string} path - the path to the file to be read
* @returns true if the path is valid, false if it is not
*/
isPathToCddaValid: (path) => {
if (File.exists(`${path}/data/cataicon.ico`) && File.exists(`${path}/gfx/tile_config_template.json`)) {
return true
} else {
return false
}
},
/**
*
* @param {string} path - path starting with file://
* @returns - path without file:// depending on OS
*/
removeFileStringFromFileUrl: (path) => {
if (tiled.platform === "windows") {
return path.toString().replace(/^file\:\/\/\//, "");
} else {
return path.toString().replace(/^file\:\//, "");
}
},
/**
*
* @returns {string|false} - the name of the currently active tileset or false if there is no active tileset.
*/
getCurrentlyActiveTileset: () => {
if(config && config.chosen_tileset && File.exists(`${FileInfo.path(tiled.projectFilePath)}/tilesets/${config.chosen_tileset}`)){
return config.chosen_tileset;
} else {
return false;
}
},
getInstalledTilesets: () => {
if(File.exists(`${FileInfo.path(tiled.projectFilePath)}/tilesets`)){
return cte.getFoldersInPath(`${FileInfo.path(tiled.projectFilePath)}/tilesets`);
}
}
}
function initialize() {
action_cdda_verbose.checked = true
if (tiled.projectFilePath === undefined) {
return tiled.log(`No project file loaded. Please load a project file.`)
}
var pathToConfig = `${ FileInfo.path(tiled.projectFilePath)}/${configfilename}`
if (!File.exists(pathToConfig)) {
tiled.log(`no config file found at ${pathToConfig}. Making new config file.`)
config = new extensionConfig(FileInfo.path(tiled.projectFilePath));
if(!config.hasOwnProperty(`path_to_cdda`)){
return wizard()
}
if (!config.path_to_cdda) { return }
cte.updateConfig()
add_config_properties()
} else {
if (verbose >= 2) { tiled.log(`config file found at ${pathToConfig}`); }
cte.load_config()
}
if (!File.exists(config.path_to_tilesets)) { File.makePath(config.path_to_tilesets); }
if (!File.exists(config.path_to_maps)) { File.makePath(config.path_to_maps); }
generateMetaTileset()
return 1;
}
function returnPromise(func) {
return Promise.resolve(func);
}
returnPromise()
.then(result => tiled.log(result))
.catch(error => tiled.error(error));
function wizard(){
if (tiled.projectFilePath === '') {
return tiled.log(`No project file loaded. Please load a project file.`)
}
pathToProjectTilesets = `${FileInfo.path(tiled.projectFilePath)}/tilesets`
pathToProjectMaps = `${FileInfo.path(tiled.projectFilePath)}/maps`
if (!File.exists(pathToProjectTilesets)) { File.makePath(pathToProjectTilesets); }
if (!File.exists(pathToProjectMaps)) { File.makePath(pathToProjectMaps); }
if (File.exists(`${FileInfo.path(tiled.projectFilePath)}/${configfilename}`)) {
initialize()
}
let wizard = new Dialog();
wizard.windowTitle = `CDDA Tiled Extension Config`;
let pathToCdda;
let chosenTileset;
let isPathValid;
let installedTilesets = cte.getInstalledTilesets()
let deleteConfirmCounter = 0;
let newPathToCDDA;
let cddaPathCheckmark;
let availableTilesetsList =[];
let rememberChosenTilesetIndex;
config.path_to_cdda ? pathToCdda = config.path_to_cdda : pathToCdda = FileInfo.path(tiled.projectFilePath)
config.chosen_tileset ? chosenTileset = config.chosen_tileset : chosenTileset;
// let img = new Image()
// img.loadFromData(Base64.decode(b64images.metatiles['unknown_tile'], "png"));
// wizard.addImage("", img)
// tile.setImage(img);
// let img = new Image();
// img.load("E:/tiledtest/tilesets/favorites/images/f_armchair.png")
let folderSelectInstructionsText = `Select any file in main CDDA folder.
For example, if your CDDA version is a clone of the main repo, you can select 'Makefile'. If you have a release version, you can select 'cataclysm-tiles.exe'.`
wizard.addSeparator(`Path to CDDA`);
let howToSelectFolderText = wizard.addLabel(folderSelectInstructionsText);
howToSelectFolderText.wordWrap = true;
wizard.addNewRow();
let currentlySavedPathToCdda = wizard.addLabel(`Current path: ${config.path_to_cdda}`);
wizard.addNewRow();
let pathInputLabel = wizard.addLabel("New path:", true);
pathInputLabel.toolTip = folderSelectInstructionsText.replace(/, /g, ",\n");
let path_to_cdda_filepicker = wizard.addFilePicker();
path_to_cdda_filepicker.toolTip = folderSelectInstructionsText.replace(/, /g, ",\n");
cddaPathCheckmark = wizard.addLabel(``);
// cddaPathCheckmark.setStyleSheet("QLabel { background-color : red; color : blue; }");
// cddaPathCheckmark.setStyleSheet("QLabel { color : red; }");
path_to_cdda_filepicker.fileUrl = pathToCdda;
updateCddaPathCheck(pathToCdda);
wizard.addSeparator(`Tilesets`);
let currentlyActiveTilesetText = wizard.addLabel(`Active tileset: ${cte.getCurrentlyActiveTileset()}`);
wizard.addNewRow();
let tilesetSelector = wizard.addComboBox(``, availableTilesetsList);
let cddaPathTilesetWarning = wizard.addLabel(`-not in root CDDA directory-`);
wizard.addNewRow();
let deleteTilesetButton = wizard.addButton(`Delete`);
let installTilesetButton = wizard.addButton(`Install`);
let activateTilesetButton = wizard.addButton(`Activate`);
wizard.addSeparator(`Maps`);
let readinessMessage = wizard.addLabel(`Not ready to import maps`);
let checkboxOpenAllTilesets = wizard.addCheckBox(`Open tileset`, true);
checkboxOpenAllTilesets.toolTip = `If checked, tileset will be opened when a new map is opened.`
if (config.open_tileset_on_map_start != null) {
checkboxOpenAllTilesets.checked = config.open_tileset_on_map_start;
} else {
config.open_tileset_on_map_start = checkboxOpenAllTilesets.checked;
cte.updateConfig();
}
checkboxOpenAllTilesets.visible = false;
wizard.addNewRow();
let importMapButton = wizard.addButton(`Import map`);
let createNewMapButton = wizard.addButton(`New map`);
wizard.addNewRow();
wizard.addSeparator();
let closeButton = wizard.addButton(`Close`);
deleteTilesetButton.clicked.connect(function () {
if(deleteConfirmCounter == 0){
deleteConfirmCounter++
deleteTilesetButton.text = `CONFIRM`
return
}
if(deleteConfirmCounter == 1){
deleteConfirmCounter = 0
rememberChosenTilesetIndex = tilesetSelector.currentIndex;
File.remove(`${FileInfo.path(tiled.projectFilePath)}/tilesets/${chosenTileset}`)
updateTilesetSelector(isPathValid)
updateTilesetList(isPathValid)
updateTilesetButtons()
deleteTilesetButton.text = `Deleted`;
tilesetSelector.currentIndex = rememberChosenTilesetIndex;
if(config.chosen_tileset == chosenTileset){
config.chosen_tileset = false;
cte.updateConfig();
}
currentlyActiveTilesetText.text = `Active tileset: ${config.chosen_tileset}`;
return
}
});
installTilesetButton.clicked.connect(function () {
installTilesetButton.text = `Installing...`;
rememberChosenTilesetIndex = tilesetSelector.currentIndex;
importTileset(`${newPathToCDDA}/gfx/${chosenTileset}`)
updateTilesetSelector(isPathValid)
updateTilesetButtons()
tilesetSelector.currentIndex = rememberChosenTilesetIndex;
wizard.show()
});
activateTilesetButton.clicked.connect(function () {
rememberChosenTilesetIndex = tilesetSelector.currentIndex;
if(!cte.isTilesetInstalled(chosenTileset)){
importTileset(`${newPathToCDDA}/gfx/${chosenTileset}`)
}
config.chosen_tileset = chosenTileset;
cte.updateConfig();
updateTilesetSelector(isPathValid)
updateTilesetButtons()
tilesetSelector.currentIndex = rememberChosenTilesetIndex;
currentlyActiveTilesetText.text = `Active tileset: ${config.chosen_tileset}`;
});
closeButton.clicked.connect(function () {
wizard.accept();
});
importMapButton.clicked.connect(function () {
wizard.accept();
tiled.trigger("cte_importMap")
});
createNewMapButton.clicked.connect(function () {
wizard.accept();
tiled.trigger("cte_createNewMap")
});
checkboxOpenAllTilesets.stateChanged.connect(function () {
config.open_tileset_on_map_start = checkboxOpenAllTilesets.checked;
cte.updateConfig();
});
cte.isPathToCddaValid(pathToCdda) ? isPathValid = true : isPathValid = false;
newPathToCDDA = pathToCdda;
updateCddaPathCheck(isPathValid)
updateTilesetSelector(isPathValid)
updateTilesetButtons()
function updateTilesetButtons(){
if(cte.isTilesetInstalled(chosenTileset) ){
installTilesetButton.enabled = false;
installTilesetButton.toolTip = `Already installed`;
installTilesetButton.text = `Installed`;
deleteTilesetButton.enabled = true;
deleteTilesetButton.text = `Delete`;
} else {
installTilesetButton.enabled = true;
installTilesetButton.toolTip = ``;
installTilesetButton.text = `Install`;
deleteTilesetButton.enabled = false;
deleteTilesetButton.text = `Delete`;
}
if(cte.isTilesetActive(chosenTileset)){
activateTilesetButton.enabled = false;
activateTilesetButton.toolTip = `Already active`;
activateTilesetButton.text = `Active`;
} else {
activateTilesetButton.enabled = true;
activateTilesetButton.toolTip = ``;
activateTilesetButton.text = `Activate`;
}
if(["favorites"].includes(chosenTileset)){
activateTilesetButton.enabled = false;
activateTilesetButton.toolTip = `This is a meta tileset and not a CDDA tileset. It cannot be imported.`;
activateTilesetButton.text = `Wrong Type`;
}
}
function updateTilesetSelector(valid){
if(valid){
updateTilesetList(valid);
}
isReadyForMapImport()
if(valid || installedTilesets.length > 0){
installedTilesets = cte.getInstalledTilesets()
tilesetSelector.visible = true;
deleteTilesetButton.visible = true;
// installTilesetButton.visible = true;
activateTilesetButton.visible = true;
cddaPathTilesetWarning.visible = false;
}
if(!valid && installedTilesets.length == 0){
tilesetSelector.clear();
tilesetSelector.visible = false;
deleteTilesetButton.visible = false;
// installTilesetButton.visible = false;
activateTilesetButton.visible = false;
cddaPathTilesetWarning.visible = true;
}
}
// ✅ ❌
// font-variant: small-caps;
function updateCddaPathCheck(valid){
if(valid){
cddaPathCheckmark.text = `✓`
cddaPathCheckmark.toolTip = `Valid path to CDDA saved`
cddaPathCheckmark.setStyleSheet("QLabel { color : #66FF99; }");
howToSelectFolderText.visible = false;
} else {
cddaPathCheckmark.text = `✗`
cddaPathCheckmark.toolTip = `This is a not valid path to CDDA`
cddaPathCheckmark.setStyleSheet("QLabel { color : red; }");
howToSelectFolderText.visible = true;
}
}
path_to_cdda_filepicker.fileUrlChanged.connect(() => {
deleteConfirmCounter = 0
path_to_cdda_filepicker.fileUrl = FileInfo.path(path_to_cdda_filepicker.fileUrl)
newPathToCDDA = cte.removeFileStringFromFileUrl(path_to_cdda_filepicker.fileUrl)
cte.isPathToCddaValid(newPathToCDDA) ? isPathValid = true : isPathValid = false;
if(isPathValid){
config.path_to_cdda = newPathToCDDA;
cte.updateConfig();
currentlySavedPathToCdda.text = `Current path: ${config.path_to_cdda}`;
};
updateCddaPathCheck(isPathValid)
updateTilesetSelector(isPathValid)
})
tilesetSelector.currentTextChanged.connect(() => {
deleteConfirmCounter = 0
chosenTileset = availableTilesetsList[tilesetSelector.currentIndex];
updateTilesetButtons()
})
function updateTilesetList(valid){
installedTilesets = cte.getInstalledTilesets()
tilesetSelector.clear()
if(valid){
availableTilesetsList = cte.getFoldersInPath(`${newPathToCDDA}/gfx`);
} else {
availableTilesetsList = installedTilesets
}
let displayAvailableTilesetsList;
if(availableTilesetsList != null){
displayAvailableTilesetsList = availableTilesetsList.map((t) => {
if(t == `favorites`){ return `${t} (not valid tileset)`}
if(installedTilesets.includes(t)){
if(cte.getCurrentlyActiveTileset() == t){ return`-${t}- (-active-)` }
return `${t} (installed)`;
} else {
return `${t}`
}
})
}
tilesetSelector.addItems(displayAvailableTilesetsList)
chosenTileset ? tilesetSelector.currentIndex = availableTilesetsList.indexOf(chosenTileset) : tilesetSelector.currentIndex = availableTilesetsList.indexOf(config.chosen_tileset);
}
function isReadyForMapImport(){
if(cte.isPathToCddaValid(pathToCdda) && config && config.chosen_tileset && cte.isTilesetInstalled(config.chosen_tileset)){
readinessMessage.text = `Ready to create CDDA maps`;
readinessMessage.active = false;
importMapButton.enabled = true;
createNewMapButton.enabled = true;
} else {
readinessMessage.text = `Not ready to create maps`;
importMapButton.enabled = false;
createNewMapButton.enabled = false;
}
}
isReadyForMapImport()
installTilesetButton.enabled = false;
installTilesetButton.visible = false;
wizard.show()
}
function getpathToCDDA(){
return cte.folderPicker(config.hasOwnProperty(`path_to_cdda`) ? config.path_to_cdda : FileInfo.path(tiled.projectFilePath), `Path to CDDA folder`)
}
function addSpriteToFavotires() {
let originalAsset = tiled.activeAsset
let tileset;
let tiles;
let is_image_collection = false;
if (tiled.activeAsset.isTileset) {
if (verbose >= 1) { tiled.log(`asset is tileset`) }
tileset = tiled.activeAsset;
tiles = tiled.activeAsset.selectedTiles;
is_image_collection = tileset.collection
}
if (tiled.activeAsset.isTileMap) {
if (verbose >= 1) { tiled.log(`asset is tilemap`) }
tileset = tiled.mapEditor.tilesetsView.currentTileset;
tiles = tiled.mapEditor.tilesetsView.selectedTiles;
}
if (tiles.length < 1) { return tiled.log(`No tiles selected.`) }
let pathToFavoriteImages = `${FileInfo.path(config.path_to_favorites_tileset)}/images`
if (!File.exists(FileInfo.path(config.path_to_favorites_tileset))) { File.makePath(FileInfo.path(config.path_to_favorites_tileset)); };
if (!File.exists(pathToFavoriteImages)) { File.makePath(pathToFavoriteImages); };
let favorites;
if (!File.exists(config.path_to_favorites_tileset)) {
favorites = new Tileset("Favorites");
tiled.tilesetFormat("json").write(favorites, config.path_to_favorites_tileset);
cte.adjustTSJ(config.path_to_favorites_tileset)
}
favorites = tiled.open(config.path_to_favorites_tileset);
for (let tile of tiles) {
let path_to_image;
if (!is_image_collection) {
path_to_image = `${pathToFavoriteImages}/${tile.property(`cdda_id`)}.png`;
if (!File.exists(path_to_image)) {
let [x, y] = cte.getTileXY(tile)
let croppedImage = cte.cropImage(tileset.image, x, y);
croppedImage.save(path_to_image);
};
} else {
path_to_image = tile.imageFileName
}
let new_image_tile = favorites.addTile()
new_image_tile.setProperty("cdda_id", tile.property(`cdda_id`))
new_image_tile.imageFileName = path_to_image
tiled.log(`'${tile.property(`cdda_id`)}' added to favorites.`)
}
// tiled.log(tiled.activeAsset.selectedTiles)
tiled.tilesetFormat("json").write(favorites, config.path_to_favorites_tileset);
tiled.reload(tiled.activeAsset)
tiled.open(originalAsset.fileName)
// tiled.activeAsset = originalAsset
}
/**
*
* @param {"string"} cdda_id
* @returns {"Tile"} - new unknown tile
*/
function addCddaIdToUnknowns(cdda_id) {
if (cdda_id == `t_null`) { return }
// make unknowns tileset if it doesn't exist
let unknowns;
if (!File.exists(config.path_to_unknowns_tileset)) {
unknowns = new Tileset("unknowntiles");
tiled.tilesetFormat("tsx").write(unknowns, config.path_to_unknowns_tileset);
}
let unknownsAssetCheck = getOpenAssetByFilepath(config.path_to_unknowns_tileset)
if (unknownsAssetCheck != null && unknownsAssetCheck.isTileset) {
tiled.log(`unknowns tileset already open`)
unknowns = unknownsAssetCheck;
} else {
tiled.log(`unknowns tileset not open, opening now...`)
unknowns = tiled.open(config.path_to_unknowns_tileset);
}
if(unknowns.isTileset == false){tiled.log(`unknowns is not tileset`)}
if(unknowns.isTileset == true){tiled.log(`unknowns is tileset`)}
// return unknown tile if already made
for (let tile_i in unknowns.tiles) {
let tile = unknowns.tiles[tile_i]
let tileProperties = tile.resolvedProperties()
for (let p in tileProperties) {
let property = tileProperties[p]
if (p == 'cdda_id' && property == cdda_id) {
return tile
}
}
}
// add tile and properties with unknown image filepath
let newUnknownTile = unknowns.addTile()
let img = new Image()
img.loadFromData(Base64.decode(b64images.metatiles['unknown_tile'], "png"));
newUnknownTile.setImage(img);
newUnknownTile.setProperty("cdda_id", cdda_id)
if (verbose >= 1) { tiled.log(`'${newUnknownTile.property(`cdda_id`)}' added to unknowns.`) }
tiled.tilesetFormat("tsx").write(unknowns, config.path_to_unknowns_tileset);
return newUnknownTile
}
// meta tileset
function generateMetaTileset() {
if (!File.exists(`${config.path_to_tilesets}/meta_tilesets`)){
File.makePath(`${config.path_to_tilesets}/meta_tilesets`);
}
if (!File.exists(config.path_to_meta_tileset)) {
File.makePath(FileInfo.path(config.path_to_meta_tileset));
}
let tilesetname = "cdda_meta_tileset";
let tileset = new Tileset(tilesetname);
for (let cddaId in b64images.metatiles) {
let tile = tileset.addTile();
let img = new Image()
img.loadFromData(Base64.decode(b64images.metatiles[cddaId], "png"));
tile.setImage(img);
tile.setProperty("cdda_id", cddaId);
}
tiled.tilesetFormat("tsx").write(tileset, config.path_to_meta_tileset)
}
function JSONread(filepath) {
const file = new TextFile(filepath, TextFile.ReadOnly)
file.codec = "UTF-8"
const file_data = file.readAll()
file.close()
return JSON.parse(file_data)
}
function getRecursiveFilePathsInFolder(targetPath) {
if (verbose >= 2) { tiled.log(`getting paths files in folder`); };
let filePaths = cte.getFilesInPath(targetPath).map(a => `${targetPath}/${a}`)
let folderPaths = cte.getFoldersInPath(targetPath).map(a => `${targetPath}/${a}`);
for (let folderPath in folderPaths) {
filePaths = filePaths.concat(cte.getFilesInPath(folderPath).map(a => `${folderPath}/${a}`));
let subfolders = cte.getFoldersInPath(folderPath).map(a => `${folderPath}/${a}`)
for (let subfolder in subfolders) {
if (subfolders != null) { folderPaths.push(subfolder); }
}
}
if (verbose >= 2) { tiled.log(`palette file paths`); };
if (verbose >= 2) { tiled.log(filePaths); };
return filePaths;
}
function importTileset(pathToChosenTileset) {
// config.set_path_to_cdda = !config.hasOwnProperty(`path_to_cdda`) ? getpathToCDDA() : config.path_to_cdda
// if (!config.path_to_cdda) { return tiled.log("Action cancelled.") }
// cte.updateConfig();
// tiled.log(config.path_to_cdda_tilesets)
// let dialogoutput = chooseTilesetDialog(config.path_to_cdda_tilesets)
// if (!dialogoutput) { return tiled.log("Action cancelled.") }
// config.path_to_chosen_cdda_tileset_files = dialogoutput
config.path_to_chosen_cdda_tileset_files = pathToChosenTileset
if (config.path_to_chosen_cdda_tileset_files.match(/\.json$/)) { config.path_to_chosen_cdda_tileset_files = FileInfo.path(config.path_to_chosen_cdda_tileset_files) }
if (!File.exists(config.path_to_chosen_tileset_files)) { tiled.log(`Making path to chosen tileset '${config.path_to_chosen_tileset_files}'`);File.makePath(config.path_to_chosen_tileset_files); }
if (!File.exists(config.path_to_meta_tileset)) { tiled.log("Generating meta tileset."); generateMetaTileset(); }
// cte.updateConfig();
let pathToDuplicateIDImages = `${config.path_to_chosen_tileset_files}/duplicate_id_images`
if (!File.exists(pathToDuplicateIDImages)) { File.makePath(pathToDuplicateIDImages); }
let pathToDuplicateIDTSJ = `${config.path_to_chosen_tileset_files}/duplicate_id_tiles.tsj`
//duplicates tiled tileset
var dupe_tileset = new Tileset("duplicate_cdda_ids");
var filename = config.path_to_chosen_cdda_tileset_json
function importSpriteData(ts, jts, j, i) {
let tiles = j['tiles-new'][i]['tiles']
for (let tile of tiles) {
tiled.log('------')
tiled.log(tile['id'])
let cdda_IDs = []
if (tile["animated"]) {
tiled.log(`is animated`)
for (let subtile of tile['fg']) {
for (let subtile in tile['fg']) {
if (typeof tile['fg'][subtile] != 'number') {
cdda_IDs.push(tile['fg'][subtile]['sprite'])
}
}
}
}
if (tile["multitile"]) {
tiled.log(`is multitile`)
cdda_IDs.push(tile['fg'])
for (let subtile in tile["additional_tiles"]) {
if (Array.isArray(tile["additional_tiles"][subtile]['fg'])) {
for (let subSubtile in tile["additional_tiles"][subtile]['fg']) {
if (typeof tile["additional_tiles"][subtile]['fg'][subSubtile] == 'number') {
cdda_IDs.push(tile["additional_tiles"][subtile]['fg'][subSubtile])
}
if (typeof tile["additional_tiles"][subtile]['fg'][subSubtile]['sprite'] == 'number') {
cdda_IDs.push(tile["additional_tiles"][subtile]['fg'][subSubtile]['sprite'])
} else {
for (let sprite in tile["additional_tiles"][subtile]['fg'][subSubtile]['sprite']) {
cdda_IDs.push(tile["additional_tiles"][subtile]['fg'][subSubtile]['sprite'][sprite])
}
}
}
} else {
cdda_IDs.push(tile["additional_tiles"][subtile]['fg'])
//subtile['id']
}
}
}
if (!tile["animated"] && !tile["multitle"]) {
if (Array.isArray(tile['fg'])) {
for (let subtile in tile['fg']) {
if (typeof tile['fg'][subtile] != 'number') {
cdda_IDs.push(tile['fg'][subtile]['sprite'])
} else {
cdda_IDs.push(tile['fg'][subtile])
}
}