Skip to content

VP3 Writer: Round stitch coordinates to the nearest grid point - #194

Open
bastanja wants to merge 1 commit into
EmbroidePy:mainfrom
bastanja:fix/vp3-rounding-to-nearest-grid-point
Open

bastanja wants to merge 1 commit into
EmbroidePy:mainfrom
bastanja:fix/vp3-rounding-to-nearest-grid-point

Conversation

@bastanja

Copy link
Copy Markdown

Hi! Using the VP3 Writer to export stitch coordinates as embroidery files, I noticed that the stitch coordinates in the written file were not always at the nearest 0.1mm grid point. This was especially noticable with satin patterns, where the stitches got back and forth. in the even runs the stitches were placed differrently than in the odd runs:

Original stitch coordinates (no rounding):
1_original

Rounded to the nearest grid point:
2_snapped

Written with VP3 Writer and read back with VP3 Reader:
3_vp3_roundtrip

Coordinates to reproduce it:
stitch_coordinates.py

The reason for this is that the VP3 writer truncates the delta between stitches instead of rounding it. Non-integer stitch coordinates might not be written to their nearest integer grid point. The error depends on which way the needle is moving, so zigzag and satin stitches come out visibly distorted.

There are two causes in Vp3Writer.py:

  1. write_stitches_block computes dx = int(x - last_x). This truncates each delta toward zero instead of rounding it.
  2. write_vp3_colorblock writes the block start position as int(start_position_from_center_x) * 100, which truncates it. write_stitches_block starts counting from the unrounded float first_pos_x, so the writer and the reader start from different positions.

Minimal example to reproduce it:

import io 
from pyem broidery import EmbPattern, STITCH, write_vp3, read_vp3

# Coordinates in pyembroidery units (1/10 mm)
points = [(0.3, 0.3), (10.6, 0.8), (-10.6, 1.4), (10.6, 1.9), (-10.6, 2.5)]

pattern = EmbPattern()
for x, y in points:
    pattern.add_stitch_absolute(STITCH, x, y)

f = io.BytesIO()
write_vp3(pattern, f)
f.seek(0)
result = [s[:2] for s in read_vp3(f).stitches if s[2] == STITCH]

print("expected (round):", [[round(x), round(y)] for x, y in points])
print("read back       :", result)

Output:
expected (round): [[0, 0], [11, 1], [-11, 1], [11, 2], [-11, 2]]
read back : [[0, 0], [10, 0], [-10, 1], [10, 1], [-10, 2]]

Proposed fix

Round absolute position of each stitch to the nearest integer and compute the delta from the previous rounded position. That way every point lands on its nearest grid point no matter where the previous stitch was. Rounding errors can't build up. The block start position is rounded the same way, so the writer and the reader start from the same point.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant