# Project Scope: Calibrated Trace CAD

## 1. Purpose

This document defines the initial product scope, technical architecture, development priorities, and implementation rules for a desktop application that converts manually traced real-world outlines into clean, scale-accurate 2D CAD geometry and DXF exports.

The application is not an AI-based image-to-vector tool. It is a deterministic, user-controlled 2D tracing and sketching application that uses a calibrated printed sheet and photo reference as a scale-accurate background layer. The user manually reconstructs clean CAD geometry over the reference image using lines, arcs, circles, and assisted fitting tools.

The goal is to produce technically valid 2D DXF drawings suitable for laser cutting, CNC routing, milling preparation, or further editing in CAD software.

---

## 2. Product Concept

The product should allow a user to:

1. Print a calibrated marker sheet.
2. Place or trace a real object on the sheet using a pencil, fineliner, or marker.
3. Photograph or scan the sheet.
4. Import the image into the application.
5. Let the software detect the sheet, correct perspective, and establish a real-world millimetre coordinate system.
6. Manually trace the visible sketch using precise CAD-style tools.
7. Optionally refine the geometry with dimensions or constraints.
8. Export a clean DXF file using real CAD entities.

The standard workflow must not require manual dimensioning. Dimensioning and constraints are optional advanced features.

The core UX principle is:

> The physical sheet provides scale. The photo provides visual reference. The user creates clean geometry manually.

---

## 3. Non-Goals

The application must not be designed as:

- A fully automatic AI image-to-DXF converter.
- A raster autotracing tool that blindly converts pixels into vector paths.
- A general-purpose 3D CAD application.
- A parametric CAD clone in the first MVP.
- A web-only prototype.
- A Python application.

Automatic detection of pencil lines may be added later as an assistive feature, but it must never become the source of final geometry without explicit user confirmation.

---

## 4. Target Platform and Technology Stack

### 4.1 Primary Stack

Use:

- Language: C#
- Runtime: .NET 8 or newer
- UI framework: Avalonia UI
- Rendering: Avalonia custom controls / SkiaSharp where useful
- Computer vision: OpenCvSharp / OpenCV
- DXF export: netDxf initially, with an abstraction layer to allow replacement later
- Project format: custom JSON
- Unit tests: xUnit

### 4.2 Release Target

The first release target is:

- Windows x64
- Portable executable or portable application folder
- No forced installer
- No Python runtime dependency
- No external CAD dependency

Preferred initial packaging:

```bash
# Portable folder build, preferred while native OpenCV DLLs are involved
dotnet publish src/TraceCad.App \
  -c Release \
  -r win-x64 \
  --self-contained true
```

Single-file publishing may be evaluated later:

```bash
dotnet publish src/TraceCad.App \
  -c Release \
  -r win-x64 \
  --self-contained true \
  /p:PublishSingleFile=true \
  /p:IncludeNativeLibrariesForSelfExtract=true
```

### 4.3 Future Platforms

The architecture should not block later builds for:

- Linux x64
- macOS x64
- macOS arm64

However, Windows x64 is the first-class MVP target.

---

## 5. Recommended Solution Structure

Use a clean multi-project .NET solution.

```text
TraceCad/
  src/
    TraceCad.App/          # Avalonia UI application
    TraceCad.Core/         # Geometry, document model, tools, snapping, validation
    TraceCad.Dxf/          # DXF export/import abstraction
    TraceCad.Vision/       # OpenCV, marker detection, homography, calibration
  tests/
    TraceCad.Tests/        # Unit tests for geometry, export, transforms, validation
  docs/
    project_scope.md
    architecture.md
    mvp.md
    dxf-export.md
  samples/
    reference-images/
    exports/
```

### 5.1 Dependency Rules

The dependencies must flow in one direction:

```text
TraceCad.App
  -> TraceCad.Core
  -> TraceCad.Dxf
  -> TraceCad.Vision

TraceCad.Dxf
  -> TraceCad.Core

TraceCad.Vision
  -> TraceCad.Core where needed for coordinate data only

TraceCad.Core
  -> no UI framework dependency
  -> no Avalonia dependency
  -> no OpenCV dependency
  -> no DXF library dependency
```

The `TraceCad.Core` project must remain UI-independent and testable.

---

## 6. Core Design Principles

### 6.1 Millimetres as Internal Units

All model-space geometry must be stored in millimetres.

Pixels may only be used in the view/rendering layer.

Required coordinate spaces:

