1 |
# Copyright (c) 2001, 2002, 2003 by Intevation GmbH |
2 |
# Authors: |
3 |
# Bernhard Herzog <[email protected]> |
4 |
# Jonathan Coles <[email protected]> |
5 |
# Frank Koormann <[email protected]> |
6 |
# |
7 |
# This program is free software under the GPL (>=v2) |
8 |
# Read the file COPYING coming with Thuban for details. |
9 |
|
10 |
"""Basic rendering logic for Thuban maps |
11 |
|
12 |
The code in this module is completely independend of wx so that it can |
13 |
be tested reasonably easily and it could make it easier to write non-wx |
14 |
renderers. |
15 |
""" |
16 |
|
17 |
from __future__ import generators |
18 |
|
19 |
__version__ = "$Revision$" |
20 |
# $Source$ |
21 |
# $Id$ |
22 |
|
23 |
import traceback |
24 |
|
25 |
from Thuban.Model.layer import Layer, RasterLayer |
26 |
from Thuban.Model.data import SHAPETYPE_ARC, SHAPETYPE_POINT |
27 |
from Thuban.Model.label import ALIGN_CENTER, ALIGN_TOP, ALIGN_BOTTOM, \ |
28 |
ALIGN_LEFT, ALIGN_RIGHT |
29 |
|
30 |
import Thuban.Model.resource |
31 |
|
32 |
if Thuban.Model.resource.has_gdal_support(): |
33 |
from gdalwarp import ProjectRasterFile |
34 |
|
35 |
|
36 |
class BaseRenderer: |
37 |
|
38 |
"""Basic Renderer Infrastructure for Thuban Maps |
39 |
|
40 |
This class can't be used directly to render because it doesn't know |
41 |
anything about real DCs such as how to create pens or brushes. That |
42 |
functionality has to be provided by derived classes. The reason for |
43 |
this is that it makes the BaseRenderer completely independend of wx |
44 |
and thus it's quite easy to write test cases for it. |
45 |
""" |
46 |
# If true the render honors the visibility flag of the layers |
47 |
honor_visibility = 1 |
48 |
|
49 |
# Transparent brushes and pens. Derived classes should define these |
50 |
# as appropriate. |
51 |
TRANSPARENT_PEN = None |
52 |
TRANSPARENT_BRUSH = None |
53 |
|
54 |
def __init__(self, dc, map, scale, offset, region = None, |
55 |
resolution = 72.0, honor_visibility = None): |
56 |
"""Inititalize the renderer. |
57 |
|
58 |
dc -- the device context to render on. |
59 |
|
60 |
scale, offset -- the scale factor and translation to convert |
61 |
between projected coordinates and the DC coordinates |
62 |
|
63 |
region -- The region to draw as a (x, y, width, height) tuple in |
64 |
the map's coordinate system. Default is None meaning |
65 |
to draw everything. |
66 |
|
67 |
resolution -- the assumed resolution of the DC. Used to convert |
68 |
absolute lengths like font sizes to DC coordinates. The |
69 |
default is 72.0. If given, this parameter must be |
70 |
provided as a keyword argument. |
71 |
|
72 |
honor_visibility -- boolean. If true, honor the visibility flag |
73 |
of the layers, otherwise draw all layers. If None (the |
74 |
default), use the renderer's default. If given, this |
75 |
parameter must be provided as a keyword argument. |
76 |
""" |
77 |
# resolution in pixel/inch |
78 |
self.dc = dc |
79 |
self.map = map |
80 |
self.scale = scale |
81 |
self.offset = offset |
82 |
self.region = region |
83 |
if honor_visibility is not None: |
84 |
self.honor_visibility = honor_visibility |
85 |
# store the resolution in pixel/point because it's more useful |
86 |
# later. |
87 |
self.resolution = resolution / 72.0 |
88 |
|
89 |
def tools_for_property(self, prop): |
90 |
"""Return a suitable pen and brush for the property |
91 |
|
92 |
This method must be implemented in derived classes. The return |
93 |
value should be a tuple (pen, brush). |
94 |
""" |
95 |
raise NotImplementedError |
96 |
|
97 |
def render_map(self): |
98 |
"""Render the map onto the DC. |
99 |
|
100 |
Both map and DC are the ones the renderer was instantiated with. |
101 |
|
102 |
This method is just a front-end for render_map_incrementally |
103 |
which does all rendering in one go. It also calls the dc's |
104 |
BeginDrawing and EndDrawing methods before and after calling |
105 |
render_map_incrementally. |
106 |
""" |
107 |
|
108 |
self.dc.BeginDrawing() |
109 |
try: |
110 |
for cont in self.render_map_incrementally(): |
111 |
pass |
112 |
finally: |
113 |
self.dc.EndDrawing() |
114 |
|
115 |
def render_map_incrementally(self): |
116 |
"""Render the map incrementally. |
117 |
|
118 |
Return an iterator whose next method should be called until it |
119 |
returns False. After returning False it will raise StopIteration |
120 |
so that you could also use it in a for loop (implementation |
121 |
detail: this method is implemented as a generator). |
122 |
|
123 |
Iterate through all layers and draw them. Layers containing |
124 |
vector data are drawn with the draw_shape_layer method, raster |
125 |
layers are drawn with draw_raster_layer. The label layer is |
126 |
drawn last with draw_label_layer. |
127 |
|
128 |
During execution of this method, the map is bound to self.map so |
129 |
that methods especially in derived classes have access to the |
130 |
map if necessary. |
131 |
""" |
132 |
# Whether the raster layer has already been drawn. See below for |
133 |
# the optimization this is used for |
134 |
seenRaster = True |
135 |
|
136 |
# |
137 |
# This is only a good optimization if there is only one |
138 |
# raster layer and the image covers the entire window (as |
139 |
# it currently does). We note if there is a raster layer |
140 |
# and only begin drawing layers once we have drawn it. |
141 |
# That way we avoid drawing layers that won't be seen. |
142 |
# |
143 |
if Thuban.Model.resource.has_gdal_support(): |
144 |
for layer in self.map.Layers(): |
145 |
if isinstance(layer, RasterLayer) and layer.Visible(): |
146 |
seenRaster = False |
147 |
break |
148 |
|
149 |
for layer in self.map.Layers(): |
150 |
# if honor_visibility is true, only draw visible layers, |
151 |
# otherwise draw all layers |
152 |
if not self.honor_visibility or layer.Visible(): |
153 |
if isinstance(layer, Layer) and seenRaster: |
154 |
for i in self.draw_shape_layer_incrementally(layer): |
155 |
yield True |
156 |
elif isinstance(layer, RasterLayer) \ |
157 |
and Thuban.Model.resource.has_gdal_support(): |
158 |
self.draw_raster_layer(layer) |
159 |
seenRaster = True |
160 |
yield True |
161 |
|
162 |
self.draw_label_layer(self.map.LabelLayer()) |
163 |
yield False |
164 |
|
165 |
def draw_shape_layer_incrementally(self, layer): |
166 |
"""Draw the shape layer layer onto the map incrementally. |
167 |
|
168 |
This method is a generator which yields True after every 500 |
169 |
shapes. |
170 |
""" |
171 |
scale = self.scale |
172 |
offx, offy = self.offset |
173 |
|
174 |
map_proj = self.map.projection |
175 |
layer_proj = layer.projection |
176 |
|
177 |
brush = self.TRANSPARENT_BRUSH |
178 |
pen = self.TRANSPARENT_PEN |
179 |
|
180 |
old_prop = None |
181 |
old_group = None |
182 |
lc = layer.GetClassification() |
183 |
field = layer.GetClassificationColumn() |
184 |
defaultGroup = lc.GetDefaultGroup() |
185 |
table = layer.ShapeStore().Table() |
186 |
|
187 |
if lc.GetNumGroups() == 0: |
188 |
# There's only the default group, so we can pretend that |
189 |
# there is no field to classifiy on which makes things |
190 |
# faster since we don't need the attribute information at |
191 |
# all. |
192 |
field = None |
193 |
|
194 |
# Determine which render function to use. |
195 |
useraw, draw_func, draw_func_param = self.low_level_renderer(layer) |
196 |
|
197 |
# Iterate through all shapes that have to be drawn. |
198 |
count = 0 |
199 |
for shape in self.layer_shapes(layer): |
200 |
count += 1 |
201 |
if field is None: |
202 |
group = defaultGroup |
203 |
else: |
204 |
record = table.ReadRowAsDict(shape.ShapeID()) |
205 |
assert record is not None |
206 |
group = lc.FindGroup(record[field]) |
207 |
|
208 |
if not group.IsVisible(): |
209 |
continue |
210 |
|
211 |
# don't recreate new objects if they are the same as before |
212 |
if group is not old_group: |
213 |
old_group = group |
214 |
|
215 |
prop = group.GetProperties() |
216 |
|
217 |
if prop != old_prop: |
218 |
pen, brush = self.tools_for_property(prop) |
219 |
|
220 |
if useraw: |
221 |
data = shape.RawData() |
222 |
else: |
223 |
data = shape.Points() |
224 |
draw_func(draw_func_param, data, pen, brush) |
225 |
if count % 500 == 0: |
226 |
yield True |
227 |
|
228 |
def layer_shapes(self, layer): |
229 |
"""Return an iterable over the shapes to be drawn from the given layer. |
230 |
|
231 |
The default implementation simply returns all ids in the layer. |
232 |
Override in derived classes to be more precise. |
233 |
""" |
234 |
return layer.ShapeStore().AllShapes() |
235 |
|
236 |
def low_level_renderer(self, layer): |
237 |
"""Return the low-level renderer for the layer for draw_shape_layer |
238 |
|
239 |
The low level renderer to be returned by this method is a tuple |
240 |
(useraw, func, param) where useraw is a boolean indicating |
241 |
whether the function uses the raw shape data, func is a callable |
242 |
object and param is passed as the first parameter to func. The |
243 |
draw_shape_layer method will call func like this: |
244 |
|
245 |
func(param, shapedata, pen, brush) |
246 |
|
247 |
where shapedata is the return value of the RawData method of the |
248 |
shape object if useraw is true or the return value of the Points |
249 |
method if it's false. pen and brush are the pen and brush to use |
250 |
to draw the shape on the dc. |
251 |
|
252 |
The default implementation returns one of |
253 |
self.draw_polygon_shape, self.draw_arc_shape or |
254 |
self.draw_point_shape as func and layer as param. None of the |
255 |
method use the raw shape data. Derived classes can override this |
256 |
method to return more efficient low level renderers. |
257 |
""" |
258 |
shapetype = layer.ShapeType() |
259 |
if shapetype == SHAPETYPE_POINT: |
260 |
func = self.draw_point_shape |
261 |
elif shapetype == SHAPETYPE_ARC: |
262 |
func = self.draw_arc_shape |
263 |
else: |
264 |
func = self.draw_polygon_shape |
265 |
return False, func, layer |
266 |
|
267 |
def make_point(self, x, y): |
268 |
"""Convert (x, y) to a point object. |
269 |
|
270 |
Derived classes must override this method. |
271 |
""" |
272 |
raise NotImplementedError |
273 |
|
274 |
def projected_points(self, layer, points): |
275 |
"""Return the projected coordinates of the points taken from layer. |
276 |
|
277 |
Transform all the points in the list of lists of coordinate |
278 |
pairs in points. |
279 |
|
280 |
The transformation applies the inverse of the layer's projection |
281 |
if any, then the map's projection if any and finally applies |
282 |
self.scale and self.offset. |
283 |
|
284 |
The returned list has the same structure as the one returned the |
285 |
shape's Points method. |
286 |
""" |
287 |
proj = self.map.GetProjection() |
288 |
if proj is not None: |
289 |
forward = proj.Forward |
290 |
else: |
291 |
forward = None |
292 |
proj = layer.GetProjection() |
293 |
if proj is not None: |
294 |
inverse = proj.Inverse |
295 |
else: |
296 |
inverse = None |
297 |
result = [] |
298 |
scale = self.scale |
299 |
offx, offy = self.offset |
300 |
make_point = self.make_point |
301 |
for part in points: |
302 |
result.append([]) |
303 |
for x, y in part: |
304 |
if inverse: |
305 |
x, y = inverse(x, y) |
306 |
if forward: |
307 |
x, y = forward(x, y) |
308 |
result[-1].append(make_point(x * scale + offx, |
309 |
-y * scale + offy)) |
310 |
return result |
311 |
|
312 |
def draw_polygon_shape(self, layer, points, pen, brush): |
313 |
"""Draw a polygon shape from layer with the given brush and pen |
314 |
|
315 |
The shape is given by points argument which is a the return |
316 |
value of the shape's Points() method. The coordinates in the |
317 |
DC's coordinate system are determined with |
318 |
self.projected_points. |
319 |
""" |
320 |
points = self.projected_points(layer, points) |
321 |
|
322 |
if brush is not self.TRANSPARENT_BRUSH: |
323 |
polygon = [] |
324 |
for part in points: |
325 |
polygon.extend(part) |
326 |
|
327 |
insert_index = len(polygon) |
328 |
for part in points[:-1]: |
329 |
polygon.insert(insert_index, part[0]) |
330 |
|
331 |
self.dc.SetBrush(brush) |
332 |
self.dc.SetPen(self.TRANSPARENT_PEN) |
333 |
self.dc.DrawPolygon(polygon) |
334 |
|
335 |
if pen is not self.TRANSPARENT_PEN: |
336 |
# At last draw the boundarys of the simple polygons |
337 |
self.dc.SetBrush(self.TRANSPARENT_BRUSH) |
338 |
self.dc.SetPen(pen) |
339 |
for part in points: |
340 |
self.dc.DrawLines(part) |
341 |
|
342 |
def draw_arc_shape(self, layer, points, pen, brush): |
343 |
"""Draw an arc shape from layer with the given brush and pen |
344 |
|
345 |
The shape is given by points argument which is a the return |
346 |
value of the shape's Points() method. The coordinates in the |
347 |
DC's coordinate system are determined with |
348 |
self.projected_points. |
349 |
""" |
350 |
points = self.projected_points(layer, points) |
351 |
self.dc.SetBrush(brush) |
352 |
self.dc.SetPen(pen) |
353 |
for part in points: |
354 |
self.dc.DrawLines(part) |
355 |
|
356 |
def draw_point_shape(self, layer, points, pen, brush): |
357 |
"""Draw a point shape from layer with the given brush and pen |
358 |
|
359 |
The shape is given by points argument which is a the return |
360 |
value of the shape's Points() method. The coordinates in the |
361 |
DC's coordinate system are determined with |
362 |
self.projected_points. |
363 |
|
364 |
The point is drawn as a circle centered on the point. |
365 |
""" |
366 |
points = self.projected_points(layer, points) |
367 |
if not points: |
368 |
return |
369 |
|
370 |
radius = self.resolution * 5 |
371 |
self.dc.SetBrush(brush) |
372 |
self.dc.SetPen(pen) |
373 |
for part in points: |
374 |
for p in part: |
375 |
self.dc.DrawEllipse(p.x - radius, p.y - radius, |
376 |
2 * radius, 2 * radius) |
377 |
|
378 |
def draw_raster_layer(self, layer): |
379 |
"""Draw the raster layer |
380 |
|
381 |
This implementation does the projection and scaling of the data |
382 |
as required by the layer's and map's projections and the scale |
383 |
and offset of the renderer and then hands the transformed data |
384 |
to self.draw_raster_data() which has to be implemented in |
385 |
derived classes. |
386 |
""" |
387 |
offx, offy = self.offset |
388 |
width, height = self.dc.GetSizeTuple() |
389 |
|
390 |
in_proj = "" |
391 |
proj = layer.GetProjection() |
392 |
if proj is not None: |
393 |
for p in proj.GetAllParameters(): |
394 |
in_proj += "+" + p + " " |
395 |
|
396 |
out_proj = "" |
397 |
proj = self.map.GetProjection() |
398 |
if proj is not None: |
399 |
for p in proj.GetAllParameters(): |
400 |
out_proj += "+" + p + " " |
401 |
|
402 |
xmin = (0 - offx) / self.scale |
403 |
ymin = (offy - height) / self.scale |
404 |
xmax = (width - offx) / self.scale |
405 |
ymax = (offy - 0) / self.scale |
406 |
|
407 |
try: |
408 |
data = ProjectRasterFile(layer.GetImageFilename(), |
409 |
in_proj, out_proj, |
410 |
(xmin, ymin, xmax, ymax), "", |
411 |
(width, height)) |
412 |
except (IOError, AttributeError, ValueError): |
413 |
# Why does this catch AttributeError and ValueError? |
414 |
# FIXME: The exception should be communicated to the user |
415 |
# better. |
416 |
traceback.print_exc() |
417 |
else: |
418 |
self.draw_raster_data(data) |
419 |
|
420 |
def draw_raster_data(self, data): |
421 |
"""Draw the raster image in data onto the DC |
422 |
|
423 |
The raster image data is a string holding the data in BMP |
424 |
format. The data is exactly the size of the dc and covers it |
425 |
completely. |
426 |
|
427 |
This method has to be implemented by derived classes. |
428 |
""" |
429 |
raise NotImplementedError |
430 |
|
431 |
def label_font(self): |
432 |
"""Return the font object for the label layer""" |
433 |
raise NotImplementedError |
434 |
|
435 |
def draw_label_layer(self, layer): |
436 |
"""Draw the label layer |
437 |
|
438 |
All labels are draw in the font returned by self.label_font(). |
439 |
""" |
440 |
scale = self.scale |
441 |
offx, offy = self.offset |
442 |
|
443 |
self.dc.SetFont(self.label_font()) |
444 |
|
445 |
map_proj = self.map.projection |
446 |
if map_proj is not None: |
447 |
forward = map_proj.Forward |
448 |
else: |
449 |
forward = None |
450 |
|
451 |
for label in layer.Labels(): |
452 |
x = label.x |
453 |
y = label.y |
454 |
text = label.text |
455 |
if forward: |
456 |
x, y = forward(x, y) |
457 |
x = x * scale + offx |
458 |
y = -y * scale + offy |
459 |
width, height = self.dc.GetTextExtent(text) |
460 |
if label.halign == ALIGN_LEFT: |
461 |
# nothing to be done |
462 |
pass |
463 |
elif label.halign == ALIGN_RIGHT: |
464 |
x = x - width |
465 |
elif label.halign == ALIGN_CENTER: |
466 |
x = x - width/2 |
467 |
if label.valign == ALIGN_TOP: |
468 |
# nothing to be done |
469 |
pass |
470 |
elif label.valign == ALIGN_BOTTOM: |
471 |
y = y - height |
472 |
elif label.valign == ALIGN_CENTER: |
473 |
y = y - height/2 |
474 |
self.dc.DrawText(text, x, y) |