-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInterpolation.cpp
More file actions
133 lines (103 loc) · 2.83 KB
/
Interpolation.cpp
File metadata and controls
133 lines (103 loc) · 2.83 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#include "defGameEngine.hpp"
// L(x) = sum(k=0..n, y_k * l_k(x))
// l_k(x) = prod(j=0..n, k!=j, (x-x_j)/(x_k-x_j))
float Lagrange_Basis(float x, int k, const std::vector<def::Vector2f>& points)
{
float prod = 1.0f;
for (int j = 0; j < points.size(); j++)
{
if (k != j)
prod *= (x - points[j].x) / (points[k].x - points[j].x);
}
return prod;
}
float Lagrange_Polynome(float x, const std::vector<def::Vector2f>& points)
{
float sum = 0.0f;
for (int k = 0; k < points.size(); k++)
sum += points[k].y * Lagrange_Basis(x, k, points);
return sum;
}
class App : public def::GameEngine
{
public:
App()
{
GetWindow()->SetTitle("Lagrange");
}
private:
std::vector<def::Vector2f> m_Points;
std::vector<def::Vector2i> m_Polynome;
def::Vector2f* m_Control = nullptr;
protected:
int SearchPoint(const def::Vector2i& pos)
{
for (int i = 0; i < m_Points.size(); i++)
{
if (def::Vector2i(m_Points[i]) == pos)
return i;
}
return -1;
}
void UpdatePolynome()
{
std::ranges::sort(m_Points, [](def::Vector2f& p1, def::Vector2f& p2) { return p1.x < p2.x; });
int start = m_Points.front().x;
int end = m_Points.back().x;
m_Polynome.clear();
int i = 0;
for (int x = start; x <= end; x++, i++)
{
int y = Lagrange_Polynome(x, m_Points);
m_Polynome.push_back({ x, y });
}
}
bool OnUserCreate() override
{
return true;
}
bool OnUserUpdate(float deltaTime) override
{
auto inp = GetInput();
if (inp->GetButtonState(def::Button::LEFT).pressed)
{
m_Points.push_back(inp->GetMousePosition());
if (m_Points.size() >= 2)
UpdatePolynome();
}
if (inp->GetKeyState(def::Key::LEFT_SHIFT).pressed)
{
int i = SearchPoint(inp->GetMousePosition());
if (i != -1)
{
m_Control = &m_Points[i]; // dangerous but OK!
UpdatePolynome();
}
}
if (inp->GetKeyState(def::Key::LEFT_SHIFT).held)
{
if (m_Control)
{
*m_Control = inp->GetMousePosition();
UpdatePolynome();
}
}
if (inp->GetKeyState(def::Key::LEFT_SHIFT).released)
m_Control = nullptr;
Clear(def::BLACK);
if (m_Polynome.size() >= 2)
{
for (int i = 1; i < m_Polynome.size(); i++)
DrawLine(m_Polynome[i - 1], m_Polynome[i], def::WHITE);
}
for (const auto& p : m_Points)
Draw(p, def::RED);
return true;
}
};
int main()
{
App app;
if (app.Construct(160, 100, 8, 8))
app.Run();
}