If you try to quote a sheet-metal laser cutting RFQ by parsing an AutoCAD .dxf file with a naive script that only sums LINE segments and bounding-box extents, four silent bugs will destroy your margin on the very first real customer bracket:

  1. Missing LWPOLYLINE bulge fillets and arcs. CAD exporters rarely emit rounded corners or stadium slots as dozens of tiny lines. They store them as LWPOLYLINE vertices with a group-code 42 bulge factor (tan(θ / 4)). Ignoring bulges turns every fillet into a straight chord and under-measures curved brackets by 10%–25%.
  2. Unitless DXF headers ($INSUNITS = 0). Legacy AutoCAD, Rhino, and CorelDRAW exports routinely omit $INSUNITS or write 0 even when the part was drawn in inches. Silently assuming millimeters makes a 4" × 2" plate quote 25.4× too small in length and 645× too small in sheet area.
  3. Stacked duplicate lines and > 0.05 mm open contours. Flattened 3D-to-2D projections frequently stack two identical lines on top of each other (doubling measured cut length) or leave a 0.2 mm corner gap where CAM kerf compensation breaks.
  4. Treating cut length as the only time driver. On perforated vent panels or multi-hole mounting plates, the laser head must stop and pierce through the sheet at every closed loop (0.20 s to 1.20 s+ per pierce under assist gas). Fifty mounting holes can cost more machine time and copper nozzle wear than the outer perimeter.

I'm David Shen, the indie builder behind LaserQuote Studio—a zero-signup, browser-local laser cutting cost workbench and DXF cut length calculator. Job shops shouldn't have to upload confidential client CAD drawings to a remote server just to measure cut path length, pierce count, and cycle time, so the entire geometry engine runs strictly in client-side TypeScript with zero npm runtime dependencies.

Here is how the four core stages of the parser and quoting pipeline work under the hood (with a standalone MIT-licensed reference implementation at kaiyilu/dxf-cut-length-audit).

1. ASCII DXF Group-Code Tokenization & Fail-Closed $INSUNITS

An ASCII DXF file is not nested XML or JSON—it is a flat stream of two-line (groupCode, value) records divided into HEADER, BLOCKS, and ENTITIES sections. Tokenizing it cleanly takes ten lines:

interface DxfPair { code: number; value: string; } function tokenizeDxf(dxfText: string): DxfPair[] { const lines = dxfText.split(/\r?\n/); const pairs: DxfPair[] = []; for (let i = 0; i + 1 < lines.length; i += 2) { const codeStr = lines[i].trim(); if (codeStr === "") continue; const code = Number.parseInt(codeStr, 10); if (Number.isNaN(code)) continue; pairs.push({ code, value: lines[i + 1].trim() }); } return pairs; } 

Before touching ENTITIES, we scan HEADER for variable $INSUNITS (group code 9, value $INSUNITS, followed by group code 70 integer code). Autodesk defines codes 1..24 (1 = inches × 25.4, 4 = mm × 1.0, 5 = cm × 10.0, 6 = m × 1000.0, down to US survey units).

The most important shop-floor safeguard is failing closed on $INSUNITS = 0 or missing headers:

  • Instead of guessing millimeters silently, the engine sets unitUncertain = true and canQuote = false, forcing a 1-click Confirm mm or Confirm in decision before unlocking a formal quote.
  • We also separate harmless non-cut annotations (TEXT, MTEXT, DIMENSION, POINT, VIEWPORT) from unsupported solid geometry (3DSOLID, REGION, SURFACE, MESH, HATCH). Annotations emit an informational warning; unsupported 3D entities block quoting so an estimator never sends a $12 quote on a drawing whose main plate was trapped inside an unexploded REGION.
  • Hidden (code 60 = 1) and paper-space (code 67 = 1) entities are skipped outright, and recursive BLOCK/INSERT expansion is capped at depth 8 with a 25,000-entity safety budget so malformed nested blocks can never freeze a browser tab.

Real-World DXF Entity Pitfalls in Laser Quoting

DXF Entity Key Group Codes Analytical / Sampling Method Common Quoting Pitfall
LINE 10/20, 11/21 Exact Euclidean distance Stacked duplicates from 3D projection double cut length
CIRCLE 10/20, 40, 210/220/230 Exact 2πr (uniform transform) Tilted OCS extrusion normal (230 = -1) mirrors X coordinates
ARC 10/20, 40, 50, 51 Exact r · Δθ (CCW wrap) Wrapping past 360° (e.g. 270° → 90°) yields negative angle if unnormalized
LWPOLYLINE / POLYLINE 70, 10/20, 42 (bulge) Analytical arc length per bulge vertex Ignoring 42 turns fillets into straight chords; negative det flips bulge sign
ELLIPSE 10/20, 11/21, 40, 41/42 Parametric sampling (32–128 steps) Group 41/42 are eccentric anomalies in radians, not degrees
SPLINE 70, 71, 40, 41, 10/20 Rational Cox–de Boor NURBS sampling Missing knot vector or rational weights (41) distort organic curves
BLOCK / INSERT 2, 10/20, 41/42, 50, 70/71, 44/45 Affine matrix stack + grid array expansion Forgetting block base-point subtraction (baseX, baseY) or *U* anonymous blocks

