mapGeneration.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203
  1. import numpy as np
  2. import yaml
  3. import base64
  4. import struct
  5. import random
  6. import sys
  7. from pyfastnoiselite.pyfastnoiselite import (
  8. FastNoiseLite,
  9. NoiseType,
  10. FractalType,
  11. CellularReturnType,
  12. CellularDistanceFunction,
  13. DomainWarpType,
  14. )
  15. import time
  16. import os
  17. if len(sys.argv) == 1:
  18. mapWidth = 300
  19. mapHeight = 300
  20. print(f"No custom mapsize specified, using defaults: {mapWidth}w x {mapHeight}h")
  21. else:
  22. mapWidth = int(sys.argv[1])
  23. mapHeight = int(sys.argv[2])
  24. print(f"Using specified mapsize: {mapWidth}w x {mapHeight}h")
  25. # -----------------------------------------------------------------------------
  26. # Tilemap
  27. # -----------------------------------------------------------------------------
  28. TILEMAP = {
  29. 0: "Space",
  30. 1: "FloorDirt",
  31. 2: "FloorPlanetGrass",
  32. 3: "FloorGrassDark",
  33. 4: "FloorSand",
  34. 5: "FloorDirtRock",
  35. }
  36. TILEMAP_REVERSE = {v: k for k, v in TILEMAP.items()}
  37. # -----------------------------------------------------------------------------
  38. # Helper Functions
  39. # -----------------------------------------------------------------------------
  40. def round_to_chunk(number, chunk):
  41. """Rounds a number to the inferior multiplier of a chunk."""
  42. return number - (number % chunk)
  43. def add_border(tile_map, border_value):
  44. """Adds a border to tile_map with the specified value."""
  45. bordered = np.pad(
  46. tile_map, pad_width=1, mode="constant", constant_values=border_value
  47. )
  48. return bordered.astype(np.int32)
  49. def encode_tiles(tile_map):
  50. """Codifies the tiles in base64 for the YAML."""
  51. tile_bytes = bytearray()
  52. for y in range(tile_map.shape[0]): # u
  53. for x in range(tile_map.shape[1]):
  54. tile_id = tile_map[y, x]
  55. flags = 0
  56. variant = 0
  57. tile_bytes.extend(struct.pack("<I", tile_id)) # 4 bytes tile_id
  58. tile_bytes.append(flags) # 1 byte flag
  59. tile_bytes.append(variant) # 1 byte variant
  60. return base64.b64encode(tile_bytes).decode("utf-8")
  61. # -----------------------------------------------------------------------------
  62. # Generating a TileMap with multiple layers
  63. # -----------------------------------------------------------------------------
  64. def generate_tile_map(width, height, biome_tile_layers, seed_base=None):
  65. """Generates the tile_map based on the layers defined in biome_tile_layers."""
  66. tile_map = np.full((height, width), TILEMAP_REVERSE["FloorDirt"], dtype=np.int32)
  67. # Orders the layers by priority (largest to smallest)
  68. sorted_layers = sorted(
  69. biome_tile_layers, key=lambda layer: layer.get("priority", 1)
  70. )
  71. for layer in sorted_layers:
  72. noise = FastNoiseLite()
  73. noise.noise_type = layer["noise_type"]
  74. noise.fractal_octaves = layer["octaves"]
  75. noise.frequency = layer["frequency"]
  76. noise.fractal_type = layer["fractal_type"]
  77. if "cellular_distance_function" in layer:
  78. noise.cellular_distance_function = layer["cellular_distance_function"]
  79. if "cellular_return_type" in layer:
  80. noise.cellular_return_type = layer["cellular_return_type"]
  81. if "cellular_jitter" in layer:
  82. noise.cellular_jitter = layer["cellular_jitter"]
  83. if "fractal_lacunarity" in layer:
  84. noise.fractal_lacunarity = layer["fractal_lacunarity"]
  85. if seed_base is not None:
  86. seed_key = layer.get("seed_key", layer["tile_type"])
  87. noise.seed = (seed_base + hash(seed_key)) % (2**31)
  88. # Modulation config, if present
  89. mod_noise = None
  90. if "modulation" in layer:
  91. mod_config = layer["modulation"]
  92. mod_noise = FastNoiseLite()
  93. mod_noise.noise_type = mod_config.get(
  94. "noise_type", NoiseType.NoiseType_OpenSimplex2
  95. )
  96. if "cellular_distance_function" in mod_config:
  97. mod_noise.cellular_distance_function = mod_config[
  98. "cellular_distance_function"
  99. ]
  100. if "cellular_return_type" in mod_config:
  101. mod_noise.cellular_return_type = mod_config["cellular_return_type"]
  102. if "cellular_jitter" in mod_config:
  103. mod_noise.cellular_jitter = mod_config["cellular_jitter"]
  104. if "fractal_lacunarity" in mod_config:
  105. mod_noise.fractal_lacunarity = mod_config["fractal_lacunarity"]
  106. mod_noise.frequency = mod_config.get("frequency", 0.010)
  107. mod_noise.seed = (seed_base + hash(seed_key + "_mod")) % (2**31)
  108. threshold_min = mod_config.get("threshold_min", 0.4)
  109. threshold_max = mod_config.get("threshold_max", 0.6)
  110. count = 0
  111. dont_overwrite = [TILEMAP_REVERSE[t] for t in layer.get("dontOverwrite", [])]
  112. for y in range(height):
  113. for x in range(width):
  114. noise_value = noise.get_noise(x, y)
  115. noise_value = (noise_value + 1) / 2 # Normalise into [0, 1]
  116. place_tile = False
  117. if mod_noise:
  118. mod_value = mod_noise.get_noise(x, y)
  119. mod_value = (mod_value + 1) / 2
  120. if noise_value > layer["threshold"]:
  121. if mod_value > threshold_max:
  122. place_tile = True
  123. elif mod_value > threshold_min:
  124. probability = (mod_value - threshold_min) / (
  125. threshold_max - threshold_min
  126. )
  127. place_tile = random.random() < probability
  128. else:
  129. if noise_value > layer["threshold"]:
  130. place_tile = True
  131. if place_tile:
  132. current_tile = tile_map[y, x]
  133. if current_tile not in dont_overwrite:
  134. if (
  135. layer.get("overwrite", True)
  136. or current_tile == TILEMAP_REVERSE["Space"]
  137. ):
  138. tile_map[y, x] = TILEMAP_REVERSE[layer["tile_type"]]
  139. count += 1
  140. print(f"Layer {layer['tile_type']}: {count} tiles placed")
  141. return tile_map
  142. # -----------------------------------------------------------------------------
  143. # Entity generation
  144. # -----------------------------------------------------------------------------
  145. global_uid = 3
  146. def next_uid():
  147. """Generates an unique UID for each entity."""
  148. global global_uid
  149. uid = global_uid
  150. global_uid += 1
  151. return uid
  152. def generate_dynamic_entities(tile_map, biome_entity_layers, seed_base=None):
  153. """Generates dynamic entities based on the entity layers, respecting priorities."""
  154. groups = {}
  155. entity_count = {} # Count entities by proto
  156. h, w = tile_map.shape
  157. occupied_positions = set() # Set to trace occupied positions
  158. # Order layers by priority. Highest first
  159. sorted_layers = sorted(
  160. biome_entity_layers, key=lambda layer: layer.get("priority", 0), reverse=True
  161. )
  162. for layer in sorted_layers:
  163. # Get entity_protos list
  164. entity_protos = layer["entity_protos"]
  165. if isinstance(entity_protos, str): # If its a string, turns it into a list
  166. entity_protos = [entity_protos]
  167. # Set layer noise
  168. noise = FastNoiseLite()
  169. noise.noise_type = layer["noise_type"]
  170. noise.fractal_octaves = layer["octaves"]
  171. noise.frequency = layer["frequency"]
  172. noise.fractal_type = layer["fractal_type"]
  173. if "cellular_distance_function" in layer:
  174. noise.cellular_distance_function = layer["cellular_distance_function"]
  175. if "cellular_return_type" in layer:
  176. noise.cellular_return_type = layer["cellular_return_type"]
  177. if "cellular_jitter" in layer:
  178. noise.cellular_jitter = layer["cellular_jitter"]
  179. if "fractal_lacunarity" in layer:
  180. noise.fractal_lacunarity = layer["fractal_lacunarity"]
  181. if seed_base is not None:
  182. # Uses "seed_key" if available, if not uses a hash based on entity_protos
  183. seed_key = layer.get("seed_key", tuple(entity_protos))
  184. noise.seed = (seed_base + hash(seed_key)) % (2**31)
  185. for y in range(h):
  186. for x in range(w):
  187. if x == 0 or x == w - 1 or y == 0 or y == h - 1:
  188. continue
  189. if (x, y) in occupied_positions:
  190. continue
  191. tile_val = tile_map[y, x]
  192. noise_value = noise.get_noise(x, y)
  193. noise_value = (noise_value + 1) / 2 # Normalise into [0, 1]
  194. if noise_value > layer["threshold"] and layer["tile_condition"](
  195. tile_val
  196. ):
  197. # Chooses randomly a proto
  198. proto = random.choice(entity_protos)
  199. if proto not in groups:
  200. groups[proto] = []
  201. groups[proto].append(
  202. {
  203. "uid": next_uid(),
  204. "components": [
  205. {"type": "Transform", "parent": 2, "pos": f"{x},{y}"}
  206. ],
  207. }
  208. )
  209. occupied_positions.add((x, y))
  210. # Counts entities by proto
  211. entity_count[proto] = entity_count.get(proto, 0) + 1
  212. # Surrounding undestructible walls
  213. groups["WallRockIndestructible"] = []
  214. for y in range(h):
  215. for x in range(w):
  216. if x == 0 or x == w - 1 or y == 0 or y == h - 1:
  217. groups["WallRockIndestructible"].append(
  218. {
  219. "uid": next_uid(),
  220. "components": [
  221. {"type": "Transform", "parent": 2, "pos": f"{x},{y}"}
  222. ],
  223. }
  224. )
  225. # Count undestructible walls
  226. entity_count["WallRockIndestructible"] = (
  227. entity_count.get("WallRockIndestructible", 0) + 1
  228. )
  229. dynamic_groups = [
  230. {"proto": proto, "entities": ents} for proto, ents in groups.items()
  231. ]
  232. # Print generated protos
  233. for proto, count in entity_count.items():
  234. print(f"Generated {count} amount of {proto}")
  235. return dynamic_groups
  236. def generate_decals(tile_map, biome_decal_layers, seed_base=None, chunk_size=16):
  237. """Generate decals using biome_decal_layers and log the count of each decal type."""
  238. decals_by_id = {}
  239. h, w = tile_map.shape
  240. occupied_tiles = set()
  241. decal_count = {}
  242. for layer in biome_decal_layers:
  243. noise = FastNoiseLite()
  244. noise.noise_type = layer["noise_type"]
  245. noise.fractal_octaves = layer["octaves"]
  246. noise.frequency = layer["frequency"]
  247. noise.fractal_type = layer["fractal_type"]
  248. if seed_base is not None:
  249. seed_key = layer.get(
  250. "seed_key",
  251. (
  252. tuple(layer["decal_id"])
  253. if isinstance(layer["decal_id"], list)
  254. else layer["decal_id"]
  255. ),
  256. )
  257. noise.seed = (seed_base + hash(seed_key)) % (2**31)
  258. decal_ids = (
  259. layer["decal_id"]
  260. if isinstance(layer["decal_id"], list)
  261. else [layer["decal_id"]]
  262. )
  263. for y in range(h):
  264. for x in range(w):
  265. if x == 0 or x == w - 1 or y == 0 or y == h - 1:
  266. continue
  267. if (x, y) in occupied_tiles:
  268. continue
  269. tile_val = tile_map[y, x]
  270. noise_value = noise.get_noise(x, y)
  271. noise_value = (noise_value + 1) / 2
  272. if noise_value > layer["threshold"] and layer["tile_condition"](
  273. tile_val
  274. ):
  275. chosen_decal_id = random.choice(decal_ids)
  276. if chosen_decal_id not in decals_by_id:
  277. decals_by_id[chosen_decal_id] = []
  278. # Small random offset for decals
  279. offset_x = (
  280. noise.get_noise(x + 1000, y + 1000) + 1
  281. ) / 4 - 0.25 # Between -0.25 and 0.25
  282. offset_y = (
  283. noise.get_noise(x + 2000, y + 2000) + 1
  284. ) / 4 - 0.25 # Between -0.25 and 0.25
  285. pos_x = x + offset_x
  286. pos_y = y + offset_y
  287. pos_str = f"{pos_x:.7f},{pos_y:.7f}"
  288. decals_by_id[chosen_decal_id].append(
  289. {"color": layer.get("color", "#FFFFFFFF"), "position": pos_str}
  290. )
  291. occupied_tiles.add((x, y))
  292. decal_count[chosen_decal_id] = (
  293. decal_count.get(chosen_decal_id, 0) + 1
  294. )
  295. return decals_by_id
  296. # Defines uniqueMixes for the atmosphere
  297. unique_mixes = [
  298. {
  299. "volume": 2500,
  300. "immutable": True,
  301. "temperature": 278.15,
  302. "moles": [21.82478, 82.10312, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  303. },
  304. {
  305. "volume": 2500,
  306. "temperature": 278.15,
  307. "moles": [21.824879, 82.10312, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  308. },
  309. ]
  310. def generate_atmosphere_tiles(width, height, chunk_size):
  311. """Generates the atmos tiles based on the map size."""
  312. max_x = (width + chunk_size - 1) // chunk_size - 1
  313. max_y = (height + chunk_size - 1) // chunk_size - 1
  314. tiles = {}
  315. for y in range(-1, max_y + 1):
  316. for x in range(-1, max_x + 1):
  317. if x == -1 or x == max_x or y == -1 or y == max_y:
  318. tiles[f"{x},{y}"] = {0: 65535}
  319. else:
  320. tiles[f"{x},{y}"] = {1: 65535}
  321. return tiles
  322. def generate_main_entities(tile_map, chunk_size=16, decals_by_id=None):
  323. """Generates entities, decals and atmos."""
  324. if decals_by_id is None:
  325. decals_by_id = {}
  326. h, w = tile_map.shape
  327. chunks = {}
  328. for cy in range(0, h, chunk_size):
  329. for cx in range(0, w, chunk_size):
  330. chunk_key = f"{cx//chunk_size},{cy//chunk_size}"
  331. chunk_tiles = tile_map[cy : cy + chunk_size, cx : cx + chunk_size]
  332. if chunk_tiles.shape[0] < chunk_size or chunk_tiles.shape[1] < chunk_size:
  333. full_chunk = np.zeros((chunk_size, chunk_size), dtype=np.int32)
  334. full_chunk[: chunk_tiles.shape[0], : chunk_tiles.shape[1]] = chunk_tiles
  335. chunk_tiles = full_chunk
  336. chunks[chunk_key] = {
  337. "ind": f"{cx//chunk_size},{cy//chunk_size}",
  338. "tiles": encode_tiles(chunk_tiles),
  339. "version": 6,
  340. }
  341. atmosphere_chunk_size = 4
  342. atmosphere_tiles = generate_atmosphere_tiles(w, h, atmosphere_chunk_size)
  343. # Decals generation
  344. decal_nodes = []
  345. global_index = 0
  346. for decal_id, decals in decals_by_id.items():
  347. if decals:
  348. node_decals = {}
  349. for decal in decals:
  350. node_decals[str(global_index)] = decal["position"]
  351. global_index += 1
  352. node = {
  353. "node": {"color": decals[0]["color"], "id": decal_id},
  354. "decals": node_decals,
  355. }
  356. decal_nodes.append(node)
  357. print(f"Total decal nodes generated: {len(decal_nodes)}")
  358. print(f"Total decals: {global_index}")
  359. main = {
  360. "proto": "",
  361. "entities": [
  362. {
  363. "uid": 1,
  364. "components": [
  365. {"type": "MetaData", "name": "Map Entity"},
  366. {"type": "Transform"},
  367. {"type": "LightCycle"},
  368. {"type": "MapLight", "ambientLightColor": "#D8B059FF"},
  369. {"type": "Map", "mapPaused": True},
  370. {"type": "PhysicsMap"},
  371. {"type": "GridTree"},
  372. {"type": "MovedGrids"},
  373. {"type": "Broadphase"},
  374. {"type": "OccluderTree"},
  375. ],
  376. },
  377. {
  378. "uid": 2,
  379. "components": [
  380. {"type": "MetaData", "name": "grid"},
  381. {"type": "Transform", "parent": 1, "pos": "0,0"},
  382. {"type": "MapGrid", "chunks": chunks},
  383. {"type": "Broadphase"},
  384. {
  385. "type": "Physics",
  386. "angularDamping": 0.05,
  387. "bodyStatus": "InAir",
  388. "bodyType": "Dynamic",
  389. "fixedRotation": True,
  390. "linearDamping": 0.05,
  391. },
  392. {"type": "Fixtures", "fixtures": {}},
  393. {"type": "OccluderTree"},
  394. {"type": "SpreaderGrid"},
  395. {"type": "Shuttle"},
  396. {"type": "SunShadow"},
  397. {"type": "SunShadowCycle"},
  398. {"type": "GridPathfinding"},
  399. {
  400. "type": "Gravity",
  401. "gravityShakeSound": {
  402. "!type:SoundPathSpecifier": {
  403. "path": "/Audio/Effects/alert.ogg"
  404. }
  405. },
  406. "inherent": True,
  407. "enabled": True,
  408. },
  409. {"type": "BecomesStation", "id": "Nomads"},
  410. {"type": "Weather"},
  411. {
  412. "type": "WeatherNomads",
  413. "enabledWeathers": [
  414. "Rain",
  415. "Storm",
  416. "SnowfallLight",
  417. "SnowfallMedium",
  418. "SnowfallHeavy",
  419. ],
  420. "minSeasonMinutes": 10,
  421. "maxSeasonMinutes": 30,
  422. },
  423. {
  424. "type": "DecalGrid",
  425. "chunkCollection": {"version": 2, "nodes": decal_nodes},
  426. },
  427. {
  428. "type": "GridAtmosphere",
  429. "version": 2,
  430. "data": {
  431. "tiles": atmosphere_tiles,
  432. "uniqueMixes": unique_mixes,
  433. "chunkSize": atmosphere_chunk_size,
  434. },
  435. },
  436. {"type": "GasTileOverlay"},
  437. {"type": "RadiationGridResistance"},
  438. ],
  439. },
  440. ],
  441. }
  442. return main
  443. def generate_all_entities(tile_map, chunk_size=16, biome_layers=None, seed_base=None):
  444. """Combines tiles, entities and decals."""
  445. entities = []
  446. if biome_layers is None:
  447. biome_layers = []
  448. biome_tile_layers = [
  449. layer for layer in biome_layers if layer["type"] == "BiomeTileLayer"
  450. ]
  451. biome_entity_layers = [
  452. layer for layer in biome_layers if layer["type"] == "BiomeEntityLayer"
  453. ]
  454. biome_decal_layers = [
  455. layer for layer in biome_layers if layer["type"] == "BiomeDecalLayer"
  456. ]
  457. dynamic_groups = generate_dynamic_entities(tile_map, biome_entity_layers, seed_base)
  458. decals_by_chunk = generate_decals(
  459. tile_map, biome_decal_layers, seed_base, chunk_size
  460. )
  461. main_entities = generate_main_entities(tile_map, chunk_size, decals_by_chunk)
  462. entities.append(main_entities)
  463. entities.extend(dynamic_groups)
  464. spawn_points = generate_spawn_points(tile_map)
  465. entities.extend(spawn_points)
  466. return entities
  467. # -----------------------------------------------------------------------------
  468. # Save YAML
  469. # -----------------------------------------------------------------------------
  470. def represent_sound_path_specifier(dumper, data):
  471. """Customised representation for the SoundPathSpecifier in the YAML."""
  472. for key, value in data.items():
  473. if isinstance(key, str) and key.startswith("!type:"):
  474. tag = key
  475. if isinstance(value, dict) and "path" in value:
  476. return dumper.represent_mapping(tag, value)
  477. return dumper.represent_dict(data)
  478. def save_map_to_yaml(
  479. tile_map,
  480. biome_layers,
  481. output_dir,
  482. filename="output.yml",
  483. chunk_size=16,
  484. seed_base=None,
  485. ):
  486. """Saves the generated map in a YAML file in the specified folder."""
  487. all_entities = generate_all_entities(tile_map, chunk_size, biome_layers, seed_base)
  488. count = sum(len(group.get("entities", [])) for group in all_entities)
  489. map_data = {
  490. "meta": {
  491. "format": 7,
  492. "category": "Map",
  493. "engineVersion": "249.0.0",
  494. "forkId": "",
  495. "forkVersion": "",
  496. "time": "03/23/2025 18:21:23",
  497. "entityCount": count,
  498. },
  499. "maps": [1],
  500. "grids": [2],
  501. "orphans": [],
  502. "nullspace": [],
  503. "tilemap": TILEMAP,
  504. "entities": all_entities,
  505. }
  506. yaml.add_representer(dict, represent_sound_path_specifier)
  507. output_path = os.path.join(output_dir, filename)
  508. with open(output_path, "w") as outfile:
  509. yaml.dump(map_data, outfile, default_flow_style=False, sort_keys=False)
  510. import numpy as np
  511. from collections import defaultdict
  512. def apply_erosion(tile_map, tile_type, min_neighbors=3):
  513. h, w = tile_map.shape
  514. new_map = tile_map.copy()
  515. for y in range(1, h - 1):
  516. for x in range(1, w - 1):
  517. if tile_map[y, x] == tile_type:
  518. neighbors = 0
  519. neighbor_types = []
  520. for dy in [-1, 0, 1]:
  521. for dx in [-1, 0, 1]:
  522. if dy == 0 and dx == 0:
  523. continue
  524. neighbor_y = y + dy
  525. neighbor_x = x + dx
  526. if 0 <= neighbor_y < h and 0 <= neighbor_x < w:
  527. nt = tile_map[neighbor_y, neighbor_x]
  528. neighbor_types.append(nt)
  529. if nt == tile_type:
  530. neighbors += 1
  531. if neighbors < min_neighbors:
  532. counts = defaultdict(int)
  533. for nt in neighbor_types:
  534. counts[nt] += 1
  535. if counts:
  536. max_count = max(counts.values())
  537. candidates = [k for k, v in counts.items() if v == max_count]
  538. majority_type = candidates[0] # Defines majority_type here
  539. new_map[y, x] = majority_type
  540. return new_map
  541. def count_isolated_tiles(tile_map, tile_type, min_neighbors=3):
  542. h, w = tile_map.shape
  543. isolated = 0
  544. for y in range(1, h - 1):
  545. for x in range(1, w - 1):
  546. if tile_map[y, x] == tile_type:
  547. neighbors = sum(
  548. 1
  549. for dy in [-1, 0, 1]
  550. for dx in [-1, 0, 1]
  551. if not (dy == 0 and dx == 0)
  552. and 0 <= y + dy < h
  553. and 0 <= x + dx < w
  554. and tile_map[y + dy, x + dx] == tile_type
  555. )
  556. if neighbors < min_neighbors:
  557. isolated += 1
  558. return isolated
  559. def apply_iterative_erosion(tile_map, tile_type, min_neighbors=3, max_iterations=10):
  560. """Applies erosion interactively untill there are no more tiles with the declared min neighbors"""
  561. iteration = 0
  562. while iteration < max_iterations:
  563. isolated_before = count_isolated_tiles(tile_map, tile_type, min_neighbors)
  564. tile_map = apply_erosion(tile_map, tile_type, min_neighbors)
  565. isolated_after = count_isolated_tiles(tile_map, tile_type, min_neighbors)
  566. if isolated_after == isolated_before or isolated_after == 0:
  567. break
  568. iteration += 1
  569. return tile_map
  570. # -----------------------------------------------------------------------------
  571. # Spawn Point Generation
  572. # -----------------------------------------------------------------------------
  573. def generate_spawn_points(tile_map, num_points_per_corner=1):
  574. """Generates 4 SpawnPointNomads and 4 SpawnPointLatejoin, one on each corner, on FloorPlanetGrass."""
  575. h, w = tile_map.shape
  576. spawn_positions = set()
  577. nomads_entities = []
  578. latejoin_entities = []
  579. corners = ["top_left", "top_right", "bottom_left", "bottom_right"]
  580. astro_grass_id = TILEMAP_REVERSE["FloorPlanetGrass"]
  581. directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
  582. for corner in corners:
  583. found = False
  584. initial_size = 15 # Initial size to search for positions
  585. while not found and initial_size <= min(w, h) // 2:
  586. x_min, x_max, y_min, y_max = get_corner_region(corner, w, h, initial_size)
  587. candidates = []
  588. # Searchs for AstroTileGrass in the initial size in the corners
  589. for y in range(y_min, y_max + 1):
  590. for x in range(x_min, x_max + 1):
  591. if (
  592. tile_map[y, x] == astro_grass_id
  593. and (x, y) not in spawn_positions
  594. ):
  595. # Verifies adjacent valid tiles
  596. adjacent = []
  597. for dx, dy in directions:
  598. nx, ny = x + dx, y + dy
  599. if (
  600. 0 <= nx < w
  601. and 0 <= ny < h
  602. and tile_map[ny, nx] == astro_grass_id
  603. and (nx, ny) not in spawn_positions
  604. ):
  605. adjacent.append((nx, ny))
  606. if adjacent:
  607. candidates.append((x, y, adjacent))
  608. if candidates:
  609. x, y, adjacent = random.choice(candidates)
  610. adj_x, adj_y = random.choice(adjacent)
  611. if random.random() < 0.5:
  612. nomads_pos = (x, y)
  613. latejoin_pos = (adj_x, adj_y)
  614. else:
  615. nomads_pos = (adj_x, adj_y)
  616. latejoin_pos = (x, y)
  617. nomads_entities.append(
  618. {
  619. "uid": next_uid(),
  620. "components": [
  621. {
  622. "type": "Transform",
  623. "parent": 2,
  624. "pos": f"{nomads_pos[0]},{nomads_pos[1]}",
  625. }
  626. ],
  627. }
  628. )
  629. latejoin_entities.append(
  630. {
  631. "uid": next_uid(),
  632. "components": [
  633. {
  634. "type": "Transform",
  635. "parent": 2,
  636. "pos": f"{latejoin_pos[0]},{latejoin_pos[1]}",
  637. }
  638. ],
  639. }
  640. )
  641. spawn_positions.add(nomads_pos)
  642. spawn_positions.add(latejoin_pos)
  643. found = True
  644. else:
  645. initial_size += 1
  646. if not found:
  647. print(
  648. f"Possible to find an available position at the corner for spawn points {corner}"
  649. )
  650. print("SpawnPointNomads positions:")
  651. for ent in nomads_entities:
  652. pos = ent["components"][0]["pos"]
  653. print(pos)
  654. print("SpawnPointLatejoin positions:")
  655. for ent in latejoin_entities:
  656. pos = ent["components"][0]["pos"]
  657. print(pos)
  658. # Retorna as entidades no formato correto para o YAML
  659. return [
  660. {"proto": "SpawnPointNomads", "entities": nomads_entities},
  661. {"proto": "SpawnPointLatejoin", "entities": latejoin_entities},
  662. ]
  663. def get_corner_region(corner, w, h, initial_size):
  664. """Defines a region to search in the map's corners."""
  665. if corner == "top_left":
  666. x_min = 1
  667. x_max = min(initial_size, w - 2)
  668. y_min = 1
  669. y_max = min(initial_size, h - 2)
  670. elif corner == "top_right":
  671. x_min = max(w - 1 - initial_size, 1)
  672. x_max = w - 2
  673. y_min = 1
  674. y_max = min(initial_size, h - 2)
  675. elif corner == "bottom_left":
  676. x_min = 1
  677. x_max = min(initial_size, w - 2)
  678. y_min = max(h - 1 - initial_size, 1)
  679. y_max = h - 2
  680. elif corner == "bottom_right":
  681. x_min = max(w - 1 - initial_size, 1)
  682. x_max = w - 2
  683. y_min = max(h - 1 - initial_size, 1)
  684. y_max = h - 2
  685. else:
  686. raise ValueError("Invalid corner")
  687. return x_min, x_max, y_min, y_max
  688. # -----------------------------------------------------------------------------
  689. # Configuração do Mapa (MAP_CONFIG)
  690. # -----------------------------------------------------------------------------
  691. MAP_CONFIG = [
  692. { # Rock dirt formations
  693. "type": "BiomeTileLayer",
  694. "tile_type": "FloorDirtRock",
  695. "noise_type": NoiseType.NoiseType_OpenSimplex2,
  696. "octaves": 2,
  697. "frequency": 0.01,
  698. "fractal_type": FractalType.FractalType_None,
  699. "threshold": -1.0,
  700. "overwrite": True,
  701. },
  702. { # Sprinkled dirt around the map
  703. "type": "BiomeTileLayer",
  704. "tile_type": "FloorDirt",
  705. "noise_type": NoiseType.NoiseType_OpenSimplex2,
  706. "octaves": 10,
  707. "frequency": 0.3,
  708. "fractal_type": FractalType.FractalType_FBm,
  709. "threshold": 0.825,
  710. "overwrite": True,
  711. "dontOverwrite": ["FloorSand", "FloorDirtRock"],
  712. "priority": 10,
  713. },
  714. {
  715. "type": "BiomeTileLayer",
  716. "tile_type": "FloorPlanetGrass",
  717. "noise_type": NoiseType.NoiseType_Perlin,
  718. "octaves": 3,
  719. "frequency": 0.02,
  720. "fractal_type": FractalType.FractalType_None,
  721. "threshold": 0.4,
  722. "overwrite": True,
  723. },
  724. { # Boulders for flints
  725. "type": "BiomeEntityLayer",
  726. "entity_protos": "FloraRockSolid",
  727. "noise_type": NoiseType.NoiseType_OpenSimplex2S,
  728. "octaves": 6,
  729. "frequency": 0.3,
  730. "fractal_type": FractalType.FractalType_FBm,
  731. "threshold": 0.815,
  732. "tile_condition": lambda tile: tile
  733. in [
  734. TILEMAP_REVERSE["FloorPlanetGrass"],
  735. TILEMAP_REVERSE["FloorDirt"],
  736. TILEMAP_REVERSE["FloorDirtRock"],
  737. ],
  738. "priority": 1,
  739. },
  740. { # Rocks
  741. "type": "BiomeEntityLayer",
  742. "entity_protos": "WallRock",
  743. "noise_type": NoiseType.NoiseType_Cellular,
  744. "cellular_distance_function": CellularDistanceFunction.CellularDistanceFunction_Hybrid,
  745. "cellular_return_type": CellularReturnType.CellularReturnType_CellValue,
  746. "cellular_jitter": 1.070,
  747. "octaves": 2,
  748. "frequency": 0.015,
  749. "fractal_type": FractalType.FractalType_FBm,
  750. "threshold": 0.30,
  751. "tile_condition": lambda tile: tile == TILEMAP_REVERSE["FloorDirtRock"],
  752. "priority": 2,
  753. },
  754. { # Wild crops
  755. "type": "BiomeEntityLayer",
  756. "entity_protos": [
  757. "WildPlantPotato",
  758. "WildPlantCorn",
  759. "WildPlantRice",
  760. "WildPlantWheat",
  761. "WildPlantHemp",
  762. "WildPlantPoppy",
  763. "WildPlantAloe",
  764. "WildPlantYarrow",
  765. "WildPlantElderflower",
  766. "WildPlantMilkThistle",
  767. "WildPlantComfrey",
  768. ],
  769. "noise_type": NoiseType.NoiseType_OpenSimplex2S,
  770. "octaves": 6,
  771. "frequency": 0.3,
  772. "fractal_type": FractalType.FractalType_FBm,
  773. "threshold": 0.84,
  774. "tile_condition": lambda tile: tile in [TILEMAP_REVERSE["FloorPlanetGrass"]],
  775. "priority": 1,
  776. },
  777. { # Rivers
  778. "type": "BiomeEntityLayer",
  779. "entity_protos": "FloorWaterEntity",
  780. "noise_type": NoiseType.NoiseType_OpenSimplex2,
  781. "octaves": 1,
  782. "fractal_lacunarity": 1.50,
  783. "frequency": 0.003,
  784. "fractal_type": FractalType.FractalType_Ridged,
  785. "threshold": 0.95,
  786. "tile_condition": lambda tile: True,
  787. "priority": 10,
  788. "seed_key": "river_noise",
  789. },
  790. { # Deep River Water (in the middle)
  791. "type": "BiomeEntityLayer",
  792. "entity_protos": "FloorWaterDeepEntity", # The deep water entity
  793. "noise_type": NoiseType.NoiseType_OpenSimplex2, # Same noise type as river
  794. "octaves": 1, # Same octaves as river
  795. "fractal_lacunarity": 1.50, # Same lacunarity as river
  796. "frequency": 0.003, # Same frequency as river
  797. "fractal_type": FractalType.FractalType_Ridged, # Same fractal type as river
  798. "threshold": 0.975, # HIGHER threshold than river (adjust if needed)
  799. "tile_condition": lambda tile: True, # Place wherever noise is high enough
  800. "priority": 11, # HIGHER priority than river (to overwrite)
  801. "seed_key": "river_noise", # MUST use the same noise seed as river
  802. },
  803. { # River sand
  804. "type": "BiomeTileLayer",
  805. "tile_type": "FloorSand",
  806. "noise_type": NoiseType.NoiseType_OpenSimplex2,
  807. "octaves": 1,
  808. "frequency": 0.003, # Same as the river
  809. "fractal_type": FractalType.FractalType_Ridged,
  810. "threshold": 0.935, # Larger than the river
  811. "overwrite": True,
  812. "seed_key": "river_noise",
  813. },
  814. { # Additional River Sand with More Curves
  815. "type": "BiomeTileLayer",
  816. "tile_type": "FloorSand",
  817. "noise_type": NoiseType.NoiseType_OpenSimplex2,
  818. "octaves": 1,
  819. "frequency": 0.003,
  820. "fractal_type": FractalType.FractalType_Ridged,
  821. "threshold": 0.92, # Slightly lower than the original
  822. "overwrite": True,
  823. "seed_key": "river_noise", # Same as the original to follow its path
  824. "modulation": {
  825. "noise_type": NoiseType.NoiseType_Perlin, # Different noise for variation
  826. "frequency": 0.01, # Controls the scale of the variation
  827. "threshold_min": 0.43, # Lower bound where sand starts appearing
  828. "threshold_max": 0.55, # Upper bound for a smooth transition
  829. },
  830. },
  831. { # Trees
  832. "type": "BiomeEntityLayer",
  833. "entity_protos": "TreeTemperate",
  834. "noise_type": NoiseType.NoiseType_OpenSimplex2,
  835. "octaves": 1,
  836. "frequency": 0.5,
  837. "fractal_type": FractalType.FractalType_FBm,
  838. "threshold": 0.9,
  839. "tile_condition": lambda tile: tile == TILEMAP_REVERSE["FloorPlanetGrass"],
  840. "priority": 0,
  841. },
  842. ####### PREDATORS
  843. { # Wolves
  844. "type": "BiomeEntityLayer",
  845. "entity_protos": "SpawnMobGreyWolf",
  846. "noise_type": NoiseType.NoiseType_OpenSimplex2,
  847. "octaves": 1,
  848. "frequency": 0.1,
  849. "fractal_type": FractalType.FractalType_FBm,
  850. "threshold": 0.9981,
  851. "tile_condition": lambda tile: tile == TILEMAP_REVERSE["FloorPlanetGrass"],
  852. "priority": 11,
  853. },
  854. { # Bears
  855. "type": "BiomeEntityLayer",
  856. "entity_protos": "SpawnMobBear",
  857. "noise_type": NoiseType.NoiseType_Perlin,
  858. "octaves": 1,
  859. "frequency": 0.300,
  860. "fractal_type": FractalType.FractalType_FBm,
  861. "threshold": 0.958,
  862. "tile_condition": lambda tile: tile
  863. in [TILEMAP_REVERSE["FloorPlanetGrass"], TILEMAP_REVERSE["FloorDirtRock"]],
  864. "priority": 1,
  865. },
  866. { # Sabertooth
  867. "type": "BiomeEntityLayer",
  868. "entity_protos": "SpawnMobSabertooth",
  869. "noise_type": NoiseType.NoiseType_Perlin,
  870. "octaves": 1,
  871. "frequency": 0.300,
  872. "fractal_type": FractalType.FractalType_FBm,
  873. "threshold": 0.96882,
  874. "tile_condition": lambda tile: tile == TILEMAP_REVERSE["FloorPlanetGrass"],
  875. "priority": 11,
  876. },
  877. ####### Preys
  878. { # Rabbits
  879. "type": "BiomeEntityLayer",
  880. "entity_protos": "SpawnMobRabbit",
  881. "noise_type": NoiseType.NoiseType_OpenSimplex2,
  882. "octaves": 1,
  883. "frequency": 0.1,
  884. "fractal_type": FractalType.FractalType_FBm,
  885. "threshold": 0.9989,
  886. "tile_condition": lambda tile: tile == TILEMAP_REVERSE["FloorPlanetGrass"],
  887. "priority": 11,
  888. },
  889. { # Chicken
  890. "type": "BiomeEntityLayer",
  891. "entity_protos": "SpawnMobChicken",
  892. "noise_type": NoiseType.NoiseType_OpenSimplex2,
  893. "octaves": 1,
  894. "frequency": 0.1,
  895. "fractal_type": FractalType.FractalType_FBm,
  896. "threshold": 0.9989,
  897. "tile_condition": lambda tile: tile == TILEMAP_REVERSE["FloorPlanetGrass"],
  898. "priority": 11,
  899. },
  900. { # Deers
  901. "type": "BiomeEntityLayer",
  902. "entity_protos": "SpawnMobDeer",
  903. "noise_type": NoiseType.NoiseType_OpenSimplex2,
  904. "octaves": 1,
  905. "frequency": 0.1,
  906. "fractal_type": FractalType.FractalType_FBm,
  907. "threshold": 0.9989,
  908. "tile_condition": lambda tile: tile == TILEMAP_REVERSE["FloorPlanetGrass"],
  909. "priority": 11,
  910. },
  911. { # Pigs
  912. "type": "BiomeEntityLayer",
  913. "entity_protos": "SpawnMobPig",
  914. "noise_type": NoiseType.NoiseType_OpenSimplex2,
  915. "octaves": 1,
  916. "frequency": 0.1,
  917. "fractal_type": FractalType.FractalType_FBm,
  918. "threshold": 0.9992,
  919. "tile_condition": lambda tile: tile == TILEMAP_REVERSE["FloorPlanetGrass"],
  920. "priority": 11,
  921. },
  922. # DECALS
  923. { # Bush Temperate group 1
  924. "type": "BiomeDecalLayer",
  925. "decal_id": [
  926. "BushTemperate1",
  927. "BushTemperate2",
  928. "BushTemperate3",
  929. "BushTemperate4",
  930. ],
  931. "noise_type": NoiseType.NoiseType_OpenSimplex2,
  932. "octaves": 1,
  933. "frequency": 0.1,
  934. "fractal_type": FractalType.FractalType_FBm,
  935. "threshold": 0.96,
  936. "tile_condition": lambda tile: tile == TILEMAP_REVERSE["FloorPlanetGrass"],
  937. "color": "#FFFFFFFF",
  938. },
  939. { # Bush Temperate group 2
  940. "type": "BiomeDecalLayer",
  941. "decal_id": [
  942. "BushTemperate5",
  943. "BushTemperate6",
  944. "BushTemperate7",
  945. "BushTemperate8",
  946. ],
  947. "noise_type": NoiseType.NoiseType_OpenSimplex2,
  948. "octaves": 1,
  949. "frequency": 0.1,
  950. "fractal_type": FractalType.FractalType_FBm,
  951. "threshold": 0.96,
  952. "tile_condition": lambda tile: tile == TILEMAP_REVERSE["FloorPlanetGrass"],
  953. "color": "#FFFFFFFF",
  954. },
  955. { # Bush Temperate group 3
  956. "type": "BiomeDecalLayer",
  957. "decal_id": ["BushTemperate9", "BushTemperate10", "BushTemperate11"],
  958. "noise_type": NoiseType.NoiseType_OpenSimplex2,
  959. "octaves": 1,
  960. "frequency": 0.1,
  961. "fractal_type": FractalType.FractalType_FBm,
  962. "threshold": 0.96,
  963. "tile_condition": lambda tile: tile == TILEMAP_REVERSE["FloorPlanetGrass"],
  964. "color": "#FFFFFFFF",
  965. },
  966. { # Bush Temperate group 4
  967. "type": "BiomeDecalLayer",
  968. "decal_id": [
  969. "BushTemperate12",
  970. "BushTemperate13",
  971. "BushTemperate14",
  972. "BushTemperate15",
  973. ],
  974. "noise_type": NoiseType.NoiseType_OpenSimplex2,
  975. "octaves": 1,
  976. "frequency": 0.1,
  977. "fractal_type": FractalType.FractalType_FBm,
  978. "threshold": 0.96,
  979. "tile_condition": lambda tile: tile == TILEMAP_REVERSE["FloorPlanetGrass"],
  980. "color": "#FFFFFFFF",
  981. },
  982. { # Bush Temperate group 5
  983. "type": "BiomeDecalLayer",
  984. "decal_id": ["BushTemperate16", "BushTemperate17", "BushTemperate18"],
  985. "noise_type": NoiseType.NoiseType_OpenSimplex2,
  986. "octaves": 1,
  987. "frequency": 0.1,
  988. "fractal_type": FractalType.FractalType_FBm,
  989. "threshold": 0.96,
  990. "tile_condition": lambda tile: tile == TILEMAP_REVERSE["FloorPlanetGrass"],
  991. "color": "#FFFFFFFF",
  992. },
  993. { # Bush Temperate group 6
  994. "type": "BiomeDecalLayer",
  995. "decal_id": [
  996. "BushTemperate19",
  997. "BushTemperate20",
  998. "BushTemperate21",
  999. "BushTemperate22",
  1000. ],
  1001. "noise_type": NoiseType.NoiseType_OpenSimplex2,
  1002. "octaves": 1,
  1003. "frequency": 0.1,
  1004. "fractal_type": FractalType.FractalType_FBm,
  1005. "threshold": 0.96,
  1006. "tile_condition": lambda tile: tile == TILEMAP_REVERSE["FloorPlanetGrass"],
  1007. "color": "#FFFFFFFF",
  1008. },
  1009. { # Bush Temperate group 7
  1010. "type": "BiomeDecalLayer",
  1011. "decal_id": ["BushTemperate23", "BushTemperate24", "BushTemperate25"],
  1012. "noise_type": NoiseType.NoiseType_OpenSimplex2,
  1013. "octaves": 1,
  1014. "frequency": 0.1,
  1015. "fractal_type": FractalType.FractalType_FBm,
  1016. "threshold": 0.96,
  1017. "tile_condition": lambda tile: tile == TILEMAP_REVERSE["FloorPlanetGrass"],
  1018. "color": "#FFFFFFFF",
  1019. },
  1020. { # Bush Temperate group 8
  1021. "type": "BiomeDecalLayer",
  1022. "decal_id": ["BushTemperate26", "BushTemperate27", "BushTemperate28"],
  1023. "noise_type": NoiseType.NoiseType_OpenSimplex2,
  1024. "octaves": 1,
  1025. "frequency": 0.1,
  1026. "fractal_type": FractalType.FractalType_FBm,
  1027. "threshold": 0.96,
  1028. "tile_condition": lambda tile: tile == TILEMAP_REVERSE["FloorPlanetGrass"],
  1029. "color": "#FFFFFFFF",
  1030. },
  1031. { # Bush Temperate group 9
  1032. "type": "BiomeDecalLayer",
  1033. "decal_id": [
  1034. "BushTemperate29",
  1035. "BushTemperate30",
  1036. "BushTemperate31",
  1037. "BushTemperate32",
  1038. ],
  1039. "noise_type": NoiseType.NoiseType_OpenSimplex2,
  1040. "octaves": 1,
  1041. "frequency": 0.1,
  1042. "fractal_type": FractalType.FractalType_FBm,
  1043. "threshold": 0.96,
  1044. "tile_condition": lambda tile: tile == TILEMAP_REVERSE["FloorPlanetGrass"],
  1045. "color": "#FFFFFFFF",
  1046. },
  1047. { # Bush Temperate group 10
  1048. "type": "BiomeDecalLayer",
  1049. "decal_id": [
  1050. "BushTemperate33",
  1051. "BushTemperate34",
  1052. "BushTemperate35",
  1053. "BushTemperate36",
  1054. ],
  1055. "noise_type": NoiseType.NoiseType_OpenSimplex2,
  1056. "octaves": 1,
  1057. "frequency": 0.1,
  1058. "fractal_type": FractalType.FractalType_FBm,
  1059. "threshold": 0.96,
  1060. "tile_condition": lambda tile: tile == TILEMAP_REVERSE["FloorPlanetGrass"],
  1061. "color": "#FFFFFFFF",
  1062. },
  1063. { # Bush Temperate group 11 - High grass
  1064. "type": "BiomeDecalLayer",
  1065. "decal_id": [
  1066. "BushTemperate37",
  1067. "BushTemperate38",
  1068. "BushTemperate39",
  1069. "BushTemperate40",
  1070. "BushTemperate41",
  1071. "BushTemperate42",
  1072. ],
  1073. "noise_type": NoiseType.NoiseType_OpenSimplex2,
  1074. "octaves": 1,
  1075. "frequency": 0.1,
  1076. "fractal_type": FractalType.FractalType_FBm,
  1077. "threshold": 0.96,
  1078. "tile_condition": lambda tile: tile == TILEMAP_REVERSE["FloorPlanetGrass"],
  1079. "color": "#FFFFFFFF",
  1080. },
  1081. ]
  1082. # -----------------------------------------------------------------------------
  1083. # Execution
  1084. # -----------------------------------------------------------------------------
  1085. start_time = time.time()
  1086. seed_base = random.randint(0, 1000000)
  1087. print(f"Generated seed: {seed_base}")
  1088. width, height = mapWidth, mapHeight
  1089. chunk_size = 16
  1090. biome_tile_layers = [layer for layer in MAP_CONFIG if layer["type"] == "BiomeTileLayer"]
  1091. biome_entity_layers = [
  1092. layer for layer in MAP_CONFIG if layer["type"] == "BiomeEntityLayer"
  1093. ]
  1094. script_dir = os.path.dirname(os.path.abspath(__file__))
  1095. output_dir = os.path.join(script_dir, "Resources", "Maps", "civ")
  1096. os.makedirs(output_dir, exist_ok=True)
  1097. tile_map = generate_tile_map(width, height, biome_tile_layers, seed_base)
  1098. # Applies erosion to lone sand tiles, overwritting it with surrounding tiles
  1099. tile_map = apply_iterative_erosion(
  1100. tile_map, TILEMAP_REVERSE["FloorSand"], min_neighbors=1
  1101. )
  1102. bordered_tile_map = add_border(tile_map, border_value=TILEMAP_REVERSE["FloorDirt"])
  1103. save_map_to_yaml(
  1104. bordered_tile_map,
  1105. MAP_CONFIG,
  1106. output_dir,
  1107. filename="nomads_classic.yml",
  1108. chunk_size=chunk_size,
  1109. seed_base=seed_base,
  1110. )
  1111. end_time = time.time()
  1112. total_time = end_time - start_time
  1113. print(f"Map generated and saved in {total_time:.2f} seconds!")