Code

Set z-orders of 3D box faces during dragging/resizing according to the perspective
[inkscape.git] / src / box3d.cpp
1 #define __SP_3DBOX_C__
3 /*
4  * SVG <box3d> implementation
5  *
6  * Authors:
7  *   Lauris Kaplinski <lauris@kaplinski.com>
8  *   bulia byak <buliabyak@users.sf.net>
9  *   Maximilian Albert <Anhalter42@gmx.de>
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 "svg/stringstream.h"
21 #include "box3d.h"
23 static void sp_3dbox_class_init(SP3DBoxClass *klass);
24 static void sp_3dbox_init(SP3DBox *box3d);
26 static void sp_3dbox_build(SPObject *object, SPDocument *document, Inkscape::XML::Node *repr);
27 static void sp_3dbox_release (SPObject *object);
28 static void sp_3dbox_set(SPObject *object, unsigned int key, const gchar *value);
29 static void sp_3dbox_update(SPObject *object, SPCtx *ctx, guint flags);
30 static Inkscape::XML::Node *sp_3dbox_write(SPObject *object, Inkscape::XML::Node *repr, guint flags);
32 static gchar *sp_3dbox_description(SPItem *item);
34 //static void sp_3dbox_set_shape(SPShape *shape);
35 //static void sp_3dbox_set_shape(SP3DBox *box3d);
37 static void sp_3dbox_update_corner_with_value_from_svg (SPObject *object, guint corner_id, const gchar *value);
38 static void sp_3dbox_update_perspective (Box3D::Perspective3D *persp, const gchar *value);
39 static gchar * sp_3dbox_get_corner_coords_string (SP3DBox *box, guint id);
40 static std::pair<gdouble, gdouble> sp_3dbox_get_coord_pair_from_string (const gchar *);
41 static gchar * sp_3dbox_get_perspective_string (SP3DBox *box);
43 static SPGroupClass *parent_class;
45 static gint counter = 0;
47 GType
48 sp_3dbox_get_type(void)
49 {
50     static GType type = 0;
52     if (!type) {
53         GTypeInfo info = {
54             sizeof(SP3DBoxClass),
55             NULL,   /* base_init */
56             NULL,   /* base_finalize */
57             (GClassInitFunc) sp_3dbox_class_init,
58             NULL,   /* class_finalize */
59             NULL,   /* class_data */
60             sizeof(SP3DBox),
61             16,     /* n_preallocs */
62             (GInstanceInitFunc) sp_3dbox_init,
63             NULL,   /* value_table */
64         };
65         type = g_type_register_static(SP_TYPE_GROUP, "SP3DBox", &info, (GTypeFlags) 0);
66     }
68     return type;
69 }
71 static void
72 sp_3dbox_class_init(SP3DBoxClass *klass)
73 {
74     SPObjectClass *sp_object_class = (SPObjectClass *) klass;
75     SPItemClass *item_class = (SPItemClass *) klass;
77     parent_class = (SPGroupClass *) g_type_class_ref(SP_TYPE_GROUP);
79     sp_object_class->build = sp_3dbox_build;
80     sp_object_class->set = sp_3dbox_set;
81     sp_object_class->write = sp_3dbox_write;
82     sp_object_class->update = sp_3dbox_update;
83     sp_object_class->release = sp_3dbox_release;
85     item_class->description = sp_3dbox_description;
86 }
88 static void
89 sp_3dbox_init(SP3DBox *box)
90 {
91     for (int i = 0; i < 8; ++i) box->corners[i] = NR::Point(0,0);
92     for (int i = 0; i < 6; ++i) box->faces[i] = NULL;
93 }
95 static void
96 sp_3dbox_build(SPObject *object, SPDocument *document, Inkscape::XML::Node *repr)
97 {
98     if (((SPObjectClass *) (parent_class))->build) {
99         ((SPObjectClass *) (parent_class))->build(object, document, repr);
100     }
102     SP3DBox *box = SP_3DBOX (object);
104     box->my_counter = counter++;
106     /* we initialize the z-orders to zero so that they are updated during dragging */
107     for (int i = 0; i < 6; ++i) {
108         box->z_orders[i] = 0;
109     }
111     box->front_bits = 0x0;
113     if (repr->attribute ("inkscape:perspective") == NULL) {
114         // we are creating a new box; link it to the current perspective
115         Box3D::Perspective3D::current_perspective->add_box (box);
116     } else {
117         // create a new perspective that we can compare with existing ones
118         Box3D::Perspective3D *persp = new Box3D::Perspective3D (Box3D::VanishingPoint (0,0),
119                                                                 Box3D::VanishingPoint (0,0),
120                                                                 Box3D::VanishingPoint (0,0));
121         sp_3dbox_update_perspective (persp, repr->attribute ("inkscape:perspective"));
122         Box3D::Perspective3D *comp =  Box3D::Perspective3D::find_perspective (persp);
123         if (comp == NULL) {
124             // perspective doesn't exist yet
125             Box3D::Perspective3D::add_perspective (persp);
126             persp->add_box (box);
127         } else {
128             // link the box to the existing perspective and delete the temporary one
129             comp->add_box (box);
130             delete persp;
131             //g_assert (Box3D::get_persp_of_box (box) == comp);
133             // FIXME: If the paths of the box's faces do not correspond to the svg representation of the perspective
134             //        the box is shown with a "wrong" initial shape that is only corrected after dragging.
135             //        Should we "repair" this by updating the paths at the end of sp_3dbox_build()?
136             //        Maybe it would be better to simply destroy and rebuild them in sp_3dbox_link_to_existing_paths().
137         }
138     }
140     sp_object_read_attr(object, "inkscape:box3dcornerA");
141     sp_object_read_attr(object, "inkscape:box3dcornerB");
142     sp_object_read_attr(object, "inkscape:box3dcornerC");
144     // TODO: We create all faces in the beginning, but only the non-degenerate ones
145     //       should be written to the svg representation later in sp_3dbox_write.
146     Box3D::Axis cur_plane, axis, dir1, dir2;
147     Box3D::FrontOrRear cur_pos;
148     for (int i = 0; i < 3; ++i) {
149         for (int j = 0; j < 2; ++j) {
150             cur_plane = Box3D::planes[i];
151             cur_pos = Box3D::face_positions[j];
152             // FIXME: The following code could theoretically be moved to
153             //        the constructor of Box3DFace (but see the comment there).
154             axis = (cur_pos == Box3D::FRONT ? Box3D::NONE : Box3D::third_axis_direction (cur_plane));
155             dir1 = extract_first_axis_direction (cur_plane);
156             dir2 = extract_second_axis_direction (cur_plane);
157             
158             box->faces[Box3D::face_to_int(cur_plane ^ cur_pos)] =
159                 new Box3DFace (box, box->corners[axis], box->corners[axis ^ dir1],
160                                     box->corners[axis ^ dir1 ^ dir2], box->corners[axis ^ dir2],
161                                     cur_plane, cur_pos);
162         }
163     }
165     // Check whether the paths of the faces of the box need to be linked to existing paths in the
166     // document (e.g., after a 'redo' operation or after opening a file) and do so if necessary.
167     sp_3dbox_link_to_existing_paths (box, repr);
169     sp_3dbox_set_ratios (box);
172 static void
173 sp_3dbox_release (SPObject *object)
175         SP3DBox *box = SP_3DBOX(object);
176         for (int i = 0; i < 6; ++i) {
177             if (box->faces[i]) {
178                 delete box->faces[i]; // FIXME: Anything else to do? Do we need to clean up the face first?
179             }
180         }
182         // FIXME: We do not duplicate perspectives if they are the same for several boxes.
183         //        Thus, don't delete the perspective when deleting a box but rather unlink the box from it.
184         Box3D::get_persp_of_box (box)->remove_box (box);
186         if (((SPObjectClass *) parent_class)->release) {
187           ((SPObjectClass *) parent_class)->release (object);
188         }
191 static void sp_3dbox_set(SPObject *object, unsigned int key, const gchar *value)
193     switch (key) {
194         case SP_ATTR_INKSCAPE_3DBOX_CORNER_A:
195             sp_3dbox_update_corner_with_value_from_svg (object, 2, value);
196             break;
197         case SP_ATTR_INKSCAPE_3DBOX_CORNER_B:
198             sp_3dbox_update_corner_with_value_from_svg (object, 1, value);
199             break;
200         case SP_ATTR_INKSCAPE_3DBOX_CORNER_C:
201             sp_3dbox_update_corner_with_value_from_svg (object, 5, value);
202             break;
203         case SP_ATTR_INKSCAPE_3DBOX_PERSPECTIVE:
204             sp_3dbox_update_perspective (Box3D::get_persp_of_box (SP_3DBOX (object)), value);
205             break;
206         default:
207             if (((SPObjectClass *) (parent_class))->set) {
208                 ((SPObjectClass *) (parent_class))->set(object, key, value);
209             }
210             break;
211     }
214 static void
215 sp_3dbox_update(SPObject *object, SPCtx *ctx, guint flags)
217     if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) {
218         SP3DBox *box = SP_3DBOX(object);
219         sp_3dbox_link_to_existing_paths (box, SP_OBJECT_REPR(object));
220     }
222     /* Invoke parent method */
223     if (((SPObjectClass *) (parent_class))->update)
224         ((SPObjectClass *) (parent_class))->update(object, ctx, flags);
229 static Inkscape::XML::Node *sp_3dbox_write(SPObject *object, Inkscape::XML::Node *repr, guint flags)
231     SP3DBox *box = SP_3DBOX(object);
232     // FIXME: How to handle other contexts???
233     // FIXME: Is tools_isactive(..) more recommended to check for the current context/tool?
234     if (!SP_IS_3DBOX_CONTEXT(inkscape_active_event_context()))
235         return repr;
237     if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) {
238         Inkscape::XML::Document *xml_doc = sp_document_repr_doc(SP_OBJECT_DOCUMENT(object));
239         repr = xml_doc->createElement("svg:g");
240         repr->setAttribute("sodipodi:type", "inkscape:3dbox");
241         /* Hook paths to the faces of the box */
242         for (int i = 0; i < 6; ++i) {
243             box->faces[i]->hook_path_to_3dbox();
244         }
245     }
247     for (int i = 0; i < 6; ++i) {
248         box->faces[i]->set_path_repr();
249     }
251     if (flags & SP_OBJECT_WRITE_EXT) {
252         gchar *str;
253         str = sp_3dbox_get_corner_coords_string (box, 2);
254         repr->setAttribute("inkscape:box3dcornerA", str);
256         str = sp_3dbox_get_corner_coords_string (box, 1);
257         repr->setAttribute("inkscape:box3dcornerB", str);
259         str = sp_3dbox_get_corner_coords_string (box, 5);
260         repr->setAttribute("inkscape:box3dcornerC", str);
262         str = sp_3dbox_get_perspective_string (box);
263         repr->setAttribute("inkscape:perspective", str);
264         sp_3dbox_set_ratios (box);
266         g_free ((void *) str);
267     }
269     if (((SPObjectClass *) (parent_class))->write) {
270         ((SPObjectClass *) (parent_class))->write(object, repr, flags);
271     }
273     return repr;
276 static gchar *
277 sp_3dbox_description(SPItem *item)
279     g_return_val_if_fail(SP_IS_3DBOX(item), NULL);
281     return g_strdup(_("<b>3D Box</b>"));
284 void sp_3dbox_set_ratios (SP3DBox *box, Box3D::Axis axes)
286     Box3D::Perspective3D *persp = Box3D::get_persp_of_box (box);
287     NR::Point pt;
289     if (axes & Box3D::X) {
290         pt = persp->get_vanishing_point (Box3D::X)->get_pos();
291         box->ratio_x = NR::L2 (pt - box->corners[2]) / NR::L2 (pt - box->corners[3]);
292     }
294     if (axes & Box3D::Y) {
295         pt = persp->get_vanishing_point (Box3D::Y)->get_pos();
296         box->ratio_y = NR::L2 (pt - box->corners[2]) / NR::L2 (pt - box->corners[0]);
297     }
299     if (axes & Box3D::Z) {
300         pt = persp->get_vanishing_point (Box3D::Z)->get_pos();
301         box->ratio_z = NR::L2 (pt - box->corners[4]) / NR::L2 (pt - box->corners[0]);
302     }
305 void
306 sp_3dbox_switch_front_face (SP3DBox *box, Box3D::Axis axis)
308     if (Box3D::get_persp_of_box (box)->get_vanishing_point (axis)->is_finite()) {
309         box->front_bits = box->front_bits ^ axis;
310     }
314 void
315 sp_3dbox_position_set (SP3DBoxContext &bc)
317     SP3DBox *box3d = SP_3DBOX(bc.item);
319     sp_3dbox_set_shape(box3d);
321     // FIXME: Why does the following call not automatically update the children
322     //        of box3d (which is an SPGroup, which should do this)?
323     //SP_OBJECT(box3d)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
325     /**
326     SP_OBJECT(box3d->path_face1)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
327     SP_OBJECT(box3d->path_face2)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
328     SP_OBJECT(box3d->path_face3)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
329     SP_OBJECT(box3d->path_face4)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
330     SP_OBJECT(box3d->path_face5)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
331     SP_OBJECT(box3d->path_face6)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
332     ***/
335 //static
336 void
337 // FIXME: Note that this is _not_ the virtual set_shape() method inherited from SPShape,
338 //        since SP3DBox is inherited from SPGroup. The following method is "artificially"
339 //        called from sp_3dbox_update().
340 //sp_3dbox_set_shape(SPShape *shape)
341 sp_3dbox_set_shape(SP3DBox *box3d, bool use_previous_corners)
343     // FIXME: How to handle other contexts???
344     // FIXME: Is tools_isactive(..) more recommended to check for the current context/tool?
345     if (!SP_IS_3DBOX_CONTEXT(inkscape_active_event_context()))
346         return;
347     SP3DBoxContext *bc = SP_3DBOX_CONTEXT(inkscape_active_event_context());
349     /* Only update the curves during dragging; setting the svg representations 
350        is expensive and only done once at the end */
351     if (!use_previous_corners) {
352         sp_3dbox_recompute_corners (box3d, bc->drag_origin, bc->drag_ptB, bc->drag_ptC);
353     } else {
354         sp_3dbox_recompute_corners (box3d, box3d->corners[2], box3d->corners[1], box3d->corners[5]);
355     }
356     if (bc->extruded) {
357         box3d->faces[0]->set_corners (box3d->corners[0], box3d->corners[4], box3d->corners[6], box3d->corners[2]);
358         box3d->faces[1]->set_corners (box3d->corners[1], box3d->corners[5], box3d->corners[7], box3d->corners[3]);
359         box3d->faces[2]->set_corners (box3d->corners[0], box3d->corners[1], box3d->corners[5], box3d->corners[4]);
360         box3d->faces[3]->set_corners (box3d->corners[2], box3d->corners[3], box3d->corners[7], box3d->corners[6]);
361         box3d->faces[5]->set_corners (box3d->corners[4], box3d->corners[5], box3d->corners[7], box3d->corners[6]);
362     }
363     box3d->faces[4]->set_corners (box3d->corners[0], box3d->corners[1], box3d->corners[3], box3d->corners[2]);
365     sp_3dbox_update_curves (box3d);
369 void sp_3dbox_recompute_corners (SP3DBox *box, NR::Point const A, NR::Point const B, NR::Point const C)
371     sp_3dbox_move_corner_in_XY_plane (box, 2, A);
372     sp_3dbox_move_corner_in_XY_plane (box, 1, B);
373     sp_3dbox_move_corner_in_Z_direction (box, 5, C);
376 inline static double
377 normalized_angle (double angle) {
378     if (angle < -M_PI) {
379         return angle + 2*M_PI;
380     } else if (angle > M_PI) {
381         return angle - 2*M_PI;
382     }
383     return angle;
386 static gdouble
387 sp_3dbox_corner_angle_to_VP (SP3DBox *box, Box3D::Axis axis, guint extreme_corner)
389     Box3D::VanishingPoint *vp = Box3D::get_persp_of_box (box)->get_vanishing_point (axis);
390     NR::Point dir;
392     if (vp->is_finite()) {
393         dir = NR::unit_vector (vp->get_pos() - box->corners[extreme_corner]);
394     } else {
395         dir = NR::unit_vector (vp->v_dir);
396     }
398     return atan2 (dir[NR::Y], dir[NR::X]);
402 bool sp_3dbox_recompute_z_orders (SP3DBox *box)
404     guint new_z_orders[6];
406     Box3D::Perspective3D *persp = Box3D::get_persp_of_box (box);
408     // TODO: Determine the front corner depending on the distance from VPs and/or the user presets
409     guint front_corner = 1;
411     gdouble dir_1x = sp_3dbox_corner_angle_to_VP (box, Box3D::X, front_corner);
412     gdouble dir_3x = sp_3dbox_corner_angle_to_VP (box, Box3D::X, front_corner ^ Box3D::Y);
414     gdouble dir_1y = sp_3dbox_corner_angle_to_VP (box, Box3D::Y, front_corner);
415     gdouble dir_0y = sp_3dbox_corner_angle_to_VP (box, Box3D::Y, front_corner ^ Box3D::X);
417     gdouble dir_1z = sp_3dbox_corner_angle_to_VP (box, Box3D::Z, front_corner);
418     gdouble dir_3z = sp_3dbox_corner_angle_to_VP (box, Box3D::Z, front_corner ^ Box3D::Y);
420     // Still not perfect, but only fails in some rather degenerate cases.
421     // I suspect that there is a more elegant model, though. :)
422     new_z_orders[0] = Box3D::face_to_int (Box3D::XY ^ Box3D::FRONT);
423     if (normalized_angle (dir_1y - dir_1z) > 0) {
424         new_z_orders[1] = Box3D::face_to_int (Box3D::YZ ^ Box3D::REAR);
425         if (normalized_angle (dir_1x - dir_1z) > 0) {
426             new_z_orders[2] = Box3D::face_to_int (Box3D::XZ ^ Box3D::REAR);
427         } else {
428             new_z_orders[2] = Box3D::face_to_int (Box3D::XZ ^ Box3D::FRONT);
429         }
430     } else {
431         if (normalized_angle (dir_3x - dir_3z) > 0) {
432             new_z_orders[1] = Box3D::face_to_int (Box3D::XZ ^ Box3D::REAR);
433             new_z_orders[2] = Box3D::face_to_int (Box3D::YZ ^ Box3D::FRONT);
434         } else {
435             if (normalized_angle (dir_1x - dir_1z) > 0) {
436                 new_z_orders[1] = Box3D::face_to_int (Box3D::YZ ^ Box3D::FRONT);
437                 new_z_orders[2] = Box3D::face_to_int (Box3D::XZ ^ Box3D::FRONT);
438             } else {
439                 new_z_orders[1] = Box3D::face_to_int (Box3D::XZ ^ Box3D::FRONT);
440                 new_z_orders[2] = Box3D::face_to_int (Box3D::YZ ^ Box3D::FRONT);
441             }
442         }
443     }
445     new_z_orders[3] = Box3D::opposite_face (new_z_orders[2]);
446     new_z_orders[4] = Box3D::opposite_face (new_z_orders[1]);
447     new_z_orders[5] = Box3D::opposite_face (new_z_orders[0]);
449     /* We only need to look for changes among the topmost three faces because the order
450        of the other ones is just inverted. */
451     // Currently we can even skip the first test since the front face is always in the XY plane.
452     if (// (box->z_orders[0] != new_z_orders[0]) ||
453         (box->z_orders[1] != new_z_orders[1]) ||
454         (box->z_orders[2] != new_z_orders[2]))
455     {
456         for (int i = 0; i < 6; ++i) {
457             box->z_orders[i] = new_z_orders[i];
458         }
459         return true;
460     }
462     return false;
465 void sp_3dbox_set_z_orders (SP3DBox *box)
467     GSList *items = sp_item_group_item_list(SP_GROUP(box));
469     // For efficiency reasons, we only set the new z-orders if something really changed
470     if (sp_3dbox_recompute_z_orders (box)) {
471         box->faces[box->z_orders[0]]->lower_to_bottom ();
472         box->faces[box->z_orders[1]]->lower_to_bottom ();
473         box->faces[box->z_orders[2]]->lower_to_bottom ();
474         box->faces[box->z_orders[3]]->lower_to_bottom ();
475         box->faces[box->z_orders[4]]->lower_to_bottom ();
476         box->faces[box->z_orders[5]]->lower_to_bottom ();
477     }
480 void
481 sp_3dbox_update_curves (SP3DBox *box) {
482     for (int i = 0; i < 6; ++i) {
483         if (box->faces[i]) box->faces[i]->set_curve();
484     }
487 /**
488  * In some situations (e.g., after cloning boxes, undo & redo, or reading boxes from a file) there are
489  * paths already present in the document which correspond to the faces of newly created boxes, but their
490  * 'path' members don't link to them yet. The following function corrects this if necessary.
491  */
492 void
493 sp_3dbox_link_to_existing_paths (SP3DBox *box, Inkscape::XML::Node *repr) {
494     // TODO: We should probably destroy the existing paths and recreate them because we don't know
495     //       precisely which path corresponds to which face. Does this make a difference?
496     //       In sp_3dbox_write we write the correct paths anyway, don't we? But we could get into
497     //       trouble at a later stage when we only write single faces for degenerate boxes.
499     SPDocument *document = SP_OBJECT_DOCUMENT(box);
500     guint face_id = 0;
502     for (Inkscape::XML::Node *i = sp_repr_children(repr); i != NULL; i = sp_repr_next(i)) {
503         if (face_id > 5) {
504             g_warning ("SVG representation of 3D boxes must contain 6 paths or less.\n");
505             break;
506         }
508         SPObject *face_object = document->getObjectByRepr((Inkscape::XML::Node *) i);
509         if (!SP_IS_PATH(face_object)) {
510             g_warning ("SVG representation of 3D boxes should only contain paths.\n");
511             continue;
512         }
513         box->faces[face_id]->hook_path_to_3dbox(SP_PATH(face_object));
514         ++face_id;
515     }
516     if (face_id < 6) {
517         //g_warning ("SVG representation of 3D boxes should contain exactly 6 paths (degenerate boxes are not yet supported).\n");
518         // TODO: Check whether it is safe to add the remaining paths to the box and do so in case it is.
519         //       (But we also land here for newly created boxes where we shouldn't add any paths because
520         //       This is done in sp_3dbox_write later on.
521     }
524 void
525 sp_3dbox_move_corner_in_XY_plane (SP3DBox *box, guint id, NR::Point pt, Box3D::Axis axes)
527     Box3D::Perspective3D * persp = Box3D::get_persp_of_box (box);
529     NR::Point A (box->corners[id ^ Box3D::XY]);
530     if (Box3D::is_single_axis_direction (axes)) {
531         pt = Box3D::PerspectiveLine (box->corners[id], axes, persp).closest_to(pt);
532     }
534     /* set the 'front' corners */
535     box->corners[id] = pt;
537     Box3D::PerspectiveLine pl_one (A, Box3D::Y, persp);
538     Box3D::PerspectiveLine pl_two (pt, Box3D::X, persp);
539     box->corners[id ^ Box3D::X] = pl_one.meet(pl_two);
541     pl_one = Box3D::PerspectiveLine (A, Box3D::X, persp);
542     pl_two = Box3D::PerspectiveLine (pt, Box3D::Y, persp);
543     box->corners[id ^ Box3D::Y] = pl_one.meet(pl_two);
545     /* set the 'rear' corners */
546     NR::Point B (box->corners[id ^ Box3D::XYZ]);
548     pl_one = Box3D::PerspectiveLine (box->corners[id ^ Box3D::X], Box3D::Z, persp);
549     pl_two = Box3D::PerspectiveLine (B, Box3D::Y, persp);
550     box->corners[id ^ Box3D::XZ] = pl_one.meet(pl_two);
552     pl_one = Box3D::PerspectiveLine (box->corners[id ^ Box3D::XZ], Box3D::X, persp);
553     pl_two = Box3D::PerspectiveLine (pt, Box3D::Z, persp);
554     box->corners[id ^ Box3D::Z] = pl_one.meet(pl_two);
556     pl_one = Box3D::PerspectiveLine (box->corners[id ^ Box3D::Z], Box3D::Y, persp);
557     pl_two = Box3D::PerspectiveLine (B, Box3D::X, persp);
558     box->corners[id ^ Box3D::YZ] = pl_one.meet(pl_two);
559     
562 void
563 sp_3dbox_move_corner_in_Z_direction (SP3DBox *box, guint id, NR::Point pt, bool constrained)
565     if (!constrained) sp_3dbox_move_corner_in_XY_plane (box, id, pt, Box3D::XY);
567     Box3D::Perspective3D * persp = Box3D::get_persp_of_box (box);
569     /* set the four corners of the face containing corners[id] */
570     box->corners[id] = Box3D::PerspectiveLine (box->corners[id], Box3D::Z, persp).closest_to(pt);
572     Box3D::PerspectiveLine pl_one (box->corners[id], Box3D::X, persp);
573     Box3D::PerspectiveLine pl_two (box->corners[id ^ Box3D::XZ], Box3D::Z, persp);
574     box->corners[id ^ Box3D::X] = pl_one.meet(pl_two);
576     pl_one = Box3D::PerspectiveLine (box->corners[id ^ Box3D::X], Box3D::Y, persp);
577     pl_two = Box3D::PerspectiveLine (box->corners[id ^ Box3D::XYZ], Box3D::Z, persp);
578     box->corners[id ^ Box3D::XY] = pl_one.meet(pl_two);
580     pl_one = Box3D::PerspectiveLine (box->corners[id], Box3D::Y, persp);
581     pl_two = Box3D::PerspectiveLine (box->corners[id ^ Box3D::YZ], Box3D::Z, persp);
582     box->corners[id ^ Box3D::Y] = pl_one.meet(pl_two);
585 NR::Maybe<NR::Point>
586 sp_3dbox_get_center (SP3DBox *box)
588     return sp_3dbox_get_midpoint_between_corners (box, 0, 7);
591 NR::Maybe<NR::Point>
592 sp_3dbox_get_midpoint_between_corners (SP3DBox *box, guint id_corner1, guint id_corner2)
594     Box3D::Axis corner_axes = (Box3D::Axis) (id_corner1 ^ id_corner2);
596     // Is all this sufficiently precise also for degenerate cases?
597     if (sp_3dbox_corners_are_adjacent (id_corner1, id_corner2)) {
598         Box3D::Axis orth_dir = get_perpendicular_axis_direction (corner_axes);
600         Box3D::Line diag1 (box->corners[id_corner1], box->corners[id_corner2 ^ orth_dir]);
601         Box3D::Line diag2 (box->corners[id_corner1 ^ orth_dir], box->corners[id_corner2]);
602         NR::Maybe<NR::Point> adjacent_face_center = diag1.intersect(diag2);
604         if (!adjacent_face_center) return NR::Nothing();
606         Box3D::Perspective3D * persp = Box3D::get_persp_of_box (box);
608         Box3D::PerspectiveLine pl (*adjacent_face_center, orth_dir, persp);
609         return pl.intersect(Box3D::PerspectiveLine(box->corners[id_corner1], corner_axes, persp));
610     } else {
611         Box3D::Axis dir = Box3D::extract_first_axis_direction (corner_axes);
612         Box3D::Line diag1 (box->corners[id_corner1], box->corners[id_corner2]);
613         Box3D::Line diag2 (box->corners[id_corner1 ^ dir], box->corners[id_corner2 ^ dir]);
614         return diag1.intersect(diag2);
615     }
618 static gchar *
619 sp_3dbox_get_corner_coords_string (SP3DBox *box, guint id)
621     id = id % 8;
622     Inkscape::SVGOStringStream os;
623     os << box->corners[id][NR::X] << "," << box->corners[id][NR::Y];
624     return g_strdup(os.str().c_str());
627 static std::pair<gdouble, gdouble>
628 sp_3dbox_get_coord_pair_from_string (const gchar *coords)
630     gchar **coordpair = g_strsplit( coords, ",", 0);
631     // We might as well rely on g_ascii_strtod to convert the NULL pointer to 0.0,
632     // but we include the following test anyway
633     if (coordpair[0] == NULL || coordpair[1] == NULL) {
634         g_strfreev (coordpair);
635         g_warning ("Coordinate conversion failed.\n");
636         return std::make_pair(0.0, 0.0);
637     }
639     gdouble coord1 = g_ascii_strtod(coordpair[0], NULL);
640     gdouble coord2 = g_ascii_strtod(coordpair[1], NULL);
641     g_strfreev (coordpair);
643     return std::make_pair(coord1, coord2);
646 static gchar *
647 sp_3dbox_get_perspective_string (SP3DBox *box)
649     
650     return sp_3dbox_get_svg_descr_of_persp (Box3D::get_persp_of_box (box));
652   
653 gchar *
654 sp_3dbox_get_svg_descr_of_persp (Box3D::Perspective3D *persp)
656     // FIXME: We should move this code to perspective3d.cpp, but this yields compiler errors. Why?
657     Inkscape::SVGOStringStream os;
659     Box3D::VanishingPoint vp = *(persp->get_vanishing_point (Box3D::X));
660     os << vp[NR::X] << "," << vp[NR::Y] << ",";
661     os << vp.v_dir[NR::X] << "," << vp.v_dir[NR::Y] << ",";
662     if (vp.is_finite()) {
663         os << "finite,";
664     } else {
665         os << "infinite,";
666     }
668     vp = *(persp->get_vanishing_point (Box3D::Y));
669     os << vp[NR::X] << "," << vp[NR::Y] << ",";
670     os << vp.v_dir[NR::X] << "," << vp.v_dir[NR::Y] << ",";
671     if (vp.is_finite()) {
672         os << "finite,";
673     } else {
674         os << "infinite,";
675     }
677     vp = *(persp->get_vanishing_point (Box3D::Z));
678     os << vp[NR::X] << "," << vp[NR::Y] << ",";
679     os << vp.v_dir[NR::X] << "," << vp.v_dir[NR::Y] << ",";
680     if (vp.is_finite()) {
681         os << "finite";
682     } else {
683         os << "infinite";
684     }
686     return g_strdup(os.str().c_str());
689 void sp_3dbox_update_perspective_lines()
691     SPEventContext *ec = inkscape_active_event_context();
692     if (!SP_IS_3DBOX_CONTEXT (ec))
693         return;
695     SP_3DBOX_CONTEXT (ec)->_vpdrag->updateLines();
698 /*
699  * Manipulates corner1 through corner4 to contain the indices of the corners
700  * from which the perspective lines in the direction of 'axis' emerge
701  */
702 void sp_3dbox_corners_for_perspective_lines (const SP3DBox * box, Box3D::Axis axis, 
703                                              NR::Point &corner1, NR::Point &corner2, NR::Point &corner3, NR::Point &corner4)
705     // along which axis to switch when takint
706     Box3D::Axis switch_axis;
707     if (axis == Box3D::X || axis == Box3D::Y) {
708         switch_axis = (box->front_bits & axis) ? Box3D::Z : Box3D::NONE;
709     } else {
710         switch_axis = (box->front_bits & axis) ? Box3D::X : Box3D::NONE;
711     }
713     switch (axis) {
714         case Box3D::X:
715             corner1 = sp_3dbox_get_corner_along_edge (box, 0 ^ switch_axis, axis, Box3D::REAR);
716             corner2 = sp_3dbox_get_corner_along_edge (box, 2 ^ switch_axis, axis, Box3D::REAR);
717             corner3 = sp_3dbox_get_corner_along_edge (box, 4 ^ switch_axis, axis, Box3D::REAR);
718             corner4 = sp_3dbox_get_corner_along_edge (box, 6 ^ switch_axis, axis, Box3D::REAR);
719             break;
720         case Box3D::Y:
721             corner1 = sp_3dbox_get_corner_along_edge (box, 0 ^ switch_axis, axis, Box3D::REAR);
722             corner2 = sp_3dbox_get_corner_along_edge (box, 1 ^ switch_axis, axis, Box3D::REAR);
723             corner3 = sp_3dbox_get_corner_along_edge (box, 4 ^ switch_axis, axis, Box3D::REAR);
724             corner4 = sp_3dbox_get_corner_along_edge (box, 5 ^ switch_axis, axis, Box3D::REAR);
725             break;
726         case Box3D::Z:
727             corner1 = sp_3dbox_get_corner_along_edge (box, 1 ^ switch_axis, axis, Box3D::REAR);
728             corner2 = sp_3dbox_get_corner_along_edge (box, 3 ^ switch_axis, axis, Box3D::REAR);
729             corner3 = sp_3dbox_get_corner_along_edge (box, 0 ^ switch_axis, axis, Box3D::REAR);
730             corner4 = sp_3dbox_get_corner_along_edge (box, 2 ^ switch_axis, axis, Box3D::REAR);
731             break;
732     }            
735 /**
736  * Returns the id of the corner on the edge along 'axis' and passing through 'corner' that
737  * lies on the front/rear face in this direction.
738  */
739 guint
740 sp_3dbox_get_corner_id_along_edge (const SP3DBox *box, guint corner, Box3D::Axis axis, Box3D::FrontOrRear rel_pos)
742     guint result;
743     guint other_corner = corner ^ axis;
744     Box3D::VanishingPoint *vp = Box3D::get_persp_of_box (box)->get_vanishing_point(axis);
745     if (vp->is_finite()) {
746         result = (  NR::L2 (vp->get_pos() - box->corners[corner])
747                   < NR::L2 (vp->get_pos() - box->corners[other_corner]) ? other_corner : corner);
748     } else {
749         // clear the axis bit and switch to the appropriate corner along axis, depending on the value of front_bits
750         result = ((corner & (0xF ^ axis)) ^ (box->front_bits & axis));
751     }
753     if (rel_pos == Box3D::FRONT) {
754         return result;
755     } else {
756         return result ^ axis;
757     }
760 NR::Point
761 sp_3dbox_get_corner_along_edge (const SP3DBox *box, guint corner, Box3D::Axis axis, Box3D::FrontOrRear rel_pos)
763     return box->corners[sp_3dbox_get_corner_id_along_edge (box, corner, axis, rel_pos)];
766 // auxiliary functions
767 static void
768 sp_3dbox_update_corner_with_value_from_svg (SPObject *object, guint corner_id, const gchar *value)
770     if (value == NULL) return;
771     SP3DBox *box = SP_3DBOX(object);
773     std::pair<gdouble, gdouble> coord_pair = sp_3dbox_get_coord_pair_from_string (value);
774     box->corners[corner_id] = NR::Point (coord_pair.first, coord_pair.second);
775     sp_3dbox_recompute_corners (box, box->corners[2], box->corners[1], box->corners[5]);
776     object->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
779 static void
780 sp_3dbox_update_perspective (Box3D::Perspective3D *persp, const gchar *value)
782     // WARNING! This function changes the perspective associated to 'box'. Since there may be
783     // many other boxes linked to the same perspective, their perspective is also changed.
784     // If this behaviour is not desired in all cases, we need a different function.
785     if (value == NULL) return;
787     gchar **vps = g_strsplit( value, ",", 0);
788     for (int i = 0; i < 15; ++i) {
789         if (vps[i] == NULL) {
790             g_warning ("Malformed svg attribute 'perspective'\n");
791             return;
792         }
793     }
795     persp->set_vanishing_point (Box3D::X, g_ascii_strtod (vps[0], NULL), g_ascii_strtod (vps[1], NULL),
796                                           g_ascii_strtod (vps[2], NULL), g_ascii_strtod (vps[3], NULL),
797                                           strcmp (vps[4], "finite") == 0 ? Box3D::VP_FINITE : Box3D::VP_INFINITE);
798     persp->set_vanishing_point (Box3D::Y, g_ascii_strtod (vps[5], NULL), g_ascii_strtod (vps[6], NULL),
799                                           g_ascii_strtod (vps[7], NULL), g_ascii_strtod (vps[8], NULL),
800                                           strcmp (vps[9], "finite") == 0 ? Box3D::VP_FINITE : Box3D::VP_INFINITE);
801     persp->set_vanishing_point (Box3D::Z, g_ascii_strtod (vps[10], NULL), g_ascii_strtod (vps[11], NULL),
802                                           g_ascii_strtod (vps[12], NULL), g_ascii_strtod (vps[13], NULL),
803                                           strcmp (vps[14], "finite") == 0 ? Box3D::VP_FINITE : Box3D::VP_INFINITE);
805     // update the other boxes linked to the same perspective
806     persp->reshape_boxes (Box3D::XYZ);
809 /*
810   Local Variables:
811   mode:c++
812   c-file-style:"stroustrup"
813   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
814   indent-tabs-mode:nil
815   fill-column:99
816   End:
817 */
818 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :