Files
hm c9f6ff5776
ci / ubuntu-latest / clang (push) Failing after 15m1s
ci / ubuntu-latest / gcc (push) Failing after 1m43s
ci / coverage / gcc (push) Failing after 33s
ci / macos-latest / apple-clang (push) Canceled after 0s
ci / windows-latest / mingw (push) Canceled after 0s
ci / windows-latest / msvc (push) Canceled after 0s
test(g702): 0-DOF 约束空段/外部几何降级/0-DOF 块早退/外部约束块防御门 可达补测覆盖收口 —— −7 行闭合(覆盖率轴同轮消费,连续第十三轮真实覆盖率 Δ)
- 可达门补测(5 测试文件 +5 用例,零 src 行为变更):
  · sparse_jacobian L193:JacobianLayout::Update 空段(rows==0||cols==0)跳过
  · continuation_solver L30:外部几何前置门 ValidateExternalGeometry
  · decomposed_solver L133/L209/L210/L247:m==0 空块早退 + 逐约束 0-DOF 列视图防御门
  · dof_analyzer L346:geometry_missing 且 verifiable_rows>0 时逐约束跳过外部约束行
- 结构性死代码登记(未强造):serializer 430(ConstraintTypesOk 前置闸门双保险)、
  vdcs_c_api 10、model L48/L4087/L4148、drag_controller L199、decomposer L523/524、
  diagnostic ToString 三默认、expression 25(gcov 函数表伪影)
- 验证:build-rel 16 targets 一次通过;受影响套件 12/25/10/23/17 全绿;
  全量 ctest build-rel 61/61 exit 0(446.83 s);build_cov ctest 60/60 exit 0(639.73 s);
  coverage_report src 95.9% (12022/12537) 门 85.0 PASS;
  line_scan src gap 518→511 行/14 文件;Python 逐行差分 Δ=−7/0 新开
- ABI 171 frozen / 0 new;零 src 行为变更 → CHANGELOG 不加行
2026-10-07 06:17:08 +08:00

