-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
1081 lines (1004 loc) · 35.3 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
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
'use strict';
const { access } = require('fs/promises')
const BufferList = require('bl')
const { Duplex } = require('stream')
const fs = require('fs')
const iconv = require('iconv-lite')
const SpriteGroup = require('./grp.js')
const triggers = require('./triggers.js')
const SPRITES = require('./sprites.js')
const UNITS = require('./units.js')
// Currently read sections.
// If a section is not here, it will be ignored by getSections().
// type defines how multiple sections with same id are read.
// If section is smaller than min_size, it will be ignored, but a section
// larger than max_size will just be cut off at max_size.
// (Bw might actually be stricter with max_size and failing completely?)
// The section goes over any previous read sections,
// but leaves old data there if new data is shorter.
const SECTION_PARTIAL_OVERWRITE = 1
// The section replaces fully any previous sections.
const SECTION_FULL_OVERWRITE = 2
// The section behaves as if it just were appended at the end of a previous section.
const SECTION_APPEND = 3
const SECTION_TYPES = {
'MTXM': { type: SECTION_PARTIAL_OVERWRITE },
'STR\x20': { type: SECTION_PARTIAL_OVERWRITE, minSize: 2 },
'STRx': { type: SECTION_PARTIAL_OVERWRITE, minSize: 4 },
'ERA\x20': { type: SECTION_FULL_OVERWRITE, minSize: 2, maxSize: 2 },
'FORC': { type: SECTION_FULL_OVERWRITE, maxSize: 20 },
'OWNR': { type: SECTION_FULL_OVERWRITE, minSize: 12, maxSize: 12 },
'SIDE': { type: SECTION_FULL_OVERWRITE, minSize: 8, maxSize: 8 },
'SPRP': { type: SECTION_FULL_OVERWRITE, minSize: 4, maxSize: 4 },
'DIM\x20': { type: SECTION_FULL_OVERWRITE, minSize: 4, maxSize: 4 },
'UNIT': { type: SECTION_APPEND },
'THG2': { type: SECTION_APPEND },
'TRIG': { type: SECTION_APPEND },
'MBRF': { type: SECTION_APPEND },
'UNIS': { type: SECTION_FULL_OVERWRITE, minSize: 4048 },
'UNIx': { type: SECTION_FULL_OVERWRITE, minSize: 4168 },
}
const SPRITE_ID_MAX = 516
const UNIT_ID_RHYNADON = 89
const UNIT_ID_BENGALAAS = 90
const UNIT_ID_SCANTID = 93
const UNIT_ID_KAKARU = 94
const UNIT_ID_RAGNASAUR = 95
const UNIT_ID_URSADON = 96
const UNIT_ID_MINERAL1 = 176
const UNIT_ID_MINERAL3 = 178
const UNIT_ID_GEYSER = 188
const UNIT_ID_START_LOCATION = 214
const UNIT_ID_MAX = 227
const UNIT_TYPE_COUNT = UNIT_ID_MAX + 1
const isResource = unitId => (unitId >= UNIT_ID_MINERAL1 && unitId <= UNIT_ID_MINERAL3) ||
unitId === UNIT_ID_GEYSER
const isCritter = unitId => (
unitId === UNIT_ID_RHYNADON ||
unitId === UNIT_ID_BENGALAAS ||
unitId === UNIT_ID_RAGNASAUR ||
unitId === UNIT_ID_SCANTID ||
unitId === UNIT_ID_URSADON ||
unitId === UNIT_ID_KAKARU
)
const NEUTRAL_PLAYER = 11
// The colors are stored in tunit.pcx
const PLAYER_COLORS = [
[0x6f, 0x17, 0x17, 0x62, 0x5e, 0xab, 0xaa, 0xa8],
[0xa5, 0xa2, 0xa2, 0x2d, 0xa0, 0x2a, 0x29, 0x28],
[0x9f, 0x9e, 0x9e, 0x9e, 0x9d, 0x9d, 0x9d, 0xb6],
[0xa4, 0xa4, 0xa4, 0xa3, 0xa1, 0xa1, 0xa1, 0x5a],
[0x9c, 0xb3, 0x1c, 0x1a, 0x15, 0x12, 0x59, 0x56],
[0x13, 0x12, 0x12, 0x5c, 0x5c, 0x59, 0x58, 0x56],
[0x54, 0x53, 0x51, 0x4e, 0x96, 0x92, 0x90, 0x43],
[0x87, 0xa7, 0xa6, 0x81, 0x65, 0x61, 0x5c, 0x56],
[0xb9, 0xb8, 0xb8, 0xb8, 0xb7, 0xb7, 0xb7, 0xb6],
[0x88, 0x88, 0x84, 0x83, 0x81, 0x93, 0x63, 0x44],
[0x67, 0x72, 0x83, 0x82, 0x6b, 0x19, 0x16, 0x12],
[0x33, 0x33, 0x31, 0x31, 0x2d, 0x2d, 0xa0, 0x29],
]
const TILESET_NAMES = ['badlands', 'platform', 'install', 'ashworld', 'jungle', 'desert', 'ice',
'twilight']
const TILESET_NICE_NAMES = ['Badlands', 'Space', 'Installation', 'Ashworld', 'Jungle', 'Desert',
'Ice', 'Twilight']
const TRIGGER_ACTION_TRANSMISSION = 7
const TRIGGER_ACTION_MESSAGE = 9
const TRIGGER_ACTION_OBJECTIVES = 12
const TRIGGER_ACTION_LEADERBOARD_CONTROL = 17
const TRIGGER_ACTION_LEADERBOARD_CONTROL_LOCATION = 18
const TRIGGER_ACTION_LEADERBOARD_MONEY = 19
const TRIGGER_ACTION_LEADERBOARD_KILLS = 20
const TRIGGER_ACTION_LEADERBOARD_SCORE = 21
const TRIGGER_ACTION_LEADERBOARD_GOAL_CONTROL = 33
const TRIGGER_ACTION_LEADERBOARD_GOAL_CONTROL_LOCATION = 34
const TRIGGER_ACTION_LEADERBOARD_GOAL_MONEY = 35
const TRIGGER_ACTION_LEADERBOARD_GOAL_KILLS = 36
const TRIGGER_ACTION_LEADERBOARD_GOAL_SCORE = 37
const BRIEFING_ACTION_MESSAGE = 3
const BRIEFING_ACTION_OBJECTIVES = 4
const BRIEFING_ACTION_TRANSMISSION = 8
// Handles accessing, decoding, and caching bw's files.
class FileAccess {
constructor(cb) {
this.read = cb
this._tilesets = new Tilesets()
this._sprites = new SpriteGroup(UNITS, SPRITES)
}
async tileset(id) {
return await this._tilesets.tileset(id, this.read)
}
async unit(id) {
return await this._sprites.unit(id, this.read)
}
async sprite(id) {
return await this._sprites.sprite(id, this.read)
}
}
class ChkError extends Error {
constructor(desc) {
super(desc)
this.name = 'ChkError'
}
}
function getSections(buf) {
const sections = new Map()
sections.section = function(key) {
const result = this.get(key)
if (result === undefined) {
throw new ChkError(`Section ${key} does not exist`)
}
return result
}
let pos = 0
while (pos >= 0 && buf.length - pos >= 8) {
// Technically this is just 32-bit magic number,
// but any valid sections have "descriptive" names.
const sectionId = buf.toString('ascii', pos, pos + 4)
const sectionType = SECTION_TYPES[sectionId]
const length = buf.readInt32LE(pos + 4)
if (sectionType !== undefined) {
const minSize = sectionType.minSize || length
const maxSize = sectionType.maxSize || length
const acceptedLength = Math.min(length, maxSize)
if (acceptedLength >= minSize) {
const previous = sections.get(sectionId)
let buffer = null
if (acceptedLength < 0) {
buffer = buf.slice(pos + 8)
} else {
buffer = buf.slice(pos + 8, pos + 8 + acceptedLength)
}
if (previous !== undefined) {
switch (sectionType.type) {
case SECTION_PARTIAL_OVERWRITE:
if (previous.length > buffer.length) {
buffer = Buffer.concat([buffer, previous.slice(buffer.length)])
}
break
case SECTION_FULL_OVERWRITE:
// Do nothing, the buffer is fine as is
break
case SECTION_APPEND:
buffer = Buffer.concat([previous, buffer])
break
default:
throw new Error('Not supposed to be reachable')
}
}
sections.set(sectionId, buffer)
}
}
pos += length + 8
}
return sections
}
function triggerDisplayStrings(trigger) {
let result = []
for (let i = 0; i < 64; i++) {
const action = trigger.readUInt8(0x140 + i * 0x20 + 0x1a)
if (action === 0) {
break
}
switch (action) {
case TRIGGER_ACTION_TRANSMISSION:
case TRIGGER_ACTION_MESSAGE:
case TRIGGER_ACTION_OBJECTIVES:
case TRIGGER_ACTION_LEADERBOARD_CONTROL:
case TRIGGER_ACTION_LEADERBOARD_CONTROL_LOCATION:
case TRIGGER_ACTION_LEADERBOARD_MONEY:
case TRIGGER_ACTION_LEADERBOARD_KILLS:
case TRIGGER_ACTION_LEADERBOARD_SCORE:
case TRIGGER_ACTION_LEADERBOARD_GOAL_CONTROL:
case TRIGGER_ACTION_LEADERBOARD_GOAL_CONTROL_LOCATION:
case TRIGGER_ACTION_LEADERBOARD_GOAL_MONEY:
case TRIGGER_ACTION_LEADERBOARD_GOAL_KILLS:
case TRIGGER_ACTION_LEADERBOARD_GOAL_SCORE: {
const string = trigger.readUInt16LE(0x140 + i * 0x20 + 4)
if (string !== 0) {
result.push(string)
}
} break
}
}
return result
}
function briefingDisplayStrings(trigger) {
let result = []
for (let i = 0; i < 64; i++) {
const action = trigger.readUInt8(0x140 + i * 0x20 + 0x1a)
if (action === 0) {
break
}
switch (action) {
case BRIEFING_ACTION_TRANSMISSION:
case BRIEFING_ACTION_MESSAGE:
case BRIEFING_ACTION_OBJECTIVES: {
const string = trigger.readUInt16LE(0x140 + i * 0x20 + 4)
if (string !== 0) {
result.push(string)
}
} break
}
}
return result
}
class StrSection {
// `usedStrings` is required with 'auto' encoding, as there may be invalid strings
// in middle of valid ones. It is a lazily called callback returning array of string ids.
constructor(sections, encoding, usedStrings) {
const oldStr = sections.get('STR\x20')
const newStr = sections.get('STRx')
if (oldStr === undefined && newStr === undefined) {
throw new ChkError('Must have either STR\x20 or STRx section')
}
this._isExtended = newStr !== undefined
// Not actually sure which one has priority is both sections exist
const buf = this._isExtended ? newStr : oldStr
this._data = buf
if (!this._isExtended) {
if (buf.length < 2) {
this._amount = 0
} else {
const maxPossibleAmt = Math.floor((buf.length - 2) / 2)
this._amount = Math.min(buf.readUInt16LE(0), maxPossibleAmt)
}
} else {
if (buf.length < 4) {
this._amount = 0
} else {
const maxPossibleAmt = Math.floor((buf.length - 4) / 4)
this._amount = Math.min(buf.readUInt32LE(0), maxPossibleAmt)
}
}
if (encoding === 'auto') {
this.encoding = this._determineEncoding(usedStrings())
} else {
this.encoding = [encoding]
}
}
_rawStringSlice(index) {
if (index > this._amount || index === 0) {
return null
}
let offset = 0
if (this._isExtended) {
offset = this._data.readUInt32LE(index * 4)
} else {
offset = this._data.readUInt16LE(index * 2)
}
if (offset >= this._data.length) {
return null
}
const end = this._data.indexOf(0, offset)
return this._data.slice(offset, end)
}
// String indices are 1-based.
// 0 might be used at some parts for "no string"?
get(index) {
// Though bw may actually accept index 0 as well?
const slice = this._rawStringSlice(index)
let text = ''
if (slice === null) {
return text
}
for (let i = 0; i < this.encoding.length; i++) {
text = iconv.decode(slice, this.encoding[i])
if (i === this.encoding.length + 1 || !text.includes('\ufffd')) {
break
}
}
return text
}
// SC 1.16.1 used either cp949 or cp1252 encoding for all map strings depending
// on whether the system locale was set to Korea or not.
// SC:R on the other hand, considers each string separately,
// defaulting to UTF-8(*), and if the string cannot be decoded with UTF-8,
// SC:R guesses between 949 and 1252 based on the string contents.
//
// (*) Unit names(?) seem to have special handling to use 949 unless
// the 949-vs-1252 guess prefers 1252, in which case UTF-8 used if
// possible before falling back to 1252.
// Doesn't make much sense but that's how it appears to go.
//
// This library tries to do a bit better than SC:R does, as maps with full 1252/949
// encoding may have a few short strings that weren't intended to be UTF-8 but
// could be decoded using it. At the same time, we want to try to be compatible
// with maps that in do mix UTF-8 and legacy encoding -- they do exist, so when
// we detect the map be using UTF-8, the `get()` function will prefer UTF-8 with
// fallback to the other codepage like SC:R does.
//
// I have seen few maps that mixes 949/1252 encodings due to being edited over
// years(?) by different creators. Not trying to support such cases.. (For now?)
_determineEncoding(usedStrings) {
const isHangul = c => (c >= 0xac00 && c < 0xd7b0) || (c >= 0x3130 && c < 0x3190)
// Strings that seem to be Korean
let korStrings = 0
// Strings that don't seem to be Korean, but still have non-ASCII chars
let otherStrings = 0
// Strings that decode with UTF-8, and *are not 949 Korean strings*
let utf8Strings = 0
for (const string of usedStrings) {
const raw = this._rawStringSlice(string)
if (raw === null) {
continue
}
const korean = iconv.decode(raw, 'cp949')
const utf8 = iconv.decode(raw, 'utf8')
let hangulChars = 0
let otherNonAscii = 0
const nonAscii1252 = new Set()
for (const char of raw) {
if (char >= 0x80) {
nonAscii1252.add(char)
}
}
const isValidUtf8 = !utf8.includes('\ufffd')
for (let idx = 0; idx < korean.length; idx++) {
const code = korean.charCodeAt(idx)
if (code === 0xfffd) {
// Replacement character - was not valid 949 encoding
// Sometimes there may be maps that have been edited in both encodings,
// so just take this as a heavy hint towards 1252
if (!isValidUtf8) {
otherStrings = otherStrings + 5
}
hangulChars = 0
break
} else if (isHangul(code)) {
hangulChars++
} else if (code > 0x80) {
otherNonAscii++
}
}
// Since some 1252 characters can appear as hangul, if there is only a single
// non-ascii character used, assume it is 1252.
const hadHangul = hangulChars >= 1 && nonAscii1252.size >= 2
if (isValidUtf8 && nonAscii1252.size > 10) {
// More than 10 non-ASCII chars and valid UTF-8; this map definitely
// should be counted as having UTF-8 strings.
utf8Strings += 50
} else if (hadHangul && hangulChars >= 5) {
korStrings++
} else if (hadHangul && hangulChars >= 1 && hangulChars > otherNonAscii) {
korStrings++
} else if (nonAscii1252.size > 0) {
if (isValidUtf8) {
utf8Strings++
} else {
otherStrings++
}
}
}
const nonUtf8Encoding = korStrings >= otherStrings ? 'cp949' : 'cp1252'
let useUtf8 = false
if (nonUtf8Encoding === 'cp949') {
if (utf8Strings > 5 || (utf8Strings > 0 && korStrings < 20)) {
useUtf8 = true
}
} else {
if (utf8Strings > 10 || (utf8Strings > 0 && otherStrings < 20)) {
useUtf8 = true
}
}
if (useUtf8) {
if (nonUtf8Encoding === 'cp949' && korStrings === 0) {
return ['utf8']
} else {
return ['utf8', nonUtf8Encoding]
}
} else {
return [nonUtf8Encoding]
}
}
}
module.exports = class Chk {
constructor(buf, options) {
const opts = Object.assign({
encoding: 'auto',
}, options)
const sections = getSections(buf)
// FORC gets zero-padded if it is smaller than 14 bytes.
// Do any other sections?
let forceSection = sections.section('FORC')
if (forceSection.length < 20) {
const oldLength = forceSection.length
forceSection = Buffer.concat([forceSection, Buffer.alloc(20 - oldLength)])
forceSection.fill(0, oldLength)
}
const usedStrings = () => this._usedStringIds(forceSection, sections)
this._usedStrings = usedStrings()
this._strings = new StrSection(sections, opts.encoding, usedStrings)
if (this._strings.encoding.length === 1) {
this._encoding = this._strings.encoding[0]
} else {
this._encoding = 'mixed'
}
[this.title, this.description] = this._parseScenarioProperties(sections.section('SPRP'))
.map(index => this._strings.get(index))
this.tileset = this._parseTileset(sections.section('ERA\x20'))
this.tilesetName = TILESET_NICE_NAMES[this.tileset]
this.size = this._parseDimensions(sections.section('DIM\x20'));
[this.forces, this._maxMeleePlayers] =
this._parsePlayers(forceSection, sections.section('OWNR'), sections.section('SIDE'))
this._tiles = sections.section('MTXM');
[this.units, this.sprites] =
this._parseUnits(sections.section('UNIT'), sections.section('THG2'))
const triggerBuf = sections.get('TRIG')
if (triggerBuf !== undefined) {
this._triggers = new triggers.Triggers(this._strings, triggerBuf)
} else {
this._triggers = new triggers.Triggers(this._strings, Buffer.alloc(0))
}
}
static createStream(callback) {
const stream = new Duplex({ readableObjectMode: true })
const buf = new BufferList()
stream._write = (data, enc, done) => {
buf.append(data)
done()
}
stream._read = () => {
}
stream.on('finish', () => {
let chk = null
try {
chk = new Chk(buf.slice())
} catch (err) {
if (callback) {
callback(err)
} else {
stream.emit('error', err)
}
return
}
if (callback) {
callback(undefined, chk)
}
stream.push(chk)
stream.push(null)
})
return stream
}
encoding() {
return this._encoding
}
maxPlayers(ums) {
if (ums) {
return this.forces.reduce((accum, force) => (
accum + force.players.filter(player => !player.computer).length
), 0)
} else {
return this._maxMeleePlayers
}
}
triggers() {
return this._triggers
}
isEudMap() {
for (const trigger of this.triggers()) {
const bytes = trigger.rawByteView()
for (let i = 0, pos = 0; i < 0x10; i++, pos += 0x14) {
if (bytes[pos + 0xf] === 0xf && bytes[pos + 0xe] < 0xc) {
const player = bytes[pos + 0x4]
if (player === 0xc || player > 0x1a || bytes.readUInt16LE(pos + 0xc) > 0xe8) {
return true
}
}
}
for (let i = 0, pos = 0x140; i < 0x40; i++, pos += 0x20) {
if (bytes[pos + 0x1a] === 0x2d && bytes[pos + 0x1b] < 0xc) {
const player = bytes[pos + 0x10]
if (player === 0xc || player > 0x1a || bytes.readUInt16LE(pos + 0x18) > 0xe8) {
return true
}
}
}
}
return false
}
static actionIds() {
return triggers.actionIds
}
static conditionIds() {
return triggers.conditionIds
}
// Creates a FileAccess object, where `directory` contains bw's sprite and tileset files.
//
// Used for `Chk.image()`. Keeping the same object between multiple `image()` calls will
// cache file accesses, reducing execution time.
static fsFileAccess(directory) {
return Chk.customFileAccess(async (fname, isOptional = false) => {
const filePath = directory + '/' + fname.replace(/\\/g, '/')
if (isOptional) {
try {
await access(filePath)
} catch {
return null
}
}
return new Promise((res, rej) => {
fs.createReadStream(filePath)
.pipe(new BufferList((err, buf) => {
if (err) {
rej(err)
} else {
res(buf)
}
}))
})
})
}
// Creates a FileAccess object with a custom file reading function `callback`.
//
// `callback` is a function receiving 2 parameters:
// - the filename of the file to be read
// - whether the file is optional (that is, whether it not being present is an error)
//
// `callback` must return a `Promise`, which resolves to a `Buffer` (-like object, BufferList is
// fine as well), containing the file. If the file is optional, `null` is also a valid return
// value, and signals the file was not present.
static customFileAccess(callback) {
return new FileAccess(callback)
}
// Returns a 24-bit RGB buffer containing the image or throws an `Error`.
//
// `fileAccess` is created either from `Chk.fsFileAccess(directory)` or
// `Chk.customFileAccess(callback)`.
//
// `options` is an object containing additional options. The currently supported options
// (and their defaults) are:
// ```
// {
// // Whether to render only units which exist in melee games: Start locations, neutral
// // resources and neutral unit sprites.
// melee: false,
// // Whether to render player start locations.
// startLocations: true,
// }
// ```
async image(fileAccess, width, height, options) {
const opts = Object.assign({
melee: false,
startLocations: true,
}, options)
const out = Buffer.alloc(width * height * 3)
const tileset = await fileAccess.tileset(this.tileset)
this._renderTerrain(tileset, out, width, height)
const mapWidthPixels = this.size[0] * 32
const mapHeightPixels = this.size[1] * 32
const scaleX = width / mapWidthPixels
const scaleY = height / mapHeightPixels
const palette = tileset.palette
await this._renderSprites(fileAccess, palette, out, width, height, scaleX, scaleY, opts)
return out
}
// Renders the terrain using hopefully-somewhat-fast method, which creates
// low-resolution tiles and then just copies them into buffer without further scaling.
// A drawback to this method is that the tile boundaries are easy to recognize
// from the final image when there are large areas of flat terrain.
_renderTerrain(tileset, out, width, height) {
const ceil = Math.ceil
const floor = Math.floor
const pixelsPerMegaX = width / this.size[0]
const pixelsPerMegaY = height / this.size[1]
const higher = Math.max(pixelsPerMegaX, pixelsPerMegaY)
let pixelsPerMega = Math.pow(2, ceil(Math.log2(higher)))
if (pixelsPerMega < 1) {
pixelsPerMega = 1
}
const scale = pixelsPerMega / 32
const megatiles = generateScaledMegatiles(tileset, pixelsPerMega)
let outPos = 0
let yPos = 0
// How many bw pixels are added for each target image pixel.
// (Not necessarily a integer)
const mapWidthPixels = this.size[0] * 32
const mapHeightPixels = this.size[1] * 32
const widthAdd = mapWidthPixels / width
const heightAdd = mapHeightPixels / height
const bytesPerMega = pixelsPerMega * pixelsPerMega * 3
const bytesPerMegaRow = pixelsPerMega * 3
let y = 0
while (y < height) {
const megaY = floor(yPos / 32)
// How many pixels tall is the current row of tiles.
// Not necessarily same for all rows, if using a strange scale.
const megaHeight = ceil(((floor(yPos / 32) + 1) * 32 - yPos) / heightAdd)
const mapTilePos = megaY * this.size[0] * 2
let xPos = 0
let x = 0
while (x < width) {
const megaX = floor(xPos / 32)
const megaWidth = ceil(((floor(xPos / 32) + 1) * 32 - xPos) / widthAdd)
let tileId = 0
if (mapTilePos + megaX * 2 + 2 > this._tiles.length) {
tileId = 0
} else {
tileId = this._tiles.readUInt16LE(mapTilePos + megaX * 2)
}
const tileGroup = tileId >> 4
const groupIndex = tileId & 0xf
const groupOffset = 2 + tileGroup * 0x34 + 0x12 + groupIndex * 2
let megatileId = 0
if (groupOffset + 2 > tileset.tilegroup.length) {
megatileId = 0
} else {
megatileId = tileset.tilegroup.readUInt16LE(groupOffset)
}
const megaBase = megatileId * bytesPerMega
// Draw the tile.
let writePos = outPos + x * 3
let currentTileY = yPos % 32
const currentTileLeft = xPos % 32
for (let tileY = 0; tileY < megaHeight; tileY++) {
const scaledY = floor(currentTileY * scale)
const megaLineBase = megaBase + scaledY * bytesPerMegaRow
let currentTileX = currentTileLeft
for (let tileX = 0; tileX < megaWidth; tileX++) {
const megaOffset = megaLineBase + floor(currentTileX * scale) * 3
out[writePos] = megatiles[megaOffset]
out[writePos + 1] = megatiles[megaOffset + 1]
out[writePos + 2] = megatiles[megaOffset + 2]
writePos = writePos + 3
currentTileX = currentTileX + widthAdd
}
currentTileY = currentTileY + heightAdd
writePos = writePos + (width - megaWidth) * 3
}
x = x + megaWidth
xPos = xPos + megaWidth * widthAdd
}
yPos = yPos + megaHeight * heightAdd
y = y + megaHeight
outPos = outPos + width * megaHeight * 3
}
}
async _renderSprites(fileAccess, palette, surface, width, height, scaleX, scaleY, opts) {
const startLocationCheck = u => u.unitId !== UNIT_ID_START_LOCATION || opts.startLocations
const meleeCheck = u => {
if (!opts.melee) {
return true
}
if (u.sprite) {
return u.player === NEUTRAL_PLAYER
}
if (u.unitId === UNIT_ID_START_LOCATION) {
return true
}
if (u.player === NEUTRAL_PLAYER && (isResource(u.unitId) || isCritter(u.unitId))) {
return true
}
return false
}
// TODO: Could order these correctly
for (const sprite of this.sprites) {
// Draw invalid sprites as the ashworld doodad of death.
const drawnSpriteId = sprite.spriteId > SPRITE_ID_MAX ? 0 : sprite.spriteId
const grp = await fileAccess.sprite(drawnSpriteId)
const x = sprite.x * scaleX
const y = sprite.y * scaleY
grp.render(0, palette, surface, x, y, width, height, scaleX, scaleY)
}
// Make a copy of palette to change the player colors as needed.
const localPalette = Buffer.from(palette)
for (const unit of this.units) {
if (!startLocationCheck(unit) || !meleeCheck(unit)) {
continue
}
setToPlayerPalette(unit.player, localPalette)
// Maps can contain invalid units, we'll just render them as marines
const drawnUnitId = unit.unitId > UNIT_ID_MAX ? 0 : unit.unitId
const sprite = await fileAccess.unit(drawnUnitId)
const x = unit.x * scaleX
const y = unit.y * scaleY
let frame = 0
if (unit.resourceAmt !== undefined) {
// Bw doesn't actually hardcode the frames,
// it calls an iscript animation that sets the frame.
if (unit.resourceAmt >= 750) {
frame = 0
} else if (unit.resourceAmt >= 500) {
frame = 1
} else if (unit.resourceAmt >= 250) {
frame = 2
} else {
frame = 3
}
}
// Another iscript thing.
if (unit.unitId === UNIT_ID_GEYSER) {
frame = this.tileset
}
sprite.render(frame, localPalette, surface, x, y, width, height, scaleX, scaleY)
}
}
// Ugly signature
_usedStringIds(forceSection, sections) {
let result = []
result = result.concat(this._parseScenarioProperties(sections.section('SPRP')))
for (let i = 0; i < 4; i++) {
result.push(forceSection.readUInt16LE(8 + i * 2))
}
const collectTriggerStrings = (section, briefing) => {
if (section !== undefined) {
for (let pos = 0; pos + 2400 <= section.length; pos += 2400) {
let strings = []
if (briefing) {
strings = briefingDisplayStrings(section.slice(pos, pos + 2400))
} else {
strings = triggerDisplayStrings(section.slice(pos, pos + 2400))
}
if (strings.length !== 0) {
result = result.concat(strings)
}
}
}
}
collectTriggerStrings(sections.get('TRIG'), false)
collectTriggerStrings(sections.get('MBRF'), true)
const unitStats = sections.get('UNIx') || sections.get('UNIS')
if (unitStats !== undefined) {
// The UNIx and UNIS are actually different from the end, but we don't read that far
for (let i = 0; i < UNIT_TYPE_COUNT; i++) {
if (unitStats.readUInt8(i) === 0) {
const string = unitStats.readUInt16LE(14 * UNIT_TYPE_COUNT + i * 2)
if (string !== 0) {
result.push(string)
}
}
}
}
return result
}
// Returns string indices [mapTitle, mapDescription]
_parseScenarioProperties(data) {
return [data.readUInt16LE(0), data.readUInt16LE(2)]
}
// Just happens to do the same thing as parseScenarioProperties
_parseDimensions(data) {
return [data.readUInt16LE(0), data.readUInt16LE(2)]
}
_parseTileset(data) {
return data.readUInt16LE(0) & 0x7
}
// Respective chk sections are FORC, OWNR, SIDE.
_parsePlayers(forceData, playerData, raceData) {
const forces = [{}, {}, {}, {}]
for (let i = 0; i < 4; i += 1) {
forces[i].name = this._strings.get(forceData.readUInt16LE(8 + i * 2))
// 0x1 = Random start loca, 0x2 = Allied, 0x4 = Allied victory, 0x8 = Shared vision.
forces[i].flags = forceData.readUInt8(16 + i)
forces[i].players = []
}
let maxPlayers = 0
for (let i = 0; i < 8; i += 1) {
const player = this._parsePlayer(i, playerData, raceData)
if (player !== null) {
maxPlayers += 1
const playerForce = forceData.readUInt8(i)
// If player does not belong in any of the 4 forces,
// their slot is not available in UMS games, but
// otherwise it works fine.
if (playerForce < 4) {
forces[playerForce].players.push(player)
}
}
}
return [forces, maxPlayers]
}
// Returns null if the player is inactive.
_parsePlayer(id, playerData, raceData) {
if (playerData.length < id) {
throw new ChkError(`OWNR is too short (${playerData.length})`)
}
if (raceData.length < id) {
throw new ChkError(`SIDE is too short (${raceData.length})`)
}
const race = raceData.readUInt8(id)
const player = {
id,
race,
computer: true,
typeId: playerData.readUInt8(id),
}
// TODO: Not sure which players are actually inactive
switch (player.typeId) {
case 1:
// Spawns in game, not in lobby, is enemy, is more aggressive than 2 and 4 (what)
player.type = 'unknown'
break
case 2:
case 4:
// Spawns in game, not in lobby, is enemy
player.type = 'unknown'
break
case 3:
player.type = 'rescueable'
break
case 5:
player.type = 'computer'
break
case 6:
player.type = 'human'
player.computer = false
break
case 7:
player.type = 'neutral'
break
default:
return null
}
return player
}
_parseUnits(unitData, spriteData) {
const units = []
const sprites = []
const width = this.size[0] * 32
const height = this.size[1] * 32
let pos = 0
while (pos + 36 <= unitData.length) {
const x = unitData.readUInt16LE(pos + 4)
const y = unitData.readUInt16LE(pos + 6)
const unitId = unitData.readUInt16LE(pos + 8)
const player = unitData.readUInt8(pos + 16)
if (x < width && y < height) {
if (isResource(unitId)) {
const resourceAmt = unitData.readUInt32LE(pos + 20)
units.push({x, y, unitId, player, resourceAmt})
} else {
units.push({x, y, unitId, player})
}
}
pos = pos + 36
}
pos = 0
while (pos + 10 <= spriteData.length) {
const x = spriteData.readUInt16LE(pos + 2)
const y = spriteData.readUInt16LE(pos + 4)
if (x < width && y < height) {
if ((spriteData.readUInt16LE(pos + 8) & 0x1000) === 0) {
const unitId = spriteData.readUInt16LE(pos + 0)
const player = spriteData.readUInt8(pos + 6)
units.push({x, y, unitId, player, sprite: true})
} else {
const spriteId = spriteData.readUInt16LE(pos + 0)
sprites.push({x, y, spriteId})
}
}
pos = pos + 10
}
return [units, sprites]
}
}
class Tilesets {
constructor() {
this._tilesets = []
this._incompleteTilesets = []
}
async tileset(id, readCb) {
if (id >= TILESET_NAMES.length) {
throw Error(`Invalid tileset id: ${id}`)
}
const tileset = this._tilesets[id]
if (tileset) {
return tileset
}
if (!this._incompleteTilesets[id]) {
this._addFiles(id, readCb)
}
await this._incompleteTilesets[id]
return this._tilesets[id]
}
_addFiles(tilesetId, readCb) {
const path = `tileset/${TILESET_NAMES[tilesetId]}`
// NOTE(tec27): vx4ex were added in Remastered and contain some additional tiles used by newer
// maps, but are not necessary for older maps.
const promises = ['.cv5', '.vx4', '.vr4', '.wpe']
.map(extension => {
if (extension === '.vx4') {
return readCb(path + '.vx4ex', true)
.then(
async x => {
if (x === null) {
return [await readCb(path + '.vx4'), false]
} else {
return [x, true]
}
},
async () => [await readCb(path + '.vx4'), false],
)
} else {
return readCb(path + extension, false)
}
})
const promise = Promise.all(promises)
.then(files => {
this._incompleteTilesets[tilesetId] = null
const [megatiles, isExtended] = files[1]
this._addBuffers(tilesetId, files[0], megatiles, files[2], files[3], isExtended)
})
this._incompleteTilesets[tilesetId] = promise
}
_addBuffers(tilesetId, tilegroup, megatiles, minitiles, palette, isExtended) {
this._tilesets[tilesetId] = {
tilegroup,
isExtended,
megatiles,
minitiles,
palette,
scaledMegatileCache: [],