"""Finite preferences for newly generated shell openings, before mesh creation. This adapter never modifies an already furnished shell. Door frames, motion volumes and metric contracts must be compiled AFTER this function returns. """ import copy import math import os VERSION = 'rhg.adaptive-shell.v1' class AuthoredWindowValidationError(ValueError): """Invalid supplied geometry with JSON-safe evidence for the build result.""" def __init__(self, diagnostic): self.diagnostic = diagnostic conflicts = '; '.join( f"{row['opening_id']}: gap {row['gap_m']:.3f} m, " f"minimum {row['minimum_gap_m']:.3f} m" for row in diagnostic['opening_conflicts']) message = ( f"authored window not in legal exterior interval: {diagnostic['window_id']} " f"in room {diagnostic['room_id']}, interval {diagnostic['window_interval_m']}, " f"legal intervals {diagnostic['legal_exterior_intervals_m']}" ) if conflicts: message += '; ' + conflicts super().__init__(message + '. ' + diagnostic['remediation']) def _invalid_window_diagnostic(plan, room, window, spans): from engine.source.scripts.internal.scene_generation.window_rules import MIN_OPENING_GAP_M lo, hi = window['window_interval_m'] conflicts = [] for kind in ('window', 'door'): for other in plan.get(kind + 's', []): if other is window or not _same_wall(window, other): continue interval = other.get(kind + '_interval_m') if not interval: continue gap = max(interval[0] - hi, lo - interval[1]) if gap < MIN_OPENING_GAP_M - 1e-6: conflicts.append(dict( opening_id=other.get(kind + '_id'), opening_kind=kind, interval_m=list(interval), gap_m=round(gap, 6), minimum_gap_m=MIN_OPENING_GAP_M, deficit_m=round(MIN_OPENING_GAP_M - gap, 6))) return dict( schema='rhg.authored-window-validation.v1', code='authored_window_not_in_legal_exterior_interval', window_id=window.get('window_id'), room_id=window['room_id'], source=window.get('source'), fixed=_fixed(window), wall_orientation=window['wall_orientation'], wall_line_m=window['wall_line_m'], window_interval_m=list(window['window_interval_m']), room_bounds_m=list(room['bounds_m']), legal_exterior_intervals_m=[[round(a, 6), round(b, 6)] for a, b in spans], opening_conflicts=conflicts, remediation='Correct the supplied window in the source plan to fit a legal exterior ' 'interval and the required opening gap, then retry. Supplied openings ' 'have not been moved.') def _components(plan): graph = {r['room_id']: set() for r in plan['rooms']} links = [d['room_ids'] for d in plan.get('doors', [])] links += [a['room_ids'] for a in plan.get('topology_adjacencies', []) if a.get('open_interval_m')] for pair in links: if len(pair) == 2 and all(r in graph for r in pair): a, b = pair; graph[a].add(b); graph[b].add(a) unseen = set(graph); components = [] while unseen: pending = [min(unseen)]; seen = set() while pending: rid = pending.pop() if rid in seen: continue seen.add(rid); pending.extend(graph[rid] - seen) unseen -= seen; components.append(sorted(seen)) return sorted(components) def _fixed(row): return any(row.get(k) for k in ('fixed', 'locked', 'authored', 'preserve_opening')) def _same_wall(a, b): return a.get('wall_orientation') == b.get('wall_orientation') and abs(a['wall_line_m'] - b['wall_line_m']) < 1e-5 def _subtract(spans, cut): result = [] for lo, hi in spans: a, b = max(lo, cut[0]), min(hi, cut[1]) if a >= b: result.append((lo, hi)); continue if lo < a: result.append((lo, a)) if b < hi: result.append((b, hi)) return result def _shared_record_valid(rec, rooms): """The record is evidence only when two actual room boundaries agree.""" if len(rec.get('room_ids', [])) != 2: return False a, b = [rooms[r]['bounds_m'] for r in rec['room_ids']] axis = 0 if rec['wall_orientation'] == 'V' else 1 tangent = 1-axis; line=rec['wall_line_m'] opposite = ((abs(a[axis+2]-line)<1e-4 and abs(b[axis]-line)<1e-4) or (abs(b[axis+2]-line)<1e-4 and abs(a[axis]-line)<1e-4)) lo, hi = rec['overlap_interval_m'] return opposite and lo >= max(a[tangent], b[tangent])-1e-4 and hi <= min(a[tangent+2],b[tangent+2])+1e-4 def _relocate_doors(plan, report): rooms={r['room_id']: r for r in plan['rooms']} for door in list(plan.get('doors', [])): if _fixed(door) or door.get('source') != 'circulation_graph_selected_v8': continue ids=door.get('room_ids', []) if len(ids)!=2: continue bedrooms=[r for r in ids if 'bedroom' in rooms[r].get('room_type','')] living=[r for r in ids if rooms[r].get('room_type')=='living_room'] if not bedrooms or not living: continue bedroom=bedrooms[0] old=next((a for a in plan['topology_adjacencies'] if a.get('door_id')==door['door_id']),None) if not old or _fixed(old): continue candidates=[a for a in plan['topology_adjacencies'] if bedroom in a['room_ids'] and any(rooms[r].get('room_type') in ('hallway','corridor') for r in a['room_ids']) and not a.get('open_connection') and not a.get('door_interval_m') and not _fixed(a) and _shared_record_valid(a,rooms)] candidates.sort(key=lambda a: (-a['overlap_len_m'],tuple(a['room_ids']))) changed=False for target in candidates[:4]: lo,hi=target['overlap_interval_m']; width=door['door_width_m'] margin=max(.30,float(plan.get('wall_thickness_m',.2))+.10) if hi-lo < width+2*margin: continue # Prefer the end closest to the old entrance, minimizing approach change. tangent=0 if target['wall_orientation']=='H' else 1 old_mid=(sum(door['door_interval_m'])/2 if door['wall_orientation']==target['wall_orientation'] else door['wall_line_m']) starts=sorted([lo+margin,hi-margin-width], key=lambda s:abs(s+width/2-old_mid)) for start in starts: interval=[round(start,3),round(start+width,3)] if any(_same_wall(target,d) and min(interval[1],d['door_interval_m'][1])- max(interval[0],d['door_interval_m'][0])>-.10 for d in plan['doors'] if d is not door): continue snapshot=copy.deepcopy(plan) before=copy.deepcopy(door) door.update(room_ids=list(target['room_ids']),room_types=list(target['room_types']), door_id='door__'+'__'.join(target['room_ids']), wall_orientation=target['wall_orientation'],wall_line_m=target['wall_line_m'], door_interval_m=interval,source='adaptive_generated_hall_access_v1') old.pop('door_id',None);old.pop('door_interval_m',None) old['connection_kind']='solid_wall_adaptive_living_furniture' target.update(door_id=door['door_id'],door_interval_m=interval, connection_kind='selected_single_room_access') if _components(plan)!=_components(snapshot): plan.clear();plan.update(snapshot) return # Defensive rollback; never continue with stale references. report.append(dict(before=before,after=copy.deepcopy(door), reason='generated_bedroom_access_to_adjacent_hall_frees_living_wall')) changed=True;break if changed:break DOOR_MIN_JAMB_M = .05 # solid wall kept between a door and the face of the perpendicular wall at its segment end def ensure_door_jambs(plan, min_jamb_m=DOOR_MIN_JAMB_M): """Keep every non-fixed interior door clear of the perpendicular walls at the ends of its shared wall. A door whose edge lies within half a wall thickness (plus a jamb) of a room corner leaves a wall stub only a centimetre long; the meshed shell then has a notch beside the frame and the saved-opening check fails. The door is slid inward along the same wall. Its width is never changed: ordinary openings are contracted to their declared width downstream. A shared wall too short for the door plus both jambs is left unchanged and reported. Returns a new plan.""" result = copy.deepcopy(plan) rooms = {r['room_id']: r for r in result.get('rooms', [])} margin = float(result.get('wall_thickness_m', .2)) / 2 + float(min_jamb_m) changes = [] for door in result.get('doors', []): ids = door.get('room_ids') or [] interval = _finite_interval(door.get('door_interval_m')) if (_fixed(door) or len(ids) != 2 or not all(r in rooms for r in ids) or interval is None or door.get('exterior') or 'exterior' in (door.get('room_types') or []) or door.get('wall_orientation') not in ('H', 'V')): continue tangent = 1 if door['wall_orientation'] == 'V' else 0 a, b = (rooms[r]['bounds_m'] for r in ids) seg_lo, seg_hi = max(a[tangent], b[tangent]), min(a[tangent + 2], b[tangent + 2]) lo, hi = interval if lo - seg_lo >= margin - 1e-6 and seg_hi - hi >= margin - 1e-6: continue width = new_width = hi - lo record = dict(door_id=door.get('door_id'), before_interval_m=[lo, hi], shared_wall_m=[seg_lo, seg_hi], required_margin_m=round(margin, 4)) if seg_hi - seg_lo - 2 * margin < width - 1e-6: changes.append(dict(record, status='unchanged_shared_wall_too_short')) continue center = min(max((lo + hi) / 2, seg_lo + margin + new_width / 2), seg_hi - margin - new_width / 2) new = [round(center - new_width / 2, 4), round(center + new_width / 2, 4)] clash = any(other is not door and _same_wall(door, other) and other.get('door_interval_m') and min(new[1], other['door_interval_m'][1]) - max(new[0], other['door_interval_m'][0]) > -.10 for other in result.get('doors', [])) if clash: changes.append(dict(record, status='unchanged_neighbour_door')) continue door['door_interval_m'] = new for adjacency in result.get('topology_adjacencies', []): if adjacency.get('door_id') and adjacency.get('door_id') == door.get('door_id'): adjacency['door_interval_m'] = list(new) changes.append(dict(record, status='adjusted', after_interval_m=new)) if changes: result.setdefault('adaptive_shell_door_jambs', []).extend(changes) return result def _exterior_spans(plan, room, window, corner_margin_m=.2): from engine.source.scripts.internal.scene_generation.window_rules import MIN_OPENING_GAP_M b=room['bounds_m'];axis=0 if window['wall_orientation']=='V' else 1;tangent=1-axis line=window['wall_line_m'] if min(abs(line-b[axis]),abs(line-b[axis+2]))>1e-5:return [] side=1 if abs(line-b[axis+2])<1e-5 else -1 spans=[(b[tangent],b[tangent+2])] for other in plan['rooms']: if other['room_id']==room['room_id']:continue ob=other['bounds_m'] # Shared/intersecting neighboring room projection is never exterior. touches=(ob[axis]-0.1 <= line < ob[axis+2]-1e-5 if side>0 else ob[axis]+1e-5 < line <= ob[axis+2]+0.1) if touches:spans=_subtract(spans,(ob[tangent],ob[tangent+2])) # Native RPLAN topology merges nearby boundaries; those spans remain # interior even when the raw rectangles have a small gap between them. for adj in plan.get('topology_adjacencies',[]): if (room['room_id'] in adj.get('room_ids',[]) and adj.get('wall_orientation')==window['wall_orientation'] and abs(adj['wall_line_m']-line)<=.29+1e-6): spans=_subtract(spans,adj['overlap_interval_m']) spans=[(lo+corner_margin_m,hi-corner_margin_m) for lo,hi in spans if hi-lo>2*corner_margin_m] for other in plan.get('windows',[])+plan.get('doors',[]): if other is window or not _same_wall(window,other):continue interval=other.get('window_interval_m',other.get('door_interval_m')) if interval:spans=_subtract(spans,(interval[0]-MIN_OPENING_GAP_M,interval[1]+MIN_OPENING_GAP_M)) return spans def _finite_interval(value): try: if len(value) != 2 or not all(math.isfinite(float(v)) for v in value): return None except (TypeError, ValueError): return None return [float(value[0]), float(value[1])] def _front_door_snap_limit_m(): try: value = float(os.environ.get('RHG_FRONT_DOOR_MAX_SNAP_M', '1.5')) except (TypeError, ValueError): return 1.5 return value if math.isfinite(value) and value >= 0 else 1.5 def _front_door_snap_candidate(interval, spans, width=1.0): lo, hi = interval center = (lo + hi) / 2.0 candidates = [] for start, end in spans: if end - start < width - 1e-6: continue candidate_start = min(max(center - width / 2.0, start), end - width) candidate = [round(candidate_start, 6), round(candidate_start + width, 6)] candidates.append((abs(candidate_start + width / 2.0 - center), candidate)) return min(candidates, key=lambda item: item[0]) if candidates else None def _resize_windows(plan, report): from engine.source.scripts.internal.scene_generation import window_rules rooms={r['room_id']:r for r in plan['rooms']};thickness=float(plan.get('wall_thickness_m',.2)) for w in plan.get('windows',[]): room=rooms[w['room_id']] if 'bedroom' not in room.get('room_type','') or _fixed(w):continue if w.get('source')!='v14_4_exterior_daylight_ventilation_glazing':continue spans=_exterior_spans(plan,room,w) if not spans: report.append(dict(window_id=w['window_id'],status='no_legal_exterior_interval'));continue b=room['bounds_m'];axis=1 if w['wall_orientation']=='V' else 0 height=min(1.5,float(plan.get('wall_height_m',3))-.25-.9) if height<=0:continue area=max(0,b[2]-b[0]-thickness)*max(0,b[3]-b[1]-thickness) target=max((b[axis+2]-b[axis]-thickness)*.5,area*.18/height) middle=sum(w['window_interval_m'])/2 spans.sort(key=lambda s:(not (s[0]<=middle<=s[1]),-(s[1]-s[0]),s[0])) lo,hi=spans[0];available=hi-lo tiers=[v for v in (1.8,2.2,2.4) if v<=available+1e-6] choices=[v for v in tiers if v>=target-1e-6] width=min(choices) if choices else max(tiers) if tiers else min(w['window_width_m'],available) if width<=0:continue old=copy.deepcopy(w);center=(lo+hi)/2 w.update(window_interval_m=[round(center-width/2,3),round(center+width/2,3)], window_width_m=round(width,3),sill_height_m=.9,head_height_m=round(.9+height,3)) w['glazing']=window_rules.glazing(w,float(plan.get('wall_height_m',3))) report.append(dict(window_id=w['window_id'],before_width_m=old['window_width_m'], chosen_width_m=w['window_width_m'],target_width_m=round(target,3), status='standard_size' if choices else 'largest_standard_below_target' if tiers else 'compact_legal_fallback', daylight_qualified=False)) def adapt_generated_shell(plan): result=copy.deepcopy(plan) if result.get('adaptive_shell',{}).get('schema')==VERSION:return result report=dict(schema=VERSION,authority='new_generated_openings_only',door_changes=[],window_changes=[], connected_before=_components(result),physical_qualified=False) _relocate_doors(result,report['door_changes']) _resize_windows(result,report['window_changes']) report['connected_after']=_components(result) result['adaptive_shell']=report return result def _reconcile_front_windows(plan, door, rooms, authored_windows): """Give the real entrance priority over unfixed native glazing on its wall.""" from engine.source.scripts.internal.scene_generation.window_rules import MIN_OPENING_GAP_M lo,hi=door['door_interval_m'] protected={w.get('window_id') for w in authored_windows} generated_sources={'v14_4_exterior_daylight_ventilation_glazing', 'window_rules_v1_second_window_for_daylight_ratio'} for window in list(plan.get('windows', [])): if (window.get('source') not in generated_sources or _fixed(window) or window.get('window_id') in protected or not _same_wall(door,window)): continue a,b=window['window_interval_m'] if max(a-hi,lo-b)>=MIN_OPENING_GAP_M-1e-6: continue width=b-a spans=_exterior_spans(plan,rooms[window['room_id']],window) starts=[min(max(a,s),t-width) for s,t in spans if t-s>=width-1e-6] if starts: start=min(starts,key=lambda v:abs(v-a)) window['window_interval_m']=[round(start,6),round(start+width,6)] else: plan['windows'].remove(window) def restore_authored_openings(generated, source): """Reconcile supplied openings after topology discovery, before meshing. Invalid supplied geometry is reported instead of silently moving a fixed opening. Partial authored lists replace their corresponding generated pair. RPLAN interior doors additionally replace other native access doors of the same private/service room. RPLAN front doors replace the native exterior entry when possible, snapping a partially out-of-range interval or recording a native-entry fallback when it cannot be used. The caller must validate the resulting graph and fall back to its native snapshot if those replacements disconnect it. """ result=copy.deepcopy(generated) rooms={r['room_id']:r for r in result['rooms']} rplan_private=set() has_rplan_front=any(d.get('source')=='rplan_png_front_door' for d in source.get('doors', [])) authored_windows=copy.deepcopy(source.get('windows',[])) if has_rplan_front: # Front-door validation must see final supplied glazing, including a # window that replaces a conflicting native window on the same wall. result['windows']=[w for w in result.get('windows',[]) if not any( w.get('room_id')==s.get('room_id') and _same_wall(w,s) for s in authored_windows)] result['windows'].extend(authored_windows) native_front_doors=[copy.deepcopy(d) for d in result.get('doors',[]) if d.get('source')=='v14_3_public_exterior_entry'] front_windows_snapshot=copy.deepcopy(result.get('windows',[])) def front_door_fallback(door, reason, spans): # A failed authored front-door attempt must leave the native entry and # the pre-attempt glazing in place for the caller's connectivity check. result['windows']=copy.deepcopy(front_windows_snapshot) result['doors']=[d for d in result.get('doors',[]) if d.get('source')!='v14_3_public_exterior_entry' and not (d.get('exterior') or 'exterior' in (d.get('room_types') or []))] result['doors'].extend(copy.deepcopy(native_front_doors)) result['authored_front_door_fallback']=dict( door_id=door.get('door_id'), reason=reason, interval=_finite_interval(door.get('door_interval_m')), legal_intervals=[[round(a,6),round(b,6)] for a,b in spans]) def front_legal_spans(door, room_id): if room_id not in rooms or door.get('wall_orientation') not in ('H','V'): return [] try: if not math.isfinite(float(door['wall_line_m'])): return [] except (KeyError,TypeError,ValueError): return [] return _exterior_spans(result, rooms[room_id], door, corner_margin_m=.1) for supplied in source.get('doors',[]): door=copy.deepcopy(supplied);ids=door.get('room_ids',[]) rplan=door.get('source')=='rplan_png_interior_door' rplan_front=door.get('source')=='rplan_png_front_door' if has_rplan_front and not rplan_front and (door.get('source')=='v14_3_public_exterior_entry' or door.get('exterior') or 'exterior' in (door.get('room_types') or [])): continue if rplan_front: room_id=ids[0] if isinstance(ids,(list,tuple)) and len(ids)==1 else None exterior=bool(door.get('exterior')) or 'exterior' in (door.get('room_types') or []) if room_id not in rooms or not exterior: front_door_fallback(door,'invalid_exterior_geometry_or_width',[]) continue try: lo,hi=door['door_interval_m'] wall_line=float(door['wall_line_m']);width=float(door['door_width_m']) lo=float(lo);hi=float(hi) geometry_valid=(door.get('wall_orientation') in ('H','V') and lo_front_door_snap_limit_m()+1e-6: front_door_fallback(door,'snap_distance_exceeds_limit',spans) continue door['snapped_from_interval_m']=[round(lo,6),round(hi,6)] door['snap_distance_m']=round(snap_distance,6) door['snap_reason']='outside_legal_exterior_interval' door['door_interval_m']=candidate_interval door['door_width_m']=1.0 result['doors']=[d for d in result.get('doors', []) if d.get('door_id')!=door.get('door_id') and not (d.get('exterior') or 'exterior' in (d.get('room_types') or []))] result['doors'].append(door) continue if not ids or any(r not in rooms for r in ids):raise ValueError('authored door room missing') # These source records describe interior swing doors only. Never turn # a native entry, public opening or balcony portal into one. if rplan and (len(ids)==1 or any(rooms[r].get('room_type')=='balcony' for r in ids)): continue if len(ids)==2: target=next((a for a in result['topology_adjacencies'] if set(a['room_ids'])==set(ids)),None) # Mixed libraries may supply a superseded default after the real # door. Skip only those defaults; keep all other authored ordering. if (door.get('source')=='circulation_graph_selected_v8' and rplan_private.intersection(ids) and not any(rooms[r].get('room_type')=='balcony' for r in ids) and not (target and (target.get('open_connection') or target.get('open_interval_m')))): continue if rplan and target is not None and (target.get('open_connection') or target.get('open_interval_m')): continue if target is None or not _same_wall(target,door):raise ValueError('authored door is not on shared wall') lo,hi=door['door_interval_m'];a,b=target['overlap_interval_m'] if not a<=lo