File size: 9,372 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
"""Read-only native bed/nightstand pair probe. This only orders admissible retries.

Callers bind clean feedback, input paths/SHA, candidate domains/record variants and
resolve source attributes exactly as native solve before calling. No candidate is
excluded here. `empty` is a complete current declared pair-domain observation,
not global source infeasibility. Unrelated furnishings and final saved geometry
remain the subsequent full solver's responsibility. Time limit is cooperative.
"""
from __future__ import annotations
import copy
import math
import time
from collections import Counter


def probe_bedside_pair(manifest, request, shell, parent_candidate, child_candidate,
                       parent_entity_id, child_entity_id, *, envelope_report=None,
                       max_parent_poses=256, timeout_s=8):
    started=time.monotonic()
    def result(status, reason, **extra):
        return dict(schema='rhg.bedside-native-pair-probe.v1', status=status,
                    reason=reason, elapsed_s=round(time.monotonic()-started,6),
                    parent_entity_id=parent_entity_id, child_entity_id=child_entity_id,
                    inventory_reduction_allowed=False, global_source_rejection=False,
                    full_room_qualified=False, **extra)
    def unknown(reason, **extra):return result('unknown',reason,**extra)
    def expired():return time.monotonic()-started>=timeout_s
    try:
        if (type(max_parent_poses) is not int or not 1<=max_parent_poses<=10000
                or type(timeout_s) not in (int,float) or not math.isfinite(timeout_s) or timeout_s<=0):
            return unknown('invalid_probe_budget')
        import joint_layout as jl
        from bind_fixed_layout import prepared_candidate,semantic_key
        from source_support import support_geometry_prepared
        from functional_layout import automatic_bedside_preference
        from stage_checkpoint import fingerprint
        entities=copy.deepcopy(manifest['entities'])
        by_id={e['entity_id']:e for e in entities}
        if len(by_id)!=len(entities):return unknown('duplicate_entity_ids')
        if parent_entity_id not in by_id or child_entity_id not in by_id:return unknown('pair_entity_missing')
        parent,child=by_id[parent_entity_id],by_id[child_entity_id]
        if (parent.get('role')!='bed' or child.get('role')!='side_table'
                or parent.get('room_id')!=child.get('room_id')
                or child.get('front_target_entity_id')!=parent_entity_id
                or child.get('layout_relation')!='nightstand_back_flush_with_bed_head_wall'
                or parent.get('layout_relation')!='headboard_against_wall_not_access_side'
                or any(e.get(k) for e in (parent,child) for k in ('supported_by_entity_id','support_entity_id'))):
            return unknown('not_declared_automatic_floor_bedside_pair')
        fixed=(request.get('search_constraints') or {}).get('fixed_entities',[])
        if any(e.get('entity_id') in (parent_entity_id,child_entity_id) for e in fixed):
            return unknown('pair_pose_fixed')
        if request.get('search',{}).get('envelope_layout'):
            room_record=(envelope_report or {}).get('rooms',{}).get(parent['room_id'],{})
            if (room_record.get('status')!='incomplete'
                    or set((envelope_report or {}).get('applied',[]))&{parent_entity_id,child_entity_id}):
                return unknown('effective_envelope_entities_not_proven')
        plan=copy.deepcopy(manifest['floor_plan']);plan_sha=fingerprint(plan)
        if (shell.get('floor_plan_sha256')!=plan_sha
                or request.get('floor_plan_sha256')!=plan_sha):return unknown('floor_plan_binding_mismatch')
        required=('window_glazing','door_swing_keepouts','door_frame_bounds','door_motion_volumes','wall_mesh_bounds','floor_mesh_bounds')
        if any(k not in shell or shell[k] is None for k in required):return unknown('measured_shell_incomplete')
        windows={w['window_id']:w for w in plan.get('windows',[])}
        measured=shell['window_glazing']
        if (len({w['window_id'] for w in measured})!=len(measured)
                or {w['window_id'] for w in measured}!=set(windows)):
            return unknown('window_readback_incomplete')
        if any(w.get('plan_record_sha256')!=fingerprint(windows[w['window_id']]) for w in measured):
            return unknown('window_record_binding_mismatch')
        plan['_window_geometry']={w['window_id']:w for w in measured}
        for k in required[1:]:plan['_'+k]=copy.deepcopy(shell[k])
        plan['_floor_body_required']=bool(request.get('floor_body_geometry_index'))
        rooms=[r for r in plan['rooms'] if r['room_id']==parent['room_id']]
        if len(rooms)!=1:return unknown('room_binding_ambiguous')
        room=rooms[0]
        candidates=[copy.deepcopy(parent_candidate),copy.deepcopy(child_candidate)]
        for candidate in candidates:
            dims=candidate.get('dimensions_m');footprint=candidate.get('source_visual_footprint_polygon_xy_m')
            if (not isinstance(dims,list) or len(dims)!=3
                    or any(type(v) not in (int,float) or not math.isfinite(v) or v<=0 for v in dims)
                    or not isinstance(footprint,list) or len(footprint)<3
                    or any(len(p)!=2 or any(type(v) not in (int,float) or not math.isfinite(v) for v in p) for p in footprint)
                    or not prepared_candidate(candidate) or not support_geometry_prepared(candidate)):
                return unknown('native_prepared_geometry_unknown')
            if footprint!=candidate['source_support_geometry']['visual_footprint_polygon_xy_m']:
                return unknown('source_footprint_support_disagree')
            if not any(p[2]<=.005 for p in candidate['source_support_geometry']['bottom_vertices_xyz_m']):
                return unknown('measured_floor_contact_unknown')
            resolution=candidate.get('functional_front_resolution')
            if resolution and resolution.get('effective_axis')!=candidate.get('canonical_front_axis'):
                return unknown('effective_front_frame_mismatch')
        relations=jl.compile_relations(entities,request)
        if not automatic_bedside_preference(child):return unknown('automatic_bedside_relation_unproven')
        if expired():return unknown('probe_time_budget')
        poses=jl.positions(parent,candidates[0],room,plan,{},request)
        if expired():return unknown('probe_time_budget')
        if len(poses)>max_parent_poses:return unknown('parent_pose_budget',parent_pose_count=len(poses))
        counts=Counter();valid=0;empty=0;children_seen=0;uncertain=False
        # Only known positive geometric rejection can prune a parent in an empty-domain proof.
        known_parent_rejections={'retained_window','native_furniture_outside_room',
            'native_furniture_outside_vertical_room_bounds','measured_floor_support_missing',
            'opening','actual_authored_door_swing_keepout','actual_authored_open_door_leaf',
            'door_frame_clearance','actual_door_motion_volume','functional_access_outside_room'}
        for p in poses:
            if expired():return unknown('probe_time_budget')
            p['binding_semantic_key']=semantic_key(parent)
            errors=jl.placement_errors(p,{},plan,relations)
            if errors:
                counts.update(e['reason'] for e in errors)
                if any(e['reason'] not in known_parent_rejections for e in errors):uncertain=True
                continue
            valid+=1
            children=jl.positions(child,candidates[1],room,plan,{parent_entity_id:p},request)
            if expired():return unknown('probe_time_budget')
            if not children:empty+=1
            children_seen+=len(children)
            for c in children:
                if expired():return unknown('probe_time_budget')
                c['binding_semantic_key']=semantic_key(child)
                if not jl.placement_errors(c,{parent_entity_id:p},plan,relations):
                    keys=('asset_id','pool_candidate_key','center_xy_m','yaw_deg','base_z_m','dimensions_m','canonical_front_axis','wall_anchor')
                    witness={key:{k:pose[k] for k in keys if k in pose} for key,pose in [('parent',p),('child',c)]}
                    for key,pose in [('parent',p),('child',c)]:witness[key]['world_front']=jl.front_vector(pose)
                    return result('witness','native_pair_pose_passed',witness=witness,parent_pose_count=len(poses),parent_poses_checked=valid,excluded_context='wardrobe_lamp_other_furnishings_and_final_saved_mesh')
        evidence=dict(parent_pose_count=len(poses),valid_parent_pose_count=valid,
                      child_empty_parent_pose_count=empty,child_pose_count=children_seen,
                      parent_rejections=dict(counts),floor_plan_sha256=plan_sha,
                      parent_asset_id=candidates[0]['asset_id'],child_asset_id=candidates[1]['asset_id'])
        if not uncertain and valid>0 and valid==empty:
            return result('empty','all_native_valid_parent_poses_have_empty_child_domain',evidence=evidence)
        return unknown('no_positive_witness_or_complete_empty_domain_proof',evidence=evidence)
    except Exception as error:
        return unknown('probe_input_or_native_error',error_type=type(error).__name__)