o
    iD                     @   s  d dl Z d dlZd dlZd dlm  mZ d dlm	Z	m
Z
mZ zd dlmZ W n ey;   d dlmZ ed Y nw d dlmZ e dRdd	Ze 	
	dSdejdejdedededefddZe 	
		dTdejdejdededededefddZe dejdejdejdejfddZdejd ejd!ejd"ejdejf
d#d$Zd%ejdejfd&d'Zd(ejd)ejdejfd*d+Z	,dUd%ejd-ejd.edejfd/d0Z d1ejd2e!dejfd3d4Z"d1ejd2e!dejfd5d6Z#d7ejd8ejd9ejdejfd:d;Z$d<ejd8ejd9ejdejfd=d>Z%d%ejd-ejdejdejfd?d@Z&dejdejdejdejfdAdBZ'e 	,dUdejdejdejd.edejf
dCdDZ(e 	E	FdVdGejdejdHedIe)dejf
dJdKZ*e 	LdWdejdMejdNedOefdPdQZ+dS )X    N)einsum	rearrangereduce)Rotation)loggerzKDependency 'scipy' not found. Required for interpolating camera trajectory.)as_homogeneous-   c                 C   sv  | j d }| j}| j}|dkrt| S |dk rd}|d dkr#|d7 }|d dkr+|n|d }|dk r5d}t||}|dkrD|dk rDd}g }t|D ]*}|tj| |ddddf | |ddddf | |ddddf gdd qJt	|}t
j|dd	tj }tj|||d
ddd}|d }	g }
tdD ]<}|dddd|f jdd}|dddd|f jd}tj||	|	fdd}t||}|
|dj q|
\}}}||jddd }||jddd }g }t|D ]7}tj|| || }tj|| d|| d|d|| dgdd}||ddddf  qttj	|dd}|S )zyRendering stabilized camera path.
    poses: [batch, 4, 4] or [batch, 3, 4],
    return:
        smooth path: [batch 4 4]r            N   dim)Zksizesigmadtypedevicereflect)modeTr   keepdim)shaper   r   r   minrangeappendtorchcatstackcv2getGaussianKernelastypenpfloat32squeezetensorviewT	unsqueezeFpadconv1dnormlinalgcross)Zposesk_size
num_framesr   r   Zmax_oddZinput_posesiZgaussian_kernelr*   Zoutput_vectorsidxvecZ
vec_paddedfilteredZ	output_r1Z	output_r2Zoutput_tZoutput_posesZ	output_r3Zrender_pose r5   G/data/cameron/da3_repo/src/depth_anything_3/utils/camera_trj_helpers.pyrender_stabilization_path   sb   

H
"
	r7   x         H@	cam2world	intrinsichwr0   max_dispc                 C   s   | j | j}}|d | }|| }	tjddtj |||d}
|	t|
 }|	t|
 d }tjd||dd	|dd}tj
|||gd	d
d |d d d ddf< | d| }tj| d|| dgdd
}|d	|jd dd}||fS )Nr   r   r          @stepsr   r   g      @r   r   r   r	   r   r   g      r   )r   r   r   linspacepisincoseyer(   repeatr   r   r   )r:   r;   r<   r=   r0   r>   r   r   fxrthxZyzr'   c2wsKsr5   r5   r6   render_wander_pathl   s   	 * rP   皙?      $@D_focusc                 C   s  | j | j}}|d | |d | }	}
tjdd|||d}ddttj|   | }tjd||d	d
|dd}| |d d ddf< | d
| }tj	|||d	}|||  j
dd}|d
|dd}|	| | |d d d
d
f< |
| | |d d ddf< ||fS )Nr?   )r	   r	   g        r@   rA         ?g      ?r   rC   r   r	   r
   r   gư>)r   )r   r   r   rD   rG   rE   rH   r(   rI   	as_tensorclamp)r:   r;   r<   r=   r0   r>   rS   r   r   fx0Zfy0tzr'   rN   ZDfscalerO   r5   r5   r6   render_dolly_zoom_path   s   
 r[   initialfinalrX   returnc                 C   s.   t | d} t |d}t |d}| ||  |  S )N... i j -> ... () i jzt -> t () ())r   )r\   r]   rX   r5   r5   r6   interpolate_intrinsics   s   


