summaryrefslogtreecommitdiffstats
path: root/src/object/box3d.cpp
blob: 49a57b8f070cd8daa503b5eb1813682eac8a24ae (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
// SPDX-License-Identifier: GPL-2.0-or-later
/*
 * SVG <box3d> implementation
 *
 * Authors:
 *   Maximilian Albert <Anhalter42@gmx.de>
 *   Lauris Kaplinski <lauris@kaplinski.com>
 *   bulia byak <buliabyak@users.sf.net>
 *   Abhishek Sharma
 *   Jon A. Cruz <jon@joncruz.org>
 *
 * Copyright (C) 2007      Authors
 * Copyright (C) 1999-2002 Lauris Kaplinski
 * Copyright (C) 2000-2001 Ximian, Inc.
 *
 * Released under GNU GPL v2+, read the file 'COPYING' for more information.
 */

#include "box3d.h"

#include <glibmm/i18n.h>
#include "attributes.h"
#include "xml/document.h"
#include "xml/repr.h"

#include "bad-uri-exception.h"
#include "box3d-side.h"
#include "ui/tools/box3d-tool.h"
#include "perspective-line.h"
#include "persp3d-reference.h"
#include "uri.h"
#include <2geom/line.h>
#include "sp-guide.h"
#include "sp-namedview.h"

#include "desktop.h"

#include "include/macros.h"

static void box3d_ref_changed(SPObject *old_ref, SPObject *ref, SPBox3D *box);

static gint counter = 0;

SPBox3D::SPBox3D() : SPGroup() {
    this->my_counter = 0;
    this->swapped = Box3D::NONE;

    this->persp_href = nullptr;
    this->persp_ref = new Persp3DReference(this);

    /* we initialize the z-orders to zero so that they are updated during dragging */
    for (int & z_order : z_orders) {
        z_order = 0;
    }
}

SPBox3D::~SPBox3D() = default;

void SPBox3D::build(SPDocument *document, Inkscape::XML::Node *repr) {
    SPGroup::build(document, repr);

    my_counter = counter++;

    /* we initialize the z-orders to zero so that they are updated during dragging */
    for (int & z_order : z_orders) {
        z_order = 0;
    }

    // TODO: Create/link to the correct perspective

    if ( document ) {
        persp_ref->changedSignal().connect(sigc::bind(sigc::ptr_fun(box3d_ref_changed), this));

        readAttr(SPAttr::INKSCAPE_BOX3D_PERSPECTIVE_ID);
        readAttr(SPAttr::INKSCAPE_BOX3D_CORNER0);
        readAttr(SPAttr::INKSCAPE_BOX3D_CORNER7);
    }
}

void SPBox3D::release() {
    SPBox3D* object = this;
    SPBox3D *box = object;

    if (box->persp_href) {
        g_free(box->persp_href);
    }

    // We have to store this here because the Persp3DReference gets destroyed below, but we need to
    // access it to call Persp3D::remove_box(), which cannot be called earlier because the reference
    // needs to be destroyed first.
    Persp3D *persp = box->get_perspective();

    if (box->persp_ref) {
        box->persp_ref->detach();
        delete box->persp_ref;
        box->persp_ref = nullptr;
    }
    if (persp) {
        persp->remove_box (box);

        if (persp->perspective_impl->boxes.empty()) {
            SPDocument *doc = box->document;
            doc->setCurrentPersp3D(Persp3D::document_first_persp(doc));
        }
    }

    SPGroup::release();
}

void SPBox3D::set(SPAttr key, const gchar* value) {
    SPBox3D* object = this;
    SPBox3D *box = object;

    switch (key) {
        case SPAttr::INKSCAPE_BOX3D_PERSPECTIVE_ID:
            if ( value && box->persp_href && ( strcmp(value, box->persp_href) == 0 ) ) {
                /* No change, do nothing. */
            } else {
                if (box->persp_href) {
                    g_free(box->persp_href);
                    box->persp_href = nullptr;
                }
                if (value) {
                    box->persp_href = g_strdup(value);

                    // Now do the attaching, which emits the changed signal.
                    try {
                        box->persp_ref->attach(Inkscape::URI(value));
                    } catch (Inkscape::BadURIException &e) {
                        g_warning("%s", e.what());
                        box->persp_ref->detach();
                    }
                } else {
                    // Detach, which emits the changed signal.
                    box->persp_ref->detach();
                }
            }

            // FIXME: Is the following update doubled by some call in either persp3d.cpp or vanishing_point_new.cpp?
            box->position_set();
            break;
        case SPAttr::INKSCAPE_BOX3D_CORNER0:
            if (value && strcmp(value, "0 : 0 : 0 : 0")) {
                box->orig_corner0 = Proj::Pt3(value);
                box->save_corner0 = box->orig_corner0;
                box->position_set();
            }
            break;
        case SPAttr::INKSCAPE_BOX3D_CORNER7:
            if (value && strcmp(value, "0 : 0 : 0 : 0")) {
                box->orig_corner7 = Proj::Pt3(value);
                box->save_corner7 = box->orig_corner7;
                box->position_set();
            }
            break;
        default:
            SPGroup::set(key, value);
            break;
    }
}

/**
 * Gets called when (re)attached to another perspective.
 */
static void
box3d_ref_changed(SPObject *old_ref, SPObject *ref, SPBox3D *box)
{
    if (old_ref && G_TYPE_CHECK_INSTANCE((gpointer)old_ref)) { // See issue 2390 (crash when quitting while dragging a 3D Box) ...
        //... G_TYPE_CHECK_INSTANCE prevents triggering a glib assert after the SPObject has been deleted; a warning will still be thrown though
        sp_signal_disconnect_by_data(old_ref, box);
        Persp3D *oldPersp = dynamic_cast<Persp3D *>(old_ref);
        if (oldPersp) {
            oldPersp->remove_box(box);
        }
    }
    Persp3D *persp = dynamic_cast<Persp3D *>(ref);
    if ( persp && (ref != box) ) // FIXME: Comparisons sane?
    {
        persp->add_box(box);
    }
}

void SPBox3D::update(SPCtx *ctx, guint flags) {
    if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) {

        /* FIXME?: Perhaps the display updates of box sides should be instantiated from here, but this
           causes evil update loops so it's all done from SPBox3D::position_set, which is called from
           various other places (like the handlers in shape-editor-knotholders.cpp, vanishing-point.cpp, etc. */

    }

    // Invoke parent method
    SPGroup::update(ctx, flags);
}

