-
Notifications
You must be signed in to change notification settings - Fork 12
/
reggie.py
9067 lines (7198 loc) · 334 KB
/
reggie.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
#!/usr/bin/python
# -*- coding: latin-1 -*-
# Reggie! - New Super Mario Bros. Wii Level Editor
# Copyright (C) 2009-2010 Treeki, Tempus
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import archive
import lz77
import os.path
import pickle
import sprites
import struct
import sys
import time
import warnings
from ctypes import create_string_buffer
from PyQt4 import QtCore, QtGui
from xml.dom import minidom
ReggieID = 'Reggie r3 by Treeki, Tempus'
# pre-Qt4.6 compatibility
QtCompatVersion = QtCore.QT_VERSION
if QtCompatVersion < 0x40600 or not hasattr(QtGui.QGraphicsItem, 'ItemSendsGeometryChanges'):
# enables itemChange being called on QGraphicsItem
QtGui.QGraphicsItem.ItemSendsGeometryChanges = QtGui.QGraphicsItem.GraphicsItemFlag(0x800)
# use psyco for optimisation if available
try:
import psyco
HavePsyco = True
except ImportError:
HavePsyco = False
# use nsmblib if possible
try:
import nsmblib
HaveNSMBLib = True
except ImportError:
HaveNSMBLib = False
app = None
mainWindow = None
settings = None
gamePath = None
def module_path():
"""This will get us the program's directory, even if we are frozen using py2exe"""
if hasattr(sys, 'frozen'):
return os.path.dirname(sys.executable)
if __name__ == '__main__':
return os.path.dirname(os.path.abspath(sys.argv[0]))
return None
def IsNSMBLevel(filename):
"""Does some basic checks to confirm a file is a NSMB level"""
if not os.path.isfile(filename): return False
f = open(filename, 'rb')
data = f.read()
if not data.startswith('U\xAA8-'):
return False
if 'course\0' not in data and 'course1.bin\0' not in data and '\0\0\0\x80' not in data:
return False
return True
def FilesAreMissing():
"""Checks to see if any of the required files for Reggie are missing"""
if not os.path.isdir('reggiedata'):
QtGui.QMessageBox.warning(None, 'Error', 'Sorry, you seem to be missing the required data files for Reggie! to work. Please redownload your copy of the editor.')
return True
required = ['entrances.png', 'entrancetypes.txt', 'icon.png', 'levelnames.txt', 'overrides.png',
'spritedata.xml', 'tilesets.txt', 'bga/000A.png', 'bga.txt', 'bgb/000A.png', 'bgb.txt',
'about.html', 'spritecategories.xml']
missing = []
for check in required:
if not os.path.isfile('reggiedata/' + check):
missing.append(check)
if len(missing) > 0:
QtGui.QMessageBox.warning(None, 'Error', 'Sorry, you seem to be missing some of the required data files for Reggie! to work. Please redownload your copy of the editor. These are the files you are missing: ' + ', '.join(missing))
return True
return False
def GetIcon(name):
"""Helper function to grab a specific icon"""
return QtGui.QIcon('reggiedata/icon_%s.png' % name)
def SetGamePath(newpath):
"""Sets the NSMBWii game path"""
global gamePath
# you know what's fun?
# isValidGamePath crashes in os.path.join if QString is used..
# so we must change it to a Python string manually
gamePath = unicode(newpath)
def isValidGamePath(check='ug'):
"""Checks to see if the path for NSMBWii contains a valid game"""
if check == 'ug': check = gamePath
if check == None or check == '': return False
if not os.path.isdir(check): return False
if not os.path.isdir(os.path.join(check, 'Texture')): return False
if not os.path.isfile(os.path.join(check, '01-01.arc')): return False
return True
LevelNames = None
def LoadLevelNames():
"""Ensures that the level name info is loaded"""
global LevelNames
if LevelNames != None: return
f = open('reggiedata/levelnames.txt')
raw = [x.strip() for x in f.readlines()]
f.close()
LevelNames = []
CurrentWorldName = None
CurrentWorld = None
for line in raw:
if line == '': continue
if line.startswith('-'):
if CurrentWorld != None:
LevelNames.append((CurrentWorldName,CurrentWorld))
CurrentWorldName = line[1:]
CurrentWorld = []
else:
d = line.split('|')
CurrentWorld.append((d[0], d[1]))
if CurrentWorld != None:
LevelNames.append((CurrentWorldName,CurrentWorld))
TilesetNames = None
def LoadTilesetNames():
"""Ensures that the tileset name info is loaded"""
global TilesetNames
if TilesetNames != None: return
f = open('reggiedata/tilesets.txt')
raw = [x.strip() for x in f.readlines()]
f.close()
TilesetNames = []
StandardSuite = []
StageSuite = []
BackgroundSuite = []
InteractiveSuite = []
for line in raw:
if line.startswith('Pa0'):
w = line.split('=')
StandardSuite.append((w[0], w[1]))
if line.startswith('Pa1'):
w = line.split('=')
StageSuite.append((w[0], w[1]))
if line.startswith('Pa2'):
w = line.split('=')
BackgroundSuite.append((w[0], w[1]))
if line.startswith('Pa3'):
w = line.split('=')
InteractiveSuite.append((w[0], w[1]))
TilesetNames.append(StandardSuite)
TilesetNames.append(StageSuite)
TilesetNames.append(BackgroundSuite)
TilesetNames.append(InteractiveSuite)
ObjDesc = None
def LoadObjDescriptions():
"""Ensures that the object description is loaded"""
global ObjDesc
if ObjDesc != None: return
f = open('reggiedata/ts1_descriptions.txt')
raw = [x.strip() for x in f.readlines()]
f.close()
ObjDesc = {}
for line in raw:
w = line.split('=')
ObjDesc[int(w[0])] = w[1]
BgANames = None
def LoadBgANames():
"""Ensures that the background name info is loaded"""
global BgANames
if BgANames != None: return
f = open('reggiedata/bga.txt')
raw = [x.strip() for x in f.readlines()]
f.close()
BgANames = []
for line in raw:
w = line.split('=')
BgANames.append([w[0], w[1]])
BgBNames = None
def LoadBgBNames():
"""Ensures that the background name info is loaded"""
global BgBNames
if BgBNames != None: return
f = open('reggiedata/bgb.txt')
raw = [x.strip() for x in f.readlines()]
f.close()
BgBNames = []
for line in raw:
w = line.split('=')
BgBNames.append([w[0], w[1]])
BgScrollRates = [0.0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0, 0.0, 1.2, 1.5, 2.0, 4.0]
BgScrollRateStrings = ['None', '0.125x', '0.25x', '0.375x', '0.5x', '0.625x', '0.75x', '0.875x', '1x', 'None', '1.2x', '1.5x', '2x', '4x']
ZoneThemeValues = [
'Overworld', 'Underground', 'Underwater', 'Lava/Volcano [reddish]',
'Desert', 'Beach*', 'Forest*', 'Snow Overworld*',
'Sky/Bonus*', 'Mountains*', 'Tower', 'Castle',
'Ghost House', 'River Cave', 'Ghost House Exit', 'Underwater Cave',
'Desert Cave', 'Icy Cave*', 'Lava/Volcano', 'Final Battle',
'World 8 Castle', 'World 8 Doomship*', 'Lit Tower'
]
ZoneTerrainThemeValues = [
'Normal/Overworld', 'Underground', 'Underwater', 'Lava/Volcano',
]
Sprites = None
SpriteCategories = None
class SpriteDefinition():
"""Stores and manages the data info for a specific sprite"""
class ListPropertyModel(QtCore.QAbstractListModel):
"""Contains all the possible values for a list property on a sprite"""
def __init__(self, entries, existingLookup, max):
"""Constructor"""
QtCore.QAbstractListModel.__init__(self)
self.entries = entries
self.existingLookup = existingLookup
self.max = max
def rowCount(self, parent=None):
"""Required by Qt"""
#return self.max
return len(self.entries)
def data(self, index, role=QtCore.Qt.DisplayRole):
"""Get what we have for a specific row"""
if not index.isValid(): return None
n = index.row()
if n < 0: return None
#if n >= self.max: return None
if n >= len(self.entries): return None
if role == QtCore.Qt.DisplayRole:
#entries = self.entries
#if entries.has_key(n):
# return '%d: %s' % (n, entries[n])
#else:
# return '%d: <unknown/unused>' % n
return '%d: %s' % self.entries[n]
return None
def loadFrom(self, elem):
"""Loads in all the field data from an XML node"""
self.fields = []
fields = self.fields
for field in elem.childNodes:
if field.nodeType != field.ELEMENT_NODE: continue
attribs = field.attributes
if attribs.has_key('comment'):
comment = '<b>%s</b>: %s' % (attribs['title'].nodeValue, attribs['comment'].nodeValue)
else:
comment = None
if field.nodeName == 'checkbox':
# parameters: title, nybble, mask, comment
snybble = attribs['nybble'].nodeValue
if '-' not in snybble:
nybble = int(snybble) - 1
else:
getit = snybble.split('-')
nybble = (int(getit[0]) - 1, int(getit[1]))
fields.append((0, attribs['title'].nodeValue, nybble, int(attribs['mask'].nodeValue) if attribs.has_key('mask') else 1, comment))
elif field.nodeName == 'list':
# parameters: title, nybble, model, comment
snybble = attribs['nybble'].nodeValue
if '-' not in snybble:
nybble = int(snybble) - 1
max = 16
else:
getit = snybble.split('-')
nybble = (int(getit[0]) - 1, int(getit[1]))
max = (16 << ((nybble[1] - nybble[0] - 1) * 4))
entries = []
existing = [None for i in xrange(max)]
for e in field.childNodes:
if e.nodeType != e.ELEMENT_NODE: continue
if e.nodeName != 'entry': continue
i = int(e.attributes['value'].nodeValue)
entries.append((i, e.childNodes[0].nodeValue))
existing[i] = True
fields.append((1, attribs['title'].nodeValue, nybble, SpriteDefinition.ListPropertyModel(entries, existing, max), comment))
elif field.nodeName == 'value':
# parameters: title, nybble, max, comment
snybble = attribs['nybble'].nodeValue
# if it's 5-12 skip it
# fixes tobias's crashy "unknown values"
if snybble == '5-12': continue
if '-' not in snybble:
nybble = int(snybble) - 1
max = 16
else:
getit = snybble.split('-')
nybble = (int(getit[0]) - 1, int(getit[1]))
max = (16 << ((nybble[1] - nybble[0] - 1) * 4))
fields.append((2, attribs['title'].nodeValue, nybble, max, comment))
def LoadSpriteData():
"""Ensures that the sprite data info is loaded"""
global Sprites
if Sprites != None: return
Sprites = [None] * 483
sd = minidom.parse('reggiedata/spritedata.xml')
root = sd.documentElement
errors = []
errortext = []
for sprite in root.childNodes:
if sprite.nodeType != sprite.ELEMENT_NODE: continue
if sprite.nodeName != 'sprite': continue
spriteid = int(sprite.attributes['id'].nodeValue)
spritename = unicode(sprite.attributes['name'].nodeValue)
notes = None
if sprite.attributes.has_key('notes'):
notes = '<b>Sprite Notes:</b> ' + sprite.attributes['notes'].nodeValue
sdef = SpriteDefinition()
sdef.id = spriteid
sdef.name = spritename
sdef.notes = notes
try:
sdef.loadFrom(sprite)
except Exception, e:
errors.append(str(spriteid))
errortext.append(str(e))
Sprites[spriteid] = sdef
sd.unlink()
if len(errors) > 0:
QtGui.QMessageBox.warning(None, 'Warning', 'The sprite data file didn\'t load correctly. The following sprites have incorrect and/or broken data in them, and may not be editable correctly in the editor: ' + (', '.join(errors)), QtGui.QMessageBox.Ok)
QtGui.QMessageBox.warning(None, 'Errors', repr(errortext))
def LoadSpriteCategories():
"""Ensures that the sprite category info is loaded"""
global Sprites, SpriteCategories
if SpriteCategories != None: return
SpriteCategories = []
sd = minidom.parse('reggiedata/spritecategories.xml')
root = sd.documentElement
CurrentView = None
for view in root.childNodes:
if view.nodeType != view.ELEMENT_NODE: continue
if view.nodeName != 'view': continue
viewname = unicode(view.attributes['name'].nodeValue)
CurrentView = []
SpriteCategories.append((viewname, CurrentView, []))
CurrentCategory = None
for category in view.childNodes:
if category.nodeType != category.ELEMENT_NODE: continue
if category.nodeName != 'category': continue
catname = unicode(category.attributes['name'].nodeValue)
CurrentCategory = []
CurrentView.append((catname, CurrentCategory))
for attach in category.childNodes:
if attach.nodeType != attach.ELEMENT_NODE: continue
if attach.nodeName != 'attach': continue
sprite = attach.attributes['sprite'].nodeValue
if '-' not in sprite:
CurrentCategory.append(int(sprite))
else:
x = sprite.split('-')
for i in xrange(int(x[0]), int(x[1])+1):
CurrentCategory.append(i)
sd.unlink()
SpriteCategories.append(('Search', [('Search Results', range(0,483))], []))
SpriteCategories[-1][1][0][1].append(9999) # "no results" special case
EntranceTypeNames = None
def LoadEntranceNames():
"""Ensures that the entrance names are loaded"""
global EntranceTypeNames
if EntranceTypeNames != None: return
getit = open('reggiedata/entrancetypes.txt', 'r')
EntranceTypeNames = [x.strip() for x in getit.readlines()]
class ChooseLevelNameDialog(QtGui.QDialog):
"""Dialog which lets you choose a level from a list"""
def __init__(self):
"""Creates and initialises the dialog"""
QtGui.QDialog.__init__(self)
self.setWindowTitle('Choose Level')
LoadLevelNames()
self.currentlevel = None
# create the tree
tree = QtGui.QTreeWidget()
tree.setColumnCount(1)
tree.setHeaderHidden(True)
tree.setIndentation(16)
tree.currentItemChanged.connect(self.HandleItemChange)
tree.itemActivated.connect(self.HandleItemActivated)
for worldname, world in LevelNames:
wnode = QtGui.QTreeWidgetItem()
wnode.setText(0, worldname)
for levelname, level in world:
lnode = QtGui.QTreeWidgetItem()
lnode.setText(0, levelname)
lnode.setData(0, QtCore.Qt.UserRole, level)
lnode.setToolTip(0, level + '.arc')
wnode.addChild(lnode)
tree.addTopLevelItem(wnode)
self.leveltree = tree
# create the buttons
self.buttonBox = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel)
self.buttonBox.button(QtGui.QDialogButtonBox.Ok).setEnabled(False)
self.buttonBox.accepted.connect(self.accept)
self.buttonBox.rejected.connect(self.reject)
# create the layout
layout = QtGui.QVBoxLayout()
layout.addWidget(self.leveltree)
layout.addWidget(self.buttonBox)
self.setLayout(layout)
self.layout = layout
@QtCore.pyqtSlot(QtGui.QTreeWidgetItem, QtGui.QTreeWidgetItem)
def HandleItemChange(self, current, previous):
"""Catch the selected level and enable/disable OK button as needed"""
self.currentlevel = current.data(0, QtCore.Qt.UserRole)
if self.currentlevel == None:
self.buttonBox.button(QtGui.QDialogButtonBox.Ok).setEnabled(False)
else:
self.buttonBox.button(QtGui.QDialogButtonBox.Ok).setEnabled(True)
self.currentlevel = unicode(self.currentlevel.toPyObject())
@QtCore.pyqtSlot(QtGui.QTreeWidgetItem, int)
def HandleItemActivated(self, item, column):
"""Handle a doubleclick on a level"""
self.currentlevel = item.data(0, QtCore.Qt.UserRole)
if self.currentlevel != None:
self.currentlevel = unicode(self.currentlevel.toPyObject())
self.accept()
Tiles = None # 256 tiles per tileset, plus 64 for each type of override
Overrides = None # 320 tiles, this is put into Tiles usually
TileBehaviours = None
ObjectDefinitions = None # 4 tilesets
class ObjectDef():
"""Class for the object definitions"""
def __init__(self):
"""Constructor"""
self.width = 0
self.height = 0
self.rows = []
def load(self, source, offset, tileoffset):
"""Load an object definition"""
i = offset
row = []
while True:
cbyte = ord(source[i])
if cbyte == 0xFE:
self.rows.append(row)
i += 1
row = []
elif cbyte == 0xFF:
return
elif (cbyte & 0x80) != 0:
row.append((cbyte,))
i += 1
else:
extra = ord(source[i+2])
tile = (cbyte, ord(source[i+1]) | ((extra & 3) << 8), extra >> 2)
row.append(tile)
i += 3
def RenderObject(tileset, objnum, width, height, fullslope=False):
"""Render a tileset object into an array"""
# allocate an array
dest = []
for i in xrange(height): dest.append([0]*width)
# ignore non-existent objects
tileset_defs = ObjectDefinitions[tileset]
if tileset_defs == None: return dest
obj = tileset_defs[objnum]
if obj == None: return dest
if len(obj.rows) == 0: return dest
# diagonal objects are rendered differently
if (obj.rows[0][0][0] & 0x80) != 0:
RenderDiagonalObject(dest, obj, width, height, fullslope)
else:
# standard object
repeatFound = False
beforeRepeat = []
inRepeat = []
afterRepeat = []
for row in obj.rows:
if len(row) == 0: continue
if (row[0][0] & 2) != 0:
repeatFound = True
inRepeat.append(row)
else:
if repeatFound:
afterRepeat.append(row)
else:
beforeRepeat.append(row)
bc = len(beforeRepeat); ic = len(inRepeat); ac = len(afterRepeat)
if ic == 0:
for y in xrange(height):
RenderStandardRow(dest[y], beforeRepeat[y % bc], y, width)
else:
afterthreshold = height - ac - 1
for y in xrange(height):
if y < bc:
RenderStandardRow(dest[y], beforeRepeat[y], y, width)
elif y > afterthreshold:
RenderStandardRow(dest[y], afterRepeat[y - height + ac], y, width)
else:
RenderStandardRow(dest[y], inRepeat[(y - bc) % ic], y, width)
return dest
def RenderStandardRow(dest, row, y, width):
"""Render a row from an object"""
repeatFound = False
beforeRepeat = []
inRepeat = []
afterRepeat = []
for tile in row:
if (tile[0] & 1) != 0:
repeatFound = True
inRepeat.append(tile)
else:
if repeatFound:
afterRepeat.append(tile)
else:
beforeRepeat.append(tile)
bc = len(beforeRepeat); ic = len(inRepeat); ac = len(afterRepeat)
if ic == 0:
for x in xrange(width):
dest[x] = beforeRepeat[x % bc][1]
else:
afterthreshold = width - ac - 1
for x in xrange(width):
if x < bc:
dest[x] = beforeRepeat[x][1]
elif x > afterthreshold:
dest[x] = afterRepeat[x - width + ac][1]
else:
dest[x] = inRepeat[(x - bc) % ic][1]
def RenderDiagonalObject(dest, obj, width, height, fullslope):
"""Render a diagonal object"""
# set all to empty tiles
for row in dest:
for x in xrange(width):
row[x] = -1
# get sections
mainBlock,subBlock = GetSlopeSections(obj)
cbyte = obj.rows[0][0][0]
# get direction
goLeft = ((cbyte & 1) != 0)
goDown = ((cbyte & 2) != 0)
# base the amount to draw by seeing how much we can fit in each direction
if fullslope:
drawAmount = max(height // len(mainBlock), width // len(mainBlock[0]))
else:
drawAmount = min(height // len(mainBlock), width // len(mainBlock[0]))
# if it's not goingLeft and not goingDown:
if not goLeft and not goDown:
# slope going from SW => NE
# start off at the bottom left
x = 0
y = height - len(mainBlock) - (0 if subBlock == None else len(subBlock))
xi = len(mainBlock[0])
yi = -len(mainBlock)
# ... and if it's goingLeft and not goingDown:
elif goLeft and not goDown:
# slope going from SE => NW
# start off at the top left
x = 0
y = 0
xi = len(mainBlock[0])
yi = len(mainBlock)
# ... and if it's not goingLeft but it's goingDown:
elif not goLeft and goDown:
# slope going from NW => SE
# start off at the top left
x = 0
y = (0 if subBlock == None else len(subBlock))
xi = len(mainBlock[0])
yi = len(mainBlock)
# ... and finally, if it's goingLeft and goingDown:
else:
# slope going from SW => NE
# start off at the bottom left
x = 0
y = height - len(mainBlock)
xi = len(mainBlock[0])
yi = -len(mainBlock)
# finally draw it
for i in xrange(drawAmount):
PutObjectArray(dest, x, y, mainBlock, width, height)
if subBlock != None:
xb = x
if goLeft: xb = x + len(mainBlock[0]) - len(subBlock[0])
if goDown:
PutObjectArray(dest, xb, y - len(subBlock), subBlock, width, height)
else:
PutObjectArray(dest, xb, y + len(mainBlock), subBlock, width, height)
x += xi
y += yi
def PutObjectArray(dest, xo, yo, block, width, height):
"""Places a tile array into an object"""
#for y in xrange(yo,min(yo+len(block),height)):
for y in xrange(yo,yo+len(block)):
if y < 0: continue
if y >= height: continue
drow = dest[y]
srow = block[y-yo]
#for x in xrange(xo,min(xo+len(srow),width)):
for x in xrange(xo,xo+len(srow)):
if x < 0: continue
if x >= width: continue
drow[x] = srow[x-xo][1]
def GetSlopeSections(obj):
"""Sorts the slope data into sections"""
sections = []
currentSection = None
for row in obj.rows:
if len(row) > 0 and (row[0][0] & 0x80) != 0: # begin new section
if currentSection != None:
sections.append(CreateSection(currentSection))
currentSection = []
currentSection.append(row)
if currentSection != None: # end last section
sections.append(CreateSection(currentSection))
if len(sections) == 1:
return (sections[0],None)
else:
return (sections[0],sections[1])
def CreateSection(rows):
"""Create a slope section"""
# calculate width
width = 0
for row in rows:
thiswidth = CountTiles(row)
if width < thiswidth: width = thiswidth
# create the section
section = []
for row in rows:
drow = [0] * width
x = 0
for tile in row:
if (tile[0] & 0x80) == 0:
drow[x] = tile
x += 1
section.append(drow)
return section
def CountTiles(row):
"""Counts the amount of real tiles in an object row"""
res = 0
for tile in row:
if (tile[0] & 0x80) == 0:
res += 1
return res
def CreateTilesets():
"""Blank out the tileset arrays"""
global Tiles, TileBehaviours, ObjectDefinitions
Tiles = [None]*1024
Tiles += Overrides
#TileBehaviours = [0]*1024
ObjectDefinitions = [None]*4
sprites.Tiles = Tiles
def LoadTileset(idx, name):
try:
return _LoadTileset(idx, name)
except:
QtGui.QMessageBox.warning(None, 'Error', 'An error occurred while trying to load %s.arc. Check your Texture folder to make sure it is complete and not corrupted. The editor may run in a broken state or crash after this.' % name)
return False
def _LoadTileset(idx, name):
"""Load in a tileset into a specific slot"""
# read the archive
arcname = os.path.join(gamePath, 'Texture', name+'.arc')
if not os.path.isfile(arcname):
QtGui.QMessageBox.warning(None, 'Error', 'Cannot find the required tileset file %s.arc for this level. Check your Texture folder and make sure it contains the required file.' % name)
return False
arcf = open(arcname,'rb')
arcdata = arcf.read()
arcf.close()
arc = archive.U8.load(arcdata)
# decompress the textures
try:
comptiledata = arc['BG_tex/%s_tex.bin.LZ' % name]
except KeyError:
QtGui.QMessageBox.warning(None, 'Error', 'Cannot find the required texture within the tileset file %s.arc, so it will not be loaded. Keep in mind that the tileset file cannot be renamed without changing the names of the texture/object files within the archive as well!' % name)
return False
# load in the textures - uses a different method if nsmblib exists
if HaveNSMBLib:
tiledata = nsmblib.decompress11LZS(comptiledata)
rgbdata = nsmblib.decodeTileset(tiledata)
img = QtGui.QImage(rgbdata, 1024, 256, 4096, QtGui.QImage.Format_ARGB32_Premultiplied)
else:
lz = lz77.LZS11()
img = LoadTextureUsingOldMethod(lz.Decompress11LZS(comptiledata))
# crop the tiles out
dest = QtGui.QPixmap.fromImage(img)
sourcex = 4
sourcey = 4
tileoffset = idx*256
for i in xrange(tileoffset,tileoffset+256):
Tiles[i] = dest.copy(sourcex,sourcey,24,24)
sourcex += 32
if sourcex >= 1024:
sourcex = 4
sourcey += 32
# tile behaviours aren't needed yet?
# load the object definitions
defs = [None]*256
indexfile = arc['BG_unt/%s_hd.bin' % name]
deffile = arc['BG_unt/%s.bin' % name]
objcount = len(indexfile) / 4
indexstruct = struct.Struct('>HBB')
for i in xrange(objcount):
data = indexstruct.unpack_from(indexfile, i << 2)
obj = ObjectDef()
obj.width = data[1]
obj.height = data[2]
obj.load(deffile,data[0],tileoffset)
defs[i] = obj
ObjectDefinitions[idx] = defs
ProcessOverrides(idx, name)
def LoadTextureUsingOldMethod(tiledata):
tx = 0; ty = 0
iter = tiledata.__iter__()
dest = QtGui.QImage(1024,256,QtGui.QImage.Format_ARGB32)
dest.fill(QtCore.Qt.transparent)
# this is for optimisation
if EnableAlpha:
for i in xrange(16384):
for y in xrange(ty,ty+4):
for x in xrange(tx,tx+4):
d = iter.next() << 8
d |= iter.next()
if (d & 0x8000) == 0:
argb = ((d & 0x7000) << 17) | ((d & 0xf00) << 12) | ((d & 0xf0) << 8) | ((d & 0xf) << 4)
else:
argb = 0xFF000000 | ((d & 0x7c00) << 9) | ((d & 0x3e0) << 6) | ((d & 0x1f) << 3)
dest.setPixel(x,y,argb)
tx += 4
if tx >= 1024: tx = 0; ty += 4
else:
for i in xrange(16384):
for y in xrange(ty,ty+4):
for x in xrange(tx,tx+4):
d = iter.next() << 8
d |= iter.next()
if (d & 0x8000) == 0:
argb = 0xFF000000 | ((d & 0xf00) << 12) | ((d & 0xf0) << 8) | ((d & 0xf) << 4)
else:
argb = 0xFF000000 | ((d & 0x7c00) << 9) | ((d & 0x3e0) << 6) | ((d & 0x1f) << 3)
dest.setPixel(x,y,argb)
tx += 4
if tx >= 1024: tx = 0; ty += 4
return dest
def UnloadTileset(idx):
"""Unload the tileset from a specific slot"""
for i in xrange(idx*256, idx*256+256):
Tiles[i] = None
ObjectDefinitions[idx] = None
def ProcessOverrides(idx, name):
"""Load overridden tiles if there are any"""
try:
tsindexes = ['Pa0_jyotyu', 'Pa0_jyotyu_chika', 'Pa0_jyotyu_setsugen', 'Pa0_jyotyu_yougan', 'Pa0_jyotyu_staffRoll']
if name in tsindexes:
offset = 1024 + tsindexes.index(name) * 64
# Setsugen/Snow is unused for some reason? but we still override it
# StaffRoll is the same as plain Jyotyu, so if it's used, let's be lazy and treat it as the normal one
if offset == 1280: offset = 1024
defs = ObjectDefinitions[idx]
t = Tiles
# Invisible blocks
# these are all the same so let's just load them from the first row
replace = 1024
for i in [3,4,5,6,7,8,9,10,13]:
t[i] = t[replace]
replace += 1
# Question and brick blocks
# these don't have their own tiles so we have to do them by objects
replace = offset + 9
for i in xrange(38, 49):
defs[i].rows[0][0] = (0, replace, 0)
replace += 1
for i in xrange(26, 38):
defs[i].rows[0][0] = (0, replace, 0)
replace += 1
# now the extra stuff (invisible collisions etc)
t[1] = t[1280] # solid
t[2] = t[1311] # vine stopper
t[11] = t[1310] # jumpthrough platform
t[12] = t[1309] # 16x8 roof platform
t[16] = t[1291] # 1x1 slope going up
t[17] = t[1292] # 1x1 slope going down
t[18] = t[1281] # 2x1 slope going up (part 1)
t[19] = t[1282] # 2x1 slope going up (part 2)
t[20] = t[1283] # 2x1 slope going down (part 1)
t[21] = t[1284] # 2x1 slope going down (part 2)
t[22] = t[1301] # 4x1 slope going up (part 1)
t[23] = t[1302] # 4x1 slope going up (part 2)
t[24] = t[1303] # 4x1 slope going up (part 3)
t[25] = t[1304] # 4x1 slope going up (part 4)
t[26] = t[1305] # 4x1 slope going down (part 1)
t[27] = t[1306] # 4x1 slope going down (part 2)
t[28] = t[1307] # 4x1 slope going down (part 3)
t[29] = t[1308] # 4x1 slope going down (part 4)
t[30] = t[1062] # coin
t[32] = t[1289] # 1x1 roof going down
t[33] = t[1290] # 1x1 roof going up
t[34] = t[1285] # 2x1 roof going down (part 1)
t[35] = t[1286] # 2x1 roof going down (part 2)
t[36] = t[1287] # 2x1 roof going up (part 1)
t[37] = t[1288] # 2x1 roof going up (part 2)
t[38] = t[1293] # 4x1 roof going down (part 1)
t[39] = t[1294] # 4x1 roof going down (part 2)