File size: 7,739 Bytes
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
"""Bounded rigid cooktop bridging measured independently from saved triangles.

Corridors describe unsupported space only; they never modify a mesh, fill a
support polygon, or exempt a solid collision. No native receipt is consulted.
"""
import itertools
import math

MAX_WIDTH_M = .010
MIN_SUPPORT_FRACTION = .95
CONTACT_TOLERANCE_M = 1e-5
POLICY = 'rigid_cooktop_counter_interior_seam_v1'


def _parts(geometry):
    if geometry.geom_type == 'Polygon':
        return [geometry]
    return [p for p in getattr(geometry, 'geoms', ()) if p.geom_type == 'Polygon']


def _coordinates(geometry):
    for polygon in _parts(geometry):
        yield from polygon.exterior.coords
        for ring in polygon.interiors:
            yield from ring.coords


def _corridors(support, bottom, missing, area_epsilon):
    from shapely.geometry import Polygon
    from shapely.geometry.polygon import orient
    parts = [orient(p, sign=1.) for p in _parts(support)]
    for left, right in itertools.combinations(parts, 2):
        if left.distance(right) > MAX_WIDTH_M + 1e-12:
            continue
        # A cooktop ending inside the seam is an overhang, not a bridge.
        if (left.intersection(bottom).area <= area_epsilon or
                right.intersection(bottom).area <= area_epsilon):
            continue
        for a, b in zip(left.exterior.coords, list(left.exterior.coords)[1:]):
            length = math.dist(a, b)
            if length <= 1e-8:
                continue
            ux, uy = (b[0]-a[0])/length, (b[1]-a[1])/length
            for c, d in zip(right.exterior.coords, list(right.exterior.coords)[1:]):
                other = math.dist(c, d)
                if other <= 1e-8:
                    continue
                vx, vy = (d[0]-c[0])/other, (d[1]-c[1])/other
                dot = ux*vx + uy*vy
                # CCW exterior edges must face one another across empty space.
                if abs(ux*vy-uy*vx) > 1e-6 or dot >= 0:
                    continue
                distances = [-uy*(p[0]-a[0])+ux*(p[1]-a[1]) for p in (c,d)]
                width = max(abs(value) for value in distances)
                if max(distances) >= 0 or not 1e-9 < width <= MAX_WIDTH_M+1e-12:
                    continue
                start = max(0., min(ux*(p[0]-a[0])+uy*(p[1]-a[1]) for p in (c,d)))
                end = min(length, max(ux*(p[0]-a[0])+uy*(p[1]-a[1]) for p in (c,d)))
                if end-start <= 1e-8:
                    continue

                def pair(t):
                    p = (a[0]+ux*t, a[1]+uy*t)
                    along = ((p[0]-c[0])*ux+(p[1]-c[1])*uy)/dot
                    return p, (c[0]+vx*along, c[1]+vy*along)

                p, q = pair(start)
                r, s = pair(end)
                corridor = Polygon([p,r,s,q])
                if (not corridor.is_valid or corridor.area <= area_epsilon or
                        corridor.intersection(support).area > area_epsilon or
                        corridor.intersection(missing).area <= area_epsilon):
                    continue
                yield corridor, width


def measure_seam(child, parent, bottom, targets, low, samples, gaps, *,
                 closed_child, tolerance):
    """Return raw world-space seam measurements, or None for a strict rejection.

    The caller supplies its saved bottom-triangle union and unedited ray gaps.
    Support geometry and contact heights are recomputed from actual target
    triangles. Misses/deep positive hits may occur only inside a proven seam;
    negative hits remain failures everywhere.
    """
    if (not closed_child or not parent or
            parent.get('layout_slot_id') != 'kitchen_counter' or
            child.get('layout_slot_id') != 'kitchen_cooktop' or
            child.get('role') not in ('oven','cooktop') or
            (child.get('supported_by_entity_id') or child.get('support_entity_id'))
                != parent.get('entity_id') or
            child.get('uniform_scale', 1.) != 1. or
            bottom.is_empty or not bottom.is_valid or bottom.area <= 1e-12 or
            len(samples) != len(gaps) or not samples or
            any(g is not None and (not math.isfinite(g) or g < 0) for g in gaps)):
        return None
    import numpy as np
    from shapely.geometry import Point, Polygon
    from shapely.ops import unary_union
    tolerance = min(tolerance, CONTACT_TOLERANCE_M)
    faces = []
    contact_gaps = []
    for mesh in targets:
        triangles = mesh['vertices'][mesh['triangles']]
        normals = np.cross(triangles[:,1]-triangles[:,0], triangles[:,2]-triangles[:,0])
        selected = ((normals[:,2] > 1e-12) &
                    (np.max(abs(triangles[:,:,2]-low), axis=1) <= tolerance))
        for triangle, normal in zip(triangles[selected], normals[selected]):
            polygon = Polygon(triangle[:,:2])
            if not polygon.is_valid or polygon.area <= 1e-15:
                continue
            faces.append(polygon)
            clipped = polygon.intersection(bottom)
            if clipped.area <= 1e-15:
                continue
            for x, y in _coordinates(clipped):
                z = triangle[0,2] - (normal[0]*(x-triangle[0,0]) +
                                    normal[1]*(y-triangle[0,1]))/normal[2]
                contact_gaps.append(float(low-z))
    if (not contact_gaps or min(contact_gaps) < 0 or
            max(contact_gaps) > tolerance):
        return None
    support = unary_union(faces)
    if support.is_empty or not support.is_valid:
        return None
    area_epsilon = max(1e-12, bottom.area*1e-10)
    # Actual interior holes are never eligible, however narrow they may be.
    holes = unary_union([Polygon(ring) for p in _parts(support) for ring in p.interiors])
    if holes.intersection(bottom).area > area_epsilon:
        return None
    missing = bottom.difference(support)
    fraction = 1-missing.area/bottom.area
    if missing.area <= area_epsilon or fraction < MIN_SUPPORT_FRACTION:
        return None
    seams = list(_corridors(support, bottom, missing, area_epsilon))
    if not seams:
        return None
    corridors = unary_union([p for p, _ in seams])
    if missing.difference(corridors).area > area_epsilon:
        return None
    supported_count = unsupported_count = 0
    unsupported_indices = []
    for index, (xy, gap) in enumerate(zip(samples, gaps)):
        point = Point(xy)
        if support.covers(point):
            if gap is None or not 0 <= gap <= tolerance:
                return None
            supported_count += 1
        elif corridors.distance(point) <= 1e-10:
            unsupported_count += 1
            unsupported_indices.append(index)
        else:
            return None
    if not supported_count:
        return None
    return dict(policy=POLICY, method='saved_actual_flat_triangles_parallel_exterior_edges',
        maximum_allowed_width_m=MAX_WIDTH_M,
        maximum_unsupported_width_m=max(width for _,width in seams),
        minimum_actual_support_fraction=MIN_SUPPORT_FRACTION,
        actual_support_fraction=fraction,
        actual_support_area_m2=bottom.area-missing.area,
        unsupported_projection_area_m2=missing.area,
        bottom_area_m2=bottom.area, actual_contact_tolerance_m=tolerance,
        minimum_actual_contact_gap_m=min(contact_gaps),
        maximum_actual_contact_gap_m=max(contact_gaps),
        seam_polygons_world_xy_m=[list(p.exterior.coords) for p,_ in seams],
        supported_sample_count=supported_count, unsupported_sample_count=unsupported_count,
        unsupported_sample_indices=unsupported_indices,
        physical_stability='unknown_not_simulated', physical_qualified=False,
        whole_task_acceptance=False, source_region_modified=False)