lib/Database/BI/Model/Boundary.pm

Structural Coverage (Approximate)

TER1 (Statement): 100.00%
TER2 (Branch): 98.90%
TER3 (LCSAJ): 100.0% (16/16)
Approximate LCSAJ segments: 183

LCSAJ Legend

โ— Covered โ€” this LCSAJ path was executed during testing.

โ— Not covered โ€” this LCSAJ path was never executed. These are the paths to focus on.

Multiple dots on a line indicate that multiple control-flow paths begin at that line. Hovering over any dot shows:

        start โ†’ end โ†’ jump
        

Uncovered paths show [NOT COVERED] in the tooltip.

Mutant Testing Legend

Survived (tests missed this) Killed (tests detected this) No mutation
    1: package Database::BI::Model::Boundary;
    2: 
    3: # The outline of the area each map marker is in: its country, state or
    4: # province, county, city, town or neighbourhood (the level).
    5: #
    6: # A map can draw the boundary of the area around each of its markers.  The
    7: # outlines come from OpenStreetMap's Nominatim, through its reverse lookup:
    8: # given a point and a zoom, it names the administrative area there and, with
    9: # polygon_geojson, sends its shape.  Asking by point rather than by name means
   10: # the same code serves coordinate columns and geocoded places, in any country,
   11: # and needs no state or country column to tell one Richmond from another.
   12: #
   13: # Nominatim allows one request a second, so this module asks as little as it
   14: # can:
   15: #
   16: #   1. Each point is rounded to 3 decimal places (about 110 m), which is also
   17: #      all of it that leaves this machine, and remembered with the outline it
   18: #      fell in (or with none, for a point at sea).
   19: #   2. A point not remembered is first tested against the outlines already
   20: #      known, through an index of their bounding boxes, so ten thousand shops
   21: #      in one county cost one request, not ten thousand.
   22: #   3. Only then is Nominatim asked, at most online_max times a call, and a
   23: #      point it does not answer is left pending, not remembered as nowhere.
   24: #
   25: # The outlines are simplified by Nominatim (polygon_threshold), about 7 KB each,
   26: # because they are written into the page.
   27: #
   28: # What Nominatim has at each level differs by country, and was probed in
   29: # November 2026 (the points and what came back are in the comments at %LEVELS).
   30: # A level is therefore a plan: a list of tries, each a reverse zoom and the
   31: # place ranks an answer may have, taken in order until one gives an outline.
   32: #
   33: #   country        zoom 3, rank 4.
   34: #   state          zoom 5, rank 8: a US or Indian state, a Canadian province, a
   35: #                  New Zealand region, England or Scotland.
   36: #   county         below, one rank a country.
   37: #   city           zoom 10, ranks 12 to 16, an administrative area or a place
   38: #                  mapped as an area: Toronto, Manchester, Canterbury (the
   39: #                  district), Bristol.  Where zoom 10 gives only a point (York,
   40: #                  Pune), zoom 8 at rank 12: the unitary authority or city
   41: #                  district.  A point in no city gets its rank 12 area
   42: #                  too (a US county): zoom 10 answers with it.  New Zealand's cities are its territorial
   43: #                  authorities, rank 12 at zoom 8 (Hamilton City), or the region
   44: #                  where that is one (Auckland).
   45: #   town           zoom 12, ranks 13 to 18: Margate, a Toronto ward.  Then zoom
   46: #                  14, ranks 19 and 20, administrative areas only: a town
   47: #                  that is a civil parish (Westgate-on-Sea).
   48: #   neighbourhood  zoom 14, ranks 17 to 20: a Toronto neighbourhood, an English
   49: #                  civil parish (Westgate-on-Sea), a suburb mapped as an area
   50: #                  (Manchester's City Centre).  Most suburbs are mapped as a
   51: #                  point (Cliftonville, Garlinge), and those have no outline.
   52: #
   53: # The larger the area, the more its outline is simplified (the level's detail),
   54: # or a country would be megabytes.  An outline is kept under its detail, so one
   55: # relation drawn at two levels (Auckland, a state and a city) is kept twice.
   56: #
   57: # A "county" is the division of a country below its states.  Which
   58: # of Nominatim's place ranks that is depends on the country, so %LEVELS gives a
   59: # rank for most (12: a US county, an English county, a German Landkreis, a
   60: # French departement, a Pakistani district) and the countries that differ (10:
   61: # an Indian or Bangladeshi district, a Chinese prefecture, a Spanish province;
   62: # 8: a Kenyan county), and config map_bounds_ranks can add more.  Each reply
   63: # names its country, so a point is asked at the zoom of the last country seen,
   64: # and again at its own country's zoom when that guess was wrong: one extra
   65: # request at each border a map crosses.  The rank an outline was accepted at is
   66: # kept with it, so a changed table asks again rather than draw the old level.
   67: # The other levels do the same with their plans: a point is asked the first try
   68: # of the last country's plan, and its own country's plan from there.
   69: 
   70: use strict;
   71: use warnings;
   72: 
   73: use Carp			qw(croak);
   74: use JSON::PP			();
   75: use List::Util			qw(first);
   76: use Params::Get			();
   77: use Params::Validate::Strict	qw(validate_strict);
   78: use Readonly;
   79: use Scalar::Util		qw(blessed);
   80: use Storable			qw(dclone);
   81: use URI				();
   82: 
   83: our $VERSION = '0.025.0';
   84: 
   85: # The place rank an answer must have at each level: rank for a country not
   86: # listed, countries for those that differ, by ISO 3166-1 alpha-2 code.  Checked
   87: # against Nominatim's reverse lookup in November 2026: rank 12
   88: # at zoom 8 is the county level in the US, UK, Ireland, Germany, France, Italy,
   89: # Pakistan, Mexico, Nigeria, South Africa, Russia, Indonesia and Canada.
   90: # Australia, Brazil and Japan have nothing between their states and their
   91: # towns, so a point there is nowhere.
   92: #
   93: # The other levels are plans: tries => [ { zoom, ranks => [low, high], places } ],
   94: # with plans => { country => [ tries ] } for a country that differs.  places
   95: # lets a try take a place mapped as an area (place=city, town, suburb; a
   96: # relation or a closed way) as well as an administrative boundary.  detail is
   97: # how far Nominatim may move an outline's edge to simplify it, in degrees, as
   98: # text: it is stored with each outline and compared.  name and names are what
   99: # the area is called, as a word a caller can name it by to its readers
  100: # (name_for).  What the reverse lookup gave, November 2026 (zoom: rank, name):
  101: #
  102: #   Toronto         5: 8 Ontario; 8 and 10: 12 Toronto; 12: 18 Toronto Centre
  103: #                   (ward); 14: 20 Financial District
  104: #   Pune            5: 8 Maharashtra; 8: 12 Pune City Subdistrict; 10 and up:
  105: #                   points only
  106: #   Canterbury      8: 12 Kent; 10 and 12: 16 Canterbury (the district)
  107: #   Manchester      8: 10 Greater Manchester; 10: 16 Manchester; 14: 19 City
  108: #                   Centre (place=suburb, a way)
  109: #   Bristol, York   8: 12, the unitary authority; 10: 16 Bristol (place=city, a
  110: #                   relation), York a point
  111: #   Hamilton NZ     5: 8 Waikato; 8, 10 and 12: 12 Hamilton City
  112: #   Auckland        5 and 8: 8 Auckland; 10: 16 Waitemata (a local board)
  113: #   Wellington      8: 12 Wellington City; 10: a point
  114: #   Margate         10: 16 Thanet; 12: 18 Margate (place=town, a relation); 13
  115: #                   and 14: points (Cliftonville, Westbrook, Garlinge)
  116: #   Westgate-on-Sea 14: 20, the civil parish; 12: 18 Birchington, a point
  117: Readonly my %LEVELS => (
  118: 	country => {
  119: 		name   => 'country',
  120: 		detail => '0.02',	# Canada 15 KB, India 29 KB
  121: 		tries  => [ { zoom => 3, ranks => [ 4, 4 ] } ],
  122: 	},
  123: 	state => {
  124: 		name   => 'state',
  125: 		names  => {
  126: 			ca => 'province', cn => 'province', es => 'region', fr => 'region',
  127: 			gb => 'country', it => 'region', jp => 'prefecture', nl => 'province',
  128: 			nz => 'region', pk => 'province', za => 'province',
  129: 		},
  130: 		detail => '0.01',	# Ontario 12 KB, Maharashtra 30 KB, England 7 KB
  131: 		tries  => [ { zoom => 5, ranks => [ 8, 8 ] } ],
  132: 	},
  133: 	county => {
  134: 		rank      => 12,
  135: 		countries => {
  136: 			bd => 10,	# district (zila); 12 is an upazila
  137: 			cn => 10,	# prefecture-level city; 12 is a district
  138: 			es => 10,	# province; Spain has no rank 12
  139: 			in => 10,	# district; 12 is a sub-district (tehsil, taluk)
  140: 			ke => 8,	# county; 12 is a sub-county
  141: 		},
  142: 		name  => 'county',
  143: 		names => {
  144: 			bd => 'district', cn => 'prefecture', de => 'district', es => 'province',
  145: 			fr => 'department', in => 'district', it => 'province',
  146: 		},
  147: 		# About 100 m.  Each outline is simplified alone, so neighbours' shared
  148: 		# borders differ by up to this, which shows as gaps and overlaps now
  149: 		# that each is drawn on its own side of the border; 0.005 (500 m, 2 KB
  150: 		# a county) was 7 pixels out at the zoom a county fills the map, this
  151: 		# (7 KB) under 2.
  152: 		detail => '0.001',
  153: 	},
  154: 	city => {
  155: 		name   => 'city',
  156: 		names  => { gb => 'district', nz => 'district' },
  157: 		detail => '0.0005',	# Thanet 4 KB
  158: 		tries  => [
  159: 			{ zoom => 10, ranks => [ 12, 16 ], places => 1 },
  160: 			{ zoom => 8,  ranks => [ 12, 12 ] },
  161: 		],
  162: 		plans  => {
  163: 			nz => [ { zoom => 8, ranks => [ 8, 12 ] } ],
  164: 		},
  165: 	},
  166: 	town => {
  167: 		name   => 'town',
  168: 		detail => '0.0002',
  169: 		tries  => [
  170: 			{ zoom => 12, ranks => [ 13, 18 ], places => 1 },
  171: 			# A parished English town is its civil parish, rank 20, and zoom
  172: 			# 12 there answers with the nearest town mapped as a point.
  173: 			{ zoom => 14, ranks => [ 19, 20 ] },
  174: 		],
  175: 	},
  176: 	neighbourhood => {
  177: 		name   => 'neighbourhood',
  178: 		detail => '0.0002',	# Westgate-on-Sea 1 KB
  179: 		tries  => [ { zoom => 14, ranks => [ 17, 20 ], places => 1 } ],
  180: 	},
  181: );
  182: 
  183: # The levels, largest area first: the order a reader chooses from.
  184: Readonly my @LEVEL_ORDER => qw(country state county city town neighbourhood);
  185: 
  186: # The reverse zoom that asks for each rank.  A zoom names the most detailed
  187: # rank it may return, so a point with no area at that rank comes back as
  188: # something larger (a state), which the rank check turns away rather than
  189: # drawing.
  190: Readonly my %ZOOM_FOR_RANK => (8 => 5, 10 => 6, 12 => 8);