```text
Model Space      real geometry in mm
View Space       screen pixels
Reference Space  calibrated image/background
Export Space     DXF coordinate output in mm
```

Never store final CAD geometry in pixels.

### 6.2 Deterministic Geometry

Final geometry must consist of explicit CAD entities:

- Lines
- Circles
- Arcs
- Polylines where appropriate
- Optional dimensions later
- Optional construction entities

Do not export raw traced raster contours as the main workflow.

### 6.3 Reference Image Is Not Geometry

The imported photo or scan is a locked background/reference layer.

It provides:

- visual guidance
- scale
- orientation
- real-world coordinate alignment

It does not directly define final CAD geometry unless the user explicitly creates geometry from it.

### 6.4 Optional Precision, Low Friction by Default

The default workflow should require no manual bemaßung/dimensioning.

Advanced users may later add:

- exact length
- exact radius/diameter
- exact angle
- horizontal/vertical constraints
- parallel/perpendicular constraints
- tangency
- equality constraints

But the primary workflow is visual tracing over a scale-accurate reference.

---

## 7. User Workflow

### 7.1 Standard Workflow

1. Start new project.
2. Import a photo/scan of a traced calibration sheet.
3. The application detects the printed sheet and sets the document scale.
4. The reference image is displayed on the canvas as a locked, semi-transparent layer.
5. The user manually traces the outline with CAD tools.
6. The application displays endpoint snaps, grid, and geometry previews.
7. The user validates the sketch.
8. The application exports a clean DXF.

### 7.2 Early MVP Workflow Before Marker Detection

For MVP staging, marker detection may be delayed.

Initial workflow:

1. Start app.
2. Work on an empty millimetre canvas.
3. Draw lines, circles, and arcs.
4. Export DXF.

Then add:

1. Import reference image.
2. Manually scale/position the reference image.
3. Trace over it.

Then add:

1. Marker sheet detection.
2. Automatic calibration.

---

## 8. MVP Phases

### 8.1 Version 0.1 — Editor Core

Goal: prove that the application can create clean 2D CAD geometry and export valid DXF.

Required features:

- Avalonia desktop app starts reliably.
- Custom drawing canvas.
- Model-space coordinate system in mm.
- Pan and zoom.
- Grid display.
- Basic snapping to existing endpoints.
- Draw line.
- Draw circle through 3 points.
- Draw arc through 3 points.
- Select entity.
- Delete selected entity.
- Undo/redo.
- Save/load custom JSON project file.
- Export DXF containing LINE, CIRCLE, and ARC entities.

Not required in 0.1:

- OpenCV
- marker detection
- camera input
- real-time calibration
- constraints
- automatic image tracing
- dimensions

### 8.2 Version 0.2 — Reference Image Layer

Goal: allow manual tracing over an imported background image.

Required features:

- Import image as reference.
- Display reference below CAD entities.
- Adjust image opacity.
- Lock/unlock reference image.
- Move/scale/rotate reference image manually if needed.
- Continue drawing geometry over image.

### 8.3 Version 0.3 — Calibration Sheet

Goal: automatically convert a photographed sheet into a scale-accurate reference layer.

Required features:

- Generate printable A4 calibration sheet.
- Sheet contains machine-readable markers and known geometry.
- Detect markers in imported photo.
- Compute perspective transform/homography.
- Warp image into orthographic top-down view.
- Place image into model space using millimetres.
- Show calibration status.

Preferred marker types:

- ArUco
- ChArUco
- AprilTag if practical

### 8.4 Version 0.4 — Assisted Tracing

Goal: make manual tracing faster and cleaner without automatic black-box vectorisation.

Required features:

- Fit line from multiple user-selected points.
- Fit circle from multiple user-selected points.
- Fit arc from multiple user-selected points.
- Snap endpoints together.
- Close contour command.
- Highlight open endpoints.
- Detect duplicate or near-duplicate segments.
- Detect very short unwanted segments.

### 8.5 Version 0.5 — Optional Precision and Export Profiles

Goal: add CAD-like refinement and production checks.

Required features:

- Optional length correction.
- Optional radius/diameter correction.
- Optional angle correction.
- Horizontal/vertical constraints.
- Parallel/perpendicular constraints.
- Simple layer system UI.
- Export profiles for CAD and laser/CAM.
- Export validation report.

---

## 9. Calibration Sheet Requirements

The printed sheet should be designed for reliable detection and practical tracing.

### 9.1 Initial Sheet Size

Start with:

- A4 portrait
- Units: millimetres
- Printed at 100 percent scale

Future options:

