工厂原仅接收 height 且把 radius 硬绑等于 height。改为 hex_prism(radius,height,sides=6),SdfParams 增 sides;新增通用 regular_polygon_prism 精确 SDF(扇区折叠,sides=6 与旧 hex_prism 几何一致),evaluate 经其求值;bounds 半径随 radius/height 计算。python 绑定同步。 判别性测试 +7:test_sdf_tree 半径/高度独立、边数控截面、非法边数夹取;test_sdf_primitives 顶点共享、面法向精确距离。sdf 6 套全绿(tree 34、primitives 69、to_mesh 6、optimize 21、operations 33、gradient 51)。
594 lines
24 KiB
C++
594 lines
24 KiB
C++
#include <pybind11/pybind11.h>
|
||
#include <pybind11/eigen.h>
|
||
#include <pybind11/stl.h>
|
||
#include <pybind11/functional.h>
|
||
|
||
#include "vde/sdf/sdf_tree.h"
|
||
#include "vde/sdf/sdf_primitives.h"
|
||
#include "vde/sdf/sdf_operations.h"
|
||
#include "vde/sdf/sdf_to_mesh.h"
|
||
#include "vde/sdf/sdf_optimize.h"
|
||
#include "vde/sdf/sdf_gradient.h"
|
||
|
||
namespace py = pybind11;
|
||
using namespace vde::sdf;
|
||
|
||
void bind_sdf(py::module& m) {
|
||
auto sdf_m = m.def_submodule("sdf",
|
||
R"pbdoc(
|
||
Signed Distance Field (SDF) implicit modeling and optimization.
|
||
|
||
SDF is a volumetric representation where f(p) < 0 means inside,
|
||
f(p) = 0 means on surface, f(p) > 0 means outside.
|
||
|
||
Submodules / classes:
|
||
SdfNode: expression tree node for building SDF CSG trees
|
||
sdf_to_mesh(): marching cubes mesh conversion
|
||
fit_to_point_cloud(): gradient descent shape optimization
|
||
)pbdoc");
|
||
|
||
// ── SdfNode ────────────────────────────────────────
|
||
py::class_<SdfNode, std::shared_ptr<SdfNode>>(sdf_m, "SdfNode",
|
||
R"pbdoc(
|
||
A node in a signed-distance-field CSG expression tree.
|
||
|
||
SdfNode represents either a primitive shape, a boolean CSG operation,
|
||
a distance modifier, or a domain transform. Build trees by combining
|
||
nodes with the static factory methods.
|
||
|
||
Primitive factories:
|
||
sphere(radius) — sphere centered at origin
|
||
box(half_extents) — axis-aligned box
|
||
cylinder(radius, height) — cylinder along Y axis
|
||
torus(major_r, minor_r) — torus in XZ plane
|
||
|
||
Boolean operations (two children):
|
||
union(a, b) — CSG union: min
|
||
intersection(a, b) — CSG intersection: max
|
||
difference(a, b) — CSG difference: max(a, -b)
|
||
smooth_union(a, b, k) — smooth blend union
|
||
|
||
Example:
|
||
>>> root = brep.SdfNode.union(
|
||
... brep.SdfNode.sphere(1.0),
|
||
... brep.SdfNode.box(Point3D(0.5, 0.5, 0.5))
|
||
... )
|
||
>>> d = sdf.evaluate(root, Point3D(0, 0, 0))
|
||
)pbdoc")
|
||
// Primitive factories
|
||
.def_static("sphere", &SdfNode::sphere,
|
||
py::arg("radius"), "Sphere centered at origin")
|
||
.def_static("box", &SdfNode::box,
|
||
py::arg("half_extents"), "Axis-aligned box")
|
||
.def_static("round_box", &SdfNode::round_box,
|
||
py::arg("half_extents"), py::arg("radius"), "Rounded box")
|
||
.def_static("cylinder", &SdfNode::cylinder,
|
||
py::arg("radius"), py::arg("height"), "Capped cylinder along Y")
|
||
.def_static("torus", &SdfNode::torus,
|
||
py::arg("major_radius"), py::arg("minor_radius"), "Torus in XZ plane")
|
||
.def_static("capsule", &SdfNode::capsule,
|
||
py::arg("a"), py::arg("b"), py::arg("radius"), "Capsule from a to b")
|
||
.def_static("cone", &SdfNode::cone,
|
||
py::arg("angle_rad"), py::arg("height"), "Cone along Y axis")
|
||
.def_static("plane", &SdfNode::plane,
|
||
py::arg("normal"), py::arg("offset"), "Infinite plane")
|
||
.def_static("ellipsoid", &SdfNode::ellipsoid,
|
||
py::arg("radii"), "Ellipsoid centered at origin")
|
||
.def_static("triangular_prism", &SdfNode::triangular_prism,
|
||
py::arg("height"), "Triangular prism along Y")
|
||
.def_static("hex_prism", &SdfNode::hex_prism,
|
||
py::arg("radius"), py::arg("height"), py::arg("sides") = 6,
|
||
"Regular-polygon prism along Y (sides=6 → hexagon)")
|
||
.def_static("link", &SdfNode::link,
|
||
py::arg("radius"), py::arg("length"), py::arg("thickness"),
|
||
"Link segment")
|
||
.def_static("wedge", &SdfNode::wedge,
|
||
py::arg("extents"), "Wedge shape")
|
||
|
||
// Boolean CSG operations
|
||
.def_static("union", &SdfNode::op_union,
|
||
py::arg("a"), py::arg("b"),
|
||
R"pbdoc(CSG union: A ∪ B (min distance))pbdoc")
|
||
.def_static("intersection", &SdfNode::op_intersection,
|
||
py::arg("a"), py::arg("b"),
|
||
R"pbdoc(CSG intersection: A ∩ B (max distance))pbdoc")
|
||
.def_static("difference", &SdfNode::op_difference,
|
||
py::arg("a"), py::arg("b"),
|
||
R"pbdoc(CSG difference: A \\ B (max(a, -b)))pbdoc")
|
||
.def_static("smooth_union", &SdfNode::smooth_union,
|
||
py::arg("a"), py::arg("b"), py::arg("k"),
|
||
"Smooth blend union with blend parameter k")
|
||
.def_static("smooth_intersection", &SdfNode::smooth_intersection,
|
||
py::arg("a"), py::arg("b"), py::arg("k"),
|
||
"Smooth blend intersection")
|
||
.def_static("smooth_difference", &SdfNode::smooth_difference,
|
||
py::arg("a"), py::arg("b"), py::arg("k"),
|
||
"Smooth blend difference")
|
||
|
||
// Modifiers
|
||
.def_static("round", &SdfNode::round,
|
||
py::arg("child"), py::arg("radius"),
|
||
"Offset surface outward (isometric rounding)")
|
||
.def_static("onion", &SdfNode::onion,
|
||
py::arg("child"), py::arg("thickness"),
|
||
"Hollow shell of given thickness")
|
||
|
||
// Domain transforms
|
||
.def_static("repeat", &SdfNode::repeat,
|
||
py::arg("child"), py::arg("cell"),
|
||
"Infinite repetition in a periodic lattice")
|
||
.def_static("mirror_x", &SdfNode::mirror_x,
|
||
py::arg("child"), "Mirror across YZ plane")
|
||
.def_static("mirror_y", &SdfNode::mirror_y,
|
||
py::arg("child"), "Mirror across XZ plane")
|
||
.def_static("mirror_z", &SdfNode::mirror_z,
|
||
py::arg("child"), "Mirror across XY plane")
|
||
.def_static("translate", &SdfNode::translate,
|
||
py::arg("child"), py::arg("offset"),
|
||
"Translate in space (inverse transform)")
|
||
.def_static("rotate", &SdfNode::rotate,
|
||
py::arg("child"), py::arg("angle_rad"),
|
||
"Rotate around Y axis (inverse transform)")
|
||
.def_static("scale", &SdfNode::scale,
|
||
py::arg("child"), py::arg("factors"),
|
||
"Non-uniform scale (inverse transform)")
|
||
.def_static("twist", &SdfNode::twist,
|
||
py::arg("child"), py::arg("amount"),
|
||
"Twist around Y axis")
|
||
.def_static("bend", &SdfNode::bend,
|
||
py::arg("child"), py::arg("amount"),
|
||
"Bend around Z axis")
|
||
.def_static("elongate", &SdfNode::elongate,
|
||
py::arg("child"), py::arg("h"),
|
||
"Elongate (stretch space)")
|
||
.def_static("cheap_bend", &SdfNode::cheap_bend,
|
||
py::arg("child"), py::arg("amount"),
|
||
"Simplified bend (cheaper, less accurate)")
|
||
.def_static("displace", &SdfNode::displace,
|
||
py::arg("child"), py::arg("amplitude"), py::arg("frequency"),
|
||
"Sinusoidal displacement noise")
|
||
|
||
// Parameters and accessors
|
||
.def_readwrite("params", &SdfNode::params,
|
||
"SdfParams: mutable parameter block for optimization")
|
||
.def_readwrite("name", &SdfNode::name, "Optional label for debugging")
|
||
.def_readonly("children", &SdfNode::children, "Child node list")
|
||
.def("__repr__", [](const SdfNode& n) {
|
||
return "SdfNode(\"" + n.name + "\")";
|
||
});
|
||
|
||
// ── SdfParams ──────────────────────────────────────
|
||
py::class_<SdfParams>(sdf_m, "SdfParams",
|
||
R"pbdoc(
|
||
Parameter block for an SDF node.
|
||
|
||
Different operation types use different fields. Key parameters:
|
||
|
||
Primitives:
|
||
radius: sphere/cylinder/capsule/round radius
|
||
extents: box half-extents (Point3D)
|
||
height: cylinder/cone/prism height
|
||
major_radius, minor_radius: torus parameters
|
||
|
||
Boolean:
|
||
blend_k: smooth CSG blend parameter
|
||
|
||
Transforms:
|
||
translate_offset: translation vector
|
||
scale_factors: non-uniform scale factors
|
||
amount: twist/bend magnitude
|
||
amplitude, frequency: displacement noise parameters
|
||
|
||
Read-write; modify to drive gradient-based optimization.
|
||
)pbdoc")
|
||
.def(py::init<>())
|
||
.def_readwrite("radius", &SdfParams::radius)
|
||
.def_readwrite("extents", &SdfParams::extents)
|
||
.def_readwrite("pt_a", &SdfParams::pt_a)
|
||
.def_readwrite("pt_b", &SdfParams::pt_b)
|
||
.def_readwrite("major_radius", &SdfParams::major_radius)
|
||
.def_readwrite("minor_radius", &SdfParams::minor_radius)
|
||
.def_readwrite("angle_rad", &SdfParams::angle_rad)
|
||
.def_readwrite("height", &SdfParams::height)
|
||
.def_readwrite("thickness", &SdfParams::thickness)
|
||
.def_readwrite("normal", &SdfParams::normal)
|
||
.def_readwrite("offset", &SdfParams::offset)
|
||
.def_readwrite("blend_k", &SdfParams::blend_k)
|
||
.def_readwrite("amount", &SdfParams::amount)
|
||
.def_readwrite("amplitude", &SdfParams::amplitude)
|
||
.def_readwrite("frequency", &SdfParams::frequency)
|
||
.def_readwrite("repeat_cell", &SdfParams::repeat_cell)
|
||
.def_readwrite("translate_offset", &SdfParams::translate_offset)
|
||
.def_readwrite("scale_factors", &SdfParams::scale_factors)
|
||
.def("__repr__", [](const SdfParams& p) {
|
||
return "SdfParams(radius=" + std::to_string(p.radius) + ")";
|
||
});
|
||
|
||
// ── evaluate() ─────────────────────────────────────
|
||
sdf_m.def("evaluate", &evaluate,
|
||
py::arg("node"), py::arg("point"),
|
||
R"pbdoc(
|
||
Evaluate SDF tree at a point. Returns signed distance.
|
||
|
||
Args:
|
||
node: root SdfNode of the tree
|
||
point: Point3D sampling point
|
||
|
||
Returns:
|
||
float: signed distance (negative = inside, zero = on surface, positive = outside)
|
||
|
||
Example:
|
||
>>> root = SdfNode.sphere(2.0)
|
||
>>> sdf.evaluate(root, Point3D(0, 0, 0)) # -2.0 (inside)
|
||
>>> sdf.evaluate(root, Point3D(2, 0, 0)) # ~0.0 (on surface)
|
||
>>> sdf.evaluate(root, Point3D(3, 0, 0)) # ~1.0 (outside)
|
||
)pbdoc");
|
||
|
||
// ── Bounds estimation ──────────────────────────────
|
||
sdf_m.def("estimate_bounds", &estimate_bounds,
|
||
py::arg("root"), py::arg("margin") = 1.0,
|
||
"Estimate half-extent bounding radius of SDF tree");
|
||
|
||
py::class_<SdfBBox>(sdf_m, "SdfBBox",
|
||
"Axis-aligned bounding box of an SDF tree")
|
||
.def(py::init<>())
|
||
.def_readwrite("min", &SdfBBox::min, "Minimum corner (Point3D)")
|
||
.def_readwrite("max", &SdfBBox::max, "Maximum corner (Point3D)")
|
||
.def("__repr__", [](const SdfBBox& b) {
|
||
return "SdfBBox(min=" + std::to_string(b.min.x())
|
||
+ ", max=" + std::to_string(b.max.x()) + ")";
|
||
});
|
||
|
||
sdf_m.def("estimate_bbox", &estimate_bbox,
|
||
py::arg("root"), py::arg("margin") = 1.0,
|
||
"Estimate full AABB of SDF tree");
|
||
|
||
// ── sdf_to_mesh() ──────────────────────────────────
|
||
py::class_<vde::mesh::MCMesh>(sdf_m, "MCMesh",
|
||
R"pbdoc(
|
||
Marching cubes mesh result.
|
||
|
||
Attributes:
|
||
vertices: N x 3 list of Point3D
|
||
triangles: M x 3 list of index triples
|
||
)pbdoc")
|
||
.def(py::init<>())
|
||
.def_readwrite("vertices", &vde::mesh::MCMesh::vertices)
|
||
.def_readwrite("triangles", &vde::mesh::MCMesh::triangles)
|
||
.def("__repr__", [](const vde::mesh::MCMesh& m) {
|
||
return "MCMesh(v=" + std::to_string(m.vertices.size())
|
||
+ ", t=" + std::to_string(m.triangles.size()) + ")";
|
||
});
|
||
|
||
sdf_m.def("sdf_to_mesh", &sdf_to_mesh,
|
||
py::arg("root"), py::arg("resolution") = 64,
|
||
py::arg("iso_level") = 0.0,
|
||
R"pbdoc(
|
||
Convert SDF tree to triangle mesh via marching cubes.
|
||
|
||
Args:
|
||
root: SdfNode tree root
|
||
resolution: per-axis grid resolution (e.g. 64 = 64³ voxels)
|
||
iso_level: isosurface level (0.0 = implicit surface)
|
||
|
||
Returns:
|
||
MCMesh with vertices and triangles
|
||
)pbdoc");
|
||
|
||
sdf_m.def("sdf_to_mesh_lambda", &sdf_to_mesh_lambda,
|
||
py::arg("f"), py::arg("bmin"), py::arg("bmax"),
|
||
py::arg("resolution") = 64, py::arg("iso_level") = 0.0,
|
||
R"pbdoc(
|
||
Convert Python lambda SDF to triangle mesh.
|
||
|
||
Args:
|
||
f: callable f(x, y, z) -> signed distance
|
||
bmin: Point3D minimum corner of sampling box
|
||
bmax: Point3D maximum corner of sampling box
|
||
resolution: per-axis grid resolution
|
||
iso_level: isosurface level
|
||
|
||
Returns:
|
||
MCMesh with vertices and triangles
|
||
)pbdoc");
|
||
|
||
// ── SDF Gradient ──────────────────────────────────
|
||
sdf_m.def("gradient", &gradient,
|
||
py::arg("f"), py::arg("p"), py::arg("h") = 1e-6,
|
||
R"pbdoc(
|
||
Compute spatial gradient of an SDF function at a point (central finite difference).
|
||
|
||
Args:
|
||
f: callable f(Point3D) -> double
|
||
p: evaluation point
|
||
h: difference step size (default 1e-6)
|
||
|
||
Returns:
|
||
Vector3D: gradient vector ∇f(p)
|
||
)pbdoc");
|
||
|
||
py::class_<GradResult>(sdf_m, "GradResult",
|
||
"Result of SDF evaluation with gradient")
|
||
.def_readonly("value", &GradResult::value, "SDF value f(p)")
|
||
.def_readonly("grad", &GradResult::grad, "Spatial gradient ∇f(p)")
|
||
.def("__repr__", [](const GradResult& r) {
|
||
return "GradResult(value=" + std::to_string(r.value) + ")";
|
||
});
|
||
|
||
sdf_m.def("evaluate_with_gradient", &evaluate_with_gradient,
|
||
py::arg("f"), py::arg("p"), py::arg("h") = 1e-6,
|
||
R"pbdoc(
|
||
Compute both SDF value and gradient at a point in one call.
|
||
|
||
Args:
|
||
f: callable f(Point3D) -> double
|
||
p: evaluation point
|
||
h: difference step size
|
||
|
||
Returns:
|
||
GradResult(value, grad)
|
||
)pbdoc");
|
||
|
||
// ── Analytical gradients ──────────────────────────
|
||
sdf_m.def("sphere_gradient_analytic", &sphere_gradient_analytic,
|
||
py::arg("p"), py::arg("radius"),
|
||
"Exact gradient of sphere SDF: p / |p|");
|
||
sdf_m.def("box_gradient_analytic", &box_gradient_analytic,
|
||
py::arg("p"), py::arg("half_extents"),
|
||
"Exact gradient of box SDF");
|
||
sdf_m.def("torus_gradient_analytic", &torus_gradient_analytic,
|
||
py::arg("p"), py::arg("major_r"), py::arg("minor_r"),
|
||
"Exact gradient of torus SDF");
|
||
sdf_m.def("cylinder_gradient_analytic", &cylinder_gradient_analytic,
|
||
py::arg("p"), py::arg("radius"),
|
||
"Exact gradient of cylinder SDF (along Y axis)");
|
||
|
||
// ── SDF Operations (free functions) ────────────────
|
||
sdf_m.def("op_union", &op_union,
|
||
py::arg("d1"), py::arg("d2"),
|
||
"Boolean union of two SDF values: min(d1, d2)");
|
||
sdf_m.def("op_intersection", &op_intersection,
|
||
py::arg("d1"), py::arg("d2"),
|
||
"Boolean intersection: max(d1, d2)");
|
||
sdf_m.def("op_difference", &op_difference,
|
||
py::arg("d1"), py::arg("d2"),
|
||
"Boolean difference: max(d1, -d2)");
|
||
sdf_m.def("op_smooth_union", &op_smooth_union,
|
||
py::arg("d1"), py::arg("d2"), py::arg("k"),
|
||
"Smooth blend union with blend parameter k");
|
||
sdf_m.def("op_smooth_intersection", &op_smooth_intersection,
|
||
py::arg("d1"), py::arg("d2"), py::arg("k"),
|
||
"Smooth blend intersection");
|
||
sdf_m.def("op_smooth_difference", &op_smooth_difference,
|
||
py::arg("d1"), py::arg("d2"), py::arg("k"),
|
||
"Smooth blend difference");
|
||
|
||
// ── SDF Optimization ───────────────────────────────
|
||
py::class_<OptimizeResult>(sdf_m, "OptimizeResult",
|
||
R"pbdoc(
|
||
Result of SDF shape optimization.
|
||
|
||
Attributes:
|
||
optimized_shape: SdfNodePtr with updated parameters
|
||
final_loss: final loss value
|
||
iterations: actual iteration count
|
||
converged: True if optimization converged
|
||
loss_history: list of loss values per iteration
|
||
)pbdoc")
|
||
.def_readonly("optimized_shape", &OptimizeResult::optimized_shape)
|
||
.def_readonly("final_loss", &OptimizeResult::final_loss)
|
||
.def_readonly("iterations", &OptimizeResult::iterations)
|
||
.def_readonly("converged", &OptimizeResult::converged)
|
||
.def_readonly("loss_history", &OptimizeResult::loss_history)
|
||
.def("__repr__", [](const OptimizeResult& r) {
|
||
return "OptimizeResult(loss=" + std::to_string(r.final_loss)
|
||
+ ", iters=" + std::to_string(r.iterations)
|
||
+ ", converged=" + std::string(r.converged ? "True" : "False") + ")";
|
||
});
|
||
|
||
sdf_m.def("fit_to_point_cloud", &fit_to_point_cloud,
|
||
py::arg("initial"), py::arg("target_points"),
|
||
py::arg("learning_rate") = 0.01,
|
||
py::arg("max_iterations") = 100,
|
||
R"pbdoc(
|
||
Fit a parameterized SDF shape to a target point cloud via gradient descent.
|
||
|
||
Minimizes mean absolute SDF distance of target points to the shape.
|
||
|
||
Args:
|
||
initial: starting SdfNodePtr (e.g. sphere, box, cylinder)
|
||
target_points: list of Point3D surface samples
|
||
learning_rate: gradient descent step size (default 0.01)
|
||
max_iterations: max iterations (default 100)
|
||
|
||
Returns:
|
||
OptimizeResult with optimized shape and convergence info
|
||
|
||
Example:
|
||
>>> shape = SdfNode.sphere(1.0)
|
||
>>> points = [Point3D(1,0,0), Point3D(0,1,0), Point3D(0,0,1), ...]
|
||
>>> result = sdf.fit_to_point_cloud(shape, points, 0.01, 200)
|
||
>>> if result.converged:
|
||
... optimized = result.optimized_shape
|
||
)pbdoc");
|
||
|
||
sdf_m.def("gradient_descent_optimize", &fit_to_point_cloud,
|
||
py::arg("initial"), py::arg("target_points"),
|
||
py::arg("learning_rate") = 0.01,
|
||
py::arg("max_iterations") = 100,
|
||
R"pbdoc(
|
||
Alias for fit_to_point_cloud — gradient descent SDF shape optimization.
|
||
|
||
Args:
|
||
initial: starting SdfNodePtr
|
||
target_points: list of Point3D target points
|
||
learning_rate: step size (default 0.01)
|
||
max_iterations: max iterations (default 100)
|
||
|
||
Returns:
|
||
OptimizeResult
|
||
)pbdoc");
|
||
|
||
sdf_m.def("fit_surface_to_points", &fit_surface_to_points,
|
||
py::arg("initial"), py::arg("surface_points"),
|
||
py::arg("learning_rate") = 0.01,
|
||
py::arg("max_iterations") = 100,
|
||
R"pbdoc(
|
||
Fit shape surface to target surface points by minimizing |sdf(p)|.
|
||
|
||
Args:
|
||
initial: starting SdfNodePtr
|
||
surface_points: list of Point3D on the target surface
|
||
learning_rate: step size
|
||
max_iterations: max iterations
|
||
|
||
Returns:
|
||
OptimizeResult
|
||
)pbdoc");
|
||
|
||
sdf_m.def("fit_to_sdf", &fit_to_sdf,
|
||
py::arg("source"), py::arg("target_sdf"),
|
||
py::arg("bmin"), py::arg("bmax"),
|
||
py::arg("grid_resolution") = 16,
|
||
py::arg("learning_rate") = 0.01,
|
||
py::arg("max_iterations") = 100,
|
||
R"pbdoc(
|
||
Fit a parameterized SDF shape to match another target SDF.
|
||
|
||
Args:
|
||
source: SdfNodePtr to optimize
|
||
target_sdf: callable f(Point3D) -> double
|
||
bmin, bmax: sampling grid bounding box
|
||
grid_resolution: sampling grid resolution
|
||
learning_rate: step size
|
||
max_iterations: max iterations
|
||
|
||
Returns:
|
||
OptimizeResult
|
||
)pbdoc");
|
||
|
||
// ── Gradient Descent Utility ───────────────────────
|
||
py::class_<GradientDescent>(sdf_m, "GradientDescent",
|
||
R"pbdoc(
|
||
Fixed-learning-rate gradient descent optimizer.
|
||
|
||
Manages iteration count and learning rate. Call step() to perform
|
||
a single parameter update.
|
||
|
||
Example:
|
||
>>> gd = sdf.GradientDescent(0.01)
|
||
>>> for i in range(100):
|
||
... loss = gd.step(params, grad_fn)
|
||
... if loss < tol:
|
||
... break
|
||
)pbdoc")
|
||
.def(py::init<double>(),
|
||
py::arg("learning_rate"),
|
||
"Construct optimizer with given learning rate")
|
||
.def("step", &GradientDescent::step,
|
||
py::arg("params"), py::arg("grad_fn"),
|
||
R"pbdoc(
|
||
Perform a single gradient descent step.
|
||
|
||
Args:
|
||
params: list of float parameter values (modified in place)
|
||
grad_fn: callable grad_fn(values, grad_out) -> float loss
|
||
Takes current param values, fills grad_out, returns loss.
|
||
|
||
Returns:
|
||
float: current loss value
|
||
)pbdoc")
|
||
.def_property("learning_rate",
|
||
&GradientDescent::learning_rate,
|
||
&GradientDescent::set_learning_rate,
|
||
"Gradient descent step size")
|
||
.def_property_readonly("iteration", &GradientDescent::iteration,
|
||
"Current iteration count");
|
||
|
||
// ── Parameter collection and numerical gradient ────
|
||
py::class_<ParamRef>(sdf_m, "ParamRef",
|
||
"Reference to a mutable parameter in an SDF tree for optimization")
|
||
.def_readwrite("value", &ParamRef::value,
|
||
"Raw pointer to the parameter value (double*)")
|
||
.def_readwrite("name", &ParamRef::name,
|
||
"Parameter name for debugging")
|
||
.def("__repr__", [](const ParamRef& pr) {
|
||
return "ParamRef(name=\"" + pr.name + "\")";
|
||
});
|
||
|
||
sdf_m.def("collect_params", &collect_params,
|
||
py::arg("root"),
|
||
R"pbdoc(
|
||
Collect all mutable numeric parameters from leaf nodes of an SDF tree.
|
||
|
||
Returns:
|
||
list of ParamRef, each pointing to a specific parameter field
|
||
)pbdoc");
|
||
|
||
sdf_m.def("numerical_gradient", &numerical_gradient,
|
||
py::arg("params"), py::arg("loss_fn"),
|
||
py::arg("eps") = 1e-6,
|
||
R"pbdoc(
|
||
Compute numerical gradient of a scalar loss w.r.t. collected parameters.
|
||
|
||
Uses central finite difference for each parameter.
|
||
|
||
Args:
|
||
params: list of ParamRef from collect_params()
|
||
loss_fn: callable () -> float, the loss function
|
||
eps: difference step (default 1e-6)
|
||
|
||
Returns:
|
||
list of float: gradient vector
|
||
|
||
Example:
|
||
>>> params = sdf.collect_params(root)
|
||
>>> def loss_fn():
|
||
... s = 0
|
||
... for pt in target_points:
|
||
... s += abs(sdf.evaluate(root, pt))
|
||
... return s / len(target_points)
|
||
>>> grad = sdf.numerical_gradient(params, loss_fn, 1e-6)
|
||
)pbdoc");
|
||
|
||
// ── Utility: volume, symmetry, collision ───────────
|
||
sdf_m.def("estimate_volume", &estimate_volume,
|
||
py::arg("shape"), py::arg("bmin"), py::arg("bmax"),
|
||
py::arg("samples") = 10000,
|
||
"Estimate volume of implicit shape via Monte Carlo sampling");
|
||
|
||
sdf_m.def("center_of_mass", ¢er_of_mass,
|
||
py::arg("shape"), py::arg("bmin"), py::arg("bmax"),
|
||
py::arg("samples") = 10000,
|
||
"Estimate center of mass via Monte Carlo sampling");
|
||
|
||
sdf_m.def("resolve_collision", &resolve_collision,
|
||
py::arg("shape_a"), py::arg("shape_b"),
|
||
py::arg("step_size") = 0.1,
|
||
py::arg("max_iterations") = 50,
|
||
"Resolve penetration between two shapes by translating them");
|
||
|
||
sdf_m.def("symmetry_score", &symmetry_score,
|
||
py::arg("shape"), py::arg("bmin"), py::arg("bmax"),
|
||
py::arg("plane_normal"), py::arg("plane_offset") = 0.0,
|
||
py::arg("samples") = 1000,
|
||
"Compute reflection symmetry score [0, 1] for a shape");
|
||
|
||
py::class_<SymmetryResult>(sdf_m, "SymmetryResult",
|
||
"Result of automatic symmetry plane detection")
|
||
.def_readonly("score", &SymmetryResult::score,
|
||
"Symmetry score [0, 1]")
|
||
.def_readonly("normal", &SymmetryResult::normal,
|
||
"Best symmetry plane normal")
|
||
.def_readonly("offset", &SymmetryResult::offset,
|
||
"Best symmetry plane offset")
|
||
.def("__repr__", [](const SymmetryResult& r) {
|
||
return "SymmetryResult(score=" + std::to_string(r.score) + ")";
|
||
});
|
||
|
||
sdf_m.def("find_symmetry_plane", &find_symmetry_plane,
|
||
py::arg("shape"), py::arg("bmin"), py::arg("bmax"),
|
||
py::arg("samples") = 1000,
|
||
"Find the best reflection symmetry plane for a shape");
|
||
}
|