Mutants (Total: 2, Killed: 2, Survived: 0)

191: 192: Readonly my $REVERSE_URL => 'https://nominatim.openstreetmap.org/reverse'; 193: # The detail outlines had before levels did (the county's): an outline at it is 194: # kept under its plain key, so a cache from 0.023.0 is still read. 195: Readonly my $PLAIN_DETAIL => '0.001'; 196: Readonly my $DECIMALS => 3; # of a point, in its key and in what is sent 197: Readonly my $DEFAULT_MAX => 20; # Nominatim requests in one call, as map_geocode_online_max 198: Readonly my $CACHE_DIR => 'boundary-cache'; # under model_dir, for file_cache() 199: Readonly my $CACHE_NAMESPACE => __PACKAGE__; 200: Readonly my $CACHE_MAX_SIZE => 8 * 1024 * 1024; # bytes, for the process-wide default 201: 202: my $json = JSON::PP->new->canonical->utf8; 203: 204: =head1 NAME 205: 206: Database::BI::Model::Boundary - The outline of the area around each map marker 207: 208: =head1 VERSION 209: 210: 0.025.0 211: 212: =head1 SYNOPSIS 213: 214: use Database::BI::Model::Boundary; 215: 216: my $boundary = Database::BI::Model::Boundary->new( 217: cache => Database::BI::Model::Boundary->file_cache('.bi'), 218: online => 1, 219: level => 'state', # country, state, county (default), city, town, neighbourhood 220: ); 221: 222: my $result = $boundary->outlines([ [ 39.09, -77.64 ], [ 38.85, -77.31 ] ]); 223: $map->add_geojson( 224: { type => 'FeatureCollection', features => $result->{features} }, 225: name => 'County boundaries', 226: ); 227: 228: # A point the map page listed as pending, looked up on its own 229: my $answer = $boundary->lookup_point($result->{pending}[0]);

