Guest User

fmg_map_to_json.py

a guest
Jun 21st, 2019
571
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.33 KB | None | 0 0
  1. """
  2. Parses a *.map file from Azgaar's Fantasy-Map-Generator into a *.json String.
  3.  
  4. For the map generator see:
  5.  
  6. https://github.com/Azgaar/Fantasy-Map-Generator/
  7.  
  8. Most of the code in here is copied/translated from
  9.  
  10. https://github.com/Azgaar/Fantasy-Map-Generator/blob/master/modules/save-and-load.js
  11.  
  12. Doesn't copy all generated data, only:
  13.  
  14.    -mapVersion
  15.    -archive
  16.    -biomesData,
  17.    -mapCoordinates,
  18.    -notes,
  19.    -seed,
  20.    -biomes,
  21.    -grid,
  22.    -pack,    
  23.    
  24. Usage example:
  25.  
  26.    python3 -i fmg_map_to_json.py ~/home/user/mapfile.map
  27.    
  28. """
  29. import sys
  30. import os
  31. import json
  32. import re
  33. import math
  34. import itertools
  35.  
  36. path = sys.argv[1]
  37.  
  38. assert path.endswith(".map")
  39.  
  40. byte_string = b''
  41.  
  42. file = open(path, "rb")
  43.  
  44. for line in file:
  45.     byte_string += line
  46.  
  47. version = '0.9b' #hardcoded. This code is only guaranteed to work for this version.
  48.    
  49. data = byte_string.split(b"\r\n")
  50. mapVersion = data[0].split(b'|')[0].decode() or data[0].decode();
  51. print("Loading Fantasy-Map-Generator Mapfile-Version {}".format(mapVersion))
  52. archive = "<a href='https://github.com/Azgaar/Fantasy-Map-Generator/wiki/Changelog' target='_blank'>archived version</a>";
  53.  
  54. parsed = float(re.sub("[a-z]*", "", mapVersion.lower())) #Not quite the same as js parseFloat, But should suffice for conventional versioning.
  55.  
  56. message = "";
  57. load = False
  58.  
  59. if math.isnan(parsed) or len(data) < 26 or not data[5]:
  60.     message = 'The file you are trying to load is outdated or not a valid .map file. <br>Please try to open it using an {archive}';
  61.     print("Alert! " + message);
  62.     print ("Version conflict!")
  63. elif(parsed < 0.7):
  64.     message = 'The map version you are trying to load ({mapVersion}) is too old and cannot be updated to the current version.<br>Please keep using an {archive}';
  65.     print("Alert! " + message);
  66.     print ("Version conflict!")
  67. else:
  68.   load = True;
  69.   #message =  'The map version ({}) does not match the Generator version ({}). The map will be auto-updated. <br>In case of issues please keep using an {} of the Generator'.format(mapVersion, version, archive);
  70.  
  71.  
  72.  
  73. """
  74. Initialize biomesData as in 'applyDefaultBiomesSystem()' in 'main.js'
  75. """
  76. biomesData = {}
  77. biomesData["name"] = ["Marine","Hot desert","Cold desert","Savanna","Grassland","Tropical seasonal forest","Temperate deciduous forest","Tropical rain forest","Temperate rain forest","Taiga","Tundra","Glacier"];
  78. biomesData["color"] = ["#53679f","#fbe79f","#b5b887","#d2d082","#c8d68f","#b6d95d","#29bc56","#7dcb35","#45b348","#4b6b32","#96784b","#d5e7eb"];
  79.  
  80. biomesData["i"] = list(range(0, len(biomesData["name"])));
  81. #biomesData["habitability"] = [0,2,5,15,25,50,100,80,90,10,2,0];
  82. #iconsDensity = [0,3,2,120,120,120,120,150,150,100,5,0];
  83. #//const icons = [{},{dune:1},{dune:1},{acacia:1, grass:9},{grass:1},{acacia:1, palm:1},{deciduous:1},{acacia:7, palm:2, deciduous:1},{deciduous:7, swamp:3},{conifer:1},{grass:1},{}];
  84. #const icons = [{},{dune:3, cactus:6, deadTree:1},{dune:9, deadTree:1},{acacia:1, grass:9},{grass:1},{acacia:8, palm:1},{deciduous:1},{acacia:5, palm:3, deciduous:1, swamp:2},{deciduous:5, swamp:3},{conifer:1},{grass:1},{}];
  85. #const cost = new Uint8Array([10,200,150,60,50,70,70,80,90,80,100,255]); // biome movement cost
  86. biomesData["biomesMartix"] = [
  87.   [1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2],
  88.   [3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,9,9,9,9,9,10,10],
  89.   [5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,9,9,9,9,9,10,10,10],
  90.   [5,6,6,6,6,6,6,8,8,8,8,8,8,8,8,8,8,9,9,9,9,9,9,10,10,10],
  91.   [7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,9,9,9,9,9,9,10,10,10]
  92.   ]
  93.  
  94. """ Parse params """
  95. params = data[0].split(b"|");
  96.  
  97. if (params[3]):
  98.     seed = params[3].decode();
  99. """
  100. if (params[4]):
  101.    graphWidth = +params[4]; #Not implemented
  102. if (params[5]):
  103.    graphHeight = +params[5]; #Not implemented
  104. """
  105.  
  106. """ Parse config """
  107. if (data[2]):
  108.     mapCoordinates = json.loads(data[2]);
  109. if (data[4]):
  110.     notes = json.loads(data[4]);
  111.    
  112. """ Parse biomes """
  113. biomes = [b.decode() for b in data[3].split(b"|")]
  114.  
  115. """ Parse name """
  116. name = biomes[2].split(",")
  117.  
  118. if (len(name) != len(biomesData["name"])):
  119.     print("Biomes data is not correct and will not be loaded");
  120.  
  121. biomesData["color"] = biomes[0].split(",");
  122. #biomesData.habitability = biomes[1].split(",").map(h => +h);
  123. biomesData["name"] = name;
  124.  
  125. """
  126. Parse grid data
  127. Keep the actual data as string (no UintArray)
  128. """
  129. grid = json.loads(data[6])
  130. grid["cells"] = {}
  131. #calculateVoronoi(grid, grid.points) #Not implemented
  132. grid["cells"]["h"] = [b.decode() for b in (data[7].split(b","))]
  133. grid["cells"]["prec"] = [b.decode() for b in (data[8].split(b","))];
  134. grid["cells"]["f"] = [b.decode() for b in (data[9].split(b","))];
  135. grid["cells"]["t"] = [b.decode() for b in (data[10].split(b","))];
  136. grid["cells"]["temp"] = [b.decode() for b in (data[11].split(b","))];
  137.  
  138. """
  139. Parse Pack data
  140. """
  141. pack = {};
  142. #reGraph(); #Not implemented
  143. #reMarkFeatures(); #Not implemented
  144. pack["features"] = json.loads(data[12]);
  145. pack["cultures"] = json.loads(data[13]);
  146. pack["states"] = json.loads(data[14]);
  147. pack["burgs"] = json.loads(data[15]);
  148.  
  149. pack["cells"] = {}
  150.  
  151. pack["cells"]["biome"] = [b.decode() for b in(data[16].split(b","))]
  152. pack["cells"]["burg"] = [b.decode() for b in(data[17].split(b","))]
  153. pack["cells"]["conf"] = [b.decode() for b in(data[18].split(b","))]
  154. pack["cells"]["culture"] = [b.decode() for b in(data[19].split(b","))]
  155. pack["cells"]["fl"] = [b.decode() for b in(data[20].split(b","))]
  156. pack["cells"]["pop"] = [b.decode() for b in(data[21].split(b","))]
  157. pack["cells"]["r"] = [b.decode() for b in(data[22].split(b","))]
  158. pack["cells"]["road"] = [b.decode() for b in(data[23].split(b","))]
  159. pack["cells"]["s"] = [b.decode() for b in(data[24].split(b","))]
  160. pack["cells"]["state"] = [b.decode() for b in(data[25].split(b","))]
  161.  
  162. """
  163. Output data as .json to current directory.
  164. """
  165. parsed_data = {
  166.     "mapVersion" : mapVersion,
  167.     "archive" : archive,
  168.     "biomesData" : biomesData,
  169.     "mapCoordinates" : mapCoordinates,
  170.     "notes" : notes,
  171.     "seed" : seed,
  172.     "biomes" : biomes,
  173.     "grid" : grid,
  174.     "pack" : pack,    
  175.     }
  176.  
  177. """
  178. Save parsed_data at *.map location as json.
  179. """
  180.  
  181. out_path = os.path.splitext(path)[0] + ".json"
  182. with open(out_path, "w") as outfile:
  183.     json = json.dump(parsed_data, outfile, indent=4)
  184.     print("Successfully saved data to {}".format(out_path))
  185.     outfile.close()
Advertisement
Add Comment
Please, Sign In to add comment