Coverage for pygeodesy/clipy.py: 96%

316 statements  

« prev     ^ index     » next       coverage.py v7.10.7, created at 2026-03-25 15:01 -0400

1 

2# -*- coding: utf-8 -*- 

3 

4u'''Clip a path or polygon of C{LatLon} points against a rectangular box or 

5an arbitrary (convex) region. 

6 

7Box clip functions L{clipCS4} I{Cohen-Sutherland} and L{clipLB6} I{Liang-Barsky}, 

8region clip functions L{clipFHP4} I{Foster-Hormann-Popa}, L{clipGH4} 

9I{Greiner-Hormann} and L{clipSH} and L{clipSH3} I{Sutherland-Hodgeman}. 

10. 

11''' 

12# make sure int/int division yields float quotient, see .basics 

13from __future__ import division as _; del _ # noqa: E702 ; 

14 

15from pygeodesy.basics import len2, typename 

16from pygeodesy.constants import EPS, _0_0, _1_0 

17from pygeodesy.errors import _AssertionError, ClipError, PointsError 

18from pygeodesy.fmath import fabs, Fsum 

19# from pygeodesy.fsums import Fsum # from .fmath 

20# from pygeodesy.internals import typename # from .basics 

21from pygeodesy.interns import NN, _clipid_, _convex_, _DOT_, _end_, _few_, \ 

22 _fi_, _height_, _i_, _invalid_, _j_, _lat_, \ 

23 _lon_, _near_, _not_, _points_, _start_, _too_ 

24from pygeodesy.iters import _imdex2, points2 

25from pygeodesy.lazily import _ALL_LAZY, _ALL_MODS as _MODS 

26from pygeodesy.named import _Named, _NamedTuple, _Pass, Property_RO 

27from pygeodesy.points import areaOf, boundsOf, isconvex_, LatLon_ 

28# from pygeodesy.props import Property_RO # from .named 

29from pygeodesy.units import Bool, FIx, HeightX, Lat, Lon, Number_ 

30 

31# from math import fabs # from .fmath 

32 

33__all__ = _ALL_LAZY.clipy 

34__version__ = '25.10.30' 

35 

36_fj_ = 'fj' 

37_original_ = 'original' 

38 

39 

40def _box4(lowerleft, upperight, name): 

41 '''(INTERNAL) Get the clip box edges. 

42 

43 @see: Class C{_Box} in .ellipsoidalBaseDI.py. 

44 ''' 

45 try: 

46 yb, yt = lowerleft.lat, upperight.lat 

47 xl, xr = lowerleft.lon, upperight.lon 

48 if xl > xr or yb > yt: 

49 raise ValueError(_invalid_) 

50 except (AttributeError, TypeError, ValueError) as x: 

51 raise ClipError(name, 2, (lowerleft, upperight), cause=x) 

52 return xl, yb, xr, yt 

53 

54 

55def _4corners(corners): 

56 '''(INTERNAL) Clip region or box. 

57 ''' 

58 n, cs = len2(corners) 

59 if n == 2: # make a box 

60 yb, xl, yt, xr = boundsOf(cs, wrap=False) 

61 cs = (LatLon_(yb, xl), LatLon_(yt, xl), 

62 LatLon_(yt, xr), LatLon_(yb, xr)) 

63 return cs 

64 

65 

66def _eq(p1, p2, eps=EPS): 

67 '''(INTERNAL) Check for near-equal points. 

68 ''' 

69 return not _neq(p1, p2, eps) 

70 

71 

72def _neq(p1, p2, eps=EPS): 

73 '''(INTERNAL) Check for not near-equal points. 

74 ''' 

75 return fabs(p1.lat - p2.lat) > eps or \ 

76 fabs(p1.lon - p2.lon) > eps 

77 

78 

79def _pts2(points, closed, inull): 

80 '''(INTERNAL) Get the points to clip as a list. 

81 ''' 

82 if closed and inull: 

83 n, pts = len2(points) 

84 # only remove the final, closing point 

85 if n > 1 and _eq(pts[n-1], pts[0]): 

86 n -= 1 

87 pts = pts[:n] 

88 if n < 2: 

89 raise PointsError(points=n, txt=_too_(_few_)) 

90 else: 

91 n, pts = points2(points, closed=closed) 

92 return n, list(pts) 

93 

94 

95class _CS(_Named): 

96 '''(INTERNAL) Cohen-Sutherland line clipping. 

97 ''' 

98 # single-bit clip codes 

99 _IN = 0 # inside clip box 

100 _XR = 1 # right of upperight.lon 

101 _XL = 2 # left of lowerleft.lon 

102 _YT = 4 # above upperight.lat 

103 _YB = 8 # below lowerleft.lat 

104 

105 _dx = _0_0 # pts edge delta lon 

106 _dy = _0_0 # pts edge delta lat 

107 _x1 = _0_0 # pts corner 

108 _y1 = _0_0 # pts corner 

109 

110 _xr = _0_0 # clip box upperight.lon 

111 _xl = _0_0 # clip box lowerleft.lon 

112 _yt = _0_0 # clip box upperight.lat 

113 _yb = _0_0 # clip box lowerleft.lat 

114 

115 def __init__(self, lowerleft, upperight, name=__name__): 

116 self._xl, self._yb, \ 

117 self._xr, self._yt = _box4(lowerleft, upperight, name) 

118 self.name = name 

119 

120# def clip4(self, p, c): # clip point p for code c 

121# if c & _CS._YB: 

122# return self.lon4(p, self._yb) 

123# elif c & _CS._YT: 

124# return self.lon4(p, self._yt) 

125# elif c & _CS._XL: 

126# return self.lat4(p, self._xl) 

127# elif c & _CS._XR: 

128# return self.lat4(p, self._xr) 

129# # should never get here 

130# raise _AssertionError(self._DOT_(typename(self.clip4))) 

131 

132 def code4(self, p): # compute code for point p 

133 if p.lat < self._yb: 

134 c, m, b = _CS._YB, self.lon4, self._yb 

135 elif p.lat > self._yt: 

136 c, m, b = _CS._YT, self.lon4, self._yt 

137 else: 

138 c, m, b = _CS._IN, self.nop4, None 

139 if p.lon < self._xl: 

140 c |= _CS._XL 

141 m, b = self.lat4, self._xl 

142 elif p.lon > self._xr: 

143 c |= _CS._XR 

144 m, b = self.lat4, self._xr 

145 return c, m, b, p 

146 

147 def edge(self, p1, p2): # set edge p1 to p2 

148 self._y1, self._dy = p1.lat, float(p2.lat - p1.lat) 

149 self._x1, self._dx = p1.lon, float(p2.lon - p1.lon) 

150 return fabs(self._dx) > EPS or fabs(self._dy) > EPS 

151 

152 def lat4(self, x, p): # new lat and code at lon x 

153 y = self._y1 + self._dy * float(x - self._x1) / self._dx 

154 if y < self._yb: # still outside 

155 return _CS._YB, self.lon4, self._yb, p 

156 elif y > self._yt: # still outside 

157 return _CS._YT, self.lon4, self._yt, p 

158 else: # inside 

159 return _CS._IN, self.nop4, None, p.classof(y, x) 

160 

161 def lon4(self, y, p): # new lon and code at lat y 

162 x = self._x1 + self._dx * float(y - self._y1) / self._dy 

163 if x < self._xl: # still outside 

164 return _CS._XL, self.lat4, self._xl, p 

165 elif x > self._xr: # still outside 

166 return _CS._XR, self.lat4, self._xr, p 

167 else: # inside 

168 return _CS._IN, self.nop4, None, p.classof(y, x) 

169 

170 def nop4(self, b, p): # PYCHOK no cover 

171 if p: # should never get here 

172 raise _AssertionError(self._DOT_(typename(self.nop4))) 

173 return _CS._IN, self.nop4, b, p 

174 

175 

176class ClipCS4Tuple(_NamedTuple): 

177 '''4-Tuple C{(start, end, i, j)} for each edge of a I{clipped} 

178 path with the C{start} and C{end} points (C{LatLon}) of the 

179 portion of the edge inside or on the clip box and the indices 

180 C{i} and C{j} (C{int}) of the edge start and end points in 

181 the original path. 

182 ''' 

183 _Names_ = (_start_, _end_, _i_, _j_) 

184 _Units_ = (_Pass, _Pass, Number_, Number_) 

185 

186 

187def clipCS4(points, lowerleft, upperight, closed=False, inull=False): 

188 '''Clip a path against a rectangular clip box using the U{Cohen-Sutherland 

189 <https://WikiPedia.org/wiki/Cohen-Sutherland_algorithm>} algorithm. 

190 

191 @arg points: The points (C{LatLon}[]). 

192 @arg lowerleft: Bottom-left corner of the clip box (C{LatLon}). 

193 @arg upperight: Top-right corner of the clip box (C{LatLon}). 

194 @kwarg closed: Optionally, close the path (C{bool}). 

195 @kwarg inull: Optionally, retain null edges if inside (C{bool}). 

196 

197 @return: Yield a L{ClipCS4Tuple}C{(start, end, i, j)} for each 

198 edge of the I{clipped} path. 

199 

200 @raise ClipError: The B{C{lowerleft}} and B{C{upperight}} corners 

201 specify an invalid clip box. 

202 

203 @raise PointsError: Insufficient number of B{C{points}}. 

204 ''' 

205 T4 = ClipCS4Tuple 

206 cs = _CS(lowerleft, upperight, name=typename(clipCS4)) 

207 n, pts = _pts2(points, closed, inull) 

208 

209 i, m = _imdex2(closed, n) 

210 cmbp = cs.code4(pts[i]) 

211 for j in range(m, n): 

212 c1, m1, b1, p1 = cmbp 

213 c2, m2, b2, p2 = cmbp = cs.code4(pts[j]) 

214 if c1 & c2: # edge outside 

215 pass 

216 elif cs.edge(p1, p2): 

217 for _ in range(5): 

218 if c1: # clip p1 

219 c1, m1, b1, p1 = m1(b1, p1) 

220 elif c2: # clip p2 

221 c2, m2, b2, p2 = m2(b2, p2) 

222 else: # inside 

223 if inull or _neq(p1, p2): 

224 yield T4(p1, p2, i, j) 

225 break 

226 if c1 & c2: # edge outside 

227 break 

228 else: # PYCHOK no cover 

229 raise _AssertionError(_DOT_(cs.name, 'for_else')) 

230 

231 elif inull and not c1: # null edge 

232 yield T4(p1, p1, i, j) 

233 elif inull and not c2: 

234 yield T4(p2, p2, i, j) 

235 

236 i = j 

237 

238 

239class ClipFHP4Tuple(_NamedTuple): 

240 '''4-Tuple C{(lat, lon, height, clipid)} for each point of the L{clipFHP4} result 

241 with the C{lat}-, C{lon}gitude, C{height} and C{clipid} of the polygon or clip. 

242 

243 @note: The C{height} is a L{HeightX} instance if this point is 

244 an intersection, otherwise a L{Height} or C{int(0)}. 

245 ''' 

246 _Names_ = (_lat_, _lon_, _height_, _clipid_) 

247 _Units_ = ( Lat, Lon, _Pass, Number_) 

248 

249 @Property_RO 

250 def isintersection(self): 

251 '''Is this an intersection? 

252 ''' 

253 return isinstance(self.height, HeightX) 

254 

255 @Property_RO 

256 def ispoint(self): 

257 '''Is this an original (polygon) point? 

258 ''' 

259 return not self.isintersection 

260 

261 

262def clipFHP4(points, corners, closed=False, inull=False, raiser=False, eps=EPS): 

263 '''Clip one or more polygons against a clip region or box using U{Forster-Hormann-Popa 

264 <https://www.ScienceDirect.com/science/article/pii/S259014861930007X>}'s C++ 

265 implementation transcoded to pure Python. 

266 

267 @arg points: The polygon points and clips (C{LatLon}[]). 

268 @arg corners: Three or more points defining the clip regions (C{LatLon}[]) 

269 or two points to specify a single, rectangular clip box. 

270 @kwarg closed: If C{True}, close each result clip (C{bool}). 

271 @kwarg inull: If C{True}, retain null edges in result clips (C{bool}). 

272 @kwarg raiser: If C{True}, throw L{ClipError} exceptions (C{bool}). 

273 @kwarg esp: Tolerance for eliminating null edges (C{degrees}, same units 

274 as the B{C{points}} and B{C{corners}} coordinates). 

275 

276 @return: Yield a L{ClipFHP4Tuple}C{(lat, lon, height, clipid)} for each 

277 clipped point. The result may consist of several I{clips}, each 

278 a (closed) polygon with a unique C{clipid} identifier. 

279 

280 @raise ClipError: Insufficient B{C{points}} or B{C{corners}} or an open clip. 

281 

282 @see: U{Forster, Hormann and Popa<https://www.ScienceDirect.com/science/ 

283 article/pii/S259014861930007X>} and class L{BooleanFHP}. 

284 ''' 

285 P = _MODS.booleans._CompositeFHP(points, kind=_points_, raiser=raiser, 

286 eps=eps, name__=clipFHP4) 

287 Q = _4corners(corners) 

288 return P._clip(Q, Union=False, Clas=ClipFHP4Tuple, closed=closed, 

289 inull=inull, raiser=P._raiser, eps=eps) 

290 

291 

292class ClipGH4Tuple(ClipFHP4Tuple): 

293 '''4-Tuple C{(lat, lon, height, clipid)} for each point of the L{clipGH4} result 

294 with the C{lat}-, C{lon}gitude, C{height} and C{clipid} of the polygon or clip. 

295 

296 @note: The C{height} is a L{HeightX} instance if this is an intersection, 

297 otherwise a L{Height} or C{int(0)}. 

298 ''' 

299 _Names_ = ClipFHP4Tuple._Names_ 

300 _Units_ = ClipFHP4Tuple._Units_ 

301 

302 

303def clipGH4(points, corners, closed=False, inull=False, raiser=True, xtend=False, eps=EPS): 

304 '''Clip one or more polygons against a clip region or box using the U{Greiner-Hormann 

305 <http://www.Inf.USI.CH/hormann/papers/Greiner.1998.ECO.pdf>} algorithm, extended. 

306 

307 @arg points: The polygon points and clips (C{LatLon}[]). 

308 @arg corners: Three or more points defining the clip regions (C{LatLon}[]) 

309 or two points to specify a single, rectangular clip box. 

310 @kwarg closed: If C{True}, close each result clip (C{bool}). 

311 @kwarg inull: If C{True}, retain null edges in result clips (C{bool}). 

312 @kwarg raiser: If C{True}, throw L{ClipError} exceptions (C{bool}). 

313 @kwarg xtend: If C{True}, extend edges of I{degenerate cases}, an attempt 

314 to handle the latter (C{bool}). 

315 @kwarg esp: Tolerance for eliminating null edges (C{degrees}, same units 

316 as the B{C{points}} and B{C{corners}} coordinates). 

317 

318 @return: Yield a L{ClipGH4Tuple}C{(lat, lon, height, clipid)} for each 

319 clipped point. The result may consist of several I{clips}, each 

320 a (closed) polygon with a unique C{clipid} identifier. 

321 

322 @raise ClipError: Insufficient B{C{points}} or B{C{corners}}, an open clip, 

323 a I{degenerate case} or I{unhandled} intersection. 

324 

325 @note: To handle I{degenerate cases} like C{point-edge} and C{point-point} 

326 intersections I{properly}, use function L{clipFHP4}. 

327 

328 @see: U{Greiner-Hormann<https://WikiPedia.org/wiki/Greiner–Hormann_clipping_algorithm>} 

329 and class L{BooleanGH}. 

330 ''' 

331 S = _MODS.booleans._CompositeGH(points, raiser=raiser, xtend=xtend, eps=eps, 

332 name__=clipGH4, kind=_points_) 

333 C = _4corners(corners) 

334 return S._clip(C, False, False, Clas=ClipGH4Tuple, closed=closed, inull=inull, 

335 raiser=S._raiser, xtend=S._xtend, eps=eps) 

336 

337 

338def _LBtrim(p, q, t): 

339 # Liang-Barsky trim t[0] or t[1] 

340 if p < 0: 

341 r = q / p 

342 if r > t[1]: 

343 return False # too far above 

344 elif r > t[0]: 

345 t[0] = r 

346 elif p > 0: 

347 r = q / p 

348 if r < t[0]: 

349 return False # too far below 

350 elif r < t[1]: 

351 t[1] = r 

352 elif q < 0: # vertical or horizontal 

353 return False # ... outside 

354 return True 

355 

356 

357class ClipLB6Tuple(_NamedTuple): 

358 '''6-Tuple C{(start, end, i, fi, fj, j)} for each edge of the 

359 I{clipped} path with the C{start} and C{end} points (C{LatLon}) 

360 of the portion of the edge inside or on the clip box, indices 

361 C{i} and C{j} (both C{int}) of the original path edge start 

362 and end points and I{fractional} indices C{fi} and C{fj} 

363 (both L{FIx}) of the C{start} and C{end} points along the 

364 edge of the original path. 

365 

366 @see: Class L{FIx} and function L{pygeodesy.fractional}. 

367 ''' 

368 _Names_ = (_start_, _end_, _i_, _fi_, _fj_, _j_) 

369 _Units_ = (_Pass, _Pass, Number_, _Pass, _Pass, Number_) 

370 

371 

372def clipLB6(points, lowerleft, upperight, closed=False, inull=False): 

373 '''Clip a path against a rectangular clip box using the U{Liang-Barsky 

374 <https://www.CSE.UNT.edu/~renka/4230/LineClipping.pdf>} algorithm. 

375 

376 @arg points: The points (C{LatLon}[]). 

377 @arg lowerleft: Bottom-left corner of the clip box (C{LatLon}). 

378 @arg upperight: Top-right corner of the clip box (C{LatLon}). 

379 @kwarg closed: Optionally, close the path (C{bool}). 

380 @kwarg inull: Optionally, retain null edges if inside (C{bool}). 

381 

382 @return: Yield a L{ClipLB6Tuple}C{(start, end, i, fi, fj, j)} for 

383 each edge of the I{clipped} path. 

384 

385 @raise ClipError: The B{C{lowerleft}} and B{C{upperight}} corners 

386 specify an invalid clip box. 

387 

388 @raise PointsError: Insufficient number of B{C{points}}. 

389 

390 @see: U{Liang-Barsky Line Clipping<https://www.CS.Helsinki.FI/group/goa/ 

391 viewing/leikkaus/intro.html>}, U{Liang-Barsky line clipping algorithm 

392 <https://www.Skytopia.com/project/articles/compsci/clipping.html>} and 

393 U{Liang-Barsky algorithm<https://WikiPedia.org/wiki/Liang-Barsky_algorithm>}. 

394 ''' 

395 xl, yb, \ 

396 xr, yt = _box4(lowerleft, upperight, typename(clipLB6)) 

397 n, pts = _pts2(points, closed, inull) 

398 

399 T6 = ClipLB6Tuple 

400 fin = n if closed else None # wrapping fi [n] to [0] 

401 _LB = _LBtrim 

402 

403 i, m = _imdex2(closed, n) 

404 for j in range(m, n): 

405 p1 = pts[i] 

406 y1 = p1.lat 

407 x1 = p1.lon 

408 

409 p2 = pts[j] 

410 dy = float(p2.lat - y1) 

411 dx = float(p2.lon - x1) 

412 if fabs(dx) > EPS or fabs(dy) > EPS: 

413 # non-null edge pts[i]...pts[j] 

414 t = [_0_0, _1_0] 

415 if _LB(-dx, -xl + x1, t) and \ 

416 _LB( dx, xr - x1, t) and \ 

417 _LB(-dy, -yb + y1, t) and \ 

418 _LB( dy, yt - y1, t): 

419 # clip edge pts[i]...pts[j] 

420 # at fractions t[0] to t[1] 

421 f, t = t 

422 if f > _0_0: # EPS 

423 p1 = p1.classof(y1 + f * dy, 

424 x1 + f * dx) 

425 fi = i + f 

426 else: 

427 fi = i 

428 

429 if (t - f) > EPS: # EPS0 

430 if t < _1_0: # EPS1 

431 p2 = p2.classof(y1 + t * dy, 

432 x1 + t * dx) 

433 fj = i + t 

434 else: 

435 fj = j 

436 fi = FIx(fi, fin=fin) 

437 fj = FIx(fj, fin=fin) 

438 yield T6(p1, p2, i, fi, fj, j) 

439 

440 elif inull: 

441 fi = FIx(fi, fin=fin) 

442 yield T6(p1, p1, i, fi, fi, j) 

443# else: # outside 

444# pass 

445 elif inull: # null edge 

446 yield T6(p1, p2, i, FIx(i, fin=fin), 

447 FIx(j, fin=fin), j) 

448 i = j 

449 

450 

451class _SH(_Named): 

452 '''(INTERNAL) Sutherland-Hodgman polyon clipping. 

453 ''' 

454 _cs = () # clip corners 

455 _cw = 0 # counter-/clockwise 

456 _ccw = 0 # clock-/counterwise 

457 _dx = _0_0 # clip edge[e] delta lon 

458 _dy = _0_0 # clip edge[e] delta lat 

459 _nc = 0 # len(._cs) 

460 _x1 = _0_0 # clip edge[e] lon origin 

461 _xy = _0_0 # see .clipedges 

462 _y1 = _0_0 # clip edge[e] lat origin 

463 

464 def __init__(self, corners, name=__name__): 

465 n, cs = 0, corners 

466 try: # check the clip box/region 

467 cs = _4corners(cs) 

468 n, cs = len2(cs) 

469 n, cs = points2(cs, closed=True) 

470 self._cs = cs = cs[:n] 

471 self._nc = n 

472 self._cw = isconvex_(cs, adjust=False, wrap=False) 

473 if not self._cw: 

474 raise ValueError(_not_(_convex_)) 

475 if areaOf(cs, adjust=True, radius=1, wrap=True) < EPS: 

476 raise ValueError(NN(_near_, 'zero area')) 

477 self._ccw = -self._cw 

478 except (PointsError, TypeError, ValueError) as x: 

479 raise ClipError(name, n, cs, cause=x) 

480 self.name = name 

481 

482 def clip2(self, points, closed, inull): # MCCABE 13, clip points 

483 np, pts = _pts2(points, closed, inull) 

484 pcs = _SHlist(inull) # clipped points 

485 _ap = pcs.append 

486 _d2 = self.dot2 

487 _in = self.intersect 

488 

489 ne = 0 # number of non-null clip edges 

490 for e in self.clipedges(): 

491 ne += 1 # non-null clip edge 

492 

493 # clip points, closed always 

494 d1, p1 = _d2(pts[np - 1]) 

495 for i in range(np): 

496 d2, p2 = _d2(pts[i]) 

497 if d1 < 0: # p1 inside, p2 ... 

498 # _ap(p1) 

499 _ap(p2 if d2 < 0 else # ... in- 

500 _in(p1, p2, e)) # ... outside 

501 elif d2 < 0: # p1 out-, p2 inside 

502 _ap(_in(p1, p2, e)) 

503 _ap(p2) 

504# elif d1 > 0: # both outside 

505# pass 

506 d1, p1 = d2, p2 

507 

508 # replace points, in-place 

509 pts[:] = pcs 

510 pcs[:] = [] 

511 np = len(pts) 

512 if not np: # all outside 

513 break 

514 else: 

515 if ne < 3: 

516 raise ClipError(self.name, ne, self._cs, txt=_too_(_few_)) 

517 

518 if np > 1: 

519 p = pts[0] 

520 if closed: # close clipped pts 

521 if _neq(pts[np - 1], p): 

522 pts.append(p) 

523 np += 1 

524 elif not inull: # open clipped pts 

525 while np > 0 and _eq(pts[np - 1], p): 

526 pts.pop() 

527 np -= 1 

528 # assert len(pts) == np 

529 return np, pts 

530 

531 def clipedges(self): # yield clip edge index 

532 # and set self._x1, ._y1, ._dx, ._dy and 

533 # ._xy for each non-null clip edge 

534 nc = self._nc 

535 cs = self._cs 

536 c = cs[nc - 1] 

537 for e in range(nc): 

538 y, x, c = c.lat, c.lon, cs[e] 

539 dy = float(c.lat - y) 

540 dx = float(c.lon - x) 

541 if fabs(dx) > EPS or fabs(dy) > EPS: 

542 self._y1, self._dy = y, dy 

543 self._x1, self._dx = x, dx 

544 self._xy = y * dx - x * dy 

545 yield e + 1 

546 

547 def clipped2(self, p): # return (clipped point [i], edge) 

548 if isinstance(p, _SHlli): # intersection point 

549 return p.classof(p.lat, p.lon), p.edge 

550 else: # original point 

551 return p, 0 

552 

553 def dot2(self, p): # dot product of point p to clip 

554 # corner c1 and clip edge c1 to c2, indicating where 

555 # point p is located: to the right, to the left or 

556 # on top of the (extended) clip edge from c1 to c2 

557 d = float(p.lat - self._y1) * self._dx - \ 

558 float(p.lon - self._x1) * self._dy 

559 # clockwise corners, +1 means point p is to the right 

560 # of, -1 means on the left of, 0 means on edge c1 to c2 

561 d = self._ccw if d < 0 else (self._cw if d > 0 else 0) 

562 return d, p 

563 

564 def intersect(self, p1, p2, edge): # compute intersection 

565 # of polygon edge p1 to p2 and the current clip edge, 

566 # where p1 and p2 are known to NOT be located on the 

567 # same side of or on the current, non-null clip edge 

568 # <https://StackOverflow.com/questions/563198/ 

569 # how-do-you-detect-where-two-line-segments-intersect> 

570 y, dy = p1.lat, self._dy 

571 x, dx = p1.lon, self._dx 

572 fy = float(p2.lat - y) 

573 fx = float(p2.lon - x) 

574 d = fy * dx - fx * dy # fdot((fx, fy), dx, -dy) 

575 if fabs(d) < EPS: # PYCHOK no cover 

576 raise _AssertionError(self._DOT_(typename(self.intersect))) 

577 d = Fsum(self._xy, -y * dx, x * dy).fover(d) 

578 y += d * fy 

579 x += d * fx 

580 return _SHlli(y, x, p1.classof, edge) 

581 

582 

583class _SHlist(list): 

584 '''(INTERNAL) List of _SH clipped points. 

585 ''' 

586 _inull = False 

587 

588 def __init__(self, inull): 

589 self._inull = inull 

590 list.__init__(self) 

591 

592 def append(self, p): 

593 if (not self) or self._inull or _neq(p, self[-1]): 

594 list.append(self, p) 

595 

596 

597class _SHlli(LatLon_): 

598 '''(INTERNAL) LatLon_ for _SH intersections. 

599 ''' 

600 # __slots__ are no longer space savers, see 

601 # the comments at the class .points.LatLon_ 

602 # __slots__ = _lat_, _lon_, 'classof', 'edge', _name_ 

603 

604 def __init__(self, lat, lon, classof, edge): 

605 self.lat = lat 

606 self.lon = lon 

607 self.classof = classof 

608 self.edge = edge # clip edge 

609 self.name = NN 

610 

611 

612class ClipSH3Tuple(_NamedTuple): 

613 '''3-Tuple C{(start, end, original)} for each edge of a I{clipped} 

614 polygon, the C{start} and C{end} points (C{LatLon}) of the 

615 portion of the edge inside or on the clip region and C{original} 

616 indicates whether the edge is part of the original polygon or 

617 part of the clip region (C{bool}). 

618 ''' 

619 _Names_ = (_start_, _end_, _original_) 

620 _Units_ = (_Pass, _Pass, Bool) 

621 

622 

623def clipSH(points, corners, closed=False, inull=False): 

624 '''Clip a polygon against a clip region or box using the U{Sutherland-Hodgman 

625 <https://WikiPedia.org/wiki/Sutherland-Hodgman_algorithm>} algorithm. 

626 

627 @arg points: The polygon points (C{LatLon}[]). 

628 @arg corners: Three or more points defining a convex clip 

629 region (C{LatLon}[]) or two points to specify 

630 a rectangular clip box. 

631 @kwarg closed: Close the clipped points (C{bool}). 

632 @kwarg inull: Optionally, include null edges (C{bool}). 

633 

634 @return: Yield the clipped points (C{LatLon}[]). 

635 

636 @raise ClipError: The B{C{corners}} specify a polar, zero-area, 

637 non-convex or otherwise invalid clip box or 

638 region. 

639 

640 @raise PointsError: Insufficient number of B{C{points}}. 

641 ''' 

642 sh = _SH(corners, name=typename(clipSH)) 

643 n, pts = sh.clip2(points, closed, inull) 

644 for i in range(n): 

645 p, _ = sh.clipped2(pts[i]) 

646 yield p 

647 

648 

649def clipSH3(points, corners, closed=False, inull=False): 

650 '''Clip a polygon against a clip region or box using the U{Sutherland-Hodgman 

651 <https://WikiPedia.org/wiki/Sutherland-Hodgman_algorithm>} algorithm. 

652 

653 @arg points: The polygon points (C{LatLon}[]). 

654 @arg corners: Three or more points defining a convex clip 

655 region (C{LatLon}[]) or two points to specify 

656 a rectangular clip box. 

657 @kwarg closed: Close the clipped points (C{bool}). 

658 @kwarg inull: Optionally, include null edges (C{bool}). 

659 

660 @return: Yield a L{ClipSH3Tuple}C{(start, end, original)} for 

661 each edge of the I{clipped} polygon. 

662 

663 @raise ClipError: The B{C{corners}} specify a polar, zero-area, 

664 non-convex or otherwise invalid clip box or 

665 region. 

666 

667 @raise PointsError: Insufficient number of B{C{points}} or B{C{corners}}. 

668 ''' 

669 sh = _SH(corners, name=typename(clipSH3)) 

670 n, pts = sh.clip2(points, closed, inull) 

671 if n > 1: 

672 T3 = ClipSH3Tuple 

673 p1, e1 = sh.clipped2(pts[0]) 

674 for i in range(1, n): 

675 p2, e2 = sh.clipped2(pts[i]) 

676 yield T3(p1, p2, not bool(e1 and e2 and e1 == e2)) 

677 p1, e1 = p2, e2 

678 

679# **) MIT License 

680# 

681# Copyright (C) 2018-2026 -- mrJean1 at Gmail -- All Rights Reserved. 

682# 

683# Permission is hereby granted, free of charge, to any person obtaining a 

684# copy of this software and associated documentation files (the "Software"), 

685# to deal in the Software without restriction, including without limitation 

686# the rights to use, copy, modify, merge, publish, distribute, sublicense, 

687# and/or sell copies of the Software, and to permit persons to whom the 

688# Software is furnished to do so, subject to the following conditions: 

689# 

690# The above copyright notice and this permission notice shall be included 

691# in all copies or substantial portions of the Software. 

692# 

693# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 

694# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 

695# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 

696# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR 

697# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 

698# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 

699# OTHER DEALINGS IN THE SOFTWARE.