COIN-OR::LEMON - Graph Library

source: lemon-0.x/lemon/graph_to_eps.h @ 1575:438bc5defad1

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