Commit 48dad1b3 authored by Rick Gruber-Riemer's avatar Rick Gruber-Riemer

* Patch for issue #28 regarding division by zero errors in roofs

* Patch for issue #27 ways without references
* Correction for error during convex hull checking (adding building after loop instead of inside)
* Add multiprocessing Lock for writing to stg-files
* Using os.path.join
parent f0fa57c3
......@@ -186,7 +186,7 @@ done
# Manipulate the properties file and write to new destination
with open(args.properties, "r") as sources:
lines = sources.readlines()
with open(path + os.sep + params_out_file_name, "w") as sources:
with open(os.path.join(path, params_out_file_name), "w") as sources:
replacement = '\\1 "' + replacement_path + '"'
for line in lines:
line = re.sub('^\s*(PREFIX\s*=)(.*)', replacement, line)
......@@ -209,7 +209,7 @@ done
calc_tile.get_west_lon(lon, lat, dx),
calc_tile.get_south_lat(lat, dy),
calc_tile.get_east_lon(lon, lat, dx),
replacement_path + os.sep + OSM_FILE_NAME))
os.path.join(replacement_path, OSM_FILE_NAME)))
else:
download_command = 'curl -f --retry 6 --proxy-ntlm -o %s/%s -g %s*[bbox=%f,%f,%f,%f] '
if BASH_PARALLEL_PROCESS:
......@@ -223,14 +223,16 @@ done
calc_tile.get_east_lon(lon, lat, dx),
calc_tile.get_north_lat(lat, dy)))
for command in files:
_write_to_file(command[0], command[1], python_exe, replacement_path + os.sep + params_out_file_name)
_write_to_file(command[0], command[1], python_exe,
os.path.join(replacement_path, params_out_file_name))
for command in files:
command[1].close()
# chmod u+x on created scripts for linux
if is_linux_or_mac:
for util in utils + ['download', ]:
f = calc_tile.root_directory_name((lon, lat)) + os.sep + _get_file_name(util + "_", args.tile_name)
f = os.path.join(calc_tile.root_directory_name((lon, lat)),
_get_file_name(util + "_", args.tile_name))
try:
st = os.stat(f)
os.chmod(f, st.st_mode | stat.S_IEXEC)
......
import argparse
import datetime
from enum import IntEnum, unique
import logging
import multiprocessing as mp
......@@ -12,7 +13,7 @@ import unittest
import buildings
import copy_data_stuff
# import piers
import piers
import platforms
import pylons
import roads
......@@ -61,20 +62,22 @@ def _parse_exec_for_procedure(exec_argument: str) -> Procedures:
def process_scenery_tile(scenery_tile: SceneryTile, params_file_name: str, log_level: str,
exec_argument: Procedures, my_airports: List[aptdat_io.Airport]) -> None:
parameters.read_from_file(params_file_name)
parameters.set_loglevel(log_level)
parameters.USE_DATABASE = True # just to be sure
# adapt boundary
parameters.BOUNDARY_WEST = scenery_tile.boundary_west
parameters.BOUNDARY_SOUTH = scenery_tile.boundary_south
parameters.BOUNDARY_EAST = scenery_tile.boundary_east
parameters.BOUNDARY_NORTH = scenery_tile.boundary_north
parameters.PREFIX = scenery_tile.prefix
logging.info("Processing tile {} in prefix {} with process id = {}".format(scenery_tile.tile_index,
parameters.PREFIX,
os.getpid()))
exec_argument: Procedures, my_airports: List[aptdat_io.Airport],
file_lock: mp.Lock) -> None:
try:
parameters.read_from_file(params_file_name)
parameters.set_loglevel(log_level)
parameters.USE_DATABASE = True # just to be sure
# adapt boundary
parameters.BOUNDARY_WEST = scenery_tile.boundary_west
parameters.BOUNDARY_SOUTH = scenery_tile.boundary_south
parameters.BOUNDARY_EAST = scenery_tile.boundary_east
parameters.BOUNDARY_NORTH = scenery_tile.boundary_north
parameters.PREFIX = scenery_tile.prefix
logging.info("Processing tile {} in prefix {} with process id = {}".format(scenery_tile.tile_index,
parameters.PREFIX,
os.getpid()))
# prepare shared resources
the_coords_transform = coordinates.Transformation(parameters.get_center_global())
my_fg_elev = FGElev(the_coords_transform)
......@@ -87,21 +90,21 @@ def process_scenery_tile(scenery_tile: SceneryTile, params_file_name: str, log_l
# run programs
if exec_argument is Procedures.all:
buildings.process(the_coords_transform, my_fg_elev, my_blocked_areas, my_stg_entries)
roads.process(the_coords_transform, my_fg_elev, my_blocked_areas, my_stg_entries)
pylons.process(the_coords_transform, my_fg_elev, my_stg_entries)
platforms.process(the_coords_transform, my_fg_elev)
# piers.process(the_coords_transform, my_fg_elev)
buildings.process(the_coords_transform, my_fg_elev, my_blocked_areas, my_stg_entries, file_lock)
roads.process(the_coords_transform, my_fg_elev, my_blocked_areas, my_stg_entries, file_lock)
pylons.process(the_coords_transform, my_fg_elev, my_stg_entries, file_lock)
platforms.process(the_coords_transform, my_fg_elev, file_lock)
piers.process(the_coords_transform, my_fg_elev, file_lock)
elif exec_argument is Procedures.buildings:
buildings.process(the_coords_transform, my_fg_elev, my_blocked_areas, my_stg_entries)
buildings.process(the_coords_transform, my_fg_elev, my_blocked_areas, my_stg_entries, file_lock)
elif exec_argument is Procedures.roads:
roads.process(the_coords_transform, my_fg_elev, my_blocked_areas, my_stg_entries)
roads.process(the_coords_transform, my_fg_elev, my_blocked_areas, my_stg_entries, file_lock)
elif exec_argument is Procedures.pylons:
pylons.process(the_coords_transform, my_fg_elev, my_stg_entries)
pylons.process(the_coords_transform, my_fg_elev, my_stg_entries, file_lock)
elif exec_argument is Procedures.platforms:
platforms.process(the_coords_transform, my_fg_elev)
platforms.process(the_coords_transform, my_fg_elev, file_lock)
elif exec_argument is Procedures.piers:
# piers.process(the_coords_transform, my_fg_elev)
piers.process(the_coords_transform, my_fg_elev, file_lock)
pass
# clean-up
......@@ -114,13 +117,14 @@ def process_scenery_tile(scenery_tile: SceneryTile, params_file_name: str, log_l
scenery_tile.boundary_east, scenery_tile.boundary_north)
logging.exception(msg)
f = open("osm2city-exceptions.log", "a")
# print info
print(msg, file=f)
# print exception
exc_type, exc_value, exc_traceback = sys.exc_info()
print(''.join(traceback.format_exception(exc_type, exc_value, exc_traceback)), file=f)
f.close()
time_now = datetime.datetime.now().strftime('%Y%m%d_%H:%M:%S - ')
with open("osm2city-exceptions.log", "a") as f:
# print info
f.write(msg + ' at ' + time_now + os.linesep)
# print exception
exc_type, exc_value, exc_traceback = sys.exc_info()
f.write(''.join(traceback.format_exception(exc_type, exc_value, exc_traceback)))
logging.info("******* Finished tile {} *******".format(scenery_tile.tile_index))
......@@ -136,7 +140,7 @@ if __name__ == '__main__':
required=True)
parser.add_argument("-p", "--processes", dest="processes", type=int,
help="number of parallel processes (should not be more than number of cores/CPUs)",
required=True, )
required=True)
parser.add_argument("-e", "--execute", dest="exec",
help="execute only the given osm2city procedure (buildings, piers, platforms, pylons, roads)",
required=False)
......@@ -217,9 +221,10 @@ if __name__ == '__main__':
start_time = time.time()
mp.set_start_method('spawn') # use safe approach to make sure e.g. parameters module is initialized separately
pool = mp.Pool(processes=args.processes, maxtasksperchild=1)
the_file_lock = mp.Manager().Lock()
for my_scenery_tile in scenery_tiles_list:
pool.apply_async(process_scenery_tile, (my_scenery_tile, args.filename, args.loglevel,
exec_procedure, airports))
exec_procedure, airports, the_file_lock))
pool.close()
pool.join()
......
......@@ -1045,12 +1045,14 @@ def map_building_type(tags) -> str:
def overlap_check_blocked_areas(buildings: List[Building], blocked_areas: List[shg.Polygon]) -> List[Building]:
cleared_buildings = list()
for building in buildings:
is_intersected = False
for blocked_area in blocked_areas:
if building.polygon.intersects(blocked_area):
logging.debug("Building osm_id=%d intersects with blocked area.", building.osm_id)
continue
else:
cleared_buildings.append(building)
is_intersected = True
break
if not is_intersected:
cleared_buildings.append(building)
return cleared_buildings
......
......@@ -56,6 +56,8 @@ You should disable random buildings.
import argparse
import logging
import multiprocessing as mp
import os
import random
import textwrap
from typing import Dict, List, Optional
......@@ -211,7 +213,7 @@ def _process_osm_building(nodes_dict: Dict[int, osmparser.Node], ways_dict: Dict
clipping_border = shg.Polygon(parameters.get_clipping_border())
for key, way in ways_dict.items():
if not ('building' in way.tags or 'building:part' in way.tags):
if not ('building' in way.tags or 'building:part' in way.tags) or len(way.refs) == 0:
continue
first_node = nodes_dict[way.refs[0]]
......@@ -263,9 +265,9 @@ def _make_building_from_way(nodes_dict: Dict[int, osmparser.Node], all_tags: Dic
_roof_height = 0
if 'roof:height' in all_tags:
try:
_roof_height = float(all_tags['roof:height'])
_roof_height = utils.osmparser.parse_length(all_tags['roof:height'])
except:
_roof_height = 0
_roof_height = 0.
_building_type = building_lib.map_building_type(all_tags)
......@@ -315,7 +317,7 @@ def _refs_to_ring(coords_transform: coordinates.Transformation, refs, nodes_dict
def _write_xml(path: str, file_name: str, the_buildings: List[building_lib.Building], cluster_offset: v.Vec2d) -> None:
# -- LOD animation
xml = open(path + file_name + ".xml", "w")
xml = open(os.path.join(path, file_name + ".xml"), "w")
xml.write("""<?xml version="1.0"?>\n<PropertyList>\n""")
xml.write("<path>%s.ac</path>" % file_name)
......@@ -360,7 +362,8 @@ def _write_xml(path: str, file_name: str, the_buildings: List[building_lib.Build
def process(coords_transform: coordinates.Transformation, fg_elev: utilities.FGElev,
blocked_areas: List[shg.Polygon], stg_entries: List[utils.stg_io2.STGEntry]) -> None:
blocked_areas: List[shg.Polygon], stg_entries: List[utils.stg_io2.STGEntry],
file_lock: mp.Lock=None) -> None:
random.seed(42)
stats = utilities.Stats()
......@@ -480,7 +483,7 @@ def process(coords_transform: coordinates.Transformation, fg_elev: utilities.FGE
stg_manager.add_object_static('lightmap-switch.xml', center_global, cluster_elev, 0, once=True)
# -- write .ac and .xml
building_lib.write(path_to_stg + file_name + ".ac", cl.objects, fg_elev,
building_lib.write(os.path.join(path_to_stg, file_name + ".ac"), cl.objects, fg_elev,
cluster_elev, cluster_offset, prepare_textures.roofs, stats)
_write_xml(path_to_stg, file_name, cl.objects, cluster_offset)
total_buildings_written += len(cl.objects)
......@@ -488,7 +491,7 @@ def process(coords_transform: coordinates.Transformation, fg_elev: utilities.FGE
handled_index += 1
logging.debug("Total number of buildings written to a cluster *.ac files: %d", total_buildings_written)
stg_manager.write()
stg_manager.write(file_lock)
stats.print_summary()
utilities.troubleshoot(stats)
......
......@@ -58,7 +58,7 @@ class ClusterContainer(object):
self.__len = self.max_grid.ix * self.max_grid.iy
self.stg_verb_type = stg_verb_type
logging.info("Generating clusters %s %s", min_point, max_point)
logging.info("Generating clusters %s %s for %s", min_point, max_point, stg_verb_type.name)
self._clusters = [[self._init_cluster(GridIndex(i, j)) for j in range(self.max_grid.iy)] for i in
range(self.max_grid.ix)]
......@@ -118,7 +118,7 @@ class ClusterContainer(object):
def write_statistics_for_buildings(self, clusters_name: str) -> None:
if parameters.log_level_debug_or_lower() and parameters.WRITE_CLUSTER_STATS:
my_file = open(parameters.PREFIX + os.sep + clusters_name + ".dat", "w")
my_file = open(os.path.join(parameters.PREFIX, clusters_name + ".dat"), "w")
for j in range(self.max_grid.iy):
for i in range(self.max_grid.ix):
cl = self._clusters[i][j]
......
......@@ -16,7 +16,7 @@ import utils.stg_io2 as stg
def _write_roads_eff(path_to_dir: str) -> None:
eff = open(path_to_dir + 'roads.eff', 'w')
eff = open(os.path.join(path_to_dir, 'roads.eff'), 'w')
eff.write(textwrap.dedent("""<?xml version="1.0" encoding="utf-8"?>
<PropertyList>
<name>roadsLM</name>
......@@ -37,7 +37,7 @@ def _write_roads_eff(path_to_dir: str) -> None:
def _write_citylm_eff(path_to_dir: str) -> None:
eff = open(path_to_dir + 'cityLM.eff', 'w')
eff = open(os.path.join(path_to_dir, 'cityLM.eff'), 'w')
eff.write(textwrap.dedent("""<?xml version="1.0" encoding="utf-8"?>
<PropertyList>
<name>cityLM</name>
......@@ -63,53 +63,51 @@ def _write_citylm_eff(path_to_dir: str) -> None:
def process(scenery_type: stg.SceneryType) -> None:
scenery_path = parameters.get_output_path()
scenery_path = os.path.join(parameters.get_output_path(), stg.scenery_directory_name(scenery_type))
scenery_path += os.sep + stg.scenery_directory_name(scenery_type)
if os.path.exists(scenery_path):
level_one_dirs = os.listdir(scenery_path)
level_two_dirs = list()
for level_one_dir in level_one_dirs:
sub_dir_path = scenery_path + os.sep + level_one_dir
sub_dir_path = os.path.join(scenery_path, level_one_dir)
if os.path.isdir(sub_dir_path):
level_two_dir_list = os.listdir(sub_dir_path)
for level_two_dir in level_two_dir_list:
if os.path.isdir(sub_dir_path + os.sep + level_two_dir):
level_two_dirs.append(sub_dir_path + os.sep + level_two_dir)
if os.path.isdir(os.path.join(sub_dir_path, level_two_dir)):
level_two_dirs.append(os.path.join(sub_dir_path, level_two_dir))
if not level_two_dirs:
logging.info("ERROR: The scenery path does not seem to have necessary sub-directories in %s", scenery_path)
else:
data_dir = util.assert_trailing_slash(parameters.PATH_TO_OSM2CITY_DATA)
# textures
source_dir = data_dir + "tex"
source_dir = os.path.join(parameters.PATH_TO_OSM2CITY_DATA, "tex")
content_list = os.listdir(source_dir)
if not os.path.exists(source_dir):
logging.error("The original tex dir seems to be missing: %s", source_dir)
sys.exit(1)
for level_two_dir in level_two_dirs:
if scenery_type in [stg.SceneryType.roads, stg.SceneryType.buildings]:
tex_dir = level_two_dir + os.sep + "tex"
tex_dir = os.path.join(level_two_dir, "tex")
if not os.path.exists(tex_dir):
os.mkdir(tex_dir)
logging.info("Copying texture stuff to sub-directory %s", tex_dir)
for content in content_list:
if scenery_type is stg.SceneryType.roads and content.startswith('road') \
and content.endswith('.png'):
shutil.copy(source_dir + os.sep + content, tex_dir)
shutil.copy(os.path.join(source_dir, content), tex_dir)
if scenery_type is stg.SceneryType.buildings and content.startswith('atlas') \
and content.endswith('.png'):
shutil.copy(source_dir + os.sep + content, tex_dir)
shutil.copy(os.path.join(source_dir, content), tex_dir)
if parameters.FLAG_2017_2:
for level_two_dir in level_two_dirs:
if scenery_type is stg.SceneryType.roads:
_write_roads_eff(level_two_dir + os.sep)
_write_roads_eff(level_two_dir)
elif scenery_type is stg.SceneryType.buildings:
_write_citylm_eff(level_two_dir + os.sep)
_write_citylm_eff(level_two_dir)
else:
# light-map effects
source_dir = data_dir + "lightmap"
source_dir = os.path.join(parameters.PATH_TO_OSM2CITY_DATA, "lightmap")
if not os.path.exists(source_dir):
logging.error("The original lightmap dir seems to be missing: %s", source_dir)
sys.exit(1)
......@@ -117,12 +115,12 @@ def process(scenery_type: stg.SceneryType) -> None:
logging.info("Copying lightmap stuff directory %s", level_two_dir)
content_list = os.listdir(source_dir)
for content in content_list:
shutil.copy(source_dir + os.sep + content, level_two_dir)
shutil.copy(os.path.join(source_dir, content), level_two_dir)
if parameters.TRAFFIC_SHADER_ENABLE and not parameters.FLAG_2017_2:
fg_root_dir = util.get_fg_root()
logging.info("Copying fgdata directory into $FG_ROOT (%s)", fg_root_dir)
source_dir = data_dir + "fgdata"
source_dir = os.path.join(parameters.PATH_TO_OSM2CITY_DATA, "fgdata")
copy_tree(source_dir, fg_root_dir)
else:
......
......@@ -6,7 +6,6 @@ Created on Fri Sep 6 19:37:03 2013
"""
import logging
import os
import random
import parameters
......@@ -15,7 +14,7 @@ from utils import utilities
from utils.vec2d import Vec2d
def myskel(out, b, stats: utilities.Stats, offset_xy=Vec2d(0, 0), offset_z=0., header=False, max_height=1e99):
def myskel(out, b, stats: utilities.Stats, offset_xy=Vec2d(0, 0), offset_z=0., header=False, max_height=1e99) -> bool:
vertices = b.X_outer
no = len(b.X_outer)
edges = [(i, i+1) for i in range(no-1)]
......@@ -28,6 +27,7 @@ def myskel(out, b, stats: utilities.Stats, offset_xy=Vec2d(0, 0), offset_z=0., h
angle = float(b.tags['roof:angle'])
else:
angle = random.uniform(parameters.BUILDING_SKEL_ROOFS_MIN_ANGLE, parameters.BUILDING_SKEL_ROOFS_MAX_ANGLE)
roof_height = 0.
while angle > 0:
roof_mesh = poly.roof_3D(angle * 3.1415 / 180.)
# roof.mesh.vertices
......@@ -44,7 +44,7 @@ def myskel(out, b, stats: utilities.Stats, offset_xy=Vec2d(0, 0), offset_z=0., h
except Exception as reason:
logging.debug("ERROR: while creating 3d roof (OSM_ID %s, %s)" % (b.osm_id, reason))
stats.roof_errors += 1
gp = parameters.PREFIX + os.sep + 'roof-error-%04i' % stats.roof_errors
gp = parameters.get_repl_prefix() + '_roof-error-%04i' % stats.roof_errors
if parameters.log_level_debug_or_lower():
utilities.write_one_gp(b, gp)
return False
......
......@@ -273,7 +273,7 @@ def get_OSM_file_name():
"""
Returns the path to the OSM File
"""
return PREFIX + os.sep + OSM_FILE
return os.path.join(PREFIX, OSM_FILE)
def get_repl_prefix():
......
......@@ -10,6 +10,7 @@ Created on Sun Sep 29 10:42:12 2013
import argparse
import logging
import math
import multiprocessing as mp
import os
from random import randint
from typing import List
......@@ -93,7 +94,7 @@ def _write_piers(stg_manager, replacement_prefix, clusters, coords_transform: co
else:
_write_pier_line(pier, obj, cl.center)
path = stg_manager.add_object_static(ac_file_name, center_tile, 0, 0)
file_name = path + os.sep + ac_file_name
file_name = os.path.join(path, ac_file_name)
f = open(file_name, 'w')
f.write(str(ac))
f.close()
......@@ -312,7 +313,7 @@ def _write_pier_line(pier, obj, offset):
obj.face(sideface, mat=0)
def process(coords_transform: coordinates.Transformation, fg_elev: utilities.FGElev) -> None:
def process(coords_transform: coordinates.Transformation, fg_elev: utilities.FGElev, file_lock: mp.Lock=None) -> None:
stats = utilities.Stats()
# -- prepare transformation to local coordinates
cmin, cmax = parameters.get_extent_global()
......@@ -350,7 +351,7 @@ def process(coords_transform: coordinates.Transformation, fg_elev: utilities.FGE
_write_boats(stg_manager, piers, coords_transform)
# -- write stg
stg_manager.write()
stg_manager.write(file_lock)
if __name__ == "__main__":
......
......@@ -8,6 +8,7 @@ Created on Sun Sep 29 10:42:12 2013
"""
import argparse
import logging
import multiprocessing as mp
import numpy as np
import os
from typing import List
......@@ -81,7 +82,7 @@ def _write(fg_elev: utilities.FGElev, stg_manager, replacement_prefix, clusters,
# using 0 elevation and 0 heading because ac-models already account for it
path = stg_manager.add_object_static(ac_file_name, center_tile, 0, 0)
file_name = path + os.sep + ac_file_name
file_name = os.path.join(path, ac_file_name)
f = open(file_name, 'w')
f.write(str(ac))
f.close()
......@@ -204,7 +205,7 @@ def _write_line(platform, fg_elev: utilities.FGElev, obj, offset) -> None:
obj.face(sideface, mat=0)
def process(coords_transform: coordinates.Transformation, fg_elev: utilities.FGElev) -> None:
def process(coords_transform: coordinates.Transformation, fg_elev: utilities.FGElev, file_lock: mp.Lock=None) -> None:
stats = utilities.Stats()
# -- prepare transformation to local coordinates
cmin, cmax = parameters.get_extent_global()
......@@ -238,7 +239,7 @@ def process(coords_transform: coordinates.Transformation, fg_elev: utilities.FGE
_write(fg_elev, stg_manager, replacement_prefix, clusters, coords_transform, stats)
# -- write stg
stg_manager.write()
stg_manager.write(file_lock)
if __name__ == "__main__":
......
......@@ -169,7 +169,7 @@ def _check_missed_input_textures(tex_prefix: str, registered_textures: List[Text
if filename[-4:] in [".jpg", ".png"]:
if filename[-7:-4] in ["_LM", "_MA"]:
continue
my_path = subdir + os.sep + filename
my_path = os.path.join(subdir, filename)
found = False
for registered in registered_textures:
if registered.filename == my_path:
......@@ -190,7 +190,7 @@ def _append_dynamic(facade_manager: FacadeManager, tex_prefix: str) -> None:
elif filename == ROOFS_DEFAULT_FILE_NAME:
continue
my_path = subdir + os.sep + filename
my_path = os.path.join(subdir, filename)
logging.info("Executing %s ", my_path)
try:
facade_manager.current_registered_in = my_path
......@@ -205,7 +205,7 @@ def _append_roofs(roof_manager: RoofManager, tex_prefix: str) -> None:
Argument roof_manager is used dynamically in execfile
."""
try:
file_name = tex_prefix + os.sep + ROOFS_DEFAULT_FILE_NAME
file_name = os.path.join(tex_prefix, ROOFS_DEFAULT_FILE_NAME)
roof_manager.current_registered_in = file_name
exec(compile(open(file_name).read(), file_name, 'exec'))
except Exception as e:
......@@ -243,12 +243,11 @@ def init(stats: util.Stats, create_atlas: bool=True) -> None:
global roofs
global atlas_file_name
my_tex_prefix = util.assert_trailing_slash(parameters.PATH_TO_OSM2CITY_DATA)
atlas_file_name = "tex" + os.sep + "atlas_facades"
my_tex_prefix_src = my_tex_prefix + 'tex.src'
atlas_file_name = os.path.join("tex", "atlas_facades")
my_tex_prefix_src = os.path.join(parameters.PATH_TO_OSM2CITY_DATA, 'tex.src')
Texture.tex_prefix = my_tex_prefix_src # need to set static variable so managers get full path
pkl_file_name = my_tex_prefix + "tex" + os.sep + "atlas_facades.pkl"
pkl_file_name = os.path.join(parameters.PATH_TO_OSM2CITY_DATA, "tex", "atlas_facades.pkl")
if create_atlas:
facades = FacadeManager('facade', stats)
......@@ -260,7 +259,6 @@ def init(stats: util.Stats, create_atlas: bool=True) -> None:
texture_list = facades.get_list() + roofs.get_list()
# warn for missed out textures
_check_missed_input_textures(my_tex_prefix_src, texture_list)
......@@ -269,7 +267,7 @@ def init(stats: util.Stats, create_atlas: bool=True) -> None:
now = datetime.datetime.now()
atlas_file_name += "_%04i%02i%02i" % (now.year, now.month, now.day)
_make_texture_atlas(texture_list, my_tex_prefix + atlas_file_name, '.png',
_make_texture_atlas(texture_list, os.path.join(parameters.PATH_TO_OSM2CITY_DATA, atlas_file_name), '.png',
lightmap=True, ambient_occlusion=parameters.BUILDING_FAKE_AMBIENT_OCCLUSION)
params = dict()
......
#===============================================================================
# ===============================================================================
# File : mesh.py
# Author : Olivier Teboul, olivier.teboul@ecp.fr
# Date : 31 july 2008, 14:03
# Class : Mesh
#===============================================================================
# ===============================================================================
import numpy as np
import roofs
......@@ -24,7 +24,7 @@ class Mesh:
* save and load (with a internal format)
"""
def __init__(self,vertices = [], faces = []):
def __init__(self,vertices=list(), faces=list()):
self.vertices = vertices
self.faces = faces
self.nv = len(self.vertices)
......@@ -114,24 +114,14 @@ class Mesh:
X = []
for p in self.vertices:
# s += "%f %f %f\n" % (p.x, p.y, p.z)
x = -(p.x - offset_xy.x)
y = -(p.y - offset_xy.y)
X.append([x, y])
s += "%f %f %f\n" % (y, p.z + offset_z, x)
# for p in self.vertices:
## s += "%f %f %f\n" % (p.x, p.y, p.z)
# x = -(p.x - offset_xy.x)
# y = -(p.y - offset_xy.y)
# print "nod ", x, y
#
# print "tot", X
# print "---"
s += "numsurf %i\n" % len(self.faces)
for face in self.faces:
face = np.roll(face[::-1], 1) # -- make outer edge the first
face = np.roll(face[::-1], 1) # -- make outer edge the first
s += "SURF 0x0\n"
s += "mat %i\n" % b.roof_mat
s += "refs %i\n" % len(face)
......@@ -139,13 +129,11 @@ class Mesh:
i = 0
for index in face:
s += "%i %1.3g %1.3g\n" % (index, uv[i, 0], uv[i, 1])
#print "UV coord", uv[i,0], uv[i,1]
# print "z=%g %g %g" % (self.vertices[index].z, uv[i,0], uv[i,1])
i += 1
return s
def to_out(self, out, b, offset_xy = Vec2d(0, 0), offset_z = 0., header = False):
def to_out(self, out, b, offset_xy=Vec2d(0, 0), offset_z=0., header = False) -> bool:
"""create 3d object"""
if header:
out.new_object(b.roof_ac_name, b.roof_texture.filename + '.png')
......@@ -153,21 +141,18 @@ class Mesh:
X = []
o = out.next_node_index()
for p in self.vertices:
# s += "%f %f %f\n" % (p.x, p.y, p.z)
x = -(p.x - offset_xy.x)
y = -(p.y - offset_xy.y)
X.append([x, y])
out.node(y, p.z + offset_z, x)
for face in self.faces:
face = np.roll(face[::-1], 1) # -- make outer edge the first
face = np.roll(face[::-1], 1) # -- make outer edge the first
uv = roofs.face_uv(face, np.array(X), b.roof_texture)
i = 0
l = []
for index in face:
l.append((o + index, uv[i, 0], uv[i, 1]))
#print "UV coord", uv[i,0], uv[i,1]
# print "z=%g %g %g" % (self.vertices[index].z, uv[i,0], uv[i,1])
i += 1
out.face(l)
......
......@@ -98,8 +98,8 @@ class Sector:
def move_first_point(self, d):
""" move the first point along the first half line with respect to its speed """
cosAlpha = self.edge.u*self.h1.d
alpha = 0 # if cosAlpha outside allowed range, then assume max value (= 1) and therefore acos(1) = 0
if -1. <= cosAlpha <= .1:
alpha = 0.0000001 # if cosAlpha outside allowed range, then assume max value (= 1) and therefore acos(1) = 0
if -1. <= cosAlpha <= 1.:
alpha = math.acos(cosAlpha)
s = d*float(self.edge.w)/math.sin(alpha)
return self.h1.getPoint(s)
......@@ -20,6 +20,8 @@ import argparse
from enum import IntEnum, unique
import logging
import math
import multiprocessing as mp
import os
import time
from typing import Dict, List, Tuple
import unittest
......@@ -263,7 +265,8 @@ def _get_cable_vertices(pylon_model: str, direction_type: PylonDirectionType) ->
elif "tension" in pylon_model:
return _create_rail_stop_tension()
else:
raise Exception(msg='Pylon model not found for creating cable vertices: {}'.format(pylon_model))
text = 'Pylon model not found for creating cable vertices: {}'.format(pylon_model)
raise Exception(text)
@unique
......@@ -1484,7 +1487,7 @@ def _write_cable_clusters(cluster_container: cluster.ClusterContainer, coords_tr
cable.translate_vertices_relative(cluster_x, cluster_y, cluster_elevation)
ac_file_lines.append(cable.make_ac_entry(0)) # material is 0-indexed
with open(path_to_stg + cluster_filename + ".ac", 'w') as f:
with open(os.path.join(path_to_stg, cluster_filename + ".ac"), 'w') as f:
f.write("\n".join(ac_file_lines))
......@@ -1547,7 +1550,7 @@ def _optimize_catenary(half_distance_pylons: float, max_value: float, sag: float
"""
my_variation = sag * max_variation
try:
for a in range(1, max_value):
for a in range(1, int(max_value)):
value = a * math.cosh(float(half_distance_pylons)/a) - a # float() needed to make sure result is float
if (value >= (sag - my_variation)) and (value <= (sag + my_variation)):
return a, value
......@@ -1771,7 +1774,7 @@ def _fetch_osm_file_data() -> Tuple[Dict[int, osmparser.Node], Dict[int, osmpars
def process(coords_transform: coordinates.Transformation, fg_elev: utilities.FGElev,
stg_entries: List[stg_io2.STGEntry]) -> None:
stg_entries: List[stg_io2.STGEntry], file_lock: mp.Lock=None) -> None:
# Transform to real objects
logging.info("Transforming OSM data to Line and Pylon objects")
......@@ -1898,7 +1901,7 @@ def process(coords_transform: coordinates.Transformation, fg_elev: utilities.FGE
for tank in storage_tanks:
tank.make_stg_entry(stg_manager)
stg_manager.write()
stg_manager.write(file_lock)
if __name__ == "__main__":
......
......@@ -77,6 +77,8 @@ import argparse
import enum
import logging
import math
import multiprocessing as mp
import os
import random
import textwrap
from typing import Dict, List, Optional
......@@ -1007,7 +1009,7 @@ class Roads(object):
ac.add_label(' %i h=%1.1f' % (the_node.osm_id, the_node.h_add), -anchor.y, e, -anchor.x, scale=1.)
path_to_stg = stg_manager.add_object_static(file_name + '.ac', Vec2d(self.transform.toGlobal((0, 0))), 0, 0)
ac.write(path_to_stg + file_name + '.ac')
ac.write(os.path.join(path_to_stg, file_name + '.ac'))
def debug_print_refs_of_way(self, way_osm_id):