{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "OneSimulation (venv)",
   "language": "python",
   "name": "onesim"
  },
  "language_info": {
   "name": "python"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Editing and repairing surface meshes\n",
    "\n",
    "Surface meshes from scanners, from image segmentation or from other programs are rarely ready\n",
    "for meshing: they have holes where the scanner could not see, millions of tiny triangles, and long\n",
    "thin triangles that spoil the cells behind them. OneSimulation edits them as facet bodies:\n",
    "\n",
    "| step | call | what changes |\n",
    "|---|---|---|\n",
    "| find holes | `body.holes()` | the open rims of the skin, each as a loop of points |\n",
    "| fill holes | `body.closed(largest=...)` | rims filled from their points; openings longer than `largest` stay |\n",
    "| thin out | `body.simplified(tolerance)` | as few triangles as keep every point within the tolerance of the skin |\n",
    "| lay anew | `FacetMesher(target_size=...).skin(body)` | even triangles of about the target size on the same surface |\n",
    "| fill | `FacetMesher(target_size=..., keep_facets=True)` | tetrahedra inside; the skin is kept triangle for triangle |\n",
    "\n",
    "The file `surface_mesh_editing_repair.stl` is written by `surface_mesh_editing_repair_geometry.py`\n",
    "from the dense skin of a ball of radius $R$ = 30 mm, without the cap above $z_c$ = 25 mm and\n",
    "without a small torn patch on its side.\n",
    "\n",
    "**Reference.** A skin on the sphere has all its points at the distance $R$ from the centre. A flat\n",
    "patch over the cap opening leaves out the cap of height $h = R - z_c$, so the closed body has\n",
    "about $\\tfrac43\\pi R^3 - \\tfrac13\\pi h^2 (3R-h)$; the rim of the opening follows the triangles,\n",
    "so it lies a little above $z_c$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.meshing import FacetMesher\n",
    "from onesim.meshing.quality import quality\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Reading and inspecting\n",
    "\n",
    "The distance of the points from the centre measures how far a skin strays from the sphere; the\n",
    "points of the flat patch over the cap opening are left out of it."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "radius, cap = 0.03, 0.025\n",
    "scan = load(\"surface_mesh_editing_repair.stl\")\n",
    "stray = (\n",
    "    lambda body: 1e6\n",
    "    * np.abs(\n",
    "        np.linalg.norm(body.points[body.points[:, 2] < cap - 0.001], axis=1) - radius\n",
    "    ).max()\n",
    ")\n",
    "print(\n",
    "    f\"scan: {len(scan.triangles)} triangles, {len(scan.points)} points, closed {scan.is_closed}, \"\n",
    "    f\"largest distance from the sphere {stray(scan):.2f} um\"\n",
    ")\n",
    "print(\n",
    "    f\"open rims: {len(scan.holes())}, with {', '.join(str(len(rim)) for rim in scan.holes())} points\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Filling, thinning out, laying anew\n",
    "\n",
    "The holes are filled without adding points. The skin is then thinned out to 0.1 mm and laid anew\n",
    "with triangles of 3 mm."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "closed = scan.closed()\n",
    "thinned = closed.simplified(1e-4)\n",
    "even = FacetMesher(target_size=0.003).skin(thinned)\n",
    "height = radius - cap\n",
    "expected = 4 / 3 * np.pi * radius**3 - np.pi * height**2 * (3 * radius - height) / 3\n",
    "print(\n",
    "    \"skin                 triangles   points   closed   volume [cm3]   largest distance from the sphere below the cap [um]\"\n",
    ")\n",
    "for name, body in {\n",
    "    \"scan\": scan,\n",
    "    \"holes filled\": closed,\n",
    "    \"thinned to 0.1 mm\": thinned,\n",
    "    \"laid anew at 3 mm\": even,\n",
    "}.items():\n",
    "    volume = f\"{body.measure * 1e6:13.4f}\" if body.is_closed else f\"{'open':>13s}\"\n",
    "    print(\n",
    "        f\"{name:19s} {len(body.triangles):10d} {len(body.points):8d} {str(body.is_closed):>8s} {volume} {stray(body):24.2f}\"\n",
    "    )\n",
    "print(\n",
    "    f\"sphere less a flat cap: {expected * 1e6:.4f} cm3 (the filled cap rim lies a little above z = 25 mm)\"\n",
    ")\n",
    "\n",
    "mesh = FacetMesher(target_size=0.003, keep_facets=True).generate(even)\n",
    "report = quality(mesh)\n",
    "view = plots.Camera(elevation=35, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(16, 7))\n",
    "plots.geometry(\n",
    "    scan,\n",
    "    camera=view,\n",
    "    title=f\"Scan: {len(scan.triangles)} triangles, two holes\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"Edited skin filled: {mesh.cell_count} tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The volume mesh keeps the edited skin as it is: its volume is that of the skin to rounding."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "print(\n",
    "    f\"volume mesh: {mesh.cell_count} cells, volume {report['size'].sum() * 1e6:.4f} cm3 against the skin {even.measure * 1e6:.4f} cm3; \"\n",
    "    f\"smallest shape {report['shape'].min():.3f}, mean {report['shape'].mean():.3f}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The skin after filling, after thinning out and after laying anew, seen on the filled cap, with\n",
    "every triangle drawn."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "top = plots.Camera(elevation=60, azimuth=-60)\n",
    "fig = plots.figure(1, 3, size=(21, 7))\n",
    "for index, (name, body) in enumerate(\n",
    "    {\n",
    "        \"holes filled\": closed,\n",
    "        \"thinned to 0.1 mm\": thinned,\n",
    "        \"laid anew at 3 mm\": even,\n",
    "    }.items()\n",
    "):\n",
    "    plots.trisurface(\n",
    "        body.points,\n",
    "        body.triangles,\n",
    "        1e3 * body.points[:, 2],\n",
    "        edges=True,\n",
    "        limits=(-30, 30),\n",
    "        label=\"height z [mm]\",\n",
    "        camera=top,\n",
    "        title=f\"{name}: {len(body.triangles)} triangles\",\n",
    "        ax=fig[index],\n",
    "    )\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Keep an opening that is meant to be one with `closed(largest=...)`, split the skin into named\n",
    "faces along its sharp edges with `split_boundaries`, or add boundary layers to the volume mesh\n",
    "with `BoundaryLayers(walls=...)`."
   ]
  }
 ]
}