Inkscape::XML::Node* SPBox3D::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) {
    SPBox3D* object = this;
    SPBox3D *box = object;

    if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) {
        // this is where we end up when saving as plain SVG (also in other circumstances?)
        // thus we don' set "sodipodi:type" so that the box is only saved as an ordinary svg:g
        repr = xml_doc->createElement("svg:g");
    }

    if (flags & SP_OBJECT_WRITE_EXT) {

        if (box->persp_href) {
            repr->setAttribute("inkscape:perspectiveID", box->persp_href);
        } else {
            /* box is not yet linked to a perspective; use the document's current perspective */
            SPDocument *doc = object->document;
            if (box->persp_ref->getURI()) {
                auto uri_string = box->persp_ref->getURI()->str();
                repr->setAttributeOrRemoveIfEmpty("inkscape:perspectiveID", uri_string);
            } else {
                Glib::ustring href = "#";
                href += doc->getCurrentPersp3D()->getId();
                repr->setAttribute("inkscape:perspectiveID", href);
            }
        }

        gchar *coordstr0 = box->orig_corner0.coord_string();
        gchar *coordstr7 = box->orig_corner7.coord_string();
        repr->setAttribute("inkscape:corner0", coordstr0);
        repr->setAttribute("inkscape:corner7", coordstr7);
        g_free(coordstr0);
        g_free(coordstr7);

        box->orig_corner0.normalize();
        box->orig_corner7.normalize();

        box->save_corner0 = box->orig_corner0;
        box->save_corner7 = box->orig_corner7;
    }

    SPGroup::write(xml_doc, repr, flags);

    return repr;
}

const char* SPBox3D::display_name() {
    return _("3D Box");
}

void SPBox3D::position_set()
{
    /* This draws the curve and calls requestDisplayUpdate() for each side (the latter is done in
       Box3DSide::position_set() to avoid update conflicts with the parent box) */
    for (auto& obj: this->children) {
        Box3DSide *side = dynamic_cast<Box3DSide *>(&obj);
        if (side) {
            side->position_set();
        }
    }
}

Geom::Affine SPBox3D::set_transform(Geom::Affine const &xform) {
    // We don't apply the transform to the box directly but instead to its perspective (which is
    // done in sp_selection_apply_affine). Here we only adjust strokes, patterns, etc.

    Geom::Affine ret(Geom::Affine(xform).withoutTranslation());
    gdouble const sw = hypot(ret[0], ret[1]);
    gdouble const sh = hypot(ret[2], ret[3]);

    for (auto& child: children) {
        SPItem *childitem = dynamic_cast<SPItem *>(&child);
        if (childitem) {
            // Adjust stroke width
            childitem->adjust_stroke(sqrt(fabs(sw * sh)));

            // Adjust pattern fill
            childitem->adjust_pattern(xform);

            // Adjust gradient fill
            childitem->adjust_gradient(xform);
        }
    }

    return Geom::identity();
}

static Proj::Pt3
box3d_get_proj_corner (guint id, Proj::Pt3 const &c0, Proj::Pt3 const &c7) {
    return Proj::Pt3 ((id & Box3D::X) ? c7[Proj::X] : c0[Proj::X],
                      (id & Box3D::Y) ? c7[Proj::Y] : c0[Proj::Y],
                      (id & Box3D::Z) ? c7[Proj::Z] : c0[Proj::Z],
                      1.0);
}

static Proj::Pt3
box3d_get_proj_corner (SPBox3D const *box, guint id) {
    return Proj::Pt3 ((id & Box3D::X) ? box->orig_corner7[Proj::X] : box->orig_corner0[Proj::X],
                      (id & Box3D::Y) ? box->orig_corner7[Proj::Y] : box->orig_corner0[Proj::Y],
                      (id & Box3D::Z) ? box->orig_corner7[Proj::Z] : box->orig_corner0[Proj::Z],
                      1.0);
}

Geom::Point
SPBox3D::get_corner_screen (guint id, bool item_coords) const {
    Proj::Pt3 proj_corner (box3d_get_proj_corner (this, id));
    if (!this->get_perspective()) {
        return Geom::Point (Geom::infinity(), Geom::infinity());
    }
    Geom::Affine const i2d(this->i2dt_affine ());
    if (item_coords) {
        return this->get_perspective()->perspective_impl->tmat.image(proj_corner).affine() * i2d.inverse();
    } else {
        return this->get_perspective()->perspective_impl->tmat.image(proj_corner).affine();
    }
}

Proj::Pt3
SPBox3D::get_proj_center () {
    this->orig_corner0.normalize();
    this->orig_corner7.normalize();
    return Proj::Pt3 ((this->orig_corner0[Proj::X] + this->orig_corner7[Proj::X]) / 2,
                      (this->orig_corner0[Proj::Y] + this->orig_corner7[Proj::Y]) / 2,
                      (this->orig_corner0[Proj::Z] + this->orig_corner7[Proj::Z]) / 2,
                      1.0);
}

Geom::Point
SPBox3D::get_center_screen () {
    Proj::Pt3 proj_center (this->get_proj_center ());
    if (!this->get_perspective()) {
        return Geom::Point (Geom::infinity(), Geom::infinity());
    }
    Geom::Affine const i2d( this->i2dt_affine() );
    return this->get_perspective()->perspective_impl->tmat.image(proj_center).affine() * i2d.inverse();
}

/*
 * To keep the snappoint from jumping randomly between the two lines when the mouse pointer is close to
 * their intersection, we remember the last snapped line and keep snapping to this specific line as long
 * as the distance from the intersection to the mouse pointer is less than remember_snap_threshold.
 */

// Should we make the threshold settable in the preferences?
static double remember_snap_threshold = 30;
static guint remember_snap_index = 0;

// constant for sizing the array of points to be considered:
static const int MAX_POINT_COUNT = 4;

