COIN-OR::LEMON - Graph Library

source: lemon-0.x/lemon/graph_to_eps.h @ 1574:697ed4dd309a

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