Open
Graph Drawing
Framework

 v. 2023.09 (Elderberry)
 

RandomPointInPolygon.h
Go to the documentation of this file.
1 
31 #pragma once
32 
33 #ifdef OGDF_INCLUDE_CGAL
34 
40 
41 # include <random>
42 # include <vector>
43 
44 # include <CGAL/Triangle_2.h>
45 
46 namespace ogdf {
47 namespace internal {
48 namespace gcm {
49 namespace geometry {
50 
51 
54 template<typename Kernel>
55 Point_t<Kernel> random_point_in_polygon(const Polygon_t<Kernel>& polygon, std::mt19937_64& gen) {
56  auto triang = triangulation(polygon);
57  std::vector<double> weights; // index * 3 yields index in triang
58  std::vector<double> interval;
59  interval.push_back(0);
60 
61  for (unsigned int i = 0; i < triang.size(); i = i + 3) {
62  unsigned int a = triang[i];
63  unsigned int b = triang[i + 1];
64  unsigned int c = triang[i + 2];
65 
66  CGAL::Triangle_2<Kernel> t(polygon[a], polygon[b], polygon[c]);
67 
68  weights.push_back(CGAL::to_double(CGAL::abs(t.area())));
69 
70  interval.push_back(interval.back() + 1);
71  }
72 
73  // select triangle in polygon proportional to weight
74  std::piecewise_constant_distribution<double> dist(interval.begin(), interval.end(),
75  weights.begin());
76 
77  // barycenter coordinate at random -> random point in triangle
78  std::uniform_real_distribution<double> t_dist(0.0, 1.0);
79  double w_1 = t_dist(gen);
80  double w_2 = t_dist(gen);
81  double w_3 = t_dist(gen);
82  double n_w = w_1 + w_2 + w_3;
83 
84  using Vector = Vector_t<Kernel>;
85  using Point = Point_t<Kernel>;
86  Point p(0, 0);
87 
88 
89  unsigned tri_id = std::floor(dist(gen)) * 3;
90 
91  unsigned int a = triang[tri_id];
92  unsigned int b = triang[tri_id + 1];
93  unsigned int c = triang[tri_id + 2];
94  Vector v_1(p, polygon[a]);
95  Vector v_2(p, polygon[b]);
96  Vector v_3(p, polygon[c]);
97 
98  Vector v = (v_1 * w_1 + v_2 * w_2 + v_3 * w_3) * (1.0 / n_w);
99  Point r(v.x(), v.y());
100  return r;
101 }
102 
103 
104 }
105 }
106 }
107 }
108 
109 #endif
ogdf
The namespace for all OGDF objects.
Definition: multilevelmixer.cpp:39
Point.h
Vector.h
r
int r[]
Definition: hierarchical-ranking.cpp:13
RestrictedTriangulation.h
MapBoxTriangulation.h
Polygon.h
ogdf::gml::Key::Point
@ Point