BOSL2 icon indicating copy to clipboard operation
BOSL2 copied to clipboard

Proposal: joined_circles() - asymmetric glued circles with tangent waist arcs

Open JasonKoolman opened this issue 1 year ago • 8 comments

Hi, I’ve been experimenting with an extension of glued_circles() that supports different radii for the two circles. The inspiration came from this article. I thought it might be of interest for BOSL2 since the existing glued_circles() only handles equal radii.

I needed two different radii to create a ball joint, but I can see more interesting and valid use cases for it as well.

Image

Here is the code:

/**
 * Creates a closed 2D outline of two circles smoothly joined by tangent
 * waist arcs. The outline runs clockwise starting from the rightmost point,
 * and follows the left outer arc, bottom waist, right outer arc, and top
 * waist back to the start. Waist arcs are constructed as exact tangents,
 * so the outline has no skew or gaps. Unlike `glued_circles()`, the two
 * circles may have different radii.
 *
 * The waist arcs exist only if the enlarged circles (r1+rb and r2+rb)
 * intersect; otherwise an error is raised. Larger values of `rb` produce
 * a fuller, rounder waist. The resulting path is suitable for use with
 * `polygon()` or `stroke()`.
 *
 * @param r1      Radius of the left circle, alternative to `d1`.
 * @param r2      Radius of the right circle, alternative to `d2`.
 * @param spread  Distance between circle centers along the X axis.
 * @param rb      Blend radius that controls the curvature of the waist arcs.
 * @param d1      Diameter of the left circle, alternative to `r1`.
 * @param d2      Diameter of the right circle, alternative to `r2`.
 * @param anchor  Anchor setting passed to `reorient()`.
 * @param spin    Rotation in degrees passed to `reorient()`.
 * @return        A list of 2D points.
 */
function joined_circles(r1, r2, spread, rb, d1, d2, anchor, spin) =
    let(
        // radii + centers
        rL = get_radius(r=r1, d=d1, dflt=10),
        rR = get_radius(r=r2, d=d2, dflt=10),
        CL = [-spread/2, 0],
        CR = [ spread/2, 0],

        // waist data (centers & tangency points)
        Ccand = circle_circle_intersection(r1=rL+rb, cp1=CL, r2=rR+rb, cp2=CR),
        Ccheck = assert(len(Ccand) > 1, "No waist arcs possible with these parameters"),

        Ctop = Ccand[0].y > Ccand[1].y ? Ccand[0] : Ccand[1],
        Cbot = Ccand[0].y < Ccand[1].y ? Ccand[0] : Ccand[1],

        TLt = CL + rL*unit(Ctop-CL),
        TRt = CR + rR*unit(Ctop-CR),
        TLb = CL + rL*unit(Cbot-CL),
        TRb = CR + rR*unit(Cbot-CR),

        // angles for outer arcs (ensure we go the long way around the outside)
        aLt = atan2(TLt.y-CL.y, TLt.x-CL.x),
        aLb = atan2(TLb.y-CL.y, TLb.x-CL.x),
        saL = aLt,
        eaL = (aLb < saL ? aLb + 360 : aLb), // left outer: top→bottom via outside

        aRb = atan2(TRb.y-CR.y, TRb.x-CR.x),
        aRt = atan2(TRt.y-CR.y, TRt.x-CR.x),
        saR = aRb,
        eaR = (aRt < saR ? aRt + 360 : aRt), // right outer: bottom→top via outside

        // build each segment
        left_outer   = arc(n=ceil(segs(rL)*abs(eaL-saL)/360)+1, r=rL, cp=CL, angle=[saL,eaL], endpoint=true),
        bottom_waist = _minor_arc(Cbot, TLb, TRb, endpoint=false),
        right_outer  = arc(n=ceil(segs(rR)*abs(eaR-saR)/360)+1, r=rR, cp=CR, angle=[saR,eaR], endpoint=true),
        top_waist    = _minor_arc(Ctop, TRt, TLt, endpoint=false),

        // concatenate while dropping the first point of each subsequent segment
        path = concat(
            left_outer,
            select(bottom_waist, 1, -1),
            right_outer,
            select(top_waist, 1, -1)
        ),

        // start from rightmost x
        maxx_idx = max_index(column(path, 0)),
        pts      = reverse_polygon(list_rotate(path, maxx_idx))
    ) reorient(anchor, spin, p = pts, two_d = true, path = pts, extent=true);

