"""Stage-derived floor, explicit unknown boundaries and capability-grid raw coverage.""" from dataclasses import dataclass import math import numpy as np from ..artifacts import ContractError from .ground_stream import project _GEOMETRY_CHUNK_PIXELS = 32768 @dataclass class FloorResult: labels: np.ndarray # 0=not derived floor, 1=derived floor, 2=unknown stage boundary/depth world_uv: np.ndarray candidate_indices: np.ndarray candidate_height_m: np.ndarray candidate_normal_y: np.ndarray class FloorProjector: """Cache exact pixel-centre rays by projection, with camera depth -Z=1.""" def __init__(self,policy,dtype=np.float32): self.policy=dict(policy);self.dtype=np.dtype(dtype);self.cache={};self.workspace={} if policy['method']!='derived_floor/3-inverse-depth-planar':raise ContractError('Unknown floor method') def rays(self,shape,projection): key=(tuple(shape),np.asarray(projection,np.float64).tobytes()) if key not in self.cache: h,w=shape;x,y=np.meshgrid(np.arange(w)+.5,np.arange(h)+.5) clip=np.stack((2*x/w-1,1-2*y/h,-np.ones_like(x),np.ones_like(x)),axis=-1) p=clip@np.linalg.inv(np.asarray(projection,np.float64)).T rays=p[:,:,:3]/p[:,:,3,None];rays/=(-rays[:,:,2,None]) self.cache[key]=rays.astype(self.dtype).reshape(-1,3) return self.cache[key] def derive(self,depth,semantic,camera,projection,floor): """Float32 fast path: normals only at eligible stage-height pixels, not furniture.""" h,w=depth.shape;d=np.asarray(depth,dtype=self.dtype);sem=np.asarray(semantic) if sem.shape!=d.shape:raise ContractError('Floor channels differ') if project is not None and self.dtype==np.dtype('float32'): cast=self.dtype.type return FloorResult(*project(d,sem,self.rays((h,w),projection),np.asarray(camera,dtype=self.dtype), cast(floor),cast(self.policy['inverse_depth_abs_m_inv']),cast(self.policy['inverse_depth_relative']), cast(self.policy['height_tolerance_m']),cast(math.cos(math.radians(self.policy['normal_angle_deg']))))) # These buffers are scratch only; all FloorResult arrays remain independently owned. if d.shape not in self.workspace: inner=d[1:-1,1:-1].shape self.workspace[d.shape]=(np.empty(d.shape,bool),np.empty(d.shape,bool), np.empty(d.shape,bool),np.empty_like(d),np.empty(inner,self.dtype), np.empty(inner,self.dtype),np.empty(inner,self.dtype),np.empty(inner,bool)) valid,stage,eligible,inv,limit,twice,delta,within=self.workspace[d.shape] np.isfinite(d,out=valid);np.greater(d,0,out=eligible) np.logical_and(valid,eligible,out=valid);np.equal(sem,0,out=stage) np.logical_and(stage,valid,out=eligible) continuous=np.zeros_like(eligible) ok=eligible[1:-1,1:-1].copy() for neighbor in (eligible[:-2,1:-1],eligible[2:,1:-1],eligible[1:-1,:-2],eligible[1:-1,2:]): ok&=neighbor inv.fill(0);np.divide(1,d,out=inv,where=valid) center=inv[1:-1,1:-1] np.multiply(self.policy['inverse_depth_relative'],center,out=limit) np.maximum(self.policy['inverse_depth_abs_m_inv'],limit,out=limit) np.multiply(2,center,out=twice) for left,right in ((inv[1:-1,:-2],inv[1:-1,2:]),(inv[:-2,1:-1],inv[2:,1:-1])): np.add(left,right,out=delta);np.subtract(delta,twice,out=delta);np.abs(delta,out=delta) np.less_equal(delta,limit,out=within);ok&=within continuous[1:-1,1:-1]=ok labels=np.zeros((h,w),np.uint8);labels[stage&~continuous]=2 rays=self.rays((h,w),projection);m=np.asarray(camera,dtype=self.dtype) idx=np.flatnonzero(continuous.ravel());z=d.ravel() # Bound the geometry working set without changing any per-pixel arithmetic. # Row order and each returned array's ownership are preserved across chunks. indices=[];heights=[];normals=[];coordinates=[] for offset in range(0,max(1,len(idx)),_GEOMETRY_CHUNK_PIXELS): chunk=idx[offset:offset+_GEOMETRY_CHUNK_PIXELS] points=rays[chunk]*z[chunk,None];height=np.einsum('ij,j->i',points,m[1,:3])+m[1,3]-self.dtype.type(floor) keep=np.abs(height)<=self.policy['height_tolerance_m'];chunk=chunk[keep];height=height[keep];points=points[keep] dx=rays[chunk+1]*z[chunk+1,None]-rays[chunk-1]*z[chunk-1,None] dy=rays[chunk+w]*z[chunk+w,None]-rays[chunk-w]*z[chunk-w,None] normal=np.cross(dx,dy);length=np.linalg.norm(normal,axis=1) facing=np.einsum('ij,ij->i',normal,-points);normal[facing<0]*=-1 ny=np.divide(np.einsum('ij,j->i',normal,m[1,:3]),length,out=np.full(len(chunk),np.nan,self.dtype),where=length>1e-12) labels.ravel()[chunk[~np.isfinite(ny)]]=2 selected=np.isfinite(ny)&(ny>=math.cos(math.radians(self.policy['normal_angle_deg']))) ids=chunk[selected];labels.ravel()[ids]=1 points=points[selected] uv=np.column_stack((np.einsum('ij,j->i',points,m[0,:3])+m[0,3],-(np.einsum('ij,j->i',points,m[2,:3])+m[2,3]))) indices.append(chunk);heights.append(height);normals.append(ny);coordinates.append(uv) return FloorResult(labels,np.concatenate(coordinates),np.concatenate(indices), np.concatenate(heights),np.concatenate(normals)) def polygon_mask(uv,vertices): """Vectorized parity with boundary inclusion; capability cells are represented by centres.""" p=np.asarray(uv);v=np.asarray(vertices);inside=np.zeros(len(p),bool);edge=np.zeros(len(p),bool) for a,b in zip(v,np.roll(v,-1,axis=0)): d=b-a;r=p-a;cross=d[0]*r[:,1]-d[1]*r[:,0] edge|=(np.abs(cross)<=1e-10)&(np.einsum('ij,ij->i',r,p-b)<=1e-10) if d[1]!=0:inside^=((a[1]>p[:,1])!=(b[1]>p[:,1]))&(p[:,0]i',delta,tangent);side=np.einsum('ij,j->i',delta,np.array([-tangent[1],tangent[0]])) band=(along>=0)&(along<=length)&(np.abs(side)<=.3) self.doors[door['id']]=(ids[band&(side>=0)],ids[band&(side<0)]) def measure(self,uv): cells=np.floor((uv-self.origin)/self.cell_m).astype(np.int64) valid=(cells[:,0]>=0)&(cells[:,1]>=0)&(cells[:,0]