-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathswitch_device.cpp
98 lines (87 loc) · 2.68 KB
/
switch_device.cpp
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
#include "device.h"
std::string SwitchDevice::name(void) {
return "SwitchDevice";
}
Device *SwitchDevice::create(void) {
return new SwitchDevice();
}
std::string SwitchDevice::prefix(void) {
return "switch";
}
// A valid SwitchDevice is white if on, black if off.
bool SwitchDevice::sub_parse(AspngSurface *surface, int32_t min_x, int32_t min_y, int32_t max_x, int32_t max_y, std::string param) {
if (param != "") {
return false;
}
enum {
On,
Off,
Unknown
} switch_state = Unknown;
for (int32_t x = min_x; x <= max_x; x++) {
for (int32_t y = min_y; y <= max_y; y++) {
Rgb pixel = surface->get_pixel(x, y);
switch (switch_state) {
case On:
if (pixel != Rgb(0xff, 0xff, 0xff)) {
return false;
}
this->closed = true;
break;
case Off:
if (pixel != Rgb(0, 0, 0)) {
return false;
}
this->closed = false;
break;
case Unknown:
if (pixel == Rgb(0xff, 0xff, 0xff)) {
switch_state = On;
} else if (pixel == Rgb(0, 0, 0)) {
switch_state = Off;
} else {
return false;
}
break;
}
this->sub_patch.insert(Coord(x, y));
}
}
return switch_state != Unknown;
}
bool SwitchDevice::link(void) {
return true;
}
std::list<std::shared_ptr<Port>> SwitchDevice::propagate(std::shared_ptr<Port> port) {
if (this->closed) {
std::list<std::shared_ptr<Port>> next_ports = this->all_ports();
next_ports.remove(port);
return next_ports;
} else {
std::list<std::shared_ptr<Port>> empty;
return empty;
}
}
ElectricalValue SwitchDevice::get_value_at_port(std::shared_ptr<Port>) {
return EmptyElectricalValue;
}
void SwitchDevice::apply_new_value(std::shared_ptr<Port>, ElectricalValue) {
// Deliberately empty.
}
std::list<Patch *> SwitchDevice::sub_patches(void) {
std::list<Patch *> sub_patches;
sub_patches.push_back(&(this->sub_patch));
return sub_patches;
}
// White if closed, black otherwise.
void SwitchDevice::sub_draw(AspngSurface *surface, int32_t min_x, int32_t min_y, int32_t max_x, int32_t max_y) {
Rgb color = this->closed ? Rgb(0xff, 0xff, 0xff) : Rgb(0, 0, 0);
for (int32_t x = min_x; x <= max_x; x++) {
for (int32_t y = min_y; y <= max_y; y++) {
surface->set_pixel(x, y, color);
}
}
}
void SwitchDevice::click(Coord) {
this->closed = !this->closed;
}