forked from solvespace/solvespace
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexport.cpp
More file actions
1268 lines (1116 loc) · 43.8 KB
/
export.cpp
File metadata and controls
1268 lines (1116 loc) · 43.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
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
//-----------------------------------------------------------------------------
// The 2d vector output stuff that isn't specific to any particular file
// format: getting the appropriate lines and curves, performing hidden line
// removal, calculating bounding boxes, and so on. Also raster and triangle
// mesh output.
//
// Copyright 2008-2013 Jonathan Westhues.
//-----------------------------------------------------------------------------
#include "solvespace.h"
#include "config.h"
void SolveSpaceUI::ExportSectionTo(const Platform::Path &filename) {
Vector gn = (SS.GW.projRight).Cross(SS.GW.projUp);
gn = gn.WithMagnitude(1);
Group *g = SK.GetGroup(SS.GW.activeGroup);
g->GenerateDisplayItems();
if(g->displayMesh.IsEmpty()) {
Error(_("No solid model present; draw one with extrudes and revolves, "
"or use Export 2d View to export bare lines and curves."));
return;
}
// The plane in which the exported section lies; need this because we'll
// reorient from that plane into the xy plane before exporting.
Vector origin, u, v, n;
double d;
SS.GW.GroupSelection();
auto const &gs = SS.GW.gs;
if((gs.n == 0 && g->activeWorkplane != Entity::FREE_IN_3D)) {
Entity *wrkpl = SK.GetEntity(g->activeWorkplane);
origin = wrkpl->WorkplaneGetOffset();
n = wrkpl->Normal()->NormalN();
u = wrkpl->Normal()->NormalU();
v = wrkpl->Normal()->NormalV();
} else if(gs.n == 1 && gs.faces == 1) {
Entity *face = SK.GetEntity(gs.entity[0]);
origin = face->FaceGetPointNum();
n = face->FaceGetNormalNum();
if(n.Dot(gn) < 0) n = n.ScaledBy(-1);
u = n.Normal(0);
v = n.Normal(1);
} else if(gs.n == 3 && gs.vectors == 2 && gs.points == 1) {
Vector ut = SK.GetEntity(gs.entity[0])->VectorGetNum(),
vt = SK.GetEntity(gs.entity[1])->VectorGetNum();
ut = ut.WithMagnitude(1);
vt = vt.WithMagnitude(1);
if(fabs(SS.GW.projUp.Dot(vt)) < fabs(SS.GW.projUp.Dot(ut))) {
swap(ut, vt);
}
if(SS.GW.projRight.Dot(ut) < 0) ut = ut.ScaledBy(-1);
if(SS.GW.projUp. Dot(vt) < 0) vt = vt.ScaledBy(-1);
origin = SK.GetEntity(gs.point[0])->PointGetNum();
n = ut.Cross(vt);
u = ut.WithMagnitude(1);
v = (n.Cross(u)).WithMagnitude(1);
} else {
Error(_("Bad selection for export section. Please select:\n\n"
" * nothing, with an active workplane "
"(workplane is section plane)\n"
" * a face (section plane through face)\n"
" * a point and two line segments "
"(plane through point and parallel to lines)\n"));
return;
}
SS.GW.ClearSelection();
n = n.WithMagnitude(1);
d = origin.Dot(n);
SEdgeList el = {};
SBezierList bl = {};
// If there's a mesh, then grab the edges from it.
g->runningMesh.MakeEdgesInPlaneInto(&el, n, d);
// If there's a shell, then grab the edges and possibly Beziers.
bool export_as_pwl = SS.exportPwlCurves || fabs(SS.exportOffset) > LENGTH_EPS;
g->runningShell.MakeSectionEdgesInto(n, d, &el, export_as_pwl ? NULL : &bl);
// All of these are solid model edges, so use the appropriate style.
SEdge *se;
for(se = el.l.First(); se; se = el.l.NextAfter(se)) {
se->auxA = Style::SOLID_EDGE;
}
SBezier *sb;
for(sb = bl.l.First(); sb; sb = bl.l.NextAfter(sb)) {
sb->auxA = Style::SOLID_EDGE;
}
// Remove all overlapping edges/beziers to merge the areas they describe.
el.CullExtraneousEdges(/*both=*/true);
bl.CullIdenticalBeziers(/*both=*/true);
// Collect lines and beziers with custom style & export.
for(auto &ent : SK.entity) {
Entity *e = &ent;
if (!e->IsVisible()) continue;
if (e->style.v < Style::FIRST_CUSTOM) continue;
if (!Style::Exportable(e->style.v)) continue;
if (!e->IsInPlane(n,d)) continue;
if (export_as_pwl) {
e->GenerateEdges(&el);
} else {
e->GenerateBezierCurves(&bl);
}
}
// Only remove half of the overlapping edges/beziers to support TTF Stick Fonts.
el.CullExtraneousEdges(/*both=*/false);
bl.CullIdenticalBeziers(/*both=*/false);
// And write the edges.
VectorFileWriter *out = VectorFileWriter::ForFile(filename);
if(out) {
// parallel projection (no perspective), and no mesh
ExportLinesAndMesh(&el, &bl, NULL,
u, v, n, origin, 0,
out);
}
el.Clear();
bl.Clear();
}
// This is an awful temporary hack to replace Constraint::GetEdges until we have proper
// export through Canvas.
class GetEdgesCanvas : public Canvas {
public:
Camera camera;
SEdgeList *edges;
const Camera &GetCamera() const override {
return camera;
}
void DrawLine(const Vector &a, const Vector &b, hStroke hcs) override {
edges->AddEdge(a, b, Style::CONSTRAINT);
}
void DrawEdges(const SEdgeList &el, hStroke hcs) override {
for(const SEdge &e : el.l) {
edges->AddEdge(e.a, e.b, Style::CONSTRAINT);
}
}
void DrawVectorText(const std::string &text, double height,
const Vector &o, const Vector &u, const Vector &v,
hStroke hcs) override {
auto traceEdge = [&](Vector a, Vector b) { edges->AddEdge(a, b, Style::CONSTRAINT); };
VectorFont::Builtin()->Trace(height, o, u, v, text, traceEdge, camera);
}
void DrawQuad(const Vector &a, const Vector &b, const Vector &c, const Vector &d,
hFill hcf) override {
// Do nothing
}
bool DrawBeziers(const SBezierList &bl, hStroke hcs) override {
ssassert(false, "Not implemented");
}
void DrawOutlines(const SOutlineList &ol, hStroke hcs, DrawOutlinesAs drawAs) override {
ssassert(false, "Not implemented");
}
void DrawPoint(const Vector &o, hStroke hcs) override {
ssassert(false, "Not implemented");
}
void DrawPolygon(const SPolygon &p, hFill hcf) override {
ssassert(false, "Not implemented");
}
void DrawMesh(const SMesh &m, hFill hcfFront, hFill hcfBack = {}) override {
ssassert(false, "Not implemented");
}
void DrawFaces(const SMesh &m, const std::vector<uint32_t> &faces, hFill hcf) override {
ssassert(false, "Not implemented");
}
void DrawPixmap(std::shared_ptr<const Pixmap> pm,
const Vector &o, const Vector &u, const Vector &v,
const Point2d &ta, const Point2d &tb, hFill hcf) override {
ssassert(false, "Not implemented");
}
void InvalidatePixmap(std::shared_ptr<const Pixmap> pm) override {
ssassert(false, "Not implemented");
}
};
void SolveSpaceUI::ExportViewOrWireframeTo(const Platform::Path &filename, bool exportWireframe) {
SEdgeList edges = {};
SBezierList beziers = {};
VectorFileWriter *out = VectorFileWriter::ForFile(filename);
if(!out) return;
SS.exportMode = true;
GenerateAll(Generate::ALL);
SMesh *sm = NULL;
if(SS.GW.showShaded || SS.GW.drawOccludedAs != GraphicsWindow::DrawOccludedAs::VISIBLE) {
Group *g = SK.GetGroup(SS.GW.activeGroup);
g->GenerateDisplayItems();
sm = &(g->displayMesh);
}
if(sm && sm->IsEmpty()) {
sm = NULL;
}
for(auto &entity : SK.entity) {
Entity *e = &entity;
if(!e->IsVisible()) continue;
if(SS.exportPwlCurves || sm || fabs(SS.exportOffset) > LENGTH_EPS)
{
// We will be doing hidden line removal, which we can't do on
// exact curves; so we need things broken down to pwls. Same
// problem with cutter radius compensation.
e->GenerateEdges(&edges);
} else {
e->GenerateBezierCurves(&beziers);
}
}
if(SS.GW.showEdges || SS.GW.showOutlines) {
Group *g = SK.GetGroup(SS.GW.activeGroup);
g->GenerateDisplayItems();
if(SS.GW.showEdges) {
g->displayOutlines.ListTaggedInto(&edges, Style::SOLID_EDGE);
}
}
if(SS.GW.showConstraints) {
if(!out->OutputConstraints(&SK.constraint)) {
GetEdgesCanvas canvas = {};
canvas.camera = SS.GW.GetCamera();
canvas.edges = &edges;
// The output format cannot represent constraints directly,
// so convert them to edges.
for(Constraint &c : SK.constraint) {
c.Draw(Constraint::DrawAs::DEFAULT, &canvas);
}
canvas.Clear();
}
}
if(exportWireframe) {
Vector u = Vector::From(1.0, 0.0, 0.0),
v = Vector::From(0.0, 1.0, 0.0),
n = Vector::From(0.0, 0.0, 1.0),
origin = Vector::From(0.0, 0.0, 0.0);
double cameraTan = 0.0,
scale = 1.0;
out->SetModelviewProjection(u, v, n, origin, cameraTan, scale);
ExportWireframeCurves(&edges, &beziers, out);
} else {
Vector u = SS.GW.projRight,
v = SS.GW.projUp,
n = u.Cross(v),
origin = SS.GW.offset.ScaledBy(-1);
out->SetModelviewProjection(u, v, n, origin,
SS.CameraTangent()*SS.GW.scale, SS.exportScale);
ExportLinesAndMesh(&edges, &beziers, sm,
u, v, n, origin, SS.CameraTangent()*SS.GW.scale,
out);
if(!out->HasCanvasSize()) {
// These file formats don't have a canvas size, so they just
// get exported in the raw coordinate system. So indicate what
// that was on-screen.
SS.justExportedInfo.showOrigin = true;
SS.justExportedInfo.pt = origin;
SS.justExportedInfo.u = u;
SS.justExportedInfo.v = v;
} else {
SS.justExportedInfo.showOrigin = false;
}
SS.justExportedInfo.draw = true;
GW.Invalidate();
}
edges.Clear();
beziers.Clear();
}
void SolveSpaceUI::ExportWireframeCurves(SEdgeList *sel, SBezierList *sbl,
VectorFileWriter *out)
{
SBezierLoopSetSet sblss = {};
SEdge *se;
for(se = sel->l.First(); se; se = sel->l.NextAfter(se)) {
SBezier sb = SBezier::From(
(se->a).ScaledBy(1.0 / SS.exportScale),
(se->b).ScaledBy(1.0 / SS.exportScale));
sblss.AddOpenPath(&sb);
}
sbl->ScaleSelfBy(1.0/SS.exportScale);
SBezier *sb;
for(sb = sbl->l.First(); sb; sb = sbl->l.NextAfter(sb)) {
sblss.AddOpenPath(sb);
}
out->OutputLinesAndMesh(&sblss, NULL);
sblss.Clear();
}
void SolveSpaceUI::ExportLinesAndMesh(SEdgeList *sel, SBezierList *sbl, SMesh *sm,
Vector u, Vector v, Vector n,
Vector origin, double cameraTan,
VectorFileWriter *out)
{
double s = 1.0 / SS.exportScale;
// Project into the export plane; so when we're done, z doesn't matter,
// and x and y are what goes in the DXF.
for(SEdge *e = sel->l.First(); e; e = sel->l.NextAfter(e)) {
// project into the specified csys, and apply export scale
(e->a) = e->a.InPerspective(u, v, n, origin, cameraTan).ScaledBy(s);
(e->b) = e->b.InPerspective(u, v, n, origin, cameraTan).ScaledBy(s);
}
if(sbl) {
for(SBezier *b = sbl->l.First(); b; b = sbl->l.NextAfter(b)) {
*b = b->InPerspective(u, v, n, origin, cameraTan);
int i;
for(i = 0; i <= b->deg; i++) {
b->ctrl[i] = (b->ctrl[i]).ScaledBy(s);
}
}
}
// If cutter radius compensation is requested, then perform it now
if(fabs(SS.exportOffset) > LENGTH_EPS) {
// assemble those edges into a polygon, and clear the edge list
SPolygon sp = {};
sel->AssemblePolygon(&sp, NULL);
sel->Clear();
SPolygon compd = {};
sp.normal = Vector::From(0, 0, -1);
sp.FixContourDirections();
sp.OffsetInto(&compd, SS.exportOffset*s);
sp.Clear();
compd.MakeEdgesInto(sel);
compd.Clear();
}
// Now the triangle mesh; project, then build a BSP to perform
// occlusion testing and generated the shaded surfaces.
SMesh smp = {};
if(sm) {
Vector l0 = (SS.lightDir[0]).WithMagnitude(1),
l1 = (SS.lightDir[1]).WithMagnitude(1);
STriangle *tr;
for(tr = sm->l.First(); tr; tr = sm->l.NextAfter(tr)) {
STriangle tt = *tr;
tt.a = (tt.a).InPerspective(u, v, n, origin, cameraTan).ScaledBy(s);
tt.b = (tt.b).InPerspective(u, v, n, origin, cameraTan).ScaledBy(s);
tt.c = (tt.c).InPerspective(u, v, n, origin, cameraTan).ScaledBy(s);
// And calculate lighting for the triangle
Vector n = tt.Normal().WithMagnitude(1);
double lighting = min(1.0, SS.ambientIntensity +
max(0.0, (SS.lightIntensity[0])*(n.Dot(l0))) +
max(0.0, (SS.lightIntensity[1])*(n.Dot(l1))));
double r = min(1.0, tt.meta.color.redF() * lighting),
g = min(1.0, tt.meta.color.greenF() * lighting),
b = min(1.0, tt.meta.color.blueF() * lighting);
tt.meta.color = RGBf(r, g, b);
smp.AddTriangle(&tt);
}
}
SMesh sms = {};
// We need the mesh for occlusion testing, but if we don't/can't export it,
// don't generate it.
if(SS.GW.showShaded && out->CanOutputMesh()) {
// Use the BSP routines to generate the split triangles in paint order.
SBsp3 *bsp = SBsp3::FromMesh(&smp);
if(bsp) bsp->GenerateInPaintOrder(&sms);
// And cull the back-facing triangles
STriangle *tr;
sms.l.ClearTags();
for(tr = sms.l.First(); tr; tr = sms.l.NextAfter(tr)) {
Vector n = tr->Normal();
if(n.z < 0) {
tr->tag = 1;
}
}
sms.l.RemoveTagged();
}
// And now we perform hidden line removal if requested
SEdgeList hlrd = {};
if(sm) {
SKdNode *root = SKdNode::From(&smp);
// Generate the edges where a curved surface turns from front-facing
// to back-facing.
if(SS.GW.showEdges || SS.GW.showOutlines) {
root->MakeCertainEdgesInto(sel, EdgeKind::TURNING,
/*coplanarIsInter=*/false, NULL, NULL,
GW.showOutlines ? Style::OUTLINE : Style::SOLID_EDGE);
}
root->ClearTags();
int cnt = 1234;
SEdge *se;
for(se = sel->l.First(); se; se = sel->l.NextAfter(se)) {
if(se->auxA == Style::CONSTRAINT) {
// Constraints should not get hidden line removed; they're
// always on top.
hlrd.AddEdge(se->a, se->b, se->auxA);
continue;
}
SEdgeList edges = {};
// Split the original edge against the mesh
edges.AddEdge(se->a, se->b, se->auxA);
root->OcclusionTestLine(*se, &edges, cnt);
if(SS.GW.drawOccludedAs == GraphicsWindow::DrawOccludedAs::STIPPLED) {
for(SEdge &se : edges.l) {
if(se.tag == 1) {
se.auxA = Style::HIDDEN_EDGE;
}
}
} else if(SS.GW.drawOccludedAs == GraphicsWindow::DrawOccludedAs::INVISIBLE) {
edges.l.RemoveTagged();
}
// the occlusion test splits unnecessarily; so fix those
edges.MergeCollinearSegments(se->a, se->b);
cnt++;
// And add the results to our output
SEdge *sen;
for(sen = edges.l.First(); sen; sen = edges.l.NextAfter(sen)) {
hlrd.AddEdge(sen->a, sen->b, sen->auxA);
}
edges.Clear();
}
sel = &hlrd;
}
// Clean up: remove overlapping line segments and
// segments with zero-length projections.
sel->l.ClearTags();
for(int i = 0; i < sel->l.n; ++i) {
SEdge *sei = &sel->l[i];
hStyle hsi = { (uint32_t)sei->auxA };
Style *si = Style::Get(hsi);
if(sei->tag != 0) continue;
// Remove segments with zero length projections.
Vector ai = sei->a;
ai.z = 0.0;
Vector bi = sei->b;
bi.z = 0.0;
Vector di = bi.Minus(ai);
if(fabs(di.x) < LENGTH_EPS && fabs(di.y) < LENGTH_EPS) {
sei->tag = 1;
continue;
}
for(int j = i + 1; j < sel->l.n; ++j) {
SEdge *sej = &sel->l[j];
if(sej->tag != 0) continue;
Vector *pAj = &sej->a;
Vector *pBj = &sej->b;
// Remove segments with zero length projections.
Vector aj = sej->a;
aj.z = 0.0;
Vector bj = sej->b;
bj.z = 0.0;
Vector dj = bj.Minus(aj);
if(fabs(dj.x) < LENGTH_EPS && fabs(dj.y) < LENGTH_EPS) {
sej->tag = 1;
continue;
}
// Skip non-collinear segments.
const double eps = 1e-6;
if(aj.DistanceToLine(ai, di) > eps) continue;
if(bj.DistanceToLine(ai, di) > eps) continue;
double ta = aj.Minus(ai).Dot(di) / di.Dot(di);
double tb = bj.Minus(ai).Dot(di) / di.Dot(di);
if(ta > tb) {
std::swap(pAj, pBj);
std::swap(ta, tb);
}
hStyle hsj = { (uint32_t)sej->auxA };
Style *sj = Style::Get(hsj);
bool canRemoveI = sej->auxA == sei->auxA || si->zIndex < sj->zIndex;
bool canRemoveJ = sej->auxA == sei->auxA || sj->zIndex < si->zIndex;
if(canRemoveJ) {
// j-segment inside i-segment
if(ta > 0.0 - eps && tb < 1.0 + eps) {
sej->tag = 1;
continue;
}
// cut segment
bool aInside = ta > 0.0 - eps && ta < 1.0 + eps;
if(tb > 1.0 - eps && aInside) {
*pAj = sei->b;
continue;
}
// cut segment
bool bInside = tb > 0.0 - eps && tb < 1.0 + eps;
if(ta < 0.0 - eps && bInside) {
*pBj = sei->a;
continue;
}
// split segment
if(ta < 0.0 - eps && tb > 1.0 + eps) {
sel->AddEdge(sei->b, *pBj, sej->auxA, sej->auxB);
*pBj = sei->a;
continue;
}
}
if(canRemoveI) {
// j-segment inside i-segment
if(ta < 0.0 + eps && tb > 1.0 - eps) {
sei->tag = 1;
break;
}
// cut segment
bool aInside = ta > 0.0 + eps && ta < 1.0 - eps;
if(tb > 1.0 - eps && aInside) {
sei->b = *pAj;
i--;
break;
}
// cut segment
bool bInside = tb > 0.0 + eps && tb < 1.0 - eps;
if(ta < 0.0 + eps && bInside) {
sei->a = *pBj;
i--;
break;
}
// split segment
if(ta > 0.0 + eps && tb < 1.0 - eps) {
sel->AddEdge(*pBj, sei->b, sei->auxA, sei->auxB);
sei->b = *pAj;
i--;
break;
}
}
}
}
sel->l.RemoveTagged();
// We kept the line segments and Beziers separate until now; but put them
// all together, and also project everything into the xy plane, since not
// all export targets ignore the z component of the points.
ssassert(sbl != nullptr, "Adding line segments to beziers assumes bezier list is non-null.");
for(SEdge *e = sel->l.First(); e; e = sel->l.NextAfter(e)) {
SBezier sb = SBezier::From(e->a, e->b);
sb.auxA = e->auxA;
sbl->l.Add(&sb);
}
for(SBezier *b = sbl->l.First(); b; b = sbl->l.NextAfter(b)) {
for(int i = 0; i <= b->deg; i++) {
b->ctrl[i].z = 0;
}
}
// If possible, then we will assemble these output curves into loops. They
// will then get exported as closed paths.
SBezierLoopSetSet sblss = {};
SBezierLoopSet leftovers = {};
SSurface srf = SSurface::FromPlane(Vector::From(0, 0, 0),
Vector::From(1, 0, 0),
Vector::From(0, 1, 0));
SPolygon spxyz = {};
bool allClosed;
SEdge notClosedAt;
sbl->l.ClearTags();
sblss.FindOuterFacesFrom(sbl, &spxyz, &srf,
SS.ExportChordTolMm(),
&allClosed, ¬ClosedAt,
NULL, NULL,
&leftovers);
sblss.l.Add(&leftovers);
// Now write the lines and triangles to the output file
out->OutputLinesAndMesh(&sblss, &sms);
spxyz.Clear();
sblss.Clear();
smp.Clear();
sms.Clear();
hlrd.Clear();
}
double VectorFileWriter::MmToPts(double mm) {
// 72 points in an inch
return (mm/25.4)*72;
}
VectorFileWriter *VectorFileWriter::ForFile(const Platform::Path &filename) {
VectorFileWriter *ret;
bool needOpen = true;
if(filename.HasExtension("dxf")) {
static DxfFileWriter DxfWriter;
ret = &DxfWriter;
needOpen = false;
} else if(filename.HasExtension("ps") || filename.HasExtension("eps")) {
static EpsFileWriter EpsWriter;
ret = &EpsWriter;
} else if(filename.HasExtension("pdf")) {
static PdfFileWriter PdfWriter;
ret = &PdfWriter;
} else if(filename.HasExtension("svg")) {
static SvgFileWriter SvgWriter;
ret = &SvgWriter;
} else if(filename.HasExtension("plt") || filename.HasExtension("hpgl")) {
static HpglFileWriter HpglWriter;
ret = &HpglWriter;
} else if(filename.HasExtension("step") || filename.HasExtension("stp")) {
static Step2dFileWriter Step2dWriter;
ret = &Step2dWriter;
} else if(filename.HasExtension("txt") || filename.HasExtension("ngc")) {
static GCodeFileWriter GCodeWriter;
ret = &GCodeWriter;
} else {
Error("Can't identify output file type from file extension of "
"filename '%s'; try "
".step, .stp, .dxf, .svg, .plt, .hpgl, .pdf, .txt, .ngc, "
".eps, or .ps.",
filename.raw.c_str());
return NULL;
}
ret->filename = filename;
if(!needOpen) return ret;
FILE *f = OpenFile(filename, "wb");
if(!f) {
Error("Couldn't write to '%s'", filename.raw.c_str());
return NULL;
}
ret->f = f;
return ret;
}
void VectorFileWriter::SetModelviewProjection(const Vector &u, const Vector &v, const Vector &n,
const Vector &origin, double cameraTan,
double scale) {
this->u = u;
this->v = v;
this->n = n;
this->origin = origin;
this->cameraTan = cameraTan;
this->scale = scale;
}
Vector VectorFileWriter::Transform(Vector &pos) const {
return pos.InPerspective(u, v, n, origin, cameraTan).ScaledBy(1.0 / scale);
}
void VectorFileWriter::OutputLinesAndMesh(SBezierLoopSetSet *sblss, SMesh *sm) {
STriangle *tr;
SBezier *b;
// First calculate the bounding box.
ptMin = Vector::From(VERY_POSITIVE, VERY_POSITIVE, VERY_POSITIVE);
ptMax = Vector::From(VERY_NEGATIVE, VERY_NEGATIVE, VERY_NEGATIVE);
if(sm) {
for(tr = sm->l.First(); tr; tr = sm->l.NextAfter(tr)) {
(tr->a).MakeMaxMin(&ptMax, &ptMin);
(tr->b).MakeMaxMin(&ptMax, &ptMin);
(tr->c).MakeMaxMin(&ptMax, &ptMin);
}
}
if(sblss) {
SBezierLoopSet *sbls;
for(sbls = sblss->l.First(); sbls; sbls = sblss->l.NextAfter(sbls)) {
SBezierLoop *sbl;
for(sbl = sbls->l.First(); sbl; sbl = sbls->l.NextAfter(sbl)) {
for(b = sbl->l.First(); b; b = sbl->l.NextAfter(b)) {
for(int i = 0; i <= b->deg; i++) {
(b->ctrl[i]).MakeMaxMin(&ptMax, &ptMin);
}
}
}
}
}
// And now we compute the canvas size.
double s = 1.0 / SS.exportScale;
if(SS.exportCanvasSizeAuto) {
// It's based on the calculated bounding box; we grow it along each
// boundary by the specified amount.
ptMin.x -= s*SS.exportMargin.left;
ptMax.x += s*SS.exportMargin.right;
ptMin.y -= s*SS.exportMargin.bottom;
ptMax.y += s*SS.exportMargin.top;
} else {
ptMin.x = (s*SS.exportCanvas.dx);
ptMin.y = (s*SS.exportCanvas.dy);
ptMax.x = ptMin.x + (s*SS.exportCanvas.width);
ptMax.y = ptMin.y + (s*SS.exportCanvas.height);
}
StartFile();
if(SS.exportBackgroundColor) {
Background(SS.backgroundColor);
}
if(sm && SS.exportShadedTriangles) {
for(tr = sm->l.First(); tr; tr = sm->l.NextAfter(tr)) {
Triangle(tr);
}
}
if(sblss) {
SBezierLoopSet *sbls;
for(sbls = sblss->l.First(); sbls; sbls = sblss->l.NextAfter(sbls)) {
for(SBezierLoop *sbl = sbls->l.First(); sbl; sbl = sbls->l.NextAfter(sbl)) {
b = sbl->l.First();
if(!b || !Style::Exportable(b->auxA)) continue;
hStyle hs = { (uint32_t)b->auxA };
Style *stl = Style::Get(hs);
double lineWidth = Style::WidthMm(b->auxA)*s;
RgbaColor strokeRgb = Style::Color(hs, /*forExport=*/true);
RgbaColor fillRgb = Style::FillColor(hs, /*forExport=*/true);
StartPath(strokeRgb, lineWidth, stl->filled, fillRgb, hs);
for(b = sbl->l.First(); b; b = sbl->l.NextAfter(b)) {
Bezier(b);
}
FinishPath(strokeRgb, lineWidth, stl->filled, fillRgb, hs);
}
}
}
FinishAndCloseFile();
}
void VectorFileWriter::BezierAsPwl(SBezier *sb) {
List<Vector> lv = {};
sb->MakePwlInto(&lv, SS.ExportChordTolMm());
for(int i = 1; i < lv.n; i++) {
SBezier sb = SBezier::From(lv[i-1], lv[i]);
Bezier(&sb);
}
lv.Clear();
}
void VectorFileWriter::BezierAsNonrationalCubic(SBezier *sb, int depth) {
Vector t0 = sb->TangentAt(0), t1 = sb->TangentAt(1);
// The curve is correct, and the first derivatives are correct, at the
// endpoints.
SBezier bnr = SBezier::From(
sb->Start(),
sb->Start().Plus(t0.ScaledBy(1.0/3)),
sb->Finish().Minus(t1.ScaledBy(1.0/3)),
sb->Finish());
double tol = SS.ExportChordTolMm();
// Arbitrary choice, but make it a little finer than pwl tolerance since
// it should be easier to achieve that with the smooth curves.
tol /= 2;
bool closeEnough = true;
int i;
for(i = 1; i <= 3; i++) {
double t = i/4.0;
Vector p0 = sb->PointAt(t),
pn = bnr.PointAt(t);
double d = (p0.Minus(pn)).Magnitude();
if(d > tol) {
closeEnough = false;
}
}
if(closeEnough || depth > 3) {
Bezier(&bnr);
} else {
SBezier bef, aft;
sb->SplitAt(0.5, &bef, &aft);
BezierAsNonrationalCubic(&bef, depth+1);
BezierAsNonrationalCubic(&aft, depth+1);
}
}
//-----------------------------------------------------------------------------
// Export a triangle mesh, in the requested format.
//-----------------------------------------------------------------------------
void SolveSpaceUI::ExportMeshTo(const Platform::Path &filename) {
SS.exportMode = true;
GenerateAll(Generate::ALL);
Group *g = SK.GetGroup(SS.GW.activeGroup);
g->GenerateDisplayItems();
SMesh *m = &(SK.GetGroup(SS.GW.activeGroup)->displayMesh);
if(m->IsEmpty()) {
Error(_("Active group mesh is empty; nothing to export."));
return;
}
FILE *f = OpenFile(filename, "wb");
if(!f) {
Error("Couldn't write to '%s'", filename.raw.c_str());
return;
}
ShowNakedEdges(/*reportOnlyWhenNotOkay=*/true);
if(filename.HasExtension("stl")) {
ExportMeshAsStlTo(f, m);
} else if(filename.HasExtension("obj")) {
Platform::Path mtlFilename = filename.WithExtension("mtl");
FILE *fMtl = OpenFile(mtlFilename, "wb");
if(!fMtl) {
Error("Couldn't write to '%s'", filename.raw.c_str());
return;
}
fprintf(f, "mtllib %s\n", mtlFilename.FileName().c_str());
ExportMeshAsObjTo(f, fMtl, m);
fclose(fMtl);
} else if(filename.HasExtension("js") ||
filename.HasExtension("html")) {
SOutlineList *e = &(SK.GetGroup(SS.GW.activeGroup)->displayOutlines);
ExportMeshAsThreeJsTo(f, filename, m, e);
} else if(filename.HasExtension("wrl")) {
ExportMeshAsVrmlTo(f, filename, m);
} else {
Error("Can't identify output file type from file extension of "
"filename '%s'; try .stl, .obj, .js, .html.", filename.raw.c_str());
}
fclose(f);
SS.justExportedInfo.showOrigin = false;
SS.justExportedInfo.draw = true;
GW.Invalidate();
}
//-----------------------------------------------------------------------------
// Export the mesh as an STL file; it should always be vertex-to-vertex and
// not self-intersecting, so not much to do.
//-----------------------------------------------------------------------------
void SolveSpaceUI::ExportMeshAsStlTo(FILE *f, SMesh *sm) {
char str[80] = {};
strcpy(str, "STL exported mesh");
fwrite(str, 1, 80, f);
uint32_t n = sm->l.n;
fwrite(&n, 4, 1, f);
double s = SS.exportScale;
int i;
for(i = 0; i < sm->l.n; i++) {
STriangle *tr = &(sm->l[i]);
Vector n = tr->Normal().WithMagnitude(1);
float w;
w = (float)n.x; fwrite(&w, 4, 1, f);
w = (float)n.y; fwrite(&w, 4, 1, f);
w = (float)n.z; fwrite(&w, 4, 1, f);
w = (float)((tr->a.x)/s); fwrite(&w, 4, 1, f);
w = (float)((tr->a.y)/s); fwrite(&w, 4, 1, f);
w = (float)((tr->a.z)/s); fwrite(&w, 4, 1, f);
w = (float)((tr->b.x)/s); fwrite(&w, 4, 1, f);
w = (float)((tr->b.y)/s); fwrite(&w, 4, 1, f);
w = (float)((tr->b.z)/s); fwrite(&w, 4, 1, f);
w = (float)((tr->c.x)/s); fwrite(&w, 4, 1, f);
w = (float)((tr->c.y)/s); fwrite(&w, 4, 1, f);
w = (float)((tr->c.z)/s); fwrite(&w, 4, 1, f);
fputc(0, f);
fputc(0, f);
}
}
//-----------------------------------------------------------------------------
// Export the mesh as Wavefront OBJ format. This requires us to reduce all the
// identical vertices to the same identifier, so do that first.
//-----------------------------------------------------------------------------
void SolveSpaceUI::ExportMeshAsObjTo(FILE *fObj, FILE *fMtl, SMesh *sm) {
std::map<RgbaColor, std::string, RgbaColorCompare> colors;
for(const STriangle &t : sm->l) {
RgbaColor color = t.meta.color;
if(colors.find(color) == colors.end()) {
std::string id = ssprintf("h%02x%02x%02x",
color.red,
color.green,
color.blue);
colors.emplace(color, id);
}
for(int i = 0; i < 3; i++) {
fprintf(fObj, "v %.10f %.10f %.10f\n",
CO(t.vertices[i].ScaledBy(1 / SS.exportScale)));
}
}
for(auto &it : colors) {
fprintf(fMtl, "newmtl %s\n",
it.second.c_str());
fprintf(fMtl, "Kd %.3f %.3f %.3f\n",
it.first.redF(), it.first.greenF(), it.first.blueF());
}
for(const STriangle &t : sm->l) {
for(int i = 0; i < 3; i++) {
Vector n = t.normals[i].WithMagnitude(1.0);
fprintf(fObj, "vn %.10f %.10f %.10f\n",
CO(n));
}
}
RgbaColor currentColor = {};
for(int i = 0; i < sm->l.n; i++) {
const STriangle &t = sm->l[i];
if(!currentColor.Equals(t.meta.color)) {
currentColor = t.meta.color;
fprintf(fObj, "usemtl %s\n", colors[currentColor].c_str());
}
fprintf(fObj, "f %d//%d %d//%d %d//%d\n",
i * 3 + 1, i * 3 + 1,
i * 3 + 2, i * 3 + 2,
i * 3 + 3, i * 3 + 3);
}
}
//-----------------------------------------------------------------------------
// Export the mesh as a JavaScript script, which is compatible with Three.js.
//-----------------------------------------------------------------------------
void SolveSpaceUI::ExportMeshAsThreeJsTo(FILE *f, const Platform::Path &filename,
SMesh *sm, SOutlineList *sol)
{
SPointList spl = {};
STriangle *tr;
Vector bndl, bndh;
const std::string THREE_FN("three-r111.min.js");
const std::string HAMMER_FN("hammer-2.0.8.js");
const std::string CONTROLS_FN("SolveSpaceControls.js");
const char htmlbegin[] = R"(
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"></meta>
<title>Three.js Solvespace Mesh</title>
<script id="%s">%s</script>
<script id="%s">%s</script>
<script id="%s">%s</script>
<style type="text/css">
body { margin: 0; overflow: hidden; }
</style>
</head>
<body>
<script>
)";
const char htmlend[] = R"(
document.body.appendChild(solvespace(solvespace_model_%s, {
scale: %g,
offset: new THREE.Vector3(%g, %g, %g),
projUp: new THREE.Vector3(%g, %g, %g),
projRight: new THREE.Vector3(%g, %g, %g)
}));
</script>
</body>
</html>
)";
// A default three.js viewer with OrthographicTrackballControls is
// generated as a comment preceding the data.
// x bounds should be the range of x or y, whichever
// is larger, before aspect ratio correction is applied.
// y bounds should be the range of x or y, whichever is
// larger. No aspect ratio correction is applied.
// Near plane should be 1.
// Camera's z-position should be the range of z + 1 or the larger of
// the x or y bounds, whichever is larger.
// Far plane should be at least twice as much as the camera's
// z-position.
// Edge projection bias should be about 1/500 of the far plane's distance.