forked from openscad/openscad
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathopenscad.cc
More file actions
1214 lines (1089 loc) · 40.1 KB
/
Copy pathopenscad.cc
File metadata and controls
1214 lines (1089 loc) · 40.1 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
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* OpenSCAD (www.openscad.org)
* Copyright (C) 2009-2011 Clifford Wolf <clifford@clifford.at> and
* Marius Kintel <marius@kintel.net>
*
* 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.
*
* As a special exception, you have permission to link this program
* with the CGAL library and distribute executables, as long as you
* follow the requirements of the GNU GPL in regard to all of the
* software in the executable aside from CGAL.
*
* 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include "openscad.h"
#include "version.h"
#ifdef _WIN32
#include <fcntl.h>
#include <io.h>
#include <cassert>
#endif
#include <libintl.h>
#include <array>
#include <boost/algorithm/string/case_conv.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/dll/runtime_symbol_info.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/lexical_cast/bad_lexical_cast.hpp>
#include <boost/optional/optional.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/positional_options.hpp>
#include <boost/program_options/value_semantic.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/range/adaptor/transformed.hpp>
#include <boost/range/iterator_range_core.hpp>
#include <clocale>
#include <cstddef>
#include <cstdlib>
#include <exception>
#include <filesystem>
#include <fstream>
#include <iomanip>
#include <ios>
#include <iostream>
#include <istream>
#include <iterator>
#include <map>
#include <memory>
#include <ostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <tuple>
#include <unordered_map>
#include <utility>
#include <vector>
#ifdef ENABLE_CGAL
#include <CGAL/assertions.h>
#include <CGAL/assertions_behaviour.h>
#endif
#include "Feature.h"
#include "LibraryInfo.h"
#include "RenderStatistic.h"
#include "core/AST.h"
#include "core/BuiltinContext.h"
#include "core/Builtins.h"
#include "core/CSGTreeEvaluator.h"
#include "core/Context.h"
#include "core/EvaluationSession.h"
#include "core/RenderVariables.h"
#include "core/ScopeContext.h"
#include "core/Settings.h"
#include "core/customizer/CommentParser.h"
#include "core/customizer/ParameterObject.h"
#include "core/customizer/ParameterSet.h"
#include "core/node.h"
#include "core/parsersettings.h"
#include "geometry/Geometry.h"
#include "geometry/GeometryEvaluator.h"
#include "geometry/GeometryUtils.h"
#include "geometry/PolySet.h"
#include "glview/Camera.h"
#include "glview/ColorMap.h"
#include "glview/OffscreenView.h"
#include "glview/RenderSettings.h"
#include "handle_dep.h"
#include "io/export.h"
#include "openscad_gui.h"
#include "openscad_mimalloc.h"
#include "platform/PlatformUtils.h"
#include "utils/StackCheck.h"
#include "utils/exceptions.h"
#include "utils/printutils.h"
#ifdef ENABLE_PYTHON
#include "python/python_public.h"
#endif
namespace po = boost::program_options;
namespace fs = std::filesystem;
std::string commandline_commands;
std::string arg_colorscheme;
namespace {
bool arg_info = false;
} // namespace
class Echostream
{
public:
Echostream(std::ostream& stream) : stream(stream)
{
set_output_handler(&Echostream::output, nullptr, this);
}
Echostream(const std::string& filename) : fstream(std::filesystem::u8path(filename)), stream(fstream)
{
set_output_handler(&Echostream::output, nullptr, this);
}
static void output(const Message& msgObj, void *userdata)
{
auto self = static_cast<Echostream *>(userdata);
if (msgObj.group != message_group::HtmlLink) {
self->stream << msgObj.str() << "\n";
}
}
~Echostream()
{
if (fstream.is_open()) fstream.close();
}
private:
std::ofstream fstream;
std::ostream& stream;
};
struct AnimateArgs {
unsigned frames = 0;
unsigned num_shards = 1;
unsigned shard = 1;
};
struct CommandLine {
const bool is_stdin;
const std::string& filename;
const bool is_stdout;
std::string output_file;
const fs::path& original_path;
const std::string& parameterFile;
const std::string& setName;
const ViewOptions& viewOptions;
const Camera& camera;
const boost::optional<FileFormat> export_format;
const CmdLineExportOptions& exportOptions;
const AnimateArgs animate;
const std::vector<std::string> summaryOptions;
const std::string summaryFile;
};
namespace {
#ifndef OPENSCAD_NOGUI
bool useGUI()
{
#ifdef Q_OS_X11
// see <http://qt.nokia.com/doc/4.5/qapplication.html#QApplication-2>:
// On X11, the window system is initialized if GUIenabled is true. If GUIenabled
// is false, the application does not connect to the X server. On Windows and
// Macintosh, currently the window system is always initialized, regardless of the
// value of GUIenabled. This may change in future versions of Qt.
return getenv("DISPLAY") != 0;
#else
return true;
#endif
}
#endif // OPENSCAD_NOGUI
bool checkAndExport(const std::shared_ptr<const Geometry>& root_geom, unsigned dimensions,
ExportInfo& exportInfo, const bool is_stdout, const std::string& filename)
{
if (root_geom->getDimension() != dimensions) {
LOG("Current top level object is not a %1$dD object.", dimensions);
return false;
}
if (root_geom->isEmpty()) {
LOG("Current top level object is empty.");
return false;
}
if (is_stdout) {
exportFileStdOut(root_geom, exportInfo);
} else {
exportFileByName(root_geom, filename, exportInfo);
}
return true;
}
void help(const char *arg0, const po::options_description& desc, bool failure = false)
{
const fs::path progpath(arg0);
LOG("Usage: %1$s [options] file.scad\n%2$s", progpath.filename().string(), desc);
exit(failure ? 1 : 0);
}
template <std::size_t size>
void help_export(const std::array<const Settings::SettingsEntryBase *, size>& options)
{
LOG("Section '%1$s':", options.at(0)->category());
for (const auto option : options) {
const auto [type, values] = option->help();
LOG(" - %1$s (%2$s): %3$s", option->name(), type, values);
}
}
void help_export()
{
LOG("OpenSCAD version %1$s\n", openscad_versionnumber);
LOG("List of settings that can be given using the -O option using the");
LOG("format '<section>/<key>=value', e.g.:");
LOG("openscad -O export-pdf/paper-size=a6 -O export-pdf/show-grid=false\n");
help_export(Settings::SettingsExportPdf::cmdline);
help_export(Settings::SettingsExport3mf::cmdline);
help_export(Settings::SettingsExportSvg::cmdline);
exit(0);
}
void version()
{
LOG("OpenSCAD version %1$s", openscad_versionnumber);
exit(0);
}
int info()
{
std::cout << LibraryInfo::info() << "\n\n";
try {
OffscreenView const glview(512, 512);
std::cout << glview.getRendererInfo() << "\n";
} catch (const OffscreenViewException& ex) {
LOG("Can't create OpenGL OffscreenView: %1$s. Exiting.\n", ex.what());
return 1;
}
return 0;
}
template <typename F>
bool with_output(const bool is_stdout, const std::string& filename, const F& f,
std::ios::openmode mode = std::ios::out)
{
if (is_stdout) {
#ifdef _WIN32
if ((mode & std::ios::binary) != 0) {
_setmode(_fileno(stdout), _O_BINARY);
}
#endif
f(std::cout);
return true;
}
std::ofstream fstream(std::filesystem::u8path(filename), mode);
if (!fstream.is_open()) {
LOG("Can't open file \"%1$s\" for export", filename);
return false;
} else {
f(fstream);
return true;
}
}
AnimateArgs get_animate(const po::variables_map& vm)
{
AnimateArgs animate;
if (vm.count("animate")) {
animate.frames = vm["animate"].as<unsigned>();
}
if (vm.count("animate_sharding")) {
std::vector<std::string> strs;
boost::split(strs, vm["animate_sharding"].as<std::string>(), boost::is_any_of("/"));
if (strs.size() != 2) {
LOG("--animate_sharding requires <shard>/<num_shards>");
exit(1);
}
try {
animate.shard = boost::lexical_cast<unsigned>(strs[0]);
animate.num_shards = boost::lexical_cast<unsigned>(strs[1]);
} catch (const boost::bad_lexical_cast&) {
LOG("--animate_sharding parameters need to be positive integers");
exit(1);
}
if (animate.shard > animate.num_shards || animate.shard == 0) {
LOG("--animate_sharding: shard needs to be in range <1..num_shards>");
exit(1);
}
}
return animate;
}
Camera get_camera(const po::variables_map& vm)
{
Camera camera;
if (vm.count("camera")) {
std::vector<std::string> strs;
std::vector<double> cam_parameters;
boost::split(strs, vm["camera"].as<std::string>(), boost::is_any_of(","));
if (strs.size() == 6 || strs.size() == 7) {
try {
for (const auto& s : strs) {
cam_parameters.push_back(boost::lexical_cast<double>(s));
}
camera.setup(cam_parameters);
} catch (boost::bad_lexical_cast&) {
LOG("Camera setup requires numbers as parameters");
}
} else {
LOG("Camera setup requires either 7 numbers for Gimbal Camera or 6 numbers for Vector Camera");
exit(1);
}
} else {
camera.viewall = true;
camera.autocenter = true;
}
if (vm.count("viewall")) {
camera.viewall = true;
}
if (vm.count("autocenter")) {
camera.autocenter = true;
}
if (vm.count("projection")) {
auto proj = vm["projection"].as<std::string>();
if (proj == "o" || proj == "ortho" || proj == "orthogonal") {
camera.projection = Camera::ProjectionType::ORTHOGONAL;
} else if (proj == "p" || proj == "perspective") {
camera.projection = Camera::ProjectionType::PERSPECTIVE;
} else {
LOG("projection needs to be 'o' or 'p' for ortho or perspective\n");
exit(1);
}
}
if (vm.count("imgsize")) {
std::vector<std::string> strs;
boost::split(strs, vm["imgsize"].as<std::string>(), boost::is_any_of(","));
if (strs.size() != 2) {
LOG("Need 2 numbers for imgsize");
exit(1);
} else {
try {
int const w = boost::lexical_cast<int>(strs[0]);
int const h = boost::lexical_cast<int>(strs[1]);
camera.pixel_width = w;
camera.pixel_height = h;
} catch (boost::bad_lexical_cast&) {
LOG("Need 2 numbers for imgsize");
}
}
}
return camera;
}
int do_export(const CommandLine& cmd, const RenderVariables& render_variables, FileFormat export_format,
SourceFile *root_file)
{
auto filename_str = fs::path(cmd.output_file).generic_string();
// Avoid possibility of fs::absolute throwing when passed an empty path
auto fpath = cmd.filename.empty() ? fs::current_path() : fs::absolute(fs::path(cmd.filename));
auto fparent = fpath.parent_path();
// set CWD relative to source file
fs::current_path(fparent);
EvaluationSession session{fparent.string()};
ContextHandle<BuiltinContext> builtin_context{Context::create<BuiltinContext>(&session)};
render_variables.applyToContext(builtin_context);
#ifdef DEBUG
PRINTDB("BuiltinContext:\n%s", builtin_context->dump());
#endif
AbstractNode::resetIndexCounter();
std::shared_ptr<const FileContext> file_context;
std::shared_ptr<AbstractNode> absolute_root_node;
#ifdef ENABLE_PYTHON
if (python_result_node != NULL && python_active) {
absolute_root_node = python_result_node;
} else {
#endif
absolute_root_node = root_file->instantiate(*builtin_context, &file_context);
#ifdef ENABLE_PYTHON
}
#endif
Camera camera = cmd.camera;
if (file_context) {
camera.updateView(file_context, true);
}
// restore CWD after module instantiation finished
fs::current_path(cmd.original_path);
// Do we have an explicit root node (! modifier)?
std::shared_ptr<const AbstractNode> root_node;
const Location *nextLocation = nullptr;
if (!(root_node = find_root_tag(absolute_root_node, &nextLocation))) {
root_node = absolute_root_node;
}
if (nextLocation) {
LOG(message_group::Warning, *nextLocation, builtin_context->documentRoot(),
"More than one Root Modifier (!)");
}
Tree tree(root_node, fparent.string());
if (export_format == FileFormat::CSG) {
// https://github.com/openscad/openscad/issues/128
// When I use the csg ouptput from the command line the paths in 'import'
// statements become relative. But unfortunately they become relative to
// the current working dir and neither to the location of the input nor
// the output.
fs::current_path(fparent); // Force exported filenames to be relative to document path
with_output(cmd.is_stdout, filename_str, [&tree, root_node](std::ostream& stream) {
stream << tree.getString(*root_node, "\t") << "\n";
});
fs::current_path(cmd.original_path);
} else if (export_format == FileFormat::AST) {
fs::current_path(fparent); // Force exported filenames to be relative to document path
with_output(cmd.is_stdout, filename_str,
[root_file](std::ostream& stream) { stream << root_file->dump(""); });
fs::current_path(cmd.original_path);
} else if (export_format == FileFormat::PARAM) {
with_output(cmd.is_stdout, filename_str,
[&root_file, &fpath](std::ostream& stream) { export_param(root_file, fpath, stream); });
} else if (export_format == FileFormat::TERM) {
CSGTreeEvaluator csgRenderer(tree);
auto root_raw_term = csgRenderer.buildCSGTree(*root_node);
with_output(cmd.is_stdout, filename_str, [root_raw_term](std::ostream& stream) {
if (!root_raw_term || root_raw_term->isEmptySet()) {
stream << "No top-level CSG object\n";
} else {
stream << root_raw_term->dump() << "\n";
}
});
} else if (export_format == FileFormat::ECHO) {
// echo -> don't need to evaluate any geometry
} else {
// start measuring render time
RenderStatistic renderStatistic;
GeometryEvaluator geomevaluator(tree);
std::unique_ptr<OffscreenView> glview;
std::shared_ptr<const Geometry> root_geom;
if ((export_format == FileFormat::ECHO || export_format == FileFormat::PNG) &&
(cmd.viewOptions.renderer == RenderType::OPENCSG ||
cmd.viewOptions.renderer == RenderType::THROWNTOGETHER)) {
// OpenCSG or throwntogether png -> just render a preview
glview = prepare_preview(tree, cmd.viewOptions, camera);
if (!glview) return 1;
} else {
// Force creation of concrete geometry (mostly for testing)
// FIXME: Consider adding MANIFOLD as a valid --render argument and ViewOption, to be able to
// distinguish from CGAL
constexpr bool allownef = true;
root_geom = geomevaluator.evaluateGeometry(*tree.root(), allownef);
if (!root_geom) root_geom = std::make_shared<PolySet>(3);
if (cmd.viewOptions.renderer == RenderType::BACKEND_SPECIFIC && root_geom->getDimension() == 3) {
if (auto geomlist = std::dynamic_pointer_cast<const GeometryList>(root_geom)) {
auto flatlist = geomlist->flatten();
for (auto& child : flatlist) {
if (child.second->getDimension() == 3) {
child.second = GeometryUtils::getBackendSpecificGeometry(child.second);
}
}
root_geom = std::make_shared<GeometryList>(flatlist);
} else {
root_geom = GeometryUtils::getBackendSpecificGeometry(root_geom);
assert(root_geom != nullptr);
}
LOG("Converted to backend-specific geometry");
}
}
const std::string input_filename = cmd.is_stdin ? "<stdin>" : cmd.filename;
const int dim = fileformat::is3D(export_format) ? 3 : fileformat::is2D(export_format) ? 2 : 0;
ExportInfo exportInfo = createExportInfo(export_format, fileformat::info(export_format),
input_filename, &cmd.camera, cmd.exportOptions);
if (dim > 0 && !checkAndExport(root_geom, dim, exportInfo, cmd.is_stdout, filename_str)) {
return 1;
}
if (export_format == FileFormat::PNG) {
bool success = true;
bool const wrote = with_output(
cmd.is_stdout, filename_str,
[&success, &root_geom, &cmd, &camera, &glview](std::ostream& stream) {
if (cmd.viewOptions.renderer == RenderType::BACKEND_SPECIFIC ||
cmd.viewOptions.renderer == RenderType::GEOMETRY) {
success = export_png(root_geom, cmd.viewOptions, camera, stream);
} else {
success = export_png(*glview, stream);
}
},
std::ios::out | std::ios::binary);
if (!success || !wrote) {
return 1;
}
}
renderStatistic.printAll(root_geom, camera, cmd.summaryOptions, cmd.summaryFile);
}
return 0;
}
int cmdline(const CommandLine& cmd)
{
FileFormat export_format;
// Determine output file format and assign it to formatName
if (cmd.export_format.is_initialized()) {
export_format = cmd.export_format.get();
} else {
// else extract format from file extension
const auto path = fs::path(cmd.output_file);
std::string suffix = path.has_extension() ? path.extension().generic_string().substr(1) : "";
boost::algorithm::to_lower(suffix);
if (!fileformat::fromIdentifier(suffix, export_format)) {
LOG(
"Invalid suffix %1$s. Either add a valid suffix or specify one using the --export-format "
"option.",
suffix);
return 1;
}
}
// Do some minimal checking of output directory before rendering (issue #432)
auto output_dir = fs::path(cmd.output_file).parent_path();
if (output_dir.empty()) {
// If output_file_str has no directory prefix, set output directory to current directory.
output_dir = fs::current_path();
}
if (!fs::is_directory(output_dir)) {
LOG("\n'%1$s' is not a directory for output file %2$s - Skipping\n", output_dir.generic_string(),
cmd.output_file);
return 1;
}
set_render_color_scheme(arg_colorscheme, true);
std::shared_ptr<Echostream> echostream;
if (export_format == FileFormat::ECHO) {
echostream.reset(cmd.is_stdout ? new Echostream(std::cout) : new Echostream(cmd.output_file));
}
std::string text;
if (cmd.is_stdin) {
text = std::string((std::istreambuf_iterator<char>(std::cin)), std::istreambuf_iterator<char>());
} else {
std::ifstream ifs(std::filesystem::u8path(cmd.filename));
if (!ifs.is_open()) {
LOG("Can't open input file '%1$s'!\n", cmd.filename);
return 1;
}
handle_dep(cmd.filename);
text = std::string((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());
}
#ifdef ENABLE_PYTHON
python_active = false;
if (cmd.filename.c_str() != NULL) {
if (boost::algorithm::ends_with(cmd.filename, ".py")) {
if (python_trusted == true) python_active = true;
else LOG("Python is not enabled");
}
}
if (python_active) {
auto fulltext_py = text;
initPython("", 0.0);
auto error = evaluatePython(fulltext_py, false);
if (error.size() > 0) LOG(error.c_str());
text = "\n";
}
#endif // ifdef ENABLE_PYTHON
text += "\n\x03\n" + commandline_commands;
SourceFile *root_file = nullptr;
if (!parse(root_file, text, cmd.filename, cmd.filename, false)) {
delete root_file; // parse failed
root_file = nullptr;
}
if (!root_file) {
LOG("Can't parse file '%1$s'!\n", cmd.filename);
return 1;
}
// add parameter to AST
CommentParser::collectParameters(text.c_str(), root_file);
if (!cmd.parameterFile.empty() && !cmd.setName.empty()) {
ParameterObjects parameters = ParameterObjects::fromSourceFile(root_file);
ParameterSets sets;
sets.readFile(cmd.parameterFile);
for (const auto& set : sets) {
if (set.name() == cmd.setName) {
parameters.importValues(set);
parameters.apply(root_file);
break;
}
}
}
root_file->handleDependencies();
RenderVariables render_variables = {
.preview = fileformat::canPreview(export_format)
? (cmd.viewOptions.renderer == RenderType::OPENCSG ||
cmd.viewOptions.renderer == RenderType::THROWNTOGETHER)
: false,
.camera = cmd.camera,
};
if (cmd.animate.frames == 0) {
render_variables.time = 0;
return do_export(cmd, render_variables, export_format, root_file);
} else {
// export the requested number of animated frames
const unsigned start_frame = ((cmd.animate.shard - 1) * cmd.animate.frames) / cmd.animate.num_shards;
const unsigned limit_frame = (cmd.animate.shard * cmd.animate.frames) / cmd.animate.num_shards;
for (unsigned frame = start_frame; frame < limit_frame; ++frame) {
render_variables.time = frame * (1.0 / cmd.animate.frames);
std::ostringstream oss;
oss << std::setw(5) << std::setfill('0') << frame;
auto frame_file = fs::path(cmd.output_file);
auto extension = frame_file.extension();
frame_file.replace_extension();
frame_file += oss.str();
frame_file.replace_extension(extension);
std::string const frame_str = frame_file.generic_string();
LOG("Exporting %1$s...", cmd.filename);
CommandLine frame_cmd = cmd;
frame_cmd.output_file = frame_str;
int const r = do_export(frame_cmd, render_variables, export_format, root_file);
if (r != 0) {
return r;
}
}
return 0;
}
}
template <class Seq, typename ToString>
static std::string str_join(const Seq& seq, const std::string& sep, const ToString& toString)
{
return boost::algorithm::join(boost::adaptors::transform(seq, toString), sep);
}
static bool flagConvert(const std::string& str)
{
if (str == "1" || boost::iequals(str, "on") || boost::iequals(str, "true")) {
return true;
}
if (str == "0" || boost::iequals(str, "off") || boost::iequals(str, "false")) {
return false;
}
throw std::runtime_error("");
return false;
}
static std::tuple<std::string, std::string> simple_split(const std::string& str, const char c)
{
const auto idx = str.find_first_of(c);
if (idx == std::string::npos) return {};
const auto first = str.substr(0, idx);
const auto second = str.substr(idx + 1);
return {first, second};
}
static CmdLineExportOptions convert_export_options(const po::variables_map& vm)
{
if (vm.count("O") == 0) {
return {};
}
CmdLineExportOptions map;
const auto& options = vm["O"].as<std::vector<std::string>>();
for (const auto& option : options) {
const auto [key, value] = simple_split(option, '=');
const auto [section, name] = simple_split(key, '/');
map[section][name] = value;
}
return map;
}
} // namespace
void set_render_color_scheme(const std::string& color_scheme, const bool exit_if_not_found)
{
if (color_scheme.empty()) {
return;
}
if (ColorMap::inst()->findColorScheme(color_scheme)) {
RenderSettings::inst()->colorscheme = color_scheme;
return;
}
if (exit_if_not_found) {
LOG((boost::algorithm::join(ColorMap::inst()->colorSchemeNames(), "\n")));
exit(1);
} else {
LOG("Unknown color scheme '%1$s', using default '%2$s'.", arg_colorscheme,
ColorMap::inst()->defaultColorSchemeName());
}
}
/**
* Initialize gettext. This must be called after the application path was
* determined so we can lookup the resource path for the language translation
* files.
*/
void localization_init()
{
fs::path const po_dir(PlatformUtils::resourcePath("locale"));
const std::string& locale_path(po_dir.string());
if (fs::is_directory(locale_path)) {
setlocale(LC_ALL, "");
bindtextdomain("openscad", locale_path.c_str());
bind_textdomain_codeset("openscad", "UTF-8");
textdomain("openscad");
} else {
LOG("Could not initialize localization (application path is '%1$s').",
PlatformUtils::applicationPath());
}
}
#ifdef Q_OS_MACOS
std::pair<std::string, std::string> customSyntax(const std::string& s)
{
if (s.find("-psn_") == 0) return {"psn", s.substr(5)};
#else
std::pair<std::string, std::string> customSyntax(const std::string&)
{
#endif
return {};
}
/*!
This makes boost::program_option parse comma-separated values
*/
struct CommaSeparatedVector {
std::vector<std::string> values;
friend std::istream& operator>>(std::istream& in, CommaSeparatedVector& value)
{
std::string token;
in >> token;
// NOLINTNEXTLINE(*NewDeleteLeaks) LLVM bug https://github.com/llvm/llvm-project/issues/40486
boost::split(value.values, token, boost::is_any_of(","));
return in;
}
};
// OpenSCAD
int openscad_main(int argc, char **argv)
{
#if defined(ENABLE_CGAL) && defined(USE_MIMALLOC)
// call init_mimalloc before any GMP variables are initialized. (defined in src/openscad_mimalloc.h)
init_mimalloc();
#endif
int rc = 0;
StackCheck::inst();
#ifdef Q_OS_MACOS
bool isGuiLaunched = getenv("GUI_LAUNCHED") != nullptr;
auto nslog = [](const Message& msg, void *userdata) { CocoaUtils::nslog(msg.msg, userdata); };
if (isGuiLaunched) set_output_handler(nslog, nullptr, nullptr);
#else
PlatformUtils::ensureStdIO();
#endif
#ifndef __EMSCRIPTEN__
const auto applicationPath =
weakly_canonical(boost::dll::program_location()).parent_path().generic_string();
#else
const auto applicationPath = boost::dll::fs::current_path();
#endif
PlatformUtils::registerApplicationPath(applicationPath);
#ifdef ENABLE_PYTHON
// The original name as called, not resolving links and so on. This will
// just forward everything to the python main.
const auto applicationName = fs::path(argv[0]).filename().generic_string();
if (applicationName == "python" || applicationName == "python3" ||
applicationName.rfind("python3.", 0) == 0 || applicationName == "openscad-python") {
return pythonRunArgs(argc, argv);
}
#endif
#ifdef ENABLE_CGAL
// Always throw exceptions from CGAL, so we can catch instead of crashing on bad geometry.
CGAL::set_error_behaviour(CGAL::THROW_EXCEPTION);
CGAL::set_warning_behaviour(CGAL::THROW_EXCEPTION);
#endif
Builtins::instance()->initialize();
auto original_path = fs::current_path();
std::vector<std::string> output_files;
const char *deps_output_file = nullptr;
boost::optional<FileFormat> export_format;
ViewOptions viewOptions{};
po::options_description desc("Allowed options");
// clang-format off
desc.add_options()
("export-format", po::value<std::string>(),
"overrides format of exported scad file when using option '-o', arg can be any of its supported "
"file extensions. For ASCII stl export, specify 'asciistl', and for binary stl export, specify "
"'binstl'. ASCII export is the current stl default, but binary stl is planned as the future "
"default so asciistl should be explicitly specified in scripts when needed.\n")
("o,o", po::value<std::vector<std::string>>(),
"output specified file instead of running the GUI. The file extension specifies the type: stl, "
"off, wrl, amf, 3mf, csg, dxf, svg, pdf, png, echo, ast, term, nef3, nefdbg, param, pov. May be "
"used multiple times for different exports. Use '-' for stdout.\n")
("O,O", po::value<std::vector<std::string>>(),
"pass settings value to the file export using the format section/key=value, e.g "
"export-pdf/paper-size=a3. Use --help-export to list all available settings.")
("D,D", po::value<std::vector<std::string>>(), "var=val -pre-define variables")
("p,p", po::value<std::string>(), "customizer parameter file")
("P,P", po::value<std::string>(), "customizer parameter set")
#ifdef ENABLE_EXPERIMENTAL
("enable", po::value<std::vector<std::string>>(),
("enable experimental features (specify 'all' for enabling all available features): " +
str_join(boost::make_iterator_range(Feature::begin(), Feature::end()), " | ",
[](const Feature *feature) { return feature->get_name(); }) +
"\n")
.c_str())
#endif
("help,h", "print this help message and exit")
("help-export", "print list of export parameters and values that can be set via -O")
("version,v", "print the version")
("info", "print information about the build process\n")
("camera", po::value<std::string>(),
"camera parameters when exporting png: =translate_x,y,z,rot_x,y,z,dist or "
"=eye_x,y,z,center_x,y,z")("autocenter", "adjust camera to look at object's center")
("viewall", "adjust camera to fit object")
("backend", po::value<std::string>(),
"3D rendering backend to use: 'CGAL' (old/slow) or 'Manifold' (new/fast) [default]")
("imgsize", po::value<std::string>(), "=width,height of exported png")
("render", po::value<std::string>()->implicit_value(""),
"for full geometry evaluation when exporting png")
("preview", po::value<std::string>()->implicit_value(""),
"[=throwntogether] -for ThrownTogether preview png")
("animate", po::value<unsigned>(), "export N animated frames")
("animate_sharding", po::value<std::string>(),
"Parameter <shard>/<num_shards> - Divide work into <num_shards> and only output frames for "
"<shard>. E.g. 2/5 only outputs the second 1/5 of frames. Use to parallelize work on multiple "
"cores or machines.")
("view", po::value<CommaSeparatedVector>(),
("=view options: " + boost::algorithm::join(viewOptions.names(), " | ")).c_str())
("projection", po::value<std::string>(), "=(o)rtho or (p)erspective when exporting png")
("csglimit", po::value<unsigned int>(), "=n -stop rendering at n CSG elements when exporting png")
("summary", po::value<std::vector<std::string>>(),
"enable additional render summary and statistics: all | cache | time | camera | geometry | "
"bounding-box | area")
("summary-file", po::value<std::string>(),
"output summary information in JSON format to the given file, using '-' outputs to stdout")
("colorscheme", po::value<std::string>(),
("=colorscheme: " +
str_join(ColorMap::inst()->colorSchemeNames(), " | ",
[](const std::string& colorScheme) {
return (colorScheme == ColorMap::inst()->defaultColorSchemeName() ? "*" : "") +
colorScheme;
}) +
"\n")
.c_str())
("d,d", po::value<std::string>(), "deps_file -generate a dependency file for make")
("m,m", po::value<std::string>(), "make_cmd -runs make_cmd file if file is missing")
("quiet,q", "quiet mode (don't print anything *except* errors)")
("reset-window-settings", "Reset GUI settings for window placement and fonts.")
("hardwarnings", "Stop on the first warning")
("trace-depth", po::value<unsigned int>(), "=n, maximum number of trace messages")
("trace-usermodule-parameters", po::value<std::string>(),
"=true/false, configure the output of user module parameters in a trace")
("check-parameters", po::value<std::string>(),
"=true/false, configure the parameter check for user modules and functions")
("check-parameter-ranges", po::value<std::string>(),
"=true/false, configure the parameter range check for builtin modules")
("debug", po::value<std::string>(),
"special debug info - specify 'all' or a set of source file names")
#ifdef ENABLE_PYTHON
("trust-python", "Trust python")
("python-module", po::value<std::string>(), "=module Call pip python module")
#endif
;
// clang-format on
#ifdef ENABLE_GUI_TESTS
// clang-format off
desc.add_options()("run-all-gui-tests", "special gui testing mode - run all the tests");
// clang-format on
#endif
po::options_description hidden("Hidden options");
// clang-format off
hidden.add_options()
#ifdef Q_OS_MACOS
("psn", po::value<std::string>(), "process serial number")
#endif
("input-file", po::value<std::vector<std::string>>(), "input file");
// clang-format on
po::positional_options_description p;
p.add("input-file", -1);
po::options_description all_options;
all_options.add(desc).add(hidden);
po::variables_map vm;
try {
po::store(po::command_line_parser(argc, argv)
.options(all_options)
.positional(p)
.extra_parser(customSyntax)
.run(),
vm);
} catch (const std::exception& e) { // Catches e.g. unknown options
LOG("%1$s\n", e.what());
help(argv[0], desc, true);
}
OpenSCAD::debug = "";
if (vm.count("debug")) {
OpenSCAD::debug = vm["debug"].as<std::string>();
LOG("Debug on. --debug=%1$s", OpenSCAD::debug);
}
#ifdef ENABLE_PYTHON
if (vm.count("trust-python")) {
LOG("Python Engine enabled", OpenSCAD::debug);
python_trusted = true;
}
const auto pymod = "python-module";
if (vm.count(pymod)) {
PRINTDB("Running Python Module %s", pymod);
std::vector<std::string> args;
if (vm.count("input-file")) {
args = vm["input-file"].as<std::vector<std::string>>();
}
return pythonRunModule(applicationPath, vm[pymod].as<std::string>(), args);
}
#endif // ifdef ENABLE_PYTHON
if (vm.count("quiet")) {
OpenSCAD::quiet = true;
}
if (vm.count("hardwarnings")) {
OpenSCAD::hardwarnings = true;
}
if (vm.count("traceDepth")) {
OpenSCAD::traceDepth = vm["traceDepth"].as<unsigned int>();
}