r`   	a_originsa_directions	b_originsb_directionsc           	      C   s   t | |||\} }}}t j| |fdd}t j||fdd}t||d}|t jd|j|jd }t|dd}t||d}t|d	d}t j	||j
S )
zCompute the least-squares intersection of rays. Uses the math from here:
    https://math.stackexchange.com/a/1762491/286022
    r   z... n i, ... n j -> ... n i jr   r   z... n i j -> ... i jsumz... n i j, ... n j -> ... n iz... n i -> ... i)r   broadcast_tensorsr   r   rH   r   r   r   r-   lstsqsolution)	ra   rb   rc   rd   origins
directionsnlhsrhsr5   r5   r6   intersect_rays   s   ro   ac                 C   s   | | j ddd S )Nr   Tr   )r,   )rp   r5   r5   r6   	normalize   s   rq   yrY   c                 C   s.   t | |\} }t j| j|dd| |gddS )zMGenerate a coordinate frame given perpendicular, unit-length Y and Z vectors.r   r   )r   rg   r   r.   )rr   rY   r5   r5   r6   generate_coordinate_frame   s   rs   -C6?bepsc                 C   s   | j }|  }t| |d d  |k }tjg d|j|d||< t| |d d  |k }tjg d|j|d||< tt	tj
| || S )zGenerate a coordinate frame where the Y direction is normal to the plane defined
    by unit vectors a and b. The other axes are arbitrary.... i, ... i -> ...r	   )r   r   r	   r   )r   r	   r   )r   detachcloner   absr   r%   r   rs   rq   r-   r.   )rp   ru   rv   r   parallelr5   r5   r6   "generate_rotation_coordinate_frame   s   r|   	rotationspatternc                 C   s`   | j ^ }}}| ddd} t|    |}tj	|| j