/**
 * Minor arc between two points A and B, centered at C.
 *
 * When `endpoint=true` (default) the returned point list includes the exact
 * start/end points A and B. This avoids tiny "skews" at the tangency.
 *
 * @param C         Center point of the arc (undefined for no arc).
 * @param A         Start point of the arc.
 * @param B         End point of the arc.
 * @param endpoint  Include both endpoints in the list. Default: true.
 * @return          List of 2D points along the *shortest* (minor) arc from A to B.
 */
function _minor_arc(C, A, B, endpoint=true) =
    let(
        r   = hypot(A.y-C.y, A.x-C.x),
        a1  = atan2(A.y-C.y, A.x-C.x),
        a2  = atan2(B.y-C.y, B.x-C.x),
        da  = (a2 - a1 + 540)%360 - 180,  // shortest turn (-180..180]
        n   = endpoint == true
              ? max(2, ceil(segs(r)*abs(da)/360) + 1)
              : max(3, ceil(segs(r)*abs(da)/360))
    ) arc(n=n, r=r, cp=C, angle=[a1, a1+da], endpoint=endpoint);

Some examples:

Image Image Image

The only thing I don’t really like about this method compared to glued_circles() is that we have to supply a blending circle diameter instead of a tangent. The tangent parameter produces more consistent results, while the blend circle is coupled to the spread and can feel less intuitive.

I tried to create a solver to map a tangent angle or waist thickness into a blend radius, but failed and I suspect it might be computationally heavy anyway. Maybe someone else has better ideas.

JasonKoolman avatar Oct 02 '25 08:10 JasonKoolman

I can probably work out the required math if we identify the desired problem statement. It's not entirely obvious to me what that is. It seems like you would like to be able to generate the "flat" case without a lot of trouble. When circles are identical this is 90 deg, but it's complicated when circles are different sizes---requires a trig calculation. So requiring a tangent angle isn't obviously the best measure with mismatched circles. It seems like maybe specifying the deviation from the "flat" case might be a natural idea. More specifically, specifying the difference between the wait thickness of the object produced and the waist thickness for the flat case, so this parameter would be zero to produce a flat output, and then you could make it positive to get a bulging shape and negative to get a concave shape. Waist thickness also has the problem of being more complex to relate to the flat case (it's a bit unclear what it means since there's no waist in that case....so where is the waist?) Actually looks like code above can't produce bulging case, and flat case requires rb=inf.

Actually going back to tangent angle, it looks like it's impossible. That is, for a pair of given tangent angles with mis-matched circles there doesn't usually exist a circular arc tangent to the circles at the specified points. If you specify the tangent angle to circle 1 only then we can compute the required radius like this:

function findR(r1,r2,spread,tangent) =
  let(
       ang1 = 90-tangent,
       distpair = function(ang2)
           let(
                  ray1 = right(-spread/2,zrot(ang1,[r1,0])),
                  ray2 = right(spread/2,zrot(ang2,[r2,0])),
                  cp = line_intersection([[-spread/2,0],ray1], [[spread/2,0],ray2], RAY, RAY),
                  rest1 = norm(cp-ray1),
                  rest2 = norm(cp-ray2),
           )
           [rest1,rest2],
       error = function(ang2) let(d=distpair(ang2)) d[0]-d[1],           
       tan_pts = circle_circle_tangents(r1,[-spread/2,0],r2,[spread/2,0]),
       dummy=assert(len(tan_pts)>0),
       fe=echo(tan_pts=tan_pts[1]), 
       min_ang2 = atan2(tan_pts[0][1].y, tan_pts[0][1].x-spread/2),
       max_ang2 = 170,   // What's a good value for this?  
       dummy2=echo(error(min_ang2),error(max_ang2)),
       ang2 = root_find(error, min_ang2, 170),
       rblend = distpair(ang2)[0]
   )
   rblend;

This also internally produces all the other information needed to make the arc (center point and endpoints).

