COIN-OR::LEMON - Graph Library

source: lemon-0.x/src/lemon/graph_to_eps.h @ 1233:f3d856bf1ebf

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