new question on how to use older versions of PyX
[PyX/mjg.git] / pyx / connector.py
blob86bbb2591ca638ba094551a40af409130754be38
1 #!/usr/bin/env python
2 # -*- coding: ISO-8859-1 -*-
5 # Copyright (C) 2003-2004 Michael Schindler <m-schindler@users.sourceforge.net>
7 # This file is part of PyX (http://pyx.sourceforge.net/).
9 # PyX is free software; you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 2 of the License, or
12 # (at your option) any later version.
14 # PyX is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
19 # You should have received a copy of the GNU General Public License
20 # along with PyX; if not, write to the Free Software
21 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 import math
25 from math import pi, sin, cos, atan2, tan, hypot, acos, sqrt
26 import path, unit, helper
27 try:
28 from math import radians, degrees
29 except ImportError:
30 # fallback implementation for Python 2.1 and below
31 def radians(x): return x*pi/180
32 def degrees(x): return x*180/pi
35 #########################
36 ## helpers
37 #########################
39 class connector_pt(path.normpath):
41 def omitends(self, box1, box2):
42 """intersects a path with the boxes' paths"""
44 # cut off the start of self
45 # XXX how can decoration of this box1.path() be handled?
46 sp = self.intersect(box1.path())[0]
47 if sp:
48 self.normsubpaths = self.split(sp[-1:])[1].normsubpaths
50 # cut off the end of self
51 sp = self.intersect(box2.path())[0]
52 if sp:
53 self.normsubpaths = self.split(sp[:1])[0].normsubpaths
55 def shortenpath(self, dists):
56 """shortens a path by the given distances"""
58 # XXX later, this should be done by extended boxes instead of intersecting with circles
59 # cut off the start of self
60 center = self.begin_pt()
61 cutpath = path.circle_pt(center[0], center[1], dists[0])
62 try:
63 cutpath = cutpath.normpath()
64 except path.PathException:
65 pass
66 else:
67 sp = self.intersect(cutpath)[0]
68 self.normsubpaths = self.split(sp[-1:])[1].normsubpaths
70 # cut off the end of self
71 center = self.end_pt()
72 cutpath = path.circle_pt(center[0], center[1], dists[1])
73 try:
74 cutpath = cutpath.normpath()
75 except path.PathException:
76 pass
77 else:
78 sp = self.intersect(cutpath)[0]
79 self.normsubpaths = self.split(sp[:1])[0].normsubpaths
82 ################
83 ## classes
84 ################
87 class line_pt(connector_pt):
89 def __init__(self, box1, box2, boxdists=[0,0]):
91 self.box1 = box1
92 self.box2 = box2
94 connector_pt.__init__(self,
95 [path.normsubpath([path.normline(*(self.box1.center+self.box2.center))], 0)])
97 self.omitends(box1, box2)
98 self.shortenpath(boxdists)
101 class arc_pt(connector_pt):
103 def __init__(self, box1, box2, relangle=45,
104 absbulge=None, relbulge=None, boxdists=[0,0]):
106 # the deviation of arc from the straight line can be specified:
107 # 1. By an angle between a straight line and the arc
108 # This angle is measured at the centers of the box.
109 # 2. By the largest normal distance between line and arc: absbulge
110 # or, equivalently, by the bulge relative to the length of the
111 # straight line from center to center.
112 # Only one can be used.
114 self.box1 = box1
115 self.box2 = box2
117 rel = (self.box2.center[0] - self.box1.center[0],
118 self.box2.center[1] - self.box1.center[1])
119 distance = hypot(*rel)
121 # usage of bulge overrides the relangle parameter
122 if relbulge is not None or absbulge is not None:
123 relangle = None
124 bulge = 0
125 try: bulge += absbulge
126 except: pass
127 try: bulge += relbulge*distance
128 except: pass
130 try: radius = abs(0.5 * (bulge + 0.25 * distance**2 / bulge))
131 except: radius = 10 * distance # default value for too straight arcs
132 radius = min(radius, 10 * distance)
133 center = 2.0*(radius-abs(bulge))/distance
134 center *= 2*(bulge>0.0)-1
135 # otherwise use relangle
136 else:
137 bulge=None
138 try: radius = 0.5 * distance / abs(cos(0.5*math.pi - radians(relangle)))
139 except: radius = 10 * distance
140 try: center = tan(0.5*math.pi - radians(relangle))
141 except: center = 0
143 # up to here center is only the distance from the middle of the
144 # straight connection
145 center = (0.5 * (self.box1.center[0] + self.box2.center[0] - rel[1]*center),
146 0.5 * (self.box1.center[1] + self.box2.center[1] + rel[0]*center))
147 angle1 = atan2(self.box1.center[1] - center[1], self.box1.center[0] - center[0])
148 angle2 = atan2(self.box2.center[1] - center[1], self.box2.center[0] - center[0])
150 # draw the arc in positive direction by default
151 # negative direction if relangle<0 or bulge<0
152 if (relangle is not None and relangle < 0) or (bulge is not None and bulge < 0):
153 connectorpath = path.path(path.moveto_pt(*self.box1.center),
154 path.arcn_pt(center[0], center[1], radius, degrees(angle1), degrees(angle2)))
155 connector_pt.__init__(self, connectorpath.normpath().normsubpaths)
156 else:
157 connectorpath = path.path(path.moveto_pt(*self.box1.center),
158 path.arc_pt(center[0], center[1], radius, degrees(angle1), degrees(angle2)))
159 connector_pt.__init__(self, connectorpath.normpath().normsubpaths)
161 self.omitends(box1, box2)
162 self.shortenpath(boxdists)
165 class curve_pt(connector_pt):
167 def __init__(self, box1, box2,
168 relangle1=45, relangle2=45,
169 absangle1=None, absangle2=None,
170 absbulge=0, relbulge=0.39, boxdists=[0,0]):
172 # The deviation of the curve from a straight line can be specified:
173 # A. By an angle at each center
174 # These angles are either absolute angles with origin at the positive x-axis
175 # or the relative angle with origin at the straight connection line
176 # B. By the (expected) largest normal distance between line and arc: absbulge
177 # and/or by the (expected) bulge relative to the length of the
178 # straight line from center to center.
179 # Here, we need both informations.
181 # a curve with relbulge=0.39 and relangle1,2=45 leads
182 # approximately to the arc with angle=45
184 self.box1 = box1
185 self.box2 = box2
187 rel = (self.box2.center[0] - self.box1.center[0],
188 self.box2.center[1] - self.box1.center[1])
189 distance = hypot(*rel)
190 # absolute angle of the straight connection
191 dangle = atan2(rel[1], rel[0])
193 # calculate the armlength and absolute angles for the control points:
194 # absolute and relative bulges are added
195 bulge = abs(distance*relbulge + absbulge)
197 if absangle1 is not None:
198 angle1 = radians(absangle1)
199 else:
200 angle1 = dangle - radians(relangle1)
201 if absangle2 is not None:
202 angle2 = radians(absangle2)
203 else:
204 angle2 = dangle + radians(relangle2)
206 # get the control points
207 control1 = (cos(angle1), sin(angle1))
208 control2 = (cos(angle2), sin(angle2))
209 control1 = (self.box1.center[0] + control1[0] * bulge, self.box1.center[1] + control1[1] * bulge)
210 control2 = (self.box2.center[0] - control2[0] * bulge, self.box2.center[1] - control2[1] * bulge)
212 connector_pt.__init__(self,
213 [path.normsubpath([path.normcurve(*(self.box1.center +
214 control1 +
215 control2 + self.box2.center))], 0)])
217 self.omitends(box1, box2)
218 self.shortenpath(boxdists)
221 class twolines_pt(connector_pt):
223 def __init__(self, box1, box2,
224 absangle1=None, absangle2=None,
225 relangle1=None, relangle2=None, relangleM=None,
226 length1=None, length2=None,
227 bezierradius=None, beziersoftness=1,
228 arcradius=None,
229 boxdists=[0,0]):
231 # The connection with two lines can be done in the following ways:
232 # 1. an angle at each box-center
233 # 2. two armlengths (if they are long enough)
234 # 3. angle and armlength at the same box
235 # 4. angle and armlength at different boxes
236 # 5. one armlength and the angle between the arms
238 # Angles at the box-centers can be relative or absolute
239 # The angle in the middle is always relative
240 # lengths are always absolute
242 self.box1 = box1
243 self.box2 = box2
245 begin = self.box1.center
246 end = self.box2.center
247 rel = (self.box2.center[0] - self.box1.center[0],
248 self.box2.center[1] - self.box1.center[1])
249 distance = hypot(*rel)
250 dangle = atan2(rel[1], rel[0])
252 # find out what arguments are given:
253 if relangle1 is not None: relangle1 = radians(relangle1)
254 if relangle2 is not None: relangle2 = radians(relangle2)
255 if relangleM is not None: relangleM = radians(relangleM)
256 # absangle has priority over relangle:
257 if absangle1 is not None: relangle1 = dangle - radians(absangle1)
258 if absangle2 is not None: relangle2 = math.pi - dangle + radians(absangle2)
260 # check integrity of arguments
261 no_angles, no_lengths=0,0
262 for anangle in (relangle1, relangle2, relangleM):
263 if anangle is not None: no_angles += 1
264 for alength in (length1, length2):
265 if alength is not None: no_lengths += 1
267 if no_angles + no_lengths != 2:
268 raise NotImplementedError, "Please specify exactly two angles or lengths"
270 # calculate necessary angles and armlengths
271 # always length1 and relangle1
273 # the case with two given angles
274 # use the "sine-theorem" for calculating length1
275 if no_angles == 2:
276 if relangle1 is None: relangle1 = math.pi - relangle2 - relangleM
277 elif relangle2 is None: relangle2 = math.pi - relangle1 - relangleM
278 elif relangleM is None: relangleM = math.pi - relangle1 - relangle2
279 length1 = distance * abs(sin(relangle2)/sin(relangleM))
280 middle = self._middle_a(begin, dangle, length1, relangle1)
281 # the case with two given lengths
282 # uses the "cosine-theorem" for calculating length1
283 elif no_lengths == 2:
284 relangle1 = acos((distance**2 + length1**2 - length2**2) / (2.0*distance*length1))
285 middle = self._middle_a(begin, dangle, length1, relangle1)
286 # the case with one length and one angle
287 else:
288 if relangle1 is not None:
289 if length1 is not None:
290 middle = self._middle_a(begin, dangle, length1, relangle1)
291 elif length2 is not None:
292 length1 = self._missinglength(length2, distance, relangle1)
293 middle = self._middle_a(begin, dangle, length1, relangle1)
294 elif relangle2 is not None:
295 if length1 is not None:
296 length2 = self._missinglength(length1, distance, relangle2)
297 middle = self._middle_b(end, dangle, length2, relangle2)
298 elif length2 is not None:
299 middle = self._middle_b(end, dangle, length2, relangle2)
300 elif relangleM is not None:
301 if length1 is not None:
302 length2 = self._missinglength(distance, length1, relangleM)
303 relangle1 = acos((distance**2 + length1**2 - length2**2) / (2.0*distance*length1))
304 middle = self._middle_a(begin, dangle, length1, relangle1)
305 elif length2 is not None:
306 length1 = self._missinglength(distance, length2, relangleM)
307 relangle1 = acos((distance**2 + length1**2 - length2**2) / (2.0*distance*length1))
308 middle = self._middle_a(begin, dangle, length1, relangle1)
309 else:
310 raise NotImplementedError, "I found a strange combination of arguments"
312 connectorpath = path.path(path.moveto_pt(*self.box1.center),
313 path.lineto_pt(*middle),
314 path.lineto_pt(*self.box2.center))
315 connector_pt.__init__(self, connectorpath.normpath().normsubpaths)
317 self.omitends(box1, box2)
318 self.shortenpath(boxdists)
320 def _middle_a(self, begin, dangle, length1, angle1):
321 a = dangle - angle1
322 dir = cos(a), sin(a)
323 return begin[0] + length1*dir[0], begin[1] + length1*dir[1]
325 def _middle_b(self, end, dangle, length2, angle2):
326 # a = -math.pi + dangle + angle2
327 return self._middle_a(end, -math.pi+dangle, length2, -angle2)
329 def _missinglength(self, lenA, lenB, angleA):
330 # calculate lenC, where side A and angleA are opposite
331 tmp1 = lenB * cos(angleA)
332 tmp2 = sqrt(tmp1**2 - lenB**2 + lenA**2)
333 if tmp1 > tmp2: return tmp1 - tmp2
334 return tmp1 + tmp2
338 class line(line_pt):
340 """a line is the straight connector between the centers of two boxes"""
342 def __init__(self, box1, box2, boxdists=[0,0]):
344 boxdists_pt = (unit.topt(helper.getitemno(boxdists, 0)),
345 unit.topt(helper.getitemno(boxdists, 1)))
347 line_pt.__init__(self, box1, box2, boxdists=boxdists_pt)
350 class curve(curve_pt):
352 """a curve is the curved connector between the centers of two boxes.
353 The constructor needs both angle and bulge"""
356 def __init__(self, box1, box2,
357 relangle1=45, relangle2=45,
358 absangle1=None, absangle2=None,
359 absbulge=0, relbulge=0.39,
360 boxdists=[0,0]):
362 boxdists_pt = (unit.topt(helper.getitemno(boxdists, 0)),
363 unit.topt(helper.getitemno(boxdists, 1)))
365 curve_pt.__init__(self, box1, box2,
366 relangle1=relangle1, relangle2=relangle2,
367 absangle1=absangle1, absangle2=absangle2,
368 absbulge=unit.topt(absbulge), relbulge=relbulge,
369 boxdists=boxdists_pt)
371 class arc(arc_pt):
373 """an arc is a round connector between the centers of two boxes.
374 The constructor gets
375 either an angle in (-pi,pi)
376 or a bulge parameter in (-distance, distance)
377 (relbulge and absbulge are added)"""
379 def __init__(self, box1, box2, relangle=45,
380 absbulge=None, relbulge=None, boxdists=[0,0]):
382 boxdists_pt = (unit.topt(helper.getitemno(boxdists, 0)),
383 unit.topt(helper.getitemno(boxdists, 1)))
385 if absbulge is not None:
386 absbulge = unit.topt(absbulge)
387 arc_pt.__init__(self, box1, box2,
388 relangle=relangle,
389 absbulge=absbulge, relbulge=relbulge,
390 boxdists=boxdists_pt)
393 class twolines(twolines_pt):
395 """a twolines is a connector consisting of two straight lines.
396 The construcor takes a combination of angles and lengths:
397 either two angles (relative or absolute)
398 or two lenghts
399 or one length and one angle"""
401 def __init__(self, box1, box2,
402 absangle1=None, absangle2=None,
403 relangle1=None, relangle2=None, relangleM=None,
404 length1=None, length2=None,
405 bezierradius=None, beziersoftness=1,
406 arcradius=None,
407 boxdists=[0,0]):
409 boxdists_pt = (unit.topt(helper.getitemno(boxdists, 0)),
410 unit.topt(helper.getitemno(boxdists, 1)))
412 if length1 is not None:
413 length1 = unit.topt(length1)
414 if length2 is not None:
415 length2 = unit.topt(length2)
416 if bezierradius is not None:
417 bezierradius = unit.topt(bezierradius)
418 if arcradius is not None:
419 arcradius = unit.topt(arcradius)
420 twolines_pt.__init__(self, box1, box2,
421 absangle1=absangle1, absangle2=absangle2,
422 relangle1=relangle1, relangle2=relangle2,
423 relangleM=relangleM,
424 length1=length1, length2=length2,
425 bezierradius=bezierradius, beziersoftness=1,
426 arcradius=arcradius,
427 boxdists=boxdists_pt)