43 #include <ilqgames/cost/polyline2_signed_distance_cost.h> 44 #include <ilqgames/cost/time_invariant_cost.h> 45 #include <ilqgames/geometry/polyline2.h> 46 #include <ilqgames/utils/types.h> 52 float Polyline2SignedDistanceCost::Evaluate(
const VectorXf& input)
const {
53 CHECK_LT(xidx_, input.size());
54 CHECK_LT(yidx_, input.size());
57 float signed_squared_distance;
58 polyline_.ClosestPoint(Point2(input(xidx_), input(yidx_)),
nullptr,
nullptr,
59 &signed_squared_distance);
60 if (!oriented_same_as_polyline_) signed_squared_distance *= -1.0;
62 return sgn(signed_squared_distance) *
63 std::sqrt(std::abs(signed_squared_distance)) -
67 void Polyline2SignedDistanceCost::Quadraticize(
const VectorXf& input,
69 VectorXf* grad)
const {
70 CHECK_LT(xidx_, input.size());
71 CHECK_LT(yidx_, input.size());
75 CHECK_EQ(input.size(), hess->rows());
76 CHECK_EQ(input.size(), hess->cols());
77 CHECK_EQ(input.size(), grad->size());
80 const Point2 current_position(input(xidx_), input(yidx_));
83 float signed_squared_distance;
84 LineSegment2 segment(Point2(0.0, 0.0), Point2(1.0, 1.0));
85 const Point2 closest_point = polyline_.ClosestPoint(
86 current_position, &is_vertex, &segment, &signed_squared_distance);
87 if (!oriented_same_as_polyline_) signed_squared_distance *= -1.0;
89 const float sign = sgn(signed_squared_distance);
90 const float distance = std::sqrt(std::abs(signed_squared_distance));
91 const float delta_x = current_position.x() - closest_point.x();
92 const float delta_y = current_position.y() - closest_point.y();
96 float dx = sign * delta_x / distance;
97 float dy = sign * delta_y / distance;
99 const float denom = signed_squared_distance * distance;
100 float ddx = delta_y * delta_y / denom;
101 float ddy = delta_x * delta_x / denom;
102 float dxdy = -delta_x * delta_y / denom;
105 const Point2& unit_segment = segment.UnitDirection();
107 dx = unit_segment.y();
108 dy = -unit_segment.x();
114 (*grad)(xidx_) += dx;
115 (*grad)(yidx_) += dy;
117 (*hess)(xidx_, xidx_) += ddx;
118 (*hess)(yidx_, yidx_) += ddy;
119 (*hess)(xidx_, yidx_) += dxdy;
120 (*hess)(yidx_, xidx_) += dxdy;