I still specifying tangent is still not easy to use, though. It's easy to pick tangent angles that are impossible and not obvious what the valid range is. We may need to support tangent angle for backward compatibility, but the idea of a waist based measure is appealing. Actually now I think maybe multiplicative. Like 1 gives a flat join, and close to zero gives a zero think waist, and 1/2 gives a half-thick waist. Larger than 1 would give a bulge. Above code is going to fail for bulges. That requires a separate case because the center is on the other side. But your code doesn't do bulges at the moment.

Why do you need _minor_arc? It seems like it's equivalent to arc(cp=C, points=[A,B]);

adrianVmariano avatar Oct 02 '25 16:10 adrianVmariano

The blending radius corresponding to a waist can be found like this:

function findR_waist(r1,r2,s,waist) =
  let(
       A = (r1^2-r2^2)/2/s+s/2,
       B = (r1-r2)/s,
       rts=quadratic_roots(B^2,
                           2*A*B-2*r1+waist,
                           A^2+(waist/2)^2 - r1^2,real=true),
       f=echo(rts=rts)  // larger root is the outer tangent circle
  )
  min(rts);

There is a problem with specifying waist, though, which is that there's a range of concave shapes for which it's not a well defined thing, basically as soon as the waist exceeds the diameter of the smaller circle.

Here's the same approach for specifying tangent angle on circle 1:

function findRang(r1,r2,s,ang) =
  let(
       tan_pts = circle_circle_tangents(r1,[-s/2,0], r2,[s/2,0]),
       maxang = atan2(tan_pts[0][0].y, tan_pts[0][0].x+s/2),
       dummy=echo(maxang=maxang),
       alpha = 90-ang,
       A = (r1^2-r2^2)/2/s+s/2,
       B = (r1-r2)/s,
       rts = quadratic_roots(B^2-cos(alpha)^2,
                             2*A*B-2*cos(alpha)^2*r1,
                             A^2-cos(alpha)^2*r1^2,real=true),
       f=echo(rts=rts)
         // negative root gives the bulging case (inverted)
  )
  alpha<=90 ? rts[0] : rts[1];

I think we can turn the 2nd one into a full solution, but it's not so clear about the first one given trouble defining what the waist is.

adrianVmariano avatar Oct 02 '25 21:10 adrianVmariano

function findR_tang(r1,r2,s,ang) =
  let(
       A = (r1^2-r2^2)/2/s+s/2,
       B = (r1-r2)/s,
       maxang = acos(B),
       alpha = 90-ang > maxang ? 90+ang : 90-ang, 
       rts = quadratic_roots(B^2-cos(alpha)^2,
                             2*A*B-2*cos(alpha)^2*r1,
                             A^2-cos(alpha)^2*r1^2,real=true),
       f=echo(rts=rts)
         // negative root gives the bulging case (inverted)
  )
  90-ang>maxang ? alpha>=90 ? rts[0] : rts[1]
                :  alpha<=90 ? rts[0] : rts[1];

r1=10;
r2=17;
s=24;
ang=31;

rr = findR_tang(r1,r2,s,ang);
left(s/2)stroke(circle(r=r1),width=.1);
right(s/2)stroke(circle(r=r2),width=.1);
pts=circle_circle_intersection( abs(r1+rr),[-s/2,0], abs(r2+rr), [s/2,0]);
color("red")move(pts[rr<0?1:0])stroke(circle(r=abs(rr)), width=.1);
left(s/2)stroke([[0,0],zrot(90-ang,[r1,0])], width=.1, color="purple", endcap2="arrow2");

I think the above is the general solution based on specifying the tangent to circle 1. Except the linear degenerate case isn't treated. That will occur if alpha==maxang. In that case you just don't draw any points for the connecting arc.
I think rather than calculating angles this can be neatly done by finding the intersections with the circles and using those intersections for all the arcs. It might be tidiest to compute the bottom half, so it starts at the right point, and then mirror and reverse that to make the top half.

There is also another degenerate case of tangent = -90. And some check is needed that tangent is large enough that the connecting arc doesn't cross the X axis.

adrianVmariano avatar Oct 03 '25 02:10 adrianVmariano

