Metadata-Version: 2.4
Name: sanchousf-ai-toolkit-cad
Version: 0.7.0
Summary: Modular 3D CAD modeling, procedural synthesis, and interactive scene viewer
Author: sanchousf
Author-email: sanchousf@gmail.com
License-Expression: MIT
Project-URL: Homepage, https://github.com/sanchousf/ai-toolkit
Project-URL: Repository, https://github.com/sanchousf/ai-toolkit
Project-URL: Issues, https://github.com/sanchousf/ai-toolkit/issues
Project-URL: Documentation, https://github.com/sanchousf/ai-toolkit#readme
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Operating System :: OS Independent
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Manufacturing
Classifier: Intended Audience :: Science/Research
Classifier: Topic :: Scientific/Engineering
Classifier: Topic :: Scientific/Engineering :: Visualization
Classifier: Topic :: Multimedia :: Graphics
Classifier: Topic :: Multimedia :: Graphics :: 3D Modeling
Classifier: Topic :: Multimedia :: Graphics :: 3D Rendering
Classifier: Topic :: Multimedia :: Graphics :: Viewers
Requires-Python: >=3.9
Description-Content-Type: text/markdown
Requires-Dist: dearpygui>=1.10.0
Requires-Dist: numpy>=1.22.0
Requires-Dist: scipy>=1.9.0
Requires-Dist: scikit-image>=0.19.0
Requires-Dist: trimesh>=3.15.0
Requires-Dist: PyOpenGL>=3.1.5
Requires-Dist: pillow>=9.0.0
Requires-Dist: shapely>=2.0.0
Requires-Dist: manifold3d>=3.0.0
Requires-Dist: glfw>=2.5.0
Requires-Dist: matplotlib>=3.5.0
Requires-Dist: rich>=12.0.0
Requires-Dist: tomli>=1.1.0; python_version < "3.11"
Provides-Extra: remesh
Requires-Dist: pyvista>=0.40.0; extra == "remesh"
Provides-Extra: blender
Requires-Dist: bpy>=4.0.0; extra == "blender"
Provides-Extra: test
Requires-Dist: pytest>=8.0.0; extra == "test"
Requires-Dist: pytest-cov>=7.0.0; extra == "test"
Requires-Dist: pyvista>=0.40.0; extra == "test"
Provides-Extra: dev
Requires-Dist: pytest>=8.0.0; extra == "dev"
Requires-Dist: pytest-cov>=7.0.0; extra == "dev"
Requires-Dist: pyvista>=0.40.0; extra == "dev"
Requires-Dist: setuptools>=61.0; extra == "dev"
Requires-Dist: wheel; extra == "dev"
Provides-Extra: all
Requires-Dist: pyvista>=0.40.0; extra == "all"
Requires-Dist: bpy>=4.0.0; extra == "all"

# 3D CAD Toolkit

A high-performance, modular 3D Computer-Aided Design (CAD), procedural modeling, skeletal rigging, and visualization engine engineered for both interactive human workflows and autonomous AI agent collaboration.

---

## Key Features

