# /// script
# requires-python = ">=3.11"
# dependencies = [
#     "marimo",
#     "numpy",
#     "matplotlib",
# ]
# ///

import marimo

__generated_with = "0.26.0"
app = marimo.App(width="medium")


@app.cell
def _():
    import marimo as mo
    import matplotlib.pyplot as plt
    import numpy as np

    return mo, np, plt


@app.cell
def _(mo):
    mo.md(r"""
    # Module 2.2: Visual Meshes vs. Collision Primitives

    Simulators separate what a robot **looks like** (`<visual>`) from what **bumps into things** (`<collision>`). Replacing a 40,000-triangle CAD mesh with a handful of spheres and capsules slashes contact-check cost down to a few dozen floating-point operations.

    In this notebook, you'll compute exact **point-to-segment** and **capsule-to-capsule** clearances and compare primitive collision checks against dense mesh vertex tests.
    """)
    return


@app.cell
def _(np):
    def point_to_segment_closest(p, a, b):
        """Return closest point on segment [a, b] to point p and Euclidean distance."""
        ab = b - a
        denom = float(np.dot(ab, ab))
        if denom < 1e-12:
            return a.copy(), float(np.linalg.norm(p - a))
        t = float(np.clip(np.dot(p - a, ab) / denom, 0.0, 1.0))
        closest = a + t * ab
        return closest, float(np.linalg.norm(p - closest))

    def capsule_vs_sphere_clearance(a, b, r_capsule, center, r_sphere):
        """Signed clearance between a capsule (a, b, r_capsule) and a sphere."""
        closest, dist = point_to_segment_closest(center, a, b)
        return dist - (r_capsule + r_sphere), closest

    def sample_visual_hull(a, b, half_width=0.05, n_points=120):
        """Create a dense tapered CAD-like polygon outline around segment [a, b]."""
        ab = b - a
        length = float(np.linalg.norm(ab))
        u = ab / max(length, 1e-9)
        n = np.array([-u[1], u[0]])
        ts = np.linspace(0.0, 1.0, n_points // 2)
        # Tapered profile with a central servo bulge
        profile = half_width * (0.75 + 0.35 * np.sin(np.pi * ts) ** 2 + 0.15 * np.cos(6 * np.pi * ts))
        top = [a + t * ab + w * n for t, w in zip(ts, profile)]
        bot = [a + t * ab - w * n for t, w in zip(ts[::-1], profile[::-1])]
        return np.array(top + bot)

    return capsule_vs_sphere_clearance, point_to_segment_closest, sample_visual_hull


@app.cell
def _(mo):
    elbow_s = mo.ui.slider(-75, 75, step=5, value=25, label="Forearm angle (deg)")
    radius_s = mo.ui.slider(0.03, 0.14, step=0.005, value=0.065, label="Capsule radius r (m)")
    obs_x_s = mo.ui.slider(0.15, 0.95, step=0.02, value=0.62, label="Obstacle X (m)")
    obs_y_s = mo.ui.slider(-0.35, 0.45, step=0.02, value=0.14, label="Obstacle Y (m)")
    mesh_pts_dd = mo.ui.dropdown(["120", "1200", "12000"], value="1200", label="Visual polygon vertices")

    mo.vstack([
        mo.hstack([elbow_s, radius_s], justify="start"),
        mo.hstack([obs_x_s, obs_y_s, mesh_pts_dd], justify="start"),
    ])
    return elbow_s, mesh_pts_dd, obs_x_s, obs_y_s, radius_s


@app.cell
def _(
    capsule_vs_sphere_clearance,
    elbow_s,
    mesh_pts_dd,
    mo,
    np,
    obs_x_s,
    obs_y_s,
    plt,
    radius_s,
    sample_visual_hull,
):
    _a = np.array([0.1, 0.0])
    _ang = np.deg2rad(elbow_s.value)
    _b = _a + 0.72 * np.array([np.cos(_ang), np.sin(_ang)])
    _obs = np.array([obs_x_s.value, obs_y_s.value])
    _r_obs = 0.09

    _clearance, _closest = capsule_vs_sphere_clearance(_a, _b, radius_s.value, _obs, _r_obs)
    _n_verts = int(mesh_pts_dd.value)
    _hull = sample_visual_hull(_a, _b, half_width=0.055, n_points=min(_n_verts, 300))

    # Draw capsule envelope outline
    _theta = np.linspace(0, 2 * np.pi, 48)
    _cap_pts = []
    for _c in (_a, _b):
        _cap_pts.append(_c + radius_s.value * np.column_stack([np.cos(_theta), np.sin(_theta)]))

    _fig, _ax = plt.subplots(figsize=(6.8, 4.4))
    _ax.fill(_hull[:, 0], _hull[:, 1], color="#111827", alpha=0.18, label=f"Visual CAD outline ({_n_verts} verts)")
    _ax.plot(_hull[:, 0], _hull[:, 1], color="#111827", lw=1.2, alpha=0.6)

    # Capsule body
    _ab = _b - _a
    _u = _ab / np.linalg.norm(_ab)
    _n = np.array([-_u[1], _u[0]])
    _r = radius_s.value
    _rect = np.array([_a + _r * _n, _b + _r * _n, _b - _r * _n, _a - _r * _n])
    _ax.fill(_rect[:, 0], _rect[:, 1], color="#2563eb", alpha=0.16, label="Collision capsule")
    _ax.add_patch(plt.Circle(_a, _r, color="#2563eb", fill=False, ls="--", lw=1.4))
    _ax.add_patch(plt.Circle(_b, _r, color="#2563eb", fill=False, ls="--", lw=1.4))
    _ax.plot([_a[0], _b[0]], [_a[1], _b[1]], "--", color="#2563eb", lw=1.2)

    _obs_color = "#dc2626" if _clearance <= 0 else "#059669"
    _ax.add_patch(plt.Circle(_obs, _r_obs, color=_obs_color, alpha=0.28, label="Obstacle sphere"))
    _ax.plot([_closest[0], _obs[0]], [_closest[1], _obs[1]], "-", color=_obs_color, lw=2)

    _ax.set_aspect("equal")
    _ax.set_xlim(-0.05, 1.15)
    _ax.set_ylim(-0.45, 0.55)
    _ax.grid(True, alpha=0.25)
    _ax.legend(loc="upper left", fontsize=8)
    _status = "COLLISION" if _clearance <= 0 else "CLEAR"
    _ax.set_title(f"{_status} | Signed clearance = {_clearance:+.3f} m (1 capsule check vs {_n_verts} vertex checks)")

    mo.vstack([_fig])
    return


@app.cell
def _(mo):
    mo.md(r"""
    ## Try this on your own

    1. **Capsule-to-capsule clearance:** Write a helper that samples 20 points along a second segment `[c, d]` and calls `capsule_vs_sphere_clearance` to find the minimum clearance between two arm links.
    2. **Conservative padding:** Using `sample_visual_hull(..., half_width=0.055)`, compute the maximum perpendicular distance from any visual vertex to the centerline `[a, b]` so you know the exact minimum capsule radius `r` that encloses 100% of the visual mesh.
    """)
    return


@app.cell
def _(np, point_to_segment_closest, sample_visual_hull):
    # Exercise sandbox — edit and run!
    _a = np.array([0.0, 0.0])
    _b = np.array([0.7, 0.0])
    _verts = sample_visual_hull(_a, _b, half_width=0.055, n_points=200)
    _dists = [point_to_segment_closest(_v, _a, _b)[1] for _v in _verts]
    print(f"Minimum capsule radius enclosing all 200 visual vertices: {max(_dists):.4f} m")
    return


if __name__ == "__main__":
    app.run()
