COIN-OR::LEMON - Graph Library

source: lemon-0.x/lemon/graph_to_eps.h @ 2064:2c5f81b35269

Last change on this file since 2064:2c5f81b35269 was 2028:d0e8a86a1ff2, checked in by Balazs Dezso, 14 years ago

MinGW32 compatibility

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