2 * src/lemon/graph_to_eps.h - Part of LEMON, a generic C++ optimization library
4 * Copyright (C) 2004 Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
5 * (Egervary Combinatorial Optimization Research Group, EGRES).
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.
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
17 #ifndef LEMON_GRAPH_TO_EPS_H
18 #define LEMON_GRAPH_TO_EPS_H
27 #include<lemon/maps.h>
28 #include<lemon/bezier.h>
32 ///\brief Simple graph drawer
34 ///\author Alpar Juttner
38 ///Data structure representing RGB colors.
40 ///Data structure representing RGB colors.
46 ///Default constructor
49 Color(double r,double g,double b) :_r(r),_g(g),_b(b) {};
50 ///Returns the red component
51 double getR() {return _r;}
52 ///Returns the green component
53 double getG() {return _g;}
54 ///Returns the blue component
55 double getB() {return _b;}
56 ///Set the color components
57 void set(double r,double g,double b) { _r=r;_g=g;_b=b; };
60 ///Default traits class of \ref GraphToEps
62 ///Default traits class of \ref GraphToEps
64 ///\c G is the type of the underlying graph.
66 struct DefaultGraphToEpsTraits
69 typedef typename Graph::Node Node;
70 typedef typename Graph::NodeIt NodeIt;
71 typedef typename Graph::Edge Edge;
72 typedef typename Graph::EdgeIt EdgeIt;
73 typedef typename Graph::InEdgeIt InEdgeIt;
74 typedef typename Graph::OutEdgeIt OutEdgeIt;
81 ConstMap<typename Graph::Node,xy<double> > _coords;
82 ConstMap<typename Graph::Node,double > _nodeSizes;
84 ConstMap<typename Graph::Node,Color > _nodeColors;
85 ConstMap<typename Graph::Edge,Color > _edgeColors;
87 ConstMap<typename Graph::Edge,double > _edgeWidths;
89 double _edgeWidthScale;
92 double _xBorder, _yBorder;
94 double _nodeBorderQuotient;
97 double _arrowLength, _arrowWidth;
99 bool _showNodes, _showEdges;
101 bool _enableParallel;
105 ConstMap<typename Graph::Node,bool > _nodeTexts;
106 double _nodeTextSize;
108 bool _showNodePsText;
109 ConstMap<typename Graph::Node,bool > _nodePsTexts;
110 char *_nodePsTextsPreamble;
113 bool _pleaseRemoveOsStream;
117 ///\param _g is a reference to the graph to be printed
118 ///\param _os is a reference to the output stream.
119 ///\param _os is a reference to the output stream.
120 ///\param _pros If it is \c true, then the \c ostream referenced by \c _os
121 ///will be explicitly deallocated by the destructor.
122 ///By default it is <tt>std::cout</tt>
123 DefaultGraphToEpsTraits(const G &_g,std::ostream& _os=std::cout,
126 _coords(xy<double>(1,1)), _nodeSizes(1.0),
127 _nodeColors(Color(1,1,1)), _edgeColors(Color(0,0,0)),
128 _edgeWidths(1), _edgeWidthScale(0.3),
129 _nodeScale(1.0), _xBorder(10), _yBorder(10), _scale(1.0),
130 _nodeBorderQuotient(.1),
131 _drawArrows(false), _arrowLength(1), _arrowWidth(0.3),
132 _showNodes(true), _showEdges(true),
133 _enableParallel(false), _parEdgeDist(1),
134 _showNodeText(false), _nodeTexts(false), _nodeTextSize(1),
135 _showNodePsText(false), _nodePsTexts(false), _nodePsTextsPreamble(0),
137 _pleaseRemoveOsStream(_pros) {}
140 ///Helper class to implement the named parameters of \ref graphToEps()
142 ///Helper class to implement the named parameters of \ref graphToEps()
143 ///\todo Is 'helper class' a good name for this?
145 template<class T> class GraphToEps : public T
147 typedef typename T::Graph Graph;
148 typedef typename Graph::Node Node;
149 typedef typename Graph::NodeIt NodeIt;
150 typedef typename Graph::Edge Edge;
151 typedef typename Graph::EdgeIt EdgeIt;
152 typedef typename Graph::InEdgeIt InEdgeIt;
153 typedef typename Graph::OutEdgeIt OutEdgeIt;
160 edgeLess(const Graph &_g) : g(_g) {}
161 bool operator()(Edge a,Edge b) const
163 Node ai=min(g.source(a),g.target(a));
164 Node aa=max(g.source(a),g.target(a));
165 Node bi=min(g.source(b),g.target(b));
166 Node ba=max(g.source(b),g.target(b));
168 (ai==bi && (aa < ba ||
169 (aa==ba && ai==g.source(a) && bi==g.target(b))));
172 bool isParallel(Edge e,Edge f) const
174 return (g.source(e)==g.source(f)&&g.target(e)==g.target(f))||
175 (g.source(e)==g.target(f)&&g.target(e)==g.source(f));
177 static xy<double> rot(xy<double> v)
179 return xy<double>(v.y,-v.x);
182 static std::string psOut(const xy &p)
184 std::ostringstream os;
185 os << p.x << ' ' << p.y;
190 GraphToEps(const T &t) : T(t), dontPrint(false) {};
192 template<class X> struct CoordsTraits : public T {
194 CoordsTraits(const T &t,const X &x) : T(t), _coords(x) {}
196 ///Sets the map of the node coordinates
198 ///Sets the map of the node coordinates.
199 ///\param x must be a node map with xy<double> or xy<int> values.
200 template<class X> GraphToEps<CoordsTraits<X> > coords(const X &x) {
202 return GraphToEps<CoordsTraits<X> >(CoordsTraits<X>(*this,x));
204 template<class X> struct NodeSizesTraits : public T {
206 NodeSizesTraits(const T &t,const X &x) : T(t), _nodeSizes(x) {}
208 ///Sets the map of the node sizes
210 ///Sets the map of the node sizes
211 ///\param x must be a node map with \c double (or convertible) values.
212 template<class X> GraphToEps<NodeSizesTraits<X> > nodeSizes(const X &x)
215 return GraphToEps<NodeSizesTraits<X> >(NodeSizesTraits<X>(*this,x));
217 template<class X> struct NodeTextsTraits : public T {
219 NodeTextsTraits(const T &t,const X &x) : T(t), _nodeTexts(x) {}
221 ///Sets the text printed on the nodes
223 ///Sets the text printed on the nodes
224 ///\param x must be a node map with type that can be pushed to a standard
226 template<class X> GraphToEps<NodeTextsTraits<X> > nodeTexts(const X &x)
230 return GraphToEps<NodeTextsTraits<X> >(NodeTextsTraits<X>(*this,x));
232 template<class X> struct NodePsTextsTraits : public T {
233 const X &_nodePsTexts;
234 NodePsTextsTraits(const T &t,const X &x) : T(t), _nodePsTexts(x) {}
236 ///Inserts a PostScript block to the nodes
238 ///With this command it is possible to insert a verbatim PostScript
239 ///block to the nodes.
240 ///The PS current point will be moved to the centre of the node before
241 ///the PostScript block inserted.
243 ///Before and after the block a newline character is inserted to you
244 ///don't have to bother with the separators.
246 ///\param x must be a node map with type that can be pushed to a standard
249 ///\sa nodePsTextsPreamble()
250 ///\todo Offer the choise not to move to the centre but pass the coordinates
251 ///to the Postscript block inserted.
252 template<class X> GraphToEps<NodePsTextsTraits<X> > nodePsTexts(const X &x)
255 _showNodePsText=true;
256 return GraphToEps<NodePsTextsTraits<X> >(NodePsTextsTraits<X>(*this,x));
258 template<class X> struct EdgeWidthsTraits : public T {
259 const X &_edgeWidths;
260 EdgeWidthsTraits(const T &t,const X &x) : T(t), _edgeWidths(x) {}
262 ///Sets the map of the edge widths
264 ///Sets the map of the edge widths
265 ///\param x must be a edge map with \c double (or convertible) values.
266 template<class X> GraphToEps<EdgeWidthsTraits<X> > edgeWidths(const X &x)
269 return GraphToEps<EdgeWidthsTraits<X> >(EdgeWidthsTraits<X>(*this,x));
272 template<class X> struct NodeColorsTraits : public T {
273 const X &_nodeColors;
274 NodeColorsTraits(const T &t,const X &x) : T(t), _nodeColors(x) {}
276 ///Sets the map of the node colors
278 ///Sets the map of the node colors
279 ///\param x must be a node map with \ref Color values.
280 template<class X> GraphToEps<NodeColorsTraits<X> >
281 nodeColors(const X &x)
284 return GraphToEps<NodeColorsTraits<X> >(NodeColorsTraits<X>(*this,x));
286 template<class X> struct EdgeColorsTraits : public T {
287 const X &_edgeColors;
288 EdgeColorsTraits(const T &t,const X &x) : T(t), _edgeColors(x) {}
290 ///Sets the map of the edge colors
292 ///Sets the map of the edge colors
293 ///\param x must be a edge map with \ref Color values.
294 template<class X> GraphToEps<EdgeColorsTraits<X> >
295 edgeColors(const X &x)
298 return GraphToEps<EdgeColorsTraits<X> >(EdgeColorsTraits<X>(*this,x));
300 ///Sets a global scale factor for node sizes
302 ///Sets a global scale factor for node sizes
304 GraphToEps<T> &nodeScale(double d) {_nodeScale=d;return *this;}
305 ///Sets a global scale factor for edge widths
307 ///Sets a global scale factor for edge widths
309 GraphToEps<T> &edgeWidthScale(double d) {_edgeWidthScale=d;return *this;}
310 ///Sets a global scale factor for the whole picture
312 ///Sets a global scale factor for the whole picture
314 GraphToEps<T> &scale(double d) {_scale=d;return *this;}
315 ///Sets the width of the border around the picture
317 ///Sets the width of the border around the picture
319 GraphToEps<T> &border(double b) {_xBorder=_yBorder=b;return *this;}
320 ///Sets the width of the border around the picture
322 ///Sets the width of the border around the picture
324 GraphToEps<T> &border(double x, double y) {
325 _xBorder=x;_yBorder=y;return *this;
327 ///Sets whether to draw arrows
329 ///Sets whether to draw arrows
331 GraphToEps<T> &drawArrows(bool b=true) {_drawArrows=b;return *this;}
332 ///Sets the length of the arrowheads
334 ///Sets the length of the arrowheads
336 GraphToEps<T> &arrowLength(double d) {_arrowLength*=d;return *this;}
337 ///Sets the width of the arrowheads
339 ///Sets the width of the arrowheads
341 GraphToEps<T> &arrowWidth(double d) {_arrowWidth*=d;return *this;}
343 ///Enables parallel edges
345 ///Enables parallel edges
346 ///\todo Partially implemented
347 GraphToEps<T> &enableParallel(bool b=true) {_enableParallel=b;return *this;}
353 GraphToEps<T> &parEdgeDist(double d) {_parEdgeDist*=d;return *this;}
359 GraphToEps<T> &hideEdges(bool b=true) {_showEdges=!b;return *this;}
364 GraphToEps<T> &hideNodes(bool b=true) {_showNodes=!b;return *this;}
366 ///Sets the size of the node texts
368 ///Sets the size of the node texts
370 GraphToEps<T> &nodeTextSize(double d) {_nodeTextSize=d;return *this;}
371 ///Gives a preamble block for node Postscript block.
373 ///Gives a preamble block for node Postscript block.
376 GraphToEps<T> & nodePsTextsPreamble(const char *str) {
377 _nodePsTextsPreamble=s ;return *this;
379 ///Sets whether the the graph is undirected
381 ///Sets whether the the graph is undirected
383 GraphToEps<T> &undir(bool b=true) {_undir=b;return *this;}
384 ///Sets whether the the graph is directed
386 ///Sets whether the the graph is directed.
387 ///Use it to show the undirected edges as a pair of directed ones.
388 GraphToEps<T> &bidir(bool b=true) {_undir=!b;return *this;}
392 if(dontPrint) return;
394 os << "%!PS-Adobe-2.0 EPSF-2.0\n";
395 //\todo: Chech whether the graph is empty.
396 BoundingBox<double> bb;
397 for(NodeIt n(g);n!=INVALID;++n) {
398 double ns=_nodeSizes[n]*_nodeScale;
403 os << "%%BoundingBox: "
404 << bb.left()* _scale-_xBorder << ' '
405 << bb.bottom()*_scale-_yBorder << ' '
406 << bb.right()* _scale+_xBorder << ' '
407 << bb.top()* _scale+_yBorder << '\n';
408 //x1 y1 x2 y2 x3 y3 cr cg cb w
409 os << "/lb { setlinewidth setrgbcolor newpath moveto\n"
410 << " 4 2 roll 1 index 1 index curveto stroke } bind def\n";
411 os << "/l { setlinewidth setrgbcolor newpath moveto lineto stroke } bind def\n";
412 os << "/c { newpath dup 3 index add 2 index moveto 0 360 arc closepath } bind def\n";
414 os << "/n { setrgbcolor 2 index 2 index 2 index c fill\n"
415 << " 0 0 0 setrgbcolor dup "
416 << _nodeBorderQuotient << " mul setlinewidth "
417 << 1+_nodeBorderQuotient/2 << " div c stroke\n"
419 os << "/arrl " << _arrowLength << " def\n";
420 os << "/arrw " << _arrowWidth << " def\n";
422 os << "/lrl { 2 index mul exch 2 index mul exch rlineto pop} bind def\n";
423 //len w dx_norm dy_norm x1 y1 cr cg cb
424 os << "/arr { setrgbcolor /y1 exch def /x1 exch def /dy exch def /dx exch def\n"
425 << " /w exch def /len exch def\n"
426 // << " 0.1 setlinewidth x1 y1 moveto dx len mul dy len mul rlineto stroke"
427 << " newpath x1 dy w 2 div mul add y1 dx w 2 div mul sub moveto\n"
428 << " len w sub arrl sub dx dy lrl\n"
429 << " arrw dy dx neg lrl\n"
430 << " dx arrl w add mul dy w 2 div arrw add mul sub\n"
431 << " dy arrl w add mul dx w 2 div arrw add mul add rlineto\n"
432 << " dx arrl w add mul neg dy w 2 div arrw add mul sub\n"
433 << " dy arrl w add mul neg dx w 2 div arrw add mul add rlineto\n"
434 << " arrw dy dx neg lrl\n"
435 << " len w sub arrl sub neg dx dy lrl\n"
436 << " closepath fill } bind def\n";
437 os << "/cshow { 2 index 2 index moveto dup stringwidth pop\n"
438 << " neg 2 div fosi .35 mul neg rmoveto show pop pop} def\n";
441 if(_scale!=1.0) os << _scale << " dup scale\n";
444 os << "%Edges:\ngsave\n";
445 if(_enableParallel) {
446 std::vector<Edge> el;
447 for(EdgeIt e(g);e!=INVALID;++e)
448 if(!_undir||g.source(e)<g.target(e)) el.push_back(e);
449 sort(el.begin(),el.end(),edgeLess(g));
451 typename std::vector<Edge>::iterator j;
452 for(typename std::vector<Edge>::iterator i=el.begin();i!=el.end();i=j) {
453 for(j=i+1;j!=el.end()&&isParallel(*i,*j);++j) ;
456 for(typename std::vector<Edge>::iterator e=i;e!=j;++e)
457 sw+=_edgeWidths[*e]*_edgeWidthScale+_parEdgeDist;
460 xy<double> dvec(_coords[g.target(*i)]-_coords[g.source(*i)]);
461 double l=sqrt(dvec.normSquare());
462 xy<double> d(dvec/l);
464 // m=xy<double>(_coords[g.target(*i)]+_coords[g.source(*i)])/2.0;
466 // m=xy<double>(_coords[g.source(*i)])+
467 // dvec*(double(_nodeSizes[g.source(*i)])/
468 // (_nodeSizes[g.source(*i)]+_nodeSizes[g.target(*i)]));
470 m=xy<double>(_coords[g.source(*i)])+
471 d*(l+_nodeSizes[g.source(*i)]-_nodeSizes[g.target(*i)])/2.0;
473 for(typename std::vector<Edge>::iterator e=i;e!=j;++e) {
474 sw+=_edgeWidths[*e]*_edgeWidthScale/2.0;
475 xy<double> mm=m+rot(d)*sw/.75;
477 const int INERPOL_PREC=20;
478 xy<double> s=_coords[g.source(*e)];
479 xy<double> t=_coords[g.target(*e)];
480 double rn=_nodeSizes[g.target(*e)]*_nodeScale;
482 Bezier3 bez(s,mm,mm,t);
484 for(int i=0;i<INERPOL_PREC;++i)
485 if((bez((t1+t2)/2)-t).normSquare()>rn) t1=(t1+t2)/2;
487 xy<double> apoint=bez((t1+t2)/2);
488 rn = _nodeSizes[g.target(*e)]*_nodeScale+_arrowLength+
489 _edgeWidths[*e]*_edgeWidthScale;
492 for(int i=0;i<INERPOL_PREC;++i)
493 if((bez((t1+t2)/2)-t).normSquare()>rn) t1=(t1+t2)/2;
495 xy<double> linend=bez((t1+t2)/2);
496 bez=bez.before((t1+t2)/2);
497 rn=_nodeSizes[g.source(*e)]*_nodeScale; rn*=rn;
499 for(int i=0;i<INERPOL_PREC;++i)
500 if((bez((t1+t2)/2)-s).normSquare()>rn) t2=(t1+t2)/2;
502 bez=bez.after((t1+t2)/2);
503 os << _edgeWidths[*e]*_edgeWidthScale << " setlinewidth "
504 << _edgeColors[*e].getR() << ' '
505 << _edgeColors[*e].getG() << ' '
506 << _edgeColors[*e].getB() << " setrgbcolor newpath\n"
507 << bez.p1.x << ' ' << bez.p1.y << " moveto\n"
508 << bez.p2.x << ' ' << bez.p2.y << ' '
509 << bez.p3.x << ' ' << bez.p3.y << ' '
510 << bez.p4.x << ' ' << bez.p4.y << " curveto stroke\n";
511 xy<double> dd(rot(linend-apoint));
512 dd*=(_edgeWidths[*e]*_edgeWidthScale+_arrowWidth)/
513 sqrt(dd.normSquare());
514 os << "newpath " << psOut(apoint) << " moveto "
515 << psOut(linend+dd) << " lineto "
516 << psOut(linend-dd) << " lineto closepath fill\n";
519 os << _coords[g.source(*e)].x << ' '
520 << _coords[g.source(*e)].y << ' '
521 << mm.x << ' ' << mm.y << ' '
522 << _coords[g.target(*e)].x << ' '
523 << _coords[g.target(*e)].y << ' '
524 << _edgeColors[*e].getR() << ' '
525 << _edgeColors[*e].getG() << ' '
526 << _edgeColors[*e].getB() << ' '
527 << _edgeWidths[*e]*_edgeWidthScale << " lb\n";
529 sw+=_edgeWidths[*e]*_edgeWidthScale/2.0+_parEdgeDist;
533 else for(EdgeIt e(g);e!=INVALID;++e)
534 if(!_undir||g.source(e)<g.target(e))
536 xy<double> d(_coords[g.target(e)]-_coords[g.source(e)]);
537 double l=sqrt(d.normSquare());
539 xy<double> x1(d*_nodeScale*_nodeSizes[g.source(e)]+
540 _coords[g.source(e)]);
541 os << l-(_nodeSizes[g.source(e)]+
542 _nodeSizes[g.target(e)])*_nodeScale << ' '
543 << _edgeWidths[e]*_edgeWidthScale << ' '
544 << d.x << ' ' << d.y << ' '
545 << x1.x << ' ' << x1.y << ' '
546 << _edgeColors[e].getR() << ' '
547 << _edgeColors[e].getG() << ' '
548 << _edgeColors[e].getB() << " arr\n";
550 else os << _coords[g.source(e)].x << ' '
551 << _coords[g.source(e)].y << ' '
552 << _coords[g.target(e)].x << ' '
553 << _coords[g.target(e)].y << ' '
554 << _edgeColors[e].getR() << ' '
555 << _edgeColors[e].getG() << ' '
556 << _edgeColors[e].getB() << ' '
557 << _edgeWidths[e]*_edgeWidthScale << " l\n";
561 os << "%Nodes:\ngsave\n";
562 for(NodeIt n(g);n!=INVALID;++n)
563 os << _coords[n].x << ' ' << _coords[n].y << ' '
564 << _nodeSizes[n]*_nodeScale << ' '
565 << _nodeColors[n].getR() << ' '
566 << _nodeColors[n].getG() << ' '
567 << _nodeColors[n].getB() << " n\n";
571 os << "%Node texts:\ngsave\n";
572 os << "/fosi " << _nodeTextSize << " def\n";
573 os << "(Helvetica) findfont fosi scalefont setfont\n";
574 os << "0 0 0 setrgbcolor\n";
575 for(NodeIt n(g);n!=INVALID;++n)
576 os << _coords[n].x << ' ' << _coords[n].y
577 << " (" << _nodeTexts[n] << ") cshow\n";
580 if(_showNodePsText) {
581 os << "%Node PS blocks:\ngsave\n";
582 for(NodeIt n(g);n!=INVALID;++n)
583 os << _coords[n].x << ' ' << _coords[n].y
584 << " moveto\n" << _nodePsTexts[n] << "\n";
591 if(_pleaseRemoveOsStream) {delete &os;}
596 ///Generates an EPS file from a graph
599 ///Generates an EPS file from a graph.
600 ///\param g is a reference to the graph to be printed
601 ///\param os is a reference to the output stream.
602 ///By default it is <tt>std::cout</tt>
604 ///This function also has a lot of \ref named-templ-param "named parameters",
605 ///they are declared as the members of class \ref GraphToEps. The following
606 ///example shows how to use these parameters.
608 /// graphToEps(g).scale(10).coords(coords)
609 /// .nodeScale(2).nodeSizes(sizes)
610 /// .edgeWidthScale(.4);
613 ///\sa graphToEps(G &g, char *file_name)
615 GraphToEps<DefaultGraphToEpsTraits<G> >
616 graphToEps(G &g, std::ostream& os=std::cout)
619 GraphToEps<DefaultGraphToEpsTraits<G> >(DefaultGraphToEpsTraits<G>(g,os));
622 ///Generates an EPS file from a graph
625 ///This function does the same as
626 ///\ref graphToEps(G &g,std::ostream& os)
627 ///but it writes its output into the file \c file_name
628 ///instead of a stream.
629 ///\sa graphToEps(G &g, std::ostream& os)
631 GraphToEps<DefaultGraphToEpsTraits<G> >
632 graphToEps(G &g,char *file_name)
634 return GraphToEps<DefaultGraphToEpsTraits<G> >
635 (DefaultGraphToEpsTraits<G>(g,*new std::ofstream(file_name),true));
638 } //END OF NAMESPACE LEMON
640 #endif // LEMON_GRAPH_TO_EPS_H