static Proj::Pt3
box3d_snap (SPBox3D *box, int id, Proj::Pt3 const &pt_proj, Proj::Pt3 const &start_pt) {
    double z_coord = start_pt[Proj::Z];
    double diff_x = box->save_corner7[Proj::X] - box->save_corner0[Proj::X];
    double diff_y = box->save_corner7[Proj::Y] - box->save_corner0[Proj::Y];
    double x_coord = start_pt[Proj::X];
    double y_coord = start_pt[Proj::Y];
    Proj::Pt3 A_proj (x_coord,          y_coord,          z_coord, 1.0);
    Proj::Pt3 B_proj (x_coord + diff_x, y_coord,          z_coord, 1.0);
    Proj::Pt3 C_proj (x_coord + diff_x, y_coord + diff_y, z_coord, 1.0);
    Proj::Pt3 D_proj (x_coord,          y_coord + diff_y, z_coord, 1.0);
    Proj::Pt3 E_proj (x_coord - diff_x, y_coord + diff_y, z_coord, 1.0);

    Persp3DImpl *persp_impl = box->get_perspective()->perspective_impl;
    Geom::Point A = persp_impl->tmat.image(A_proj).affine();
    Geom::Point B = persp_impl->tmat.image(B_proj).affine();
    Geom::Point C = persp_impl->tmat.image(C_proj).affine();
    Geom::Point D = persp_impl->tmat.image(D_proj).affine();
    Geom::Point E = persp_impl->tmat.image(E_proj).affine();
    Geom::Point pt = persp_impl->tmat.image(pt_proj).affine();

    // TODO: Replace these lines between corners with lines from a corner to a vanishing point
    //       (this might help to prevent rounding errors if the box is small)
    Box3D::Line pl1(A, B);
    Box3D::Line pl2(A, D);
    Box3D::Line diag1(A, (id == -1 || (!(id & Box3D::X) == !(id & Box3D::Y))) ? C : E);
    Box3D::Line diag2(A, E); // diag2 is only taken into account if id equals -1, i.e., if we are snapping the center

    int num_snap_lines = (id != -1) ? 3 : 4;
    Geom::Point snap_pts[MAX_POINT_COUNT];

    snap_pts[0] = pl1.closest_to (pt);
    snap_pts[1] = pl2.closest_to (pt);
    snap_pts[2] = diag1.closest_to (pt);
    if (id == -1) {
        snap_pts[3] = diag2.closest_to (pt);
    }

    gdouble const zoom = SP_ACTIVE_DESKTOP->current_zoom();

    // determine the distances to all potential snapping points
    double snap_dists[MAX_POINT_COUNT];
    for (int i = 0; i < num_snap_lines; ++i) {
        snap_dists[i] = Geom::L2 (snap_pts[i] - pt) * zoom;
    }

    // while we are within a given tolerance of the starting point,
    // keep snapping to the same point to avoid jumping
    bool within_tolerance = true;
    for (int i = 0; i < num_snap_lines; ++i) {
        if (snap_dists[i] > remember_snap_threshold) {
            within_tolerance = false;
            break;
        }
    }

    // find the closest snapping point
    int snap_index = -1;
    double snap_dist = Geom::infinity();
    for (int i = 0; i < num_snap_lines; ++i) {
        if (snap_dists[i] < snap_dist) {
            snap_index = i;
            snap_dist = snap_dists[i];
        }
    }

    // snap to the closest point (or the previously remembered one
    // if we are within tolerance of the starting point)
    Geom::Point result;
    if (within_tolerance) {
        result = snap_pts[remember_snap_index];
    } else {
        remember_snap_index = snap_index;
        result = snap_pts[snap_index];
    }
    return box->get_perspective()->perspective_impl->tmat.preimage (result, z_coord, Proj::Z);
}

SPBox3D * SPBox3D::createBox3D(SPItem * parent)
{
    SPBox3D *box3d = nullptr;
    Inkscape::XML::Document *xml_doc = parent->document->getReprDoc();
    Inkscape::XML::Node *repr = xml_doc->createElement("svg:g");
    repr->setAttribute("sodipodi:type", "inkscape:box3d");
    box3d = reinterpret_cast<SPBox3D *>(parent->appendChildRepr(repr));
    return box3d;
}

void
SPBox3D::set_corner (const guint id, Geom::Point const &new_pos, const Box3D::Axis movement, bool constrained) {
    g_return_if_fail ((movement != Box3D::NONE) && (movement != Box3D::XYZ));

    this->orig_corner0.normalize();
    this->orig_corner7.normalize();

    /* update corners 0 and 7 according to which handle was moved and to the axes of movement */
    if (!(movement & Box3D::Z)) {
        Persp3DImpl *persp_impl = this->get_perspective()->perspective_impl;
        Proj::Pt3 pt_proj (persp_impl->tmat.preimage (new_pos, (id < 4) ? this->orig_corner0[Proj::Z] :
                                                      this->orig_corner7[Proj::Z], Proj::Z));
        if (constrained) {
            pt_proj = box3d_snap (this, id, pt_proj, box3d_get_proj_corner (id, this->save_corner0, this->save_corner7));
        }

        // normalizing pt_proj is essential because we want to mingle affine coordinates
        pt_proj.normalize();
        this->orig_corner0 = Proj::Pt3 ((id & Box3D::X) ? this->save_corner0[Proj::X] : pt_proj[Proj::X],
                                       (id & Box3D::Y) ? this->save_corner0[Proj::Y] : pt_proj[Proj::Y],
                                       this->save_corner0[Proj::Z],
                                       1.0);
        this->orig_corner7 = Proj::Pt3 ((id & Box3D::X) ? pt_proj[Proj::X] : this->save_corner7[Proj::X],
                                       (id & Box3D::Y) ? pt_proj[Proj::Y] : this->save_corner7[Proj::Y],
                                       this->save_corner7[Proj::Z],
                                       1.0);
    } else {
        Persp3D *persp = this->get_perspective();
        Persp3DImpl *persp_impl = this->get_perspective()->perspective_impl;
        Box3D::PerspectiveLine pl(persp_impl->tmat.image(
                                      box3d_get_proj_corner (id, this->save_corner0, this->save_corner7)).affine(),
                                  Proj::Z, persp);
        Geom::Point new_pos_snapped(pl.closest_to(new_pos));
        Proj::Pt3 pt_proj (persp_impl->tmat.preimage (new_pos_snapped,
                                      box3d_get_proj_corner (this, id)[(movement & Box3D::Y) ? Proj::X : Proj::Y],
                                                      (movement & Box3D::Y) ? Proj::X : Proj::Y));
        bool corner0_move_x = !(id & Box3D::X) && (movement & Box3D::X);
        bool corner0_move_y = !(id & Box3D::Y) && (movement & Box3D::Y);
        bool corner7_move_x =  (id & Box3D::X) && (movement & Box3D::X);
        bool corner7_move_y =  (id & Box3D::Y) && (movement & Box3D::Y);
        // normalizing pt_proj is essential because we want to mingle affine coordinates
        pt_proj.normalize();
        this->orig_corner0 = Proj::Pt3 (corner0_move_x ? pt_proj[Proj::X] : this->orig_corner0[Proj::X],
                                       corner0_move_y ? pt_proj[Proj::Y] : this->orig_corner0[Proj::Y],
                                       (id & Box3D::Z) ? this->orig_corner0[Proj::Z] : pt_proj[Proj::Z],
                                       1.0);
        this->orig_corner7 = Proj::Pt3 (corner7_move_x ? pt_proj[Proj::X] : this->orig_corner7[Proj::X],
                                       corner7_move_y ? pt_proj[Proj::Y] : this->orig_corner7[Proj::Y],
                                       (id & Box3D::Z) ? pt_proj[Proj::Z] : this->orig_corner7[Proj::Z],
                                       1.0);
    }
    // FIXME: Should we update the box here? If so, how?
}

