4-Connected Marching Squares, Half-Pixel EDT Drill Clearance & 2D Ceiling CAD Collision Math in TypeScript
Browser-based CAD tools tend to fail right at the boundary between discrete raster grids and physical workshop tolerances. A vector contour tracer that drops a single interior loop turns a scroll-saw portrait into solid
Browser-based CAD tools tend to fail right at the boundary between discrete raster grids and physical workshop tolerances. A vector contour tracer that drops a single interior loop turns a scroll-saw portrait into solid uncut wood; an integer-pixel distance check misses a 1.03 mm serif pinhole that snaps a #55 (1.32 mm) wire-gauge drill bit; a ceiling lighting planner that treats 4 ft LED shop strips as zero-size points cheerfully places steel housings straight across an open overhead garage door track.
While building zero-backend CAD engines for Scroll Saw Pattern Generator and Lighting Layout Calculatorβand extracting their standalone algorithms into grid-and-fretwork-math and building-layout-mathβwe had to make three geometric invariants exact in pure TypeScript:
-
4-Connected Clockwise Marching Squares (
99.24%pixel-to-vector Intersection-over-Union with zero unclosed or inverted SVG holes); -
Half-Pixel
(2W + 1) Γ (2H + 1)FelzenszwalbβHuttenlocher Euclidean Distance Transforms (O(WΒ·H)) for wire-gauge pilot drill clearance (#65to#44) and flat-bottom plaque descender coves; -
2D Rotated AABB Fixture Envelopes & Radial Strobe Avoidance on calibrated
1/4" = 1'-0"(1:48) andISO 1:50Reflected Ceiling Plans (RCPs).
Here is the math and TypeScript implementation behind each stage.
1. Why Naive Marching Squares Collapses SVG Holes (case 5/10/13/14)
Suppose you have a binary mask wood[y * W + x] β {0, 1} where 1 represents solid wood to keep and 0 represents cut kerf waste. To export a true 1:1 vector SVG <path fill-rule="evenodd">, every outer boundary and every enclosed interior cutout must stitch into a watertight closed polygon ring.
Two subtle bugs break standard textbook Marching Squares implementations on fretwork masks:
-
8-Connected Saddle Fusion (
case 5andcase 10): When diagonally opposite pixels are solid (tl = 1, br = 1incase 10, ortr = 1, bl = 1incase 5) across an empty diagonal, connecting them into one merged corridor creates a zero-width wood bridge that snaps immediately under scroll-saw vibration. Structural fretwork is strictly 4-connected, so saddles must separate the two solid corners across the empty kerf. -
Reversed Half-Edges on Concave Hole Corners (
case 13andcase 14): In top-down SVG coordinates (xright,ydown), keeping1-pixels on the interior right-hand side of every directed half-edge(dx, dy)requires the inward normal(-dy, dx)to point toward the1-pixels. Oncase 13(tl = tr = bl = 1, br = 0), emittingbottom -> rightinstead ofright -> bottom(orleft -> bottominstead ofbottom -> leftoncase 14) reverses a single edge along concave cutout corners. During chain stitching, the directed graph hits a dead end (outDegree = 0), silently discarding entire interior holes and collapsing pixel-to-vector IoU.
Zero-padding the mask by 1 px and enforcing the clockwise right-hand invariant across all 14 active cell states guarantees that every vertex has inDegree === outDegree:
export interface Pt {
x: number;
y: number;
}
export function traceMarchingSquaresHalfEdges(
mask: Uint8Array,
w: number,
h: number
): Map<string, string[]> {
const pw = w + 2;
const ph = h + 2;
const padded = new Uint8Array(pw * ph);
for (let y = 0; y < h; y++) {
for (let x = 0; x < w; x++) {
padded[(y + 1) * pw + (x + 1)] = mask[y * w + x] ? 1 : 0;
}
}
const adj = new Map<string, string[]>();
const addSeg = (x1: number, y1: number, x2: number, y2: number) => {
const k1 = `${x1.toFixed(1)},${y1.toFixed(1)}`;
const k2 = `${x2.toFixed(1)},${y2.toFixed(1)}`;
const list = adj.get(k1);
if (list) list.push(k2);
else adj.set(k1, [k2]);
};
for (let y = 0; y < ph - 1; y++) {
for (let x = 0; x < pw - 1; x++) {
const tl = padded[y * pw + x];
const tr = padded[y * pw + (x + 1)];
const br = padded[(y + 1) * pw + (x + 1)];
const bl = padded[(y + 1) * pw + x];
const code = (tl << 3) | (tr << 2) | (br << 1) | bl;
if (code === 0 || code === 15) continue;
const cx = x - 0.5;
const cy = y - 0.5;
const top = [cx + 0.5, cy] as const;
const right = [cx + 1, cy + 0.5] as const;
const bottom = [cx + 0.5, cy + 1] as const;
const left = [cx, cy + 0.5] as const;
switch (code) {
case 1: addSeg(left[0], left[1], bottom[0], bottom[1]); break;
case 2: addSeg(bottom[0], bottom[1], right[0], right[1]); break;
case 3: addSeg(left[0], left[1], right[0], right[1]); break;
case 4: addSeg(right[0], right[1], top[0], top[1]); break;
case 5: // 4-connected saddle: keep tr=1 and bl=1 separated
addSeg(left[0], left[1], bottom[0], bottom[1]);
addSeg(right[0], right[1], top[0], top[1]);
break;
case 6: addSeg(bottom[0], bottom[1], top[0], top[1]); break;
case 7: addSeg(left[0], left[1], top[0], top[1]); break;
case 8: addSeg(top[0], top[1], left[0], left[1]); break;
case 9: addSeg(top[0], top[1], bottom[0], bottom[1]); break;
case 10: // 4-connected saddle: keep tl=1 and br=1 separated
addSeg(top[0], top[1], left[0], left[1]);
addSeg(bottom[0], bottom[1], right[0], right[1]);
break;
case 11: addSeg(top[0], top[1], right[0], right[1]); break;
case 12: addSeg(right[0], right[1], left[0], left[1]); break;
case 13: addSeg(right[0], right[1], bottom[0], bottom[1]); break; // br=0
case 14: addSeg(bottom[0], bottom[1], left[0], left[1]); break; // bl=0
}
}
}
return adj;
}
Antipodal-Split RamerβDouglasβPeucker on Closed Loops
Once a closed ring is stitched, passing [p0, p1, ..., p0] directly into standard open-polyline RamerβDouglasβPeucker (RDP) creates a degenerate baseline chord of length 0 (or, if p[end] is merely adjacent to p0, biases simplification asymmetrically around the arbitrary start vertex). Instead, we locate the antipodal vertex pB maximizing (pB.x - p0.x)^2 + (pB.y - p0.y)^2, run open RDP independently on ring[0..B] and [...ring[B..end], ring[0]], and apply 1 pass of bounded Chaikin corner cutting (maxCutPx = 0.75).
Across complex portrait fretwork medallions, this pipeline achieves 99.24% pixel-to-vector IoU while separating outer wood contours (signedArea > 0) from interior cutout holes (signedArea < 0) by shoelace sign alone.
2. Half-Pixel (2W + 1) Γ (2H + 1) EDT for Wire-Gauge Pilot Drills
Every enclosed scroll-saw cutout requires a drilled pilot hole to thread the blade (#65 / 0.89 mm for #2/0 veneer blades up to #44 / 2.18 mm for #12 hardwood blades, with #58 / 1.07 mm and #55 / 1.32 mm as workshop staples). Thresholding script or CJK typography inevitably leaves sub-millimeter counter pinholes where no physical twist drill can fit without blowing out adjacent wood walls.
Why not run an Euclidean Distance Transform (EDT) on the W Γ H pixel centers? Consider an even 2 Γ 2 pixel hole: its four pixel centers sit only 0.5 px inside each wall, whereas its true maximum inscribed circle is centered at the shared interior pixel corner with radius 1.0 px (diameter = 2.0 px). Integer-center EDT underestimates even-width holes by up to 29%.
Evaluating Felzenszwalb and Huttenlocher's separable 1D parabolic lower envelope on the (2W + 1) Γ (2H + 1) half-pixel lattice samples pixel corners, edge midpoints, and pixel centers simultaneously in strict O(WΒ·H) time. Better yet, because 1 half-pixel step equals 0.5 px, the Euclidean distance in lattice units equals 2 * radiusPxβthe exact inscribed circle diameter in pixels:
export function computeHalfPixelEdt(
wood: Uint8Array,
gridW: number,
gridH: number
): Float32Array {
const sw = gridW * 2 + 1;
const sh = gridH * 2 + 1;
const INF = 1e9;
const dt = new Float32Array(sw * sh);
for (let iy = 0; iy < sh; iy++) {
const y0 = Math.max(0, (iy - 1) >> 1);
const y1 = Math.min(gridH - 1, iy >> 1);
const onBorderY = iy === 0 || iy === sh - 1;
for (let ix = 0; ix < sw; ix++) {
if (onBorderY || ix === 0 || ix === sw - 1) {
dt[iy * sw + ix] = 0;
continue;
}
const x0 = Math.max(0, (ix - 1) >> 1);
const x1 = Math.min(gridW - 1, ix >> 1);
let touchesWood = false;
for (let py = y0; py <= y1 && !touchesWood; py++) {
for (let px = x0; px <= x1; px++) {
if (wood[py * gridW + px] === 1) touchesWood = true;
}
}
dt[iy * sw + ix] = touchesWood ? 0 : INF;
}
}
const maxDim = Math.max(sw, sh);
const v = new Int32Array(maxDim);
const z = new Float64Array(maxDim + 1);
const f = new Float64Array(maxDim);
const edt1D = (n: number) => {
let k = 0;
v[0] = 0;
z[0] = -1e12;
z[1] = 1e12;
for (let q = 1; q < n; q++) {
let s = (f[q] + q * q - (f[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k]);
while (s <= z[k]) {
k--;
s = (f[q] + q * q - (f[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k]);
}
k++;
v[k] = q;
z[k] = s;
z[k + 1] = 1e12;
}
k = 0;
for (let q = 0; q < n; q++) {
while (z[k + 1] < q) k++;
const dv = q - v[k];
f[q] = dv * dv + f[v[k]];
}
};
for (let ix = 0; ix < sw; ix++) {
for (let iy = 0; iy < sh; iy++) f[iy] = dt[iy * sw + ix];
edt1D(sh);
for (let iy = 0; iy < sh; iy++) dt[iy * sw + ix] = f[iy];
}
for (let iy = 0; iy < sh; iy++) {
const row = iy * sw;
for (let ix = 0; ix < sw; ix++) f[ix] = dt[row + ix];
edt1D(sw);
for (let ix = 0; ix < sw; ix++) dt[row + ix] = f[ix];
}
return dt; // sqrt(dt[idx]) === inscribed circle diameter in pixels!
}
On a 12" plaque (304.80 mm), a 2 Γ 2 px serif pinhole evaluates to 1.03 mm effective clearanceβsmaller than a #55 (1.32 mm) pilot drill bitβand is automatically flooded back to solid wood (wood[p] = 1), whereas cutouts >= 1.50 mm survive and receive a sub-pixel Pole-of-Inaccessibility crosshair (survivingHoleLoops === drillPoints.length).
Cut-to-Cut 304.80 mm Plaques & Open-Top Descender Relief Coves
Freestanding desk and mantle name plaques (Scroll Saw Name Pattern Maker) introduce two competing mechanical requirements:
- The bottom edge must be a dead-flat plane so the finished hardwood sign stands upright without rocking, and the cut-to-cut outer width must match the woodworker's nominal blank (
12.0000" === 304.80 mm,0.00 mmdiscrepancy). - Lowercase script or serif descenders (
g, j, p, q, y) dip below the alphabetic baseline. Simply clipping descenders flat makes"g"look like"o", while letting them protrude below the rail ruins tabletop stability.
Sampling at 40 px/in makes every pixel an exact rational inch (0.025 in = 0.635 mm). Stamping 4 px (2.54 mm) vertical micro-lands at x = 0 and x = gridW - 1 on the beveled base rail and snapping cropped height to an even pixel count (2k / 40 = exact 0.05" multiple) locks Marching Squares outer bounds to 304.80 mm.
To keep lowercase descenders legible without overhanging the bottom rail, a two-pass Canvas2D stencil carves an overhang-free open-top U-relief cove into the upper half of the base bar ([barTopY - 1.5, pocketBottomY]) while welding the bottom curve of each descender hook into a continuous >= 4.4 mm bottom hardwood spine:
// Pass A: Carve open-top U-relief cove in [barTopY - 1.5 .. pocketBottomY]
// Sweeping upward (`-lift`) eliminates floating wood islands above descender bowls!
ctx.save();
ctx.beginPath();
ctx.rect(0, barTopY - 1.5, canvasWidth, pocketBottomY - (barTopY - 1.5));
ctx.clip();
ctx.translate(centerX, effBaselineY);
ctx.scale(fitScale, 1);
ctx.fillStyle = "#ffffff";
ctx.strokeStyle = "#ffffff";
ctx.lineJoin = "round";
ctx.lineCap = "round";
ctx.lineWidth = darkStrokeW + 2 * clearGapPx; // >= minDrillMm + 1.95 mm kerf clearance
chars.forEach((ch, idx) => {
if (!isDescender[idx]) return;
ctx.save();
ctx.translate(charXs[idx], 0);
for (let lift = 0; lift <= pocketDepth; lift += 2) {
ctx.strokeText(ch, 0, -lift);
ctx.fillText(ch, 0, -lift);
}
ctx.restore();
});
ctx.restore();
// Pass B: Render dark wood glyphs strictly above `flatBottomY`, welding bottoms into the rail
Sweeping the white clearance halo strictly upward (0 -> -pocketDepth) ensures no overhanging wood peninsula can ever form inside the cove, while clearGapPx guarantees room for #55 (1.32 mm) through #50 (1.78 mm) scroll-saw blades to turn cleanly.
3. 2D Rotated Fixture Envelopes & Ceiling Fan Strobe Avoidance in Architectural RCPs
Reflected Ceiling Plan calculators frequently treat luminaires as (x, y) points. That shortcut fails in real garages and living rooms:
-
Rotated
4 ftLinear Strips vs. Open Overhead Garage Doors: Suppose a21.5 Γ 19.5 ftgarage has a16 Γ 8.5 ftsectional roll-up door. When open, the door tracks occupyy β [11.00 ft, 19.50 ft], leaving an11.00 ftclear ceiling bay near the workbench wall. If the user rotates4 ft Γ 0.42 ftshop strips by90Β°, each fixture's Y-axis span jumps from0.42 ftto4.00 ft(halfH = 2.00 ft). -
Ceiling Fan Strobe Zones: Placing recessed downlights within
24"of spinning52"fan blade tips (R_blade = 26") creates distracting shadow strobing across the workplane, yet shifting fixtures radially must preserve the underlying carpenter grid callouts (baseGrid) while clamping against drywall perimeters.
In solveRcpObstacleLayout (building-layout-math), we compute rotated physical envelopes (spanXFt, spanYFt) first, bound automatic row count in clear ceiling bays via maxClearBayRows, and run an exact 2D AABB intersection check so manual grid overrides never emit a false PASS:
export function computeGarageDoorBayClearance(params: {
roomWidthFt: number;
doorDepthFt: number;
fixtureLengthFt: number;
fixtureWidthFt: number;
rotateLinear90: boolean;
rows: number;
}) {
const spanY = params.rotateLinear90 ? params.fixtureLengthFt : params.fixtureWidthFt;
const halfH = spanY / 2;
const doorStopYFt = params.roomWidthFt - params.doorDepthFt; // e.g. 19.5 - 8.5 = 11.00 ft
// Max non-overlapping rows that physically fit inside the clear ceiling bay
const maxClearBayRows = Math.max(
1,
Math.floor((doorStopYFt - 0.8 + 0.45) / (spanY + 0.45))
);
const minSafeY = Math.max(halfH + 0.45, 1.85);
const maxSafeY = doorStopYFt - halfH - 0.4;
const minPhysicalPitchY = spanY + 0.35;
const rowCentersFt =
maxSafeY - minSafeY >= (params.rows - 1) * minPhysicalPitchY
? Array.from(
{ length: params.rows },
(_, r) => minSafeY + (r * (maxSafeY - minSafeY)) / Math.max(1, params.rows - 1)
)
: Array.from(
{ length: params.rows },
(_, r) => halfH + 0.35 + r * minPhysicalPitchY
);
const southMostEdgeFt = Number((rowCentersFt[rowCentersFt.length - 1] + halfH).toFixed(2));
const blocked = southMostEdgeFt > doorStopYFt + 0.01;
return {
doorStopYFt,
maxClearBayRows,
rowCentersFt,
southMostEdgeFt,
status: blocked ? "WARNING" : "PASS",
intrusionFt: blocked ? Number((southMostEdgeFt - doorStopYFt).toFixed(2)) : 0,
};
}
On the 21.5 Γ 19.5 ft garage with 90Β° rotated 4 ft strips:
-
Auto Grid (
2 Γ 6):maxClearBayRowsresolves to2, placing row centers at[2.45 ft, 8.60 ft]. Row 2's trailing edge sits at10.60 ft <= 11.00 ft(PASS,0door collisions). -
Manual Override (
3 Γ 4): Three4 ftstrips cannot fit end-to-end inside11.00 ftwithout steel-on-steel overlap. Non-overlapping physical pitch places Row 3 aty = 11.05 ft, pushing its south housing edge to13.05 ft > 11.00 ftand emitting an explicitWARNING(2.05 ftdoor-zone intrusion).
Similarly, on a 4.85 Γ 4.25 m metric room with a 52" ceiling fan (R_blade = 26"), solveRcpObstacleLayout evaluates exact 2D housing-edge-to-blade-tip clearance and exports both the unmodified baseGrid schedule (so electricians can snap chalk lines along the primary grid) and the fanShifted coordinates radially pushed outside R_blade + 30 in:
const targetEdgeRadiusFt = fanRadiusFt + 2.5; // 30" strobe-free buffer outside blade tips
if (edgeDistFromFanCenter < targetEdgeRadiusFt) {
const angle = centerDist < 0.05 ? 0 : Math.atan2(dy, dx);
const pushCenterRadiusFt = targetEdgeRadiusFt + Math.max(halfW, halfH);
const minWallX = Math.min(L / 2, Math.max(1.25, halfW + 0.5));
const minWallY = Math.min(W / 2, Math.max(1.25, halfH + 0.5));
fx = Math.min(L - minWallX, Math.max(minWallX, fanCenterX + Math.cos(angle) * pushCenterRadiusFt));
fy = Math.min(W - minWallY, Math.max(minWallY, fanCenterY + Math.sin(angle) * pushCenterRadiusFt));
}
Exporting the resulting Reflected Ceiling Plan SVG and multi-page vector PDF at 1/4" = 1'-0" (1:48, 24.00 SVG user units per foot at 96 u/in, giving a 5.3750" Γ 4.8750" room boundary for 21.5 Γ 19.5 ft) or ISO 1:50 (20 mm = 1 m, giving an exact 97.00 Γ 85.00 mm room boundary for 4.85 Γ 4.25 m) lets architects and contractors lay a physical scale rule directly onto the printed sheet.
Open-Source Modules & Live Studios
All algorithms above run in zero-dependency ES modules (0 npm packages, node:test verified):
- Discrete Fretwork, EDT & Marching Squares: github.com/kaiyilu/grid-and-fretwork-math β powering Scroll Saw Pattern Generator
- IES Photometrics, 2D RCP Obstacles & CAD Scale Math: github.com/kaiyilu/building-layout-math β powering Lighting Layout Calculator
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.