543 lines
20 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.
//===--------------------------------------------------------------===//
// VDCS - 几何约束求解引擎
// File: tests/unit/test_external_curve.cpp
// Description: P4-S1 外部(宿主)曲线单测——投影/残差/雅可比/
// 求解吸附/DOF/无 adapter 拒绝/序列化往返/工厂槽位
//===--------------------------------------------------------------===//
#include <gtest/gtest.h>
#include <Eigen/Core>
#include <atomic>
#include <cmath>
#include <cstdio>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include "vdcs/core/decomposed_solver.h"
#include "vdcs/core/dof_analyzer.h"
#include "vdcs/core/dogleg_solver.h"
#include "vdcs/core/drag_controller.h"
#include "vdcs/core/multi_start_solver.h"
#include "vdcs/core/newton_solver.h"
#include "vdcs/core/solve_context.h"
#include "vdcs/core/sparse_lm_solver.h"
#include "vdcs/io/serializer.h"
#include "vdcs/model/entity.h"
#include "vdcs/model/external_constraint.h"
#include "vdcs/model/geometry_adapter.h"
#include "vdcs/model/model.h"
using vdcs::ExternalCurve2D;
using vdcs::ErrorCode;
using vdcs::GenerateUid;
using vdcs::IGeometryAdapter;
using vdcs::LoadModel;
using vdcs::LoadModelJson;
using vdcs::Model;
using vdcs::Point2D;
using vdcs::PointOnExternalCurve2D;
using vdcs::ProjectOnCurve;
using vdcs::SaveModel;
using vdcs::SaveModelJson;
using vdcs::SolveContext;
using vdcs::Uid;
using vdcs::Vec2;
namespace {
/// 测试后端:抛物线 C(t) = (4t, 8t²),t ∈ [0, 1]。
/// C'(t) = (4, 16t),C''(t) = (0, 16)——解析精确(差分对拍无模型误差)
class ParabolaAdapter : public IGeometryAdapter {
public:
explicit ParabolaAdapter(Uid curve) : curve_(curve) {}
Vec2 Evaluate(Uid curve, double t) const override {
ExpectKnown(curve);
return {4.0 * t, 8.0 * t * t};
}
Vec2 Derivative(Uid curve, double t, int order) const override {
ExpectKnown(curve);
switch (order) {
case 1:
return {4.0, 16.0 * t};
case 2:
return {0.0, 16.0};
default:
return {0.0, 0.0};
}
}
private:
void ExpectKnown(Uid curve) const { EXPECT_EQ(curve, curve_); }
Uid curve_;
};
/// 直连约束求值的轻量上下文:点(2 参数) + 曲线(0 参数身份载体)
struct PtCurveModel {
Point2D p;
ExternalCurve2D curve;
ParabolaAdapter adapter;
Eigen::VectorXd q;
std::unordered_map<Uid, int> offsets;
PtCurveModel(double px, double py)
: p{GenerateUid(), px, py}, curve{GenerateUid()},
adapter{curve.Id()} {
q.resize(2);
p.WriteParams(q.data());
offsets[p.Id()] = 0;
// 与 DofAnalyzer 同布局:0-DOF 实体也占偏移表一项(无参数区)
offsets[curve.Id()] = 2;
}
SolveContext Ctx() const {
return SolveContext{q.data(), 2, offsets, nullptr, &adapter};
}
};
/// 数值差分雅可比(中心差分,仅点两列非零)
Eigen::MatrixXd NumericJacobian(const PtCurveModel& m, double h = 1e-6) {
PointOnExternalCurve2D c{GenerateUid(), "C", m.p.Id(), m.curve.Id()};
Eigen::VectorXd qp = m.q;
Eigen::MatrixXd num(2, 2);
for (int col = 0; col < 2; ++col) {
qp[col] = m.q[col] + h;
const Eigen::VectorXd rp =
c.Residual(SolveContext{qp.data(), 2, m.offsets, nullptr,
&m.adapter});
qp[col] = m.q[col] - h;
const Eigen::VectorXd rm =
c.Residual(SolveContext{qp.data(), 2, m.offsets, nullptr,
&m.adapter});
qp[col] = m.q[col];
num.col(col) = (rp - rm) / (2.0 * h);
}
return num;
}
struct TempPath {
std::string path;
explicit TempPath(const char* suffix) {
static std::atomic<int> counter{0};
path = "vdcs_test_ext_" + std::to_string(counter.fetch_add(1)) +
suffix;
}
~TempPath() { std::remove(path.c_str()); }
};
/// 建参考模型:点(2,3) + 外部曲线 + 点在曲线上(求解后点吸附到抛物线)
Model BuildSnapModel(Uid* point_out, Uid* curve_out) {
Model model;
auto p = model.AddPoint2D("P", 2.0, 3.0);
auto c = model.AddExternalCurve2D("host_spline");
(void)model.AddPointOnCurve2D("on_curve", p.Value(), c.Value());
*point_out = p.Value();
*curve_out = c.Value();
return model;
}
/// 求解后点到曲线的最近距离(投影点 |p − C(t*)|)
double DistanceToCurve(const ParabolaAdapter& g, Uid curve,
const Vec2& p) {
const double t = ProjectOnCurve(g, curve, p);
return (g.Evaluate(curve, t) - p).Norm();
}
} // namespace
TEST(ExternalCurveTest, EntityIsZeroDofIdentity) {
ExternalCurve2D curve{GenerateUid()};
EXPECT_EQ(curve.Type(), vdcs::EntityType::kExternalCurve2D);
EXPECT_EQ(curve.Dof(), 0);
// 0 参数:Write/Read 为空操作(参数区长度恒为 0)
double sink[1] = {1.0};
curve.WriteParams(sink);
EXPECT_DOUBLE_EQ(sink[0], 1.0);
curve.ReadParams(sink);
}
TEST(ExternalCurveTest, ResidualZeroAtCurvePoint) {
// p = C(0.25) = (1.0, 0.5)
PtCurveModel m{1.0, 0.5};
PointOnExternalCurve2D c{GenerateUid(), "C", m.p.Id(), m.curve.Id()};
EXPECT_EQ(c.RemovedDof(), 2);
const Eigen::VectorXd r = c.Residual(m.Ctx());
EXPECT_NEAR(r.norm(), 0.0, 1e-12);
}
TEST(ExternalCurveTest, ProjectionIsOptimalAndPerpendicular) {
PtCurveModel m{2.0, 3.0};
const double t = ProjectOnCurve(m.adapter, m.curve.Id(),
Vec2{m.q[0], m.q[1]});
EXPECT_GE(t, 0.0);
EXPECT_LE(t, 1.0);
// 最优性①:残差 ⊥ 切向(C'(t*)·(p − C(t*)) = 0)
const Vec2 c = m.adapter.Evaluate(m.curve.Id(), t);
const Vec2 d1 = m.adapter.Derivative(m.curve.Id(), t, 1);
const Vec2 r{m.q[0] - c.x, m.q[1] - c.y};
EXPECT_NEAR(d1.Dot(r), 0.0, 1e-8);
// 最优性②:不劣于 1001 点均匀扫描的全局最优
double best = 1e300;
for (int k = 0; k <= 1000; ++k) {
const Vec2 ck =
m.adapter.Evaluate(m.curve.Id(), k / 1000.0);
best = std::min(best, (ck - Vec2{m.q[0], m.q[1]}).SquaredNorm());
}
EXPECT_LE(r.SquaredNorm(), best + 1e-12);
}
TEST(ExternalCurveTest, ProjectionRecoversCurveParameter) {
const Uid curve = GenerateUid();
ParabolaAdapter adapter{curve};
// 曲线上的点:t* 精确恢复(内部无退化)
for (const double t_true : {0.1, 0.3, 0.5, 0.7, 0.9}) {
const Vec2 p = adapter.Evaluate(curve, t_true);
EXPECT_NEAR(ProjectOnCurve(adapter, curve, p), t_true, 1e-10);
}
// 域外点:夹取到端点([0,1] 参数域契约)
EXPECT_NEAR(ProjectOnCurve(adapter, curve, Vec2{10.0, 10.0}), 1.0,
1e-12);
EXPECT_NEAR(ProjectOnCurve(adapter, curve, Vec2{-5.0, 0.0}), 0.0,
1e-12);
}
TEST(ExternalCurveTest, JacobianAnalyticMatchesNumeric) {
for (const auto [px, py] : std::vector<std::pair<double, double>>{
{2.0, 3.0}, {0.3, 6.0}, {3.9, 7.5}}) {
PtCurveModel m{px, py};
PointOnExternalCurve2D c{GenerateUid(), "C", m.p.Id(),
m.curve.Id()};
const Eigen::MatrixXd analytic = c.Jacobian(m.Ctx());
ASSERT_EQ(analytic.rows(), 2);
ASSERT_EQ(analytic.cols(), 2);
const Eigen::MatrixXd numeric = NumericJacobian(m);
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
EXPECT_NEAR(analytic(i, j), numeric(i, j), 1e-5)
<< "p=(" << px << "," << py << ") row=" << i
<< " col=" << j;
}
}
}
}
TEST(ExternalCurveTest, SolveSnapsPointToCurve) {
Uid p_uid = 0;
Uid c_uid = 0;
Model model = BuildSnapModel(&p_uid, &c_uid);
// DOF 记账:点 2 − 约束 2 = 0(外部曲线自身 0 DOF)
EXPECT_EQ(model.TotalEntityDof(), 2);
EXPECT_EQ(model.TotalRemovedDof(), 2);
model.SetGeometryAdapter(std::make_shared<ParabolaAdapter>(c_uid));
auto report = model.Solve();
ASSERT_TRUE(report.Ok()) << report.Err().Message();
EXPECT_TRUE(report.Value().converged);
double xy[2] = {0.0, 0.0};
model.FindEntity(p_uid)->WriteParams(xy);
const ParabolaAdapter g{c_uid};
EXPECT_LT(DistanceToCurve(g, c_uid, Vec2{xy[0], xy[1]}), 1e-8);
}
/// g702:分解求解器的 0-DOF 实体列防御门可达覆盖。外部曲线实体自身
/// Dof=0——块装配逐约束建局部列视图时,「引用实体含 0 DOF」即视图不可
/// 构建(原路径 LocalJacobian 空矩阵 UB 读),该约束行按零贡献跳过(不
/// 装配进块雅可比)。可达路径:adapter 已注入(几何可求值、前置门放行)
/// 但外部曲线实体 0 参数,分解路径经 SolveBlock 逐约束装配命中该门——
/// 契约 = 不崩溃、返回报告
TEST(ExternalCurveTest, DecomposedSolverHandlesZeroDofCurveEntity) {
Uid p_uid = 0;
Uid c_uid = 0;
Model model = BuildSnapModel(&p_uid, &c_uid);
model.SetGeometryAdapter(std::make_shared<ParabolaAdapter>(c_uid));
vdcs::SolveOptions opts;
auto r = vdcs::DecomposedSolver::Solve(model, opts);
ASSERT_TRUE(r.Ok()) << r.Err().Message();
}
TEST(ExternalCurveTest, SolveWithoutAdapterFails) {
Uid p_uid = 0;
Uid c_uid = 0;
Model model = BuildSnapModel(&p_uid, &c_uid);
// 未注入 adapter:入口 Result 校验拦截(非异常逃逸)
auto report = model.Solve();
ASSERT_FALSE(report.Ok());
EXPECT_EQ(report.Err().Code(), ErrorCode::kInvalidInput);
}
// g19:无 adapter 契约扩展——独立求解器入口/拖拽会话/DofAnalyzer
// 同样不得抛异常(fuzz 种子 D 实测暴露的缺口):求解器统一
// kInvalidInput 拒绝;DofAnalyzer 计数分类照常、秩校验降级置
// rank_partial(外部约束行不参与 SVD)
TEST(ExternalCurveTest, StandaloneEntriesWithoutAdapterRejectedNotThrown) {
Uid p_uid = 0;
Uid c_uid = 0;
Model model = BuildSnapModel(&p_uid, &c_uid);
const vdcs::SolveOptions opts;
auto sparse = vdcs::SparseLmSolver::Solve(model, opts);
ASSERT_FALSE(sparse.Ok());
EXPECT_EQ(sparse.Err().Code(), ErrorCode::kInvalidInput);
auto dogleg = vdcs::DogLegSolver::Solve(model, opts);
ASSERT_FALSE(dogleg.Ok());
EXPECT_EQ(dogleg.Err().Code(), ErrorCode::kInvalidInput);
auto newton = vdcs::NewtonSolver::Solve(model, opts);
ASSERT_FALSE(newton.Ok());
EXPECT_EQ(newton.Err().Code(), ErrorCode::kInvalidInput);
auto decomposed = vdcs::DecomposedSolver::Solve(model, opts);
ASSERT_FALSE(decomposed.Ok());
EXPECT_EQ(decomposed.Err().Code(), ErrorCode::kInvalidInput);
vdcs::MultiStartSolver::Options ms;
ms.inner = &vdcs::SparseLmSolver::Solve;
ms.restarts = 1;
auto multi = vdcs::MultiStartSolver::Solve(model, opts, ms);
ASSERT_FALSE(multi.Ok());
EXPECT_EQ(multi.Err().Code(), ErrorCode::kInvalidInput);
vdcs::DragController drag;
auto begin = drag.Begin(model, p_uid);
ASSERT_FALSE(begin.Ok());
EXPECT_EQ(begin.Err().Code(), ErrorCode::kInvalidInput);
EXPECT_FALSE(drag.Active());
// DofAnalyzer:不抛异常;计数分类含外部约束(removed_dof=2),
// 秩校验降级(rank_partial,verifiable 子集为空 → 不判亏损)
const auto dof = vdcs::DofAnalyzer::Analyze(model);
ASSERT_EQ(dof.components.size(), 1u);
EXPECT_EQ(dof.components[0].removed_dof, 2);
EXPECT_TRUE(dof.components[0].rank_partial);
EXPECT_FALSE(dof.components[0].rank_deficient);
}
TEST(ExternalCurveTest, SerializationRoundtripBinary) {
Uid p_uid = 0;
Uid c_uid = 0;
Model model = BuildSnapModel(&p_uid, &c_uid);
model.SetGeometryAdapter(std::make_shared<ParabolaAdapter>(c_uid));
ASSERT_TRUE(model.Solve().Ok());
TempPath tmp(".vdcs");
ASSERT_TRUE(SaveModel(model, tmp.path).Ok());
auto loaded = LoadModel(tmp.path);
ASSERT_TRUE(loaded.Ok()) << loaded.Err().Message();
ASSERT_NE(loaded.Value().FindEntity(c_uid), nullptr);
EXPECT_EQ(loaded.Value().FindEntity(c_uid)->Type(),
vdcs::EntityType::kExternalCurve2D);
// 序列化与几何注入解耦:加载物重新 SetGeometryAdapter 即可求解
loaded.Value().SetGeometryAdapter(
std::make_shared<ParabolaAdapter>(c_uid));
auto report = loaded.Value().Solve();
ASSERT_TRUE(report.Ok()) << report.Err().Message();
EXPECT_TRUE(report.Value().converged);
double xy[2] = {0.0, 0.0};
loaded.Value().FindEntity(p_uid)->WriteParams(xy);
const ParabolaAdapter g{c_uid};
EXPECT_LT(DistanceToCurve(g, c_uid, Vec2{xy[0], xy[1]}), 1e-8);
}
TEST(ExternalCurveTest, SerializationRoundtripJson) {
Uid p_uid = 0;
Uid c_uid = 0;
Model model = BuildSnapModel(&p_uid, &c_uid);
model.SetGeometryAdapter(std::make_shared<ParabolaAdapter>(c_uid));
ASSERT_TRUE(model.Solve().Ok());
TempPath tmp(".json");
ASSERT_TRUE(SaveModelJson(model, tmp.path).Ok());
auto loaded = LoadModelJson(tmp.path);
ASSERT_TRUE(loaded.Ok()) << loaded.Err().Message();
ASSERT_NE(loaded.Value().FindEntity(c_uid), nullptr);
EXPECT_EQ(loaded.Value().FindEntity(c_uid)->Type(),
vdcs::EntityType::kExternalCurve2D);
loaded.Value().SetGeometryAdapter(
std::make_shared<ParabolaAdapter>(c_uid));
auto report = loaded.Value().Solve();
ASSERT_TRUE(report.Ok()) << report.Err().Message();
EXPECT_TRUE(report.Value().converged);
// 已收敛解:0 迭代(对拍 test_solve3d 语义)
EXPECT_EQ(report.Value().iterations, 0);
}
TEST(ExternalCurveTest, FactoryRejectsWrongSlots) {
Model model;
auto p1 = model.AddPoint2D("P1", 0.0, 0.0);
auto p2 = model.AddPoint2D("P2", 1.0, 1.0);
auto c = model.AddExternalCurve2D("spline");
ASSERT_TRUE(c.Ok());
// 槽位 0 必须 Point2D(曲线实体不是点)
auto r1 = model.AddPointOnCurve2D("bad1", c.Value(), p1.Value());
EXPECT_FALSE(r1.Ok());
// 槽位 1 只接受 Line/Circle/Arc/ExternalCurve(点不是曲线)
auto r2 = model.AddPointOnCurve2D("bad2", p1.Value(), p2.Value());
EXPECT_FALSE(r2.Ok());
// 正确槽位:Point2D + ExternalCurve2D → PointOnExternalCurve2D
auto ok = model.AddPointOnCurve2D("good", p1.Value(), c.Value());
ASSERT_TRUE(ok.Ok());
EXPECT_EQ(model.TotalRemovedDof(), 2);
}
// ---- P4-S1-02:直线与外部曲线相切 -----------------------------------------
namespace {
/// 直连相切约束求值的轻量上下文:直线 (φ, d) 2 参数 + 0-DOF 曲线
struct LineCurveModel {
vdcs::Line2D line;
ExternalCurve2D curve;
ParabolaAdapter adapter;
Eigen::VectorXd q;
std::unordered_map<Uid, int> offsets;
LineCurveModel(double phi, double d)
: line{GenerateUid(), phi, d}, curve{GenerateUid()},
adapter{curve.Id()} {
q.resize(2);
line.WriteParams(q.data());
offsets[line.Id()] = 0;
offsets[curve.Id()] = 2;
}
SolveContext Ctx() const {
return SolveContext{q.data(), 2, offsets, nullptr, &adapter};
}
};
/// 抛物线 C(t0) 处的真切线参数 (φ, d)(n = 单位法向,n·x = d)
std::pair<double, double> TrueTangentLine(double t0) {
const Vec2 c{4.0 * t0, 8.0 * t0 * t0};
const Vec2 tangent{4.0, 16.0 * t0};
const Vec2 n = Vec2{tangent.y, -tangent.x}.Normalized();
return {std::atan2(n.y, n.x), n.Dot(c)};
}
} // namespace
TEST(ExternalCurveTangentTest, ResidualZeroAtTrueTangentLine) {
const auto [phi, d] = TrueTangentLine(0.5);
LineCurveModel m{phi, d};
vdcs::TangentLineExternalCurve2D c{GenerateUid(), "T", m.line.Id(),
m.curve.Id()};
EXPECT_EQ(c.RemovedDof(), 1);
const Eigen::VectorXd r = c.Residual(m.Ctx());
EXPECT_NEAR(r[0], 0.0, 1e-12);
// 平移离开切线(仅改 d 参数):残差 = 平移量(横穿线非支撑线)
Eigen::VectorXd q_off = m.q;
q_off[1] += 0.5;
const Eigen::VectorXd r_off = c.Residual(
SolveContext{q_off.data(), 2, m.offsets, nullptr, &m.adapter});
EXPECT_NEAR(std::abs(r_off[0]), 0.5, 1e-9);
}
TEST(ExternalCurveTangentTest, SupportParameterFindsExtremum) {
const Uid curve = GenerateUid();
const ParabolaAdapter g{curve};
// f(t) = 4·n.x·t + 8·n.y·t²,抛物线凸:f' = 0 内点极小
// t* = −n.x/(4·n.y),取 n.x < 0 < n.y 保证 t* ∈ (0, 1)
const Vec2 n{-0.6, 0.8};
const double t = vdcs::SupportParameter(g, curve, n, -10.0);
const Vec2 d1 = g.Derivative(curve, t, 1);
EXPECT_NEAR(n.Dot(d1), 0.0, 1e-10); // 极值条件 n·C'(t*) = 0
EXPECT_NEAR(t, -n.x / (4.0 * n.y), 1e-9);
}
TEST(ExternalCurveTangentTest, JacobianAnalyticMatchesNumeric) {
const auto [phi0, d0] = TrueTangentLine(0.5);
// 非解处直线(远离切线),对拍链式项消失后的解析雅可比
LineCurveModel m{phi0 + 0.12, d0 - 0.3};
vdcs::TangentLineExternalCurve2D c{GenerateUid(), "T", m.line.Id(),
m.curve.Id()};
const Eigen::MatrixXd analytic = c.Jacobian(m.Ctx());
ASSERT_EQ(analytic.rows(), 1);
ASSERT_EQ(analytic.cols(), 2);
const double h = 1e-6;
for (int col = 0; col < 2; ++col) {
Eigen::VectorXd qp = m.q;
qp[col] += h;
const double rp = c.Residual(
SolveContext{qp.data(), 2, m.offsets, nullptr, &m.adapter})[0];
qp[col] -= 2.0 * h;
const double rm = c.Residual(
SolveContext{qp.data(), 2, m.offsets, nullptr, &m.adapter})[0];
EXPECT_NEAR(analytic(0, col), (rp - rm) / (2.0 * h), 1e-5)
<< "col=" << col;
}
}
TEST(ExternalCurveTangentTest, SolveWellConstrainedTangent) {
// 抛物线段 C(t)=(4t,8t²),点 P=(0,-0.5) 恰在 t*=0.25 切线(x0=1 切线
// y = x − 0.5)上:Fixed(P) + P∈L + L 相切曲线 = well(4−2−1−1=0)。
// 支撑式相切有端点支撑分支(如 y 轴 x=0 过端点 (0,0) 与 P)——分支
// 由初值选择(与圆相切内外切同语义),本用例初值取内点切线邻域
Model model;
auto p = model.AddPoint2D("P", 0.0, -0.5);
auto l = model.AddLine2D("L", 0.0, 0.0);
auto c = model.AddExternalCurve2D("host_spline");
(void)model.AddFixed2D("F", p.Value());
(void)model.AddPointOnCurve2D("PonL", p.Value(), l.Value());
auto t = model.AddTangent2D("T", l.Value(), c.Value());
ASSERT_TRUE(t.Ok());
EXPECT_EQ(model.TotalRemovedDof(), 4);
// 初值:真解切线 (φ0, d0) 小扰动(留在内点切线分支吸引域内)
const auto [phi0, d0] = TrueTangentLine(0.25);
double ld[2] = {phi0 + 0.05, d0 - 0.03};
model.FindEntity(l.Value())->ReadParams(ld);
model.SetGeometryAdapter(std::make_shared<ParabolaAdapter>(c.Value()));
auto report = model.Solve();
ASSERT_TRUE(report.Ok()) << report.Err().Message();
EXPECT_TRUE(report.Value().converged);
double solved[2] = {0.0, 0.0};
model.FindEntity(l.Value())->WriteParams(solved);
const ParabolaAdapter g{c.Value()};
const Vec2 n{std::cos(solved[0]), std::sin(solved[0])};
const double ts = vdcs::SupportParameter(g, c.Value(), n, solved[1]);
// 相切双条件:支撑点在直线上 + 切向⊥法向(内点驻点相切)
EXPECT_NEAR(n.Dot(g.Evaluate(c.Value(), ts)) - solved[1], 0.0, 1e-8);
EXPECT_NEAR(n.Dot(g.Derivative(c.Value(), ts, 1)), 0.0, 1e-6);
// 收敛到 t*=0.25 内点切线分支
EXPECT_NEAR(solved[0], phi0, 1e-6);
EXPECT_NEAR(solved[1], d0, 1e-6);
// JSON 往返:加载重注入 adapter 后保持收敛解(0 迭代)
TempPath tmp(".json");
ASSERT_TRUE(SaveModelJson(model, tmp.path).Ok());
auto loaded = LoadModelJson(tmp.path);
ASSERT_TRUE(loaded.Ok()) << loaded.Err().Message();
loaded.Value().SetGeometryAdapter(
std::make_shared<ParabolaAdapter>(c.Value()));
auto again = loaded.Value().Solve();
ASSERT_TRUE(again.Ok()) << again.Err().Message();
EXPECT_TRUE(again.Value().converged);
EXPECT_EQ(again.Value().iterations, 0);
}
TEST(ExternalCurveTangentTest, FactoryDispatchAndSlotRejection) {
Model model;
auto p = model.AddPoint2D("P", 0.0, 0.0);
auto l = model.AddLine2D("L", 0.0, 1.0);
auto c = model.AddExternalCurve2D("spline");
// 两个槽位方向都派发 TangentLineExternalCurve2D(与线-圆先例一致)
auto r1 = model.AddTangent2D("T1", l.Value(), c.Value());
ASSERT_TRUE(r1.Ok());
EXPECT_EQ(model.TotalRemovedDof(), 1);
auto r2 = model.AddTangent2D("T2", c.Value(), l.Value());
ASSERT_TRUE(r2.Ok());
EXPECT_EQ(model.TotalRemovedDof(), 2);
// 点不是直线:拒绝
auto bad = model.AddTangent2D("bad", p.Value(), c.Value());
EXPECT_FALSE(bad.Ok());
}