"""
ga-arch.studio - Parametric manta (GhPython)
============================================

The manta ray swimming on the B-Side of https://ga-arch.studio, rebuilt for
Grasshopper. Same outline formulas, same wing beat, same random generator:
with the same seed the Formation swarm matches the one on the website.

Setup (Rhino 8, Grasshopper):
  1. Add a "Python 3 Script" component.
  2. Create these inputs (all optional, type hint float/int):
       wingspan      span factor                    (0.5 - 1.5)
       length        body length factor             (0.5 - 1.5)
       sweep         how far the tips sit back      (0.4 - 1.5)
       tip_curve     leading edge curvature         (0.8 - 2.2)
       lobes         cephalic lobes                 (0 - 2)
       body          body thickness                 (0.5 - 2)
       tail          tail length factor             (0.5 - 1.5)
       density       mesh density                   (1 - 4)
       wing_beat     flap amplitude                 (0 - 1.5)
       swim_speed    swim speed                     (0.2 - 2)
       count         number of mantas               (1 - 48)
       spacing       distance between mantas        (8 - 30)
       randomness    offsets and rotations          (0 - 3)
       seed          random seed                    (1 - 100)
       time          animation time in seconds      (0 = first frame)
  3. Create three outputs: mantas, outline, info
  4. Paste this script, connect sliders and bake "mantas".

Species from the website (wingspan, length, sweep, tip_curve, lobes, body, tail):
  Giant manta  1.0, 1.0, 1.0, 1.35, 1.0, 1.0, 1.0
  Mobula       0.9, 1.0, 1.1, 1.10, 0.6, 0.9, 0.8
  Eagle ray    0.8, 1.1, 1.2, 1.00, 0.0, 1.3, 1.5
  Stingray     0.6, 1.0, 0.5, 2.20, 0.0, 1.2, 1.4

Units are metres: the reference giant manta (wingspan 1.0) is 7 m wide.
Z is up, the snout points towards -Y.
Feel free to use and adapt it in your own projects.
"""

import math
import Rhino.Geometry as rg

M32 = 0xFFFFFFFF


def _value(name, default):
    """Unconnected inputs fall back to the website defaults."""
    v = globals().get(name)
    return default if v is None else v


def _imul(a, b):
    return ((a & M32) * (b & M32)) & M32


def mulberry32(seed):
    """Port of the JavaScript mulberry32 used on the website."""
    state = int(seed) & M32

    def rnd():
        nonlocal state
        state = (state + 0x6D2B79F5) & M32
        t = state
        t = _imul(t ^ (t >> 15), t | 1)
        t ^= (t + _imul(t ^ (t >> 7), t | 61)) & M32
        return ((t ^ (t >> 14)) & M32) / 4294967296.0

    return rnd


span_f = float(_value("wingspan", 1.0))
length_f = float(_value("length", 1.0))
sweep_f = float(_value("sweep", 1.0))
tip_f = float(_value("tip_curve", 1.35))
lobes_f = float(_value("lobes", 1.0))
body_f = float(_value("body", 1.0))
tail_f = float(_value("tail", 1.0))
lod = max(1, min(4, int(_value("density", 2))))
beat = float(_value("wing_beat", 1.0)) * 0.55
speed = float(_value("swim_speed", 1.0))
n_mantas = max(1, int(_value("count", 9)))
gap = float(_value("spacing", 16.0))
rand_amount = float(_value("randomness", 1.2))
seed_value = int(_value("seed", 1))
t_now = float(_value("time", 0.0))

# Model units: the reference manta is 18 units wide = 7 m
HALF_SPAN = 9.0
TAIL_ROOT = -4.6
TAIL_LENGTH = 11.0
METRE = 7.0 / (HALF_SPAN * 2)

# Graph Mapper of the website (default curve): how much the wing bends from body to tip.
# Bezier in the unit square: [y0, x1, y1, x2, y2, y3]
GRAPH = (0.0, 0.35, 0.28, 0.7, 0.68, 1.0)
GRAPH_SAMPLES = 16


