Guest User

ZnK Dumper v2.2

a guest
Jun 13th, 2014
306
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 14.30 KB | None | 0 0
  1. #OK guys, I "cheated" and modified the program to get the opcode positions from the .pre files
  2. #Not sure if that was a good idea or not but...
  3. import os
  4. import sys
  5. import struct
  6. import functools
  7.  
  8. facedict = {}
  9. facedict['00'] = 'Lloyd'
  10. facedict['01'] = 'Elie'
  11. facedict['02'] = 'Tio'
  12. facedict['03'] = 'Randy'
  13. facedict['04'] = 'Lazy'
  14. facedict['05'] = 'Noel'
  15. facedict['06'] = 'Dudley'
  16. facedict['07'] = 'Yin'
  17. facedict['08'] = 'Estelle'
  18. facedict['09'] = 'Joshua'
  19. facedict['10'] = 'Sergei'
  20. facedict['11'] = 'KeA'
  21. facedict['12'] = 'Zeit'
  22. facedict['13'] = 'Cecil'
  23. facedict['14'] = 'Arios'
  24. facedict['15'] = 'Sizuku'
  25. facedict['16'] = 'Wald'
  26. facedict['17'] = 'Ilya'
  27. facedict['18'] = 'Rixia'
  28. facedict['19'] = 'Fran'
  29. facedict['20'] = 'Sonya'
  30. facedict['21'] = 'Grace'
  31. facedict['22'] = 'Ian'
  32. facedict['23'] = 'Jona'
  33. facedict['24'] = 'Joachim'
  34. facedict['25'] = 'McDowell'
  35. facedict['26'] = 'Earnest'
  36. facedict['27'] = 'Hartman'
  37. facedict['28'] = 'Dieter'
  38. facedict['29'] = 'Mariabell'
  39. facedict['30'] = 'Marconi'
  40. facedict['31'] = 'Garcia'
  41. facedict['32'] = 'Cao'
  42. facedict['33'] = 'Renne'
  43. facedict['34'] = 'Kirika'
  44. facedict['35'] = 'Lector'
  45. facedict['36'] = 'Harold'
  46. facedict['37'] = 'Sophia'
  47. facedict['38'] = 'Colin'
  48. facedict['39'] = 'Jorg'
  49. facedict['50'] = 'Lloyd (Fancy)'
  50. facedict['51'] = 'Lloyd (Fancy Glasses)'
  51. facedict['52'] = 'Lloyd (Casual)'
  52. facedict['53'] = 'Elie (Fancy)'
  53. facedict['54'] = 'Special'
  54. facedict['55'] = 'Tio (Casual)'
  55. facedict['56'] = 'Randy (Fancy)'
  56. facedict['57'] = 'Lazy (Fancy)'
  57. facedict['58'] = 'KeA (Fancy)'
  58. facedict['59'] = 'Cecil (Fancy)'
  59. facedict['60'] = 'Sizuku (Fancy)'
  60. facedict['61'] = 'Ilya (Dancer)'
  61. facedict['62'] = 'Rixia (Priestess)'
  62. facedict['63'] = 'Noel (Casual)'
  63. facedict['64'] = 'Fran (Casual)'
  64. facedict['65'] = 'McDowell (PJs)'
  65. facedict['66'] = 'Earnest (Suit)'
  66. facedict['67'] = 'Joachim (Blue Hair)'
  67. facedict['68'] = 'Joachim (White Hair)'
  68.  
  69. #Grabs data. It's called by getpointers and myprogram
  70. #myprogram (couldn't think of better name) is the top level function
  71. def get_data(filename):
  72.     totalbytes = os.path.getsize(filename)
  73.     infile = open(filename, 'rb')
  74.     totalfiledata = infile.read(totalbytes)
  75.     return totalfiledata
  76.  
  77. #sys.argv=[sys.argv[0],'c0110']
  78. filedata = get_data(sys.argv[1] + '.orig')
  79. EOFposition = filedata.rfind(sys.argv[1])
  80. nameslist = filedata[EOFposition:].split("\x00")
  81.  
  82. #Takes the input string and makes a nicely formatted output string for the translators
  83. def calculateoutputstring(opcodeaddress,inputstring):
  84.     outputstring = '\n' + opcodeaddress + ";" #1st field is address - write to output
  85.     opcode = inputstring[0].encode('hex') #What opcode is it?
  86.     outputstring += opcode + ';' #2nd field is opcode - write to output
  87.     n = -2
  88.     while True: #looking for last shift-JIS character in opcode
  89.         if ord(inputstring[n]) > 127 and ord(inputstring[n]) < 255 and ord(inputstring[n+1]) > 39:
  90.             break
  91.         n -= 1
  92.         if len(inputstring) + n == 0:
  93.             print "No text in opcode " + opcode + " at address " + opcodeaddress
  94.             return ""
  95.     strpos = 1
  96.     while True:
  97.         if ord(inputstring[strpos]) == 35: break # Pound character is 1st
  98. # Shift-JIS character is first
  99.         if ord(inputstring[strpos]) > 127 and ord(inputstring[strpos]) < 255 and ord(inputstring[strpos+1]) > 39: break
  100.         if strpos == len(inputstring)-1:
  101.             print "No user text in opcode 5b at address " + opcodeaddress
  102.             return ""
  103.         strpos += 1
  104.  
  105.     startofline = strpos #tells program where the start of the current line is
  106.  
  107.     userlength = len(inputstring)-startofline+n+2
  108.    
  109.     lastuserchar = len(inputstring)+n+1 #tells program when to stop
  110.  
  111.     startflag = True #tells program whether the first line in the opcode has been output yet or not (True = not yet)
  112.     JIScharpos = 0 #misleading name. Really the position of the last ascii character. lastasciichar was too long a name...
  113.  
  114. #Go byte by byte
  115.     while strpos <= lastuserchar + 2: #Until end of the string...
  116.         output = False #reset flag
  117. #Our byte is a SHIFT-JIS value
  118.         if ord(inputstring[strpos]) > 127:
  119.             strpos += 2 #move pointer forward and check again
  120. #Our byte is an ASCII value (which is fine too)
  121.         elif int(inputstring[strpos].encode('hex'),16) > 19:
  122.             strpos += 1 #move pointer forward and check again
  123.             if inputstring[strpos] in ('P','K','F','N'): #If the character is the end of a text code then:
  124.                 JIScharpos = strpos #Set (or reset) the position of the last ascii character
  125. #Our byte at this point must be some weird Falcom text code
  126. #The 0x00 code is used in 0x5D opcodes to separate the name and what the name should say
  127.         elif inputstring[strpos].encode('hex') == '00':
  128.             if opcode in ('5b','5d'): #For 5D opcodes, the speaker name is in the opcode itself
  129.                 speaker = inputstring[startofline:strpos] + ";"
  130.             if opcode == '5b':
  131.                 breaktype = 'None'
  132.                 codes = ';'
  133.                 speech = ';'
  134.                 outputstring += speaker + codes + speech + breaktype + ";" + str(userlength)
  135.                 return outputstring
  136.             strpos, startofline = strpos + 1, strpos + 1
  137.             JIScharpos = strpos
  138. #The 0x01 opcode is a line break
  139.         elif inputstring[strpos].encode('hex') == '01':
  140.             breaktype = "linebreak"
  141.             output = True #Tells the program to do the "output" routine on this pass through the loop
  142. #We output a line every time there is either linebreak, newdialogbox or terminalcode
  143.  
  144. #There's two codes starting with 0x02 that we know of:
  145. #0x0200 ends the opcode
  146. #0x0203 starts a new dialog box within the same opcode
  147.         elif strpos == lastuserchar + 1: #The pointer (within this program) is at the end of the opcode
  148. #I call it the "pointer" because we are looking at the actual opcode byte by byte, moving the pointer each time
  149.             output = True
  150.             breaktype = "terminalcode"
  151.            
  152.         elif inputstring[strpos].encode('hex') == '02':
  153.             output = True
  154.             if inputstring[strpos+1].encode('hex') == '03':
  155.                 breaktype = "newdialogbox"
  156.             else:
  157.                 print "Unknown opcode format in opcode %s at address %s." % (opcode,opcodeaddress)
  158.                 return ""
  159.         elif inputstring[strpos].encode('hex') == '07':
  160.             breaktype = '0x' + inputstring[strpos:strpos+2].encode('hex')
  161.             output = True
  162.         else:
  163.             print "Unknown opcode format in opcode %s at address %s." % (opcode,opcodeaddress)
  164.             return ""
  165.  
  166.         if output: #output routine
  167.  
  168.             thisline = inputstring[startofline:strpos] #Gives the string. Further processed below.
  169.             JIScharpos += 1 #That's because the value computed above is really the character _before_ the first JIS character
  170.  
  171.             if len(inputstring[startofline:JIScharpos]) > 1: #There are ASCII characters in thisline
  172.                 codes = inputstring[startofline:JIScharpos] + ";" #Grabs the codes
  173.                 speech = inputstring[JIScharpos:strpos] + ";" #Grabs the non-codes part of the line
  174.                 if codes.find('F') > -1 and opcode != '5d': #If there is an "F" code in the codes, we need the faces routine
  175.                     facecodepos = codes.find('F') #Gets face code position within the codes
  176.                     facecode1 = thisline[facecodepos-4:facecodepos-2] #First two numbers of face code (as string)
  177.                     facecode2 = thisline[facecodepos-2:facecodepos] #Last two numbers of face code (as string)
  178.                     speaker = facedict.get(facecode1,'Unknown') + ";" #You know that dictionary at the top? Go get the name based on the 1st two numbers.
  179.                     if speaker == 'Special': #What to do if the face code starts with "54"
  180.                         if int(facecode2) < 12: speaker = "Tio (Fancy);"
  181.                         else: speaker = "Zeit;"
  182.                 elif opcode != '5d': #For 5D opcodes, the speaker has already been set; we don't want to mess that up.
  183.                     if opcode == '5c' and inputstring[2] == "\x00":
  184.                         nameindex = ord(inputstring[1]) - 7
  185.                         speaker = nameslist[nameindex] + ";"
  186.                     else:
  187.                         speaker = ";" #For non 5D opcodes, there's no speaker on this line, so we make a blank
  188.  
  189.             else: #No text codes on this line - make some blanks
  190.                 codes = ";"
  191.                 speaker = ";"
  192.                 speech = thisline + ";"
  193.  
  194.             if startflag == True: #What to do on the first pass
  195.                 outputstring += speaker + codes + speech + breaktype + ";" + str(userlength)
  196.                 startflag = False
  197.             else: #Second and later passes have a newline and don't have address or opcode, so two blanks are needed
  198.                 outputstring += "\n;;" + speaker + codes + speech + breaktype
  199.  
  200.             if breaktype == "linebreak": #Update state variables at the end, move the pointer, etc...
  201.                 strpos, startofline = strpos + 1, strpos + 1
  202.             else:
  203.                 strpos, startofline = strpos + 2, strpos + 2
  204.  
  205.             JIScharpos = strpos
  206.            
  207.     return outputstring
  208.  
  209. #Loads the *.pre file and returns the pointers from it
  210. def getpointers():
  211. #    filedata = get_data(filename)
  212. #    opcodepos = filedata.find('\x00\xcc\xcc')-1 #I can't decode .pre headers so this'll have to do.
  213. #    if opcodepos < 0:
  214. #        return 'error' #if there's no dialog here then exit program entirely
  215.     opcodes = []
  216.     pointers = []
  217. #    while opcodepos < len(filedata)-12: #Weird magic number here ("12")
  218. # Could use some help getting rid of this magic number
  219. # I need the program to stop before the end of the file to avoid string index out of range error
  220. # The last opcode usually doesn't point to dialog so I think this could be fine for now
  221. #        opcode = []
  222. #        for n in range(11):
  223. #            opcode.append(filedata[opcodepos+n].encode('hex'))
  224. #        opcodepos += 12 #This magic number is fine; opcodes/pointer bytes/whatever in .pre are 12 bytes long
  225. #        opcodes.append(opcode)
  226. #    for opcode in opcodes:
  227. #        if [opcode[2],opcode[3]] == ['cc','cc']:
  228. # It converts the little endian value (which makes no sense) to big endian (which does make sense)
  229. #            thisval = hex(struct.unpack('<I',(opcode[4] + opcode[5] + opcode[6] + opcode[7]).decode('hex'))[0])
  230. #            if not thisval in pointers:
  231. #                pointers.append(thisval)
  232.     strpos = 0
  233.  
  234. #    filedata = get_data(filename2)
  235.     while strpos > -1:
  236.         strpos = filedata.find('\x5e\x00\x00\xff\xff\xff\xff',strpos+1)
  237.         if strpos > 0 and hex(strpos) not in pointers:
  238.             pointers.append(hex(strpos))
  239.  
  240.     strpos = 0
  241.     while strpos > -1:
  242.         strpos = filedata.find('\x55\xff\x00',strpos+1)
  243.         if strpos > 0 and hex(strpos) not in pointers:
  244.             pointers.append(hex(strpos))
  245.        
  246.     strpos = 0
  247.     while strpos > -1:
  248.         strpos = filedata.find('\x5c',strpos+1)
  249.         if strpos > 0 and ord(filedata[strpos-1]) < 128:
  250.             if ord(filedata[strpos+3]) == 35:
  251.                 if hex(strpos) not in pointers: pointers.append(hex(strpos))
  252.             elif ord(filedata[strpos+3]) > 127 and ord(filedata[strpos+3]) < 255 and ord(filedata[strpos+4]) > 39:
  253.                 if hex(strpos) not in pointers: pointers.append(hex(strpos))
  254.  
  255.     strpos = 0
  256.     while strpos > -1:
  257.         strpos = filedata.find('\x5d',strpos+1)
  258.         if strpos > 0 and ord(filedata[strpos-1]) < 128:
  259.             if ord(filedata[strpos+3]) > 127 and ord(filedata[strpos+3]) < 255 and ord(filedata[strpos+4]) > 39:
  260.                 if hex(strpos) not in pointers: pointers.append(hex(strpos))
  261.    
  262.     strpos = 0
  263.     while strpos > -1:
  264.         strpos = filedata.find('\x5b\xff\xff',strpos+1)
  265.         if strpos > 0:
  266.             if hex(strpos) not in pointers: pointers.append(hex(strpos))
  267.     return pointers
  268.  
  269. def myprogram(filename):
  270.     pointers = getpointers() #First grab the pointers. We'll need these later.
  271.     if pointers == 'error':
  272.         print 'No dialog in this file.'
  273.         quit()
  274.  
  275. #    filedata = get_data(filename)
  276.     outfiledata = filename
  277.  
  278.     for pointer in sorted(pointers,key=functools.partial(int,base=16)):
  279. # The 5C and 5D opcodes we're looking for in this program are variable length.
  280. # We have to search for their ends.
  281.         if int(pointer,16) < len(filedata):
  282.             opcode = filedata[int(pointer,16)].encode('hex')
  283.             if opcode == '5e':
  284.                 strend = filedata.find('\x01\x00',int(pointer,16)) #Find the end of the opcode
  285.                 strend += 2
  286.             elif opcode in ('55','5c','5d'):
  287.                 strend = filedata.find('\x02\x00',int(pointer,16)) #Find the end of the opcode
  288.                 strend += 2
  289.             elif opcode == '5b':
  290.                 strpos = int(pointer,16)
  291.                 while True:
  292.                     if filedata[strpos].encode('hex') == '55':
  293.                         if ord(filedata[strpos-1]) < 128 or ord(filedata[strpos-1]) > 254:
  294.                             strend = strpos
  295.                             break
  296.                     strpos += 1
  297.                     if strpos - int(pointer,16) > 30:
  298.                         print "5b opcode miss at address " + pointer
  299.                         opcode = ""
  300.                         break
  301.  
  302.             else:
  303.                 print "Unknown opcode " + filedata[int(pointer,16)].encode('hex') + " at address " + pointer
  304.     # Pass the pointer address and entire opcode to a function for formatting the dump
  305.             if opcode in ('55','5c','5d','5e','5b'):
  306.                 if filedata[int(pointer,16):strend] != "":
  307.                     outputstring = calculateoutputstring(pointer,filedata[int(pointer,16):strend])
  308.                     outfiledata += outputstring #Append formatted string to program output
  309.         else:
  310.             print "Data at address " + pointer + " is not within the file."
  311.        
  312.     outfile = open(os.path.splitext(filename)[0] + '.data','wb')
  313.     outfile.write(outfiledata) #write the output
  314.     outfile.close
  315.        
  316. ##if __name__ == '__main__':
  317. ##
  318. ##    sys.argv=[sys.argv[0],'e0410']
  319. ##    myprogram(sys.argv[1] + '.orig',sys.argv[1] + '.pre')
  320. myprogram(sys.argv[1] + '.orig')
Add Comment
Please, Sign In to add comment