- A3
- Letter
- custom sheet sizes

### 9.2 Sheet Elements

The sheet should include:

- Four corner markers outside the main drawing area.
- Known marker positions in millimetres.
- A visible outer reference frame.
- A light drawing grid, e.g. 5 mm or 10 mm.
- A 100 mm printed control line.
- Template ID/version.
- Instruction text: print at 100 percent / actual size / no scaling.

### 9.3 Drawing Area

Markers must not overlap with the main tracing area.

The drawing area should be visually clean and not interfere with pencil lines.

Recommended:

- light grey grid
- high contrast markers
- dark outer frame
- reserved margins for markers

---

## 10. Geometry Model

### 10.1 Required Primitive Types

The core model must support at least:

- Point2
- Vector2
- LineEntity
- CircleEntity
- ArcEntity
- PolylineEntity later
- Layer
- SketchDocument
- ReferenceImage

Example conceptual model:

```csharp
public readonly record struct Point2(double X, double Y);

public abstract record Entity(Guid Id, string Layer);

public record LineEntity(
    Guid Id,
    string Layer,
    Point2 Start,
    Point2 End
) : Entity(Id, Layer);

public record CircleEntity(
    Guid Id,
    string Layer,
    Point2 Center,
    double Radius
) : Entity(Id, Layer);

public record ArcEntity(
    Guid Id,
    string Layer,
    Point2 Center,
    double Radius,
    double StartAngleDeg,
    double EndAngleDeg
) : Entity(Id, Layer);
```

### 10.2 Three-Point Circle

The application must allow a circle to be defined by three user-selected points on its circumference.

Implementation must compute:

- centre point
- radius
- validity check for collinear or near-collinear points

### 10.3 Three-Point Arc

The application must allow an arc to be defined by:

- start point
- point on arc
- end point

Implementation must compute:

- centre point
- radius
- start angle
- end angle
- direction/orientation
- validity check for collinear or near-collinear points

### 10.4 Entity Editing

At minimum:

- select
- delete
- move later
- edit via properties later

Do not overbuild editing in the first iteration.

---

## 11. Tool System

The canvas must use a tool-state model. Do not hard-code all interactions into the canvas control.

Recommended interface concept:

```csharp
public interface ISketchTool
{
    string Name { get; }
    void PointerDown(ToolContext context, Point2 modelPoint);
    void PointerMove(ToolContext context, Point2 modelPoint);
    void PointerUp(ToolContext context, Point2 modelPoint);
    void KeyDown(ToolContext context, Key key);
    void RenderOverlay(DrawingContext context, ToolRenderContext renderContext);
}
```

Initial tools:

- SelectTool
- LineTool
- Circle3PointTool
- Arc3PointTool
- PanTool or integrated middle-mouse pan
- Delete command

Later tools:

- CircleCenterRadiusTool
- PolylineTool
- FitLineTool
- FitCircleTool
- FitArcTool
- TrimTool
- OffsetTool
- FilletTool
- DimensionTool

---

## 12. Snapping

### 12.1 MVP Snaps

Required initially:

- snap to entity endpoints
- snap to grid optionally

### 12.2 Later Snaps

Add later:

- midpoint
- circle centre
- arc centre
- intersection
- tangent
- perpendicular foot
- nearest point on entity
- reference-image assisted snap, if implemented

### 12.3 Snap Behaviour

Snapping must happen in model space.

The view may display snap indicators in screen space, but the resulting point must be stored in millimetres.

---

## 13. Rendering Requirements

The custom canvas should render:

- background
- grid
- reference image
- geometry entities
- selected entities
- hover highlights
- snap indicators
- active tool preview
- optional axes/origin

The canvas must support:

- zoom around cursor
- pan by middle mouse button or equivalent
- smooth redraw
- precise hit testing

Rendering must not mutate the document model.

---

## 14. Project File Format

Use a custom JSON format as the native document format.

DXF is an export format, not the internal source of truth.

Example conceptual structure:

```json
{
  "version": 1,
  "units": "mm",
  "document": {
    "width": 210.0,
    "height": 297.0
  },
  "reference": {
    "imagePath": "reference.png",
    "opacity": 0.55,
    "locked": true,
    "transform": {
      "originX": 0.0,
      "originY": 0.0,
      "scaleX": 1.0,
      "scaleY": 1.0,
      "rotationDeg": 0.0
    }
  },
  "layers": [
    { "name": "CUT", "visible": true, "locked": false },
    { "name": "CONSTRUCTION", "visible": true, "locked": false },
    { "name": "DIMENSIONS", "visible": true, "locked": false }
  ],
  "entities": [
    {
      "type": "line",
      "id": "00000000-0000-0000-0000-000000000001",
      "layer": "CUT",
      "start": [10.0, 20.0],
      "end": [80.0, 20.0]
    }
  ]
}
```

---

## 15. Layer Model

Initial layers:

- CUT
- CONSTRUCTION
- REFERENCE
- DIMENSIONS
- DEBUG

### 15.1 CUT

Final production geometry intended for DXF export.

### 15.2 CONSTRUCTION

Helper geometry. Should not be exported by default.

### 15.3 REFERENCE

Imported or calibrated reference information.

### 15.4 DIMENSIONS

Optional dimension annotations later.

### 15.5 DEBUG

Internal generated geometry or diagnostics. Hidden by default in production builds unless debug mode is enabled.

---

## 16. DXF Export Requirements

### 16.1 General

The DXF export must use millimetres.

Final entities should export as native CAD geometry where possible:

| Internal Entity | DXF Entity |
|---|---|
| LineEntity | LINE |
| CircleEntity | CIRCLE |
| ArcEntity | ARC |
| PolylineEntity | LWPOLYLINE |

### 16.2 Export Profiles

Support at least two conceptual profiles eventually.

#### CAD Profile

- Preserve LINE, CIRCLE, ARC.
- Use real geometry.
- Keep layers.
- Suitable for FreeCAD, Fusion, AutoCAD-like systems.

#### Laser/CAM Profile

- Prefer closed contours.
- Optionally preserve arcs.
- Optionally flatten arcs/circles to polylines.
- Configurable tolerance, e.g. 0.05 mm.
- Avoid duplicate line cuts.

### 16.3 Validation Before Export

The app should eventually report:

- open endpoints
- duplicate segments
- very short segments
- self-intersections
- invalid arcs
- zero-length lines
- non-mm units

For MVP 0.1, basic DXF export without full validation is acceptable, but the architecture must leave room for validation.

---

## 17. Validation and Quality Checks

The application should later include a “drawing health” check.

Important checks:

- outer contour closed
- inner contours closed
- no duplicate segments
- no tiny accidental segments below tolerance
- no self-intersections
- arcs have valid radius
- circles have positive radius
- all exportable geometry is on exportable layers

Validation results should be user-facing but not block saving.

Export may warn before writing problematic DXF files.

---

## 18. Computer Vision Scope

### 18.1 Responsibility

The vision module is responsible for:

- marker detection
- perspective correction
- coordinate calibration
- optional lens/camera calibration later
- generating a corrected reference image

The vision module is not responsible for producing final CAD entities.

### 18.2 Initial Marker Workflow

1. Load image.
2. Detect marker corners.
3. Match detected marker IDs to template definition.
4. Compute homography from image points to sheet mm points.
5. Warp image to orthographic top-down sheet view.
6. Store corrected image as reference.
7. Attach image to document at known mm dimensions.

### 18.3 Calibration Result

The result should include:

- success/failure
- detected marker count
- template ID
- sheet size in mm
- homography matrix
- warped image
- quality score later

### 18.4 Quality Feedback Later

The UI should later show:

- sheet detected: yes/no
- marker count
- blur/sharpness estimate
- perspective severity
- estimated calibration quality
- warning if image is too skewed or low resolution

---

## 19. User Interface Requirements

### 19.1 Main Window Layout

Recommended layout:

```text
┌──────────────────────────────────────────────┐
│ Menu / Toolbar                               │
├────────────┬───────────────────────┬─────────┤
│ Tools      │ Canvas                │ Props   │
│            │                       │ Panel   │
├────────────┴───────────────────────┴─────────┤
│ Status bar / command hints                   │
└──────────────────────────────────────────────┘
```

### 19.2 Main Toolbar

Initial buttons:

- New
- Open
- Save
- Import Reference
- Export DXF
- Select
- Line
- Circle 3P
- Arc 3P
- Undo
- Redo

### 19.3 Canvas UX

The canvas should feel closer to a lightweight CAD/sketch tool than a paint program.

Required controls:

- left click for tool actions
- mouse wheel zoom
- middle mouse drag pan
- Esc cancels current operation
- Delete deletes selection
- Ctrl+Z undo
- Ctrl+Y or Ctrl+Shift+Z redo
- Ctrl+S save

### 19.4 Status Bar

Show context-specific prompts, e.g.:

