点在多边形内实战:射线正好穿过顶点,为什么一条邻边要计数而另一条必须跳过

10-08 9阅读

从查询点向右发出一条水平射线,穿过多边形边界奇数次通常表示在内部。但射线恰好穿过顶点时,两条邻边都可能声称“交到了”。正确实现要给纵向端点使用半开规则,并把查询点本身位于边界的情况提前分开。

点在多边形内实战:射线正好穿过顶点,为什么一条邻边要计数而另一条必须跳过
AI模型生成概念插图,用抽象图形表达本文计算机制,不是实测结果或软件截图。

接口返回三种状态

本文返回inside、outside或boundary,输入是整数坐标的闭合轮廓,最后一条边自动连接末顶点与首顶点。允许额外重复首点,重复产生的零长度边也不会被当成普通穿越。

代码只检查坐标格式与三至128个顶点的预算,不验证轮廓是否简单。正常简单多边形按通常内外解释;自交输入则采用奇偶填充规则,可能不同于非零绕数规则。多个环、孔洞组织和地图拓扑验证不属于这个单环接口。

边界点先用整数叉积识别

对边a到b,计算cross=(bx−ax)(py−ay)−(by−ay)(px−ax)。若为零,还要检查查询点位于两端坐标的包围区间内,才说明落在线段上。只检查共线会把无限延长线上的远点也误认成边界。

边界直接返回,不再交给交叉次数处理。整数算术让这里的等于零具有精确含义。浮点版本需要另行设计稳健谓词;随便加一个固定epsilon可能把不同尺度的点错误吸到边上。

一条边只有一端严格高于射线才进入候选

条件(ay>py)与(by>py)不相等,表示射线高度位于该边的半开纵向范围内。水平边两端状态相同,自动跳过,不会出现除以零。这个条件也让普通穿越顶点时恰好只有一条邻边计数。

若顶点是局部最高或最低点,两条相邻边可能都计入或都不计入,对奇偶性影响仍为零;这符合射线只是碰一下轮廓、没有从内部穿到外部的事实。不能把所有端点比较统一改成包含,再期待顶点总是只算一次。

判断交点在右边,不一定要计算交点

边的水平交点减去px,等于cross/(by−ay)。因此向上边要求cross为正,向下边要求cross为负,才表示交点在查询点右侧。分母符号不能省略,否则轮廓方向一反转,结果就可能改变。

源码先完成纵向跨越判断,再用叉积与方向的符号比较决定是否翻转inside。整个过程不使用除法,避免产生新的分数交点,也不会因为垂直边斜率无穷而需要另一套公式。

菱形中心最容易暴露顶点重复计数

菱形顶点为(0,−2)、(2,0)、(0,2)、(−2,0),查询原点。向右射线恰好经过右顶点(2,0),两条邻边都接在那里;半开规则让实际奇偶贡献为一,因此返回inside。

查询右顶点本身返回boundary,移到(3,0)则返回outside。三份样本只差一个坐标,却分别走不同分支,适合检查“在轮廓边界”与“射线经过别处顶点”有没有被混成同一种情况。

凹形不能用所有边同侧代替

对于凸多边形,可以用每条边的同侧条件检查内部;凹多边形却不满足那种简单交集合同。本文还测试L形区域,缺口内的点应在外,而两条臂内的点在内,凹角与水平边仍按独立边界规则处理。

参考PNPOLY的精简C代码将边界一致地分到某一侧,适合平面划分。本文额外增加boundary状态,因此不声称完全复制其边界返回合同。两者共享射线奇偶与谨慎选择不等式的核心机制。

用几何区域公式核对射线算法

测试八种半径菱形,对网格点用|x|+|y|与半径直接比较得到期望结果,再检查轮廓反向时答案不变。L形用六条显式边界与两个矩形臂的内部条件作为独立裁判。

合计3697个几何查询,另有重复首点和非整数拒绝测试。裁判没有重复射线交叉公式。一次查询扫描全部边,时间O(n)、额外状态O(1);若需要对同一复杂地图查询百万次,应另行构建空间索引,而不是从这个小例推断吞吐量。

完整程序与本次实测输出

保存为demo.py,执行python3 demo.py。本次使用Linux、CPython 3.12.14与标准库,退出码为0,标准错误为空。程序仅使用内存教学样本,不访问网络或业务文件。

from itertools import product

def locate(point, polygon):
    if type(polygon) is not list or not 3 <= len(polygon) <= 128:
        raise ValueError('3..128 vertices required')
    if any(type(p) is not tuple or len(p) != 2 or any(type(v) is not int for v in p)
           for p in [point]+polygon):
        raise ValueError('integer coordinate pairs required')
    px, py = point
    inside = False
    for a, b in zip(polygon, polygon[1:]+polygon[:1]):
        ax, ay = a
        bx, by = b
        cross = (bx-ax)*(py-ay)-(by-ay)*(px-ax)
        if cross == 0 and min(ax, bx) <= px <= max(ax, bx) and min(ay, by) <= py <= max(ay, by):
            return 'boundary'
        if (ay > py) != (by > py):
            if (cross > 0) == (by > ay):
                inside = not inside
    return 'inside' if inside else 'outside'

def main():
    diamond = [(0, -2), (2, 0), (0, 2), (-2, 0)]
    print('diamond center/vertex/outside:', [locate(p, diamond) for p in [(0, 0), (2, 0), (3, 0)]])
    concave = [(0, 0), (4, 0), (4, 1), (1, 1), (1, 4), (0, 4)]
    print('concave arm/notch:', locate((0, 2), concave), locate((2, 2), concave))
    checks = 0
    for radius in range(1, 9):
        poly = [(0, -radius), (radius, 0), (0, radius), (-radius, 0)]
        for x, y in product(range(-10, 11), repeat=2):
            norm = abs(x)+abs(y)
            expected = 'boundary' if norm == radius else 'inside' if norm < radius else 'outside'
            assert locate((x, y), poly) == expected
            assert locate((x, y), list(reversed(poly))) == expected
            checks += 1
    # Double coordinates allow original half-grid queries on a concave L.
    poly = [(0, 0), (8, 0), (8, 2), (2, 2), (2, 8), (0, 8)]
    for x, y in product(range(-2, 11), repeat=2):
        boundary = ((y == 0 and 0 <= x <= 8) or (x == 0 and 0 <= y <= 8)
                    or (x == 8 and 0 <= y <= 2) or (y == 8 and 0 <= x <= 2)
                    or (y == 2 and 2 <= x <= 8) or (x == 2 and 2 <= y <= 8))
        interior = (0 < x < 8 and 0 < y < 2) or (0 < x < 2 and 0 < y < 8)
        expected = 'boundary' if boundary else 'inside' if interior else 'outside'
        assert locate((x, y), poly) == expected
        checks += 1
    print('independent diamond and L-region queries:', checks)
    assert locate((0, 0), diamond+[diamond[0]]) == 'inside'
    try:
        locate((0.5, 0), diamond)
    except ValueError:
        print('reversal, repeated endpoint and noninteger rejection: PASS')
    else:
        raise AssertionError('float accepted')

if __name__ == '__main__':
    main()
diamond center/vertex/outside: ['inside', 'boundary', 'outside']
concave arm/notch: boundary outside
independent diamond and L-region queries: 3697
reversal, repeated endpoint and noninteger rejection: PASS

来源与复现范围

资料核对与本地运行日期为2026年10月8日。本文解释、程序与测试数据独立编写,引用资料用于确认算法定义及适用前提;有限测试不等于生产系统性能或全部输入保证。


文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。