diff --git a/.fusion-addin.json b/.fusion-addin.json
index d1160f5..3f77144 100644
--- a/.fusion-addin.json
+++ b/.fusion-addin.json
@@ -1,6 +1,6 @@
{
"name": "InsertTo",
"display_name": "InsertTo",
- "description": "Place SVG curves on a sketch plane or fit them to a linked frame with accurate dimensions and live preview.",
+ "description": "Place SVGs and trace photos, logos and drawings into closed Autodesk Fusion sketch outlines.",
"initialized": true
}
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 7438ea4..b5b6c9c 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -81,7 +81,7 @@ jobs:
strategy:
fail-fast: false
matrix:
- os: [ubuntu-latest, macos-latest, windows-latest]
+ os: [ubuntu-latest, macos-26-intel, windows-latest]
env:
ADDIN_NAME: ${{ needs.project.outputs.product }}
PACKAGE_VERSION: ${{ needs.version.outputs.version || '0.1.0' }}
@@ -92,6 +92,9 @@ jobs:
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
python-version: '3.12'
+ - name: Install Linux image decoder for offline tracing tests
+ if: runner.os == 'Linux'
+ run: python -m pip install Pillow==13.0.0
- name: Compile without Autodesk Fusion
shell: bash
run: python -m compileall -q "$ADDIN_NAME" scripts tests
@@ -100,6 +103,10 @@ jobs:
- name: Generate reproducible Fusion ZIP and SHA-256
shell: bash
run: python scripts/build.py --version "$PACKAGE_VERSION" --allow-template
+ - name: Trace PNG and JPEG using the extracted product
+ if: needs.project.outputs.initialized == 'true'
+ shell: bash
+ run: python scripts/check_trace_package.py --archive "dist/${ADDIN_NAME}-${PACKAGE_VERSION}.zip"
- name: Validate package and embedded manifest
uses: 4FusionLab/.github/.github/actions/verify-archive@ad9d60ba4aabc494b4f2c85d6c566a50ca423751
with:
diff --git a/InsertTo/InsertTo.manifest b/InsertTo/InsertTo.manifest
index 03c4f4b..f5d5874 100644
--- a/InsertTo/InsertTo.manifest
+++ b/InsertTo/InsertTo.manifest
@@ -4,7 +4,7 @@
"id": "d4f953a4-7cc6-4027-9699-dc025ebc8966",
"author": "Pavel Kuznetsov",
"description": {
- "": "Place SVG curves on a sketch plane or fit them to a linked frame with accurate dimensions and live preview."
+ "": "Place SVGs and trace photos, logos and drawings into closed Autodesk Fusion sketch outlines."
},
"version": "0.1.0",
"runOnStartup": true,
diff --git a/InsertTo/InsertTo.py b/InsertTo/InsertTo.py
index 7036b9a..2793b9f 100644
--- a/InsertTo/InsertTo.py
+++ b/InsertTo/InsertTo.py
@@ -4,6 +4,7 @@
from pathlib import Path
import adsk.core
+import adsk.fusion
from . import config, dialog, frame_link
@@ -11,9 +12,70 @@
_RESOURCES = Path(__file__).parent / 'resources'
_MENU_ID = '4FusionLab_InsertTo_SmartInsert'
_menu = None
-_definition = None
-_created = None
+_definitions = []
+_created = []
_sessions = []
+_context = None
+
+
+def _editing_sketch(app):
+ sketch = adsk.fusion.Sketch.cast(app.activeEditObject) if app.activeDocument else None
+ return bool(sketch and sketch.isValid)
+
+
+class _SketchContext:
+ """Refresh after Fusion finishes switching edit objects, and guard each launch immediately."""
+
+ event_id = _MENU_ID + '_UpdateContext'
+
+ def __init__(self, app):
+ self.app = app
+ self.listeners = []
+ self.pending = False
+ self.event = None
+
+ def start(self):
+ ui = self.app.userInterface
+ self.event = self.app.registerCustomEvent(self.event_id)
+ for event, base, callback in (
+ (self.event, adsk.core.CustomEventHandler, self.refresh),
+ (ui.commandStarting, adsk.core.ApplicationCommandEventHandler, self.starting),
+ (ui.commandCreated, adsk.core.ApplicationCommandEventHandler, self.schedule),
+ (ui.commandTerminated, adsk.core.ApplicationCommandEventHandler, self.schedule),
+ (ui.workspaceActivated, adsk.core.WorkspaceEventHandler, self.schedule),
+ (self.app.documentActivated, adsk.core.DocumentEventHandler, self.schedule),
+ (self.app.documentClosed, adsk.core.DocumentEventHandler, self.schedule),
+ ):
+ self.listeners.append((event, dialog._listen(event, base, callback)))
+ self.refresh()
+
+ def schedule(self, args):
+ if not self.pending:
+ self.pending = self.app.fireCustomEvent(self.event_id)
+
+ def starting(self, args):
+ if args.commandId in (config.COMMAND_ID, config.TRACE_COMMAND_ID):
+ if not _editing_sketch(self.app):
+ args.isCanceled = True
+
+ def refresh(self, args=None):
+ self.pending = False
+ editing = _editing_sketch(self.app)
+ if _menu.isVisible != editing:
+ _menu.isVisible = editing
+ for definition in _definitions:
+ control = definition.controlDefinition
+ if control.isEnabled != editing:
+ control.isEnabled = editing
+ if control.isVisible != editing:
+ control.isVisible = editing
+
+ def close(self):
+ for event, handler in reversed(self.listeners):
+ event.remove(handler)
+ self.listeners.clear()
+ if self.event:
+ self.app.unregisterCustomEvent(self.event_id)
class _Destroyed(adsk.core.CommandEventHandler):
@@ -25,9 +87,15 @@ def notify(self, args):
class _Created(adsk.core.CommandCreatedEventHandler):
+ def __init__(self, attach):
+ super().__init__()
+ self.attach = attach
+
def notify(self, args):
try:
- session = dialog.attach(args.command)
+ if not _editing_sketch(adsk.core.Application.get()):
+ return
+ session = self.attach(args.command)
destroyed = _Destroyed()
args.command.destroy.add(destroyed)
_sessions.append((session, destroyed))
@@ -38,11 +106,12 @@ def notify(self, args):
def run(context):
- global _menu, _created, _definition
+ global _menu, _context
if _menu and _menu.isValid:
return
- ui = adsk.core.Application.get().userInterface
+ app = adsk.core.Application.get()
+ ui = app.userInterface
workspace = ui.workspaces.itemById('FusionSolidEnvironment')
sketch_tab = workspace.toolbarTabs.itemById('SketchTab') if workspace else None
panel = sketch_tab.toolbarPanels.itemById('InsertPanel') if sketch_tab else None
@@ -50,31 +119,46 @@ def run(context):
raise RuntimeError('The sketch Insert panel is unavailable.')
try:
- _definition = ui.commandDefinitions.addButtonDefinition(
- config.COMMAND_ID, 'SVG', config.DESCRIPTION, str(_RESOURCES / 'svg')
- )
- _created = _Created()
- _definition.commandCreated.add(_created)
+ from . import trace_dialog
+
_menu = panel.controls.addDropDown(
'Smart Insert', str(_RESOURCES / 'smart-insert'), _MENU_ID, 'SketchImportSVG', False
)
- _menu.controls.addCommand(_definition)
- frame_link.install(adsk.core.Application.get())
+ for identifier, label, description, resources, attach in (
+ (config.COMMAND_ID, 'SVG', config.DESCRIPTION, str(_RESOURCES / 'svg'), dialog.attach),
+ (config.TRACE_COMMAND_ID, 'Trace Image', 'Trace a PNG or JPEG as closed sketch curves.',
+ '', trace_dialog.TraceDialog),
+ ):
+ definition = ui.commandDefinitions.addButtonDefinition(identifier, label, description, resources)
+ _definitions.append(definition)
+ created = _Created(attach)
+ _created.append(created)
+ definition.commandCreated.add(created)
+ _menu.controls.addCommand(definition)
+ _context = _SketchContext(app)
+ _context.start()
+ frame_link.install(app)
except Exception:
stop(context)
raise
def stop(context):
- global _menu, _created, _definition
+ global _menu, _context
try:
+ if _context is not None:
+ _context.close()
+ _context = None
frame_link.uninstall()
if _menu and _menu.isValid:
_menu.deleteMe()
- if _definition and _definition.isValid:
- _definition.deleteMe()
+ for definition in reversed(_definitions):
+ if definition.isValid:
+ definition.deleteMe()
finally:
- _menu = _created = _definition = None
+ _menu = None
+ _definitions.clear()
+ _created.clear()
for session, _ in _sessions:
session.close()
_sessions.clear()
diff --git a/InsertTo/config.py b/InsertTo/config.py
index b627092..b1ae8a4 100644
--- a/InsertTo/config.py
+++ b/InsertTo/config.py
@@ -4,4 +4,5 @@
DISPLAY_NAME = 'InsertTo'
DESCRIPTION = 'Place SVG curves on a sketch plane or fit them to a linked frame with accurate dimensions and live preview.'
COMMAND_ID = '4FusionLab_InsertTo_77ac0485344b'
+TRACE_COMMAND_ID = COMMAND_ID + '_TraceImage'
INITIALIZED = True
diff --git a/InsertTo/dialog.py b/InsertTo/dialog.py
index e3b7730..c9d3f0f 100644
--- a/InsertTo/dialog.py
+++ b/InsertTo/dialog.py
@@ -50,6 +50,11 @@ def notify(self, args):
class _Dialog:
+ file_id = 'svgFile'
+ file_label = 'SVG file'
+ file_prompt = 'Choose an SVG file.'
+ frame_tooltip = 'Select a profile or closed contour to fit the SVG to its frame.'
+
def __init__(self, command):
self.app = adsk.core.Application.get()
self.design = adsk.fusion.Design.cast(self.app.activeProduct)
@@ -63,7 +68,6 @@ def __init__(self, command):
self.source_curves = None
self.file_error = ''
self.preview_error = ''
-
self.graphics = None
self.graphics_key = None
self.graphics_pivot = None
@@ -72,7 +76,7 @@ def __init__(self, command):
command.isExecutedWhenPreEmpted = False
command.okButtonText = 'Insert'
inputs = command.commandInputs
- self.browse = inputs.addBoolValueInput('svgFile', 'SVG file', False, '', False)
+ self.browse = inputs.addBoolValueInput(self.file_id, self.file_label, False, '', False)
self.browse.text = 'Choose file…'
self.plane = inputs.addSelectionInput(
'targetPlane', 'Sketch plane', 'Select a construction plane or a planar face'
@@ -87,13 +91,8 @@ def __init__(self, command):
self.frame.addSelectionFilter('Profiles')
self.frame.addSelectionFilter('SketchCurves')
self.frame.setSelectionLimits(0, 0)
- self.frame.tooltip = 'Select a profile or closed contour to fit the SVG to its frame.'
- self.extent = inputs.addDropDownCommandInput(
- 'svgBounds', 'Use bounds of', adsk.core.DropDownStyles.TextListDropDownStyle
- )
- self.extent.listItems.add('SVG page', True)
- self.extent.listItems.add('Artwork', False)
- self.extent.tooltip = 'Artwork measures the imported paths and ignores empty margins in the SVG page.'
+ self.frame.tooltip = self.frame_tooltip
+ self._source_options(inputs)
self.scaling = _icon_list(inputs, 'scale', 'Fit to frame', _MODES, 'fit')
self.anchor = _icon_list(inputs, 'anchor', 'Align from', _ANCHORS, 'center')
self.fit_x = _icon_list(inputs, 'fitAlignX', 'Align', _ALIGN_HORIZONTAL, 'center')
@@ -105,8 +104,7 @@ def __init__(self, command):
)
self.inset.minimumValue = 0
self.inset.tooltip = 'Apply an equal margin inside all four sides of the frame.'
- self.link = inputs.addBoolValueInput('linkFrame', 'Link to frame', True, '', True)
- self.link.tooltip = 'Update the inserted curves when the source frame changes.'
+ self.link = self._link_option(inputs)
if self.link is None:
self.transform = TransformControls(inputs, units)
self.sizes = None
@@ -120,7 +118,7 @@ def __init__(self, command):
self.status.isFullWidth = True
self._show_target_controls()
self._show_alignment(None)
- self._status('Choose an SVG file.')
+ self._status(self.file_prompt)
self.handlers = [
_listen(command.inputChanged, adsk.core.InputChangedEventHandler, self._changed),
_listen(command.validateInputs, adsk.core.ValidateInputsEventHandler, self._validate),
@@ -141,6 +139,19 @@ def __init__(self, command):
_listen(command.destroy, adsk.core.CommandEventHandler, self._release_triad_event),
))
+ def _source_options(self, inputs):
+ self.extent = inputs.addDropDownCommandInput(
+ 'svgBounds', 'Use bounds of', adsk.core.DropDownStyles.TextListDropDownStyle
+ )
+ self.extent.listItems.add('SVG page', True)
+ self.extent.listItems.add('Artwork', False)
+ self.extent.tooltip = 'Artwork measures the imported paths and ignores empty margins in the SVG page.'
+
+ def _link_option(self, inputs):
+ link = inputs.addBoolValueInput('linkFrame', 'Link to frame', True, '', True)
+ link.tooltip = 'Update the inserted curves when the source frame changes.'
+ return link
+
def _status(self, message):
if self.status.text != message:
self.status.text = message
@@ -175,14 +186,14 @@ def _changed(self, args):
if self._mode() == 'original' and self.sizes.changed(changed):
self._move_graphics()
return
- if changed not in ('svgFile', 'frame', 'targetPlane', 'scale', 'anchor',
+ if changed not in (self.file_id, 'frame', 'targetPlane', 'scale', 'anchor',
'fitAlignX', 'fitAlignY', 'svgBounds', 'frameInset', 'linkFrame'):
if self.transform.handles(changed):
self.preview_error = ''
if self.transform.changed(changed):
self._move_graphics()
return
- if changed == 'svgFile' and not self._choose_file():
+ if changed == self.file_id and not self._choose_file():
return
if changed in ('frame', 'targetPlane'):
self.bounds = None
@@ -256,7 +267,8 @@ def _show_target_controls(self):
_show(self.frame, self.sketch is not None or not has_plane or has_frame)
_show(self.scaling, has_frame)
_show(self.inset, has_frame)
- _show(self.link, has_frame and self._mode() in ('fit', 'stretch'))
+ if self.link is not None:
+ _show(self.link, has_frame and self._mode() in ('fit', 'stretch'))
if self.sizes is not None:
original = self._mode() == 'original'
self.sizes.set_visible(original)
@@ -269,9 +281,9 @@ def _show_alignment(self, fit_options):
def _destination(self):
if self.document is None:
- raise ValueError(self.file_error or 'Choose an SVG file.')
+ raise ValueError(self.file_error or self.file_prompt)
if not self.design or not self.design.isValid or self.app.activeDocument != self.owner_document:
- raise ValueError('Open a Fusion design to insert an SVG.')
+ raise ValueError('Open a Fusion design to insert sketch curves.')
if self.sketch and (not self.sketch.isValid or self.app.activeEditObject != self.sketch):
raise ValueError('The destination sketch is no longer being edited.')
if self.sizes is not None:
@@ -296,7 +308,7 @@ def _use_artwork(self):
return self.extent.selectedItem.index == 1
def _needs_artwork_bounds(self):
- return self._use_artwork() or not self.frame.selectionCount
+ return self._use_artwork() or (self.file_id == 'svgFile' and not self.frame.selectionCount)
def _placements(self):
frame = self.bounds if self.frame.selectionCount else None
diff --git a/InsertTo/frame_link.py b/InsertTo/frame_link.py
index 3a921da..93f9c86 100644
--- a/InsertTo/frame_link.py
+++ b/InsertTo/frame_link.py
@@ -99,7 +99,7 @@ class _RestoreFailed(RuntimeError):
@contextmanager
-def _batch_edit(sketch):
+def batch_edit(sketch):
"""Solve once while keeping downstream features out of the deferred edit."""
if sketch.isComputeDeferred:
yield
@@ -136,7 +136,7 @@ def _batch_edit(sketch):
try:
sketch.isComputeDeferred = False
except Exception as error:
- raise _RestoreFailed('Fusion could not recompute the linked sketch.') from error
+ raise _RestoreFailed('Fusion could not recompute the sketch.') from error
finally:
if moved and timeline.markerPosition != marker:
try:
@@ -157,7 +157,7 @@ def insert(sketch, doc, target, frame_entities, mode, anchor, *, bounds=None, in
matrix = _matrix(svg_geometry.Placement(0, 0, doc.width_mm, doc.height_mm), target)
link_id = uuid4().hex
added = []
- with _batch_edit(sketch):
+ with batch_edit(sketch):
splines = sketch.sketchCurves.sketchFixedSplines
index_attr = None
try:
@@ -253,7 +253,7 @@ def _refresh(attr, record, target, curves):
raise ValueError('Fusion could not transform a linked curve.')
edits.append((curve, original, updated))
- with _batch_edit(attr.parent):
+ with batch_edit(attr.parent):
applied = []
try:
for curve, original, updated in edits:
diff --git a/InsertTo/image_decode.py b/InsertTo/image_decode.py
new file mode 100644
index 0000000..2f4dad2
--- /dev/null
+++ b/InsertTo/image_decode.py
@@ -0,0 +1,164 @@
+"""Decode the first PNG/JPEG frame using the host system's image codecs."""
+
+import ctypes
+from dataclasses import dataclass
+import os
+from pathlib import Path
+import shutil
+import struct
+import subprocess
+import sys
+
+
+@dataclass(frozen=True)
+class Raster:
+ width: int
+ height: int
+ rgba: bytes
+ has_alpha: bool
+
+
+_JPEG_START_OF_FRAME = frozenset((0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7,
+ 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF))
+
+
+def _dimensions(stream, extension):
+ if extension == '.png':
+ header = stream.read(24)
+ if len(header) == 24 and header[:16] == b'\x89PNG\r\n\x1a\n\x00\x00\x00\x0dIHDR':
+ return struct.unpack('>II', header[16:])
+ elif stream.read(2) == b'\xff\xd8':
+ while stream.read(1) == b'\xff':
+ marker = stream.read(1)
+ while marker == b'\xff':
+ marker = stream.read(1)
+ length = stream.read(2)
+ if len(length) != 2 or marker in (b'\xda', b'\xd9'):
+ break
+ size = int.from_bytes(length, 'big')
+ if size < 2:
+ break
+ if marker and marker[0] in _JPEG_START_OF_FRAME:
+ frame = stream.read(5)
+ if len(frame) == 5:
+ height, width = struct.unpack('>HH', frame[1:])
+ return width, height
+ break
+ stream.seek(size - 2, os.SEEK_CUR)
+ raise ValueError('The selected file is not a valid PNG or JPEG image.')
+
+
+def _mac_rgba(path, width, height):
+ # Core Graphics uses lazy decoding and manages indexed, grayscale and CMYK input.
+ cg = ctypes.CDLL('/System/Library/Frameworks/CoreGraphics.framework/CoreGraphics')
+ ptr, size = ctypes.c_void_p, ctypes.c_size_t
+
+ class Rect(ctypes.Structure):
+ _fields_ = [(name, ctypes.c_double) for name in ('x', 'y', 'width', 'height')]
+
+ def bind(name, result, *arguments):
+ function = getattr(cg, name)
+ function.restype, function.argtypes = result, arguments
+ return function
+
+ releases = []
+
+ def own(value, release):
+ if not value:
+ raise ValueError('macOS could not decode the selected image.')
+ releases.append((bind(release, None, ptr), value))
+ return value
+
+ try:
+ provider = own(bind('CGDataProviderCreateWithFilename', ptr, ctypes.c_char_p)(
+ os.fsencode(path)), 'CGDataProviderRelease')
+ codec = 'PNG' if path.suffix.lower() == '.png' else 'JPEG'
+ create = bind('CGImageCreateWith' + codec + 'DataProvider', ptr, ptr, ptr,
+ ctypes.c_bool, ctypes.c_int)
+ image = own(create(provider, None, False, 0), 'CGImageRelease')
+ if (bind('CGImageGetWidth', size, ptr)(image),
+ bind('CGImageGetHeight', size, ptr)(image)) != (width, height):
+ raise ValueError('Image dimensions changed during decoding.')
+ color_space = own(bind('CGColorSpaceCreateDeviceRGB', ptr)(), 'CGColorSpaceRelease')
+ pixels = bytearray(width * height * 4)
+ buf = (ctypes.c_ubyte * len(pixels)).from_buffer(pixels)
+ # kCGBitmapByteOrder32Big | kCGImageAlphaPremultipliedLast => RGBA bytes.
+ context = own(bind('CGBitmapContextCreate', ptr, ptr, size, size, size, size, ptr,
+ ctypes.c_uint)(buf, width, height, 8, 4 * width, color_space,
+ 0x4001), 'CGContextRelease')
+ bind('CGContextDrawImage', None, ptr, Rect, ptr)(context, Rect(0, 0, width, height), image)
+ for i, alpha in enumerate(pixels[3::4]):
+ if 0 < alpha < 255:
+ for j in range(4 * i, 4 * i + 3):
+ pixels[j] = min(255, (pixels[j] * 255 + alpha // 2) // alpha)
+ return bytes(pixels)
+ finally:
+ for release, value in reversed(releases):
+ release(value)
+
+
+_WINDOWS_DECODE = """
+$ErrorActionPreference = 'Stop'
+Add-Type -AssemblyName PresentationCore
+$file = [IO.File]::OpenRead($env:INSERTTO_IMAGE_PATH)
+try {
+ $decoder = [Windows.Media.Imaging.BitmapDecoder]::Create($file, 'PreservePixelFormat', 'OnLoad')
+ $frame = $decoder.Frames[0]
+ $bitmap = New-Object Windows.Media.Imaging.FormatConvertedBitmap
+ $bitmap.BeginInit()
+ $bitmap.Source = $frame
+ $bitmap.DestinationFormat = [Windows.Media.PixelFormats]::Bgra32
+ $bitmap.EndInit()
+ $stride = 4 * $bitmap.PixelWidth
+ $pixels = New-Object byte[] ($stride * $bitmap.PixelHeight)
+ $bitmap.CopyPixels($pixels, $stride, 0)
+ [Console]::OpenStandardOutput().Write($pixels, 0, $pixels.Length)
+} finally { $file.Dispose() }
+"""
+
+
+def _windows_rgba(path):
+ command = Path(os.environ['SystemRoot'], 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe')
+ result = subprocess.run([str(command), '-NoProfile', '-NonInteractive', '-Command', _WINDOWS_DECODE],
+ env=dict(os.environ, INSERTTO_IMAGE_PATH=str(path)),
+ capture_output=True, check=True, creationflags=subprocess.CREATE_NO_WINDOW)
+ data = bytearray(result.stdout)
+ data[0::4], data[2::4] = data[2::4], data[0::4]
+ return bytes(data)
+
+
+def _offline_rgba(path):
+ # Fusion supports macOS/Windows. Also support ordinary Linux CI runners.
+ try:
+ from PIL import Image
+ except ImportError:
+ converter = shutil.which('magick') or shutil.which('convert')
+ if not converter:
+ raise ValueError('Install Pillow or ImageMagick to decode images on Linux.')
+ return subprocess.run([converter, str(path) + '[0]', '-colorspace', 'sRGB', '-alpha',
+ 'on', '-depth', '8', 'rgba:-'], check=True, capture_output=True).stdout
+ with Image.open(path) as image:
+ return image.convert('RGBA').tobytes()
+
+
+def load_image(path):
+ path = Path(path).resolve()
+ extension = path.suffix.lower()
+ if extension not in ('.png', '.jpeg', '.jpg'):
+ raise ValueError('Select a PNG or JPEG file.')
+ with path.open('rb') as stream:
+ width, height = _dimensions(stream, extension)
+ if min(width, height) <= 0 or width * height > 16_777_216:
+ raise ValueError('Trace Image supports images up to 16 megapixels.')
+ try:
+ if sys.platform == 'darwin':
+ pixels = _mac_rgba(path, width, height)
+ elif sys.platform == 'win32':
+ pixels = _windows_rgba(path)
+ else:
+ pixels = _offline_rgba(path)
+ except (OSError, subprocess.SubprocessError) as error:
+ raise ValueError('Could not decode the selected image.') from error
+ if len(pixels) != width * height * 4:
+ raise ValueError('Incomplete image data.')
+ return Raster(width, height, pixels, extension == '.png' and min(pixels[3::4]) < 255)
diff --git a/InsertTo/image_trace.py b/InsertTo/image_trace.py
new file mode 100644
index 0000000..85da622
--- /dev/null
+++ b/InsertTo/image_trace.py
@@ -0,0 +1,795 @@
+"""Trace foreground pixel cells into closed, oriented sketch polygons.
+
+Vertices use image coordinates (pixel corners, Y down). Positive rings are
+islands, negative rings are holes. The analysis is independent of placement.
+"""
+
+from array import array
+from bisect import bisect_left, bisect_right
+from collections import Counter, defaultdict
+from dataclasses import dataclass, field
+from functools import cached_property
+import heapq
+import math
+import re
+
+from .image_decode import Raster, load_image
+
+
+@dataclass(frozen=True)
+class Analysis:
+ # Each component contains one outer boundary followed by its holes.
+ components: tuple
+ preserve_corners: bool = True
+ # Keep a reference to the existing raster, without copying its alpha plane.
+ alpha_field: tuple = field(default=(), compare=False, repr=False)
+
+ photo: bool = False
+
+ @cached_property
+ def _alpha_boundaries(self):
+ raster, level = self.alpha_field
+ references = {}
+ # Work scales with selected boundaries, not empty image area. Budget
+ # and cache belong to this mask/selection, independently of placement.
+ candidates = []
+ edges = 0
+ for group in self.components:
+ for ring in group:
+ if len(ring) < 16 or any(x in (0, raster.width) or y in (0, raster.height) for x, y in ring):
+ continue
+ count = sum(abs(x - u) + abs(y - v) for (x, y), (u, v) in zip(ring, ring[1:] + ring[:1]))
+ if count > 250_000:
+ continue
+ edges += count
+ if edges > 250_000:
+ return {}
+ candidates.append((ring, count))
+ for ring, count in candidates:
+ reference = _alpha_outline(raster, level, ring, count)
+ if reference is not None:
+ references[id(ring)] = reference
+ return references
+
+ def alpha_measurements(self, ring):
+ """Ordered alpha crossings, including the correspondence to mask edges."""
+ return self._alpha_boundaries.get(id(ring)) if self.alpha_field else None
+
+ def primitive_reference(self, ring):
+ """Raw mask ring, or its measured alpha-level outline when supported."""
+ boundary = self.alpha_measurements(ring)
+ return boundary.outline if boundary is not None else ring
+
+ def ellipse_reference(self, ring):
+ return self.primitive_reference(ring)
+
+
+@dataclass(frozen=True)
+class AlphaBoundary:
+ outline: tuple
+ # One crossing per original directed unit edge, in original walk order.
+ # This permits a local arc to attach to unchanged legacy sketch vertices.
+ crossings: tuple
+
+
+@dataclass(frozen=True)
+class TraceResult:
+ rings: tuple
+ paths: tuple = ()
+ sx: float = 1.0
+ sy: float = 1.0
+ tolerance_mm: float = 0.0
+
+ @cached_property
+ def curve_count(self):
+ return sum(map(len, self.paths or self.rings))
+
+ @cached_property
+ def type_counts(self):
+ if not self.paths:
+ return self.curve_count, 0, 0, 0
+ from .trace_primitives import Arc, Circle, Ellipse, Line
+ counts = Counter(type(curve) for path in self.paths for curve in path)
+ return counts[Line], counts[Arc], counts[Circle], counts[Ellipse]
+
+
+@dataclass(frozen=True)
+class ArtworkDefaults:
+ is_artwork: bool
+ mode: str
+ threshold: int
+
+
+def artwork_defaults(raster):
+ """Estimate the paper and ink on a bounded sample of the whole sheet."""
+ if raster.has_alpha:
+ return ArtworkDefaults(True, 'alpha', 128)
+ width, height = raster.width, raster.height
+ xs = range(0, width, max(1, (width + 159) // 160))
+ ys = range(0, height, max(1, (height + 159) // 160))
+
+ def pixel(x, y):
+ offset = (y * width + x) * 4
+ return raster.rgba[offset:offset + 3]
+
+ border = [pixel(x, y) for x in xs for y in (0, height - 1)]
+ border.extend(pixel(x, y) for y in ys for x in (0, width - 1))
+ red, green, blue = (sorted(channel)[len(border) // 2] for channel in zip(*border))
+
+ def is_paper(r, g, b):
+ # Allow JPEG variation and small changes in the color of scanned paper.
+ return max(abs(r - red), abs(g - green), abs(b - blue)) <= 12
+
+ flat_edge = sum(is_paper(*rgb) for rgb in border) >= .78 * len(border)
+ histogram = [0] * 256
+ paper_samples = 0
+ for y in ys:
+ for x in xs:
+ r, g, b = pixel(x, y)
+ histogram[(54 * r + 183 * g + 19 * b + 128) // 256] += 1
+ paper_samples += is_paper(r, g, b)
+ flat_sheet = flat_edge and paper_samples >= .32 * len(xs) * len(ys)
+ paper = (54 * red + 183 * green + 19 * blue + 128) // 256
+ # Compare departures from the measured paper. This also handles light
+ # markings on mid-gray paper and dark markings on a colored sheet.
+ dark = sum((paper - i) * histogram[i] for i in range(max(0, paper - 5)))
+ light = sum((i - paper) * histogram[i] for i in range(min(256, paper + 6), 256))
+ light_ink = (paper < 128) if dark == light else light > dark
+ if not flat_sheet:
+ return ArtworkDefaults(False, 'light' if light_ink else 'dark', 128)
+ # The median ink tone is insensitive to metallic gradients. Bias toward
+ # paper to preserve antialiased fine lettering without including its noise.
+ tones = (range(paper + 6, 256) if light_ink else range(paper - 6, -1, -1))
+ count = sum(histogram[i] for i in tones)
+ ink = 255 if light_ink else 0
+ cumulative = 0
+ for tone in tones:
+ cumulative += histogram[tone]
+ if cumulative * 2 >= count and count:
+ ink = tone
+ break
+ threshold = round(paper + (ink - paper) / 3)
+ if not light_ink:
+ # Light ink uses ">" and dark ink uses "<=" on integer intensities.
+ threshold = max(0, threshold - 1)
+ return ArtworkDefaults(True, 'light' if light_ink else 'dark', threshold)
+
+
+def artwork_mode(raster):
+ return artwork_defaults(raster).mode
+
+
+def is_artwork(raster):
+ return artwork_defaults(raster).is_artwork
+
+
+def artwork_threshold(raster):
+ return artwork_defaults(raster).threshold
+
+
+def ink_cutoff(base, coverage, light):
+ """Map the center detent to the measured threshold, in either polarity."""
+ position = (100 - coverage if light else coverage) / 50
+ if position <= 1:
+ return round(base * position)
+ return round(base + (255 - base) * (position - 1))
+
+
+def _binary_mask(raster, mode, threshold, invert):
+ data = raster.rgba
+ if mode == 'alpha':
+ if not raster.has_alpha:
+ raise ValueError('This image has no transparency.')
+ table = bytes(int((value > 0 and value >= threshold) != invert) for value in range(256))
+ return data[3::4].translate(table)
+ if mode != 'luminance':
+ raise ValueError('Unknown image trace mode.')
+ # Compare visible brightness against white, including partial transparency.
+ limit = threshold * 255
+ return bytes(int(((54 * r + 183 * g + 19 * b + 128) // 256 * a +
+ 255 * (255 - a) <= limit) != invert)
+ for r, g, b, a in zip(data[::4], data[1::4], data[2::4], data[3::4]))
+
+
+def _walk(mask, visited, stride, index, direction, corner_budget):
+ """Walk with foreground on the right, separating diagonal islands."""
+ steps = (1, stride, -1, -stride)
+ offsets = ((0, 0), (1, 0), (1, 1), (0, 1))
+ start = index, direction
+ corners = []
+ while True:
+ visited[index] |= 1 << direction
+ ahead = index + steps[direction]
+ diagonal = ahead + steps[(direction - 1) % 4]
+ if not mask[ahead]:
+ turn, next_index = 1, index
+ elif mask[diagonal]:
+ turn, next_index = -1, diagonal
+ else:
+ turn, next_index = 0, ahead
+ if turn:
+ if len(corners) >= corner_budget:
+ raise ValueError('Image has too many edges. Try a smaller image.')
+ y, x = divmod(index, stride)
+ dx, dy = offsets[(direction + 1) % 4]
+ corners.append((x - 1 + dx, y - 1 + dy))
+ direction = (direction + turn) % 4
+ index = next_index
+ if (index, direction) == start:
+ return corners
+
+
+def _simple_rings(corners):
+ # A one-pixel neck can make a walk visit a corner twice. Extract both
+ # cycles there so Fusion never receives a self-touching polygon.
+ path, seen = [], {}
+ for vertex in (*corners, corners[0]):
+ index = seen.get(vertex)
+ if index is None:
+ seen[vertex] = len(path)
+ path.append(vertex)
+ else:
+ yield tuple(path[index:])
+ for removed in path[index + 1:]:
+ del seen[removed]
+ del path[index + 1:]
+
+
+def _area(ring):
+ return sum(a[0] * b[1] - a[1] * b[0] for a, b in zip(ring, ring[1:] + ring[:1])) / 2
+
+
+def _contains(ring, x, y):
+ # Input boundaries are axis-aligned. The sample is off the pixel grid.
+ return sum(a[0] > x and (a[1] > y) != (b[1] > y)
+ for a, b in zip(ring, ring[1:] + ring[:1])) % 2
+
+
+def _group_rings(rings):
+ islands, holes = [], []
+ for ring in rings:
+ area = _area(ring)
+ if area > 0:
+ xs, ys = zip(*ring)
+ islands.append((area, (min(xs), min(ys), max(xs), max(ys)), [ring]))
+ else:
+ holes.append(ring)
+ # Bucket island bounds at their own scale. A speck and a page-sized
+ # outline each occupy at most four buckets, even in a very noisy scan.
+ if not holes:
+ return tuple(tuple(group) for _, _, group in islands)
+ buckets = defaultdict(list)
+ scales = set()
+ for island in islands:
+ left, top, right, bottom = island[1]
+ scale = (max(bottom - top, right - left) - 1).bit_length()
+ scales.add(scale)
+ for row in range(top >> scale, ((bottom - 1) >> scale) + 1):
+ for col in range(left >> scale, ((right - 1) >> scale) + 1):
+ buckets[scale, col, row].append(island)
+ for hole in holes:
+ (x1, y1), (x2, y2) = hole[:2]
+ # A quarter pixel to the right of any directed boundary is foreground.
+ x = (x1 + x2) / 2 - .25 * ((y2 > y1) - (y2 < y1))
+ y = (y1 + y2) / 2 + .25 * ((x2 > x1) - (x2 < x1))
+ candidates = [island for scale in scales for island in
+ buckets.get((scale, int(x) >> scale, int(y) >> scale), ())]
+ for _, (left, top, right, bottom), group in sorted(candidates, key=lambda item: item[0]):
+ if left < x < right and top < y < bottom and _contains(group[0], x, y):
+ group.append(hole)
+ break
+ else:
+ raise ValueError('Could not resolve a hole in the image.')
+ return tuple(tuple(group) for _, _, group in islands)
+
+
+def _photo_color(r, g, b, alpha):
+ # Compare brightness and two color differences independently. A brown
+ # subject can have the same brightness as a green or gray background.
+ if alpha != 255:
+ r, g, b = (255 - (255 - value) * alpha // 255 for value in (r, g, b))
+ return (r + 2 * g + b) // 32, (r - g + 2) // 4, (g - b + 2) // 4
+
+
+def _photo_mask(raster, xs, ys, threshold):
+ data = raster.rgba
+
+ def color(x, y):
+ i = 4 * (y * raster.width + x)
+ return _photo_color(*data[i:i + 4])
+
+ # The border is a sample of the scene behind the subject. Keep its
+ # frequent colors rather than treating a single corner as representative.
+ border = Counter(color(x, y) for x in xs for y in (ys[0], ys[-1]))
+ border.update(color(x, y) for y in ys for x in (xs[0], xs[-1]))
+ radius = 1 + 4 * (255 - threshold) / 255
+ reach = int(radius)
+ neighbors = [(i, j, k) for i in range(-reach, reach + 1)
+ for j in range(-reach, reach + 1) for k in range(-reach, reach + 1)
+ if i * i + j * j + k * k <= radius * radius]
+ background = set()
+ palette = border.most_common(96)
+ min_count = min(palette[0][1], max(1, (len(xs) + len(ys)) // 600))
+ for (light, rg, gb), count in palette:
+ if count < min_count:
+ break
+ background.update((light + i, rg + j, gb + k) for i, j, k in neighbors)
+ return bytes(color(x, y) not in background for y in ys for x in xs)
+
+
+def _region_mask(raster, xs, ys, seed, threshold):
+ """Grow from the pick using its color and contrast against nearby scenery."""
+ width, height = len(xs), len(ys)
+ stride = width + 1
+ # Summed luminance lets a point near a branch be compared with its own
+ # surroundings even when the illumination changes along the tree.
+ sums = array('I', [0]) * (stride * (height + 1))
+ colors = bytearray(width * height * 3)
+ for row, y in enumerate(ys):
+ total = 0
+ for col, x in enumerate(xs):
+ src = (y * raster.width + x) * 4
+ r, g, b, a = raster.rgba[src:src + 4]
+ if a != 255:
+ r, g, b = (255 - (255 - v) * a // 255 for v in (r, g, b))
+ index = row * width + col
+ colors[3 * index] = r
+ colors[3 * index + 1] = g
+ colors[3 * index + 2] = b
+ total += (r + 2 * g + b) // 4
+ dest = (row + 1) * stride + col + 1
+ sums[dest] = sums[dest - stride] + total
+
+ def mean(x, y, radius):
+ left, right = max(0, x - radius), min(width, x + radius + 1)
+ top, bottom = max(0, y - radius), min(height, y + radius + 1)
+ value = (sums[bottom * stride + right] - sums[top * stride + right]
+ - sums[bottom * stride + left] + sums[top * stride + left])
+ return value / ((right - left) * (bottom - top))
+
+ sx, sy = seed
+ denoise = min(2, max(width, height) // 400)
+ surround = max(3, max(width, height) // 24)
+ light = mean(sx, sy, denoise)
+ local_contrast = light - mean(sx, sy, surround)
+ pick = 3 * (sy * width + sx)
+ r, g, b = colors[pick:pick + 3]
+ rg, gb = r - g, g - b
+ # Discard weak contrast as a cue when the pick is deep inside a flat
+ # subject. A clearly darker/lighter pick must stay on that side of its
+ # local background to avoid flooding a similarly colored distant object.
+ polarity = 0 if abs(local_contrast) <= 7 else math.copysign(1, local_contrast)
+ reach = threshold / 255
+ minimum_contrast = min(14, abs(local_contrast) * .45) * (1.45 - reach)
+ brightness_range = 6 + 56 * reach
+ color_range = 5 + 32 * reach
+ mask = bytearray(width * height)
+ visited = bytearray(len(mask))
+ first = sy * width + sx
+ pending = [first]
+ visited[first] = 1
+ while pending:
+ index = pending.pop()
+ y, x = divmod(index, width)
+ value = mean(x, y, denoise)
+ r, g, b = colors[3 * index:3 * index + 3]
+ if (abs(value - light) > brightness_range or
+ max(abs(r - g - rg), abs(g - b - gb)) > color_range):
+ continue
+ if polarity and polarity * (value - mean(x, y, surround)) < minimum_contrast:
+ continue
+ mask[index] = 1
+ for neighbor in (index - width, index + width, index - 1 if x else -1,
+ index + 1 if x + 1 < width else -1):
+ if 0 <= neighbor < len(mask) and not visited[neighbor]:
+ visited[neighbor] = 1
+ pending.append(neighbor)
+ return mask
+
+
+def _largest_photo_outline(mask, width, height):
+ # Flood each connected foreground component by horizontal runs. Remember
+ # only the winning seed, then follow its outer edge on the original mask.
+ stride = width + 2
+ padded = bytearray(stride * (height + 2))
+ for y in range(height):
+ offset = (y + 1) * stride + 1
+ padded[offset:offset + width] = mask[y * width:(y + 1) * width]
+ remaining = padded.copy()
+ best_size, best_seed = 0, None
+ seed = remaining.find(b'\x01')
+ while seed >= 0:
+ pending, size = [seed], 0
+ while pending:
+ index = pending.pop()
+ if not remaining[index]:
+ continue
+ left = remaining.rfind(b'\x00', 0, index) + 1
+ right = remaining.find(b'\x00', index)
+ remaining[left:right] = bytes(right - left)
+ size += right - left
+ for shift in (-stride, stride):
+ end = right + shift
+ start = remaining.find(b'\x01', left + shift, end)
+ while start >= 0:
+ pending.append(start)
+ gap = remaining.find(b'\x00', start, end)
+ if gap < 0:
+ break
+ start = remaining.find(b'\x01', gap, end)
+ if size > best_size:
+ best_size, best_seed = size, seed
+ seed = remaining.find(b'\x01', seed + 1)
+ if best_seed is None:
+ return ()
+ path = _walk(padded, bytearray(len(padded)), stride, best_seed, 3, 500_000)
+ return max(_simple_rings(path), key=_area)
+
+
+def _photo_silhouette(raster, threshold, seed):
+ # Bound photo preview work even for a 16 MP source. Sample pixel centers
+ # and map contour corners back to the original image's coordinate system.
+ scale = min(1., 1024 / max(raster.width, raster.height))
+ width, height = (max(1, round(length * scale)) for length in (raster.width, raster.height))
+ xs = [int((x + .5) * raster.width / width) for x in range(width)]
+ ys = [int((y + .5) * raster.height / height) for y in range(height)]
+ if seed is None:
+ mask = _photo_mask(raster, xs, ys, threshold)
+ ring = _largest_photo_outline(mask, width, height)
+ groups = ((ring,),) if ring else ()
+ else:
+ x, y = seed
+ if not (0 <= x < raster.width and 0 <= y < raster.height):
+ raise ValueError('Choose a point inside the image.')
+ sample = int(x * width / raster.width), int(y * height / raster.height)
+ mask = _region_mask(raster, xs, ys, sample, threshold)
+ # Keep openings between branches. Suppress isolated holes created by
+ # sensor noise at the sampling resolution.
+ if 0 not in mask:
+ return Analysis((), preserve_corners=False, photo=True)
+ min_hole = max(3, round(sum(mask) * .001))
+ groups = [(outer, *(hole for hole in holes if -_area(hole) >= min_hole))
+ for outer, *holes in _mask_components(mask, width, height)]
+
+ def original_pixels(ring):
+ return tuple((round(x * raster.width / width), round(y * raster.height / height))
+ for x, y in ring)
+
+ return Analysis(tuple(tuple(map(original_pixels, group)) for group in groups),
+ preserve_corners=False, photo=True)
+
+
+def _select_ink_group(groups, seed):
+ if not groups:
+ return ()
+ if seed is None:
+ return (max(groups, key=lambda group: sum(map(_area, group))),)
+ # Test the original pixel cell before interpolating its threshold crossings.
+ # This leaves picks in a counter (for example, the middle of O) empty.
+ x, y = (int(value) + .5 for value in seed)
+ for group in groups:
+ if _contains(group[0], x, y) and not any(_contains(hole, x, y) for hole in group[1:]):
+ return (group,)
+ return ()
+
+
+def _threshold_crossings(ring, width, height, data, stride, channel, level):
+ """Walk measurements on dual-grid edges, in the mask boundary's order."""
+ for (x, y), (end_x, end_y) in zip(ring, ring[1:] + ring[:1]):
+ dx, dy = (end_x > x) - (end_x < x), (end_y > y) - (end_y < y)
+ while (x, y) != (end_x, end_y):
+ first = second = 0
+ if dx:
+ col = min(x, x + dx)
+ py = y
+ if 0 < y < height:
+ i = (y * width + col) * stride + channel
+ first, second = data[i - width * stride], data[i]
+ py = y - .5 + (level - first) / (second - first)
+ point = (col + .5, py)
+ else:
+ row = min(y, y + dy)
+ px = x
+ if 0 < x < width:
+ i = (row * width + x) * stride + channel
+ first, second = data[i - stride], data[i]
+ px = x - .5 + (level - first) / (second - first)
+ point = (px, row + .5)
+ yield point, first, second
+ x, y = x + dx, y + dy
+
+
+def _append_crossing(points, point):
+ if len(points) >= 2 and abs(_cross(points[-2], points[-1], point)) < 1e-10:
+ points.pop()
+ points.append(point)
+
+
+def _crossing_outline(crossings):
+ points = []
+ for point, _, _ in crossings:
+ _append_crossing(points, point)
+ return tuple(points)
+
+
+def _alpha_outline(raster, level, ring, count):
+ width, data = raster.width, raster.rgba
+ # Alternating quadrants around a grid vertex form a saddle. Its alpha
+ # interpolation need not have the same connectivity as four-connected ink.
+ for x, y in ring:
+ i = 4 * (y * width + x) + 3
+ nw, ne = data[i - 4*width - 4] > level, data[i - 4*width] > level
+ sw, se = data[i - 4] > level, data[i] > level
+ if nw == se and ne == sw and nw != ne:
+ return None
+
+ points, measurements, levels, sectors = [], [], set(), set()
+ supported = 0
+ crossings = _threshold_crossings(ring, width, raster.height, data, 4, 3, level)
+ for index, (point, first, second) in enumerate(crossings):
+ soft = False
+ for value in (first, second):
+ if 8 <= value <= 247:
+ levels.add(value)
+ soft = True
+ if soft:
+ supported += 1
+ sectors.add(8 * index // count)
+ measurements.append(point)
+ _append_crossing(points, point)
+ # A two-level translucent mask or a few stray pixels add no reliable edge
+ # positions. Require several tones distributed around this particular ring.
+ if len(levels) < 3 or supported < max(12, count // 3) or len(sectors) < 6:
+ return None
+ if len(points) < 3 or _area(points) * _area(ring) <= 0:
+ return None
+ return AlphaBoundary(tuple(points), tuple(measurements))
+
+
+def _ink_boundaries(raster, threshold, invert, single_object=False, seed=None):
+ """Place ink outlines at the threshold crossing between antialiased pixels."""
+ data = raster.rgba
+ light = bytes((54 * r + 183 * g + 19 * b + 128) // 256
+ for r, g, b in zip(data[::4], data[1::4], data[2::4]))
+ if raster.has_alpha:
+ light = bytes((value * a + 255 * (255 - a) + 254) // 255
+ for value, a in zip(light, data[3::4]))
+ mask = light.translate(bytes(int((v <= threshold) != invert) for v in range(256)))
+ width, height = raster.width, raster.height
+ if single_object and 0 not in mask:
+ return Analysis((), preserve_corners=False)
+ groups = _mask_components(mask, width, height)
+ if single_object:
+ groups = _select_ink_group(groups, seed)
+
+ def smooth(ring):
+ crossings = _threshold_crossings(ring, width, height, light, 1, 0, threshold + .5)
+ return _crossing_outline(crossings)
+
+ edge_count = sum(abs(x - u) + abs(y - v) for group in groups for ring in group
+ for (x, y), (u, v) in zip(ring, ring[1:] + ring[:1]))
+ if edge_count <= 500_000:
+ groups = tuple(tuple(map(smooth, group)) for group in groups)
+ return Analysis(groups, preserve_corners=False)
+
+
+def analyze(raster, mode='alpha', threshold=128, invert=False, seed=None):
+ if not isinstance(threshold, int) or not 0 <= threshold <= 255:
+ raise ValueError('Threshold must be an integer from 0 to 255.')
+ width, height = raster.width, raster.height
+ if min(width, height) <= 0 or len(raster.rgba) != 4 * width * height:
+ raise ValueError('Incomplete image data.')
+ single_object = mode in ('ink_object', 'alpha_object')
+ if single_object and seed is not None and not (0 <= seed[0] < width and 0 <= seed[1] < height):
+ raise ValueError('Choose a point inside the image.')
+ if mode in ('ink', 'ink_object'):
+ return _ink_boundaries(raster, threshold, invert, single_object, seed)
+ if mode == 'silhouette':
+ return _photo_silhouette(raster, threshold, seed)
+ binary = _binary_mask(raster, 'alpha' if mode == 'alpha_object' else mode, threshold, invert)
+ groups = _mask_components(binary, width, height)
+ if single_object:
+ groups = _select_ink_group(groups, seed) if 0 in binary else ()
+ # Alpha comparison includes its threshold and always excludes zero before
+ # inversion. The half-step separates adjacent integer samples consistently.
+ alpha_field = (raster, max(1, threshold) - .5) if mode in ('alpha', 'alpha_object') else ()
+ return Analysis(groups, alpha_field=alpha_field)
+
+
+def _mask_components(binary, width, height):
+ stride = width + 2
+ padded = bytearray(stride * (height + 2))
+ visited = bytearray(len(padded))
+ rings = []
+ corners = 0
+ for y in range(height):
+ offset = (y + 1) * stride + 1
+ padded[offset:offset + width] = binary[y * width:(y + 1) * width]
+ # Every boundary includes a vertical edge at an end of a horizontal run.
+ # finditer skips solid interiors in C even on a large fully opaque image.
+ for run in re.finditer(b'\x01+', padded):
+ for index, direction in ((run.start(), 3), (run.end() - 1, 1)):
+ if not visited[index] & (1 << direction):
+ path = _walk(padded, visited, stride, index, direction, 500_000 - corners)
+ corners += len(path)
+ rings.extend(_simple_rings(path))
+ return _group_rings(rings)
+
+
+def _cross(a, b, p):
+ return (b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0])
+
+
+class _Vertices:
+ """Static point index; removed vertices are marked inactive in the links."""
+
+ def __init__(self, points):
+ self.axes = [sorted((p[axis], i) for i, p in enumerate(points)) for axis in (0, 1)]
+ self.points = points
+
+ def occupied_triangle(self, left, middle, right, following):
+ a, b, c = (self.points[i] for i in (left, middle, right))
+ ranges = []
+ for axis, entries in enumerate(self.axes):
+ coords = a[axis], b[axis], c[axis]
+ begin = bisect_left(entries, (min(coords), -1))
+ end = bisect_right(entries, (max(coords), len(self.points)))
+ ranges.append((end - begin, begin, end, axis))
+ _, begin, end, axis = min(ranges)
+ for k in range(begin, end):
+ i = self.axes[axis][k][1]
+ if i in (left, middle, right) or following[i] < 0:
+ continue
+ p = self.points[i]
+ if not all(min(a[j], b[j], c[j]) <= p[j] <= max(a[j], b[j], c[j]) for j in (0, 1)):
+ continue
+ sides = _cross(a, b, p), _cross(b, c, p), _cross(c, a, p)
+ if min(sides) >= 0 or max(sides) <= 0:
+ return True
+ return False
+
+
+def _photo_vertices(ring, sx, sy, tolerance):
+ # A shortest path through the original vertices. Each permitted shortcut
+ # follows the original boundary order and stays inside its physical error
+ # corridor. A bounded window keeps noisy megapixel outlines interactive.
+ n = len(ring)
+ points = tuple((x * sx, y * sy) for x, y in (*ring, ring[0]))
+ extrema = {min(range(n), key=lambda i: sign * points[i][axis])
+ for axis in (0, 1) for sign in (-1, 1)}
+ limit = tolerance * tolerance
+
+ def chord_error(i, j):
+ ax, ay = points[i]
+ bx, by = points[j]
+ dx, dy = bx - ax, by - ay
+ span = dx * dx + dy * dy
+ if not span:
+ return math.inf
+ total = 0.
+ for k in range(i + 1, j):
+ x, y = points[k]
+ x, y = x - ax, y - ay
+ projection = (x * dx + y * dy) / span
+ if projection <= 0:
+ squared = x * x + y * y
+ elif projection >= 1:
+ squared = (x - dx) ** 2 + (y - dy) ** 2
+ else:
+ squared = (x * dy - y * dx) ** 2 / span
+ if squared > limit:
+ return math.inf
+ total += squared
+ return total
+
+ cost = [(n + 1, math.inf)] * (n + 1)
+ cost[0] = (0, 0.)
+ previous = [0] * (n + 1)
+ for i in range(n):
+ count, error = cost[i]
+ for j in range(i + 1, min(n, i + 40) + 1):
+ if count + 1 <= cost[j][0]:
+ squared_error = chord_error(i, j)
+ if math.isfinite(squared_error):
+ candidate = (count + 1, error + squared_error)
+ if candidate < cost[j]:
+ cost[j], previous[j] = candidate, i
+ if j in extrema:
+ break
+ keep = set()
+ j = n
+ while j:
+ j = previous[j]
+ keep.add(j)
+ return keep
+
+
+def _simplify(rings, sx, sy, tolerance, preserve_corners, targets=None):
+ # Remove one vertex at a time. An empty swept triangle preserves the
+ # topology of all rings, including small holes and nearby islands.
+ points = [p for ring in rings for p in ring]
+ physical = [(x * sx, y * sy) for x, y in points]
+ spatial = _Vertices(points)
+ previous, following, original_next, sizes, owners, locked = [], [], [], [], [], []
+ queue = []
+ offset = 0
+ for owner, ring in enumerate(rings):
+ n = len(ring)
+ sizes.append(n)
+ for j, p in enumerate(ring):
+ before, after = ring[j - 1], ring[(j + 1) % n]
+ # Long horizontal/vertical runs meeting at a corner are artwork
+ # corners. Stair-step joins adjacent to one-pixel runs can move.
+ locked.append(n <= 4 or (targets is not None and j in targets[owner])
+ or (preserve_corners and math.dist(before, p) >= 2
+ and math.dist(after, p) >= 2))
+ previous.append(offset + (j - 1) % n)
+ following.append(offset + (j + 1) % n)
+ owners.append(owner)
+ offset += n
+ original_next.extend(following)
+ limit = tolerance ** 2
+
+ def enqueue(i):
+ if locked[i] or sizes[owners[i]] <= 3:
+ return
+ left, right = previous[i], following[i]
+ ax, ay = physical[left]
+ bx, by = physical[right]
+ dx, dy = bx - ax, by - ay
+ span = dx * dx + dy * dy
+ if not span:
+ return
+ deviation = 0
+ # Always measure against the original chain to bound cumulative error.
+ j = original_next[left]
+ while j != right:
+ px, py = physical[j][0] - ax, physical[j][1] - ay
+ t = max(0, min(1, (px * dx + py * dy) / span))
+ deviation = max(deviation, (px - t * dx) ** 2 + (py - t * dy) ** 2)
+ if deviation > limit:
+ return
+ j = original_next[j]
+ heapq.heappush(queue, (deviation, i, left, right))
+
+ for i in range(len(points)):
+ enqueue(i)
+ while queue:
+ _, i, left, right = heapq.heappop(queue)
+ if previous[i] != left or following[i] != right or sizes[owners[i]] <= 3:
+ continue
+ if spatial.occupied_triangle(left, i, right, following):
+ continue
+ following[i] = -1
+ following[left], previous[right] = right, left
+ sizes[owners[i]] -= 1
+ enqueue(left)
+ enqueue(right)
+
+ result, offset = [], 0
+ for ring in rings:
+ result.append(tuple(p for j, p in enumerate(ring, offset) if following[j] >= 0))
+ offset += len(ring)
+ return tuple(result)
+
+
+def trace(analysis, mm_per_px_x, mm_per_px_y, tolerance_mm, min_area_mm2):
+ if not all(map(math.isfinite, (mm_per_px_x, mm_per_px_y, tolerance_mm, min_area_mm2))):
+ raise ValueError('Image trace settings must be finite.')
+ if min(mm_per_px_x, mm_per_px_y) <= 0 or min(tolerance_mm, min_area_mm2) < 0:
+ raise ValueError('Image size must be positive and trace settings must be non-negative.')
+ pixel_area = mm_per_px_x * mm_per_px_y
+ rings = tuple(r for group in analysis.components
+ if sum(map(_area, group)) * pixel_area >= min_area_mm2 for r in group)
+ if tolerance_mm > 0 and any(len(r) > 4 for r in rings):
+ if analysis.photo and sum(map(len, rings)) <= 12_000:
+ targets = [_photo_vertices(r, mm_per_px_x, mm_per_px_y, tolerance_mm)
+ if len(r) > 4 else set(range(len(r))) for r in rings]
+ # Test the whole proposed path by removing only unselected points
+ # through empty triangles. Intermediate chains may exceed the final
+ # tolerance; emit the candidate only when every shortcut succeeds.
+ candidate = _simplify(rings, mm_per_px_x, mm_per_px_y, math.inf, False, targets)
+ if all(len(r) == len(t) for r, t in zip(candidate, targets)):
+ return TraceResult(candidate)
+ rings = _simplify(rings, mm_per_px_x, mm_per_px_y, tolerance_mm, analysis.preserve_corners)
+ return TraceResult(rings)
diff --git a/InsertTo/trace_dialog.py b/InsertTo/trace_dialog.py
new file mode 100644
index 0000000..1eff426
--- /dev/null
+++ b/InsertTo/trace_dialog.py
@@ -0,0 +1,370 @@
+"""Trace Image command and its session-scoped raster and geometry caches."""
+
+from dataclasses import dataclass
+import math
+from pathlib import Path
+import traceback
+
+import adsk.core
+
+from . import fusion_import, image_trace, svg_geometry, trace_primitives, trace_render
+from .dialog import _Dialog, _listen, _show
+
+
+@dataclass(frozen=True)
+class ImagePage:
+ width_mm: float
+ height_mm: float
+
+
+_PREVIEW_MODES = ('source', 'overlay', 'filled')
+_DENSE_CURVE_COUNT = 3000
+_TRACE_INPUTS = {'imageWidth', 'traceDetail', 'traceSmallShapes', 'traceEdgeCoverage', 'tracePreviewMode',
+ 'traceRecognizeCircles', 'traceRecognizeArcs', 'traceRecognizeEllipses'}
+
+
+def _picked_pixel(world_point, transform, raster):
+ # The preview uses (x, -y, 0) in image pixels before its placement matrix.
+ if world_point is None:
+ return None
+ inverse = transform.copy()
+ point = world_point.copy()
+ if not inverse.invert() or not point.transformBy(inverse):
+ return None
+ x, y = math.floor(point.x), math.floor(-point.y)
+ if 0 <= x < raster.width and 0 <= y < raster.height:
+ return x, y
+ return None
+
+
+def _choices(inputs, id_, label, choices, selected):
+ dropdown = inputs.addDropDownCommandInput(id_, label, adsk.core.DropDownStyles.TextListDropDownStyle)
+ for index, name in enumerate(choices):
+ dropdown.listItems.add(name, index == selected)
+ return dropdown
+
+
+class TraceDialog(_Dialog):
+ file_id = 'traceFile'
+ file_label = 'Image file'
+ file_prompt = 'Choose a PNG or JPEG image.'
+ frame_tooltip = 'Select a profile or closed contour to fit the image to its frame.'
+
+ def __init__(self, command):
+ self.raster = self.preview_renderer = None
+ self.analysis = self.result = None
+ self.seed = None
+ self.defaults = None
+ self._focus_pick = False
+ self._dense_count = 0
+ self._analysis_key = self._result_key = None
+ self._outlines = None
+ self._fits = {}
+ command.setDialogMinimumSize(360, 240)
+ command.setDialogInitialSize(460, 540)
+ super().__init__(command)
+ self.transform.group.isExpanded = False
+ self.handlers.append(_listen(command.preSelect, adsk.core.SelectionEventHandler, self._preselect))
+
+ def _source_options(self, inputs):
+ real = adsk.core.ValueInput.createByReal
+ self.detail = inputs.addIntegerSliderCommandInput('traceDetail', 'Outline detail', 0, 10)
+ self.detail.valueOne = 5
+ self.detail.setText('Simple', 'Detailed')
+ self.detail.tooltip = 'Move left for fewer sketch curves or right to follow smaller bends.'
+ self.small_shapes = inputs.addIntegerSliderCommandInput('traceSmallShapes', 'Remove small shapes', 0, 100)
+ self.small_shapes.valueOne = 0
+ self.small_shapes.tooltip = ('Remove separate shapes smaller than this area in source pixels (px²). '
+ 'Zero keeps all shapes. Holes stay with their surrounding shape.')
+ self.recognition = inputs.addGroupCommandInput('traceRecognition', 'Recognize')
+ self.recognition.isExpanded = True
+ shapes = self.recognition.children
+ self.circles = shapes.addBoolValueInput('traceRecognizeCircles', 'Circles', True, '', True)
+ self.circles.tooltip = 'Use a single sketch circle for an outline that follows a full circle.'
+ self.arcs = shapes.addBoolValueInput('traceRecognizeArcs', 'Arcs', True, '', True)
+ self.arcs.tooltip = 'Use circular arcs for rounded sections. Full circles have a separate option.'
+ self.ellipses = shapes.addBoolValueInput('traceRecognizeEllipses', 'Ellipses', True, '', True)
+ self.ellipses.tooltip = 'Use a single sketch ellipse for a closed oval with unequal axes.'
+ self.pick = inputs.addSelectionInput('traceSubject', 'Object', 'Click inside the object in the image.')
+ self.pick.addSelectionFilter('CustomGraphics')
+ self.pick.setSelectionLimits(0, 1)
+ self.pick.isUseCurrentSelections = False
+ self.pick.tooltip = 'Click inside the object or ink stroke you want to trace.'
+ self.reset = inputs.addBoolValueInput('traceAutoSubject', 'Object', False, '', False)
+ self.reset.text = 'Reset selection'
+ self.reset.tooltip = 'Return to the outlines chosen when you opened the image.'
+
+ self.view = inputs.addGroupCommandInput('traceView', 'More options')
+ self.view.isExpanded = False
+ self.coverage = self.view.children.addIntegerSliderCommandInput('traceEdgeCoverage', 'Edge coverage', 0, 100)
+ self.coverage.valueOne = 50
+ self.coverage.setText('Less', 'More')
+ self.coverage.tooltip = 'The middle (50) uses the automatic boundary. Move right to include more of the image.'
+
+ self.width = self.view.children.addValueInput('imageWidth', 'Image width', 'mm', real(10))
+ self.width.tooltip = 'Set the physical width of the image. Height follows its aspect ratio.'
+ self.preview_mode = _choices(self.view.children, 'tracePreviewMode', 'Preview',
+ ('Source image', 'Contours over source', 'Filled result'), 1)
+ self.confirm = inputs.addBoolValueInput('traceConfirmDense', 'Insert all sketch curves', True, '', False)
+ self.confirm.isVisible = False
+ self._show_trace_controls()
+
+ def _show_trace_controls(self):
+ loaded = self.raster is not None
+ _show(self.pick, loaded and self.preview_mode.selectedItem.index != 2)
+ _show(self.reset, loaded and self.seed is not None)
+ _show(self.detail, loaded)
+ _show(self.small_shapes, loaded)
+ _show(self.recognition, loaded)
+ # Growing an unpicked photo silhouette can jump to a different subject.
+ _show(self.coverage, loaded and (self.defaults.is_artwork or self.seed is not None))
+ _show(self.view, loaded)
+
+ def _is_source_entity(self, entity):
+ if self.preview_renderer is None or self.preview_renderer.raster is not self.raster:
+ return False
+ source = self.preview_renderer._source_entity
+ return source is not None and (entity == source or getattr(entity, 'parent', None) == source)
+
+ def _preselect(self, args):
+ if args.activeInput and args.activeInput.id == self.pick.id:
+ args.isSelectable = self._is_source_entity(args.selection.entity)
+
+ def _pick_object(self):
+ if not self.pick.selectionCount:
+ return
+ selection = self.pick.selection(0)
+ seed = None
+ if self._is_source_entity(selection.entity):
+ seed = _picked_pixel(selection.point, self.preview_renderer._group.transform, self.raster)
+ # Re-arm the input so the next click on the same image can pick another object.
+ self.pick.clearSelection()
+ if seed is not None:
+ self.seed = seed
+ self.preview_mode.listItems.item(1).isSelected = True
+ self._show_trace_controls()
+ self.preview_error = ''
+ self.pick.hasFocus = True
+
+ def _link_option(self, inputs):
+ # The source raster is used only while this command is open.
+ return None
+
+ def _use_artwork(self):
+ return False
+
+ def _show_target_controls(self):
+ super()._show_target_controls()
+ _show(self.width, self._mode() == 'original')
+
+ def _choose_file(self):
+ picker = self.app.userInterface.createFileDialog()
+ picker.title = 'Trace Image'
+ picker.filter = 'PNG and JPEG images (*.png;*.jpg;*.jpeg)'
+ picker.isMultiSelectEnabled = False
+ if picker.showOpen() != adsk.core.DialogResults.DialogOK:
+ return False
+ self._load_file(picker.filename)
+ return True
+
+ def _load_file(self, filename):
+ # The file chooser runs in inputChanged. Replace native graphics in
+ # executePreview, after Fusion has finished changing the command inputs.
+ self.document = self.raster = self.analysis = self.result = self._outlines = None
+ self._fits.clear()
+ self._analysis_key = self._result_key = None
+ self.seed = None
+ self._dense_count = 0
+ self.confirm.value = False
+ self.confirm.isVisible = False
+ self.browse.text = Path(filename).name
+ self.browse.tooltip = filename
+ self.file_error = ''
+ try:
+ raster = image_trace.load_image(filename)
+ width = raster.width * svg_geometry.MM_PER_PX
+ self.width.value = width / 10
+ self.defaults = image_trace.artwork_defaults(raster)
+ self.preview_mode.listItems.item(1).isSelected = True
+ self._focus_pick = True
+ self.detail.valueOne = 5
+ self.small_shapes.valueOne = 0
+ self.arcs.value = self.circles.value = self.ellipses.value = True
+ self.coverage.valueOne = 50
+ self.document = ImagePage(width, raster.height * svg_geometry.MM_PER_PX)
+ self.raster = raster
+ except (ValueError, OSError) as exc:
+ self.file_error = str(exc)
+ self._show_trace_controls()
+
+ def _changed(self, args):
+ changed = args.input.id
+ if changed == 'traceSubject':
+ self._pick_object()
+ return
+ if changed == 'traceAutoSubject':
+ self.seed = None
+ self._focus_pick = True
+ self._show_trace_controls()
+ self.preview_error = ''
+ return
+ if changed in _TRACE_INPUTS and self.raster is not None:
+ if changed == 'tracePreviewMode':
+ self._show_trace_controls()
+ self._focus_pick = self.pick.isVisible
+ self.preview_error = ''
+ return
+ super()._changed(args)
+
+ def _destination(self):
+ sketch, plane = super()._destination()
+ if sketch is not None:
+ timeline = sketch.timelineObject
+ if timeline and (timeline.isRolledBack or timeline.isSuppressed):
+ raise ValueError('The destination sketch is unavailable at the current timeline position.')
+ return sketch, plane
+
+ def _placements(self):
+ if self._mode() == 'original':
+ if not self.width.isValidExpression or self.width.value <= 0:
+ raise ValueError('Enter a positive image width.')
+ width = self.width.value * 10
+ self.document = ImagePage(width, width * self.raster.height / self.raster.width)
+ return super()._placements()
+
+ def _result(self, target):
+ sx, sy = target.width_mm / self.raster.width, target.height_mm / self.raster.height
+ detail = self.detail.valueOne
+ if self.defaults.is_artwork:
+ light = self.defaults.mode == 'light'
+ if self.defaults.mode == 'alpha':
+ mode = 'alpha'
+ # The opacity comparison includes the threshold itself.
+ cutoff = image_trace.ink_cutoff(self.defaults.threshold, self.coverage.valueOne, True)
+ else:
+ mode = 'ink'
+ cutoff = image_trace.ink_cutoff(self.defaults.threshold, self.coverage.valueOne, light)
+ if self.seed is not None:
+ mode += '_object'
+ key = (mode, cutoff, light, self.seed)
+ tolerance_px = .65 * 2 ** ((5 - detail) / 5)
+ else:
+ cutoff = 128 if self.seed is None else round(255 * self.coverage.valueOne / 100)
+ key = ('silhouette', cutoff, False, self.seed)
+ tolerance_px = 2.5 * 2 ** ((5 - detail) / 2.5)
+ # Detail is expressed in source pixels and never changes the foreground mask.
+ tolerance = min(sx, sy) * tolerance_px
+ if self._analysis_key != key:
+ self.analysis = image_trace.analyze(self.raster, *key)
+ self._analysis_key = key
+ self._result_key = None
+ result_key = (sx, sy, tolerance, self.small_shapes.valueOne * (sx * sy))
+ if self._result_key != result_key:
+ self._outlines = image_trace.trace(self.analysis, *result_key)
+ self._result_key = result_key
+ self._fits.clear()
+ options = (self.circles.value, self.arcs.value, self.ellipses.value)
+ if not any(options):
+ self.result = self._outlines
+ else:
+ if options not in self._fits:
+ self._fits[options] = trace_primitives.recognize(
+ self.analysis, self._outlines, sx, sy, tolerance, *options)
+ self.result = self._fits[options]
+ return self.result
+
+ def _dimensions(self, target):
+ result = self._result(target)
+ count = result.curve_count
+ dense_count = count if count > _DENSE_CURVE_COUNT else 0
+ if dense_count != self._dense_count:
+ self._dense_count = dense_count
+ self.confirm.value = False
+ _show(self.confirm, bool(dense_count))
+ if not result.rings:
+ if self.small_shapes.valueOne:
+ self._status(f'No outlines at {self.small_shapes.valueOne} px². Reduce Remove small shapes.')
+ elif self.pick.isVisible:
+ self._status('No outline here. Click inside the object or an ink stroke.')
+ else:
+ self._status('No outline here. Choose Contours over source to pick an object.')
+ return
+ size = f'{target.width_mm:.6g} × {target.height_mm:.6g} mm'
+ contours = len(result.rings)
+ contour_label = 'contour' if contours == 1 else 'contours'
+ counts = result.type_counts
+ types = ', '.join(f'{n:,} {name}{"s" if n != 1 else ""}'
+ for n, name in zip(counts, ('line', 'arc', 'circle', 'ellipse')) if n)
+ curve_label = 'sketch curve' if count == 1 else 'sketch curves'
+ summary = f'{size} · {contours} {contour_label} · {count:,} {curve_label} ({types})'
+ if dense_count:
+ self._status(summary + '\nInsertion may take time. Reduce Outline detail or increase Remove small shapes.')
+ return
+ if self.small_shapes.valueOne:
+ summary += f'\nMinimum shape area {self.small_shapes.valueOne} px²'
+ elif self.pick.isVisible:
+ summary += '\nClick another object to switch.' if self.seed else '\nClick inside an object to trace just that object.'
+ self._status(summary)
+
+ def _validate(self, args):
+ super()._validate(args)
+ # Validation can fire while Fusion is committing a command. Leave
+ # native graphics to the preview, execute and destroy handlers.
+ if not args.areInputsValid:
+ return
+ if self._dense_count and not self.confirm.value:
+ args.areInputsValid = False
+ elif self.result is not None and not self.result.rings:
+ # Keep source/overlay visible so the user can pick another object.
+ args.areInputsValid = False
+
+ def _preview_graphics(self, sketch, plane):
+ baseline, target, _ = self._placements()
+ result = self._result(target)
+ destination = fusion_import.sketch_for_target(self.design, sketch, plane)
+ try:
+ self.transform.position(destination, baseline.pivot)
+ if self.preview_renderer is not None and self.preview_renderer.raster is not self.raster:
+ self.close()
+ if self.preview_renderer is None:
+ self.preview_renderer = trace_render.Preview(self.raster)
+ self.preview_renderer.draw(destination, target, result,
+ _PREVIEW_MODES[self.preview_mode.selectedItem.index])
+ if self._focus_pick and self.pick.isVisible:
+ self._focus_pick = False
+ self.pick.hasFocus = True
+ self._dimensions(target)
+ finally:
+ if sketch is None and destination.isValid:
+ destination.deleteMe()
+
+ def _execute(self, args):
+ try:
+ self.close()
+ self.transform.read_drag()
+ sketch, plane = self._destination()
+ _, target, _ = self._placements()
+ result = self._result(target)
+ if result.curve_count > _DENSE_CURVE_COUNT and (
+ self._dense_count != result.curve_count or not self.confirm.value):
+ raise ValueError(f'Confirm insertion of all {result.curve_count:,} sketch curves.')
+ if not result.rings:
+ raise ValueError('The selected settings produced no contours.')
+ destination = fusion_import.sketch_for_target(self.design, sketch, plane)
+ try:
+ if sketch is None:
+ destination.name = 'Smart Insert Trace Image'
+ trace_render.insert_curves(destination, target, self.raster, result)
+ except Exception:
+ if sketch is None and destination.isValid:
+ destination.deleteMe()
+ raise
+ except Exception as exc:
+ self.app.log(traceback.format_exc())
+ args.executeFailed = True
+ args.executeFailedMessage = f'Image insert failed. {exc}'
+
+ def close(self):
+ if self.preview_renderer is not None:
+ self.preview_renderer.close()
+ self.preview_renderer = None
diff --git a/InsertTo/trace_ellipses.py b/InsertTo/trace_ellipses.py
new file mode 100644
index 0000000..ecdb8fe
--- /dev/null
+++ b/InsertTo/trace_ellipses.py
@@ -0,0 +1,224 @@
+"""Fit complete ellipses to closed physical outlines, independently of Fusion."""
+from bisect import bisect_right
+from dataclasses import dataclass
+import math
+
+
+@dataclass(frozen=True)
+class Ellipse:
+ """Centre and positive principal-axis endpoints in source pixel coordinates."""
+ center: tuple
+ major: tuple
+ minor: tuple
+
+
+def _dot(a, b):
+ return a.real * b.real + a.imag * b.imag
+
+
+def _point_distance(p, a, b):
+ d = b - a
+ squared = _dot(d, d)
+ t = min(1., max(0., _dot(p - a, d) / squared)) if squared else 0.
+ return abs(p - (a + t * d))
+
+
+def _angle_delta(first, last):
+ return math.remainder(last - first, math.tau)
+
+
+@dataclass
+class _Fit:
+ center: complex
+ axis: complex
+ major: float
+ minor: float
+ error_bound: float = 0.
+
+ def local(self, point):
+ return (point - self.center) * self.axis.conjugate()
+
+ def at(self, angle):
+ return complex(self.major * math.cos(angle), self.minor * math.sin(angle))
+
+ def projection(self, point):
+ """Return a point on the ellipse and its measured physical distance."""
+ angle = math.atan2(point.imag / self.minor, point.real / self.major)
+ for _ in range(3):
+ c, s = math.cos(angle), math.sin(angle)
+ v = complex(self.major * c, self.minor * s)
+ tangent = complex(-self.major * s, self.minor * c)
+ offset = v - point
+ gradient = _dot(offset, tangent)
+ curvature = _dot(tangent, tangent) - _dot(offset, v)
+ if curvature <= 0 or abs(gradient) < 1e-14 * curvature:
+ break
+ angle -= min(.35, max(-.35, gradient / curvature))
+ return angle, abs(point - self.at(angle))
+
+ def near(self, bounds, padding):
+ rx = math.hypot(self.major * self.axis.real, self.minor * self.axis.imag)
+ ry = math.hypot(self.major * self.axis.imag, self.minor * self.axis.real)
+ x, y = self.center.real, self.center.imag
+ return (x - rx - padding <= bounds[2] and y - ry - padding <= bounds[3] and
+ x + rx + padding >= bounds[0] and y + ry + padding >= bounds[1])
+
+ def clear(self, edges, padding):
+ # The inverse affine map has Lipschitz constant 1/minor. Exact radial
+ # extrema on the unit-disk segment thus exclude all physical contacts.
+ margin = padding / self.minor
+ for a, b in edges:
+ p, q = self.local(a), self.local(b)
+ u = complex(p.real / self.major, p.imag / self.minor)
+ v = complex(q.real / self.major, q.imag / self.minor)
+ if max(abs(u), abs(v)) >= 1 - margin and _point_distance(0j, u, v) <= 1 + margin:
+ return False
+ return True
+
+
+def moment_ellipse(points):
+ """Area moments are invariant to how densely different edges are sampled."""
+ origin = points[0]
+ area = x1 = y1 = xx = yy = xy = 0.
+ for p, q in zip(points, points[1:] + points[:1]):
+ p, q = p - origin, q - origin
+ x, y, u, v = p.real, p.imag, q.real, q.imag
+ w = x * v - y * u
+ area += w
+ x1 += (x + u) * w
+ y1 += (y + v) * w
+ xx += (x * x + x * u + u * u) * w
+ yy += (y * y + y * v + v * v) * w
+ xy += (2 * x * y + x * v + u * y + 2 * u * v) * w
+ if not area:
+ return None
+ x, y = x1 / (3 * area), y1 / (3 * area)
+ xx = xx / (6 * area) - x * x
+ yy = yy / (6 * area) - y * y
+ xy = xy / (12 * area) - x * y
+ separation = math.hypot(xx - yy, 2 * xy)
+ small = 2 * (xx + yy - separation)
+ if small <= 0:
+ return None
+ angle = .5 * math.atan2(2 * xy, xx - yy)
+ return _Fit(origin + complex(x, y), complex(math.cos(angle), math.sin(angle)),
+ math.sqrt(2 * (xx + yy + separation)), math.sqrt(small))
+
+
+def _certify(fit, p, q, first, last, limit, pitch, depth=0):
+ # Pair linear interpolation on the raw segment with interpolation of its
+ # ellipse parameter. The ellipse's second derivative norm is <= major,
+ # hence the maximum error between it and its chord is <= major*dt²/8.
+ # This point-to-point correspondence bounds *both* directed distances.
+ delta = _angle_delta(first[0], last[0])
+ sag = fit.major * delta * delta / 8
+ bound = max(first[1], last[1]) + sag
+ if bound <= limit and (sag <= .025 * pitch or depth >= 5):
+ return bound
+ if max(first[1], last[1]) > limit or depth >= 10:
+ return math.inf
+ middle = (p + q) / 2
+ projection = fit.projection(middle)
+ if abs(_angle_delta(first[0], projection[0]) + _angle_delta(projection[0], last[0]) - delta) > 1e-8:
+ return math.inf
+ left = _certify(fit, p, middle, first, projection, limit, pitch, depth + 1)
+ if left > limit:
+ return math.inf
+ return max(left, _certify(fit, middle, q, projection, last, limit, pitch, depth + 1))
+
+
+def _visible_facets(fit, local, pitch):
+ # Inspect the raw edge in both source directions at several angular spans.
+ # Long facets and straight shelves have a measurable bow on the analytic
+ # ellipse while the actual samples stay on their chord.
+ # Consecutive resolved straight sides are strong corner evidence. Work in
+ # the affine circle coordinates to avoid exaggerating turns under stretch.
+ straights = []
+ for p, q in zip(local, local[1:] + local[:1]):
+ d = q - p
+ d = complex(d.real * fit.minor / fit.major, d.imag)
+ if not d:
+ continue
+ if straights:
+ angle = (straights[-1].conjugate() * d)
+ if angle.real > 0 and abs(angle.imag) <= .001 * abs(angle):
+ straights[-1] += d
+ continue
+ straights.append(d)
+ for u, v in zip(straights, straights[1:] + straights[:1]):
+ angle = u.conjugate() * v
+ if min(abs(u), abs(v)) > max(1.7 * pitch, .12 * fit.minor):
+ if abs(math.atan2(angle.imag, angle.real)) > math.radians(12):
+ return True
+
+ lengths = [0.]
+ for p, q in zip(local, local[1:] + local[:1]):
+ lengths.append(lengths[-1] + abs(q - p))
+ perimeter = lengths[-1]
+ if not perimeter:
+ return True
+
+ def point_at(distance):
+ distance %= perimeter
+ i = bisect_right(lengths, distance) - 1
+ p, q = local[i], local[(i + 1) % len(local)]
+ return p + (q - p) * ((distance - lengths[i]) / (lengths[i + 1] - lengths[i]))
+
+ # Resample for this evidence test only. The error certificate still uses
+ # every original segment, independent of this bounded sample size.
+ samples = [point_at(perimeter * i / 160) for i in range(160)]
+ angles = [fit.projection(p)[0] for p in samples]
+ count = len(samples)
+ for i, p in enumerate(samples):
+ for span in (6, 10, 16, 23):
+ j = (i + span) % count
+ q = samples[j]
+ delta = _angle_delta(angles[i], angles[j])
+ if abs(delta) < .22 or abs(q - p) < 3 * pitch:
+ continue
+ ideal_mid = fit.at(angles[i] + delta / 2)
+ bow = _point_distance(ideal_mid, fit.at(angles[i]), fit.at(angles[j]))
+ if bow <= .15 * pitch:
+ continue
+ if all(_point_distance(samples[(i + k) % count], p, q) <= .045 * pitch
+ for k in range(1, span)):
+ return True
+ return False
+
+
+def fit_ellipse(points, pitch, tolerance):
+ if len(points) < 20:
+ return None
+ fit = moment_ellipse(points)
+ if (fit is None or fit.minor < 2.45 * pitch or fit.major - fit.minor < .55 * pitch
+ or fit.minor * fit.minor / fit.major < .65 * pitch):
+ return None
+ limit = min(tolerance, max(.50 * pitch, .002 * fit.minor), .14 * fit.minor)
+ local = [fit.local(p) for p in points]
+ for p in local:
+ unit_radius = math.hypot(p.real / fit.major, p.imag / fit.minor)
+ if abs(unit_radius - 1) * fit.minor > limit:
+ return None
+
+ projections = [fit.projection(p) for p in local]
+ angles = [_angle_delta(first[0], last[0])
+ for first, last in zip(projections, projections[1:] + projections[:1])]
+ if abs(abs(sum(angles)) - math.tau) > 1e-5 or max(map(abs, angles)) > .70:
+ return None
+ squared = perimeter = 0.
+ for i, p in enumerate(local):
+ j = (i + 1) % len(local)
+ first, last = projections[i], projections[j]
+ bound = _certify(fit, p, local[j], first, last, limit, pitch)
+ if bound > limit:
+ return None
+ fit.error_bound = max(fit.error_bound, bound)
+ length = abs(local[j] - p)
+ squared += (first[1] ** 2 + last[1] ** 2) * length / 2
+ perimeter += length
+ # Independently resolve both axes above the shape's own boundary noise.
+ if not perimeter or fit.major - fit.minor < 3.2 * math.sqrt(squared / perimeter):
+ return None
+ if _visible_facets(fit, local, pitch):
+ return None
+ return fit
diff --git a/InsertTo/trace_primitives.py b/InsertTo/trace_primitives.py
new file mode 100644
index 0000000..0965a92
--- /dev/null
+++ b/InsertTo/trace_primitives.py
@@ -0,0 +1,1090 @@
+"""Conservative circular fits against the extracted image boundary in physical units."""
+
+from bisect import bisect_right
+from dataclasses import dataclass, replace
+from functools import cached_property
+import math
+
+from .trace_ellipses import Ellipse, fit_ellipse, moment_ellipse
+
+
+@dataclass(frozen=True)
+class Line:
+ start: tuple
+ end: tuple
+
+
+@dataclass(frozen=True)
+class Arc:
+ start: tuple
+ mid: tuple
+ end: tuple
+
+
+@dataclass(frozen=True)
+class Circle:
+ center: tuple
+ radius: float # millimetres; points in all three primitives are source pixels
+
+
+def _edges(points):
+ return zip(points, points[1:] + points[:1])
+
+
+def _bounds(points):
+ xs = [p.real for p in points]
+ ys = [p.imag for p in points]
+ return min(xs), min(ys), max(xs), max(ys)
+
+
+def _dot(a, b):
+ return a.real * b.real + a.imag * b.imag
+
+
+def _cross(a, b):
+ return a.real * b.imag - a.imag * b.real
+
+
+def _distance(p, a, b):
+ delta = b - a
+ squared = _dot(delta, delta)
+ t = min(1., max(0., _dot(p - a, delta) / squared)) if squared else 0.
+ return abs(p - a - t * delta)
+
+
+def _distances(a, b, first, last):
+ """Minimum and maximum distance along [a,b] to the fitted centreline."""
+ if first == last:
+ return _distance(first, a, b), max(abs(a - first), abs(b - first))
+ da, db = _distance(a, first, last), _distance(b, first, last)
+ cuts = (_cross(b - a, first - a) * _cross(b - a, last - a) < 0 and
+ _cross(last - first, a - first) * _cross(last - first, b - first) < 0)
+ low = 0. if cuts else min(da, db, _distance(first, a, b), _distance(last, a, b))
+ return low, max(da, db)
+
+
+def _encloses(points, center):
+ x, y = center.real, center.imag
+ return sum(a.real + (y - a.imag) * (b.real - a.real) / (b.imag - a.imag) > x
+ for a, b in _edges(points) if (a.imag > y) != (b.imag > y)) % 2 == 1
+
+
+def _confidence(tolerance, radius, pitch):
+ # A coarse detail setting may simplify a photo but must not turn a visibly
+ # non-circular edge into a circle. Very small radii provide little evidence.
+ return min(tolerance, .07 * radius, max(.75 * pitch, .002 * radius))
+
+
+@dataclass(frozen=True)
+class _Band:
+ """Boundary of a disk or capsule; arcs use the containing disk for clearance."""
+ first: complex
+ last: complex
+ radius: float
+
+ def follows(self, edges, error):
+ for a, b in edges:
+ lo, hi = _distances(a, b, self.first, self.last)
+ if lo < self.radius - error or hi > self.radius + error:
+ return False
+ return True
+
+ def clear(self, edges, padding):
+ for a, b in edges:
+ lo, hi = _distances(a, b, self.first, self.last)
+ if lo <= self.radius + padding and hi >= self.radius - padding:
+ return False
+ return True
+
+ def near(self, bounds, padding):
+ left, top, right, bottom = bounds
+ margin = self.radius + padding
+ return (min(self.first.real, self.last.real) - margin <= right and
+ max(self.first.real, self.last.real) + margin >= left and
+ min(self.first.imag, self.last.imag) - margin <= bottom and
+ max(self.first.imag, self.last.imag) + margin >= top)
+
+
+def _circle_scanline_turn(u, v, angle, radius, pitch):
+ """Two adjacent threshold crossings on consecutive raster scanlines."""
+ if max(abs(u), abs(v)) > 1.5 * pitch:
+ return False
+ # At a five-pixel radius, a genuine circle already turns by ~11 degrees
+ # per pixel. Allow six degrees of local interpolation jitter only when the
+ # samples demonstrably came from adjacent rows or columns of the image.
+ if angle > 2 * math.asin(min(1., pitch / (2 * radius))) + math.radians(6):
+ return False
+ return any(math.isclose(a, b) and math.isclose(abs(a), pitch)
+ for a, b in ((u.real, v.real), (u.imag, v.imag)))
+
+
+def _smooth_evidence(points, center, radius, pitch, closed):
+ """Distinguish a distributed turn from persistent corners and ovality."""
+ chain = points + points[:1] if closed else points
+ straights = []
+ for a, b in zip(chain, chain[1:]):
+ delta = b - a
+ if not delta:
+ continue
+ if (straights and _dot(delta, straights[-1]) > 0 and
+ abs(_cross(delta, straights[-1])) < .001 * abs(delta) * abs(straights[-1])):
+ straights[-1] += delta
+ else:
+ straights.append(delta)
+ pairs = _edges(straights) if closed else zip(straights, straights[1:])
+ for u, v in pairs:
+ if min(abs(u), abs(v)) > .18 * radius:
+ angle = abs(math.atan2(_cross(u, v), _dot(u, v)))
+ if angle > math.radians(12) and not (closed and _circle_scanline_turn(u, v, angle, radius, pitch)):
+ return False
+ lengths = [abs(b - a) for a, b in zip(chain, chain[1:])]
+ perimeter = sum(lengths)
+ if not perimeter:
+ return False
+ # Uniform arclength avoids overweighting antialiased or noisy sections.
+ count = 128
+ step = perimeter / count
+ samples = []
+ pos = 0.
+ edge = 0
+ for i in range(count if closed else count + 1):
+ offset = i * step
+ while edge < len(lengths) - 1 and pos + lengths[edge] <= offset:
+ pos += lengths[edge]
+ edge += 1
+ fraction = min(1., (offset - pos) / lengths[edge]) if lengths[edge] else 0.
+ samples.append(chain[edge] + fraction * (chain[edge + 1] - chain[edge]))
+
+ window = max(1, round(max(.07 * radius, 2.5 * pitch) / step))
+ if 4 * window >= len(samples):
+ return False
+ floor = max(math.radians(8), math.atan2(.5 * pitch, window * step))
+ def turn(i, w):
+ before = samples[i] - samples[(i - w) % len(samples)]
+ after = samples[(i + w) % len(samples)] - samples[i]
+ return abs(math.atan2(_cross(before, after), _dot(before, after)))
+
+ positions = range(len(samples)) if closed else range(2 * window, len(samples) - 2 * window)
+ for i in positions:
+ short = turn(i, window)
+ if short > window * step / radius + floor and turn(i, 2 * window) < 1.35 * short:
+ return False
+
+ if closed:
+ radial = [p - center for p in samples]
+ residuals = [abs(v) - radius for v in radial]
+ # An ellipse produces a coherent second harmonic in the radial error,
+ # including when its axes do not line up with the image coordinates.
+ phase = [(v / abs(v)) ** 2 for v in radial]
+ harmonic = 2 * sum(d * z for d, z in zip(residuals, phase)) / count
+ if abs(harmonic) > max(.20 * pitch, .0005 * radius):
+ mean = sum(residuals) / count
+ unexplained = sum((d - mean - _dot(harmonic, z)) ** 2
+ for d, z in zip(residuals, phase)) / count
+ if unexplained < (.6 * abs(harmonic)) ** 2:
+ return False
+ return True
+
+
+def _circle(points, bounds, pitch, tolerance):
+ left, top, right, bottom = bounds
+ width, height = right - left, bottom - top
+ radius = (width + height) / 4
+ error = _confidence(tolerance, radius, pitch)
+ if radius < 5 * pitch or abs(width - height) > 4 * error:
+ return None
+ center = complex((left + right) / 2, (top + bottom) / 2)
+ if not _encloses(points, center):
+ return None
+ # Recover a minimax radius. Include internal extrema along the source
+ # segments, so a polygon inscribed in a circle cannot pass on vertices alone.
+ low, high = math.inf, 0.
+ for a, b in _edges(points):
+ if abs(b - a) > .39 * radius:
+ return None
+ lo, hi = _distances(a, b, center, center)
+ low, high = min(low, lo), max(high, hi)
+ if high - low > 2 * error:
+ return None
+ radius = (high + low) / 2
+ if not _smooth_evidence(points, center, radius, pitch, True):
+ return None
+ return _Band(center, center, radius)
+
+
+def _straight_sides(local, start, end, top, bottom, error):
+ """Check both measured sides across the central span, including long edges."""
+ sides = set()
+ for a, b in _edges(local):
+ if a.real > b.real:
+ a, b = b, a
+ lo, hi = max(start, a.real), min(end, b.real)
+ if lo > hi:
+ continue
+ if a.real == b.real:
+ y0, y1 = a.imag, b.imag
+ else:
+ slope = (b.imag - a.imag) / (b.real - a.real)
+ y0 = a.imag + slope * (lo - a.real)
+ y1 = a.imag + slope * (hi - a.real)
+ side = min((top, bottom), key=lambda y: abs(y0 - y))
+ if max(abs(y0 - side), abs(y1 - side)) > error:
+ return False
+ sides.add(side)
+ return len(sides) == 2
+
+
+def _alpha_capsule(points, pixel, pitch, tolerance):
+ capsule = _capsule(points, pixel, pitch, tolerance)
+ if capsule:
+ return capsule
+ # A rotated raster can split a long straight side into many small edges.
+ # Area moments supply an orientation hypothesis for the same capsule test.
+ moments = moment_ellipse(points)
+ if moments and moments.major - moments.minor >= 3 * pitch:
+ return _capsule(points, pixel, pitch, tolerance, moments.axis)
+ return None
+
+
+def _capsule(points, pixel, pitch, tolerance, measured_axis=None):
+ # Recover the four true joins together from the side direction and support
+ # extrema, then validate the entire original outline.
+ a, b = max(_edges(points), key=lambda edge: abs(edge[1] - edge[0]))
+ length = abs(b - a)
+ if measured_axis is None and length < 10 * pitch:
+ return None
+ axis = measured_axis if measured_axis is not None else (b - a) / length
+ local = [(p - a) * axis.conjugate() for p in points]
+ left, top, right, bottom = _bounds(local)
+ radius = (bottom - top) / 2
+ straight = right - left - 2 * radius
+ if radius < 5 * pitch or straight < 8 * pitch:
+ return None
+ if measured_axis is None:
+ if length < .55 * straight:
+ return None
+ else:
+ inset = radius + .15 * straight
+ if not _straight_sides(local, left + inset, right - inset, top, bottom,
+ min(tolerance, .25 * pitch)):
+ return None
+ first = a + axis * complex(left + radius, (top + bottom) / 2)
+ last = first + straight * axis
+ band = _Band(first, last, radius)
+ if not _encloses(points, (first + last) / 2):
+ return None
+ if not band.follows(_edges(points), _confidence(tolerance, radius, pitch)):
+ return None
+ # A polygonal cap can lie inside the radial tolerance while retaining
+ # repeatable corners. Apply the same two-window check on each circular half.
+ for center, direction in ((first, -axis), (last, axis)):
+ beyond = [_dot(p - center, direction) > 0 for p in points]
+ start = next((i for i in range(len(points)) if beyond[i] and not beyond[i - 1]), None)
+ if start is None:
+ return None
+ cap = []
+ for i in range(start, start + len(points)):
+ if not beyond[i % len(points)]:
+ break
+ cap.append(points[i % len(points)])
+ if len(cap) < 6 or not _smooth_evidence(cap, center, radius, pitch, False):
+ return None
+ # In image coordinates, the sign of the algebraic area defines the
+ # winding. The two circular halves share exact tangent points with the sides.
+ positive = sum(_cross(p - a, q - a) for p, q in _edges(points)) > 0
+ normal = (-1j if positive else 1j) * axis * radius
+ p, q, r, s = map(pixel, (first + normal, last + normal, last - normal, first - normal))
+ return band, (Line(p, q), Arc(q, pixel(last + axis * radius), r),
+ Line(r, s), Arc(s, pixel(first - axis * radius), p))
+
+
+class _Boundary:
+ """Interpolate witnesses at fixed physical arclengths on a raw outline."""
+ def __init__(self, points):
+ self.points = points
+ self.lengths = [0.]
+ for a, b in zip(points, points[1:]):
+ self.lengths.append(self.lengths[-1] + abs(b - a))
+ self.length = self.lengths[-1]
+
+ def at(self, distance):
+ i = min(len(self.points) - 2, bisect_right(self.lengths, distance) - 1)
+ a, b = self.points[i:i + 2]
+ length = self.lengths[i + 1] - self.lengths[i]
+ return a + (b - a) * ((distance - self.lengths[i]) / length) if length else a
+
+ def turn(self, at, window, cyclic=False):
+ left, right = at - window, at + window
+ if cyclic:
+ left %= self.length
+ right %= self.length
+ p = self.at(at)
+ u, v = p - self.at(left), self.at(right) - p
+ return math.atan2(_cross(u, v), _dot(u, v))
+
+
+def _smooth_local_arc(points, center, radius, pitch, error):
+ if _smooth_evidence(points, center, radius, pitch, False):
+ return True
+ # In a JPEG a single threshold crossing can create a kink at a two-pixel
+ # window. It must persist above circular curvature at a second, wider scale.
+ # This alternative requires tighter radial support and rejects straight
+ # facets even when their edges were subdivided in the original polyline.
+ band = _Band(center, center, radius)
+ if not band.follows(zip(points, points[1:]), min(error, .52 * pitch)):
+ return False
+ straight = 0j
+ previous = 0j
+ for a, b in zip(points, points[1:]):
+ delta = b - a
+ if not delta:
+ continue
+ if straight and (_dot(straight, delta) <= 0 or
+ abs(_cross(straight, delta)) > .001 * abs(straight) * abs(delta)):
+ previous, straight = straight, 0j
+ straight += delta
+ if min(abs(previous), abs(straight)) > .18 * radius:
+ if abs(math.atan2(_cross(previous, straight), _dot(previous, straight))) > math.radians(12):
+ return False
+ boundary = _Boundary(points)
+ window = max(3 * pitch, .07 * radius)
+ if 4 * window >= boundary.length:
+ return False
+ for i in range(129):
+ at = 2 * window + (boundary.length - 4 * window) * i / 128
+ short = abs(boundary.turn(at, window))
+ if short <= window / radius + max(.14, math.atan2(.5 * pitch, window)):
+ continue
+ wide = abs(boundary.turn(at, 2 * window))
+ if wide < 1.4 * short and wide > 2 * window / radius + max(.15, math.atan2(.65 * pitch, 2 * window)):
+ return False
+ return True
+
+
+@dataclass(frozen=True)
+class _ArcBand(_Band):
+ """Clearance to the finite arc, including its endpoint disks."""
+ start: complex
+ end: complex
+ sweep: float
+
+ def covers(self, direction):
+ sign = 1 if self.sweep > 0 else -1
+ slack = 1e-12 * self.radius * abs(direction)
+ after = sign * _cross(self.start - self.first, direction) >= -slack
+ before = sign * _cross(direction, self.end - self.first) >= -slack
+ return (after and before) if abs(self.sweep) <= math.pi else (after or before)
+
+ @cached_property
+ def box(self):
+ points = [self.start, self.end]
+ points.extend(self.first + u * self.radius for u in (1, 1j, -1, -1j) if self.covers(u))
+ return _bounds(points)
+
+ def near(self, bounds, padding):
+ l, t, r, b = self.box
+ return l - padding <= bounds[2] and t - padding <= bounds[3] and r + padding >= bounds[0] and b + padding >= bounds[1]
+
+ def clear(self, edges, padding):
+ # The nearest pair between an arc and a segment is at an endpoint, a
+ # shared intersection, or an interior normal perpendicular to the line.
+ center, radius = self.first, self.radius
+ for a, b in edges:
+ if not self.near((min(a.real, b.real), min(a.imag, b.imag),
+ max(a.real, b.real), max(a.imag, b.imag)), padding):
+ continue
+ if min(_distance(self.start, a, b), _distance(self.end, a, b)) <= padding:
+ return False
+ u, v = a - center, b - center
+ if any(abs(abs(p) - radius) <= padding and self.covers(p) for p in (u, v)):
+ return False
+ d = b - a
+ length2 = _dot(d, d)
+ if not length2:
+ continue
+ at = -_dot(u, d) / length2
+ foot = u + at * d
+ if 0 < at < 1 and abs(abs(foot) - radius) <= padding and self.covers(foot):
+ return False
+ squared = radius * radius - _dot(foot, foot)
+ if squared >= 0:
+ offset = math.sqrt(squared / length2)
+ for t in (at - offset, at + offset):
+ if 0 <= t <= 1 and self.covers(u + t * d):
+ return False
+ return True
+
+ def clear_of_arc(self, other, padding):
+ if not self.near(other.box, padding):
+ return True
+ shared = {self.start, self.end} & {other.start, other.end}
+ if not shared:
+ # Chords cover the finite arc with a known sagitta. Include it in
+ # the clearance budget instead of testing two full supporting disks.
+ sag = min(padding / 4, .05 * other.radius)
+ step = 4 * math.asin(math.sqrt(sag / (2 * other.radius)))
+ if step * 1024 < abs(other.sweep):
+ return False
+ steps = max(2, math.ceil(abs(other.sweep) / step))
+ start = other.start - other.first
+ points = [other.first + start * complex(math.cos(other.sweep * i / steps),
+ math.sin(other.sweep * i / steps)) for i in range(steps + 1)]
+ return self.clear(zip(points, points[1:]), padding + sag)
+ # Shared endpoint is already one intersection. Reflect it across the
+ # line of centres to find the only possible second intersection.
+ delta = other.first - self.first
+ if abs(delta) < 1e-10 * max(self.radius, other.radius):
+ return False
+ for node in shared:
+ u = node - self.first
+ second = self.first + 2 * delta * (_dot(u, delta) / _dot(delta, delta)) - u
+ if (all(abs(second - p) > 1e-9 * max(self.radius, other.radius) for p in shared)
+ and self.covers(second - self.first) and other.covers(second - other.first)):
+ return False
+ return True
+
+
+def _contains_flat(points, radius, pitch):
+ # A true circle spanning this chord would bow visibly away from its line.
+ # Preserve measurable straight shelves even if the whole arc would still
+ # satisfy the coarser UI error budget (for example the foot of a letter D).
+ length = max(.44 * radius, 3 * pitch)
+ straight_error = min(.055 * pitch, .15 * (length * length / (8 * radius)))
+ boundary = _Boundary(points)
+ for i, start in enumerate(boundary.lengths):
+ if start + length > boundary.length:
+ break
+ end = boundary.at(start + length)
+ if _distance(boundary.at(start + length / 2), points[i], end) > straight_error:
+ continue
+ stop = bisect_right(boundary.lengths, start + length)
+ if all(_distance(points[j], points[i], end) <= straight_error for j in range(i + 1, stop)):
+ return True
+ return False
+
+
+def _certify_arc_source(points, center, start, sweep, tolerance):
+ """Continuous correspondence from the measured span to the anchored arc."""
+ radius = abs(start - center)
+ unit = start - center
+ def at(t):
+ return center + unit * complex(math.cos(t), math.sin(t))
+
+ def paired(p, q, first, last, depth):
+ error = max(abs(at(first) - p), abs(at(last) - q))
+ # Second derivative bound for the circle relative to its chord.
+ if error + radius * (last - first) ** 2 / 8 <= tolerance:
+ return True
+ if error > tolerance or depth >= 10:
+ return False
+ mid, angle = (p + q) / 2, (first + last) / 2
+ return paired(p, mid, first, angle, depth + 1) and paired(mid, q, angle, last, depth + 1)
+
+ direction = 1 if sweep > 0 else -1
+ first = 0.
+ previous = points[0] - center
+ angle = math.atan2(_cross(unit, previous), _dot(unit, previous))
+ for i, (p, q) in enumerate(zip(points, points[1:]), 1):
+ next_vector = q - center
+ angle += math.atan2(_cross(previous, next_vector), _dot(previous, next_vector))
+ last = sweep if i == len(points) - 1 else direction * min(abs(sweep), max(0., direction * angle))
+ if not paired(p, q, first, last, 0):
+ return False
+ first, previous = last, next_vector
+ return True
+
+
+def _circle_through_ends(points, a, b):
+ chord = b - a
+ middle = (a + b) / 2
+ normal = 1j * chord / abs(chord)
+ half_squared = abs(chord / 2) ** 2
+ # Algebraic least squares on the perpendicular bisector fixes both end
+ # nodes. Weight by represented length to remove dependence on corner count.
+ total = numerator = 0.
+ for i in range(1, len(points) - 1):
+ p = points[i] - middle
+ weight = abs(points[i] - points[i - 1]) + abs(points[i + 1] - points[i])
+ projection = 2 * _dot(p, normal)
+ total += weight * projection ** 2
+ numerator += weight * projection * (_dot(p, p) - half_squared)
+ if total == 0:
+ return None
+ center = middle + normal * (numerator / total)
+ return center, abs(a - center)
+
+
+def _arc(points, pitch, tolerance, fixed_ends=None):
+ a, b = fixed_ends or (points[0], points[-1])
+ if abs(b - a) < 4 * pitch:
+ return None
+ fit = _circle_through_ends(points, a, b)
+ if fit is None:
+ return None
+ center, radius = fit
+ band = _Band(center, center, radius)
+ if radius < 5 * pitch:
+ return None
+ error = _confidence(tolerance, radius, pitch)
+ if not band.follows(zip(points, points[1:]), error):
+ return None
+
+ angles = [math.atan2(_cross(p - center, q - center), _dot(p - center, q - center))
+ for p, q in zip(points, points[1:])]
+ sweep = sum(angles)
+ if not math.radians(50) <= abs(sweep) < math.tau - .05:
+ return None
+ if max(map(abs, angles)) > .40 or (1 - math.cos(sweep / 2)) * radius < 2 * pitch:
+ return None
+ # Continuous angular coverage plus the radial band bounds both directed
+ # distances. Reject excursions outside the finite arc at its ends.
+ position = 0.
+ direction = 1 if sweep > 0 else -1
+ for angle in angles:
+ position += direction * angle
+ if not -1e-10 <= position <= abs(sweep) + 1e-10:
+ return None
+ if _contains_flat(points, radius, pitch) or not _smooth_local_arc(points, center, radius, pitch, error):
+ return None
+ if fixed_ends:
+ angle = math.atan2(_cross(a - center, b - center), _dot(a - center, b - center))
+ directed = direction * ((direction * angle) % math.tau)
+ if abs(directed - sweep) >= .5 or not _certify_arc_source(points, center, a, directed, error):
+ return None
+ sweep = directed
+ midpoint = center + (a - center) * complex(math.cos(sweep / 2), math.sin(sweep / 2))
+ return _ArcBand(center, center, radius, a, b, sweep), midpoint, sweep
+
+
+def _joins_once(band, sweep, a, b, shared, start, end):
+ """An incident anchor line may only meet the circular arc at their node."""
+ other = b if a == shared else a
+ delta = other - shared
+ t = -2 * _dot(shared - band.first, delta) / _dot(delta, delta)
+ if not 1e-9 < t <= 1 + 1e-9:
+ return True
+ v = shared + t * delta - band.first
+ u = start - band.first
+ angle = math.atan2(_cross(u, v), _dot(u, v))
+ along = (math.copysign(1, sweep) * angle) % math.tau
+ # A chord joining both endpoints is the straight side of a circular segment.
+ if other in (start, end) and abs(t - 1) < 1e-9:
+ return True
+ return along > abs(sweep) + 1e-9
+
+
+def _clear_replacement(band, edges, raw_span, old_span, pitch, tolerance):
+ # At a pointed join two distinct branches may already be much closer than
+ # twice the tolerance. Certify the *actual* local displacement in that case.
+ # Radially project each source segment to the fitted arc. Its entire swept
+ # region is enclosed by that finite projected arc plus the exact maximum
+ # radial deviation of the segment. This bound vanishes at fixed endpoints.
+ near = [edge for edge in edges if not band.clear((edge,), 2 * tolerance)]
+ if not near:
+ return True
+ if not band.clear(near, 1e-10 * pitch):
+ return False
+ center, radius = band.first, band.radius
+ for chain in (raw_span, old_span):
+ for a, b in zip(chain, chain[1:]):
+ pieces = max(1, math.ceil(abs(b - a) / (2 * pitch)))
+ for n in range(pieces):
+ p = a + (b - a) * (n / pieces)
+ q = a + (b - a) * ((n + 1) / pieces)
+ u, v = p - center, q - center
+ if min(abs(u), abs(v)) <= 1e-10 * pitch:
+ return False
+ low, high = _distances(p, q, center, center)
+ drift = max(radius - low, high - radius, 0.) + 1e-10 * pitch
+ start = center + u * (radius / abs(u))
+ end = center + v * (radius / abs(v))
+ sweep = math.atan2(_cross(u, v), _dot(u, v))
+ if abs(sweep) < 1e-12:
+ if any(_distance(start, x, y) <= drift for x, y in near):
+ return False
+ else:
+ part = _ArcBand(center, center, radius, start, end, sweep)
+ if not part.clear(near, drift):
+ return False
+ return True
+
+
+def _arc_intervals(raw, points, order, pitch, tolerance):
+ anchors = []
+ lengths = sorted(abs(b - a) for a, b in _edges(points))
+ minimum_run = max(10 * pitch, 1.8 * lengths[len(lengths) // 2])
+ for i, (a, b) in enumerate(_edges(points)):
+ low, high = order[i], order[(i + 1) % len(order)]
+ span = raw[low:high + 1] if low < high else raw[low:] + raw[:high + 1]
+ # A supported straight run makes either endpoint a structural join.
+ if abs(b - a) >= minimum_run and all(_distance(p, a, b) <= min(tolerance, .22 * pitch) for p in span):
+ anchors.append(i)
+ # At a genuine corner the local turn persists on two physical windows.
+ # Include sharp inward joins between two otherwise convex curved sections.
+ boundary = _Boundary(raw + raw[:1])
+ edges = [b - a for a, b in _edges(points)]
+ turns = [math.atan2(_cross(edges[i - 1], e), _dot(edges[i - 1], e)) for i, e in enumerate(edges)]
+ corners = set()
+ for i, turn in enumerate(turns):
+ opposed = turn * turns[i - 1] < 0 and turn * turns[(i + 1) % len(turns)] < 0
+ if abs(turn) < math.radians(18 if opposed else 38):
+ continue
+ pos = boundary.lengths[order[i]]
+ small = boundary.turn(pos, 2.1 * pitch, True)
+ large = boundary.turn(pos, 4.2 * pitch, True)
+ if small * large <= 0 or abs(small) < .64 * abs(large):
+ continue
+ if (abs(small) >= math.radians(26) and abs(large) >= math.radians(34)) or (
+ opposed and small * turn > 0 and abs(large) > math.radians(16)):
+ corners.add(i)
+
+ count = len(points)
+ knots = sorted(corners | set(anchors) | {(i + 1) % count for i in anchors})
+ intervals = {}
+ if len(knots) > 1:
+ intervals.update((pair, False) for pair in _edges(knots))
+ # A straight side and a major arc form a circular segment. Baseline
+ # tessellation may create additional apparent corners near that side.
+ for before, after in _edges(anchors):
+ intervals[(before + 1) % count, after] = False
+
+ # A corner can lead through a straight side into a circular lobe, then
+ # blend into a free curve. Search a bounded neighbourhood of the structural
+ # joins. Floating endpoints require a long sweep and an actual transition
+ # at the neighbouring raw data. An entirely smooth loop has no search seed.
+ for left, right in _edges(knots):
+ span_length = (right - left) % count or count
+ if span_length < 6:
+ continue
+ allowance = min(5, span_length // 3)
+ for trim_left in range(allowance + 1):
+ for trim_right in range(allowance + 1):
+ if not 0 < trim_left + trim_right <= span_length // 2:
+ continue
+ start = (left + trim_left) % count
+ end = (right - trim_right) % count
+ # One physical join must still be a corner or the far end of
+ # a substantial approach segment belonging to that corner.
+ if (trim_left > 0 and trim_right > 0 and
+ not (trim_left == 1 and abs(edges[left]) >= minimum_run) and
+ not (trim_right == 1 and abs(edges[end]) >= minimum_run)):
+ continue
+ intervals.setdefault((start, end), True)
+
+ candidates = sorted(intervals, key=lambda pair: (-((pair[1] - pair[0]) % count), pair))
+ return corners, set(knots), [(a, b, 'lobe' if intervals[a, b] else 'full') for a, b in candidates]
+
+
+
+def _bounded_lobe(band, sweep, raw, order, knots, start, end, pitch, tolerance):
+ count = len(order)
+ if abs(sweep) < math.radians(120) or band.radius < 8 * pitch:
+ return False
+ # A floating endpoint must mark a departure from the same
+ # supporting circle. Do not select an arbitrary subarc on an oval.
+ confidence = _confidence(tolerance, band.radius, pitch)
+ for node, previous in ((start, True), (end, False)):
+ if node in knots:
+ continue
+ low = order[(node - 1) % count] if previous else order[node]
+ high = order[node] if previous else order[(node + 1) % count]
+ extension = raw[low:high + 1] if low < high else raw[low:] + raw[:high + 1]
+ if band.follows(zip(extension, extension[1:]), confidence):
+ return False
+ return True
+
+
+def _corner_pair_intervals(knots, corners, count):
+ # Preserve the measured joins at both ends. Try at most four interiors
+ # per corner pair, after all ordinary, corner-anchored fits have run.
+ spans = []
+ for left, right in _edges(sorted(knots)):
+ length = (right - left) % count
+ if left not in corners or right not in corners or length < 8:
+ continue
+ for before in (1, 2):
+ for after in (1, 2):
+ size = length - before - after
+ if size >= 6:
+ spans.append((-size, (left + before) % count, (right - after) % count))
+ return [(start, end, 'interior') for _, start, end in sorted(spans)]
+
+
+def _stable_interior(points, band, sweep, pitch, tolerance):
+ # Neither endpoint is a structural join. Demand a long, well-resolved
+ # circular run with independently repeatable centre and radius on both
+ # sides. A threshold-distorted corner can stay on its original short edges.
+ if abs(sweep) < math.radians(150) or band.radius < 10 * pitch or len(points) < 24:
+ return False
+ boundary = _Boundary(points)
+ # The central window also tests a symmetric oval: its two end estimates
+ # can agree with each other while its centre section has different curvature.
+ uncertainty = min(tolerance, pitch)
+ for lower, upper, factor in ((0., .65, .75), (.35, 1., .75), (.20, .80, 1.25)):
+ lo = 0 if lower == 0 else bisect_right(boundary.lengths, lower * boundary.length)
+ hi = len(points) if upper == 1 else bisect_right(boundary.lengths, upper * boundary.length) + 1
+ section = points[lo:hi]
+ allowance = factor * uncertainty
+ if len(section) < 8 or abs(section[-1] - section[0]) < 4 * pitch:
+ return False
+ estimate = _circle_through_ends(section, section[0], section[-1])
+ if estimate is None:
+ return False
+ center, radius = estimate
+ if max(abs(center - band.first), abs(radius - band.radius)) > allowance:
+ return False
+ return True
+
+
+def _clear_of_remainder(band, sweep, raw, points, order, raw_span, span, start, end, pitch, tolerance):
+ count = len(order)
+ before, after = (start - 1) % count, end
+ covered = span | {before, after}
+ old_span = points[start:end + 1] if start < end else points[start:] + points[:end + 1]
+ outside = [(a, b) for i, (a, b) in enumerate(_edges(points)) if i not in covered]
+ if before != after:
+ lo, hi = order[(after + 1) % count], order[before]
+ remaining = raw[lo:hi + 1] if lo <= hi else raw[lo:] + raw[:hi + 1]
+ outside.extend(zip(remaining, remaining[1:]))
+ if not _clear_replacement(band, outside, raw_span, old_span, pitch, tolerance):
+ return False
+ if any(not _joins_once(band, sweep, points[edge], points[(edge + 1) % count],
+ points[shared], points[start], points[end])
+ for edge, shared in ((before, start), (after, end)) if points[edge] != points[(edge + 1) % count]):
+ return False
+ return True
+
+
+def _mixed(raw, ring, physical, pixel, pitch, tolerance, isolated, recover_joins=False):
+ points = tuple(map(physical, ring))
+ indices = {p: i for i, p in enumerate(raw)}
+ order = [indices[p] for p in points]
+ corners, knots, candidates = _arc_intervals(raw, points, order, pitch, tolerance)
+ count = len(ring)
+ if recover_joins:
+ candidates.extend(_corner_pair_intervals(knots, corners, count))
+ accepted, used, occupied = {}, [], set()
+ for start, end, kind in candidates:
+ length = (end - start) % count
+ if length < 3:
+ continue
+ span = {(start + step) % count for step in range(length)}
+ if span & occupied or (span - {start}) & corners:
+ continue
+ lo, hi = order[start], order[end]
+ raw_span = raw[lo:hi + 1] if lo < hi else raw[lo:] + raw[:hi + 1]
+ fitted = _arc(raw_span, pitch, tolerance)
+ if not fitted:
+ continue
+ band, midpoint, sweep = fitted
+ if kind == 'interior' and not _stable_interior(raw_span, band, sweep, pitch, tolerance):
+ continue
+ if kind == 'lobe' and not _bounded_lobe(band, sweep, raw, order, knots, start, end, pitch, tolerance):
+ continue
+ if not _clear_of_remainder(band, sweep, raw, points, order, raw_span, span, start, end, pitch, tolerance):
+ continue
+ if any(not band.clear_of_arc(other, 2 * tolerance) for other in used) or not isolated(band):
+ continue
+ used.append(band)
+ occupied.update(span)
+ accepted[start] = end, Arc(ring[start], pixel(midpoint), ring[end])
+ if not accepted:
+ return None
+ path = []
+ pos = initial = min(accepted)
+ while True:
+ if pos in accepted:
+ pos, arc = accepted[pos]
+ path.append(arc)
+ else:
+ following = (pos + 1) % count
+ path.append(Line(ring[pos], ring[following]))
+ pos = following
+ if pos == initial:
+ return tuple(path)
+
+
+@dataclass(frozen=True)
+class _StraightBand:
+ start: complex
+ end: complex
+
+ def near(self, bounds, padding):
+ x1, y1, x2, y2 = bounds
+ return (min(self.start.real, self.end.real) - padding <= x2 and
+ max(self.start.real, self.end.real) + padding >= x1 and
+ min(self.start.imag, self.end.imag) - padding <= y2 and
+ max(self.start.imag, self.end.imag) + padding >= y1)
+
+ def clear(self, edges, padding):
+ return all(_distances(a, b, self.start, self.end)[0] > padding for a, b in edges)
+
+
+class _MeasuredRing:
+ """Map unchanged legacy nodes to corresponding points on the alpha level."""
+ def __init__(self, source, ring, crossings, physical):
+ mask_positions = {}
+ index = 0
+ for a, b in _edges(source):
+ mask_positions[a] = index
+ index += abs(b[0] - a[0]) + abs(b[1] - a[1])
+ self.positions = [mask_positions[p] for p in ring]
+ self.crossings = tuple(map(physical, crossings))
+ self.legacy = tuple(map(physical, ring))
+ self.source_indices = {p: i for i, p in enumerate(crossings)}
+ self.joins = []
+ for point, i in zip(self.legacy, self.positions):
+ a, b = self.crossings[i - 1], self.crossings[i]
+ direction = b - a
+ norm = _dot(direction, direction)
+ fraction = min(1., max(0., _dot(point - a, direction) / norm)) if norm else 0.
+ self.joins.append(a + fraction * direction)
+
+ def span(self, start, end):
+ first, last = self.positions[start], self.positions[end]
+ inner = self.crossings[first:last] if first < last else self.crossings[first:] + self.crossings[:last]
+ return (self.joins[start],) + inner + (self.joins[end],)
+
+ def anchors(self, source_point, reach):
+ crossing = self.source_indices[source_point]
+ index = bisect_right(self.positions, crossing)
+ count = len(self.positions)
+ candidates = {(index + offset) % count for offset in (-2, -1, 0, 1)}
+ return sorted((i for i in candidates if abs(self.legacy[i] - self.crossings[crossing]) <= reach),
+ key=lambda i: (abs(self.legacy[i] - self.crossings[crossing]), i))
+
+ def line_certified(self, start, end, tolerance):
+ # Distances to the chord are convex along each source segment. Coverage
+ # of its interior follows by continuous projection, with paired ends.
+ a, b = self.legacy[start], self.legacy[end]
+ if max(abs(self.joins[start] - a), abs(self.joins[end] - b)) > tolerance:
+ return False
+ return all(_distance(p, a, b) <= tolerance for p in self.span(start, end))
+
+
+def _splice_alpha_arcs(proposal, measured, source, ring, physical, pixel, pitch, tolerance, isolated):
+ raw = tuple(map(physical, source))
+ points = measured.legacy
+ order_by_point = {p: i for i, p in enumerate(source)}
+ order = [order_by_point[p] for p in ring]
+ accepted, used, occupied = {}, [], set()
+ count = len(ring)
+ for proposal_arc in proposal:
+ if not isinstance(proposal_arc, Arc):
+ continue
+ starts = measured.anchors(proposal_arc.start, 6 * pitch)
+ ends = measured.anchors(proposal_arc.end, 6 * pitch)
+ selected = False
+ for start in starts:
+ for end in ends:
+ length = (end - start) % count
+ if length < 3 or length == count - 1:
+ continue
+ span = {(start + step) % count for step in range(length)}
+ if occupied & span:
+ continue
+ fitted = _arc(measured.span(start, end), pitch, tolerance, (points[start], points[end]))
+ if not fitted:
+ continue
+ band, midpoint, sweep = fitted
+ lo, hi = order[start], order[end]
+ legacy = raw[lo:hi + 1] if lo < hi else raw[lo:] + raw[:hi + 1]
+ if not _clear_of_remainder(band, sweep, raw, points, order, legacy, span, start, end, pitch, tolerance):
+ continue
+ if any(not band.clear_of_arc(other, 2 * tolerance) for other in used) or not isolated(band):
+ continue
+ accepted[start] = end, Arc(ring[start], pixel(midpoint), ring[end])
+ occupied.update(span)
+ used.append(band)
+ selected = True
+ break
+ if selected:
+ break
+ if not accepted:
+ return None
+ if any(not measured.line_certified(i, (i + 1) % count, tolerance) for i in range(count) if i not in occupied):
+ return None
+ path = []
+ pos = first = min(accepted)
+ while True:
+ if pos in accepted:
+ pos, arc = accepted[pos]
+ path.append(arc)
+ else:
+ following = (pos + 1) % count
+ path.append(Line(ring[pos], ring[following]))
+ pos = following
+ if pos == first:
+ return tuple(path)
+
+
+def _alpha_segment(reference, measured, provisional, physical, pixel, pitch, tolerance, isolated):
+ # A rotated raster chord may end one scanline past its true intersection
+ # with the circular side. Only search next to a single dominant flat;
+ # every trial must explain the *whole* outline as two connected curves.
+ edges = sorted(((abs(physical(b) - physical(a)), a, b) for a, b in _edges(provisional)), reverse=True)
+ length, a, b = edges[0]
+ if length < max(12 * pitch, 2.4 * edges[1][0]):
+ return None
+ first, last = reference.index(a), reference.index(b)
+ count = len(measured)
+ shifts = sorted(((u, v) for u in (-2, -1, 0, 1, 2) for v in (-2, -1, 0, 1, 2)),
+ key=lambda pair: abs(pair[0]) + abs(pair[1]))
+ for u, v in shifts:
+ left, right = (first + u) % count, (last + v) % count
+ p, q = measured[left], measured[right]
+ if max(abs(p - measured[first]), abs(q - measured[last])) > 2.5 * pitch:
+ continue
+ flat = measured[left:right + 1] if left < right else measured[left:] + measured[:right + 1]
+ if any(_distance(x, p, q) > min(tolerance, .5 * pitch) for x in flat):
+ continue
+ curved = measured[right:left + 1] if right < left else measured[right:] + measured[:left + 1]
+ fitted = _arc(curved, pitch, tolerance)
+ if fitted and abs(fitted[2]) > math.pi and isolated(fitted[0]) and isolated(_StraightBand(p, q)):
+ return (Line(reference[left], reference[right]),
+ Arc(reference[right], pixel(fitted[1]), reference[left]))
+ return None
+
+
+def _alpha_mixed(boundary, source, ring, sx, sy, physical, pixel, pitch, tolerance, isolated):
+ # This additional fitting pass is ring-local. Keep the existing sketch
+ # representation if a highly detailed contour exceeds its analysis budget.
+ if len(boundary.outline) > 16000:
+ return None
+ from .image_trace import _simplify
+ provisional, = _simplify((boundary.outline,), sx, sy, tolerance, False)
+ measured_points = tuple(map(physical, boundary.outline))
+ proposal = _mixed(measured_points, provisional, physical, pixel, pitch, tolerance, isolated)
+ if not proposal:
+ return _alpha_segment(boundary.outline, measured_points, provisional, physical, pixel,
+ pitch, tolerance, isolated)
+ if len(proposal) == 2 and sum(isinstance(p, Line) for p in proposal) == 1:
+ # A circular segment is one complete, certified profile. _mixed has
+ # tested the arc and its two meetings with the chord. Independently
+ # verify the chord against the measured boundary and other profiles.
+ line = next(p for p in proposal if isinstance(p, Line))
+ start, end = boundary.outline.index(line.start), boundary.outline.index(line.end)
+ portion = measured_points[start:end + 1] if start < end else measured_points[start:] + measured_points[:end + 1]
+ a, b = physical(line.start), physical(line.end)
+ if all(_distance(p, a, b) <= tolerance for p in portion) and isolated(_StraightBand(a, b)):
+ return proposal
+ measured = _MeasuredRing(source, ring, boundary.crossings, physical)
+ return _splice_alpha_arcs(proposal, measured, source, ring, physical, pixel, pitch, tolerance, isolated)
+
+
+def _index(boxes, indices):
+ """Balanced bounding-box tree for clearance checks on crowded sheets."""
+ left = min(boxes[i][0] for i in indices)
+ top = min(boxes[i][1] for i in indices)
+ right = max(boxes[i][2] for i in indices)
+ bottom = max(boxes[i][3] for i in indices)
+ bounds = left, top, right, bottom
+ if len(indices) <= 12:
+ return bounds, indices, ()
+ axis = 0 if right - left >= bottom - top else 1
+ indices = sorted(indices, key=lambda i: boxes[i][axis] + boxes[i][axis + 2])
+ half = len(indices) // 2
+ return bounds, (), (_index(boxes, indices[:half]), _index(boxes, indices[half:]))
+
+
+def _nearby(node, band, padding):
+ bounds, indices, children = node
+ if band.near(bounds, padding):
+ yield from indices
+ for child in children:
+ yield from _nearby(child, band, padding)
+
+
+def recognize(analysis, result, sx, sy, tolerance, circles, arcs, ellipses=False):
+ """Return typed, closed paths in surviving ring order; retain exact fallback."""
+ if not (circles or arcs or ellipses) or tolerance <= 0 or not result.rings:
+ return result
+
+ def physical(p):
+ return complex(p[0] * sx, p[1] * sy)
+
+ def pixel(p):
+ return p.real / sx, p.imag / sy
+
+ # Simplification preserves vertex order, including when a group's area
+ # filter omits that group and all its holes. Do not match on shared points.
+ raw_rings, source_rings = [], []
+ for group in analysis.components:
+ for original in group:
+ if len(raw_rings) == len(result.rings):
+ break
+ it = iter(original)
+ if all(p in it for p in result.rings[len(raw_rings)]):
+ raw_rings.append(tuple(map(physical, original)))
+ source_rings.append(original)
+ if len(raw_rings) != len(result.rings):
+ return result
+
+ pitch = min(sx, sy)
+ boxes = list(map(_bounds, raw_rings))
+ paths = []
+ index = None
+ for i, (raw, ring) in enumerate(zip(raw_rings, result.rings)):
+ def isolated(band, alpha_shift=0.):
+ # Two fitted boundaries may each move by the tolerance. Keep a
+ # corridor around each unchanged raw and simplified neighbour.
+ nonlocal index
+ if index is None:
+ index = _index(boxes, range(len(boxes)))
+ travel = getattr(band, 'error_bound', tolerance) + alpha_shift
+ # Every alpha crossing stays within half a pixel of its original
+ # edge midpoint. In each dual cell both boundary paths can be
+ # paired within the half-diagonal. Account for both fitted rings
+ # against the legacy mask, even when both alpha outlines move.
+ raw_clearance = travel + tolerance + alpha_shift
+ baseline_clearance = travel if hasattr(band, 'error_bound') else raw_clearance
+ for j in _nearby(index, band, raw_clearance):
+ if i == j or not band.near(boxes[j], raw_clearance):
+ continue
+ if not band.clear(_edges(raw_rings[j]), raw_clearance):
+ return False
+ baseline = tuple(map(physical, result.rings[j]))
+ if not band.clear(_edges(baseline), baseline_clearance):
+ return False
+ return True
+
+ path = None
+ if len(raw) >= 16 and len(ring) > 4:
+ source = source_rings[i]
+ boundary = analysis.alpha_measurements(source)
+ reference = tuple(map(physical, boundary.outline)) if boundary else raw
+ shift = math.hypot(sx, sy) / 2 if boundary else 0.
+
+ def reference_isolated(band):
+ return isolated(band, shift)
+
+ circle = _circle(reference, _bounds(reference) if boundary else boxes[i], pitch, tolerance)
+ if circle:
+ if circles and reference_isolated(circle):
+ path = (Circle(pixel(circle.first), circle.radius),)
+ elif ellipses:
+ oval = fit_ellipse(reference, pitch, tolerance)
+ if oval and reference_isolated(oval):
+ path = (Ellipse(pixel(oval.center), pixel(oval.center + oval.major * oval.axis),
+ pixel(oval.center + oval.minor * 1j * oval.axis)),)
+ if not circle and not path and arcs:
+ if boundary:
+ capsule = _alpha_capsule(reference, pixel, pitch, tolerance)
+ if capsule and reference_isolated(capsule[0]):
+ path = capsule[1]
+ elif not capsule:
+ path = _alpha_mixed(boundary, source, ring, sx, sy, physical, pixel,
+ pitch, tolerance, reference_isolated)
+ else:
+ capsule = _capsule(raw, pixel, pitch, tolerance)
+ if capsule and isolated(capsule[0]):
+ path = capsule[1]
+ elif not capsule:
+ path = _mixed(raw, ring, physical, pixel, pitch, tolerance, isolated,
+ recover_joins=not analysis.alpha_field)
+ paths.append(path)
+ if not any(paths):
+ return result
+ complete = tuple(path or tuple(Line(a, b) for a, b in _edges(ring))
+ for path, ring in zip(paths, result.rings))
+ return replace(result, paths=complete, sx=sx, sy=sy, tolerance_mm=tolerance)
diff --git a/InsertTo/trace_render.py b/InsertTo/trace_render.py
new file mode 100644
index 0000000..cceb362
--- /dev/null
+++ b/InsertTo/trace_render.py
@@ -0,0 +1,371 @@
+"""Render a raster trace on a sketch plane and insert connected editable sketch curves."""
+
+from collections import defaultdict
+import math
+
+from .frame_link import batch_edit
+from .image_trace import _area
+from .trace_primitives import Arc, Circle, Ellipse, Line
+
+
+def _chord_count(radius, sweep, error):
+ # Sagitta = 2 r sin²(step / 4). Cap the angular step so that even a
+ # subpixel closed curve has a meaningful filled preview.
+ step = min(math.pi / 4, 4 * math.asin(math.sqrt(min(1., error / (2 * radius)))))
+ return max(2, math.ceil(abs(sweep) / step))
+
+
+def _preview_ellipse(ellipse, sx, sy, error):
+ center = complex(*ellipse.center)
+ major = complex(*ellipse.major) - center
+ minor = complex(*ellipse.minor) - center
+ # The physical ellipse is a linear image of the unit circle. Its major
+ # radius bounds the stretch of every chord error, at every orientation.
+ radius = math.hypot(major.real * sx, major.imag * sy)
+ per_quadrant = _chord_count(radius, math.pi / 2, error)
+ points = []
+ for i in range(4 * per_quadrant):
+ angle = i * (math.pi / 2) / per_quadrant
+ p = center + major * math.cos(angle) + minor * math.sin(angle)
+ points.append((p.real, p.imag))
+ return points
+
+
+def _preview_arc(primitive, sx, sy, error):
+ """Sample in final millimetres, then map back to the preview's pixel space."""
+ if isinstance(primitive, Circle):
+ ox, oy = primitive.center
+ radius = primitive.radius
+ angle, sweep = 0., math.tau
+ else:
+ ax, ay = primitive.start
+ bx = (primitive.mid[0] - ax) * sx
+ by = (primitive.mid[1] - ay) * sy
+ cx = (primitive.end[0] - ax) * sx
+ cy = (primitive.end[1] - ay) * sy
+ cross = bx * cy - by * cx
+ if cross == 0:
+ raise ValueError('The traced arc has collinear points.')
+ b2, c2 = bx * bx + by * by, cx * cx + cy * cy
+ ux = (b2 * cy - by * c2) / (2 * cross)
+ uy = (bx * c2 - b2 * cx) / (2 * cross)
+ ox, oy = ax + ux / sx, ay + uy / sy
+ radius = math.hypot(ux, uy)
+ angle = math.atan2(-uy, -ux)
+ end_angle = math.atan2(cy - uy, cx - ux)
+ sweep = (end_angle - angle) % math.tau
+ if cross < 0:
+ sweep -= math.tau
+
+ count = _chord_count(radius, sweep, error)
+ samples = [(ox + radius / sx * math.cos(angle + sweep * i / count),
+ oy + radius / sy * math.sin(angle + sweep * i / count)) for i in range(count)]
+ if isinstance(primitive, Arc):
+ samples[0] = primitive.start
+ return samples
+
+
+def _preview_rings(result):
+ if not getattr(result, 'paths', ()):
+ return result.rings
+ pixel = min(result.sx, result.sy)
+ error = min(.2 * pixel, result.tolerance_mm / 4) if result.tolerance_mm else .2 * pixel
+ rings = []
+ for index, path in enumerate(result.paths):
+ ring = []
+ for primitive in path:
+ if isinstance(primitive, Line):
+ ring.append(primitive.start)
+ elif isinstance(primitive, Ellipse):
+ ring.extend(_preview_ellipse(primitive, result.sx, result.sy, error))
+ else:
+ ring.extend(_preview_arc(primitive, result.sx, result.sy, error))
+ if isinstance(path[0], (Circle, Ellipse)) and result.rings:
+ if (_area(result.rings[index]) < 0) != (_area(ring) < 0):
+ ring.reverse()
+ rings.append(tuple(ring))
+ return tuple(rings)
+
+
+def _fill_mesh(rings):
+ """Split even-odd polygon interiors into trapezoids between vertex heights."""
+ starts = defaultdict(list)
+ levels = set()
+ for ring in rings:
+ for i, (x, y) in enumerate(ring):
+ xx, yy = ring[(i + 1) % len(ring)]
+ if y == yy:
+ continue
+ if yy < y:
+ x, xx, y, yy = xx, x, yy, y
+ starts[y].append((y, yy, x, (xx - x) / (yy - y)))
+ levels.update((y, yy))
+
+ points, indices, active = [], [], []
+ ordered = sorted(levels)
+ for low, high in zip(ordered, ordered[1:]):
+ active = [edge for edge in active if edge[1] > low]
+ active.extend(starts[low])
+ spans = []
+ for y, _, x, slope in active:
+ a = x + (low - y) * slope
+ b = x + (high - y) * slope
+ spans.append(((a + b) / 2, a, b))
+ spans.sort()
+ for (_, al, bl), (_, ar, br) in zip(spans[::2], spans[1::2]):
+ base = len(points)
+ points.extend(((al, low), (ar, low), (br, high), (bl, high)))
+ if ar > al:
+ indices.extend((base, base + 2, base + 1))
+ if br > bl:
+ indices.extend((base, base + 3, base + 2))
+ return points, indices
+
+
+def _coordinates(points):
+ import adsk.fusion
+
+ return adsk.fusion.CustomGraphicsCoordinates.create(
+ [v for x, y in points for v in (x, -y, 0)])
+
+
+def _source_tiles(raster):
+ """Sample pixel centres on a continuous, vertex-coloured triangle grid."""
+ width, height = raster.width, raster.height
+ scale = min(1., (1_000_000 / (width * height)) ** .5, 2048 / max(width, height))
+
+ def axis(size):
+ samples = max(1, round(size * scale))
+ centers = [(i + .5) * size / samples for i in range(samples)]
+ positions = [0., *centers, float(size)]
+ pixels = [0, *(int(v) for v in centers), size - 1]
+ return positions, pixels
+
+ xs, ix = axis(width)
+ ys, iy = axis(height)
+ rgba = raster.rgba
+ # Tile boundaries share a row/column and keep each native index buffer small.
+ for y0 in range(0, len(ys) - 1, 128):
+ y1 = min(y0 + 129, len(ys))
+ for x0 in range(0, len(xs) - 1, 128):
+ x1 = min(x0 + 129, len(xs))
+ cols = x1 - x0
+ colors = bytearray()
+ for row in iy[y0:y1]:
+ start = 4 * (row * width)
+ if width == len(ix) - 2 and x0 > 0 and x1 < len(ix):
+ colors.extend(rgba[start + 4 * (x0 - 1):start + 4 * (x1 - 1)])
+ else:
+ for col in ix[x0:x1]:
+ i = start + 4 * col
+ colors.extend(rgba[i:i + 4])
+ if raster.has_alpha and not any(colors[3::4]):
+ continue
+ coords = [c for y in ys[y0:y1] for x in xs[x0:x1] for c in (x, -y, 0.)]
+ indices = []
+ for row in range(y1 - y0 - 1):
+ for i in range(row * cols, (row + 1) * cols - 1):
+ indices.extend((i, i + cols, i + 1, i + 1, i + cols, i + cols + 1))
+ yield coords, indices, colors
+
+
+def _placed_xy(x, y, target, raster):
+ """Map pixel corners from the upper left to sketch centimetres."""
+ u = target.left_mm + x * target.width_mm / raster.width
+ v = target.bottom_mm + (1 - y / raster.height) * target.height_mm
+ c, s = math.cos(target.rotation), math.sin(target.rotation)
+ return (u * c - v * s) / 10, (u * s + v * c) / 10
+
+
+def _insert_path(curves, path, point):
+ """Yield each native entity in traversal order, sharing each junction once."""
+ if len(path) == 1 and isinstance(path[0], (Circle, Ellipse)):
+ primitive = path[0]
+ if isinstance(primitive, Ellipse):
+ entity = curves.sketchEllipses.add(point(primitive.center), point(primitive.major),
+ point(primitive.minor))
+ else:
+ entity = curves.sketchCircles.addByCenterRadius(point(primitive.center), primitive.radius / 10)
+ if entity is None:
+ raise ValueError(f'Fusion could not create the traced {type(primitive).__name__.lower()}.')
+ yield entity
+ return
+
+ first = previous = None
+ for index, primitive in enumerate(path):
+ start = previous if previous is not None else point(primitive.start)
+ end = first if index + 1 == len(path) else point(primitive.end)
+ reverse = False
+ if isinstance(primitive, Arc):
+ curve = curves.sketchArcs.addByThreePoints(start, point(primitive.mid), end)
+ # Image Y points down. Positive orientation in pixels is clockwise
+ # in sketch space, while Fusion stores every arc counterclockwise.
+ a, b, c = primitive.start, primitive.mid, primitive.end
+ reverse = (b[0] - a[0]) * (c[1] - a[1]) > (b[1] - a[1]) * (c[0] - a[0])
+ else:
+ curve = curves.sketchLines.addByTwoPoints(start, end)
+ if curve is None:
+ raise ValueError('Fusion could not create the traced curve.')
+ if first is None:
+ first = curve.endSketchPoint if reverse else curve.startSketchPoint
+ previous = curve.startSketchPoint if reverse else curve.endSketchPoint
+ yield curve
+
+
+def insert_curves(sketch, target, raster, result):
+ import adsk.core
+
+ def point(pixel):
+ return adsk.core.Point3D.create(*_placed_xy(*pixel, target, raster), 0)
+
+ curves = sketch.sketchCurves
+ paths = getattr(result, 'paths', ())
+ total = sum(map(len, paths or result.rings))
+ if not paths:
+ paths = (tuple(Line(start, ring[(i + 1) % len(ring)])
+ for i, start in enumerate(ring)) for ring in result.rings)
+ progress = None
+ if total >= 200:
+ progress = adsk.core.Application.get().userInterface.createProgressDialog()
+ progress.isCancelButtonShown = True
+ progress.show('Trace Image', 'Creating sketch curves: %v of %m', 0, total, 1)
+ try:
+ completed = 0
+ with batch_edit(sketch):
+ for path in paths:
+ for _ in _insert_path(curves, path, point):
+ completed += 1
+ if progress and (completed % 50 == 0 or completed == total):
+ progress.progressValue = completed
+ adsk.doEvents()
+ if progress.wasCancelled:
+ raise ValueError('Insertion cancelled.')
+ if progress:
+ progress.progressValue = total
+ progress.message = 'Computing sketch profiles…'
+ progress.isCancelButtonShown = False
+ adsk.doEvents()
+ finally:
+ if progress:
+ progress.hide()
+
+
+def _matrix(sketch, target, raster):
+ import adsk.core
+
+ def model(x, y):
+ return sketch.sketchToModelSpace(
+ adsk.core.Point3D.create(*_placed_xy(x, y, target, raster), 0))
+
+ origin = model(0, 0)
+ # Graphics store (x, -y), so +Y points up the image.
+ vx, vy = origin.vectorTo(model(1, 0)), origin.vectorTo(model(0, -1))
+ normal = vx.crossProduct(vy)
+ normal.normalize()
+ cells = []
+ for row in zip(vx.asArray(), vy.asArray(), normal.asArray(), origin.asArray()):
+ cells.extend(row)
+ matrix = adsk.core.Matrix3D.create()
+ if not matrix.setWithArray(cells + [0, 0, 0, 1]):
+ raise ValueError('Fusion could not position the image preview.')
+ return matrix
+
+
+class Preview:
+ def __init__(self, raster):
+ self.raster = raster
+ self._group = self._root = self._result = None
+ self._source_entity = self._outline = self._fill_entity = None
+ self._rings = None
+
+ def clear(self):
+ if self._group and self._group.isValid:
+ self._group.deleteMe()
+ self._group = self._root = None
+ self._source_entity = self._outline = self._fill_entity = None
+
+ def close(self):
+ self.clear()
+ self._rings = self._result = None
+
+ def _create_source(self):
+ import adsk.fusion
+
+ self._source_entity = self._group.addGroup()
+ self._source_entity.isChildrenSelectable = False
+ self._source_entity.isSelectable = True
+ effect = adsk.fusion.CustomGraphicsVertexColorEffect.create()
+ for xyz, indices, colors in _source_tiles(self.raster):
+ coords = adsk.fusion.CustomGraphicsCoordinates.create(xyz)
+ coords.colors = list(colors)
+ mesh = self._source_entity.addMesh(coords, indices, [], [])
+ mesh.color = effect
+
+ def _create_outline(self):
+ import adsk.core
+ import adsk.fusion
+
+ self._outline = self._group.addGroup()
+ self._outline.isSelectable = False
+ self._outline.isChildrenSelectable = False
+ points = [p for ring in self._rings for p in (*ring, ring[0])]
+ lengths = [len(ring) + 1 for ring in self._rings]
+ lines = self._outline.addLines(_coordinates(points), [], True, lengths)
+ lines.color = adsk.fusion.CustomGraphicsSolidColorEffect.create(
+ adsk.core.Color.create(225, 28, 114, 255))
+ lines.weight = 1.5
+ lines.depthPriority = 5
+ lines.isSelectable = False
+
+ def _create_fill(self):
+ import adsk.core
+ import adsk.fusion
+
+ points, indices = _fill_mesh(self._rings)
+ self._fill_entity = self._group.addMesh(_coordinates(points), indices, [], [])
+ self._fill_entity.color = adsk.fusion.CustomGraphicsSolidColorEffect.create(
+ adsk.core.Color.create(52, 144, 187, 255))
+ self._fill_entity.isSelectable = False
+
+ def draw(self, sketch, target, result, mode):
+ design = sketch.parentComponent.parentDesign
+ root = design.rootComponent
+ occurrence = design.activeOccurrence
+ if not sketch.assemblyContext and occurrence and occurrence.component == sketch.parentComponent:
+ sketch = sketch.createForAssemblyContext(occurrence)
+ try:
+ # A Fusion preview transaction can invalidate native graphics handles.
+ layers = (self._source_entity, self._outline, self._fill_entity)
+ if (self._root != root or not self._group or not self._group.isValid
+ or any(layer is not None and not layer.isValid for layer in layers)):
+ self.clear()
+ self._group = root.customGraphicsGroups.add()
+ self._group.isChildrenSelectable = True
+ self._root = root
+ if result is not self._result:
+ for entity in (self._outline, self._fill_entity):
+ if entity and entity.isValid:
+ entity.deleteMe()
+ self._outline = self._fill_entity = self._rings = None
+ self._result = result
+
+ if mode != 'filled' and self._source_entity is None:
+ self._create_source()
+ if mode != 'source':
+ if self._rings is None:
+ self._rings = _preview_rings(result)
+ if self._rings:
+ if mode == 'filled' and self._fill_entity is None:
+ self._create_fill()
+ if self._outline is None:
+ self._create_outline()
+ if self._source_entity:
+ self._source_entity.isVisible = mode != 'filled'
+ if self._fill_entity:
+ self._fill_entity.isVisible = mode == 'filled'
+ if self._outline:
+ self._outline.isVisible = mode != 'source'
+ self._group.transform = _matrix(sketch, target, self.raster)
+ except Exception:
+ self.clear()
+ raise
diff --git a/README.md b/README.md
index 8c3d6d7..853a117 100644
--- a/README.md
+++ b/README.md
@@ -2,13 +2,13 @@

-Place SVG curves in an Autodesk Fusion sketch at their physical size, or fit them to a sketch profile.
+Place SVGs and trace photos, logos and drawings into closed Autodesk Fusion sketch outlines.
[Download InsertTo](https://github.com/4FusionLab/InsertTo/releases/latest) · [Русская версия](README.ru.md) · [Report an issue](https://github.com/4FusionLab/InsertTo/issues)
## Install
-1. On the [latest release page](https://github.com/4FusionLab/InsertTo/releases/latest), open **Assets**, download the `InsertTo-.zip` package and extract it.
+1. Download the InsertTo ZIP from the [latest release](https://github.com/4FusionLab/InsertTo/releases/latest) and extract it.
2. In Autodesk Fusion, open **Scripts and Add-Ins → Add-Ins** and add the extracted `InsertTo` folder containing `InsertTo.manifest`.
3. Select **InsertTo** and click **Run**.
@@ -16,7 +16,7 @@ The add-in supports macOS and Windows. The SVG workflow was tested in Fusion on
## Insert an SVG
-1. On the **Sketch** tab, open **Insert → Smart Insert → SVG** and choose the file. While editing a sketch, the curves go into that sketch. If you launch the command outside sketch editing, select a construction plane or planar face in **Sketch plane** to create a sketch, or select a profile or contour in an existing sketch to insert there.
+1. Create or edit a sketch, then open **Sketch → Insert → Smart Insert → SVG** and choose the file. The curves go into the sketch you are editing.
2. Choose **Use bounds of → SVG page** to include the file’s blank margins. Choose **Artwork** to position and scale the extents of the curves Fusion can import.
3. For free placement, leave **Frame (optional)** empty. The selected bounds start at their original size, centered on the sketch origin. Use **Transform** to move, rotate or uniformly scale the drawing with the handles or numeric inputs. Construction lines outline the selected bounds.
4. To fit the SVG to a frame, select a shaded profile or a closed sketch contour. One edge selects an isolated closed chain. You can also select its segments individually. Choose **Fit to frame** and, if needed, set an equal **Inset** on all four sides.
@@ -36,10 +36,36 @@ For example, fitting a 50 × 20 mm page in an 80 × 60 mm frame gives 80 × 32 m
A rectangular frame follows the direction of its sketch edges. Other closed contours use their bounding rectangle along the sketch axes, so the SVG can extend outside an irregular outline. A page declared 50 mm wide stays 50 mm wide at original size and scale 1. SVG pixel dimensions use 96 px per inch.
+## Trace a PNG or JPEG
+
+While editing a sketch, open **Insert → Smart Insert → Trace Image** and choose a PNG or JPEG. The outline appears automatically. A sheet of logos includes all symbols and lettering, a photo starts with its main subject, and a transparent PNG uses its alpha channel.
+
+- Move **Outline detail** right to follow smaller bends, or left for a simpler outline with fewer lines. For photo silhouettes, the tracer smooths pixel stair-steps within the detail setting’s tolerance.
+- **Recognize → Circles** replaces a complete round outline with one editable circle. **Arcs** fits circular sections between straight or curved edges. **Ellipses** fits an editable ellipse to a complete oval, including a circular outline stretched along one axis. All three options start on. Clear all three to keep the original line trace. Ambiguous shapes retain their existing geometry. On a transparent PNG, all three options can use partially transparent edge pixels to locate the boundary more precisely.
+- **Remove small shapes** drops separate shapes below the indicated area in source pixels. Start at zero to keep small lettering. Retained shapes keep their holes, and resizing the insert preserves the same set of shapes.
+- To isolate one shape on a sheet or another subject in a photo, activate **Object → Select** and click inside it. **Reset selection** restores the automatic result. In **More options**, **Edge coverage** includes fainter edges in artwork or more similar pixels around a picked point in a photo. The middle position uses the automatic boundary.
+
+In **More options**, choose **Preview → Filled result** to inspect holes and gaps, or **Contours over source** to compare the boundary with the original. **Image width** sets the width of the whole image. **Insert** creates the closed contours shown in the preview. The dialog counts lines, arcs, circles and ellipses and asks for confirmation above 3,000 sketch curves. Images up to 16,777,216 pixels are supported.
+
+### Try two trace examples
+
+Open either source PNG in **Trace Image**. Leave **Outline detail** at 5, **Remove small shapes** at 0 and **Edge coverage** at 50. Use the original dimensions. The diagrams on the right show the actual paths computed with all three recognition options on. Straight lines are slate blue, arcs orange, circles teal and ellipses purple.
+
+| Source PNG | Computed outlines | Result |
+| --- | --- | --- |
+| [](docs/assets/trace/mounting-plate.png) |  | **Mounting plate.** Two lines and two arcs form the outside. Two circles and one ellipse form the holes. With recognition off, the same four boundaries use 98 lines. |
+| [](docs/assets/trace/keyed-washer.png) |  | **Washer with a flat.** One straight edge meets a major arc at both ends. One circle forms the hole. With recognition off, the two boundaries use 61 lines. |
+
## Verified in Fusion
On macOS, Fusion 2706.1.17 produced a 50 × 50 mm sketch from a 50 mm medallion SVG. A 50 × 20 mm test drawing in an 80 × 60 mm frame measured 80 × 32 mm in **Fit** and 80 × 60 mm in **Stretch**. With **Stretch** and **Link to frame**, changing an 80 × 50 mm rectangular frame to 100 × 50 mm resized the linked ellipse after the edit. The 5 mm inset was preserved, and a 10 mm extrusion based on that profile updated from 21.99 to 28.27 cm³. Moving the frame 12 mm right and 4 mm down moved both linked drawings by the same amounts. The preview and inserted curves had matching bounds in **Fit** and **Stretch**, as well as after using the scale handle during free placement.
+In an earlier build tested in Fusion 2706.1.17 on macOS, tracing the deer produced one closed profile with 221 lines. The trace included all nine gold logos on a sheet along with their lettering. Fusion inserted 1,305 lines and created 157 profiles in 1.4–3.6 seconds across two runs on the test machine. In a sketch with an existing rectangle, cancelling preserved its four sides. After insertion, **Undo** restored the original rectangle and **Redo** restored the trace.
+
+The local curve-recognition candidate was also tested in Fusion 2706.1.17 on macOS. Four nested circular boundaries produced four sketch circles, a capsule produced two lines and two arcs, and a clipped disk produced one line and one major arc. The nine-logo sheet produced 1,151 lines, 12 arcs and two circles with ellipse recognition off, retaining all 157 profiles. With ellipse recognition enabled, the four oval O glyphs produced eight ellipses across their outer boundaries and holes. The sheet retained 157 profiles. A wide ellipse produced one sketch ellipse in place of 43 lines.
+
+In an earlier macOS test, Trace Image inserted a transparent logo as eight editable lines with a hole. Cancelling removed all preview graphics and preserved the selected frame.
+
## Resources
[Release notes](https://github.com/4FusionLab/InsertTo/releases) · [Development and local builds](docs/DEVELOPMENT.md)
diff --git a/README.ru.md b/README.ru.md
index 878c5d9..1c11219 100644
--- a/README.ru.md
+++ b/README.ru.md
@@ -2,13 +2,13 @@

-Вставляет кривые SVG в эскиз Autodesk Fusion в исходном физическом размере или вписывает их в профиль эскиза.
+Вставляйте SVG и превращайте фотографии, логотипы и рисунки в замкнутые контуры эскиза Autodesk Fusion.
[Скачать InsertTo](https://github.com/4FusionLab/InsertTo/releases/latest) · [English](README.md) · [Сообщить о проблеме](https://github.com/4FusionLab/InsertTo/issues)
## Установка
-1. На [странице последнего релиза](https://github.com/4FusionLab/InsertTo/releases/latest) откройте **Assets**, скачайте архив `InsertTo-<версия>.zip` и распакуйте его.
+1. Скачайте ZIP-архив InsertTo со [страницы последнего релиза](https://github.com/4FusionLab/InsertTo/releases/latest) и распакуйте его.
2. В Autodesk Fusion откройте **Scripts and Add-Ins → Add-Ins** и добавьте распакованную папку `InsertTo` с файлом `InsertTo.manifest`.
3. Выберите **InsertTo** и нажмите **Run**.
@@ -16,7 +16,7 @@
## Вставка SVG
-1. На вкладке **Sketch** откройте **Insert → Smart Insert → SVG** и выберите файл. Если эскиз открыт на редактирование, кривые появятся в нём. Если вы запустили команду вне режима редактирования, выберите в **Sketch plane** конструкционную плоскость или плоскую грань для нового эскиза. Чтобы вставить рисунок в существующий эскиз, укажите его профиль или контур.
+1. Создайте эскиз или откройте существующий на редактирование. На вкладке **Sketch** выберите **Insert → Smart Insert → SVG** и укажите файл. Кривые появятся в открытом эскизе.
2. В поле **Use bounds of** выберите **SVG page**, чтобы учитывать пустые поля страницы. Выберите **Artwork**, чтобы разместить и масштабировать рисунок по габаритам кривых, которые импортирует Fusion.
3. Для свободной вставки оставьте **Frame (optional)** пустым. Рисунок появится в исходном размере, а центр выбранной области совпадёт с началом координат эскиза. В разделе **Transform** можно переместить, повернуть и пропорционально масштабировать рисунок ручками в эскизе или вводом чисел. Вспомогательные линии показывают границы выбранной области.
4. Для вставки в рамку выберите закрашенный профиль или замкнутый контур эскиза. У изолированной замкнутой цепочки достаточно выбрать одно ребро. Также можно выбрать сегменты по отдельности. Выберите режим **Fit to frame**. Поле **Inset** задаёт одинаковый отступ внутрь со всех четырёх сторон.
@@ -36,10 +36,36 @@
У прямоугольной рамки учитывается поворот сторон. Для других контуров берётся габаритный прямоугольник по осям эскиза, поэтому рисунок может выходить за границу контура сложной формы. Страница шириной 50 мм сохраняет эту ширину в исходном размере при масштабе 1. Для размеров в пикселях используется соотношение 96 px на дюйм.
+## Обводка PNG и JPEG
+
+Во время редактирования эскиза откройте **Insert → Smart Insert → Trace Image** и выберите PNG или JPEG. Контур появится автоматически. На листе логотипов команда находит все знаки и надписи, на фотографии выделяет главный объект, а у PNG с прозрачным фоном учитывает прозрачность.
+
+- **Outline detail** вправо точнее повторяет мелкие изгибы. Влево контур становится проще и содержит меньше отрезков. На силуэтах фотографий трассировка сглаживает пиксельные ступеньки в пределах допуска выбранной детализации.
+- **Recognize → Circles** заменяет полный круговой контур одной редактируемой окружностью. **Arcs** распознаёт круговые участки границы. **Ellipses** заменяет полный овальный контур одним редактируемым эллипсом, в том числе при растяжении окружности вдоль одной оси. Все три галочки включены при открытии. Снимите все три, чтобы получить исходную трассировку отрезками. При неоднозначной форме сохраняется прежняя геометрия. На прозрачном PNG все три галочки учитывают промежуточную непрозрачность краевых пикселей, чтобы точнее определить положение границы.
+- **Remove small shapes** убирает отдельные фигуры меньше указанной площади в пикселях исходного изображения. Начните с нуля, чтобы сохранить мелкий текст. Отверстия внутри оставшихся фигур сохраняются, а изменение размера вставки не влияет на отбор.
+- Чтобы обвести одну деталь листа или другой объект на фото, используйте **Object → Select** и щёлкните внутри него. **Reset selection** возвращает автоматический результат. В **More options** ползунок **Edge coverage** помогает включить бледные края рисунка или больше похожих пикселей вокруг выбранной точки на фото. Среднее положение соответствует автоматической границе.
+
+В **More options** выберите **Preview → Filled result**, чтобы проверить отверстия и просветы, или **Contours over source**, чтобы сравнить границу с оригиналом. **Image width** задаёт ширину всего изображения. **Insert** создаёт в эскизе замкнутые контуры из предпросмотра. Диалог показывает число отрезков, дуг, окружностей и эллипсов. Если суммарно получается больше 3000 кривых, потребуется подтверждение. Поддерживаются изображения до 16 777 216 пикселей.
+
+### Два примера для проверки трассировки
+
+Откройте любой исходный PNG в **Trace Image**. Оставьте **Outline detail** на 5, **Remove small shapes** на 0, **Edge coverage** на 50 и сохраните исходный размер. На схемах справа показаны контуры, которые построила команда при включённых трёх галочках распознавания. Отрезки обозначены серо-синим, дуги — оранжевым, окружности — бирюзовым, эллипсы — фиолетовым.
+
+| Исходный PNG | Полученные контуры | Результат |
+| --- | --- | --- |
+| [](docs/assets/trace/mounting-plate.png) |  | **Крепёжная пластина.** Внешний контур состоит из двух отрезков и двух дуг. Отверстия образуют две окружности и эллипс. При выключенном распознавании те же четыре границы состоят из 98 отрезков. |
+| [](docs/assets/trace/keyed-washer.png) |  | **Шайба со срезом.** Внешний контур состоит из отрезка и большой дуги, отверстие образует одна окружность. При выключенном распознавании две границы состоят из 61 отрезка. |
+
## Проверка в Fusion
В Fusion 2706.1.17 на macOS медальон из SVG размером 50 × 50 мм дал в эскизе ровно 50 × 50 мм. В рамке 80 × 60 мм контрольный рисунок 50 × 20 мм дал 80 × 32 мм в режиме **Fit** и 80 × 60 мм в режиме **Stretch**. В режиме **Stretch** с включённым **Link to frame** изменение прямоугольной рамки с 80 × 50 мм до 100 × 50 мм обновило связанный эллипс после правки. Отступ 5 мм сохранился, а объём выдавливания этого профиля на 10 мм изменился с 21,99 до 28,27 см³. При переносе рамки на 12 мм вправо и 4 мм вниз оба связанных рисунка сдвинулись на те же расстояния. Габариты кривых в предпросмотре и после вставки совпали в режимах **Fit** и **Stretch**, а также после масштабирования ручкой при свободной вставке.
+При проверке предыдущей сборки в Fusion 2706.1.17 на macOS автоматическая трассировка оленя дала один замкнутый профиль из 221 отрезка. Команда обвела все девять золотых логотипов вместе с надписями. При вставке Fusion создал 1305 отрезков и 157 профилей за 1,4–3,6 с в двух прогонах на тестовом компьютере. В эскизе с исходным прямоугольником отмена команды сохранила его четыре стороны. После вставки **Undo** вернул исходный прямоугольник, а **Redo** восстановил трассировку.
+
+Локальную сборку с распознаванием кривых также проверили в Fusion 2706.1.17 на macOS. Четыре вложенные круглые границы дали четыре окружности, капсула — две прямые и две дуги, диск со срезом — прямую и большую дугу. На листе девяти логотипов при выключенном распознавании эллипсов получились 1151 отрезок, 12 дуг и две окружности. Сохранились все 157 профилей. При включённом распознавании эллипсов внешние границы и просветы четырёх букв O дали восемь эллипсов. Число профилей осталось равным 157. Широкий тестовый овал дал один эллипс вместо 43 отрезков.
+
+В предыдущей проверке на macOS команда Trace Image вставила прозрачный логотип как восемь редактируемых отрезков с отверстием. При отмене Fusion удалил графику предпросмотра и сохранил выбранную рамку.
+
## Материалы
[История релизов](https://github.com/4FusionLab/InsertTo/releases) · [Разработка и локальная сборка](docs/DEVELOPMENT.ru.md)
diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md
index 6d4f44b..f1f74f9 100644
--- a/docs/DEVELOPMENT.md
+++ b/docs/DEVELOPMENT.md
@@ -24,9 +24,22 @@ python scripts/build.py --version 0.1.0
The archive in `dist/` contains the installable InsertTo folder. For development, register that folder or the source package via **Scripts and Add-Ins**. Edit a sketch and open **Insert → Smart Insert → SVG**.
+## Trace Image verification cycle
+
+1. Reproduce the report using the same image type, polarity and final size. Make a small original fixture for the regression. Keep user-supplied photographs in local acceptance runs.
+2. Run the tests and validator in **Local build**. The reference `tests/fixtures/artwork-sheet.jpg` has nine signs, each with a hole, and 27 separate marks. Expect 45 outline rings. The transparent PNG should keep its outer outline and hole.
+3. Build a candidate, then run the command below with its ZIP filename. It checks the checksum and manifest version, extracts the package into a clean directory, and traces a PNG and a JPEG using the installed code.
+4. In a separate Fusion document, check the automatic subject, picking a different object, light lettering on a dark background, and holes in the filled preview. Click **Insert**, compare the counts of lines, arcs, circles and ellipses with the preview, and check **Undo**, **Redo** and a separate **Cancel**. Check the confirmation and progress display on a dense trace. Record the OS and Fusion version for each native run.
+5. For any mismatch, add a reproducer and repeat with the corrected build. Publish through the repository's existing checks and packaging workflow.
+
+```bash
+python scripts/check_trace_package.py --archive dist/InsertTo-0.1.0.zip
+```
+
## Native acceptance checklist
- Install, start, stop and restart without duplicated controls or leaking handlers.
+- In a separate design, verify that Smart Insert appears when editing a new or existing sketch and disappears after Finish Sketch. Try SVG and Trace Image from command search or a shortcut outside sketch edit mode. Neither should start. Switch documents and repeat.
- Import a 50 × 20 mm SVG in an 80 × 60 mm rectangle. Fit should produce 80 × 32 mm. At **Align → Top**, the upper edges should meet and the lower gap should be 28 mm. Stretch should produce 80 × 60 mm.
- Insert with **Link to frame** enabled and finish the edit. Change the frame from 80 × 60 mm to 100 × 60 mm, keeping InsertTo running. The linked 50 × 20 mm SVG should become 100 × 40 mm in Fit or 100 × 60 mm in Stretch. Confirm the same fixed splines update and the frame dimensions remain editable. Repeat with the option off and check that the SVG keeps its inserted size.
- Repeat Fit with a 5 mm inset on every side. The fitted SVG should measure 70 × 28 mm, with 5 mm at the top when aligned there.
diff --git a/docs/DEVELOPMENT.ru.md b/docs/DEVELOPMENT.ru.md
index 672a33b..7e00448 100644
--- a/docs/DEVELOPMENT.ru.md
+++ b/docs/DEVELOPMENT.ru.md
@@ -24,9 +24,22 @@ python scripts/build.py --version 0.1.0
Архив в `dist/` содержит папку InsertTo для установки. Для разработки подключите эту папку или папку исходников аддона через **Scripts and Add-Ins**. Откройте эскиз на редактирование и выберите **Insert → Smart Insert → SVG**.
+## Цикл проверки трассировки
+
+1. Воспроизведите проблему с тем же типом изображения, полярностью и итоговым размером. Для регрессионного теста используйте небольшой собственный пример. Фотографии пользователей остаются в локальной проверке.
+2. Выполните тесты и валидатор из раздела «Локальная сборка». В качестве контрольного листа используйте `tests/fixtures/artwork-sheet.jpg`: девять знаков с девятью отверстиями и 27 отдельными штрихами дают 45 колец. На прозрачном PNG ожидаются внешний контур и отверстие.
+3. Соберите кандидат и проверьте его из временной чистой установки. Подставьте имя собранного ZIP в команду ниже. Проверка сверяет SHA-256 и версию манифеста, распаковывает архив и обводит PNG и JPEG его собственным кодом.
+4. В Fusion откройте отдельный тестовый документ. Проверьте автоматический силуэт, выбор другого объекта на фото, светлые надписи на тёмном фоне и отверстия в закрашенном предпросмотре. Нажмите **Insert**, сравните число отрезков, дуг, окружностей и эллипсов с предпросмотром, проверьте **Undo**, **Redo** и отдельную отмену команды. Для большого результата проверьте подтверждение и сообщение о ходе вставки. Зафиксируйте ОС и версию Fusion для каждого нативного прогона.
+5. Если результат расходится с ожидаемым, добавьте тест на воспроизведение и повторите цикл с исправленным архивом. Для публикации используйте штатные проверки и сборку репозитория.
+
+```bash
+python scripts/check_trace_package.py --archive dist/InsertTo-0.1.0.zip
+```
+
## Контрольный список приёмки в Fusion
- Установка, запуск, остановка и повторный запуск без дублирующихся элементов управления и утечек обработчиков.
+- В отдельной модели проверьте, что при создании и редактировании эскиза появляется Smart Insert, а после **Finish Sketch** меню исчезает. Вне редактирования попробуйте вызвать SVG и Trace Image через поиск команд или горячую клавишу. Обе команды должны быть недоступны. Повторите после переключения документов.
- Вставьте SVG 50 × 20 мм в прямоугольник 80 × 60 мм. Проверьте размер 80 × 32 мм в режиме Fit. При выборе **Align → Top** верхние границы должны совпасть, а нижний зазор должен составить 28 мм. В режиме Stretch проверьте размер 80 × 60 мм.
- Вставьте SVG 50 × 20 мм с включённым **Link to frame** и завершите редактирование. При работающем InsertTo измените рамку с 80 × 60 мм на 100 × 60 мм. Проверьте размер рисунка 100 × 40 мм в режиме Fit или 100 × 60 мм в режиме Stretch. Должны обновиться те же фиксированные сплайны, а размеры рамки остаются доступны для редактирования. Повторите со снятым флажком и проверьте, что рисунок сохранил размер, заданный при вставке.
- Повторите Fit с внутренним отступом 5 мм со всех сторон. Ожидается рисунок 70 × 28 мм. При выравнивании по верху расстояние от верхней стороны рамки должно составить 5 мм.
diff --git a/docs/assets/trace/keyed-washer-trace.png b/docs/assets/trace/keyed-washer-trace.png
new file mode 100644
index 0000000..2026438
Binary files /dev/null and b/docs/assets/trace/keyed-washer-trace.png differ
diff --git a/docs/assets/trace/keyed-washer.png b/docs/assets/trace/keyed-washer.png
new file mode 100644
index 0000000..1384036
Binary files /dev/null and b/docs/assets/trace/keyed-washer.png differ
diff --git a/docs/assets/trace/mounting-plate-trace.png b/docs/assets/trace/mounting-plate-trace.png
new file mode 100644
index 0000000..712b51a
Binary files /dev/null and b/docs/assets/trace/mounting-plate-trace.png differ
diff --git a/docs/assets/trace/mounting-plate.png b/docs/assets/trace/mounting-plate.png
new file mode 100644
index 0000000..52c7430
Binary files /dev/null and b/docs/assets/trace/mounting-plate.png differ
diff --git a/docs/releases/1.1.0.md b/docs/releases/1.1.0.md
new file mode 100644
index 0000000..f3cc6bb
--- /dev/null
+++ b/docs/releases/1.1.0.md
@@ -0,0 +1,12 @@
+[Русская версия](https://github.com/4FusionLab/InsertTo/blob/v1.1.0/docs/releases/1.1.0.ru.md)
+
+While editing a sketch, open **Insert → Smart Insert → Trace Image** to turn a PNG or JPEG into editable closed sketch geometry. The preview shows what will be inserted and counts the resulting sketch curves.
+
+- Trace a photo silhouette, a whole sheet of artwork or one selected object. Adjust **Outline detail** and **Remove small shapes** to control the result.
+- Enable **Circles**, **Arcs** and **Ellipses** independently. Transparent PNGs can use partially transparent edge pixels when fitting these curves. Ambiguous shapes keep their line segments.
+- Photo tracing reduces pixel stair-steps within the selected tolerance. Faint features lost during subject selection can still be absent from the outline.
+- Both **SVG** and **Trace Image** are available while editing a sketch. Create or edit the destination sketch before opening Smart Insert.
+
+[Worked examples](https://github.com/4FusionLab/InsertTo/tree/v1.1.0#try-two-trace-examples) · [Installation](https://github.com/4FusionLab/InsertTo/tree/v1.1.0#install)
+
+Tracing and insertion were exercised in Fusion on macOS during development. Native Fusion acceptance on Windows is pending.
diff --git a/docs/releases/1.1.0.ru.md b/docs/releases/1.1.0.ru.md
new file mode 100644
index 0000000..4ac2c0a
--- /dev/null
+++ b/docs/releases/1.1.0.ru.md
@@ -0,0 +1,12 @@
+[English](1.1.0.md)
+
+Откройте эскиз на редактирование и выберите **Insert → Smart Insert → Trace Image**, чтобы превратить PNG или JPEG в замкнутые редактируемые контуры. Предпросмотр показывает геометрию будущей вставки и число кривых.
+
+- Обведите силуэт на фотографии, весь лист с рисунками или один выбранный объект. **Outline detail** задаёт детализацию, а **Remove small shapes** убирает мелкие фигуры.
+- Включайте **Circles**, **Arcs** и **Ellipses** независимо. Для прозрачных PNG команда учитывает полупрозрачные пиксели границы. Неоднозначные участки сохраняются в виде отрезков.
+- На фотографиях команда сглаживает пиксельные ступеньки в пределах выбранного допуска. Светлые детали, потерянные при выделении объекта, могут отсутствовать в контуре.
+- **SVG** и **Trace Image** доступны при редактировании эскиза. Перед запуском Smart Insert создайте или откройте нужный эскиз.
+
+[Примеры работы](https://github.com/4FusionLab/InsertTo/blob/v1.1.0/README.ru.md#два-примера-для-проверки-трассировки) · [Установка](https://github.com/4FusionLab/InsertTo/blob/v1.1.0/README.ru.md#установка)
+
+Трассировку и вставку проверяли в Fusion на macOS в ходе разработки. Проверка в самом Fusion на Windows ещё предстоит.
diff --git a/scripts/check_trace_package.py b/scripts/check_trace_package.py
new file mode 100644
index 0000000..0bd6e97
--- /dev/null
+++ b/scripts/check_trace_package.py
@@ -0,0 +1,77 @@
+"""Install a local build in a temporary directory and trace its reference images."""
+
+import argparse
+import hashlib
+import json
+import math
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+import zipfile
+
+
+FIXTURES = Path(__file__).resolve().parents[1] / 'tests' / 'fixtures'
+
+
+def smoke_test(installed, fixtures):
+ # Runs in a fresh isolated interpreter. Import only the extracted product.
+ sys.path.insert(0, str(installed))
+ from InsertTo import image_trace, trace_primitives
+
+ logo = image_trace.load_image(fixtures / 'transparent-logo.png')
+ result = image_trace.trace(image_trace.analyze(logo, 'alpha'), 1, 1, .75, 0)
+ if sorted(map(len, result.rings)) != [4, 4]:
+ raise ValueError('The installed build lost the transparent logo outline or its hole.')
+ sheet = image_trace.load_image(fixtures / 'artwork-sheet.jpg')
+ defaults = image_trace.artwork_defaults(sheet)
+ if not defaults.is_artwork or defaults.mode != 'light':
+ raise ValueError('The installed build did not recognize the light artwork sheet.')
+ analysis = image_trace.analyze(sheet, 'ink', defaults.threshold, True)
+ result = image_trace.trace(analysis, 1, 1, .65, 0)
+ if len(result.rings) != 45 or sum(len(group) == 2 for group in analysis.components) != 9:
+ raise ValueError('Expected nine signs with holes and all 27 detached marks.')
+
+ ring = tuple((50 + 30 * math.cos(i * math.tau / 96),
+ 50 + 30 * math.sin(i * math.tau / 96)) for i in range(96))
+ analysis = image_trace.Analysis(((ring,),))
+ linear = image_trace.trace(analysis, 1, 1, .65, 0)
+ fitted = trace_primitives.recognize(analysis, linear, 1, 1, .65, True, False)
+ if fitted.type_counts != (0, 0, 1, 0):
+ raise ValueError('The installed build did not create one circle for a circular outline.')
+
+ stretched = image_trace.trace(analysis, 2, 1, .65, 0)
+ elongated = trace_primitives.recognize(analysis, stretched, 2, 1, .65, False, False, True)
+ if elongated.type_counts != (0, 0, 0, 1):
+ raise ValueError('The installed build did not create an ellipse for a stretched circle.')
+
+
+def verify(archive):
+ expected = archive.with_suffix('.zip.sha256').read_text(encoding='ascii').split()[0]
+ if hashlib.sha256(archive.read_bytes()).hexdigest() != expected:
+ raise ValueError('Package checksum mismatch.')
+ with tempfile.TemporaryDirectory() as work:
+ with zipfile.ZipFile(archive) as bundle:
+ manifest = json.loads(bundle.read('InsertTo/InsertTo.manifest'))
+ if archive.name != f"InsertTo-{manifest['version']}.zip":
+ raise ValueError('Archive filename does not match the manifest version.')
+ for member in bundle.namelist():
+ parts = member.split('/')
+ if parts[0] != 'InsertTo' or '..' in parts or '\\' in member:
+ raise ValueError('Unexpected archive member: ' + member)
+ bundle.extractall(work)
+ subprocess.run([sys.executable, '-I', str(Path(__file__).resolve()),
+ '--installed', work], cwd=work, check=True)
+ print(f'Verified installation and PNG/JPEG tracing from {archive.name}.')
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description=__doc__)
+ source = parser.add_mutually_exclusive_group(required=True)
+ source.add_argument('--archive', type=Path)
+ source.add_argument('--installed', type=Path, help=argparse.SUPPRESS)
+ options = parser.parse_args()
+ if options.installed:
+ smoke_test(options.installed, FIXTURES)
+ else:
+ verify(options.archive)
diff --git a/tests/fixtures/artwork-sheet.jpg b/tests/fixtures/artwork-sheet.jpg
new file mode 100644
index 0000000..40bb84a
Binary files /dev/null and b/tests/fixtures/artwork-sheet.jpg differ
diff --git a/tests/fixtures/noisy-print.jpg b/tests/fixtures/noisy-print.jpg
new file mode 100644
index 0000000..0aefdb8
Binary files /dev/null and b/tests/fixtures/noisy-print.jpg differ
diff --git a/tests/fixtures/transparent-logo.png b/tests/fixtures/transparent-logo.png
new file mode 100644
index 0000000..aba6707
Binary files /dev/null and b/tests/fixtures/transparent-logo.png differ
diff --git a/tests/test_frame_link.py b/tests/test_frame_link.py
index 8d1c91a..63bcca2 100644
--- a/tests/test_frame_link.py
+++ b/tests/test_frame_link.py
@@ -141,7 +141,7 @@ def test_resized_frame_reapplies_stored_axis_factors_and_loads_legacy_links(self
def test_bulk_edit_restores_marker_on_failure(self):
with self.assertRaisesRegex(ValueError, 'invalid curve'):
- with links._batch_edit(self.sketch):
+ with links.batch_edit(self.sketch):
self.assertTrue(self.sketch.isComputeDeferred)
self.assertEqual(self.timeline.markerPosition, 3)
raise ValueError('invalid curve')
@@ -150,27 +150,27 @@ def test_bulk_edit_restores_marker_on_failure(self):
def test_grouped_sketch_uses_normal_solve_and_preserves_marker(self):
self.sketch.timelineObject.index = -1
- with links._batch_edit(self.sketch):
+ with links.batch_edit(self.sketch):
self.assertFalse(self.sketch.isComputeDeferred)
self.sketch.timelineObject.rollTo.assert_not_called()
def test_roll_disallowed_by_edit_context_keeps_standard_insert_available(self):
self.sketch.timelineObject.rollTo.side_effect = RuntimeError('Cannot roll while editing')
- with links._batch_edit(self.sketch):
+ with links.batch_edit(self.sketch):
self.assertFalse(self.sketch.isComputeDeferred)
self.assertEqual(self.timeline.markerPosition, 6)
def test_last_sketch_and_direct_design_need_no_timeline_roll(self):
for timeline in (SimpleNamespace(count=3, markerPosition=3), None):
self.sketch.parentComponent.parentDesign.timeline = timeline
- with links._batch_edit(self.sketch):
+ with links.batch_edit(self.sketch):
self.assertTrue(self.sketch.isComputeDeferred)
self.assertFalse(self.sketch.isComputeDeferred)
self.sketch.timelineObject.rollTo.assert_not_called()
def test_nested_bulk_edit_keeps_callers_deferred_state(self):
self.sketch.isComputeDeferred = True
- with links._batch_edit(self.sketch):
+ with links.batch_edit(self.sketch):
self.assertTrue(self.sketch.isComputeDeferred)
self.assertTrue(self.sketch.isComputeDeferred)
self.sketch.timelineObject.rollTo.assert_not_called()
diff --git a/tests/test_image_decode.py b/tests/test_image_decode.py
new file mode 100644
index 0000000..628afd9
--- /dev/null
+++ b/tests/test_image_decode.py
@@ -0,0 +1,42 @@
+"""Image picker inputs and pre-decode size checks on all supported platforms."""
+
+from pathlib import Path
+import shutil
+import struct
+from tempfile import TemporaryDirectory
+import unittest
+from unittest.mock import patch
+
+from InsertTo import image_decode
+
+
+class DecoderInputTests(unittest.TestCase):
+ def test_unicode_filename_and_uppercase_extension(self):
+ fixture = Path(__file__).with_name('fixtures') / 'transparent-logo.png'
+ with TemporaryDirectory() as directory:
+ path = Path(directory) / 'Белый логотип #1.PNG'
+ shutil.copyfile(fixture, path)
+ self.assertEqual(image_decode.load_image(path), image_decode.load_image(fixture))
+
+ def test_truncated_and_mislabeled_files(self):
+ with TemporaryDirectory() as directory:
+ for name, data in [('broken.jpg', b'\xff\xd8\xff\xc0\x00'),
+ ('wrong.png', b'not a png'),
+ ('renamed.gif', b'GIF89a')]:
+ with self.subTest(name=name):
+ path = Path(directory) / name
+ path.write_bytes(data)
+ with self.assertRaises(ValueError):
+ image_decode.load_image(path)
+
+ def test_rejects_empty_or_oversized_canvas_before_native_decode(self):
+ with TemporaryDirectory() as directory:
+ path = Path(directory) / 'header.png'
+ for size in [(0, 40), (8192, 8192)]:
+ with self.subTest(size=size):
+ path.write_bytes(bytes.fromhex('89504e470d0a1a0a0000000d49484452') +
+ struct.pack('>II', *size))
+ with patch.object(image_decode, '_mac_rgba') as decode:
+ with self.assertRaisesRegex(ValueError, '16 megapixels'):
+ image_decode.load_image(path)
+ decode.assert_not_called()
diff --git a/tests/test_image_trace.py b/tests/test_image_trace.py
new file mode 100644
index 0000000..9e76740
--- /dev/null
+++ b/tests/test_image_trace.py
@@ -0,0 +1,350 @@
+"""Black-box checks of the bundled decoder and physical-unit tracing controls."""
+
+import unittest
+from pathlib import Path
+
+from InsertTo import image_trace
+
+
+FIXTURES = Path(__file__).with_name('fixtures')
+
+
+def signed_area(points):
+ neighbors = list(zip(points, points[1:] + points[:1]))
+ return sum(x * v - y * u for (x, y), (u, v) in neighbors) / 2
+
+
+def contains(points, x, y):
+ inside = False
+ for (px, py), (qx, qy) in zip(points, points[1:] + points[:1]):
+ if (py > y) != (qy > y) and x < px + (y - py) * (qx - px) / (qy - py):
+ inside = not inside
+ return inside
+
+
+def traced_ink(result, x, y):
+ return sum(contains(points, x, y) for points in result.rings) % 2 == 1
+
+
+class ImageTraceTests(unittest.TestCase):
+ def test_white_logo_uses_alpha_preserving_square_corners_and_hole(self):
+ image = image_trace.load_image(str(FIXTURES / 'transparent-logo.png'))
+ self.assertEqual((image.width, image.height), (40, 36))
+ self.assertTrue(image.has_alpha)
+ analysis = image_trace.analyze(image, 'alpha', 128, False)
+ result = image_trace.trace(analysis, .5, .5, .05, 0)
+ self.assertEqual(len(result.rings), 2)
+ self.assertEqual(result.curve_count, 8)
+ outer, hole = sorted(result.rings, key=lambda p: -abs(signed_area(p)))
+ self.assertLess(signed_area(outer) * signed_area(hole), 0)
+ self.assertEqual(set(outer), {(5, 4), (35, 4), (35, 30), (5, 30)})
+ self.assertEqual(set(hole), {(12, 10), (27, 10), (27, 22), (12, 22)})
+
+ def test_grainy_jpeg_speck_filter_uses_final_square_mm(self):
+ image = image_trace.load_image(str(FIXTURES / 'noisy-print.jpg'))
+ self.assertEqual((image.width, image.height), (64, 48))
+ analysis = image_trace.analyze(image, 'luminance', 128, False)
+ small = image_trace.trace(analysis, .5, .25, .01, 0)
+ cleaned = image_trace.trace(analysis, .5, .25, .01, .5)
+ enlarged = image_trace.trace(analysis, 2, 1, .01, .5)
+ self.assertEqual(len(small.rings), 4)
+ self.assertEqual(len(cleaned.rings), 1)
+ self.assertEqual(len(enlarged.rings), 4)
+ self.assertTrue(traced_ink(cleaned, 25.5, 20.5))
+ self.assertFalse(traced_ink(cleaned, 3.5, 4.5))
+
+ def test_inverting_jpeg_threshold_reverses_ink_inside_image(self):
+ image = image_trace.load_image(str(FIXTURES / 'noisy-print.jpg'))
+ analysis = image_trace.analyze(image, 'luminance', 128, True)
+ result = image_trace.trace(analysis, 1, 1, .01, 0)
+ self.assertFalse(traced_ink(result, 25.5, 20.5))
+ self.assertTrue(traced_ink(result, .5, .5))
+
+ def test_tolerance_is_applied_after_sizing_and_can_be_reversed(self):
+ side = 60
+ pixels = bytearray()
+ for y in range(side):
+ for x in range(side):
+ inside = (x - 30) ** 2 + (y - 30) ** 2 <= 23 ** 2
+ pixels.extend((20, 20, 20, 255 if inside else 0))
+ image = image_trace.Raster(side, side, bytes(pixels), True)
+ analysis = image_trace.analyze(image, 'alpha', 128, False)
+ fine = image_trace.trace(analysis, .25, .25, .025, 0)
+ smooth = image_trace.trace(analysis, .25, .25, .5, 0)
+ restored = image_trace.trace(analysis, 5, 5, .5, 0)
+ self.assertGreater(fine.curve_count, smooth.curve_count)
+ self.assertEqual(len(smooth.rings), 1)
+ self.assertTrue(traced_ink(smooth, 30, 30))
+ self.assertEqual(fine.rings, restored.rings)
+
+ def test_threshold_selects_translucent_pixels_or_dark_pixels(self):
+ image = image_trace.Raster(3, 1, bytes((240, 240, 240, 20,
+ 20, 20, 20, 140,
+ 75, 75, 75, 240)), True)
+ for mode, threshold, invert, expected in (
+ ('alpha', 100, False, [False, True, True]),
+ ('alpha', 200, False, [False, False, True]),
+ # Brightness sees the partly transparent pixels against white.
+ ('luminance', 100, False, [False, False, True]),
+ ('luminance', 150, False, [False, True, True])):
+ with self.subTest(mode=mode, threshold=threshold):
+ analysis = image_trace.analyze(image, mode, threshold, invert)
+ result = image_trace.trace(analysis, 1, 1, .01, 0)
+ self.assertEqual([traced_ink(result, x + .5, .5) for x in range(3)], expected)
+
+ def test_spot_filter_keeps_hole_of_a_retained_logo(self):
+ image = image_trace.load_image(str(FIXTURES / 'transparent-logo.png'))
+ analysis = image_trace.analyze(image, 'alpha', 128, False)
+ result = image_trace.trace(analysis, 1, 1, .05, 200)
+ # Its 180 mm² hole belongs to the surrounding 600 mm² printed component.
+ self.assertEqual(len(result.rings), 2)
+ self.assertTrue(traced_ink(result, 8, 8))
+ self.assertFalse(traced_ink(result, 20, 17))
+
+ def test_photo_silhouette_separates_similar_brightness_and_fills_texture(self):
+ # The subject is off-center, with a thin protrusion, an enclosed light
+ # patch and a detached spot of the same color elsewhere in the scene.
+ def pixel(x, y):
+ subject = 6 <= x < 20 and 10 <= y < 22 or x == 12 and 4 <= y < 12
+ texture = 9 <= x < 16 and 14 <= y < 18
+ spot = 30 <= x < 34 and 8 <= y < 12
+ if subject and not texture or spot:
+ return bytes((128, 104, 85, 255))
+ gray = 110 + (x + y) % 8
+ return bytes((gray, gray, gray, 255))
+
+ raster = image_trace.Raster(40, 30, b''.join(pixel(x, y) for y in range(30)
+ for x in range(40)), False)
+ result = image_trace.trace(image_trace.analyze(raster, 'silhouette'), 1, 1, 0, 0)
+ self.assertEqual(len(result.rings), 1)
+ for point in ((7, 11), (12.5, 5), (11, 16)):
+ self.assertTrue(traced_ink(result, *point))
+ for point in ((2, 2), (31, 10), (13.5, 5)):
+ self.assertFalse(traced_ink(result, *point))
+
+ def test_photo_sensitivity_includes_more_of_subject(self):
+ def pixel(x, y):
+ gray = 116 if 3 <= x <= 8 and 3 <= y <= 8 else 144
+ if 5 <= x <= 6 and 5 <= y <= 6:
+ gray = 48
+ return bytes((gray, gray, gray, 255))
+
+ raster = image_trace.Raster(12, 12, b''.join(pixel(x, y) for y in range(12)
+ for x in range(12)), False)
+ outcomes = [image_trace.trace(image_trace.analyze(raster, 'silhouette', cutoff),
+ 1, 1, 0, 0) for cutoff in (0, 255)]
+ self.assertFalse(traced_ink(outcomes[0], 4.5, 4.5))
+ self.assertTrue(traced_ink(outcomes[1], 4.5, 4.5))
+ self.assertTrue(all(traced_ink(result, 5.5, 5.5) for result in outcomes))
+
+ def test_uniform_photo_produces_no_subject(self):
+ raster = image_trace.Raster(12, 9, bytes((50, 50, 50, 255)) * 108, False)
+ self.assertEqual(image_trace.analyze(raster, 'silhouette').components, ())
+
+ def test_wide_photo_outline_maps_to_original_pixel_coordinates(self):
+ row = bytes((255, 255, 255, 255)) * 2048
+ center = row[:4 * 160] + bytes((20, 20, 20, 255)) * 800 + row[4 * 960:]
+ raster = image_trace.Raster(2048, 24, row * 8 + center * 8 + row * 8, False)
+ result = image_trace.trace(image_trace.analyze(raster, 'silhouette'), 1, 1, 0, 0)
+ self.assertEqual(set(result.rings[0]), {(160, 8), (960, 8), (960, 16), (160, 16)})
+
+ def test_silhouette_detail_can_smooth_longer_pixel_steps(self):
+ # Both adjoining runs exceed one pixel on each step. These artwork
+ # corners stay locked for logos but can be simplified on a photo.
+ pixels = bytearray()
+ for y in range(40):
+ for x in range(40):
+ inside = 4 <= x < 36 and 4 <= y < 5 + 2 * (x // 2)
+ gray = 20 if inside else 240
+ pixels.extend((gray, gray, gray, 255))
+ raster = image_trace.Raster(40, 40, bytes(pixels), False)
+ analysis = image_trace.analyze(raster, 'silhouette')
+ fine = image_trace.trace(analysis, 1, 1, .25, 0)
+ smooth = image_trace.trace(analysis, 1, 1, 2.5, 0)
+ self.assertEqual(len(fine.rings), 1)
+ self.assertEqual(len(smooth.rings), 1)
+ self.assertGreater(fine.curve_count, smooth.curve_count)
+ self.assertEqual(fine, image_trace.trace(analysis, 1, 1, .25, 0))
+
+ def test_picked_tree_uses_local_contrast_and_connected_branch(self):
+ # The lower sky matches the picked trunk's brightness. A simple
+ # whole-image color threshold would spill into it and the second tree.
+ width, height = 120, 90
+ pixels = bytearray()
+ for y in range(height):
+ for x in range(width):
+ background = 206 - y // 2
+ tree = 61 <= x <= 63 or (y < 36 and abs(x - (44 + y // 2)) <= 1)
+ other_tree = 15 <= x <= 18
+ gray = background - 24 if tree or other_tree else background
+ pixels.extend((gray, gray, gray, 255))
+ raster = image_trace.Raster(width, height, bytes(pixels), False)
+ result = image_trace.trace(image_trace.analyze(raster, 'silhouette', seed=(62, 36)),
+ 1, 1, 0, 0)
+ self.assertTrue(traced_ink(result, 62.5, 65.5))
+ self.assertTrue(traced_ink(result, 49.5, 10.5))
+ self.assertFalse(traced_ink(result, 16.5, 36.5))
+ self.assertFalse(traced_ink(result, 70.5, 84.5))
+ other = image_trace.trace(image_trace.analyze(raster, 'silhouette', seed=(16, 36)),
+ 1, 1, 0, 0)
+ self.assertTrue(traced_ink(other, 16.5, 36.5))
+ self.assertFalse(traced_ink(other, 62.5, 36.5))
+
+ def test_picked_region_keeps_openings_and_respects_selection_range(self):
+ pixels = bytearray()
+ for y in range(32):
+ for x in range(40):
+ ring = 5 <= x <= 24 and 4 <= y <= 25 and not (10 <= x < 20 and 10 <= y < 20)
+ extension = 25 <= x < 30 and 4 <= y <= 25
+ gray = 110 if ring else 129 if extension else 220
+ pixels.extend((gray, gray, gray, 255))
+ raster = image_trace.Raster(40, 32, bytes(pixels), False)
+ for level, includes_extension in ((0, False), (170, True)):
+ result = image_trace.trace(
+ image_trace.analyze(raster, 'silhouette', level, seed=(8, 8)), 1, 1, 0, 0)
+ self.assertTrue(traced_ink(result, 8.5, 8.5))
+ self.assertFalse(traced_ink(result, 15.5, 14.5))
+ self.assertEqual(traced_ink(result, 27.5, 15.5), includes_extension)
+
+ def test_outside_pick_rejected_and_uniform_image_has_no_distinct_region(self):
+ raster = image_trace.Raster(6, 4, bytes((90, 90, 90, 255)) * 24, False)
+ for seed in ((-1, 2), (6, 3), (0, 4), (float('nan'), 1)):
+ with self.assertRaisesRegex(ValueError, 'inside the image'):
+ image_trace.analyze(raster, 'silhouette', seed=seed)
+ result = image_trace.analyze(raster, 'silhouette', seed=(2.75, 1.5))
+ self.assertEqual(result.components, ())
+
+ def test_artwork_mode_uses_transparency_or_dominant_border_brightness(self):
+ for background, expected in ((245, 'dark'), (25, 'light')):
+ data = bytearray((background, background, background, 255)) * 100
+ for i in range(10):
+ data[4 * i:4 * i + 4] = bytes((255 - background,) * 3 + (255,))
+ raster = image_trace.Raster(10, 10, bytes(data), False)
+ self.assertEqual(image_trace.artwork_mode(raster), expected)
+ self.assertEqual(image_trace.artwork_mode(
+ image_trace.Raster(1, 1, bytes((0, 0, 0, 0)), True)), 'alpha')
+
+ def test_artwork_sheet_defaults_retain_separate_gradient_marks_and_diagonal_hatching(self):
+ width, height = 88, 52
+ for inverse in (False, True):
+ with self.subTest(inverse=inverse):
+ pixels = bytearray()
+ for y in range(height):
+ for x in range(width):
+ # A large ring, three diagonals, and small detached
+ # lettering on paper with simulated compression noise.
+ box = 8 <= x < 36 and 8 <= y < 36
+ hole = 14 <= x < 30 and 14 <= y < 30
+ stripe = 48 <= x < 78 and 10 <= y < 30 and (x + y) % 8 < 3
+ caption = 8 <= x < 36 and 40 <= y < 43 and x % 6 < 3
+ ink = (box and not hole) or stripe or caption
+ gold = (155 + x % 55, 142 + x % 51, 104 + x % 44)
+ gray = 34 + (5 * x + 7 * y) % 5
+ rgb = gold if ink else (gray,) * 3
+ pixels.extend((*[255 - v if inverse else v for v in rgb], 255))
+ raster = image_trace.Raster(width, height, bytes(pixels), False)
+ defaults = image_trace.artwork_defaults(raster)
+ self.assertTrue(defaults.is_artwork)
+ self.assertEqual(defaults.mode, 'dark' if inverse else 'light')
+ cutoff = image_trace.ink_cutoff(defaults.threshold, 50, defaults.mode == 'light')
+ self.assertEqual(cutoff, defaults.threshold)
+ analysis = image_trace.analyze(raster, 'ink', cutoff, defaults.mode == 'light')
+ result = image_trace.trace(analysis, 1, 1, .65, 0)
+ for x, y, expected in ((2, 2, False), (10, 12, True), (20, 20, False),
+ (50, 15, True), (53, 15, False), (13, 41, True),
+ (16, 41, False)):
+ self.assertEqual(traced_ink(result, x + .5, y + .5), expected)
+ self.assertFalse(any((0, 0) in ring for ring in result.rings))
+
+ def test_photo_with_varied_border_uses_photo_default(self):
+ width, height = 60, 36
+ pixels = bytearray()
+ for y in range(height):
+ for x in range(width):
+ pixels.extend((70 + x, 60 + y, 150 - y, 255))
+ self.assertFalse(image_trace.is_artwork(image_trace.Raster(width, height, bytes(pixels), False)))
+
+ def test_ink_slider_monotonic_in_each_polarity(self):
+ for base in (33, 99, 185):
+ dark = [image_trace.ink_cutoff(base, step, False) for step in range(101)]
+ light = [image_trace.ink_cutoff(base, step, True) for step in range(101)]
+ self.assertEqual(dark, sorted(dark))
+ self.assertEqual(light, list(reversed(dark)))
+ self.assertEqual((dark[0], dark[50], dark[-1]), (0, base, 255))
+
+ def test_subpixel_ink_uses_the_antialiased_edge_values(self):
+ # The threshold crossing between columns 2 and 3 is near 3.25.
+ row = b''.join(bytes((v, v, v, 255)) for v in (30, 30, 50, 150, 210, 210, 30))
+ blank = bytes((30, 30, 30, 255)) * 7
+ raster = image_trace.Raster(7, 7, blank + row * 5 + blank, False)
+ result = image_trace.trace(image_trace.analyze(raster, 'ink', 125, True), 1, 1, 0, 0)
+ self.assertEqual(len(result.rings), 1)
+ self.assertTrue(any(abs(x - 3.255) < 1e-8 for x, _ in result.rings[0]))
+ self.assertTrue(traced_ink(result, 3.4, 3))
+ self.assertFalse(traced_ink(result, 3.1, 3))
+
+ def test_single_ink_object_retains_cuts_and_matches_subpixel_whole_sheet_edges(self):
+ # The edge of the large L-shaped cut is antialiased as in a compressed
+ # logo. A smaller disconnected mark sits inside the enclosing outline.
+ pixels = bytearray()
+ for y in range(32):
+ for x in range(56):
+ on_sheet = 3 <= x <= 29 and 3 <= y <= 28
+ slit = 8 <= x <= 10 and 8 <= y <= 23 or 8 <= x <= 23 and 21 <= y <= 23
+ aperture = 16 <= x <= 23 and 8 <= y <= 15
+ island = 19 <= x <= 20 and 11 <= y <= 12
+ separate = 37 <= x <= 47 and 9 <= y <= 22
+ ink = on_sheet and not (slit or aperture) or island or separate
+ level = 170 if ink else 34
+ if x == 3 and 3 <= y <= 28:
+ level = 94
+ pixels.extend((level, level, level, 255))
+ raster = image_trace.Raster(56, 32, bytes(pixels), False)
+ all_ink = image_trace.analyze(raster, 'ink', 85, True)
+ automatic = image_trace.analyze(raster, 'ink_object', 85, True)
+ self.assertIn(automatic.components[0], all_ink.components)
+ self.assertEqual(len(automatic.components), 1)
+ self.assertEqual(len(automatic.components[0]), 3)
+ self.assertEqual(automatic, image_trace.analyze(raster, 'ink_object', 85, True, (5, 5)))
+ result = image_trace.trace(automatic, 1, 1, .625, 0)
+ self.assertFalse(traced_ink(result, 9.5, 17.5))
+ self.assertFalse(traced_ink(result, 16.5, 22.5))
+ self.assertTrue(traced_ink(result, 12.5, 16.5))
+ self.assertFalse(traced_ink(result, 19.5, 11.5))
+ for seed in ((1.5, 1.5), (9.5, 17.5)):
+ self.assertEqual(image_trace.analyze(raster, 'ink_object', 85, True, seed).components, ())
+ for seed in ((19, 11), (40, 12)):
+ picked = image_trace.analyze(raster, 'ink_object', 85, True, seed)
+ self.assertEqual(len(picked.components), 1)
+ self.assertIn(picked.components[0], all_ink.components)
+ self.assertNotEqual(picked, automatic)
+
+ def test_single_ink_object_respects_coverage_and_never_treats_uniform_page_as_object(self):
+ row = b''.join(bytes((v, v, v, 255)) for v in (30, 30, 80, 145, 210, 210, 30))
+ blank = bytes((30, 30, 30, 255)) * 7
+ raster = image_trace.Raster(7, 7, blank + row * 5 + blank, False)
+ for cutoff, includes_edge in ((70, True), (110, False)):
+ selected = image_trace.analyze(raster, 'ink_object', cutoff, True, (4, 3))
+ self.assertEqual(traced_ink(image_trace.trace(selected, 1, 1, 0, 0),
+ 2.5, 3.5), includes_edge)
+ self.assertEqual(image_trace.analyze(raster, 'ink_object', 0, True).components, ())
+ with self.assertRaisesRegex(ValueError, 'inside the image'):
+ image_trace.analyze(raster, 'ink_object', 100, True, (-1, 3))
+
+ def test_picked_transparent_logo_matches_sheet_and_ignores_hole_and_transparent_rgb(self):
+ def pixel(x, y):
+ ring = (2 <= x < 13 and 2 <= y < 13) and not (4 <= x < 11 and 5 <= y < 10)
+ other = 16 <= x < 20 and 6 <= y < 11
+ return bytes((255, 255, 255, 255 if ring or other else 0))
+ raster = image_trace.Raster(22, 16, b''.join(pixel(x, y) for y in range(16)
+ for x in range(22)), True)
+ sheet = image_trace.analyze(raster, 'alpha')
+ ring = image_trace.analyze(raster, 'alpha_object', 128, False, (3, 5))
+ self.assertIn(ring.components[0], sheet.components)
+ self.assertEqual(len(ring.components[0]), 2)
+ self.assertEqual(image_trace.analyze(raster, 'alpha_object'), ring)
+ other = image_trace.analyze(raster, 'alpha_object', 128, False, (17, 7))
+ self.assertIn(other.components[0], sheet.components)
+ self.assertNotEqual(other, ring)
+ for pick in ((5, 6), (0, 0)):
+ self.assertEqual(image_trace.analyze(raster, 'alpha_object', 128, False, pick).components, ())
diff --git a/tests/test_sketch_context.py b/tests/test_sketch_context.py
new file mode 100644
index 0000000..83db97d
--- /dev/null
+++ b/tests/test_sketch_context.py
@@ -0,0 +1,129 @@
+"""Exercise Smart Insert's real command registration against Fusion event stand-ins."""
+
+import importlib.util
+import sys
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import Mock, patch
+
+import InsertTo
+from InsertTo import config
+
+
+class Event:
+ def __init__(self):
+ self.handlers = []
+
+ def add(self, handler):
+ self.handlers.append(handler)
+
+ def remove(self, handler):
+ self.handlers.remove(handler)
+
+ def fire(self, args=None):
+ for handler in self.handlers:
+ handler.notify(args)
+
+
+class SketchContextTests(unittest.TestCase):
+ def setUp(self):
+ class Sketch:
+ isValid = True
+
+ @staticmethod
+ def cast(value):
+ return value if isinstance(value, Sketch) else None
+
+ self.sketch = Sketch()
+ self.app = Mock(activeEditObject=None, activeDocument=object())
+ ui = self.app.userInterface
+ self.pending = Event()
+ self.app.registerCustomEvent.return_value = self.pending
+ self.app.fireCustomEvent.return_value = True
+ self.app.documentActivated = Event()
+ self.app.documentClosed = Event()
+ ui.workspaceActivated = Event()
+ ui.commandStarting = Event()
+ ui.commandCreated = Event()
+ ui.commandTerminated = Event()
+ self.menu = Mock(isValid=True, isVisible=True)
+ workspace = ui.workspaces.itemById.return_value
+ panel = workspace.toolbarTabs.itemById.return_value.toolbarPanels.itemById.return_value
+ panel.controls.addDropDown.return_value = self.menu
+ self.commands = [Mock(isValid=True, commandCreated=Event()) for _ in range(2)]
+ ui.commandDefinitions.addButtonDefinition.side_effect = self.commands
+ core = SimpleNamespace(Application=SimpleNamespace(get=lambda: self.app))
+ for kind in ('Command', 'CommandCreated', 'ApplicationCommand', 'Custom', 'Workspace', 'Document'):
+ setattr(core, kind + 'EventHandler', object)
+ sdk = SimpleNamespace(core=core, fusion=SimpleNamespace(Sketch=Sketch))
+ modules = {'adsk': sdk, 'adsk.core': core, 'adsk.fusion': sdk.fusion}
+ self.svg, self.trace = Mock(), Mock()
+ from InsertTo import svg_geometry
+ # The production subscription helper is SDK-independent and receives the event's handler type.
+ with patch.dict(sys.modules, modules):
+ from InsertTo import dialog
+ spec = importlib.util.spec_from_file_location(
+ 'InsertTo._registration_under_test', Path(svg_geometry.__file__).with_name('InsertTo.py')
+ )
+ self.module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(self.module)
+ self.enterContext(patch.object(self.module.dialog, 'attach', self.svg))
+ self.enterContext(patch.object(InsertTo, 'trace_dialog', SimpleNamespace(TraceDialog=self.trace), create=True))
+ self.enterContext(patch.object(self.module.frame_link, 'install'))
+ self.enterContext(patch.object(self.module.frame_link, 'uninstall'))
+ self.module.run(None)
+ self.addCleanup(self.module.stop, None)
+
+ def assert_available(self, enabled):
+ self.assertEqual(self.menu.isVisible, enabled)
+ for command in self.commands:
+ self.assertEqual(command.controlDefinition.isVisible, enabled)
+ self.assertEqual(command.controlDefinition.isEnabled, enabled)
+
+ def test_enters_leaves_and_switches_documents(self):
+ self.assert_available(False)
+ self.app.activeEditObject = self.sketch
+ self.app.userInterface.commandCreated.fire()
+ self.app.userInterface.commandTerminated.fire()
+ self.app.fireCustomEvent.assert_called_once()
+ self.pending.fire()
+ self.assert_available(True)
+ self.app.activeEditObject = object()
+ self.app.documentActivated.fire()
+ self.pending.fire()
+ self.assert_available(False)
+ self.app.activeDocument = None
+ self.app.documentClosed.fire()
+ self.pending.fire()
+ self.assert_available(False)
+ self.module.stop(None)
+ self.assertFalse(self.app.userInterface.commandStarting.handlers)
+ self.assertFalse(self.pending.handlers)
+ self.app.unregisterCustomEvent.assert_called_once()
+
+ def test_shortcut_uses_current_context_even_before_deferred_refresh(self):
+ self.app.activeEditObject = self.sketch
+ self.pending.fire()
+ self.app.activeEditObject = object()
+ for identifier, definition, attach in zip(
+ (config.COMMAND_ID, config.TRACE_COMMAND_ID), self.commands, (self.svg, self.trace)
+ ):
+ args = SimpleNamespace(commandId=identifier, isCanceled=False)
+ self.app.userInterface.commandStarting.fire(args)
+ self.assertTrue(args.isCanceled)
+ definition.commandCreated.fire(SimpleNamespace(command=Mock()))
+ attach.assert_not_called()
+ other = SimpleNamespace(commandId='SketchLine', isCanceled=False)
+ self.app.userInterface.commandStarting.fire(other)
+ self.assertFalse(other.isCanceled)
+ self.app.activeEditObject = self.sketch
+ for identifier, definition, attach in zip(
+ (config.COMMAND_ID, config.TRACE_COMMAND_ID), self.commands, (self.svg, self.trace)
+ ):
+ args = SimpleNamespace(commandId=identifier, isCanceled=False)
+ self.app.userInterface.commandStarting.fire(args)
+ self.assertFalse(args.isCanceled)
+ command = Mock()
+ definition.commandCreated.fire(SimpleNamespace(command=command))
+ attach.assert_called_once_with(command)
diff --git a/tests/test_trace_alpha_curves.py b/tests/test_trace_alpha_curves.py
new file mode 100644
index 0000000..22a569e
--- /dev/null
+++ b/tests/test_trace_alpha_curves.py
@@ -0,0 +1,83 @@
+"""Circular alpha features on complete and partially recognised closed paths."""
+import math
+import unittest
+
+from InsertTo.image_trace import Raster, analyze, trace
+from InsertTo.trace_primitives import Arc, Circle, Line, recognize
+
+
+def rasterize(width, height, ink):
+ offsets = [(i + .5) / 8 for i in range(8)]
+ pixels = bytearray()
+ for y in range(height):
+ for x in range(width):
+ coverage = sum(ink(x + u, y + v) for u in offsets for v in offsets)
+ pixels.extend((53, 105, 17, round(255 * coverage / 64)))
+ return Raster(width, height, bytes(pixels), True)
+
+
+def fit(raster, circles, arcs):
+ analysis = analyze(raster, 'alpha')
+ result = trace(analysis, 1, 1, .65, 0)
+ return result, recognize(analysis, result, 1, 1, .65, circles, arcs, False)
+
+
+class AlphaCurveTests(unittest.TestCase):
+ def test_ring_and_hole_are_independent_circles_and_never_arcs_when_disabled(self):
+ image = rasterize(90, 85, lambda x, y: 13**2 <= (x - 44.3)**2 + (y - 43.2)**2 <= 28**2)
+ raw, result = fit(image, True, False)
+ self.assertEqual(result.type_counts, (0, 0, 2, 0))
+ self.assertEqual(result.rings, raw.rings)
+ for radius, path in zip((28, 13), result.paths):
+ circle, = path
+ self.assertIsInstance(circle, Circle)
+ self.assertAlmostEqual(circle.radius, radius, delta=.25)
+ self.assertAlmostEqual(circle.center[0], 44.3, delta=.2)
+ self.assertAlmostEqual(circle.center[1], 43.2, delta=.2)
+ legacy, disabled = fit(image, False, True)
+ self.assertIs(legacy, disabled)
+
+ def test_diagonal_chord_and_major_arc_close_on_the_same_two_nodes(self):
+ rotation = complex(math.cos(math.radians(37)), -math.sin(math.radians(37)))
+ def clipped(x, y):
+ p = (complex(x, y) - (72.3 + 67.2j)) * rotation
+ return abs(p) <= 55 and p.real <= 41
+ raw, result = fit(rasterize(150, 140, clipped), False, True)
+ self.assertEqual(result.type_counts, (1, 1, 0, 0))
+ self.assertEqual(result.rings, raw.rings)
+ arc, = (p for p in result.paths[0] if isinstance(p, Arc))
+ line, = (p for p in result.paths[0] if isinstance(p, Line))
+ self.assertEqual(line.start, arc.end)
+ self.assertEqual(line.end, arc.start)
+ self.assertLess(((complex(*arc.mid) - (72.3 + 67.2j)) * rotation).real, -53)
+
+ def test_local_arc_reuses_all_surviving_step_segments_and_both_shared_nodes(self):
+ def step(x, y):
+ u, v = x - 70.3, y - 48.2
+ return ((u >= 0 and u*u + v*v <= 32**2) or
+ (-50 <= u <= 0 and abs(v) <= 32 and not (u < -27 and v < -8)))
+ image = rasterize(112, 90, step)
+ raw, result = fit(image, False, True)
+ self.assertEqual(result.type_counts, (5, 1, 0, 0))
+ ring, = raw.rings
+ original = set(zip(ring, ring[1:] + ring[:1]))
+ path, = result.paths
+ for primitive, following in zip(path, path[1:] + path[:1]):
+ self.assertEqual(primitive.end, following.start)
+ if isinstance(primitive, Line):
+ self.assertIn((primitive.start, primitive.end), original)
+ else:
+ self.assertIn(primitive.start, ring)
+ self.assertIn(primitive.end, ring)
+ disabled, off = fit(image, True, False)
+ self.assertIs(disabled, off)
+
+ def test_digital_step_is_kept_as_a_unit_if_unmodified_sides_exceed_the_alpha_tolerance(self):
+ rotation = complex(math.cos(math.radians(37)), -math.sin(math.radians(37)))
+ def step(x, y):
+ p = (complex(x, y) - (72.3 + 59.2j)) * rotation
+ u, v = p.real, p.imag
+ return ((u >= 0 and u*u + v*v <= 32**2) or
+ (-50 <= u <= 0 and abs(v) <= 32 and not (u < -27 and v < -8)))
+ baseline, result = fit(rasterize(140, 124, step), True, True)
+ self.assertIs(result, baseline)
diff --git a/tests/test_trace_alpha_fit.py b/tests/test_trace_alpha_fit.py
new file mode 100644
index 0000000..16bb599
--- /dev/null
+++ b/tests/test_trace_alpha_fit.py
@@ -0,0 +1,172 @@
+"""Opacity-level evidence is optional, local to the original mask ring, and bounded."""
+import math
+import unittest
+from unittest.mock import patch
+
+from InsertTo import image_trace
+from InsertTo.trace_primitives import Ellipse, recognize
+
+
+def rasterize(width, height, ink):
+ offsets = (.125, .375, .625, .875)
+ data = bytearray()
+ for y in range(height):
+ for x in range(width):
+ cover = sum(ink(x + dx, y + dy) for dx in offsets for dy in offsets)
+ # Hidden RGB deliberately varies independently of coverage.
+ data.extend((x % 256, (x + 3*y) % 256, y % 256, round(255 * cover / 16)))
+ return image_trace.Raster(width, height, bytes(data), True)
+
+
+def oval(x, y, cx, cy, a, b):
+ return ((x - cx) / a) ** 2 + ((y - cy) / b) ** 2 <= 1
+
+
+def fit(analysis, scale=1, cutoff=0):
+ baseline = image_trace.trace(analysis, scale, scale, .65 * scale, cutoff * scale**2)
+ result = recognize(analysis, baseline, scale, scale, .65 * scale, False, False, True)
+ return baseline, result
+
+
+class AlphaFitTests(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.ellipse = rasterize(120, 80, lambda x, y: oval(x, y, 60, 40, 40, 18))
+ cls.sheet = rasterize(132, 90, lambda x, y: (oval(x, y, 71, 51, 41, 22)
+ and not oval(x, y, 71, 51, 30, 13)) or oval(x, y, 14, 14, 7, 4))
+
+ def test_rotated_alpha_capsule_has_two_measured_sides_and_two_tangent_arcs(self):
+ for degrees in (15, 37):
+ angle = math.radians(degrees)
+ unit = complex(math.cos(angle), math.sin(angle))
+
+ def inside(x, y):
+ p = (complex(x, y) - complex(92.3, 70.2)) * unit.conjugate()
+ return max(0, abs(p.real) - 36) ** 2 + p.imag ** 2 <= 23 ** 2
+
+ analysis = image_trace.analyze(rasterize(184, 140, inside), 'alpha')
+ baseline = image_trace.trace(analysis, 1, 1, .65, 0)
+ result = recognize(analysis, baseline, 1, 1, .65, False, True, False)
+ self.assertEqual(result.type_counts, (2, 2, 0, 0), degrees)
+ curves = result.paths[0]
+ for i, curve in enumerate(curves):
+ self.assertEqual(curve.end, curves[(i + 1) % len(curves)].start)
+ direction = complex(*curves[0].end) - complex(*curves[0].start)
+ self.assertAlmostEqual(abs(direction), 72, delta=.55)
+ self.assertLess(abs((direction / abs(direction) / unit).imag), .015)
+
+ def test_curved_sides_are_not_converted_to_two_straights(self):
+ def inside(x, y):
+ p = (complex(x, y) - complex(92, 70)) * complex(.8, -.6)
+ along = abs(p.real)
+ if along <= 36:
+ return abs(p.imag) <= 23 - 1.5 * math.cos(math.pi * along / 72) ** 2
+ return (along - 36) ** 2 + p.imag ** 2 <= 23 ** 2
+
+ analysis = image_trace.analyze(rasterize(184, 140, inside), 'alpha')
+ baseline = image_trace.trace(analysis, 1, 1, .65, 0)
+ result = recognize(analysis, baseline, 1, 1, .65, False, True, False)
+ self.assertNotEqual(result.type_counts, (2, 2, 0, 0))
+
+ def test_isoline_uses_measured_alpha_values_and_is_cached_across_scales(self):
+ analysis = image_trace.analyze(self.ellipse, 'alpha')
+ ring = analysis.components[0][0]
+ with patch.object(image_trace, '_alpha_outline', wraps=image_trace._alpha_outline) as interpolate:
+ raw = image_trace.trace(analysis, 1, 1, .65, 0)
+ off = recognize(analysis, raw, 1, 1, .65, False, False, False)
+ self.assertIs(raw, off)
+ interpolate.assert_not_called()
+ for scale in (1, .5, 2):
+ previous, result = fit(analysis, scale)
+ self.assertEqual(result.type_counts, (0, 0, 0, 1))
+ self.assertEqual(previous.rings, result.rings)
+ interpolate.assert_called_once()
+ reference = analysis.ellipse_reference(ring)
+ self.assertIsNot(reference, ring)
+ self.assertIs(reference, analysis.ellipse_reference(ring))
+ # Verify the scalar threshold on every surviving interpolated sample.
+ width, data = self.ellipse.width, self.ellipse.rgba
+ for x, y in reference:
+ if x % 1 == .5:
+ col, row = int(x), math.floor(y - .5)
+ samples = [data[4*((row + k)*width + col) + 3] for k in (0, 1)]
+ t = y - row - .5
+ else:
+ col, row = math.floor(x - .5), int(y)
+ samples = [data[4*(row*width + col + k) + 3] for k in (0, 1)]
+ t = x - col - .5
+ self.assertAlmostEqual((1-t)*samples[0] + t*samples[1], 127.5, places=8)
+
+ def test_hard_constant_translucent_and_local_noise_do_not_redefine_a_ring(self):
+ for opacity, noise in ((255, False), (175, False), (255, True)):
+ data = bytearray(self.ellipse.rgba)
+ for i in range(3, len(data), 4):
+ x = (i // 4) % self.ellipse.width
+ value = data[i]
+ if not noise or x > 26:
+ data[i] = opacity if value >= 128 else 0
+ image = image_trace.Raster(self.ellipse.width, self.ellipse.height, bytes(data), True)
+ analysis = image_trace.analyze(image, 'alpha')
+ ring = analysis.components[0][0]
+ self.assertIs(analysis.ellipse_reference(ring), ring)
+ previous, result = fit(analysis)
+ self.assertIs(previous, result)
+
+ def test_mask_filter_seed_and_nested_hole_keep_their_own_references(self):
+ analysis = image_trace.analyze(self.sheet, 'alpha')
+ baseline, result = fit(analysis, cutoff=100)
+ self.assertEqual(result.type_counts, (0, 0, 0, 2))
+ self.assertEqual(result.rings, baseline.rings)
+ for path in result.paths:
+ self.assertIsInstance(path[0], Ellipse)
+ self.assertAlmostEqual(path[0].center[0], 71, delta=.2)
+ self.assertAlmostEqual(path[0].center[1], 51, delta=.2)
+
+ picked = image_trace.analyze(self.sheet, 'alpha_object', 128, False, (71, 32))
+ self.assertEqual([len(g) for g in picked.components], [2])
+ self.assertEqual(fit(picked)[1].type_counts, (0, 0, 0, 2))
+ self.assertEqual(image_trace.analyze(self.sheet, 'alpha_object', 128, False, (71, 51)).components, ())
+ inverse = image_trace.analyze(self.ellipse, 'alpha', 128, True)
+ outer, hole = inverse.components[0]
+ self.assertIs(inverse.ellipse_reference(outer), outer)
+ self.assertIsNot(inverse.ellipse_reference(hole), hole)
+
+ def test_coverage_moves_the_level_and_preserves_binary_mask_selection(self):
+ output = []
+ for threshold in (48, 128, 200):
+ analysis = image_trace.analyze(self.ellipse, 'alpha', threshold)
+ previous, result = fit(analysis)
+ self.assertEqual(result.type_counts, (0, 0, 0, 1))
+ self.assertEqual(result.rings, previous.rings)
+ shape = result.paths[0][0]
+ output.append(math.dist(shape.center, shape.major))
+ self.assertGreater(output[0], output[1])
+ self.assertGreater(output[1], output[2])
+
+ def test_diagonal_saddle_and_canvas_clipping_decline_subpixel_fit(self):
+ source = self.ellipse
+ width = source.width
+ cells = {(i % width, i // width) for i, a in enumerate(source.rgba[3::4]) if a >= 128}
+ touch = next((x, y) for x in range(2, width - 2) for y in range(2, source.height - 2)
+ if (x, y) not in cells and
+ all((x+dx,y+dy) not in cells for dx,dy in ((1,0),(-1,0),(0,1),(0,-1))) and
+ any((x+dx,y+dy) in cells for dx,dy in ((1,1),(-1,1),(-1,-1),(1,-1))))
+ data = bytearray(source.rgba)
+ data[4*(touch[1]*width + touch[0]) + 3] = 255
+ joined = image_trace.analyze(image_trace.Raster(width, source.height, bytes(data), True), 'alpha')
+ largest = max((g[0] for g in joined.components), key=len)
+ self.assertIs(joined.ellipse_reference(largest), largest)
+ clipped = rasterize(96, 72, lambda x, y: oval(x, y, 33, 36, 40, 18))
+ cropped = image_trace.analyze(clipped, 'alpha')
+ ring = cropped.components[0][0]
+ self.assertIs(cropped.ellipse_reference(ring), ring)
+
+ def test_narrow_rim_keeps_both_binary_profiles_when_clearance_is_uncertain(self):
+ raster = rasterize(112, 80, lambda x, y: oval(x, y, 56, 40, 40, 18)
+ and not oval(x, y, 56, 40, 38.3, 16.3))
+ analysis = image_trace.analyze(raster, 'alpha')
+ self.assertEqual([len(g) for g in analysis.components], [2])
+ for ring in analysis.components[0]:
+ self.assertIsNot(analysis.ellipse_reference(ring), ring)
+ previous, result = fit(analysis)
+ self.assertIs(previous, result)
diff --git a/tests/test_trace_arc_clearance.py b/tests/test_trace_arc_clearance.py
new file mode 100644
index 0000000..6bf6daf
--- /dev/null
+++ b/tests/test_trace_arc_clearance.py
@@ -0,0 +1,36 @@
+"""Finite arcs protect nearby geometry without blocking the unused half of a circle."""
+
+import math
+import unittest
+
+from InsertTo.trace_primitives import _ArcBand
+
+
+class FiniteArcClearanceTests(unittest.TestCase):
+ def test_minor_and_major_arcs_have_complementary_interior_intersections(self):
+ quarter = _ArcBand(0j, 0j, 10, 10+0j, 10j, math.pi / 2)
+ remainder = _ArcBand(0j, 0j, 10, 10+0j, 10j, -3 * math.pi / 2)
+ outside = [(-12+1j, -8+1j)]
+ inside = [(6+6j, 9+9j)]
+ self.assertTrue(quarter.clear(outside, .1))
+ self.assertFalse(remainder.clear(outside, .1))
+ self.assertFalse(quarter.clear(inside, .1))
+ self.assertTrue(remainder.clear(inside, .1))
+
+ def test_clearance_includes_the_ends_and_tangents_in_both_directions(self):
+ for start, end, sweep in [(10+0j, 10j, math.pi / 2), (10j, 10+0j, -math.pi / 2)]:
+ arc = _ArcBand(0j, 0j, 10, start, end, sweep)
+ self.assertFalse(arc.clear([(9-.05j, 11-.05j)], .1))
+ self.assertTrue(arc.clear([(9-.2j, 11-.2j)], .1))
+ normal = complex(2**-.5, 2**-.5)
+ a, b = normal*(10.08-2j), normal*(10.08+2j)
+ self.assertFalse(arc.clear([(a, b)], .1))
+ self.assertTrue(arc.clear([(a, b)], .05))
+
+ def test_adjacent_arcs_allow_one_join_and_reject_a_second_crossing(self):
+ first = _ArcBand(0j, 0j, 5, 3+4j, -5+0j, -math.pi-math.atan2(4,3))
+ center = 6+0j
+ outgoing = _ArcBand(center, center, 5, 3+4j, 11+0j, -math.atan2(4,-3))
+ crossing = _ArcBand(center, center, 5, 3+4j, 11+0j, math.tau-math.atan2(4,-3))
+ self.assertTrue(first.clear_of_arc(outgoing, .1))
+ self.assertFalse(first.clear_of_arc(crossing, .1))
diff --git a/tests/test_trace_command_events.py b/tests/test_trace_command_events.py
new file mode 100644
index 0000000..38c007f
--- /dev/null
+++ b/tests/test_trace_command_events.py
@@ -0,0 +1,72 @@
+"""Trace dialog input and validation callbacks must leave Fusion's transaction alone."""
+
+import importlib
+import sys
+from types import SimpleNamespace
+import unittest
+from unittest.mock import Mock, patch
+
+from InsertTo.image_trace import Raster
+
+
+class TraceCommandEventsTests(unittest.TestCase):
+ def setUp(self):
+ sdk = Mock()
+ with patch.dict(sys.modules, {'adsk': sdk, 'adsk.core': sdk.core, 'adsk.fusion': sdk.fusion}):
+ self.module = importlib.import_module('InsertTo.trace_dialog')
+ self.dialog = self.module.TraceDialog.__new__(self.module.TraceDialog)
+ self.dialog.command = Mock()
+ self.dialog.graphics = None
+ self.dialog.transform = Mock()
+ self.dialog.preview_renderer = Mock()
+ self.dialog.raster = self.dialog.preview_renderer.raster
+ self.dialog.pick = Mock()
+ self.dialog.preview_mode = Mock()
+ self.dialog._show_trace_controls = Mock()
+
+ def test_native_inputs_and_mouse_drags_do_not_start_a_preview_inside_the_callback(self):
+ for input_id in ('traceDetail', 'traceEdgeCoverage', 'traceSmallShapes',
+ 'traceRecognizeArcs', 'traceRecognizeCircles', 'traceRecognizeEllipses',
+ 'tracePreviewMode', 'imageWidth', 'traceAutoSubject'):
+ self.dialog._changed(SimpleNamespace(input=SimpleNamespace(id=input_id)))
+ self.dialog.transform.read_drag.return_value = True
+ self.dialog._dragged(None)
+ self.dialog.command.doExecutePreview.assert_not_called()
+ self.dialog.preview_renderer.draw.assert_not_called()
+
+ def test_invalid_validation_does_not_delete_live_graphics(self):
+ args = SimpleNamespace(areInputsValid=False)
+ with patch.object(self.module._Dialog, '_validate'):
+ self.dialog._validate(args)
+ self.assertFalse(args.areInputsValid)
+ self.dialog.preview_renderer.clear.assert_not_called()
+ self.dialog.preview_renderer.close.assert_not_called()
+
+ def test_new_file_replaces_old_graphics_only_at_native_preview(self):
+ dialog = self.dialog
+ old = dialog.preview_renderer
+ for field in ('confirm', 'browse', 'width', 'detail', 'small_shapes', 'arcs',
+ 'circles', 'ellipses', 'coverage'):
+ setattr(dialog, field, Mock())
+ dialog._fits = {}
+ raster = Raster(1, 1, bytes((0, 0, 0, 255)), True)
+ with patch.object(self.module.image_trace, 'load_image', return_value=raster):
+ dialog._load_file('new-source.png')
+ self.assertTrue(dialog.raster)
+ self.assertFalse(dialog._is_source_entity(old._source_entity))
+ old.close.assert_not_called()
+
+ target = object()
+ dialog._placements = Mock(return_value=(SimpleNamespace(pivot=(0, 0)), target, None))
+ result = Mock()
+ dialog._result = Mock(return_value=result)
+ dialog._dimensions = Mock()
+ dialog.preview_mode.selectedItem.index = 1
+ dialog.design = Mock()
+ sketch = Mock()
+ with patch.object(self.module.fusion_import, 'sketch_for_target', return_value=sketch), \
+ patch.object(self.module.trace_render, 'Preview') as make_renderer:
+ dialog._preview_graphics(sketch, None)
+ old.close.assert_called_once_with()
+ make_renderer.assert_called_once_with(dialog.raster)
+ make_renderer.return_value.draw.assert_called_once_with(sketch, target, result, 'overlay')
diff --git a/tests/test_trace_corner_arc_interiors.py b/tests/test_trace_corner_arc_interiors.py
new file mode 100644
index 0000000..ca8bff6
--- /dev/null
+++ b/tests/test_trace_corner_arc_interiors.py
@@ -0,0 +1,64 @@
+"""Circular interiors behind threshold-distorted end joins of a C-shaped ribbon."""
+import math
+import unittest
+
+from InsertTo.image_trace import Analysis, TraceResult, trace
+from InsertTo.trace_primitives import Arc, Line, recognize
+
+
+def ribbon():
+ # The first and last three degrees drift at the threshold. In between, the
+ # exterior and interior both have constant radius and substantial coverage.
+ sweep = math.radians(270)
+ ring = []
+ for radius, direction in ((40, 1), (24, -1)):
+ indices = range(161) if direction == 1 else reversed(range(161))
+ for index in indices:
+ fraction = index / 160
+ angle = (fraction - .5) * sweep
+ to_join = min(fraction, 1 - fraction) * sweep
+ drift = direction * 1.3 * max(0., 1 - to_join / .05)
+ ring.append(((radius + drift) * math.cos(angle), (radius + drift) * math.sin(angle)))
+ return tuple(ring)
+
+
+class CornerArcInteriorTests(unittest.TestCase):
+ def test_interiors_stop_before_the_corner_and_retain_original_nodes_and_lines(self):
+ raw = ribbon()
+ analysis = Analysis(((raw,),), preserve_corners=False)
+ old = trace(analysis, 1, 1, .65, 0)
+ for reverse in (False, True):
+ contour = tuple(reversed(raw)) if reverse else raw
+ ring = tuple(reversed(old.rings[0])) if reverse else old.rings[0]
+ evidence = Analysis(((contour,),), preserve_corners=False)
+ baseline = TraceResult((ring,))
+ out = recognize(evidence, baseline, 1, 1, .65, circles=False, arcs=True)
+ self.assertEqual(out.type_counts, (6, 2, 0, 0))
+ original_edges = set(zip(ring, ring[1:] + ring[:1]))
+ path, = out.paths
+ for curve, following in zip(path, path[1:] + path[:1]):
+ self.assertEqual(curve.end, following.start)
+ if isinstance(curve, Line):
+ self.assertIn((curve.start, curve.end), original_edges)
+ else:
+ self.assertIn(curve.start, ring)
+ self.assertIn(curve.end, ring)
+ self.assertIs(recognize(evidence, baseline, 1, 1, .65, False, False), baseline)
+
+ def test_variable_curvature_between_real_corners_is_not_a_circular_run(self):
+ analysis = Analysis(((ribbon(),),), preserve_corners=False)
+ # Stretching the underlying analytic arcs creates visibly changing
+ # curvature. Stable pixel-space radii would report a false positive.
+ baseline = trace(analysis, 1.08, 1, .65, 0)
+ out = recognize(analysis, baseline, 1.08, 1, .65, False, True)
+ self.assertIs(out, baseline)
+
+ def test_secondary_fit_obeys_clearance_to_other_islands(self):
+ neighbour = ((40.25, -1), (43, -1), (43, 1), (40.25, 1))
+ analysis = Analysis(((ribbon(),), (neighbour,)), preserve_corners=False)
+ baseline = trace(analysis, 1, 1, .65, 0)
+ out = recognize(analysis, baseline, 1, 1, .65, False, True)
+ curves = [p for p in out.paths[0] if isinstance(p, Arc)]
+ self.assertEqual(len(curves), 1)
+ self.assertAlmostEqual(math.hypot(*curves[0].mid), 24, delta=.2)
+ self.assertEqual(tuple(p.start for p in out.paths[1]), neighbour)
diff --git a/tests/test_trace_dialog.py b/tests/test_trace_dialog.py
new file mode 100644
index 0000000..6a7c67e
--- /dev/null
+++ b/tests/test_trace_dialog.py
@@ -0,0 +1,449 @@
+"""Verify what Fusion's Preview, Execute and Destroy events do to a trace."""
+
+import importlib
+import sys
+import unittest
+from itertools import product
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import Mock, patch
+
+from InsertTo import image_trace, svg_geometry, trace_primitives
+
+
+class TraceDialogTests(unittest.TestCase):
+ def setUp(self):
+ sdk = Mock()
+ sdk_modules = {'adsk': sdk, 'adsk.core': sdk.core, 'adsk.fusion': sdk.fusion}
+ with patch.dict(sys.modules, sdk_modules):
+ self.module = importlib.import_module('InsertTo.trace_dialog')
+
+ self.session = self.module.TraceDialog.__new__(self.module.TraceDialog)
+ session = self.session
+ session.raster = image_trace.load_image(str(Path(__file__).with_name('fixtures') /
+ 'transparent-logo.png'))
+ session.seed = None
+ session.preview_error = ''
+ session._focus_pick = False
+ session._dense_count = 0
+ session.defaults = image_trace.artwork_defaults(session.raster)
+ session.pick = Mock(id='traceSubject', isVisible=False)
+ session.reset = SimpleNamespace(isVisible=False)
+ session.confirm = SimpleNamespace(value=False, isVisible=False)
+ session.preview_mode = Mock(selectedItem=SimpleNamespace(index=1))
+ session.detail = SimpleNamespace(valueOne=5, isVisible=False)
+ session.small_shapes = SimpleNamespace(valueOne=0, isVisible=True)
+ session.recognition = SimpleNamespace(isVisible=False)
+ session.circles = SimpleNamespace(value=True, isVisible=False)
+ session.arcs = SimpleNamespace(value=True, isVisible=False)
+ session.ellipses = SimpleNamespace(value=True, isVisible=False)
+ session._fits = {}
+ session.coverage = SimpleNamespace(valueOne=50, isVisible=True)
+ session.view = SimpleNamespace(isVisible=True)
+ session._analysis_key = session._result_key = session.analysis = session.result = None
+ self.original = svg_geometry.Placement(0, 0, 20, 18)
+ self.moved = svg_geometry.Placement(11, -9, 20, 18, rotation=.3)
+
+ def test_move_rotation_and_refit_reuse_pixel_analysis(self):
+ session = self.session
+ with patch.object(image_trace, 'analyze', wraps=image_trace.analyze) as analyze, \
+ patch.object(image_trace, 'trace', wraps=image_trace.trace) as trace:
+ first = session._result(self.original)
+ self.assertIs(session._result(self.moved), first)
+ self.assertEqual(trace.call_count, 1)
+ session.detail.valueOne = 7
+ session._result(self.moved)
+ scaled = svg_geometry.Placement(11, -9, 40, 18, rotation=.3)
+ session._result(scaled)
+ self.assertEqual(trace.call_count, 3)
+ self.assertEqual(analyze.call_count, 1)
+ session.coverage.valueOne = 38
+ session._result(scaled)
+ self.assertEqual(analyze.call_count, 2)
+
+ def test_recognition_toggles_only_refit_curves_and_reuse_each_combination(self):
+ session = self.session
+ session.command = Mock()
+ combinations = tuple(product((False, True), repeat=3))
+ variants = {flags: Mock() for flags in combinations if any(flags)}
+ def fit(analysis, outlines, sx, sy, tolerance, circles, arcs, ellipses):
+ return variants[circles, arcs, ellipses]
+
+ with patch.object(image_trace, 'analyze', wraps=image_trace.analyze) as analyze, \
+ patch.object(image_trace, 'trace', wraps=image_trace.trace) as trace, \
+ patch.object(self.module.trace_primitives, 'recognize', side_effect=fit) as recognize:
+ for index, flags in enumerate(combinations):
+ session.circles.value, session.arcs.value, session.ellipses.value = flags
+ result = session._result(self.original)
+ if any(flags):
+ self.assertIs(result, variants[flags])
+ self.assertEqual(recognize.call_args.args[-3:], flags)
+ self.assertIs(recognize.call_args.args[1], variants[False, False, False])
+ else:
+ self.assertEqual(result.paths, ())
+ variants[flags] = result
+ self.assertEqual(recognize.call_count, index)
+ for flags in reversed(combinations):
+ session.circles.value, session.arcs.value, session.ellipses.value = flags
+ self.assertIs(session._result(self.moved), variants[flags])
+ for control in ('traceRecognizeCircles', 'traceRecognizeArcs', 'traceRecognizeEllipses'):
+ session._changed(SimpleNamespace(input=SimpleNamespace(id=control)))
+ self.assertEqual(recognize.call_count, 7)
+ self.assertEqual(trace.call_count, 1)
+ self.assertEqual(analyze.call_count, 1)
+ session.command.doExecutePreview.assert_not_called()
+
+ @staticmethod
+ def _ellipse_raster(transparent):
+ width, height = 120, 80
+ samples = (.125, .375, .625, .875)
+ pixels = bytearray()
+ for y in range(height):
+ for x in range(width):
+ covered = sum(((x + dx - 60) / 40) ** 2 + ((y + dy - 40) / 18) ** 2 <= 1
+ for dx in samples for dy in samples)
+ gray = round(255 * (1 - covered / 16))
+ color = (0, 0, 0, 255 - gray) if transparent else (gray, gray, gray, 255)
+ pixels.extend(color)
+ return image_trace.Raster(width, height, bytes(pixels), transparent)
+
+ def test_ellipse_toggle_leaves_the_baseline_available_with_other_recognizers_off(self):
+ session = self.session
+ session.raster = self._ellipse_raster(transparent=False)
+ session.defaults = image_trace.artwork_defaults(session.raster)
+ session.arcs.value = session.circles.value = False
+ target = svg_geometry.Placement(0, 0, session.raster.width, session.raster.height)
+ fitted = session._result(target)
+ self.assertEqual(fitted.type_counts, (0, 0, 0, 1))
+ session.ellipses.value = False
+ baseline = session._result(target)
+ self.assertEqual(fitted.rings, baseline.rings)
+ self.assertEqual(baseline.paths, ())
+ session.ellipses.value = True
+ self.assertIs(session._result(target), fitted)
+
+ def test_antialiased_alpha_ellipse_reuses_outline_when_recognition_is_toggled(self):
+ session = self.session
+ session.raster = self._ellipse_raster(transparent=True)
+ session.defaults = image_trace.artwork_defaults(session.raster)
+ session.arcs.value = session.circles.value = False
+ target = svg_geometry.Placement(0, 0, session.raster.width, session.raster.height)
+ with patch.object(image_trace, 'analyze', wraps=image_trace.analyze) as analyze, \
+ patch.object(trace_primitives, 'recognize', wraps=trace_primitives.recognize) as recognize:
+ fitted = session._result(target)
+ self.assertEqual(fitted.type_counts, (0, 0, 0, 1))
+ self.assertEqual(len(fitted.rings), 1)
+ session.ellipses.value = False
+ baseline = session._result(target)
+ self.assertEqual(fitted.rings, baseline.rings)
+ self.assertEqual(baseline.paths, ())
+ self.assertGreater(baseline.curve_count, 4)
+ session.ellipses.value = True
+ self.assertIs(session._result(target), fitted)
+ analyze.assert_called_once()
+ recognize.assert_called_once()
+
+ def test_changing_detail_and_mask_invalidates_recognition(self):
+ session = self.session
+ with patch.object(image_trace, 'analyze', wraps=image_trace.analyze) as analyze, \
+ patch.object(self.module.trace_primitives, 'recognize',
+ side_effect=lambda analysis, outlines, *options: outlines) as recognize:
+ first = session._result(self.original)
+ session.detail.valueOne += 1
+ second = session._result(self.original)
+ self.assertIsNot(first, second)
+ self.assertEqual(analyze.call_count, 1)
+ session.coverage.valueOne -= 10
+ third = session._result(self.original)
+ self.assertIsNot(second, third)
+ self.assertEqual(analyze.call_count, 2)
+ scaled = svg_geometry.Placement(0, 0, self.original.width_mm * 2, self.original.height_mm)
+ session._result(scaled)
+ self.assertEqual(recognize.call_count, 4)
+ self.assertEqual(analyze.call_count, 2)
+
+ def test_dense_guard_and_status_use_actual_curve_types(self):
+ session = self.session
+ self.prepare_preview()
+ session._show_target_controls = Mock()
+ ring = ((0, 0),) * 4000
+ # The source is dense, but insertion uses only four primitives.
+ paths = ((trace_primitives.Line((0, 0), (2, 0)), trace_primitives.Arc((2, 0), (1, 1), (0, 0))),
+ (trace_primitives.Circle((6, 6), 1),),
+ (trace_primitives.Ellipse((12, 12), (15, 12), (12, 13)),))
+ result = image_trace.TraceResult((ring, ((7, 6), (6, 7), (5, 6), (6, 5)),
+ ((15, 12), (12, 13), (9, 12), (12, 11))), paths)
+ session._result = Mock(return_value=result)
+ args = SimpleNamespace()
+ session._validate(args)
+ self.assertTrue(args.areInputsValid)
+ self.assertFalse(session.confirm.isVisible)
+ self.assertIn('4 sketch curves (1 line, 1 arc, 1 circle, 1 ellipse)', session.status.text)
+
+ def test_status_pluralizes_ellipse_counts(self):
+ session = self.session
+ self.prepare_preview()
+ for count, label in ((1, '1 sketch curve (1 ellipse)'), (2, '2 sketch curves (2 ellipses)')):
+ result = SimpleNamespace(curve_count=count, type_counts=(0, 0, 0, count), rings=[()] * count)
+ session._result = Mock(return_value=result)
+ session._dimensions(self.original)
+ self.assertIn(label, session.status.text)
+
+ def test_new_file_starts_automatic_and_resets_the_controls(self):
+ session = self.session
+ session.preview_renderer = None
+ session.browse = Mock()
+ session.width = Mock()
+ fixtures = Path(__file__).with_name('fixtures')
+ for filename in ('transparent-logo.png', 'noisy-print.jpg'):
+ session.seed = (1, 1)
+ session.circles.value = session.arcs.value = session.ellipses.value = False
+ session.detail.valueOne = 0
+ session.coverage.valueOne = 100
+ session.small_shapes.valueOne = 32
+ session._fits[(False, False, True)] = object()
+ session._load_file(str(fixtures / filename))
+ self.assertEqual(session._fits, {})
+ self.assertEqual(session.defaults, image_trace.artwork_defaults(session.raster))
+ self.assertTrue(session.detail.isVisible)
+ self.assertTrue(session.circles.value and session.arcs.value and session.ellipses.value)
+ self.assertTrue(session.pick.isVisible)
+ self.assertFalse(session.reset.isVisible)
+ self.assertIsNone(session.seed)
+ self.assertEqual((session.detail.valueOne, session.small_shapes.valueOne, session.coverage.valueOne),
+ (5, 0, 50))
+
+ def test_edge_coverage_grows_the_mask_for_opaque_and_transparent_artwork(self):
+ session = self.session
+ colors = ((0, 0, 0, 255), (100, 100, 100, 180), (160, 160, 160, 100), (255, 255, 255, 255))
+ for mode in ('dark', 'light', 'alpha'):
+ has_alpha = mode == 'alpha'
+ pixels = bytes(v for r, g, b, a in colors for v in (r, g, b, a if has_alpha else 255))
+ session.raster = image_trace.Raster(4, 1, pixels, has_alpha)
+ session.defaults = image_trace.ArtworkDefaults(True, mode, 128)
+ areas = []
+ for coverage in (20, 50, 80):
+ session.coverage.valueOne = coverage
+ rings = session._result(self.original).rings
+ areas.append(sum(image_trace._area(ring) for ring in rings))
+ self.assertEqual(areas, sorted(areas))
+ self.assertGreater(areas[-1], areas[0])
+
+ def test_filter_uses_source_pixel_area_and_keeps_holes_when_the_image_is_resized(self):
+ session = self.session
+ rows = ('.......', '.###...', '.#.#.#.', '.###...', '.......')
+ pixels = bytes(v for row in rows for c in row for v in (0, 0, 0, 255 if c == '#' else 0))
+ session.raster = image_trace.Raster(7, 5, pixels, True)
+ with patch.object(image_trace, 'analyze', wraps=image_trace.analyze) as analyze:
+ self.assertEqual(len(session._result(self.original).rings), 3)
+ session.small_shapes.valueOne = 2
+ cleaned = session._result(self.original)
+ self.assertEqual(len(cleaned.rings), 2)
+ self.assertEqual(sum(image_trace._area(r) for r in cleaned.rings), 8)
+ scaled = svg_geometry.Placement(0, 0, 70, 5)
+ self.assertEqual(cleaned.rings, session._result(scaled).rings)
+ self.assertEqual(analyze.call_count, 1)
+
+ def test_filter_includes_an_island_exactly_at_cutoff_at_fractional_scale(self):
+ session = self.session
+ rows = ('###..#....',) + ('..........',) * 9
+ pixels = bytes(v for row in rows for c in row for v in (0, 0, 0, 255 if c == '#' else 0))
+ session.raster = image_trace.Raster(10, 10, pixels, True)
+ session.small_shapes.valueOne = 3
+ target = svg_geometry.Placement(0, 0, 1, 3)
+ rings = session._result(target).rings
+ self.assertEqual(len(rings), 1)
+ self.assertEqual(image_trace._area(rings[0]), 3)
+
+ def test_default_artwork_keeps_a_one_pixel_slot_open_in_transparent_png(self):
+ session = self.session
+ rows = ('##.##',) * 4 + ('#####',) * 2
+ pixels = bytes(v for row in rows for c in row for v in (0, 0, 0, 255 if c == '#' else 0))
+ session.raster = image_trace.Raster(5, 6, pixels, True)
+ target = svg_geometry.Placement(0, 0, 5, 6)
+ result = session._result(target)
+ self.assertEqual(len(result.rings), 1)
+ self.assertIn((2, 4), result.rings[0])
+ self.assertIn((3, 4), result.rings[0])
+
+ def test_same_controls_for_any_image_and_no_edge_growth_until_photo_object_is_picked(self):
+ session = self.session
+ for artwork in (False, True):
+ for seed in (None, (1, 2)):
+ session.defaults = image_trace.ArtworkDefaults(artwork, 'dark', 128)
+ session.seed = seed
+ session._show_trace_controls()
+ self.assertTrue(all(c.isVisible for c in (session.detail, session.small_shapes, session.recognition, session.pick)))
+ self.assertEqual(session.reset.isVisible, seed is not None)
+ self.assertEqual(session.coverage.isVisible, artwork or seed is not None)
+ session.raster = None
+ session._show_trace_controls()
+ self.assertFalse(any(c.isVisible for c in (session.small_shapes, session.coverage, session.detail,
+ session.reset, session.pick, session.view, session.recognition)))
+
+ def test_unified_dialog_builds_two_main_sliders_and_no_trace_type_picker(self):
+ inputs = Mock()
+ inputs.addGroupCommandInput.side_effect = [Mock(), Mock()]
+ self.session._source_options(inputs)
+ ids = [call.args[0] for call in inputs.addIntegerSliderCommandInput.call_args_list]
+ self.assertEqual(ids, ['traceDetail', 'traceSmallShapes'])
+ inputs.addGroupCommandInput.assert_any_call('traceRecognition', 'Recognize')
+ self.assertTrue(self.session.recognition.isExpanded)
+ checkboxes = [call.args for call in self.session.recognition.children.addBoolValueInput.call_args_list]
+ self.assertIn(('traceRecognizeCircles', 'Circles', True, '', True), checkboxes)
+ self.assertIn(('traceRecognizeArcs', 'Arcs', True, '', True), checkboxes)
+ self.assertIn(('traceRecognizeEllipses', 'Ellipses', True, '', True), checkboxes)
+ inputs.addDropDownCommandInput.assert_not_called()
+ children = self.session.view.children
+ self.assertEqual(children.addIntegerSliderCommandInput.call_args.args[0], 'traceEdgeCoverage')
+ self.assertEqual(children.addDropDownCommandInput.call_args.args[0], 'tracePreviewMode')
+
+ def test_pick_inside_artwork_keeps_only_the_selected_shape_and_its_hole(self):
+ session = self.session
+ rows = ('.........', '.###..##.', '.#.#..##.', '.###.....', '.........')
+ for mode in ('alpha', 'light', 'dark'):
+ pixels = bytearray()
+ for row in rows:
+ for c in row:
+ ink = c == '#'
+ value = 255 if ink == (mode == 'light') else 0
+ alpha = 0 if mode == 'alpha' and not ink else 255
+ pixels.extend((value, value, value, alpha))
+ session.raster = image_trace.Raster(9, 5, bytes(pixels), mode == 'alpha')
+ session.defaults = image_trace.artwork_defaults(session.raster)
+ self.assertTrue(session.defaults.is_artwork)
+ session._analysis_key = None
+ session.seed = None
+ self.assertEqual(len(session._result(self.original).rings), 3)
+ session.seed = (1, 1)
+ session.circles.value = session.arcs.value = session.ellipses.value = False
+ selected = session._result(self.original)
+ self.assertEqual(len(selected.rings), 2)
+ self.assertLess(max(x for ring in selected.rings for x, _ in ring), 6)
+ session.seed = (2, 2)
+ self.assertFalse(session._result(self.original).rings)
+
+ def test_select_photo_pixel_reuses_the_rendered_placement_and_excludes_other_graphics(self):
+ session = self.session
+ source = object()
+ tile = SimpleNamespace(parent=source)
+ transform = Mock()
+ session.preview_renderer = SimpleNamespace(_source_entity=source, _group=SimpleNamespace(transform=transform))
+ picked_point = Mock()
+ picked_point.copy.return_value = SimpleNamespace(x=8.75, y=-13.5, transformBy=Mock(return_value=True))
+ session.pick.selection.return_value = SimpleNamespace(point=picked_point, entity=tile)
+ session.pick.selectionCount = 1
+ session.command = Mock()
+ session.defaults = image_trace.ArtworkDefaults(False, 'dark', 128)
+ session.preview_renderer.raster = session.raster
+ args = SimpleNamespace(activeInput=session.pick, selection=SimpleNamespace(entity=object()))
+ session._preselect(args)
+ self.assertFalse(args.isSelectable)
+ args.selection.entity = tile
+ session._preselect(args)
+ self.assertTrue(args.isSelectable)
+ session._changed(SimpleNamespace(input=session.pick))
+ self.assertEqual(session.seed, (8, 13))
+ transform.copy.return_value.invert.assert_called_once()
+ picked_point.copy.return_value.transformBy.assert_called_once_with(transform.copy.return_value)
+ self.assertTrue(session.coverage.isVisible)
+ self.assertTrue(session.detail.isVisible)
+ session.pick.clearSelection.assert_called_once()
+ session.command.doExecutePreview.assert_not_called()
+ with patch.object(image_trace, 'analyze', wraps=image_trace.analyze) as analyze:
+ session._result(self.original)
+ analyze.assert_called_with(session.raster, 'silhouette', 128, False, (8, 13))
+ session._changed(SimpleNamespace(input=SimpleNamespace(id='traceAutoSubject')))
+ self.assertIsNone(session.seed)
+ self.assertTrue(session.detail.isVisible)
+
+ def test_dense_trace_confirms_current_line_count_and_keeps_preview_available(self):
+ session = self.session
+ self.prepare_preview()
+ session._show_target_controls = Mock()
+ result = SimpleNamespace(curve_count=3456, type_counts=(60, 0, 0, 0), rings=[()])
+ session._result = Mock(return_value=result)
+ args = SimpleNamespace()
+ session._validate(args)
+ self.assertFalse(args.areInputsValid)
+ self.assertTrue(session.confirm.isVisible)
+ self.assertIn('3,456', session.status.text)
+ session.confirm.value = True
+ session._validate(args)
+ self.assertTrue(args.areInputsValid)
+ result.curve_count = 4000
+ session._validate(args)
+ self.assertFalse(args.areInputsValid)
+ self.assertFalse(session.confirm.value)
+ result.curve_count = 60
+ session._validate(args)
+ self.assertTrue(args.areInputsValid)
+ self.assertFalse(session.confirm.isVisible)
+
+ def prepare_preview(self, plane=None):
+ session = self.session
+ session.preview_renderer = None
+ session.transform = Mock()
+ session.app = Mock()
+ session.design = Mock()
+ session.status = SimpleNamespace(text='')
+ session.preview_mode = SimpleNamespace(selectedItem=SimpleNamespace(index=0))
+ destination = Mock(isValid=True)
+ session._destination = Mock(return_value=(None, plane) if plane else (destination, None))
+ session._placements = Mock(return_value=(self.original, self.moved, {}))
+ self.enterContext(patch.object(self.module.fusion_import, 'sketch_for_target',
+ return_value=destination))
+ make_renderer = self.enterContext(patch.object(self.module.trace_render, 'Preview'))
+ insert = self.enterContext(patch.object(self.module.trace_render, 'insert_curves'))
+ make_renderer.return_value.raster = session.raster
+ return destination, make_renderer.return_value, insert
+
+ def test_preview_modes_update_without_inserting_and_cancel_releases_renderer(self):
+ session = self.session
+ scratch, renderer, insert = self.prepare_preview(plane=object())
+ args = SimpleNamespace()
+ with patch.object(image_trace, 'analyze', wraps=image_trace.analyze) as analyze:
+ for index, mode in enumerate(('source', 'overlay', 'filled')):
+ session.preview_mode.selectedItem.index = index
+ session._preview(args)
+ self.assertFalse(args.isValidResult)
+ self.assertEqual(session.preview_error, '')
+ renderer.draw.assert_called_with(scratch, self.moved, session.result, mode)
+ self.assertEqual(analyze.call_count, 1)
+ self.assertIn('20 × 18 mm', session.status.text)
+ self.assertIn('2 contours', session.status.text)
+ self.assertIn('8 sketch curves (8 lines)', session.status.text)
+ self.assertEqual(scratch.deleteMe.call_count, 3)
+ session.close() # Destroy/Cancel from Fusion.
+ session.close()
+ renderer.close.assert_called_once()
+ insert.assert_not_called()
+
+ def test_insert_commits_displayed_contours_at_displayed_placement(self):
+ session = self.session
+ sketch, renderer, insert = self.prepare_preview()
+ session.preview_mode.selectedItem.index = 2
+ args = SimpleNamespace()
+ session._preview(args)
+ shown_sketch, shown_target, shown_result, _ = renderer.draw.call_args.args
+ with patch.object(image_trace, 'analyze') as analyze:
+ session._execute(args)
+ analyze.assert_not_called()
+ insert.assert_called_once_with(shown_sketch, shown_target, session.raster, shown_result)
+ renderer.close.assert_called_once()
+ sketch.deleteMe.assert_not_called()
+
+ def test_empty_mask_disables_insert_keeps_source_available(self):
+ session = self.session
+ sketch, renderer, insert = self.prepare_preview()
+ session._show_target_controls = Mock()
+ session.raster = image_trace.Raster(4, 4, bytes((255, 255, 255, 255)) * 16, False)
+ session.defaults = image_trace.ArtworkDefaults(True, 'light', 255)
+ args = SimpleNamespace()
+ session._preview(args)
+ session._validate(args)
+ self.assertFalse(args.areInputsValid)
+ self.assertFalse(session.result.rings)
+ renderer.draw.assert_called_with(sketch, self.moved, session.result, 'source')
+ renderer.clear.assert_not_called()
+ insert.assert_not_called()
diff --git a/tests/test_trace_ellipses.py b/tests/test_trace_ellipses.py
new file mode 100644
index 0000000..aec02f1
--- /dev/null
+++ b/tests/test_trace_ellipses.py
@@ -0,0 +1,102 @@
+"""Full, oriented ellipses and independent recognition controls."""
+import itertools
+import math
+import unittest
+
+from InsertTo.image_trace import Analysis, TraceResult
+from InsertTo.trace_ellipses import fit_ellipse
+from InsertTo.trace_primitives import Circle, Ellipse, recognize
+
+
+def oval(center, a, b, angle=0., count=144):
+ axis = complex(math.cos(angle), math.sin(angle))
+ points = []
+ for i in range(count):
+ t = i * math.tau / count
+ p = center + axis * complex(a * math.cos(t), b * math.sin(t))
+ points.append((p.real, p.imag))
+ return tuple(points)
+
+
+def recognize_rings(rings, circles=False, arcs=False, ellipses=True, sx=1., sy=1.):
+ analysis = Analysis(tuple((r,) for r in rings))
+ result = TraceResult(rings)
+ return recognize(analysis, result, sx, sy, .65 * min(sx, sy), circles, arcs, ellipses)
+
+
+class TraceEllipseTests(unittest.TestCase):
+ def test_rotated_axes_and_centres_are_independent_of_boundary_winding(self):
+ spin = .63
+ center = complex(82, 91)
+ ring = oval(center, 43, 16, spin)
+ for contour in (ring, tuple(reversed(ring))):
+ out = recognize_rings((contour,))
+ self.assertEqual(out.type_counts, (0, 0, 0, 1))
+ shape = out.paths[0][0]
+ self.assertIsInstance(shape, Ellipse)
+ origin = complex(*shape.center)
+ axis = complex(*shape.major) - origin
+ normal = complex(*shape.minor) - origin
+ self.assertLess(abs(origin - center), 1e-8)
+ self.assertAlmostEqual(abs(axis), 43, delta=.02)
+ self.assertAlmostEqual(abs(normal), 16, delta=.02)
+ self.assertAlmostEqual((axis.conjugate() * normal).real, 0, places=9)
+ self.assertAlmostEqual(abs((axis / abs(axis) * complex(math.cos(spin), -math.sin(spin))).imag), 0)
+
+ def test_each_of_the_eight_combinations_preserves_exclusivity(self):
+ disk = oval(-50 + 0j, 15, 15)
+ elongated = oval(50 + 0j, 20, 12, .48)
+ for circles, arcs, ellipses in itertools.product((False, True), repeat=3):
+ out = recognize_rings((disk, elongated), circles, arcs, ellipses)
+ expected = (0 if circles else len(disk)) + (0 if ellipses else len(elongated))
+ self.assertEqual(out.type_counts, (expected, 0, int(circles), int(ellipses)))
+ self.assertEqual(out.rings, (disk, elongated))
+
+ def test_physical_stretch_changes_primitive_and_keeps_axes_perpendicular(self):
+ disk = oval(10 + 20j, 16, 16)
+ stretched = recognize_rings((disk,), True, True, True, sx=2)
+ self.assertEqual(stretched.type_counts, (0, 0, 0, 1))
+ physical_circle = recognize_rings((oval(0j, 12, 24),), True, True, True, sx=2)
+ self.assertIsInstance(physical_circle.paths[0][0], Circle)
+ rotated = recognize_rings((oval(0j, 24, 12, .7),), sx=2).paths[0][0]
+ u = complex(2*(rotated.major[0] - rotated.center[0]), rotated.major[1] - rotated.center[1])
+ v = complex(2*(rotated.minor[0] - rotated.center[0]), rotated.minor[1] - rotated.center[1])
+ self.assertAlmostEqual((u.conjugate() * v).real, 0, places=8)
+
+ def test_inscribed_polygons_and_unresolved_axis_difference_stay_linear(self):
+ for count in (12, 16, 20):
+ corners = oval(0j, 9, 6, .35, count)
+ # Subdivision must not hide a genuine angular feature.
+ ring = tuple((x + (u - x)*j/6, y + (v - y)*j/6)
+ for (x,y),(u,v) in zip(corners, corners[1:] + corners[:1]) for j in range(6))
+ self.assertFalse(recognize_rings((ring,)).paths)
+ almost_round = oval(0j, 40, 39.8, .44)
+ self.assertFalse(recognize_rings((almost_round,)).paths)
+
+ def test_tight_clearance_preserves_an_unrelated_hole(self):
+ outer = oval(0j, 28, 12, .15)
+ hole = tuple(reversed(oval(0j, 27.93, 11.93, .15)))
+ remote = oval(70 + 0j, 12, 6)
+ analysis = Analysis(((outer, hole), (remote,)))
+ raw = TraceResult((outer, hole, remote))
+ out = recognize(analysis, raw, 1, 1, .65, False, False, True)
+ self.assertEqual(out.type_counts, (len(outer) + len(hole), 0, 0, 1))
+ self.assertIsInstance(out.paths[2][0], Ellipse)
+
+ def test_certificate_covers_edge_interiors_in_both_directions(self):
+ points = tuple(complex(*p) for p in oval(17 + 3j, 42, 13, .57, 128))
+ fitted = fit_ellipse(points, 1, .65)
+ self.assertIsNotNone(fitted)
+ def distance_to_segment(p, a, b):
+ d = b - a
+ projection = min(1., max(0., ((p - a)*d.conjugate()).real / abs(d)**2))
+ return abs(p - (a + projection*d))
+ local = [fitted.local(p) for p in points]
+ edges = list(zip(local, local[1:] + local[:1]))
+ for i in range(768):
+ point = fitted.at(math.tau * i / 768)
+ self.assertLessEqual(min(distance_to_segment(point, a, b) for a,b in edges), fitted.error_bound + 1e-9)
+ for a,b in edges:
+ for j in range(9):
+ point = a + (b - a)*j/8
+ self.assertLessEqual(fitted.projection(point)[1], fitted.error_bound + 1e-9)
diff --git a/tests/test_trace_logo_arcs.py b/tests/test_trace_logo_arcs.py
new file mode 100644
index 0000000..54fd719
--- /dev/null
+++ b/tests/test_trace_logo_arcs.py
@@ -0,0 +1,80 @@
+"""Circular subpaths on composite artwork, with physical clearance and flat edges."""
+
+import math
+import unittest
+
+from InsertTo.image_trace import Analysis, trace
+from InsertTo.trace_primitives import Arc, Line, _arc, recognize
+
+
+def fit(raw, tolerance=.65):
+ analysis = Analysis(((tuple(raw),),), preserve_corners=False)
+ result = trace(analysis, 1, 1, tolerance, 0)
+ return recognize(analysis, result, 1, 1, tolerance, True, True)
+
+
+def samples(center, radius, start, end, steps):
+ return [center + radius * complex(math.cos(start + (end - start) * i / steps),
+ math.sin(start + (end - start) * i / steps))
+ for i in range(steps + 1)]
+
+
+def as_xy(points):
+ return [(v.real, v.imag) for v in points]
+
+
+class LocalLogoArcTests(unittest.TestCase):
+ def test_curved_band_with_short_ends_keeps_both_concentric_arcs(self):
+ outer = samples(0j, 35, .3, 5, 120)
+ inner = samples(0j, 31, 5, .3, 110)
+ ring = tuple(as_xy(outer + inner))
+ solid = fit(ring)
+ self.assertEqual(solid.type_counts, (2, 2, 0, 0))
+
+ frame = ((-80, -80), (80, -80), (80, 80), (-80, 80))
+ hole = tuple(reversed(ring))
+ analysis = Analysis(((frame, hole),), preserve_corners=False)
+ baseline = trace(analysis, 1, 1, .65, 0)
+ negative = recognize(analysis, baseline, 1, 1, .65, True, True)
+ self.assertEqual(negative.type_counts, (6, 2, 0, 0))
+ for path in (solid.paths[0], negative.paths[1]):
+ for first, following in zip(path, path[1:] + path[:1]):
+ self.assertEqual(first.end, following.start)
+ for primitive in path:
+ if isinstance(primitive, Line):
+ self.assertAlmostEqual(math.dist(primitive.start, primitive.end), 4, delta=.01)
+
+ def test_lobe_blending_into_a_free_tail_keeps_a_major_arc(self):
+ radius, end_angle = 32, math.tau + .75
+ lobe = samples(0j, radius, math.pi, end_angle, 100)
+ end = lobe[-1]
+ tangent = complex(-math.sin(end_angle), math.cos(end_angle))
+ tip = complex(-radius, 49)
+ control = end + 32 * tangent
+ tail = [(1 - t) ** 2 * end + 2 * (1 - t) * t * control + t * t * tip
+ for t in (i / 80 for i in range(1, 81))]
+ result = fit(as_xy(lobe + tail))
+ self.assertEqual(result.type_counts[1:], (1, 0, 0))
+ self.assertGreater(result.type_counts[0], 1)
+ arc, = (c for c in result.paths[0] if isinstance(c, Arc))
+ self.assertIn(arc.start, as_xy(lobe + tail))
+ self.assertIn(arc.end, as_xy(lobe + tail))
+ self.assertLess(arc.mid[1], -20)
+
+ def test_flat_shelf_at_end_of_letter_cannot_be_absorbed(self):
+ # A 4 px flat can appear circular at a .65 px global error budget.
+ # The right side really curves and must pass on its own evidence.
+ flank = samples(0j, 8, -.6, math.pi / 2, 40)
+ shelf = [complex(-x, 8 + .016 * math.sin(x)) for x in range(1, 5)]
+ self.assertIsNotNone(_arc(tuple(flank), 1, .65))
+ self.assertIsNone(_arc(tuple(flank + shelf), 1, .65))
+
+ def test_finite_arc_clearance_only_applies_to_the_covered_sweep(self):
+ fit_arc = _arc(tuple(samples(0j, 20, 0, math.pi / 2, 80)), 1, .65)
+ self.assertIsNotNone(fit_arc)
+ band = fit_arc[0]
+ self.assertTrue(band.clear(((-21 + 0j, -19 + 0j),), .5))
+ self.assertFalse(band.clear(((19 + 0j, 21 + 0j),), .5))
+ self.assertFalse(band.clear(((0 + 19.8j, .1 + 20.2j),), .5))
+ normal = complex(1, 1) / math.sqrt(2)
+ self.assertFalse(band.clear(((normal * 19, normal * 21),), .05))
diff --git a/tests/test_trace_logo_circles.py b/tests/test_trace_logo_circles.py
new file mode 100644
index 0000000..9d42b1d
--- /dev/null
+++ b/tests/test_trace_logo_circles.py
@@ -0,0 +1,47 @@
+"""Small raster circles and similarly sized logo details must remain distinct."""
+
+import math
+import unittest
+
+from InsertTo import image_trace, trace_primitives
+
+
+def perforated_artwork(rx, ry):
+ # A subpixel hole through a light patch. Linear edge coverage yields actual
+ # threshold crossings a pixel apart, as on antialiased artwork.
+ rgba = bytearray()
+ for y in range(32):
+ for x in range(32):
+ norm = math.hypot((x + .5 - 15) / rx, (y + .5 - 15) / ry)
+ coverage = min(1., max(0., (norm - 1) * min(rx, ry) + .5))
+ value = round(30 + 180 * coverage)
+ rgba.extend((value, value, value, 255))
+ raster = image_trace.Raster(32, 32, bytes(rgba), False)
+ analysis = image_trace.analyze(raster, 'ink', 120, True)
+ outlines = image_trace.trace(analysis, 1, 1, .65, 0)
+ return trace_primitives.recognize(analysis, outlines, 1, 1, .65, True, False)
+
+
+class SmallLogoCirclesTests(unittest.TestCase):
+ def test_round_hole_has_curvature_even_at_one_pixel_spacing(self):
+ result = perforated_artwork(5.25, 5.25)
+ self.assertEqual(len(result.rings), 2)
+ circle, = result.paths[1]
+ self.assertIsInstance(circle, trace_primitives.Circle)
+ self.assertLess(math.dist(circle.center, (15, 15)), .1)
+ self.assertAlmostEqual(circle.radius, 5.25, delta=.15)
+
+ def test_oval_counter_of_similar_size_stays_a_polyline(self):
+ result = perforated_artwork(5.25, 6.05)
+ self.assertEqual(result.type_counts[2], 0)
+
+ def test_small_regular_polygons_preserve_their_short_sides(self):
+ for sides in (18, 24, 28):
+ with self.subTest(sides=sides):
+ vertices = tuple(5.5 * complex(math.cos(i * math.tau / sides),
+ math.sin(i * math.tau / sides))
+ for i in range(sides))
+ points = tuple(a + (b - a) * j / 3 for a, b in
+ zip(vertices, vertices[1:] + vertices[:1]) for j in range(3))
+ band = trace_primitives._circle(points, trace_primitives._bounds(points), 1, .65)
+ self.assertIsNone(band)
diff --git a/tests/test_trace_photo_outlines.py b/tests/test_trace_photo_outlines.py
new file mode 100644
index 0000000..fdb25fa
--- /dev/null
+++ b/tests/test_trace_photo_outlines.py
@@ -0,0 +1,49 @@
+"""Accuracy and clearance for simplification of photographed silhouettes."""
+
+from dataclasses import replace
+import math
+import unittest
+
+from InsertTo import image_trace
+
+
+def distance(p, a, b):
+ dx, dy = b[0] - a[0], b[1] - a[1]
+ t = max(0., min(1., ((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / (dx * dx + dy * dy)))
+ return math.hypot(p[0] - a[0] - t * dx, p[1] - a[1] - t * dy)
+
+
+class PhotoOutlineTests(unittest.TestCase):
+ def test_pixel_steps_follow_source_with_physical_error_and_fewer_turns(self):
+ # A long sloping edge crosses rounded sample pixels of different widths.
+ steps = [(0, 0)]
+ for i in range(41):
+ x, y = steps[-1]
+ steps.extend(((x + (2 if i % 5 == 0 else 1), y),
+ (x + (2 if i % 5 == 0 else 1), y + (2 if i % 6 == 0 else 1))))
+ ring = tuple(steps + [(0, steps[-1][1])])
+ analysis = image_trace.Analysis(((ring,),), preserve_corners=False, photo=True)
+ for sx, sy, tolerance in ((1, 1, 1.09), (.3, .45, .41)):
+ with self.subTest(sx=sx, sy=sy):
+ result, = image_trace.trace(analysis, sx, sy, tolerance, 0).rings
+ legacy, = image_trace.trace(replace(analysis, photo=False), sx, sy, tolerance, 0).rings
+ self.assertLess(len(result), len(legacy))
+ self.assertTrue(set(result).issubset(ring))
+ self.assertEqual((max(x for x, y in result), max(y for x, y in result)), steps[-1])
+ for a, b in zip(result, result[1:] + result[:1]):
+ i, j = ring.index(a), ring.index(b)
+ chain = ring[i:j + 1] if i < j else ring[i:] + ring[:j + 1]
+ pa, pb = (a[0] * sx, a[1] * sy), (b[0] * sx, b[1] * sy)
+ self.assertLessEqual(max(distance((x * sx, y * sy), pa, pb) for x, y in chain),
+ tolerance + 1e-10)
+ self.assertEqual(image_trace.trace(analysis, 1, 1, 0, 0).rings, (ring,))
+
+ def test_shortcut_cannot_cross_a_hole_inside_a_narrow_protrusion(self):
+ outer = ((0, 0), (60, 0), (60, 40), (36, 40), (36, 44),
+ (26, 44), (26, 40), (8, 40), (8, 48), (0, 48))
+ hole = ((28, 41), (28, 43), (34, 43), (34, 41))
+ analysis = image_trace.Analysis(((outer, hole),), preserve_corners=False, photo=True)
+ result, retained_hole = image_trace.trace(analysis, 1., 1., 8., 0).rings
+ self.assertEqual(retained_hole, hole)
+ self.assertTrue(all(image_trace._contains(result, x, y) for x, y in hole))
+ self.assertGreater(image_trace._area(result), 0)
diff --git a/tests/test_trace_primitives.py b/tests/test_trace_primitives.py
new file mode 100644
index 0000000..1d17614
--- /dev/null
+++ b/tests/test_trace_primitives.py
@@ -0,0 +1,128 @@
+"""Independent recognition controls and geometry checks in final sketch units."""
+import math
+import unittest
+
+from InsertTo.image_trace import Analysis, TraceResult
+from InsertTo.trace_primitives import Arc, Circle, Line, recognize
+
+
+def oval(cx, cy, rx, ry, count=128):
+ return tuple((cx + rx * math.cos(i * math.tau / count),
+ cy + ry * math.sin(i * math.tau / count)) for i in range(count))
+
+
+def fit(rings, scales=(1., 1.), tolerance=.65, circles=True, arcs=True):
+ analysis = Analysis(tuple((ring,) for ring in rings))
+ return recognize(analysis, TraceResult(rings), *scales, tolerance, circles, arcs)
+
+
+def rounded_slot():
+ right = [(40 + 15 * math.cos(i * math.pi / 48), 15 * math.sin(i * math.pi / 48))
+ for i in range(-24, 25)]
+ left = [(15 * math.cos(i * math.pi / 48), 15 * math.sin(i * math.pi / 48))
+ for i in range(24, 73)]
+ return tuple(right + left)
+
+
+class TracePrimitiveTests(unittest.TestCase):
+ def test_checkboxes_do_not_emulate_each_other(self):
+ disk = oval(2, 4, 18, 18)
+ for circles in (False, True):
+ for arcs in (False, True):
+ result = fit((disk,), circles=circles, arcs=arcs)
+ self.assertEqual(result.type_counts, (0, 0, 1, 0) if circles else (128, 0, 0, 0))
+ self.assertEqual(result.rings, (disk,))
+ if circles:
+ circle, = result.paths[0]
+ self.assertIsInstance(circle, Circle)
+ self.assertAlmostEqual(circle.center[0], 2)
+ self.assertAlmostEqual(circle.center[1], 4)
+ self.assertAlmostEqual(circle.radius, 18, delta=.01)
+ baseline = TraceResult((disk,))
+ self.assertIs(recognize(Analysis(((disk,),)), baseline, 1, 1, .65, False, False), baseline)
+
+ def test_tangent_slot_preserves_geometry_and_winding_after_rotation(self):
+ angle = math.radians(37)
+ rotate = complex(math.cos(angle), math.sin(angle))
+ slot = tuple((w.real, w.imag) for x, y in rounded_slot()
+ for w in [complex(x, y) * rotate + complex(12, -9)])
+ for ring in (slot, tuple(reversed(slot))):
+ self.assertEqual(fit((ring,), arcs=False).type_counts, (len(ring), 0, 0, 0))
+ result = fit((ring,), circles=False)
+ self.assertEqual(result.type_counts, (2, 2, 0, 0))
+ lines = [obj for obj in result.paths[0] if isinstance(obj, Line)]
+ for line in lines:
+ self.assertAlmostEqual(math.dist(line.start, line.end), 40, delta=.01)
+ curves = result.paths[0]
+ for i, current in enumerate(curves):
+ following = curves[(i + 1) % 4]
+ self.assertEqual(current.end, following.start)
+ if isinstance(current, Arc):
+ center = (complex(*current.start) + complex(*current.end)) / 2
+ self.assertAlmostEqual(abs(complex(*current.mid) - center), 15, delta=.01)
+ radius = complex(*current.end) - center
+ side = complex(*following.end) - complex(*following.start)
+ self.assertAlmostEqual((radius.conjugate() * side).real, 0, delta=1e-8)
+ old_area = sum(x * v - y * u for (x, y), (u, v) in zip(ring, ring[1:] + ring[:1]))
+ ends = tuple(c.start for c in curves)
+ new_area = sum(x * v - y * u for (x, y), (u, v) in zip(ends, ends[1:] + ends[:1]))
+ self.assertGreater(old_area * new_area, 0)
+
+ def test_four_quarter_arcs_keep_their_straight_sides(self):
+ points = []
+ for cx, cy, start in ((80, 10, -90), (80, 50, 0), (10, 50, 90), (10, 10, 180)):
+ for step in range(25):
+ angle = math.radians(start + 90 * step / 24)
+ points.append((cx + 10 * math.cos(angle), cy + 10 * math.sin(angle)))
+ result = fit((tuple(points),))
+ self.assertEqual(result.type_counts, (4, 4, 0, 0))
+ path, = result.paths
+ for current, following in zip(path, path[1:] + path[:1]):
+ self.assertEqual(current.end, following.start)
+
+ def test_major_arc_on_both_windings_keeps_flat_and_true_side(self):
+ # The chord truncates the right side. The selected arc passes far left
+ # of its centre, regardless of the starting vertex and winding.
+ ring = tuple((70 * math.cos(.6 + (math.tau - 1.2) * i / 90),
+ 70 * math.sin(.6 + (math.tau - 1.2) * i / 90)) for i in range(91))
+ for test_ring in (ring[17:] + ring[:17], tuple(reversed(ring))):
+ result = fit((test_ring,))
+ self.assertEqual(result.type_counts, (1, 1, 0, 0))
+ arc, = (c for c in result.paths[0] if isinstance(c, Arc))
+ self.assertAlmostEqual(arc.mid[0], -70)
+ self.assertAlmostEqual(arc.mid[1], 0)
+ self.assertAlmostEqual(arc.start[0], arc.end[0])
+
+ def test_nearby_hole_blocks_fit_but_filtered_islands_do_not_change_alignment(self):
+ outer = oval(0, 0, 40, 40)
+ hole = tuple(reversed(oval(0, 0, 39.5, 39.5)))
+ remote = oval(120, 0, 15, 15)
+ result = fit((outer, hole, remote))
+ self.assertEqual(result.type_counts, (256, 0, 1, 0))
+ self.assertIsInstance(result.paths[2][0], Circle)
+
+ gone = ((-80, -80), (-79, -80), (-80, -79))
+ keep = Analysis(((gone,), (outer, hole), (remote,)))
+ result = recognize(keep, TraceResult((remote,)), 1, 1, .65, True, True)
+ self.assertEqual(result.type_counts, (0, 0, 1, 0))
+ self.assertAlmostEqual(result.paths[0][0].center[0], 120)
+
+ def test_polygon_and_rotated_near_ellipse_within_loose_tolerance_stay_lines(self):
+ tiny_polygon = oval(0, 0, 20, 20, 20)
+ dense_polygon = tuple((x + t * (u - x) / 5, y + t * (v - y) / 5)
+ for (x, y), (u, v) in zip(tiny_polygon, tiny_polygon[1:] + tiny_polygon[:1])
+ for t in range(5))
+ spin = complex(math.cos(.64), math.sin(.64))
+ near_oval = tuple((w.real, w.imag) for x, y in oval(0, 0, 80, 80.8)
+ for w in [complex(x, y) * spin])
+ for ring in (tiny_polygon, dense_polygon, near_oval):
+ self.assertEqual(fit((ring,), tolerance=3).type_counts, (len(ring), 0, 0, 0))
+
+ def test_fitting_in_physical_space_only(self):
+ circle = oval(0, 0, 20, 20)
+ self.assertEqual(fit((circle,), scales=(2, 1)).type_counts, (128, 0, 0, 0))
+ ellipse = oval(0, 0, 20, 40)
+ upright = fit((ellipse,), scales=(2, 1))
+ self.assertEqual(upright.type_counts, (0, 0, 1, 0))
+ self.assertAlmostEqual(upright.paths[0][0].radius, 40, delta=.02)
+ self.assertEqual((upright.sx, upright.sy), (2, 1))
diff --git a/tests/test_trace_render.py b/tests/test_trace_render.py
new file mode 100644
index 0000000..1c7bae8
--- /dev/null
+++ b/tests/test_trace_render.py
@@ -0,0 +1,282 @@
+"""Check the filled Fusion preview represents the same nested outline topology."""
+
+import math
+import sys
+import unittest
+from types import SimpleNamespace
+from unittest.mock import Mock, patch
+
+from InsertTo import svg_geometry, trace_render
+from InsertTo.image_trace import TraceResult
+from InsertTo.trace_primitives import Arc, Circle, Ellipse, Line
+
+
+def cross(a, b, point):
+ return (b[0] - a[0]) * (point[1] - a[1]) - (b[1] - a[1]) * (point[0] - a[0])
+
+
+def covered(triangles, point):
+ for a, b, c in triangles:
+ signs = (cross(a, b, point), cross(b, c, point), cross(c, a, point))
+ if min(signs) >= 0 or max(signs) <= 0:
+ return True
+ return False
+
+
+class FilledPreviewTests(unittest.TestCase):
+ def test_fill_respects_hole_island_and_disconnected_sloping_edges(self):
+ outer = ((0, 0), (20, 0), (20, 20), (0, 20))
+ hole = ((3, 3), (3, 17), (17, 17), (17, 3))
+ island = ((6, 6), (14, 6), (8, 12))
+ diamond = ((26, 4), (30, 8), (26, 12), (22, 8))
+ points, indices = trace_render._fill_mesh((outer, hole, island, diamond))
+ self.assertEqual(len(indices) % 3, 0)
+ triangles = [tuple(points[i] for i in indices[j:j + 3])
+ for j in range(0, len(indices), 3)]
+ self.assertAlmostEqual(sum(abs(cross(a, b, c)) / 2 for a, b, c in triangles),
+ 400 - 196 + 24 + 32)
+ for point, expected in (((1, 2), True), ((4, 5), False), ((9, 8), True),
+ ((15, 15), False), ((24, 8), True), ((22, 4), False)):
+ with self.subTest(point=point):
+ self.assertEqual(covered(triangles, point), expected)
+
+ def test_circular_hole_keeps_its_winding_in_the_preview(self):
+ hole = ((-1, 0), (0, 1), (1, 0), (0, -1))
+ result = TraceResult((hole,), ((Circle((0, 0), 1),),), tolerance_mm=.1)
+ ring, = trace_render._preview_rings(result)
+ area = sum(x * v - y * u for (x, y), (u, v) in zip(ring, ring[1:] + ring[:1]))
+ self.assertLess(area, 0)
+
+ def test_insert_reuses_sketch_points_to_close_each_loop(self):
+ points = SimpleNamespace(create=lambda x, y, z: (x, y, z))
+ core = SimpleNamespace(Point3D=points)
+ sdk = {'adsk': SimpleNamespace(core=core), 'adsk.core': core}
+ sketch = Mock()
+ rings = (((0, 0), (8, 0), (8, 6), (0, 6)),
+ ((1, 1), (1, 3), (3, 3), (3, 1)))
+ made = []
+
+ def line(a, b):
+ value = SimpleNamespace(startSketchPoint=object(), endSketchPoint=object())
+ made.append((a, b, value))
+ return value
+
+ sketch.sketchCurves.sketchLines.addByTwoPoints.side_effect = line
+ target = svg_geometry.Placement(10, 20, 40, 60)
+ raster = SimpleNamespace(width=8, height=6)
+ with patch.dict(sys.modules, sdk):
+ trace_render.insert_curves(sketch, target, raster, SimpleNamespace(rings=rings))
+ self.assertEqual(len(made), 8)
+ self.assertEqual(made[0][:2], ((1., 8., 0), (5., 8., 0)))
+ self.assertEqual(made[4][:2], ((1.5, 7., 0), (1.5, 5., 0)))
+ for start in (0, 4):
+ for i in range(start + 1, start + 4):
+ self.assertIs(made[i][0], made[i-1][2].endSketchPoint)
+ self.assertIs(made[start + 3][1], made[start][2].startSketchPoint)
+
+ def test_arc_line_loops_share_native_endpoints_for_both_windings(self):
+ points = SimpleNamespace(create=lambda x, y, z: (x, y, z))
+ core = SimpleNamespace(Point3D=points)
+ sdk = {'adsk': SimpleNamespace(core=core), 'adsk.core': core}
+ for mid, clockwise in (((4, 2), False), ((4, -2), True)):
+ with self.subTest(mid=mid):
+ a, b = (0, 0), (8, 0)
+ sketch = Mock()
+ curves = sketch.sketchCurves
+ result = TraceResult((), ((Arc(a, mid, b), Line(b, a)),))
+ target = svg_geometry.Placement(10, -5, 40, 30, rotation=.3)
+ raster = SimpleNamespace(width=8, height=6)
+ with patch.dict(sys.modules, sdk):
+ trace_render.insert_curves(sketch, target, raster, result)
+ create_arc = curves.sketchArcs.addByThreePoints
+ expected = [(*trace_render._placed_xy(*p, target, raster), 0) for p in (a, mid, b)]
+ self.assertEqual(create_arc.call_args.args, tuple(expected))
+ arc = create_arc.return_value
+ end = arc.startSketchPoint if clockwise else arc.endSketchPoint
+ start = arc.endSketchPoint if clockwise else arc.startSketchPoint
+ curves.sketchLines.addByTwoPoints.assert_called_once_with(end, start)
+
+ def test_circle_insertion_uses_physical_radius_in_centimetres(self):
+ core = SimpleNamespace(Point3D=SimpleNamespace(create=lambda x, y, z: (x, y, z)))
+ sdk = {'adsk': SimpleNamespace(core=core), 'adsk.core': core}
+ sketch = Mock()
+ result = TraceResult((), ((Circle((4, 2), 5),),), sx=2, sy=3)
+ with patch.dict(sys.modules, sdk):
+ trace_render.insert_curves(sketch, svg_geometry.Placement(0, 0, 16, 18),
+ SimpleNamespace(width=8, height=6), result)
+ args = sketch.sketchCurves.sketchCircles.addByCenterRadius.call_args.args
+ self.assertAlmostEqual(args[0][0], .8)
+ self.assertAlmostEqual(args[0][1], 1.2)
+ self.assertEqual(args[1], .5)
+ sketch.sketchCurves.sketchLines.addByTwoPoints.assert_not_called()
+
+ def test_ellipse_insertion_maps_center_and_both_axis_ends_to_the_rotated_sketch(self):
+ ellipse = Ellipse((9, 10), (15, 26), (7, 22))
+ result = TraceResult((), ((ellipse,),), sx=2, sy=.5, tolerance_mm=.2)
+ sketch = Mock()
+ core = SimpleNamespace(Point3D=SimpleNamespace(create=lambda x, y, z: (x, y, z)))
+ sdk = {'adsk': SimpleNamespace(core=core), 'adsk.core': core}
+ target = svg_geometry.Placement(2, -3, 40, 10, rotation=math.pi / 2)
+ with patch.dict(sys.modules, sdk):
+ trace_render.insert_curves(sketch, target, SimpleNamespace(width=20, height=20), result)
+ create = sketch.sketchCurves.sketchEllipses.add
+ create.assert_called_once()
+ expected = ((-.2, 2., 0), (.6, 3.2, 0), (.4, 1.6, 0))
+ for actual, point in zip(create.call_args.args, expected):
+ self.assertLess(math.dist(actual, point), 1e-12)
+
+ def test_failed_native_ellipse_aborts_the_insertion(self):
+ curves = Mock()
+ curves.sketchEllipses.add.return_value = None
+ ellipse = Ellipse((1, 2), (6, 2), (1, 4))
+ with self.assertRaisesRegex(ValueError, 'traced ellipse'):
+ list(trace_render._insert_path(curves, (ellipse,), lambda p: p))
+ curves.sketchLines.addByTwoPoints.assert_not_called()
+
+ def test_rotated_ellipse_preview_obeys_physical_chord_error_after_stretch(self):
+ ellipse = Ellipse((9, 10), (15, 26), (7, 22))
+ result = TraceResult((), ((ellipse,),), sx=2, sy=.5, tolerance_mm=.2)
+ ring, = trace_render._preview_rings(result)
+ # In physical space the semi-axes are (12,8) and (-4,6) mm.
+ step = math.tau / len(ring)
+ def physical(angle):
+ return (18 + 12 * math.cos(angle) - 4 * math.sin(angle),
+ 5 + 8 * math.cos(angle) + 6 * math.sin(angle))
+
+ for i, (start, end) in enumerate(zip(ring, ring[1:] + ring[:1])):
+ a = (start[0] * result.sx, start[1] * result.sy)
+ b = (end[0] * result.sx, end[1] * result.sy)
+ self.assertLess(math.dist(a, physical(i * step)), 1e-12)
+ chord_mid = tuple((x + y) / 2 for x, y in zip(a, b))
+ self.assertLessEqual(math.dist(chord_mid, physical((i + .5) * step)),
+ result.tolerance_mm / 4)
+
+ def test_concentric_ellipses_keep_hole_and_restore_source_windings(self):
+ outer = ((0, 0), (12, 0), (12, 8), (0, 8))
+ hole = ((3, 3), (3, 5), (9, 5), (9, 3))
+ # The fitted minor axes have opposite signs to the source loop order.
+ paths = ((Ellipse((6, 4), (12, 4), (6, 0)),),
+ (Ellipse((6, 4), (9, 4), (6, 5)),))
+ result = TraceResult((outer, hole), paths, sx=1, sy=1, tolerance_mm=.1)
+ rings = trace_render._preview_rings(result)
+ self.assertGreater(trace_render._area(rings[0]), 0)
+ self.assertLess(trace_render._area(rings[1]), 0)
+ points, indices = trace_render._fill_mesh(rings)
+ triangles = [tuple(points[i] for i in indices[j:j + 3]) for j in range(0, len(indices), 3)]
+ self.assertFalse(covered(triangles, (6.2, 4.1)))
+ self.assertTrue(covered(triangles, (6.2, 6.1)))
+ self.assertFalse(covered(triangles, (6.2, 9.1)))
+
+ def test_chord_budget_applies_in_final_mm_for_stretched_placement(self):
+ # A quarter of a circle in physical coordinates passes through a
+ # non-axis-aligned middle point. Its complement exercises major arcs.
+ sx, sy, radius = 4., 1., 8.
+ a, b = (2, 0), (0, 8)
+ paths = ((Arc(a, (-2, 0), b), Line(b, a)), (Circle((5, 5), radius),))
+ result = TraceResult((), paths, sx, sy, .2)
+ major, circle = trace_render._preview_rings(result)
+ self.assertEqual((major[0], major[-1]), (a, b))
+ self.assertTrue(any(y < -7.9 for _, y in major))
+ for ring, center in ((major, (0, 0)), (circle, (5, 5))):
+ points = [((x - center[0]) * sx, (y - center[1]) * sy) for x, y in ring]
+ for x, y in points:
+ self.assertAlmostEqual(math.hypot(x, y), radius)
+ pairs = zip(points, points[1:] + (points[:1] if ring is circle else []))
+ for (ax, ay), (bx, by) in pairs:
+ error = radius - math.hypot((ax + bx) / 2, (ay + by) / 2)
+ self.assertLessEqual(error, result.tolerance_mm / 4)
+
+ def test_view_changes_keep_one_raster_and_one_primitive_tessellation(self):
+ core, fusion = Mock(), Mock()
+ sdk = {'adsk': SimpleNamespace(core=core, fusion=fusion),
+ 'adsk.core': core, 'adsk.fusion': fusion}
+ sketch = Mock()
+ group = sketch.parentComponent.parentDesign.rootComponent.customGraphicsGroups.add.return_value
+ source, outline = Mock(), Mock()
+ group.addGroup.side_effect = [source, outline]
+ renderer = trace_render.Preview(SimpleNamespace(width=1, height=1, has_alpha=False,
+ rgba=bytes([0, 0, 0, 255])))
+ result = TraceResult((), ((Circle((0, 0), 4),),), 1, 1, .2)
+ with patch.dict(sys.modules, sdk), patch.object(trace_render, '_matrix'), \
+ patch.object(trace_render, '_preview_rings', wraps=trace_render._preview_rings) as sample:
+ for mode in ('overlay', 'source', 'filled', 'overlay'):
+ renderer.draw(sketch, object(), result, mode)
+ self.assertEqual(source.isVisible, mode != 'filled')
+ self.assertEqual(outline.isVisible, mode != 'source')
+ sample.assert_called_once_with(result)
+ source.addMesh.assert_called_once()
+ outline.addLines.assert_called_once()
+ group.addMesh.assert_called_once()
+ self.assertFalse(group.addMesh.return_value.isVisible)
+
+ def test_cancel_removes_live_graphics_group_exactly_once(self):
+ renderer = trace_render.Preview(object())
+ group = Mock(isValid=True)
+ renderer._group = group
+ renderer.close()
+ renderer.close()
+ group.deleteMe.assert_called_once_with()
+
+ def test_tiles_keep_every_sample_in_deer_sized_photo_and_share_seams(self):
+ width, height = 1159, 3
+ rgba = bytes(v for y in range(height) for x in range(width)
+ for v in (x % 256, y, 128, 255))
+ tiles = list(trace_render._source_tiles(SimpleNamespace(
+ width=width, height=height, rgba=rgba, has_alpha=False)))
+ for xyz, indices, colors in tiles:
+ self.assertLess(max(indices), len(xyz) // 3)
+ for i in range(len(colors) // 4):
+ x = min(width-1, int(xyz[i*3]))
+ y = min(height-1, int(-xyz[i*3+1]))
+ self.assertEqual(colors[i*4:i*4+4], bytes((x % 256, y, 128, 255)))
+ self.assertEqual(tiles[0][0][128*3:129*3], tiles[1][0][:3])
+ self.assertEqual(tiles[0][2][128*4:129*4], tiles[1][2][:4])
+
+ def test_extremely_wide_source_has_bounded_preview_and_reaches_last_pixel(self):
+ raster = SimpleNamespace(width=30000, height=2, has_alpha=False,
+ rgba=bytes([40, 100, 180, 255]) * 60000)
+ tiles = list(trace_render._source_tiles(raster))
+ self.assertLessEqual(len(tiles), 17)
+ self.assertEqual(max(max(xyz[::3]) for xyz, _, _ in tiles), 30000)
+
+ def test_overlay_preserves_source_and_never_joins_separate_rings(self):
+ raster = SimpleNamespace(width=2, height=2, rgba=bytes([0, 0, 0, 255] * 4),
+ has_alpha=False)
+ renderer = trace_render.Preview(raster)
+ core, fusion = Mock(), Mock()
+ sdk = {'adsk': SimpleNamespace(core=core, fusion=fusion),
+ 'adsk.core': core, 'adsk.fusion': fusion}
+ sketch = Mock()
+ groups = sketch.parentComponent.parentDesign.rootComponent.customGraphicsGroups
+ group = groups.add.return_value
+ source, outline, replacement = Mock(), Mock(), Mock()
+ group.addGroup.side_effect = [source, outline, replacement]
+ rings = (((0, 0), (1, 0), (1, 1)), ((4, 4), (5, 4), (5, 5)))
+ with patch.dict(sys.modules, sdk), patch.object(trace_render, '_matrix'), \
+ patch.object(trace_render, '_coordinates') as coords:
+ renderer.draw(sketch, object(), SimpleNamespace(rings=rings), 'overlay')
+ coords.assert_called_once_with([p for ring in rings for p in (*ring, ring[0])])
+ for call in outline.addLines.call_args_list:
+ self.assertEqual(call.args[1:], ([], True, [4, 4]))
+ renderer.draw(sketch, object(), SimpleNamespace(rings=()), 'overlay')
+ renderer.draw(sketch, object(), SimpleNamespace(rings=rings[:1]), 'overlay')
+ groups.add.assert_called_once()
+ source.addMesh.assert_called_once()
+ outline.deleteMe.assert_called_once()
+ self.assertEqual(replacement.addLines.call_count, 1)
+
+ def test_cancel_during_insertion_restores_compute_and_hides_progress(self):
+ sdk = Mock()
+ sketch = Mock(isComputeDeferred=False)
+ sketch.parentComponent.parentDesign.timeline = None
+ progress = sdk.core.Application.get.return_value.userInterface.createProgressDialog.return_value
+ progress.wasCancelled = True
+ ring = tuple((i, i % 2) for i in range(250))
+ with patch.dict(sys.modules, {'adsk': sdk, 'adsk.core': sdk.core}):
+ with self.assertRaisesRegex(ValueError, 'cancelled'):
+ trace_render.insert_curves(sketch, svg_geometry.Placement(0, 0, 10, 10),
+ SimpleNamespace(width=250, height=2),
+ SimpleNamespace(rings=(ring,)))
+ self.assertEqual(sketch.sketchCurves.sketchLines.addByTwoPoints.call_count, 50)
+ self.assertFalse(sketch.isComputeDeferred)
+ progress.hide.assert_called_once()
diff --git a/tests/test_trace_topology.py b/tests/test_trace_topology.py
new file mode 100644
index 0000000..5c49b52
--- /dev/null
+++ b/tests/test_trace_topology.py
@@ -0,0 +1,98 @@
+"""Topology checks against independent pixel and connected-component oracles."""
+
+from itertools import product
+import unittest
+
+from InsertTo import image_trace
+
+
+def raster(rows, mode):
+ pixels = bytearray()
+ for row in rows:
+ for cell in row:
+ ink = cell == '#'
+ gray = 0 if ink else 255
+ alpha = 0 if mode == 'alpha' and not ink else 255
+ pixels.extend((gray, gray, gray, alpha))
+ return image_trace.Raster(len(rows[0]), len(rows), bytes(pixels), mode == 'alpha')
+
+
+def islands(rows):
+ remaining = {(x, y) for y, row in enumerate(rows) for x, cell in enumerate(row) if cell == '#'}
+ count = 0
+ while remaining:
+ count += 1
+ pending = [remaining.pop()]
+ while pending:
+ x, y = pending.pop()
+ neighbors = remaining.intersection(((x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)))
+ pending.extend(neighbors)
+ remaining.difference_update(neighbors)
+ return count
+
+
+def area(ring):
+ return sum(x * v - y * u for (x, y), (u, v) in zip(ring, ring[1:] + ring[:1])) / 2
+
+
+def painted(rings, x, y):
+ crossings = 0
+ for ring in rings:
+ for (u, v), (s, t) in zip(ring, ring[1:] + ring[:1]):
+ if (v > y) != (t > y) and u + (y - v) * (s - u) / (t - v) > x:
+ crossings += 1
+ return crossings % 2 == 1
+
+
+class TraceTopologyTests(unittest.TestCase):
+ def assert_pixels(self, rings, rows):
+ actual = tuple(''.join('#' if painted(rings, x + .5, y + .5) else '.'
+ for x in range(len(row))) for y, row in enumerate(rows))
+ self.assertEqual(actual, rows)
+
+ def test_all_three_by_three_masks_restore_every_pixel_and_separate_diagonal_islands(self):
+ for cells in product('.#', repeat=9):
+ rows = tuple(''.join(cells[i:i + 3]) for i in (0, 3, 6))
+ for mode in ('alpha', 'ink'):
+ with self.subTest(rows=rows, mode=mode):
+ analysis = image_trace.analyze(raster(rows, mode), mode)
+ self.assertEqual(len(analysis.components), islands(rows))
+ result = image_trace.trace(analysis, 1, 1, 0, 0)
+ self.assert_pixels(result.rings, rows)
+ for outer, *holes in analysis.components:
+ self.assertGreater(area(outer), 0)
+ self.assertTrue(all(area(hole) < 0 for hole in holes))
+ for ring in result.rings:
+ self.assertGreaterEqual(len(ring), 3)
+ self.assertEqual(len(set(ring)), len(ring))
+ if mode == 'alpha':
+ self.assertEqual(sum(area(ring) for ring in result.rings), cells.count('#'))
+
+ def test_four_nested_islands_keep_their_own_holes_and_area_cutoff(self):
+ rows = tuple(''.join('#' if min(x, y, 12 - x, 12 - y) % 2 == 0 else '.'
+ for x in range(13)) for y in range(13))
+ for mode in ('alpha', 'ink'):
+ with self.subTest(mode=mode):
+ analysis = image_trace.analyze(raster(rows, mode), mode)
+ self.assertEqual(sorted(len(group) for group in analysis.components), [1, 2, 2, 2])
+ result = image_trace.trace(analysis, 1, 1, 0, 0)
+ self.assert_pixels(result.rings, rows)
+ # The two inner ink islands have areas below 20; their holes belong to them.
+ filtered = image_trace.trace(analysis, 1, 1, 0, 20)
+ self.assertEqual(len(filtered.rings), 4)
+ self.assertEqual([painted(filtered.rings, x + .5, 6.5) for x in range(7)],
+ [True, False, True, False, False, False, False])
+
+ def test_one_pixel_slot_stays_open_along_its_length_after_simplification(self):
+ rows = ('##.##',) * 4 + ('#####',) * 2
+ for mode in ('alpha', 'ink'):
+ with self.subTest(mode=mode):
+ analysis = image_trace.analyze(raster(rows, mode), mode)
+ # A non-square placement must preserve an opening along the shorter axis.
+ result = image_trace.trace(analysis, 1, 2, .65, 0)
+ self.assertEqual(len(result.rings), 1)
+ for y in range(4):
+ self.assertTrue(painted(result.rings, 1.5, y + .5))
+ self.assertFalse(painted(result.rings, 2.5, y + .5))
+ self.assertTrue(painted(result.rings, 3.5, y + .5))
+ self.assertTrue(painted(result.rings, 2.5, 4.5))