quadopt.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. /*
  2. * Copyright 2014 Google Inc. All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. *
  16. * Contributor: Raph Levien
  17. */
  18. #include <iostream>
  19. #include <fstream>
  20. #include <cmath>
  21. #include <vector>
  22. #include <algorithm>
  23. using std::vector;
  24. #define HALF_STEP 1
  25. class Point {
  26. public:
  27. Point() : x(0), y(0) { }
  28. Point(double x, double y) : x(x), y(y) { }
  29. double x, y;
  30. };
  31. bool operator==(const Point& p0, const Point& p1) {
  32. return p0.x == p1.x && p0.y == p1.y;
  33. }
  34. std::ostream& operator<<(std::ostream& os, const Point& p) {
  35. os << "(" << p.x << ", " << p.y << ")";
  36. return os;
  37. }
  38. double dist(Point p0, Point p1) {
  39. return std::hypot(p0.x - p1.x, p0.y - p1.y);
  40. }
  41. double dist2(Point p0, Point p1) {
  42. double dx = p0.x - p1.x;
  43. double dy = p0.y - p1.y;
  44. return dx * dx + dy * dy;
  45. }
  46. Point lerp(double t, Point p0, Point p1) {
  47. return Point(p0.x + t * (p1.x - p0.x), p0.y + t * (p1.y - p0.y));
  48. }
  49. Point unitize(Point p) {
  50. double scale = 1/std::hypot(p.x, p.y);
  51. return Point(p.x * scale, p.y * scale);
  52. }
  53. Point round(Point p) {
  54. return Point(std::round(p.x), std::round(p.y));
  55. }
  56. class Quad {
  57. public:
  58. Quad() : p() { }
  59. Quad(Point p0, Point p1, Point p2) : p() {
  60. p[0] = p0;
  61. p[1] = p1;
  62. p[2] = p2;
  63. }
  64. Point p[3];
  65. double arclen() const;
  66. Point eval(double t) const;
  67. bool isLine() const;
  68. void print(std::ostream& o) const {
  69. o << p[0].x << " " << p[0].y << " " << p[1].x << " " << p[1].y << " "
  70. << p[2].x << " " << p[2].y << std::endl;
  71. }
  72. };
  73. bool Quad::isLine() const {
  74. return p[1] == lerp(0.5, p[0], p[2]);
  75. }
  76. // One step of a 4th-order Runge-Kutta numerical integration
  77. template <size_t n, typename F>
  78. void rk4(double y[n], double x, double h, F& derivs) {
  79. double dydx[n];
  80. double dyt[n];
  81. double dym[n];
  82. double yt[n];
  83. derivs(dydx, x, y);
  84. double hh = h * .5;
  85. double h6 = h * (1./6);
  86. for (size_t i = 0; i < n; i++) {
  87. yt[i] = y[i] + hh * dydx[i];
  88. }
  89. derivs(dyt, x + hh, yt);
  90. for (size_t i = 0; i < n; i++) {
  91. yt[i] = y[i] + hh * dyt[i];
  92. }
  93. derivs(dym, x + hh, yt);
  94. for (size_t i = 0; i < n; i++) {
  95. yt[i] = y[i] + h * dym[i];
  96. dym[i] += dyt[i];
  97. }
  98. derivs(dyt, x + h, yt);
  99. for (size_t i = 0; i < n; i++) {
  100. y[i] += h6 * (dydx[i] + dyt[i] + 2 * dym[i]);
  101. }
  102. }
  103. class ArclenFunctor {
  104. public:
  105. ArclenFunctor(const Quad& q)
  106. : dx0(2 * (q.p[1].x - q.p[0].x))
  107. , dy0(2 * (q.p[1].y - q.p[0].y))
  108. , dx1(2 * (q.p[2].x - q.p[1].x))
  109. , dy1(2 * (q.p[2].y - q.p[1].y)) { }
  110. void operator()(double dydx[1], double t, const double y[1]) {
  111. Point p(deriv(t));
  112. dydx[0] = std::hypot(p.x, p.y);
  113. }
  114. Point deriv(double t) const {
  115. return Point(dx0 + t * (dx1 - dx0), dy0 + t * (dy1 - dy0));
  116. }
  117. private:
  118. double dx0, dy0, dx1, dy1;
  119. };
  120. double Quad::arclen() const {
  121. ArclenFunctor derivs(*this);
  122. const int n = 10;
  123. double dt = 1./n;
  124. double t = 0;
  125. double y[1] = { 0 };
  126. for (int i = 0; i < n; i++) {
  127. rk4<1>(y, t, dt, derivs);
  128. t += dt;
  129. }
  130. return y[0];
  131. }
  132. Point Quad::eval(double t) const {
  133. Point p01(lerp(t, p[0], p[1]));
  134. Point p12(lerp(t, p[1], p[2]));
  135. return lerp(t, p01, p12);
  136. }
  137. class Thetas {
  138. public:
  139. void init(const vector<Quad>& qs);
  140. Point xy(double s) const;
  141. Point dir(double s) const;
  142. double arclen;
  143. private:
  144. vector<Point> xys;
  145. vector<Point> dirs;
  146. };
  147. void Thetas::init(const vector<Quad>& qs) {
  148. xys.clear();
  149. dirs.clear();
  150. double s = 0;
  151. int ix = 0;
  152. Point lastxy;
  153. Point lastd;
  154. double lasts = -1;
  155. for (size_t i = 0; i < qs.size(); i++) {
  156. const Quad& q = qs[i];
  157. ArclenFunctor derivs(q);
  158. const int n = 100;
  159. double dt = 1./n;
  160. double t = 0;
  161. double y[1];
  162. y[0] = s;
  163. for (int j = 0; j < n; j++) {
  164. Point thisxy(q.eval(t));
  165. Point thisd(derivs.deriv(t));
  166. while (ix <= y[0]) {
  167. double u = (ix - lasts) / (y[0] - lasts);
  168. xys.push_back(lerp(u, lastxy, thisxy));
  169. dirs.push_back(unitize(lerp(u, lastd, thisd)));
  170. ix++;
  171. }
  172. lasts = y[0];
  173. rk4<1>(y, t, dt, derivs);
  174. t += dt;
  175. lastxy = thisxy;
  176. lastd = thisd;
  177. }
  178. s = y[0];
  179. }
  180. const Quad& q = qs[qs.size() - 1];
  181. Point thisxy(q.p[2]);
  182. Point thisd(ArclenFunctor(q).deriv(1));
  183. while (ix <= s + 1) {
  184. double u = (ix - lasts) / (s - lasts);
  185. xys.push_back(lerp(u, lastxy, thisxy));
  186. dirs.push_back(unitize(lerp(u, lastd, thisd)));
  187. ix++;
  188. }
  189. arclen = s;
  190. }
  191. Point Thetas::xy(double s) const {
  192. int bucket = (int)s;
  193. double frac = s - bucket;
  194. return lerp(frac, xys[bucket], xys[bucket + 1]);
  195. }
  196. Point Thetas::dir(double s) const {
  197. int bucket = (int)s;
  198. double frac = s - bucket;
  199. return lerp(frac, dirs[bucket], dirs[bucket + 1]);
  200. }
  201. #define NORM_LEVEL 2
  202. // L1 angle norm, 2, L2 angle norm, 0.05
  203. // L1 distance norm, 200
  204. double dist_factor = .005;
  205. double angle_factor = 5;
  206. class MeasureFunctor {
  207. public:
  208. MeasureFunctor(const Thetas& curve, double s0, double ss, const ArclenFunctor& af,
  209. Quad q)
  210. : curve(curve), s0(s0), ss(ss), af(af), q(q) { }
  211. void operator()(double dydx[2], double t, const double y[2]) {
  212. Point dxy(af.deriv(t));
  213. dydx[0] = std::hypot(dxy.x, dxy.y);
  214. // distance error
  215. Point curvexy = curve.xy(s0 + y[0] * ss);
  216. #if NORM_LEVEL == 1
  217. double disterr = dist(q.eval(t), curvexy);
  218. #endif
  219. #if NORM_LEVEL == 2
  220. double disterr = dist2(q.eval(t), curvexy);
  221. #endif
  222. disterr *= dydx[0];
  223. // angle error
  224. Point dir = curve.dir(s0 + y[0] * ss);
  225. double angleerr = dir.x * dxy.y - dir.y * dxy.x;
  226. #if NORM_LEVEL == 1
  227. angleerr = std::abs(angleerr);
  228. #endif
  229. #if NORM_LEVEL == 2
  230. angleerr = (angleerr * angleerr) / dydx[0];
  231. #endif
  232. dydx[1] = dist_factor * disterr + angle_factor * angleerr;
  233. }
  234. private:
  235. const Thetas& curve;
  236. double s0;
  237. double ss;
  238. const ArclenFunctor& af;
  239. Quad q;
  240. };
  241. // measure how closely the quad fits the section of curve, using L1 norm
  242. // of angle mismatch
  243. double measureQuad(const Thetas& curve, double s0, double s1, const Quad& q) {
  244. ArclenFunctor derivs(q);
  245. double ss = 0;
  246. if (q.arclen() != 0)
  247. ss = (s1 - s0) / q.arclen();
  248. MeasureFunctor err(curve, s0, ss, derivs, q);
  249. const int n = 10;
  250. double dt = 1./n;
  251. double t = 0;
  252. double y[2] = { 0, 0 };
  253. for (int i = 0; i < n; i++) {
  254. rk4<2>(y, t, dt, err);
  255. t += dt;
  256. }
  257. return y[1];
  258. }
  259. struct Break {
  260. Break(double s, Point xy, Point dir) : s(s), xy(xy), dir(dir) { }
  261. double s;
  262. Point xy;
  263. Point dir;
  264. };
  265. struct Statelet {
  266. void combine(const Statelet* prev, double score, Quad q, double penalty);
  267. const Statelet* prev;
  268. double score;
  269. Quad q;
  270. };
  271. void Statelet::combine(const Statelet* newprev, double newscore, Quad newq, double penalty) {
  272. prev = newprev;
  273. double pmul = 2;
  274. if (newq.isLine()) {
  275. pmul = 1;
  276. } else if (newprev != 0 && !newprev->q.isLine()
  277. && lerp(0.5, newprev->q.p[1], newq.p[1]) == newq.p[0]) {
  278. pmul = 1;
  279. }
  280. score = (newprev == 0 ? 0 : newprev->score) + penalty * pmul + newscore;
  281. q = newq;
  282. }
  283. struct State {
  284. void combine(const State* prev, double score, Quad q, double penalty);
  285. vector<Statelet> sts;
  286. bool init;
  287. };
  288. void State::combine(const State* prev, double score, Quad q, double penalty) {
  289. const Statelet* prevsl = prev->sts.empty() ? 0 : &prev->sts[0];
  290. if (prevsl == 0 && !prev->init) {
  291. return;
  292. }
  293. Statelet sl;
  294. sl.combine(prevsl, score, q, penalty);
  295. if (sts.empty()) {
  296. sts.push_back(sl);
  297. } else {
  298. if (sl.score < sts[0].score) {
  299. sts[0] = sl;
  300. }
  301. }
  302. }
  303. bool isInt(double x) {
  304. return x == (int) x;
  305. }
  306. bool okForHalf(const State* prev, Quad q) {
  307. if (isInt(q.p[0].x) && isInt(q.p[0].y)) {
  308. return true;
  309. }
  310. if (q.isLine()) {
  311. return false;
  312. }
  313. const Statelet* prevsl = prev->sts.empty() ? 0 : &prev->sts[0];
  314. if (prevsl == 0 || prevsl->q.isLine()) {
  315. return false;
  316. }
  317. return lerp(0.5, prevsl->q.p[1], q.p[1]) == q.p[0];
  318. }
  319. void findBreaks(vector<Break>* breaks, const Thetas& curve) {
  320. breaks->clear();
  321. double lastd;
  322. int n = round(10 * curve.arclen);
  323. for (int i = 0; i <= n; i++) {
  324. double s = curve.arclen * i / n;
  325. Point origp = curve.xy(s);
  326. #if HALF_STEP
  327. Point p(.5 * std::round(2 * origp.x), .5 * std::round(2 * origp.y));
  328. #else
  329. Point p = round(origp);
  330. #endif
  331. double d = dist(p, origp);
  332. if (i == 0 || !(p == (*breaks)[breaks->size() - 1].xy)) {
  333. Break bk(s, p, curve.dir(s));
  334. breaks->push_back(bk);
  335. lastd = d;
  336. } else if (d < lastd) {
  337. (*breaks)[breaks->size() - 1] = Break(s, p, curve.dir(s));
  338. lastd = d;
  339. }
  340. }
  341. }
  342. bool intersect(Point* result, Point p0, Point dir0, Point p1, Point dir1) {
  343. double det = dir0.x * dir1.y - dir0.y * dir1.x;
  344. if (std::abs(det) < 1e-6 || std::isnan(det)) return false;
  345. det = 1 / det;
  346. double a = p0.y * dir0.x - p0.x * dir0.y;
  347. double b = p1.y * dir1.x - p1.x * dir1.y;
  348. result->x = (a * dir1.x - b * dir0.x) * det;
  349. result->y = (a * dir1.y - b * dir0.y) * det;
  350. return true;
  351. }
  352. void tryQuad(const State* prev, State* st, const Thetas& curve,
  353. const Break& bk0, const Break& bk1, const Quad& q, double penalty) {
  354. double score = measureQuad(curve, bk0.s, bk1.s, q);
  355. st->combine(prev, score, q, penalty);
  356. }
  357. void tryLineQuad(const State* prev, State* st, const Thetas& curve,
  358. const Break& bk0, const Break& bk1, double penalty) {
  359. if (isInt(bk0.xy.x) && isInt(bk0.xy.y)) {
  360. Quad line(bk0.xy, lerp(0.5, bk0.xy, bk1.xy), bk1.xy);
  361. tryQuad(prev, st, curve, bk0, bk1, line, penalty);
  362. }
  363. Point pmid;
  364. if (intersect(&pmid, bk0.xy, bk0.dir, bk1.xy, bk1.dir)) {
  365. Quad q(bk0.xy, round(pmid), bk1.xy);
  366. if (okForHalf(prev, q)) {
  367. tryQuad(prev, st, curve, bk0, bk1, q, penalty);
  368. }
  369. }
  370. }
  371. vector<Quad> optimize(const Thetas& curve, double penalty=1) {
  372. vector<Break> breaks;
  373. findBreaks(&breaks, curve);
  374. int n = breaks.size() - 1;
  375. vector<State> states;
  376. states.resize(n + 1);
  377. states[0].init = true;
  378. tryLineQuad(&states[0], &states[n], curve, breaks[0], breaks[n], penalty);
  379. if (states[n].sts[0].score <= 3 * penalty) {
  380. goto done;
  381. }
  382. for (int i = 1; i < n; i++) {
  383. tryLineQuad(&states[0], &states[i], curve, breaks[0], breaks[i], penalty);
  384. tryLineQuad(&states[i], &states[n], curve, breaks[i], breaks[n], penalty);
  385. }
  386. if (states[n].sts[0].score <= 4 * penalty) {
  387. goto done;
  388. }
  389. for (int i = 1; i <= n; i++) {
  390. for (int j = i - 1; j >= 0; j--) {
  391. tryLineQuad(&states[j], &states[i], curve, breaks[j], breaks[i], penalty);
  392. }
  393. }
  394. done:
  395. vector<Quad> result;
  396. for (const Statelet* sl = &states[n].sts[0]; sl != 0; sl = sl->prev) {
  397. result.push_back(sl->q);
  398. }
  399. std::reverse(result.begin(), result.end());
  400. return result;
  401. }
  402. void readBzs(vector<Quad>* result, std::istream& is) {
  403. double x0, y0, x1, y1, x2, y2;
  404. while (is >> x0 >> y0 >> x1 >> y1 >> x2 >> y2) {
  405. result->push_back(Quad(Point(x0, y0), Point(x1, y1), Point(x2, y2)));
  406. }
  407. // Round the endpoints, they must be on integers
  408. result->front().p[0] = round(result->front().p[0]);
  409. result->back().p[2] = round(result->back().p[2]);
  410. }
  411. int main(int argc, char** argv) {
  412. if (argc != 3) {
  413. std::cerr << "usage: quadopt in out\n";
  414. return 1;
  415. }
  416. #if 0
  417. Quad q(Point(100, 0), Point(0, 0), Point(0, 100));
  418. std::cout.precision(8);
  419. std::cout << q.arclen() << "\n";
  420. #endif
  421. vector<Quad> bzs;
  422. std::ifstream is;
  423. is.open(argv[1]);
  424. readBzs(&bzs, is);
  425. Thetas thetas;
  426. thetas.init(bzs);
  427. #if 0
  428. for (int i = 0; i < thetas.arclen; i++) {
  429. Point xy = thetas.dir(i);
  430. std::cout << xy.x << " " << xy.y << std::endl;
  431. }
  432. #endif
  433. vector<Quad> optbzs = optimize(thetas);
  434. std::ofstream os;
  435. os.open(argv[2]);
  436. for (size_t i = 0; i < optbzs.size(); i++) {
  437. optbzs[i].print(os);
  438. }
  439. return 0;
  440. }