COIN-OR::LEMON - Graph Library

source: lemon-0.x/lemon/graph_to_eps.h @ 2379:248152674a9e

Last change on this file since 2379:248152674a9e was 2379:248152674a9e, checked in by Alpar Juttner, 13 years ago

Prescaling can be turned off

File size: 35.8 KB
Line 
1/* -*- C++ -*-
2 *
3 * This file is a part of LEMON, a generic C++ optimization library
4 *
5 * Copyright (C) 2003-2006
6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 *
9 * Permission to use, modify and distribute this software is granted
10 * provided that this copyright notice appears in all copies. For
11 * precise terms see the accompanying LICENSE file.
12 *
13 * This software is provided "AS IS" with no warranty of any kind,
14 * express or implied, and with no claim as to its suitability for any
15 * purpose.
16 *
17 */
18
19#ifndef LEMON_GRAPH_TO_EPS_H
20#define LEMON_GRAPH_TO_EPS_H
21
22#include <sys/time.h>
23
24#ifdef WIN32
25#include <lemon/bits/mingw32_time.h>
26#endif
27
28#include<iostream>
29#include<fstream>
30#include<sstream>
31#include<algorithm>
32#include<vector>
33
34#include <ctime>
35#include <cmath>
36
37#include<lemon/bits/invalid.h>
38#include<lemon/dim2.h>
39#include<lemon/maps.h>
40#include<lemon/color.h>
41#include<lemon/bits/bezier.h>
42
43
44///\ingroup eps_io
45///\file
46///\brief Simple graph drawer
47///
48///\author Alpar Juttner
49
50namespace lemon {
51
52template<class MT>
53class _NegY {
54public:
55  typedef typename MT::Key Key;
56  typedef typename MT::Value Value;
57  const MT &map;
58  int yscale;
59  _NegY(const MT &m,bool b) : map(m), yscale(1-b*2) {}
60  Value operator[](Key n) { return Value(map[n].x,map[n].y*yscale);}
61};
62
63///Default traits class of \ref GraphToEps
64
65///Default traits class of \ref GraphToEps
66///
67///\c G is the type of the underlying graph.
68template<class G>
69struct DefaultGraphToEpsTraits
70{
71  typedef G Graph;
72  typedef typename Graph::Node Node;
73  typedef typename Graph::NodeIt NodeIt;
74  typedef typename Graph::Edge Edge;
75  typedef typename Graph::EdgeIt EdgeIt;
76  typedef typename Graph::InEdgeIt InEdgeIt;
77  typedef typename Graph::OutEdgeIt OutEdgeIt;
78 
79
80  const Graph &g;
81
82  std::ostream& os;
83 
84  typedef ConstMap<typename Graph::Node,dim2::Point<double> > CoordsMapType;
85  CoordsMapType _coords;
86  ConstMap<typename Graph::Node,double > _nodeSizes;
87  ConstMap<typename Graph::Node,int > _nodeShapes;
88
89  ConstMap<typename Graph::Node,Color > _nodeColors;
90  ConstMap<typename Graph::Edge,Color > _edgeColors;
91
92  ConstMap<typename Graph::Edge,double > _edgeWidths;
93
94  double _edgeWidthScale;
95 
96  double _nodeScale;
97  double _xBorder, _yBorder;
98  double _scale;
99  double _nodeBorderQuotient;
100 
101  bool _drawArrows;
102  double _arrowLength, _arrowWidth;
103 
104  bool _showNodes, _showEdges;
105
106  bool _enableParallel;
107  double _parEdgeDist;
108
109  bool _showNodeText;
110  ConstMap<typename Graph::Node,bool > _nodeTexts; 
111  double _nodeTextSize;
112
113  bool _showNodePsText;
114  ConstMap<typename Graph::Node,bool > _nodePsTexts; 
115  char *_nodePsTextsPreamble;
116 
117  bool _undirected;
118
119  bool _pleaseRemoveOsStream;
120
121  bool _scaleToA4;
122
123  std::string _title;
124  std::string _copyright;
125
126  enum NodeTextColorType
127    { DIST_COL=0, DIST_BW=1, CUST_COL=2, SAME_COL=3 } _nodeTextColorType;
128  ConstMap<typename Graph::Node,Color > _nodeTextColors;
129
130  bool _autoNodeScale;
131  bool _autoEdgeWidthScale;
132
133  bool _absoluteNodeSizes;
134  bool _absoluteEdgeWidths;
135
136  bool _negY;
137
138  bool _preScale;
139  ///Constructor
140
141  ///Constructor
142  ///\param _g is a reference to the graph to be printed
143  ///\param _os is a reference to the output stream.
144  ///\param _os is a reference to the output stream.
145  ///\param _pros If it is \c true, then the \c ostream referenced by \c _os
146  ///will be explicitly deallocated by the destructor.
147  ///By default it is <tt>std::cout</tt>
148  DefaultGraphToEpsTraits(const G &_g,std::ostream& _os=std::cout,
149                          bool _pros=false) :
150    g(_g), os(_os),
151    _coords(dim2::Point<double>(1,1)), _nodeSizes(.01), _nodeShapes(0),
152    _nodeColors(WHITE), _edgeColors(BLACK),
153    _edgeWidths(1.0), _edgeWidthScale(0.003),
154    _nodeScale(1.0), _xBorder(10), _yBorder(10), _scale(1.0),
155    _nodeBorderQuotient(.1),
156    _drawArrows(false), _arrowLength(1), _arrowWidth(0.3),
157    _showNodes(true), _showEdges(true),
158    _enableParallel(false), _parEdgeDist(1),
159    _showNodeText(false), _nodeTexts(false), _nodeTextSize(1),
160    _showNodePsText(false), _nodePsTexts(false), _nodePsTextsPreamble(0),
161    _undirected(false),
162    _pleaseRemoveOsStream(_pros), _scaleToA4(false),
163    _nodeTextColorType(SAME_COL), _nodeTextColors(BLACK),
164    _autoNodeScale(false),
165    _autoEdgeWidthScale(false),
166    _absoluteNodeSizes(false),
167    _absoluteEdgeWidths(false),
168    _negY(false),
169    _preScale(true)
170  {}
171};
172
173///Helper class to implement the named parameters of \ref graphToEps()
174
175///Helper class to implement the named parameters of \ref graphToEps()
176///\todo Is 'helper class' a good name for this?
177///
178///\todo Follow PostScript's DSC.
179/// Use own dictionary.
180///\todo Useful new features.
181/// - Linestyles: dotted, dashed etc.
182/// - A second color and percent value for the lines.
183template<class T> class GraphToEps : public T
184{
185  // Can't believe it is required by the C++ standard
186  using T::g;
187  using T::os;
188
189  using T::_coords;
190  using T::_nodeSizes;
191  using T::_nodeShapes;
192  using T::_nodeColors;
193  using T::_edgeColors;
194  using T::_edgeWidths;
195
196  using T::_edgeWidthScale;
197  using T::_nodeScale;
198  using T::_xBorder;
199  using T::_yBorder;
200  using T::_scale;
201  using T::_nodeBorderQuotient;
202 
203  using T::_drawArrows;
204  using T::_arrowLength;
205  using T::_arrowWidth;
206 
207  using T::_showNodes;
208  using T::_showEdges;
209
210  using T::_enableParallel;
211  using T::_parEdgeDist;
212
213  using T::_showNodeText;
214  using T::_nodeTexts; 
215  using T::_nodeTextSize;
216
217  using T::_showNodePsText;
218  using T::_nodePsTexts; 
219  using T::_nodePsTextsPreamble;
220 
221  using T::_undirected;
222
223  using T::_pleaseRemoveOsStream;
224
225  using T::_scaleToA4;
226
227  using T::_title;
228  using T::_copyright;
229
230  using T::NodeTextColorType;
231  using T::CUST_COL;
232  using T::DIST_COL;
233  using T::DIST_BW;
234  using T::_nodeTextColorType;
235  using T::_nodeTextColors;
236
237  using T::_autoNodeScale;
238  using T::_autoEdgeWidthScale;
239
240  using T::_absoluteNodeSizes;
241  using T::_absoluteEdgeWidths;
242
243
244  using T::_negY;
245  using T::_preScale;
246
247  // dradnats ++C eht yb deriuqer si ti eveileb t'naC
248
249  typedef typename T::Graph Graph;
250  typedef typename Graph::Node Node;
251  typedef typename Graph::NodeIt NodeIt;
252  typedef typename Graph::Edge Edge;
253  typedef typename Graph::EdgeIt EdgeIt;
254  typedef typename Graph::InEdgeIt InEdgeIt;
255  typedef typename Graph::OutEdgeIt OutEdgeIt;
256
257  static const int INTERPOL_PREC;
258  static const double A4HEIGHT;
259  static const double A4WIDTH;
260  static const double A4BORDER;
261
262  bool dontPrint;
263
264public:
265  ///Node shapes
266
267  ///Node shapes
268  ///
269  enum NodeShapes {
270    /// = 0
271    ///\image html nodeshape_0.png
272    ///\image latex nodeshape_0.eps "CIRCLE shape (0)" width=2cm
273    CIRCLE=0,
274    /// = 1
275    ///\image html nodeshape_1.png
276    ///\image latex nodeshape_1.eps "SQUARE shape (1)" width=2cm
277    ///
278    SQUARE=1,
279    /// = 2
280    ///\image html nodeshape_2.png
281    ///\image latex nodeshape_2.eps "DIAMOND shape (2)" width=2cm
282    ///
283    DIAMOND=2,
284    /// = 3
285    ///\image html nodeshape_3.png
286    ///\image latex nodeshape_2.eps "MALE shape (4)" width=2cm
287    ///
288    MALE=3,
289    /// = 4
290    ///\image html nodeshape_4.png
291    ///\image latex nodeshape_2.eps "FEMALE shape (4)" width=2cm
292    ///
293    FEMALE=4
294  };
295
296private:
297  class edgeLess {
298    const Graph &g;
299  public:
300    edgeLess(const Graph &_g) : g(_g) {}
301    bool operator()(Edge a,Edge b) const
302    {
303      Node ai=std::min(g.source(a),g.target(a));
304      Node aa=std::max(g.source(a),g.target(a));
305      Node bi=std::min(g.source(b),g.target(b));
306      Node ba=std::max(g.source(b),g.target(b));
307      return ai<bi ||
308        (ai==bi && (aa < ba ||
309                    (aa==ba && ai==g.source(a) && bi==g.target(b))));
310    }
311  };
312  bool isParallel(Edge e,Edge f) const
313  {
314    return (g.source(e)==g.source(f)&&
315            g.target(e)==g.target(f)) ||
316      (g.source(e)==g.target(f)&&
317       g.target(e)==g.source(f));
318  }
319  template<class TT>
320  static std::string psOut(const dim2::Point<TT> &p)
321    {
322      std::ostringstream os;   
323      os << p.x << ' ' << p.y;
324      return os.str();
325    }
326  static std::string psOut(const Color &c)
327    {
328      std::ostringstream os;   
329      os << c.red() << ' ' << c.green() << ' ' << c.blue();
330      return os.str();
331    }
332 
333public:
334  GraphToEps(const T &t) : T(t), dontPrint(false) {};
335 
336  template<class X> struct CoordsTraits : public T {
337  typedef X CoordsMapType;
338    const X &_coords;
339    CoordsTraits(const T &t,const X &x) : T(t), _coords(x) {}
340  };
341  ///Sets the map of the node coordinates
342
343  ///Sets the map of the node coordinates.
344  ///\param x must be a node map with dim2::Point<double> or
345  ///\ref dim2::Point "dim2::Point<int>" values.
346  template<class X> GraphToEps<CoordsTraits<X> > coords(const X &x) {
347    dontPrint=true;
348    return GraphToEps<CoordsTraits<X> >(CoordsTraits<X>(*this,x));
349  }
350  template<class X> struct NodeSizesTraits : public T {
351    const X &_nodeSizes;
352    NodeSizesTraits(const T &t,const X &x) : T(t), _nodeSizes(x) {}
353  };
354  ///Sets the map of the node sizes
355
356  ///Sets the map of the node sizes
357  ///\param x must be a node map with \c double (or convertible) values.
358  template<class X> GraphToEps<NodeSizesTraits<X> > nodeSizes(const X &x)
359  {
360    dontPrint=true;
361    return GraphToEps<NodeSizesTraits<X> >(NodeSizesTraits<X>(*this,x));
362  }
363  template<class X> struct NodeShapesTraits : public T {
364    const X &_nodeShapes;
365    NodeShapesTraits(const T &t,const X &x) : T(t), _nodeShapes(x) {}
366  };
367  ///Sets the map of the node shapes
368
369  ///Sets the map of the node shapes.
370  ///The availabe shape values
371  ///can be found in \ref NodeShapes "enum NodeShapes".
372  ///\param x must be a node map with \c int (or convertible) values.
373  ///\sa NodeShapes
374  template<class X> GraphToEps<NodeShapesTraits<X> > nodeShapes(const X &x)
375  {
376    dontPrint=true;
377    return GraphToEps<NodeShapesTraits<X> >(NodeShapesTraits<X>(*this,x));
378  }
379  template<class X> struct NodeTextsTraits : public T {
380    const X &_nodeTexts;
381    NodeTextsTraits(const T &t,const X &x) : T(t), _nodeTexts(x) {}
382  };
383  ///Sets the text printed on the nodes
384
385  ///Sets the text printed on the nodes
386  ///\param x must be a node map with type that can be pushed to a standard
387  ///ostream.
388  template<class X> GraphToEps<NodeTextsTraits<X> > nodeTexts(const X &x)
389  {
390    dontPrint=true;
391    _showNodeText=true;
392    return GraphToEps<NodeTextsTraits<X> >(NodeTextsTraits<X>(*this,x));
393  }
394  template<class X> struct NodePsTextsTraits : public T {
395    const X &_nodePsTexts;
396    NodePsTextsTraits(const T &t,const X &x) : T(t), _nodePsTexts(x) {}
397  };
398  ///Inserts a PostScript block to the nodes
399
400  ///With this command it is possible to insert a verbatim PostScript
401  ///block to the nodes.
402  ///The PS current point will be moved to the centre of the node before
403  ///the PostScript block inserted.
404  ///
405  ///Before and after the block a newline character is inserted so you
406  ///don't have to bother with the separators.
407  ///
408  ///\param x must be a node map with type that can be pushed to a standard
409  ///ostream.
410  ///
411  ///\sa nodePsTextsPreamble()
412  ///\todo Offer the choise not to move to the centre but pass the coordinates
413  ///to the Postscript block inserted.
414  template<class X> GraphToEps<NodePsTextsTraits<X> > nodePsTexts(const X &x)
415  {
416    dontPrint=true;
417    _showNodePsText=true;
418    return GraphToEps<NodePsTextsTraits<X> >(NodePsTextsTraits<X>(*this,x));
419  }
420  template<class X> struct EdgeWidthsTraits : public T {
421    const X &_edgeWidths;
422    EdgeWidthsTraits(const T &t,const X &x) : T(t), _edgeWidths(x) {}
423  };
424  ///Sets the map of the edge widths
425
426  ///Sets the map of the edge widths
427  ///\param x must be a edge map with \c double (or convertible) values.
428  template<class X> GraphToEps<EdgeWidthsTraits<X> > edgeWidths(const X &x)
429  {
430    dontPrint=true;
431    return GraphToEps<EdgeWidthsTraits<X> >(EdgeWidthsTraits<X>(*this,x));
432  }
433
434  template<class X> struct NodeColorsTraits : public T {
435    const X &_nodeColors;
436    NodeColorsTraits(const T &t,const X &x) : T(t), _nodeColors(x) {}
437  };
438  ///Sets the map of the node colors
439
440  ///Sets the map of the node colors
441  ///\param x must be a node map with \ref Color values.
442  ///
443  ///\sa Palette
444  template<class X> GraphToEps<NodeColorsTraits<X> >
445  nodeColors(const X &x)
446  {
447    dontPrint=true;
448    return GraphToEps<NodeColorsTraits<X> >(NodeColorsTraits<X>(*this,x));
449  }
450  template<class X> struct NodeTextColorsTraits : public T {
451    const X &_nodeTextColors;
452    NodeTextColorsTraits(const T &t,const X &x) : T(t), _nodeTextColors(x) {}
453  };
454  ///Sets the map of the node text colors
455
456  ///Sets the map of the node text colors
457  ///\param x must be a node map with \ref Color values.
458  ///
459  ///\sa Palette
460  template<class X> GraphToEps<NodeTextColorsTraits<X> >
461  nodeTextColors(const X &x)
462  {
463    dontPrint=true;
464    _nodeTextColorType=CUST_COL;
465    return GraphToEps<NodeTextColorsTraits<X> >
466      (NodeTextColorsTraits<X>(*this,x));
467  }
468  template<class X> struct EdgeColorsTraits : public T {
469    const X &_edgeColors;
470    EdgeColorsTraits(const T &t,const X &x) : T(t), _edgeColors(x) {}
471  };
472  ///Sets the map of the edge colors
473
474  ///Sets the map of the edge colors
475  ///\param x must be a edge map with \ref Color values.
476  ///
477  ///\sa Palette
478  template<class X> GraphToEps<EdgeColorsTraits<X> >
479  edgeColors(const X &x)
480  {
481    dontPrint=true;
482    return GraphToEps<EdgeColorsTraits<X> >(EdgeColorsTraits<X>(*this,x));
483  }
484  ///Sets a global scale factor for node sizes
485
486  ///Sets a global scale factor for node sizes.
487  ///
488  /// If nodeSizes() is not given, this function simply sets the node
489  /// sizes to \c d.  If nodeSizes() is given, but
490  /// autoNodeScale() is not, then the node size given by
491  /// nodeSizes() will be multiplied by the value \c d.
492  /// If both nodeSizes() and autoNodeScale() are used, then the
493  /// node sizes will be scaled in such a way that the greatest size will be
494  /// equal to \c d.
495  /// \sa nodeSizes()
496  /// \sa autoNodeScale()
497  GraphToEps<T> &nodeScale(double d) {_nodeScale=d;return *this;}
498  ///Turns on/off the automatic node width scaling.
499
500  ///Turns on/off the automatic node width scaling.
501  ///
502  ///\sa nodeScale()
503  ///
504  GraphToEps<T> &autoNodeScale(bool b=true) {
505    _autoNodeScale=b;return *this;
506  }
507
508  ///Turns on/off the absolutematic node width scaling.
509
510  ///Turns on/off the absolutematic node width scaling.
511  ///
512  ///\sa nodeScale()
513  ///
514  GraphToEps<T> &absoluteNodeSizes(bool b=true) {
515    _absoluteNodeSizes=b;return *this;
516  }
517
518  ///Negates the Y coordinates.
519
520  ///Negates the Y coordinates.
521  ///
522  ///\todo More docs.
523  ///
524  GraphToEps<T> &negateY(bool b=true) {
525    _negY=b;return *this;
526  }
527
528  ///Turns on/off prescaling
529
530  ///Turns on/off prescaling
531  ///
532  ///\todo More docs.
533  ///
534  GraphToEps<T> &preScale(bool b=true) {
535    _preScale=b;return *this;
536  }
537
538  ///Sets a global scale factor for edge widths
539
540  /// Sets a global scale factor for edge widths.
541  ///
542  /// If edgeWidths() is not given, this function simply sets the edge
543  /// widths to \c d.  If edgeWidths() is given, but
544  /// autoEdgeWidthScale() is not, then the edge withs given by
545  /// edgeWidths() will be multiplied by the value \c d.
546  /// If both edgeWidths() and autoEdgeWidthScale() are used, then the
547  /// edge withs will be scaled in such a way that the greatest width will be
548  /// equal to \c d.
549  GraphToEps<T> &edgeWidthScale(double d) {_edgeWidthScale=d;return *this;}
550  ///Turns on/off the automatic edge width scaling.
551
552  ///Turns on/off the automatic edge width scaling.
553  ///
554  ///\sa edgeWidthScale()
555  ///
556  GraphToEps<T> &autoEdgeWidthScale(bool b=true) {
557    _autoEdgeWidthScale=b;return *this;
558  }
559  ///Turns on/off the absolutematic edge width scaling.
560
561  ///Turns on/off the absolutematic edge width scaling.
562  ///
563  ///\sa edgeWidthScale()
564  ///
565  GraphToEps<T> &absoluteEdgeWidths(bool b=true) {
566    _absoluteEdgeWidths=b;return *this;
567  }
568  ///Sets a global scale factor for the whole picture
569
570  ///Sets a global scale factor for the whole picture
571  ///
572
573  GraphToEps<T> &scale(double d) {_scale=d;return *this;}
574  ///Sets the width of the border around the picture
575
576  ///Sets the width of the border around the picture
577  ///
578  GraphToEps<T> &border(double b) {_xBorder=_yBorder=b;return *this;}
579  ///Sets the width of the border around the picture
580
581  ///Sets the width of the border around the picture
582  ///
583  GraphToEps<T> &border(double x, double y) {
584    _xBorder=x;_yBorder=y;return *this;
585  }
586  ///Sets whether to draw arrows
587
588  ///Sets whether to draw arrows
589  ///
590  GraphToEps<T> &drawArrows(bool b=true) {_drawArrows=b;return *this;}
591  ///Sets the length of the arrowheads
592
593  ///Sets the length of the arrowheads
594  ///
595  GraphToEps<T> &arrowLength(double d) {_arrowLength*=d;return *this;}
596  ///Sets the width of the arrowheads
597
598  ///Sets the width of the arrowheads
599  ///
600  GraphToEps<T> &arrowWidth(double d) {_arrowWidth*=d;return *this;}
601 
602  ///Scales the drawing to fit to A4 page
603
604  ///Scales the drawing to fit to A4 page
605  ///
606  GraphToEps<T> &scaleToA4() {_scaleToA4=true;return *this;}
607 
608  ///Enables parallel edges
609
610  ///Enables parallel edges
611  GraphToEps<T> &enableParallel(bool b=true) {_enableParallel=b;return *this;}
612 
613  ///Sets the distance
614 
615  ///Sets the distance
616  ///
617  GraphToEps<T> &parEdgeDist(double d) {_parEdgeDist*=d;return *this;}
618 
619  ///Hides the edges
620 
621  ///Hides the edges
622  ///
623  GraphToEps<T> &hideEdges(bool b=true) {_showEdges=!b;return *this;}
624  ///Hides the nodes
625 
626  ///Hides the nodes
627  ///
628  GraphToEps<T> &hideNodes(bool b=true) {_showNodes=!b;return *this;}
629 
630  ///Sets the size of the node texts
631 
632  ///Sets the size of the node texts
633  ///
634  GraphToEps<T> &nodeTextSize(double d) {_nodeTextSize=d;return *this;}
635
636  ///Sets the color of the node texts to be different from the node color
637
638  ///Sets the color of the node texts to be as different from the node color
639  ///as it is possible
640  ///
641  GraphToEps<T> &distantColorNodeTexts()
642  {_nodeTextColorType=DIST_COL;return *this;}
643  ///Sets the color of the node texts to be black or white and always visible.
644
645  ///Sets the color of the node texts to be black or white according to
646  ///which is more
647  ///different from the node color
648  ///
649  GraphToEps<T> &distantBWNodeTexts()
650  {_nodeTextColorType=DIST_BW;return *this;}
651
652  ///Gives a preamble block for node Postscript block.
653 
654  ///Gives a preamble block for node Postscript block.
655  ///
656  ///\sa nodePsTexts()
657  GraphToEps<T> & nodePsTextsPreamble(const char *str) {
658    _nodePsTextsPreamble=str ;return *this;
659  }
660  ///Sets whether the the graph is undirected
661
662  ///Sets whether the the graph is undirected
663  ///
664  GraphToEps<T> &undirected(bool b=true) {_undirected=b;return *this;}
665
666  ///Sets whether the the graph is directed
667
668  ///Sets whether the the graph is directed.
669  ///Use it to show the undirected edges as a pair of directed ones.
670  GraphToEps<T> &bidir(bool b=true) {_undirected=!b;return *this;}
671
672  ///Sets the title.
673
674  ///Sets the title of the generated image,
675  ///namely it inserts a <tt>%%Title:</tt> DSC field to the header of
676  ///the EPS file.
677  GraphToEps<T> &title(const std::string &t) {_title=t;return *this;}
678  ///Sets the copyright statement.
679
680  ///Sets the copyright statement of the generated image,
681  ///namely it inserts a <tt>%%Copyright:</tt> DSC field to the header of
682  ///the EPS file.
683  ///\todo Multiline copyright notice could be supported.
684  GraphToEps<T> &copyright(const std::string &t) {_copyright=t;return *this;}
685
686protected:
687  bool isInsideNode(dim2::Point<double> p, double r,int t)
688  {
689    switch(t) {
690    case CIRCLE:
691    case MALE:
692    case FEMALE:
693      return p.normSquare()<=r*r;
694    case SQUARE:
695      return p.x<=r&&p.x>=-r&&p.y<=r&&p.y>=-r;
696    case DIAMOND:
697      return p.x+p.y<=r && p.x-p.y<=r && -p.x+p.y<=r && -p.x-p.y<=r;
698    }
699    return false;
700  }
701
702public:
703  ~GraphToEps() { }
704 
705  ///Draws the graph.
706
707  ///Like other functions using
708  ///\ref named-templ-func-param "named template parameters",
709  ///this function calles the algorithm itself, i.e. in this case
710  ///it draws the graph.
711  void run() {
712    ///\todo better 'epsilon' would be nice here.
713    const double EPSILON=1e-9;
714    if(dontPrint) return;
715   
716    _NegY<typename T::CoordsMapType> mycoords(_coords,_negY);
717
718    os << "%!PS-Adobe-2.0 EPSF-2.0\n";
719    if(_title.size()>0) os << "%%Title: " << _title << '\n';
720     if(_copyright.size()>0) os << "%%Copyright: " << _copyright << '\n';
721//        << "%%Copyright: XXXX\n"
722    os << "%%Creator: LEMON, graphToEps()\n";
723   
724    {
725      char cbuf[50];
726      timeval tv;
727      gettimeofday(&tv, 0);
728      ctime_r(&tv.tv_sec,cbuf);
729      os << "%%CreationDate: " << cbuf;
730    }
731
732    if (_autoEdgeWidthScale) {
733      double max_w=0;
734      for(EdgeIt e(g);e!=INVALID;++e)
735        max_w=std::max(double(_edgeWidths[e]),max_w);
736      ///\todo better 'epsilon' would be nice here.
737      if(max_w>EPSILON) {
738        _edgeWidthScale/=max_w;
739      }
740    }
741
742    if (_autoNodeScale) {
743      double max_s=0;
744      for(NodeIt n(g);n!=INVALID;++n)
745        max_s=std::max(double(_nodeSizes[n]),max_s);
746      ///\todo better 'epsilon' would be nice here.
747      if(max_s>EPSILON) {
748        _nodeScale/=max_s;
749      }
750    }
751
752    double diag_len = 1;
753    if(!(_absoluteNodeSizes&&_absoluteEdgeWidths)) {
754      dim2::BoundingBox<double> bb;
755      for(NodeIt n(g);n!=INVALID;++n) bb.add(mycoords[n]);
756      if (bb.empty()) {
757        bb = dim2::BoundingBox<double>(dim2::Point<double>(0,0));
758      }
759      diag_len = std::sqrt((bb.bottomLeft()-bb.topRight()).normSquare());
760      if(diag_len<EPSILON) diag_len = 1;
761      if(!_absoluteNodeSizes) _nodeScale*=diag_len;
762      if(!_absoluteEdgeWidths) _edgeWidthScale*=diag_len;
763    }
764   
765    dim2::BoundingBox<double> bb;
766    for(NodeIt n(g);n!=INVALID;++n) {
767      double ns=_nodeSizes[n]*_nodeScale;
768      dim2::Point<double> p(ns,ns);
769      switch(_nodeShapes[n]) {
770      case CIRCLE:
771      case SQUARE:
772      case DIAMOND:
773        bb.add(p+mycoords[n]);
774        bb.add(-p+mycoords[n]);
775        break;
776      case MALE:
777        bb.add(-p+mycoords[n]);
778        bb.add(dim2::Point<double>(1.5*ns,1.5*std::sqrt(3.0)*ns)+mycoords[n]);
779        break;
780      case FEMALE:
781        bb.add(p+mycoords[n]);
782        bb.add(dim2::Point<double>(-ns,-3.01*ns)+mycoords[n]);
783        break;
784      }
785    }
786    if (bb.empty()) {
787      bb = dim2::BoundingBox<double>(dim2::Point<double>(0,0));
788    }
789   
790    if(_scaleToA4)
791      os <<"%%BoundingBox: 0 0 596 842\n%%DocumentPaperSizes: a4\n";
792    else {
793      if(_preScale) {
794        //Rescale so that BoundingBox won't be neither to big nor too small.
795        while(bb.height()*_scale>1000||bb.width()*_scale>1000) _scale/=10;
796        while(bb.height()*_scale<100||bb.width()*_scale<100) _scale*=10;
797      }
798     
799      os << "%%BoundingBox: "
800         << int(floor(bb.left()   * _scale - _xBorder)) << ' '
801         << int(floor(bb.bottom() * _scale - _yBorder)) << ' '
802         << int(ceil(bb.right()  * _scale + _xBorder)) << ' '
803         << int(ceil(bb.top()    * _scale + _yBorder)) << '\n';
804    }
805   
806    os << "%%EndComments\n";
807   
808    //x1 y1 x2 y2 x3 y3 cr cg cb w
809    os << "/lb { setlinewidth setrgbcolor newpath moveto\n"
810       << "      4 2 roll 1 index 1 index curveto stroke } bind def\n";
811    os << "/l { setlinewidth setrgbcolor newpath moveto lineto stroke } bind def\n";
812    //x y r
813    os << "/c { newpath dup 3 index add 2 index moveto 0 360 arc closepath } bind def\n";
814    //x y r
815    os << "/sq { newpath 2 index 1 index add 2 index 2 index add moveto\n"
816       << "      2 index 1 index sub 2 index 2 index add lineto\n"
817       << "      2 index 1 index sub 2 index 2 index sub lineto\n"
818       << "      2 index 1 index add 2 index 2 index sub lineto\n"
819       << "      closepath pop pop pop} bind def\n";
820    //x y r
821    os << "/di { newpath 2 index 1 index add 2 index moveto\n"
822       << "      2 index             2 index 2 index add lineto\n"
823       << "      2 index 1 index sub 2 index             lineto\n"
824       << "      2 index             2 index 2 index sub lineto\n"
825       << "      closepath pop pop pop} bind def\n";
826    // x y r cr cg cb
827    os << "/nc { 0 0 0 setrgbcolor 5 index 5 index 5 index c fill\n"
828       << "     setrgbcolor " << 1+_nodeBorderQuotient << " div c fill\n"
829       << "   } bind def\n";
830    os << "/nsq { 0 0 0 setrgbcolor 5 index 5 index 5 index sq fill\n"
831       << "     setrgbcolor " << 1+_nodeBorderQuotient << " div sq fill\n"
832       << "   } bind def\n";
833    os << "/ndi { 0 0 0 setrgbcolor 5 index 5 index 5 index di fill\n"
834       << "     setrgbcolor " << 1+_nodeBorderQuotient << " div di fill\n"
835       << "   } bind def\n";
836    os << "/nfemale { 0 0 0 setrgbcolor 3 index "
837       << _nodeBorderQuotient/(1+_nodeBorderQuotient)
838       << " 1.5 mul mul setlinewidth\n"
839       << "  newpath 5 index 5 index moveto "
840       << "5 index 5 index 5 index 3.01 mul sub\n"
841       << "  lineto 5 index 4 index .7 mul sub 5 index 5 index 2.2 mul sub moveto\n"
842       << "  5 index 4 index .7 mul add 5 index 5 index 2.2 mul sub lineto stroke\n"
843       << "  5 index 5 index 5 index c fill\n"
844       << "  setrgbcolor " << 1+_nodeBorderQuotient << " div c fill\n"
845       << "  } bind def\n";
846    os << "/nmale {\n"
847       << "  0 0 0 setrgbcolor 3 index "
848       << _nodeBorderQuotient/(1+_nodeBorderQuotient)
849       <<" 1.5 mul mul setlinewidth\n"
850       << "  newpath 5 index 5 index moveto\n"
851       << "  5 index 4 index 1 mul 1.5 mul add\n"
852       << "  5 index 5 index 3 sqrt 1.5 mul mul add\n"
853       << "  1 index 1 index lineto\n"
854       << "  1 index 1 index 7 index sub moveto\n"
855       << "  1 index 1 index lineto\n"
856       << "  exch 5 index 3 sqrt .5 mul mul sub exch 5 index .5 mul sub lineto\n"
857       << "  stroke\n"
858       << "  5 index 5 index 5 index c fill\n"
859       << "  setrgbcolor " << 1+_nodeBorderQuotient << " div c fill\n"
860       << "  } bind def\n";
861   
862
863    os << "/arrl " << _arrowLength << " def\n";
864    os << "/arrw " << _arrowWidth << " def\n";
865    // l dx_norm dy_norm
866    os << "/lrl { 2 index mul exch 2 index mul exch rlineto pop} bind def\n";
867    //len w dx_norm dy_norm x1 y1 cr cg cb
868    os << "/arr { setrgbcolor /y1 exch def /x1 exch def /dy exch def /dx exch def\n"
869       << "       /w exch def /len exch def\n"
870      //         << "       0.1 setlinewidth x1 y1 moveto dx len mul dy len mul rlineto stroke"
871       << "       newpath x1 dy w 2 div mul add y1 dx w 2 div mul sub moveto\n"
872       << "       len w sub arrl sub dx dy lrl\n"
873       << "       arrw dy dx neg lrl\n"
874       << "       dx arrl w add mul dy w 2 div arrw add mul sub\n"
875       << "       dy arrl w add mul dx w 2 div arrw add mul add rlineto\n"
876       << "       dx arrl w add mul neg dy w 2 div arrw add mul sub\n"
877       << "       dy arrl w add mul neg dx w 2 div arrw add mul add rlineto\n"
878       << "       arrw dy dx neg lrl\n"
879       << "       len w sub arrl sub neg dx dy lrl\n"
880       << "       closepath fill } bind def\n";
881    os << "/cshow { 2 index 2 index moveto dup stringwidth pop\n"
882       << "         neg 2 div fosi .35 mul neg rmoveto show pop pop} def\n";
883
884    os << "\ngsave\n";
885    if(_scaleToA4)
886      if(bb.height()>bb.width()) {
887        double sc= std::min((A4HEIGHT-2*A4BORDER)/bb.height(),
888                  (A4WIDTH-2*A4BORDER)/bb.width());
889        os << ((A4WIDTH -2*A4BORDER)-sc*bb.width())/2 + A4BORDER << ' '
890           << ((A4HEIGHT-2*A4BORDER)-sc*bb.height())/2 + A4BORDER
891           << " translate\n"
892           << sc << " dup scale\n"
893           << -bb.left() << ' ' << -bb.bottom() << " translate\n";
894      }
895      else {
896        //\todo Verify centering
897        double sc= std::min((A4HEIGHT-2*A4BORDER)/bb.width(),
898                  (A4WIDTH-2*A4BORDER)/bb.height());
899        os << ((A4WIDTH -2*A4BORDER)-sc*bb.height())/2 + A4BORDER << ' '
900           << ((A4HEIGHT-2*A4BORDER)-sc*bb.width())/2 + A4BORDER
901           << " translate\n"
902           << sc << " dup scale\n90 rotate\n"
903           << -bb.left() << ' ' << -bb.top() << " translate\n";
904        }
905    else if(_scale!=1.0) os << _scale << " dup scale\n";
906   
907    if(_showEdges) {
908      os << "%Edges:\ngsave\n";     
909      if(_enableParallel) {
910        std::vector<Edge> el;
911        for(EdgeIt e(g);e!=INVALID;++e)
912          if((!_undirected||g.source(e)<g.target(e))&&_edgeWidths[e]>0
913             &&g.source(e)!=g.target(e))
914            el.push_back(e);
915        std::sort(el.begin(),el.end(),edgeLess(g));
916       
917        typename std::vector<Edge>::iterator j;
918        for(typename std::vector<Edge>::iterator i=el.begin();i!=el.end();i=j) {
919          for(j=i+1;j!=el.end()&&isParallel(*i,*j);++j) ;
920
921          double sw=0;
922          for(typename std::vector<Edge>::iterator e=i;e!=j;++e)
923            sw+=_edgeWidths[*e]*_edgeWidthScale+_parEdgeDist;
924          sw-=_parEdgeDist;
925          sw/=-2.0;
926          dim2::Point<double>
927            dvec(mycoords[g.target(*i)]-mycoords[g.source(*i)]);
928          double l=std::sqrt(dvec.normSquare());
929          ///\todo better 'epsilon' would be nice here.
930          dim2::Point<double> d(dvec/std::max(l,EPSILON));
931          dim2::Point<double> m;
932//        m=dim2::Point<double>(mycoords[g.target(*i)]+mycoords[g.source(*i)])/2.0;
933
934//        m=dim2::Point<double>(mycoords[g.source(*i)])+
935//          dvec*(double(_nodeSizes[g.source(*i)])/
936//             (_nodeSizes[g.source(*i)]+_nodeSizes[g.target(*i)]));
937
938          m=dim2::Point<double>(mycoords[g.source(*i)])+
939            d*(l+_nodeSizes[g.source(*i)]-_nodeSizes[g.target(*i)])/2.0;
940
941          for(typename std::vector<Edge>::iterator e=i;e!=j;++e) {
942            sw+=_edgeWidths[*e]*_edgeWidthScale/2.0;
943            dim2::Point<double> mm=m+rot90(d)*sw/.75;
944            if(_drawArrows) {
945              int node_shape;
946              dim2::Point<double> s=mycoords[g.source(*e)];
947              dim2::Point<double> t=mycoords[g.target(*e)];
948              double rn=_nodeSizes[g.target(*e)]*_nodeScale;
949              node_shape=_nodeShapes[g.target(*e)];
950              dim2::Bezier3 bez(s,mm,mm,t);
951              double t1=0,t2=1;
952              for(int i=0;i<INTERPOL_PREC;++i)
953                if(isInsideNode(bez((t1+t2)/2)-t,rn,node_shape)) t2=(t1+t2)/2;
954                else t1=(t1+t2)/2;
955              dim2::Point<double> apoint=bez((t1+t2)/2);
956              rn = _arrowLength+_edgeWidths[*e]*_edgeWidthScale;
957              rn*=rn;
958              t2=(t1+t2)/2;t1=0;
959              for(int i=0;i<INTERPOL_PREC;++i)
960                if((bez((t1+t2)/2)-apoint).normSquare()>rn) t1=(t1+t2)/2;
961                else t2=(t1+t2)/2;
962              dim2::Point<double> linend=bez((t1+t2)/2);             
963              bez=bez.before((t1+t2)/2);
964//            rn=_nodeSizes[g.source(*e)]*_nodeScale;
965//            node_shape=_nodeShapes[g.source(*e)];
966//            t1=0;t2=1;
967//            for(int i=0;i<INTERPOL_PREC;++i)
968//              if(isInsideNode(bez((t1+t2)/2)-t,rn,node_shape)) t1=(t1+t2)/2;
969//              else t2=(t1+t2)/2;
970//            bez=bez.after((t1+t2)/2);
971              os << _edgeWidths[*e]*_edgeWidthScale << " setlinewidth "
972                 << _edgeColors[*e].red() << ' '
973                 << _edgeColors[*e].green() << ' '
974                 << _edgeColors[*e].blue() << " setrgbcolor newpath\n"
975                 << bez.p1.x << ' ' <<  bez.p1.y << " moveto\n"
976                 << bez.p2.x << ' ' << bez.p2.y << ' '
977                 << bez.p3.x << ' ' << bez.p3.y << ' '
978                 << bez.p4.x << ' ' << bez.p4.y << " curveto stroke\n";
979              dim2::Point<double> dd(rot90(linend-apoint));
980              dd*=(.5*_edgeWidths[*e]*_edgeWidthScale+_arrowWidth)/
981                std::sqrt(dd.normSquare());
982              os << "newpath " << psOut(apoint) << " moveto "
983                 << psOut(linend+dd) << " lineto "
984                 << psOut(linend-dd) << " lineto closepath fill\n";
985            }
986            else {
987              os << mycoords[g.source(*e)].x << ' '
988                 << mycoords[g.source(*e)].y << ' '
989                 << mm.x << ' ' << mm.y << ' '
990                 << mycoords[g.target(*e)].x << ' '
991                 << mycoords[g.target(*e)].y << ' '
992                 << _edgeColors[*e].red() << ' '
993                 << _edgeColors[*e].green() << ' '
994                 << _edgeColors[*e].blue() << ' '
995                 << _edgeWidths[*e]*_edgeWidthScale << " lb\n";
996            }
997            sw+=_edgeWidths[*e]*_edgeWidthScale/2.0+_parEdgeDist;
998          }
999        }
1000      }
1001      else for(EdgeIt e(g);e!=INVALID;++e)
1002        if((!_undirected||g.source(e)<g.target(e))&&_edgeWidths[e]>0
1003           &&g.source(e)!=g.target(e))
1004          if(_drawArrows) {
1005            dim2::Point<double> d(mycoords[g.target(e)]-mycoords[g.source(e)]);
1006            double rn=_nodeSizes[g.target(e)]*_nodeScale;
1007            int node_shape=_nodeShapes[g.target(e)];
1008            double t1=0,t2=1;
1009            for(int i=0;i<INTERPOL_PREC;++i)
1010              if(isInsideNode((-(t1+t2)/2)*d,rn,node_shape)) t1=(t1+t2)/2;
1011              else t2=(t1+t2)/2;
1012            double l=std::sqrt(d.normSquare());
1013            d/=l;
1014           
1015            os << l*(1-(t1+t2)/2) << ' '
1016               << _edgeWidths[e]*_edgeWidthScale << ' '
1017               << d.x << ' ' << d.y << ' '
1018               << mycoords[g.source(e)].x << ' '
1019               << mycoords[g.source(e)].y << ' '
1020               << _edgeColors[e].red() << ' '
1021               << _edgeColors[e].green() << ' '
1022               << _edgeColors[e].blue() << " arr\n";
1023          }
1024          else os << mycoords[g.source(e)].x << ' '
1025                  << mycoords[g.source(e)].y << ' '
1026                  << mycoords[g.target(e)].x << ' '
1027                  << mycoords[g.target(e)].y << ' '
1028                  << _edgeColors[e].red() << ' '
1029                  << _edgeColors[e].green() << ' '
1030                  << _edgeColors[e].blue() << ' '
1031                  << _edgeWidths[e]*_edgeWidthScale << " l\n";
1032      os << "grestore\n";
1033    }
1034    if(_showNodes) {
1035      os << "%Nodes:\ngsave\n";
1036      for(NodeIt n(g);n!=INVALID;++n) {
1037        os << mycoords[n].x << ' ' << mycoords[n].y << ' '
1038           << _nodeSizes[n]*_nodeScale << ' '
1039           << _nodeColors[n].red() << ' '
1040           << _nodeColors[n].green() << ' '
1041           << _nodeColors[n].blue() << ' ';
1042        switch(_nodeShapes[n]) {
1043        case CIRCLE:
1044          os<< "nc";break;
1045        case SQUARE:
1046          os<< "nsq";break;
1047        case DIAMOND:
1048          os<< "ndi";break;
1049        case MALE:
1050          os<< "nmale";break;
1051        case FEMALE:
1052          os<< "nfemale";break;
1053        }
1054        os<<'\n';
1055      }
1056      os << "grestore\n";
1057    }
1058    if(_showNodeText) {
1059      os << "%Node texts:\ngsave\n";
1060      os << "/fosi " << _nodeTextSize << " def\n";
1061      os << "(Helvetica) findfont fosi scalefont setfont\n";
1062      for(NodeIt n(g);n!=INVALID;++n) {
1063        switch(_nodeTextColorType) {
1064        case DIST_COL:
1065          os << psOut(distantColor(_nodeColors[n])) << " setrgbcolor\n";
1066          break;
1067        case DIST_BW:
1068          os << psOut(distantBW(_nodeColors[n])) << " setrgbcolor\n";
1069          break;
1070        case CUST_COL:
1071          os << psOut(distantColor(_nodeTextColors[n])) << " setrgbcolor\n";
1072          break;
1073        default:
1074          os << "0 0 0 setrgbcolor\n";
1075        }
1076        os << mycoords[n].x << ' ' << mycoords[n].y
1077           << " (" << _nodeTexts[n] << ") cshow\n";
1078      }
1079      os << "grestore\n";
1080    }
1081    if(_showNodePsText) {
1082      os << "%Node PS blocks:\ngsave\n";
1083      for(NodeIt n(g);n!=INVALID;++n)
1084        os << mycoords[n].x << ' ' << mycoords[n].y
1085           << " moveto\n" << _nodePsTexts[n] << "\n";
1086      os << "grestore\n";
1087    }
1088   
1089    os << "grestore\nshowpage\n";
1090
1091    //CleanUp:
1092    if(_pleaseRemoveOsStream) {delete &os;}
1093  }
1094};
1095
1096template<class T>
1097const int GraphToEps<T>::INTERPOL_PREC = 20;
1098template<class T>
1099const double GraphToEps<T>::A4HEIGHT = 841.8897637795276;
1100template<class T>
1101const double GraphToEps<T>::A4WIDTH  = 595.275590551181;
1102template<class T>
1103const double GraphToEps<T>::A4BORDER = 15;
1104
1105
1106///Generates an EPS file from a graph
1107
1108///\ingroup eps_io
1109///Generates an EPS file from a graph.
1110///\param g is a reference to the graph to be printed
1111///\param os is a reference to the output stream.
1112///By default it is <tt>std::cout</tt>
1113///
1114///This function also has a lot of
1115///\ref named-templ-func-param "named parameters",
1116///they are declared as the members of class \ref GraphToEps. The following
1117///example shows how to use these parameters.
1118///\code
1119/// graphToEps(g,os).scale(10).coords(coords)
1120///              .nodeScale(2).nodeSizes(sizes)
1121///              .edgeWidthScale(.4).run();
1122///\endcode
1123///\warning Don't forget to put the \ref GraphToEps::run() "run()"
1124///to the end of the parameter list.
1125///\sa GraphToEps
1126///\sa graphToEps(G &g, const char *file_name)
1127template<class G>
1128GraphToEps<DefaultGraphToEpsTraits<G> >
1129graphToEps(G &g, std::ostream& os=std::cout)
1130{
1131  return
1132    GraphToEps<DefaultGraphToEpsTraits<G> >(DefaultGraphToEpsTraits<G>(g,os));
1133}
1134 
1135///Generates an EPS file from a graph
1136
1137///\ingroup eps_io
1138///This function does the same as
1139///\ref graphToEps(G &g,std::ostream& os)
1140///but it writes its output into the file \c file_name
1141///instead of a stream.
1142///\sa graphToEps(G &g, std::ostream& os)
1143template<class G>
1144GraphToEps<DefaultGraphToEpsTraits<G> >
1145graphToEps(G &g,const char *file_name)
1146{
1147  return GraphToEps<DefaultGraphToEpsTraits<G> >
1148    (DefaultGraphToEpsTraits<G>(g,*new std::ofstream(file_name),true));
1149}
1150
1151///Generates an EPS file from a graph
1152
1153///\ingroup eps_io
1154///This function does the same as
1155///\ref graphToEps(G &g,std::ostream& os)
1156///but it writes its output into the file \c file_name
1157///instead of a stream.
1158///\sa graphToEps(G &g, std::ostream& os)
1159template<class G>
1160GraphToEps<DefaultGraphToEpsTraits<G> >
1161graphToEps(G &g,const std::string& file_name)
1162{
1163  return GraphToEps<DefaultGraphToEpsTraits<G> >
1164    (DefaultGraphToEpsTraits<G>(g,*new std::ofstream(file_name.c_str()),true));
1165}
1166
1167} //END OF NAMESPACE LEMON
1168
1169#endif // LEMON_GRAPH_TO_EPS_H
Note: See TracBrowser for help on using the repository browser.