allow empty paramlist in normath._split_pt -- and some consequence in connector
[PyX/mjg.git] / pyx / connector.py
blobcc34164569f08198181d018f2e05f91d99b32734
1 #!/usr/bin/env python
2 # -*- coding: ISO-8859-1 -*-
5 # Copyright (C) 2003-2006 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
24 import math
25 from math import pi, sin, cos, atan2, tan, hypot, acos, sqrt
26 import path, unit, mathutils, normpath
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(normpath.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.atbegin_pt()
61 cutpath = path.circle_pt(center[0], center[1], dists[0])
62 try:
63 cutpath = cutpath.normpath()
64 except normpath.NormpathException:
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.atend_pt()
72 cutpath = path.circle_pt(center[0], center[1], dists[1])
73 try:
74 cutpath = cutpath.normpath()
75 except normpath.NormpathException:
76 pass
77 else:
78 sp = self.intersect(cutpath)[0]
79 if sp:
80 self.normsubpaths = self.split(sp[:1])[0].normsubpaths
83 ################
84 ## classes
85 ################
88 class line_pt(connector_pt):
90 def __init__(self, box1, box2, boxdists=[0,0]):
92 self.box1 = box1
93 self.box2 = box2
95 connector_pt.__init__(self,
96 [path.normsubpath([path.normline_pt(self.box1.center[0], self.box1.center[1],
97 self.box2.center[0], self.box2.center[1])], closed=0)])
99 self.omitends(box1, box2)
100 self.shortenpath(boxdists)
103 class arc_pt(connector_pt):
105 def __init__(self, box1, box2, relangle=45,
106 absbulge=None, relbulge=None, boxdists=[0,0]):
108 # the deviation of arc from the straight line can be specified:
109 # 1. By an angle between a straight line and the arc
110 # This angle is measured at the centers of the box.
111 # 2. By the largest normal distance between line and arc: absbulge
112 # or, equivalently, by the bulge relative to the length of the
113 # straight line from center to center.
114 # Only one can be used.
116 self.box1 = box1
117 self.box2 = box2
119 tangent = (self.box2.center[0] - self.box1.center[0],
120 self.box2.center[1] - self.box1.center[1])
121 distance = hypot(*tangent)
122 tangent = tangent[0] / distance, tangent[1] / distance
124 if relbulge is not None or absbulge is not None:
125 # usage of bulge overrides the relangle parameter
126 bulge = 0
127 if absbulge is not None:
128 bulge += absbulge
129 if relbulge is not None:
130 bulge += relbulge*distance
131 else:
132 # otherwise use relangle, which should be present
133 bulge = 0.5 * distance * math.tan(0.5*radians(relangle))
135 if abs(bulge) < normpath._epsilon:
136 # fallback solution for too straight arcs
137 connector_pt.__init__(self,
138 [path.normsubpath([path.normline_pt(*(self.box1.center+self.box2.center))], closed=0)])
139 else:
140 radius = abs(0.5 * (bulge + 0.25 * distance**2 / bulge))
141 centerdist = mathutils.sign(bulge) * (radius - abs(bulge))
142 center = (0.5 * (self.box1.center[0] + self.box2.center[0]) + tangent[1]*centerdist,
143 0.5 * (self.box1.center[1] + self.box2.center[1]) - tangent[0]*centerdist)
144 angle1 = atan2(self.box1.center[1] - center[1], self.box1.center[0] - center[0])
145 angle2 = atan2(self.box2.center[1] - center[1], self.box2.center[0] - center[0])
147 if bulge > 0:
148 connectorpath = path.path(path.moveto_pt(*self.box1.center),
149 path.arcn_pt(center[0], center[1], radius, degrees(angle1), degrees(angle2)))
150 connector_pt.__init__(self, connectorpath.normpath().normsubpaths)
151 else:
152 connectorpath = path.path(path.moveto_pt(*self.box1.center),
153 path.arc_pt(center[0], center[1], radius, degrees(angle1), degrees(angle2)))
154 connector_pt.__init__(self, connectorpath.normpath().normsubpaths)
156 self.omitends(box1, box2)
157 self.shortenpath(boxdists)
160 class curve_pt(connector_pt):
162 def __init__(self, box1, box2,
163 relangle1=45, relangle2=45,
164 absangle1=None, absangle2=None,
165 absbulge=0, relbulge=0.39, boxdists=[0,0]):
167 # The deviation of the curve from a straight line can be specified:
168 # A. By an angle at each center
169 # These angles are either absolute angles with origin at the positive x-axis
170 # or the relative angle with origin at the straight connection line
171 # B. By the (expected) largest normal distance between line and arc: absbulge
172 # and/or by the (expected) bulge relative to the length of the
173 # straight line from center to center.
174 # Here, we need both informations.
176 # a curve with relbulge=0.39 and relangle1,2=45 leads
177 # approximately to the arc with angle=45
179 self.box1 = box1
180 self.box2 = box2
182 rel = (self.box2.center[0] - self.box1.center[0],
183 self.box2.center[1] - self.box1.center[1])
184 distance = hypot(*rel)
185 # absolute angle of the straight connection
186 dangle = atan2(rel[1], rel[0])
188 # calculate the armlength and absolute angles for the control points:
189 # absolute and relative bulges are added
190 bulge = abs(distance*relbulge + absbulge)
192 if absangle1 is not None:
193 angle1 = radians(absangle1)
194 else:
195 angle1 = dangle + radians(relangle1)
196 if absangle2 is not None:
197 angle2 = radians(absangle2)
198 else:
199 angle2 = dangle + radians(relangle2)
201 # get the control points
202 control1 = (cos(angle1), sin(angle1))
203 control2 = (cos(angle2), sin(angle2))
204 control1 = (self.box1.center[0] + control1[0] * bulge, self.box1.center[1] + control1[1] * bulge)
205 control2 = (self.box2.center[0] - control2[0] * bulge, self.box2.center[1] - control2[1] * bulge)
207 connector_pt.__init__(self,
208 [path.normsubpath([path.normcurve_pt(*(self.box1.center +
209 control1 +
210 control2 + self.box2.center))], 0)])
212 self.omitends(box1, box2)
213 self.shortenpath(boxdists)
216 class twolines_pt(connector_pt):
218 def __init__(self, box1, box2,
219 absangle1=None, absangle2=None,
220 relangle1=None, relangle2=None, relangleM=None,
221 length1=None, length2=None,
222 bezierradius=None, beziersoftness=1,
223 arcradius=None,
224 boxdists=[0,0]):
226 # The connection with two lines can be done in the following ways:
227 # 1. an angle at each box-center
228 # 2. two armlengths (if they are long enough)
229 # 3. angle and armlength at the same box
230 # 4. angle and armlength at different boxes
231 # 5. one armlength and the angle between the arms
233 # Angles at the box-centers can be relative or absolute
234 # The angle in the middle is always relative
235 # lengths are always absolute
237 self.box1 = box1
238 self.box2 = box2
240 begin = self.box1.center
241 end = self.box2.center
242 rel = (self.box2.center[0] - self.box1.center[0],
243 self.box2.center[1] - self.box1.center[1])
244 distance = hypot(*rel)
245 dangle = atan2(rel[1], rel[0])
247 # find out what arguments are given:
248 if relangle1 is not None: relangle1 = radians(relangle1)
249 if relangle2 is not None: relangle2 = radians(relangle2)
250 if relangleM is not None: relangleM = radians(relangleM)
251 # absangle has priority over relangle:
252 if absangle1 is not None: relangle1 = dangle - radians(absangle1)
253 if absangle2 is not None: relangle2 = math.pi - dangle + radians(absangle2)
255 # check integrity of arguments
256 no_angles, no_lengths=0,0
257 for anangle in (relangle1, relangle2, relangleM):
258 if anangle is not None: no_angles += 1
259 for alength in (length1, length2):
260 if alength is not None: no_lengths += 1
262 if no_angles + no_lengths != 2:
263 raise NotImplementedError, "Please specify exactly two angles or lengths"
265 # calculate necessary angles and armlengths
266 # always length1 and relangle1
268 # the case with two given angles
269 # use the "sine-theorem" for calculating length1
270 if no_angles == 2:
271 if relangle1 is None: relangle1 = math.pi - relangle2 - relangleM
272 elif relangle2 is None: relangle2 = math.pi - relangle1 - relangleM
273 elif relangleM is None: relangleM = math.pi - relangle1 - relangle2
274 length1 = distance * abs(sin(relangle2)/sin(relangleM))
275 middle = self._middle_a(begin, dangle, length1, relangle1)
276 # the case with two given lengths
277 # uses the "cosine-theorem" for calculating length1
278 elif no_lengths == 2:
279 relangle1 = acos((distance**2 + length1**2 - length2**2) / (2.0*distance*length1))
280 middle = self._middle_a(begin, dangle, length1, relangle1)
281 # the case with one length and one angle
282 else:
283 if relangle1 is not None:
284 if length1 is not None:
285 middle = self._middle_a(begin, dangle, length1, relangle1)
286 elif length2 is not None:
287 length1 = self._missinglength(length2, distance, relangle1)
288 middle = self._middle_a(begin, dangle, length1, relangle1)
289 elif relangle2 is not None:
290 if length1 is not None:
291 length2 = self._missinglength(length1, distance, relangle2)
292 middle = self._middle_b(end, dangle, length2, relangle2)
293 elif length2 is not None:
294 middle = self._middle_b(end, dangle, length2, relangle2)
295 elif relangleM is not None:
296 if length1 is not None:
297 length2 = self._missinglength(distance, length1, relangleM)
298 relangle1 = acos((distance**2 + length1**2 - length2**2) / (2.0*distance*length1))
299 middle = self._middle_a(begin, dangle, length1, relangle1)
300 elif length2 is not None:
301 length1 = self._missinglength(distance, length2, relangleM)
302 relangle1 = acos((distance**2 + length1**2 - length2**2) / (2.0*distance*length1))
303 middle = self._middle_a(begin, dangle, length1, relangle1)
304 else:
305 raise NotImplementedError, "I found a strange combination of arguments"
307 connectorpath = path.path(path.moveto_pt(*self.box1.center),
308 path.lineto_pt(*middle),
309 path.lineto_pt(*self.box2.center))
310 connector_pt.__init__(self, connectorpath.normpath().normsubpaths)
312 self.omitends(box1, box2)
313 self.shortenpath(boxdists)
315 def _middle_a(self, begin, dangle, length1, angle1):
316 a = dangle - angle1
317 dir = cos(a), sin(a)
318 return begin[0] + length1*dir[0], begin[1] + length1*dir[1]
320 def _middle_b(self, end, dangle, length2, angle2):
321 # a = -math.pi + dangle + angle2
322 return self._middle_a(end, -math.pi+dangle, length2, -angle2)
324 def _missinglength(self, lenA, lenB, angleA):
325 # calculate lenC, where side A and angleA are opposite
326 tmp1 = lenB * cos(angleA)
327 tmp2 = sqrt(tmp1**2 - lenB**2 + lenA**2)
328 if tmp1 > tmp2: return tmp1 - tmp2
329 return tmp1 + tmp2
333 class line(line_pt):
335 """a line is the straight connector between the centers of two boxes"""
337 def __init__(self, box1, box2, boxdists=(0,0)):
338 line_pt.__init__(self, box1, box2, boxdists=map(unit.topt, boxdists))
341 class curve(curve_pt):
343 """a curve is the curved connector between the centers of two boxes.
344 The constructor needs both angle and bulge"""
347 def __init__(self, box1, box2,
348 relangle1=45, relangle2=45,
349 absangle1=None, absangle2=None,
350 absbulge=0, relbulge=0.39,
351 boxdists=[0,0]):
352 curve_pt.__init__(self, box1, box2,
353 relangle1=relangle1, relangle2=relangle2,
354 absangle1=absangle1, absangle2=absangle2,
355 absbulge=unit.topt(absbulge), relbulge=relbulge,
356 boxdists=map(unit.topt, boxdists))
358 class arc(arc_pt):
360 """an arc is a round connector between the centers of two boxes.
361 The constructor gets
362 either an angle in (-pi,pi)
363 or a bulge parameter in (-distance, distance)
364 (relbulge and absbulge are added)"""
366 def __init__(self, box1, box2, relangle=45,
367 absbulge=None, relbulge=None, boxdists=[0,0]):
368 if absbulge is not None:
369 absbulge = unit.topt(absbulge)
370 arc_pt.__init__(self, box1, box2,
371 relangle=relangle,
372 absbulge=absbulge, relbulge=relbulge,
373 boxdists=map(unit.topt, boxdists))
376 class twolines(twolines_pt):
378 """a twolines is a connector consisting of two straight lines.
379 The construcor takes a combination of angles and lengths:
380 either two angles (relative or absolute)
381 or two lenghts
382 or one length and one angle"""
384 def __init__(self, box1, box2,
385 absangle1=None, absangle2=None,
386 relangle1=None, relangle2=None, relangleM=None,
387 length1=None, length2=None,
388 bezierradius=None, beziersoftness=1,
389 arcradius=None,
390 boxdists=[0,0]):
391 if length1 is not None:
392 length1 = unit.topt(length1)
393 if length2 is not None:
394 length2 = unit.topt(length2)
395 if bezierradius is not None:
396 bezierradius = unit.topt(bezierradius)
397 if arcradius is not None:
398 arcradius = unit.topt(arcradius)
399 twolines_pt.__init__(self, box1, box2,
400 absangle1=absangle1, absangle2=absangle2,
401 relangle1=relangle1, relangle2=relangle2,
402 relangleM=relangleM,
403 length1=length1, length2=length2,
404 bezierradius=bezierradius, beziersoftness=1,
405 arcradius=arcradius,
406 boxdists=map(unit.topt, boxdists))