Mutants (Total: 2, Killed: 2, Survived: 0)

230: 231: =head1 DESCRIPTION 232: 233: Finds the area each point is in, at one level, and returns its outline as a GeoJSON 234: Feature, for L<HTML::OSM>'s C<add_geojson>. The outlines come from 235: OpenStreetMap's Nominatim reverse lookup, through the same throttled user agent 236: as the geocoder (L<Database::BI::Model::Geocode/nominatim_ua>), so the two 237: together never ask more than once a second. 238: 239: Only the point is sent, rounded to three decimal places (about 110 metres). 240: Every answer is cached: a point with the outline it is in, and the outline 241: itself. A point inside an outline already known is matched here, without a 242: request, so many points in one county cost one lookup. 243: 244: The levels, largest first: 245: 246: =over 4 247: 248: =item country 249: 250: =item state 251: 252: A US or Indian state, a Canadian province, a New Zealand region, England. 253: 254: =item county

Mutants (Total: 2, Killed: 2, Survived: 0)

255: 256: The default; see below. 257: 258: =item city 259: 260: A city or the district named after it: Toronto, Manchester, the district of 261: Canterbury, Hamilton City in New Zealand. Where OpenStreetMap has no city round a point, or has the city only as a point 262: (York, Pune), the area at the county's rank there: the unitary authority, the 263: city district, or the county itself. 264: 265: =item town 266: 267: A town or city ward: Margate, Toronto Centre. An English town that is a civil 268: parish (Westgate-on-Sea) is that parish. 269: 270: =item neighbourhood 271: 272: A neighbourhood, suburb or civil parish that OpenStreetMap has as an area. 273: Many suburbs are mapped only as a point, and those have no outline. 274:

Mutants (Total: 2, Killed: 2, Survived: 0)

275: =back 276: 277: Larger areas are simplified more, so an outline is a few kilobytes at any 278: level. 279: 280: A county here is the division of a country below its states, whose place rank 281: in Nominatim depends on the country: 12 (a US county or independent city, an 282: English county, a German Landkreis, a French departement) unless the country is 283: listed otherwise: 10 for India, Bangladesh, China and Spain (district, 284: prefecture, province), 8 for Kenya. C<ranks> adds or changes countries. 285: Anything else Nominatim answers is taken as "no county here" and remembered as 286: such. A country with nothing at its rank (Australia, Brazil, Japan) gets no 287: outlines. 288: 289: Each reply names the point's country, so a point is asked at the zoom of the 290: last country seen, and asked again when its own country wants another rank. 291: An outline is kept with the rank it was accepted at; when C<ranks> changes, the 292: points it covered are asked again. 293: 294: =head1 METHODS 295: 296: =head2 new 297: 298: my $boundary = Database::BI::Model::Boundary->new(%args); 299: 300: =head3 API SPECIFICATION

Mutants (Total: 3, Killed: 0, Survived: 3)
301: 302: =head4 INPUT 303: 304: cache : object with get() and set() (CHI) optional; default one 305: CHI Memory cache for the process 306: online : boolean optional, default 0: may Nominatim be asked 307: online_max : integer optional, default 20: requests in one outlines() call

Mutants (Total: 2, Killed: 2, Survived: 0)

308: level : string optional, default 'county'; one of levels() 309: ranks : hashref optional: { country code => place rank }, over the 310: county level's own list; codes are two letters (any case), 311: ranks 8, 10 or 12. The other levels ignore it 312: ua : object with get() optional: the user agent to ask with 313: (tests); default Geocode::nominatim_ua() 314: 315: =head4 OUTPUT 316: 317: A Database::BI::Model::Boundary object. Croaks on an unknown level, a cache 318: without get and set, or ranks that are not a hash of two-letter codes to 8, 10 319: or 12. 320: 321: =cut 322: 323: sub new { 324: my $class = shift; 325: my $raw = Params::Get::get_params(undef, \@_) // {}; 326: 327: my $args = validate_strict( 328: schema => { 329: cache => { type => 'object', optional => 1, default => undef }, 330: online => { type => 'boolean', optional => 1, default => 0 }, 331: online_max => { type => 'integer', optional => 1, default => $DEFAULT_MAX, min => 0 }, 332: level => { type => 'string', optional => 1, default => 'county' }, 333: ua => { type => 'object', optional => 1, default => undef, can => 'get' }, 334: ranks => { type => 'hashref', optional => 1, default => undef }, 335: }, 336: input => $raw, 337: ); 338: 339: my $level_name = $args->{level} // ''; 340: my $level = $LEVELS{$level_name} 341: or croak "Unknown boundary level '$level_name'"; 342: croak 'The boundary cache needs get() and set()' 343: if defined($args->{cache}) && !($args->{cache}->can('get') && $args->{cache}->can('set')); 344: 345: return bless { 346: %{$args}, 347: ranks => { %{ $level->{countries} // {} }, %{ $class->check_ranks($args->{ranks} // {}) } }, 348: cache => $args->{cache} // _default_cache(), 349: }, $class; 350: } 351: 352: =head2 check_ranks 353: 354: my $ranks = Database::BI::Model::Boundary->check_ranks({ LK => 10 }); # { lk => 10 } 355: 356: =head3 API SPECIFICATION 357: 358: =head4 INPUT 359: 360: ranks : hashref of { country code => place rank }

Mutants (Total: 1, Killed: 1, Survived: 0)

361: Domains: a code is exactly two ASCII letters (any case); a rank is

Mutants (Total: 1, Killed: 1, Survived: 0)

362: 8, 10 or 12 as a whole number (7, 9, 11, 13, '08' and '8 ' are not) 363:

Mutants (Total: 3, Killed: 3, Survived: 0)

364: =head4 OUTPUT 365: 366: A new hashref with the codes in lower case and the ranks as numbers. Croaks 367: on a value that is not a hashref, a key that is not a two-letter code, or a 368: rank that is not 8, 10 or 12, naming the entry. Used by C<new> and by the 369: application's startup check of C<map_bounds_ranks>.

Mutants (Total: 1, Killed: 1, Survived: 0)

370: 371: =cut 372: 373: sub check_ranks {

Mutants (Total: 1, Killed: 1, Survived: 0)

โ—374 โ†’ 378 โ†’ 386 374: my (undef, $ranks) = @_; 375: croak 'Boundary ranks must be a hash of country codes to place ranks' 376: unless ref($ranks) eq 'HASH'; 377: my %checked; 378: for my $code (sort keys %{$ranks}) { 379: my $rank = $ranks->{$code}; 380: croak "'$code' is not a two-letter country code" unless $code =~ /\A[A-Za-z]{2}\z/; 381: croak "the rank for '$code' must be one of " . join(', ', sort { $a <=> $b } keys %ZOOM_FOR_RANK) 382: unless defined($rank) && !ref($rank) && $rank =~ /\A[0-9]+\z/ && $ZOOM_FOR_RANK{$rank}; 383: croak "'$code' is given twice" if exists $checked{ lc $code }; 384: $checked{ lc $code } = $rank + 0; 385: } 386: return \%checked; 387: } 388: 389: =head2 rank_for 390: 391: my $rank = $boundary->rank_for('in'); # 10 392: 393: =head3 API SPECIFICATION 394: 395: =head4 INPUT 396: 397: country : string, an ISO 3166-1 alpha-2 code in any case; undef or '' 398: for a point in no country (the sea) 399: 400: =head4 OUTPUT 401: 402: The place rank an outline in that country must have at the county level: the 403: country's own, from C<ranks> or the built-in list, else 12. At another level, 404: the most detailed rank its first try takes there. 405: 406: =cut 407: 408: sub rank_for { 409: my ($self, $country) = @_; 410: my $level = $LEVELS{ $self->{level} }; 411: return $self->_plan($country)->[0]{ranks}[1] unless defined $level->{rank}; 412: my $rank = (defined($country) && !ref($country) && length($country)) 413: ? $self->{ranks}{ lc $country } : undef; 414: return $rank // $level->{rank}; 415: } 416: 417: =head2 name_for 418: 419: my $word = $boundary->name_for('in'); # 'district' 420: 421: What this object's level is called in a country, so a caller can say 422: "district" on a map of India rather than "county". 423: 424: =head3 API SPECIFICATION 425: 426: =head4 INPUT 427: 428: country : string, an ISO 3166-1 alpha-2 code in any case; undef or '' 429: for a point in no country 430: 431: =head4 OUTPUT 432: 433: One lower-case English word: C<country>, C<state>, C<region>, C<province>, 434: C<prefecture>, C<county>, C<district>, C<department>, C<city>, C<town> or

Mutants (Total: 1, Killed: 1, Survived: 0)

435: C<neighbourhood>. A country not listed gets the level's own name 436: (L</level_name>). It is a word to look a translation up by, not text to show. 437: Called on the class, it answers for the county level. 438: 439: =cut 440: 441: sub name_for { 442: my ($self, $country) = @_; 443: my $level = $LEVELS{ ref($self) ? $self->{level} : 'county' }; 444: my $name = (defined($country) && !ref($country) && length($country)) 445: ? ($level->{names} // {})->{ lc $country } : undef; 446: return $name // $level->{name}; 447: } 448: 449: =head2 level_name 450: 451: my $word = Database::BI::Model::Boundary->level_name('state'); # 'state' 452: 453: =head3 API SPECIFICATION 454: 455: =head4 INPUT 456: 457: level : string, one of levels() 458: 459: =head4 OUTPUT 460: 461: What the level's areas are called where no country says otherwise, as 462: L</name_for> gives it: the word to use before a point's country is known. 463: Undef for a level that is not one. 464: 465: =cut 466: 467: sub level_name { 468: my (undef, $level) = @_; 469: return unless defined($level) && !ref($level) && $LEVELS{$level}; 470: return $LEVELS{$level}{name}; 471: } 472:

Mutants (Total: 2, Killed: 2, Survived: 0)

473: =head2 levels 474: 475: my @levels = Database::BI::Model::Boundary->levels; 476: # ('country', 'state', 'county', 'city', 'town', 'neighbourhood') 477: 478: =head3 API SPECIFICATION 479: 480: =head4 INPUT 481: 482: None. 483: 484: =head4 OUTPUT 485: 486: The names of the levels new() takes, the largest area first. 487: 488: =cut 489: 490: sub levels { 491: return @LEVEL_ORDER; 492: } 493: 494: =head2 point_key 495: 496: my $key = Database::BI::Model::Boundary->point_key(39.0901, -77.6402); # '39.090,-77.640' 497: 498: =head3 API SPECIFICATION 499:

Mutants (Total: 2, Killed: 0, Survived: 2)
500: =head4 INPUT 501: 502: lat : number -90 .. 90 503: lon : number -180 .. 180 504: 505: Domains: each is a plain decimal, an optional minus and ASCII digits with an 506: optional fraction (1, -1.5, 12.345678). A plus sign, a bare point (.5, 5.), 507: an exponent, spaces, a newline, a comma, NaN, Inf and non-ASCII digits are 508: not numbers here. The edges -90, 90, -180 and 180 are in; anything past 509: them, however slightly (90.0001), is out, even if it would round to an edge.

Mutants (Total: 2, Killed: 2, Survived: 0)

510: 511: =head4 OUTPUT 512: 513: The point rounded to three decimal places, as C<"lat,lon">: what the cache is 514: keyed by and all of the point that is sent. Undef for a point out of range.