def _bezier(t, a, b, c, d):
    u = 1.0 - t
    return u * u * u * a + 3 * u * u * t * b + 3 * u * t * t * c + t * t * t * d


def _graph_table():
    table = []
    for k in range(GRAPH_SAMPLES + 1):
        x = k / float(GRAPH_SAMPLES)
        lo, hi = 0.0, 1.0
        for _ in range(22):
            mid = (lo + hi) / 2.0
            if _bezier(mid, 0.0, GRAPH[1], GRAPH[3], 1.0) < x:
                lo = mid
            else:
                hi = mid
        table.append(_bezier((lo + hi) / 2.0, GRAPH[0], GRAPH[2], GRAPH[4], GRAPH[5]))
    return table


GRAPH_TABLE = _graph_table()


def graph_at(a):
    g = max(0.0, min(1.0, a)) * GRAPH_SAMPLES
    i = min(GRAPH_SAMPLES - 1, int(math.floor(g)))
    return GRAPH_TABLE[i] + (GRAPH_TABLE[i + 1] - GRAPH_TABLE[i]) * (g - i)


# Outline in plan: a = distance from the body along the span (0 - 1)
def leading_edge(a):
    return (4.2 - 5.2 * sweep_f * a ** tip_f
            + lobes_f * (1.1 * math.exp(-(((a - 0.13) / 0.05) ** 2)) - 0.45 * math.exp(-((a / 0.06) ** 2))))


def trailing_edge(a):
    return TAIL_ROOT + (8.75 - 5.2 * sweep_f) * a ** 0.7 + 0.55 * math.sin(math.pi * a)


def thickness(a):
    return body_f * (1.15 * (1 - a) ** 1.7 + 0.05)


def profile(v):
    return max(0.0, math.sin(math.pi * v ** 0.62)) ** 0.75


def sign(x):
    return (x > 0) - (x < 0)


def deform(x, y, z, s, v, part, t):
    """Wing beat and tail undulation, same formulas as the website shader."""
    if part == 0:
        y += 0.14 * math.sin(t * 0.9 - z * 0.35)
        a = abs(s)
        ang = (beat * math.sin(t - a * 1.5 - v * 0.6) * (0.35 + 0.65 * a) + 0.08) * graph_at(a) * sign(s)
        c, sn = math.cos(ang), math.sin(ang)
        xs = x * span_f
        x, y = xs * c - y * sn, xs * sn + y * c
    else:
        z = TAIL_ROOT + (z - TAIL_ROOT) * tail_f
        x += math.sin(t * 0.8 - v * 3.2) * 0.9 * v * v
        y += math.cos(t * 0.7 - v * 2.6) * 0.5 * v * v + 0.14 * math.sin(t * 0.9 - TAIL_ROOT * 0.35) * (1 - v)
    return x, y, z * length_f


def span_position(i, nu):
    """More samples near the body, where the cephalic lobes are."""
    u = (i / float(nu)) * 2 - 1
    return sign(u) * abs(u) ** 1.4


# Rest mesh: vertices as (x, y, z, s, v, part) in website axes (Y up, snout towards +Z), quads as index tuples
nu = 12 + lod * 8
nv = 5 + lod * 3
nt = 8 + lod * 3
rest = []
quads = []
for side in (1, -1):
    base = len(rest)
    for i in range(nu + 1):
        s = span_position(i, nu)
        a = abs(s)
        le, te, th = leading_edge(a), trailing_edge(a), thickness(a)
        for j in range(nv + 1):
            v = j / float(nv)
            rest.append((s * HALF_SPAN, (0.62 if side > 0 else -0.38) * th * profile(v), le + (te - le) * v, s, v, 0))
    for i in range(nu):
        for j in range(nv):
            p0 = base + i * (nv + 1) + j
            p1, p2, p3 = p0 + 1, p0 + nv + 1, p0 + nv + 2
            quads.append((p0, p1, p3, p2) if side > 0 else (p0, p2, p3, p1))
# Tail: two crossed ribbons
for vertical in (False, True):
    base = len(rest)
    for k in range(nt + 1):
        t = k / float(nt)
        w = 0.16 * (1 - t) + 0.015
        for e in (-1, 1):
            rest.append((0.0 if vertical else e * w, e * w if vertical else 0.0, TAIL_ROOT - t * TAIL_LENGTH, 0.0, t, 1))
    for k in range(nt):
        p0 = base + k * 2
        quads.append((p0, p0 + 1, p0 + 3, p0 + 2))


def to_rhino(x, y, z):
    """Website axes (Y up) to Rhino axes (Z up), in metres."""
    return rg.Point3d(x * METRE, -z * METRE, y * METRE)


def normalize(v):
    d = math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]) or 1.0
    return (v[0] / d, v[1] / d, v[2] / d)


def cross(a, b):
    return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])


# Formation swarm: same grid, offsets and random sequence as the website
random = mulberry32(seed_value)
sim_time = t_now * speed
flap_time = t_now * (0.7 + speed * 0.9) * 2.3
cols = int(math.ceil(math.sqrt(n_mantas * 1.5)))
rows = int(math.ceil(n_mantas / float(cols)))

mantas = []
for index in range(n_mantas):
    # Same order of random draws as the website
    rx, ry, rz, ryaw, rroll = (random() - 0.5 for _ in range(5))
    random()  # wander direction, used by the Flock behaviour only
    phase = random() * math.pi * 2
    rate = 0.85 + random() * 0.3

    row = index // cols
    in_row = n_mantas - cols * (rows - 1) if row == rows - 1 else cols
    col = index % cols
    bob = sim_time * 0.9 * rate + phase
    px = (col - (in_row - 1) / 2.0) * gap + rx * rand_amount * 4
    py = ry * rand_amount * 3 + math.sin(bob) * (1 + rand_amount * 0.6)
    pz = ((rows - 1) / 2.0 - row) * gap * 1.1 + (col % 2) * gap * 0.3 + rz * rand_amount * 4

    # Local frame: Z along the swim direction, then roll around it
    yaw = ryaw * rand_amount * 0.25
    roll = rroll * rand_amount * 0.15
    az = normalize((math.sin(yaw), -math.cos(bob) * 0.07, math.cos(yaw)))
    ax = normalize(cross((0.0, 1.0, 0.0), az))
    ay = cross(az, ax)
    cr, sr = math.cos(roll), math.sin(roll)
    bx = tuple(ax[k] * cr + ay[k] * sr for k in range(3))
    by = tuple(-ax[k] * sr + ay[k] * cr for k in range(3))

    t = flap_time * rate + phase
    mesh = rg.Mesh()
    for (x, y, z, s, v, part) in rest:
        dx, dy, dz = deform(x, y, z, s, v, part, t)
        mesh.Vertices.Add(to_rhino(px + bx[0] * dx + by[0] * dy + az[0] * dz,
                                   py + bx[1] * dx + by[1] * dy + az[1] * dz,
                                   pz + bx[2] * dx + by[2] * dy + az[2] * dz))
    for a, b, c, d in quads:
        mesh.Faces.AddFace(a, b, c, d)
    mesh.Normals.ComputeNormals()
    mesh.Compact()
    mantas.append(mesh)

# Plan outline of one manta at rest (flat, at the origin): useful for 2D work or laser cutting
outline_points = []
for i in range(nu + 1):
    s = span_position(i, nu)
    outline_points.append(to_rhino(s * HALF_SPAN * span_f, 0.0, leading_edge(abs(s)) * length_f))
for i in range(nu, -1, -1):
    s = span_position(i, nu)
    outline_points.append(to_rhino(s * HALF_SPAN * span_f, 0.0, trailing_edge(abs(s)) * length_f))
outline_points.append(outline_points[0])
outline = rg.PolylineCurve(outline_points)

info = "{} mantas | wingspan {:.1f} m | seed {} | {} faces each | ga-arch.studio".format(
    len(mantas), HALF_SPAN * 2 * span_f * METRE, seed_value, len(quads))
