#! python 3
# -*- coding: utf-8 -*-
"""
Unroller drops points (and text dots) when a curve is unrolled with them

What it shows
-------------
Rhino.Geometry.Unroller returns no points or text dots when a curve is also
added as following geometry, depending on which way the surface faces.
- Points on their own unroll fine either way.
- Curve + points unroll fine with the surface facing down (normal -Z).
- With the surface facing up (normal +Z, after Brep.Flip here) the curve still comes back
  but the points and dots don't.

How to run
----------
Rhino 8 or 9: open the Script Editor, paste this in, and run it (Python 3 or IronPython).
Nothing is added to the document unless ADD_TO_DOCUMENT is True.

Seen in Rhino 8.36.26296.17001 and Rhino 9.0.26293.12303 (WIP).
rhinoscriptsyntax's rs.UnrollSurface uses Rhino.Geometry.Unroller, so it's affected too.

Workaround we use: if points go missing, unroll the surface again with only the points
(it lands in the same place) and keep those points.
"""
import math
import System
import Rhino
import Rhino.Geometry as G

ADD_TO_DOCUMENT = True   # True = also add the test geometry and unrolled results to the document
TOL = 0.001


def make_test_geometry():
    """A simple single-curved surface, a circle projected onto it and two points on it."""
    arc = G.Arc(G.Point3d(-500, 0, 0), G.Point3d(0, 0, 100), G.Point3d(500, 0, 0)).ToNurbsCurve()
    brep = G.Brep.CreateFromSurface(G.Surface.CreateExtrusion(arc, G.Vector3d(0, 1000, 0)))

    circle = G.Circle(G.Plane(G.Point3d(0, 500, 300), G.Vector3d.ZAxis), 200).ToNurbsCurve()
    curve = G.Curve.ProjectToBrep(circle, brep, G.Vector3d.ZAxis, TOL)[0]

    face = brep.Faces[0]
    points = []
    for x in (-100, 100):
        rc, u, v = face.ClosestPoint(G.Point3d(x, 500, 0))
        points.append(G.Point(face.PointAt(u, v)))
    dot = G.TextDot("A", points[0].Location)
    return brep, curve, points, dot


def unroll(brep, following):
    unroller = G.Unroller(brep)
    unroller.AbsoluteTolerance = TOL
    unroller.RelativeTolerance = 0.01
    for geometry in following:
        unroller.AddFollowingGeometry(geometry)
    breps, curves, points, dots = unroller.PerformUnroll()
    return breps, curves, points, dots


def main():
    brep, curve, points, dot = make_test_geometry()
    print("Rhino {}".format(Rhino.RhinoApp.Version))
    print("Expected back: 2 points, 1 dot where they were added.")
    print("In the document (ADD_TO_DOCUMENT): one column per test, the test surface at the")
    print("bottom with its unrolled output above it, and a label underneath.\n")

    cases = [
        ("points only", list(points)),
        ("curve + points", [curve] + list(points)),
        ("curve + text dot", [curve, dot]),
    ]
    bug_seen = False
    results_to_add = []
    for flipped in (False, True):
        test_brep = brep.DuplicateBrep()
        if flipped:
            test_brep.Flip()
        # Label by which way the surface really faces (the extrusion is built facing down)
        face = test_brep.Faces[0]
        normal_z = face.NormalAt(face.Domain(0).Mid, face.Domain(1).Mid).Z
        side = "surface facing up  " if normal_z > 0 else "surface facing down"
        for name, following in cases:
            breps, curves, pts, dots = unroll(test_brep, following)
            want_pts = sum(1 for g in following if isinstance(g, G.Point))
            want_dots = sum(1 for g in following if isinstance(g, G.TextDot))
            ok = len(pts) == want_pts and len(dots) == want_dots
            bug_seen = bug_seen or not ok
            result = "curves {}  points {}/{}  dots {}/{}  {}".format(
                len(curves), len(pts), want_pts, len(dots), want_dots, "OK" if ok else "<-- MISSING")
            print("{} | {:<16} -> {}".format(side, name, result))
            label = "{}\n{}\n{}".format(side.strip().upper(), name, result.replace("<-- ", ""))
            results_to_add.append((test_brep, following, breps, curves, pts, dots, label, ok))

    print("\nBUG PRESENT: points/dots dropped when a curve is unrolled with them." if bug_seen
          else "\nAll points and dots came back. Looks fixed in this Rhino version.")

    if ADD_TO_DOCUMENT:
        add_to_document(results_to_add)


