4
1

qrsc_to_tw.py 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322
  1. #!/usr/bin/env python3
  2. import fileinput
  3. import io, os, re, datetime
  4. import hashlib
  5. import variables
  6. import time
  7. verbose = False
  8. #verbose = True
  9. skipMode = 0
  10. #skipMode = -1
  11. verbose_i = 20
  12. error_counter = 1
  13. regex_parts = {}
  14. regex_parts['operator_assign'] = r'=|\+=|-='
  15. regex_parts['parameter'] = r"\$ARGS\[\d+\]"
  16. regex_parts['var'] = r"\$?[a-z]+\w*"
  17. regex_parts['functioncall'] = r"\w+\s*\(\s*\w+\s*(?:,\s*\w*\s*)*\)"
  18. regex_parts['integer'] = r"\d+"
  19. regex_parts['string'] = r"""'\w'|"""+ r'''"\w"'''
  20. regex_parts['value_literal'] = "|".join([regex_parts['integer'],regex_parts['string']])
  21. regex_parts['value'] = "|".join([regex_parts['parameter'],regex_parts['var'],regex_parts['functioncall'],regex_parts['value_literal'] ])
  22. regex_parts['statement'] = '?'
  23. regex_parts['assignment'] = f"\s*({regex_parts['var']})\s*({regex_parts['operator_assign']})\s*({regex_parts['value']})\s*"
  24. def pv(desc,line):
  25. if(verbose):
  26. print(desc.ljust(verbose_i, ' ')+line)
  27. def convert_calculation(right):
  28. pv("START CALCULATION:",right)
  29. brackets_regex = r"""(?<![a-zA-Z0-9])\(\s*([^\)^\(]+(\s*\-|mod|\+|/|\*\s*)[^\)^\(]+)\s*\)"""
  30. #brackets_regex = r"""(?<![a-zA-Z0-9])(?:min|rand|max|mid)\(\s*([^\)^\(]+(\s*\-|mod|\+|/|\*\s*)[^\)^\(]+)\s*\)"""
  31. calculations = []
  32. #print(right)
  33. while b_match := re.search(brackets_regex,right):
  34. complete_match = b_match.group(0)
  35. calculation_raw = b_match.group(1)
  36. operator = b_match.group(2)
  37. if operator == 'mod':
  38. calculation_raw = calculation_raw.replace('mod','%')
  39. calculation = convert_literal(calculation_raw)
  40. index = f"$CALC_HELPER_{len(calculations)}"
  41. right = right.replace(complete_match,index)
  42. calculations.append(calculation)
  43. right = convert_literal(right)
  44. #function_name_regex = r"""(?<![a-zA-Z0-9])(min|rand|mid|max)\s*\$LIT_HELPER_(0)"""
  45. #while function_name_match := re.search(function_name_regex,right):
  46. # complete_match = function_name_match.group(0)
  47. # index = f"$LIT_HELPER_{len(calculations)}"
  48. # right = right.replace(complete_match,index)
  49. # calculations.append(complete_match)
  50. while len(calculations) > 0:
  51. calculation = calculations.pop()
  52. index = f"$CALC_HELPER_{len(calculations)}"
  53. right = right.replace(index,f"({calculation})")
  54. pv("IS CALCULATION:",right)
  55. return right
  56. def convert_command(command_raw):
  57. command = command_raw.strip()
  58. #if (command.startswith('<') or and command.endswith('>'):
  59. # return command
  60. split_by_and = command.split(' & ')
  61. if len(split_by_and) > 1:
  62. return ' '.join([convert_command(s) for s in split_by_and])
  63. assign_operators = ['=','-=','+=']
  64. for assign_operator in assign_operators:
  65. split_by_assign = command.split(assign_operator,1)
  66. if len(split_by_assign) > 1:
  67. left = split_by_assign[0]
  68. if left.startswith('set '):
  69. left = left[4:]
  70. right = split_by_assign[1]
  71. right = convert_calculation(right)
  72. pv("IS ASSIGNMENT:",right)
  73. return f'<<set {convert_literal(left)} {assign_operator} {right}>>'
  74. if match := re.match(r"^(?:set\s*)?(\$?\w+)\s*(\+=|-=|=)\s*([\$']?\w*'?|\w+\s*\(\s*\w+\s*(?:,\s*\w*\s*)*\))$",command):
  75. return f'<<set {convert_literal(match.group(1))} {match.group(2)} {convert_literal(match.group(3))}>>'
  76. if match := re.match(r"""^(x?gt|gs)([\s'"].+)$""",command):
  77. arguments = match.group(2)
  78. pv('GS OR GT:',command)
  79. i = 0
  80. replaces = []
  81. while brackets_match := re.search(r"""\(([^\(^\)]*?,[^\(^\)]*?)\)""",arguments):
  82. original = brackets_match.group(1)
  83. pv("REPLACE:",original)
  84. indentifier = f'$BRACKET_HELER_{i}'
  85. arguments = arguments.replace(original,indentifier)
  86. replaces.append(original)
  87. i += 1
  88. arguments = " ".join([convert_literal(l) for l in arguments.split(',')])
  89. while len(replaces) > 0:
  90. original = replaces.pop()
  91. indentifier = f'$BRACKET_HELER_{len(replaces)}'
  92. arguments = arguments.replace(indentifier,original)
  93. return f'<<{match.group(1)} {arguments}>>'
  94. if match := re.match(r"""^msg\s*(.+)$""",command,re.I):
  95. return f"<<msg {match.group(1)}>>"
  96. if match := re.match(r"""^dynamic \$(.*)$""",command,re.I):
  97. arguments = match.group(1).replace(',',' ')
  98. return f"<<{arguments}>>"
  99. pv("NO COMMAND MATCH:",command)
  100. return ''
  101. def convert_condition(condition_raw):
  102. condition = condition_raw.strip()
  103. if(re.match(r"dyneval\(",condition)):
  104. return condition
  105. #condition = convert_calculation(condition)
  106. #print(condition)
  107. subconditions = []
  108. bracket_search_regex = r"""(?<![a-zA-Z0-9])\(\s*([^\)^\(]+)\s*\)"""
  109. bracket_search_regex = r"""(?<![a-zA-Z0-9])\(\s*([^\)^\(]+(\s*and|or|xor\s*)[^\)^\(]+)\s*\)"""
  110. while match := re.search(bracket_search_regex,condition):
  111. fullmatch = match.group(0)
  112. subcondition = match.group(1)
  113. subcondition_converted = convert_condition(subcondition)
  114. subcondition_ident = f"$CON_HELPER_{len(subconditions)} == 1"
  115. condition = condition.replace(fullmatch,subcondition_ident)
  116. subconditions.append(subcondition_converted)
  117. #print(condition)
  118. if len(subconditions) > 0:
  119. condition = convert_condition(condition)
  120. while len(subconditions) > 0:
  121. subcondition = subconditions.pop()
  122. subcondition_ident = f"$CON_HELPER_{len(subconditions)} == 1"
  123. condition = condition.replace(subcondition_ident,f"({subcondition})")
  124. #print(condition)
  125. return condition
  126. split_by_or = condition.split(' or ')
  127. if len(split_by_or) > 1:
  128. return ' or '.join([convert_condition(s) for s in split_by_or])
  129. split_by_xor = condition.split(' xor ')
  130. if len(split_by_xor) > 1:
  131. return ' xor '.join([convert_condition(s) for s in split_by_xor])
  132. split_by_and = condition.split(' and ')
  133. if len(split_by_and) > 1:
  134. return ' and '.join([convert_condition(s) for s in split_by_and])
  135. #match = re.match(r"(\$ARGS\[\d+\]|\$?\w+)\s*([=><]+)\s*('?\w+'?)",condition)
  136. #match = re.match(r"(\S+)\s*([=><]+)\s*(\S+)",condition)
  137. if(len(condition) >= 2 and condition[0] == '(' and condition[-1] == ')'):
  138. condition = condition[1:-1]
  139. #print(condition)
  140. match = re.match(r"([^<^>^=^!]+)\s*([=><!]+)\s*([^<^>^=^!]+)",condition)
  141. if match:
  142. left = convert_literal(convert_calculation(match.group(1)))
  143. right = convert_literal(match.group(3))
  144. operator = match.group(2)
  145. if operator == '=':
  146. operator = '=='
  147. elif operator == '!':
  148. operator = '!='
  149. elif operator == '=>':
  150. operator = '>='
  151. elif operator == '=<':
  152. operator = '<='
  153. return ' '.join([left,operator,right])
  154. return f'ERROR: FAILED TO CONVERT CONDITION: {condition}'
  155. def convert_literal(literal_raw):
  156. literal = literal_raw.strip()
  157. pv("START LITERAL:",literal)
  158. if not literal:
  159. return ''
  160. subliterals = []
  161. bracket_search_regex = r"""\[\s*([^\]^\[]+)\s*\]"""
  162. while match := re.search(bracket_search_regex,literal):
  163. fullmatch = match.group(0)
  164. subcondition = match.group(1)
  165. subcondition_converted = convert_literal(subcondition)
  166. subcondition_ident = f"LIT_HELPER_{len(subliterals)}"
  167. literal = literal.replace(fullmatch,subcondition_ident)
  168. subliterals.append(subcondition_converted)
  169. #print(condition)
  170. if len(subliterals) > 0:
  171. literal = convert_literal(literal)
  172. while len(subliterals) > 0:
  173. subcondition = subliterals.pop()
  174. subcondition_ident = f"LIT_HELPER_{len(subliterals)}"
  175. literal = literal.replace(subcondition_ident,f"[{subcondition}]")
  176. #print(condition)
  177. return literal
  178. #brackets_regex = r"""\(\s*([^\)^\(]+)\s*\)"""
  179. #function_name_regex = r"""(?<![a-zA-Z0-9])(min|rand|mid|max)\s*\$LIT_HELPER_(0)"""
  180. #calculations = []
  181. #while b_match := re.search(brackets_regex,literal):
  182. # complete_match = b_match.group(0)
  183. # calculation_raw = b_match.group(1)
  184. # calculation_parts = calculation_raw.split(',')
  185. # calculation = ','.join([convert_literal(s) for s in calculation_parts])
  186. # index = f"$LIT_HELPER_{len(calculations)}"
  187. # literal = literal.replace(complete_match,index)
  188. # calculations.append(calculation)
  189. #while function_name_match := re.search(function_name_regex,literal):
  190. # complete_match = function_name_match.group(0)
  191. # index = f"$LIT_HELPER_{len(calculations)}"
  192. # literal = literal.replace(complete_match,index)
  193. # calculations.append(complete_match)
  194. #if len(calculations) > 0:
  195. # literal = convert_literal(literal)
  196. # while len(calculations) > 0:
  197. # calculation = calculations.pop()
  198. # index = f"$LIT_HELPER_{len(calculations)}"
  199. # literal = literal.replace(index,f"({calculation})")
  200. # pv("LITERAL AFTER BRACKETS:",literal)
  201. if(re.match(r"dyneval\(",literal)):
  202. return literal
  203. if literal == "''" or literal == '""':
  204. return literal
  205. if(literal.isnumeric() or (literal.startswith('-') and literal[1:].isnumeric())):
  206. pv("IS NUMERIC",literal)
  207. return literal
  208. if(literal.startswith('(') and len(literal) > 1):
  209. return '('+literal[1:]
  210. if(literal.endswith(')') and len(literal) > 1):
  211. return literal[:-1]+')'
  212. #array_braces = False
  213. #while match:=re.match(r"\$?([a-z][a-z0-9\-_{}'\+]*)(\['(.*?<<.*?>>'*?)'\])",literal,re.I):
  214. # value = match.group(3)
  215. # if not value.startswith("<"):
  216. # value = value.replace("<<","'+")
  217. # else:
  218. # value = value.replace("<<","")#
  219. #
  220. # if not value.endswith(">"):
  221. # value = value.replace(">>","+'")
  222. # else:
  223. # value = value.replace(">>","")
  224. # literal = literal.replace(match.group(2),r"{{"+value+r"}}")
  225. # array_braces = True
  226. #if array_braces:
  227. # literal = literal.replace(r'{{','[').replace(r'}}',']')
  228. if(len(literal)>= 3 and ((literal[0] == '\'' and literal[-1] == '\'') or (literal[0] == '"' and literal[-1] == '"') )):
  229. literal = literal.replace('<<','')
  230. literal = literal.replace('>>','')
  231. literal = literal.replace("''","'")
  232. return literal
  233. if(match := re.match(r"^arrsize\(\s*'(\$?)([a-z]+\w*)'\s*\)$",literal)):
  234. return f"${match.group(2)}.length"
  235. if(match := re.match(r"^killvar\s+'(\$?)([a-z]+\w*)'$",literal,re.I)):
  236. return f"<<set ${match.group(2)} to null>>"
  237. if(match := re.match(r'^\$ARGS\[(\d+)\]$',literal,re.I)):
  238. #ARGS
  239. return f'$location_var[$here][{match.group(1)}]'
  240. if(match := re.match(r'^\$ARGS(LIT_HELPER_\d+)$',literal,re.I)):
  241. #ARGS
  242. return f'$location_var[$here]'+match.group(1)
  243. if(match := re.match(r"^(\$?)[a-zA-z]+\w*(\[('\w*'|\d+)\])?$",literal)):
  244. if match.group(1):
  245. return literal
  246. return '$'+literal
  247. if(match := re.match(r"^(\$?)([a-zA-z]+\w*)\[(.+)\]$",literal)):
  248. #if match.group(1):
  249. # return f"${match.group(2)}[{convert_literal(match.group(3))}]"
  250. return f"${match.group(2)}[{convert_literal(match.group(3))}]"
  251. #print(literal)
  252. if(match := re.match(r'^(\w+)\s*\((\s*\w+\s*(?:,\s*\w*\s*)*)\)$',literal)):
  253. function_name = match.group(1)
  254. function_parameters = match.group(2)
  255. return f'{function_name}({convert_literal(function_parameters)})'
  256. while(match := re.search(r'<<(\$\w+)>>',literal)):
  257. literal = literal.replace(match.group(0),match.group(1))
  258. #Arithmetic Operations
  259. arith_operations = ['*','/','-','+','%',',','mod']
  260. for arith_operation in arith_operations:
  261. split_by_arith = literal.split(arith_operation)
  262. if len(split_by_arith) > 1:
  263. if arith_operation == 'mod':
  264. arith_operation = '%'
  265. return f' {arith_operation} '.join([convert_literal(s) for s in split_by_arith])
  266. if literal.startswith('wait '):
  267. return f'<<{literal}>>'
  268. if(match := re.match(r"""^killvar\s+['"]\$?(.*)['"]$""",literal)):
  269. return f'<<set ${match.group(1)} = 0>>'
  270. if literal.startswith('jump '):
  271. jump_san = literal.replace('"','').replace("'","")
  272. return f"<<warn 'JUMP COMMAND ENCOUNTERED: {jump_san}'>>"
  273. if literal.startswith(':'):
  274. return f"<<warn 'JUMP MARKER ENCOUNTERED: {literal}'>>"
  275. if literal == "'" or literal == '"':
  276. return ''
  277. if re.match(r"""^['"\w\s\?\.!\(\)\$]+$""",literal):
  278. pv("Plain String",literal)
  279. return literal
  280. #return literal
  281. return f'ERROR: FAILED TO CONVERT LITERAL: """{literal}"""'
  282. function_name_conversions = []
  283. def convert_lineblock(lines,location_identifier=''):
  284. outputs = []
  285. nesting = []
  286. commenting = False
  287. isfunction = False
  288. functionlines = []
  289. functionlines_temp = []
  290. function_name = ''
  291. subpassages = {}
  292. subpassage = ''
  293. for line_raw in lines:
  294. #line_raw = lines[line_num]
  295. line = line_raw.strip()
  296. original = line
  297. pv("START:",line)
  298. if len(line) == 0:
  299. continue
  300. whitespace_count = len(nesting)
  301. # Subpassages
  302. if len(subpassage) > 0:
  303. if line.startswith('~$'):
  304. endSubpassageName = line[2:]
  305. gtOrGs = 'gt'
  306. if endSubpassageName.startswith('gs:'):
  307. gtOrGs = 'gs'
  308. endSubpassageName = endSubpassageName[3:]
  309. if endSubpassageName == subpassage:
  310. outputs.append( whitespace_count * '\t' + f"<<{gtOrGs} '{subpassage}' $location_var[$here][0] $location_var[$here][1] $location_var[$here][2] $location_var[$here][3] $location_var[$here][4]>>\n")
  311. subpassages[subpassage].append('<!-- END: '+subpassage+' -->')
  312. subpassage = ''
  313. continue
  314. subpassages[subpassage].append(line)
  315. continue
  316. if len(subpassage) == 0:
  317. if line.startswith('~^'):
  318. startSubpassageName = line[2:]
  319. subpassage = startSubpassageName
  320. subpassages[subpassage] = []
  321. continue
  322. for preparation in preparations:
  323. if len(preparation) > 2:
  324. line = re.sub(preparation[0],preparation[1],line,0,preparation[2])
  325. else:
  326. line = re.sub(preparation[0],preparation[1],line)
  327. line_output = ''
  328. purges = [
  329. 'CLOSE ALL',
  330. 'close all',
  331. '*clr & cla',
  332. 'killall',
  333. 'showstat 0','showstat 1',
  334. 'showobjs 0','showobjs 1',
  335. 'showinput 0','showinput 1',
  336. "gs 'stat'","gs'stat'",
  337. ]
  338. for purge in purges:
  339. line = line.replace(purge,'')
  340. pv("AFTER PURGES:",line)
  341. #line = line.replace(" mod "," % ")
  342. #while match := re.match(r"iif\s*\((.+),(.*),(.*)\)",line):
  343. # line = line.replace(match.group(0),f"({convert_condition(match.group(1))}) ? {convert_literal(match.group(2))} : {convert_literal(match.group(3))}")
  344. # FUNCTIONS
  345. if isfunction:
  346. if line.endswith('}'):
  347. isfunction = False
  348. functionname_sanatized = function_name.replace('$','').replace('[','').replace(']','').replace("'",'')
  349. functionlines.append(f':: {functionname_sanatized}_macro[widget]\n<<widget "{functionname_sanatized}">>\n')
  350. functionlines_temp = convert_lineblock(functionlines_temp)
  351. for fl in functionlines_temp:
  352. functionlines.append(f'\t{fl}')
  353. functionlines.append(f'<</widget>>\n')
  354. function_name_conversions.append([function_name,functionname_sanatized])
  355. else:
  356. functionlines_temp.append(line)
  357. continue
  358. if match := re.match(r"""(\$[a-z][a-z0-9\-_'"\[\]]+)\s*=\s*{""",line,re.I):
  359. isfunction = True
  360. #functionlines.append(f'<<widget "{match.group(1)}">>')
  361. function_name = match.group(1)
  362. functionlines_temp = []
  363. continue
  364. pv("AFTER FUNCTIONS:",line)
  365. while fuckyoumatch := re.search(r"""\[["']([^\]]*?)<<(.*?)>>(.*?)["']\]""",line):
  366. index = f'${fuckyoumatch.group(2)}'
  367. #left = ''
  368. if fuckyoumatch.group(1):
  369. index = f"'{fuckyoumatch.group(1)}'+" + index
  370. #right = ''
  371. if fuckyoumatch.group(3):
  372. index = index + f"+'{fuckyoumatch.group(3)}'"
  373. # right = fuckyoumatch.group(3)
  374. #index = f"'{left}'+${fuckyoumatch.group(2)}+'{right}'"
  375. #print(index)
  376. line = line.replace(fuckyoumatch.group(0),f"[{index}]")
  377. #print("MATCH")
  378. pv("AFTER ARRAY []:",line)
  379. while dynevalmatch := re.search(r"""dyneval\s*\(\s*'\s*RESULT\s*=\s*(<<.*?)'\s*\)""",line):
  380. fullmatch = dynevalmatch.group(0)
  381. varname = dynevalmatch.group(1)
  382. varname = varname.replace(r"[''",r"['").replace(r"'']",r"']")
  383. varname = "State.getVar('$"+varname.replace('<<',"'+").replace('>>',"+'")+"')"
  384. line = line.replace(fullmatch,varname)
  385. #print(line)
  386. pv("AFTER DYNEVAL:",line)
  387. while dynevalmatch := re.search(r"""dyneval\s*\(\s*'\s*RESULT\s*=\s*\$?(.*?)'\s*\)""",line):
  388. fullmatch = dynevalmatch.group(0)
  389. varname = "$"+dynevalmatch.group(1)
  390. varname = varname.replace('<<',"'+").replace('>>',"+'")
  391. #varname = varname.replace(r"[''",r"['").replace(r"'']",r"']")
  392. varname = varname.replace("['+","[").replace(r"+']",r"]")
  393. varname = varname.replace('$$',"$")
  394. line = line.replace(fullmatch,varname)
  395. pv("AFTER DYNEVAL2:",line)
  396. if line.startswith('!{') or line.startswith('!!{') or line == '!!{':
  397. line_output = '<!-- ' + line
  398. if line.endswith('}'):
  399. line_output += ' -->'
  400. else:
  401. commenting = True
  402. pv("IS COMMENT:",line_output)
  403. elif line.endswith('}') and commenting:
  404. line_output = line+' -->'
  405. commenting = False
  406. pv("IS COMMENT:",line_output)
  407. elif commenting:
  408. line_output = line.replace('--','-')
  409. pv("IS COMMENT:",line_output)
  410. elif line.lower() == 'end' or line.lower().startswith('end &!'):
  411. whitespace_count -= 1
  412. if len(nesting) > 0:
  413. end_command = nesting.pop()
  414. if end_command == 'if':
  415. #file.write('<</if>>\n')
  416. line_output = '<</if>>'
  417. elif end_command == 'while':
  418. #file.write('<</while>>\n')
  419. line_output = '<</while>>'
  420. elif end_command == 'act':
  421. #file.write('<</act>>\n')
  422. line_output = '<</act>>'
  423. else:
  424. print(f'ERROR: UNKNOWN NESTRING: {end_command}')
  425. else:
  426. line_output = '<</END>>'
  427. pv("IS END:",line_output)
  428. elif line.startswith('!'):
  429. line_output = '<!-- ' + line + '-->'
  430. pv("IS COMMENT:",line_output)
  431. elif line.lower() == 'else':
  432. #file.write('<<else>>\n')
  433. line_output = '<<else>>'
  434. whitespace_count -= 1
  435. pv("IS ELSE:",line_output)
  436. elif line.lower() == 'cls':
  437. line_output = ''
  438. pv("IS CLS:",line_output)
  439. elif line.lower() == '*nl':
  440. #file.write('\n')
  441. line_output = ''
  442. pv("IS NL:",line_output)
  443. elif line[0:3] == '---':
  444. line_output = ''
  445. pv("IS EOF:",line_output)
  446. elif match := re.match(r"^\s*msg\s*'(.*)'\s*$",line,re.I):
  447. msg = match.group(1).replace("'",'"')
  448. line_output = f"""<<msg '{msg}'>>"""
  449. pv("IS MSG:",line_output)
  450. elif match := re.match(r"""act\s*'(.*?)\s*\(<font color="red"><<will_cost>> Willpower</font>\)':\s*'<br><font color="red">You don''t have enough willpower to use this action.</font>'""",line,re.I):
  451. label = match.group(1).replace("'",'"')
  452. line_output = f"<<act `'{label} ('+$will_cost+')'`>><font color=red><br/>You don`t have enough willpower to use this action.</font><</act>>"
  453. elif match := re.match(r"""^'(?:<center>)?<img\s+(?:<<\$?\w+>>\s+)src="images\/([\w\/\.]+)(?:'\s*\+\s*rand\((\d+,\d+)\)\s*\+\s*')?([\w\/\.]+)"\s*>(?:<\/center>)?'""",line,re.I):
  454. #Images
  455. if match.group(2):
  456. line_output = f'''<<image "{match.group(1)}#{match.group(3)}" {match.group(2).replace(',',' ')}>>'''
  457. else:
  458. line_output = f'''<<image "{match.group(1)}{match.group(3)}">>'''
  459. pv("IS IMAGE:",line_output)
  460. elif match := re.match(r"""^'?(?:<center>)?<video\s+(?:<<\$?\w+>>\s+)*(?:\s*autoplay\s*|\s*loop\s*)*src="images\/([\w\/\.]+)(?:'\s*\+\s*rand\((\d+,\d+)\)\s*\+\s*')?([\w\/\.]+)"\s*>(?:<\/video>)?(?:<\/center>)?'?""",line,re.I):
  461. #Images
  462. if match.group(2):
  463. line_output = f'''<<video "{match.group(1)}#{match.group(3)}" {match.group(2).replace(',',' ')}>>'''
  464. else:
  465. line_output = f'''<<video "{match.group(1)}{match.group(3)}">>'''
  466. pv("IS VIDEO:",line_output)
  467. elif line.startswith('<') and line.endswith('>'):
  468. line_output = line
  469. pv("IS HTML:",line_output)
  470. elif line.startswith("'<") and line.endswith(">'"):
  471. line_output = line[1:-1]
  472. pv("IS COMMENTED HTML:",line_output)
  473. elif match := re.match(r"""^'[\w<>\s=:'"\/\.\(\),\*]+'$""",line):
  474. #Plain HTML
  475. line_output = line[1:-1]
  476. if link_match := re.findall(r"""(<a href="exec:([^"]+)">([^<]+)<\/a>)""",line_output):
  477. #line_output = #line_output.replace(link_match[0],"moep")
  478. #print("moep")
  479. #print(link_match)
  480. for lmatch in link_match:
  481. line_output = line_output.replace(lmatch[0],f"""<<link "{lmatch[2]}">>{convert_command(lmatch[1])}<</link>>""")
  482. pv("IS PLAIN HTML:",line_output)
  483. elif match := re.match(r"^\s*(if|while)\s+([^:]+):(.*)",line,re.I):
  484. command = match.group(1).lower()
  485. line_w = f'<<{command} {convert_condition(match.group(2))}>>'
  486. if match.group(3):
  487. #if com := convert_command(match.group(3)):
  488. # line_w += '\n' + (whitespace_count+1) * '\t' + com
  489. #else:
  490. # line_w += '\n' + (whitespace_count+1) * '\t' + convert_literal(match.group(3))
  491. converted = convert_lineblock([match.group(3)])
  492. if len(converted)>0 and converted[0]:
  493. line_w += '\n' + (whitespace_count+1) * '\t' + converted[0]
  494. line_w += '\n' + whitespace_count * '\t'+f'<</{command}>>'
  495. else:
  496. nesting.append(command)
  497. #file.write(line_w)
  498. line_output = line_w
  499. pv("IS IF:",line_output)
  500. elif match := re.match(r"\s*(act)\s*(.+):(.*)",line,re.I):
  501. # Act-Command
  502. command = match.group(1).lower()
  503. line_w = f'<<{command} {convert_literal(match.group(2))}>>'
  504. if match.group(3):
  505. line_w += '\n' + (whitespace_count+1) * '\t'+convert_command(match.group(3))
  506. line_w += '\n' + whitespace_count * '\t'+f'<</{command}>>'
  507. else:
  508. nesting.append(command)
  509. #file.write(line_w)
  510. line_output = line_w
  511. pv("IS ACT:",line_output)
  512. elif match := re.match(r"\s*(elseif)\s+([^:]+):(.*)",line,re.I):
  513. # ElseIf
  514. command = match.group(1).lower()
  515. line_w = f'<<{command} {convert_condition(match.group(2))}>>'
  516. whitespace_count -= 1
  517. if match.group(3):
  518. #line_w += '\n' + (whitespace_count+1) * '\t'+convert_command(match.group(3))
  519. line_w += '\n' + whitespace_count * '\t'+f'<</if>>'
  520. #nesting.pop()
  521. #file.write(line_w)
  522. line_output = line_w
  523. pv("IS ELSEIF:",line_output)
  524. #elif match := re.match(r"^dynamic\s+'(.*)'$",line,re.I):
  525. # out = match.group(1).replace('<<',"'+").replace('>>',"+'")
  526. # line_output = f"<<dynamic {out}>>"
  527. elif match := re.match(r"^dynamic '\$?(.*?)\s*([\+\-]?=)\s*(.*?)\s*'$",line,re.I):
  528. left = match.group(1)
  529. right = match.group(3)
  530. operator = match.group(2)
  531. left = left.replace(r"[''",r"['").replace(r"'']",r"']")
  532. left = left.replace(r"['+",r"[").replace(r"+']",r"]")
  533. left = left.replace('<<',"'+").replace('>>',"+'")
  534. left = left.replace('$$',"$")
  535. right = right.replace(r"[''",r"['").replace(r"'']",r"']")
  536. right = right.replace(r"['+",r"[").replace(r"+']",r"]")
  537. right = right.replace('<<',"").replace('>>',"")
  538. right = right.replace('$$',"$")
  539. right = convert_literal(right)
  540. line_output = f'<<set {left} {operator} {right}>>'
  541. pv("IS DYNAMIC:",line_output)
  542. #elif match := re.match(r"^dynamic '\$?(.*?)\s*([\+\-]?=)\s*(.*?)\s*'$",line,re.I):
  543. elif match := re.match(r"^dynamic\s*\$([a-zA-Z]\w+)$",line,re.I):
  544. line_output = f'<<{match.group(1)}>>'
  545. elif match := re.match(r"""^([^\$])*<a\s+href\s*=\s*"exec:\s*(?:minut\s*\+=\s*(\d+)\s*&\s*)?gt(.*)?"\s*>(.*?)</a>.*$""",line,re.I):
  546. while link_match := re.search(r"""<a\s+href\s*=\s*"exec:\s*(?:minut\s*\+=\s*(\d+)\s*&\s*)?gt(.*)?"\s*>(.*?)</a>""",line,re.I):
  547. full_match = link_match.group(0)
  548. time = ""
  549. if link_match.group(1):
  550. time = f"<<set $minut += {link_match.group(1)}>>"
  551. goto = link_match.group(2)
  552. goto = goto.replace(","," ").replace(r"''",r"'")
  553. label = link_match.group(3)
  554. link = f"<<link '{label}'>>{time}<<gt {goto}>><</link>>"
  555. line = line.replace(full_match,link)
  556. line_output = line
  557. elif match := convert_command(line):
  558. line_output = match
  559. pv("IS COMMAND:",line_output)
  560. else:
  561. line_output = convert_literal(line)
  562. if len(line_output) >= 2 and line_output[0] == '\'' and line_output[-1] == '\'':
  563. line_output = f'<p>{line_output[1:-1]}</p>'
  564. pv("IS LITERAL:",line_output)
  565. whitespace = whitespace_count * '\t'
  566. output = f'{whitespace}{line_output}\n'
  567. if output.strip():
  568. #file.write(cleanUpTheMess(output))
  569. output = cleanUpTheMess(output)
  570. if "ERROR:" in output:
  571. global error_counter
  572. output = f'{whitespace}<!-- FAILED TO CONVERT\n{whitespace}\t{original}\n{whitespace}-----\n\t{output}\n{whitespace}-->\n{whitespace}<<warn "CONVERSION ERROR {(hashlib.md5(original.encode())).hexdigest()}">>\n'
  573. error_counter += 1
  574. outputs.append(output)
  575. for subpassId in subpassages:
  576. subpass = subpassages[subpassId]
  577. subpassageLines = convert_lineblock(subpass)
  578. outputs.append(f'\n:: {subpassId}\n')
  579. for subpassageLine in subpassageLines:
  580. outputs.append(subpassageLine)
  581. if len(functionlines) > 0:
  582. #outputs.append(f'::{location_identifier}_widgets[widget]\n')
  583. for functionline in functionlines:
  584. functionline = functionline.replace('$ARGS','_args').replace('$location_var[$here][','_args[')
  585. outputs.append(functionline)
  586. return outputs
  587. def convert_file(filename,skipIfNotExplicit=0,defaultsubfolder=False):
  588. skip = skipIfNotExplicit
  589. qsp_filename = filename+".qsrc"
  590. qsp_filepath = os.path.join(qsp_sources_path,qsp_filename)
  591. tw_filename = filename+".tw"
  592. tw_filepath = os.path.join(tw_sources_path,tw_filename)
  593. if defaultsubfolder:
  594. os.makedirs(os.path.join(tw_sources_path,defaultsubfolder),exist_ok =True)
  595. tw_filepath = os.path.join(tw_sources_path,defaultsubfolder,tw_filename)
  596. try:
  597. with open(qsp_filepath) as file:
  598. lines = [line.rstrip() for line in file]
  599. except:
  600. try:
  601. with open(qsp_filepath, encoding="utf-8") as file:
  602. lines = [line.rstrip() for line in file]
  603. except:
  604. return f"FAILED: {qsp_filename}"
  605. location_identifier = ''
  606. ignore_recusions = 0
  607. if match := re.match(r"^\s*!!\s*(FOLDER\s*:\s*\w+)?\s*(SKIP\s*:\s*-?\d)?\s*(IGNORERECURSIONS\s*:\s*-?\d)?\s*$",lines[0],re.I):
  608. if match.group(1):
  609. parts = match.group(1).split(':')
  610. new_path = os.path.join(tw_sources_path,parts[1].strip())
  611. os.makedirs(new_path,exist_ok =True)
  612. tw_filepath = os.path.join(new_path,tw_filename)
  613. if match.group(2):
  614. parts = match.group(2).split(':')
  615. arg = int(parts[1])
  616. if arg == 1:
  617. skip = 1
  618. elif arg == 0:
  619. skip = 0
  620. elif arg == -1:
  621. skip = -1
  622. if match.group(3):
  623. parts = match.group(3).split(':')
  624. arg = int(parts[1])
  625. if arg == 1:
  626. ignore_recusions = 1
  627. elif arg == 0:
  628. ignore_recusions = 0
  629. if skip == 1:
  630. return
  631. if skip == -1 and os.path.exists(tw_filepath):
  632. modification_time_delta = os.path.getmtime(qsp_filepath) - os.path.getmtime(tw_filepath)
  633. if modification_time_delta <= 0:
  634. return
  635. identifier_line = 0
  636. for line_num in range(0,len(lines)-1):
  637. line_raw = lines[line_num]
  638. line = line_raw.strip()
  639. match = re.match(r"#\s*(\S+)", line)
  640. if match:
  641. location_identifier = match.group(1)
  642. identifier_line = line_num
  643. break
  644. with open(tw_filepath, 'w') as file:
  645. #file.write(f'<!-- GENERATED: {datetime.datetime.now()} -->\n')
  646. file.write(f':: {location_identifier}\n')
  647. file.write(f"<<set $here = '{location_identifier}'>>\n<<set $ARGS = $location_var[$here]>>\n")
  648. if ignore_recusions == 1:
  649. file.write(f'<<set _ts to Math.floor(Date.now() / 10000)>>\n')
  650. file.write(f'<<setinit $gt_history[_ts][$here] = 0>>\n')
  651. #for line_num in range(identifier_line+1,len(lines)-1):
  652. outputs = convert_lineblock(lines[identifier_line+1:],location_identifier)
  653. for output in outputs:
  654. file.write(output)
  655. with open(tw_filepath, 'r') as file:
  656. data = file.read()
  657. with open(tw_filepath, 'w') as file:
  658. regex1 = r"""<<gs 'willpower' ([\s'\w]*)>>\s*<<if \$will_cost <= \$pc\.pcs_willpwr>>\s*<<act '([\w\s]*?)\s*\(will_cost Willpower\)'>>"""
  659. while match := re.search(regex1,data,re.I):
  660. blockStart = match.end()
  661. regex_close = r"""<<else>>\s*<<act `?'"""+match.group(2)+r""".*?<</act>>\s*<</if>>"""
  662. if close_match := re.search(regex_close,data,re.I):
  663. blockEnd = close_match.start()
  664. block = data[blockStart:blockEnd]
  665. # Remove the re-calculation of the willpower-cost
  666. newBlock = block
  667. newBlock = newBlock.replace("<<gs 'willpower' "+match.group(1)+">>",'')
  668. newBlock = re.sub(r"""<<gs 'willpower' 'pay' ([\s'\w]*)>>""","",newBlock)
  669. data = data.replace(block,newBlock)
  670. data = data.replace(close_match.group(0),"")
  671. arguments = match.group(1).replace(' ',',')
  672. data = data.replace(match.group(0),"<<act '"+match.group(2)+"' undefined `{willpower:["+arguments+"]}`>>")
  673. else:
  674. print("FAIL: "+match.group(0))
  675. break
  676. data = data.replace('<<act ','<<actCLA ')
  677. data = data.replace('<</act>>','<</actCLA>>')
  678. file.write(data)
  679. with open(tw_filepath, 'r') as file:
  680. data = file.read()
  681. regex_split = r"""::\s*SPLIT:(\w+)"""
  682. while match := re.search(regex_split,data,re.I):
  683. identifier = match.group(1)
  684. regex_split_end = r"""<!-- END: SPLIT:"""+identifier+r"""\s*-->"""
  685. if end_match := re.search(regex_split_end,data,re.I):
  686. sub_filepath = os.path.join(new_path,identifier+'.tw')
  687. subdata = data[match.start():end_match.end()]
  688. subdata = subdata.replace("SPLIT:"+identifier,identifier,1)
  689. with open(sub_filepath, 'w') as subfile:
  690. subfile.write(subdata)
  691. data = data[:match.start()]+data[end_match.end():]
  692. data = data.replace("SPLIT:"+identifier,identifier,1)
  693. with open(tw_filepath, 'w') as file:
  694. file.write(data)
  695. return tw_filepath
  696. FTCL = [r'ERROR: FAILED TO CONVERT LITERAL:\s*"""',r'"""']
  697. VAR = r"""\$?([a-zA-Z][a-zA-Z0-9-_\[\]'"]+]*)"""
  698. preparations = [
  699. [
  700. r"""\$week\[""",
  701. r"$week_name["
  702. ],
  703. [
  704. r"""pcs_pubecol\[""",
  705. r"pcs_pubecol_num["
  706. ],
  707. [
  708. r"""pcs_pubes\[""",
  709. r"pcs_pubes_num["
  710. ],
  711. [
  712. r"""^PLAY\s*.*""",
  713. r""
  714. ],
  715. [
  716. r"""^\s*pl\s+(.*)$""",
  717. r"\1"
  718. ]
  719. #[
  720. # r"""(</?(?:table|center|th|tr|td))([^>]*=[^>]*)(>)""",
  721. # r'\1\3',
  722. # re.I
  723. #]
  724. ]
  725. skill_names = [
  726. [r"\$pcs_heels","highHeels"],
  727. [r"\$pcs_stren","strength"],
  728. [r"\$pcs_agil","agility"],
  729. [r"\$pcs_intel","intelligence"],
  730. [r"\$pcs_react","reaction"],
  731. [r"\$pcs_sprt","spirit"],
  732. [r"\$pcs_chrsm","charisma"],
  733. [r"\$pcs_prcptn","perception"],
  734. [r"\$pcs_humint","people"],
  735. [r"\$pcs_persuas","persuasion"],
  736. [r"\$pcs_observ","observation"],
  737. [r"\$pcs_jab","jabs"],
  738. [r"\$pcs_punch","punch"],
  739. [r"\$pcs_kick","kick"],
  740. [r"\$pcs_def","defense"],
  741. [r"\$pcs_run","run"],
  742. [r"\$pcs_vball","volleyball"],
  743. [r"\$pcs_ftbll","football"],
  744. [r"\$pcs_wrstlng","wrestling"],
  745. [r"\$pcs_shoot","shoot"],
  746. [r"\$pcs_bushcraft","bushcraft"],
  747. [r"\$pcs_chess","chess"],
  748. [r"\$pcs_icesktng","iceskating"],
  749. [r"\$pcs_gaming","gaming"],
  750. [r"\$pcs_makupskl","makeup"],
  751. [r"\$pcs_danc","dance"],
  752. [r"\$pcs_dancero","eroticdance"],
  753. [r"\$pcs_dancpol","poledance"],
  754. [r"\$pcs_cheer","cheerleading"],
  755. [r"\$pcs_mdlng","modelling"],
  756. [r"\$pcs_vokal","singing"],
  757. [r"\$pcs_instrmusic","playInstrument"],
  758. [r"\$pcs_photoskl","photo"],
  759. [r"\$pcs_artskls","art"],
  760. [r"\$pcs_compskl","computer"],
  761. [r"\$pcs_comphckng","hacking"],
  762. [r"\$pcs_hndiwrk","handyWork"],
  763. [r"\$pcs_sewng","sewing"],
  764. [r"\$pcs_servng","serving"],
  765. [r"\$pcs_medcn","medicine"],
  766. ]
  767. replaces = [
  768. [
  769. r"ERROR: FAILED TO CONVERT CONDITION: func\(",
  770. r"func("
  771. ],
  772. [
  773. r"ERROR: FAILED TO CONVERT CONDITION: \$?([a-zA-Z])",
  774. r"$\1"
  775. ],
  776. [
  777. FTCL[0]+r"killvar\s*'"+VAR+r"'"+FTCL[1],
  778. r"<<set $\1 to undefined>>"
  779. ],
  780. [
  781. r"""<img\s+(<<\$set_imgh>>)?\s*src="([^<^\.]*)(<<\$?([a-zA-Z][a-zA-Z0-9-_\[\]'"\)\(),\s]+]*)>>)?(\.[^"]+)">""",
  782. r"<<image `'\2\3\5'`>>"
  783. ],
  784. [
  785. r"""'([\w\/]+)<<\s*rand\s*\(\s*(\-?\d+)\s*,\s*(\-?\d+)\s*\)\s*>>([^']*)'""",
  786. r"""'\1'+rand(\2,\3)+'\4'"""
  787. ],
  788. [
  789. r"""<<set \$?([a-zA-Z][a-zA-Z0-9-_'"]+]*\[.*)>>""",
  790. r"""<<setinit $\1>>"""
  791. ],
  792. [
  793. # <<set $gopnikbandQW += -1>> -> <<setn $gopnikbandQW += -1>>
  794. r"""<<set (\$[^>]*?)\s([+-]=)\s*(-?\d+)>>""",
  795. r"""<<setn \1 \2 \3>>""",
  796. 1
  797. ],
  798. [
  799. # asd
  800. r"""<<set (\$[^>]*?)\s(\+=)\s*(["'][^>]*?)>>""",
  801. r"""<<sets \1 \2 \3>>""",
  802. 1
  803. ],
  804. [
  805. r"""(\+)\s+=""",
  806. r"""\1="""
  807. ],
  808. [
  809. r"(I|you|You|he|He|she|She|it|It|we|We|they|They|can|Can|don|Don)''(m|re|s|ll|ve|t)",
  810. r"\1'\2"
  811. ],
  812. #[
  813. # r"^(.*"+FTCL[0]+r"(.*)"+FTCL[1]+r".*)$",
  814. # r"<!-- \1 -->\n<<warn 'FTCL: \1'>>"
  815. #],
  816. [
  817. r"=\s*\$(mid|MID)\s*\(",
  818. r"= mid("
  819. ],
  820. [
  821. r"(<<set\s*.*?\[)([a-zA-Z].*?)(\]\s*=.*>>)",
  822. r"\1$\2\3"
  823. ],
  824. [
  825. r"(<<act\s*'.*)(\$.*?\])(.*'>>)",
  826. r"\1'+\2+'\3"
  827. ],
  828. [
  829. r"\[([a-zA-Z]\w*)\]",
  830. r"[$\1]"
  831. ],
  832. [
  833. r"([\+\-])\s+=",
  834. r"\1="
  835. ],
  836. [
  837. r"<<setinit\s*(.*)\[\]\s*=\s*(.*)>>",
  838. r"""<<setinitpush "\1" \2>>"""
  839. ],
  840. [
  841. r"\s+min\(",
  842. r" Math.min("
  843. ],
  844. [
  845. r"\s+max\(",
  846. r" Math.max("
  847. ],
  848. [
  849. r"""<<set (.*) to null>>\s*,\s*(.*)(\s*)""",
  850. r"<<set \1[\2] to null>>\3"
  851. ]
  852. ,
  853. [
  854. r"""\$arrsize\(""",
  855. r"arrsize("
  856. ],
  857. [
  858. r"""<<set(?:init)?\s+\$?(?P<name>\w+)\[arrsize\('\$?(?P=name)'\)\]\s*=\s*(.*)\s*>>""",
  859. r"<<run $\1.push(\2)>>"
  860. ],
  861. [
  862. r"""<center><(?:h\d|b)><font color="maroon">(.*)</font></(?:h\d|b)></center>""",
  863. r"<h2>\1</h2>"
  864. ],
  865. [
  866. r"""(<<act '[^']*)'([^']*'>>)""",
  867. r"\1`\2"
  868. ],
  869. # NPC-Stuff Start
  870. [
  871. r"""\$npc_(\w*?)\[([^\]]*?)\]""",
  872. r"$npcs.get(\2,'\1')",
  873. 1
  874. ],
  875. # Fix for Sub-Arrays
  876. [
  877. r"""\$npcs\.get\((.*?),('\w*')\)(\[[^\]]*\]+?)\]""",
  878. r"$npcs.get(\1]\3,\2)",
  879. 1
  880. ],
  881. [
  882. r"""<<set(?:init)?\s+\$npcs\.get\((.*?)\)\s*=\s*(.*?)>>""",
  883. r"<<run $npcs.set(\1,\2)>>",
  884. 1
  885. ],
  886. [
  887. r"""<<set(?:init)?\s+\$npcs\.get\((.*?)\)\s*\+=\s*(.*?)>>""",
  888. r"<<run $npcs.inc(\1,\2)>>",
  889. 1
  890. ],
  891. [
  892. r"""<<set(?:init)?\s+\$npcs\.get\((.*?)\)\s*-=\s*(.*?)>>""",
  893. r"<<run $npcs.dec(\1,\2)>>",
  894. 1
  895. ],
  896. # NPC-Stuff END
  897. [
  898. r"""(\$\w+(?:\['\w+'\])?)\s*(==|>=?|<=?|!=)\s*(\-?\d+)""",
  899. r"""getvar("\1") \2 \3""",
  900. 1
  901. ],
  902. [
  903. #Example: $property_construction_status[$i] == 0 -> getvar("$property_construction_status["+$i+"]") == 0
  904. r"""(\$\w+)(?:\[(\$\w+)\])\s*(==|>=?|<=?|!=)\s*(\-?\d+)""",
  905. r"""getvar("\1["+\2+"]") \3 \4""",
  906. 1
  907. ],
  908. [
  909. r"""\*?\s*\$\s*cl[ar]\s*$""",
  910. r""
  911. ],
  912. [
  913. r"""<<gs 'clothing' 'wear'\s*(.*?)\s+(.*?)>>""",
  914. r"<<run $wardrobe.wear_clothes_legacy('clothes',\1,\2)>>"
  915. ],
  916. [
  917. r"""<<gs 'shoes' 'wear'\s+(.*?)\s+(.*?)>>""",
  918. r"<<run $wardrobe.wear('shoes',\1,\2)>>"
  919. ],
  920. [
  921. r"""<<gs\s+'shoes'\s+'wear'\s+'last_worn'\s*>>""",
  922. r"<<run $wardrobe.wear_last('shoes')>>"
  923. ],
  924. [
  925. r"""<<gs\s+'bras'\s+'wear'\s+(.+?)\s+(.+?)\s*>>""",
  926. r"<<run $wardrobe.wear('bra',\1,\2)>>"
  927. ],
  928. [
  929. r"""<<gs\s+'panties'\s+'wear'\s+(.+?)\s+(.+?)\s*>>""",
  930. r"<<run $wardrobe.wear('panties',\1,\2)>>"
  931. ],
  932. [
  933. r"""<<gs\s+'coats'\s+'wear'\s+(.+?)\s+(.+?)\s*>>""",
  934. r"<<run $wardrobe.wear('coat',\1,\2)>>"
  935. ],
  936. [
  937. r"""<<gs\s+'bras'\s+'wear'\s*>>""",
  938. r"<<run $wardrobe.wear_last('bra')>>"
  939. ],
  940. [
  941. r"""<<gs\s+'panties'\s+'wear'\s*>>""",
  942. r"<<run $wardrobe.wear_last('panties')>>"
  943. ],
  944. [
  945. r"""iif\(([^)]*?)\s*==?\s*'',""",
  946. r"iif(!\1,",
  947. 1
  948. ],
  949. # Rand in gs Fix
  950. [
  951. r"""<<g([st].*?)\srand\((.*?)\)(.*?)>>""",
  952. r"<<g\1 `rand(\2)`\3>>",
  953. 1
  954. ],
  955. # Pain
  956. [
  957. r"""(<<(?:else)?if\s+|and\s+|x?or\s+)(?:getvar\(")\$pain\[('\w+')\](?:"\))(.*?>>)""",
  958. r"\1$pc.pain(\2)\3",
  959. 1
  960. ],
  961. [
  962. r"""<<set(?:init)?\s+\$pain\[('\w+')\]\s*\+=\s*(.*?)>>""",
  963. r"<<run $pc.painInc(\1,\2)>>",
  964. 1
  965. ],
  966. [
  967. r"""<<set(?:init)?\s+\$pain\[('\w+')\]\s*-=\s*(.*?)>>""",
  968. r"<<run $pc.painDec(\1,\2)>>",
  969. 1
  970. ],
  971. [
  972. r"""<<set(?:init)?\s+\$pain\[('\w+')\]\s*=\s*(.*?)>>""",
  973. r"<<run $pc.painSet(\1,\2)>>",
  974. 1
  975. ],
  976. #Cum
  977. [
  978. r"""\$cumloc\[(\d+)\]""",
  979. r"$pc.cumAtLocation(\1)",
  980. 1
  981. ],
  982. # Inner Thought
  983. [
  984. r"""(?:'?\s*\+\s*)?\$OpenInnerThought\s*\+\s*'(.*?)'\s*\+\s*\$CloseInnerThought(?:\s*\+\s*'?)?""",
  985. r"""<span class="innerThought">\1</span>""",
  986. 1
  987. ],
  988. ]
  989. purge_messes=[
  990. r"""<<set(init)? \$npc_selfie\[""",
  991. r'''<<set(init)? \$npcGo\[''', # We need to replace this by another function,
  992. r'''<<set(init)? \$npcGoSchool\['''
  993. ]
  994. def cleanUpTheMess(output):
  995. for purge_mess in purge_messes:
  996. if match := re.search(purge_mess,output):
  997. return ''
  998. for skill_name in skill_names:
  999. oldSN = skill_name[0]
  1000. newSN = skill_name[1]
  1001. oldSN_without_prefix = oldSN.split('_')[1]
  1002. output = re.sub(r"<<set(?:init)?\s+"+oldSN+r"\s*=\s*(.*?)\s*>>",r"<<run $pc.skillSetLevel('"+newSN+r"',\1)>>",output)
  1003. output = re.sub(r"<<gs\s+'exp_gain'\s+('"+oldSN_without_prefix+r"')\s+`?(.*?)`?>>",r"<<run $pc.skillExperienceGain('"+newSN+r"',\2)>>",output)
  1004. output = re.sub(oldSN,'$pc.skillLevel("'+newSN+'")',output)
  1005. for replace in replaces:
  1006. if len(replace) > 2:
  1007. if replace[2] == 1:
  1008. while(re.search(replace[0],output)):
  1009. output = re.sub(replace[0],replace[1],output)
  1010. else:
  1011. output = re.sub(replace[0],replace[1],output)
  1012. if warnmatch := re.search(r"""<<warn '(.*)'>>""",output):
  1013. return output.replace(warnmatch.group(1),warnmatch.group(1).replace("'",'"'))
  1014. if link_match := re.findall(r"""(<a href="exec:([^"]+)">([^<]+)<\/a>)""",output):
  1015. for lmatch in link_match:
  1016. output = output.replace(lmatch[0],f"""<<link "{lmatch[2]}">>{convert_command(lmatch[1])}<</link>>""")
  1017. output = re.sub(r"""\$result""","$result",output,0,re.I)
  1018. while image_match := re.match(r"""<img\s+(<<\$set_imgh>>)?\s*src="([^<^\.]*)(<<\$?([a-zA-Z][a-zA-Z0-9-_\[\]'"]+]*)>>)?\.[^"]+">""",output):
  1019. if len(image_match.group(3)) == 0:
  1020. break
  1021. output = output.replace(image_match.group(3),f'"+${image_match.group(4)}+"')
  1022. while match := re.search(r"""<<set(?:init)?[^=]+=\s*'([a-zA-Z0-9\.\?!<>"\s,`\-\(\)]+)('([a-zA-Z0-9\.\?!<>"\s,`\-\(\)]+))+'>>""",output):
  1023. output = output.replace(match.group(2),f"`{match.group(3)}")
  1024. # NPCs: add print to all get-calls which are not inside a macro
  1025. if(not output.strip().startswith('<<')):
  1026. output = re.sub(r"(?<!=)(\$npcs\.get\(.*?\))",r"<<=\1>>",output)
  1027. # Arousal
  1028. while match := re.search(r"<<gs 'arousal' '(\w+)' (.*?)(\s.*?)?>>",output):
  1029. if match.group(3):
  1030. arguments = "["+match.group(3).replace("' '","','").strip()+"]"
  1031. else:
  1032. arguments = ''
  1033. output = output.replace(match.group(0),"<<arouse '"+match.group(1)+"' "+match.group(2)+" "+arguments+">>")
  1034. for variable_replacement in variables.variable_replacements:
  1035. if len(variable_replacement) > 2:
  1036. if variable_replacement[2] == 1:
  1037. output = re.sub(variable_replacement[0],variable_replacement[1],output)
  1038. else:
  1039. output = output.replace(variable_replacement[0],variable_replacement[1])
  1040. else:
  1041. output = output.replace(variable_replacement[0],variable_replacement[1])
  1042. for get_set_variable in variables.get_set_variables:
  1043. output = re.sub(rf"<<set(?:init)?\s+{get_set_variable[0]}\s*=\s*(.*?)\s*>>",rf"<<run {get_set_variable[2]}>>",output)
  1044. if(len(get_set_variable) == 5):
  1045. output = re.sub(rf"<<set(?:init)?\s+{get_set_variable[0]}\s*\+=\s*(.*?)\s*>>",rf"<<run {get_set_variable[3]}>>",output)
  1046. output = re.sub(rf"<<set(?:init)?\s+{get_set_variable[0]}\s*\-=\s*(.*?)\s*>>",rf"<<run {get_set_variable[4]}>>",output)
  1047. #output = re.sub(rf"<<set(?:init)?\s+\${get_set_variable[0]}\s*-=\s*(.*?)\s*>>",rf"<<run $inventory.dec('{inventory_variable[1]}',\1)>>",output)
  1048. #output = re.sub(rf"<<set(?:init)?\s+\${get_set_variable[0]}\s*\+=\s*(.*?)\s*>>",rf"<<run $inventory.inc('{inventory_variable[1]}',\1)>>",output)
  1049. output = re.sub(rf"<<{get_set_variable[0]}>>",get_set_variable[1],output)
  1050. output = re.sub(rf"""getvar\("{get_set_variable[0]}"\)""",get_set_variable[1],output)
  1051. output = re.sub(rf"""{get_set_variable[0]}(?P<stuffToTheRight>[^\w])""",rf"""{get_set_variable[1]}\g<stuffToTheRight>""",output)
  1052. for pgsvr in variables.post_get_set_variables_replacements:
  1053. output = output.replace(pgsvr[0],pgsvr[1])
  1054. output = output.replace("$location_var[$here][0] == ''","!$location_var[$here][0]")
  1055. return output
  1056. test_line = ''
  1057. #test_line = """gs 'npc_relationship', 'socialgroup_setting', 0, 0, -10, 10, -10, -10"""
  1058. if len(test_line) > 0:
  1059. verbose = True
  1060. print(test_line)
  1061. result = convert_lineblock([test_line])
  1062. if len(result) > 0:
  1063. print(result[0])
  1064. else:
  1065. print("EMPTY RESULT")
  1066. exit()
  1067. qsp_sources_path = "locations"
  1068. tw_sources_path = os.path.join("sugarcube","src","autogenerated")
  1069. output_files = []
  1070. os.makedirs(tw_sources_path, exist_ok=True)
  1071. #for replace in replaces:
  1072. # print(replace[0])
  1073. restrictfiles = []
  1074. #restrictfiles = ['intro_city_select']
  1075. files = os.listdir(qsp_sources_path)
  1076. file_counter = 0
  1077. last_displayed_percentage_time = time.time()
  1078. for file in files:
  1079. if len(restrictfiles) == 0 or (os.path.splitext(file)[0] in restrictfiles):
  1080. if file.endswith(".qsrc"):
  1081. filesToDo.append(os.path.splitext(file)[0])
  1082. #output_files.append(convert_file(os.path.splitext(file)[0],skipMode,'unsorted'))
  1083. with ThreadPoolExecutor(32) as executor:
  1084. # submit all tasks
  1085. futures = [executor.submit(convert_file, p, skipMode, 'unsorted') for p in filesToDo]
  1086. # process all results
  1087. for future in as_completed(futures):
  1088. # open the file and load the data
  1089. completedPath = future.result()
  1090. # report progress
  1091. #print(f'.loaded {filepath}')
  1092. file_counter += 1
  1093. if(last_displayed_percentage_time + 5 < time.time()):
  1094. print(str(round(file_counter/len(files)*100, 2))+"%")
  1095. last_displayed_percentage_time = time.time()
  1096. #for output_file in output_files:
  1097. # for line in fileinput.input(output_file, inplace=True):
  1098. #
  1099. # for function_name_conversion in function_name_conversions:
  1100. #
  1101. #
  1102. # if fileinput.filelineno() == 10:
  1103. # print(('10'+line), end='')
  1104. # break