Browse Source

Fixed chamfer bug in exact extrusion

Toby Chui 1 day ago
parent
commit
24d2b6a967

+ 5 - 0
src/web/3D Modeler/PROPOSAL.md

@@ -3186,6 +3186,11 @@ js/drawing/         drawing mode (14.17): drawing.js (controller, panels),
 js/silhouette.js    outlines of round faces for the view (14.24)
 js/planedrag.js     dragging a plane into an offset sketch plane, with
                     offsetbox.js (the value box by the pointer) (14.24)
+js/regionpick.js    which shaded sketch area a click picks when areas of
+                    two sketches lie over each other (the smallest)
+js/featuremark.js   the faces and edges a feature made, by face name, for
+                    the dotted green outline shown while its row in the
+                    model browser is hovered
 js/io/              files.js (AGI open / save / export, browser fallback),
                     exchange.js (STL, OBJ, 3MF writers), drawsvg.js,
                     pdf.js, dxf.js, png.js (drawing writers), paths.js

+ 4 - 0
src/web/3D Modeler/js/app.js

@@ -260,6 +260,10 @@ const browser = createBrowser($('tree'), doc, {
     onPlaneHover: function (key) {
         viewport.setHotPlane(key);
     },
+    // A feature row hovered: outline in the model what it made
+    onFeatureHover: function (id) {
+        viewport.setFeatureMark(id);
+    },
     onPlaneClick: function (key) {
         // A work feature panel waiting for a plane takes it
         if (viewport.offerRef({ kind: 'plane', target: { kind: 'origin', key: key } })) {

+ 21 - 0
src/web/3D Modeler/js/browser.js

@@ -544,6 +544,27 @@ export function createBrowser(el, doc, handlers) {
         }
     });
 
+    // The feature row under the pointer (onFeatureHover(id), null when it
+    // leaves), so the model can show where that feature changed it. Watched
+    // on the whole tree: rows are made anew on every render, and a row that
+    // goes away under the pointer never says it was left.
+    let hovering = null;
+    function hoverFeature(id) {
+        if (id !== hovering) {
+            hovering = id;
+            if (handlers.onFeatureHover) {
+                handlers.onFeatureHover(id);
+            }
+        }
+    }
+    el.addEventListener('mouseover', function (event) {
+        const node = event.target && event.target.closest ? event.target.closest('.node[data-feature]') : null;
+        hoverFeature(node && el.contains(node) ? node.dataset.feature : null);
+    });
+    el.addEventListener('mouseleave', function () {
+        hoverFeature(null);
+    });
+
     return {
         // Redraw; pass the rebuild report and body count when they changed
         render: function (newReport, newBodyCount) {

+ 56 - 0
src/web/3D Modeler/js/featuremark.js

@@ -0,0 +1,56 @@
+/*
+    3D Modeler - where a feature changed the model
+
+    Hovering a feature in the model browser outlines, in the model, what that
+    feature made (viewport.js setFeatureMark draws it dotted light green), so
+    the feature to edit is easy to find. Every face carries a name built from
+    the feature that made it (kernel/naming.js): "<id>/start", "<id>/end+",
+    "<id>/side:<curve>", "<id>/new", ... A face a later feature only trims or
+    splits keeps its name, so the outline follows it.
+
+        featureFaces(body, id)       indices of the faces of `body` (a
+                                     described body: faces with name and
+                                     edges) feature `id` made
+        featureEdgePoints(body, id)  the edges of those faces as line
+                                     segments: [x, y, z, x, y, z, ...], two
+                                     points per segment, each edge once
+*/
+
+export function featureFaces(body, id) {
+    const out = [];
+    if (!body || !id || !Array.isArray(body.faces)) {
+        return out;
+    }
+    const prefix = id + '/';
+    body.faces.forEach(function (face, i) {
+        if (face && typeof face.name === 'string' && face.name.indexOf(prefix) === 0) {
+            out.push(i);
+        }
+    });
+    return out;
+}
+
+export function featureEdgePoints(body, id) {
+    const points = [];
+    const edges = body && Array.isArray(body.edges) ? body.edges : [];
+    const positions = body ? body.edgePositions : null;
+    if (!positions) {
+        return points;
+    }
+    const seen = new Set();
+    featureFaces(body, id).forEach(function (f) {
+        (body.faces[f].edges || []).forEach(function (e) {
+            const edge = edges[e];
+            if (seen.has(e) || !edge) {
+                return;
+            }
+            seen.add(e);
+            // edgePositions holds point pairs; an edge is `count` points from `start`
+            const end = Math.min((edge.start + edge.count) * 3, positions.length);
+            for (let k = edge.start * 3; k < end; k++) {
+                points.push(positions[k]);
+            }
+        });
+    });
+    return points;
+}

+ 21 - 1
src/web/3D Modeler/js/features/extrude.js

@@ -15,6 +15,8 @@
     slanted); To Next (the first face of the solid ahead); Through All.
     A taper leans the sides in (out when negative) for one-way extents.
     The card beside the panel animates the chosen extent and Boolean.
+    Flipping the direction (the button, or the arrow pulled through the
+    plane) turns a Join into a Cut and back (followDirection).
 
     createExtrude(options)
         stage       element the panel is added to
@@ -255,8 +257,10 @@ export function createExtrude(options) {
         }, function (distance) {
             // Pulled through the plane: the extrusion turns round
             if (distance < 0 && (draft.direction === 'positive' || draft.direction === 'negative')) {
-                draft.direction = draft.direction === 'positive' ? 'negative' : 'positive';
+                const from = draft.direction;
+                draft.direction = from === 'positive' ? 'negative' : 'positive';
                 directionTouched = true;
+                followDirection(from, draft.direction);
             }
             const size = Math.abs(distance) * (draft.direction === 'symmetric' ? 2 : 1);
             draft.value = Math.max(Math.round(size * 4) / 4, 0.25); // the arrow moves in quarter millimetres; type for anything finer
@@ -308,6 +312,20 @@ export function createExtrude(options) {
         }, 40);
     }
 
+    // Turning the extrusion round turns a Join into a Cut and a Cut back
+    // into a Join: flipped, it grows into the material. Intersect and New
+    // Solid stay as chosen, and with no solid yet there is nothing to cut.
+    // The card beside the panel shows the new Boolean.
+    function followDirection(from, to) {
+        if (from === 'positive' && to === 'negative' && draft.operation === 'join' && viewport.bodyCount() > 0) {
+            draft.operation = 'cut';
+            lastSeg = 'operation';
+        } else if (from === 'negative' && to === 'positive' && draft.operation === 'cut') {
+            draft.operation = 'join';
+            lastSeg = 'operation';
+        }
+    }
+
     function setOperation(id) {
         draft.operation = id;
         // A cut usually goes into the material, a join away from it; follow
@@ -341,8 +359,10 @@ export function createExtrude(options) {
         refresh();
     });
     segmented(el.direction, DIRECTIONS, function (id) {
+        const from = draft.direction;
         draft.direction = id;
         directionTouched = true;
+        followDirection(from, id);
         refresh();
     });
     segmented(el.operation, OPERATIONS, function (id) {

+ 109 - 71
src/web/3D Modeler/js/kernel/occt.js

@@ -2419,7 +2419,7 @@ function onEdges(oc, bodies, feature, what, make, report, retry) {
                 }
             }
             if (report) {
-                // a chamfer that was cut (cutChamfer) knows its new faces itself
+                // a chamfer made of wedges (wedgeChamfer) knows its new faces itself
                 report.fresh[index] = maker.fresh ? maker.fresh() : freshFaces(oc, maker, body, made);
             }
             return made;
@@ -2543,7 +2543,7 @@ export function chamfer(oc, bodies, feature, report) {
     if (mode === 'angle' && !(angle > 0 && angle < 90)) {
         throw new Error('The chamfer angle must be between 0 and 90 degrees');
     }
-    // What building the chamfer of `edges` on `body` needs (cutChamfer):
+    // What building the chamfer of `edges` on `body` needs (wedgeChamfer):
     // { build(scale), sizes(i, faces, between), free() }
     const plan = function (body, edges) {
         // Two distances or an angle are measured from one of the edge's two
@@ -2630,11 +2630,11 @@ export function chamfer(oc, bodies, feature, report) {
             free: free
         };
     };
-    // The builder's chamfer; cut (cutChamfer) when the builder refuses it
+    // The builder's chamfer; made of wedges (wedgeChamfer) when it refuses
     const make = function (body, edges) {
         const p = plan(body, edges);
         try {
-            const maker = p.build(1) || cutChamfer(oc, body, edges, p.sizes, p.build);
+            const maker = p.build(1) || wedgeChamfer(oc, body, edges, p.sizes, p.build);
             if (!maker) {
                 throw new Error('The chamfer could not be built on these edges. Try a smaller distance');
             }
@@ -2644,11 +2644,11 @@ export function chamfer(oc, bodies, feature, report) {
         }
     };
     // The builder may also say done and leave the face it should take away
-    // as a broken sliver (the end of a rib standing on a plate): cut it then
+    // as a broken sliver (the end of a rib standing on a plate): wedges then
     const retry = function (body, edges) {
         const p = plan(body, edges);
         try {
-            return cutChamfer(oc, body, edges, p.sizes, p.build);
+            return wedgeChamfer(oc, body, edges, p.sizes, p.build);
         } finally {
             p.free();
         }
@@ -2658,19 +2658,20 @@ export function chamfer(oc, bodies, feature, report) {
 
 /* ---- a chamfer that takes a whole face away ---- */
 // OpenCascade's chamfer builder refuses a bevel that ends exactly on the far
-// edge of a face next to the edge: a 10 mm chamfer on the end of a 10 mm
-// plate, which takes the end face away, fails while 9.99 builds (and so do
-// two chamfers that meet in a ridge), or it says done and leaves the face as
-// a broken sliver. On straight edges between flat faces a
-// chamfer is the same as cutting a wedge off along the edge, so that is what
-// is done then. The cut is only kept when it takes off what the builder's
-// own chamfers a hair smaller say it should: their volumes, carried on to
-// the full size. A wedge that bites into something past the end of an edge
-// (a wall the edge runs into) fails that check, and the chamfer fails as it
-// did before.
+// edge of a face next to the edge, so that the face goes away: a 10 mm
+// chamfer on the end of a 10 mm plate, or in the inside corner of a 10 mm
+// step (which fills the step up into a ramp), fails while 9.99 builds; so do
+// two chamfers that meet in a ridge. Or it says done and leaves the face as
+// a broken sliver. On straight edges between flat faces a chamfer is a
+// wedge along the edge, cut off at an outside corner and added in an inside
+// one, so that is what is built then (wedgeChamfer). It is only kept when it
+// changes the volume as much as the builder's own chamfers a hair smaller
+// say it should, carried on to the full size: a wedge that reaches
+// something past the end of an edge fails that check, and the chamfer fails
+// as it did before.
 
 // how much smaller (as a fraction) the builder's chamfers for the check are
-const CUT_CHECK_STEP = 1e-3;
+const WEDGE_CHECK_STEP = 1e-3;
 
 function vSub(a, b) {
     return [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
@@ -2693,10 +2694,12 @@ function vUnit(a) {
     return l > 1e-12 ? [a[0] / l, a[1] / l, a[2] / l] : null;
 }
 
-// A straight edge between two flat faces that meet at an outside corner:
-// { start, e: unit direction, length, faces: [face, face] (facesOfEdge
-// order, the caller's to delete), u: per face the direction across it away
-// from the edge, between: the angle between the two in radians }, or null.
+// A straight edge between two flat faces: { start, e: unit direction,
+// length, faces: [face, face] (facesOfEdge order, the caller's to delete),
+// convex: an outside corner (else inside), u: per face the direction across
+// it away from the edge, between: the angle between the two in radians
+// (the open side of an inside corner), open: per end, whether the material
+// stops there }, or null.
 function bevelSite(oc, body, edge) {
     const curve = new oc.BRepAdaptor_Curve(edge);
     let ends = null;
@@ -2732,16 +2735,20 @@ function bevelSite(oc, body, edge) {
         return drop();
     }
     // An outside corner: a step off the edge across one face and under the
-    // other is out of the material (as edgeSignature)
+    // other is out of the material (as edgeSignature); inside it at an
+    // inside corner
     const off = vUnit(vSub(normals[0], normals[1]));
-    if (!off || isInside(oc, body, vAdd(mid, off, 0.01))) {
-        return drop();
+    if (!off) {
+        return drop(); // the faces lie on one plane: no corner
     }
+    const convex = !isInside(oc, body, vAdd(mid, off, 0.01));
     // Across a face away from the edge is in the face's plane, square to the
-    // edge, and (at an outside corner) against the other face's normal
+    // edge, against the other face's normal at an outside corner and along
+    // it at an inside one
     const u = [0, 1].map(function (k) {
         const across = vUnit(vCross(normals[k], e));
-        return across && vDot(across, normals[1 - k]) > 0 ? across.map(function (c) {
+        const along = across ? vDot(across, normals[1 - k]) : 0;
+        return across && (convex ? along > 0 : along < 0) ? across.map(function (c) {
             return -c;
         }) : across;
     });
@@ -2749,11 +2756,15 @@ function bevelSite(oc, body, edge) {
         return drop();
     }
     // Per end, does the material stop there? Every other face through the
-    // end looks away from the edge (the end of a box): the wedge may run on
-    // past it. A face that looks back at the edge (the plate a rib stands
-    // on) carries the material on: the wedge stops at the end.
+    // end looks away from the edge (the end of a box): a cut may run on past
+    // it. A face that looks back at the edge (the plate a rib stands on)
+    // carries the material on: the cut stops at the end. Only a cut asks:
+    // a wedge that is added always stops at the ends.
     const open = [false, false];
     [0, 1].forEach(function (k) {
+        if (!convex) {
+            return;
+        }
         const end = ends[k];
         const away = k === 0 ? e.map(function (c) {
             return -c;
@@ -2771,7 +2782,7 @@ function bevelSite(oc, body, edge) {
         explorer.delete();
         open[k] = stops;
     });
-    return { start: ends[0], e: e, length: length, faces: faces, u: u, open: open, between: Math.acos(Math.max(-1, Math.min(1, vDot(u[0], u[1])))) };
+    return { start: ends[0], e: e, length: length, faces: faces, convex: convex, u: u, open: open, between: Math.acos(Math.max(-1, Math.min(1, vDot(u[0], u[1])))) };
 }
 
 // A solid: the triangle `corners` swept by `sweep`
@@ -2795,11 +2806,23 @@ function wedgeSolid(oc, corners, sweep) {
     return outward(oc, solid);
 }
 
-// The chamfer of `edges` (on `body`) cut as wedges. sizes(i, faces,
-// between): the distances on the two faces of edge i; build(scale): the
-// builder's chamfer with every distance times scale, or null. Returns a
-// stand-in for the builder ({ Shape, fresh, delete }) or null.
-function cutChamfer(oc, body, edges, sizes, build) {
+// Join `solid` into `tool` (null: none yet); null when the join fails
+function gather(oc, tool, solid) {
+    if (!tool) {
+        return solid;
+    }
+    const joined = boolean(oc, 'join', tool, solid);
+    tool.delete();
+    solid.delete();
+    return joined;
+}
+
+// The chamfer of `edges` (on `body`) as wedges, cut off at outside corners
+// and added in inside ones. sizes(i, faces, between): the distances on the
+// two faces of edge i; build(scale): the builder's chamfer with every
+// distance times scale, or null. Returns a stand-in for the builder
+// ({ Shape, fresh, delete }) or null.
+function wedgeChamfer(oc, body, edges, sizes, build) {
     const sites = [];
     const free = function () {
         sites.forEach(function (site) {
@@ -2808,10 +2831,12 @@ function cutChamfer(oc, body, edges, sizes, build) {
             });
         });
     };
-    let tool = null;
-    let cut = null;
+    let cutTool = null;
+    let fillTool = null;
+    let result = null;
     try {
         const bevels = [];
+        let nominal = 0; // the volume of the wedges, for the check
         for (let i = 0; i < edges.length; i++) {
             const site = bevelSite(oc, body, edges[i]);
             if (!site) {
@@ -2823,55 +2848,69 @@ function cutChamfer(oc, body, edges, sizes, build) {
                 return null;
             }
             // The cross section: the bevel from one face to the other, and a
-            // corner off the material so no side lies on a face of the body.
-            // Run on past an end where the material stops, so it clears the
-            // face there (the end of a box may lean); else stop at the end.
+            // third corner so no side lies on a face of the body: off the
+            // material for a cut, a little into it for a wedge that is added.
+            // A cut runs on past an end where the material stops, so it
+            // clears the face there (the end of a box may lean); otherwise
+            // the wedge stops at the end.
             const a = site.u[0].map(function (c) {
                 return c * d[0];
             });
             const b = site.u[1].map(function (c) {
                 return c * d[1];
             });
-            const outside = vUnit(vAdd(site.u[0], site.u[1], 1));
-            if (!outside) {
+            const into = vUnit(vAdd(site.u[0], site.u[1], 1)); // towards the open side of an inside corner
+            if (!into) {
                 return null;
             }
             const past = 2 * Math.max(d[0], d[1]);
             const head = site.open[0] ? past : 0;
             const tail = site.open[1] ? past : 0;
             const base = vAdd(site.start, site.e, -head);
-            const corners = [vAdd(base, a, 1), vAdd(base, b, 1), vAdd(base, outside, -0.5 * Math.min(d[0], d[1]))];
+            const back = (site.convex ? 0.5 : 0.1) * Math.min(d[0], d[1]);
+            const corners = [vAdd(base, a, 1), vAdd(base, b, 1), vAdd(base, into, -back)];
             const solid = wedgeSolid(oc, corners, site.e.map(function (c) {
                 return c * (site.length + head + tail);
             }));
-            const joined = tool ? boolean(oc, 'join', tool, solid) : solid;
-            if (tool) {
-                tool.delete();
-                solid.delete();
+            if (site.convex) {
+                cutTool = gather(oc, cutTool, solid);
+            } else {
+                fillTool = gather(oc, fillTool, solid);
             }
-            tool = joined;
-            if (!tool) {
+            if (!(site.convex ? cutTool : fillTool)) {
                 return null;
             }
-            // the bevel's plane, its normal pointing out of the material
+            nominal += 0.5 * d[0] * d[1] * Math.sin(site.between) * site.length;
+            // the bevel's plane, its normal pointing out of the material:
+            // towards the edge after a cut, away from it after a fill
             let normal = vUnit(vCross(vSub(b, a), site.e));
-            if (vDot(normal, outside) > 0) {
+            if (vDot(normal, into) * (site.convex ? 1 : -1) > 0) {
                 normal = normal.map(function (c) {
                     return -c;
                 });
             }
             bevels.push({ point: vAdd(site.start, a, 1), normal: normal });
         }
-        cut = boolean(oc, 'cut', body, tool);
-        if (!cut || isEmpty(oc, cut)) {
+        result = cutTool ? boolean(oc, 'cut', body, cutTool) : body;
+        if (result && fillTool) {
+            const filled = boolean(oc, 'join', result, fillTool);
+            if (result !== body) {
+                result.delete();
+            }
+            result = filled;
+        }
+        if (!result || result === body || isEmpty(oc, result)) {
+            if (result === body) {
+                result = null;
+            }
             return null;
         }
-        // The check: the material the builder takes off at 1 - h and 1 - 2h
-        // of the size, carried on to the full size (a chamfer takes off an
-        // amount that grows smoothly with its size: square, plus a cube
-        // part where bevels meet at a corner, so the error is tiny)
+        // The check: the volume the builder's chamfers change at 1 - h and
+        // 1 - 2h of the size, carried on to the full size. That change
+        // grows smoothly with the size (square, plus a cube part where
+        // bevels meet at a corner), so the error is tiny next to the wedges.
         const before = volume(oc, body);
-        const taken = [1 - CUT_CHECK_STEP, 1 - 2 * CUT_CHECK_STEP].map(function (scale) {
+        const change = [1 - WEDGE_CHECK_STEP, 1 - 2 * WEDGE_CHECK_STEP].map(function (scale) {
             const maker = build(scale);
             if (!maker) {
                 return null;
@@ -2880,18 +2919,18 @@ function cutChamfer(oc, body, edges, sizes, build) {
             const v = volume(oc, shape);
             shape.delete();
             maker.delete();
-            return before - v;
+            return v - before;
         });
-        if (taken[0] === null || taken[1] === null) {
+        if (change[0] === null || change[1] === null) {
             return null;
         }
-        const expected = 2 * taken[0] - taken[1];
-        const got = before - volume(oc, cut);
-        if (!(expected > 0) || !(Math.abs(got - expected) <= Math.max(expected * 1e-4, Math.abs(before) * 1e-9))) {
+        const expected = 2 * change[0] - change[1];
+        const got = volume(oc, result) - before;
+        if (!(Math.abs(got - expected) <= Math.max(nominal * 1e-4, Math.abs(before) * 1e-9))) {
             return null;
         }
-        const shape = cut;
-        cut = null;
+        const shape = result;
+        result = null;
         return {
             Shape: function () {
                 return shape;
@@ -2915,12 +2954,11 @@ function cutChamfer(oc, body, edges, sizes, build) {
         };
     } finally {
         free();
-        if (tool) {
-            tool.delete();
-        }
-        if (cut) {
-            cut.delete();
-        }
+        [cutTool, fillTool, result].forEach(function (shape) {
+            if (shape && shape !== body) {
+                shape.delete();
+            }
+        });
     }
 }
 

+ 52 - 0
src/web/3D Modeler/js/regionpick.js

@@ -0,0 +1,52 @@
+/*
+    3D Modeler - which sketch region a click means
+
+    While Extrude, Revolve, Sweep or Loft is open, the closed areas of every
+    sketch they may use are shaded in the model and drawn through it. Areas
+    of two sketches can lie over each other: the outline of a plate and a
+    sketch drawn on the plate's face, often on the very same plane. Taking the
+    nearest hit gave the big outline wherever it was in front (and, on one
+    plane, whichever rounding put first), so the area inside it could not be
+    picked. The smallest area under the pointer wins instead; a big area is
+    still had wherever nothing smaller covers it. Of areas the same size the
+    nearest wins.
+
+        trianglesArea(positions)   area of a triangle list (x, y, z each)
+        pickRegion(hits, areas)    hits: region indices nearest first (an
+                                   index may repeat); areas: per region.
+                                   Returns the index to use, or -1
+*/
+
+export function trianglesArea(positions) {
+    let area = 0;
+    for (let i = 0; i + 8 < positions.length; i += 9) {
+        const ux = positions[i + 3] - positions[i];
+        const uy = positions[i + 4] - positions[i + 1];
+        const uz = positions[i + 5] - positions[i + 2];
+        const vx = positions[i + 6] - positions[i];
+        const vy = positions[i + 7] - positions[i + 1];
+        const vz = positions[i + 8] - positions[i + 2];
+        area += Math.hypot(uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx) / 2;
+    }
+    return area;
+}
+
+// Areas within this fraction of each other count as the same size
+const SAME_SIZE = 1e-6;
+
+export function pickRegion(hits, areas) {
+    let best = -1;
+    let bestArea = Infinity;
+    hits.forEach(function (index) {
+        if (index < 0) {
+            return;
+        }
+        const area = areas[index];
+        const size = typeof area === 'number' && isFinite(area) ? area : Infinity;
+        if (best < 0 || size < bestArea * (1 - SAME_SIZE)) {
+            best = index;
+            bestArea = size;
+        }
+    });
+    return best;
+}

+ 67 - 2
src/web/3D Modeler/js/viewport.js

@@ -30,6 +30,8 @@ import { transformInfo } from './assembly/geometry.js';
 import { silhouetteSource, silhouetteSegments } from './silhouette.js';
 import { dragOffset, snapOffset } from './planedrag.js';
 import { faceView } from './faceview.js';
+import { pickRegion, trianglesArea } from './regionpick.js';
+import { featureEdgePoints } from './featuremark.js';
 
 const HOME_DIRECTION = new THREE.Vector3(1, -1, 1).normalize();
 const WORLD_UP = new THREE.Vector3(0, 0, 1);
@@ -588,6 +590,16 @@ export function createViewport(options) {
         selectededge: new LineMaterial({ color: SELECTED, linewidth: 3, depthWrite: false }),
         selectededgehidden: new LineMaterial({ color: SELECTED, linewidth: 2, depthTest: false, depthWrite: false, transparent: true, opacity: 0.35 })
     };
+    // What a feature made, while its row in the model browser is hovered
+    // (setFeatureMark): dotted light green, fainter behind the model
+    const FEATURE_MARK = 0x7ddc6f;
+    const featureMarkMaterials = {
+        front: new LineMaterial({ color: FEATURE_MARK, linewidth: 3, dashed: true, depthWrite: false }),
+        behind: new LineMaterial({ color: FEATURE_MARK, linewidth: 2, dashed: true, depthTest: false, depthWrite: false, transparent: true, opacity: 0.45 })
+    };
+    const featureMarkGroup = new THREE.Group();
+    scene.add(featureMarkGroup);
+    let featureMark = null;     // the id of the feature shown, or null
     let visualStyle = 'shaded-edges';
     let interactive = true; // false while the sketcher owns the pointer
     let pickFilter = null;  // { edges, faces, toggle } while a feature panel picks, else null
@@ -628,6 +640,43 @@ export function createViewport(options) {
             material.dashSize = 6 * w;
             material.gapSize = 4 * w;
         });
+        // short dashes: a dotted line
+        [featureMarkMaterials.front, featureMarkMaterials.behind].forEach(function (material) {
+            material.dashSize = 3 * w;
+            material.gapSize = 4 * w;
+        });
+    }
+
+    // Outline what feature `id` made: the edges of the faces it made, which
+    // keep its id in their names while later features trim them
+    // (kernel/naming.js: "<id>/start", "<id>/side:<curve>", "<id>/new").
+    // null takes it away. Drawn again when the bodies change (setBodies).
+    function setFeatureMark(id) {
+        featureMark = id || null;
+        disposeGroup(featureMarkGroup);
+        if (featureMark) {
+            bodies.forEach(function (body) {
+                if (body.off) {
+                    return;
+                }
+                const points = featureEdgePoints(body.data, featureMark);
+                if (!points.length) {
+                    return;
+                }
+                const geometry = new LineSegmentsGeometry();
+                geometry.setPositions(points);
+                [['behind', 8], ['front', 9]].forEach(function (layer) {
+                    const line = new LineSegments2(geometry, featureMarkMaterials[layer[0]]);
+                    line.computeLineDistances();
+                    line.renderOrder = layer[1];
+                    if (body.matrix) {
+                        new THREE.Matrix4().fromArray(body.matrix).decompose(line.position, line.quaternion, line.scale);
+                    }
+                    featureMarkGroup.add(line);
+                });
+            });
+        }
+        invalidate();
     }
 
     // Put a body's objects where its placement matrix says (assemblies)
@@ -914,6 +963,10 @@ export function createViewport(options) {
                 child.material.opacity = hiddenEdgeMaterial.opacity;
             }
         });
+        // new bodies, or one hidden or shown: the hovered feature's outline again
+        if (featureMark) {
+            setFeatureMark(featureMark);
+        }
     }
 
     /* ---------------- section view ---------------- */
@@ -1418,6 +1471,8 @@ export function createViewport(options) {
         ['hoveredge', 'hoveredgehidden', 'selectededge', 'selectededgehidden'].forEach(function (key) {
             overlayMaterials[key].resolution.set(w, h);
         });
+        featureMarkMaterials.front.resolution.set(w, h);
+        featureMarkMaterials.behind.resolution.set(w, h);
         Object.keys(axisMaterials).forEach(function (key) {
             axisMaterials[key].resolution.set(w, h);
         });
@@ -2029,6 +2084,7 @@ export function createViewport(options) {
         selectedHot: regionMaterial(HOVER, 0.68)
     };
     let regionItems = [];
+    let regionAreas = [];       // per region, its area (regionUnderPointer)
     let regionHandler = null;
     let hotRegion = -1;
 
@@ -2047,6 +2103,9 @@ export function createViewport(options) {
         regionItems = list || [];
         regionHandler = list ? handler : null;
         hotRegion = -1;
+        regionAreas = regionItems.map(function (item) {
+            return trianglesArea(item.positions);
+        });
         regionItems.forEach(function (item) {
             const geometry = new THREE.BufferGeometry();
             geometry.setAttribute('position', new THREE.BufferAttribute(item.positions, 3));
@@ -2460,10 +2519,14 @@ export function createViewport(options) {
         return best;
     }
 
+    // Areas of two sketches can lie over each other: the smallest one under
+    // the pointer wins, not the nearest (regionpick.js says why)
     function regionUnderPointer(event) {
         aim(event);
-        const hit = raycaster.intersectObjects(regionGroup.children, false)[0];
-        return hit ? regionGroup.children.indexOf(hit.object) : -1;
+        const hits = raycaster.intersectObjects(regionGroup.children, false);
+        return pickRegion(hits.map(function (hit) {
+            return regionGroup.children.indexOf(hit.object);
+        }), regionAreas);
     }
 
     const previewColors = { join: 0x4caf6d, new: 0x4caf6d, cut: 0xd64545, intersect: 0x3b78e0 };
@@ -3458,6 +3521,8 @@ export function createViewport(options) {
             }
         },
         coveredEdges: coveredEdges,
+        // Outline what a feature made (its id; null: none), dotted light green
+        setFeatureMark: setFeatureMark,
         setRegions: setRegions,
         setAxes: setAxes,
         setPreview: setPreview,

+ 61 - 3
src/web/3D Modeler/tests/chamfer-whole-face.test.mjs

@@ -1,8 +1,10 @@
 /*
     A chamfer exactly as wide as a face next to its edge takes that face away
-    (10 mm on the end of a 10 mm plate). OpenCascade's chamfer builder refuses
-    it while 9.99 builds, so the kernel cuts it as a wedge instead (cutChamfer
-    in kernel/occt.js). Run with: node tests/run.mjs chamfer-whole
+    (10 mm on the end of a 10 mm plate, or in the inside corner of a 10 mm
+    step, which fills the step up into a ramp). OpenCascade's chamfer builder
+    refuses it while 9.99 builds, so the kernel builds it as a wedge instead,
+    cut off at an outside corner and added in an inside one (wedgeChamfer in
+    kernel/occt.js). Run with: node tests/run.mjs chamfer-whole
 */
 import init from '../lib/occt/replicad_single.js';
 import { createRebuilder } from '../js/kernel/rebuild.js';
@@ -89,6 +91,62 @@ a(r.edges === 4 && r.status === 'ok', 'four chamfers of half the width build', r
 a(r.body && near(r.body.volume, 3000 - (500 - 100 * 5 / 3)), 'the column ends in a pyramid 5 tall', r.body && r.body.volume);
 a(r.body && r.body.faces.length === 9, 'four sides, bottom and four bevels', r.body && r.body.faces.length);
 
+/* ---- inside corners: the chamfer adds a wedge ---- */
+// An outline on the XZ plane extruded 20, as the reported part was drawn:
+// a sketch of a 10 x 10 square beside a 10 x 20 rectangle
+function outline(points, inside, extraLines) {
+    const g = points.map((p, i) => ({ id: 'p' + i, type: 'point', x: p[0], y: p[1] }));
+    points.forEach((p, i) => g.push({ id: 'l' + i, type: 'line', p1: 'p' + i, p2: 'p' + ((i + 1) % points.length) }));
+    (extraLines || []).forEach((l, i) => g.push({ id: 'x' + i, type: 'line', p1: l[0], p2: l[1] }));
+    return { features: [
+        { id: 's', type: 'sketch', name: 'S', plane: { ref: 'origin:xz' }, geometry: g, constraints: [] },
+        { id: 'e', type: 'extrude', name: 'E', sketch: 's', regions: inside, operation: 'join', extent: { type: 'distance', value: 20, direction: 'positive' } }
+    ] };
+}
+const line = e => e.curve && e.curve.type === 'line';
+// The report: both regions of the sketch (the line between them splits it)
+const step = outline([[-20, -20], [-10, -20], [0, -20], [0, 0], [-10, 0], [-10, -10], [-20, -10]], [[-15, -15], [-5, -10]], [['p1', 'p5']]);
+const corner = e => line(e) && near(e.mid[0], -10) && near(e.mid[2], -10);
+r = chamfered(step, corner, { distance: 9.99 });
+a(r.status === 'ok' && r.body.faces.length === r.before.faces.length + 1, '9.99 in the inside corner builds as before, with slivers of the step top and the wall', r.body && r.body.faces.length);
+r = chamfered(step, corner, { distance: 10 });
+a(r.edges === 1 && r.status === 'ok', 'a 10 chamfer in the inside corner of a 10 x 10 step builds', r.message);
+a(r.body && near(r.body.volume, r.before.volume + 0.5 * 10 * 10 * 20), 'it adds half of 10 x 10 x 20: the step becomes a ramp', r.body && [r.before.volume, r.body.volume]);
+a(r.body && r.body.faces.length === r.before.faces.length - 1, 'the step top and the wall both went into the one ramp face', r.body && [r.before.faces.length, r.body.faces.length]);
+['two', 'angle'].forEach(function (mode) {
+    r = chamfered(step, corner, { distance: 10, mode: mode, distance2: 10, angle: 45 });
+    a(r.status === 'ok' && near(r.body.volume, r.before.volume + 1000), mode === 'two' ? 'two distances 10 and 10 fill it the same' : 'distance 10 at 45 degrees fills it the same', r);
+});
+
+// A step 20 wide below a wall 10 tall: only the wall is used up. Sizes a
+// hair either side of the wall (as a solver may leave them) build cleanly.
+const wide = outline([[-30, -20], [0, -20], [0, 0], [-10, 0], [-10, -10], [-30, -10]], [[-5, -10]]);
+[10, 10.0000001, 9.9999999].forEach(function (d) {
+    r = chamfered(wide, corner, { distance: d });
+    a(r.status === 'ok' && near(r.body.volume, r.before.volume + 1000, 1e-3) && r.body.faces.length === r.before.faces.length, 'the wall becomes the bevel at ' + d + ', no sliver left', r.body && [r.status, r.message, r.body.volume, r.body.faces.length]);
+});
+r = chamfered(wide, corner, { distance: 12 });
+a(r.status !== 'ok' && near(r.body.volume, r.before.volume), 'a chamfer taller than the wall is still refused, the body untouched', r.status);
+
+// A U channel 10 wide: both inside bottom edges at 5 fill it to a V
+const channel = outline([[0, 0], [30, 0], [30, 20], [20, 20], [20, 10], [10, 10], [10, 20], [0, 20]], [[5, 5]]);
+r = chamfered(channel, e => line(e) && near(e.mid[2], 10) && (near(e.mid[0], 10) || near(e.mid[0], 20)), { distance: 5 });
+a(r.edges === 2 && r.status === 'ok' && near(r.body.volume, r.before.volume + 2 * 0.5 * 5 * 5 * 20), 'the channel bottom fills to a V', r);
+a(r.body && r.body.faces.length === r.before.faces.length + 1, 'the bottom went, two bevels came', r.body && [r.before.faces.length, r.body.faces.length]);
+
+// The preview of the reported step marks the ramp as the new face
+{
+    const rbStep = createRebuilder(oc);
+    const stepState = rbStep.shapesBefore(step, null);
+    const stepBody = rbStep.rebuild(step).bodies[0];
+    const stepReport = { fresh: [] };
+    const stepMade = kernel.chamfer(oc, stepState.bodies, { edges: stepBody.edges.filter(corner).map(ref), distance: 10 }, stepReport);
+    const stepFaces = kernel.describe(oc, stepMade[0]).faces;
+    const ramp = stepFaces.filter((f, i) => (stepReport.fresh[0] || [])[i]);
+    a(ramp.length === 1 && ramp[0].type === 'plane' && near(Math.abs(ramp[0].normal[0]), Math.SQRT1_2) && near(Math.abs(ramp[0].normal[2]), Math.SQRT1_2), 'the preview marks only the ramp as new', ramp.map(f => f.normal));
+    stepMade[0].delete();
+}
+
 // The live preview marks the bevel as the new face
 const rb = createRebuilder(oc);
 const state = rb.shapesBefore(plate, null);

+ 75 - 0
src/web/3D Modeler/tests/featuremark.test.mjs

@@ -0,0 +1,75 @@
+/*
+    Hovering a feature in the model browser outlines what it made in the
+    model (js/featuremark.js, drawn by viewport.js setFeatureMark): the
+    edges of the faces whose names say that feature made them.
+    Run with: node tests/run.mjs featuremark
+*/
+import init from '../lib/occt/replicad_single.js';
+import { createRebuilder } from '../js/kernel/rebuild.js';
+import { featureFaces, featureEdgePoints } from '../js/featuremark.js';
+
+const oc = await init();
+let failed = 0;
+const a = (c, m, x) => { if (!c) { failed++; console.log('FAIL', m, x === undefined ? '' : JSON.stringify(x)); } };
+const near = (x, y, t) => Math.abs(x - y) < (t || 1e-3);
+
+function rect(id, x0, y0, x1, y1, plane) {
+    const pts = [[x0, y0], [x1, y0], [x1, y1], [x0, y1]];
+    const g = [];
+    pts.forEach((p, i) => g.push({ id: id + 'p' + i, type: 'point', x: p[0], y: p[1] }));
+    pts.forEach((p, i) => g.push({ id: id + 'l' + i, type: 'line', p1: id + 'p' + i, p2: id + 'p' + ((i + 1) % 4) }));
+    return { id: id, type: 'sketch', name: id, plane: plane || { ref: 'origin:xy' }, geometry: g, constraints: [] };
+}
+function extrude(id, sketch, at, height) {
+    return { id: id, type: 'extrude', name: id, sketch: sketch, regions: [at], operation: 'join', extent: { type: 'distance', value: height, direction: 'positive' } };
+}
+
+// A 40 x 30 x 10 block ("e"), a 10 x 10 boss 5 tall on its top ("e2", an
+// id that starts with the block's), and a chamfer on a bottom edge ("c")
+const doc = { features: [
+    rect('s', 0, 0, 40, 30), extrude('e', 's', [20, 15], 10),
+    rect('s2', 15, 10, 25, 20, { ref: 'face', frame: { o: [0, 0, 10], x: [1, 0, 0], y: [0, 1, 0], n: [0, 0, 1] }, face: { normal: [0, 0, 1], point: [20, 15, 10] } }),
+    extrude('e2', 's2', [20, 15], 5)
+] };
+let body = createRebuilder(oc).rebuild(doc).bodies[0];
+const bottomFront = body.edges.find(e => near(e.mid[1], 0) && near(e.mid[2], 0) && near(e.length, 40));
+a(!!bottomFront, 'found the bottom front edge');
+doc.features.push({ id: 'c', type: 'chamfer', name: 'Chamfer1', edges: [{ body: 0, mid: bottomFront.mid, length: bottomFront.length }], distance: 2 });
+const result = createRebuilder(oc).rebuild(doc);
+a(result.features.c.status === 'ok', 'the chamfer builds', result.features.c);
+body = result.bodies[0];
+a(body.faces.every(f => typeof f.name === 'string'), 'every face has a name', body.faces.map(f => f.name));
+
+const block = featureFaces(body, 'e');
+const boss = featureFaces(body, 'e2');
+const bevel = featureFaces(body, 'c');
+a(block.length === 6, 'the block made six faces, still there though trimmed (top with a hole, front and bottom cut back)', block.map(i => body.faces[i].name));
+a(boss.length === 5, 'the boss made its four sides and its top', boss.map(i => body.faces[i].name));
+a(!boss.some(i => block.indexOf(i) >= 0), 'an id that starts with another id is not mixed up with it');
+a(bevel.length === 1 && body.faces[bevel[0]].type === 'plane' && near(body.faces[bevel[0]].normal[1], -Math.SQRT1_2) && near(body.faces[bevel[0]].normal[2], -Math.SQRT1_2), 'the chamfer made the bevel', bevel.map(i => body.faces[i]));
+a(featureFaces(body, 's').length === 0 && featureFaces(body, 'nothing').length === 0, 'a sketch or an unknown id made no face');
+a(block.length + boss.length + bevel.length === body.faces.length, 'every face belongs to one of the three features', body.faces.length);
+
+// The outline of the bevel: its four edges, each once, as point pairs
+const points = featureEdgePoints(body, 'c');
+a(points.length > 0 && points.length % 6 === 0, 'whole segments: two points of three numbers each', points.length);
+let length = 0;
+for (let i = 0; i < points.length; i += 6) {
+    length += Math.hypot(points[i + 3] - points[i], points[i + 4] - points[i + 1], points[i + 5] - points[i + 2]);
+}
+a(near(length, 2 * 40 + 2 * 2 * Math.SQRT2, 1e-2), 'the outline runs round the bevel: 40 + 40 + two short ends', length);
+const onBevel = points.every((v, i) => i % 3 !== 1 || v <= 2 + 1e-6);
+a(onBevel, 'and stays on the bevel (y within 2 of the front)');
+
+// The boss: its top and sides share edges; each is drawn once
+const bossPoints = featureEdgePoints(body, 'e2');
+let bossLength = 0;
+for (let i = 0; i < bossPoints.length; i += 6) {
+    bossLength += Math.hypot(bossPoints[i + 3] - bossPoints[i], bossPoints[i + 4] - bossPoints[i + 1], bossPoints[i + 5] - bossPoints[i + 2]);
+}
+a(near(bossLength, 4 * 10 + 4 * 10 + 4 * 5, 1e-2), 'the boss outline: top square, foot square and four upright edges, once each', bossLength);
+
+a(featureEdgePoints(body, null).length === 0 && featureEdgePoints(null, 'c').length === 0, 'no feature or no body: nothing to draw');
+
+console.log(failed ? failed + ' check(s) FAILED' : 'featuremark: all checks passed');
+process.exitCode = failed ? 1 : 0;

+ 34 - 0
src/web/3D Modeler/tests/regionpick.test.mjs

@@ -0,0 +1,34 @@
+/*
+    Picking a shaded sketch area while Extrude (Revolve, Sweep, Loft) is
+    open: where areas of two sketches lie over each other, the smallest one
+    under the pointer is picked, not the nearest (js/regionpick.js).
+    Run with: node tests/run.mjs regionpick
+*/
+import { pickRegion, trianglesArea } from '../js/regionpick.js';
+
+let failed = 0;
+const a = (c, m, x) => { if (!c) { failed++; console.log('FAIL', m, x === undefined ? '' : JSON.stringify(x)); } };
+const near = (x, y, t) => Math.abs(x - y) < (t || 1e-9);
+
+// A w x h rectangle at height z as two triangles
+const rect = (w, h, z) => new Float32Array([0, 0, z, w, 0, z, w, h, z, 0, 0, z, w, h, z, 0, h, z]);
+
+a(near(trianglesArea(rect(100, 40, 2)), 4000), 'a 100 x 40 rectangle has an area of 4000', trianglesArea(rect(100, 40, 2)));
+a(near(trianglesArea(new Float32Array([0, 0, 0, 3, 0, 0, 0, 0, 4])), 6), 'a 3-4-5 triangle standing up has an area of 6');
+a(trianglesArea(new Float32Array([])) === 0, 'no triangles: no area');
+
+// The plate's outline (region 0, 4000) and two halves of a window drawn on
+// it (regions 1 and 2, 400 each)
+const areas = [4000, 400, 400];
+a(pickRegion([0, 1], areas) === 1, 'the outline in front: the window half under the pointer is picked');
+a(pickRegion([1, 0], areas) === 1, 'the window half in front: still the window half');
+a(pickRegion([0, 0, 2], areas) === 2, 'a region hit twice counts once');
+a(pickRegion([0], areas) === 0, 'outside the window only the outline is under the pointer');
+a(pickRegion([], areas) === -1, 'nothing under the pointer: no pick');
+a(pickRegion([1, 2], areas) === 1, 'two areas the same size: the nearest');
+a(pickRegion([2, 1], [4000, 400, 400 * (1 + 1e-9)]) === 2, 'a rounding apart counts as the same size: the nearest');
+a(pickRegion([0, 1], [4000, undefined, 400]) === 0, 'an area of unknown size loses to one of known size');
+a(pickRegion([1], [4000, undefined]) === 1, 'and is still picked when it is the only one');
+
+console.log(failed ? failed + ' check(s) FAILED' : 'regionpick: all checks passed');
+process.exitCode = failed ? 1 : 0;