-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathline.cpp
More file actions
115 lines (94 loc) · 2.7 KB
/
Copy pathline.cpp
File metadata and controls
115 lines (94 loc) · 2.7 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
/**
* @file line.cpp
* Implementation of the Line class.
*/
#include "line.h"
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <vector>
using std::vector;
using cs225::PNG;
using cs225::HSLAPixel;
vector<double> Line::linearInterpolation(const Vector2& a, const Vector2& b)
{
/* http://gabrielongraphics.blogspot.com/2005/09/drawing-line-segments.html */
vector<double> values;
const int num_steps = abs(static_cast<int>(b.x() - a.x()));
if (num_steps == 0) {
values.push_back(a.y());
} else {
const double slope = (b.y() - a.y()) / num_steps;
double y = a.y();
for (int i = 0; i < num_steps; i++) {
values.push_back(y);
y += slope;
}
}
return values;
}
Line::Line(const Vector2& pa, const Vector2& pb, const HSLAPixel& pcolor)
: a_(pa), b_(pb), color_(pcolor)
{
/* Nothing see initialization list. */
}
void Line::draw(PNG* canvas) const
{
/* http://gabrielongraphics.blogspot.com/2005/09/drawing-line-segments.html */
const double delta_x = abs(static_cast<int>(b_.x() - a_.x()));
const double delta_y = abs(static_cast<int>(b_.y() - a_.y()));
// HSLAPixel* pixel;
if (delta_x > delta_y) {
const Vector2* left = &a_;
const Vector2* right = &b_;
if (a_.isEastOf(b_)) {
left = &b_;
right = &a_;
}
vector<double> y_values = linearInterpolation(*left, *right);
for (int x = static_cast<int>(left->x()); x < static_cast<int>(right->x()); x++) {
const int y = static_cast<int>(y_values[static_cast<int>(x - left->x())]);
HSLAPixel &pixel = (canvas->getPixel(x, y));
pixel = this->color();
}
} else {
const Vector2* small = &a_;
const Vector2* large = &b_;
if (a_.y() > b_.y()) {
small = &b_;
large = &a_;
}
const Vector2 flipped0(small->y(), small->x());
const Vector2 flipped1(large->y(), large->x());
vector<double> x_values = linearInterpolation(flipped0, flipped1);
for (int y = static_cast<int>(small->y()); y < static_cast<int>(large->y()); y++) {
const int x = static_cast<int>(x_values[static_cast<int>(y - small->y())]);
HSLAPixel & pixel = (canvas->getPixel(x, y));
pixel = this->color();
}
}
}
Vector2 Line::a() const
{
return this->a_;
}
void Line::set_a(const Vector2& pa)
{
this->a_ = pa;
}
Vector2 Line::b() const
{
return this->b_;
}
void Line::set_b(const Vector2& pb)
{
this->b_ = pb;
}
HSLAPixel Line::color() const
{
return this->color_;
}
void Line::set_color(const HSLAPixel& pcolor)
{
this->color_ = pcolor;
}