void SPBox3D::set_center (Geom::Point const &new_pos, Geom::Point const &old_pos, const Box3D::Axis movement, bool constrained) {
    g_return_if_fail ((movement != Box3D::NONE) && (movement != Box3D::XYZ));

    this->orig_corner0.normalize();
    this->orig_corner7.normalize();

    Persp3D *persp = this->get_perspective();
    if (!(movement & Box3D::Z)) {
        double coord = (this->orig_corner0[Proj::Z] + this->orig_corner7[Proj::Z]) / 2;
        double radx = (this->orig_corner7[Proj::X] - this->orig_corner0[Proj::X]) / 2;
        double rady = (this->orig_corner7[Proj::Y] - this->orig_corner0[Proj::Y]) / 2;

        Proj::Pt3 pt_proj (persp->perspective_impl->tmat.preimage (new_pos, coord, Proj::Z));
        if (constrained) {
            Proj::Pt3 old_pos_proj (persp->perspective_impl->tmat.preimage (old_pos, coord, Proj::Z));
            old_pos_proj.normalize();
            pt_proj = box3d_snap (this, -1, pt_proj, old_pos_proj);
        }
        // normalizing pt_proj is essential because we want to mingle affine coordinates
        pt_proj.normalize();
        this->orig_corner0 = Proj::Pt3 ((movement & Box3D::X) ? pt_proj[Proj::X] - radx : this->orig_corner0[Proj::X],
                                       (movement & Box3D::Y) ? pt_proj[Proj::Y] - rady : this->orig_corner0[Proj::Y],
                                       this->orig_corner0[Proj::Z],
                                       1.0);
        this->orig_corner7 = Proj::Pt3 ((movement & Box3D::X) ? pt_proj[Proj::X] + radx : this->orig_corner7[Proj::X],
                                       (movement & Box3D::Y) ? pt_proj[Proj::Y] + rady : this->orig_corner7[Proj::Y],
                                       this->orig_corner7[Proj::Z],
                                       1.0);
    } else {
        double coord = (this->orig_corner0[Proj::X] + this->orig_corner7[Proj::X]) / 2;
        double radz = (this->orig_corner7[Proj::Z] - this->orig_corner0[Proj::Z]) / 2;

        Box3D::PerspectiveLine pl(old_pos, Proj::Z, persp);
        Geom::Point new_pos_snapped(pl.closest_to(new_pos));
        Proj::Pt3 pt_proj (persp->perspective_impl->tmat.preimage (new_pos_snapped, coord, Proj::X));

        /* normalizing pt_proj is essential because we want to mingle affine coordinates */
        pt_proj.normalize();
        this->orig_corner0 = Proj::Pt3 (this->orig_corner0[Proj::X],
                                       this->orig_corner0[Proj::Y],
                                       pt_proj[Proj::Z] - radz,
                                       1.0);
        this->orig_corner7 = Proj::Pt3 (this->orig_corner7[Proj::X],
                                       this->orig_corner7[Proj::Y],
                                       pt_proj[Proj::Z] + radz,
                                       1.0);
    }
}

/*
 * Manipulates corner1 through corner4 to contain the indices of the corners
 * from which the perspective lines in the direction of 'axis' emerge
 */
void SPBox3D::corners_for_PLs (Proj::Axis axis,
                            Geom::Point &corner1, Geom::Point &corner2, Geom::Point &corner3, Geom::Point &corner4) const
{
    Persp3D *persp = this->get_perspective();
    g_return_if_fail (persp);
    Persp3DImpl *persp_impl = persp->perspective_impl;
    //this->orig_corner0.normalize();
    //this->orig_corner7.normalize();
    double coord = (this->orig_corner0[axis] > this->orig_corner7[axis]) ?
        this->orig_corner0[axis] :
        this->orig_corner7[axis];

    Proj::Pt3 c1, c2, c3, c4;
    // FIXME: This can certainly be done more elegantly/efficiently than by a case-by-case analysis.
    switch (axis) {
        case Proj::X:
            c1 = Proj::Pt3 (coord, this->orig_corner0[Proj::Y], this->orig_corner0[Proj::Z], 1.0);
            c2 = Proj::Pt3 (coord, this->orig_corner7[Proj::Y], this->orig_corner0[Proj::Z], 1.0);
            c3 = Proj::Pt3 (coord, this->orig_corner7[Proj::Y], this->orig_corner7[Proj::Z], 1.0);
            c4 = Proj::Pt3 (coord, this->orig_corner0[Proj::Y], this->orig_corner7[Proj::Z], 1.0);
            break;
        case Proj::Y:
            c1 = Proj::Pt3 (this->orig_corner0[Proj::X], coord, this->orig_corner0[Proj::Z], 1.0);
            c2 = Proj::Pt3 (this->orig_corner7[Proj::X], coord, this->orig_corner0[Proj::Z], 1.0);
            c3 = Proj::Pt3 (this->orig_corner7[Proj::X], coord, this->orig_corner7[Proj::Z], 1.0);
            c4 = Proj::Pt3 (this->orig_corner0[Proj::X], coord, this->orig_corner7[Proj::Z], 1.0);
            break;
        case Proj::Z:
            c1 = Proj::Pt3 (this->orig_corner7[Proj::X], this->orig_corner7[Proj::Y], coord, 1.0);
            c2 = Proj::Pt3 (this->orig_corner7[Proj::X], this->orig_corner0[Proj::Y], coord, 1.0);
            c3 = Proj::Pt3 (this->orig_corner0[Proj::X], this->orig_corner0[Proj::Y], coord, 1.0);
            c4 = Proj::Pt3 (this->orig_corner0[Proj::X], this->orig_corner7[Proj::Y], coord, 1.0);
            break;
        default:
            return;
    }
    corner1 = persp_impl->tmat.image(c1).affine();
    corner2 = persp_impl->tmat.image(c2).affine();
    corner3 = persp_impl->tmat.image(c3).affine();
    corner4 = persp_impl->tmat.image(c4).affine();
}

/* Auxiliary function: Checks whether the half-line from A to B crosses the line segment joining C and D */
static bool
box3d_half_line_crosses_joining_line (Geom::Point const &A, Geom::Point const &B,
                                      Geom::Point const &C, Geom::Point const &D) {
    Geom::Point n0 = (B - A).ccw();
    double d0 = dot(n0,A);

    Geom::Point n1 = (D - C).ccw();
    double d1 = dot(n1,C);

    Geom::Line lineAB(A,B);
    Geom::Line lineCD(C,D);

    Geom::OptCrossing inters = Geom::OptCrossing(); // empty by default
    try
    {
        inters = Geom::intersection(lineAB, lineCD);
    }
    catch (Geom::InfiniteSolutions& e)
    {
        // We're probably dealing with parallel lines, so they don't really cross
        return false;
    }

    if (!inters) {
        return false;
    }

    Geom::Point E = lineAB.pointAt((*inters).ta); // the point of intersection

    if ((dot(C,n0) < d0) == (dot(D,n0) < d0)) {
        // C and D lie on the same side of the line AB
        return false;
    }
    if ((dot(A,n1) < d1) != (dot(B,n1) < d1)) {
        // A and B lie on different sides of the line CD
        return true;
    } else if (Geom::distance(E,A) < Geom::distance(E,B)) {
        // The line CD passes on the "wrong" side of A
        return false;
    }

    // The line CD passes on the "correct" side of A
    return true;
}

static bool
box3d_XY_axes_are_swapped (SPBox3D *box) {
    Persp3D *persp = box->get_perspective();
    g_return_val_if_fail(persp, false);
    Box3D::PerspectiveLine l1(box->get_corner_screen(3, false), Proj::X, persp);
    Box3D::PerspectiveLine l2(box->get_corner_screen(3, false), Proj::Y, persp);
    Geom::Point v1(l1.direction());
    Geom::Point v2(l2.direction());
    v1.normalize();
    v2.normalize();

    return (v1[Geom::X]*v2[Geom::Y] - v1[Geom::Y]*v2[Geom::X] > 0);
}

