-
-
Notifications
You must be signed in to change notification settings - Fork 557
/
Copy pathgcodepreprocessorutils.cpp
539 lines (445 loc) · 15.2 KB
/
gcodepreprocessorutils.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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
// This file is a part of "grblControl" application.
// This file was originally ported from "GcodePreprocessorUtils.java" class
// of "Universal GcodeSender" application written by Will Winder
// (https://github.com/winder/Universal-G-Code-Sender)
// Copyright 2015 Hayrullin Denis Ravilevich
#include <QRegExp>
#include <QDebug>
#include <QVector3D>
#include "gcodepreprocessorutils.h"
#include "math.h"
#include "limits"
/**
* Searches the command string for an 'f' and replaces the speed value
* between the 'f' and the next space with a percentage of that speed.
* In that way all speed values become a ratio of the provided speed
* and don't get overridden with just a fixed speed.
*/
QString GcodePreprocessorUtils::overrideSpeed(QString command, double speed, double *original)
{
QRegExp re("[Ff]([0-9.]+)");
if (re.indexIn(command) != -1) {
command.replace(re, QString("F%1").arg(re.cap(1).toDouble() / 100 * speed));
if (original) *original = re.cap(1).toDouble();
}
return command;
}
/**
* Removes any comments within parentheses or beginning with a semi-colon.
*/
QString GcodePreprocessorUtils::removeComment(QString command)
{
// Remove any comments within ( parentheses ) using regex "\([^\(]*\)"
command.replace(QRegExp("\\(+[^\\(]*\\)+"), "");
// Remove any comment beginning with ';' using regex ";.*"
command.replace(QRegExp(";.*"), "");
return command.trimmed();
}
/**
* Searches for a comment in the input string and returns the first match.
*/
QString GcodePreprocessorUtils::parseComment(QString command)
{
// REGEX: Find any comment, includes the comment characters:
// "(?<=\()[^\(\)]*|(?<=\;)[^;]*"
// "(?<=\\()[^\\(\\)]*|(?<=\\;)[^;]*"
QRegExp re("(\\([^\\(\\)]*\\)|;[^;].*)");
if (re.indexIn(command) != -1) {
return re.cap(1);
}
return "";
}
QString GcodePreprocessorUtils::truncateDecimals(int length, QString command)
{
QRegExp re("(\\d*\\.\\d*)");
int pos = 0;
while ((pos = re.indexIn(command, pos)) != -1)
{
QString newNum = QString::number(re.cap(1).toDouble(), 'f', length);
command = command.left(pos) + newNum + command.mid(pos + re.matchedLength());
pos += newNum.length() + 1;
}
return command;
}
QString GcodePreprocessorUtils::removeAllWhitespace(QString command)
{
return command.replace(QRegExp("\\s"),"");
}
QList<QString> GcodePreprocessorUtils::parseCodes(QList<QString> args, char code)
{
QList<QString> l;
foreach (QString s, args) {
if (s.length() > 0 && s[0].toUpper() == code) l.append(s.mid(1));
}
return l;
}
QList<int> GcodePreprocessorUtils::parseGCodes(QString command)
{
QRegExp re("[Gg]0*(\\d+)");
QList<int> codes;
int pos = 0;
while ((pos = re.indexIn(command, pos)) != -1) {
codes.append(re.cap(1).toInt());
pos += re.matchedLength();
}
return codes;
}
QList<int> GcodePreprocessorUtils::parseMCodes(QString command)
{
QRegExp re("[Mm]0*(\\d+)");
QList<int> codes;
int pos = 0;
while ((pos = re.indexIn(command, pos)) != -1) {
codes.append(re.cap(1).toInt());
pos += re.matchedLength();
}
return codes;
}
/**
* Update a point given the arguments of a command.
*/
QVector3D GcodePreprocessorUtils::updatePointWithCommand(QString command, QVector3D initial, bool absoluteMode)
{
QList<QString> l = splitCommand(command);
return updatePointWithCommand(l, initial, absoluteMode);
}
/**
* Update a point given the arguments of a command, using a pre-parsed list.
*/
QVector3D GcodePreprocessorUtils::updatePointWithCommand(QList<QString> commandArgs, QVector3D initial, bool absoluteMode)
{
double x = NAN;
double y = NAN;
double z = NAN;
char c;
for (int i = 0; i < commandArgs.length(); i++) {
// foreach (QString t, commandArgs)
// {
if (commandArgs[i].length() > 0) {
c = commandArgs[i][0].toUpper().toLatin1();
switch (c) {
case 'X':
x = commandArgs[i].mid(1).toDouble();
break;
case 'Y':
y = commandArgs[i].mid(1).toDouble();
break;
case 'Z':
z = commandArgs[i].mid(1).toDouble();
break;
}
}
}
return updatePointWithCommand(initial, x, y, z, absoluteMode);
}
/**
* Update a point given the new coordinates.
*/
QVector3D GcodePreprocessorUtils::updatePointWithCommand(QVector3D initial, double x, double y, double z, bool absoluteMode)
{
QVector3D newPoint(initial.x(), initial.y(), initial.z());
if (absoluteMode) {
if (!std::isnan(x)) newPoint.setX(x);
if (!std::isnan(y)) newPoint.setY(y);
if (!std::isnan(z)) newPoint.setZ(z);
} else {
if (!std::isnan(x)) newPoint.setX(newPoint.x() + x);
if (!std::isnan(y)) newPoint.setY(newPoint.y() + y);
if (!std::isnan(z)) newPoint.setZ(newPoint.z() + z);
}
return newPoint;
}
QVector3D GcodePreprocessorUtils::updateCenterWithCommand(QList<QString> commandArgs, QVector3D initial, QVector3D nextPoint, bool absoluteIJKMode, bool clockwise)
{
double i = NAN;
double j = NAN;
double k = NAN;
double r = NAN;
char c;
foreach (QString t, commandArgs)
{
if (t.length() > 0) {
c = t[0].toUpper().toLatin1();
switch (c) {
case 'I':
i = t.mid(1).toDouble();
break;
case 'J':
j = t.mid(1).toDouble();
break;
case 'K':
k = t.mid(1).toDouble();
break;
case 'R':
r = t.mid(1).toDouble();
break;
}
}
}
if (std::isnan(i) && std::isnan(j) && std::isnan(k)) {
return convertRToCenter(initial, nextPoint, r, absoluteIJKMode, clockwise);
}
return updatePointWithCommand(initial, i, j, k, absoluteIJKMode);
}
QString GcodePreprocessorUtils::generateG1FromPoints(QVector3D start, QVector3D end, bool absoluteMode, int precision)
{
QString sb("G1");
if (absoluteMode) {
if (!std::isnan(end.x())) sb.append("X" + QString::number(end.x(), 'f', precision));
if (!std::isnan(end.y())) sb.append("Y" + QString::number(end.y(), 'f', precision));
if (!std::isnan(end.z())) sb.append("Z" + QString::number(end.z(), 'f', precision));
} else {
if (!std::isnan(end.x())) sb.append("X" + QString::number(end.x() - start.x(), 'f', precision));
if (!std::isnan(end.y())) sb.append("Y" + QString::number(end.y() - start.y(), 'f', precision));
if (!std::isnan(end.z())) sb.append("Z" + QString::number(end.z() - start.z(), 'f', precision));
}
return sb;
}
///**
//* Splits a gcode command by each word/argument, doesn't care about spaces.
//* This command is about the same speed as the string.split(" ") command,
//* but might be a little faster using precompiled regex.
//*/
QList<QString> GcodePreprocessorUtils::splitCommand(QString command) {
QList<QString> l;
bool readNumeric = false;
QString sb;
QByteArray ba(command.toLatin1());
const char *cmd = ba.constData(); // Direct access to string data
char c;
for (int i = 0; i < command.length(); i++) {
c = cmd[i];
if (readNumeric && !isDigit(c) && c != '.') {
readNumeric = false;
l.append(sb);
sb.clear();
if (isLetter(c)) sb.append(c);
} else if (isDigit(c) || c == '.' || c == '-') {
sb.append(c);
readNumeric = true;
} else if (isLetter(c)) sb.append(c);
}
if (sb.length() > 0) l.append(sb);
// QChar c;
// for (int i = 0; i < command.length(); i++) {
// c = command[i];
// if (readNumeric && !c.isDigit() && c != '.') {
// readNumeric = false;
// l.append(sb);
// sb = "";
// if (c.isLetter()) sb.append(c);
// } else if (c.isDigit() || c == '.' || c == '-') {
// sb.append(c);
// readNumeric = true;
// } else if (c.isLetter()) sb.append(c);
// }
// if (sb.length() > 0) l.append(sb);
return l;
}
// TODO: Replace everything that uses this with a loop that loops through
// the string and creates a hash with all the values.
double GcodePreprocessorUtils::parseCoord(QList<QString> argList, char c)
{
// int n = argList.length();
// for (int i = 0; i < n; i++) {
// if (argList[i].length() > 0 && argList[i][0].toUpper() == c) return argList[i].mid(1).toDouble();
// }
foreach (QString t, argList)
{
if (t.length() > 0 && t[0].toUpper() == c) return t.mid(1).toDouble();
}
return NAN;
}
//static public List<String> convertArcsToLines(Point3d start, Point3d end) {
// List<String> l = new ArrayList<String>();
// return l;
//}
QVector3D GcodePreprocessorUtils::convertRToCenter(QVector3D start, QVector3D end, double radius, bool absoluteIJK, bool clockwise) {
double R = radius;
QVector3D center;
double x = end.x() - start.x();
double y = end.y() - start.y();
double h_x2_div_d = 4 * R * R - x * x - y * y;
if (h_x2_div_d < 0) { qDebug() << "Error computing arc radius."; }
h_x2_div_d = (-sqrt(h_x2_div_d)) / hypot(x, y);
if (!clockwise) h_x2_div_d = -h_x2_div_d;
// Special message from gcoder to software for which radius
// should be used.
if (R < 0) {
h_x2_div_d = -h_x2_div_d;
// TODO: Places that use this need to run ABS on radius.
radius = -radius;
}
double offsetX = 0.5 * (x - (y * h_x2_div_d));
double offsetY = 0.5 * (y + (x * h_x2_div_d));
if (!absoluteIJK) {
center.setX(start.x() + offsetX);
center.setY(start.y() + offsetY);
} else {
center.setX(offsetX);
center.setY(offsetY);
}
return center;
}
/**
* Return the angle in radians when going from start to end.
*/
double GcodePreprocessorUtils::getAngle(QVector3D start, QVector3D end) {
double deltaX = end.x() - start.x();
double deltaY = end.y() - start.y();
double angle = 0.0;
if (deltaX != 0) { // prevent div by 0
// it helps to know what quadrant you are in
if (deltaX > 0 && deltaY >= 0) { // 0 - 90
angle = atan(deltaY / deltaX);
} else if (deltaX < 0 && deltaY >= 0) { // 90 to 180
angle = M_PI - fabs(atan(deltaY / deltaX));
} else if (deltaX < 0 && deltaY < 0) { // 180 - 270
angle = M_PI + fabs(atan(deltaY / deltaX));
} else if (deltaX > 0 && deltaY < 0) { // 270 - 360
angle = M_PI * 2 - fabs(atan(deltaY / deltaX));
}
}
else {
// 90 deg
if (deltaY > 0) {
angle = M_PI / 2.0;
}
// 270 deg
else {
angle = M_PI * 3.0 / 2.0;
}
}
return angle;
}
double GcodePreprocessorUtils::calculateSweep(double startAngle, double endAngle, bool isCw)
{
double sweep;
// Full circle
if (startAngle == endAngle) {
sweep = (M_PI * 2);
// Arcs
} else {
// Account for full circles and end angles of 0/360
if (endAngle == 0) {
endAngle = M_PI * 2;
}
// Calculate distance along arc.
if (!isCw && endAngle < startAngle) {
sweep = ((M_PI * 2 - startAngle) + endAngle);
} else if (isCw && endAngle > startAngle) {
sweep = ((M_PI * 2 - endAngle) + startAngle);
} else {
sweep = fabs(endAngle - startAngle);
}
}
return sweep;
}
/**
* Generates the points along an arc including the start and end points.
*/
QList<QVector3D> GcodePreprocessorUtils::generatePointsAlongArcBDring(PointSegment::planes plane, QVector3D start, QVector3D end, QVector3D center, bool clockwise, double R, double minArcLength, double arcPrecision, bool arcDegreeMode)
{
double radius = R;
// Rotate vectors according to plane
QMatrix4x4 m;
m.setToIdentity();
switch (plane) {
case PointSegment::XY:
break;
case PointSegment::ZX:
m.rotate(90, 1.0, 0.0, 0.0);
break;
case PointSegment::YZ:
m.rotate(-90, 0.0, 1.0, 0.0);
break;
}
start = m * start;
end = m * end;
center = m * center;
// Check center
if (std::isnan(center.length())) return QList<QVector3D>();
// Calculate radius if necessary.
if (radius == 0) {
radius = sqrt(pow((double)(start.x() - center.x()), 2.0) + pow((double)(end.y() - center.y()), 2.0));
}
double startAngle = getAngle(center, start);
double endAngle = getAngle(center, end);
double sweep = calculateSweep(startAngle, endAngle, clockwise);
// Convert units.
double arcLength = sweep * radius;
// If this arc doesn't meet the minimum threshold, don't expand.
// if (minArcLength > 0 && arcLength < minArcLength) {
// QList<QVector3D> empty;
// return empty;
// }
int numPoints;
if (arcDegreeMode && arcPrecision > 0) {
numPoints = qMax(1.0, sweep / (M_PI * arcPrecision / 180));
} else {
if (arcPrecision <= 0 && minArcLength > 0) {
arcPrecision = minArcLength;
}
numPoints = (int)ceil(arcLength/arcPrecision);
}
return generatePointsAlongArcBDring(plane, start, end, center, clockwise, radius, startAngle, sweep, numPoints);
}
/**
* Generates the points along an arc including the start and end points.
*/
QList<QVector3D> GcodePreprocessorUtils::generatePointsAlongArcBDring(PointSegment::planes plane, QVector3D p1, QVector3D p2,
QVector3D center, bool isCw,
double radius, double startAngle,
double sweep, int numPoints)
{
// Prepare rotation matrix to restore plane
QMatrix4x4 m;
m.setToIdentity();
switch (plane) {
case PointSegment::XY:
break;
case PointSegment::ZX:
m.rotate(-90, 1.0, 0.0, 0.0);
break;
case PointSegment::YZ:
m.rotate(90, 0.0, 1.0, 0.0);
break;
}
QVector3D lineEnd(p2.x(), p2.y(), p1.z());
QList<QVector3D> segments;
double angle;
// Calculate radius if necessary.
if (radius == 0) {
radius = sqrt(pow((double)(p1.x() - center.x()), 2.0) + pow((double)(p1.y() - center.y()), 2.0));
}
double zIncrement = (p2.z() - p1.z()) / numPoints;
for (int i = 1; i < numPoints; i++)
{
if (isCw) {
angle = (startAngle - i * sweep / numPoints);
} else {
angle = (startAngle + i * sweep / numPoints);
}
if (angle >= M_PI * 2) {
angle = angle - M_PI * 2;
}
lineEnd.setX(cos(angle) * radius + center.x());
lineEnd.setY(sin(angle) * radius + center.y());
lineEnd.setZ(lineEnd.z() + zIncrement);
segments.append(m * lineEnd);
}
segments.append(m * p2);
return segments;
}
bool GcodePreprocessorUtils::isDigit(char c)
{
return c > 47 && c < 58;
}
bool GcodePreprocessorUtils::isLetter(char c)
{
return (c > 64 && c < 91) || (c > 96 && c < 123);
}
char GcodePreprocessorUtils::toUpper(char c)
{
return (c > 96 && c < 123) ? c - 32 : c;
}