Exact 2D DXF Bulge Arcs, AutoCAD OCS Transforms & 2-Core Laser Pierce Counting in TypeScript
If you build a browser-side 2D .dxf parser to estimate fiber or CO2 laser cycle time on sheet-metal brackets, summing Euclidean distances between polyline vertices works right up until a mechanical engineer drops a real
If you build a browser-side 2D .dxf parser to estimate fiber or CO2 laser cycle time on sheet-metal brackets, summing Euclidean distances between polyline vertices works right up until a mechanical engineer drops a real SolidWorks or AutoCAD flat pattern onto your canvas.
Four failure modes show up immediately in production drawings:
-
Silent
57%Cut-Length Underestimates (LWPOLYLINEGroup Code42): CAD exporters represent stadium slots, rounded mounting tabs, and corner fillets as two-vertexLWPOLYLINEsegments carrying a scalar bulgeb = tan(ΞΈ / 4)rather than discreteARCentities. Measuring straight chords instead of bulge arcs under-measures a semicircular slot endcap by57.08%. -
Mirrored Bottom-Face Cutouts (
210 / 220 / 230OCS Extrusion): Exporting the underside of a bent sheet-metal part often writesCIRCLEandARCentities with extrusion normal(0, 0, -1). Ignoring AutoCAD's1/64Arbitrary Axis Algorithm leaves hole X-coordinates negatedβteleporting bolt holes outside the plate boundary and doubling bounding-box material cost. -
Stacked Construction Lines & T-Junction Tails: Drawings exported from 2D sketches routinely contain duplicate overlapping lines (
2xcycle time) or stray T-junction lead-in ticks that break naive greedy loop chainers into false extra pierces. -
Unitless
$INSUNITS = 0& Penny Rounding Drift: Imperial inch drawings saved with$INSUNITS = 0under-quote material by25.4Β² = 645Γif silently assumed to be millimeters, while unrounded floating-point unit prices produce client invoices where$4.13 Γ 17prints as$70.27instead of$70.21.
Here is how to solve all four deterministically in zero-dependency TypeScript / ES Modules.
1. Exact LWPOLYLINE Group-Code 42 Bulge Integration
In the Autodesk DXF specification, each vertex P_i = (x_i, y_i) in an LWPOLYLINE may carry an optional group code 42 bulge scalar b governing the segment from P_i to P_{i+1}:
b = tan(theta / 4)
where ΞΈ β (0, 2Ο) is the included arc sweep angle (b > 0 counter-clockwise, b < 0 clockwise, |b| = 1 an exact 180Β° semicircle).
Given chord vector (dx, dy) = P2 - P1 and chord length c = Math.hypot(dx, dy):
- Sweep angle:
ΞΈ = 4 * atan(|b|) - Since
sin(ΞΈ / 2) = 2|b| / (1 + bΒ²)andc = 2 * R * sin(ΞΈ / 2), the exact radius is:
R = c * (1 + b^2) / (4 * |b|)
- Exact cut arc length:
L_arc = R * ΞΈ - Using
cot(ΞΈ / 2) = (1 - bΒ²) / (2b), the circle center offset from chord midpointMalong the left normal(-dy, dx)needs zerosin/coscalls:
export interface Point2D {
x: number;
y: number;
bulge?: number;
}
export function bulgeSegmentGeometry(p1: Point2D, p2: Point2D, bulge = 0) {
const dx = p2.x - p1.x;
const dy = p2.y - p1.y;
const chord = Math.hypot(dx, dy);
if (chord < 1e-12 || !Number.isFinite(bulge) || Math.abs(bulge) < 1e-9) {
return {
isArc: false,
chordLength: chord,
arcLength: chord,
radius: chord < 1e-12 ? 0 : Infinity,
sweepRad: 0,
center: { x: (p1.x + p2.x) / 2, y: (p1.y + p2.y) / 2 },
};
}
const absB = Math.abs(bulge);
const sweepRad = 4 * Math.atan(absB);
const radius = (chord * (1 + absB * absB)) / (4 * absB);
const arcLength = radius * sweepRad;
// Signed normal offset from chord midpoint: cot(theta/2)/(2) = (1 - b^2)/(4b)
const offsetFactor = (1 - bulge * bulge) / (4 * bulge);
const center = {
x: (p1.x + p2.x) / 2 - dy * offsetFactor,
y: (p1.y + p2.y) / 2 + dx * offsetFactor,
};
return { isArc: true, chordLength: chord, arcLength, radius, sweepRad, center };
}
For a 100 Γ 40 mm stadium slot (60 mm straight sides + two bulge = 1 semicircular endcaps across 40 mm chords), summing straight chords yields 200.00 mm, whereas bulgeSegmentGeometry yields the exact 120 + 40Ο = 245.66 mm cut path.
2. AutoCAD's 1/64 Arbitrary Axis Algorithm (OCS -> WCS)
Planar 2D DXF entities (CIRCLE, ARC, LWPOLYLINE, SOLID, INSERT) store coordinates in an Object Coordinate System (OCS) rather than World Coordinates (WCS), parameterized solely by the unit extrusion normal N = (Nx, Ny, Nz) in group codes 210, 220, 230.
To reconstruct the exact orthonormal basis (Ax, Ay, N) that AutoCAD uses internally, you must apply the exact 1/64 (0.015625) gimbal-lock switch between World Wz = (0, 0, 1) and World Wy = (0, 1, 0):
export interface Vec3 {
x: number;
y: number;
z: number;
}
export function ocsToWcsPoint(point: Vec3, normal: Vec3 = { x: 0, y: 0, z: 1 }): Vec3 {
const mag = Math.hypot(normal.x, normal.y, normal.z) || 1;
const nx = normal.x / mag;
const ny = normal.y / mag;
const nz = normal.z / mag;
const THRESHOLD = 1 / 64;
let axX: number, axY: number, axZ: number;
if (Math.abs(nx) < THRESHOLD && Math.abs(ny) < THRESHOLD) {
// Ax = Wy (0,1,0) x N
axX = nz;
axY = 0;
axZ = -nx;
} else {
// Ax = Wz (0,0,1) x N
axX = -ny;
axY = nx;
axZ = 0;
}
const axMag = Math.hypot(axX, axY, axZ) || 1;
axX /= axMag;
axY /= axMag;
axZ /= axMag;
// Ay = N x Ax
let ayX = ny * axZ - nz * axY;
let ayY = nz * axX - nx * axZ;
let ayZ = nx * axY - ny * axX;
const ayMag = Math.hypot(ayX, ayY, ayZ) || 1;
ayX /= ayMag;
ayY /= ayMag;
ayZ /= ayMag;
return {
x: point.x * axX + point.y * ayX + point.z * nx,
y: point.x * axY + point.y * ayY + point.z * ny,
z: point.x * axZ + point.y * ayZ + point.z * nz,
};
}
Notice what happens when a sheet-metal flat pattern exports with N = (0, 0, -1): |Nx| = 0 < 1/64 and |Ny| = 0 < 1/64, so Ax = Wy Γ (0, 0, -1) = (-1, 0, 0) and Ay = (0, 1, 0). Every OCS (x, y) maps cleanly to (-x, y), snapping mirrored bolt circles right back inside the bracket perimeter!
3. Segment Deduplication & 2-Core Leaf Peeling for Exact Pierce Counts
Why does pierce count matter almost as much as linear cut length in laser quoting?
On a 3 kW fiber laser cutting 6.0 mm (1/4 in) mild steel plate under O2 assist gas, linear feed runs around 1,650 mm/min, while each stationary pierce dwells for ~1.20 s plus copper nozzle spatter wear. A perforated mounting plate with 60 bolt/vent holes spends 72 seconds just piercingβoften exceeding the outer perimeter traverse time.
When chaining loose LINE and ARC entities exported by older CAD systems:
-
Undirected Snap-Grid Deduplication (
0.05 mm): Quantize segment endpoints(u, v)onto a0.05 mmtolerance grid and hash canonical undirected keysmin(u,v)|max(u,v)|lenBucketso stacked sketch lines don't double-charge cycle time. -
Vertex-Degree
2-Core Leaf Peeling: If a drawing has a5 mmlead-in tick touching a closed rectangular contour at a degree-3 T-junction, a greedy walk from the rectangle can accidentally exit onto the open tick and report 2 open contours instead of 1 closed contour + 1 open lead-in.
Peeling degree-1 vertices iteratively before extracting cycles isolates the 2-core cleanly:
// 1. Enqueue all degree-1 vertices (open endpoints)
const leafQueue = [...vertices.entries()]
.filter(([, node]) => node.edges.size === 1)
.map(([vid]) => vid);
while (leafQueue.length > 0) {
const startLeaf = leafQueue.shift()!;
if (vertices.get(startLeaf)!.edges.size !== 1) continue;
openPathCount++;
let curr = startLeaf;
while (vertices.get(curr)!.edges.size === 1) {
const edgeIdx = vertices.get(curr)!.edges.values().next().value!;
const edge = graphEdges[edgeIdx];
edge.active = false;
vertices.get(edge.u)!.edges.delete(edgeIdx);
vertices.get(edge.v)!.edges.delete(edgeIdx);
const next = edge.u === curr ? edge.v : edge.u;
// Stop at isolated end (deg 0) or T-junction branch onto a closed loop (deg >= 2)
if (vertices.get(next)!.edges.size !== 1) break;
curr = next;
}
for (const [vid, node] of vertices) {
if (node.edges.size === 1 && !leafQueue.includes(vid)) leafQueue.push(vid);
}
}
// Every remaining active edge now belongs strictly to closed 2-core contours!
4. Cent-Exact Unit Γ Quantity Quote Reconciliation
Once cutLengthMm, pierceCount, and bbox are known, direct part cost combines nested blank area (bounding box + kerf/skeleton gap + scrap allowance), traverse + pierce machine time, pierce consumables, and setup amortization:
const cutTimeSec = (cutLengthMm / cutSpeedMmPerMin) * 60;
const pierceTimeSecTotal = pierceCount * pierceTimeSec;
const machineCostUsd = ((cutTimeSec + pierceTimeSecTotal) / 3600) * shopHourlyRateUsd;
const blankAreaM2 =
(((bbox.widthMm + nestGapMm) * (bbox.heightMm + nestGapMm)) / 1_000_000) *
(1 + scrapPercent / 100);
const directUnitCostUsd =
blankAreaM2 * pricePerM2Usd +
machineCostUsd +
pierceCount * costPerPierceUsd +
setupFeeUsd / quantity;
// Round unit price ONCE to integer cents so Unit_Price * Qty === Line_Total to $0.00!
const quotedUnitPriceCents = Math.round(directUnitPriceWithMargin(directUnitCostUsd) * 100);
const quotedLineTotalCents = quotedUnitPriceCents * quantity;
Rounding quotedUnitPriceCents to integer cents before multiplying by quantity guarantees that Unit Price Γ Qty === Line Total and sum(Lines) + Setup + Tax === Grand Total reconcile to $0.00 across browser tables, client PDFs, and ERP CSVs.
Open-Source Module & Browser Workbench
-
MIT ES Module & Interactive Spec: github.com/kaiyilu/dxf-laser-quote-math (Live Field Guide) β zero-dependency solvers and
node:testsuite covering bulge arcs, OCS transforms,2-core topology, and cent-exact quoting. -
Browser-Local CAD Quoting Workbench: Laser Cutting Cost Calculator (DXF & SVG) β drop 2D
.dxfand.svgfiles locally in your browser (with$INSUNITSunit confirmation, dark blueprint open-loop inspection, and saved browser shop-rate presets) without uploading customer CAD geometry to a third-party queue.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.