press_pull_rsolid: one signed distance pulls a planar face out (its prism joined) or presses it in (cut), recorded as its extrude and boolean steps; the editor's Press / pull on a picked flat face replaces Pull face / Push in on the selection bar: an arrow on the face along its normal drags the distance (0.5 mm snap, Shift free) while the panel types it, across zero; the face's frame comes from its triangles on screen, at once
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -442,6 +442,7 @@ This index includes generated docs for the public SimpleCAD API surface, includi
|
||||
- [placement_frame_mm](placement_frame_mm.md) *(from product/placement.py)* `submodule:product/placement`
|
||||
- [placement_from_canonical](placement_from_canonical.md) *(from product/placement.py)* `submodule:product/placement`
|
||||
- [placement_ticks](placement_ticks.md) *(from product/placement.py)* `submodule:product/placement`
|
||||
- [press_pull_rsolid](press_pull_rsolid.md) *(from operators/features.py)* `top-level`
|
||||
- [project_rsketch](project_rsketch.md) *(from operators/sketch.py)* `top-level`
|
||||
- [prop](prop.md) *(from ql.py)* `submodule:ql`
|
||||
- [ql.ref](ql.ref.md) *(from ql.py)* `submodule:ql`
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
# press_pull_rsolid
|
||||
|
||||
## API Definition
|
||||
|
||||
```python
|
||||
def press_pull_rsolid(solid, face, distance)
|
||||
```
|
||||
|
||||
*Source: operators/features.py*
|
||||
|
||||
## Import Surface
|
||||
|
||||
- top-level: `from simplecadapi import press_pull_rsolid`
|
||||
|
||||
## Description
|
||||
|
||||
Pull one planar face out along its normal, or press it in.
|
||||
|
||||
A positive ``distance`` pulls the face out: the prism of the face along its
|
||||
outward normal is joined to the solid (a boss, a step). A negative one presses
|
||||
it in: the prism into the solid is cut (a pocket, a recess; through the solid it
|
||||
cuts a hole). Zero leaves the solid as it is. One signed number covers both, so
|
||||
a parameter can be tuned across zero without changing the code.
|
||||
|
||||
Pair it with ``inset_face_rsolid``: inset a face, then press or pull its inner
|
||||
face, to build steps, bosses and walls without a sketch.
|
||||
|
||||
The operation is recorded as its steps: ``make_extrude_rsolid`` of the face,
|
||||
then ``make_union_rsolid`` (pull) or ``make_cut_rsolid`` (press), so the new
|
||||
faces carry the extrusion's roles (``extrusion.end`` is the moved face,
|
||||
``extrusion.side`` its walls) and element references follow them.
|
||||
|
||||
## Parameters
|
||||
|
||||
### solid
|
||||
|
||||
- **Description**: The body whose face is pressed or pulled.
|
||||
|
||||
### face
|
||||
|
||||
- **Description**: One planar face of ``solid``, or a QL selector that picks exactly one.
|
||||
|
||||
### distance
|
||||
|
||||
- **Description**: How far, in mm, along the face's outward normal: positive pulls, negative presses.
|
||||
|
||||
## Returns
|
||||
|
||||
The solid with the face pulled out or pressed in.
|
||||
|
||||
## Raises
|
||||
|
||||
- **TypeError**: ``solid`` is not a Solid.
|
||||
- **ValueError**: Not exactly one face, a face of another solid, a curved face, a non-finite distance, or a press that removes the whole solid.
|
||||
|
||||
## Examples
|
||||
|
||||
```python
|
||||
import simplecadapi as scad
|
||||
ql = scad.ql
|
||||
box = scad.make_box_rsolid(40, 30, 20)
|
||||
top = ql.faces().where(ql.prop("geom.center.z", ">=", 19.9)).exactly(1)
|
||||
stepped = scad.inset_face_rsolid(box, top, 3)
|
||||
inner = scad.ref.faces(scad.ref.face("", "make_inset_face_rsolid", role="inset.inner"))
|
||||
boss = scad.press_pull_rsolid(stepped, inner, 10)
|
||||
pocket = scad.press_pull_rsolid(stepped, inner, -4)
|
||||
```
|
||||
@@ -73,8 +73,9 @@ consult their own documentation before the first call.
|
||||
`loft_rsolid`, `loft_rshell`, `shell_rsolid`.
|
||||
- Detail: `fillet_rsolid`, `chamfer_rsolid`.
|
||||
- Face loops: `inset_face_rsolid(solid, face, distance)` imprints a planar face's loops moved inside it (the
|
||||
shape is unchanged; the face splits into roles `inset.inner` and `inset.ring`). Pull or push the inner face
|
||||
next (`extrude_rsolid(profile=inner, ...)` joined or cut) to build steps, bosses and walls without a sketch.
|
||||
shape is unchanged; the face splits into roles `inset.inner` and `inset.ring`).
|
||||
`press_pull_rsolid(solid, face, distance)` pulls a planar face out (positive) or presses it in (negative);
|
||||
inset then press/pull builds steps, bosses, pockets and walls without a sketch.
|
||||
|
||||
## Boolean discipline
|
||||
|
||||
|
||||
+23
-3
@@ -20,6 +20,7 @@ import { TagSplits, parseTagSplits, type TagSplit } from "@/components/TagSplits
|
||||
import { NewNotebookPrompt } from "@/components/NewNotebookPrompt";
|
||||
import { FloatingPanels } from "@/components/FloatingPanels";
|
||||
import { OperationPanel } from "@/components/OperationPanel";
|
||||
import { PressPullHandle } from "@/components/PressPullHandle";
|
||||
import { featureParams, quickStart } from "@/lib/operation-session";
|
||||
import { createSettler, SETTLE_MS } from "@/lib/settle";
|
||||
import { PartialNotice } from "@/components/PartialModel";
|
||||
@@ -625,7 +626,8 @@ export function App() {
|
||||
|
||||
// -- an operation in progress (lib/operation-session.ts): added at once, its numbers tuned live by the selection ----------
|
||||
|
||||
type OpSession = { slug: string; cell: string | null; title: string; specId: string; anchorMm: Vec3 | null; editing: boolean; busy: boolean; error: string | null };
|
||||
/** `handle`: a press / pull's arrow, on the picked face (mm, world) along its outward normal. */
|
||||
type OpSession = { slug: string; cell: string | null; title: string; specId: string; anchorMm: Vec3 | null; editing: boolean; busy: boolean; error: string | null; handle: { origin: Vec3; normal: Vec3 } | null };
|
||||
const [session, setSession] = useState<OpSession | null>(null);
|
||||
const sessionRef = useRef(session);
|
||||
sessionRef.current = session;
|
||||
@@ -633,6 +635,8 @@ export function App() {
|
||||
const paramsRef = useRef<ParamMeta[]>([]);
|
||||
const sessionSettler = useRef(createSettler<ParamValue>(SETTLE_MS, (values) => socketRef.current?.send({ type: "param.set", values })));
|
||||
const sessionParams = useMemo(() => (session ? featureParams(params, session.slug) : []), [params, session]);
|
||||
/** The distance a press / pull's arrow drags. */
|
||||
const sessionDistance = sessionParams.find((param) => param.id.endsWith("_DISTANCE"));
|
||||
/** The numbers changed in the session (the server's `modified` may not have come back yet when Enter is pressed). */
|
||||
const sessionTouched = useRef(new Set<string>());
|
||||
/** The numbers of the session the notebook source does not have yet. */
|
||||
@@ -673,7 +677,10 @@ export function App() {
|
||||
const start = quickStart(request.spec, gui.state, selectionRef.current, request.prefill);
|
||||
if (!start) return false;
|
||||
const title = t(plainLabel(request.spec.id, request.spec.label));
|
||||
setSession({ slug: start.name, cell: null, title, specId: request.spec.id, anchorMm: anchorRef.current, editing: false, busy: true, error: null });
|
||||
const picked = request.spec.id === "press_pull" ? selectionRef.current.find((item) => item.kind === "face") : undefined;
|
||||
const frame = picked?.entityId ? (viewRef.current?.faceFrameMm(picked.nodeId, picked.entityId) ?? null) : null;
|
||||
const handle = frame ? { origin: frame.centroid, normal: frame.normal } : null;
|
||||
setSession({ slug: start.name, cell: null, title, specId: request.spec.id, anchorMm: frame?.centroid ?? anchorRef.current, editing: false, busy: true, error: null, handle });
|
||||
setDialog(null);
|
||||
gui
|
||||
.run(start.command)
|
||||
@@ -694,7 +701,7 @@ export function App() {
|
||||
/** Tune the numbers of a feature of the tree in place (Esc gives them back). */
|
||||
const editInPlace = useCallback((feature: FeatureRow, spec: Spec): boolean => {
|
||||
if (!featureParams(paramsRef.current, feature.slug).length) return false;
|
||||
setSession({ slug: feature.slug, cell: feature.cell, title: t(plainLabel(spec.id, spec.label)), specId: spec.id, anchorMm: anchorRef.current, editing: true, busy: false, error: null });
|
||||
setSession({ slug: feature.slug, cell: feature.cell, title: t(plainLabel(spec.id, spec.label)), specId: spec.id, anchorMm: anchorRef.current, editing: true, busy: false, error: null, handle: null });
|
||||
return true;
|
||||
}, []);
|
||||
|
||||
@@ -1586,6 +1593,19 @@ export function App() {
|
||||
<CommandBar commands={commands} fit={fit} hint={hint} belowTop={floating && !taskOpen} />
|
||||
</div>
|
||||
)}
|
||||
{session?.handle && viewRef.current && sessionDistance && (
|
||||
<PressPullHandle
|
||||
view={viewRef.current}
|
||||
origin={session.handle.origin}
|
||||
normal={session.handle.normal}
|
||||
distance={Number(sessionDistance.value)}
|
||||
onChange={(distance, done) => {
|
||||
sessionTouched.current.add(sessionDistance.id);
|
||||
sessionSettler.current.push(sessionDistance.id, distance);
|
||||
if (done) sessionSettler.current.flush();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{session && viewRef.current && (
|
||||
<OperationPanel
|
||||
view={viewRef.current}
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
import * as THREE from "three";
|
||||
import { TransformControls } from "three/addons/controls/TransformControls.js";
|
||||
|
||||
import type { Vec3 } from "@/lib/sketch-plane";
|
||||
import { OVERLAY_LAYER } from "@/scene/renderer/brep-renderer";
|
||||
import type { SceneView } from "@/scene/scene-view";
|
||||
|
||||
/** Snap of a drag, mm (Shift drags freely). */
|
||||
const SNAP_MM = 0.5;
|
||||
|
||||
/** The arrow of a press / pull: it stands on the picked face, along its outward normal, at `distance` (mm) from it.
|
||||
* Dragging it out pulls the face, dragging it in presses it (the distance goes negative); typing the distance moves it.
|
||||
* The scene is the CAD frame in metres. */
|
||||
export function PressPullHandle({
|
||||
view,
|
||||
origin,
|
||||
normal,
|
||||
distance,
|
||||
onChange,
|
||||
}: {
|
||||
view: SceneView;
|
||||
/** A point of the face, mm (its centroid). */
|
||||
origin: Vec3;
|
||||
/** The face's outward unit normal. */
|
||||
normal: Vec3;
|
||||
distance: number;
|
||||
onChange: (distance: number, done: boolean) => void;
|
||||
}) {
|
||||
const targetRef = useRef<THREE.Group | null>(null);
|
||||
const dragging = useRef(false);
|
||||
const changeRef = useRef(onChange);
|
||||
changeRef.current = onChange;
|
||||
const at = useRef({ origin, normal });
|
||||
at.current = { origin, normal };
|
||||
|
||||
useEffect(() => {
|
||||
const { engine } = view;
|
||||
const axis = new THREE.Vector3(...normal).normalize();
|
||||
const base = new THREE.Vector3(...origin).multiplyScalar(0.001);
|
||||
const target = new THREE.Group();
|
||||
target.quaternion.setFromUnitVectors(new THREE.Vector3(0, 0, 1), axis);
|
||||
target.position.copy(base);
|
||||
engine.threeScene.add(target);
|
||||
const controls = new TransformControls(engine.camera, engine.domElement);
|
||||
controls.setMode("translate");
|
||||
controls.setSpace("local");
|
||||
controls.showX = false;
|
||||
controls.showY = false;
|
||||
controls.setTranslationSnap(SNAP_MM / 1000);
|
||||
controls.attach(target);
|
||||
const helper = controls.getHelper();
|
||||
helper.traverse((o) => o.layers.enable(OVERLAY_LAYER));
|
||||
engine.threeScene.add(helper);
|
||||
const measured = () => Math.round(target.position.clone().sub(base).dot(axis) * 1e6) / 1e3;
|
||||
const onRender = () => engine.invalidate();
|
||||
const onDrag = (event: { value: unknown }) => {
|
||||
dragging.current = Boolean(event.value);
|
||||
engine.controls.enabled = !dragging.current;
|
||||
if (!dragging.current) changeRef.current(measured(), true);
|
||||
};
|
||||
const onObject = () => changeRef.current(measured(), false);
|
||||
controls.addEventListener("change", onRender);
|
||||
controls.addEventListener("dragging-changed", onDrag);
|
||||
controls.addEventListener("objectChange", onObject);
|
||||
const onKey = (event: KeyboardEvent) => {
|
||||
if (event.key === "Shift") controls.setTranslationSnap(event.type === "keydown" ? null : SNAP_MM / 1000);
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
window.addEventListener("keyup", onKey);
|
||||
targetRef.current = target;
|
||||
engine.invalidate();
|
||||
return () => {
|
||||
window.removeEventListener("keydown", onKey);
|
||||
window.removeEventListener("keyup", onKey);
|
||||
controls.removeEventListener("change", onRender);
|
||||
controls.removeEventListener("dragging-changed", onDrag);
|
||||
controls.removeEventListener("objectChange", onObject);
|
||||
controls.detach();
|
||||
helper.removeFromParent();
|
||||
controls.dispose();
|
||||
target.removeFromParent();
|
||||
engine.controls.enabled = true;
|
||||
engine.invalidate();
|
||||
targetRef.current = null;
|
||||
};
|
||||
// the handle is made once per face: origin and normal do not change while it stands
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [view]);
|
||||
|
||||
// A typed distance moves the arrow; a drag in progress is the source of the distance, not its target.
|
||||
useEffect(() => {
|
||||
const target = targetRef.current;
|
||||
if (!target || dragging.current || !Number.isFinite(distance)) return;
|
||||
const { origin: o, normal: n } = at.current;
|
||||
target.position.set(...o).multiplyScalar(0.001).addScaledVector(new THREE.Vector3(...n).normalize(), distance / 1000);
|
||||
view.engine.invalidate();
|
||||
}, [distance, view]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ArrowDownToLine, ArrowUpFromLine, Blend, Box, CircleDot, Circle, Combine, Copy, Cylinder, FlipHorizontal2, Globe, Layers, Move3d, RotateCw, Scaling, Scissors, Shell, Spline, Square, Triangle, type LucideIcon } from "lucide-react";
|
||||
import { ArrowDownToLine, ArrowUpFromLine, MoveVertical, ScanBox, Blend, Box, CircleDot, Circle, Combine, Copy, Cylinder, FlipHorizontal2, Globe, Layers, Move3d, RotateCw, Scaling, Scissors, Shell, Spline, Square, Triangle, type LucideIcon } from "lucide-react";
|
||||
|
||||
/** The icon of each feature operation, by spec id (an operation without one shows none). */
|
||||
export const FEATURE_ICONS: Record<string, LucideIcon> = {
|
||||
@@ -15,6 +15,8 @@ export const FEATURE_ICONS: Record<string, LucideIcon> = {
|
||||
extrude_face: ArrowUpFromLine,
|
||||
extrude_face_join: ArrowUpFromLine,
|
||||
extrude_face_cut: ArrowDownToLine,
|
||||
press_pull: MoveVertical,
|
||||
inset_face: ScanBox,
|
||||
extrude_sketch_join: ArrowUpFromLine,
|
||||
extrude_sketch_cut: ArrowDownToLine,
|
||||
fillet: Blend,
|
||||
|
||||
@@ -454,6 +454,7 @@
|
||||
"Pole count": "控制点数",
|
||||
"Poles": "控制点",
|
||||
"Polyline": "多段线",
|
||||
"Press / pull": "推拉",
|
||||
"Pressure angle": "压力角",
|
||||
"Primitives": "基本体",
|
||||
"Prismatic constraint": "移动副约束",
|
||||
@@ -462,7 +463,9 @@
|
||||
"Profiles": "轮廓",
|
||||
"Project an Assembly into an explicit flattened Compound geometry value.": "把装配展平为一个显式的复合体几何。",
|
||||
"Public connector id": "公开连接器 id",
|
||||
"Pull a flat face out along its normal (a positive distance) or press it in (a negative one): its prism is joined or cut.": "沿法向把平面拉出(距离为正)或压入(距离为负):面的拉伸体与实体合并或从中切除。",
|
||||
"Pull face": "拉出面",
|
||||
"Pull one planar face out along its outward normal (positive distance) or press it in (negative).": "沿外法向把一个平面拉出(正距离)或压入(负距离)。",
|
||||
"Pulley radius a": "带轮半径 a",
|
||||
"Pulley radius b": "带轮半径 b",
|
||||
"Push a flat face of the body out (or into it) along its normal, without a sketch.": "不画草图,直接把实体的平面沿法向向外推出(或向内压入)。",
|
||||
|
||||
@@ -100,8 +100,7 @@ export function contextKind(context: SelectionContext): ContextKind | null {
|
||||
/** The contextual actions of each kind, in order: the command id and the short word shown on the button. */
|
||||
export const CONTEXT_ACTIONS: Record<ContextKind, { id: string; label: string }[]> = {
|
||||
face: [
|
||||
{ id: "extrude_face_join", label: "Pull face" },
|
||||
{ id: "extrude_face_cut", label: "Push in" },
|
||||
{ id: "press_pull", label: "Press / pull" },
|
||||
{ id: "inset_face", label: "Inset" },
|
||||
{ id: "sketch_on_face", label: "Sketch on this face" },
|
||||
{ id: "workplane_place", label: "Workplane" },
|
||||
@@ -148,6 +147,7 @@ const WHEN: Record<string, (context: SelectionContext) => boolean> = {
|
||||
extrude_face_join: (c) => c.faces === 1 && c.planarFaces === 1 && c.edges === 0 && c.sketches === 0,
|
||||
extrude_face_cut: (c) => c.faces === 1 && c.planarFaces === 1 && c.edges === 0 && c.sketches === 0,
|
||||
shell: (c) => c.faces >= 1 && c.edges === 0 && c.sketches === 0,
|
||||
press_pull: (c) => c.faces === 1 && c.planarFaces === 1 && c.edges === 0 && c.sketches === 0,
|
||||
inset_face: (c) => c.faces === 1 && c.planarFaces === 1 && c.edges === 0 && c.sketches === 0,
|
||||
fillet: (c) => c.edges >= 1 && c.sketches === 0,
|
||||
chamfer: (c) => c.edges >= 1 && c.sketches === 0,
|
||||
@@ -238,6 +238,7 @@ const SYNONYMS: Record<string, string[]> = {
|
||||
chamfer: ["bevel", "edge"],
|
||||
shell: ["hollow", "thin", "wall"],
|
||||
inset_face: ["offset", "outline", "loop", "imprint", "step", "boss", "inset"],
|
||||
press_pull: ["pull", "push", "press", "extrude", "pad", "pocket", "drag"],
|
||||
linear_pattern: ["array", "copies", "repeat", "row"],
|
||||
radial_pattern: ["array", "circular", "polar", "copies", "repeat"],
|
||||
mirror: ["flip", "symmetry", "reflect"],
|
||||
|
||||
@@ -267,6 +267,42 @@ export class SceneView {
|
||||
return out;
|
||||
}
|
||||
|
||||
/** A face of the model as the viewport draws it: its area-weighted centroid (mm, world) and outward normal, from its
|
||||
* triangles (null when the node or face is not on screen). Immediate: no kernel round trip. */
|
||||
faceFrameMm(nodeId: string, entityId: string): { centroid: [number, number, number]; normal: [number, number, number] } | null {
|
||||
const object = this.engine.nodeObject(nodeId);
|
||||
const node = this.engine.nodes.find((item) => item.node_id === nodeId);
|
||||
const group = this.engine.sidecarFor(node)?.face_groups.find((item: FaceGroup) => item.entity_id === entityId);
|
||||
let mesh: THREE.Mesh | null = null;
|
||||
object?.traverse((child) => {
|
||||
if (!mesh && child instanceof THREE.Mesh && child.name === 'cad-faces') mesh = child;
|
||||
});
|
||||
if (!group || !mesh) return null;
|
||||
const faces = mesh as THREE.Mesh;
|
||||
faces.updateWorldMatrix(true, false);
|
||||
const position = faces.geometry.getAttribute('position');
|
||||
const index = faces.geometry.index;
|
||||
const a = new THREE.Vector3(), b = new THREE.Vector3(), c = new THREE.Vector3();
|
||||
const centroid = new THREE.Vector3(), normal = new THREE.Vector3(), cross = new THREE.Vector3();
|
||||
let area = 0;
|
||||
for (let i = group.first_index; i + 2 < group.first_index + group.index_count; i += 3) {
|
||||
const at = (k: number) => (index ? index.getX(k) : k);
|
||||
a.fromBufferAttribute(position, at(i)).applyMatrix4(faces.matrixWorld);
|
||||
b.fromBufferAttribute(position, at(i + 1)).applyMatrix4(faces.matrixWorld);
|
||||
c.fromBufferAttribute(position, at(i + 2)).applyMatrix4(faces.matrixWorld);
|
||||
cross.subVectors(b, a).cross(c.clone().sub(a));
|
||||
const twice = cross.length();
|
||||
if (twice === 0) continue;
|
||||
area += twice;
|
||||
normal.add(cross);
|
||||
centroid.addScaledVector(a.clone().add(b).add(c), twice / 3);
|
||||
}
|
||||
if (area === 0) return null;
|
||||
centroid.divideScalar(area).multiplyScalar(1000);
|
||||
normal.normalize();
|
||||
return { centroid: [centroid.x, centroid.y, centroid.z], normal: [normal.x, normal.y, normal.z] };
|
||||
}
|
||||
|
||||
/** The model's bounding box in the world frame, mm ([min, max]), or null for an empty scene. */
|
||||
modelBoundsMm(): { min: [number, number, number]; max: [number, number, number] } | null {
|
||||
this.engine.modelRoot.updateMatrixWorld(true);
|
||||
|
||||
@@ -446,6 +446,15 @@ void bind_derived(py::module_& m) {
|
||||
py::arg("plane_normal") = unit_z(),
|
||||
"Draft planar, cylindrical or conical faces by a signed angle in degrees about a neutral plane.");
|
||||
|
||||
m.def(
|
||||
"press_pull_rsolid",
|
||||
[](const Solid& solid, const FacesOrQuery& face, const Length& distance) {
|
||||
const FaceSelection selection = selection_from<Face>(face);
|
||||
return unlocked(selection.is_selector(), [&] { return press_pull_rsolid(solid, selection, distance); });
|
||||
},
|
||||
py::arg("solid"), py::arg("face"), py::arg("distance"),
|
||||
"Pull one planar face out along its outward normal (positive distance) or press it in (negative).");
|
||||
|
||||
m.def(
|
||||
"inset_face_rsolid",
|
||||
[](const Solid& solid, const FacesOrQuery& face, const Length& distance) {
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
#include "scad/ops/features/support.hpp"
|
||||
#include "scad/ops/features/tags.hpp"
|
||||
#include "scad/ops/geometry/types.hpp"
|
||||
#include "scad/topo/shape.hpp"
|
||||
@@ -17,6 +18,11 @@ namespace scad {
|
||||
Solid extrude_rsolid(const Shape& profile, const Scalar3& direction, const Scalar& distance,
|
||||
const SweepTags& tags = {});
|
||||
|
||||
// Press or pull one planar face of `solid` along its outward normal by a signed `distance`: positive pulls it out
|
||||
// (the prism of the face joined), negative presses it in (the prism cut), zero leaves the solid. Recorded as its
|
||||
// steps (make_extrude_rsolid, then make_union_rsolid or make_cut_rsolid).
|
||||
Solid press_pull_rsolid(const Solid& solid, const FaceSelection& face, const Scalar& distance);
|
||||
|
||||
// A planar face extruded by `vector` with `taper` degrees of draft (positive shrinks the outer
|
||||
// loop; inner loops go the other way when `flip_inner`). Recorded as make_extrude_taper_rsolid.
|
||||
Solid extrude_taper_rsolid(const Face& profile, const Scalar3& vector, const Scalar& taper, bool flip_inner = true);
|
||||
|
||||
@@ -1,6 +1,15 @@
|
||||
// extrude_rsolid (operators/features.py).
|
||||
// extrude_rsolid, press_pull_rsolid (operators/features.py).
|
||||
#include <BRepAdaptor_Surface.hxx>
|
||||
#include <GeomAbs_SurfaceType.hxx>
|
||||
#include <TopoDS.hxx>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
#include "scad/core/tolerance.hpp"
|
||||
#include "scad/ops/features/extrusion.hpp"
|
||||
#include "scad/ops/features/booleans.hpp"
|
||||
#include "scad/core/coordinate_system.hpp"
|
||||
|
||||
#include "internal.hpp"
|
||||
#include "scad/ops/geometry/diagnostics.hpp"
|
||||
@@ -70,4 +79,29 @@ Solid extrude_rsolid(const Shape& profile, const Scalar3& direction, const Scala
|
||||
});
|
||||
}
|
||||
|
||||
Solid press_pull_rsolid(const Solid& solid, const FaceSelection& face, const Scalar& distance) {
|
||||
const double amount = evaluate_finite(distance);
|
||||
if (!std::isfinite(amount))
|
||||
throw ValueError("distance must be finite");
|
||||
const std::vector<Face> resolved = face.resolve(solid);
|
||||
if (resolved.size() != 1)
|
||||
throw ValueError("press_pull takes exactly one face, got " + std::to_string(resolved.size()));
|
||||
const Face target = resolved.front();
|
||||
const std::vector<Face> own_faces = solid.faces();
|
||||
if (std::none_of(own_faces.begin(), own_faces.end(), [&](const Face& f) { return f.wrapped().IsSame(target.wrapped()); }))
|
||||
throw ValueError("the face must belong to the input solid");
|
||||
if (occt_guard([&] { return BRepAdaptor_Surface(TopoDS::Face(target.wrapped())).GetType(); }) != GeomAbs_Plane)
|
||||
throw ValueError("press_pull needs a planar face");
|
||||
if (amount == 0)
|
||||
return solid; // nothing pressed or pulled
|
||||
// the face's outward normal is a world direction: the prism is built in the world frame
|
||||
const Vec3 outward = target.normal_at();
|
||||
const Vec3 along = amount > 0 ? outward : outward * -1.0;
|
||||
Solid tool = [&] {
|
||||
CoordinateSystemScope world(world_cs());
|
||||
return extrude_rsolid(target, scalar3(along.x, along.y, along.z), Scalar(std::abs(amount)));
|
||||
}();
|
||||
return amount > 0 ? union_rsolid({solid, tool}) : cut_rsolid({solid, tool});
|
||||
}
|
||||
|
||||
} // namespace scad
|
||||
|
||||
@@ -185,6 +185,7 @@ from simplecadapi._cpp import (
|
||||
cut_rsolid_list,
|
||||
draft_rsolid,
|
||||
inset_face_rsolid,
|
||||
press_pull_rsolid,
|
||||
extrude_rsolid,
|
||||
extrude_taper_rsolid,
|
||||
extrude_until_rsolid,
|
||||
@@ -729,6 +730,7 @@ __all__ = [
|
||||
# 3D operations
|
||||
"draft_rsolid",
|
||||
"inset_face_rsolid",
|
||||
"press_pull_rsolid",
|
||||
"extrude_rsolid",
|
||||
"extrude_taper_rsolid",
|
||||
"extrude_until_rsolid",
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -378,5 +378,6 @@
|
||||
"make_workplane_normal_to_curve_rworkplane": "Create a workplane normal to a curve: the plane of a sweep profile.\n\norigin = the point at ``at`` (a fraction of the curve's length: 0 = start, 1 = end); normal = the direction of\ntravel there; x = ``x_dir`` projected onto the plane, or global Z made square to the normal (global X when the\ntangent is near Z).\n\nRecorded: the node takes the inputs as ordered references, so a model-JSON replay builds the frame again from the\ngeometry as it is then, and a sketch on the workplane (``plane=wp``) or an operation inside ``with wp:`` follows it.\n\nArgs:\n curve: An Edge or a Wire (the sweep path).\n at: The fraction of the length, in [0, 1].\n x_dir: The direction of x, projected onto the plane.\n\nReturns:\n SimpleWorkplane: a frame in world coordinates (``origin``, ``normal``, ``x_dir``, ``y_dir``, ``plane``) that is\n also a context manager: ``with wp:`` makes it the current coordinate system, ``make_sketch_rsketch(plane=wp)``\n draws on it. It is a value: enter it again in later code, pickle it (the notebook cell cache does).\n\nRaises:\n SimpleCADError: ``at`` is outside [0, 1], the curve has no length, or ``x_dir`` is along the tangent.\n\nUsage:\n ``start = scad.make_workplane_normal_to_curve_rworkplane(path, 0)``;\n ``profile = ... make_sketch_rsketch(\"profile\", plane=start) ...``; ``sweep_rsolid(profile, path)``.\n",
|
||||
"list_tag_splits": "The tagged entities that the operations behind a shape split into pieces.\n\nA tag follows its entity the way a reference does: while the entity stays one entity it keeps the tag; when an\noperation splits it (a slot cut across a tagged face, a cut through a tagged body), the tag does not go to every\npiece. Each piece carries ``<tag>.split1`` .. ``<tag>.split<n>`` instead, numbered as the operation recorded them (by\ncentre, then size), and ``ql.tag(\"<tag>\")`` finds none of them. Name the pieces you mean with tags of your own after the\nsplit, or select them with ``ql.tag(\"<tag>.split1\")`` / ``ql.tag(\"<tag>.*\")``.\n\nArgs:\n shape: A shape made in a recording session (its history is read).\n\nReturns:\n list[dict]: One row per split, upstream first: ``tag`` (the tag the entity had), ``into`` (the tags of the pieces,\n in piece order), ``node_id`` and ``op`` (the operation that split it), ``source_topo_id`` and ``pieces``\n (``output_slot``, ``kind``, ``topo_id`` of each piece in that operation's output). Empty for a shape without\n recorded history.\n\nExamples:\n >>> top = scad.apply_tag_rselection(box, scad.ql.faces().where(scad.ql.prop(\"geom.center.z\", \">=\", 9.9)), \"mount.top\")\n >>> halves = scad.cut_rsolid(top, slot) # the slot splits the top face (and the body)\n >>> [row[\"into\"] for row in scad.list_tag_splits(halves[0])]\n [['mount.top.split1', 'mount.top.split2']]",
|
||||
"make_workplane_offset_rworkplane": "Create a workplane moved and turned relative to a workplane or a named plane.\n\nThe editor's move and turn handles write this operation: a plane placed by hand on a base, without any model geometry.\n\nArgs:\n base: The plane it is placed on: a workplane value (made by a ``make_workplane_*_rworkplane`` operation, recorded\n as this node's input so the new plane follows it when it moves) or a named plane ``\"XY\"`` / ``\"XZ\"`` / ``\"YZ\"``\n (axes as sketches read them).\n offset: How far the origin moves, ``(dx, dy, dz)`` along the base's own x, y and normal.\n rx, ry, rz: Turns in degrees about the base's own axes, applied in that order, each about the axis as the previous\n turn left it (R = Rx(rx) Ry(ry) Rz(rz) in the base's frame).\n\nReturns:\n SimpleWorkplane: The new frame. Use it as a sketch plane (``plane=wp``) or as a context (``with wp:``).\n\nExamples:\n >>> wp = scad.make_workplane_offset_rworkplane(\"XY\", offset=(0, 0, 20), rx=30)\n >>> lid = scad.make_workplane_offset_rworkplane(wp, offset=(0, 0, 5)) # follows wp",
|
||||
"inset_face_rsolid": "Imprint the loops of one planar face moved a distance inside it.\n\nThe outline of the face (and the outline of each of its holes) is offset in\nthe face's plane by ``distance`` towards the inside, and the offset loops are\nimprinted on the solid: the face becomes an inner face and the ring around it\n(a ring around each hole too). The solid keeps its shape and volume; it only\nhas one face more, which the next operation can pull out, push in or open, so\nsteps, bosses and walls are built by insetting and pulling again.\n\nThe operation is recorded as ``make_inset_face_rsolid``; the body and the face\nare ordered inputs and the distance is a parameter, so model JSON replay is\nstrict. The split pieces are fragments of the face (element references and\ntags follow them as a split) and carry the kernel roles ``inset.inner`` and\n``inset.ring``, so ``scad.ref.face(..., role=\"inset.inner\")`` names the inner\nface whatever the face was.\n\nArgs:\n solid: The body whose face is inset.\n face: One planar face of ``solid``, or a QL selector that picks exactly one.\n distance: How far inside the face the loops run, in mm; positive.\n\nReturns:\n The same solid with the face split in its inner face and ring.\n\nRaises:\n TypeError: ``solid`` is not a Solid.\n ValueError: Not exactly one face, a face of another solid, a curved\n face, a non-positive distance, or a distance at which nothing of the\n face is left inside the loops.\n\nExamples:\n import simplecadapi as scad\n ql = scad.ql\n box = scad.make_box_rsolid(40, 30, 20)\n top = ql.faces().where(ql.prop(\"geom.center.z\", \">=\", 19.9)).exactly(1)\n inset = scad.inset_face_rsolid(box, top, 3)\n inner = scad.ref.face(\"\", \"make_inset_face_rsolid\", role=\"inset.inner\").one(inset)\n"
|
||||
"inset_face_rsolid": "Imprint the loops of one planar face moved a distance inside it.\n\nThe outline of the face (and the outline of each of its holes) is offset in\nthe face's plane by ``distance`` towards the inside, and the offset loops are\nimprinted on the solid: the face becomes an inner face and the ring around it\n(a ring around each hole too). The solid keeps its shape and volume; it only\nhas one face more, which the next operation can pull out, push in or open, so\nsteps, bosses and walls are built by insetting and pulling again.\n\nThe operation is recorded as ``make_inset_face_rsolid``; the body and the face\nare ordered inputs and the distance is a parameter, so model JSON replay is\nstrict. The split pieces are fragments of the face (element references and\ntags follow them as a split) and carry the kernel roles ``inset.inner`` and\n``inset.ring``, so ``scad.ref.face(..., role=\"inset.inner\")`` names the inner\nface whatever the face was.\n\nArgs:\n solid: The body whose face is inset.\n face: One planar face of ``solid``, or a QL selector that picks exactly one.\n distance: How far inside the face the loops run, in mm; positive.\n\nReturns:\n The same solid with the face split in its inner face and ring.\n\nRaises:\n TypeError: ``solid`` is not a Solid.\n ValueError: Not exactly one face, a face of another solid, a curved\n face, a non-positive distance, or a distance at which nothing of the\n face is left inside the loops.\n\nExamples:\n import simplecadapi as scad\n ql = scad.ql\n box = scad.make_box_rsolid(40, 30, 20)\n top = ql.faces().where(ql.prop(\"geom.center.z\", \">=\", 19.9)).exactly(1)\n inset = scad.inset_face_rsolid(box, top, 3)\n inner = scad.ref.face(\"\", \"make_inset_face_rsolid\", role=\"inset.inner\").one(inset)\n",
|
||||
"press_pull_rsolid": "Pull one planar face out along its normal, or press it in.\n\nA positive ``distance`` pulls the face out: the prism of the face along its\noutward normal is joined to the solid (a boss, a step). A negative one presses\nit in: the prism into the solid is cut (a pocket, a recess; through the solid it\ncuts a hole). Zero leaves the solid as it is. One signed number covers both, so\na parameter can be tuned across zero without changing the code.\n\nPair it with ``inset_face_rsolid``: inset a face, then press or pull its inner\nface, to build steps, bosses and walls without a sketch.\n\nThe operation is recorded as its steps: ``make_extrude_rsolid`` of the face,\nthen ``make_union_rsolid`` (pull) or ``make_cut_rsolid`` (press), so the new\nfaces carry the extrusion's roles (``extrusion.end`` is the moved face,\n``extrusion.side`` its walls) and element references follow them.\n\nArgs:\n solid: The body whose face is pressed or pulled.\n face: One planar face of ``solid``, or a QL selector that picks exactly one.\n distance: How far, in mm, along the face's outward normal: positive pulls,\n negative presses.\n\nReturns:\n The solid with the face pulled out or pressed in.\n\nRaises:\n TypeError: ``solid`` is not a Solid.\n ValueError: Not exactly one face, a face of another solid, a curved face,\n a non-finite distance, or a press that removes the whole solid.\n\nExamples:\n import simplecadapi as scad\n ql = scad.ql\n box = scad.make_box_rsolid(40, 30, 20)\n top = ql.faces().where(ql.prop(\"geom.center.z\", \">=\", 19.9)).exactly(1)\n stepped = scad.inset_face_rsolid(box, top, 3)\n inner = scad.ref.faces(scad.ref.face(\"\", \"make_inset_face_rsolid\", role=\"inset.inner\"))\n boss = scad.press_pull_rsolid(stepped, inner, 10)\n pocket = scad.press_pull_rsolid(stepped, inner, -4)\n"
|
||||
}
|
||||
@@ -197,6 +197,7 @@
|
||||
"distance": "simplecadapi.kernel.ocp_properties",
|
||||
"draft_rsolid": "simplecadapi.operators.features",
|
||||
"inset_face_rsolid": "simplecadapi.operators.features",
|
||||
"press_pull_rsolid": "simplecadapi.operators.features",
|
||||
"edges": "simplecadapi.ql",
|
||||
"edges_of": "simplecadapi.kernel.ocp_topology",
|
||||
"evaluate_scalar": "simplecadapi.params.expr",
|
||||
|
||||
@@ -536,6 +536,10 @@ def _chamfer(c: Context) -> list[str]:
|
||||
return [*c.recipe("edges", "tip"), f"{c.slug} = scad.chamfer_rsolid(solid={c.body('body')}, edges={c.selection('edges')}, distance={c.var('distance')})"]
|
||||
|
||||
|
||||
def _press_pull(c: Context) -> list[str]:
|
||||
return [*c.recipe("face", "tip"), f"{c.slug} = scad.press_pull_rsolid(solid={c.body('body')}, face={c.selection('face')}, distance={c.var('distance')})"]
|
||||
|
||||
|
||||
def _inset_face(c: Context) -> list[str]:
|
||||
return [*c.recipe("face", "tip"), f"{c.slug} = scad.inset_face_rsolid(solid={c.body('body')}, face={c.selection('face')}, distance={c.var('distance')})"]
|
||||
|
||||
@@ -683,6 +687,10 @@ SPECS: tuple[Spec, ...] = (
|
||||
Spec("extrude_face", "Extrude face", "Features", "build", "solid", "Push a flat face of the body out (or into it) along its normal, without a sketch.",
|
||||
(_BODY(), Slot("face", "Face", "select", entity="face", single=True, help="Pick one flat face of the body."),
|
||||
_enum("direction", "Direction", _FACE_DIRECTIONS, "normal"), _signed("distance", "Distance", 10.0, min=0.001)), _extrude_face),
|
||||
Spec("press_pull", "Press / pull", "Features", "modifier", "solid",
|
||||
"Pull a flat face out along its normal (a positive distance) or press it in (a negative one): its prism is joined or cut.",
|
||||
(_BODY(), Slot("face", "Face", "select", entity="face", single=True, help="Pick one flat face of the body."),
|
||||
_signed("distance", "Distance", 5.0)), _press_pull),
|
||||
Spec("inset_face", "Inset face", "Features", "modifier", "solid",
|
||||
"Imprint the outline of a flat face moved inside it: the face splits into an inner face (pull it out or push it in next) and the ring around it.",
|
||||
(_BODY(), Slot("face", "Face", "select", entity="face", single=True, help="Pick one flat face of the body."),
|
||||
|
||||
@@ -29,6 +29,7 @@ from simplecadapi._cpp import (
|
||||
diagnose_boolean_failure,
|
||||
draft_rsolid,
|
||||
inset_face_rsolid,
|
||||
press_pull_rsolid,
|
||||
extrude_rsolid,
|
||||
extrude_taper_rsolid,
|
||||
extrude_until_rsolid,
|
||||
@@ -320,6 +321,7 @@ __all__ = [
|
||||
"diff_sketch_rsketchdiff",
|
||||
"draft_rsolid",
|
||||
"inset_face_rsolid",
|
||||
"press_pull_rsolid",
|
||||
"elevate_curve_degree_redge",
|
||||
"elevate_surface_degree_rface",
|
||||
"explain_tag",
|
||||
|
||||
@@ -21,6 +21,7 @@ from simplecadapi._cpp import (
|
||||
diagnose_blend_failure,
|
||||
draft_rsolid,
|
||||
inset_face_rsolid,
|
||||
press_pull_rsolid,
|
||||
extrude_rsolid,
|
||||
extrude_taper_rsolid,
|
||||
extrude_until_rsolid,
|
||||
@@ -58,6 +59,7 @@ __all__ = [
|
||||
"diagnose_blend_failure",
|
||||
"draft_rsolid",
|
||||
"inset_face_rsolid",
|
||||
"press_pull_rsolid",
|
||||
"extrude_rsolid",
|
||||
"extrude_taper_rsolid",
|
||||
"extrude_until_rsolid",
|
||||
|
||||
@@ -472,6 +472,11 @@ PUBLIC_API_COVERAGE: Dict[str, Dict[str, str]] = {
|
||||
"extrude_until_rsolid": {"status": "replayable", "op": "make_extrude_until_rsolid"},
|
||||
"draft_rsolid": {"status": "replayable", "op": "make_draft_rsolid"},
|
||||
"inset_face_rsolid": {"status": "replayable", "op": "make_inset_face_rsolid"},
|
||||
"press_pull_rsolid": {
|
||||
"status": "expanded_macro",
|
||||
"op": "make_extrude_rsolid",
|
||||
"reason": "Recorded as make_extrude_rsolid of the face, then make_union_rsolid (pull) or make_cut_rsolid (press).",
|
||||
},
|
||||
"mirror_shape": {"status": "replayable", "op": "make_mirror_rshape"},
|
||||
"extrude_rsolid": {"status": "replayable", "op": "make_extrude_rsolid"},
|
||||
"revolve_rsolid": {"status": "replayable", "op": "make_revolve_rsolid"},
|
||||
|
||||
@@ -66,3 +66,28 @@ def test_what_it_refuses():
|
||||
s.inset_face_rsolid(box, ql.faces(), 1)
|
||||
with pytest.raises(ValueError, match="planar"):
|
||||
s.inset_face_rsolid(s.make_cylinder_rsolid(5, 10), ql.faces().where(ql.prop("geom.type", "==", "CYLINDER")).exactly(1), 1)
|
||||
|
||||
|
||||
def test_press_pull_pulls_out_presses_in_and_leaves_zero_alone():
|
||||
box = s.make_box_rsolid(40, 30, 20)
|
||||
assert s.press_pull_rsolid(box, TOP, 5).get_volume() == pytest.approx(24000 + 1200 * 5)
|
||||
assert s.press_pull_rsolid(box, TOP, -5).get_volume() == pytest.approx(24000 - 1200 * 5)
|
||||
assert s.press_pull_rsolid(box, TOP, 0).get_volume() == pytest.approx(24000)
|
||||
with pytest.raises(ValueError, match="exactly one"):
|
||||
s.press_pull_rsolid(box, ql.faces(), 5)
|
||||
|
||||
|
||||
def test_inset_then_press_pull_makes_a_boss_or_a_pocket_named_by_the_extrusion():
|
||||
with GraphSession() as session:
|
||||
stepped = s.inset_face_rsolid(s.make_box_rsolid(40, 30, 20), TOP, 3)
|
||||
inner = s.ref.faces(s.ref.face("", "make_inset_face_rsolid", role="inset.inner"))
|
||||
boss = s.press_pull_rsolid(stepped, inner, 10)
|
||||
pocket = s.press_pull_rsolid(stepped, inner, -4)
|
||||
assert boss.get_volume() == pytest.approx(24000 + 816 * 10)
|
||||
assert pocket.get_volume() == pytest.approx(24000 - 816 * 4)
|
||||
cap = max(boss._iter_faces(), key=lambda face: face.get_center().z)
|
||||
assert s.ref.of(cap, boss).role == "extrusion.end"
|
||||
session.capture_result(value=boss)
|
||||
assert [node.op for node in session.graph.nodes][-2:] == ["make_extrude_rsolid", "make_cut_rsolid"]
|
||||
replayed = s.replay_model_json(s.export_model_json(session))[0]
|
||||
assert replayed.get_volume() == pytest.approx(24000 + 816 * 10)
|
||||
|
||||
Reference in New Issue
Block a user