source: subversion/applications/rendering/parking/osray/osray_geom.py @ 22386

Last change on this file since 22386 was 22368, checked in by kdrangmeister, 9 years ago

roads as network - layer heights averaged

  • Property svn:mime-type set to text/plain
File size: 5.8 KB
Line 
1# -*- coding: utf-8 -*-
2
3#import string, cgi, time
4#from os import curdir, sep
5#from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
6#import urlparse
7#import osray
8import math
9import random
10import re
11
12def avg(a,b): return (a+b)/2.0
13def swap(tuple): return (tuple[1],tuple[0])
14
15#
16# parsing postgis strings
17#
18
19def WKT_to_point(pointstring):
20    pointstring = pointstring[6:] # cut off the "POINT("
21    pointstring = pointstring[:-1] # cut off the ")"
22    latlon = pointstring.split(' ')
23    return (latlon[0],latlon[1])
24
25def WKT_to_line(linestring):
26    linestring = linestring[11:] # cut off the "LINESTRING("
27    linestring = linestring[:-1] # cut off the ")"
28    points = linestring.split(',')
29    numpoints = len(points)
30    line=[]
31    for i,point in enumerate(points):
32        x,y = point.split(' ')
33        #x=x.strip('(').strip(')')
34        #y=y.strip('(').strip(')')
35        line.append((x,y))
36    return line
37
38def WKT_to_polygon(polygonstring):
39    polygonstring = polygonstring[8:] # cut off the "POLYGON("
40    polygonstring = polygonstring[:-1] # cut off the ")"
41    points = polygonstring.split(',') #.strip('(').strip(')')
42    numpoints = len(points)
43    polygon=[]
44    for i,point in enumerate(points):
45        x,y = point.split(' ')
46        x=x.strip('(').strip(')')
47        y=y.strip('(').strip(')')
48        polygon.append((x,y))
49    return polygon
50
51#
52# string stuff to handle bbox strings
53#
54def bbox_string(xmin,ymin,xmax,ymax):
55    return str(xmin)+" "+str(ymin)+","+str(xmax)+" "+str(ymax)
56
57def bbox_format_3_to_1_comma(bbox):
58    coords = bbox.split(',')
59    if len(coords)!=4:
60        raise 'wrong bbox format: '+bbox
61    return coords[0]+" "+coords[1]+","+coords[2]+" "+coords[3]
62   
63def coords_from_bbox(bbox):
64    bbox = bbox.replace(' ',',')
65    coordslist = map(lambda coord: float(coord), bbox.split(','))
66    return tuple(coordslist)
67
68def scale_coords(xmin,ymin,xmax,ymax,scale):
69    xmid = avg(xmin,xmax)
70    ymid = avg(ymin,ymax)
71    xradius = xmid-xmin
72    yradius = ymid-ymin
73    xradius *= scale
74    yradius *= scale
75    xmin = xmid-xradius
76    xmax = xmid+xradius
77    ymin = ymid-yradius
78    ymax = ymid+yradius
79    return (xmin,ymin,xmax,ymax)
80
81def scale_bbox(bbox,scale):
82    xmin,ymin,xmax,ymax = coords_from_bbox(bbox)
83    xmin,ymin,xmax,ymax = scale_coords(xmin,ymin,xmax,ymax,scale)
84    return bbox_string(xmin,ymin,xmax,ymax)
85
86#
87# mathematical calculations
88#
89def num2deg(xtile, ytile, zoom):
90    n = 2.0 ** zoom
91    lon_deg = xtile / n * 360.0 - 180.0
92    lat_rad = math.atan(math.sinh(math.pi * (1 - 2 * ytile / n)))
93    lat_deg = math.degrees(lat_rad)
94    return(lat_deg, lon_deg)
95
96def num2bbox(xtile, ytile, zoom):
97    bottomleft = swap(num2deg(xtile,ytile+1,zoom))
98    topright = swap(num2deg(xtile+1,ytile,zoom))
99    bbox = str(bottomleft)[1:-1].replace(',',' ')+","+str(topright)[1:-1].replace(',',' ')
100    return bbox
101
102def shift_by_meters(lat, lon, brng, d):
103    R = 6371000.0 # earth's radius in m
104    lat=math.radians(lat)
105    lon=math.radians(lon)
106    lat2 = math.asin( math.sin(lat)*math.cos(d/R) +
107                      math.cos(lat)*math.sin(d/R)*math.cos(brng))
108    lon2 = lon + math.atan2(math.sin(brng)*math.sin(d/R)*math.cos(lat),
109                             math.cos(d/R)-math.sin(lat)*math.sin(lat2))
110    lat2=math.degrees(lat2)
111    lon2=math.degrees(lon2)
112    return [lat2,lon2]
113
114def calc_bearing(x1,y1,x2,y2,side):
115    Q = complex(x1,y1)
116    R = complex(x2,y2)
117    v = R-Q
118    if side=='left':
119        v=v*complex(0,1);
120    elif side=='right':
121        v=v*complex(0,-1);
122    else:
123        raise TypeError('side must be left or right')
124    #v=v*(1/abs(v)) # normalize
125    angl = angle(v) # angle (radians) (0°=right, and counterclockwise)
126    bearing = math.pi/2.0-angl # (0°=up, and clockwise)
127    return bearing
128
129def random_range_seed(a,b,s):
130    random.seed(s)
131    return random.uniform(a,b)
132
133#
134# parsing OSM strings
135#
136def parse_length_in_meters(length,default):
137    units={
138           'm':1.0, 'metres':1.0, 'meters':1.0, 'metre':1.0, 'meter':1.0,
139           'km':1000.0,
140           'ft':0.3,
141           'yd':1.1,
142           }
143    parsed = re.split('(\d*[,.]?\d+)',length)
144    if len(parsed)!=3:
145        print "### unparsable length '{0}', parsed: {1}".format(length,parsed)
146        return default
147    prefix = parsed[0].strip()
148    if prefix!='':
149        print "### unknown prefix '{0}' in length '{1}'".format(prefix,length)
150        return default
151    unit = parsed[2].strip().lower()
152    if unit=='': unit='m' # defaults to m
153    factor = units.get(unit,0.0)
154    if factor==0.0:
155        print "### unknown unit '{0}' in length '{1}'".format(unit,length)
156    meter = float(parsed[1])*factor
157    return meter
158
159def parse_int_safely(intstring,default):
160    """ parses a intstring and returns an int - any error: returns default """
161    if intstring==None:
162        return default
163    try:
164        layer = int(intstring)
165    except ValueError:
166        print "### unknown integer '{0}'".format(intstring)
167        layer = default
168    return layer
169
170def parse_float_safely(floatstring,default):
171    if floatstring==None:
172        return default
173    try:
174        f = float(floatstring)
175    except ValueError:
176        print "### unknown float '{0}'".format(floatstring)
177        f = default
178    return f
179
180def parse_yes_no_safely(boolstring,default):
181    if boolstring == None:
182        return default
183    boolstring = boolstring.upper()
184    if boolstring == 'YES':
185        return True
186    if boolstring == 'NO':
187        return False
188    if boolstring == '1':
189        return True
190    if boolstring == '0':
191        return False
192    if boolstring == 'TRUE':
193        return True
194    if boolstring == 'FALSE':
195        return False
196    return default
Note: See TracBrowser for help on using the repository browser.