-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathLsystem.cpp
273 lines (253 loc) · 9.64 KB
/
Lsystem.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
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
// This is an independent project of an individual developer. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
#include "Lsystem.h"
#include "Cmd.h"
#include "Lexer.h"
#include "Parser.h"
#include "Rule.h"
#include "Token.h"
#include <fstream>
#include <memory>
#include <stdexcept>
#include <string>
using std::ifstream;
using std::make_unique;
using std::runtime_error;
using std::string_view;
using std::vector;
using std::string;
void assertdatatoken(const Token &t) {
if (t.iseof()) throw runtime_error("Unexpected end of file");
if (t.iseol()) throw runtime_error("Unexpected end of line");
}
namespace {
Commands readrule(Lexer &lex) {
Commands retval;
Token t = lex.nexttoken();
while (!t.iseol()) {
assertdatatoken(t);
if (t.getdata() == "left") {
t = lex.nexttoken();
assertdatatoken(t);
retval.push_back(make_unique<RotateCommand>(parse(t)));
} else if (t.getdata() == "right") {
t = lex.nexttoken();
assertdatatoken(t);
retval.push_back(make_unique<RotateCommand>(parse("-(" + t.getdata() + ")")));
} else if (t.getdata() == "+")
retval.push_back(make_unique<RotateCommand>(parse("$angle")));
else if (t.getdata() == "-")
retval.push_back(make_unique<RotateCommand>(parse("-$angle")));
else if (t.getdata() == "|" || t.getdata() == "flip")
retval.push_back(make_unique<FlipCommand>());
else if (t.getdata() == "[" || t.getdata() == "push")
retval.push_back(make_unique<PushCommand>());
else if (t.getdata() == "]" || t.getdata() == "pop")
retval.push_back(make_unique<PopCommand>());
else { //A rule
bool rev = false;
bool flip = false;
string_view thisrule = t.getdata();
while (thisrule[0] == '~' || thisrule[0] == '|' || thisrule[0] == '_') {
if (thisrule[0] == '~' || thisrule[0] == '_')
rev = !rev;
if (thisrule[0] == '~' || thisrule[0] == '|')
flip = !flip;
thisrule.remove_prefix(1);
}
if (thisrule[thisrule.length() - 1] == '@') {
thisrule.remove_suffix(1);
auto localScale = lex.nexttoken();
assertdatatoken(localScale);
retval.push_back(make_unique<RuleCommand>(string(thisrule), rev, flip, parse(localScale.getdata())));
} else
retval.push_back(make_unique<RuleCommand>(string(thisrule), rev, flip));
}
t = lex.nexttoken();
}
return retval;
}
}//end anonymous namespace
Lsystem::Lsystem(string_view name, Lexer &lex) {
_name = name;
auto t = lex.nexttoken();
while (t.isdata()) {
if (t.getdata() == "inactive") {
active = false;
t = lex.nexttoken();
} else
throw runtime_error("Unrecognized option after system name: " + _name);
}
if (t.iseof())
throw runtime_error("Unexpected end of file during " + _name);
// t is EOL
t = lex.nexttoken();
while (t.isdata()) //read (rule, rule option, or expression) line
{
std::string rulename = t.getdata();
try {
if (rulename[0] == '$') {
t = lex.nexttoken();
assertdatatoken(t);
if (t.getdata() != "=")
throw runtime_error("Expected '='");
t = lex.nexttoken();
assertdatatoken(t);
expressions[rulename] = parse(t);
t = lex.nexttoken();
if (t.isdata())
throw runtime_error("Unexpected additional characters " + t.getdata());
} else if (rulename == "system") {
t = lex.nexttoken();
assertdatatoken(t);
if (t.getdata() != "?")
throw runtime_error("Expected '?' after keyword 'system'");
readSystemOptions(lex);
} else {
if (startrule.empty())
startrule = rulename;
t = lex.nexttoken();
assertdatatoken(t);
if (t.getdata() == ":")
_rules[rulename].setcmds(readrule(lex));
else if (t.getdata() == "?")
_rules[rulename].readruleoptions(lex);
else
throw runtime_error("Expected option line or rule definition");
}
} catch (runtime_error &error) {
throw runtime_error(std::string(error.what()).append(" in ").append(_name).append(" rule ").append(rulename));
}
t = lex.nexttoken();
}
if(_drawStrategyToken._name.empty())
_drawStrategyToken._name = "normal"; //!!!Use empty for normal?
if(expressions.find("$angle") == expressions.end())
expressions["$angle"] = parse("90");
}
vector<Lsystem> readlsystemfile(const std::string &configfilename) {
ifstream in(configfilename);
if (!in) {
in.clear();
in.open("../" + configfilename);
}
if (!in)
throw runtime_error("Couldn't open file " + configfilename);
Lexer lex(in);
vector<Lsystem> thelsystems;
while (true) {
//!!! Should be able to clean up this loop
//I don't like reading the name, then calling the constructor
//Some sort of builder pattern? I don't know
Token t;
do
t = lex.nexttoken();
while (t.iseol()); //get a non EOL token
if (t.iseof()) {
if (thelsystems.empty())
throw runtime_error("No L systems in file " + configfilename);
return thelsystems;
}
thelsystems.emplace_back(t.getdata(),lex);
}
}
void Lsystem::readSystemOptions(Lexer &lex) {
for (auto t = lex.nexttoken(); t.isdata(); t = lex.nexttoken()) {
if (t.getdata() == "drawmethod") {
t = lex.nexttoken();
assertdatatoken(t);
_drawStrategyToken._name = t.getdata();
_drawStrategyToken._parameters.clear();
if (_drawStrategyToken._name == "drop") {
t = lex.nexttoken();
assertdatatoken(t);
_drawStrategyToken._parameters.push_back(t.getdata());
t = lex.nexttoken();
assertdatatoken(t);
_drawStrategyToken._parameters.push_back(t.getdata());
//!!! continue
}
else if (_drawStrategyToken._name == "normal")
;
// else if (t.getdata() == "rectangle")
// ...
else if (_drawStrategyToken._name == "midpoint") {
_drawStrategyToken._name = "drop";
_drawStrategyToken._parameters.emplace_back("0.0");
_drawStrategyToken._parameters.emplace_back("1.0/2.0");
} else
throw std::runtime_error("Unexpected draw method " + t.getdata());
} else if (t.getdata() == "info") {
t = lex.nexttoken();
assertdatatoken(t);
_info = t.getdata();
} else if (t.getdata() == "rotationsteps") {
t = lex.nexttoken();
assertdatatoken(t);
expressions["$angle"] = parse("360/"+t.getdata());
} else if (t.getdata() == "rotationangle") {
t = lex.nexttoken();
assertdatatoken(t);
expressions["$angle"] = parse(t.getdata());
}
else throw runtime_error("Unexpected system option: " + t.getdata());
}
}
const std::string& Lsystem::getname() const {
return _name;
}
bool Lsystem::isactive() const {
return active;
}
const Exprtype & Lsystem::getExpressions() const {
return expressions;
}
const Ruletable & Lsystem::getRules() const {
return _rules;
}
const string & Lsystem::startRule() const {
return startrule;
}
DrawStrategyToken Lsystem::getDrawStrategyToken() const {
return _drawStrategyToken;
}
void Lsystem::fixRules(const Context &context) {
DrawStrategy drawStrategy;
for(auto & [name,rule] : _rules) {
if(!rule.shouldFix())
continue;
if(rule.isFixed()) {
rule._commands.pop_front();
rule._commands.pop_back();
}
rule._localScale = 1.0;
draw(1,drawStrategy,name);
auto endPoint = drawStrategy.getPosition();
auto distanceSqr = endPoint.x*endPoint.x+endPoint.y*endPoint.y;
if( distanceSqr < 0.01)
continue; //!!!possibly still want to fix turtle angle here?
rule._localScale = 1.0/sqrt(distanceSqr);
rule._localScaleExpression = parse(std::to_string(rule._localScale));
auto angleWent = atan2(endPoint.y,endPoint.x)/DEG2RAD;
rule._commands.push_front(make_unique<RotateCommand>(parse(std::to_string(-angleWent))));
rule._commands.front()->evaluateExpressions(context);
auto endTurtleAngle = drawStrategy.getAngle();
rule._commands.push_back(make_unique<RotateCommand>(parse(std::to_string(angleWent-endTurtleAngle))));
rule._commands.back()->evaluateExpressions(context);
rule._isFixed = true;
}
}
void Lsystem::evaluateExpressions(const Context &context) {
for (auto & [name,rule] : _rules)
rule.evaluateExpressions(context);
fixRules(context);
}
void Lsystem::draw(int level, DrawStrategy & drawStrategy) const {
draw(level, drawStrategy, startrule);
}
void Lsystem::draw(int level, DrawStrategy & drawStrategy, std::string_view name) const {
drawStrategy.reset();
drawStrategy.start();
RuleCommand::run(name,_rules,drawStrategy,level);
drawStrategy.finish();
}