# https://discourse.mcneel.com/t/revolve-points/222152

#! python 3
import math
import Rhino
import scriptcontext as sc
from Rhino.Geometry import Arc, Circle, Plane, Vector3d
from Rhino.Input import GetResult
from Rhino.Input.Custom import GetLine, GetLineMode, GetObject, GetPoint, OptionToggle

TWO_PI = 2.0 * math.pi

# Prompts for the point objects to revolve. Returns a list of ObjRef.
def get_points():
    go = GetObject()
    go.SetCommandPrompt("Select points to revolve")
    go.GeometryFilter = Rhino.DocObjects.ObjectType.Point
    go.GroupSelect = True
    go.SubObjectSelect = False
    if go.GetMultiple(1, 0) != GetResult.Object:
        return None
    return [go.Object(i) for i in range(go.ObjectCount)]

# Prompts for the revolve axis. Returns a Line, or None if cancelled.
def get_axis():
    gl = GetLine()
    gl.FirstPointPrompt = "Start of revolve axis"
    gl.SecondPointPrompt = "End of revolve axis (Press Enter to use CPlane z-axis direction)"
    gl.GetLineMode = GetLineMode.CPlaneNormalVector
    rc, axis = gl.Get()
    if rc != Rhino.Commands.Result.Success:
        return None
    return axis

#P lane at the axis start whose x-axis aims at the points.
def angle_frame(points, axis):
    zaxis = axis.Direction
    zaxis.Unitize()
    xaxis = Vector3d.Zero
    for point in points:
        xaxis += point - axis.ClosestPoint(point, False)
    yaxis = Vector3d.CrossProduct(zaxis, xaxis)
    xaxis = Vector3d.CrossProduct(yaxis, zaxis)
    if yaxis.IsTiny() or xaxis.IsTiny():
        return Plane(axis.From, zaxis)  # points straddle the axis - any frame will do
    return Plane(axis.From, xaxis, yaxis)

# Angle, in [0, 2pi), of a point measured from the plane's x-axis.
def calc_angle(plane, point):
    rc, u, v = plane.ClosestParameter(point)
    if not rc:
        return 0.0
    angle = math.atan2(v, u)
    return angle + TWO_PI if angle < 0.0 else angle

# Revolves one point about an axis. Returns an Arc, a Circle, or None.
def revolve_point(point, axis, start_angle, revolution_angle):
    center = axis.ClosestPoint(point, False)
    radius = center.DistanceTo(point)
    if radius <= Rhino.RhinoMath.ZeroTolerance:
        return None

    zaxis = axis.Direction
    zaxis.Unitize()
    xaxis = point - center
    plane = Plane(center, xaxis, Vector3d.CrossProduct(zaxis, xaxis))

    if abs(revolution_angle) >= TWO_PI - Rhino.RhinoMath.SqrtEpsilon:
        plane.Rotate(start_angle, zaxis)
        return Circle(plane, radius)

    # Draw the arc counter-clockwise about the axis, whichever way it was given
    from_angle = start_angle
    to_angle = start_angle + revolution_angle
    if to_angle < from_angle:
        from_angle, to_angle = to_angle, from_angle
    plane.Rotate(from_angle, zaxis)
    return Arc(plane, radius, to_angle - from_angle)

# Revolves each point. Returns a list of Arc and Circle.
def revolve_points(points, axis, start_angle, revolution_angle):
    curves = []
    for point in points:
        curve = revolve_point(point, axis, start_angle, revolution_angle)
        if curve:
            curves.append(curve)
    return curves

# Draws the preview arcs and circles.
def draw_curves(display, curves, color):
    for curve in curves:
        if isinstance(curve, Circle):
            display.DrawCircle(curve, color)
        else:
            display.DrawArc(curve, color)