| jd} | jg |dR  S Nr   r   r   )r   reshapeRZfrom_matrixrx   cpunumpyZas_eulerr   r%   r   r   )r}   r~   batch_Z	angles_npr5   r5   r6   matrix_to_euler   s
   r   c                 C   s`   | j ^ }}| dd} t||     }tj	|| j
| jd} | jg |ddR  S r   )r   r   r   
from_eulerrx   r   r   	as_matrixr   r%   r   r   )r}   r~   r   r   Z	matrix_npr5   r5   r6   euler_to_matrix   s
   r   
extrinsicspivot_coordinate_framepivot_pointc                 C   s   |ddddf }t || ddddf }| ddddf }|| }t||d}| | dddddf  }t|djdd	\}	}
}tj||	d
 |d
 gdd	S )aS  Convert the extrinsics to a representation with 5 degrees of freedom:
    1. Distance from pivot point in the "X" (look cross pivot axis) direction.
    2. Distance from pivot point in the "Y" (pivot axis) direction.
    3. Distance from pivot point in the Z (look) direction
    4. Angle in plane
    5. Twist (rotation not in plane)
    .Nr	   r   r
   z... i j, ... i -> ... jYXZr   r   .N)rs   r   inverser   unbindr   r   )r   r   r   
pivot_axistranslation_frameorigindeltatranslationinvertedrr   r   rY   r5   r5   r6   extrinsics_to_pivot_parameters  s   r   
parametersc                 C   s   | j ddd\}}}tj|t||fdd}|t|d }|dd d df }t||dd ddf }	t|	|d	}
||
 }|j^ }}tjd
| j	| j
d}|g |d
d
R  }d|d< ||dd dd df< ||dd ddf< |S )N)r   r	   r	   r   r   r   .r	   r   r
   z... i j, ... j -> ... ir   r   ).r   r   )splitr   r   
zeros_liker   rs   r   r   rH   r   r   broadcast_tory   )r   r   r   r   rr   rY   eulerrotationr   r   r   r   r   r   r   r5   r5   r6   pivot_parameters_to_extrinsics  s   r   c                 C   s   t | ||\} }}dt j }| | } || }||   }| | }||  }| | }||  }||k ||k @ }	||k |	 @ }
|	 |
 @ }| ||  |  }||| |  |
 ||
< ||| |  | ||< |S )Nr
   )r   rg   rE   rz   )rp   ru   rX   taudZa_leftZd_leftZa_rightZd_rightZuse_dZ
use_d_leftZuse_d_rightresultr5   r5   r6   interpolate_circular8  s    
r   c           	      C   sp   t | d} t |d}t |d}| jddd\}}|jddd\}}||| |  }t|||}tj||fddS )Nz... d -> ... () dz	t -> t ())r   r
   r   r   )r   r   r   r   r   )	r\   r]   rX   tiritfrfZt_lerpZr_lerpr5   r5   r6   interpolate_pivot_parametersT  s   


r   c                 C   s&  |  tj} | tj}| tj}| ddddf }|ddddf }t||d}| d  |k }| ddddf }|ddddf }	d||	  }
t||  ||  |	|  ||  |
| < t|||d}t| ||
}t|||
}t|||}t	| tj
t|d	 tj
t|
d
 tj
S )zInterpolate extrinsics by rotating around their "focus point," which is the
    least-squares intersection between the look vectors of the initial and final
    extrinsics.
    .Nr   r
   rw   r	   rT   )rv   r_   z... xyz -> ... () xyz)typer   float64r   rz   ro   r|   r   r   r   r#   r   )r\   r]   rX   rv   Zinitial_lookZ
final_lookZdot_productsZparallel_maskZinitial_originZfinal_originr   Zpivot_frameZinitial_paramsZfinal_paramsZinterpolated_paramsr5   r5   r6   interpolate_extrinsicse  s2   

r   r	   Tradiusnum_rotationsscale_radius_with_tc                 C   s   t jdt j|jd}|g | j|jd ddR  }| d } |r(| | } t dt j | | |  |d< t 	dt j | |  |  |d< |S )Nr   r   r   r   r
   ).r   r   ).r	   r   )
r   rH   r#   r   r   r   ry   rF   rE   rG   )r   rX   r   r   r   r5   r5   r6   generate_wobble_transformation  s   ( "r   r   intr_normed	inter_lenn_skipc              
   C   s  || }d}t jdd|t j| jd}g }g }t| jd D ]}	g }
g }td| jd | |D ]w}| |	|dddf }| |	|| dddf }|| jdd}|dkrU|}n|| d }|}t|d	 ||d
d}t| |	|f | |	|| f || }|
	||dkrdndd  |	t
||	|f ||	|| f ||dkrdndd  q.|	t |
 |	t | qt |}
t |}|
|fS )zB
    cam2world: [batch, 4, 4],
    intr_normed: [batch, 3, 3]
    r	   r   r   Nr   r   r   r
   rT   F)r   rX   r   r   )r   rD   r#   r   r   r   r,   r   r   r   r`   r   r   )r:   r   r   r   Zframe_per_roundr   rX   	tgt_c2w_b
tgt_intr_bb_idxtgt_c2wtgt_intrcur_idxZorigin_aZorigin_br   
delta_prevr   Z	cur_extrsr5   r5   r6   render_wobble_inter_path  sZ   



r   )r   )r8   r9   )r8   rQ   rR   )rt   )r	   T)r   ),r   r   r"   r   Ztorch.nn.functionalnn
functionalr)   einopsr   r   r   Zscipy.spatial.transformr   r   ImportErrordepth_anything_3.utils.loggerr   warndepth_anything_3.utils.geometryr   no_gradr7   TensorintfloatrP   r[   r`   ro   rq   rs   r|   strr   r   r   r   r   r   r   boolr   r   r5   r5   r5   r6   <module>   s`  L
 







2