First of all, great and solid write-up! I also find “waist thickness” very intuitive - right up until the circles intersect, as you noted. Once there’s overlap the waist isn’t well defined and that control falls apart. The “tangent on circle-1” approach feels sound and keeps the look consistent as spread changes, but it’s less obvious for end users and I’m not fully sure how to guard the degenerate ends in a way that’s easy to expose.

What I’d love is a single knob for users and do the math under the hood.

A couple of ideas I was thinking of:

  1. A blend in [0..1] where 0 = just-touch and 1 = flat (omit the connecting arc). If spread ≥ r1+r2 I’d drive by waist and solve rb from the quadratic; if spread < r1+r2 I’d switch to tangent-on-circle-1 and map blend into a safe angle range between the “just-touch” limit and the gap-facing common tangent. I’m not sure about the exact mapping/bounds here, and this might feel a bit “magical.”

  2. Simply forbid overlap (require spread ≥ r1+r2) and keep a single waist parameter; very intuitive, maybe allow negative for a bulge. That keeps the mental model clear: two circles connected by a waist/neck.

  3. Default to two circles with a straight neck of width min(r1,r2) (keyhole-like), then add a curvature parameter that morphs the neck from straight → concave/convex. Overlap would still be disallowed. Sounds good on paper (it would be combination of keyhole(), egg() and glued_circles), but I’m not sure it holds up in practice.

You’re right that the problem statement (what shape I'm actually trying to produce) needs to be crisp. I feel like the second solution is the most logical.

JasonKoolman avatar Oct 03 '25 10:10 JasonKoolman

First of all, to make sure we're on the same page, we're talking about an expansion of glued_circles here, not a second function that does the same thing. That means we can add functionality, but we also need to maintain compatibility with what the current interface does. The failure of waist to be well-defined happens even if the circles do not overlap. Here's the basic case. Small circle r=10, waist=10. The box shows the waist size.

Image

Now if I push the waist up to the max value where there's a solution it's basically when the waist equals the diameter of the smaller circle. And we get this:

Image

It doesn't look very waist-like at this point. But also note we're not flat yet. There's still a parameter range beyond this, between this case and the case where the circles are connected by a line. There's not an obvious notion of waist here, so how can you extend the parameter to cover that range? The same problem happens with bulging. Here's the minimal bulge for an example, which happens when the bulge is basically equal the larger circle diam:

Image

So in between this case and the preceding case there's a region where neither bulge nor waist have an obvious meaning, as shown here:

Image

I don't understand your concern about the overlapping circle case. The waist is perfectly well defined there, just like when they don't overlap.

Image

The only difference is that the minimum waist is defined by the circle intersection point instead of being zero like for well separated circles. When the computed blending radius goes negative that signals that you've requested a waist that is too small. Or you could compare the waist to the circle intersection y value.

A single knob is ideal if it can be done. But I'm not seeing how to handle that transition region. One idea would be to give up on the transition region and add waist as a parameter that only works over a limited domain (you use tangent angle for other cases), though we do potentially end up with a weird requirement that waist < min(r1,r2) or waist>max(r1,r2) with a banned range in the middle. (The waist>max(r1,r2) case would produce the bulge.) Or add a parameter p that if negative sets waist to min(r1,r2)+p and if positive sets waist to max(r1,r2)+p. (Don't know what p would be called.) Or add mutually exclusive waist and bulge parameters that act like p. Note that just like there's a minimum waist there is a maximum bulge, spread+r1+r2 (at which point you have a single big circle). It's not clear that a knob that controls bulge say on [0,1] produces intuitive behavior, though, because when spread is large, the bulge will seem much bigger compared to when spread is small at the same fractional point on the valid range.

It does seem like that transition region is potentially an area of interest, since it results in a shape without "excessive" concavity that elegantly connects the two circles. A measure that does work across the range would be to measure the maximum deviation between the flat connecting line and the chosen connecting arc. If you say zero you get a flat line, and larger values give you larger distances. Not sure if the math is tractable for that formulation.

adrianVmariano avatar Oct 03 '25 13:10 adrianVmariano

It turns out that the proposal I made there is hard to do directly because it turns into a fairly nasty 4th order polynomial whose terms I didn't want to figure out. The problem can be solved using the general root finder, though I had to decrease the tolerance considerably or it would fail to converge near the flat results. I don't know if this is robust across the range of in puts. Basically at a certain large enough radius I round it to flat. Maybe 2500 is unnecessarily big.

