Files
hm c922fb6996 feat(curves/collision): B2 NURBS Trim/Untrim + B3 连续碰撞检测
- B2: trim_curve/untrim_curve — Boehm 节点插入 + 齐次控制点子段提取
  * 归一化参数语义 (t0/t1 为 [0,1] 比例),自动 clamp 与交换
  * 13 个测试覆盖端点匹配/中点几何/圆几何保持/边界/退化/折线
- B3: conservative_advancement + swept_sphere_triangle
  * GJK 距离查询保守推进,保证不穿透
  * 8 个测试覆盖命中时间/远离/重叠/正交/对撞/扫掠球
2026-08-08 23:57:35 +08:00

99 lines
3.2 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* @file ccd.h
* @brief 连续碰撞检测 (Continuous Collision Detection, CCD)
*
* 基于保守推进 (Conservative Advancement, Mirtich 1998) 的
* 时间域碰撞检测:给定两个凸形状及其线性速度,计算归一化
* 首次碰撞时间 (TOI ∈ [0,1]) 与接触信息。
*
* 与静态 GJK 的区别:
* - GJK 只回答"现在是否碰撞"(离散采样会隧穿)
* - CCD 回答"时间步内何时碰撞"(无隧穿)
*
* 对标:Bullet Physics btGjkConvexCast / PhysX sweepQuery
*
* @ingroup collision
*/
#pragma once
#include "vde/core/point.h"
#include "vde/collision/gjk.h"
namespace vde::collision {
using core::Point3D;
using core::Vector3D;
/**
* @brief CCD 命中结果
*/
struct CCDHit {
bool hit = false; ///< 时间步内是否发生碰撞
double time_of_impact = -1.0; ///< 归一化首次碰撞时间 [0,1]
Point3D point_a; ///< 形状 A 上的接触点
Point3D point_b; ///< 形状 B 上的接触点
Vector3D normal; ///< 接触法向(从 B 指向 A 的分离方向)
double initial_distance = 0.0; ///< t=0 时两形状最近距离
};
/**
* @brief 保守推进连续碰撞检测
*
* 两凸体分别以常速度 va / vb 平移,在时间区间 [0, max_time] 内
* 检测首次碰撞。算法每步用 GJK 求当前距离 d,按安全步长
* dt = d / ||va - vb|| 推进——该步长保证不会穿透(保守推进的
* 核心保证)。
*
* @param a 形状 A 的支撑函数(位置)
* @param va 形状 A 的线性速度
* @param b 形状 B 的支撑函数(位置)
* @param vb 形状 B 的线性速度
* @param max_time 归一化时间上限(默认 1.0 = 一个时间步)
* @param tolerance 碰撞判定距离容差
* @return CCDHit;hit=true 时 time_of_impact ∈ [0, max_time]
*
* @code{.cpp}
* // 两个球:A 从 (0,0,0) 以 10 m/s 沿 +X,B 静止在 (5,0,0),半径 1
* auto sphere_a = [&](const Vector3D& d) {
* return Point3D(0,0,0) + 1.0 * d.normalized();
* };
* auto sphere_b = [&](const Vector3D& d) {
* return Point3D(5,0,0) + 1.0 * d.normalized();
* };
* auto hit = conservative_advancement(sphere_a, {10,0,0},
* sphere_b, {0,0,0});
* // 中心距 5,碰撞距离 2 → TOI = (5-2)/10 = 0.3
* @endcode
*
* @see gjk_full, GJKResult
*/
[[nodiscard]] CCDHit conservative_advancement(
const SupportFunc& a, const Vector3D& va,
const SupportFunc& b, const Vector3D& vb,
double max_time = 1.0, double tolerance = 1e-6);
/**
* @brief 扫掠球 vs 三角形 CCD(快速近似)
*
* 将运动球体(中心路径 = 线段)对三角形做扫掠检测。
* 用于碰撞响应/角色控制器等无需精确凸体 TOI 的场景。
*
* @param from 球心起点
* @param to 球心终点
* @param radius 球半径
* @param v0,v1,v2 三角形顶点
* @return 扫掠是否与三角形相交
*
* @code{.cpp}
* bool hit = swept_sphere_triangle(
* {0,0,0}, {0,0,5}, 1.0,
* {-1,0,1}, {1,0,1}, {0,0,0});
* @endcode
*
* @see ray_intersect
*/
[[nodiscard]] bool swept_sphere_triangle(
const Point3D& from, const Point3D& to, double radius,
const Point3D& v0, const Point3D& v1, const Point3D& v2);
} // namespace vde::collision