-
-
Notifications
You must be signed in to change notification settings - Fork 161
Expand file tree
/
Copy pathPySimulation.cpp
More file actions
675 lines (498 loc) · 17.8 KB
/
PySimulation.cpp
File metadata and controls
675 lines (498 loc) · 17.8 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
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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
/******************************************************************************\
CAMotics is an Open-Source simulation and CAM software.
Copyright (C) 2011-2021 Joseph Coffland <joseph@cauldrondevelopment.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
\******************************************************************************/
#include "PyPtr.h"
#include "PySimulation.h"
#include "PyJSON.h"
#include "PyJSONSink.h"
#include "PyLogger.h"
#include "PyTask.h"
#include "SmartPyGIL.h"
#include "Catch.h"
#include <camotics/sim/Simulation.h>
#include <camotics/sim/SimulationRun.h>
#include <camotics/sim/ToolPathTask.h>
#include <camotics/project/Project.h>
#include <camotics/contour/Surface.h>
#include <cbang/Catch.h>
#include <cbang/os/SystemUtilities.h>
#include <cbang/os/SystemInfo.h>
#include <limits>
#include <strings.h>
using namespace CAMotics;
using namespace cb;
using namespace std;
namespace {
struct Simulation {
Project::Project project;
SmartPointer<GCode::ToolPath> path;
SmartPointer<Surface> surface;
SmartPointer<PyTask> task;
};
typedef struct {
PyObject_HEAD;
Simulation *s;
} PySimulation;
void _dealloc(PySimulation *self) {
if (self->s) {
// End task gracefully
if (self->s->task.isSet()) self->s->task->join();
delete self->s;
}
Py_TYPE(self)->tp_free((PyObject *)self);
}
PyObject *_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
return type->tp_alloc(type, 0);
}
int _init(PySimulation *self, PyObject *args, PyObject *kwds) {
try {
self->s = new Simulation;
return 0;
} CATCH_PYTHON;
return -1;
}
void set_task(PySimulation *self, const SmartPointer<PyTask> &task) {
if (self->s->task.isSet()) THROW("A task is already active");
self->s->task = task;
}
PyObject *_open(PySimulation *self, PyObject *args, PyObject *kwds) {
try {
Simulation &s = *self->s;
const char *kwlist[] = {"filename", 0};
const char *filename = 0;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "s", (char **)kwlist,
&filename))
return 0;
if (!filename) {
PyErr_SetString(PyExc_RuntimeError, "Missing filename.");
return 0;
}
string ext = SystemUtilities::extension(filename);
if (ext == "xml" || ext == "camotics") s.project.load(filename);
else s.project.addFile(filename); // Assume TPL or G-Code
Py_RETURN_NONE;
} CATCH_PYTHON;
return 0;
}
PyObject *_is_metric(PySimulation *self) {
if (self->s->project.isMetric()) Py_RETURN_TRUE;
else Py_RETURN_FALSE;
}
PyObject *_set_metric(PySimulation *self, PyObject *args, PyObject *kwds) {
try {
const char *kwlist[] = {"metric", 0};
int metric = true;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|p", (char **)kwlist,
&metric))
return 0;
auto units = metric ? GCode::Units::METRIC : GCode::Units::IMPERIAL;
self->s->project.setUnits(units);
Py_RETURN_NONE;
} CATCH_PYTHON;
return 0;
}
PyObject *_get_resolution(PySimulation *self) {
try {
auto &p = self->s->project;
string mode = p.getResolutionMode().toString();
return Py_BuildValue("ds", p.getResolution(), mode.data());
} CATCH_PYTHON;
return 0;
}
PyObject *_set_resolution(PySimulation *self, PyObject *args,
PyObject *kwds) {
try {
auto &p = self->s->project;
const char *kwlist[] = {"resolution", 0};
PyObject *res = 0;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O", (char **)kwlist, &res))
return 0;
if (PyFloat_Check(res)) {
p.setResolutionMode(ResolutionMode::RESOLUTION_MANUAL);
p.setResolution(PyFloat_AsDouble(res));
} else if (PyUnicode_Check(res)) {
Py_ssize_t size;
const char *mode = PyUnicode_AsUTF8AndSize(res, &size);
if (!mode) THROW("Conversion from Python object to string failed");
p.setResolutionMode(ResolutionMode::parse(string(mode, size)));
} else THROW("Invalid argument type");
Py_RETURN_NONE;
} CATCH_PYTHON;
return 0;
}
PyObject *_get_tools(PySimulation *self) {
try {
PyJSONSink sink;
self->s->project.getTools().write(sink);
return sink.getRoot();
} CATCH_PYTHON;
return 0;
}
PyObject *_set_tools(PySimulation *self, PyObject *args, PyObject *kwds) {
try {
Simulation &s = *self->s;
const char *kwlist[] = {"tools", 0};
PyObject *tools = 0;
if (!PyArg_ParseTupleAndKeywords
(args, kwds, "O", (char **)kwlist, &tools))
return 0;
if (!tools) THROW("``tools`` not set'");
s.project.getTools().read(*PyJSON(tools).toJSON());
Py_RETURN_NONE;
} CATCH_PYTHON;
return 0;
}
PyObject *_set_tool(PySimulation *self, PyObject *args, PyObject *kwds) {
try {
auto &tools = self->s->project.getTools();
const char *kwlist[] = {
"number", "metric", "shape", "length", "diameter", "snub",
"description", 0};
unsigned number = 1;
int metric = true;
const char *shape = 0;
double length = 0;
double diameter = 0;
double snub = 0;
const char *desc = 0;
if (!PyArg_ParseTupleAndKeywords
(args, kwds, "Ipsdd|ds", (char **)kwlist, &number, &metric, &shape,
&length, &diameter, &snub, &desc))
return 0;
auto units = metric ? GCode::Units::METRIC : GCode::Units::IMPERIAL;
GCode::Tool t(number, 0, units);
t.setShape(GCode::ToolShape::parse(shape));
t.setLength(length);
t.setDiameter(diameter);
t.setSnubDiameter(snub);
if (desc) t.setDescription(desc);
tools.set(t);
Py_RETURN_NONE;
} CATCH_PYTHON;
return 0;
}
PyObject *_get_workpiece(PySimulation *self) {
try {
PyJSONSink sink;
self->s->project.getWorkpiece().write(sink);
return sink.getRoot();
} CATCH_PYTHON;
return 0;
}
PyObject *_set_workpiece(PySimulation *self, PyObject *args, PyObject *kwds) {
try {
Simulation &s = *self->s;
const char *kwlist[] = {"min", "max", "automatic", "margin", 0};
double minX = 0, minY = 0, minZ = 0, maxX = 0, maxY = 0, maxZ = 0;
int automatic = false;
double margin = 5;
if (!PyArg_ParseTupleAndKeywords
(args, kwds, "|(ddd)(ddd)pd", (char **)kwlist, &minX, &minY, &minZ,
&maxX, &maxY, &maxZ, &automatic, &margin))
return 0;
auto &w = s.project.getWorkpiece();
if (automatic) {
w.setAutomatic(true);
w.setMargin(margin);
} else {
Rectangle3D bounds(Vector3D(minX, minY, minZ),
Vector3D(maxX, maxY, maxZ));
w.setAutomatic(false);
w.setBounds(bounds);
}
Py_RETURN_NONE;
} CATCH_PYTHON;
return 0;
}
PyObject *_compute_path(PySimulation *self, PyObject *args, PyObject *kwds) {
try {
class Runner : public PyTask {
Simulation &s;
string gcode;
string tpl;
ToolPathTask task;
public:
Runner(PySimulation *self, const string &gcode, const string &tpl,
GCode::PlannerConfig *config) :
s(*self->s), gcode(gcode), tpl(tpl), task(s.project, config) {
start();
}
// From Thread
void run() override {
if (!gcode.empty()) task.runGCodeString(gcode);
else if (!tpl.empty()) task.runTPLString(tpl);
else task.run();
SmartPyGIL gil;
s.path = task.getPath();
}
};
const char *kwlist[] = {"gcode", "tpl", "config", 0};
const char *gcode = 0;
const char *tpl = 0;
PyObject *config = 0;
if (!PyArg_ParseTupleAndKeywords
(args, kwds, "|ssO", (char **)kwlist, &gcode, &tpl, &config))
return 0;
if (gcode && tpl) THROW("Cannot set both ``gcode`` and ``tpl``");
GCode::PlannerConfig planConfig;
if (config) planConfig.read(*PyJSON(config).toJSON());
set_task(self, new Runner(self, gcode ? gcode : "", tpl ? tpl : "",
config ? &planConfig : 0));
Py_RETURN_NONE;
} CATCH_PYTHON;
return 0;
}
PyObject *_set_path(PySimulation *self, PyObject *args, PyObject *kwds) {
try {
const char *kwlist[] = {"path", 0};
PyObject *path = 0;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O", (char **)kwlist, &path))
return 0;
if (self->s->path.isNull())
self->s->path = new GCode::ToolPath(self->s->project.getTools());
self->s->path->read(*PyJSON(path).toJSON());
Py_RETURN_NONE;
} CATCH_PYTHON;
return 0;
}
PyObject *_get_path(PySimulation *self) {
try {
if (!self->s->path.isSet()) THROW("Tool path not set");
PyJSONSink sink;
self->s->path->write(sink);
return sink.getRoot();
} CATCH_PYTHON;
return 0;
}
void call_done(PyPtr &done, bool success) {
if (!done) return;
try {
PyObject *args = PyTuple_New(1);
if (!args) THROW("Failed to allocate tuple");
PyTuple_SetItem(args, 0, success ? Py_True : Py_False);
PyObject *result = PyObject_Call(done.get(), args, 0);
Py_DECREF(args);
if (result) Py_DECREF(result);
} CATCH_ERROR;
}
PyObject *_start(PySimulation *self, PyObject *args, PyObject *kwds) {
try {
class Runner : public PyTask {
Simulation &s;
double time = 0;
unsigned threads = 0;
int reduce = false;
PyPtr done;
SmartPointer<GCode::ToolPath> path;
Rectangle3D bounds;
double resolution;
public:
Runner(PySimulation *self, PyObject *args, PyObject *kwds) :
s(*self->s) {
try {
const char *kwlist[] =
{"callback", "time", "threads", "reduce", "done", 0};
PyObject *cb = 0;
PyObject *done = 0;
if (!PyArg_ParseTupleAndKeywords(
args, kwds, "|OdIpO", (char **)kwlist, &cb, &time, &threads,
&reduce, &done))
THROW("Invalid arguments");
this->done = done;
setCallback(cb);
if (!threads) threads = SystemInfo::instance().getCPUCount();
if (!time) time = numeric_limits<double>::max();
if (!s.path.isSet()) THROW("Missing tool path");
path = s.path;
s.project.getWorkpiece().update(*path);
bounds = s.project.getWorkpiece().getBounds();
resolution = s.project.getResolution();
start();
} catch (...) {
call_done(done, false);
throw;
}
}
// From Thread
void run() override {
try {
CAMotics::Simulation
sim(path, 0, 0, bounds, resolution, time, RenderMode(), threads);
auto surface = SimulationRun(sim).compute(*this);
if (reduce) surface->reduce(*this);
SmartPyGIL gil;
s.surface = surface;
call_done(done, surface.isSet());
return;
} CATCH_ERROR;
SmartPyGIL gil;
call_done(done, false);
}
};
set_task(self, new Runner(self, args, kwds));
Py_RETURN_NONE;
} CATCH_PYTHON;
return 0;
}
PyObject *_write_surface(PySimulation *self, PyObject *args, PyObject *kwds) {
try {
Simulation &s = *self->s;
const char *kwlist[] = {"filename", "binary", 0};
const char *filename = 0;
int binary = true;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|p", (char **)kwlist,
&filename, &binary))
return 0;
if (!filename) {
PyErr_SetString(PyExc_RuntimeError, "Missing filename.");
return 0;
}
s.surface->writeSTL(*SystemUtilities::oopen(filename), binary,
"CAMotics Surface", "");
Py_RETURN_NONE;
} CATCH_PYTHON;
return 0;
}
PyObject *_get_surface(PySimulation *self, PyObject *args, PyObject *kwds) {
try {
Simulation &s = *self->s;
const char *kwlist[] = {"format", 0};
const char *format = "binary";
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|s", (char **)kwlist,
&format))
return 0;
if (strcasecmp(format, "python") == 0) {
PyJSONSink sink;
s.surface->write(sink);
return sink.getRoot();
}
bool binary;
if (strcasecmp(format, "binary") == 0) binary = true;
else if (strcasecmp(format, "ascii") == 0) binary = false;
else THROW("Invalid format");
if (s.surface.isNull()) Py_RETURN_NONE;
ostringstream str;
s.surface->writeSTL(str, binary, "CAMotics Surface", "");
string data = str.str();
return PyBytes_FromStringAndSize(data.data(), data.length());
} CATCH_PYTHON;
return 0;
}
PyObject *_is_running(PySimulation *self) {
try {
auto &task = self->s->task;
if (task.isSet() && task->isRunning()) Py_RETURN_TRUE;
else Py_RETURN_FALSE;
} CATCH_PYTHON;
return 0;
}
PyObject *_wait(PySimulation *self) {
try {
auto &task = self->s->task;
if (task.isSet()) {
task->wait();
task.release();
}
Py_RETURN_NONE;
} CATCH_PYTHON;
return 0;
}
PyObject *_interrupt(PySimulation *self) {
try {
auto &task = self->s->task;
if (task.isSet()) task->stop();
Py_RETURN_NONE;
} CATCH_PYTHON;
return 0;
}
PyMethodDef _methods[] = {
{"open", (PyCFunction)_open, METH_VARARGS | METH_KEYWORDS,
"Open a CAMotics project, GCode or TPL file."},
{"is_metric", (PyCFunction)_is_metric, METH_NOARGS,
"Return true if project is in metric mode."},
{"set_metric", (PyCFunction)_set_metric,
METH_VARARGS | METH_KEYWORDS, "Enable or disable metric mode."},
{"get_resolution", (PyCFunction)_get_resolution, METH_NOARGS,
"Get resolution and mode."},
{"set_resolution", (PyCFunction)_set_resolution,
METH_VARARGS | METH_KEYWORDS, "Set simulation resolution."},
{"get_tools", (PyCFunction)_get_tools, METH_NOARGS, "Get tool table."},
{"set_tools", (PyCFunction)_set_tools,
METH_VARARGS | METH_KEYWORDS, "Set tool table."},
{"set_tool", (PyCFunction)_set_tool,
METH_VARARGS | METH_KEYWORDS, "Set tool table."},
{"get_workpiece", (PyCFunction)_get_workpiece, METH_NOARGS,
"Get workpiece dimensions."},
{"set_workpiece", (PyCFunction)_set_workpiece,
METH_VARARGS | METH_KEYWORDS, "Set workpiece dimensions."},
{"compute_path", (PyCFunction)_compute_path, METH_VARARGS | METH_KEYWORDS,
"Compute tool path"},
{"set_path", (PyCFunction)_set_path, METH_VARARGS | METH_KEYWORDS,
"Set tool path."},
{"get_path", (PyCFunction)_get_path, METH_NOARGS, ""},
{"start", (PyCFunction)_start, METH_VARARGS | METH_KEYWORDS,
"Start a simulation run."},
{"write_surface", (PyCFunction)_write_surface, METH_VARARGS | METH_KEYWORDS,
"Write surface STL to named file."},
{"get_surface", (PyCFunction)_get_surface, METH_VARARGS | METH_KEYWORDS,
"Get surface as STL data or Python object."},
{"is_running", (PyCFunction)_is_running, METH_NOARGS,
"Returns true if a task is running."},
{"wait", (PyCFunction)_wait, METH_NOARGS, "Wait on running task."},
{"interrupt", (PyCFunction)_interrupt, METH_NOARGS,
"Interrupt running task."},
{0}
};
}
PyTypeObject SimulationType = {
PyVarObject_HEAD_INIT(0, 0)
"Simulation", // tp_name
sizeof(PySimulation), // tp_basicsize
0, // tp_itemsize
(destructor)_dealloc, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
0, // tp_reserved
0, // tp_repr
0, // tp_as_number
0, // tp_as_sequence
0, // tp_as_mapping
0, // tp_hash
0, // tp_call
0, // tp_str
0, // tp_getattro
0, // tp_setattro
0, // tp_as_buffer
Py_TPFLAGS_DEFAULT |
Py_TPFLAGS_BASETYPE, // tp_flags
"Simulation object", // tp_doc
0, // tp_traverse
0, // tp_clear
0, // tp_richcompare
0, // tp_weaklistoffset
0, // tp_iter
0, // tp_iternext
_methods, // tp_methods
0, // tp_members
0, // tp_getset
0, // tp_base
0, // tp_dict
0, // tp_descr_get
0, // tp_descr_set
0, // tp_dictoffset
(initproc)_init, // tp_init
0, // tp_alloc
_new, // tp_new
};