function findR_dist(r1,r2,s,h) =
   let(
        tan_pts = circle_circle_tangents(r1,[-s/2,0],r2,[s/2,0])[0],
        circ_int = circle_circle_intersection(r1,[-s/2,0],r2,[s/2,0]),
        minR = h<0 ? -2500 : len(circ_int)==0 ? findR_waist(r1,r2,s,0) : 0,
        maxR = h>=0 ? 2500 : -(r1+r2+s)/2,
        dir = unit(zrot(-90,tan_pts[1]-tan_pts[0])),
        gap = function(rr)
                 let(
                     pts=circle_circle_intersection( abs(r1+rr),[-s/2,0], abs(r2+rr), [s/2,0]),
                     cp = len(pts)==1 ? pts[0] : pts[rr<0?1:0],
                     isect = line_intersection([cp,cp+dir], tan_pts, LINE, LINE)
                 )
                 norm(isect - cp-rr*dir)
    )
    h==0 || abs(h) < min(gap(minR),gap(maxR)) ? INF
    :
    let(
        maxh = gap(minR),
        minh = gap(maxR),
        dummy = assert(h<0 || h<=maxh, str("For this geometry must have h < ",maxh," but h=",h))
                assert(h>0 || abs(h)<minh, str("For this geometry must have abs(h) < ",minh," but h=",h)),
        error = function(r) gap(r)-abs(h),
        goodR = root_find(error, minR, maxR, tol=1e-7)
    )
    goodR;
Image

Reversing the sign on h (making it negative) gives this:

Image

Separated circles:

Image

Does this seem like a good interface? The only place it feels like it really falls down is if you want the shape to neck down to zero thickness in the middle. That's a parameter it's hard to determine.

It would be good to test this for robustness. if you want the code that draws the pictures here's the test code:

r1=10;
r2=17;
s=44;
h=10;

rr = findR_dist(r1,r2,s,h);
echo(rr=rr);

if (is_finite(rr)){
  left(s/2)stroke(circle(r=r1),width=.1);
  right(s/2)stroke(circle(r=r2),width=.1);
  pts=circle_circle_intersection( abs(r1+rr),[-s/2,0], abs(r2+rr), [s/2,0]);
  cp = pts[rr<0?1:0];
  color("red")move(cp)stroke(circle(r=abs(rr)), width=.1);
  tan_pts = circle_circle_tangents(r1,[-s/2,0],r2,[s/2,0])[0];
  dir = unit(zrot(-90,tan_pts[1]-tan_pts[0]));
  stroke(tan_pts, width=.1, color="black");
  isect = line_intersection([cp,cp+dir], tan_pts, LINE, LINE);
  if (abs(h)>.3)
    stroke([isect, cp+rr*dir], endcap2="arrow2", width=.1, color="black");
  echo(h_check=norm(isect-cp-rr*dir));
}

adrianVmariano avatar Oct 03 '25 22:10 adrianVmariano


function findR_waist(r1,r2,s,waist) =
  let(
       A = (r1^2-r2^2)/2/s+s/2,
       B = (r1-r2)/s,
       rts=quadratic_roots(B^2,
                           2*A*B-2*r1+waist,
                           A^2+(waist/2)^2 - r1^2,real=true)
  )
  min(rts);

function findR_tang(r1,r2,s,ang) =
  let(
       pts = circle_circle_intersection(r1,[-s/2,0],r2,[s/2,0]),
       minang = len(pts)==0 ? let( minr=findR_waist(r1,r2,s,0),
                                   pts=circle_circle_intersection(r1+minr,[-s/2,0], r2+minr, [s/2,0]))
                              atan2(pts[0].y, pts[0].x+s/2)
              : atan2(pts[0].y, pts[0].x+s/2),
       dummy = assert(ang>-90 && ang<90-minang, 
                      str("Tangent angle must be between -90 and ", 90-minang, " for this geometry but was ",ang)),
       A = (r1^2-r2^2)/2/s+s/2,
       B = (r1-r2)/s,
       maxang = acos(B),
       alpha = 90-ang > maxang ? 90+ang : 90-ang, 
       rts = quadratic_roots(B^2-cos(alpha)^2,
                             2*A*B-2*cos(alpha)^2*r1,
                             A^2-cos(alpha)^2*r1^2,real=true)
  )
  90-ang>maxang ? alpha>=90 ? rts[0] : rts[1]
                :  alpha<=90 ? rts[0] : rts[1];


