/
crystal.py
8810 lines (7689 loc) · 357 KB
/
crystal.py
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
# -*- coding: utf-8 -*-
#utilities to help disassemble pokémon crystal
import sys, os, inspect, md5, json
from copy import copy, deepcopy
import subprocess
from new import classobj
import random
#for IntervalMap
from bisect import bisect_left, bisect_right
from itertools import izip
#for testing all this crap
try:
import unittest2 as unittest
except ImportError:
import unittest
# for capwords
import string
# Check for things we need in unittest.
if not hasattr(unittest.TestCase, 'setUpClass'):
sys.stderr.write("The unittest2 module or Python 2.7 is required to run this script.")
sys.exit(1)
if not hasattr(json, "dumps"):
json.dumps = json.write
# New versions of json don't have read anymore.
if not hasattr(json, "read"):
json.read = json.loads
spacing = "\t"
lousy_dragon_shrine_hack = [0x18d079, 0x18d0a9, 0x18d061, 0x18d091]
#table of pointers to map groups
#each map group contains some number of map headers
map_group_pointer_table = 0x94000
map_group_count = 26
map_group_offsets = []
map_header_byte_size = 9
second_map_header_byte_size = 12
#event segment sizes
warp_byte_size = 5
trigger_byte_size = 8
signpost_byte_size = 5
people_event_byte_size = 13
#a message to show with NotImplementedErrors
bryan_message = "bryan hasn't got to this yet"
max_texts = 3
text_count = 0
texts = []
#these appear outside of quotes (see pokered/extras/pretty_map_headers.py)
#this doesn't do anything but is still used in TextScript
constant_abbreviation_bytes = {}
# Import the characters from its module.
from chars import chars, jap_chars
from trainers import *
from move_constants import moves
# for fixing trainer_group_names
import re
trainer_group_pointer_table_address = 0x39999
trainer_group_pointer_table_address_gs = 0x3993E
class Size():
"""a simple way to track whether or not a size
includes the first value or not, like for
whether or not the size of a command in a script
also includes the command byte or not"""
def __init__(self, size, inclusive=False):
self.inclusive = inclusive
if inclusive: size = size-1
self.size = size
def inclusive(self):
return self.size + 1
def exclusive(self):
return self.size
class IntervalMap(object):
"""
This class maps a set of intervals to a set of values.
>>> i = IntervalMap()
>>> i[0:5] = "hello world"
>>> i[6:10] = "hello cruel world"
>>> print i[4]
"hello world"
"""
def __init__(self):
"""initializes an empty IntervalMap"""
self._bounds = []
self._items = []
self._upperitem = None
def __setitem__(self, _slice, _value):
"""sets an interval mapping"""
assert isinstance(_slice, slice), 'The key must be a slice object'
if _slice.start is None:
start_point = -1
else:
start_point = bisect_left(self._bounds, _slice.start)
if _slice.stop is None:
end_point = -1
else:
end_point = bisect_left(self._bounds, _slice.stop)
if start_point>=0:
if start_point < len(self._bounds) and self._bounds[start_point]<_slice.start:
start_point += 1
if end_point>=0:
self._bounds[start_point:end_point] = [_slice.start, _slice.stop]
if start_point < len(self._items):
self._items[start_point:end_point] = [self._items[start_point], _value]
else:
self._items[start_point:end_point] = [self._upperitem, _value]
else:
self._bounds[start_point:] = [_slice.start]
if start_point < len(self._items):
self._items[start_point:] = [self._items[start_point], _value]
else:
self._items[start_point:] = [self._upperitem]
self._upperitem = _value
else:
if end_point>=0:
self._bounds[:end_point] = [_slice.stop]
self._items[:end_point] = [_value]
else:
self._bounds[:] = []
self._items[:] = []
self._upperitem = _value
def __getitem__(self,_point):
"""gets a value from the mapping"""
assert not isinstance(_point, slice), 'The key cannot be a slice object'
index = bisect_right(self._bounds, _point)
if index < len(self._bounds):
return self._items[index]
else:
return self._upperitem
def items(self):
"""returns an iterator with each item being
((low_bound, high_bound), value)
these items are returned in order"""
previous_bound = None
for (b, v) in izip(self._bounds, self._items):
if v is not None:
yield (previous_bound, b), v
previous_bound = b
if self._upperitem is not None:
yield (previous_bound, None), self._upperitem
def values(self):
"""returns an iterator with each item being a stored value
the items are returned in order"""
for v in self._items:
if v is not None:
yield v
if self._upperitem is not None:
yield self._upperitem
def __repr__(self):
s = []
for b,v in self.items():
if v is not None:
s.append('[%r, %r] => %r'%(
b[0],
b[1],
v
))
return '{'+', '.join(s)+'}'
# ---- script_parse_table explanation ----
# This is an IntervalMap that keeps track of previously parsed scripts, texts
# and other objects. Anything that has a location in the ROM should be mapped
# to an interval (a range of addresses) in this structure. Each object that is
# assigned to an interval should implement attributes or methods like:
# ATTRIBUTE/METHOD EXPLANATION
# label what the heck to call the object
# address where it begins
# to_asm() spit out asm (not including label)
#keys are intervals "500..555" of byte addresses for each script
#last byte is not inclusive(?) really? according to who??
#this is how to make sure scripts are not recalculated
script_parse_table = IntervalMap()
def is_script_already_parsed_at(address):
"""looks up whether or not a script is parsed at a certain address"""
if script_parse_table[address] == None: return False
return True
def script_parse_table_pretty_printer():
"""helpful debugging output"""
for each in script_parse_table.items():
print each
def map_name_cleaner(input):
"""generate a valid asm label for a given map name"""
return input.replace(":", "").\
replace("(", "").\
replace(")", "").\
replace("'", "").\
replace("/", "").\
replace(",", "").\
replace(".", "").\
replace("Pokémon Center", "PokeCenter").\
replace("é", "e").\
replace("-", "").\
replace("Hooh", "HoOh").\
replace("hooh", "HoOh").\
replace(" ", "")
from romstr import RomStr, AsmList
rom = RomStr(None)
def direct_load_rom(filename="../baserom.gbc"):
"""loads bytes into memory"""
global rom
file_handler = open(filename, "rb")
rom = RomStr(file_handler.read())
file_handler.close()
return rom
def load_rom(filename="../baserom.gbc"):
"""checks that the loaded rom matches the path
and then loads the rom if necessary."""
global rom
if rom != RomStr(None) and rom != None:
return rom
if not isinstance(rom, RomStr):
return direct_load_rom(filename=filename)
elif os.lstat(filename).st_size != len(rom):
return direct_load_rom(filename)
def load_asm(filename="../main.asm"):
"""loads the asm source code into memory"""
global asm
asm = open(filename, "r").read().split("\n")
asm = AsmList(asm)
return asm
def grouper(some_list, count=2):
"""splits a list into sublists
given: [1, 2, 3, 4]
returns: [[1, 2], [3, 4]]"""
return [some_list[i:i+count] for i in range(0, len(some_list), count)]
def is_valid_address(address):
"""is_valid_rom_address"""
if address == None: return False
if type(address) == str:
address = int(address, 16)
if 0 <= address <= 2097152: return True
else: return False
def rom_interval(offset, length, strings=True, debug=True):
"""returns hex values for the rom starting at offset until offset+length"""
global rom
return rom.interval(offset, length, strings=strings, debug=debug)
def rom_until(offset, byte, strings=True, debug=True):
"""returns hex values from rom starting at offset until the given byte"""
global rom
return rom.until(offset, byte, strings=strings, debug=debug)
def how_many_until(byte, starting):
index = rom.find(byte, starting)
return index - starting
def load_map_group_offsets():
"""reads the map group table for the list of pointers"""
global map_group_pointer_table, map_group_count, map_group_offsets
global rom
map_group_offsets = [] #otherwise this method can only be used once
data = rom_interval(map_group_pointer_table, map_group_count*2, strings=False)
data = grouper(data)
for pointer_parts in data:
pointer = pointer_parts[0] + (pointer_parts[1] << 8)
offset = pointer - 0x4000 + map_group_pointer_table
map_group_offsets.append(offset)
return map_group_offsets
from pointers import calculate_bank, calculate_pointer
def calculate_pointer_from_bytes_at(address, bank=False):
"""calculates a pointer from 2 bytes at a location
or 3-byte pointer [bank][2-byte pointer] if bank=True"""
if bank == True:
bank = ord(rom[address])
address += 1
elif bank == False or bank == None:
bank = calculate_bank(address)
elif bank == "reverse" or bank == "reversed":
bank = ord(rom[address+2])
elif type(bank) == int:
pass
else:
raise Exception, "bad bank given to calculate_pointer_from_bytes_at"
byte1 = ord(rom[address])
byte2 = ord(rom[address+1])
temp = byte1 + (byte2 << 8)
if temp == 0:
return None
return calculate_pointer(temp, bank)
def clean_up_long_info(long_info):
"""cleans up some data from parse_script_engine_script_at formatting issues"""
long_info = str(long_info)
#get rid of the first newline
if long_info[0] == "\n":
long_info = long_info[1:]
#get rid of the last newline and any leftover space
if long_info.count("\n") > 0:
if long_info[long_info.rindex("\n")+1:].isspace():
long_info = long_info[:long_info.rindex("\n")]
#remove spaces+hash from the front of each line
new_lines = []
for line in long_info.split("\n"):
line = line.strip()
if line[0] == "#":
line = line[1:]
new_lines.append(line)
long_info = "\n".join(new_lines)
return long_info
def command_debug_information(command_byte=None, map_group=None, map_id=None, address=0, info=None, long_info=None, pksv_name=None):
"used to help debug in parse_script_engine_script_at"
info1 = "parsing command byte " + hex(command_byte) + " for map " + \
str(map_group) + "." + str(map_id) + " at " + hex(address)
info1 += " pksv: " + str(pksv_name)
#info1 += " info: " + str(info)
#info1 += " long_info: " + long_info
return info1
all_texts = []
class TextScript:
""" A text is a sequence of bytes (and sometimes commands). It's not the
same thing as a Script. The bytes are translated into characters based
on the lookup table (see chars.py). The in-text commands are for including
values from RAM, playing sound, etc.
see: http://hax.iimarck.us/files/scriptingcodes_eng.htm#InText
"""
base_label = "UnknownText_"
def __init__(self, address, map_group=None, map_id=None, debug=False, label=None, force=False, show=None):
self.address = address
# $91, $84, $82, $54, $8c
# 0x19768c is a a weird problem?
if address in [0x26ef, 0x26f2, 0x6ee, 0x1071, 0x5ce33, 0x69523, 0x7ee98, 0x72176, 0x7a578, 0x19c09b, 0x19768c]:
return None
self.map_group, self.map_id, self.debug = map_group, map_id, debug
self.dependencies = None
self.commands = None
self.force = force
if is_script_already_parsed_at(address) and not force:
raise Exception, "TextScript already parsed at "+hex(address)
if not label:
label = self.base_label + hex(address)
self.label = Label(name=label, address=address, object=self)
self.parse()
def is_valid(self):
return not (self.address in [0x26ef, 0x26f2, 0x6ee, 0x1071, 0x5ce33, 0x69523, 0x7ee98, 0x72176, 0x7a578, 0x19c09b, 0x19768c])
# hmm this looks exactly like Script.get_dependencies (which makes sense..)
def get_dependencies(self, recompute=False, global_dependencies=set()):
if self.address in [0x26ef, 0x26f2, 0x6ee, 0x1071, 0x5ce33, 0x69523, 0x7ee98, 0x72176, 0x7a578, 0x19c09b, 0x19768c]:
return []
if self.dependencies != None and not recompute:
global_dependencies.update(self.dependencies)
return self.dependencies
dependencies = []
for command in self.commands:
deps = command.get_dependencies(recompute=recompute, global_dependencies=global_dependencies)
dependencies.extend(deps)
self.dependencies = dependencies
return self.dependencies
# this is almost an exact copy of Script.parse
# with the exception of using text_command_classes instead of command_classes
def parse(self):
if self.address in [0x26ef, 0x26f2, 0x6ee, 0x1071, 0x5ce33, 0x69523, 0x7ee98, 0x72176, 0x7a578, 0x19c09b, 0x19768c]:
return None
global text_command_classes, script_parse_table
current_address = copy(self.address)
start_address = copy(current_address)
# don't clutter up my screen
if self.debug:
print "NewTextScript.parse address="+hex(self.address)+" map_group="+str(self.map_group)+" map_id="+str(self.map_id)
# load up the rom if it hasn't been loaded already
load_rom()
# in the event that the script parsing fails.. it would be nice to leave evidence
script_parse_table[start_address:start_address+1] = "incomplete NewTextScript.parse"
# start with a blank script
commands = []
# use this to control the while loop
end = False
# for each command found...
while not end:
# get the current scripting byte
cur_byte = ord(rom[current_address])
# reset the command class (last command was probably different)
scripting_command_class = None
# match the command id byte to a scripting command class like MainText
for class_ in text_command_classes:
if class_[1].id == cur_byte:
scripting_command_class = class_[1]
if self.address == 0x9c00e and self.debug:
if current_address > 0x9c087:
print "self.commands is: " + str(commands)
print "command 0 address is: " + hex(commands[0].address) + " last_address="+hex(commands[0].last_address)
print "command 1 address is: " + hex(commands[1].address) + " last_address="+hex(commands[1].last_address)
raise Exception, "going beyond the bounds for this text script"
# no matching command found
if scripting_command_class == None:
raise Exception, "unable to parse text command $%.2x in the text script at %s at %s" % (cur_byte, hex(start_address), hex(current_address))
# create an instance of the command class and let it parse its parameter bytes
cls = scripting_command_class(address=current_address, map_group=self.map_group, map_id=self.map_id, debug=self.debug, force=self.force)
if self.debug:
print cls.to_asm()
# store it in this script object
commands.append(cls)
# certain commands will end the scripting engine
end = cls.end
# skip past the command's parameter bytes to go to the next command
#current_address += cls.size
current_address = cls.last_address
# last byte belonging to script is last byte of last command,
# or the last byte of the last command's last parameter
# (actually i think this might be the next byte after??)
self.last_address = current_address
if self.debug:
print "cls.address is: " + hex(cls.address)
print "cls.size is: " + hex(cls.size)
print "cls.last_address is: " + hex(cls.last_address)
print "self.last_address is: " + hex(self.last_address)
assert self.last_address == (cls.address + cls.size), "the last address should equal the last command's (address + size)"
assert self.last_address == cls.last_address, "the last address of the TextScript should be the last_address of its last command"
# just some debugging..
if self.debug:
last_address = self.last_address
print "TextScript last_address == " + hex(last_address)
#assert last_address != 0x5db06, "TextScript.parse somehow has a text with a last_address of 0x5db06 instead of 0x5db07"
# store the script in the global table/map thing
script_parse_table[start_address:current_address] = self
all_texts.append(self)
if self.debug:
asm_output = "\n".join([command.to_asm() for command in commands])
print "--------------\n"+asm_output
# store the script
self.commands = commands
return commands
def to_asm(self):
if self.address in [0x26ef, 0x26f2, 0x6ee, 0x1071, 0x5ce33, 0x69523, 0x7ee98, 0x72176, 0x7a578, 0x19c09b, 0x19768c]:
return None
asm_output = "\n".join([command.to_asm() for command in self.commands])
return asm_output
class OldTextScript:
"a text is a sequence of commands different from a script-engine script"
base_label = "UnknownText_"
def __init__(self, address, map_group=None, map_id=None, debug=True, show=True, force=False, label=None):
self.address = address
self.map_group, self.map_id, self.debug, self.show, self.force = map_group, map_id, debug, show, force
if not label:
label = self.base_label + hex(address)
self.label = Label(name=label, address=address, object=self)
self.dependencies = []
self.parse_text_at(address)
@staticmethod
def find_addresses():
"""returns a list of text pointers
useful for testing parse_text_engine_script_at
Note that this list is not exhaustive. There are some texts that
are only pointed to from some script that a current script just
points to. So find_all_text_pointers_in_script_engine_script will
have to recursively follow through each script to find those.
.. it does this now :)
"""
addresses = set()
#for each map group
for map_group in map_names:
#for each map id
for map_id in map_names[map_group]:
#skip the offset key
if map_id == "offset": continue
#dump this into smap
smap = map_names[map_group][map_id]
#signposts
signposts = smap["signposts"]
#for each signpost
for signpost in signposts:
if signpost["func"] in [0, 1, 2, 3, 4]:
#dump this into script
script = signpost["script"]
elif signpost["func"] in [05, 06]:
script = signpost["script"]
else: continue
#skip signposts with no bytes
if len(script) == 0: continue
#find all text pointers in script
texts = find_all_text_pointers_in_script_engine_script(script, smap["event_bank"])
#dump these addresses in
addresses.update(texts)
#xy triggers
xy_triggers = smap["xy_triggers"]
#for each xy trigger
for xy_trigger in xy_triggers:
#dump this into script
script = xy_trigger["script"]
#find all text pointers in script
texts = find_all_text_pointers_in_script_engine_script(script, smap["event_bank"])
#dump these addresses in
addresses.update(texts)
#trigger scripts
triggers = smap["trigger_scripts"]
#for each trigger
for (i, trigger) in triggers.items():
#dump this into script
script = trigger["script"]
#find all text pointers in script
texts = find_all_text_pointers_in_script_engine_script(script, calculate_bank(trigger["address"]))
#dump these addresses in
addresses.update(texts)
#callback scripts
callbacks = smap["callback_scripts"]
#for each callback
for (k, callback) in callbacks.items():
#dump this into script
script = callback["script"]
#find all text pointers in script
texts = find_all_text_pointers_in_script_engine_script(script, calculate_bank(callback["address"]))
#dump these addresses in
addresses.update(texts)
#people-events
events = smap["people_events"]
#for each event
for event in events:
if event["event_type"] == "script":
#dump this into script
script = event["script"]
#find all text pointers in script
texts = find_all_text_pointers_in_script_engine_script(script, smap["event_bank"])
#dump these addresses in
addresses.update(texts)
if event["event_type"] == "trainer":
trainer_data = event["trainer_data"]
addresses.update([trainer_data["text_when_seen_ptr"]])
addresses.update([trainer_data["text_when_trainer_beaten_ptr"]])
trainer_bank = calculate_bank(event["trainer_data_address"])
script1 = trainer_data["script_talk_again"]
texts1 = find_all_text_pointers_in_script_engine_script(script1, trainer_bank)
addresses.update(texts1)
script2 = trainer_data["script_when_lost"]
texts2 = find_all_text_pointers_in_script_engine_script(script2, trainer_bank)
addresses.update(texts2)
return addresses
def parse_text_at(self, address):
"""parses a text-engine script ("in-text scripts")
http://hax.iimarck.us/files/scriptingcodes_eng.htm#InText
This is presently very broken.
see parse_text_at2, parse_text_at, and process_00_subcommands
"""
global rom, text_count, max_texts, texts, script_parse_table
if rom == None:
direct_load_rom()
if address == None:
return "not a script"
map_group, map_id, debug, show, force = self.map_group, self.map_id, self.debug, self.show, self.force
commands = {}
if is_script_already_parsed_at(address) and not force:
print "text is already parsed at this location: " + hex(address)
raise Exception, "text is already parsed, what's going on ?"
return script_parse_table[address]
total_text_commands = 0
command_counter = 0
original_address = address
offset = address
end = False
script_parse_table[original_address:original_address+1] = "incomplete text"
while not end:
address = offset
command = {}
command_byte = ord(rom[address])
if debug:
print "TextScript.parse_script_at has encountered a command byte " + hex(command_byte) + " at " + hex(address)
end_address = address + 1
if command_byte == 0:
#read until $57, $50 or $58
jump57 = how_many_until(chr(0x57), offset)
jump50 = how_many_until(chr(0x50), offset)
jump58 = how_many_until(chr(0x58), offset)
#whichever command comes first
jump = min([jump57, jump50, jump58])
end_address = offset + jump #we want the address before $57
lines = process_00_subcommands(offset+1, end_address, debug=debug)
if show and debug:
text = parse_text_at2(offset+1, end_address-offset+1, debug=debug)
print text
command = {"type": command_byte,
"start_address": offset,
"end_address": end_address,
"size": jump,
"lines": lines,
}
offset += jump
elif command_byte == 0x17:
#TX_FAR [pointer][bank]
pointer_byte1 = ord(rom[offset+1])
pointer_byte2 = ord(rom[offset+2])
pointer_bank = ord(rom[offset+3])
pointer = (pointer_byte1 + (pointer_byte2 << 8))
pointer = extract_maps.calculate_pointer(pointer, pointer_bank)
text = TextScript(pointer, map_group=self.map_group, map_id=self.amp_id, debug=self.debug, \
show=self.debug, force=self.debug, label="Target"+self.label.name)
if text.is_valid():
self.dependencies.append(text)
command = {"type": command_byte,
"start_address": offset,
"end_address": offset + 3, #last byte belonging to this command
"pointer": pointer, #parameter
"text": text,
}
offset += 3 + 1
elif command_byte == 0x50 or command_byte == 0x57 or command_byte == 0x58: #end text
command = {"type": command_byte,
"start_address": offset,
"end_address": offset,
}
#this byte simply indicates to end the script
end = True
#this byte simply indicates to end the script
if command_byte == 0x50 and ord(rom[offset+1]) == 0x50: #$50$50 means end completely
end = True
commands[command_counter+1] = command
#also save the next byte, before we quit
commands[command_counter+1]["start_address"] += 1
commands[command_counter+1]["end_address"] += 1
add_command_byte_to_totals(command_byte)
elif command_byte == 0x50: #only end if we started with $0
if len(commands.keys()) > 0:
if commands[0]["type"] == 0x0: end = True
elif command_byte == 0x57 or command_byte == 0x58: #end completely
end = True
offset += 1 #go past this 0x50
elif command_byte == 0x1:
#01 = text from RAM. [01][2-byte pointer]
size = 3 #total size, including the command byte
pointer_byte1 = ord(rom[offset+1])
pointer_byte2 = ord(rom[offset+2])
command = {"type": command_byte,
"start_address": offset+1,
"end_address": offset+2, #last byte belonging to this command
"pointer": [pointer_byte1, pointer_byte2], #RAM pointer
}
#view near these bytes
#subsection = rom[offset:offset+size+1] #peak ahead
#for x in subsection:
# print hex(ord(x))
#print "--"
offset += 2 + 1 #go to the next byte
#use this to look at the surrounding bytes
if debug:
print "next command is: " + hex(ord(rom[offset])) + " ... we are at command number: " + str(command_counter) + " near " + hex(offset) + " on map_id=" + str(map_id)
elif command_byte == 0x7:
#07 = shift texts 1 row above (2nd line becomes 1st line); address for next text = 2nd line. [07]
size = 1
command = {"type": command_byte,
"start_address": offset,
"end_address": offset,
}
offset += 1
elif command_byte == 0x3:
#03 = set new address in RAM for text. [03][2-byte RAM address]
size = 3
command = {"type": command_byte, "start_address": offset, "end_address": offset+2}
offset += size
elif command_byte == 0x4: #draw box
#04 = draw box. [04][2-Byte pointer][height Y][width X]
size = 5 #including the command
command = {
"type": command_byte,
"start_address": offset,
"end_address": offset + size,
"pointer_bytes": [ord(rom[offset+1]), ord(rom[offset+2])],
"y": ord(rom[offset+3]),
"x": ord(rom[offset+4]),
}
offset += size + 1
elif command_byte == 0x5:
#05 = write text starting at 2nd line of text-box. [05][text][ending command]
#read until $57, $50 or $58
jump57 = how_many_until(chr(0x57), offset)
jump50 = how_many_until(chr(0x50), offset)
jump58 = how_many_until(chr(0x58), offset)
#whichever command comes first
jump = min([jump57, jump50, jump58])
end_address = offset + jump #we want the address before $57
lines = process_00_subcommands(offset+1, end_address, debug=debug)
if show and debug:
text = parse_text_at2(offset+1, end_address-offset+1, debug=debug)
print text
command = {"type": command_byte,
"start_address": offset,
"end_address": end_address,
"size": jump,
"lines": lines,
}
offset = end_address + 1
elif command_byte == 0x6:
#06 = wait for keypress A or B (put blinking arrow in textbox). [06]
command = {"type": command_byte, "start_address": offset, "end_address": offset}
offset += 1
elif command_byte == 0x7:
#07 = shift texts 1 row above (2nd line becomes 1st line); address for next text = 2nd line. [07]
command = {"type": command_byte, "start_address": offset, "end_address": offset}
offset += 1
elif command_byte == 0x8:
#08 = asm until whenever
command = {"type": command_byte, "start_address": offset, "end_address": offset}
offset += 1
end = True
elif command_byte == 0x9:
#09 = write hex-to-dec number from RAM to textbox [09][2-byte RAM address][byte bbbbcccc]
# bbbb = how many bytes to read (read number is big-endian)
# cccc = how many digits display (decimal)
#(note: max of decimal digits is 7,i.e. max number correctly displayable is 9999999)
ram_address_byte1 = ord(rom[offset+1])
ram_address_byte2 = ord(rom[offset+2])
read_byte = ord(rom[offset+3])
command = {
"type": command_byte,
"address": [ram_address_byte1, ram_address_byte2],
"read_byte": read_byte, #split this up when we make a macro for this
}
offset += 4
else:
#if len(commands) > 0:
# print "Unknown text command " + hex(command_byte) + " at " + hex(offset) + ", script began with " + hex(commands[0]["type"])
if debug:
print "Unknown text command at " + hex(offset) + " - command: " + hex(ord(rom[offset])) + " on map_id=" + str(map_id)
#end at the first unknown command
end = True
commands[command_counter] = command
command_counter += 1
total_text_commands += len(commands)
text_count += 1
#if text_count >= max_texts:
# sys.exit()
self.commands = commands
self.last_address = offset
script_parse_table[original_address:offset] = self
all_texts.append(self)
self.size = self.byte_count = self.last_address - original_address
return commands
def get_dependencies(self, recompute=False, global_dependencies=set()):
#if recompute:
# raise NotImplementedError, bryan_message
global_dependencies.update(self.dependencies)
return self.dependencies
def to_asm(self, label=None):
address = self.address
start_address = address
if label == None: label = self.label.name
#using deepcopy because otherwise additional @s get appended each time
#like to the end of the text for TextScript(0x5cf3a)
commands = deepcopy(self.commands)
#apparently this isn't important anymore?
needs_to_begin_with_0 = True
#start with zero please
byte_count = 0
#where we store all output
output = ""
had_text_end_byte = False
had_text_end_byte_57_58 = False
had_db_last = False
xspacing = ""
#reset this pretty fast..
first_line = True
#for each command..
for this_command in commands.keys():
if not "lines" in commands[this_command].keys():
command = commands[this_command]
if not "type" in command.keys():
print "ERROR in command: " + str(command)
continue #dunno what to do here?
if command["type"] == 0x1: #TX_RAM
p1 = command["pointer"][0]
p2 = command["pointer"][1]
#remember to account for big endian -> little endian
output += "\n" + xspacing + "TX_RAM $%.2x%.2x" %(p2, p1)
byte_count += 3
had_db_last = False
elif command["type"] == 0x17: #TX_FAR
#p1 = command["pointer"][0]
#p2 = command["pointer"][1]
output += "\n" + xspacing + "TX_FAR _" + label + " ; " + hex(command["pointer"])
byte_count += 4 #$17, bank, address word
had_db_last = False
elif command["type"] == 0x9: #TX_RAM_HEX2DEC
#address, read_byte
output += "\n" + xspacing + "TX_NUM $%.2x%.2x, $%.2x" % (command["address"][1], command["address"][0], command["read_byte"])
had_db_last = False
byte_count += 4
elif command["type"] == 0x50 and not had_text_end_byte:
#had_text_end_byte helps us avoid repeating $50s
if had_db_last:
output += ", $50"
else:
output += "\n" + xspacing + "db $50"
byte_count += 1
had_db_last = True
elif command["type"] in [0x57, 0x58] and not had_text_end_byte_57_58:
if had_db_last:
output += ", $%.2x" % (command["type"])
else:
output += "\n" + xspacing + "db $%.2x" % (command["type"])
byte_count += 1
had_db_last = True
elif command["type"] in [0x57, 0x58] and had_text_end_byte_57_58:
pass #this is ok
elif command["type"] == 0x50 and had_text_end_byte:
pass #this is also ok
elif command["type"] == 0x0b:
if had_db_last:
output += ", $0b"
else:
output += "\n" + xspacing + "db $0B"
byte_count += 1
had_db_last = True
elif command["type"] == 0x11:
if had_db_last:
output += ", $11"
else:
output += "\n" + xspacing + "db $11"
byte_count += 1
had_db_last = True
elif command["type"] == 0x6: #wait for keypress
if had_db_last:
output += ", $6"
else:
output += "\n" + xspacing + "db $6"
byte_count += 1
had_db_last = True
else:
print "ERROR in command: " + hex(command["type"])
had_db_last = False
#everything else is for $0s, really
continue
lines = commands[this_command]["lines"]
#reset this in case we have non-$0s later
had_db_last = False
#add the ending byte to the last line- always seems $57
#this should already be in there, but it's not because of a bug in the text parser
lines[len(lines.keys())-1].append(commands[len(commands.keys())-1]["type"])
first = True #first byte
for line_id in lines:
line = lines[line_id]
output += xspacing + "db "
if first and needs_to_begin_with_0:
output += "$0, "
first = False
byte_count += 1
quotes_open = False
first_byte = True
was_byte = False
for byte in line:
if byte == 0x50:
had_text_end_byte = True #don't repeat it
if byte in [0x58, 0x57]:
had_text_end_byte_57_58 = True
if byte in chars:
if not quotes_open and not first_byte: #start text
output += ", \""
quotes_open = True
first_byte = False
if not quotes_open and first_byte: #start text
output += "\""
quotes_open = True
output += chars[byte]
elif byte in constant_abbreviation_bytes:
if quotes_open:
output += "\""
quotes_open = False
if not first_byte:
output += ", "
output += constant_abbreviation_bytes[byte]
else:
if quotes_open:
output += "\""
quotes_open = False
#if you want the ending byte on the last line
#if not (byte == 0x57 or byte == 0x50 or byte == 0x58):
if not first_byte:
output += ", "
output += "$" + hex(byte)[2:]
was_byte = True
#add a comma unless it's the end of the line