static inline void
box3d_aux_set_z_orders (int z_orders[6], int a, int b, int c, int d, int e, int f) {
    // TODO add function argument: SPDocument *doc = box->document
    auto doc = SP_ACTIVE_DOCUMENT;

    if (doc->is_yaxisdown()) {
        std::swap(a, f);
        std::swap(b, e);
        std::swap(c, d);
    }

    z_orders[0] = a;
    z_orders[1] = b;
    z_orders[2] = c;
    z_orders[3] = d;
    z_orders[4] = e;
    z_orders[5] = f;
}


/*
 * In standard perspective we have:
 * 2 = front face
 * 1 = top face
 * 0 = left face
 * 3 = right face
 * 4 = bottom face
 * 5 = rear face
 */

/* All VPs infinite */
static void
box3d_set_new_z_orders_case0 (SPBox3D *box, int z_orders[6], Box3D::Axis central_axis) {
    bool swapped = box3d_XY_axes_are_swapped(box);

    switch(central_axis) {
        case Box3D::X:
            if (!swapped) {
                box3d_aux_set_z_orders (z_orders, 2, 0, 4, 1, 3, 5);
            } else {
                box3d_aux_set_z_orders (z_orders, 3, 1, 5, 2, 4, 0);
            }
            break;
        case Box3D::Y:
            if (!swapped) {
                box3d_aux_set_z_orders (z_orders, 2, 3, 1, 4, 0, 5);
            } else {
                box3d_aux_set_z_orders (z_orders, 5, 0, 4, 1, 3, 2);
            }
            break;
        case Box3D::Z:
            if (!swapped) {
                box3d_aux_set_z_orders (z_orders, 2, 0, 1, 4, 3, 5);
            } else {
                box3d_aux_set_z_orders (z_orders, 5, 3, 4, 1, 0, 2);
            }
            break;
        case Box3D::NONE:
            if (!swapped) {
                box3d_aux_set_z_orders (z_orders, 2, 3, 4, 1, 0, 5);
            } else {
                box3d_aux_set_z_orders (z_orders, 5, 0, 1, 4, 3, 2);
            }
            break;
        default:
            g_assert_not_reached();
            break;
    }
}

/* Precisely one finite VP */
static void
box3d_set_new_z_orders_case1 (SPBox3D *box, int z_orders[6], Box3D::Axis central_axis, Box3D::Axis fin_axis) {
    Persp3D *persp = box->get_perspective();
    Geom::Point vp(persp->get_VP(Box3D::toProj(fin_axis)).affine());

    // note: in some of the case distinctions below we rely upon the fact that oaxis1 and oaxis2 are ordered
    Box3D::Axis oaxis1 = Box3D::get_remaining_axes(fin_axis).first;
    Box3D::Axis oaxis2 = Box3D::get_remaining_axes(fin_axis).second;
    int inside1 = 0;
    int inside2 = 0;
    inside1 = box->pt_lies_in_PL_sector (vp, 3, 3 ^ oaxis2, oaxis1);
    inside2 = box->pt_lies_in_PL_sector (vp, 3, 3 ^ oaxis1, oaxis2);

    bool swapped = box3d_XY_axes_are_swapped(box);

    switch(central_axis) {
        case Box3D::X:
            if (!swapped) {
                box3d_aux_set_z_orders (z_orders, 2, 4, 0, 1, 3, 5);
            } else {
                box3d_aux_set_z_orders (z_orders, 5, 3, 1, 0, 2, 4);
            }
            break;
        case Box3D::Y:
            if (inside2 > 0) {
                box3d_aux_set_z_orders (z_orders, 1, 2, 3, 0, 5, 4);
            } else if (inside2 < 0) {
                box3d_aux_set_z_orders (z_orders, 2, 3, 1, 4, 0, 5);
            } else {
                if (!swapped) {
                    box3d_aux_set_z_orders (z_orders, 2, 3, 1, 5, 0, 4);
                } else {
                    box3d_aux_set_z_orders (z_orders, 5, 0, 4, 1, 3, 2);
                }
            }
            break;
        case Box3D::Z:
            if (inside2) {
                if (!swapped) {
                    box3d_aux_set_z_orders (z_orders, 2, 1, 3, 0, 4, 5);
                } else {
                    box3d_aux_set_z_orders (z_orders, 5, 3, 4, 0, 1, 2);
                }
            } else if (inside1) {
                if (!swapped) {
                    box3d_aux_set_z_orders (z_orders, 2, 0, 1, 4, 3, 5);
                } else {
                    box3d_aux_set_z_orders (z_orders, 5, 3, 4, 1, 0, 2);
                }
            } else {
                // "regular" case
                if (!swapped) {
                    box3d_aux_set_z_orders (z_orders, 0, 1, 2, 5, 4, 3);
                } else {
                    box3d_aux_set_z_orders (z_orders, 5, 3, 4, 0, 2, 1);
                }
            }
            break;
        case Box3D::NONE:
            if (!swapped) {
                box3d_aux_set_z_orders (z_orders, 2, 3, 4, 5, 0, 1);
            } else {
                box3d_aux_set_z_orders (z_orders, 5, 0, 1, 3, 2, 4);
            }
            break;
        default:
            g_assert_not_reached();
    }
}

/* Precisely 2 finite VPs */
static void
box3d_set_new_z_orders_case2 (SPBox3D *box, int z_orders[6], Box3D::Axis central_axis, Box3D::Axis /*infinite_axis*/) {
    bool swapped = box3d_XY_axes_are_swapped(box);

    int insidexy = box->VP_lies_in_PL_sector (Proj::X, 3, 3 ^ Box3D::Z, Box3D::Y);
    //int insidexz = box->VP_lies_in_PL_sector (Proj::X, 3, 3 ^ Box3D::Y, Box3D::Z);

    int insideyx = box->VP_lies_in_PL_sector (Proj::Y, 3, 3 ^ Box3D::Z, Box3D::X);
    int insideyz = box->VP_lies_in_PL_sector (Proj::Y, 3, 3 ^ Box3D::X, Box3D::Z);

    //int insidezx = box->VP_lies_in_PL_sector (Proj::Z, 3, 3 ^ Box3D::Y, Box3D::X);
    int insidezy = box->VP_lies_in_PL_sector (Proj::Z, 3, 3 ^ Box3D::X, Box3D::Y);

    switch(central_axis) {
        case Box3D::X:
            if (!swapped) {
                if (insidezy == -1) {
                    box3d_aux_set_z_orders (z_orders, 2, 4, 0, 1, 3, 5);
                } else if (insidexy == 1) {
                    box3d_aux_set_z_orders (z_orders, 2, 4, 0, 5, 1, 3);
                } else {
                    box3d_aux_set_z_orders (z_orders, 2, 4, 0, 1, 3, 5);
                }
            } else {
                if (insideyz == -1) {
                    box3d_aux_set_z_orders (z_orders, 3, 1, 5, 0, 2, 4);
                } else {
                    if (!swapped) {
                        box3d_aux_set_z_orders (z_orders, 3, 1, 5, 2, 4, 0);
                    } else {
                        if (insidexy == 0) {
                            box3d_aux_set_z_orders (z_orders, 3, 5, 1, 0, 2, 4);
                        } else {
                            box3d_aux_set_z_orders (z_orders, 3, 1, 5, 0, 2, 4);
                        }
                    }
                }
            }
            break;
        case Box3D::Y:
            if (!swapped) {
                if (insideyz == 1) {
                    box3d_aux_set_z_orders (z_orders, 2, 3, 1, 0, 5, 4);
                } else {
                    box3d_aux_set_z_orders (z_orders, 2, 3, 1, 5, 0, 4);
                }
            } else {
                if (insideyx == 1) {
                    box3d_aux_set_z_orders (z_orders, 4, 0, 5, 1, 3, 2);
                } else {
                    box3d_aux_set_z_orders (z_orders, 5, 0, 4, 1, 3, 2);
                }
            }
            break;
        case Box3D::Z:
            if (!swapped) {
                if (insidezy == 1) {
                    box3d_aux_set_z_orders (z_orders, 2, 1, 0, 4, 3, 5);
                } else if (insidexy == -1) {
                    box3d_aux_set_z_orders (z_orders, 2, 1, 0, 5, 4, 3);
                } else {
                    box3d_aux_set_z_orders (z_orders, 2, 0, 1, 5, 3, 4);
                }
            } else {
                box3d_aux_set_z_orders (z_orders, 3, 4, 5, 1, 0, 2);
            }
            break;
        case Box3D::NONE:
            if (!swapped) {
                box3d_aux_set_z_orders (z_orders, 2, 3, 4, 1, 0, 5);
            } else {
                box3d_aux_set_z_orders (z_orders, 5, 0, 1, 4, 3, 2);
            }
            break;
        default:
            g_assert_not_reached();
            break;
    }
}

/*
 * It can happen that during dragging the box is everted.
 * In this case the opposite sides in this direction need to be swapped
 */
static Box3D::Axis
box3d_everted_directions (SPBox3D *box) {
    Box3D::Axis ev = Box3D::NONE;

    box->orig_corner0.normalize();
    box->orig_corner7.normalize();

    if (box->orig_corner0[Proj::X] < box->orig_corner7[Proj::X])
        ev = (Box3D::Axis) (ev ^ Box3D::X);
    if (box->orig_corner0[Proj::Y] < box->orig_corner7[Proj::Y])
        ev = (Box3D::Axis) (ev ^ Box3D::Y);
    if (box->orig_corner0[Proj::Z] > box->orig_corner7[Proj::Z]) // FIXME: Remove the need to distinguish signs among the cases
        ev = (Box3D::Axis) (ev ^ Box3D::Z);

    return ev;
}

static void
box3d_swap_sides(int z_orders[6], Box3D::Axis axis) {
    int pos1 = -1;
    int pos2 = -1;

    for (int i = 0; i < 6; ++i) {
        if (!(Box3D::int_to_face(z_orders[i]) & axis)) {
            if (pos1 == -1) {
                pos1 = i;
            } else {
                pos2 = i;
                break;
            }
        }
    }

    if ((pos1 != -1) && (pos2 != -1)){
        int tmp = z_orders[pos1];
        z_orders[pos1] = z_orders[pos2];
        z_orders[pos2] = tmp;
    }
}


bool
SPBox3D::recompute_z_orders () {
    Persp3D *persp = this->get_perspective();

    if (!persp)
        return false;

    int z_orders[6];

    Geom::Point c3(this->get_corner_screen(3, false));

    // determine directions from corner3 to the VPs
    int num_finite = 0;
    Box3D::Axis axis_finite = Box3D::NONE;
    Box3D::Axis axis_infinite = Box3D::NONE;
    Geom::Point dirs[3];
    for (int i = 0; i < 3; ++i) {
        dirs[i] = persp->get_PL_dir_from_pt(c3, Box3D::toProj(Box3D::axes[i]));
        if (Persp3D::VP_is_finite(persp->perspective_impl, Proj::axes[i])) {
            num_finite++;
            axis_finite = Box3D::axes[i];
        } else {
            axis_infinite = Box3D::axes[i];
        }
    }

    // determine the "central" axis (if there is one)
    Box3D::Axis central_axis = Box3D::NONE;
    if(Box3D::lies_in_sector(dirs[0], dirs[1], dirs[2])) {
        central_axis = Box3D::Z;
    } else if(Box3D::lies_in_sector(dirs[1], dirs[2], dirs[0])) {
        central_axis = Box3D::X;
    } else if(Box3D::lies_in_sector(dirs[2], dirs[0], dirs[1])) {
        central_axis = Box3D::Y;
    }

    switch (num_finite) {
        case 0:
            // TODO: Remark: In this case (and maybe one of the others, too) the z-orders for all boxes
            //               coincide, hence only need to be computed once in a more central location.
            box3d_set_new_z_orders_case0(this, z_orders, central_axis);
            break;
        case 1:
            box3d_set_new_z_orders_case1(this, z_orders, central_axis, axis_finite);
            break;
        case 2:
        case 3:
            box3d_set_new_z_orders_case2(this, z_orders, central_axis, axis_infinite);
            break;
        default:
        /*
         * For each VP F, check whether the half-line from the corner3 to F crosses the line segment
         * joining the other two VPs. If this is the case, it determines the "central" corner from
         * which the visible sides can be deduced. Otherwise, corner3 is the central corner.
         */
        // FIXME: We should eliminate the use of Geom::Point altogether
        Box3D::Axis central_axis = Box3D::NONE;
        Geom::Point vp_x = persp->get_VP(Proj::X).affine();
        Geom::Point vp_y = persp->get_VP(Proj::Y).affine();
        Geom::Point vp_z = persp->get_VP(Proj::Z).affine();
        Geom::Point vpx(vp_x[Geom::X], vp_x[Geom::Y]);
        Geom::Point vpy(vp_y[Geom::X], vp_y[Geom::Y]);
        Geom::Point vpz(vp_z[Geom::X], vp_z[Geom::Y]);

        Geom::Point c3 = this->get_corner_screen(3, false);
        Geom::Point corner3(c3[Geom::X], c3[Geom::Y]);

        if (box3d_half_line_crosses_joining_line (corner3, vpx, vpy, vpz)) {
            central_axis = Box3D::X;
        } else if (box3d_half_line_crosses_joining_line (corner3, vpy, vpz, vpx)) {
            central_axis = Box3D::Y;
        } else if (box3d_half_line_crosses_joining_line (corner3, vpz, vpx, vpy)) {
            central_axis = Box3D::Z;
        }

        // FIXME: At present, this is not used.  Why is it calculated?
        /*
        unsigned int central_corner = 3 ^ central_axis;
        if (central_axis == Box3D::Z) {
            central_corner = central_corner ^ Box3D::XYZ;
        }
        if (box3d_XY_axes_are_swapped(this)) {
            central_corner = central_corner ^ Box3D::XYZ;
        }
        */

        Geom::Point c1(this->get_corner_screen(1, false));
        Geom::Point c2(this->get_corner_screen(2, false));
        Geom::Point c7(this->get_corner_screen(7, false));

        Geom::Point corner1(c1[Geom::X], c1[Geom::Y]);
        Geom::Point corner2(c2[Geom::X], c2[Geom::Y]);
        Geom::Point corner7(c7[Geom::X], c7[Geom::Y]);
        // FIXME: At present we don't use the information about central_corner computed above.
        switch (central_axis) {
            case Box3D::Y:
                if (!box3d_half_line_crosses_joining_line(vpz, vpy, corner3, corner2)) {
                    box3d_aux_set_z_orders (z_orders, 2, 3, 1, 5, 0, 4);
                } else {
                    // degenerate case
                    box3d_aux_set_z_orders (z_orders, 2, 1, 3, 0, 5, 4);
                }
                break;

            case Box3D::Z:
                if (box3d_half_line_crosses_joining_line(vpx, vpz, corner3, corner1)) {
                    // degenerate case
                    box3d_aux_set_z_orders (z_orders, 2, 0, 1, 4, 3, 5);
                } else if (box3d_half_line_crosses_joining_line(vpx, vpy, corner3, corner7)) {
                    // degenerate case
                    box3d_aux_set_z_orders (z_orders, 2, 1, 0, 5, 3, 4);
                } else {
                    box3d_aux_set_z_orders (z_orders, 2, 1, 0, 3, 4, 5);
                }
                break;

            case Box3D::X:
                if (box3d_half_line_crosses_joining_line(vpz, vpx, corner3, corner1)) {
                    // degenerate case
                    box3d_aux_set_z_orders (z_orders, 2, 1, 0, 4, 5, 3);
                } else {
                    box3d_aux_set_z_orders (z_orders, 2, 4, 0, 5, 1, 3);
                }
                break;

            case Box3D::NONE:
                box3d_aux_set_z_orders (z_orders, 2, 3, 4, 1, 0, 5);
                break;

            default:
                g_assert_not_reached();
                break;
        } // end default case
    }

    // TODO: If there are still errors in z-orders of everted boxes, we need to choose a variable corner
    //       instead of the hard-coded corner #3 in the computations above
    Box3D::Axis ev = box3d_everted_directions(this);
    for (auto & axe : Box3D::axes) {
        if (ev & axe) {
            box3d_swap_sides(z_orders, axe);
        }
    }

    // Check whether anything actually changed
    for (int i = 0; i < 6; ++i) {
        if (this->z_orders[i] != z_orders[i]) {
            for (int j = i; j < 6; ++j) {
                this->z_orders[j] = z_orders[j];
            }
            return true;
        }
    }
    return false;
}