# Runs the angle prompts and options.
def get_angles(points, axis):
    frame = angle_frame(points, axis)
    quadrant_plane = Plane(frame)
    state = {"step": 0, "start_angle": 0.0, "revolution_angle": TWO_PI}
    delete_input = OptionToggle(False, "No", "Yes")
    ask_for_start_angle = OptionToggle(True, "No", "Yes")
    color = Rhino.ApplicationSettings.AppearanceSettings.FeedbackColor

    def on_dynamic_draw(sender, e):
        if state["step"] == 0:
            start = calc_angle(frame, e.CurrentPoint)
            revolution = state["revolution_angle"]
        else:
            start = state["start_angle"]
            revolution = calc_angle(quadrant_plane, e.CurrentPoint)
        draw_curves(e.Display, revolve_points(points, axis, start, revolution), color)

    while state["step"] < 2:
        gp = GetPoint()
        gp.DynamicDraw += on_dynamic_draw
        if state["step"] == 0:
            gp.SetCommandPrompt("Start angle")
            gp.SetDefaultNumber(math.degrees(state["start_angle"]))
        else:
            gp.SetCommandPrompt("Revolution angle")
            gp.SetDefaultNumber(math.degrees(state["revolution_angle"]))
        gp.Constrain(frame, False)
        gp.DrawLineFromPoint(axis.From, False)
        gp.AcceptNothing(True)
        gp.AcceptNumber(True, True)
        gp.AddOptionToggle("DeleteInput", delete_input)
        full_circle = gp.AddOption("FullCircle")
        if (state["step"] == 0) == ask_for_start_angle.CurrentValue:
            gp.AddOptionToggle("AskForStartAngle", ask_for_start_angle)

        was_asking = ask_for_start_angle.CurrentValue
        res = gp.Get()
        if res == GetResult.Cancel:
            return None

        if res == GetResult.Option:
            if gp.OptionIndex() == full_circle:
                return state["start_angle"], TWO_PI, delete_input.CurrentValue
            if was_asking != ask_for_start_angle.CurrentValue:
                if not ask_for_start_angle.CurrentValue:
                    state["start_angle"] = 0.0
                state["step"] = 1 - state["step"]
            continue

        angle = None
        if res == GetResult.Point:
            found, number = gp.NumberPreview()
            if found:
                angle = math.radians(number)
            elif state["step"] == 0:
                angle = calc_angle(frame, gp.Point())
            else:
                angle = calc_angle(quadrant_plane, gp.Point())
        elif res == GetResult.Number:
            angle = math.radians(gp.Number())
        elif res != GetResult.Nothing:
            return None

        if angle is not None:
            if state["step"] == 0:
                state["start_angle"] = angle
                quadrant_plane = Plane(frame)
                quadrant_plane.Rotate(angle, quadrant_plane.ZAxis)
            elif abs(angle) <= Rhino.RhinoMath.SqrtEpsilon:
                print("Revolution angle too close to zero.")
                continue
            else:
                state["revolution_angle"] = angle
        state["step"] += 1

    return state["start_angle"], state["revolution_angle"], delete_input.CurrentValue

# Main function
def revolve_point_command():
    obj_refs = get_points()
    if not obj_refs:
        return

    axis = get_axis()
    if not axis:
        return

    points = [obj_ref.Point().Location for obj_ref in obj_refs]
    angles = get_angles(points, axis)
    if not angles:
        return
    start_angle, revolution_angle, delete_input = angles

    curves = revolve_points(points, axis, start_angle, revolution_angle)
    if not curves:
        print("None of the points selected can be revolved around that axis.")
        return

    undo_record = sc.doc.BeginUndoRecord("RevolvePoint")
    try:
        for curve in curves:
            if isinstance(curve, Circle):
                sc.doc.Objects.AddCircle(curve)
            else:
                sc.doc.Objects.AddArc(curve)
        if delete_input:
            for obj_ref in obj_refs:
                sc.doc.Objects.Delete(obj_ref, True)
    finally:
        sc.doc.EndUndoRecord(undo_record)
    sc.doc.Views.Redraw()

if __name__ == "__main__":
    revolve_point_command()
