Sketch.cpp 2.63 KB
Newer Older
Jason Pries's avatar
Jason Pries committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include "Sketch.hpp"

Sketch::Sketch() {
    NumEquations = 0;
    NumVariables = 0;
    Boundary = new Contour();
}

void Sketch::solve() {
    // #TODO: Tolerance based iteration convergence monitoring
    // #TODO: Use sparse matrix representation for Jacobian

    Eigen::VectorXd delta = Eigen::VectorXd::Zero(NumVariables);
    Eigen::VectorXd r = Eigen::VectorXd::Zero(NumEquations);
    Eigen::VectorXd dr = Eigen::VectorXd::Zero(NumEquations);
    Eigen::MatrixXd J = Eigen::MatrixXd::Zero(NumEquations, NumVariables);
    Eigen::MatrixXd JJT = Eigen::MatrixXd::Zero(NumEquations, NumEquations);
    Eigen::FullPivLU<Eigen::MatrixXd> LU;

    for (size_t j = 0; j < 32; ++j) {
        // #TODO: Use QR or LDLT decomposition instead
        // #TODO: Check for over/underdetermined system
        // #TODO: Try extracting sub matrix and solving
        // #TODO: Extract newton_update over Verticies, Curves, and Constraints into a private method

        J.setZero();

        for (size_t i = 0; i < Verticies.size(); ++i) {
            Verticies[i]->update(J, r);
        }

        for (size_t i = 0; i < Curves.size(); ++i) {
            Curves[i]->update(J, r);
        }

        for (size_t i = 0; i < Constraints.size(); ++i) {
            Constraints[i]->update(J, r);
        }

        JJT = J * J.transpose();
        LU = JJT.fullPivLu();
        delta = J.transpose() * LU.solve(r);

        for (size_t i = 0; i < Variables.size(); ++i) {
            Variables[i]->update(delta);
        }
    }
}

bool Sketch::build() {
    Constellation c = Constellation(this);

    bool success = c.boundary(Boundary);

    Contours.resize(0);
    success = c.contours(Contours) && success;

    return success;
}

void Sketch::add_element(Vertex &v) {
    add_element(Verticies, v);
}

void Sketch::add_element(Curve &c) {
    add_element(Curves, c);
}

void Sketch::add_element(Constraint &c) {
    add_element(Constraints, c);
}

void Sketch::add_element(Pattern &p) {
    add_element(Patterns, p);
    p.register_elements(this);
}

template<>
void Sketch::save_as<SaveMethod::Rasterize>(std::string file_name) const {
    /*
        This is a stub for visualization
    */
    std::fstream fs;
    fs.open(file_name, std::fstream::out);
    for (size_t i = 0; i < Curves.size(); ++i) {
        if (!Curves[i]->ForConstruction) {
            for (size_t j = 0; j <= 10; ++j) {
                Vertex v = Curves[i]->point(j / 10.0);
                fs << v.x() << "," << v.y() << "\n";
            }
            fs << "NaN" << "," << "NaN" << "\n";
        }
    }
    fs.close();
}