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