static std::map<int, Box3DSide *> box3d_get_sides(SPBox3D *box)
{
    std::map<int, Box3DSide *> sides;
    for (auto& obj: box->children) {
        Box3DSide *side = dynamic_cast<Box3DSide *>(&obj);
        if (side) {
            sides[Box3D::face_to_int(side->getFaceId())] = side;
        }
    }
    sides.erase(-1);
    return sides;
}


// TODO: Check whether the box is everted in any direction and swap the sides opposite to this direction
void
SPBox3D::set_z_orders () {
    // For efficiency reasons, we only set the new z-orders if something really changed
    if (this->recompute_z_orders ()) {
        std::map<int, Box3DSide *> sides = box3d_get_sides(this);
        std::map<int, Box3DSide *>::iterator side;
        for (int z_order : this->z_orders) {
            side = sides.find(z_order);
            if (side != sides.end()) {
                ((*side).second)->lowerToBottom();
            }
        }
    }
}

/*
 * Auxiliary function for z-order recomputing:
 * Determines whether \a pt lies in the sector formed by the two PLs from the corners with IDs
 * \a i21 and \a id2 to the VP in direction \a axis. If the VP is infinite, we say that \a pt
 * lies in the sector if it lies between the two (parallel) PLs.
 * \ret *  0 if \a pt doesn't lie in the sector
 *      *  1 if \a pt lies in the sector and either VP is finite of VP is infinite and the direction
 *           from the edge between the two corners to \a pt points towards the VP
 *      * -1 otherwise
 */
// TODO: Maybe it would be useful to have a similar method for projective points pt because then we
//       can use it for VPs and perhaps merge the case distinctions during z-order recomputation.
int
SPBox3D::pt_lies_in_PL_sector (Geom::Point const &pt, int id1, int id2, Box3D::Axis axis) const {
    Persp3D *persp = this->get_perspective();

    // the two corners
    Geom::Point c1(this->get_corner_screen(id1, false));
    Geom::Point c2(this->get_corner_screen(id2, false));

    int ret = 0;
    if (Persp3D::VP_is_finite(persp->perspective_impl, Box3D::toProj(axis))) {
        Geom::Point vp(persp->get_VP(Box3D::toProj(axis)).affine());
        Geom::Point v1(c1 - vp);
        Geom::Point v2(c2 - vp);
        Geom::Point w(pt - vp);
        ret = static_cast<int>(Box3D::lies_in_sector(v1, v2, w));
    } else {
        Box3D::PerspectiveLine pl1(c1, Box3D::toProj(axis), persp);
        Box3D::PerspectiveLine pl2(c2, Box3D::toProj(axis), persp);
        if (pl1.lie_on_same_side(pt, c2) && pl2.lie_on_same_side(pt, c1)) {
            // test whether pt lies "towards" or "away from" the VP
            Box3D::Line edge(c1,c2);
            Geom::Point c3(this->get_corner_screen(id1 ^ axis, false));
            if (edge.lie_on_same_side(pt, c3)) {
                ret = 1;
            } else {
                ret = -1;
            }
        }
    }
    return ret;
}

int
SPBox3D::VP_lies_in_PL_sector (Proj::Axis vpdir, int id1, int id2, Box3D::Axis axis) const {
    Persp3D *persp = this->get_perspective();

    if (!Persp3D::VP_is_finite(persp->perspective_impl, vpdir)) {
        return 0;
    } else {
        return this->pt_lies_in_PL_sector(persp->get_VP(vpdir).affine(), id1, id2, axis);
    }
}

/* swap the coordinates of corner0 and corner7 along the specified axis */
static void
box3d_swap_coords(SPBox3D *box, Proj::Axis axis, bool smaller = true) {
    box->orig_corner0.normalize();
    box->orig_corner7.normalize();
    if ((box->orig_corner0[axis] < box->orig_corner7[axis]) != smaller) {
        double tmp = box->orig_corner0[axis];
        box->orig_corner0[axis] = box->orig_corner7[axis];
        box->orig_corner7[axis] = tmp;
    }
    // Should we also swap the coordinates of save_corner0 and save_corner7?
}

