def polygons(): try: Singleton("polygons").kill() polygons_main.submain() except Exception: import traceback, warnings warnings.warn(":warning: exception caught") traceback.print_exc() print(errormessage) else: print(donemessage) finally: Singleton("polygons").kill()
def main(vertex_list=None): '''Input: list of vertices representing the Roadmap Output: List of all Polygon2Ds representing Lots, List of all Polygon2Ds representing Blocks List of all Polygon2Ds which are too large to be Lots Polygon2D representing the road-network''' singleton = Singleton("polygons") if vertex_list is None: from procedural_city_generation.additional_stuff import jsontools vertex_list = jsontools.reconstruct() print "Reconstructing of data structure finished" import os import procedural_city_generation path = os.path.dirname(procedural_city_generation.__file__) with open(path + "/temp/border.txt", "r") as f: border = f.read() border = [int(x) for x in border.split(" ") if x is not ''] print "Extracting Polygon2Ds" from procedural_city_generation.polygons import construct_polygons polylist = construct_polygons.getPolygon2Ds(vertex_list) print "Polygon2Ds extracted" #TODO: DISCUSS from procedural_city_generation.polygons.getLots import getLots as getLots "%s vertices" % (len(vertex_list)) polygons = getLots(polylist, vertex_list) print "Lots found" if singleton.plotbool: print "Plotting..." if gui is None: import matplotlib.pyplot as plt for g in polygons: g.selfplot(plt=plt) plt.show() else: i = 0 for g in polygons: g.selfplot(plt=gui) i += 1 if i % singleton.plot_counter == 0: gui.update() gui.update() import pickle with open( os.path.dirname(procedural_city_generation.__file__) + "/outputs/polygons.txt", "w") as f: s = pickle.dumps(polygons) f.write(s) return 0
def main(vertex_list=None): """Input: list of vertices representing the Roadmap Output: List of all Polygon2Ds representing Lots, List of all Polygon2Ds representing Blocks List of all Polygon2Ds which are too large to be Lots Polygon2D representing the road-network""" singleton = Singleton("polygons") if vertex_list is None: from procedural_city_generation.additional_stuff import pickletools vertex_list = pickletools.reconstruct(singleton.input_name) print("Reconstructing of data structure finished") path = os.path.dirname(procedural_city_generation.__file__) with open( os.path.join(path, "temp", singleton.input_name + "_heightmap.txt"), "r") as f: border = [int(x) for x in f.read().split("_")[-2:] if x is not ''] print("Extracting Polygon2Ds") polylist = construct_polygons.getPolygon2Ds(vertex_list) print("Polygon2Ds extracted") #TODO: DISCUSS "%s vertices" % (len(vertex_list)) polygons = getLots(polylist, vertex_list) print("Lots found") sorted if singleton.plotbool: print("Plotting...") if gui is None: import matplotlib.pyplot as plt for g in polygons: g.selfplot(plt=plt) plt.show() else: i = 0 for g in polygons: g.selfplot(plt=gui) i += 1 if i % singleton.plot_counter == 0: gui.update() gui.update() with open( os.path.join(os.path.dirname(procedural_city_generation.__file__), "temp", singleton.input_name + "_polygons.txt"), "wb") as f: import sys if sys.version[0] == "2": s = pickle.dumps(polygons) f.write(s) else: pickle.dump(polygons, f) return 0
def building_generation(): try: building_generation_main.submain() except Exception: import traceback, warnings warnings.warn(":warning: exception caught") traceback.print_exc() print(errormessage) else: print(donemessage) finally: Singleton("building_generation").kill()
def building_generation(): import pickle try: with open(path + "/outputs/polygons.txt", 'r') as f: polygons = pickle.loads(f.read()) building_generation_main.main(polygons) from procedural_city_generation.additional_stuff.Singleton import Singleton Singleton("building_generation").kill() except IOError: print "Input could not be located. Try to run the previous program in the chain first." return 0 print donemessage
def building_generation(): import pickle # try: if 1==1: with open(path+"/outputs/polygons.txt",'r') as f: polygons=pickle.loads(f.read()) building_generation_main.main(polygons) Singleton("building_generation").kill() # except IOError: # print "Input could not be located. Try to run the previous program in the chain first." # return 0 print donemessage
def save_params(): for i,param in enumerate(params): it=table.item(i,3).text() try: it=eval(str(it)) except: it=str(it) param.setValue(it) Singleton(submodule).kill() jsonFromParams(os.getcwd()+"/procedural_city_generation/inputs/"+submodule+".conf",params) print "Save successful" save_button.hide() table.hide() print UI.donemessage
def setBuilding_generationGUI(gui): building_generation_main.gui = gui Singleton("building_generation").kill()
def polygons(): polygons_main.main(None) Singleton("polygons").kill() print donemessage
def roadmap(): roadmap_main.main() Singleton("roadmap").kill() print donemessage
def setPolygonsGUI(gui): polygons_main.gui = gui Singleton("polygons").kill()
def setRoadmapGUI(gui): roadmap_main.gui = gui Singleton("roadmap").kill()
def config(): """ Starts the program up with all necessary things. Reads the inputs, creates the Singleton objects properly, sets up the heightmap for later, makes sure all Vertices in the axiom have the correct neighbor. Could need a rework in which the Singletons are unified and not broken as they are now. Returns ------- variables : Variables object Singleton with all numeric values which are not to be changed at runtime singleton.global_lists : singleton.global_lists object Singleton with the Global Lists which will be altered at runtime """ import json from collections import namedtuple import os import procedural_city_generation from procedural_city_generation.additional_stuff.Singleton import Singleton path = os.path.dirname(procedural_city_generation.__file__) singleton = Singleton("roadmap") #Creates Singleton-Variables object from namedtuple from procedural_city_generation.roadmap.Vertex import Vertex, set_plotbool #Creates Vertex objects from coordinates singleton.axiom = [ Vertex(np.array([float(x[0]), float(x[1])])) for x in singleton.axiom ] set_plotbool(singleton.plot) #Finds the longest possible length of a connection between to vertices singleton.maxLength = max(singleton.radiallMax, singleton.gridlMax, singleton.organiclMax, singleton.minor_roadlMax, singleton.seedlMax) import os from procedural_city_generation.roadmap.config_functions.input_image_setup import input_image_setup singleton.img, singleton.img2 = input_image_setup( path + "/inputs/rule_pictures/" + singleton.rule_image_name, path + "/inputs/density_pictures/" + singleton.density_image_name) from procedural_city_generation.roadmap.config_functions.find_radial_centers import find_radial_centers singleton.center = find_radial_centers(singleton) singleton.center = [ np.array([ singleton.border[0] * ((x[1] / singleton.img.shape[1]) - 0.5) * 2, singleton.border[1] * (((singleton.img.shape[0] - x[0]) / singleton.img.shape[0]) - 0.5) * 2 ]) for x in singleton.center ] from procedural_city_generation.roadmap.config_functions.setup_heightmap import setup_heightmap setup_heightmap(singleton, path) with open(path + "/temp/border.txt", 'w') as f: f.write(str(singleton.border[0]) + " " + str(singleton.border[1])) singleton.global_lists = Global_Lists() singleton.global_lists.vertex_list.extend(singleton.axiom) singleton.global_lists.coordsliste = [ x.coords for x in singleton.global_lists.vertex_list ] def setNeighbours(vertex): """ Correctly Sets up the neighbors for a vertex from the axiom. Parameters ---------- vertex : vertex Object """ d = np.inf neighbour = None for v in singleton.axiom: if v is not vertex: dneu = np.linalg.norm(v.coords - vertex.coords) if dneu < d: d = dneu neighbour = v vertex.neighbours = [neighbour] for k in singleton.axiom: setNeighbours(k) from scipy.spatial import cKDTree singleton.global_lists.tree = cKDTree(singleton.global_lists.coordsliste, leafsize=160) return singleton
def polygons(): from procedural_city_generation.polygons import main as polygon_main polygon_main.main(None) from procedural_city_generation.additional_stuff.Singleton import Singleton Singleton("polygons").kill()
from __future__ import division import numpy as np from procedural_city_generation.polygons.Polygon2D import Edge, Polygon2D from procedural_city_generation.additional_stuff.Singleton import Singleton singleton = Singleton("polygons") def p_in_poly(poly, point): x, y = point n = len(poly) inside = False p1x, p1y = poly[0][0] for i in range(n + 1): p2x, p2y = poly[i % n][0] if y > min(p1y, p2y): if y <= max(p1y, p2y): if x <= max(p1x, p2x): if p1y != p2y: xinters = (y - p1y) * (p2x - p1x) / (p2y - p1y) + p1x if p1x == p2x or x <= xinters: inside = not inside p1x, p1y = p2x, p2y return inside def getBlock(wedges, vertex_list): '''Calculate block to be divided into lots, as well as street polygons'''
def visualization(): os.system("blender --python " + path + "/visualization/blenderize.py") from procedural_city_generation.additional_stuff.Singleton import Singleton Singleton("visualization").kill()
def roadmap(): from procedural_city_generation.roadmap import main as roadmap_main roadmap_main.main() from procedural_city_generation.additional_stuff.Singleton import Singleton Singleton("roadmap").kill()
def main(polylist): singleton = Singleton("building_generation") """ Accepts a list of procedural_city_generation.polygons.Polygon2D objects and constructs buildings on top of these. The buildings consist of Polygon3D objects, which are saved to /outputs/polygons.txt. See merger module for more details. Parameters ---------- polylist : List<procedural_city_generation.polygons.Polygon2D> """ #TODO: Discuss with lenny how we get the largest polygon out. maxl = 0 index = 0 for i in range(len(polylist)): if len(polylist[i].vertices ) > maxl and polylist[i].poly_type == 'vacant': index = i maxl = len(polylist[i].vertices) polylist.pop(index) gb = BuildingHeight() surface = Surface() textures = updateTextures() texGetter = textureGetter(textures) roadtexture = texGetter.getTexture('Road', 50) polygons = [] for poly in polylist: #Determines the floortexture. If the Polygon3D is not a building, there is obviously no need for walls/windows/roofs if poly.poly_type == "road": floortexture = roadtexture elif poly.poly_type == "vacant": floortexture = texGetter.getTexture('Floor', 0) elif poly.poly_type == "lot": #If poly is a building, get all other necessary textures and numerical values center = sum(poly.vertices) / len(poly.vertices) buildingheight = gb.getBuildingHeight(center) floortexture = texGetter.getTexture('Floor', buildingheight) windowtexture = texGetter.getTexture('Window', buildingheight) walltexture = texGetter.getTexture('Wall', buildingheight) rooftexture = texGetter.getTexture('Roof', buildingheight) floorheight = np.random.uniform(singleton.floorheight_min, singleton.floorheight_max) windowwidth = random.uniform(singleton.windowwidth_min, singleton.windowwidth_max) housebool = True if buildingheight < singleton.house_height else False if housebool: windowheight = random.uniform(singleton.windowheight_min, singleton.windowheight_max_house) windowdist = random.uniform( 0, windowwidth + singleton.windowdist_max_house) else: windowheight_max = singleton.windowheight_max_not_house if singleton.windowheight_max_not_house != 0 else floorheight windowheight = random.uniform(singleton.windowheight_min, windowheight_max) windowdist = random.uniform( singleton.windowdist_min_not_house, windowwidth + singleton.windowdist_max_not_house) base_h_low, base_h_high = surface.getSurfaceHeight(poly.vertices) #TODO: Fix after lennys fix, #Scales and Translates floor if poly.is_convex: walls = walls_from_poly(poly) else: walls = walls_from_poly(poly) #TODO: make abhaengig von height if housebool: factor = random.uniform(singleton.scalefactor_min_house, singleton.scalefactor_max_house) if not poly.is_convex: walls = scaletransform(walls, factor) else: walls = scale(walls, factor) else: factor = random.uniform(singleton.scalefactor_min_not_house, singleton.scalefactor_max_not_house) if not poly.is_convex: walls = scaletransform(walls, factor) else: walls = scale(walls, factor) roofwalls = copy(walls) #Creates floorplan walls = randomcut(walls, housebool) #Floor-height is found and the Building is vertically split. #TODO: Constants in some sort of conf file plan = verticalsplit(buildingheight, floorheight) #Random, decides if ledges will be scaled nach aussen ledgefactor = 1.0 if random.uniform(0, 1) > singleton.prob_ledge: ledgefactor = random.uniform(singleton.ledgefactor_min, singleton.ledgefactor_max) #Scales the walls to the outside ledge = scale(walls, ledgefactor) #Keeps track of height where we are currently building currentheight = base_h_high #Get a list of windows for each floor windows = scale(walls, 1.01) list_of_currentheights = [] #Goes through the plan list for element in plan: if element == 'b' or element == 'f': list_of_currentheights.append(currentheight) currentheight += floorheight elif element == 'l': if ledgefactor != 1: polygons.append( buildledge(ledge, currentheight, currentheight + floorheight / 10, rooftexture)) currentheight += floorheight / 10. elif element == 'r': if ledgefactor == 1: polygons.extend( roof(walls, roofwalls, currentheight, housebool, rooftexture, texGetter.getTexture("Roof", buildingheight))) polygons.append( buildwalls(walls, base_h_low, currentheight, walltexture)) polygons.append( get_windows(windows, list_of_currentheights, floorheight, windowwidth, windowheight, windowdist, windowtexture)) else: print "Polygon3D.poly_type not understood" #Builds the floor Polygon polygons.append( Polygon3D([np.array([x[0], x[1], 0]) for x in poly.vertices], [range(len(poly.vertices))], floortexture)) mergedpolys = merge_polygons(polygons, textures) return 0
import sys,os import numpy as np import procedural_city_generation path=os.path.dirname(procedural_city_generation.__file__) from procedural_city_generation.building_generation.cuts import * from procedural_city_generation.building_generation.building_tools import * from procedural_city_generation.building_generation.roofs import roof from procedural_city_generation.building_generation.Surface import Surface from procedural_city_generation.building_generation.BuildingHeight import BuildingHeight from procedural_city_generation.building_generation.updateTextures import updateTextures, textureGetter from procedural_city_generation.building_generation.getFoundation import getFoundation from procedural_city_generation.building_generation.merge_polygons import merge_polygons from procedural_city_generation.additional_stuff.Singleton import Singleton from copy import copy singleton=Singleton("building_generation") def main(polylist): """ Accepts a list of procedural_city_generation.polygons.Polygon2D objects and constructs buildings on top of these. The buildings consist of Polygon3D objects, which are saved to /outputs/polygons.txt. See merger module for more details. Parameters ---------- polylist : List<procedural_city_generation.polygons.Polygon2D> """ #TODO: Discuss with lenny how we get the largest polygon out.
def visualization(): os.system( "blender --python Z:/GithubProjects/The-Conurbation-Algorithm/src/procedural_city_generation/visualization/blenderize.py") from procedural_city_generation.additional_stuff.Singleton import Singleton Singleton("visualization").kill()
def main(): """ Reads list of procedural_city_generation.polygons.Polygon2D objects from file and constructs buildings on top of these. The buildings consist of Polygon3D objects, which are saved to /outputs/polygons.txt. See merger module for more details. """ import procedural_city_generation path = os.path.dirname(procedural_city_generation.__file__) from procedural_city_generation.building_generation.cuts import scale, scaletransform, walls_from_poly, randomcut from procedural_city_generation.building_generation.building_tools import Polygon3D, verticalsplit, buildledge, buildwalls, get_windows from procedural_city_generation.building_generation.roofs import roof from procedural_city_generation.building_generation.Surface import Surface from procedural_city_generation.building_generation.BuildingHeight import BuildingHeight from procedural_city_generation.building_generation.updateTextures import updateTextures, textureGetter from procedural_city_generation.building_generation.merge_polygons import merge_polygons from procedural_city_generation.additional_stuff.Singleton import Singleton from copy import copy singleton = Singleton("building_generation") import pickle with open(path + "/temp/" + singleton.input_name + "_polygons.txt", "rb") as f: polylist = pickle.loads(f.read()) if gui is None: import matplotlib.pyplot as plt #TODO: Discuss with lenny how we get the largest polygon out. maxl = 0 index = 0 for i in range(len(polylist)): if len(polylist[i].vertices ) > maxl and polylist[i].poly_type == 'vacant': index = i maxl = len(polylist[i].vertices) polylist.pop(index) gb = BuildingHeight(singleton.input_name) surface = Surface(singleton.input_name) textures = updateTextures() texGetter = textureGetter(textures) roadtexture = texGetter.getTexture('Road', 50) polygons = [] counter = 0 for poly in polylist: #Determines the floortexture. If the Polygon3D is not a building, there is obviously no need for walls/windows/roofs if poly.poly_type == "road": floortexture = roadtexture elif poly.poly_type == "vacant": floortexture = texGetter.getTexture('Floor', 0) elif poly.poly_type == "lot": #If poly is a building, get all other necessary textures and numerical values center = sum(poly.vertices) / len(poly.vertices) buildingheight = gb.getBuildingHeight(center) floortexture = texGetter.getTexture('Floor', buildingheight) windowtexture = texGetter.getTexture('Window', buildingheight) walltexture = texGetter.getTexture('Wall', buildingheight) rooftexture = texGetter.getTexture('Roof', buildingheight) floorheight = np.random.uniform(singleton.floorheight_min, singleton.floorheight_max) windowwidth = np.random.uniform(singleton.windowwidth_min, singleton.windowwidth_max) housebool = True if buildingheight < singleton.house_height else False if housebool: windowheight = np.random.uniform( singleton.windowheight_min, singleton.windowheight_max_house) windowdist = np.random.uniform( 0, windowwidth + singleton.windowdist_max_house) else: windowheight_max = singleton.windowheight_max_not_house if singleton.windowheight_max_not_house != 0 else floorheight windowheight = np.random.uniform(singleton.windowheight_min, windowheight_max) windowdist = np.random.uniform( singleton.windowdist_min_not_house, windowwidth + singleton.windowdist_max_not_house) base_h_low, base_h_high = surface.getSurfaceHeight(poly.vertices) #TODO: Fix after lennys fix, #Scales and Translates floor if poly.is_convex: walls = walls_from_poly(poly) else: walls = walls_from_poly(poly) #TODO: make abhaengig von height if housebool: factor = np.random.uniform(singleton.scalefactor_min_house, singleton.scalefactor_max_house) if not poly.is_convex: walls = scaletransform(walls, factor) else: walls = scale(walls, factor) else: factor = np.random.uniform(singleton.scalefactor_min_not_house, singleton.scalefactor_max_not_house) if not poly.is_convex: walls = scaletransform(walls, factor) else: walls = scale(walls, factor) roofwalls = copy(walls) #Creates floorplan walls = randomcut(walls, housebool) if singleton.plotbool: walls.selfplot() #Floor-height is found and the Building is vertically split. #TODO: Constants in some sort of conf file plan = verticalsplit(buildingheight, floorheight) #Random, decides if ledges will be scaled nach aussen ledgefactor = 1.0 if np.random.uniform(0, 1) > singleton.prob_ledge: ledgefactor = np.random.uniform(singleton.ledgefactor_min, singleton.ledgefactor_max) #Scales the walls to the outside ledge = scale(walls, ledgefactor) #Keeps track of height where we are currently building currentheight = base_h_high #Get a list of windows for each floor windows = scale(walls, 1.01) list_of_currentheights = [] #Goes through the plan list for element in plan: if element == 'b' or element == 'f': list_of_currentheights.append(currentheight) currentheight += floorheight elif element == 'l': if ledgefactor != 1: polygons.append( buildledge(ledge, currentheight, currentheight + floorheight / 10, rooftexture)) currentheight += floorheight / 10. elif element == 'r': if ledgefactor == 1: polygons.extend( roof(walls, roofwalls, currentheight, housebool, rooftexture, texGetter.getTexture("Roof", buildingheight))) polygons.append( buildwalls(walls, base_h_low, currentheight, walltexture)) polygons.append( get_windows(windows, list_of_currentheights, floorheight, windowwidth, windowheight, windowdist, windowtexture)) else: print("Polygon3D.poly_type not understood") if singleton.plotbool: if counter % singleton.plot_counter == 0: if gui is not None: gui.update() else: plt.draw() counter += 1 #Builds the floor Polygon polygons.append( Polygon3D([np.array([x[0], x[1], 0]) for x in poly.vertices], [range(len(poly.vertices))], floortexture)) #Uncomment these lines if you are interested in working with .obj (Wavefront) format. #See Github issues concerning this format #from procedural_city_generation.additional_stuff.Wavefront import Wavefront #Wavefront([x.name for x in textures],polygons) mergedpolys = merge_polygons(polygons, textures, singleton.output_name) return 0
def building_generation(): building_generation_main.main() Singleton("building_generation").kill() print(donemessage)
from __future__ import division import numpy as np import random import math from procedural_city_generation.roadmap.Vertex import Vertex from procedural_city_generation.additional_stuff.rotate import rotate from procedural_city_generation.additional_stuff.Singleton import Singleton singleton = Singleton("roadmap") def radial(center, vertex, b): #Sammelt Numerische Werte aus Variables-Objekt pForward = singleton.radialpForward pTurn = singleton.radialpTurn lMin = singleton.radiallMin lMax = singleton.radiallMax #Berechnet Radialvector und Vektor des letzten Weges zu diesem Punkt radialvector = vertex.coords - center previous_vector = np.array(vertex.coords - vertex.neighbours[len(vertex.neighbours) - 1].coords) previous_vector = previous_vector / np.linalg.norm(previous_vector) suggested_vertices = [] weiter = False
def config(): """ Starts the program up with all necessary things. Reads the inputs, creates the Singleton objects properly, sets up the heightmap for later, makes sure all Vertices in the axiom have the correct neighbor. Could need a rework in which the Singletons are unified and not broken as they are now. Returns ------- variables : Variables object Singleton with all numeric values which are not to be changed at runtime singleton.global_lists : singleton.global_lists object Singleton with the Global Lists which will be altered at runtime """ import json from collections import namedtuple import os import procedural_city_generation from procedural_city_generation.additional_stuff.Singleton import Singleton path=os.path.dirname(procedural_city_generation.__file__) singleton=Singleton("roadmap") #Creates Singleton-Variables object from namedtuple from procedural_city_generation.roadmap.Vertex import Vertex, set_plotbool #Creates Vertex objects from coordinates singleton.axiom=[Vertex(np.array([float(x[0]),float(x[1])])) for x in singleton.axiom] set_plotbool(singleton.plot) #Finds the longest possible length of a connection between to vertices singleton.maxLength=max(singleton.radiallMax,singleton.gridlMax,singleton.organiclMax,singleton.minor_roadlMax,singleton.seedlMax) import os from procedural_city_generation.roadmap.config_functions.input_image_setup import input_image_setup singleton.img,singleton.img2=input_image_setup(path+"/inputs/rule_pictures/"+singleton.rule_image_name, path+"/inputs/density_pictures/"+singleton.density_image_name) from procedural_city_generation.roadmap.config_functions.find_radial_centers import find_radial_centers singleton.center=find_radial_centers(singleton) singleton.center= [np.array([singleton.border[0]*((x[1]/singleton.img.shape[1])-0.5)*2,singleton.border[1]*(((singleton.img.shape[0]-x[0])/singleton.img.shape[0])-0.5)*2]) for x in singleton.center] from procedural_city_generation.roadmap.config_functions.setup_heightmap import setup_heightmap setup_heightmap(singleton,path) with open(path+"/temp/border.txt",'w') as f: f.write(str(singleton.border[0])+" "+str(singleton.border[1])) singleton.global_lists=Global_Lists() singleton.global_lists.vertex_list.extend(singleton.axiom) singleton.global_lists.coordsliste=[x.coords for x in singleton.global_lists.vertex_list] def setNeighbours(vertex): """ Correctly Sets up the neighbors for a vertex from the axiom. Parameters ---------- vertex : vertex Object """ d=np.inf neighbour=None for v in singleton.axiom: if v is not vertex: dneu=np.linalg.norm(v.coords-vertex.coords) if dneu<d: d=dneu neighbour=v vertex.neighbours=[neighbour] for k in singleton.axiom: setNeighbours(k) from scipy.spatial import cKDTree singleton.global_lists.tree=cKDTree(singleton.global_lists.coordsliste, leafsize=160) return singleton