function findR_dist(r1,r2,s,h) =
   let(
        tan_pts = circle_circle_tangents(r1,[-s/2,0],r2,[s/2,0])[0],
        circ_int = circle_circle_intersection(r1,[-s/2,0],r2,[s/2,0]),
        minR = h<0 ? -2500 : len(circ_int)==0 ? findR_waist(r1,r2,s,0) : 0,
        maxR = h>=0 ? 2500 : -(r1+r2+s)/2,
        dir = unit(zrot(-90,tan_pts[1]-tan_pts[0])),
        gap = function(rr)
                 let(
                     pts=circle_circle_intersection( abs(r1+rr),[-s/2,0], abs(r2+rr), [s/2,0]),
                     cp = len(pts)==1 ? pts[0] : pts[rr<0?1:0],
                     isect = line_intersection([cp,cp+dir], tan_pts, LINE, LINE)
                 )
                 norm(isect - cp-rr*dir)
    )
    h==0 || abs(h) < min(gap(minR),gap(maxR)) ? INF
    :
    let(
        maxh = gap(minR),
        minh = gap(maxR),
        dummy = assert(h<0 || h<=maxh, str("For this geometry must have h < ",maxh," but h=",h))
                assert(h>0 || abs(h)<minh, str("For this geometry must have abs(h) < ",minh," but h=",h)),
        error = function(r) gap(r)-abs(h),
        goodR = root_find(error, minR, maxR, tol=1e-7)
    )
    goodR;


// tangent sets tangent angle of circle 1
// blendR sets blending arc radius
// bulge sets the amount of bulge---deviation from a flat line connection

function gs(r1,r2,spread, tangent, bulge, blendR) =
  assert(num_defined([tangent,bulge,blendR])==1, "Must define exactly one of 'tangent', 'bulge' and 'blendR'")
  let(
      cp1 = [-spread/2,0],
      cp2 = [spread/2,0],
      blendR = is_def(blendR) ? let(
                                    minR = spread<=r1+r2 ? 0 : findR_waist(r1,r2,spread,0),
                                    maxR = (r1+r2+spread)/2
                                )
                                assert(blendR>minR && blendR<maxR,
                                       str("For this geometry blendR must be between ",minR," and ",maxR," but was ",blendR))
                                blendR
             : is_def(tangent) ? findR_tang(r1,r2,spread,tangent)
             : findR_dist(r1,r2,spread,bulge),
      cp_blend = is_finite(blendR) ?
                     let(
                        pts=circle_circle_intersection(abs(r1+blendR), cp1, abs(r2+blendR), cp2)
                     )
                     pts[blendR<0?0:1]
               : undef,     
      pts = is_finite(blendR) ?
                 let(
                     result = [ cp1 + sign(blendR)*r1*unit(cp_blend-cp1),
                                cp2 + sign(blendR)*r2*unit(cp_blend-cp2)]
                 )
                 result
          : let(
                 tan_pts = circle_circle_tangents(r1,cp1,r2,cp2)
            )
            tan_pts[1],
      botpath = [
                 each arc(r=r2, cp=cp2, points=[right(r2,cp2),pts[1]],endpoint=false),
                 if (is_finite(blendR))
                   each arc(r=r2, cp=cp_blend, points=reverse(pts),endpoint=false),
                 each arc(r=r1, cp=cp1, points=[pts[0],left(r1,cp1)], endpoint=false)],
      toppath = yflip(reverse(botpath))
  )
  [each botpath, left(r1,cp1), each toppath];

There's a complete implementation of the basic approach. Needs docs and more error handling, and support for more radius/diameter args. But testing this for robustness would be helpful.

adrianVmariano avatar Oct 05 '25 02:10 adrianVmariano

This has been merged as an updated glued_circles() implementation. Report any bugs you encounter in a new issue.

adrianVmariano avatar Oct 05 '25 19:10 adrianVmariano