#include "Graph.h" #include namespace Graph_lib { void Shape::draw_lines() const { if (color().visibility() && 1 line_intersect(Point p1, Point p2, Point p3, Point p4, bool& parallel) { double x1 = p1.x; double x2 = p2.x; double x3 = p3.x; double x4 = p4.x; double y1 = p1.y; double y2 = p2.y; double y3 = p3.y; double y4 = p4.y; double denom = ((y4 - y3)*(x2-x1) - (x4-x3)*(y2-y1)); if (denom == 0){ parallel= true; return pair{0,0}; } parallel = false; return pair{ ((x4-x3)*(y1-y3) - (y4-y3)*(x1-x3))/denom, ((x2-x1)*(y1-y3) - (y2-y1)*(x1-x3))/denom}; } //intersection between two line segments //Returns true if the two segments intersect, //in which case intersection is set to the point of intersection bool line_segment_intersect(Point p1, Point p2, Point p3, Point p4, Point& intersection) { bool parallel; pair u = line_intersect(p1,p2,p3,p4,parallel); if (parallel || u.first < 0 || u.first > 1 || u.second < 0 || u.second > 1) return false; intersection.x = static_cast(p1.x + u.first*(p2.x - p1.x)); intersection.y = static_cast(p1.y + u.first*(p2.y - p1.y)); return true; } void Polygon::add(Point p) { int np = number_of_points(); if (1 suffix_map; void init_suffix_map() // int init_suffix_map() { suffix_map["jpg"] = Suffix::jpg; suffix_map["JPG"] = Suffix::jpg; suffix_map["jpeg"] = Suffix::jpg; suffix_map["JPEG"] = Suffix::jpg; suffix_map["gif"] = Suffix::gif; suffix_map["GIF"] = Suffix::gif; suffix_map["bmp"] = Suffix::bmp; suffix_map["BMP"] = Suffix::bmp; // return 0; } Suffix::Encoding get_encoding(const string& s) // try to deduce type from file name using a lookup table { // static int x = init_suffix_map(); init_suffix_map(); string::const_iterator p = find(s.begin(),s.end(),'.'); if (p==s.end()) return Suffix::none; // no suffix string suf{p+1,s.end()}; return suffix_map[suf]; } bool can_open(const string& s) // check if a file named s exists and can be opened for reading { ifstream ff{ s.c_str() }; return bool(ff); } // somewhat overelaborate constructor // because errors related to image files can be such a pain to debug Image::Image(Point xy, string s, Suffix::Encoding e) :w{0}, h{0}, fn{xy,""} { add(xy); if (!can_open(s)) { fn.set_label("cannot open \""+s+'\"'); p = new Bad_image{30,20}; // the "error image" return; } if (e == Suffix::none) e = get_encoding(s); switch(e) { case Suffix::jpg: p = new Fl_JPEG_Image{s.c_str()}; break; case Suffix::gif: p = new Fl_GIF_Image{s.c_str()}; break; // case Suffix::bmp: // p = new Fl_BMP_Image(s.c_str()); // break; default: // Unsupported image encoding fn.set_label("unsupported file type \""+s+'\"'); p = new Bad_image{30,20}; // the "error image" } } void Image::draw_lines() const { if (fn.label()!="") fn.draw_lines(); if (w&&h) p->draw(point(0).x,point(0).y,w,h,cx,cy); else p->draw(point(0).x,point(0).y); } } // Graph