Mutants (Total: 2, Killed: 0, Survived: 2)
515: 516: =cut 517: 518: sub point_key { 519: my (undef, $lat, $lon) = @_;

Mutants (Total: 2, Killed: 2, Survived: 0)

520: 521: return unless defined($lat) && defined($lon) 522: && $lat =~ /\A-?[0-9]+(?:\.[0-9]+)?\z/ && $lon =~ /\A-?[0-9]+(?:\.[0-9]+)?\z/ 523: && abs($lat) <= 90 && abs($lon) <= 180; 524: 525: my @parts = map { 526: my $text = sprintf("%.${DECIMALS}f", $_); 527: $text =~ s/\A-(?=0\.0+\z)//; # no "-0.000", so a point has one key 528: $text; 529: } ($lat, $lon); 530: return join(',', @parts);

Mutants (Total: 2, Killed: 2, Survived: 0)

531: } 532: 533: =head2 outlines 534: 535: my $result = $boundary->outlines(\@points, lookup => 1); 536: 537: =head3 API SPECIFICATION 538: 539: =head4 INPUT 540: 541: points : arrayref of [lat, lon]

Mutants (Total: 1, Killed: 1, Survived: 0)

542: lookup : boolean, default 1. 0 asks Nominatim nothing: the points not 543: known yet come back in pending, for the caller to look up one at 544: a time (lookup_point)

Mutants (Total: 1, Killed: 1, Survived: 0)

545: 546: =head4 OUTPUT 547: 548: { 549: features => [ GeoJSON Feature, ... ] one per outline, in the order 550: their first point came; properties { name, osm, called } 551: (called: what the division is called there, as name_for) 552: pending => [ point_key, ... ] points not known, not asked 553: inside => { point_key => osm, ... } the outline each point drawn is in, 554: by the osm of its Feature (to total what is in each)

Mutants (Total: 6, Killed: 6, Survived: 0)

555: counts => { points, drawn, attempted, nowhere } 556: offline => 0|1 points were left because Nominatim may not be asked 557: failed => 0|1 Nominatim did not answer; the rest were left 558: } 559: 560: A point out of range is ignored. A Feature's name is the place's name as 561: OpenStreetMap has it: text, not HTML. 562: 563: =cut 564: 565: sub outlines { โ—566 โ†’ 574 โ†’ 580 566: my ($self, $points, @rest) = @_; 567: croak 'outlines() needs an arrayref of [lat, lon]' unless ref($points) eq 'ARRAY'; 568: my %opt = @rest;

Mutants (Total: 2, Killed: 2, Survived: 0)

569: my $lookup = exists($opt{lookup}) ? $opt{lookup} : 1;

Mutants (Total: 3, Killed: 3, Survived: 0)

570: 571: local ($@, $!); 572: 573: my (@keys, %seen); 574: for my $point (@{$points}) { 575: next unless ref($point) eq 'ARRAY'; 576: my $key = $self->point_key(@{$point}[0, 1]); 577: push @keys, $key if defined($key) && !$seen{$key}++; 578: }

Mutants (Total: 1, Killed: 1, Survived: 0)

579: โ—580 โ†’ 584 โ†’ 607 580: my %counts = (points => scalar(@keys), drawn => 0, attempted => 0, nowhere => 0); 581: my (@order, %used, %inside, @pending, $failed, $offline);

Mutants (Total: 2, Killed: 0, Survived: 2)
582: my $index = $self->_index; 583:

Mutants (Total: 2, Killed: 2, Survived: 0)

584: for my $key (@keys) { 585: my ($osm, $status) = $self->_known($key, $index); 586: if (!defined($status) && $lookup) { 587: if (!$self->_can_ask) { 588: $offline = 1;

Mutants (Total: 2, Killed: 2, Survived: 0)

589: } elsif (!$failed && $counts{attempted} < $self->{online_max}) {

Mutants (Total: 2, Killed: 2, Survived: 0)

590: $counts{attempted}++; 591: ($osm, $status) = $self->_ask($key, $index);

Mutants (Total: 2, Killed: 2, Survived: 0)

592: $failed = 1 if $status eq 'failed'; 593: } 594: } 595: if (!defined($status) || $status eq 'failed') { 596: push @pending, $key; 597: next; 598: } 599: if ($status eq 'nowhere') { 600: $counts{nowhere}++; 601: next; 602: } 603: push @order, $osm unless $used{$osm}++; 604: $inside{$key} = $osm; 605: } 606: โ—607 โ†’ 608 โ†’ 620 607: my @features; 608: for my $osm (@order) { 609: my $outline = $self->_get($self->_outline_key($osm)) or next; 610: push @features, { 611: type => 'Feature', 612: properties => { name => $outline->{name}, osm => $osm,

Mutants (Total: 1, Killed: 1, Survived: 0)

613: called => $self->name_for($outline->{country}) }, 614: # A copy: the cache may hand out the one it holds (an in-memory 615: # layer does), and a caller that changes its result must not change

Mutants (Total: 2, Killed: 2, Survived: 0)

616: # what the next one is given. 617: geometry => (ref($outline->{geometry}) ? dclone($outline->{geometry}) : $outline->{geometry}), 618: }; 619: } 620: $counts{drawn} = scalar @features; 621: my %drawn = map { $_->{properties}{osm} => 1 } @features; 622: delete @inside{ grep { !$drawn{ $inside{$_} } } keys %inside }; 623: 624: return { 625: features => \@features, 626: pending => \@pending,

Mutants (Total: 1, Killed: 1, Survived: 0)

627: inside => \%inside, 628: counts => \%counts, 629: offline => $offline ? 1 : 0, 630: failed => $failed ? 1 : 0, 631: };

Mutants (Total: 1, Killed: 1, Survived: 0)

632: } 633: 634: =head2 lookup_point 635: 636: my $answer = $boundary->lookup_point('39.090,-77.640'); 637: 638: =head3 API SPECIFICATION 639: 640: =head4 INPUT 641: 642: key : string, a point_key 643: 644: =head4 OUTPUT 645: 646: { status => 'found' | 'nowhere' | 'held', name => string|undef, asked => 0|1 } 647:

Mutants (Total: 1, Killed: 1, Survived: 0)

648: 'found' and 'nowhere' are remembered. 'held' is a point that could not be 649: settled now - Nominatim did not answer, or may not be asked - and is asked

Mutants (Total: 1, Killed: 1, Survived: 0)

650: again next time. asked says whether Nominatim was asked. Croaks on a key 651: that is not a point_key. 652: 653: =cut 654: 655: sub lookup_point { โ—656 โ†’ 668 โ†’ 673 656: my ($self, $key) = @_; 657: 658: croak 'lookup_point() needs a point key such as 39.090,-77.640' 659: unless defined($key) && !ref($key) 660: && $key =~ /\A(-?[0-9]{1,2}\.[0-9]{$DECIMALS}),(-?[0-9]{1,3}\.[0-9]{$DECIMALS})\z/ 661: && defined($self->point_key($1, $2)) && $self->point_key($1, $2) eq $key; 662: 663: local ($@, $!); 664: 665: my $index = $self->_index; 666: my ($osm, $status) = $self->_known($key, $index); 667: my $asked = 0; 668: if (!defined($status) && $self->_can_ask) { 669: $asked = 1; 670: ($osm, $status) = $self->_ask($key, $index); 671: } 672: 673: return { status => 'held', name => undef, asked => $asked } 674: if !defined($status) || $status eq 'failed'; 675: return { status => 'nowhere', name => undef, asked => $asked } if $status eq 'nowhere'; 676: 677: my $outline = $self->_get($self->_outline_key($osm)); 678: return { status => 'found', name => ($outline ? $outline->{name} : undef), asked => $asked }; 679: } 680: 681: =head2 file_cache 682: 683: my $cache = Database::BI::Model::Boundary->file_cache($model_dir);

Mutants (Total: 2, Killed: 2, Survived: 0)

684: 685: =head3 API SPECIFICATION 686: 687: =head4 INPUT 688: 689: dir : string, an existing directory (model_dir) 690: 691: =head4 OUTPUT 692:

Mutants (Total: 2, Killed: 0, Survived: 2)
693: A CHI File cache under C<< <dir>/boundary-cache >>, with a copy of what it 694: reads in memory for as long as the cache object lives. Croaks when dir is not a directory. 695: 696: =cut 697: 698: sub file_cache { 699: my (undef, $dir) = @_; 700: 701: croak 'The boundary cache needs a directory, not ' . (defined($dir) ? $dir : 'undef') 702: unless defined($dir) && !ref($dir) && -d $dir; 703:

Mutants (Total: 3, Killed: 3, Survived: 0)

704: require CHI;

Mutants (Total: 3, Killed: 3, Survived: 0)

705: require File::Spec;

Mutants (Total: 3, Killed: 3, Survived: 0)

706: return CHI->new(

Mutants (Total: 3, Killed: 3, Survived: 0)

707: driver => 'File', 708: root_dir => File::Spec->catdir($dir, $CACHE_DIR), 709: namespace => $CACHE_NAMESPACE,

Mutants (Total: 2, Killed: 2, Survived: 0)

710: # A copy in memory for this object, which a request makes afresh: it 711: # saves reading the index and outlines again within the request. Not 712: # global, which would share it with every cache of this namespace in 713: # the process, whatever its folder, and keep a worker from seeing 714: # what another has added since. 715: l1_cache => { driver => 'RawMemory', global => 0, max_size => $CACHE_MAX_SIZE }, 716: ); 717: } 718: 719: # --------------------------------------------------------------------------- 720: # Private

Mutants (Total: 2, Killed: 2, Survived: 0)

721: # --------------------------------------------------------------------------- 722:

Mutants (Total: 2, Killed: 2, Survived: 0)

723: my $default_cache; 724: 725: sub _default_cache { 726: require CHI; 727: $default_cache //= CHI->new(

Mutants (Total: 5, Killed: 0, Survived: 5)
728: driver => 'Memory', 729: global => 1, 730: namespace => $CACHE_NAMESPACE, 731: max_size => $CACHE_MAX_SIZE, 732: );

Mutants (Total: 5, Killed: 5, Survived: 0)

733: return $default_cache;

Mutants (Total: 3, Killed: 0, Survived: 3)
734: } 735: 736: # _get($key) / _set($key, $value): the cache, under this level's prefix for a 737: # point and under _outline_key for an outline. A cache that fails reads as empty and writes as nothing: the page 738: # still draws, and asks again next time.

Mutants (Total: 2, Killed: 2, Survived: 0)

739: sub _get { 740: my ($self, $key) = @_; 741: my $value = eval { $self->{cache}->get($key) }; 742: return $value; 743: } 744: 745: sub _set { 746: my ($self, $key, $value) = @_; 747: return eval { $self->{cache}->set($key, $value, 'never'); 1 }; 748: } 749: 750: sub _point_cache_key { 751: my ($self, $key) = @_; 752: return "point:$self->{level}:$key"; 753: } 754: 755: # _detail() -> how far this level's outlines are simplified, as text 756: sub _detail { 757: my $self = shift; 758: return $LEVELS{ $self->{level} }{detail}; 759: } 760: 761: # _outline_key($osm) -> the cache key of an outline at this level's detail. 762: # One relation is one outline at every level of the same detail, and a copy 763: # apiece where they differ, so two levels never fetch over each other's. 764: sub _outline_key { 765: my ($self, $osm) = @_; 766: my $detail = $self->_detail; 767: return $detail eq $PLAIN_DETAIL ? "outline:$osm" : "outline:$osm:$detail"; 768: } 769: 770: # _plan($country) -> arrayref of tries { zoom, ranks => [low, high], places } 771: # 772: # How this level is asked for in a country (undef or '' for none known): the 773: # county level's one rank at the zoom that asks for it, else the level's 774: # tries, or the country's own. 775: sub _plan { โ—776 โ†’ 779 โ†’ 783 776: my ($self, $country) = @_; 777: my $level = $LEVELS{ $self->{level} }; 778: $country = (defined($country) && !ref($country)) ? lc($country) : ''; 779: if (defined $level->{rank}) { 780: my $rank = $self->{ranks}{$country} // $level->{rank}; 781: return [ { zoom => $ZOOM_FOR_RANK{$rank}, ranks => [ $rank, $rank ] } ]; 782: } 783: return ($level->{plans} // {})->{$country} // $level->{tries}; 784: } 785: 786: # _plan_sig(\@plan) -> the plan as text, kept with a point found nowhere so a 787: # changed plan asks again. 788: sub _plan_sig { 789: my $plan = shift; 790: return join(';', map { "$_->{zoom}:$_->{ranks}[0]-$_->{ranks}[1]" . ($_->{places} ? ':p' : '') } @{$plan}); 791: } 792: 793: # _accepts(\@plan, $rank) -> 1 when some try of the plan takes that rank 794: sub _accepts { 795: my ($plan, $rank) = @_; 796: return (first { $rank >= $_->{ranks}[0] && $rank <= $_->{ranks}[1] } @{$plan}) ? 1 : 0; 797: } 798: 799: # _index() -> arrayref of [osm, south, west, north, east] 800: # 801: # The bounding box of every outline this level has found, so a point can be 802: # tested against the few that could hold it. Two processes adding at once can 803: # lose one's entry; that costs a request later, not a wrong answer. 804: sub _index { 805: my $self = shift; 806: my $index = $self->_get("index:$self->{level}"); 807: return ref($index) eq 'ARRAY' ? [ @{$index} ] : []; 808: } 809: 810: # _known($key, \@index) -> ($osm, $status) or () 811: # 812: # What is known of a point without asking: remembered with an outline or with 813: # none, or inside an outline the index holds (which is then remembered). 814: sub _known { โ—815 โ†’ 818 โ†’ 832 815: my ($self, $key, $index) = @_; 816: 817: my $remembered = $self->_get($self->_point_cache_key($key)); 818: if (ref($remembered) eq 'HASH') { 819: # Nowhere, by the plan its country had then. 0.023.0 kept the rank 820: # alone, which names a county plan. 821: my $sig = $remembered->{plan}; 822: $sig //= "$ZOOM_FOR_RANK{ $remembered->{rank} }:$remembered->{rank}-$remembered->{rank}" 823: if defined($remembered->{rank}) && $ZOOM_FOR_RANK{ $remembered->{rank} }; 824: return (undef, 'nowhere') 825: if defined($sig) && $sig eq _plan_sig($self->_plan($remembered->{country})); 826: } elsif (defined($remembered) && length($remembered)) { 827: return ($remembered, 'found') if $self->_current($self->_get($self->_outline_key($remembered))); 828: # The outline has gone from the cache, or its country's rank changed. 829: } 830: # '' is nowhere from before ranks were kept: ask again. 831: โ—832 โ†’ 833 โ†’ 844 832: my ($lat, $lon) = split /,/, $key; 833: for my $entry (@{$index}) { 834: # A damaged index entry (not five defined values) knows no outline. 835: next unless ref($entry) eq 'ARRAY' && 5 == grep { defined && !ref } @{$entry}[0 .. 4]; 836: my ($osm, $south, $west, $north, $east) = @{$entry}; 837: next if $lat < $south || $lat > $north || $lon < $west || $lon > $east; 838: my $outline = $self->_get($self->_outline_key($osm)); 839: next unless $self->_current($outline) && _contains($outline->{geometry}, $lat, $lon); 840: $self->_set($self->_point_cache_key($key), $osm); 841: return ($osm, 'found'); 842: } 843: 844: return; 845: } 846: 847: # _current($outline) -> 1 when an outline was accepted at the rank its country 848: # wants now, and simplified as outlines are now. One kept before ranks were 849: # (no rank), or at another level of detail, is not. 850: sub _current { 851: my ($self, $outline) = @_; 852: return 0 unless ref($outline) eq 'HASH' && defined($outline->{rank}); 853: return 0 unless ($outline->{detail} // '') eq $self->_detail; 854: return _accepts($self->_plan($outline->{country}), $outline->{rank}); 855: } 856: 857: # _last_country() / _last_country($code): the country of the last reply at 858: # this level, whose rank the next point is asked at first. Kept in the cache, 859: # so the first point of a later map is not asked twice. 860: sub _last_country { โ—861 โ†’ 863 โ†’ 868 861: my ($self, @set) = @_; 862: my $key = "country:$self->{level}"; 863: if (@set) { 864: $self->{last_country} = $set[0]; 865: $self->_set($key, $set[0]) unless ($self->_get($key) // '') eq $set[0]; 866: return $set[0]; 867: } 868: return $self->{last_country} //= $self->_get($key) // ''; 869: } 870: 871: sub _can_ask { 872: my $self = shift; 873: return 0 unless $self->{online}; 874: return 1 if $self->{ua}; 875: require Database::BI::Model::Geocode; 876: return Database::BI::Model::Geocode::nominatim_ua() ? 1 : 0; 877: } 878: 879: # _ask($key, \@index) -> ($osm, 'found') | (undef, 'nowhere') | (undef, 'failed') 880: # 881: # Reverse lookups down a plan. The first is the first try of the plan of the 882: # last country seen; its reply names the point's country, whose plan is then 883: # followed from its start (a try at a zoom already asked uses that reply), to 884: # the first try that gives an outline. A found outline is remembered with its 885: # country and rank, added to the index (and to @$index, so the caller's later 886: # points are tested against it), and the point remembered with it. A point no 887: # try gives an outline for is remembered as nowhere, with its country and the 888: # plan. A failure is remembered as nothing. 889: sub _ask { โ—890 โ†’ 904 โ†’ 909 890: my ($self, $key, $index) = @_; 891: my ($lat, $lon) = split /,/, $key; 892: 893: my %replies; # by zoom 894: my $reverse = sub { 895: my $zoom = shift; 896: return $replies{$zoom} //= $self->_reverse($lat, $lon, $zoom); 897: }; 898: 899: my $plan = $self->_plan($self->_last_country); 900: my $first = $reverse->($plan->[0]{zoom}) or return (undef, 'failed'); 901: 902: my $country = ref($first->{address}) eq 'HASH' ? $first->{address}{country_code} : undef; 903: $country = (defined($country) && !ref($country) && $country =~ /\A[A-Za-z]{2}\z/) ? lc($country) : ''; 904: if (length $country) { 905: $self->_last_country($country); 906: $plan = $self->_plan($country); 907: } 908: โ—909 โ†’ 911 โ†’ 918 909: my ($reply, $osm); 910: # "Unable to geocode" is the sea at any zoom: no try will do better. 911: for my $try (defined($first->{error}) ? () : @{$plan}) { 912: my $answer = $reverse->($try->{zoom}) or return (undef, 'failed'); 913: $osm = _outline_id($answer, $try) // next; 914: $reply = $answer; 915: last; 916: } 917: โ—918 โ†’ 918 โ†’ 926 918: unless ($reply) { 919: # The sea, and answers at other ranks or with no shape, alike. rank is 920: # what 0.023.0 kept, and reads back as the same county plan. 921: $self->_set($self->_point_cache_key($key), 922: { country => $country, rank => $plan->[0]{ranks}[1], plan => _plan_sig($plan) }); 923: return (undef, 'nowhere'); 924: } 925: โ—926 โ†’ 937 โ†’ 946 926: my $geometry = $reply->{geojson}; 927: my $name = $reply->{name}; 928: $name = $reply->{display_name} unless defined($name) && length($name); 929: $self->_set($self->_outline_key($osm), { 930: name => $name // $osm, 931: geometry => $geometry, 932: country => $country, 933: rank => $reply->{place_rank} + 0, 934: detail => $self->_detail, 935: }); 936: 937: unless (grep { $_->[0] eq $osm } @{$index}) { 938: my $box = _bounds($geometry); 939: if ($box) { 940: push @{$index}, [ $osm, @{$box} ]; 941: my $stored = $self->_index; 942: push @{$stored}, [ $osm, @{$box} ] unless grep { $_->[0] eq $osm } @{$stored}; 943: $self->_set("index:$self->{level}", $stored); 944: } 945: } 946: $self->_set($self->_point_cache_key($key), $osm); 947: 948: return ($osm, 'found'); 949: } 950: 951: # _outline_id($reply, $try) -> 'R<id>' or 'W<id>' when the reply is an outline 952: # the try takes, else undef. 953: # 954: # An outline is an area with a shape, at a rank in the try's range: an 955: # administrative boundary's relation, or, for a try that takes places, a place 956: # mapped as an area (place=city, town, suburb), which may be a closed way. A 957: # place mapped as a point has no shape and is not one. 958: sub _outline_id { 959: my ($reply, $try) = @_; 960: 961: my $geometry = $reply->{geojson}; 962: my $rank = $reply->{place_rank}; 963: my $category = $reply->{category} // ''; 964: my $osm_type = $reply->{osm_type} // ''; 965: return unless defined($reply->{osm_id}) && $reply->{osm_id} =~ /\A[0-9]+\z/ 966: && defined($rank) && !ref($rank) && $rank =~ /\A[0-9]+\z/ 967: && $rank >= $try->{ranks}[0] && $rank <= $try->{ranks}[1] 968: && ref($geometry) eq 'HASH' 969: && ($geometry->{type} // '') =~ /\A(?:Multi)?Polygon\z/ 970: && ref($geometry->{coordinates}) eq 'ARRAY'; 971: 972: my $boundary = $category eq 'boundary' && ($reply->{type} // '') eq 'administrative' 973: && $osm_type eq 'relation'; 974: my $place = $try->{places} && $category eq 'place' && ($osm_type eq 'relation' || $osm_type eq 'way'); 975: return unless $boundary || $place; 976: 977: return ($osm_type eq 'way' ? 'W' : 'R') . $reply->{osm_id}; 978: } 979: 980: # _reverse($lat, $lon, $zoom) -> the decoded reply, or undef when Nominatim 981: # did not answer with JSON. 982: sub _reverse { 983: my ($self, $lat, $lon, $zoom) = @_; 984: 985: my $uri = URI->new($REVERSE_URL); 986: $uri->query_form( 987: lat => $lat, 988: lon => $lon, 989: zoom => $zoom, 990: format => 'jsonv2', 991: polygon_geojson => 1, 992: polygon_threshold => $self->_detail, 993: 'accept-language' => 'en', 994: ); 995: 996: require Database::BI::Model::Geocode; 997: my $ua = $self->{ua} // Database::BI::Model::Geocode::nominatim_ua(); 998: my $res = eval { $ua->get($uri) }; 999: return unless blessed($res) && $res->can('is_success') && $res->is_success; 1000: 1001: my $reply = eval { $json->decode($res->decoded_content // '') }; 1002: return ref($reply) eq 'HASH' ? $reply : undef; 1003: } 1004: 1005: # _polygons($geometry) -> list of polygons, each an arrayref of rings, each 1006: # ring an arrayref of [lon, lat]. 1007: sub _polygons { 1008: my $geometry = shift; 1009: return () unless ref($geometry) eq 'HASH' && ref($geometry->{coordinates}) eq 'ARRAY'; 1010: return ($geometry->{coordinates}) if ($geometry->{type} // '') eq 'Polygon'; 1011: return @{ $geometry->{coordinates} } if ($geometry->{type} // '') eq 'MultiPolygon'; 1012: return (); 1013: } 1014: 1015: # _bounds($geometry) -> [south, west, north, east], or undef with no points 1016: sub _bounds { โ—1017 โ†’ 1019 โ†’ 1028 1017: my $geometry = shift; 1018: my ($south, $west, $north, $east); 1019: for my $polygon (_polygons($geometry)) { 1020: for my $position (@{ $polygon->[0] // [] }) { 1021: my ($lon, $lat) = @{$position}; 1022: $south = $lat if !defined($south) || $lat < $south; 1023: $north = $lat if !defined($north) || $lat > $north; 1024: $west = $lon if !defined($west) || $lon < $west; 1025: $east = $lon if !defined($east) || $lon > $east; 1026: } 1027: } 1028: return defined($south) ? [ $south, $west, $north, $east ] : undef; 1029: } 1030: 1031: # _contains($geometry, $lat, $lon) -> 1 when the point is inside a polygon's 1032: # outer ring and none of its holes (Fairfax County's hole is the City of 1033: # Fairfax). Even-odd ray casting, with longitude as x. 1034: sub _contains { โ—1035 โ†’ 1036 โ†’ 1045 1035: my ($geometry, $lat, $lon) = @_; 1036: for my $polygon (_polygons($geometry)) { 1037: # Premise 1: the geometry came from a web service and a cache file. 1038: # Premise 2: a damaged entry must not turn a map into a 500. 1039: # Conclusion: what is not a polygon holds no point. 1040: next unless ref($polygon) eq 'ARRAY'; 1041: my ($outer, @holes) = @{$polygon}; 1042: next unless _in_ring($outer, $lon, $lat); 1043: return 1 unless grep { _in_ring($_, $lon, $lat) } @holes; 1044: } 1045: return 0; 1046: } 1047: 1048: # _is_position($value) -> 1 | 0 1049: # 1050: # A GeoJSON position is a list of at least two defined numbers. Anything else 1051: # in a ring means the ring is damaged, and a damaged ring holds no point. 1052: sub _is_position { 1053: my ($position) = @_; 1054: return 0 unless ref($position) eq 'ARRAY' && @{$position} >= 2; 1055: return (defined $position->[0] && defined $position->[1] 1056: && !ref($position->[0]) && !ref($position->[1])) ? 1 : 0; 1057: } 1058: 1059: sub _in_ring { โ—1060 โ†’ 1065 โ†’ 1074 1060: my ($ring, $x, $y) = @_; 1061: return 0 unless ref($ring) eq 'ARRAY' && @{$ring} >= 3; 1062: my $inside = 0; 1063: return 0 unless _is_position($ring->[-1]); 1064: my ($px, $py) = @{ $ring->[-1] }; 1065: for my $position (@{$ring}) { 1066: return 0 unless _is_position($position); 1067: my ($qx, $qy) = @{$position}; 1068: if ((($qy > $y) != ($py > $y)) 1069: && ($x < ($px - $qx) * ($y - $qy) / ($py - $qy) + $qx)) { 1070: $inside = !$inside; 1071: } 1072: ($px, $py) = ($qx, $qy); 1073: } 1074: return $inside ? 1 : 0; 1075: } 1076: 1077: 1; 1078: 1079: __END__ 1080: 1081: =head1 AUTHOR 1082: 1083: Nigel Horne C<< <njh@nigelhorne.com> >> 1084: 1085: =head1 LICENCE AND COPYRIGHT 1086: 1087: Copyright 2026 Nigel Horne. 1088: 1089: Usage is subject to the GPL2 licence terms. 1090: If you use it, 1091: please let me know. 1092: 1093: =cut