```text
Line Tool: choose start point
Line Tool: choose end point
Circle 3P: choose first point on circle
Arc 3P: choose point on arc
```

This reduces the need for documentation.

---

## 20. Undo/Redo

Implement undo/redo early.

Preferred model:

- command pattern
- each document change is a command
- commands can apply and revert

Initial commands:

- AddEntityCommand
- DeleteEntityCommand
- AddLayerCommand later
- SetReferenceImageCommand later

Avoid editing the document directly from tools without command tracking.

---

## 21. Testing Requirements

### 21.1 Geometry Tests

Test:

- line length
- circle from three points
- arc from three points
- collinear failure cases
- angle normalization
- coordinate transforms

### 21.2 DXF Tests

Test:

- export line
- export circle
- export arc
- units are mm
- layer names preserved

### 21.3 Document Tests

Test:

- save/load JSON roundtrip
- entity IDs preserved
- layers preserved
- document version handled

### 21.4 Vision Tests Later

Use sample images for:

- marker detection
- homography
- failed detection
- distorted/skewed sheet

---

## 22. Implementation Priorities

### Highest Priority

1. Clean Core model.
2. Custom canvas with model/view transform.
3. Tool system.
4. Line/Circle/Arc creation.
5. DXF export.
6. JSON project file.
7. Undo/redo.

### Medium Priority

1. Reference image layer.
2. Manual scaling/rotation of reference image.
3. Layers UI.
4. Basic validation.
5. Export profiles.

### Later Priority

1. Marker sheet generation.
2. OpenCV marker detection.
3. Homography correction.
4. Fit tools.
5. Optional dimensions.
6. Optional constraints.
7. Camera live mode.

---

## 23. Development Rules for the Agent

When implementing, follow these rules:

1. Do not implement automatic AI tracing as a core feature.
2. Do not store geometry in pixels.
3. Do not put CAD logic inside Avalonia UI controls.
4. Do not make DXF the internal document format.
5. Do not build a monolithic canvas class containing all tools.
6. Do not add OpenCV before the basic editor and DXF export work.
7. Keep `TraceCad.Core` independent from Avalonia and OpenCV.
8. Prefer small testable geometry functions.
9. Use explicit entity classes instead of generic loosely typed objects.
10. Keep the first MVP narrow and working.
11. Implement robust error handling for invalid circle/arc definitions.
12. Maintain millimetre units across the model and export layers.
13. Every tool should have clear interaction state.
14. Every document mutation should eventually go through undoable commands.

---

## 24. First Development Task

Create the initial .NET solution with this structure:

```text
TraceCad/
  src/
    TraceCad.App/
    TraceCad.Core/
    TraceCad.Dxf/
    TraceCad.Vision/
  tests/
    TraceCad.Tests/
```

Then implement MVP 0.1 skeleton:

1. `TraceCad.Core`
   - `Point2`
   - `Vector2`
   - `Entity`
   - `LineEntity`
   - `CircleEntity`
   - `ArcEntity`
   - `SketchDocument`
   - `Layer`
   - basic geometry helpers

2. `TraceCad.App`
   - Avalonia main window
   - custom canvas control
   - pan/zoom view transform
   - grid rendering
   - render lines/circles/arcs from document
   - toolbar for select/line/circle3p/arc3p

3. `TraceCad.Dxf`
   - exporter interface
   - initial netDxf-based exporter
   - export LINE/CIRCLE/ARC in mm

4. `TraceCad.Tests`
   - circle from 3 points tests
   - arc from 3 points tests
   - JSON document roundtrip test
   - basic DXF export smoke test

Do not implement marker detection yet.

---

## 25. Acceptance Criteria for MVP 0.1

MVP 0.1 is acceptable when:

1. The app launches as a Windows desktop application.
2. The user can pan and zoom the canvas.
3. The user can draw a line by clicking two points.
4. The user can create a circle from three clicked points.
5. The user can create an arc from three clicked points.
6. The user can select and delete entities.
7. The user can save and reload a project file.
8. The user can export a DXF.
9. The exported DXF opens in at least one external CAD/CAM program with correct millimetre scale.
10. The core geometry calculations are covered by unit tests.

---

## 26. Product Positioning Summary

The application should be developed as:

> A calibrated 2D tracing CAD tool that helps users turn real-world traced outlines into clean, scale-accurate DXF geometry without forcing them into traditional CAD dimensioning workflows.

Primary value:

- approachable workflow
- real-world scale from printed sheet
- deterministic geometry
- clean CAD export
- no AI/autotrace slop
- optional precision tools for advanced users