2. Exact LWPOLYLINE Bulge-Arc Math & Rational NURBS SPLINE Tessellation

In AutoCAD DXF, a polyline vertex's group code 42 stores the bulge connecting vertex P1 to P2:

bulge = tan(θ / 4) θ = 4 * atan(|bulge|) R = chord / (2 * sin(θ / 2)) L = R * θ 

Positive bulge sweeps counter-clockwise; negative bulge sweeps clockwise; bulge = 1.0 is an exact semicircle (180°); bulge = tan(π/8) ≈ 0.41421356 is a 90° corner fillet.

Rather than approximating the arc length by summing coarse chords (which always under-reports perimeter), we compute the exact analytical arc length L = R * θ directly while also emitting tessellated points for bounding-box extents, SVG preview rendering, and point-in-polygon hole detection:

function evaluateBulgeSegment( p1: Point2D, p2: Point2D, bulge: number ): { exactLength: number; points: Point2D[] } { const dx = p2.x - p1.x; const dy = p2.y - p1.y; const chord = Math.hypot(dx, dy); if (chord < 1e-9) return { exactLength: 0, points: [p1] }; if (Math.abs(bulge) < 1e-8) return { exactLength: chord, points: [p1, p2] }; const theta = 4 * Math.atan(Math.abs(bulge)); const sinHalf = Math.sin(theta * 0.5); const radius = sinHalf > 1e-12 ? chord / (2 * sinHalf) : chord * 0.5; const exactLength = radius * theta; // Circle center offset perpendicular to chord midpoint const mx = (p1.x + p2.x) * 0.5; const my = (p1.y + p2.y) * 0.5; const k = (1 - bulge * bulge) / (4 * bulge); const cx = mx - dy * k; const cy = my + dx * k; const startAngle = Math.atan2(p1.y - cy, p1.x - cx); const signedSweep = 4 * Math.atan(bulge); const steps = Math.max(8, Math.min(96, Math.ceil((theta * 180) / Math.PI / 5))); const pts: Point2D[] = [p1]; for (let i = 1; i < steps; i++) { const ang = startAngle + signedSweep * (i / steps); pts.push({ x: cx + radius * Math.cos(ang), y: cy + radius * Math.sin(ang), }); } pts.push(p2); return { exactLength, points: pts }; } 

Two subtle CAD edge cases show up once BLOCK/INSERT transforms enter the picture:

  • Mirrored blocks (sx = -1) or flipped OCS normals (230 = -1): Whenever the 2D affine transform determinant a * d - b * c < 0, chirality flips, so you must multiply the bulge by -1 before evaluating the arc—otherwise concave pockets invert outward into convex bumps.
  • Non-uniform block scaling (sx !== sy): A scaled circular arc becomes an elliptical arc. When isUniformTransform(transform) is false, we tessellate the bulge in local block space first, transform every sampled vertex through the affine matrix, and sum the transformed polyline length.

For freeform SPLINE entities (common in signage, brackets exported from SolidWorks/Fusion, and organic cutouts), we evaluate rational NURBS curves in homogeneous coordinates using Cox–de Boor recursion (evaluateBSplinePoint), automatically synthesizing a clamped uniform knot vector if the DXF omits group code 40 knots, and sampling at Math.max(64, controlPts.length * 20) steps.

3. Deduplication, 0.05 mm Open-Loop Graph Chaining & Pierce Counting

Once every entity has been converted into millimeter-scaled raw segments, raw entity count still doesn't equal laser pierces. A single rectangular cutout exported from an older CAM tool might arrive as four independent LINE entities (or two LINEs + two ARCs forming a stadium slot).

To audit cut topology accurately without false merges, the engine runs a four-step pass at ENDPOINT_TOLERANCE_MM = 0.05:

  1. Open-segment deduplication: Bucket open segments in a 1.0 mm spatial hash grid. Two segments are treated as stacked duplicates only if their lengths match within 0.15 mm, their endpoints match in forward or reversed order within 0.05 mm, their arc-length midpoints agree, and mutual point-to-segment distance across sampled vertices is <= 0.05 mm.
  2. Spatial-grid endpoint snapping & 2-core graph chaining:
    • Snap every open segment's start and end points into shared graph vertices within a 0.05 mm cell grid.
    • Contract all degree-2 vertex chains into super-edges, closing disconnected degree-2 cycles directly into closedFromGraph.
    • On graphs with T-junctions or shared edges, iteratively peel degree-1 leaves into openFromGraph (unclosed paths) and run BFS on the remaining 2-core to recover valid closed cycles without falsely erasing junctions.
  3. Closed-loop mutual Hausdorff deduplication: Two closed contours are deduplicated only when every sampled arc-length point and vertex on loop A lies within 0.05 mm of loop B and vice versa. Checking bounding box + perimeter alone is unsafe—two mirrored triangles or L-brackets can share the exact same bounding box and perimeter while being distinct cuts.
  4. Nesting depth & pierce count: For every closed loop, cast a ray from a point on its boundary against every larger closed loop's polygon (isPointInsidePolygon). Even nesting depth (0, 2, ...) marks an Outer silhouette; odd depth (1, 3, ...) marks an Inner hole or slot. Every continuous contour (closed or open) adds exactly 1 laser pierce.
// Any open contour remaining after 0.05 mm endpoint snapping & 2-core cycle extraction // is surfaced as an actionable fabrication warning before CAM nesting. const closedContourCount = closedStructs.length; const openContourCount = openFromGraph.length; const pierceCount = closedContourCount + openContourCount; if (openContourCount > 0) { warnings.push( `${openContourCount} unclosed open contour${openContourCount === 1 ? "" : "s"} ` + `detected (> 0.05 mm gap). Verify kerf compensation & lead-ins before cutting.` ); } 

On the 120 × 80 mm bracket fixture in examples/bracket-sample.dxf (an LWPOLYLINE perimeter with four R10 mm bulge fillets, two Ø10 mm CIRCLE bolt holes, and a central slot made from two LINEs + two ARCs), both the minimal reference CLI and the full production parser return identical analytical results:

  • Bounding Box: 120.00 × 80.00 mm
  • Outer Perimeter: 382.83 mm (200 + 120 + 2π × 10)
  • Inner Cutouts: 140.53 mm (2 × 2π × 5 + stitched 40 + 2π × 6 slot)
  • Total Cut Length: 523.36 mm · Pierces: 4 (4 closed, 0 open)

4. Pierce Dwell, Cycle Time & Cent-Exact Cost Reconciliation

Accurate geometry only gets you halfway to a defensible shop quote. Fiber lasers cutting steel and CO2 lasers cutting acrylic or birch behave very differently on pierce dwell and nozzle consumables. Below are the baseline presets used inside LaserQuote Studio:

Material & Thickness Laser / Assist Gas Feed Rate (mm/min) Pierce Dwell (s) Pierce Consumable ($/pierce) Reference Shop Rate ($/hr)
Mild Steel — 1.5 mm (16 ga) Fiber (N₂ / Air) 6,800 0.25 s $0.03 $95
Mild Steel — 3.0 mm (11 ga) Fiber (O₂ / N₂) 3,400 0.55 s $0.05 $105
Mild Steel Plate — 6.0 mm (1/4") Fiber (O₂) 1,650 1.20 s $0.10 $115
304 Stainless — 2.0 mm (14 ga) Fiber (High-PSI N₂) 4,600 0.40 s $0.06 $120
5052 Aluminum — 3.0 mm (0.125") Fiber (High-PSI N₂) 3,800 0.50 s $0.07 $120
Cast Acrylic — 3.0 mm (1/8") CO2 (Low-PSI Air) 1,500 0.20 s $0.01 $65
Baltic Birch — 6.0 mm (1/4") CO2 (Shop Air) 1,200 0.30 s $0.01 $60

When turning geometry into dollars, floating-point rounding discrepancies on multi-quantity quotes ($4.804 × 25 = $120.10 displaying as $4.80 × 25 = $120.10—a $0.10 mismatch!) immediately erode buyer trust on formal PDFs. We round the unit price to integer cents first and derive the line total strictly from quotedUnitPriceCents * qty:

const blankW = geometry.bbox.widthMm > 0 ? geometry.bbox.widthMm + nestGapMm : 0; const blankH = geometry.bbox.heightMm > 0 ? geometry.bbox.heightMm + nestGapMm : 0; const nestedAreaM2 = ((blankW * blankH) / 1_000_000) * (1 + scrapPercent / 100); const materialCost = nestedAreaM2 * effectivePricePerM2Usd; const cutTimeSec = (geometry.cutLengthMm / Math.max(0.5, cutSpeedMmPerMin)) * 60; const pierceTimeSec = geometry.pierceCount * pierceTimeSecPerHole; const machineCost = (cutTimeSec + pierceTimeSec) * (shopHourlyRateUsd / 3600); const pierceConsumable = geometry.pierceCount * costPerPierceUsd; const setupShare = includeLineSetup ? setupFeeUsd / qty : 0; const directShopCost = materialCost + machineCost + pierceConsumable + setupShare; const rawUnitUsd = markupMode === "margin" ? directShopCost / (1 - Math.min(95, markupPercent) / 100) : directShopCost * (1 + markupPercent / 100); // Cent-exact accounting: displayed unitPrice * qty === displayed lineTotal to $0.00 const quotedUnitPriceCents = Math.round(rawUnitUsd * 100); const quotedLineTotalCents = quotedUnitPriceCents * qty; 

Notice how nestGapMm (kerf + skeleton web bridge between nested parts) and scrapPercent expand the bounding blank before multiplying by sheet cost per m², preventing shops from pricing only the net silhouette area and eating the skeleton drop.

Try the Reference Repo or Full Browser Workbench

If you build browser-side CAD/CAM parsers or quoting pipelines, I'd be curious how you handle nasty real-world DXF edge cases—especially self-intersecting splines, corner acceleration slowdown factors on micro-perforated grids, or non-standard AC1032 exports from SolidWorks and Illustrator.