- **Interactive 3D Viewport (`cad` / `cad-view`)**:
  - Built with [Dear PyGui](https://github.com/hoffstadt/DearPyGui) for a responsive, lightweight cross-platform GUI.
  - Hardware-accelerated OpenGL offscreen rendering with per-pixel depth buffering (Z-buffer), polygon-offset shaded-wireframe overlays, and automatic CPU rasterizer fallback.
  - Adaptive camera speed, pickable 3D orbit/zoom pivot (`P` / `Alt+Click` / Middle-Click) or selected-object pivot, first-person fly mode (WASD + Q/E), 3D translate/rotate/scale manipulator gizmos for both meshes and skeleton bones (with live reactive skinning and nearby-bone distance culling), global **Undo/Redo** (`Ctrl+Z` / `Ctrl+Y`), RGB coordinate axes, and build-plate grid.
  - **Live Cross-Section Slicing**: Interactive Z/X/Y clipping planes with hollow-aware capped cuts, relative bounding-box centering, and `--slice` startup support.
  - **3D Scratchpad & Measurements**: Freehand 3D surface polyline annotations (`Ctrl+Left Drag`) with an 8-color palette, individual stroke **Eraser** (`Ctrl+Right Drag` or Eraser Mode toggle with adjustable brush radius), sweep-to-solid / stroke-to-polyline conversion, and interactive point-to-point distance, angle, and surface area calipers.
  - **In-Memory Multi-Scene Workspace**: Edit and preview scenes with zero disk footprint (`--code`), switch seamlessly between on-disk and `[Memory]` tabs, and load/export all supported CAD formats from the sidebar.

- **AI Agent CollabBridge (HTTP API & Modular `cad-bridge` CLI)**:
  - Built-in HTTP JSON API (`port 8765`) and modular CLI (`cad-bridge`) built for autonomous AI agents and live pair-programming.
  - Supports `--then` command chaining, live in-memory scene injection (`push-code`, `new-scene`, `push-project`), scene/tree/schema inspection, object transforms, camera control, cross-section slicing, cavity solidification (`solidify`, `plug`), `slice-center`, `scan-sections`, `rig-check`, X-ray `screenshot`, `drawings --json` (full polyline vertices + endpoints), topology diagnostics, and file/in-memory export.

- **Procedural & Parametric Modeling**:
  - **Primitives**: `BoxModel`, `RoundedBoxModel`, `SphereModel`, `CylinderModel`, `ConeModel`, `TorusModel`, `WedgeModel`, `RegularPrismModel`, `TextModel`, and `PolylineModel`.
  - **2D Sketches & 3D Operations**: `Sketch2D` (rectangles, circles, polygons, fillets, chamfers, offsets, 2D booleans) with `ExtrusionModel`, `RevolveModel`, `SweepModel`, `LoftModel`, linear/circular patterns, and mirroring.
  - **Exact & Fuzzy CSG Booleans**: Exact 2-manifold Boolean Union, Difference, and Intersection via [Manifold3D](https://github.com/elalish/manifold), plus penetrating `fuse()` / `fuzzy_union()` and sliver cleanup.
  - **Universal File Asset Loading (`FileModel`)**: Polymorphic importing (`MeshFileModel`, `FileGroupModel`, `SceneFileModel`) supporting **3MF, FBX, STL, OBJ, PLY, GLB, GLTF, BLEND**, and external Python scene scripts (`.py`) with multi-part hierarchy preservation, FBX per-material face groups (`material_groups`, `get_material_vertex_mask()`, `split_by_material=True`), disconnected island decomposition (`split_islands()`, `get_islands_info()`), and exact triangle mesh SDF evaluation.
  - **Assemblies & Geometry Caching**: Hierarchical `ObjectGroup` / `CADAssembly` with mate constraints, interactive exploded views, and `@memoize_geometry()` caching.

- **Skeletal Rigging, Geodesic Skinning & Verification**:
  - Hierarchical `Bone` nodes with world-space construction (`Bone.from_points`, `add_child_bone_world`, `world_head`/`world_tail`) and non-cumulative relative posing (`capture_rest_pose`, `set_pose_offset`, `reset_pose`).
  - **Dual Quaternion Skinning (DQS)** (default, volume-preserving) and **Linear Blend Skinning (LBS)** via `SkinBinding`, `SkinnedMesh`, and `SkinMethod`, vectorized Euclidean & mesh-surface **geodesic** `compute_bone_weights` (with `_L`/`_R` side isolation, `region_masks`, `bone_radii`, and Laplacian smoothing), rigid accessory attachment, and bone weight heatmap visualization.
  - Built-in geometry & rig diagnostics: `slice_center` (surface-to-interior cross-section centering), `scan_sections` (multi-slice limb transition & pinch scanner), `verify_rig` (SDF interior containment, L/R mirror symmetry, and weight leak validation), plus pure-Python Binary (7.1–7.7) and ASCII **FBX** skeletal import/export.

- **Signed Distance Fields (SDF), Cavity Detection & Solidification**:
  - Mathematical SDF representation with smooth polynomial CSG blending (`smooth_union`, `smooth_difference`, `smooth_intersection`) and exact Euclidean triangle mesh SDF (`TriangleMeshSDF`).
  - High-resolution Marching Cubes and Dual Contouring meshing with optional quadric mesh decimation (`pyvista` / custom fallback).
  - Enclosed hollow cavity detection (`detect_hollow_spaces()`) with `manifold` (exact B-Rep), `linear_slice` (ruled loft), and `step_slice` algorithms, plus declarative `SolidifyOp`, `CavitiesOp`, `PlugOp`, and composite operators (`UnionOp() + SolidifyOp()`).

- **3D Printability Analysis**:
  - Watertight, manifold, Euler/genus topology diagnostics, critical overhang detection, thin-wall estimation, and support volume calculation.
  - **30+ Printer Build-Volume Presets**: Creality (K1/K1C/K1 SE/K1 Max, K2/K2 Pro/K2 Plus, K3, Hi, SparkX i7, Ender-3/5 series, CR-10/CR-M4), Bambu Lab (X1/P1/A1, A1 Mini, H2D), Prusa (MK3/MK4, CORE One, Mini, XL), Voron (0.2, 2.4/Trident 250/300/350), Elegoo (Centauri Carbon, Neptune 4 series), Anycubic Kobra 3/Max, Qidi Plus 4, Sovol SV08, Flashforge AD5M, and RatRig V-Core 400 (plus custom `WxDxH` dimensions).
  - Automatic print orientation optimization (`--auto-orient`) to reduce support volume and improve build-plate contact.

- **Multi-Format Export & Headless Rendering (`cad-save`)**:
  - **3D Formats**: 3MF, Binary/ASCII FBX, Binary/ASCII STL, OBJ, PLY, GLB, GLTF, and BLEND (with optional `bpy`).
  - **2D Formats**: DXF and SVG.
  - **In-Memory & Stdout Streaming**: `--memory` (raw bytes / base64 JSON) and `-o -` (`--stdout`) with zero disk writes.
  - **High-Resolution Snapshots & X-Ray Multi-View Contact Sheets**: Anti-aliased (SSAA 1x/2x/4x) headless PNG/JPEG/WebP/TIFF/BMP renders with `--show-bones`, `--xray-bones`, `--bone-labels`, `--views front,side,iso`, `--focus <name>`, and `--param key=val` pose overrides.

- **Bundled AI Agent Skills & Type Stubs**:
  - Ships 6 installable agent skills (`cad-tool`, `cad-rigging`, `cad-macro-automator`, `cad-mesh-surgery`, `cad-slicer-sandbox`, `cad-visual-inspector`) via `cad --install-skill`.
  - PEP 561 typed (`py.typed` + `.pyi` stubs across all modules).

- **Cross-Platform & Headless Compatibility**:
  - Tested on Linux (including headless Xvfb and Android Termux/PRoot), Windows, and macOS, with an automated OpenGL driver probe and cache.

---

## Directory Structure

```text
cad/
├── pyproject.toml           # `sanchousf-ai-toolkit-cad` package metadata & console scripts
├── view.py                  # Interactive 3D CAD viewer & unified CLI (`cad`, `cad-view`)
├── save.py                  # Headless exporter & snapshot generator (`cad-save`)
├── check.py                 # Headless scene validator & printability analyzer (`cad-check`)
├── remesh.py                # Standalone mesh decimation & remeshing tool
├── view.sh / view.bat       # Repo-local launchers for the interactive viewer
├── run.sh / run.bat         # Repo-local launchers for bundled example scenes
├── save.sh / save.bat       # Repo-local launchers for headless export
├── check.sh / check.bat     # Repo-local launchers for headless validation
├── bridge.sh / bridge.bat   # Repo-local launchers for CollabBridge CLI
├── requirements.txt         # Core runtime dependencies
├── requirements-dev.txt     # Development and testing dependencies
├── pytest.ini               # Pytest configuration (90% coverage enforcement on `core/`)
│
├── core/                    # Core engine implementation
│   ├── analysis/            # Printability, printer presets, cavity topology, slice_center, scan_sections & verify_rig
│   ├── bridge/              # Modular CollabBridge server, CLI parser, actions, commands & requests
│   ├── common/              # Global constants and progress reporting
│   ├── config.py            # Workspace configuration loader & schema (`.cadrc`, `cad.config.json`)
│   ├── init.py              # Project scaffolder (`cad init` / `cad config`)
│   ├── introspection.py     # Schema introspection & scene template generator (`cad info` / `cad schema`)
│   ├── geometry/            # MeshObject, CADPart, FileModel, Bone, Skinning, transforms & vectors
│   ├── io/                  # Exporters & loaders (3MF, FBX, BLEND, STL, OBJ, PLY, GLB, DXF, SVG)
│   ├── modeling/            # CSG booleans, sketches, extrude/revolve/sweep/loft, assemblies & remesh
│   ├── primitives/          # Parametric shapes, extruded text & 3D polyline sweeps
│   ├── rendering/           # OpenGL FBO renderer, DPG viewport, camera, gizmo, grid, measure & snapshots
│   ├── scratchpad/          # Interactive 3D polyline annotation canvas
│   ├── sdf/                 # Analytical & triangle mesh SDF models, solidify ops & Marching Cubes mesher
│   └── spatial/             # Raycasting, BVH and screen-space object picking
│
├── scene/                   # Scene authoring framework
│   ├── base.py              # `BaseScene` / `CadScene` lifecycle contract
│   ├── cache.py             # Geometry memoization cache (`@memoize_geometry`)
│   ├── loader.py            # Disk & in-memory (`load_scene_from_code`) scene loader
│   └── mock_ui.py           # Headless Dear PyGui mock context for `cad check`
│
├── scenes/                  # Ready-to-run demo scene definitions
│   ├── assembly_demo.py     # Multi-part mechanical assembly with exploded view
│   ├── parametric_demo.py   # Live slider-driven parametric model
│   ├── polyline.py          # Complex 3D swept path demonstrations
│   ├── skinning_demo.py     # Articulated skeletal rigging & DQS/LBS skinning demo
│   └── test.py              # 3D primitives, text, and SDF CSG / Gyroid models
│
├── skills/                  # Bundled AI agent skills & installer (`cad --install-skill`)
│   ├── cad-tool/            # Core modeling, scene authoring & CLI skill
│   ├── cad-rigging/         # Skeletal rigging, DQS/LBS skinning & FBX skill
│   ├── cad-macro-automator/ # Headless macro & bridge automation skill
│   ├── cad-mesh-surgery/    # External mesh repair & healing sidecar skill
│   ├── cad-slicer-sandbox/  # Layer cross-section & printability audit skill
│   └── cad-visual-inspector/# Multi-view visual QA & clipping inspection skill
│
├── scripts/                 # Modular helper scripts
│   ├── env.sh / env.bat     # Dynamic virtual environment and path discovery
│   ├── setup_base.sh/.bat   # Unified installer backend
│   ├── check_gl.sh          # Self-testing OpenGL compatibility probe & cache
│   └── probe_gl.py          # Micro-probe for OpenGL rasterization validation
│
├── ci/                      # Continuous Integration
│   └── action.yml           # GitHub Actions composite action for CAD
│
└── tests/                   # Comprehensive unit & integration test suite (>=90% coverage)
```

---

## Installation & Setup

### Install via PyPI or `ai-toolkit` (Recommended for Users)

```bash
# Install directly from PyPI
pip install sanchousf-ai-toolkit-cad

# Optional extras:
pip install "sanchousf-ai-toolkit-cad[remesh]"   # PyVista / VTK mesh simplification
pip install "sanchousf-ai-toolkit-cad[blender]"  # Blender (.blend) support via bpy
pip install "sanchousf-ai-toolkit-cad[all]"      # All optional features

# Or via the AI-Toolkit manager CLI:
ai-toolkit install cad
ai-toolkit install "cad[all]"
```

This installs the console scripts `cad`, `cad-view`, `cad-save`, `cad-bridge`, and `cad-check` onto your `PATH`.

### Local Source Setup (Repository Checkout / Contributors)

Automated setup scripts create an isolated `.venv`, upgrade `pip`, install requirements, and verify core imports:

- **Runtime Setup**:
  - Linux / macOS / Termux: `./setup.sh`
  - Windows: `setup.bat`
- **Developer Setup (includes `pytest`, `pytest-cov`, and `pyvista`)**:
  - Linux / macOS / Termux: `./setup_dev.sh`
  - Windows: `setup_dev.bat`

> When working directly from a repository checkout without activating `.venv`, you can also use the wrapper scripts (`./view.sh`, `./run.sh`, `./save.sh`, `./bridge.sh`, `./check.sh` on Linux/macOS, or `.bat` equivalents on Windows).

---

## Quick Start

### 1. Project Initialization & Scaffolding (`cad init`)

Initialize a new CAD modeling workspace with auto-detected directories, configuration, starter scene, and convenience launchers:

```bash
# Initialize current directory with auto-detected scenes/ and output/
cad init

# Initialize a custom directory with a 300x300x400 mm bed and pre-installed agent skill
cad init path/to/project --bed 300x300x400 --install-skill

# Machine-readable JSON output for automated AI agent scaffolding
cad init path/to/project --bed voron350 --json
```

**Generated Project Artifacts:**
- `cad.config.json` & `.cadrc`: Workspace configuration defining `scenes_dir`, `export_dir`, `default_scene`, and `printer_bed` (also supports `[tool.cad]` in `pyproject.toml`).
- `scenes/`: Dedicated scene folder with an auto-generated starter template (if empty).
- `output/`: Default target for headless exports.
- Convenience Launchers: `view`, `check`, `export`, `new_scene`, and `bridge` wrapper scripts.

---

### 2. Workspace Configuration, Introspection & Templates (`cad config`, `cad info`, `cad schema`, `cad new-scene`)

Inspect workspace settings, discover primitive/operation APIs, inspect external 3D meshes, or scaffold new scenes:

```bash
# Inspect and validate active workspace configuration
cad config show --json
cad config validate
cad schema config --json

# Introspect primitives, modeling operations, and class schemas
cad info --primitives
cad info --operations
cad info --mesh model.3mf --json
cad schema BoxModel

# Generate a ready-to-run scene template (parametric, basic, assembly, sdf, sketch)
cad new-scene --type parametric --output scenes/my_param_scene.py
```

---

### 3. Launching the Interactive 3D Viewer

```bash
# Launch viewer discovering scenes in the current workspace
cad
# (or repo-local wrappers: ./view.sh / view.bat, or ./run.sh / run.bat for bundled demos)

# Open a specific Python scene or 3D file directly (.3mf, .fbx, .stl, .obj, .ply, .glb, .blend)
cad scenes/assembly_demo.py
cad scenes/skinning_demo.py
cad assets/part.3mf

# Launch an in-memory scene with zero files written to disk (or pipe via stdin)
cad --code "from cad.scene import BoxModel; model = BoxModel(20, 20, 20)"
cat my_scene.py | cad --code -

# Start with a live cross-section clipping plane or cavity solidification enabled
cad -s assembly_demo --slice --slice-axis X --slice-offset 0.0
cad -s housing --solidify

# Force hardware OpenGL or CPU software rendering
cad --opengl
cad --cpu
```

#### Viewport Navigation & Controls
- **Left Mouse Drag**: Orbit camera around active 3D pivot (or selected object's center); click to select meshes or **skeleton bones** (repeat-click cycles through overlapping bones and meshes).
- **Right Mouse Drag**: First-person look / pan-tilt in place (**WASD + Q/E** to fly with adaptive camera speed).
- **Middle Mouse Drag**: Pan camera laterally in the view plane.
- **Middle Click / Alt + Left Click / `P`**: Point at any 3D surface or bone joint to set it as the camera's **3D orbit & zoom pivot** (displayed with a crosshair reticle; press `Esc` or click **Reset Pivot** / **Reset Camera** to clear).
- **Mouse Wheel**: Zoom smoothly toward/away from the active orbit pivot.
- **`Q` / `W` / `E` / `R` / `M` / `P`**: Switch between Select, Move (Translate), Rotate, Scale, Caliper Measure, and Pick Orbit Pivot tools. Both `WORLD` and `LOCAL` gizmo spaces work directly on selected `Bone`s with live skinning deformation.
- **Nearby Bones Slider** (Display Settings): Hide skeleton bones farther than a chosen camera distance (`0 = All`) so distant bones never overlap nearby joints when zoomed in.
- **Ctrl + Left Mouse Drag**: Draw 3D polyline annotations onto surfaces or in 3D space (`C` cycles color, `1`–`8` quick-selects palette colors).
- **Ctrl + Right Mouse Click/Drag (or Eraser Mode)**: Erase individual 3D scratchpad strokes with hover highlight and adjustable pixel radius (`Esc` exits Eraser Mode).
- **`Ctrl + Z` / `Ctrl + Y` (or `Ctrl + Shift + Z`)**: Global **Undo / Redo** across all interactive edits (object & bone gizmo transforms, bone/rig pose resets, dynamic properties, visibility toggles, SDF operators, scratchpad draw/erase/recolor/clear, measurements, and orbit pivots).

---

### 4. Headless Scene Exporting & Snapshot Generation (`cad-save` / `cad save`)

```bash
# Exact 2-manifold CSG boolean merge to STL (no voxelization, instant via Manifold3D)
cad save -s scenes/assembly_demo.py -o output/assembly.stl --merge

# Export to 3MF, FBX, GLB, OBJ, PLY, BLEND, DXF, or SVG (auto-detected from extension)
cad save -s scenes/parametric_demo.py -e output/model.glb
cad save -s scenes/skinning_demo.py -e output/rigged.fbx
cad save -s scenes/assembly_demo.py -e output/model.stl --ascii

# Export directly from an in-memory script to disk, stdout, or base64 JSON memory buffer
cad save --code "from cad.scene import BoxModel; model = BoxModel(20, 20, 10)" -o output/box.stl
cad save --code "from cad.scene import BoxModel; model = BoxModel(20, 20, 10)" --memory --format stl --json
cad save --code "from cad.scene import BoxModel; model = BoxModel(20, 20, 10)" -o - --format stl > box.stl

# Volumetric SDF merge with smooth blending (Marching Cubes)
cad save -s scenes/assembly_demo.py --sdf-merge smooth_union --sdf-k 3.0 --voxel-size 0.2 -o output/merged.stl

# Detect and solidify internal hollow cavities before export
cad save -s hollow_part.stl -o output/solid_part.stl --solidify --cavity-algorithm manifold

# Generate a 4K anti-aliased isometric preview image or X-ray rig multi-view contact sheet
cad save -s scenes/assembly_demo.py -i preview.png --resolution 3840x2160 --cam-ori iso --supersample 4
cad save -s scenes/skinning_demo.py -i rig_check.png --views front,side,iso --xray-bones --bone-labels --param bend=45

# Analyze 3D printability and auto-orient for a printer preset
cad save -s scenes/assembly_demo.py --analyze-print --printer-bed bambu --auto-orient
```

---

### 5. AI Agent CollabBridge (`cad-bridge`)

When the viewer is running, it hosts an HTTP JSON API on port `8765`. External processes and AI agents can query and manipulate the live viewport using `cad-bridge` (or `./bridge.sh` / `bridge.bat`), including chaining multiple actions in a single invocation with `--then`:

```bash
# Inspect viewer status, scenes, hierarchy tree, or latest runtime error
cad-bridge status --json
cad-bridge scenes
cad-bridge tree --json
cad-bridge last-error

# Create an in-memory scene tab or hot-reload Python code directly (zero files on disk)
cad-bridge new-scene "Prototype Bracket"
cad-bridge push-code "from cad.scene import CylinderModel; model = CylinderModel(10, 30)" my_part
cat scene.py | cad-bridge push-code - my_part
cad-bridge push-project .

# Switch scenes, read active source code, or validate a script
cad-bridge scene parametric_demo
cad-bridge code
cad-bridge validate scenes/parametric_demo.py

# Select, transform, explode, and chain commands with --then
cad-bridge select "BasePlate" --then translate 10,0,5 --then camera reset
cad-bridge explode 0.5

# Live cross-section slicing, cavity solidification, anatomy & rig verification, and X-ray screenshots
cad-bridge section Z 5.0
cad-bridge section X 0.0 --flip
cad-bridge section clear
cad-bridge slice-center 15.0,-2.0,110.0 Z --json
cad-bridge scan-sections Z 24 --json
cad-bridge rig-check --json
cad-bridge screenshot rig_xray.png front,side,iso --xray-bones --bone-labels
cad-bridge screenshot hand_zoom.png front,side --xray-bones --focus Hand_L
cad-bridge solidify
cad-bridge plug "Housing" --plug-only --no-auto-cap --max-z 16.8
cad-bridge topology --json
cad-bridge print-check

# Query and convert 3D scratchpad annotations
cad-bridge drawings --json
cad-bridge color red
cad-bridge color green 0        # Recolor stroke #0 to green
cad-bridge sweep -1 2.5         # Sweep last stroke into a 3D solid tube
cad-bridge polyline -1 1.5      # Convert last stroke into a PolylineModel
cad-bridge clear-drawings

# Export active viewer model to disk or in-memory base64 JSON
cad-bridge export output/exported_model.stl
cad-bridge export memory --format stl --json
```

---

### 6. Headless Scene Validation & Health Analyzer (`cad check` / `cad-check`)

Validate scene scripts headlessly without opening a GUI window (import checks, instantiation, headless UI dry-run, geometry checks, cavity detection, and 3D printability diagnostics):

```bash
# Validate a single scene or all workspace scenes with JSON output
cad check scenes/parametric_demo.py --json
cad check --all --json

# Validate in-memory scene code (or piped stdin) with zero files created on disk
cad check --code "from cad.scene import BoxModel; model = BoxModel(20, 20, 20)" --json
cat my_scene.py | cad check --code - --strict

# Override scene parameters, inspect cavities, and enforce strict printer bed checks
cad check scenes/parametric_demo.py --param length=120 --param width=80
cad check scenes/assembly_demo.py --cavities --strict --bed k1_max
```

---

### 7. Installing Bundled AI Agent Skills

Install any or all of the 6 bundled CAD skills (`cad-tool`, `cad-rigging`, `cad-macro-automator`, `cad-mesh-surgery`, `cad-slicer-sandbox`, `cad-visual-inspector`) for your AI coding agent:

```bash
# List all bundled CAD skills
cad --list-skills

# Install all bundled CAD skills (including cad-tool & cad-rigging) into the active workspace (.agents/skills/)
cad --install-skills
# (or: cad --install-skill --all)

# Install a single skill (e.g. cad-rigging) or target another agent (antigravity, claude, cursor, windsurf, copilot)
cad --install-skill workspace --skill cad-rigging
cad --install-skills global --agent claude

# Or install skills across all installed AI-Toolkit subprojects via the manager CLI
ai-toolkit install-skills
```

---

### 8. Running Tests & Code Coverage

Execute the test suite from `cad/`:

```bash
./run_tests.sh
# Windows: run_tests.bat
# Or inside your activated environment: pytest
```

- **Enforced Coverage**: [pytest.ini](pytest.ini) enforces a minimum of **90% test coverage** across `core/`; test runs below this threshold fail automatically.
- **Coverage Reports**: HTML reports are generated at `cad/htmlcov/index.html` and XML reports at `cad/coverage.xml`.

---

## OpenGL Driver Compatibility & Probing

In virtualized, containerized, or headless environments (such as Android PRoot, headless CI runners, or systems without GPU drivers), default OpenGL drivers may lack hardware WGL/GLX support.

The toolkit includes an automated driver probe:
- **Automatic Fallback**: [scripts/check_gl.sh](scripts/check_gl.sh) tests OpenGL rasterization via [scripts/probe_gl.py](scripts/probe_gl.py) and caches the result in `.venv/.gallium_probe`. If default Mesa `llvmpipe` fails, it automatically selects `softpipe`.
- **Force Re-testing**: Pass `--retest-gl` to any shell launcher script to re-evaluate the host environment:
  ```bash
  ./run.sh --retest-gl
  ./run_tests.sh --retest-gl
  ./scripts/check_gl.sh --retest
  ```
- **Inspect Status**:
  ```bash
  ./scripts/check_gl.sh --status
  ```

---

## Continuous Integration

CI is configured in [`.github/workflows/cad.yml`](../.github/workflows/cad.yml) and runs on pushes and pull requests affecting `cad/` on `main`, `dev/**`, and `release/**`:
- **Matrix**: Runs on Ubuntu (`ubuntu-latest` with Xvfb) for branch pushes/PRs, adds Windows (`windows-latest`) on pull requests targeting `main`, and supports a full Linux + Windows + macOS matrix via manual `workflow_dispatch` (`run_full: true`) on Python 3.12.
- **Action**: Uses the self-contained composite action in [ci/action.yml](ci/action.yml).
- **Artifacts**: Uploads HTML coverage reports and submits `cad/coverage.xml` to Codecov.