def add_geometry(doc, geometry, move, colour=None):
    """Adds a copy of a piece of geometry (or a Point3d), moved by the transform."""
    attributes = Rhino.DocObjects.ObjectAttributes()
    if colour is not None:
        attributes.ColorSource = Rhino.DocObjects.ObjectColorSource.ColorFromObject
        attributes.ObjectColor = colour
    if isinstance(geometry, G.Point3d):
        return doc.Objects.AddPoint(move * geometry, attributes)
    copy = geometry.Duplicate()
    copy.Transform(move)
    if isinstance(copy, G.Brep):
        return doc.Objects.AddBrep(copy, attributes)
    if isinstance(copy, G.Curve):
        return doc.Objects.AddCurve(copy, attributes)
    if isinstance(copy, G.Point):
        return doc.Objects.AddPoint(copy.Location, attributes)
    if isinstance(copy, G.TextDot):
        return doc.Objects.AddTextDot(copy, attributes)


def add_label(doc, text, point, colour):
    attributes = Rhino.DocObjects.ObjectAttributes()
    attributes.ColorSource = Rhino.DocObjects.ObjectColorSource.ColorFromObject
    attributes.ObjectColor = colour
    entity = G.TextEntity.Create(text, G.Plane(point, G.Vector3d.ZAxis), doc.DimStyles.Current, False, 0, 0)
    entity.TextHorizontalAlignment = Rhino.DocObjects.TextHorizontalAlignment.Center
    entity.TextVerticalAlignment = Rhino.DocObjects.TextVerticalAlignment.Top
    doc.Objects.AddText(entity, attributes)


def add_to_document(results):
    """
    One column per test. Bottom: the test surface with the curve/points/dot used in that test.
    Above it: what the Unroller gave back. Underneath: a label with the result.
    """
    doc = Rhino.RhinoDoc.ActiveDoc
    green = System.Drawing.Color.FromArgb(0, 150, 0)
    red = System.Drawing.Color.FromArgb(210, 0, 0)
    column_width = 1400
    output_gap = 300          # space between the test surface and its output above it
    for i, (test_brep, following, breps, curves, pts, dots, label, ok) in enumerate(results):
        # Facing-down tests on the left, facing-up tests on the right, with a wider gap between
        column_x = i * column_width + (600 if i >= 3 else 0)
        colour = green if ok else red

        # Test input, centred on the column
        test_bb = test_brep.GetBoundingBox(True)
        to_column = G.Transform.Translation(column_x - test_bb.Center.X, -test_bb.Min.Y, 0)
        add_geometry(doc, test_brep, to_column)
        for geometry in following:
            add_geometry(doc, geometry, to_column)

        # Unrolled output, turned to line up with the test surface (the Unroller lays the
        # curved direction along Y; the test surface curves along X), then centred on the
        # column above the test input. Turned the opposite way for the facing-up surface so
        # its points end up on the same sides as on the test surface.
        out_bb = breps[0].GetBoundingBox(True)
        face = test_brep.Faces[0]
        facing_up = face.NormalAt(face.Domain(0).Mid, face.Domain(1).Mid).Z > 0
        angle = math.pi / 2 if facing_up else -math.pi / 2
        turn = G.Transform.Rotation(angle, G.Vector3d.ZAxis, out_bb.Center)
        out_bb = breps[0].GetBoundingBox(turn)   # box of the turned output
        above = G.Transform.Translation(column_x - out_bb.Center.X,
                                        test_bb.Max.Y - test_bb.Min.Y + output_gap - out_bb.Min.Y, -out_bb.Min.Z)
        above = above * turn
        for geometry in list(breps) + list(curves) + list(pts) + list(dots):
            add_geometry(doc, geometry, above, colour)

        add_label(doc, label, G.Point3d(column_x, -100, 0), colour)
    doc.Views.Redraw()


main()