/* ensure that the coordinates of corner0 and corner7 are in the correct order (to prevent everted boxes) */
void
SPBox3D::relabel_corners() {
    box3d_swap_coords(this, Proj::X, false);
    box3d_swap_coords(this, Proj::Y, false);
    box3d_swap_coords(this, Proj::Z, true);
}

static void
box3d_check_for_swapped_coords(SPBox3D *box, Proj::Axis axis, bool smaller) {
    box->orig_corner0.normalize();
    box->orig_corner7.normalize();

    if ((box->orig_corner0[axis] < box->orig_corner7[axis]) != smaller) {
        box->swapped = (Box3D::Axis) (box->swapped | Proj::toAffine(axis));
    } else {
        box->swapped = (Box3D::Axis) (box->swapped & ~Proj::toAffine(axis));
    }
}

static void
box3d_exchange_coords(SPBox3D *box) {
    box->orig_corner0.normalize();
    box->orig_corner7.normalize();

    for (int i = 0; i < 3; ++i) {
        if (box->swapped & Box3D::axes[i]) {
            double tmp = box->orig_corner0[i];
            box->orig_corner0[i] = box->orig_corner7[i];
            box->orig_corner7[i] = tmp;
        }
    }
}

void
SPBox3D::check_for_swapped_coords() {
    box3d_check_for_swapped_coords(this, Proj::X, false);
    box3d_check_for_swapped_coords(this, Proj::Y, false);
    box3d_check_for_swapped_coords(this, Proj::Z, true);

    box3d_exchange_coords(this);
}

static void box3d_extract_boxes_rec(SPObject *obj, std::list<SPBox3D *> &boxes) {
    SPBox3D *box = dynamic_cast<SPBox3D *>(obj);
    if (box) {
        boxes.push_back(box);
    } else if (dynamic_cast<SPGroup *>(obj)) {
        for (auto& child: obj->children) {
            box3d_extract_boxes_rec(&child, boxes);
        }
    }
}

std::list<SPBox3D *>
SPBox3D::extract_boxes(SPObject *obj) {
    std::list<SPBox3D *> boxes;
    box3d_extract_boxes_rec(obj, boxes);
    return boxes;
}

Persp3D *
SPBox3D::get_perspective() const {
    if(this->persp_ref) {
        return this->persp_ref->getObject();
    }
    return nullptr;
}

void
SPBox3D::switch_perspectives(Persp3D *old_persp, Persp3D *new_persp, bool recompute_corners) {
    if (recompute_corners) {
        this->orig_corner0.normalize();
        this->orig_corner7.normalize();
        double z0 = this->orig_corner0[Proj::Z];
        double z7 = this->orig_corner7[Proj::Z];
        Geom::Point corner0_screen = this->get_corner_screen(0, false);
        Geom::Point corner7_screen = this->get_corner_screen(7, false);

        this->orig_corner0 = new_persp->perspective_impl->tmat.preimage(corner0_screen, z0, Proj::Z);
        this->orig_corner7 = new_persp->perspective_impl->tmat.preimage(corner7_screen, z7, Proj::Z);
    }

    old_persp->remove_box (this);
    new_persp->add_box (this);

    Glib::ustring href = "#";
    href += new_persp->getId();
    this->setAttribute("inkscape:perspectiveID", href);
}

/* Converts the 3D box to an ordinary SPGroup, adds it to the XML tree at the same position as
   the original box and deletes the latter */
SPGroup *SPBox3D::convert_to_group()
{
    SPDocument *doc = this->document;
    Inkscape::XML::Document *xml_doc = doc->getReprDoc();

    // remember position of the box
    int pos = this->getPosition();

    // remember important attributes
    gchar const *id = this->getAttribute("id");
    gchar const *style = this->getAttribute("style");
    gchar const *mask = this->getAttribute("mask");
    gchar const *clip_path = this->getAttribute("clip-path");

    // create a new group and add the sides (converted to ordinary paths) as its children
    Inkscape::XML::Node *grepr = xml_doc->createElement("svg:g");

    for (auto& obj: this->children) {
        Box3DSide *side = dynamic_cast<Box3DSide *>(&obj);
        if (side) {
            Inkscape::XML::Node *repr = side->convert_to_path();
            grepr->appendChild(repr);
        } else {
            g_warning("Non-side item encountered as child of a 3D box.");
        }
    }

    // add the new group to the box's parent and set remembered position
    SPObject *parent = this->parent;
    parent->appendChild(grepr);
    grepr->setPosition(pos);
    grepr->setAttributeOrRemoveIfEmpty("style", style);
    grepr->setAttributeOrRemoveIfEmpty("mask", mask);
    grepr->setAttributeOrRemoveIfEmpty("clip-path", clip_path);

    this->deleteObject(true);

    grepr->setAttribute("id", id);

    SPGroup *group = dynamic_cast<SPGroup *>(doc->getObjectByRepr(grepr));
    g_assert(group != nullptr);
    return group;
}

const char *SPBox3D::displayName() const {
    return _("3D Box");
}

gchar *SPBox3D::description() const {
    // We could put more details about the 3d box here
    return g_strdup("");
}

static inline void
box3d_push_back_corner_pair(SPBox3D const *box, std::list<std::pair<Geom::Point, Geom::Point> > &pts, int c1, int c2) {
    pts.emplace_back(box->get_corner_screen(c1, false),
                     box->get_corner_screen(c2, false));
}

void SPBox3D::convert_to_guides() const {
    Inkscape::Preferences *prefs = Inkscape::Preferences::get();

    if (!prefs->getBool("/tools/shapes/3dbox/convertguides", true)) {
        this->convert_to_guides();
        return;
    }

    std::list<std::pair<Geom::Point, Geom::Point> > pts;

    /* perspective lines in X direction */
    box3d_push_back_corner_pair(this, pts, 0, 1);
    box3d_push_back_corner_pair(this, pts, 2, 3);
    box3d_push_back_corner_pair(this, pts, 4, 5);
    box3d_push_back_corner_pair(this, pts, 6, 7);

    /* perspective lines in Y direction */
    box3d_push_back_corner_pair(this, pts, 0, 2);
    box3d_push_back_corner_pair(this, pts, 1, 3);
    box3d_push_back_corner_pair(this, pts, 4, 6);
    box3d_push_back_corner_pair(this, pts, 5, 7);

    /* perspective lines in Z direction */
    box3d_push_back_corner_pair(this, pts, 0, 4);
    box3d_push_back_corner_pair(this, pts, 1, 5);
    box3d_push_back_corner_pair(this, pts, 2, 6);
    box3d_push_back_corner_pair(this, pts, 3, 7);

    sp_guide_pt_pairs_to_guides(this->document, pts);
}

/*
  Local Variables:
  mode:c++
  c-file-style:"stroustrup"
  c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
  indent-tabs-mode:nil
  fill-column:99
  End:
*/
// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :