1

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

3

4 u'''I{Boolean} operations on I{composite} polygons and I{clip}s.

5

6 Classes L{BooleanFHP} and L{BooleanGH} are I{composites} and

7 provide I{boolean} operations C{intersection}, C{difference},

8 C{reverse-difference}, C{sum} and C{union}.

9

10@note: A I{clip} is defined as a single, usually closed polygon,

11 a I{composite} is a collection of one or more I{clip}s.

12

13@see: U{Forster-Hormann-Popa<https://www.ScienceDirect.com/science/

14 article/pii/S259014861930007X>} and U{Greiner-Hormann

15 <http://www.Inf.USI.CH/hormann/papers/Greiner.1998.ECO.pdf>}.

16'''

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

18 from __future__ import division as _; del _ # PYCHOK semicolon

19

20 from pygeodesy.basics import isodd, issubclassof, map2, _xscalar

21 from pygeodesy.constants import EPS, EPS2, INT0, _0_0, _0_5, _1_0

22 from pygeodesy.errors import ClipError, _IsnotError, _TypeError, \

23 _ValueError, _xattr, _xkwds_get, _xkwds_pop2

24 from pygeodesy.fmath import favg, hypot, hypot2

25# from pygeodesy.fsums import fsum1 # _MODS

26 from pygeodesy.interns import NN, _BANG_, _clip_, _clipid_, _COMMASPACE_, \

27 _composite_, _DOT_, _duplicate_, _e_, \

28 _ELLIPSIS_, _few_, _height_, _lat_, _LatLon_, \

29 _lon_, _not_, _points_, _SPACE_, _too_, _X_, \

30 _x_, _B_, _d_, _R_ # PYCHOK used!

31 from pygeodesy.lazily import _ALL_DOCS, _ALL_LAZY, _ALL_MODS as _MODS

32 from pygeodesy.latlonBase import LatLonBase, \

33 LatLon2Tuple, Property_RO, property_RO

34 from pygeodesy.named import _name__, _Named, _NotImplemented, \

35 Fmt, pairs, unstr

36# from pygeodesy.namedTuples import LatLon2Tupe # from .latlonBase

37# from pygeodesy.points import boundsOf # _MODS

38# from pygeodesy.props import Property_RO, property_RO # from .latlonBase

39# from pygeodesy.streprs import Fmt, pairs, unstr # from .named

40 from pygeodesy.units import Height, HeightX

41 from pygeodesy.utily import fabs, _unrollon, _Wrap

42

43# from math import fabs # from .utily

44

45__all__ = _ALL_LAZY.booleans

46__version__ = '24.09.28'

47

48_0_EPS = EPS # near-zero, positive

49_EPS_0 = -EPS # near-zero, negative

50_1_EPS = _1_0 + EPS # near-one, over

51_EPS_1 = _1_0 - EPS # near-one, under

52_10EPS = EPS * 10 # see ._2Abs, ._10eps

53

54_alpha_ = 'alpha'

55_boolean_ = 'boolean'

56_case_ = 'case'

57_corners_ = 'corners'

58_open_ = 'open'

59

60

61 def _Enum(txt, enum): # PYCHOK unused

62 return txt # NN(txt, _TILDE_, enum)

63

64

65 class _L(object): # Intersection labels

66 CROSSING = _Enum(_X_, 1) # C++ enum

67 CROSSING_D = _Enum(_X_ + _d_, 8)

68 CROSSINGs = (CROSSING, CROSSING_D)

69 BOUNCING = _Enum(_B_, 2)

70 BOUNCING_D = _Enum(_B_ + _d_, 9)

71 BOUNCINGs = (BOUNCING, BOUNCING_D) + CROSSINGs

72 LEFT_ON = _Enum('Lo', 3)

73 ON_ON = _Enum('oo', 5)

74 ON_LEFT = _Enum('oL', 6)

75 ON_RIGHT = _Enum('oR', 7)

76 RIGHT_ON = _Enum('Ro', 4)

77 RIGHT_LEFT_ON = (RIGHT_ON, LEFT_ON)

78 # Entry/Exit flags

79 ENTRY = _Enum(_e_, 1)

80 EXIT = _Enum(_x_, 0)

81 Toggle = {ENTRY: EXIT,

82 EXIT: ENTRY,

83 None: None}

84

85_L = _L() # PYCHOK singleton

86

87

88 class _RP(object): # RelativePositions

89 IS_Pm = _Enum('Pm', 2) # C++ enum

90 IS_Pp = _Enum('Pp', 3)

91 LEFT = _Enum('L', 0)

92 RIGHT = _Enum(_R_, 1)

93

94_RP = _RP() # PYCHOK singleton

95

96_RP2L = {(_RP.LEFT, _RP.RIGHT): _L.CROSSING,

97 (_RP.RIGHT, _RP.LEFT): _L.CROSSING,

98 (_RP.LEFT, _RP.LEFT): _L.BOUNCING,

99 (_RP.RIGHT, _RP.RIGHT): _L.BOUNCING,

100 # overlapping cases

101 (_RP.RIGHT, _RP.IS_Pp): _L.LEFT_ON,

102 (_RP.IS_Pp, _RP.RIGHT): _L.LEFT_ON,

103 (_RP.LEFT, _RP.IS_Pp): _L.RIGHT_ON,

104 (_RP.IS_Pp, _RP.LEFT): _L.RIGHT_ON,

105 (_RP.IS_Pm, _RP.IS_Pp): _L.ON_ON,

106 (_RP.IS_Pp, _RP.IS_Pm): _L.ON_ON,

107 (_RP.IS_Pm, _RP.RIGHT): _L.ON_LEFT,

108 (_RP.RIGHT, _RP.IS_Pm): _L.ON_LEFT,

109 (_RP.LEFT, _RP.IS_Pm): _L.ON_RIGHT,

110 (_RP.IS_Pm, _RP.LEFT): _L.ON_RIGHT}

111

112

113 class _LatLonBool(_Named):

114 '''(INTERNAL) Base class for L{LatLonFHP} and L{LatLonGH}.

115 '''

116 _alpha = None # point AND intersection else length

117 _checked = False # checked in phase 3 iff intersection

118 _clipid = INT0 # (polygonal) clip identifier, number

119 _dupof = None # original of a duplicate

120# _e_x_str = NN # shut up PyChecker

121 _height = Height(0) # interpolated height, usually meter

122 _linked = None # link to neighbor iff intersection

123 _next = None # link to the next vertex

124 _prev = None # link to the previous vertex

125

126 def __init__(self, lat_ll, lon=None, height=0, clipid=INT0, wrap=False, **name):

127 '''New C{LatLon[FHP|GH]} from separate C{lat}, C{lon}, C{height} and C{clipid}

128 scalars or from a previous C{LatLon[FHP|GH]}, C{Clip[FHP|GH]4Tuple} or some

129 other C{LatLon} instance.

130

131 @arg lat_ll: Latitude (C{scalar}) or a lat-/longitude (C{LatLon[FHP|GH]},

132 C{Clip[FHP|GH]4Tuple} or some other C{LatLon}).

133 @kwarg lon: Longitude (C{scalar}), required B{C{lat_ll}} is scalar,

134 ignored otherwise.

135 @kwarg height: Height (C{scalar}), conventionally C{meter}.

136 @kwarg clipid: Clip identifier (C{int}).

137 @kwarg wrap: If C{True}, wrap or I{normalize} B{C{lat}} and B{C{lon}} (C{bool}).

138 @kwarg name: Optional C{B{name}=NN} (C{str}).

139 '''

140 h, name = _xkwds_pop2(name, h=height) if name else (height, name)

141

142 if lon is None:

143 y, x = lat_ll.lat, lat_ll.lon

144 h = _xattr(lat_ll, height=h)

145 c = _xattr(lat_ll, clipid=clipid)

146 else:

147 y, x, c = lat_ll, lon, clipid

148 self.y, self.x = _Wrap.latlon(y, x) if wrap else (y, x)

149 # don't duplicate defaults

150 if self._height != h:

151 self._height = h

152 if self._clipid != c:

153 self._clipid = c

154 if name:

155 self.name = name

156

157 def __abs__(self):

158 return max(fabs(self.x), fabs(self.y))

159

160 def __eq__(self, other):

161 return other is self or bool(_other(self, other) and

162 other.x == self.x and

163 other.y == self.y)

164

165 def __ne__(self, other): # required for Python 2

166 return not self.__eq__(other)

167

168 def __repr__(self):

169 '''String C{repr} of this lat-/longitude.

170 '''

171 if self._prev or self._next:

172 t = _ELLIPSIS_(self._prev, self._next)

173 t = _SPACE_(self, Fmt.ANGLE(t))

174 else:

175 t = str(self)

176 return t

177

178 def __str__(self):

179 '''String C{str} of this lat-/longitude.

180 '''

181 t = (_lat_, self.lat), (_lon_, self.lon)

182 if self._height:

183 X = _X_ if self.isintersection else NN

184 t += (_height_ + X, self._height),

185 if self._clipid:

186 t += (_clipid_, self._clipid),

187 if self._alpha is not None:

188 t += (_alpha_, self._alpha),

189# if self._dupof: # recursion risk

190# t += (_dupof_, self._dupof.name),

191 t = pairs(t, prec=8, fmt=Fmt.g, ints=True)

192 t = Fmt.PAREN(_COMMASPACE_.join(t))

193 if self._linked:

194 k = _DOT_ if self._checked else _BANG_

195 t = NN(t, self._e_x_str(k)) # PYCHOK expected

196 return NN(self.name, t)

197

198 def __sub__(self, other):

199 _other(self, other)

200 return self.__class__(self.y - other.y, # classof

201 self.x - other.x)

202

203 def _2A(self, p2, p3):

204 # I{Signed} area of a triangle, I{doubled}.

205 x, y = self.x, self.y

206 return (p2.x - x) * (p3.y - y) - \

207 (p3.x - x) * (p2.y - y)

208

209 def _2Abs(self, p2, p3, eps=_10EPS):

210 # I{Unsigned} area of a triangle, I{doubled}

211 # or 0 if below the given threshold C{eps}.

212 a = fabs(self._2A(p2, p3))

213 return 0 if a < eps else a

214

215 @property_RO

216 def clipid(self):

217 '''Get the I{clipid} (C{int} or C{0}).

218 '''

219 return self._clipid

220

221 def _equi(self, llb, eps):

222 # Is this LLB I{equivalent} to B{C{llb}} within

223 # the given I{non-negative} tolerance B{C{eps}}?

224 return not (fabs(llb.lon - self.x) > eps or

225 fabs(llb.lat - self.y) > eps)

226

227 @property_RO

228 def height(self):

229 '''Get the I{height} (C{Height} or C{int}).

230 '''

231 h = self._height

232 return HeightX(h) if self.isintersection else (

233 Height(h) if h else _LatLonBool._height)

234

235 def isequalTo(self, other, eps=None):

236 '''Is this point equal to an B{C{other}} within a given,

237 I{non-negative} tolerance, ignoring C{height}?

238

239 @arg other: The other point (C{LatLon}).

240 @kwarg eps: Tolerance for equality (C{degrees} or C{None}).

241

242 @return: C{True} if equivalent, C{False} otherwise (C{bool}).

243

244 @raise TypeError: Invalid B{C{other}}.

245 '''

246 try:

247 return self._equi(other, _eps0(eps))

248 except (AttributeError, TypeError, ValueError):

249 raise _IsnotError(_LatLon_, other=other)

250

251 @property_RO

252 def isintersection(self):

253 '''Is this an intersection? May be C{ispoint} too!

254 '''

255 return bool(self._linked)

256

257 @property_RO

258 def ispoint(self):

259 '''Is this an I{original} point? May be C{isintersection} too!

260 '''

261 return self._alpha is None

262

263 @property_RO

264 def lat(self):

265 '''Get the latitude (C{scalar}).

266 '''

267 return self.y

268

269 @property_RO

270 def latlon(self):

271 '''Get the lat- and longitude (L{LatLon2Tuple}).

272 '''

273 return LatLon2Tuple(self.y, self.x)

274

275 def _link(self, other):

276 # Make this and an other point neighbors.

277 # assert _other(self, other)

278 self._linked = other

279 other._linked = self

280

281 @property_RO

282 def lon(self):

283 '''Get the longitude (C{scalar}).

284 '''

285 return self.x

286

287 def _toClas(self, Clas, clipid):

288 # Return this vertex as a C{Clas} instance

289 # (L{Clip[FHP|GH]4Tuple} or L{LatLon[FHP|GH]}).

290 return Clas(self.lat, self.lon, self.height, clipid)

291

292

293 class LatLonFHP(_LatLonBool):

294 '''A point or intersection in a L{BooleanFHP} clip or composite.

295 '''

296 _en_ex = None

297 _label = None

298 _2split = None # or C{._Clip}

299 _2xing = False

300

301 def __init__(self, lat_ll, lon=None, height=0, clipid=INT0, **wrap_name):

302 '''New C{LatLonFHP} from separate C{lat}, C{lon}, C{h}eight and C{clipid}

303 scalars, or from a previous L{LatLonFHP}, L{ClipFHP4Tuple} or some other

304 C{LatLon} instance.

305

306 @arg lat_ll: Latitude (C{scalar}) or a lat-/longitude (L{LatLonFHP},

307 L{ClipFHP4Tuple} or some other C{LatLon}).

308

309 @see: L{Here<_LatLonBool.__init__>} for further details.

310 '''

311 _LatLonBool.__init__(self, lat_ll, lon, height, clipid, **wrap_name)

312

313 def __add__(self, other):

314 _other(self, other)

315 return self.__class__(self.y + other.y, self.x + other.x)

316

317 def __mod__(self, other): # cross product

318 _other(self, other)

319 return self.x * other.y - self.y * other.x

320

321 def __mul__(self, other): # dot product

322 _other(self, other)

323 return self.x * other.x + self.y * other.y

324

325 def __rmul__(self, other): # scalar product

326 _xscalar(other=other)

327 return self.__class__(self.y * other, self.x * other)

328

329 def _e_x_str(self, t): # PYCHOK no cover

330 if self._label:

331 t = NN(self._label, t)

332 if self._en_ex:

333 t = NN(t, self._en_ex)

334 return t

335

336 @property_RO

337 def _isduplicate(self):

338 # Is this point a I{duplicate} intersection?

339 p = self._dupof

340 return bool(p and self._linked

341 and p is not self

342 and p == self

343# and p._alpha in (None, self._alpha)

344 and self._alpha in (_0_0, p._alpha))

345

346# @property_RO

347# def _isduplicated(self):

348# # Return the number of I{duplicates}?

349# d, v = 0, self

350# while v:

351# if v._dupof is self:

352# d += 1

353# v = v._next

354# if v is self:

355# break

356# return d

357

358 def isenclosedBy(self, *composites_points, **wrap):

359 '''Is this point inside one or more composites or polygons based on

360 the U{winding number<https://www.ScienceDirect.com/science/article/

361 pii/S0925772101000128>}?

362

363 @arg composites_points: Composites and/or iterables of points

364 (L{ClipFHP4Tuple}, L{ClipGH4Tuple}, L{LatLonFHP},

365 L{LatLonGH} or any C{LatLon}).

366 @kwarg wrap: Optional keyword argument C{B{wrap}=False}, if C{True},

367 wrap or I{normalize} and unroll all C{points} (C{bool}).

368

369 @raise ValueError: Some C{points} invalid.

370

371 @see: U{Algorithm 6<https://www.ScienceDirect.com/science/

372 article/pii/S0925772101000128>}.

373 '''

374 class _Pseudo(object):

375 # Pseudo-_CompositeBase._clips tuple

376

377 @property_RO

378 def _clips(self):

379 for cp in _Cps(_CompositeFHP, composites_points,

380 LatLonFHP.isenclosedBy): # PYCHOK yield

381 for c in cp._clips:

382 yield c

383

384 return self._isinside(_Pseudo(), **wrap)

385

386 def _isinside(self, composite, *excludes, **wrap):

387 # Is this point inside a composite, excluding

388 # certain C{_Clip}s? I{winding number}?

389 x, y, i = self.x, self.y, False

390 for c in composite._clips:

391 if c not in excludes:

392 w = 0

393 for p1, p2 in c._edges2(**wrap):

394 # edge [p1,p2] must straddle y

395 if (p1.y < y) is not (p2.y < y): # or ^

396 r = p2.x > x

397 s = p2.y > p1.y

398 if p1.x < x:

399 b = r and (s is (p1._2A(p2, self) > 0))

400 else:

401 b = r or (s is (p1._2A(p2, self) > 0))

402 if b:

403 w += 1 if s else -1

404 if isodd(w):

405 i = not i

406 return i

407

408 @property_RO

409 def _prev_next2(self):

410 # Adjust 2-tuple (._prev, ._next) iff a I{duplicate} intersection

411 p, n = self, self._next

412 if self._isduplicate:

413 p = self._dupof

414 while p._isduplicate:

415 p = p._dupof

416 while n._isduplicate:

417 n = n._next

418 return p._prev, n

419

420# def _edge2(self):

421# # Return the start and end point of the

422# # edge containing I{intersection} C{v}.

423# n = p = self

424# while p.isintersection:

425# p = p._prev

426# if p is self:

427# break

428# while n.isintersection:

429# n = n._next

430# if n is self:

431# break

432# # assert p == self or not p._2Abs(self, n)

433# return p, n

434

435 def _RPoracle(self, p1, p2, p3):

436 # Relative Position oracle

437 if p1._linked is self: # or p1._linked2(self):

438 T = _RP.IS_Pm

439 elif p3._linked is self: # or p3._linked2(self):

440 T = _RP.IS_Pp

441 elif p1._2A(p2, p3) > 0: # left turn

442 T = _RP.LEFT if self._2A(p1, p2) > 0 and \

443 self._2A(p2, p3) > 0 else \

444 _RP.RIGHT # PYCHOK indent

445 else: # right turn (or straight)

446 T = _RP.RIGHT if self._2A(p1, p2) < 0 and \

447 self._2A(p2, p3) < 0 else \

448 _RP.LEFT # PYCHOK indent

449 return T

450

451

452 class LatLonGH(_LatLonBool):

453 '''A point or intersection in a L{BooleanGH} clip or composite.

454 '''

455 _entry = None # entry or exit iff intersection

456

457 def __init__(self, lat_ll, lon=None, height=0, clipid=INT0, **wrap_name):

458 '''New C{LatLonGH} from separate C{lat}, C{lon}, C{h}eight and C{clipid}

459 scalars, or from a previous L{LatLonGH}, L{ClipGH4Tuple} or some other

460 C{LatLon} instance.

461

462 @arg lat_ll: Latitude (C{scalar}) or a lat-/longitude (L{LatLonGH},

463 L{ClipGH4Tuple} or some other C{LatLon}).

464

465 @see: L{Here<_LatLonBool.__init__>} for further details.

466 '''

467 _LatLonBool.__init__(self, lat_ll, lon, height, clipid, **wrap_name)

468

469 def _check(self):

470 # Check-mark this vertex and its link.

471 self._checked = True

472 k = self._linked

473 if k and not k._checked:

474 k._checked = True

475

476 def _e_x_str(self, t): # PYCHOK no cover

477 return t if self._entry is None else NN(t,

478 (_e_ if self._entry else _x_))

479

480 def isenclosedBy(self, *composites_points, **wrap):

481 '''Is this point inside one or more composites or polygons based

482 on the U{even-odd-rule<https://www.ScienceDirect.com/science/

483 article/pii/S0925772101000128>}?

484

485 @arg composites_points: Composites and/or iterables of points

486 (L{ClipFHP4Tuple}, L{ClipGH4Tuple}, L{LatLonFHP},

487 L{LatLonGH} or any C{LatLon}).

488 @kwarg wrap: Optional keyword argument C{B{wrap}=False}, if C{True},

489 wrap or I{normalize} and unroll all C{points} (C{bool}).

490

491 @raise ValueError: Some B{C{points}} invalid.

492 '''

493 class _Pseudo(object):

494 # Pseudo-_CompositeBase._edges3 method

495

496 def _edges3(self, **kwds):

497 for cp in _Cps(_CompositeGH, composites_points,

498 LatLonGH.isenclosedBy): # PYCHOK yield

499 for e in cp._edges3(**kwds):

500 yield e

501

502 return self._isinside(_Pseudo(), **wrap)

503

504 def _isinside(self, composite, *bottom_top, **wrap):

505 # Is this vertex inside the composite? I{even-odd rule}?

506

507 def _x(y, p1, p2):

508 # return C{x} at given C{y} on edge [p1,p2]

509 return (y - p1.y) / (p2.y - p1.y) * (p2.x - p1.x)

510

511 # The I{even-odd} rule counts the number of edges

512 # intersecting a ray emitted from this point to

513 # east-bound infinity. When I{odd} this point lies

514 # inside, if I{even} outside.

515 y, i = self.y, False

516 if not (bottom_top and _outside(y, y, *bottom_top)):

517 x = self.x

518 for p1, p2, _ in composite._edges3(**wrap):

519 if (p1.y < y) is not (p2.y < y): # or ^

520 r = p2.x > x

521 if p1.x < x:

522 b = r and (_x(y, p1, p2) > x)

523 else:

524 b = r or (_x(y, p1, p2) > x)

525 if b:

526 i = not i

527 return i

528

529

530 class _Clip(_Named):

531 '''(INTERNAL) A I{doubly-linked} list representing a I{closed}

532 polygon of L{LatLonFHP} or L{LatLonGH} points, duplicates

533 and intersections with other clips.

534 '''

535 _composite = None

536 _dups = 0

537 _first = None

538 _id = 0

539 _identical = False

540 _noInters = False

541 _last = None

542 _LL = None

543 _len = 0

544 _pushback = False

545

546 def __init__(self, composite, clipid=INT0):

547 '''(INTERNAL) New C{_Clip}.

548 '''

549 # assert isinstance(composite, _CompositeBase)

550 if clipid in composite._clipids:

551 raise ClipError(clipid=clipid, txt=_duplicate_)

552 self._composite = composite

553 self._id = clipid

554 self._LL = composite._LL

555 composite._clips = composite._clips + (self,)

556

557 def __contains__(self, point): # PYCHOK no cover

558 '''Is the B{C{point}} in this clip?

559 '''

560 for v in self:

561 if v is point: # or ==?

562 return True

563 return False

564

565 def __eq__(self, other):

566 '''Is this clip I{equivalent} to an B{C{other}} clip,

567 do both have the same C{len}, the same points, in

568 the same order, possibly rotated?

569 '''

570 return self._equi(_other(self, other), 0)

571

572 def __ge__(self, other):

573 '''See method C{__lt__}.

574 '''

575 return not self.__lt__(other)

576

577 def __gt__(self, other):

578 '''Is this clip C{"above"} an B{C{other}} clip,

579 located or stretched farther North or East?

580 '''

581 return self._bltr4 > _other(self, other)._bltr4

582

583 def __hash__(self): # PYCHOK no over

584 return hash(self._bltr4)

585

586 def __iter__(self):

587 '''Yield the points, duplicates and intersections.

588 '''

589 v = f = self._first

590 while v:

591 yield v

592 v = v._next

593 if v is f:

594 break

595

596 def __le__(self, other):

597 '''See method C{__gt__}.

598 '''

599 return not self.__gt__(other)

600

601 def __len__(self):

602 '''Return the number of points, duplicates and

603 intersections in this clip.

604 '''

605 return self._len

606

607 def __lt__(self, other):

608 '''Is this clip C{"below"} an B{C{other}} clip,

609 located or stretched farther South or West?

610 '''

611 return self._bltr4 < _other(self, other)._bltr4

612

613 def __ne__(self, other): # required for Python 2

614 '''See method C{__eq__}.

615 '''

616 return not self.__eq__(other)

617

618 _all = __iter__

619

620 @property_RO

621 def _all_ON_ON(self):

622 # Check whether all vertices are ON_ON.

623 L_ON_ON = _L.ON_ON

624 return all(v._label is L_ON_ON for v in self)

625

626 def _append(self, y_v, *x_h_clipid):

627 # Append a point given as C{y}, C{x}, C{h}eight and

628 # C{clipid} args or as a C{LatLon[FHP|GH]}.

629 self._last = v = self._LL(y_v, *x_h_clipid) if x_h_clipid else y_v

630 self._len += 1

631 # assert v._clipid == self._id

632

633 v._next = n = self._first

634 if n is None: # set ._first

635 self._first = p = n = v

636 else: # insert before ._first

637 v._prev = p = n._prev

638 p._next = n._prev = v

639 return v

640

641# def _appendedup(self, v, clipid=0):

642# # Like C{._append}, but only append C{v} if not a

643# # duplicate of the one previously append[edup]'ed.

644# y, x, p = v.y, v.x, self._last

645# if p is None or y != p.y or x != p.x or clipid != p._clipid:

646# p = self._append(y, x, v._height, clipid)

647# if v._linked:

648# p._linked = True # to force errors

649# return p

650

651 @Property_RO

652 def _bltr4(self):

653 # Get the bounds as 4-tuple C{(bottom, left, top, right)}.

654 return map2(float, _MODS.points.boundsOf(self, wrap=False))

655

656 def _bltr4eps(self, eps):

657 # Get the ._bltr4 bounds tuple, slightly oversized.

658 if eps > 0: # > EPS

659 yb, xl, yt, xr = self._bltr4

660 yb, yt = _low_high_eps2(yb, yt, eps)

661 xl, xr = _low_high_eps2(xl, xr, eps)

662 t = yb, xl, yt, xr

663 else:

664 t = self._bltr4

665 return t

666

667 def _closed(self, raiser): # PYCHOK unused

668 # End a clip, un-close it and check C{len}.

669 p, f = self._last, self._first

670 if f and f._prev is p and p is not f and \

671 p._next is f and p == f: # PYCHOK no cover

672 # un-close the clip

673 f._prev = p = p._prev

674 p._next = f

675 self._len -= 1

676# elif f and raiser:

677# raise self._OpenClipError(p, f)

678 if len(self) < 3:

679 raise self._Error(_too_(_few_))

680

681 def _dup(self, q):

682 # Duplicate a point (or intersection) as intersection.

683 v = self._insert(q.y, q.x, q)

684 v._alpha = q._alpha or _0_0 # _0_0 replaces None

685 v._dupof = q._dupof or q

686 # assert v._prev is q

687 # assert q._next is v

688 return v

689

690 def _edges2(self, wrap=False, **unused):

691 # Yield each I{original} edge as a 2-tuple

692 # (p1, p2), a pair of C{LatLon[FHP|GH])}s.

693 p1 = p = f = self._first

694 while p:

695 p2 = p = p._next

696 if p.ispoint:

697 if wrap and p is not f:

698 p2 = _unrollon(p1, p)

699 yield p1, p2

700 p1 = p2

701 if p is f:

702 break

703

704 def _equi(self, clip, eps):

705 # Is this clip I{equivalent} to B{C{clip}} within

706 # the given I{non-negative} tolerance B{C{eps}}?

707 r, f = len(self), self._first

708 if f and r == len(clip) and self._bltr4eps(eps) \

709 == clip._bltr4eps(eps):

710 _equi = _LatLonBool._equi

711 for v in clip:

712 if _equi(f, v, eps):

713 s, n = f, v

714 for _ in range(r):

715 s, n = s._next, n._next

716 if not _equi(s, n, eps):

717 break # next v

718 else: # equivalent

719 return True

720 return False

721

722 def _Error(self, txt): # PYCHOK no cover

723 # Build a C{ClipError} instance

724 kwds = dict(len=len(self), txt=txt)

725 if self._dups:

726 kwds.update(dups=self._dups)

727 cp = self._composite

728 if self._id:

729 try:

730 i = cp._clips.index(self)

731 if i != self._id:

732 kwds[_clip_] = i

733 except ValueError:

734 pass

735 kwds[_clipid_] = self._id

736 return ClipError(cp._kind, cp.name, **kwds)

737

738 def _index(self, clips, eps):

739 # see _CompositeBase._equi

740 for i, c in enumerate(clips):

741 if c._equi(self, eps):

742 return i

743 raise ValueError(NN) # like clips.index(self)

744

745 def _insert(self, y, x, start, *end_alpha):

746 # insertVertex between points C{start} and

747 # C{end}, ordered by C{alpha} iff given.

748 v = self._LL(y, x, start._height, start._clipid)

749 n = start._next

750 if end_alpha:

751 end, alpha = end_alpha

752 v._alpha = alpha

753 v._height = favg(v._height, end._height, f=alpha)

754 # assert start is not end

755 while n is not end and n._alpha < alpha:

756 n = n._next

757 v._next = n

758 v._prev = p = n._prev

759 p._next = n._prev = v

760 self._len += 1

761# _Clip._bltr4._update(self)

762# _Clip._ishole._update(self)

763 return v

764

765 def _intersection(self, unused, q, *p1_p2_alpha):

766 # insert an intersection or make a point both

767 if p1_p2_alpha: # intersection on edge

768 v = self._insert(q.y, q.x, *p1_p2_alpha)

769 else: # intersection at point

770 v = q

771 # assert not v._linked

772 # assert v._alpha is None

773 return v

774

775 def _intersections(self):

776 # Yield all intersections, some may be points too.

777 for v in self:

778 if v.isintersection:

779 yield v

780

781 @Property_RO

782 def _ishole(self): # PYCHOK no cover

783 # Is this clip a hole inside its composite?

784 v = self._first

785 return v._isinside(self._composite, self) if v else False

786

787 @property_RO

788 def _nodups(self):

789 # Yield all non-duplicates.

790 for v in self:

791 if not v._dupof:

792 yield v

793

794 def _noXings(self, Union):

795 # Are all intersections non-CROSSINGs, -BOUNCINGs?

796 Xings = _L.BOUNCINGs if Union else _L.CROSSINGs

797 return all(v._label not in Xings for v in self._intersections())

798

799 def _OpenClipError(self, s, e): # PYCHOK no cover

800 # Return a C{CloseError} instance

801 t = NN(s, _ELLIPSIS_(_COMMASPACE_, e))

802 return self._Error(_SPACE_(_open_, t))

803

804 def _point2(self, insert):

805 # getNonIntersectionPoint and -Vertex

806 if not (insert and self._noInters):

807 for p in self._points(may_be=False): # not p._isduplicated?

808 return p, None

809 for n in self._intersections():

810 p, _ = n._prev_next2

811 k = p._linked

812 if k:

813 if n._linked not in k._prev_next2:

814 # create a pseudo-point

815 k = _0_5 * (p + n)

816 if insert:

817 k = self._insert(k.y, k.x, n._prev)

818 r = k # to remove later

819 else: # no ._prev, ._next

820 k._clipid = n._clipid

821 r = None

822 return k, r

823 return None, None

824

825 def _points(self, may_be=True):

826 # Yield all points I{in original order}, which may be intersections too.

827 for v in self:

828 if v.ispoint and (may_be or not v.isintersection):

829 yield v

830

831 def _remove2(self, v):

832 # Remove vertex C{v}.

833 # assert not v._isduplicated

834 if len(self) > 1:

835 p = v._prev

836 p._next = n = v._next

837 n._prev = p

838 if self._first is v:

839 self._first = n

840 if self._last is v:

841 self._last = p

842 self._len -= 1

843 else:

844 n = self._last = \

845 p = self._first = None

846 self._len = 0

847 return p, n

848

849 def _update_all(self): # PYCHOK no cover

850 # Zap the I{cached} properties.

851 _Clip._bltr4._update( self)

852 _Clip._ishole._update(self)

853 return self # for _special_identicals

854

855 def _Xings(self):

856 # Yield all I{un-checked} CROSSING intersections.

857 CROSSING = _L.CROSSING

858 for v in self._intersections():

859 if v._label is CROSSING and not v._checked:

860 yield v

861

862

863 class _CompositeBase(_Named):

864 '''(INTERNAL) Base class for L{BooleanFHP} and L{BooleanGH}

865 (C{_CompositeFHP} and C{_CompositeGH}).

866 '''

867 _clips = () # tuple of C{_Clips}

868 _eps = EPS # null edges

869 _kind = _corners_

870 _LL = _LatLonBool # shut up PyChecker

871 _raiser = False

872 _xtend = False

873

874 def __init__(self, lls, kind=NN, eps=EPS, **name):

875 '''(INTERNAL) See L{BooleanFHP} and L{BooleanGH}.

876 '''

877 n = _name__(name, _or_nameof=lls)

878 if n:

879 self.name = n

880 if kind:

881 self._kind = kind

882 if self._eps < eps:

883 self._eps = eps

884

885 c = _Clip(self)

886 lp = None

887 for ll in lls:

888 ll = self._LL(ll)

889 if lp is None:

890 c._id = ll._clipid # keep clipid

891 lp = c._append(ll)

892 elif ll._clipid != lp._clipid: # new clip

893 c._closed(self.raiser)

894 c = _Clip(self, ll._clipid)

895 lp = c._append(ll)

896 elif abs(ll - lp) > eps: # PYCHOK lp

897 lp = c._append(ll)

898 else:

899 c._dups += 1

900 c._closed(self.raiser)

901

902 def __contains__(self, point): # PYCHOK no cover

903 '''Is the B{C{point}} in one of the clips?

904 '''

905 for c in self._clips:

906 if point in c:

907 return True

908 return False

909

910 def __eq__(self, other):

911 '''Is this I{composite} equivalent to an B{C{other}}, i.e.

912 do both contain I{equivalent} clips in the same or in a

913 different order? Two clips are considered I{equivalent}

914 if both have the same points etc. in the same order,

915 possibly rotated.

916 '''

917 return self._equi(_other(self, other), 0)

918

919 def __iter__(self):

920 '''Yield all points, duplicates and intersections.

921 '''

922 for c in self._clips:

923 for v in c:

924 yield v

925

926 def __ne__(self, other): # required for Python 2

927 '''See method C{__eq__}.

928 '''

929 return not self.__eq__(other)

930

931 def __len__(self):

932 '''Return the I{total} number of points.

933 '''

934 return sum(map(len, self._clips)) if self._clips else 0

935

936 def __repr__(self):

937 '''String C{repr} of this composite.

938 '''

939 c = len(self._clips)

940 c = Fmt.SQUARE(c) if c > 1 else NN

941 n = Fmt.SQUARE(len(self))

942 t = Fmt.PAREN(self) # XXX not unstr

943 return NN(self.__class__.__name__, c, n, t)

944

945 def __str__(self):

946 '''String C{str} of this composite.

947 '''

948 return _COMMASPACE_.join(map(str, self))

949

950 @property_RO

951 def _bottom_top_eps2(self):

952 # Get the bottom and top C{y} bounds, oversized.

953 return _min_max_eps2(min(v.y for v in self),

954 max(v.y for v in self))

955

956 def _class(self, corners, kwds, **dflts):

957 # Return a new instance

958 _g = kwds.get

959 kwds = dict((n, _g(n, v)) for n, v in dflts.items())

960 return self.__class__(corners or (), **kwds)

961

962 @property_RO

963 def _clipids(self): # PYCHOK no cover

964 for c in self._clips:

965 yield c._id

966

967 def clipids(self):

968 '''Return a tuple with all C{clipid}s, I{ordered}.

969 '''

970 return tuple(self._clipids)

971

972# def _clipidups(self, other):

973# # Number common C{clipid}s between this and an C{other} composite

974# return len(set(self._clipids).intersection(set(other._clipids)))

975

976 def _edges3(self, **raiser_wrap):

977 # Yield each I{original} edge as a 3-tuple

978 # C{(LatLon[FHP|GH], LatLon[FHP|GH], _Clip)}.

979 for c in self._clips:

980 for p1, p2 in c._edges2(**raiser_wrap):

981 yield p1, p2, c

982

983 def _encloses(self, lat, lon, **wrap):

984 # see function .points.isenclosedBy

985 return self._LL(lat, lon).isenclosedBy(self, **wrap)

986

987 @property

988 def eps(self):

989 '''Get the null edges tolerance (C{degrees}, usually).

990 '''

991 return self._eps

992

993 @eps.setter # PYCHOK setter!

994 def eps(self, eps):

995 '''Set the null edges tolerance (C{degrees}, usually).

996 '''

997 self._eps = eps

998

999 def _10eps(self, **eps_):

1000 # Get eps for _LatLonBool._2Abs

1001 e = _xkwds_get(eps_, eps=self._eps)

1002 if e != EPS:

1003 e *= _10EPS / EPS

1004 else:

1005 e = _10EPS

1006 return e

1007

1008 def _equi(self, other, eps):

1009 # Is this composite I{equivalent} to an B{C{other}} within

1010 # the given, I{non-negative} tolerance B{C{eps}}?

1011 cs, co = self._clips, other._clips

1012 if cs and len(cs) == len(co):

1013 if eps > 0:

1014 _index = _Clip._index

1015 else:

1016 def _index(c, cs, unused):

1017 return cs.index(c)

1018 try:

1019 cs = list(sorted(cs))

1020 for c in sorted(co):

1021 cs.pop(_index(c, cs, eps))

1022 except ValueError: # from ._index

1023 pass

1024 return False if cs else True

1025 else: # both null?

1026 return False if cs or co else True

1027

1028 def _intersections(self):

1029 # Yield all intersections.

1030 for c in self._clips:

1031 for v in c._intersections():

1032 yield v

1033

1034 def isequalTo(self, other, eps=None):

1035 '''Is this boolean/composite equal to an B{C{other}} within

1036 a given, I{non-negative} tolerance?

1037

1038 @arg other: The other boolean/composite (C{Boolean[FHP|GB]}).

1039 @kwarg eps: Tolerance for equality (C{degrees} or C{None}).

1040

1041 @return: C{True} if equivalent, C{False} otherwise (C{bool}).

1042

1043 @raise TypeError: Invalid B{C{other}}.

1044

1045 @see: Method C{__eq__}.

1046 '''

1047 if isinstance(other, _CompositeBase):

1048 return self._equi(other, _eps0(eps))

1049 raise _IsnotError(_boolean_, _composite_, other=other)

1050

1051 def _kwds(self, op, **more):

1052 # Get all keyword arguments as C{dict}.

1053 kwds = dict(raiser=self.raiser, eps=self.eps,

1054 name=self.name or op.__name__)

1055 kwds.update(more)

1056 return kwds

1057

1058 @property_RO

1059 def _left_right_eps2(self):

1060 # Get the left and right C{x} bounds, oversized.

1061 return _min_max_eps2(min(v.x for v in self),

1062 max(v.x for v in self))

1063

1064 def _points(self, may_be=True): # PYCHOK no cover

1065 # Yield all I{original} points, which may be intersections too.

1066 for c in self._clips:

1067 for v in c._points(may_be=may_be):

1068 yield v

1069

1070 @property

1071 def raiser(self):

1072 '''Get the option to throw L{ClipError} exceptions (C{bool}).

1073 '''

1074 return self._raiser

1075

1076 @raiser.setter # PYCHOK setter!

1077 def raiser(self, throw):

1078 '''Set the option to throw L{ClipError} exceptions (C{bool}).

1079 '''

1080 self._raiser = bool(throw)

1081

1082 def _results(self, _presults, Clas, closed=False, inull=False, **eps):

1083 # Yield the dedup'd results, as L{ClipFHP4Tuple}s

1084 C = self._LL if Clas is None else Clas

1085 e = self._10eps(**eps)

1086 for clipid, ns in enumerate(_presults):

1087 f = p = v = None

1088 for n in ns:

1089 if f is None:

1090 yield n._toClas(C, clipid)

1091 f = p = n

1092 elif v is None:

1093 v = n # got f, p, v

1094 elif inull or p._2Abs(v, n, eps=e):

1095 yield v._toClas(C, clipid)

1096 p, v = v, n

1097 else: # null, colinear, ... skipped

1098 v = n

1099 if v and (inull or p._2Abs(v, f, eps=e)):

1100 yield v._toClas(C, clipid)

1101 p = v

1102 if f and p != f and closed: # close clip

1103 yield f._toClas(C, clipid)

1104

1105 def _sum(self, other, op):

1106 # Combine this and an C{other} composite

1107 LL = self._LL

1108 sp = self.copy(name=self.name or op.__name__)

1109 sp._clips, sid = (), INT0 # new clips

1110 for cp in (self, other):

1111 for c in cp._clips:

1112 _ap = _Clip(sp, sid)._append

1113 for v in c._nodups:

1114 _ap(LL(v.y, v.x, v.height, sid))

1115 sid += 1

1116 return sp

1117

1118 def _sum1(self, _a_p, *args, **kwds): # in .karney, .points

1119 # Sum the area or perimeter of all clips

1120 return _MODS.fsums.fsum1((_a_p(c, *args, **kwds) for c in self._clips))

1121

1122 def _sum2(self, LL, _a_p, *args, **kwds): # in .sphericalNvector, -Trigonometry

1123 # Sum the area or perimeter of all clips

1124

1125 def _lls(clip): # convert clip to LLs

1126 _LL = LL

1127 for v in clip:

1128 yield _LL(v.lat, v.lon) # datum=Sphere

1129

1130 return _MODS.fsums.fsum1((_a_p(_lls(c), *args, **kwds) for c in self._clips))

1131

1132 def toLatLon(self, LatLon=None, closed=False, **LatLon_kwds):

1133 '''Yield all (non-duplicate) points and intersections

1134 as an instance of B{C{LatLon}}.

1135

1136 @kwarg LatLon: Class to use (C{LatLon}) or if C{None},

1137 L{LatLonFHP} or L{LatLonGH}.

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

1139 @kwarg LatLon_kwds: Optional, additional B{C{LatLon}}

1140 keyword arguments, ignore if

1141 C{B{LatLon} is None}.

1142

1143 @raise TypeError: Invalid B{C{LatLon}}.

1144

1145 @note: For intersections, C{height} is an instance

1146 of L{HeightX}, otherwise of L{Height}.

1147 '''

1148 if LatLon is None:

1149 LL, kwds = self._LL, {}

1150 elif issubclassof(LatLon, _LatLonBool, LatLonBase):

1151 LL, kwds = LatLon, LatLon_kwds

1152 else:

1153 raise _TypeError(LatLon=LatLon)

1154

1155 for c in self._clips:

1156 lf, cid = None, c._id

1157 for v in c._nodups:

1158 ll = LL(v.y, v.x, **kwds)

1159 ll._height = v.height

1160 if ll._clipid != cid:

1161 ll._clipid = cid

1162 yield ll

1163 if lf is None:

1164 lf = ll

1165 if closed and lf:

1166 yield lf

1167

1168

1169 class _CompositeFHP(_CompositeBase):

1170 '''(INTERNAL) A list of clips representing a I{composite}

1171 of L{LatLonFHP} points, duplicates and intersections

1172 with an other I{composite}.

1173 '''

1174 _LL = LatLonFHP

1175 _Union = False

1176

1177 def __init__(self, lls, raiser=False, **name_kind_eps):

1178 # New L{_CompositeFHP}.

1179 if raiser:

1180 self._raiser = True

1181 _CompositeBase.__init__(self, lls, **name_kind_eps)

1182

1183 def _classify(self):

1184 # 2) Classify intersection chains.

1185 L = _L

1186 for v in self._intersections():

1187 n, b = v, v._label

1188 if b in L.RIGHT_LEFT_ON: # next chain

1189 while True:

1190 n._label = None # _xkwds_pop(n.__dict__, _label=None)

1191 n = n._next

1192 if n is v or n._label is not L.ON_ON: # n._label and ...

1193 break

1194 a = L.LEFT_ON if n._label is L.ON_LEFT else L.RIGHT_ON

1195 v._label = n._label = L.BOUNCING_D if a is b else L.CROSSING_D

1196

1197 # 3) Copy labels

1198 for v in self._intersections():

1199 v._linked._label = v._label

1200

1201 def _clip(self, corners, Union=False, Clas=None,

1202 **closed_inull_raiser_eps):

1203 # Clip this composite with another one, C{corners},

1204 # using Foster-Hormann-Popa's algorithm.

1205 P = self

1206 Q = self._class(corners, closed_inull_raiser_eps,

1207 eps=P._eps, raiser=False)

1208 if Union:

1209 P._Union = Q._Union = True

1210

1211 bt = Q._bottom_top_eps2

1212 lr = Q._left_right_eps2

1213 # compute and insert intersections

1214 for p1, p2, Pc in P._edges3(**closed_inull_raiser_eps):

1215 if not (_outside(p1.x, p2.x, *lr) or

1216 _outside(p1.y, p2.y, *bt)):

1217 e = _EdgeFHP(p1, p2)

1218 if e._dp2 > EPS2: # non-null edge

1219 for q1, q2, Qc in Q._edges3(**closed_inull_raiser_eps):

1220 for T, p, q in e._intersect3(q1, q2):

1221 p = Pc._intersection(T, *p)

1222 q = Qc._intersection(T, *q)

1223 # assert not p._linked

1224 # assert not q._linked

1225 p._link(q)

1226

1227 # label and classify intersections

1228 P._labelize()

1229 P._classify()

1230

1231 # check for special cases

1232 P._special_cases(Q)

1233 Q._special_cases(P)

1234 # handle identicals

1235 P._special_identicals(Q)

1236

1237 # set Entry/Exit flags

1238 P._set_entry_exits(Q)

1239 Q._set_entry_exits(P)

1240

1241 # handle splits and crossings

1242 P._splits_xings(Q)

1243

1244 # yield the results

1245 return P._results(P._presults(Q), Clas, **closed_inull_raiser_eps)

1246

1247 @property_RO

1248 def _identicals(self):

1249 # Yield all clips marked C{._identical}.

1250 for c in self._clips:

1251 if c._identical:

1252 yield c

1253

1254 def _labelize(self):

1255 # 1) Intersections classification

1256 for p in self._intersections():

1257 q = p._linked

1258 # determine local configuration at this intersection

1259 # and positions of Q- and Q+ relative to (P-, I, P+)

1260 p1, p3 = p._prev_next2

1261 q1, q3 = q._prev_next2

1262 t = (q1._RPoracle(p1, p, p3),

1263 q3._RPoracle(p1, p, p3))

1264 # check intersecting and overlapping cases

1265 p._label = _RP2L.get(t, None)

1266

1267 def _presults(self, other):

1268 # Yield the result clips, each as a generator

1269 # of the L{_LatLonFHP}s in that clip

1270 for cp in (self, other):

1271 for c in cp._clips:

1272 if c._pushback:

1273 yield c._all()

1274 for c in self._clips:

1275 for X in c._Xings():

1276 yield self._resultX(X)

1277

1278 def _resultX(self, X):

1279 # Yield the results from CROSSING C{X}.

1280 L, U, v = _L, self._Union, X

1281 while v:

1282 v._checked = True

1283 r = v # in P or Q

1284 s = L.Toggle[v._en_ex]

1285 e = (s is L.EXIT) ^ U

1286 while True:

1287 v = v._next if e else v._prev

1288 yield v

1289 v._checked = True

1290 if v._en_ex is s or v is X:

1291 break

1292 if v is r: # full circle

1293 raise ClipError(full_circle=v, clipid=v._clipid)

1294 if v is not X:

1295 v = v._linked

1296 if v is X:

1297 break

1298

1299 def _set_entry_exits(self, other): # MCCABE 14

1300 # 4) Set entry/exit flags

1301 L, U = _L, self._Union

1302 for c in self._clips:

1303 n, k = c._point2(True)

1304 if n:

1305 f = n

1306 s = L.EXIT if n._isinside(other) else L.ENTRY

1307 t = L.EXIT # first_chain_vertex = True

1308 while True:

1309 if n.isintersection:

1310 b = n._label

1311 if b is L.CROSSING:

1312 n._en_ex = s

1313 s = L.Toggle[s]

1314 elif b is L.BOUNCING and ((s is L.EXIT) ^ U):

1315 n._2split = c # see ._splits_xings

1316 elif b is L.CROSSING_D:

1317 n._en_ex = s

1318 if (s is t) ^ U:

1319 n._label = L.CROSSING

1320 t = L.Toggle[t]

1321 if t is L.EXIT: # first_chain_vertex == True

1322 s = L.Toggle[s]

1323 elif b is L.BOUNCING_D:

1324 n._en_ex = s

1325 if (s is t) ^ U:

1326 n._2xing = True # see ._splits_xings

1327 s = L.Toggle[s]

1328 t = L.Toggle[t]

1329 n = n._next # _, n = n._prev_next2

1330 if n is f:

1331 break # PYCHOK attr?

1332 if k:

1333 c._remove2(k)

1334

1335 def _special_cases(self, other):

1336 # 3.5) Check special cases

1337 U = self._Union

1338 for c in self._clips:

1339 if c._noXings(U):

1340 c._noInters = True

1341 if c._all_ON_ON:

1342 c._identical = True

1343 else:

1344 p, _ = c._point2(False)

1345 if p and (p._isinside(other) ^ U):

1346 c._pushback = True

1347

1348 def _special_identicals(self, other):

1349 # 3.5) Handle identicals

1350 _u = _Clip._update_all

1351 cds = dict((c._id, _u(c)) for c in other._identicals)

1352 # assert len(cds) == len(other._identicals)

1353 if cds: # PYCHOK no cover

1354 for c in self._identicals:

1355 c._update_all()

1356 for v in c._intersections():

1357 d = cds.get(v._linked._clipid, None)

1358 if d and d._ishole is c._ishole:

1359 c._pushback = True

1360 break # next c

1361

1362 @property_RO

1363 def _2splits(self):

1364 # Yield all intersections marked C{._2split}

1365 for p in self._intersections():

1366 if p._2split:

1367 # assert isinstance(p._2split, _Clip)

1368 yield p

1369

1370 def _splits_xings(self, other): # MCCABE 15

1371 # 5) Handle split pairs and 6) crossing candidates

1372

1373 def _2A_dup2(p, P): # PYCHOK unused

1374 p1, p2 = p._prev_next2

1375 ap = p1._2A(p, p2)

1376 Pc = p._2split

1377 # assert Pc in P._clips

1378 # assert p in Pc

1379 return ap, Pc._dup(p)

1380

1381 def _links2(ps, qs): # PYCHOK P unused?

1382 # Yield each link as a 2-tuple(p, q)

1383 id_qs = set(map(id, qs))

1384 if id_qs:

1385 for p in ps:

1386 q = p._linked

1387 if q and id(q) in id_qs:

1388 yield p, q

1389

1390 L = _L

1391 E = L.ENTRY if self._Union else L.EXIT

1392 X = L.Toggle[E]

1393 for p, q in _links2(self._2splits, other._2splits):

1394 ap, pp = _2A_dup2(p, self)

1395 aq, qq = _2A_dup2(q, other)

1396 if (ap * aq) > 0: # PYCHOK no cover

1397 p._link(qq) # overwrites ...

1398 q._link(pp) # ... p-q link

1399 else:

1400 pp._link(qq)

1401 p._en_ex = q._en_ex = E

1402 pp._en_ex = qq._en_ex = X

1403 p._label = pp._label = \

1404 q._label = qq._label = L.CROSSING

1405

1406 for p, q in _links2(self._2xings, other._2xings):

1407 p._label = q._label = L.CROSSING

1408

1409 @property_RO

1410 def _2xings(self):

1411 # Yield all intersections marked C{._2xing}

1412 for p in self._intersections():

1413 if p._2xing:

1414 yield p

1415

1416

1417 class _CompositeGH(_CompositeBase):

1418 '''(INTERNAL) A list of clips representing a I{composite}

1419 of L{LatLonGH} points, duplicates and intersections

1420 with an other I{composite}.

1421 '''

1422 _LL = LatLonGH

1423 _xtend = False

1424

1425 def __init__(self, lls, raiser=False, xtend=False, **name_kind_eps):

1426 # New L{_CompositeGH}.

1427 if xtend:

1428 self._xtend = True

1429 elif raiser:

1430 self._raiser = True

1431 _CompositeBase.__init__(self, lls, **name_kind_eps)

1432

1433 def _clip(self, corners, s_entry, c_entry, Clas=None,

1434 **closed_inull_raiser_xtend_eps):

1435 # Clip this polygon with another one, C{corners}.

1436

1437 # Core of Greiner/Hormann's algorithm, enhanced U{Correia's

1438 # <https://GitHub.com/helderco/univ-polyclip>} implementation***

1439 # and extended to optionally handle so-called "degenerate cases"

1440 S = self

1441 C = self._class(corners, closed_inull_raiser_xtend_eps,

1442 raiser=False, xtend=False)

1443 bt = C._bottom_top_eps2

1444 lr = C._left_right_eps2

1445 # 1. find intersections

1446 for s1, s2, Sc in S._edges3(**closed_inull_raiser_xtend_eps):

1447 if not (_outside(s1.x, s2.x, *lr) or

1448 _outside(s1.y, s2.y, *bt)):

1449 e = _EdgeGH(s1, s2, **closed_inull_raiser_xtend_eps)

1450 if e._hypot2 > EPS2: # non-null edge

1451 for c1, c2, Cc in C._edges3(**closed_inull_raiser_xtend_eps):

1452 for y, x, sa, ca in e._intersect4(c1, c2):

1453 s = Sc._insert(y, x, s1, s2, sa)

1454 c = Cc._insert(y, x, c1, c2, ca)

1455 s._link(c)

1456

1457 # 2. identify entry/exit intersections

1458 if S._first:

1459 s_entry ^= S._first._isinside(C, *bt)

1460 for v in S._intersections():

1461 v._entry = s_entry = not s_entry

1462

1463 if C._first:

1464 c_entry ^= C._first._isinside(S)

1465 for v in C._intersections():

1466 v._entry = c_entry = not c_entry

1467

1468 # 3. yield the result(s)

1469 return S._results(S._presults(), Clas, **closed_inull_raiser_xtend_eps)

1470

1471 @property_RO

1472 def _first(self):

1473 # Get the very first vertex of the first clip

1474 for v in self:

1475 return v

1476 return None # PYCHOK no cover

1477

1478 def _kwds(self, op, **more):

1479 # Get the kwds C{dict}.

1480 return _CompositeBase._kwds(self, op, xtend=self.xtend, **more)

1481

1482 def _presults(self):

1483 # Yield the unchecked intersection(s).

1484 for c in self._clips:

1485 for v in c._intersections():

1486 if not v._checked:

1487 yield self._resultU(v)

1488

1489 def _resultU(self, v):

1490 # Yield the result from an un-checked intersection.

1491 while v and not v._checked:

1492 v._check()

1493 yield v

1494 r = v

1495 e = v._entry

1496 while True:

1497 v = v._next if e else v._prev

1498 yield v

1499 if v._linked:

1500 break

1501 if v is r:

1502 raise ClipError(full_circle=v, clipid=v._clipid)

1503 v = v._linked # switch

1504

1505 @property

1506 def xtend(self):

1507 '''Get the option to handle I{degenerate cases} (C{bool}).

1508 '''

1509 return self._xtend

1510

1511 @xtend.setter # PYCHOK setter!

1512 def xtend(self, xtend):

1513 '''Set the option to handle I{degenerate cases} (C{bool}).

1514 '''

1515 self._xtend = bool(xtend)

1516

1517

1518 class _EdgeFHP(object):

1519 # An edge between two L{LatLonFHP} points.

1520

1521 X_INTERSECT = _Enum('Xi', 1) # C++ enum

1522 X_OVERLAP = _Enum('Xo', 5)

1523 P_INTERSECT = _Enum('Pi', 3)

1524 P_OVERLAP = _Enum('Po', 7)

1525 Ps = (P_INTERSECT, P_OVERLAP, X_OVERLAP)

1526 Q_INTERSECT = _Enum('Qi', 2)

1527 Q_OVERLAP = _Enum('Qo', 6)

1528 Qs = (Q_INTERSECT, Q_OVERLAP, X_OVERLAP)

1529 V_INTERSECT = _Enum('Vi', 4)

1530 V_OVERLAP = _Enum('Vo', 8)

1531 Vs = (V_INTERSECT, V_OVERLAP)

1532

1533 def __init__(self, p1, p2, **unused):

1534 # New edge between points C{p1} and C{p2}, each a L{LatLonFHP}.

1535 self._p1_p2 = p1, p2

1536 self._dp = dp = p2 - p1

1537 self._dp2 = dp * dp # dot product, hypot2

1538

1539 self._lr, \

1540 self._bt = _left_right_bottom_top_eps2(p1, p2)

1541

1542 def _intersect3(self, q1, q2):

1543 # Yield intersection(s) Type or C{None}

1544 if not (_outside(q1.x, q2.x, *self._lr) or

1545 _outside(q1.y, q2.y, *self._bt)):

1546 dq = q2 - q1

1547 dq2 = dq * dq # dot product, hypot2

1548 if dq2 > EPS2: # like ._clip

1549 T, E = None, _EdgeFHP # self.__class__

1550 p1, p2 = self._p1_p2

1551 ap1 = p1._2A(q1, q2)

1552 ap2_1 = p2._2A(q1, q2) - ap1

1553 if fabs(ap2_1) > _0_EPS: # non-parallel edges

1554 aq1 = q1._2A(p1, p2)

1555 aq2_1 = q2._2A(p1, p2) - aq1

1556 if fabs(aq2_1) > _0_EPS:

1557 # compute and classify alpha and beta

1558 a, a_0, a_0_1, _ = _alpha4(-ap1 / ap2_1)

1559 b, b_0, b_0_1, _ = _alpha4(-aq1 / aq2_1)

1560 # distinguish intersection types

1561 T = E.X_INTERSECT if a_0_1 and b_0_1 else (

1562 E.P_INTERSECT if a_0_1 and b_0 else (

1563 E.Q_INTERSECT if a_0 and b_0_1 else (

1564 E.V_INTERSECT if a_0 and b_0 else None)))

1565

1566 elif fabs(ap1) < _0_EPS: # parallel or colinear edges

1567 dp = self._dp

1568 d1 = q1 - p1

1569 # compute and classify alpha and beta

1570 a, a_0, a_0_1, _a_0_1 = _alpha4((d1 * dp) / self._dp2)

1571 b, b_0, b_0_1, _b_0_1 = _alpha4((d1 * dq) / (-dq2))

1572 # distinguish overlap type

1573 T = E.X_OVERLAP if a_0_1 and b_0_1 else (

1574 E.P_OVERLAP if a_0_1 and _b_0_1 else (

1575 E.Q_OVERLAP if _a_0_1 and b_0_1 else (

1576 E.V_OVERLAP if a_0 and b_0 else None)))

1577

1578 if T:

1579 if T is E.X_INTERSECT:

1580 v = p1 + a * self._dp

1581 yield T, (v, p1, p2, a), (v, q1, q2, b)

1582 elif T in E.Vs:

1583 yield T, (p1,), (q1,)

1584 else:

1585 if T in E.Qs:

1586 yield T, (p1,), (p1, q1, q2, b)

1587 if T in E.Ps:

1588 yield T, (q1, p1, p2, a), (q1,)

1589

1590

1591 class _EdgeGH(object):

1592 # An edge between two L{LatLonGH} points.

1593

1594 _raiser = False

1595 _xtend = False

1596

1597 def __init__(self, s1, s2, raiser=False, xtend=False, **unused):

1598 # New edge between points C{s1} and C{s2}, each a L{LatLonGH}.

1599 self._s1, self._s2 = s1, s2

1600 self._x_sx_y_sy = (s1.x, s2.x - s1.x,

1601 s1.y, s2.y - s1.y)

1602 self._lr, \

1603 self._bt = _left_right_bottom_top_eps2(s1, s2)

1604

1605 if xtend:

1606 self._xtend = True

1607 elif raiser:

1608 self._raiser = True

1609

1610 def _alpha2(self, x, y, dx, dy):

1611 # Return C{(alpha)}, see .points.nearestOn5

1612 a = (y * dy + x * dx) / self._hypot2

1613 d = (y * dx - x * dy) / self._hypot0

1614 return a, fabs(d)

1615

1616 def _Error(self, n, *args, **kwds): # PYCHOK no cover

1617 t = _DOT_(unstr(_EdgeGH, self._s1, self._s2),

1618 unstr(_EdgeGH._intersect4, *args, **kwds))

1619 return ClipError(_case_, n, txt=t)

1620

1621 @Property_RO

1622 def _hypot0(self):

1623 _, sx, _, sy = self._x_sx_y_sy

1624 return hypot(sx, sy) * _0_EPS

1625

1626 @Property_RO

1627 def _hypot2(self):

1628 _, sx, _, sy = self._x_sx_y_sy

1629 return hypot2(sx, sy)

1630

1631 def _intersect4(self, c1, c2, parallel=True): # MCCABE 14

1632 # Yield the intersection(s) of this and another edge.

1633

1634 # @return: None, 1 or 2 intersections, each a 4-Tuple

1635 # (y, x, s_alpha, c_alpha) with intersection

1636 # coordinates x and y and both alphas.

1637

1638 # @raise ClipError: Intersection unhandled.

1639

1640 # @see: U{Intersection point of two line segments

1641 # <http://PaulBourke.net/geometry/pointlineplane/>}.

1642 c1_x, c1_y = c1.x, c1.y

1643 if not (_outside(c1_x, c2.x, *self._lr) or

1644 _outside(c1_y, c2.y, *self._bt)):

1645 x, sx, \

1646 y, sy = self._x_sx_y_sy

1647

1648 cx = c2.x - c1_x

1649 cy = c2.y - c1_y

1650 d = cy * sx - cx * sy

1651

1652 if fabs(d) > _0_EPS: # non-parallel edges

1653 dx = x - c1_x

1654 dy = y - c1_y

1655 ca = (sx * dy - sy * dx) / d

1656 if _0_EPS < ca < _EPS_1 or (self._xtend and

1657 _EPS_0 < ca < _1_EPS):

1658 sa = (cx * dy - cy * dx) / d

1659 if _0_EPS < sa < _EPS_1 or (self._xtend and

1660 _EPS_0 < sa < _1_EPS):

1661 yield (y + sa * sy), (x + sa * sx), sa, ca

1662

1663 # unhandled, "degenerate" cases 1, 2 or 3

1664 elif self._raiser and not (sa < _EPS_0 or sa > _1_EPS): # PYCHOK no cover

1665 raise self._Error(1, c1, c2, sa=sa) # intersection at s1 or s2

1666

1667 elif self._raiser and not (ca < _EPS_0 or ca > _1_EPS): # PYCHOK no cover

1668 # intersection at c1 or c2 or at c1 or c2 and s1 or s2

1669 sa = (cx * dy - cy * dx) / d

1670 e = 2 if sa < _EPS_0 or sa > _1_EPS else 3

1671 raise self._Error(e, c1, c2, ca=ca)

1672

1673 elif parallel and (sx or sy) and (cx or cy): # PYCHOK no cover

1674 # non-null, parallel or colinear edges

1675 sa1, d1 = self._alpha2(c1_x - x, c1_y - y, sx, sy)

1676 sa2, d2 = self._alpha2(c2.x - x, c2.y - y, sx, sy)

1677 if max(d1, d2) < _0_EPS:

1678 if self._xtend and not _outside(sa1, sa2, _EPS_0, _1_EPS):

1679 if sa1 > sa2: # anti-parallel

1680 sa1, sa2 = sa2, sa1

1681 ca1, ca2 = _1_0, _0_0

1682 else: # parallel

1683 ca1, ca2 = _0_0, _1_0

1684 ca = fabs((sx / cx) if cx else (sy / cy))

1685 # = hypot(sx, sy) / hypot(cx, cy)

1686 if sa1 < 0: # s1 is between c1 and c2

1687 ca *= ca1 + sa1

1688 yield y, x, ca1, _alpha1(ca)

1689 else: # c1 is between s1 and s2

1690 yield (y + sa1 * sy), (x + sa1 * sx), sa1, ca1

1691 if sa2 > 1: # s2 is between c1 and c2

1692 ca *= sa2 - _1_0

1693 yield (y + sy), (x + sx), ca2, _alpha1(ca2 - ca)

1694 else: # c2 is between s1 and s2

1695 yield (y + sa2 * sy), (x + sa2 * sx), sa2, ca2

1696 elif self._raiser and not _outside(sa1, sa2, _0_0, _1_EPS):

1697 raise self._Error(4, c1, c2, d1=d1, d2=d2)

1698

1699

1700 class _BooleanBase(object):

1701 # Shared C{Boolean[FHP|GH]} methods.

1702

1703 def __add__(self, other):

1704 '''Sum: C{this + other} clips.

1705 '''

1706 return self._sum(_other(self, other), self.__add__) # PYCHOK OK

1707

1708 def __and__(self, other):

1709 '''Intersection: C{this & other}.

1710 '''

1711 return self._boolean(other, False, False, self.__and__) # PYCHOK OK

1712

1713 def __iadd__(self, other):

1714 '''In-place sum: C{this += other} clips.

1715 '''

1716 return self._inplace(self.__add__(other))

1717

1718 def __iand__(self, other):

1719 '''In-place intersection: C{this &= other}.

1720 '''

1721 return self._inplace(self.__and__(other))

1722

1723 def __ior__(self, other):

1724 '''In-place union: C{this |= other}.

1725 '''

1726 return self._inplace(self.__or__(other))

1727

1728 def __or__(self, other):

1729 '''Union: C{this | other}.

1730 '''

1731 return self._boolean(other, True, True, self.__or__) # PYCHOK OK

1732

1733 def __radd__(self, other):

1734 '''Reverse sum: C{other + this} clips.

1735 '''

1736 return _other(self, other)._sum(self, self.__radd__)

1737

1738 def __rand__(self, other):

1739 '''Reverse intersection: C{other & this}

1740 '''

1741 return _other(self, other).__and__(self)

1742

1743 def __ror__(self, other):

1744 '''Reverse union: C{other | this}

1745 '''

1746 return _other(self, other).__or__(self)

1747

1748 def _boolean4(self, other, op):

1749 # Set up a new C{Boolean[FHP|GH]}.

1750 C = self.__class__

1751 kwds = C._kwds(self, op)

1752 a = C(self, **kwds)

1753 b = _other(self, other)

1754 return a, b, C, kwds

1755

1756 def _inplace(self, r):

1757 # Replace this with a L{Boolean*} result.

1758 self._clips, r._clips = r._clips, None

1759# if self._raiser != r._raiser:

1760# self._raiser = r._raiser

1761# if self._xtend != r._xtend:

1762# self._xtend = r._xtend

1763# if self._eps != r._eps:

1764# self._eps = r._eps

1765 return self

1766

1767

1768 class BooleanFHP(_CompositeFHP, _BooleanBase):

1769 '''I{Composite} class providing I{boolean} operations between two

1770 I{composites} using U{Forster-Hormann-Popa<https://www.ScienceDirect.com/

1771 science/article/pii/S259014861930007X>}'s C++ implementation, transcoded

1772 to pure Python.

1773

1774 The supported operations between (composite) polygon A and B are:

1775

1776 - C = A & B or A &= B, intersection of A and B

1777

1778 - C = A + B or A += B, sum of A and B clips

1779

1780 - C = A | B or A |= B, union of A and B

1781

1782 - A == B or A != B, equivalent A and B clips

1783

1784 - A.isequalTo(B, eps), equivalent within tolerance

1785

1786 @see: Methods C{__eq__} and C{isequalTo}, function L{clipFHP4}

1787 and class L{BooleanGH}.

1788 '''

1789 _kind = _boolean_

1790

1791 def __init__(self, lls, raiser=False, eps=EPS, **name):

1792 '''New L{BooleanFHP} operand for I{boolean} operation.

1793

1794 @arg lls: The polygon points and clips (iterable of L{LatLonFHP}s,

1795 L{ClipFHP4Tuple}s or other C{LatLon}s).

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

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

1798 units as the B{C{lls}} coordinates).

1799 @kwarg name: Optional C{B{name}=NN} (C{str}).

1800 '''

1801 _CompositeFHP.__init__(self, lls, raiser=raiser, eps=eps, **name)

1802

1803 def __isub__(self, other):

1804 '''Not implemented.'''

1805 return _NotImplemented(self, other)

1806

1807 def __rsub__(self, other):

1808 '''Not implemented.'''

1809 return _NotImplemented(self, other)

1810

1811 def __sub__(self, other):

1812 '''Not implemented.'''

1813 return _NotImplemented(self, other)

1814

1815 def _boolean(self, other, Union, unused, op):

1816 # One C{BooleanFHP} operation.

1817 p, q, C, kwds = self._boolean4(other, op)

1818 r = p._clip(q, Union=Union, **kwds)

1819 return C(r, **kwds)

1820

1821

1822 class BooleanGH(_CompositeGH, _BooleanBase):

1823 '''I{Composite} class providing I{boolean} operations between two

1824 I{composites} using the U{Greiner-Hormann<http://www.Inf.USI.CH/

1825 hormann/papers/Greiner.1998.ECO.pdf>} algorithm and U{Correia

1826 <https://GitHub.com/helderco/univ-polyclip>}'s implementation,

1827 modified and extended.

1828

1829 The supported operations between (composite) polygon A and B are:

1830

1831 - C = A - B or A -= B, difference A less B

1832

1833 - C = B - A or B -= A, difference B less B

1834

1835 - C = A & B or A &= B, intersection of A and B

1836

1837 - C = A + B or A += B, sum of A and B clips

1838

1839 - C = A | B or A |= B, union of A and B

1840

1841 - A == B or A != B, equivalent A and B clips

1842

1843 - A.isequalTo(B, eps), equivalent within tolerance

1844

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

1846 C{point-point} intersections, use class L{BooleanFHP}.

1847

1848 @see: Methods C{__eq__} and C{isequalTo}, function L{clipGH4}

1849 and class L{BooleanFHP}.

1850 '''

1851 _kind = _boolean_

1852

1853 def __init__(self, lls, raiser=True, xtend=False, eps=EPS, **name):

1854 '''New L{BooleanFHP} operand for I{boolean} operation.

1855

1856 @arg lls: The polygon points and clips (iterable of L{LatLonGH}s,

1857 L{ClipGH4Tuple}s or other C{LatLon}s).

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

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

1860 attempt to handle the latter (C{bool}).

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

1862 units as the B{C{lls}} coordinates).

1863 @kwarg name: Optional C{B{name}=NN} (C{str}).

1864 '''

1865 _CompositeGH.__init__(self, lls, raiser=raiser, xtend=xtend, eps=eps, **name)

1866

1867 def _boolean(self, other, s_entry, c_entry, op):

1868 # One C{BooleanGH} operation.

1869 s, c, C, kwds = self._boolean4(other, op)

1870 r = s._clip(c, s_entry, c_entry, **kwds)

1871 return C(r, **kwds)

1872

1873 def __isub__(self, other):

1874 '''In-place difference: C{this -= other}.

1875 '''

1876 return self._inplace(self.__sub__(other))

1877

1878 def __rsub__(self, other):

1879 ''' Reverse difference: C{other - this}

1880 '''

1881 return _other(self, other).__sub__(self)

1882

1883 def __sub__(self, other):

1884 '''Difference: C{this - other}.

1885 '''

1886 return self._boolean(other, True, False, self.__sub__)

1887

1888

1889 def _alpha1(alpha):

1890 # Return C{alpha} in C{[0..1]} range

1891 if _EPS_0 < alpha < _1_EPS:

1892 return max(_0_0, min(alpha, _1_0))

1893 t = _not_(Fmt.SQUARE(_ELLIPSIS_(0, 1)))

1894 raise ClipError(_alpha_, alpha, txt=t)

1895

1896

1897 def _alpha4(a):

1898 # Return 4-tuple (alpha, -EPS < alpha < EPS,

1899 # 0 < alpha < 1,

1900 # not 0 < alpha < 1)

1901 return (a, False, True, False) if _0_EPS < a < _EPS_1 else (

1902 (a, False, False, True) if _0_EPS < fabs(a) else

1903 (a, True, False, False))

1904

1905

1906 def _Cps(Cp, composites_points, where):

1907 # Yield composites and points as a C{Cp} composite.

1908 try:

1909 kwds = dict(kind=_points_, name__=where)

1910 for cp in composites_points:

1911 yield cp if isBoolean(cp) else Cp(cp, **kwds)

1912 except (AttributeError, ClipError, TypeError, ValueError) as x:

1913 raise _ValueError(points=cp, cause=x)

1914

1915

1916 def _eps0(eps):

1917 # Adjust C{eps} or C{None}.

1918 return eps if eps and eps > EPS else 0

1919

1920

1921 def isBoolean(obj):

1922 '''Check for C{Boolean} composites.

1923

1924 @arg obj: The object (any C{type}).

1925

1926 @return: C{True} if B{C{obj}} is L{BooleanFHP}, L{BooleanGH}

1927 or some other composite, C{False} otherwise.

1928 '''

1929 return isinstance(obj, _CompositeBase)

1930

1931

1932 def _left_right_bottom_top_eps2(p1, p2):

1933 '''(INTERNAL) Return 2-tuple C{(left, right), (bottom, top)}, oversized.

1934 '''

1935 return (_min_max_eps2(p1.x, p2.x),

1936 _min_max_eps2(p1.y, p2.y))

1937

1938

1939 def _low_high_eps2(lo, hi, eps):

1940 '''(INTERNAL) Return 2-tuple C{(lo, hi)}, oversized.

1941 '''

1942 lo *= (_1_0 + eps) if lo < 0 else (_1_0 - eps)

1943 hi *= (_1_0 - eps) if hi < 0 else (_1_0 + eps)

1944 return (lo or -eps), (hi or eps)

1945

1946

1947 def _min_max_eps2(*xs):

1948 '''(INTERNAL) Return 2-tuple C{(min, max)}, oversized.

1949 '''

1950 lo, hi = min(xs), max(xs)

1951 lo *= _1_EPS if lo < 0 else _EPS_1

1952 hi *= _EPS_1 if hi < 0 else _1_EPS

1953 return (lo or _EPS_0), (hi or _0_EPS)

1954

1955

1956 def _other(this, other):

1957 '''(INTERNAL) Check for compatible C{type}s.

1958 '''

1959 C = this.__class__

1960 if isinstance(other, C):

1961 return other

1962 raise _IsnotError(C, other=other)

1963

1964

1965 def _outside(x1, x2, lo, hi):

1966 '''(INTERNAL) Is C{(x1, x2)} outside C{(lo, hi)}?

1967 '''

1968 return max(x1, x2) < lo or min(x1, x2) > hi

1969

1970

1971__all__ += _ALL_DOCS(_BooleanBase, _Clip,

1972 _CompositeBase, _CompositeFHP, _CompositeGH,

1973 _LatLonBool)

1974

1975# **) MIT License

1976#

1977# Copyright (C) 2018-2024 -- mrJean1 at Gmail -- All Rights Reserved.

1978#

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

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

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

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

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

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

1985#

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

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

1988#

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

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

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

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

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

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

1995# OTHER DEALINGS IN THE SOFTWARE.

1996

1997# ***) GNU GPL 3

1998#

1999# Copyright (C) 2011-2012 Helder Correia <Helder.MC@Gmail.com>

2000#

2001# This program is free software: you can redistribute it and/or

2002# modify it under the terms of the GNU General Public License as

2003# published by the Free Software Foundation, either version 3 of

2004# the License, or any later version.

2005#

2006# This program is distributed in the hope that it will be useful,

2007# but WITHOUT ANY WARRANTY; without even the implied warranty of

2008# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the

2009# GNU General Public License for more details.

2010#

2011# You should have received a copy of the GNU General Public License

2012# along with this program. If not, see <http://www.GNU.org/licenses/>.

2013#

2014# You should have received the README file along with this program.

2015# If not, see <https://GitHub.com/helderco/univ-polyclip>.