Code

Fix another small z-order issue for 3D boxes
[inkscape.git] / src / box3d.cpp
1 #define __SP_BOX3D_C__
3 /*
4  * SVG <box3d> implementation
5  *
6  * Authors:
7  *   Maximilian Albert <Anhalter42@gmx.de>
8  *   Lauris Kaplinski <lauris@kaplinski.com>
9  *   bulia byak <buliabyak@users.sf.net>
10  *
11  * Copyright (C) 2007      Authors
12  * Copyright (C) 1999-2002 Lauris Kaplinski
13  * Copyright (C) 2000-2001 Ximian, Inc.
14  *
15  * Released under GNU GPL, read the file 'COPYING' for more information
16  */
18 #include <glibmm/i18n.h>
19 #include "attributes.h"
20 #include "xml/document.h"
21 #include "xml/repr.h"
23 #include "box3d.h"
24 #include "box3d-side.h"
25 #include "box3d-context.h"
26 #include "proj_pt.h"
27 #include "transf_mat_3x4.h"
28 #include "perspective-line.h"
29 #include "inkscape.h"
30 #include "persp3d.h"
31 #include "line-geometry.h"
32 #include "persp3d-reference.h"
33 #include "uri.h"
34 #include "2geom/geom.h"
35 #include "sp-guide.h"
36 #include "sp-namedview.h"
37 #include "prefs-utils.h"
39 #include "desktop.h"
40 #include "macros.h"
42 static void box3d_class_init(SPBox3DClass *klass);
43 static void box3d_init(SPBox3D *box3d);
45 static void box3d_build(SPObject *object, SPDocument *document, Inkscape::XML::Node *repr);
46 static void box3d_release(SPObject *object);
47 static void box3d_set(SPObject *object, unsigned int key, const gchar *value);
48 static void box3d_update(SPObject *object, SPCtx *ctx, guint flags);
49 static Inkscape::XML::Node *box3d_write(SPObject *object, Inkscape::XML::Node *repr, guint flags);
51 static gchar *box3d_description(SPItem *item);
52 static NR::Matrix box3d_set_transform(SPItem *item, NR::Matrix const &xform);
53 static void box3d_convert_to_guides(SPItem *item);
55 static void box3d_ref_changed(SPObject *old_ref, SPObject *ref, SPBox3D *box);
56 static void box3d_ref_modified(SPObject *href, guint flags, SPBox3D *box);
58 static SPGroupClass *parent_class;
60 static gint counter = 0;
62 GType
63 box3d_get_type(void)
64 {
65     static GType type = 0;
67     if (!type) {
68         GTypeInfo info = {
69             sizeof(SPBox3DClass),
70             NULL,   /* base_init */
71             NULL,   /* base_finalize */
72             (GClassInitFunc) box3d_class_init,
73             NULL,   /* class_finalize */
74             NULL,   /* class_data */
75             sizeof(SPBox3D),
76             16,     /* n_preallocs */
77             (GInstanceInitFunc) box3d_init,
78             NULL,   /* value_table */
79         };
80         type = g_type_register_static(SP_TYPE_GROUP, "SPBox3D", &info, (GTypeFlags) 0);
81     }
83     return type;
84 }
86 static void
87 box3d_class_init(SPBox3DClass *klass)
88 {
89     SPObjectClass *sp_object_class = (SPObjectClass *) klass;
90     SPItemClass *item_class = (SPItemClass *) klass;
92     parent_class = (SPGroupClass *) g_type_class_ref(SP_TYPE_GROUP);
94     sp_object_class->build = box3d_build;
95     sp_object_class->release = box3d_release;
96     sp_object_class->set = box3d_set;
97     sp_object_class->write = box3d_write;
98     sp_object_class->update = box3d_update;
100     item_class->description = box3d_description;
101     item_class->set_transform = box3d_set_transform;
102     item_class->convert_to_guides = box3d_convert_to_guides;
105 static void
106 box3d_init(SPBox3D *box)
108     box->persp_href = NULL;
109     box->persp_ref = new Persp3DReference(SP_OBJECT(box));
110     new (&box->modified_connection) sigc::connection();
113 static void
114 box3d_build(SPObject *object, SPDocument *document, Inkscape::XML::Node *repr)
116     if (((SPObjectClass *) (parent_class))->build) {
117         ((SPObjectClass *) (parent_class))->build(object, document, repr);
118     }
120     SPBox3D *box = SP_BOX3D (object);
121     box->my_counter = counter++;
123     /* we initialize the z-orders to zero so that they are updated during dragging */
124     for (int i = 0; i < 6; ++i) {
125         box->z_orders[i] = 0;
126     }
128     // TODO: Create/link to the correct perspective
130     SPDocument *doc = SP_OBJECT_DOCUMENT(box);
131     if (!doc) {
132         g_print ("No document for the box!!!!\n");
133         return;
134     }
135     /**
136     if (!box->persp3d) {
137         g_print ("Box seems to be newly created since no perspective is referenced yet. We reference the current perspective.\n");
138         box->persp3d = doc->current_persp3d;
139     }
140     **/
142     box->persp_ref->changedSignal().connect(sigc::bind(sigc::ptr_fun(box3d_ref_changed), box));
144     sp_object_read_attr(object, "inkscape:perspectiveID");
145     sp_object_read_attr(object, "inkscape:corner0");
146     sp_object_read_attr(object, "inkscape:corner7");
149 /**
150  * Virtual release of SPBox3D members before destruction.
151  */
152 static void
153 box3d_release(SPObject *object)
155     SPBox3D *box = (SPBox3D *) object;
157     if (box->persp_href) {
158         g_free(box->persp_href);
159     }
160     if (box->persp_ref) {
161         box->persp_ref->detach();
162         delete box->persp_ref;
163         box->persp_ref = NULL;
164     }
166     box->modified_connection.disconnect();
167     box->modified_connection.~connection();
169     //persp3d_remove_box (box3d_get_perspective(box), box);
171     if (((SPObjectClass *) parent_class)->release)
172         ((SPObjectClass *) parent_class)->release(object);
175 static void
176 box3d_set(SPObject *object, unsigned int key, const gchar *value)
178     SPBox3D *box = SP_BOX3D(object);
180     switch (key) {
181         case SP_ATTR_INKSCAPE_BOX3D_PERSPECTIVE_ID:
182             if ( value && box->persp_href && ( strcmp(value, box->persp_href) == 0 ) ) {
183                 /* No change, do nothing. */
184             } else {
185                 if (box->persp_href) {
186                     g_free(box->persp_href);
187                     box->persp_href = NULL;
188                 }
189                 if (value) {
190                     box->persp_href = g_strdup(value);
192                     // Now do the attaching, which emits the changed signal.
193                     try {
194                         box->persp_ref->attach(Inkscape::URI(value));
195                     } catch (Inkscape::BadURIException &e) {
196                         g_warning("%s", e.what());
197                         box->persp_ref->detach();
198                     }
199                 } else {
200                     // Detach, which emits the changed signal.
201                     box->persp_ref->detach();
202                         // TODO: Clean this up (also w.r.t the surrounding if construct)
203                         /***
204                         g_print ("No perspective given. Attaching to current perspective instead.\n");
205                         g_free(box->persp_href);
206                         Inkscape::XML::Node *repr = SP_OBJECT_REPR(inkscape_active_document()->current_persp3d);
207                         box->persp_href = g_strdup(repr->attribute("id"));
208                         box->persp_ref->attach(Inkscape::URI(box->persp_href));
209                         ***/
210                 }
211             }
213             // FIXME: Is the following update doubled by some call in either persp3d.cpp or vanishing_point_new.cpp?
214             box3d_position_set(box);
215             break;
216         case SP_ATTR_INKSCAPE_BOX3D_CORNER0:
217             if (value && strcmp(value, "0 : 0 : 0 : 0")) {
218                 box->orig_corner0 = Proj::Pt3(value);
219                 box->save_corner0 = box->orig_corner0;
220                 box3d_position_set(box);
221             }
222             break;
223         case SP_ATTR_INKSCAPE_BOX3D_CORNER7:
224             if (value && strcmp(value, "0 : 0 : 0 : 0")) {
225                 box->orig_corner7 = Proj::Pt3(value);
226                 box->save_corner7 = box->orig_corner7;
227                 box3d_position_set(box);
228             }
229             break;
230         default:
231             if (((SPObjectClass *) (parent_class))->set) {
232                 ((SPObjectClass *) (parent_class))->set(object, key, value);
233             }
234             break;
235     }
236     //object->updateRepr(); // This ensures correct update of the box after undo/redo. FIXME: Why is this not present in sp-rect.cpp and similar files?
239 /**
240  * Gets called when (re)attached to another perspective.
241  */
242 static void
243 box3d_ref_changed(SPObject *old_ref, SPObject *ref, SPBox3D *box)
245     if (old_ref) {
246         sp_signal_disconnect_by_data(old_ref, box);
247         persp3d_remove_box (SP_PERSP3D(old_ref), box);
248         /* Note: This sometimes leads to attempts to remove boxes twice from the list of selected/transformed
249            boxes in a perspectives, but this should be uncritical. */
250         persp3d_remove_box_transform (SP_PERSP3D(old_ref), box);
251     }
252     if ( SP_IS_PERSP3D(ref) && ref != box ) // FIXME: Comparisons sane?
253     {
254         box->modified_connection.disconnect();
255         box->modified_connection = ref->connectModified(sigc::bind(sigc::ptr_fun(&box3d_ref_modified), box));
256         box3d_ref_modified(ref, 0, box);
257         persp3d_add_box (SP_PERSP3D(ref), box);
258         /* Note: This sometimes leads to attempts to add boxes twice to the list of selected/transformed
259            boxes in a perspectives, but this should be uncritical. */
260         persp3d_add_box_transform (SP_PERSP3D(ref), box);
261     }
264 static void
265 box3d_update(SPObject *object, SPCtx *ctx, guint flags)
267     if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) {
269         /* FIXME?: Perhaps the display updates of box sides should be instantiated from here, but this
270            causes evil update loops so it's all done from box3d_position_set, which is called from
271            various other places (like the handlers in object-edit.cpp, vanishing-point.cpp, etc. */
273     }
275     // Invoke parent method
276     if (((SPObjectClass *) (parent_class))->update)
277         ((SPObjectClass *) (parent_class))->update(object, ctx, flags);
281 static Inkscape::XML::Node *box3d_write(SPObject *object, Inkscape::XML::Node *repr, guint flags)
283     SPBox3D *box = SP_BOX3D(object);
285     if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) {
286         // this is where we end up when saving as plain SVG (also in other circumstances?)
287         // thus we don' set "sodipodi:type" so that the box is only saved as an ordinary svg:g
288         Inkscape::XML::Document *xml_doc = sp_document_repr_doc(SP_OBJECT_DOCUMENT(object));
289         repr = xml_doc->createElement("svg:g");
290     }
292     if (flags & SP_OBJECT_WRITE_EXT) {
294         if (box->persp_href) {
295             repr->setAttribute("inkscape:perspectiveID", box->persp_href);
296         } else {
297             /* box is not yet linked to a perspective; use the document's current perspective */
298             SPDocument *doc = inkscape_active_document();
299             if (box->persp_ref->getURI()) {
300                 gchar *uri_string = box->persp_ref->getURI()->toString();
301                 repr->setAttribute("inkscape:perspectiveID", uri_string);
302                 g_free(uri_string);
303             } else if (doc) {
304                 //persp3d_add_box (doc->current_persp3d, box);
305                 Inkscape::XML::Node *persp_repr = SP_OBJECT_REPR(doc->current_persp3d);
306                 const gchar *persp_id = persp_repr->attribute("id");
307                 gchar *href = g_strdup_printf("#%s", persp_id);
308                 repr->setAttribute("inkscape:perspectiveID", href);
309                 g_free(href);
310             } else {
311                 g_print ("No active document while creating perspective!!!\n");
312             }
313         }
315         gchar *coordstr0 = box->orig_corner0.coord_string();
316         gchar *coordstr7 = box->orig_corner7.coord_string();
317         repr->setAttribute("inkscape:corner0", coordstr0);
318         repr->setAttribute("inkscape:corner7", coordstr7);
319         g_free(coordstr0);
320         g_free(coordstr7);
322         box->orig_corner0.normalize();
323         box->orig_corner7.normalize();
325         box->save_corner0 = box->orig_corner0;
326         box->save_corner7 = box->orig_corner7;
327     }
329     if (((SPObjectClass *) (parent_class))->write) {
330         ((SPObjectClass *) (parent_class))->write(object, repr, flags);
331     }
333     return repr;
336 static gchar *
337 box3d_description(SPItem *item)
339     g_return_val_if_fail(SP_IS_BOX3D(item), NULL);
341     return g_strdup(_("<b>3D Box</b>"));
344 void
345 box3d_position_set (SPBox3D *box)
347     /* This draws the curve and calls requestDisplayUpdate() for each side (the latter is done in
348        box3d_side_position_set() to avoid update conflicts with the parent box) */
349     for (SPObject *child = sp_object_first_child(SP_OBJECT (box)); child != NULL; child = SP_OBJECT_NEXT(child) ) {
350         box3d_side_position_set (SP_BOX3D_SIDE (child));
351     }
354 static NR::Matrix
355 box3d_set_transform(SPItem *item, NR::Matrix const &xform)
357     SPBox3D *box = SP_BOX3D(item);
359     /* check whether we need to unlink any boxes from their perspectives */
360     Persp3D *persp = box3d_get_perspective(box);
361     Persp3D *transf_persp;
363     if (!persp3d_has_all_boxes_in_selection (persp)) {
364         std::list<SPBox3D *> sel = persp3d_selected_boxes (persp);
366         /* create a new perspective as a copy of the current one and link the selected boxes to it */
367         transf_persp = persp3d_create_xml_element (SP_OBJECT_DOCUMENT(persp), persp);
369         for (std::list<SPBox3D *>::iterator b = sel.begin(); b != sel.end(); ++b) {
370             box3d_switch_perspectives(*b, persp, transf_persp);
371         }
372     } else {
373         transf_persp = persp;
374     }
376     /* only transform the perspective once, even if it has several selected boxes */
377     if(!persp3d_was_transformed (transf_persp)) {
378         /* concatenate the affine transformation with the perspective mapping; this
379            function also triggers repr updates of boxes and the perspective itself */
380         persp3d_apply_affine_transformation(transf_persp, xform);
381     }
383     box3d_mark_transformed(box);
385     if (persp3d_all_transformed(transf_persp)) {
386         /* all boxes were transformed; make perspective sensitive for further transformations */
387         persp3d_unset_transforms(transf_persp);
388     }
390     NR::Matrix ret(NR::transform(xform));
391     gdouble const sw = hypot(ret[0], ret[1]);
392     gdouble const sh = hypot(ret[2], ret[3]);
394     SPItem *sideitem = NULL;
395     for (SPObject *side = sp_object_first_child(box); side != NULL; side = SP_OBJECT_NEXT(side)) {
396         sideitem = SP_ITEM(side);
398         // Adjust stroke width
399         sp_item_adjust_stroke(sideitem, sqrt(fabs(sw * sh)));
401         // Adjust pattern fill
402         sp_item_adjust_pattern(sideitem, xform);
404         // Adjust gradient fill
405         sp_item_adjust_gradient(sideitem, xform);
407         // Adjust LPE
408         sp_item_adjust_livepatheffect(item, xform);
409     }
411     return NR::identity();
415 /**
416  * Gets called when persp(?) repr contents change: i.e. parameter change.
417  */
418 static void
419 box3d_ref_modified(SPObject */*href*/, guint /*flags*/, SPBox3D */*box*/)
421     /***
422     g_print ("FIXME: box3d_ref_modified was called. What should we do?\n");
423     g_print ("Here is at least the the href's id: %s\n", SP_OBJECT_REPR(href)->attribute("id"));
424     g_print ("             ... and the box's, too: %s\n", SP_OBJECT_REPR(box)->attribute("id"));
425     ***/
429 Proj::Pt3
430 box3d_get_proj_corner (guint id, Proj::Pt3 const &c0, Proj::Pt3 const &c7) {
431     return Proj::Pt3 ((id & Box3D::X) ? c7[Proj::X] : c0[Proj::X],
432                       (id & Box3D::Y) ? c7[Proj::Y] : c0[Proj::Y],
433                       (id & Box3D::Z) ? c7[Proj::Z] : c0[Proj::Z],
434                       1.0);
437 Proj::Pt3
438 box3d_get_proj_corner (SPBox3D const *box, guint id) {
439     return Proj::Pt3 ((id & Box3D::X) ? box->orig_corner7[Proj::X] : box->orig_corner0[Proj::X],
440                       (id & Box3D::Y) ? box->orig_corner7[Proj::Y] : box->orig_corner0[Proj::Y],
441                       (id & Box3D::Z) ? box->orig_corner7[Proj::Z] : box->orig_corner0[Proj::Z],
442                       1.0);
445 NR::Point
446 box3d_get_corner_screen (SPBox3D const *box, guint id) {
447     Proj::Pt3 proj_corner (box3d_get_proj_corner (box, id));
448     if (!box3d_get_perspective(box)) {
449         //g_print ("No perspective present in box!! Should we simply use the currently active perspective?\n");
450         return NR::Point (NR_HUGE, NR_HUGE);
451     }
452     return box3d_get_perspective(box)->tmat.image(proj_corner).affine();
455 Proj::Pt3
456 box3d_get_proj_center (SPBox3D *box) {
457     box->orig_corner0.normalize();
458     box->orig_corner7.normalize();
459     return Proj::Pt3 ((box->orig_corner0[Proj::X] + box->orig_corner7[Proj::X]) / 2,
460                       (box->orig_corner0[Proj::Y] + box->orig_corner7[Proj::Y]) / 2,
461                       (box->orig_corner0[Proj::Z] + box->orig_corner7[Proj::Z]) / 2,
462                       1.0);
465 NR::Point
466 box3d_get_center_screen (SPBox3D *box) {
467     Proj::Pt3 proj_center (box3d_get_proj_center (box));
468     if (!box3d_get_perspective(box)) {
469         //g_print ("No perspective present in box!! Should we simply use the currently active perspective?\n");
470         return NR::Point (NR_HUGE, NR_HUGE);
471     }
472     return box3d_get_perspective(box)->tmat.image(proj_center).affine();
475 /*
476  * To keep the snappoint from jumping randomly between the two lines when the mouse pointer is close to
477  * their intersection, we remember the last snapped line and keep snapping to this specific line as long
478  * as the distance from the intersection to the mouse pointer is less than remember_snap_threshold.
479  */
481 // Should we make the threshold settable in the preferences?
482 static double remember_snap_threshold = 30;
483 //static guint remember_snap_index = 0;
484 static guint remember_snap_index_center = 0;
486 static Proj::Pt3
487 box3d_snap (SPBox3D *box, int id, Proj::Pt3 const &pt_proj, Proj::Pt3 const &start_pt) {
488     double z_coord = start_pt[Proj::Z];
489     double diff_x = box->save_corner7[Proj::X] - box->save_corner0[Proj::X];
490     double diff_y = box->save_corner7[Proj::Y] - box->save_corner0[Proj::Y];
491     double x_coord = start_pt[Proj::X];
492     double y_coord = start_pt[Proj::Y];
493     Proj::Pt3 A_proj (x_coord,          y_coord,          z_coord, 1.0);
494     Proj::Pt3 B_proj (x_coord + diff_x, y_coord,          z_coord, 1.0);
495     Proj::Pt3 C_proj (x_coord + diff_x, y_coord + diff_y, z_coord, 1.0);
496     Proj::Pt3 D_proj (x_coord,          y_coord + diff_y, z_coord, 1.0);
497     Proj::Pt3 E_proj (x_coord - diff_x, y_coord + diff_y, z_coord, 1.0);
499     Persp3D *persp = box3d_get_perspective(box);
500     NR::Point A = persp->tmat.image(A_proj).affine();
501     NR::Point B = persp->tmat.image(B_proj).affine();
502     NR::Point C = persp->tmat.image(C_proj).affine();
503     NR::Point D = persp->tmat.image(D_proj).affine();
504     NR::Point E = persp->tmat.image(E_proj).affine();
505     NR::Point pt = persp->tmat.image(pt_proj).affine();
507     // TODO: Replace these lines between corners with lines from a corner to a vanishing point
508     //       (this might help to prevent rounding errors if the box is small)
509     Box3D::Line pl1(A, B);
510     Box3D::Line pl2(A, D);
511     Box3D::Line diag1(A, (id == -1 || (!(id & Box3D::X) == !(id & Box3D::Y))) ? C : E);
512     Box3D::Line diag2(A, E); // diag2 is only taken into account if id equals -1, i.e., if we are snapping the center
514     int num_snap_lines = (id != -1) ? 3 : 4;
515     NR::Point snap_pts[num_snap_lines];
517     snap_pts[0] = pl1.closest_to (pt);
518     snap_pts[1] = pl2.closest_to (pt);
519     snap_pts[2] = diag1.closest_to (pt);
520     if (id == -1) {
521         snap_pts[3] = diag2.closest_to (pt);
522     }
524     gdouble const zoom = inkscape_active_desktop()->current_zoom();
526     // determine the distances to all potential snapping points
527     double snap_dists[num_snap_lines];
528     for (int i = 0; i < num_snap_lines; ++i) {
529         snap_dists[i] = NR::L2 (snap_pts[i] - pt) * zoom;
530     }
532     // while we are within a given tolerance of the starting point,
533     // keep snapping to the same point to avoid jumping
534     bool within_tolerance = true;
535     for (int i = 0; i < num_snap_lines; ++i) {
536         if (snap_dists[i] > remember_snap_threshold) {
537             within_tolerance = false;
538             break;
539         }
540     }
542     // find the closest snapping point
543     int snap_index = -1;
544     double snap_dist = NR_HUGE;
545     for (int i = 0; i < num_snap_lines; ++i) {
546         if (snap_dists[i] < snap_dist) {
547             snap_index = i;
548             snap_dist = snap_dists[i];
549         }
550     }
552     // snap to the closest point (or the previously remembered one
553     // if we are within tolerance of the starting point)
554     NR::Point result;
555     if (within_tolerance) {
556         result = snap_pts[remember_snap_index_center];
557     } else {
558         remember_snap_index_center = snap_index;
559         result = snap_pts[snap_index];
560     }
561     return box3d_get_perspective(box)->tmat.preimage (result, z_coord, Proj::Z);
564 void
565 box3d_set_corner (SPBox3D *box, const guint id, NR::Point const &new_pos, const Box3D::Axis movement, bool constrained) {
566     g_return_if_fail ((movement != Box3D::NONE) && (movement != Box3D::XYZ));
568     box->orig_corner0.normalize();
569     box->orig_corner7.normalize();
571     /* update corners 0 and 7 according to which handle was moved and to the axes of movement */
572     if (!(movement & Box3D::Z)) {
573         Proj::Pt3 pt_proj (box3d_get_perspective(box)->tmat.preimage (new_pos, (id < 4) ? box->orig_corner0[Proj::Z] :
574                                                                       box->orig_corner7[Proj::Z], Proj::Z));
575         if (constrained) {
576             pt_proj = box3d_snap (box, id, pt_proj, box3d_get_proj_corner (id, box->save_corner0, box->save_corner7));
577         }
579         // normalizing pt_proj is essential because we want to mingle affine coordinates
580         pt_proj.normalize();
581         box->orig_corner0 = Proj::Pt3 ((id & Box3D::X) ? box->save_corner0[Proj::X] : pt_proj[Proj::X],
582                                        (id & Box3D::Y) ? box->save_corner0[Proj::Y] : pt_proj[Proj::Y],
583                                        box->save_corner0[Proj::Z],
584                                        1.0);
585         box->orig_corner7 = Proj::Pt3 ((id & Box3D::X) ? pt_proj[Proj::X] : box->save_corner7[Proj::X],
586                                        (id & Box3D::Y) ? pt_proj[Proj::Y] : box->save_corner7[Proj::Y],
587                                        box->save_corner7[Proj::Z],
588                                        1.0);
589     } else {
590         Persp3D *persp = box3d_get_perspective(box);
591         Box3D::PerspectiveLine pl(persp->tmat.image(
592                                       box3d_get_proj_corner (id, box->save_corner0, box->save_corner7)).affine(),
593                                   Proj::Z, persp);
594         NR::Point new_pos_snapped(pl.closest_to(new_pos));
595         Proj::Pt3 pt_proj (persp->tmat.preimage (new_pos_snapped,
596                                           box3d_get_proj_corner (box, id)[(movement & Box3D::Y) ? Proj::X : Proj::Y],
597                                           (movement & Box3D::Y) ? Proj::X : Proj::Y));
598         bool corner0_move_x = !(id & Box3D::X) && (movement & Box3D::X);
599         bool corner0_move_y = !(id & Box3D::Y) && (movement & Box3D::Y);
600         bool corner7_move_x =  (id & Box3D::X) && (movement & Box3D::X);
601         bool corner7_move_y =  (id & Box3D::Y) && (movement & Box3D::Y);
602         // normalizing pt_proj is essential because we want to mingle affine coordinates
603         pt_proj.normalize();
604         box->orig_corner0 = Proj::Pt3 (corner0_move_x ? pt_proj[Proj::X] : box->orig_corner0[Proj::X],
605                                        corner0_move_y ? pt_proj[Proj::Y] : box->orig_corner0[Proj::Y],
606                                        (id & Box3D::Z) ? box->orig_corner0[Proj::Z] : pt_proj[Proj::Z],
607                                        1.0);
608         box->orig_corner7 = Proj::Pt3 (corner7_move_x ? pt_proj[Proj::X] : box->orig_corner7[Proj::X],
609                                        corner7_move_y ? pt_proj[Proj::Y] : box->orig_corner7[Proj::Y],
610                                        (id & Box3D::Z) ? pt_proj[Proj::Z] : box->orig_corner7[Proj::Z],
611                                        1.0);
612     }
613     // FIXME: Should we update the box here? If so, how?
616 void box3d_set_center (SPBox3D *box, NR::Point const &new_pos, NR::Point const &old_pos, const Box3D::Axis movement, bool constrained) {
617     g_return_if_fail ((movement != Box3D::NONE) && (movement != Box3D::XYZ));
619     box->orig_corner0.normalize();
620     box->orig_corner7.normalize();
622     Persp3D *persp = box3d_get_perspective(box);
623     if (!(movement & Box3D::Z)) {
624         double coord = (box->orig_corner0[Proj::Z] + box->orig_corner7[Proj::Z]) / 2;
625         double radx = (box->orig_corner7[Proj::X] - box->orig_corner0[Proj::X]) / 2;
626         double rady = (box->orig_corner7[Proj::Y] - box->orig_corner0[Proj::Y]) / 2;
628         Proj::Pt3 pt_proj (persp->tmat.preimage (new_pos, coord, Proj::Z));
629         if (constrained) {
630             Proj::Pt3 old_pos_proj (persp->tmat.preimage (old_pos, coord, Proj::Z));
631             old_pos_proj.normalize();
632             pt_proj = box3d_snap (box, -1, pt_proj, old_pos_proj);
633         }
634         // normalizing pt_proj is essential because we want to mingle affine coordinates
635         pt_proj.normalize();
636         box->orig_corner0 = Proj::Pt3 ((movement & Box3D::X) ? pt_proj[Proj::X] - radx : box->orig_corner0[Proj::X],
637                                        (movement & Box3D::Y) ? pt_proj[Proj::Y] - rady : box->orig_corner0[Proj::Y],
638                                        box->orig_corner0[Proj::Z],
639                                        1.0);
640         box->orig_corner7 = Proj::Pt3 ((movement & Box3D::X) ? pt_proj[Proj::X] + radx : box->orig_corner7[Proj::X],
641                                        (movement & Box3D::Y) ? pt_proj[Proj::Y] + rady : box->orig_corner7[Proj::Y],
642                                        box->orig_corner7[Proj::Z],
643                                        1.0);
644     } else {
645         double coord = (box->orig_corner0[Proj::X] + box->orig_corner7[Proj::X]) / 2;
646         double radz = (box->orig_corner7[Proj::Z] - box->orig_corner0[Proj::Z]) / 2;
648         Box3D::PerspectiveLine pl(old_pos, Proj::Z, persp);
649         NR::Point new_pos_snapped(pl.closest_to(new_pos));
650         Proj::Pt3 pt_proj (persp->tmat.preimage (new_pos_snapped, coord, Proj::X));
652         /* normalizing pt_proj is essential because we want to mingle affine coordinates */
653         pt_proj.normalize();
654         box->orig_corner0 = Proj::Pt3 (box->orig_corner0[Proj::X],
655                                        box->orig_corner0[Proj::Y],
656                                        pt_proj[Proj::Z] - radz,
657                                        1.0);
658         box->orig_corner7 = Proj::Pt3 (box->orig_corner7[Proj::X],
659                                        box->orig_corner7[Proj::Y],
660                                        pt_proj[Proj::Z] + radz,
661                                        1.0);
662     }
665 /*
666  * Manipulates corner1 through corner4 to contain the indices of the corners
667  * from which the perspective lines in the direction of 'axis' emerge
668  */
669 void box3d_corners_for_PLs (const SPBox3D * box, Proj::Axis axis,
670                             NR::Point &corner1, NR::Point &corner2, NR::Point &corner3, NR::Point &corner4)
672     Persp3D *persp = box3d_get_perspective(box);
673     g_return_if_fail (persp);
674     //box->orig_corner0.normalize();
675     //box->orig_corner7.normalize();
676     double coord = (box->orig_corner0[axis] > box->orig_corner7[axis]) ?
677         box->orig_corner0[axis] :
678         box->orig_corner7[axis];
680     Proj::Pt3 c1, c2, c3, c4;
681     // FIXME: This can certainly be done more elegantly/efficiently than by a case-by-case analysis.
682     switch (axis) {
683         case Proj::X:
684             c1 = Proj::Pt3 (coord, box->orig_corner0[Proj::Y], box->orig_corner0[Proj::Z], 1.0);
685             c2 = Proj::Pt3 (coord, box->orig_corner7[Proj::Y], box->orig_corner0[Proj::Z], 1.0);
686             c3 = Proj::Pt3 (coord, box->orig_corner7[Proj::Y], box->orig_corner7[Proj::Z], 1.0);
687             c4 = Proj::Pt3 (coord, box->orig_corner0[Proj::Y], box->orig_corner7[Proj::Z], 1.0);
688             break;
689         case Proj::Y:
690             c1 = Proj::Pt3 (box->orig_corner0[Proj::X], coord, box->orig_corner0[Proj::Z], 1.0);
691             c2 = Proj::Pt3 (box->orig_corner7[Proj::X], coord, box->orig_corner0[Proj::Z], 1.0);
692             c3 = Proj::Pt3 (box->orig_corner7[Proj::X], coord, box->orig_corner7[Proj::Z], 1.0);
693             c4 = Proj::Pt3 (box->orig_corner0[Proj::X], coord, box->orig_corner7[Proj::Z], 1.0);
694             break;
695         case Proj::Z:
696             c1 = Proj::Pt3 (box->orig_corner7[Proj::X], box->orig_corner7[Proj::Y], coord, 1.0);
697             c2 = Proj::Pt3 (box->orig_corner7[Proj::X], box->orig_corner0[Proj::Y], coord, 1.0);
698             c3 = Proj::Pt3 (box->orig_corner0[Proj::X], box->orig_corner0[Proj::Y], coord, 1.0);
699             c4 = Proj::Pt3 (box->orig_corner0[Proj::X], box->orig_corner7[Proj::Y], coord, 1.0);
700             break;
701         default:
702             return;
703     }
704     corner1 = persp->tmat.image(c1).affine();
705     corner2 = persp->tmat.image(c2).affine();
706     corner3 = persp->tmat.image(c3).affine();
707     corner4 = persp->tmat.image(c4).affine();
710 /* Auxiliary function: Checks whether the half-line from A to B crosses the line segment joining C and D */
711 static bool
712 box3d_half_line_crosses_joining_line (Geom::Point const &A, Geom::Point const &B,
713                                       Geom::Point const &C, Geom::Point const &D) {
714     Geom::Point E; // the point of intersection
715     Geom::Point n0 = (B - A).ccw();
716     double d0 = dot(n0,A);
718     Geom::Point n1 = (D - C).ccw();
719     double d1 = dot(n1,C);
720     Geom::IntersectorKind intersects = Geom::line_intersection(n0, d0, n1, d1, E);
721     if (intersects == Geom::coincident || intersects == Geom::parallel) {
722         return false;
723     }
725     if ((dot(C,n0) < d0) == (dot(D,n0) < d0)) {
726         // C and D lie on the same side of the line AB
727         return false;
728     }
729     if ((dot(A,n1) < d1) != (dot(B,n1) < d1)) {
730         // A and B lie on different sides of the line CD
731         return true;
732     } else if (Geom::distance(E,A) < Geom::distance(E,B)) {
733         // The line CD passes on the "wrong" side of A
734         return false;
735     }
737     // The line CD passes on the "correct" side of A
738     return true;
741 static bool
742 box3d_XY_axes_are_swapped (SPBox3D *box) {
743     Persp3D *persp = box3d_get_perspective(box);
744     g_return_val_if_fail(persp, false);
745     Box3D::PerspectiveLine l1(box3d_get_corner_screen(box, 3), Proj::X, persp);
746     Box3D::PerspectiveLine l2(box3d_get_corner_screen(box, 3), Proj::Y, persp);
747     NR::Point v1(l1.direction());
748     NR::Point v2(l2.direction());
749     v1.normalize();
750     v2.normalize();
752     return (v1[NR::X]*v2[NR::Y] - v1[NR::Y]*v2[NR::X] > 0);
755 static inline void
756 box3d_aux_set_z_orders (int z_orders[6], int a, int b, int c, int d, int e, int f) {
757     z_orders[0] = a;
758     z_orders[1] = b;
759     z_orders[2] = c;
760     z_orders[3] = d;
761     z_orders[4] = e;
762     z_orders[5] = f;
765 static inline void
766 box3d_swap_z_orders (int z_orders[6]) {
767     int tmp;
768     for (int i = 0; i < 3; ++i) {
769         tmp = z_orders[i];
770         z_orders[i] = z_orders[5-i];
771         z_orders[5-i] = tmp;
772     }
775 /*
776  * In standard perspective we have:
777  * 2 = front face
778  * 1 = top face
779  * 0 = left face
780  * 3 = right face
781  * 4 = bottom face
782  * 5 = rear face
783  */
785 /* All VPs infinite */
786 static void
787 box3d_set_new_z_orders_case0 (SPBox3D *box, int z_orders[6], Box3D::Axis central_axis) {
788     Persp3D *persp = box3d_get_perspective(box);
789     NR::Point xdir(persp3d_get_infinite_dir(persp, Proj::X));
790     NR::Point ydir(persp3d_get_infinite_dir(persp, Proj::Y));
791     NR::Point zdir(persp3d_get_infinite_dir(persp, Proj::Z));
793     bool swapped = box3d_XY_axes_are_swapped(box);
795     //g_print ("3 infinite VPs; ");
796     switch(central_axis) {
797         case Box3D::X:
798             if (!swapped) {
799                 //g_print ("central axis X (case a)");
800                 box3d_aux_set_z_orders (z_orders, 2, 0, 4, 1, 3, 5);
801             } else {
802                 //g_print ("central axis X (case b)");
803                 box3d_aux_set_z_orders (z_orders, 3, 1, 5, 2, 4, 0);
804             }
805             break;
806         case Box3D::Y:
807             if (!swapped) {
808                 //g_print ("central axis Y (case a)");
809                 box3d_aux_set_z_orders (z_orders, 2, 3, 1, 4, 0, 5);
810             } else {
811                 //g_print ("central axis Y (case b)");
812                 box3d_aux_set_z_orders (z_orders, 5, 0, 4, 1, 3, 2);
813             }
814             break;
815         case Box3D::Z:
816             if (!swapped) {
817                 //g_print ("central axis Z (case a)");
818                 box3d_aux_set_z_orders (z_orders, 2, 0, 1, 4, 3, 5);
819             } else {
820                 //g_print ("central axis Z (case b)");
821                 box3d_aux_set_z_orders (z_orders, 5, 3, 4, 1, 0, 2);
822             }
823             break;
824         case Box3D::NONE:
825             if (!swapped) {
826                 //g_print ("central axis NONE (case a)");
827                 box3d_aux_set_z_orders (z_orders, 2, 3, 4, 1, 0, 5);
828             } else {
829                 //g_print ("central axis NONE (case b)");
830                 box3d_aux_set_z_orders (z_orders, 5, 0, 1, 4, 3, 2);
831             }
832             break;
833         default:
834             g_assert_not_reached();
835             break;
836     }
837     /**
838     if (swapped) {
839         g_print ("; swapped");
840     }
841     g_print ("\n");
842     **/
845 /* Precisely one finite VP */
846 static void
847 box3d_set_new_z_orders_case1 (SPBox3D *box, int z_orders[6], Box3D::Axis central_axis, Box3D::Axis fin_axis) {
848     Persp3D *persp = box3d_get_perspective(box);
849     NR::Point vp(persp3d_get_VP(persp, Box3D::toProj(fin_axis)).affine());
851     // note: in some of the case distinctions below we rely upon the fact that oaxis1 and oaxis2 are ordered
852     Box3D::Axis oaxis1 = Box3D::get_remaining_axes(fin_axis).first;
853     Box3D::Axis oaxis2 = Box3D::get_remaining_axes(fin_axis).second;
854     //g_print ("oaxis1  = %s, oaxis2  = %s\n", Box3D::string_from_axes(oaxis1), Box3D::string_from_axes(oaxis2));
855     int inside1 = 0;
856     int inside2 = 0;
857     inside1 = box3d_pt_lies_in_PL_sector (box, vp, 3, 3 ^ oaxis2, oaxis1);
858     inside2 = box3d_pt_lies_in_PL_sector (box, vp, 3, 3 ^ oaxis1, oaxis2);
859     //g_print ("inside1 = %d, inside2 = %d\n", inside1, inside2);
861     bool swapped = box3d_XY_axes_are_swapped(box);
863     //g_print ("2 infinite VPs; ");
864     //g_print ("finite axis: %s; ", Box3D::string_from_axes(fin_axis));
865     switch(central_axis) {
866         case Box3D::X:
867             if (!swapped) {
868                 //g_print ("central axis X (case a)");
869                 box3d_aux_set_z_orders (z_orders, 2, 4, 0, 1, 3, 5);
870             } else {
871                 //if (inside2) {
872                     //g_print ("central axis X (case b)");
873                     box3d_aux_set_z_orders (z_orders, 5, 3, 1, 0, 2, 4);
874                 //} else {
875                     //g_print ("central axis X (case c)");
876                     //box3d_aux_set_z_orders (z_orders, 5, 3, 1, 2, 0, 4);
877                 //}
878             }
879             break;
880         case Box3D::Y:
881             if (inside2 > 0) {
882                 //g_print ("central axis Y (case a)");
883                 box3d_aux_set_z_orders (z_orders, 1, 2, 3, 0, 5, 4);
884             } else if (inside2 < 0) {
885                 //g_print ("central axis Y (case b)");
886                 box3d_aux_set_z_orders (z_orders, 2, 3, 1, 4, 0, 5);
887             } else {
888                 if (!swapped) {
889                     //g_print ("central axis Y (case c1)");
890                     box3d_aux_set_z_orders (z_orders, 2, 3, 1, 5, 0, 4);
891                 } else {
892                     //g_print ("central axis Y (case c2)");
893                     box3d_aux_set_z_orders (z_orders, 5, 0, 4, 1, 3, 2);
894                 }
895             }
896             break;
897         case Box3D::Z:
898             if (inside2) {
899                 if (!swapped) {
900                     //g_print ("central axis Z (case a1)");
901                     box3d_aux_set_z_orders (z_orders, 2, 1, 3, 0, 4, 5);
902                 } else {
903                     //g_print ("central axis Z (case a2)");
904                     box3d_aux_set_z_orders (z_orders, 5, 3, 4, 0, 1, 2);
905                 }
906             } else if (inside1) {
907                 if (!swapped) {
908                     //g_print ("central axis Z (case b1)");
909                     box3d_aux_set_z_orders (z_orders, 2, 0, 1, 4, 3, 5);
910                 } else {
911                     //g_print ("central axis Z (case b2)");
912                     box3d_aux_set_z_orders (z_orders, 5, 3, 4, 1, 0, 2);
913                     //box3d_aux_set_z_orders (z_orders, 5, 3, 0, 1, 2, 4);
914                 }
915             } else {
916                 // "regular" case
917                 if (!swapped) {
918                     //g_print ("central axis Z (case c1)");
919                     box3d_aux_set_z_orders (z_orders, 0, 1, 2, 5, 4, 3);
920                 } else {
921                     //g_print ("central axis Z (case c2)");
922                     box3d_aux_set_z_orders (z_orders, 5, 3, 4, 0, 2, 1);
923                     //box3d_aux_set_z_orders (z_orders, 5, 3, 4, 0, 2, 1);
924                 }
925             }
926             break;
927         case Box3D::NONE:
928             if (!swapped) {
929                 //g_print ("central axis NONE (case a)");
930                 box3d_aux_set_z_orders (z_orders, 2, 3, 4, 5, 0, 1);
931             } else {
932                 //g_print ("central axis NONE (case b)");
933                 box3d_aux_set_z_orders (z_orders, 5, 0, 1, 3, 2, 4);
934                 //box3d_aux_set_z_orders (z_orders, 2, 3, 4, 1, 0, 5);
935             }
936             break;
937         default:
938             g_assert_not_reached();
939     }
940     /**
941     if (swapped) {
942         g_print ("; swapped");
943     }
944     g_print ("\n");
945     **/
948 /* Precisely 2 finite VPs */
949 static void
950 box3d_set_new_z_orders_case2 (SPBox3D *box, int z_orders[6], Box3D::Axis central_axis, Box3D::Axis /*infinite_axis*/) {
951     Persp3D *persp = box3d_get_perspective(box);
953     NR::Point c3(box3d_get_corner_screen(box, 3));
954     NR::Point xdir(persp3d_get_PL_dir_from_pt(persp, c3, Proj::X));
955     NR::Point ydir(persp3d_get_PL_dir_from_pt(persp, c3, Proj::Y));
956     NR::Point zdir(persp3d_get_PL_dir_from_pt(persp, c3, Proj::Z));
958     bool swapped = box3d_XY_axes_are_swapped(box);
960     int insidexy = box3d_VP_lies_in_PL_sector (box, Proj::X, 3, 3 ^ Box3D::Z, Box3D::Y);
961     int insidexz = box3d_VP_lies_in_PL_sector (box, Proj::X, 3, 3 ^ Box3D::Y, Box3D::Z);
963     int insideyx = box3d_VP_lies_in_PL_sector (box, Proj::Y, 3, 3 ^ Box3D::Z, Box3D::X);
964     int insideyz = box3d_VP_lies_in_PL_sector (box, Proj::Y, 3, 3 ^ Box3D::X, Box3D::Z);
966     int insidezx = box3d_VP_lies_in_PL_sector (box, Proj::Z, 3, 3 ^ Box3D::Y, Box3D::X);
967     int insidezy = box3d_VP_lies_in_PL_sector (box, Proj::Z, 3, 3 ^ Box3D::X, Box3D::Y);
969     //g_print ("Insides: xy = %d, xz = %d, yx = %d, yz = %d, zx = %d, zy = %d\n",
970     //         insidexy, insidexz, insideyx, insideyz, insidezx, insidezy);
971     (void)insidexz;
972     (void)insideyx;
973     (void)insidezx;
975     //g_print ("1 infinite VP; ");
976     switch(central_axis) {
977         case Box3D::X:
978             if (!swapped) {
979                 if (insidezy == -1) {
980                     //g_print ("central axis X (case a1)");
981                     box3d_aux_set_z_orders (z_orders, 2, 4, 0, 1, 3, 5);
982                 } else if (insidexy == 1) {
983                     //g_print ("central axis X (case a2)");
984                     box3d_aux_set_z_orders (z_orders, 2, 4, 0, 5, 1, 3);
985                 } else {
986                     //g_print ("central axis X (case a3)");
987                     box3d_aux_set_z_orders (z_orders, 2, 4, 0, 1, 3, 5);
988                 }
989             } else {
990                 if (insideyz == -1) {
991                     //g_print ("central axis X (case b1)");
992                     box3d_aux_set_z_orders (z_orders, 3, 1, 5, 0, 2, 4);
993                 } else {
994                     if (!swapped) {
995                         //g_print ("central axis X (case b2)");
996                         box3d_aux_set_z_orders (z_orders, 3, 1, 5, 2, 4, 0);
997                     } else {
998                         //g_print ("central axis X (case b3)");
999                         if (insidexy == 0) {
1000                             box3d_aux_set_z_orders (z_orders, 3, 5, 1, 0, 2, 4);
1001                         } else {
1002                             box3d_aux_set_z_orders (z_orders, 3, 1, 5, 0, 2, 4);
1003                         }
1004                     }
1005                 }
1006             }
1007             break;
1008         case Box3D::Y:
1009             if (!swapped) {
1010                 if (insideyz == 1) {
1011                     //g_print ("central axis Y (case a1)");
1012                     box3d_aux_set_z_orders (z_orders, 2, 3, 1, 0, 5, 4);
1013                 } else {
1014                     //g_print ("central axis Y (case a2)");
1015                     box3d_aux_set_z_orders (z_orders, 2, 3, 1, 5, 0, 4);
1016                 }
1017             } else {
1018                 //g_print ("central axis Y (case b)");
1019                 if (insideyx == 1) {
1020                     box3d_aux_set_z_orders (z_orders, 4, 0, 5, 1, 3, 2);
1021                 } else {
1022                     box3d_aux_set_z_orders (z_orders, 5, 0, 4, 1, 3, 2);
1023                 }
1024             }
1025             break;
1026         case Box3D::Z:
1027             if (!swapped) {
1028                 if (insidezy == 1) {
1029                     //g_print ("central axis Z (case a1)");
1030                     box3d_aux_set_z_orders (z_orders, 2, 1, 0, 4, 3, 5);
1031                 } else if (insidexy == -1) {
1032                     //g_print ("central axis Z (case a2)");
1033                     box3d_aux_set_z_orders (z_orders, 2, 1, 0, 5, 4, 3);
1034                 } else {
1035                     //g_print ("central axis Z (case a3)");
1036                     box3d_aux_set_z_orders (z_orders, 2, 0, 1, 5, 3, 4);
1037                 }
1038             } else {
1039                 //g_print ("central axis Z (case b)");
1040                 box3d_aux_set_z_orders (z_orders, 3, 4, 5, 1, 0, 2);
1041             }
1042             break;
1043         case Box3D::NONE:
1044             if (!swapped) {
1045                 //g_print ("central axis NONE (case a)");
1046                 box3d_aux_set_z_orders (z_orders, 2, 3, 4, 1, 0, 5);
1047             } else {
1048                 //g_print ("central axis NONE (case b)");
1049                 box3d_aux_set_z_orders (z_orders, 5, 0, 1, 4, 3, 2);
1050             }
1051             break;
1052         default:
1053             g_assert_not_reached();
1054             break;
1055     }
1056     /**
1057     if (swapped) {
1058         g_print ("; swapped");
1059     }
1060     g_print ("\n");
1061     **/
1064 /*
1065  * It can happen that during dragging the box is everted.
1066  * In this case the opposite sides in this direction need to be swapped
1067  */
1068 static Box3D::Axis
1069 box3d_everted_directions (SPBox3D *box) {
1070     Box3D::Axis ev = Box3D::NONE;
1072     box->orig_corner0.normalize();
1073     box->orig_corner7.normalize();
1075     if (box->orig_corner0[Proj::X] < box->orig_corner7[Proj::X])
1076         ev = (Box3D::Axis) (ev ^ Box3D::X);
1077     if (box->orig_corner0[Proj::Y] < box->orig_corner7[Proj::Y])
1078         ev = (Box3D::Axis) (ev ^ Box3D::Y);
1079     if (box->orig_corner0[Proj::Z] > box->orig_corner7[Proj::Z]) // FIXME: Remove the need to distinguish signs among the cases
1080         ev = (Box3D::Axis) (ev ^ Box3D::Z);
1082     return ev;
1085 static void
1086 box3d_swap_sides(int z_orders[6], Box3D::Axis axis) {
1087     int pos1 = -1;
1088     int pos2 = -1;
1090     for (int i = 0; i < 6; ++i) {
1091         if (!(Box3D::int_to_face(z_orders[i]) & axis)) {
1092             if (pos1 == -1) {
1093                 pos1 = i;
1094             } else {
1095                 pos2 = i;
1096                 break;
1097             }
1098         }
1099     }
1101     int tmp = z_orders[pos1];
1102     z_orders[pos1] = z_orders[pos2];
1103     z_orders[pos2] = tmp;
1107 bool
1108 box3d_recompute_z_orders (SPBox3D *box) {
1109     Persp3D *persp = box3d_get_perspective(box);
1111     //g_return_val_if_fail(persp, false);
1112     if (!persp)
1113         return false;
1115     int z_orders[6];
1117     NR::Point c3(box3d_get_corner_screen(box, 3));
1119     // determine directions from corner3 to the VPs
1120     int num_finite = 0;
1121     Box3D::Axis axis_finite = Box3D::NONE;
1122     Box3D::Axis axis_infinite = Box3D::NONE;
1123     NR::Point dirs[3];
1124     for (int i = 0; i < 3; ++i) {
1125         dirs[i] = persp3d_get_PL_dir_from_pt(persp, c3, Box3D::toProj(Box3D::axes[i]));
1126         if (persp3d_VP_is_finite(persp, Proj::axes[i])) {
1127             num_finite++;
1128             axis_finite = Box3D::axes[i];
1129         } else {
1130             axis_infinite = Box3D::axes[i];
1131         }
1132     }
1134     // determine the "central" axis (if there is one)
1135     Box3D::Axis central_axis = Box3D::NONE;
1136     if(Box3D::lies_in_sector(dirs[0], dirs[1], dirs[2])) {
1137         central_axis = Box3D::Z;
1138     } else if(Box3D::lies_in_sector(dirs[1], dirs[2], dirs[0])) {
1139         central_axis = Box3D::X;
1140     } else if(Box3D::lies_in_sector(dirs[2], dirs[0], dirs[1])) {
1141         central_axis = Box3D::Y;
1142     }
1144     switch (num_finite) {
1145         case 0:
1146             // TODO: Remark: In this case (and maybe one of the others, too) the z-orders for all boxes
1147             //               coincide, hence only need to be computed once in a more central location.
1148             box3d_set_new_z_orders_case0(box, z_orders, central_axis);
1149             break;
1150         case 1:
1151             box3d_set_new_z_orders_case1(box, z_orders, central_axis, axis_finite);
1152             break;
1153         case 2:
1154         case 3:
1155             box3d_set_new_z_orders_case2(box, z_orders, central_axis, axis_infinite);
1156             break;
1157         default:
1158         /*
1159          * For each VP F, check wether the half-line from the corner3 to F crosses the line segment
1160          * joining the other two VPs. If this is the case, it determines the "central" corner from
1161          * which the visible sides can be deduced. Otherwise, corner3 is the central corner.
1162          */
1163         // FIXME: We should eliminate the use of NR::Point altogether
1164         Box3D::Axis central_axis = Box3D::NONE;
1165         NR::Point vp_x = persp3d_get_VP(persp, Proj::X).affine();
1166         NR::Point vp_y = persp3d_get_VP(persp, Proj::Y).affine();
1167         NR::Point vp_z = persp3d_get_VP(persp, Proj::Z).affine();
1168         Geom::Point vpx(vp_x[NR::X], vp_x[NR::Y]);
1169         Geom::Point vpy(vp_y[NR::X], vp_y[NR::Y]);
1170         Geom::Point vpz(vp_z[NR::X], vp_z[NR::Y]);
1172         NR::Point c3 = box3d_get_corner_screen(box, 3);
1173         Geom::Point corner3(c3[NR::X], c3[NR::Y]);
1175         if (box3d_half_line_crosses_joining_line (corner3, vpx, vpy, vpz)) {
1176             central_axis = Box3D::X;
1177         } else if (box3d_half_line_crosses_joining_line (corner3, vpy, vpz, vpx)) {
1178             central_axis = Box3D::Y;
1179         } else if (box3d_half_line_crosses_joining_line (corner3, vpz, vpx, vpy)) {
1180             central_axis = Box3D::Z;
1181         }
1182         //g_print ("Crossing: %s\n", Box3D::string_from_axes(central_axis));
1184         unsigned int central_corner = 3 ^ central_axis;
1185         if (central_axis == Box3D::Z) {
1186             central_corner = central_corner ^ Box3D::XYZ;
1187         }
1188         if (box3d_XY_axes_are_swapped(box)) {
1189             //g_print ("Axes X and Y are swapped\n");
1190             central_corner = central_corner ^ Box3D::XYZ;
1191         }
1193         NR::Point c1(box3d_get_corner_screen(box, 1));
1194         NR::Point c2(box3d_get_corner_screen(box, 2));
1195         NR::Point c7(box3d_get_corner_screen(box, 7));
1197         Geom::Point corner1(c1[NR::X], c1[NR::Y]);
1198         Geom::Point corner2(c2[NR::X], c2[NR::Y]);
1199         Geom::Point corner7(c7[NR::X], c7[NR::Y]);
1200         // FIXME: At present we don't use the information about central_corner computed above.
1201         switch (central_axis) {
1202             case Box3D::Y:
1203                 if (!box3d_half_line_crosses_joining_line(vpz, vpy, corner3, corner2)) {
1204                     box3d_aux_set_z_orders (z_orders, 2, 3, 1, 5, 0, 4);
1205                 } else {
1206                     // degenerate case
1207                     //g_print ("Degenerate case #1\n");
1208                     box3d_aux_set_z_orders (z_orders, 2, 1, 3, 0, 5, 4);
1209                 }
1210                 break;
1212             case Box3D::Z:
1213                 if (box3d_half_line_crosses_joining_line(vpx, vpz, corner3, corner1)) {
1214                     // degenerate case
1215                     //g_print ("Degenerate case #2\n");
1216                     box3d_aux_set_z_orders (z_orders, 2, 0, 1, 4, 3, 5);
1217                 } else if (box3d_half_line_crosses_joining_line(vpx, vpy, corner3, corner7)) {
1218                     // degenerate case
1219                     //g_print ("Degenerate case #3\n");
1220                     box3d_aux_set_z_orders (z_orders, 2, 1, 0, 5, 3, 4);
1221                 } else {
1222                     box3d_aux_set_z_orders (z_orders, 2, 1, 0, 3, 4, 5);
1223                 }
1224                 break;
1226             case Box3D::X:
1227                 if (box3d_half_line_crosses_joining_line(vpz, vpx, corner3, corner1)) {
1228                     // degenerate case
1229                     //g_print ("Degenerate case #4\n");
1230                     box3d_aux_set_z_orders (z_orders, 2, 1, 0, 4, 5, 3);
1231                 } else {
1232                     box3d_aux_set_z_orders (z_orders, 2, 4, 0, 5, 1, 3);
1233                 }
1234                 break;
1236             case Box3D::NONE:
1237                 box3d_aux_set_z_orders (z_orders, 2, 3, 4, 1, 0, 5);
1238                 break;
1240             default:
1241                 g_assert_not_reached();
1242                 break;
1243         } // end default case
1244     }
1246     // TODO: If there are still errors in z-orders of everted boxes, we need to choose a variable corner
1247     //       instead of the hard-coded corner #3 in the computations above
1248     Box3D::Axis ev = box3d_everted_directions(box);
1249     for (int i = 0; i < 3; ++i) {
1250         if (ev & Box3D::axes[i]) {
1251             box3d_swap_sides(z_orders, Box3D::axes[i]);
1252         }
1253     }
1255     // Check whether anything actually changed
1256     for (int i = 0; i < 6; ++i) {
1257         if (box->z_orders[i] != z_orders[i]) {
1258             for (int j = i; j < 6; ++j) {
1259                 box->z_orders[j] = z_orders[j];
1260             }
1261             return true;
1262         }
1263     }
1264     return false;
1267 static std::map<int, Box3DSide *>
1268 box3d_get_sides (SPBox3D *box) {
1269     std::map<int, Box3DSide *> sides;
1270     for (SPObject *side = sp_object_first_child(box); side != NULL; side = SP_OBJECT_NEXT(side)) {
1271         sides[Box3D::face_to_int(sp_repr_get_int_attribute(SP_OBJECT_REPR(side),
1272                                                            "inkscape:box3dsidetype", -1))] = SP_BOX3D_SIDE(side);
1273     }
1274     sides.erase(-1);
1275     return sides;
1279 // TODO: Check whether the box is everted in any direction and swap the sides opposite to this direction
1280 void
1281 box3d_set_z_orders (SPBox3D *box) {
1282     // For efficiency reasons, we only set the new z-orders if something really changed
1283     if (box3d_recompute_z_orders (box)) {
1284         std::map<int, Box3DSide *> sides = box3d_get_sides(box);
1285         std::map<int, Box3DSide *>::iterator side;
1286         for (unsigned int i = 0; i < 6; ++i) {
1287             side = sides.find(box->z_orders[i]);
1288             if (side != sides.end()) {
1289                 SP_ITEM((*side).second)->lowerToBottom();
1290             }
1291         }
1292         /**
1293         g_print ("Resetting z-orders: ");
1294         for (int i = 0; i < 6; ++i) {
1295             g_print ("%d ", box->z_orders[i]);
1296         }
1297         g_print ("\n");
1298         **/
1299     }
1302 /*
1303  * Auxiliary function for z-order recomputing:
1304  * Determines whether \a pt lies in the sector formed by the two PLs from the corners with IDs
1305  * \a i21 and \a id2 to the VP in direction \a axis. If the VP is infinite, we say that \a pt
1306  * lies in the sector if it lies between the two (parallel) PLs.
1307  * \ret *  0 if \a pt doesn't lie in the sector
1308  *      *  1 if \a pt lies in the sector and either VP is finite of VP is infinite and the direction
1309  *           from the edge between the two corners to \a pt points towards the VP
1310  *      * -1 otherwise
1311  */
1312 // TODO: Maybe it would be useful to have a similar method for projective points pt because then we
1313 //       can use it for VPs and perhaps merge the case distinctions during z-order recomputation.
1314 int
1315 box3d_pt_lies_in_PL_sector (SPBox3D const *box, NR::Point const &pt, int id1, int id2, Box3D::Axis axis) {
1316     Persp3D *persp = box3d_get_perspective(box);
1318     // the two corners
1319     NR::Point c1(box3d_get_corner_screen(box, id1));
1320     NR::Point c2(box3d_get_corner_screen(box, id2));
1322     int ret = 0;
1323     if (persp3d_VP_is_finite(persp, Box3D::toProj(axis))) {
1324         NR::Point vp(persp3d_get_VP(persp, Box3D::toProj(axis)).affine());
1325         NR::Point v1(c1 - vp);
1326         NR::Point v2(c2 - vp);
1327         NR::Point w(pt - vp);
1328         ret = static_cast<int>(Box3D::lies_in_sector(v1, v2, w));
1329         //g_print ("Case 0 - returning %d\n", ret);
1330     } else {
1331         Box3D::PerspectiveLine pl1(c1, Box3D::toProj(axis), persp);
1332         Box3D::PerspectiveLine pl2(c2, Box3D::toProj(axis), persp);
1333         if (pl1.lie_on_same_side(pt, c2) && pl2.lie_on_same_side(pt, c1)) {
1334             // test whether pt lies "towards" or "away from" the VP
1335             Box3D::Line edge(c1,c2);
1336             NR::Point c3(box3d_get_corner_screen(box, id1 ^ axis));
1337             if (edge.lie_on_same_side(pt, c3)) {
1338                 ret = 1;
1339             } else {
1340                 ret = -1;
1341             }
1342         }
1343         //g_print ("Case 1 - returning %d\n", ret);
1344     }
1345     return ret;
1348 int
1349 box3d_VP_lies_in_PL_sector (SPBox3D const *box, Proj::Axis vpdir, int id1, int id2, Box3D::Axis axis) {
1350     Persp3D *persp = box3d_get_perspective(box);
1352     if (!persp3d_VP_is_finite(persp, vpdir)) {
1353         return 0;
1354     } else {
1355         return box3d_pt_lies_in_PL_sector(box, persp3d_get_VP(persp, vpdir).affine(), id1, id2, axis);
1356     }
1359 /* swap the coordinates of corner0 and corner7 along the specified axis */
1360 static void
1361 box3d_swap_coords(SPBox3D *box, Proj::Axis axis, bool smaller = true) {
1362     box->orig_corner0.normalize();
1363     box->orig_corner7.normalize();
1364     if ((box->orig_corner0[axis] < box->orig_corner7[axis]) != smaller) {
1365         double tmp = box->orig_corner0[axis];
1366         box->orig_corner0[axis] = box->orig_corner7[axis];
1367         box->orig_corner7[axis] = tmp;
1368     }
1369     // FIXME: Should we also swap the coordinates of save_corner0 and save_corner7?
1372 /* ensure that the coordinates of corner0 and corner7 are in the correct order (to prevent everted boxes) */
1373 void
1374 box3d_relabel_corners(SPBox3D *box) {
1375     box3d_swap_coords(box, Proj::X, false);
1376     box3d_swap_coords(box, Proj::Y, false);
1377     box3d_swap_coords(box, Proj::Z, true);
1380 static void
1381 box3d_check_for_swapped_coords(SPBox3D *box, Proj::Axis axis, bool smaller) {
1382     box->orig_corner0.normalize();
1383     box->orig_corner7.normalize();
1385     if ((box->orig_corner0[axis] < box->orig_corner7[axis]) != smaller) {
1386         box->swapped = (Box3D::Axis) (box->swapped | Proj::toAffine(axis));
1387     } else {
1388         box->swapped = (Box3D::Axis) (box->swapped & ~Proj::toAffine(axis));
1389     }
1392 static void
1393 box3d_exchange_coords(SPBox3D *box) {
1394     box->orig_corner0.normalize();
1395     box->orig_corner7.normalize();
1397     for (int i = 0; i < 3; ++i) {
1398         if (box->swapped & Box3D::axes[i]) {
1399             double tmp = box->orig_corner0[i];
1400             box->orig_corner0[i] = box->orig_corner7[i];
1401             box->orig_corner7[i] = tmp;
1402         }
1403     }
1406 void
1407 box3d_check_for_swapped_coords(SPBox3D *box) {
1408     box3d_check_for_swapped_coords(box, Proj::X, false);
1409     box3d_check_for_swapped_coords(box, Proj::Y, false);
1410     box3d_check_for_swapped_coords(box, Proj::Z, true);
1412     box3d_exchange_coords(box);
1415 void
1416 box3d_add_to_selection(SPBox3D *box) {
1417     Persp3D *persp = box3d_get_perspective(box);
1418     g_return_if_fail(persp);
1419     persp3d_add_box_transform(persp, box);
1422 void
1423 box3d_remove_from_selection(SPBox3D *box) {
1424     Persp3D *persp = box3d_get_perspective(box);
1425     if (!persp) {
1426         /* this can happen if a box is deleted through undo and the persp_ref is already detached;
1427            should we rebuild the boxes of each perspective in this case or is it safe to leave it alone? */
1428         return;
1429     }
1430     persp3d_remove_box_transform(persp, box);
1433 void
1434 box3d_mark_transformed(SPBox3D *box) {
1435     Persp3D *persp = box3d_get_perspective(box);
1436     g_return_if_fail(persp);
1437     persp3d_set_box_transformed(persp, box, true);
1440 Persp3D *
1441 box3d_get_perspective(SPBox3D const *box) {
1442     return box->persp_ref->getObject();
1445 void
1446 box3d_switch_perspectives(SPBox3D *box, Persp3D *old_persp, Persp3D *new_persp, bool recompute_corners) {
1447     if (recompute_corners) {
1448         box->orig_corner0.normalize();
1449         box->orig_corner7.normalize();
1450         double z0 = box->orig_corner0[Proj::Z];
1451         double z7 = box->orig_corner7[Proj::Z];
1452         NR::Point corner0_screen = box3d_get_corner_screen(box, 0);
1453         NR::Point corner7_screen = box3d_get_corner_screen(box, 7);
1455         box->orig_corner0 = new_persp->tmat.preimage(corner0_screen, z0, Proj::Z);
1456         box->orig_corner7 = new_persp->tmat.preimage(corner7_screen, z7, Proj::Z);
1457     }
1459     persp3d_remove_box (old_persp, box);
1460     persp3d_add_box (new_persp, box);
1462     persp3d_remove_box_transform (old_persp, box);
1463     persp3d_add_box_transform (new_persp, box);
1465     gchar *href = g_strdup_printf("#%s", SP_OBJECT_REPR(new_persp)->attribute("id"));
1466     SP_OBJECT_REPR(box)->setAttribute("inkscape:perspectiveID", href);
1467     g_free(href);
1470 /* Converts the 3D box to an ordinary SPGroup, adds it to the XML tree at the same position as
1471    the original box and deletes the latter */
1472 // TODO: Copy over all important attributes (see sp_selected_item_to_curved_repr() for an example)
1473 SPGroup *
1474 box3d_convert_to_group(SPBox3D *box) {
1475     SPDocument *doc = SP_OBJECT_DOCUMENT(box);
1476     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
1478     // remember position of the box
1479     int pos = SP_OBJECT_REPR(box)->position();
1481     // create a new group and add the sides (converted to ordinary paths) as its children
1482     Inkscape::XML::Node *grepr = xml_doc->createElement("svg:g");
1484     Inkscape::XML::Node *repr;
1485     for (SPObject *child = sp_object_first_child(SP_OBJECT(box)); child != NULL; child = SP_OBJECT_NEXT(child) ) {
1486         if (SP_IS_BOX3D_SIDE(child)) {
1487             repr = box3d_side_convert_to_path(SP_BOX3D_SIDE(child));
1488             grepr->appendChild(repr);
1489         } else {
1490             g_warning("Non-side object encountered as child of a 3D box.\n");
1491         }
1492     }
1494     // add the new group to the box's parent and set remembered position
1495     SPObject *parent = SP_OBJECT_PARENT(box);
1496     SP_OBJECT_REPR(parent)->appendChild(grepr);
1497     grepr->setPosition(pos);
1499     SP_OBJECT(box)->deleteObject(true);
1501     return SP_GROUP(doc->getObjectByRepr(grepr));
1504 static inline void
1505 box3d_push_back_corner_pair(SPBox3D *box, std::list<std::pair<Geom::Point, Geom::Point> > &pts, int c1, int c2) {
1506     pts.push_back(std::make_pair(box3d_get_corner_screen(box, c1).to_2geom(),
1507                                  box3d_get_corner_screen(box, c2).to_2geom()));
1510 void
1511 box3d_convert_to_guides(SPItem *item) {
1512     SPBox3D *box = SP_BOX3D(item);
1514     if (prefs_get_int_attribute("tools.shapes.3dbox", "convertguides", 1) == 0) {
1515         sp_item_convert_to_guides(SP_ITEM(box));
1516         return;
1517     }
1519     SPDocument *doc = SP_OBJECT_DOCUMENT(box);
1521     std::list<std::pair<Geom::Point, Geom::Point> > pts;
1523     /* perspective lines in X direction */
1524     box3d_push_back_corner_pair(box, pts, 0, 1);
1525     box3d_push_back_corner_pair(box, pts, 2, 3);
1526     box3d_push_back_corner_pair(box, pts, 4, 5);
1527     box3d_push_back_corner_pair(box, pts, 6, 7);
1529     /* perspective lines in Y direction */
1530     box3d_push_back_corner_pair(box, pts, 0, 2);
1531     box3d_push_back_corner_pair(box, pts, 1, 3);
1532     box3d_push_back_corner_pair(box, pts, 4, 6);
1533     box3d_push_back_corner_pair(box, pts, 5, 7);
1535     /* perspective lines in Z direction */
1536     box3d_push_back_corner_pair(box, pts, 0, 4);
1537     box3d_push_back_corner_pair(box, pts, 1, 5);
1538     box3d_push_back_corner_pair(box, pts, 2, 6);
1539     box3d_push_back_corner_pair(box, pts, 3, 7);
1541     sp_guide_pt_pairs_to_guides(doc, pts);
1544 /*
1545   Local Variables:
1546   mode:c++
1547   c-file-style:"stroustrup"
1548   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1549   indent-tabs-mode:nil
1550   fill-column:99
1551   End:
1552 */
1553 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :