add question concerning the order of deformer and trafo application
[PyX/mjg.git] / pyx / deco.py
blobc8f444673307b82964f0e8849625c9a7cea7bebc
1 #!/usr/bin/env python
2 # -*- coding: ISO-8859-1 -*-
5 # Copyright (C) 2002-2004 Jörg Lehmann <joergl@users.sourceforge.net>
6 # Copyright (C) 2003-2004 Michael Schindler <m-schindler@users.sourceforge.net>
7 # Copyright (C) 2002-2004 André Wobst <wobsta@users.sourceforge.net>
9 # This file is part of PyX (http://pyx.sourceforge.net/).
11 # PyX is free software; you can redistribute it and/or modify
12 # it under the terms of the GNU General Public License as published by
13 # the Free Software Foundation; either version 2 of the License, or
14 # (at your option) any later version.
16 # PyX is distributed in the hope that it will be useful,
17 # but WITHOUT ANY WARRANTY; without even the implied warranty of
18 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 # GNU General Public License for more details.
21 # You should have received a copy of the GNU General Public License
22 # along with PyX; if not, write to the Free Software
23 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 # TODO:
26 # - should we improve on the arc length -> arg parametrization routine or
27 # should we at least factor it out?
29 import sys, math
30 import attr, base, canvas, color, path, style, trafo, unit
32 try:
33 from math import radians
34 except ImportError:
35 # fallback implementation for Python 2.1 and below
36 def radians(x): return x*math.pi/180
39 # Decorated path
42 class decoratedpath(base.canvasitem):
43 """Decorated path
45 The main purpose of this class is during the drawing
46 (stroking/filling) of a path. It collects attributes for the
47 stroke and/or fill operations.
48 """
50 def __init__(self, path, strokepath=None, fillpath=None,
51 styles=None, strokestyles=None, fillstyles=None,
52 ornaments=None):
54 self.path = path
56 # global style for stroking and filling and subdps
57 self.styles = styles
59 # styles which apply only for stroking and filling
60 self.strokestyles = strokestyles
61 self.fillstyles = fillstyles
63 # the decoratedpath can contain additional elements of the
64 # path (ornaments), e.g., arrowheads.
65 if ornaments is None:
66 self.ornaments = canvas.canvas()
67 else:
68 self.ornaments = ornaments
70 self.nostrokeranges = None
72 def ensurenormpath(self):
73 """convert self.path into a normpath"""
74 assert self.nostrokeranges is None or isinstance(self.path, path.normpath), "you don't understand what you are doing"
75 self.path = self.path.normpath()
77 def excluderange(self, begin, end):
78 assert isinstance(self.path, path.normpath), "you don't understand what this is about"
79 if self.nostrokeranges is None:
80 self.nostrokeranges = [(begin, end)]
81 else:
82 ibegin = 0
83 while ibegin < len(self.nostrokeranges) and self.nostrokeranges[ibegin][1] < begin:
84 ibegin += 1
86 if ibegin == len(self.nostrokeranges):
87 self.nostrokeranges.append((begin, end))
88 return
90 iend = len(self.nostrokeranges) - 1
91 while 0 <= iend and end < self.nostrokeranges[iend][0]:
92 iend -= 1
94 if iend == -1:
95 self.nostrokeranges.insert(0, (begin, end))
96 return
98 if self.nostrokeranges[ibegin][0] < begin:
99 begin = self.nostrokeranges[ibegin][0]
100 if end < self.nostrokeranges[iend][1]:
101 end = self.nostrokeranges[iend][1]
103 self.nostrokeranges[ibegin:iend+1] = [(begin, end)]
105 def bbox(self):
106 pathbbox = self.path.bbox()
107 ornamentsbbox = self.ornaments.bbox()
108 if ornamentsbbox is not None:
109 return ornamentsbbox + pathbbox
110 else:
111 return pathbbox
113 def prolog(self):
114 result = []
115 if self.styles:
116 for style in self.styles:
117 result.extend(style.prolog())
118 if self.fillstyles:
119 for style in self.fillstyles:
120 result.extend(style.prolog())
121 if self.strokestyles:
122 for style in self.strokestyles:
123 result.extend(style.prolog())
124 result.extend(self.ornaments.prolog())
125 return result
127 def strokepath(self):
128 if self.nostrokeranges:
129 splitlist = []
130 for begin, end in self.nostrokeranges:
131 splitlist.append(begin)
132 splitlist.append(end)
133 split = self.path.split(splitlist)
134 # XXX properly handle closed paths?
135 result = split[0]
136 for i in range(2, len(split), 2):
137 result += split[i]
138 return result
139 else:
140 return self.path
142 def outputPS(self, file):
143 # draw (stroke and/or fill) the decoratedpath on the canvas
144 # while trying to produce an efficient output, e.g., by
145 # not writing one path two times
147 # small helper
148 def _writestyles(styles, file=file):
149 for style in styles:
150 style.outputPS(file)
152 if self.strokestyles is None and self.fillstyles is None:
153 raise RuntimeError("Path neither to be stroked nor filled")
155 strokepath = self.strokepath()
156 fillpath = self.path
158 # apply global styles
159 if self.styles:
160 file.write("gsave\n")
161 _writestyles(self.styles)
163 if self.fillstyles is not None:
164 file.write("newpath\n")
165 fillpath.outputPS(file)
167 if strokepath is fillpath:
168 # do efficient stroking + filling if respective paths are identical
169 file.write("gsave\n")
171 if self.fillstyles:
172 _writestyles(self.fillstyles)
174 file.write("fill\n")
175 file.write("grestore\n")
177 if self.strokestyles:
178 file.write("gsave\n")
179 _writestyles(self.strokestyles)
181 file.write("stroke\n")
183 if self.strokestyles:
184 file.write("grestore\n")
185 else:
186 # only fill fillpath - for the moment
187 if self.fillstyles:
188 file.write("gsave\n")
189 _writestyles(self.fillstyles)
191 file.write("fill\n")
193 if self.fillstyles:
194 file.write("grestore\n")
196 if self.strokestyles is not None and (strokepath is not fillpath or self.fillstyles is None):
197 # this is the only relevant case still left
198 # Note that a possible stroking has already been done.
200 if self.strokestyles:
201 file.write("gsave\n")
202 _writestyles(self.strokestyles)
204 file.write("newpath\n")
205 strokepath.outputPS(file)
206 file.write("stroke\n")
208 if self.strokestyles:
209 file.write("grestore\n")
211 # now, draw additional elements of decoratedpath
212 self.ornaments.outputPS(file)
214 # restore global styles
215 if self.styles:
216 file.write("grestore\n")
218 def outputPDF(self, file):
219 # draw (stroke and/or fill) the decoratedpath on the canvas
221 def _writestyles(styles, file=file):
222 for style in styles:
223 style.outputPDF(file)
225 def _writestrokestyles(strokestyles, file=file):
226 for style in strokestyles:
227 if isinstance(style, color.color):
228 style.outputPDF(file, fillattr=0)
229 else:
230 style.outputPDF(file)
232 def _writefillstyles(fillstyles, file=file):
233 for style in fillstyles:
234 if isinstance(style, color.color):
235 style.outputPDF(file, strokeattr=0)
236 else:
237 style.outputPDF(file)
239 if self.strokestyles is None and self.fillstyles is None:
240 raise RuntimeError("Path neither to be stroked nor filled")
242 strokepath = self.strokepath()
243 fillpath = self.path
245 # apply global styles
246 if self.styles:
247 file.write("q\n") # gsave
248 _writestyles(self.styles)
250 if self.fillstyles is not None:
251 fillpath.outputPDF(file)
253 if strokepath is fillpath:
254 # do efficient stroking + filling
255 file.write("q\n") # gsave
257 if self.fillstyles:
258 _writefillstyles(self.fillstyles)
259 if self.strokestyles:
260 _writestrokestyles(self.strokestyles)
262 file.write("B\n") # both stroke and fill
263 file.write("Q\n") # grestore
264 else:
265 # only fill fillpath - for the moment
266 if self.fillstyles:
267 file.write("q\n") # gsave
268 _writefillstyles(self.fillstyles)
270 file.write("f\n") # fill
272 if self.fillstyles:
273 file.write("Q\n") # grestore
275 if self.strokestyles is not None and (strokepath is not fillpath or self.fillstyles is None):
276 # this is the only relevant case still left
277 # Note that a possible stroking has already been done.
279 if self.strokestyles:
280 file.write("q\n") # gsave
281 _writestrokestyles(self.strokestyles)
283 strokepath.outputPDF(file)
284 file.write("S\n") # stroke
286 if self.strokestyles:
287 file.write("Q\n") # grestore
289 # now, draw additional elements of decoratedpath
290 self.ornaments.outputPDF(file)
292 # restore global styles
293 if self.styles:
294 file.write("Q\n") # grestore
297 # Path decorators
300 class deco:
302 """decorators
304 In contrast to path styles, path decorators depend on the concrete
305 path to which they are applied. In particular, they don't make
306 sense without any path and can thus not be used in canvas.set!
310 def decorate(self, dp):
311 """apply a style to a given decoratedpath object dp
313 decorate accepts a decoratedpath object dp, applies PathStyle
314 by modifying dp in place and returning the new dp.
317 pass
320 # stroked and filled: basic decos which stroked and fill,
321 # respectively the path
324 class _stroked(deco, attr.exclusiveattr):
326 """stroked is a decorator, which draws the outline of the path"""
328 def __init__(self, styles=[]):
329 attr.exclusiveattr.__init__(self, _stroked)
330 self.styles = attr.mergeattrs(styles)
331 attr.checkattrs(self.styles, [style.strokestyle])
333 def __call__(self, styles=[]):
334 # XXX or should we also merge self.styles
335 return _stroked(styles)
337 def decorate(self, dp):
338 if dp.strokestyles is not None:
339 raise RuntimeError("Cannot stroke an already stroked path")
340 dp.strokestyles = self.styles
341 return dp
343 stroked = _stroked()
344 stroked.clear = attr.clearclass(_stroked)
347 class _filled(deco, attr.exclusiveattr):
349 """filled is a decorator, which fills the interior of the path"""
351 def __init__(self, styles=[]):
352 attr.exclusiveattr.__init__(self, _filled)
353 self.styles = attr.mergeattrs(styles)
354 attr.checkattrs(self.styles, [style.fillstyle])
356 def __call__(self, styles=[]):
357 # XXX or should we also merge self.styles
358 return _filled(styles)
360 def decorate(self, dp):
361 if dp.fillstyles is not None:
362 raise RuntimeError("Cannot fill an already filled path")
363 dp.fillstyles = self.styles
364 return dp
366 filled = _filled()
367 filled.clear = attr.clearclass(_filled)
370 # Arrows
373 # helper function which constructs the arrowhead
375 def _arrowhead(anormsubpath, size, angle, constrictionlen, reversed):
377 """helper routine, which returns an arrowhead from a given anormsubpath
379 returns arrowhead at begin of anormpath with size,
380 opening angle and constriction length constrictionlen
383 if reversed:
384 anormsubpath = anormsubpath.reversed()
385 alen = anormsubpath.arclentoparam(size)
386 tx, ty = anormsubpath.begin()
388 # now we construct the template for our arrow but cutting
389 # the path a the corresponding length
390 arrowtemplate = anormsubpath.split([alen])[0]
392 # from this template, we construct the two outer curves
393 # of the arrow
394 arrowl = path.normpath([arrowtemplate.transformed(trafo.rotate(-angle/2.0, tx, ty))])
395 arrowr = path.normpath([arrowtemplate.transformed(trafo.rotate( angle/2.0, tx, ty))])
397 # now come the joining backward parts
399 # constriction point (cx, cy) lies on path
400 cx, cy = anormsubpath.at(anormsubpath.arclentoparam(constrictionlen))
402 arrowcr= path.line(*(arrowr.end()+(cx,cy)))
404 arrow = arrowl.reversed() << arrowr << arrowcr
405 arrow[-1].close()
407 return arrow
410 _base = 6 * unit.v_pt
412 class arrow(deco, attr.attr):
414 """arrow is a decorator which adds an arrow to either side of the path"""
416 def __init__(self, attrs=[], position=0, size=_base, angle=45, constriction=0.8):
417 self.attrs = attr.mergeattrs([style.linestyle.solid, filled] + attrs)
418 attr.checkattrs(self.attrs, [deco, style.fillstyle, style.strokestyle])
419 self.position = position
420 self.size = size
421 self.angle = angle
422 self.constriction = constriction
424 def __call__(self, attrs=None, position=None, size=None, angle=None, constriction=None):
425 if attrs is None:
426 attrs = self.attrs
427 if position is None:
428 position = self.position
429 if size is None:
430 size = self.size
431 if angle is None:
432 angle = self.angle
433 if constriction is None:
434 constriction = self.constriction
435 return arrow(attrs=attrs, position=position, size=size, angle=angle, constriction=constriction)
437 def decorate(self, dp):
438 dp.ensurenormpath()
439 anormpath = dp.path
441 # calculate absolute arc length of constricition
442 # Note that we have to correct this length because the arrowtemplates are rotated
443 # by self.angle/2 to the left and right. Hence, if we want no constriction, i.e., for
444 # self.constriction = 1, we actually have a length which is approximately shorter
445 # by the given geometrical factor.
446 constrictionlen = self.size*self.constriction*math.cos(radians(self.angle/2.0))
448 if self.position == 0:
449 # Note that the template for the arrow head should only be constructed
450 # from the first normsubpath
451 firstnormsubpath = anormpath[0]
452 arrowhead = _arrowhead(firstnormsubpath, self.size, self.angle, constrictionlen, reversed=0)
453 else:
454 lastnormsubpath = anormpath[-1]
455 arrowhead = _arrowhead(lastnormsubpath, self.size, self.angle, constrictionlen, reversed=1)
457 # add arrowhead to decoratedpath
458 dp.ornaments.draw(arrowhead, self.attrs)
460 if self.position == 0:
461 # exclude first part of the first normsubpath from stroking
462 ilen = firstnormsubpath.arclentoparam(min(self.size, constrictionlen))
463 dp.excluderange((0, 0), (0,ilen))
464 else:
465 ilen = lastnormsubpath.arclentoparam(lastnormsubpath.arclen()-min(self.size, constrictionlen))
466 # TODO. provide a better way to access the number of normsubpaths in a normpath
467 lastnormsubpathindex = len(anormpath.normsubpaths)-1
468 dp.excluderange((lastnormsubpathindex, ilen), (lastnormsubpathindex, lastnormsubpath.range()))
470 return dp
472 arrow.clear = attr.clearclass(arrow)
474 # arrows at begin of path
475 barrow = arrow(position=0)
476 barrow.SMALL = barrow(size=_base/math.sqrt(64))
477 barrow.SMALl = barrow(size=_base/math.sqrt(32))
478 barrow.SMAll = barrow(size=_base/math.sqrt(16))
479 barrow.SMall = barrow(size=_base/math.sqrt(8))
480 barrow.Small = barrow(size=_base/math.sqrt(4))
481 barrow.small = barrow(size=_base/math.sqrt(2))
482 barrow.normal = barrow(size=_base)
483 barrow.large = barrow(size=_base*math.sqrt(2))
484 barrow.Large = barrow(size=_base*math.sqrt(4))
485 barrow.LArge = barrow(size=_base*math.sqrt(8))
486 barrow.LARge = barrow(size=_base*math.sqrt(16))
487 barrow.LARGe = barrow(size=_base*math.sqrt(32))
488 barrow.LARGE = barrow(size=_base*math.sqrt(64))
490 # arrows at end of path
491 earrow = arrow(position=1)
492 earrow.SMALL = earrow(size=_base/math.sqrt(64))
493 earrow.SMALl = earrow(size=_base/math.sqrt(32))
494 earrow.SMAll = earrow(size=_base/math.sqrt(16))
495 earrow.SMall = earrow(size=_base/math.sqrt(8))
496 earrow.Small = earrow(size=_base/math.sqrt(4))
497 earrow.small = earrow(size=_base/math.sqrt(2))
498 earrow.normal = earrow(size=_base)
499 earrow.large = earrow(size=_base*math.sqrt(2))
500 earrow.Large = earrow(size=_base*math.sqrt(4))
501 earrow.LArge = earrow(size=_base*math.sqrt(8))
502 earrow.LARge = earrow(size=_base*math.sqrt(16))
503 earrow.LARGe = earrow(size=_base*math.sqrt(32))
504 earrow.LARGE = earrow(size=_base*math.sqrt(64))