{
 "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": [
    "# Combining CAD geometry with meshes\n",
    "\n",
    "Scanned parts, organic shapes and meshes exported from other programs come as triangles, not as\n",
    "exact surfaces. To fit them with CAD details, a mounting stem, a bore, a flange, the triangle body\n",
    "and the CAD objects are combined by Boolean operations:\n",
    "\n",
    "| call | what it does |\n",
    "|---|---|\n",
    "| `load(\"knob.stl\")` | a closed `FacetBody` from the triangles |\n",
    "| `body.combined(cad, \"union\", resolution)` | the body joined with the CAD object, laid out anew as triangles on a grid of `resolution` steps |\n",
    "| `body.combined(cad, \"difference\", resolution)` | the CAD object cut out of the body |\n",
    "| `OctreeMesher(target_size=...)` | tetrahedra cut from a grid of cubes that follows the triangles |\n",
    "\n",
    "The file `cad_and_mesh_combined.stl` is written by `cad_and_mesh_combined_geometry.py`: an\n",
    "ellipsoid with half axes $a = 20$ mm (twice) and $c = 12$ mm, triangulated from a level set on a\n",
    "grid of 2 mm.\n",
    "\n",
    "**Reference.** A coaxial cylinder of radius $\\rho$ cuts from the ellipsoid the column\n",
    "$V_c(\\rho) = \\tfrac43\\pi a^2 c\\,\\big(1-(1-\\rho^2/a^2)^{3/2}\\big)$, half of it below the equator.\n",
    "The stem of radius $\\rho_s$ and length $H$ below the equator adds\n",
    "$\\pi\\rho_s^2 H - V_c(\\rho_s)/2$; the bore of radius $\\rho_b$ through everything removes\n",
    "$V_c(\\rho_b) + \\pi\\rho_b^2 H - V_c(\\rho_b)/2$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d3 import Cylinder\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.meshing import OctreeMesher\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": [
    "## The triangle body\n",
    "\n",
    "The volume of the triangulated knob against the ellipsoid it approximates."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "knob = load(\"cad_and_mesh_combined.stl\")\n",
    "a, c = 0.02, 0.012\n",
    "print(\n",
    "    f\"knob: {len(knob.triangles)} triangles, closed {knob.is_closed}, faces {', '.join(face.id for face in knob.faces)}\"\n",
    ")\n",
    "print(\n",
    "    f\"volume {knob.measure * 1e6:.4f} cm3, ellipsoid 4/3 pi a^2 c {4 / 3 * np.pi * a**2 * c * 1e6:.4f} cm3 \"\n",
    "    f\"({knob.measure / (4 / 3 * np.pi * a**2 * c) - 1:+.2%})\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Adding the stem, drilling the bore\n",
    "\n",
    "The stem is 30 mm long below the equator with 7 mm radius; the bore of 4 mm radius runs from the\n",
    "end of the stem through the top of the knob. The combined body is laid out anew on a grid of 96\n",
    "steps across its extent (about 0.8 mm), from the signed distance to both bodies; its round edges\n",
    "are therefore resolved to about one grid step."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "stem_radius, stem_length, bore_radius = 0.007, 0.03, 0.004\n",
    "stem = Cylinder(\n",
    "    radius=stem_radius, length=stem_length, origin=(0.0, 0.0, -stem_length)\n",
    ").named(\"stem\")\n",
    "bore = Cylinder(\n",
    "    radius=bore_radius,\n",
    "    length=stem_length + 0.02,\n",
    "    origin=(0.0, 0.0, -stem_length - 0.001),\n",
    ").named(\"bore\")\n",
    "handle = knob.combined(stem, \"union\", 96)\n",
    "drilled = handle.combined(bore, \"difference\", 96)\n",
    "\n",
    "column = lambda rho: 4 / 3 * np.pi * a**2 * c * (1 - (1 - rho**2 / a**2) ** 1.5)\n",
    "added = np.pi * stem_radius**2 * stem_length - column(stem_radius) / 2\n",
    "removed = (\n",
    "    column(bore_radius) + np.pi * bore_radius**2 * stem_length - column(bore_radius) / 2\n",
    ")\n",
    "print(\n",
    "    f\"stem added   {(handle.measure - knob.measure) * 1e6:8.4f} cm3, closed form {added * 1e6:8.4f} cm3\"\n",
    ")\n",
    "print(\n",
    "    f\"bore removed {(handle.measure - drilled.measure) * 1e6:8.4f} cm3, closed form {removed * 1e6:8.4f} cm3\"\n",
    ")\n",
    "print(f\"combined body: closed {drilled.is_closed}, {len(drilled.triangles)} triangles\")\n",
    "\n",
    "mesh = OctreeMesher(target_size=0.0015, coarsening=1).generate(drilled)\n",
    "view = plots.Camera(elevation=20, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(16, 7))\n",
    "plots.geometry(\n",
    "    drilled,\n",
    "    selection={\"combined body\": drilled.boundaries.all},\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Scanned knob with CAD stem and bore\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"Mesh of the combined body: {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 of the mesh against the combined body and the shape of its cells."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "report = quality(mesh)\n",
    "print(\n",
    "    f\"mesh volume {report['size'].sum() * 1e6:.4f} cm3, body {drilled.measure * 1e6:.4f} cm3 ({report['size'].sum() / drilled.measure - 1:+.2%}); \"\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 original triangles of the knob, and the mesh cut open along the axis with the bore through\n",
    "knob and stem."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 2, size=(16, 7))\n",
    "plots.trisurface(\n",
    "    knob.points,\n",
    "    knob.triangles,\n",
    "    1e3 * knob.points[:, 2],\n",
    "    edges=True,\n",
    "    limits=(-12, 12),\n",
    "    label=\"height z [mm]\",\n",
    "    camera=view,\n",
    "    title=f\"Triangles from the file: {len(knob.triangles)}\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    cell_values=report[\"shape\"],\n",
    "    limits=(0, 1),\n",
    "    plane=((0.0, 0.0, -0.005), (0.0, 1.0, 0.0)),\n",
    "    label=\"shape measure\",\n",
    "    camera=plots.Camera(elevation=5, azimuth=90),\n",
    "    title=\"Cut along the axis\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Thin out the triangles first with `knob.simplified(tolerance)`, add a flange from a `Box`, or turn\n",
    "a body with flat and round faces into an exact solid with `exact()` and model on it in CAD."
   ]
  }
 ]
}
