Applied upstream as r3028 r3025 r3024
[PyX/mjg.git] / pyx / connector.py
blob53a52445ee96ca386eafaf07f009666af34c67f7
1 # -*- coding: ISO-8859-1 -*-
4 # Copyright (C) 2003-2006 Michael Schindler <m-schindler@users.sourceforge.net>
6 # This file is part of PyX (http://pyx.sourceforge.net/).
8 # PyX is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 2 of the License, or
11 # (at your option) any later version.
13 # PyX is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with PyX; if not, write to the Free Software
20 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
23 import math
24 from math import pi, sin, cos, atan2, tan, hypot, acos, sqrt
25 import path, unit, mathutils, normpath
26 try:
27 from math import radians, degrees
28 except ImportError:
29 # fallback implementation for Python 2.1 and below
30 def radians(x): return x*pi/180
31 def degrees(x): return x*180/pi
34 #########################
35 ## helpers
36 #########################
38 class connector_pt(normpath.normpath):
40 def omitends(self, box1, box2):
41 """intersects a path with the boxes' paths"""
43 # cut off the start of self
44 # XXX how can decoration of this box1.path() be handled?
45 sp = self.intersect(box1.path())[0]
46 if sp:
47 self.normsubpaths = self.split(sp[-1:])[1].normsubpaths
49 # cut off the end of self
50 sp = self.intersect(box2.path())[0]
51 if sp:
52 self.normsubpaths = self.split(sp[:1])[0].normsubpaths
54 def shortenpath(self, dists):
55 """shortens a path by the given distances"""
57 # XXX later, this should be done by extended boxes instead of intersecting with circles
58 # cut off the start of self
59 center = self.atbegin_pt()
60 cutpath = path.circle_pt(center[0], center[1], dists[0])
61 try:
62 cutpath = cutpath.normpath()
63 except normpath.NormpathException:
64 pass
65 else:
66 sp = self.intersect(cutpath)[0]
67 self.normsubpaths = self.split(sp[-1:])[1].normsubpaths
69 # cut off the end of self
70 center = self.atend_pt()
71 cutpath = path.circle_pt(center[0], center[1], dists[1])
72 try:
73 cutpath = cutpath.normpath()
74 except normpath.NormpathException:
75 pass
76 else:
77 sp = self.intersect(cutpath)[0]
78 if sp:
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_pt(self.box1.center[0], self.box1.center[1],
96 self.box2.center[0], self.box2.center[1])], closed=0)])
98 self.omitends(box1, box2)
99 self.shortenpath(boxdists)
102 class arc_pt(connector_pt):
104 def __init__(self, box1, box2, relangle=45,
105 absbulge=None, relbulge=None, boxdists=[0,0]):
107 # the deviation of arc from the straight line can be specified:
108 # 1. By an angle between a straight line and the arc
109 # This angle is measured at the centers of the box.
110 # 2. By the largest normal distance between line and arc: absbulge
111 # or, equivalently, by the bulge relative to the length of the
112 # straight line from center to center.
113 # Only one can be used.
115 self.box1 = box1
116 self.box2 = box2
118 tangent = (self.box2.center[0] - self.box1.center[0],
119 self.box2.center[1] - self.box1.center[1])
120 distance = hypot(*tangent)
121 tangent = tangent[0] / distance, tangent[1] / distance
123 if relbulge is not None or absbulge is not None:
124 # usage of bulge overrides the relangle parameter
125 bulge = 0
126 if absbulge is not None:
127 bulge += absbulge
128 if relbulge is not None:
129 bulge += relbulge*distance
130 else:
131 # otherwise use relangle, which should be present
132 bulge = 0.5 * distance * math.tan(0.5*radians(relangle))
134 if abs(bulge) < normpath._epsilon:
135 # fallback solution for too straight arcs
136 connector_pt.__init__(self,
137 [path.normsubpath([path.normline_pt(*(self.box1.center+self.box2.center))], closed=0)])
138 else:
139 radius = abs(0.5 * (bulge + 0.25 * distance**2 / bulge))
140 centerdist = mathutils.sign(bulge) * (radius - abs(bulge))
141 center = (0.5 * (self.box1.center[0] + self.box2.center[0]) + tangent[1]*centerdist,
142 0.5 * (self.box1.center[1] + self.box2.center[1]) - tangent[0]*centerdist)
143 angle1 = atan2(self.box1.center[1] - center[1], self.box1.center[0] - center[0])
144 angle2 = atan2(self.box2.center[1] - center[1], self.box2.center[0] - center[0])
146 if bulge > 0:
147 connectorpath = path.path(path.moveto_pt(*self.box1.center),
148 path.arcn_pt(center[0], center[1], radius, degrees(angle1), degrees(angle2)))
149 connector_pt.__init__(self, connectorpath.normpath().normsubpaths)
150 else:
151 connectorpath = path.path(path.moveto_pt(*self.box1.center),
152 path.arc_pt(center[0], center[1], radius, degrees(angle1), degrees(angle2)))
153 connector_pt.__init__(self, connectorpath.normpath().normsubpaths)
155 self.omitends(box1, box2)
156 self.shortenpath(boxdists)
159 class curve_pt(connector_pt):
161 def __init__(self, box1, box2,
162 relangle1=45, relangle2=45,
163 absangle1=None, absangle2=None,
164 absbulge=0, relbulge=0.39, boxdists=[0,0]):
166 # The deviation of the curve from a straight line can be specified:
167 # A. By an angle at each center
168 # These angles are either absolute angles with origin at the positive x-axis
169 # or the relative angle with origin at the straight connection line
170 # B. By the (expected) largest normal distance between line and arc: absbulge
171 # and/or by the (expected) bulge relative to the length of the
172 # straight line from center to center.
173 # Here, we need both informations.
175 # a curve with relbulge=0.39 and relangle1,2=45 leads
176 # approximately to the arc with angle=45
178 self.box1 = box1
179 self.box2 = box2
181 rel = (self.box2.center[0] - self.box1.center[0],
182 self.box2.center[1] - self.box1.center[1])
183 distance = hypot(*rel)
184 # absolute angle of the straight connection
185 dangle = atan2(rel[1], rel[0])
187 # calculate the armlength and absolute angles for the control points:
188 # absolute and relative bulges are added
189 bulge = abs(distance*relbulge + absbulge)
191 if absangle1 is not None:
192 angle1 = radians(absangle1)
193 else:
194 angle1 = dangle + radians(relangle1)
195 if absangle2 is not None:
196 angle2 = radians(absangle2)
197 else:
198 angle2 = dangle + radians(relangle2)
200 # get the control points
201 control1 = (cos(angle1), sin(angle1))
202 control2 = (cos(angle2), sin(angle2))
203 control1 = (self.box1.center[0] + control1[0] * bulge, self.box1.center[1] + control1[1] * bulge)
204 control2 = (self.box2.center[0] - control2[0] * bulge, self.box2.center[1] - control2[1] * bulge)
206 connector_pt.__init__(self,
207 [path.normsubpath([path.normcurve_pt(*(self.box1.center +
208 control1 +
209 control2 + self.box2.center))], 0)])
211 self.omitends(box1, box2)
212 self.shortenpath(boxdists)
215 class twolines_pt(connector_pt):
217 def __init__(self, box1, box2,
218 absangle1=None, absangle2=None,
219 relangle1=None, relangle2=None, relangleM=None,
220 length1=None, length2=None,
221 bezierradius=None, beziersoftness=1,
222 arcradius=None,
223 boxdists=[0,0]):
225 # The connection with two lines can be done in the following ways:
226 # 1. an angle at each box-center
227 # 2. two armlengths (if they are long enough)
228 # 3. angle and armlength at the same box
229 # 4. angle and armlength at different boxes
230 # 5. one armlength and the angle between the arms
232 # Angles at the box-centers can be relative or absolute
233 # The angle in the middle is always relative
234 # lengths are always absolute
236 self.box1 = box1
237 self.box2 = box2
239 begin = self.box1.center
240 end = self.box2.center
241 rel = (self.box2.center[0] - self.box1.center[0],
242 self.box2.center[1] - self.box1.center[1])
243 distance = hypot(*rel)
244 dangle = atan2(rel[1], rel[0])
246 # find out what arguments are given:
247 if relangle1 is not None: relangle1 = radians(relangle1)
248 if relangle2 is not None: relangle2 = radians(relangle2)
249 if relangleM is not None: relangleM = radians(relangleM)
250 # absangle has priority over relangle:
251 if absangle1 is not None: relangle1 = dangle - radians(absangle1)
252 if absangle2 is not None: relangle2 = math.pi - dangle + radians(absangle2)
254 # check integrity of arguments
255 no_angles, no_lengths=0,0
256 for anangle in (relangle1, relangle2, relangleM):
257 if anangle is not None: no_angles += 1
258 for alength in (length1, length2):
259 if alength is not None: no_lengths += 1
261 if no_angles + no_lengths != 2:
262 raise NotImplementedError, "Please specify exactly two angles or lengths"
264 # calculate necessary angles and armlengths
265 # always length1 and relangle1
267 # the case with two given angles
268 # use the "sine-theorem" for calculating length1
269 if no_angles == 2:
270 if relangle1 is None: relangle1 = math.pi - relangle2 - relangleM
271 elif relangle2 is None: relangle2 = math.pi - relangle1 - relangleM
272 elif relangleM is None: relangleM = math.pi - relangle1 - relangle2
273 length1 = distance * abs(sin(relangle2)/sin(relangleM))
274 middle = self._middle_a(begin, dangle, length1, relangle1)
275 # the case with two given lengths
276 # uses the "cosine-theorem" for calculating length1
277 elif no_lengths == 2:
278 relangle1 = acos((distance**2 + length1**2 - length2**2) / (2.0*distance*length1))
279 middle = self._middle_a(begin, dangle, length1, relangle1)
280 # the case with one length and one angle
281 else:
282 if relangle1 is not None:
283 if length1 is not None:
284 middle = self._middle_a(begin, dangle, length1, relangle1)
285 elif length2 is not None:
286 length1 = self._missinglength(length2, distance, relangle1)
287 middle = self._middle_a(begin, dangle, length1, relangle1)
288 elif relangle2 is not None:
289 if length1 is not None:
290 length2 = self._missinglength(length1, distance, relangle2)
291 middle = self._middle_b(end, dangle, length2, relangle2)
292 elif length2 is not None:
293 middle = self._middle_b(end, dangle, length2, relangle2)
294 elif relangleM is not None:
295 if length1 is not None:
296 length2 = self._missinglength(distance, length1, relangleM)
297 relangle1 = acos((distance**2 + length1**2 - length2**2) / (2.0*distance*length1))
298 middle = self._middle_a(begin, dangle, length1, relangle1)
299 elif length2 is not None:
300 length1 = self._missinglength(distance, length2, relangleM)
301 relangle1 = acos((distance**2 + length1**2 - length2**2) / (2.0*distance*length1))
302 middle = self._middle_a(begin, dangle, length1, relangle1)
303 else:
304 raise NotImplementedError, "I found a strange combination of arguments"
306 connectorpath = path.path(path.moveto_pt(*self.box1.center),
307 path.lineto_pt(*middle),
308 path.lineto_pt(*self.box2.center))
309 connector_pt.__init__(self, connectorpath.normpath().normsubpaths)
311 self.omitends(box1, box2)
312 self.shortenpath(boxdists)
314 def _middle_a(self, begin, dangle, length1, angle1):
315 a = dangle - angle1
316 dir = cos(a), sin(a)
317 return begin[0] + length1*dir[0], begin[1] + length1*dir[1]
319 def _middle_b(self, end, dangle, length2, angle2):
320 # a = -math.pi + dangle + angle2
321 return self._middle_a(end, -math.pi+dangle, length2, -angle2)
323 def _missinglength(self, lenA, lenB, angleA):
324 # calculate lenC, where side A and angleA are opposite
325 tmp1 = lenB * cos(angleA)
326 tmp2 = sqrt(tmp1**2 - lenB**2 + lenA**2)
327 if tmp1 > tmp2: return tmp1 - tmp2
328 return tmp1 + tmp2
332 class line(line_pt):
334 """a line is the straight connector between the centers of two boxes"""
336 def __init__(self, box1, box2, boxdists=(0,0)):
337 line_pt.__init__(self, box1, box2, boxdists=map(unit.topt, boxdists))
340 class curve(curve_pt):
342 """a curve is the curved connector between the centers of two boxes.
343 The constructor needs both angle and bulge"""
346 def __init__(self, box1, box2,
347 relangle1=45, relangle2=45,
348 absangle1=None, absangle2=None,
349 absbulge=0, relbulge=0.39,
350 boxdists=[0,0]):
351 curve_pt.__init__(self, box1, box2,
352 relangle1=relangle1, relangle2=relangle2,
353 absangle1=absangle1, absangle2=absangle2,
354 absbulge=unit.topt(absbulge), relbulge=relbulge,
355 boxdists=map(unit.topt, boxdists))
357 class arc(arc_pt):
359 """an arc is a round connector between the centers of two boxes.
360 The constructor gets
361 either an angle in (-pi,pi)
362 or a bulge parameter in (-distance, distance)
363 (relbulge and absbulge are added)"""
365 def __init__(self, box1, box2, relangle=45,
366 absbulge=None, relbulge=None, boxdists=[0,0]):
367 if absbulge is not None:
368 absbulge = unit.topt(absbulge)
369 arc_pt.__init__(self, box1, box2,
370 relangle=relangle,
371 absbulge=absbulge, relbulge=relbulge,
372 boxdists=map(unit.topt, boxdists))
375 class twolines(twolines_pt):
377 """a twolines is a connector consisting of two straight lines.
378 The construcor takes a combination of angles and lengths:
379 either two angles (relative or absolute)
380 or two lenghts
381 or one length and one angle"""
383 def __init__(self, box1, box2,
384 absangle1=None, absangle2=None,
385 relangle1=None, relangle2=None, relangleM=None,
386 length1=None, length2=None,
387 bezierradius=None, beziersoftness=1,
388 arcradius=None,
389 boxdists=[0,0]):
390 if length1 is not None:
391 length1 = unit.topt(length1)
392 if length2 is not None:
393 length2 = unit.topt(length2)
394 if bezierradius is not None:
395 bezierradius = unit.topt(bezierradius)
396 if arcradius is not None:
397 arcradius = unit.topt(arcradius)
398 twolines_pt.__init__(self, box1, box2,
399 absangle1=absangle1, absangle2=absangle2,
400 relangle1=relangle1, relangle2=relangle2,
401 relangleM=relangleM,
402 length1=length1, length2=length2,
403 bezierradius=bezierradius, beziersoftness=1,
404 arcradius=arcradius,
405 boxdists=map(unit.topt, boxdists))