-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathresourceBuilder.js
2393 lines (1972 loc) · 103 KB
/
resourceBuilder.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
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
// TODO:
// - Would be cool to adopt a transaction type system, where we only save all files at the very end (so that we don't save an asset when something ends up crashing the builder later)
// - Avoid reading raw asset twice (once for hash, once for cache)
// - Remove stale resource files (those which are no longer referenced)
const requirejs = require('requirejs');
requirejs.config({
nodeRequire: require,
baseUrl: __dirname,
paths: {
lodash: "https://cdn.jsdelivr.net/lodash/4.14.1/lodash.min.js"
}
});
const util = require('util'),
_ = require('lodash'),
fs = require('fs'), // TODO: Promisify this
path = require('path'),
Promise = require('bluebird'),
chalk = require('chalk'),
prettyjson = require('prettyjson'),
assert = require('assert'), // TODO: Disable in production
crypto = require('crypto'),
openpgp = require('openpgp'),
exec = require('child_process').exec,
execSync = require('child_process').execSync,
xml2js = require('xml2js');
const Settings = {
forceRebuild: false,
checkNeedsRebuild: false,
verbose: false
}
// Process Server arguments
for (let i=0; i<process.argv.length; ++i) {
const arg = process.argv[i];
if (arg === "--force-rebuild") {
console.log("Recaching all resources");
Settings.forceRebuild = true;
}
if (arg === "--needs-rebuild") {
console.log("Checking if resources need rebuilding");
Settings.checkNeedsRebuild = true;
}
if (arg === "--package") {
const filterPackage = process.argv[++i];
Settings.filterPackage = filterPackage;
}
if (arg === "--asset") {
const filterAsset = process.argv[++i];
Settings.filterAsset = filterAsset;
}
if (arg === "--verbose") {
Settings.verbose = true;
}
}
if (Settings.filterAsset && !Settings.filterPackage) {
console.error("Attempting to filter by asset, but didn't specifiy --package to filter");
process.exit(1);
}
// Prepare openpgp stuff
openpgp.initWorker({ path: 'node_modules/openpgp/dist/openpgp.worker.js' }) // set the relative web worker path
openpgp.config.aead_protect = true // activate fast AES-GCM mode (not yet OpenPGP standard)
// TODO: Need a way to read from all resources, and handle similarly
//
// - resources, sheets, icons, sounds, maps
// - need a list of raw resources and their hashes
// - go through each resource to see if hash different
// - if hash is different then mark asset in some way
// - go through marked asssets, process accordingly (need a way to classify assets so we know how to process them -- sheets w/ options (encrypt?), data (validate?), maps, sounds, images)
// - update asset hashes along the way
// - for all marked assets, update their parent package (sounds.json, resources.json, world.json, etc.)
// - NOTE: Need ordering to be available (resources.json last!)
// - Need an easy way to skip processing and only find changed assets (for --check-needs-rebuild)
// - Need an easy way to limit search to specific package (resources.json, sounds.json, etc.) in case this comes from Gruntfile/watch
// - Need an easy way to limit to specific asset in case this comes from Gruntfile/watch again
//
//
// - Single package: read through resources and only add the specified package asset; add that package
// - Single resource: go through all packages to find asset, and only add the package/asset that matches the specified resource file
// - Resources should be the top most package, other packages are under that
// Resources:
// - sheets, avatars, npcs, world, items, buffs, interactables, quests, interactions, scripts, ...
//
// Resources: {
// file: resources.json
// type: data
// rawHash: asdf
// processedhash: kljf
// options: { validate: true },
// data: ....
//
// assets: [{
// file: sheets.json
// type: data
// rawHash: 123abc
// processedHash: abc123
// options: { validate: true },
// data: .... (specific to data only -- store JSON)
//
// assets: [
// {
// file: sprite.png
// type, rawhash, processedHash, options: { encrypt: true }
// }
// ]
// }, ....]
// }
//
//
// -- get rid of areahashes and just use world.json for hash (would need 2 types of hashes stored here)
// 8) Filter asset if necessary (specified package or resource) --- if we update an asset does that mean we'll always update the package? If so then we should only filter packages in Grunt. Can Grunt listen for changes and wait X seconds before recompiling? (exceptions: npcs.json or other pure data files?), could store a list of files that have changed and pass them all into here
// - what if we have nested packages, and change one of those packages -- might need a delay?
// - delay: what if we change a package (automated) and continue processing w/ intention of changing another package or the same one again -- delay is dependent on that process finishing
// - we could ONLY watch certain packages, and expect other packages (eg. sheets) to rebuild via exporter -- but what if we touch it manually?
// - some files we want to reload immediately (eg. npcs, buffs, testing)
//
// -- Watch/Rebuild immediately: list of packages (npcs, buffs, etc.)
// -- Watch/Rebuild after delay (careful w/ delay time): list of packages (sheets, media, avatars, world)
// 10) Integrate w/ Grunt & Server
// - Grunt: Watch Resource packages; list of those w/ rebuild delay/immediate
// - Grunt: Rebuild when necessary -- read exit code for indicator of failure
// - Server: --needs-rebuild ; read exit code to determine, then exit if needed
// -- move this to tools/
// -- nicer output (colours n shiz)
// -- clean this file up
// -- get rid of references to old caching system in js
// -- hash -> processedHash; rawHash -> hash
// -- get rid of cache.json
let Resources = null;
const packageRoutines = {
"resources": {
"prepare": (data) => {},
"read": (data) => {
const assets = [];
_.forEach(data, (packageDetails, packageName) => {
const package = {
name: packageName,
file: 'resources/data/' + packageDetails.file,
output: 'dist/resources/data/' + packageDetails.file,
type: "data",
rawHash: packageDetails.rawHash,
processedHash: packageDetails.hash,
options: packageDetails.options
};
if (Settings.filterPackage) {
package.skipProcess = (Settings.filterPackage !== packageName);
if (package.skipProcess && Settings.verbose) {
console.log(`Filtering package: "${Settings.filterPackage}"`);
}
}
assets.push(package);
});
return assets;
},
"validate": (data) => {
// FIXME: Validate the data
return true;
},
"updateAsset": (data, assetName, asset) => {
data[assetName].hash = asset.processedHash;
data[assetName].rawHash = asset.hash;
},
"finalize": (package) => { }
},
"media": {
"prepare": (data) => {},
"read": (data) => {
const assets = [];
data.list.forEach((assetDetails) => {
assets.push({
name: assetDetails.name,
file: 'resources/' + assetDetails.file,
output: 'dist/resources/' + assetDetails.output,
type: assetDetails.type,
rawHash: assetDetails.rawHash,
processedHash: assetDetails.hash,
options: assetDetails.options
});
});
return assets;
},
"validate": (data) => {
return true;
},
"updateAsset": (data, assetName, asset) => {
console.log(`Updating an asset in media: ${assetName}`);
let media = data.list.find((media) => media.name === assetName);
media.hash = asset.processedHash;
media.rawHash = asset.hash;
},
"finalize": (package) => { }
},
"sheets": {
"prepare": (data) => {
// Find all tilesheets that have some sprites which need to be extracted into a separate, autogenerated
// sheet. Update these autogenerated sheets
const generatedSheets = {};
data.tilesheets.list.forEach((sheet) => {
// Find all sheets w/ sprites to be extracted
if (sheet.data.extractGroups && Object.keys(sheet.data.extractGroups).length > 0) {
_.forEach(sheet.data.extractGroups, (extractGroup, groupId) => {
const sheetId = extractGroup.sheetId,
extractSprites = [];
// Find all sprites belonging to this group
_.forEach(sheet.data.extracts, (spriteGroup, sprite) => {
if (spriteGroup === groupId) extractSprites.push(parseInt(sprite, 10));
});
// Create generated sheet if doesn't exist yet. Don't worry if it does exist, we'll just mark it
// as exists when we come across the generated asset
if (!generatedSheets[sheetId]) {
generatedSheets[sheetId] = {
exists: false,
list: null,
currentList: []
}
}
const generatedSheet = generatedSheets[sheetId];
generatedSheet.currentList.push({
assetId: sheet.id,
asset: sheet,
sprites: extractSprites
});
});
}
// Auto generated sheet
if (sheet.generated) {
if (!generatedSheets[sheet.id]) {
generatedSheets[sheet.id] = {
currentList: null
};
}
const generatedSheet = generatedSheets[sheet.id];
generatedSheet.exists = true;
generatedSheet.list = sheet.dependencies;
generatedSheet.sprites = sheet.sprites;
generatedSheet.dirty = sheet.dirty;
generatedSheet.columns = sheet.columns;
generatedSheet.rows = sheet.rows;
// Image dependencies are separate from extraction groups, but still go on the currentList
sheet.dependencies.forEach((dep) => {
if (dep.imageSrc) {
if (!generatedSheet.currentList) generatedSheet.currentList = [];
generatedSheet.currentList.push(dep);
}
});
}
});
// Mark generated sheets as dirty if lists differ
_.forEach(generatedSheets, (sheet, sheetId) => {
if (Settings.forceRebuild) {
sheet.dirty = true;
}
if (!sheet.dirty && sheet.list && sheet.currentList && (sheet.currentList.length === sheet.list.length)) {
for (let i = 0; i < sheet.currentList.length; ++i) {
const item = sheet.currentList[i];
if (item.imageSrc) {
// Image dependency
// Has the image changed?
const imageSrcHash = item.imageSrcHash; // FIXME
if (imageSrcHash !== item.imageSrcHash) {
sheet.dirty = true;
}
} else {
// Extraction group
// Have any of the assets changed amongst this group?
const newAsset = item,
oldAsset = sheet.list.find((a) => a.assetId === newAsset.assetId);
if (!oldAsset || !_.isEqual(newAsset.sprites, oldAsset.sprites)) {
sheet.dirty = true;
break;
}
}
}
} else {
sheet.dirty = true;
}
if (sheet.dirty) {
if (sheet.exists) {
const tilesheet = data.tilesheets.list.find((tilesheet) => tilesheet.id === sheetId);
tilesheet.dirty = true;
tilesheet.newDependencies = sheet.currentList;
tilesheet.sprites = sheet.sprites;
// This may be an image-based dep generated tilesheet, so already exists but output wasn't setup
if (!tilesheet.output) {
tilesheet.output = `sprites/${sheetId}.png`;
}
} else {
data.tilesheets.list.push({
id: sheetId,
generated: true,
output: `sprites/${sheetId}.png`,
options: {
cached: false,
encrypted: false,
packed: false,
preprocess: false
},
data: {},
gid: { // FIXME:
first: 0,
last: 0
},
dirty: true,
dependencies: null,
newDependencies: sheet.currentList,
sprites: [],
tilesize: 16, // FIXME: hardcoded tilesize
sheet_offset: { x: 0, y: 0 }
});
}
}
});
},
"read": (data) => {
const assets = [],
generatedAssets = [];
data.tilesheets.list.forEach((sheet) => {
// Generated sheets to be added last
if (sheet.generated) {
generatedAssets.push({
name: sheet.id,
type: "generatedTilesheet",
generated: true,
dirty: sheet.dirty,
options: sheet.options,
output: 'dist/resources/' + sheet.output,
dependencies: sheet.dependencies,
newDependencies: sheet.newDependencies,
oldSprites: sheet.oldSprites,
sprites: sheet.sprites,
spriteGroups: sheet.spriteGroups,
tilesize: sheet.tilesize,
sheetType: 'generatedTilesheet',
columns: sheet.columns,
rows: sheet.rows,
data: sheet.data
});
return;
}
assets.push({
name: sheet.id,
type: "image",
file: 'resources/' + sheet.image,
rawHash: sheet.rawHash,
processedHash: sheet.hash,
options: sheet.options,
output: 'dist/resources/' + sheet.output,
sheetType: 'tilesheet'
});
});
data.spritesheets.list.forEach((sheet) => {
assets.push({
name: sheet.id,
type: "image",
file: 'resources/' + sheet.image,
rawHash: sheet.rawHash,
processedHash: sheet.hash,
options: sheet.options,
output: 'dist/resources/' + sheet.output,
sheetType: 'spritesheet'
});
});
generatedAssets.forEach((generatedAsset) => {
assets.push(generatedAsset);
});
return assets;
},
"validate": (data) => {
return true;
},
"updateAsset": (data, assetName, asset) => {
console.log(`Updating an asset in sheets: ${assetName}`);
let list = null;
if (asset.sheetType === 'tilesheet') {
list = data.tilesheets.list;
} else if (asset.sheetType === 'spritesheet') {
list = data.spritesheets.list;
} else if (asset.sheetType === 'generatedTilesheet') {
list = data.tilesheets.list;
const sheet = list.find((sheet) => sheet.id === assetName);
sheet.dependencies = asset.dependencies;
sheet.sprites = asset.sprites;
sheet.columns = asset.columns;
sheet.rows = asset.rows;
sheet.spriteGroups = asset.spriteGroups;
delete sheet.dirty;
delete sheet.newDependencies;
delete sheet.oldSprites;
// NOTE: This part may not be necessary because we create spriteGroup again
//sheet.spriteGroups.forEach((spriteGroup) => {
// if (spriteGroup.oldSpriteGroup) {
// delete spriteGroup.oldSpriteGroup;
// }
//});
if (sheet.sprites && sheet.sprites.length === 0) {
delete sheet.sprites;
}
return;
} else {
console.error("Unexpected sheetType! " + asset.sheetType);
}
let sheet = list.find((sheet) => sheet.id === assetName);
sheet.hash = asset.processedHash;
sheet.rawHash = asset.hash;
},
"finalize": (package) => {
// Update GID for tilesheets
let gidCursor = 0;
package.data.tilesheets.list.forEach((tilesheet) => {
const totalTiles = parseInt(tilesheet.rows, 10) * parseInt(tilesheet.columns, 10);
tilesheet.gid.first = gidCursor;
gidCursor += totalTiles - 1;
tilesheet.gid.last = gidCursor;
++gidCursor;
});
}
},
"avatars": {
"prepare": (data) => {},
"read": (data) => {
return {};
},
"validate": (data) => {
return true;
},
"updateAsset": (data, assetName, asset) => {
},
"finalize": (package) => { }
},
"npcs": {
"prepare": (data) => data,
"read": (data) => {
return {};
},
"validate": (data) => {
return true;
},
"updateAsset": (data, assetName, asset) => {
},
"finalize": (package) => { }
},
"world": {
"prepare": (data) => {},
"read": (data) => {
const assets = [];
_.forEach(data.areas, (assetDetails, assetID) => {
assets.push({
name: assetID,
file: 'resources/' + assetDetails.file,
output: 'dist/resources/' + assetDetails.file,
type: "map",
rawHash: assetDetails.rawHash,
processedHash: assetDetails.hash
});
});
return assets;
},
"validate": (data) => {
return true;
},
"updateAsset": (data, assetName, asset) => {
console.log(`Updating an asset in world: ${assetName}`);
let area = data.areas[assetName];
area.hash = asset.processedHash;
area.rawHash = asset.hash;
},
"finalize": (package) => { }
},
"items": {
"prepare": (data) => {},
"read": (data) => {
return {};
},
"validate": (data) => {
return true;
},
"updateAsset": (data, assetName, asset) => {
},
"finalize": (package) => { }
},
"buffs": {
"prepare": (data) => {},
"read": (data) => {
return {};
},
"validate": (data) => {
return true;
},
"updateAsset": (data, assetName, asset) => {
},
"finalize": (package) => { }
},
"interactables": {
"prepare": (data) => {},
"read": (data) => {
return {};
},
"validate": (data) => {
return true;
},
"updateAsset": (data, assetName, asset) => {
},
"finalize": (package) => { }
},
"quests": {
"prepare": (data) => {},
"read": (data) => {
return {};
},
"validate": (data) => {
return true;
},
"updateAsset": (data, assetName, asset) => {
},
"finalize": (package) => { }
},
"interactions": {
"prepare": (data) => {},
"read": (data) => {
return {};
},
"validate": (data) => {
return true;
},
"updateAsset": (data, assetName, asset) => {
},
"finalize": (package) => { }
},
"scripts": {
"prepare": (data) => {},
"read": (data) => {
return {};
},
"validate": (data) => {
return true;
},
"updateAsset": (data, assetName, asset) => {
},
"finalize": (package) => { }
},
"components": {
"prepare": (data) => {},
"read": (data) => {
return {};
},
"validate": (data) => {
return true;
},
"updateAsset": (data, assetName, asset) => {
},
"finalize": (package) => { }
},
"rules": {
"prepare": (data) => {},
"read": (data) => {
return {};
},
"validate": (data) => {
return true;
},
"updateAsset": (data, assetName, asset) => {
},
"finalize": (package) => { }
},
"fx": {
"prepare": (data) => {},
"read": (data) => {
return {};
},
"validate": (data) => {
return true;
},
"updateAsset": (data, assetName, asset) => {
},
"finalize": (package) => { }
},
"testing": {
"prepare": (data) => {},
"read": (data) => {
return {};
},
"validate": (data) => {
return true;
},
"updateAsset": (data, assetName, asset) => {
},
"finalize": (package) => { }
},
"eventnodes": {
"prepare": (data) => {},
"read": (data) => {
return {};
},
"validate": (data) => {
return true;
},
"updateAsset": (data, assetName, asset) => {
},
"finalize": (package) => { }
},
};
let fileHash = (file) => {
let hash = execSync('cksum ' + file + ' | awk \'{printf \"%s\", $1}\' ');
return hash.toString('utf8');
};
let readPackage = (package, file) => {
return new Promise((success, fail) => {
fs.readFile(file, (err, bufferData) => {
if (err) {
console.error(`Error reading package (${package}): ${err}`);
fail(err);
return;
}
const data = JSON.parse(bufferData),
packageRoutine = packageRoutines[package];
packageRoutine.prepare(data);
const assets = packageRoutine.read(data);
success({data, assets});
});
});
};
// Load all resources and their list of assets
readPackage('resources', 'resources/data/resources.json').then((details) => {
const { data, assets, hash } = details;
const packages = [],
readPackages = [];
assets.forEach((packageDetails) => {
let readPackagePromise = new Promise((success, fail) => {
readPackage(packageDetails.name, packageDetails.file).then((details) => {
const { data, assets } = details;
const package = {
name: packageDetails.name,
file: packageDetails.file,
output: packageDetails.output,
type: "data",
rawHash: packageDetails.rawHash,
processedHash: packageDetails.processedHash,
options: packageDetails.options,
data: data,
assets: assets
};
if (packageDetails.skipProcess) {
package.skipProcess = true;
}
packages.push(package);
success();
}).catch((e) => {
console.error("There was an error reading a package from Resources");
fail(e);
});
});
readPackages.push(readPackagePromise);
});
Promise.all(readPackages).then(() => {
Resources = {
name: "resources",
file: 'resources/data/resources.json',
type: "data",
processedHash: null,
options: {},
rawHash: hash,
data: data,
assets: packages
};
processResources(Resources).then(() => {
console.log("Successfully saved packages");
const output = 'dist/' + Resources.file;
unlink(output);
fs.copyFile(Resources.file, output, (err) => {
if (err) {
console.error("Error copying package to output");
console.error(err);
process.exit(1);
}
fs.chmodSync(output, 0777);
console.log("Saved resources to " + output);
});
}).catch((err) => {
console.error("Error saving packages");
process.exit(1);
});
}, () => {
console.error("There was an error reading from Resources");
process.exit(1);
});
});
// Process the given resources/assets
// Any differing hashes will be processed to dist
let processResources = (package) => {
return new Promise((success, fail) => {
if (package.skipProcess) {
success();
return;
}
// Need to process assets in here?
// This package may or may not contain assets (NOTE: It could be an asset itself without any assets yet).
// FIXME: Confirm assets is an array (assert)
let processingAssetsPromises = [];
let updatedPackage = false;
if (package.assets && package.assets.length) {
package.assets.forEach((asset) => {
let processAsset = () => {
return new Promise((success, fail) => {
// Process asset if the hash has changed
// NOTE: We need to get the hash here, in case we've changed the asset somewhere along the way to here
let rebuildAsset = false,
hash = null,
distHash = null;
// Is this asset being filtered out?
const assetFilteredOut = Settings.filterAsset && (Settings.filterAsset !== asset.name);
if (!assetFilteredOut) {
if (Settings.filterAsset && Settings.verbose) {
console.log(`Filtering asset: "${Settings.filterAsset}"`);
}
if (Settings.forceRebuild) {
console.log(`Asset to process: ${package.name}: ${asset.name}`);
rebuildAsset = true;
} else if (asset.generated) {
// Generated assets need dirty flag explicitly set
if (asset.dirty) {
console.log(`Asset to process (dirty): ${package.name}: ${asset.name}`);
rebuildAsset = true;
}
} else {
hash = fileHash(asset.file);
distHash = fs.existsSync(asset.output) ? fileHash(asset.output) : "";
if (asset.processedHash !== distHash || asset.rawHash !== hash) {
console.log(`Asset to process (hash has changed)! ${package.name}: ${asset.name}`);
console.log("Output: " + asset.processedHash + " !== " + distHash + " ? (has the output file changed since last time?) ");
console.log("Raw Asset: " + asset.rawHash + " !== " + hash + " ? (has the source file changed?) ");
rebuildAsset = true;
}
}
}
if (rebuildAsset) {
if (Settings.checkNeedsRebuild) {
if (Settings.verbose) {
console.log("Needs rebuild");
}
process.exit(2);
}
updatedPackage = true;
if (asset.type === "image") {
processImage(asset).then(() => {
asset.hash = hash;
let processedHash = fileHash(asset.output);
asset.processedHash = processedHash;
console.log("Asset hashes: " + hash + " " + processedHash);
const packageRoutine = packageRoutines[package.name],
assets = packageRoutine.updateAsset(package.data, asset.name, asset);
success();
}, (err) => {
console.error("Error processing image: " + err);
fail(err);
});
} else if (asset.type === "generatedTilesheet") {
processGeneratedTilesheet(asset).then(() => {
const packageRoutine = packageRoutines[package.name],
assets = packageRoutine.updateAsset(package.data, asset.name, asset);
success();
}, (err) => {
console.error("Error processing generated tilesheet: " + err);
fail(err);
});
} else if (asset.type === "data") {
createDirectoriesFor(asset.output);
unlink(asset.output);
fs.copyFile(asset.file, asset.output, (err) => {
if (err) {
console.error(err);
fail();
return;
}
asset.hash = hash;
let processedHash = fileHash(asset.output);
asset.processedHash = processedHash;
console.log("Processed output: " + asset.output + ": " + processedHash);
const packageRoutine = packageRoutines[package.name],
assets = packageRoutine.updateAsset(package.data, asset.name, asset);
fs.chmodSync(asset.output, 0777);
success();
});
} else if (asset.type === "sound") {
createDirectoriesFor(asset.output);
unlink(asset.output);
fs.copyFile(asset.file, asset.output, (err) => {
if (err) {
console.error(err);
fail();
return;
}
asset.hash = hash;
let processedHash = fileHash(asset.output);
asset.processedHash = processedHash;
const packageRoutine = packageRoutines[package.name],
assets = packageRoutine.updateAsset(package.data, asset.name, asset);
fs.chmodSync(asset.output, 0777);
success();
});
} else if (asset.type === "map") {
createDirectoriesFor(asset.output);
unlink(asset.output);
fs.copyFile(asset.file, asset.output, (err) => {
if (err) {
console.error(err);
fail();
return;
}
asset.hash = hash;
let processedHash = fileHash(asset.output);
asset.processedHash = processedHash;
const packageRoutine = packageRoutines[package.name],
assets = packageRoutine.updateAsset(package.data, asset.name, asset);
fs.chmodSync(asset.output, 0777);
success();
});
} else {
success();
}
} else {
success();
}
});
};
// If this asset itself is a package, then we need to attempt to process it as a package before we
// process it as an asset. eg. data files in resources (sheets.json is both an asset and a package)
// FIXME: This promise shit is a mess, clean up this slop
if (asset.assets) {
let bothPromises = new Promise((success, fail) => {
processResources(asset).then(processAsset).then(() => {
success();
}, (err) => {
fail(err);
});
});
processingAssetsPromises.push(bothPromises);
} else {
processingAssetsPromises.push(processAsset());
}
});
// Do we have any assets processing? Wait on these first
if (processingAssetsPromises.length > 0) {
Promise.all(processingAssetsPromises).then(() => {
// Could be that nothing has changed
if (!updatedPackage) {
success();
return;
}
// Finalize any changes in the package
const packageRoutine = packageRoutines[package.name];
packageRoutine.finalize(package);
console.log("Saving package changes: " + package.name + " ==> " + package.file);
// Save package JSON (save .data)
const prettyCache = JSON.stringify(package.data, null, 2); // TODO Prettify cache json?
unlink(package.file);
fs.writeFile(package.file, prettyCache, {
mode: 0777
}, (err, bufferData) => {
if (err) {
console.error(err);
return;
}
fs.chmodSync(package.file, 0777);
console.log("Saved to " + package.file);
success();
});