src/lemon/graph_to_eps.h
author alpar
Sat, 29 Jan 2005 15:09:41 +0000
changeset 1107 d972653c89d5
parent 1103 f196dc4f1b31
child 1108 253b66e7e41d
permissions -rw-r--r--
- Node shapes are shown in the doc.
- The generated PS file is closer to be DSC conform.
     1 /* -*- C++ -*-
     2  * src/lemon/graph_to_eps.h - Part of LEMON, a generic C++ optimization library
     3  *
     4  * Copyright (C) 2004 Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
     5  * (Egervary Combinatorial Optimization Research Group, 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<iostream>
    21 #include<fstream>
    22 #include<sstream>
    23 #include<algorithm>
    24 #include<vector>
    25 
    26 #include<lemon/xy.h>
    27 #include<lemon/maps.h>
    28 #include<lemon/bezier.h>
    29 
    30 ///\ingroup misc
    31 ///\file
    32 ///\brief Simple graph drawer
    33 ///
    34 ///\author Alpar Juttner
    35 
    36 namespace lemon {
    37 
    38 ///Data structure representing RGB colors.
    39 
    40 ///Data structure representing RGB colors.
    41 ///\ingroup misc
    42 class Color
    43 {
    44   double _r,_g,_b;
    45 public:
    46   ///Default constructor
    47   Color() {}
    48   ///Constructor
    49   Color(double r,double g,double b) :_r(r),_g(g),_b(b) {};
    50   ///Returns the red component
    51   double getR() {return _r;}
    52   ///Returns the green component
    53   double getG() {return _g;}
    54   ///Returns the blue component
    55   double getB() {return _b;}
    56   ///Set the color components
    57   void set(double r,double g,double b) { _r=r;_g=g;_b=b; };
    58 };
    59   
    60 ///Default traits class of \ref GraphToEps
    61 
    62 ///Default traits class of \ref GraphToEps
    63 ///
    64 ///\c G is the type of the underlying graph.
    65 template<class G>
    66 struct DefaultGraphToEpsTraits
    67 {
    68   typedef G Graph;
    69   typedef typename Graph::Node Node;
    70   typedef typename Graph::NodeIt NodeIt;
    71   typedef typename Graph::Edge Edge;
    72   typedef typename Graph::EdgeIt EdgeIt;
    73   typedef typename Graph::InEdgeIt InEdgeIt;
    74   typedef typename Graph::OutEdgeIt OutEdgeIt;
    75   
    76 
    77   const Graph &g;
    78 
    79   std::ostream& os;
    80   
    81   ConstMap<typename Graph::Node,xy<double> > _coords;
    82   ConstMap<typename Graph::Node,double > _nodeSizes;
    83   ConstMap<typename Graph::Node,int > _nodeShapes;
    84 
    85   ConstMap<typename Graph::Node,Color > _nodeColors;
    86   ConstMap<typename Graph::Edge,Color > _edgeColors;
    87 
    88   ConstMap<typename Graph::Edge,double > _edgeWidths;
    89 
    90   static const double A4HEIGHT = 841.8897637795276;
    91   static const double A4WIDTH  = 595.275590551181;
    92   static const double A4BORDER = 15;
    93 
    94   
    95   double _edgeWidthScale;
    96   
    97   double _nodeScale;
    98   double _xBorder, _yBorder;
    99   double _scale;
   100   double _nodeBorderQuotient;
   101   
   102   bool _drawArrows;
   103   double _arrowLength, _arrowWidth;
   104   
   105   bool _showNodes, _showEdges;
   106 
   107   bool _enableParallel;
   108   double _parEdgeDist;
   109 
   110   bool _showNodeText;
   111   ConstMap<typename Graph::Node,bool > _nodeTexts;  
   112   double _nodeTextSize;
   113 
   114   bool _showNodePsText;
   115   ConstMap<typename Graph::Node,bool > _nodePsTexts;  
   116   char *_nodePsTextsPreamble;
   117   
   118   bool _undir;
   119   bool _pleaseRemoveOsStream;
   120 
   121   bool _scaleToA4;
   122   
   123   ///Constructor
   124 
   125   ///Constructor
   126   ///\param _g is a reference to the graph to be printed
   127   ///\param _os is a reference to the output stream.
   128   ///\param _os is a reference to the output stream.
   129   ///\param _pros If it is \c true, then the \c ostream referenced by \c _os
   130   ///will be explicitly deallocated by the destructor.
   131   ///By default it is <tt>std::cout</tt>
   132   DefaultGraphToEpsTraits(const G &_g,std::ostream& _os=std::cout,
   133 			  bool _pros=false) :
   134     g(_g), os(_os),
   135     _coords(xy<double>(1,1)), _nodeSizes(1.0), _nodeShapes(0),
   136     _nodeColors(Color(1,1,1)), _edgeColors(Color(0,0,0)),
   137     _edgeWidths(1), _edgeWidthScale(0.3),
   138     _nodeScale(1.0), _xBorder(10), _yBorder(10), _scale(1.0),
   139     _nodeBorderQuotient(.1),
   140     _drawArrows(false), _arrowLength(1), _arrowWidth(0.3),
   141     _showNodes(true), _showEdges(true),
   142     _enableParallel(false), _parEdgeDist(1),
   143     _showNodeText(false), _nodeTexts(false), _nodeTextSize(1),
   144     _showNodePsText(false), _nodePsTexts(false), _nodePsTextsPreamble(0),
   145     _undir(false),
   146     _pleaseRemoveOsStream(_pros), _scaleToA4(false) {}
   147 };
   148 
   149 ///Helper class to implement the named parameters of \ref graphToEps()
   150 
   151 ///Helper class to implement the named parameters of \ref graphToEps()
   152 ///\todo Is 'helper class' a good name for this?
   153 ///
   154 ///\todo Follow PostScript's DSC.
   155 /// Use own dictionary.
   156 ///\todo Provide a way to set %%Title: and %%Copyright:. Set %%CreationDate:
   157 ///\todo Useful new features.
   158 /// - Linestyles: dotted, dashed etc.
   159 /// - A second color and percent value for the lines.
   160 template<class T> class GraphToEps : public T 
   161 {
   162   typedef typename T::Graph Graph;
   163   typedef typename Graph::Node Node;
   164   typedef typename Graph::NodeIt NodeIt;
   165   typedef typename Graph::Edge Edge;
   166   typedef typename Graph::EdgeIt EdgeIt;
   167   typedef typename Graph::InEdgeIt InEdgeIt;
   168   typedef typename Graph::OutEdgeIt OutEdgeIt;
   169 
   170   static const int INTERPOL_PREC=20;
   171 
   172   bool dontPrint;
   173 
   174 public:
   175   ///Node shapes
   176 
   177   ///Node shapes
   178   ///
   179   enum NodeShapes { 
   180     /// = 0
   181     ///\image html nodeshape_0.png
   182     ///\image latex nodeshape_0.eps "CIRCLE shape (0)" width=2cm
   183     CIRCLE=0, 
   184     /// = 1
   185     ///\image html nodeshape_1.png
   186     ///\image latex nodeshape_1.eps "SQUARE shape (1)" width=2cm
   187     ///
   188     SQUARE=1, 
   189     /// = 2
   190     ///\image html nodeshape_2.png
   191     ///\image latex nodeshape_2.eps "DIAMOND shape (2)" width=2cm
   192     ///
   193     DIAMOND=2
   194   };
   195 
   196 private:
   197   class edgeLess {
   198     const Graph &g;
   199   public:
   200     edgeLess(const Graph &_g) : g(_g) {}
   201     bool operator()(Edge a,Edge b) const 
   202     {
   203       Node ai=min(g.source(a),g.target(a));
   204       Node aa=max(g.source(a),g.target(a));
   205       Node bi=min(g.source(b),g.target(b));
   206       Node ba=max(g.source(b),g.target(b));
   207       return ai<bi ||
   208 	(ai==bi && (aa < ba || 
   209 		    (aa==ba && ai==g.source(a) && bi==g.target(b))));
   210     }
   211   };
   212   bool isParallel(Edge e,Edge f) const
   213   {
   214     return (g.source(e)==g.source(f)&&g.target(e)==g.target(f))||
   215       (g.source(e)==g.target(f)&&g.target(e)==g.source(f));
   216   }
   217   static xy<double> rot(xy<double> v) 
   218   {
   219     return xy<double>(v.y,-v.x);
   220   }
   221   template<class xy>
   222   static std::string psOut(const xy &p) 
   223     {
   224       std::ostringstream os;	
   225       os << p.x << ' ' << p.y;
   226       return os.str();
   227     }
   228   
   229 public:
   230   GraphToEps(const T &t) : T(t), dontPrint(false) {};
   231   
   232   template<class X> struct CoordsTraits : public T {
   233     const X &_coords;
   234     CoordsTraits(const T &t,const X &x) : T(t), _coords(x) {}
   235   };
   236   ///Sets the map of the node coordinates
   237 
   238   ///Sets the map of the node coordinates.
   239   ///\param x must be a node map with xy<double> or \ref xy "xy<int>" values. 
   240   template<class X> GraphToEps<CoordsTraits<X> > coords(const X &x) {
   241     dontPrint=true;
   242     return GraphToEps<CoordsTraits<X> >(CoordsTraits<X>(*this,x));
   243   }
   244   template<class X> struct NodeSizesTraits : public T {
   245     const X &_nodeSizes;
   246     NodeSizesTraits(const T &t,const X &x) : T(t), _nodeSizes(x) {}
   247   };
   248   ///Sets the map of the node sizes
   249 
   250   ///Sets the map of the node sizes
   251   ///\param x must be a node map with \c double (or convertible) values. 
   252   template<class X> GraphToEps<NodeSizesTraits<X> > nodeSizes(const X &x)
   253   {
   254     dontPrint=true;
   255     return GraphToEps<NodeSizesTraits<X> >(NodeSizesTraits<X>(*this,x));
   256   }
   257   template<class X> struct NodeShapesTraits : public T {
   258     const X &_nodeShapes;
   259     NodeShapesTraits(const T &t,const X &x) : T(t), _nodeShapes(x) {}
   260   };
   261   ///Sets the map of the node shapes
   262 
   263   ///Sets the map of the node shapes.
   264   ///The availabe shape values
   265   ///can be found in \ref NodeShapes "enum NodeShapes".
   266   ///\param x must be a node map with \c int (or convertible) values. 
   267   ///\sa NodeShapes
   268   template<class X> GraphToEps<NodeShapesTraits<X> > nodeShapes(const X &x)
   269   {
   270     dontPrint=true;
   271     return GraphToEps<NodeShapesTraits<X> >(NodeShapesTraits<X>(*this,x));
   272   }
   273   template<class X> struct NodeTextsTraits : public T {
   274     const X &_nodeTexts;
   275     NodeTextsTraits(const T &t,const X &x) : T(t), _nodeTexts(x) {}
   276   };
   277   ///Sets the text printed on the nodes
   278 
   279   ///Sets the text printed on the nodes
   280   ///\param x must be a node map with type that can be pushed to a standard
   281   ///ostream. 
   282   template<class X> GraphToEps<NodeTextsTraits<X> > nodeTexts(const X &x)
   283   {
   284     dontPrint=true;
   285     _showNodeText=true;
   286     return GraphToEps<NodeTextsTraits<X> >(NodeTextsTraits<X>(*this,x));
   287   }
   288   template<class X> struct NodePsTextsTraits : public T {
   289     const X &_nodePsTexts;
   290     NodePsTextsTraits(const T &t,const X &x) : T(t), _nodePsTexts(x) {}
   291   };
   292   ///Inserts a PostScript block to the nodes
   293 
   294   ///With this command it is possible to insert a verbatim PostScript
   295   ///block to the nodes.
   296   ///The PS current point will be moved to the centre of the node before
   297   ///the PostScript block inserted.
   298   ///
   299   ///Before and after the block a newline character is inserted to you
   300   ///don't have to bother with the separators.
   301   ///
   302   ///\param x must be a node map with type that can be pushed to a standard
   303   ///ostream.
   304   ///
   305   ///\sa nodePsTextsPreamble()
   306   ///\todo Offer the choise not to move to the centre but pass the coordinates
   307   ///to the Postscript block inserted.
   308   template<class X> GraphToEps<NodePsTextsTraits<X> > nodePsTexts(const X &x)
   309   {
   310     dontPrint=true;
   311     _showNodePsText=true;
   312     return GraphToEps<NodePsTextsTraits<X> >(NodePsTextsTraits<X>(*this,x));
   313   }
   314   template<class X> struct EdgeWidthsTraits : public T {
   315     const X &_edgeWidths;
   316     EdgeWidthsTraits(const T &t,const X &x) : T(t), _edgeWidths(x) {}
   317   };
   318   ///Sets the map of the edge widths
   319 
   320   ///Sets the map of the edge widths
   321   ///\param x must be a edge map with \c double (or convertible) values. 
   322   template<class X> GraphToEps<EdgeWidthsTraits<X> > edgeWidths(const X &x)
   323   {
   324     dontPrint=true;
   325     return GraphToEps<EdgeWidthsTraits<X> >(EdgeWidthsTraits<X>(*this,x));
   326   }
   327 
   328   template<class X> struct NodeColorsTraits : public T {
   329     const X &_nodeColors;
   330     NodeColorsTraits(const T &t,const X &x) : T(t), _nodeColors(x) {}
   331   };
   332   ///Sets the map of the node colors
   333 
   334   ///Sets the map of the node colors
   335   ///\param x must be a node map with \ref Color values. 
   336   template<class X> GraphToEps<NodeColorsTraits<X> >
   337   nodeColors(const X &x)
   338   {
   339     dontPrint=true;
   340     return GraphToEps<NodeColorsTraits<X> >(NodeColorsTraits<X>(*this,x));
   341   }
   342   template<class X> struct EdgeColorsTraits : public T {
   343     const X &_edgeColors;
   344     EdgeColorsTraits(const T &t,const X &x) : T(t), _edgeColors(x) {}
   345   };
   346   ///Sets the map of the edge colors
   347 
   348   ///Sets the map of the edge colors
   349   ///\param x must be a edge map with \ref Color values. 
   350   template<class X> GraphToEps<EdgeColorsTraits<X> >
   351   edgeColors(const X &x)
   352   {
   353     dontPrint=true;
   354     return GraphToEps<EdgeColorsTraits<X> >(EdgeColorsTraits<X>(*this,x));
   355   }
   356   ///Sets a global scale factor for node sizes
   357 
   358   ///Sets a global scale factor for node sizes
   359   ///
   360   GraphToEps<T> &nodeScale(double d) {_nodeScale=d;return *this;}
   361   ///Sets a global scale factor for edge widths
   362 
   363   ///Sets a global scale factor for edge widths
   364   ///
   365   GraphToEps<T> &edgeWidthScale(double d) {_edgeWidthScale=d;return *this;}
   366   ///Sets a global scale factor for the whole picture
   367 
   368   ///Sets a global scale factor for the whole picture
   369   ///
   370   GraphToEps<T> &scale(double d) {_scale=d;return *this;}
   371   ///Sets the width of the border around the picture
   372 
   373   ///Sets the width of the border around the picture
   374   ///
   375   GraphToEps<T> &border(double b) {_xBorder=_yBorder=b;return *this;}
   376   ///Sets the width of the border around the picture
   377 
   378   ///Sets the width of the border around the picture
   379   ///
   380   GraphToEps<T> &border(double x, double y) {
   381     _xBorder=x;_yBorder=y;return *this;
   382   }
   383   ///Sets whether to draw arrows
   384 
   385   ///Sets whether to draw arrows
   386   ///
   387   GraphToEps<T> &drawArrows(bool b=true) {_drawArrows=b;return *this;}
   388   ///Sets the length of the arrowheads
   389 
   390   ///Sets the length of the arrowheads
   391   ///
   392   GraphToEps<T> &arrowLength(double d) {_arrowLength*=d;return *this;}
   393   ///Sets the width of the arrowheads
   394 
   395   ///Sets the width of the arrowheads
   396   ///
   397   GraphToEps<T> &arrowWidth(double d) {_arrowWidth*=d;return *this;}
   398   
   399   ///Scales the drawing to fit to A4 page
   400 
   401   ///Scales the drawing to fit to A4 page
   402   ///
   403   GraphToEps<T> &scaleToA4() {_scaleToA4=true;return *this;}
   404   
   405   ///Enables parallel edges
   406 
   407   ///Enables parallel edges
   408   ///\todo Partially implemented
   409   GraphToEps<T> &enableParallel(bool b=true) {_enableParallel=b;return *this;}
   410   
   411   ///Sets the distance 
   412   
   413   ///Sets the distance 
   414   ///
   415   GraphToEps<T> &parEdgeDist(double d) {_parEdgeDist*=d;return *this;}
   416   
   417   ///Hides the edges
   418   
   419   ///Hides the edges
   420   ///
   421   GraphToEps<T> &hideEdges(bool b=true) {_showEdges=!b;return *this;}
   422   ///Hides the nodes
   423   
   424   ///Hides the nodes
   425   ///
   426   GraphToEps<T> &hideNodes(bool b=true) {_showNodes=!b;return *this;}
   427   
   428   ///Sets the size of the node texts
   429   
   430   ///Sets the size of the node texts
   431   ///
   432   GraphToEps<T> &nodeTextSize(double d) {_nodeTextSize=d;return *this;}
   433   ///Gives a preamble block for node Postscript block.
   434   
   435   ///Gives a preamble block for node Postscript block.
   436   ///
   437   ///\sa nodePsTexts()
   438   GraphToEps<T> & nodePsTextsPreamble(const char *str) {
   439     _nodePsTextsPreamble=s ;return *this;
   440   }
   441   ///Sets whether the the graph is undirected
   442 
   443   ///Sets whether the the graph is undirected
   444   ///
   445   GraphToEps<T> &undir(bool b=true) {_undir=b;return *this;}
   446   ///Sets whether the the graph is directed
   447 
   448   ///Sets whether the the graph is directed.
   449   ///Use it to show the undirected edges as a pair of directed ones.
   450   GraphToEps<T> &bidir(bool b=true) {_undir=!b;return *this;}
   451 
   452 protected:
   453   bool isInsideNode(xy<double> p, double r,int t) 
   454   {
   455     switch(t) {
   456     case CIRCLE:
   457       return p.normSquare()<=r*r;
   458     case SQUARE:
   459       return p.x<=r&&p.x>=-r&&p.y<=r&&p.y>=-r;
   460     case DIAMOND:
   461       return p.x+p.y<=r && p.x-p.y<=r && -p.x+p.y<=r && -p.x-p.y<=r;
   462     }
   463     return false;
   464   }
   465 
   466 public:
   467   ~GraphToEps() { }
   468   
   469   ///Draws the graph.
   470 
   471   ///Like other functions using
   472   ///\ref named-templ-func-param "named template parameters",
   473   ///this function calles the algorithm itself, i.e. in this case
   474   ///it draws the graph.
   475   void run() {
   476     if(dontPrint) return;
   477     
   478     os << "%!PS-Adobe-2.0 EPSF-2.0\n";
   479     os << "%%Title: LEMON GraphToEps figure\n" ///\todo setTitle() is needed
   480 //        << "%%Copyright: XXXX\n"
   481        << "%%Creator: LEMON GraphToEps function\n"
   482 //        << "%%CreationDate: XXXXXXX\n"
   483       ;
   484     ///\todo: Chech whether the graph is empty.
   485     BoundingBox<double> bb;
   486     for(NodeIt n(g);n!=INVALID;++n) {
   487       double ns=_nodeSizes[n]*_nodeScale;
   488       xy<double> p(ns,ns);
   489       bb+=p+_coords[n];
   490       bb+=-p+_coords[n];
   491       }
   492     if(!_scaleToA4) os << "%%BoundingBox: "
   493 		      << bb.left()*  _scale-_xBorder << ' '
   494 		      << bb.bottom()*_scale-_yBorder << ' '
   495 		      << bb.right()* _scale+_xBorder << ' '
   496 		      << bb.top()*   _scale+_yBorder << '\n';
   497 
   498     os << "%%EndComments\n";
   499     
   500     //x1 y1 x2 y2 x3 y3 cr cg cb w
   501     os << "/lb { setlinewidth setrgbcolor newpath moveto\n"
   502        << "      4 2 roll 1 index 1 index curveto stroke } bind def\n";
   503     os << "/l { setlinewidth setrgbcolor newpath moveto lineto stroke } bind def\n";
   504     //x y r
   505     os << "/c { newpath dup 3 index add 2 index moveto 0 360 arc closepath } bind def\n";
   506     //x y r
   507     os << "/sq { newpath 2 index 1 index add 2 index 2 index add moveto\n"
   508        << "      2 index 1 index sub 2 index 2 index add lineto\n"
   509        << "      2 index 1 index sub 2 index 2 index sub lineto\n"
   510        << "      2 index 1 index add 2 index 2 index sub lineto\n"
   511        << "      closepath pop pop pop} bind def\n";
   512     //x y r
   513     os << "/di { newpath 2 index 1 index add 2 index moveto\n"
   514        << "      2 index             2 index 2 index add lineto\n"
   515        << "      2 index 1 index sub 2 index             lineto\n"
   516        << "      2 index             2 index 2 index sub lineto\n"
   517        << "      closepath pop pop pop} bind def\n";
   518     // x y r cr cg cb
   519     os << "/nc { 0 0 0 setrgbcolor 5 index 5 index 5 index c fill\n"
   520        << "     setrgbcolor " << 1+_nodeBorderQuotient << " div c fill\n"
   521        << "   } bind def\n";
   522     os << "/nsq { 0 0 0 setrgbcolor 5 index 5 index 5 index sq fill\n"
   523        << "     setrgbcolor " << 1+_nodeBorderQuotient << " div sq fill\n"
   524        << "   } bind def\n";
   525     os << "/ndi { 0 0 0 setrgbcolor 5 index 5 index 5 index di fill\n"
   526        << "     setrgbcolor " << 1+_nodeBorderQuotient << " div di fill\n"
   527        << "   } bind def\n";
   528     os << "/arrl " << _arrowLength << " def\n";
   529     os << "/arrw " << _arrowWidth << " def\n";
   530     // l dx_norm dy_norm
   531     os << "/lrl { 2 index mul exch 2 index mul exch rlineto pop} bind def\n";
   532     //len w dx_norm dy_norm x1 y1 cr cg cb
   533     os << "/arr { setrgbcolor /y1 exch def /x1 exch def /dy exch def /dx exch def\n"
   534        << "       /w exch def /len exch def\n"
   535       //	 << "       0.1 setlinewidth x1 y1 moveto dx len mul dy len mul rlineto stroke"
   536        << "       newpath x1 dy w 2 div mul add y1 dx w 2 div mul sub moveto\n"
   537        << "       len w sub arrl sub dx dy lrl\n"
   538        << "       arrw dy dx neg lrl\n"
   539        << "       dx arrl w add mul dy w 2 div arrw add mul sub\n"
   540        << "       dy arrl w add mul dx w 2 div arrw add mul add rlineto\n"
   541        << "       dx arrl w add mul neg dy w 2 div arrw add mul sub\n"
   542        << "       dy arrl w add mul neg dx w 2 div arrw add mul add rlineto\n"
   543        << "       arrw dy dx neg lrl\n"
   544        << "       len w sub arrl sub neg dx dy lrl\n"
   545        << "       closepath fill } bind def\n";
   546     os << "/cshow { 2 index 2 index moveto dup stringwidth pop\n"
   547        << "         neg 2 div fosi .35 mul neg rmoveto show pop pop} def\n";
   548 
   549     os << "\ngsave\n";
   550     if(_scaleToA4)
   551       if(bb.height()>bb.width()) {
   552 	double sc= min((A4HEIGHT-2*A4BORDER)/bb.height(),
   553 		  (A4WIDTH-2*A4BORDER)/bb.width());
   554 	os << ((A4WIDTH -2*A4BORDER)-sc*bb.width())/2 + A4BORDER << ' '
   555 	   << ((A4HEIGHT-2*A4BORDER)-sc*bb.height())/2 + A4BORDER << " translate\n"
   556 	   << sc << " dup scale\n"
   557 	   << -bb.left() << ' ' << -bb.bottom() << " translate\n";
   558       }
   559       else {
   560 	//\todo Verify centering
   561 	double sc= min((A4HEIGHT-2*A4BORDER)/bb.width(),
   562 		  (A4WIDTH-2*A4BORDER)/bb.height());
   563 	os << ((A4WIDTH -2*A4BORDER)-sc*bb.height())/2 + A4BORDER << ' '
   564 	   << ((A4HEIGHT-2*A4BORDER)-sc*bb.width())/2 + A4BORDER  << " translate\n"
   565 	   << sc << " dup scale\n90 rotate\n"
   566 	   << -bb.left() << ' ' << -bb.top() << " translate\n";	
   567 	}
   568     else if(_scale!=1.0) os << _scale << " dup scale\n";
   569     
   570     if(_showEdges) {
   571       os << "%Edges:\ngsave\n";      
   572       if(_enableParallel) {
   573 	std::vector<Edge> el;
   574 	for(EdgeIt e(g);e!=INVALID;++e)
   575 	  if(!_undir||g.source(e)<g.target(e)) el.push_back(e);
   576 	sort(el.begin(),el.end(),edgeLess(g));
   577 	
   578 	typename std::vector<Edge>::iterator j;
   579 	for(typename std::vector<Edge>::iterator i=el.begin();i!=el.end();i=j) {
   580 	  for(j=i+1;j!=el.end()&&isParallel(*i,*j);++j) ;
   581 
   582 	  double sw=0;
   583 	  for(typename std::vector<Edge>::iterator e=i;e!=j;++e)
   584 	    sw+=_edgeWidths[*e]*_edgeWidthScale+_parEdgeDist;
   585 	  sw-=_parEdgeDist;
   586 	  sw/=-2.0;
   587 	  xy<double> dvec(_coords[g.target(*i)]-_coords[g.source(*i)]);
   588 	  double l=sqrt(dvec.normSquare());
   589 	  xy<double> d(dvec/l);
   590  	  xy<double> m;
   591 // 	  m=xy<double>(_coords[g.target(*i)]+_coords[g.source(*i)])/2.0;
   592 
   593 //  	  m=xy<double>(_coords[g.source(*i)])+
   594 // 	    dvec*(double(_nodeSizes[g.source(*i)])/
   595 // 	       (_nodeSizes[g.source(*i)]+_nodeSizes[g.target(*i)]));
   596 
   597  	  m=xy<double>(_coords[g.source(*i)])+
   598 	    d*(l+_nodeSizes[g.source(*i)]-_nodeSizes[g.target(*i)])/2.0;
   599 
   600 	  for(typename std::vector<Edge>::iterator e=i;e!=j;++e) {
   601 	    sw+=_edgeWidths[*e]*_edgeWidthScale/2.0;
   602 	    xy<double> mm=m+rot(d)*sw/.75;
   603 	    if(_drawArrows) {
   604 	      int node_shape;
   605 	      xy<double> s=_coords[g.source(*e)];
   606 	      xy<double> t=_coords[g.target(*e)];
   607 	      double rn=_nodeSizes[g.target(*e)]*_nodeScale;
   608 	      node_shape=_nodeShapes[g.target(*e)];
   609 	      Bezier3 bez(s,mm,mm,t);
   610 	      double t1=0,t2=1;
   611 	      for(int i=0;i<INTERPOL_PREC;++i)
   612 		if(isInsideNode(bez((t1+t2)/2)-t,rn,node_shape)) t2=(t1+t2)/2;
   613 		else t1=(t1+t2)/2;
   614 	      xy<double> apoint=bez((t1+t2)/2);
   615 	      rn = _arrowLength+_edgeWidths[*e]*_edgeWidthScale;
   616 	      rn*=rn;
   617 	      t2=(t1+t2)/2;t1=0;
   618 	      for(int i=0;i<INTERPOL_PREC;++i)
   619 		if((bez((t1+t2)/2)-apoint).normSquare()>rn) t1=(t1+t2)/2;
   620 		else t2=(t1+t2)/2;
   621 	      xy<double> linend=bez((t1+t2)/2);	      
   622 	      bez=bez.before((t1+t2)/2);
   623 // 	      rn=_nodeSizes[g.source(*e)]*_nodeScale;
   624 // 	      node_shape=_nodeShapes[g.source(*e)];
   625 // 	      t1=0;t2=1;
   626 // 	      for(int i=0;i<INTERPOL_PREC;++i)
   627 // 		if(isInsideNode(bez((t1+t2)/2)-t,rn,node_shape)) t1=(t1+t2)/2;
   628 // 		else t2=(t1+t2)/2;
   629 // 	      bez=bez.after((t1+t2)/2);
   630 	      os << _edgeWidths[*e]*_edgeWidthScale << " setlinewidth "
   631 		 << _edgeColors[*e].getR() << ' '
   632 		 << _edgeColors[*e].getG() << ' '
   633 		 << _edgeColors[*e].getB() << " setrgbcolor newpath\n"
   634 		 << bez.p1.x << ' ' <<  bez.p1.y << " moveto\n"
   635 		 << bez.p2.x << ' ' << bez.p2.y << ' '
   636 		 << bez.p3.x << ' ' << bez.p3.y << ' '
   637 		 << bez.p4.x << ' ' << bez.p4.y << " curveto stroke\n";
   638 	      xy<double> dd(rot(linend-apoint));
   639 	      dd*=(.5*_edgeWidths[*e]*_edgeWidthScale+_arrowWidth)/
   640 		sqrt(dd.normSquare());
   641 	      os << "newpath " << psOut(apoint) << " moveto "
   642 		 << psOut(linend+dd) << " lineto "
   643 		 << psOut(linend-dd) << " lineto closepath fill\n";
   644 	    }
   645 	    else {
   646 	      os << _coords[g.source(*e)].x << ' '
   647 		 << _coords[g.source(*e)].y << ' '
   648 		 << mm.x << ' ' << mm.y << ' '
   649 		 << _coords[g.target(*e)].x << ' '
   650 		 << _coords[g.target(*e)].y << ' '
   651 		 << _edgeColors[*e].getR() << ' '
   652 		 << _edgeColors[*e].getG() << ' '
   653 		 << _edgeColors[*e].getB() << ' '
   654 		 << _edgeWidths[*e]*_edgeWidthScale << " lb\n";
   655 	    }
   656 	    sw+=_edgeWidths[*e]*_edgeWidthScale/2.0+_parEdgeDist;
   657 	  }
   658 	}
   659       }
   660       else for(EdgeIt e(g);e!=INVALID;++e)
   661 	if(!_undir||g.source(e)<g.target(e))
   662 	  if(_drawArrows) {
   663 	    xy<double> d(_coords[g.target(e)]-_coords[g.source(e)]);
   664 	    double rn=_nodeSizes[g.target(e)]*_nodeScale;
   665 	    int node_shape=_nodeShapes[g.target(e)];
   666 	    double t1=0,t2=1;
   667 	    for(int i=0;i<INTERPOL_PREC;++i)
   668 	      if(isInsideNode((-(t1+t2)/2)*d,rn,node_shape)) t1=(t1+t2)/2;
   669 	      else t2=(t1+t2)/2;
   670 	    double l=sqrt(d.normSquare());
   671 	    d/=l;
   672 	    
   673 	    os << l*(1-(t1+t2)/2) << ' '
   674 	       << _edgeWidths[e]*_edgeWidthScale << ' '
   675 	       << d.x << ' ' << d.y << ' '
   676 	       << _coords[g.source(e)].x << ' '
   677 	       << _coords[g.source(e)].y << ' '
   678 	       << _edgeColors[e].getR() << ' '
   679 	       << _edgeColors[e].getG() << ' '
   680 	       << _edgeColors[e].getB() << " arr\n";
   681 	  }
   682 	  else os << _coords[g.source(e)].x << ' '
   683 		  << _coords[g.source(e)].y << ' '
   684 		  << _coords[g.target(e)].x << ' '
   685 		  << _coords[g.target(e)].y << ' '
   686 		  << _edgeColors[e].getR() << ' '
   687 		  << _edgeColors[e].getG() << ' '
   688 		  << _edgeColors[e].getB() << ' '
   689 		  << _edgeWidths[e]*_edgeWidthScale << " l\n";
   690       os << "grestore\n";
   691     }
   692     if(_showNodes) {
   693       os << "%Nodes:\ngsave\n";
   694       for(NodeIt n(g);n!=INVALID;++n) {
   695 	os << _coords[n].x << ' ' << _coords[n].y << ' '
   696 	   << _nodeSizes[n]*_nodeScale << ' '
   697 	   << _nodeColors[n].getR() << ' '
   698 	   << _nodeColors[n].getG() << ' '
   699 	   << _nodeColors[n].getB() << ' ';
   700 	switch(_nodeShapes[n]) {
   701 	case CIRCLE:
   702 	  os<< "nc";break;
   703 	case SQUARE:
   704 	  os<< "nsq";break;
   705 	case DIAMOND:
   706 	  os<< "ndi";break;
   707 	}
   708 	os<<'\n';
   709       }
   710       os << "grestore\n";
   711     }
   712     if(_showNodeText) {
   713       os << "%Node texts:\ngsave\n";
   714       os << "/fosi " << _nodeTextSize << " def\n";
   715       os << "(Helvetica) findfont fosi scalefont setfont\n";
   716       os << "0 0 0 setrgbcolor\n";
   717       for(NodeIt n(g);n!=INVALID;++n)
   718 	os << _coords[n].x << ' ' << _coords[n].y
   719 	   << " (" << _nodeTexts[n] << ") cshow\n";
   720       os << "grestore\n";
   721     }
   722     if(_showNodePsText) {
   723       os << "%Node PS blocks:\ngsave\n";
   724       for(NodeIt n(g);n!=INVALID;++n)
   725 	os << _coords[n].x << ' ' << _coords[n].y
   726 	   << " moveto\n" << _nodePsTexts[n] << "\n";
   727       os << "grestore\n";
   728     }
   729     
   730     os << "grestore\nshowpage\n";
   731 
   732     //CleanUp:
   733     if(_pleaseRemoveOsStream) {delete &os;}
   734   } 
   735 };
   736 
   737 
   738 ///Generates an EPS file from a graph
   739 
   740 ///\ingroup misc
   741 ///Generates an EPS file from a graph.
   742 ///\param g is a reference to the graph to be printed
   743 ///\param os is a reference to the output stream.
   744 ///By default it is <tt>std::cout</tt>
   745 ///
   746 ///This function also has a lot of
   747 ///\ref named-templ-func-param "named parameters",
   748 ///they are declared as the members of class \ref GraphToEps. The following
   749 ///example shows how to use these parameters.
   750 ///\code
   751 /// graphToEps(g).scale(10).coords(coords)
   752 ///              .nodeScale(2).nodeSizes(sizes)
   753 ///              .edgeWidthScale(.4).run();
   754 ///\endcode
   755 ///\warning Don't forget to put the \ref GraphToEps::run() "run()"
   756 ///to the end of the parameter list.
   757 ///\sa GraphToEps
   758 ///\sa graphToEps(G &g, char *file_name)
   759 template<class G>
   760 GraphToEps<DefaultGraphToEpsTraits<G> > 
   761 graphToEps(G &g, std::ostream& os=std::cout)
   762 {
   763   return 
   764     GraphToEps<DefaultGraphToEpsTraits<G> >(DefaultGraphToEpsTraits<G>(g,os));
   765 }
   766  
   767 ///Generates an EPS file from a graph
   768 
   769 ///\ingroup misc
   770 ///This function does the same as
   771 ///\ref graphToEps(G &g,std::ostream& os)
   772 ///but it writes its output into the file \c file_name
   773 ///instead of a stream.
   774 ///\sa graphToEps(G &g, std::ostream& os)
   775 template<class G>
   776 GraphToEps<DefaultGraphToEpsTraits<G> > 
   777 graphToEps(G &g,const char *file_name)
   778 {
   779   return GraphToEps<DefaultGraphToEpsTraits<G> >
   780     (DefaultGraphToEpsTraits<G>(g,*new std::ofstream(file_name),true));
   781 }
   782 
   783 } //END OF NAMESPACE LEMON
   784 
   785 #endif // LEMON_GRAPH_TO_EPS_H