o
    ߥiu1                     @   s4  d dl Z d dlZd dlZd dlmZ d dlZd dlm  m	Z
 d1ddZdd Zd2d
dZdd Zdd Zdd ZdejdejdejfddZdejdejdejfddZd3dejdedejfddZd3dejdedejfddZd d! Zd"d# Zd$d% Zd&d' Zd(d) Zd*d+ Zd,d- Zd.ejdejfd/d0ZdS )4    NFc                 C   sF  t | d}| }W d    n1 sw   Y  g }g }g }g }g }g }	d}
|D ]}|d d dkrHdd | ddd  D }|| |d d d	kr| ddd  }d
d |D }t|
t|}
|| d|d v rt|d dd dkrdd |D }|| d|d v rt|d ddkrt|d dd dkrdd |D }|	| |d d dkr| ddd  }dd |D }|| |d d dkr| ddd  }dd |D }|| q)t|	tj
}|
dkrt|	tj}ntd |jd dkr ||d}n|d d d df |d d dd f |d}t|dkrJt|	tj
}||d< t|dkr^t|	tj
}||d< t|dkrw|
dkrst|	tj}||d< t|	dkr|
dkrt|		tj}	|	|d< |rtdt| tdt| |S )Nrr      zv c                 S       g | ]}t |d krt|qS r   lenfloat.0a r   `/home/ubuntu/.local/lib/python3.10/site-packages/modelscope/models/cv/human3d_animation/utils.py
<listcomp>   s    zread_obj.<locals>.<listcomp>    f c                 S   s*   g | ]}t |d krt|dd  qS )r   /r   intsplitr	   r   r   r   r          * r   c                 S   *   g | ]}t |d krt|dd qS )r   r   r   r   r	   r   r   r   r   %   r      c                 S   r   )r   r   r   r   r	   r   r   r   r   *   s    $zvt c                 S   r   r   r   r	   r   r   r   r   1        zvn c                 S   r   r   r   r	   r   r   r   r   6   r   znot a triangle face mesh!)verticesfaces)r   colorsr   uvsnormalsfaces_uvfaces_normalznum of verticesznum of faces)open	readlinesstripr   appendmaxr   nparrayastypefloat32int32printshape)obj_pathprint_shapef	bfm_linesr   r   r   vnsr   r    max_face_lengthlinevertexitemsfaceface_uvface_normaluvvnmeshr   r   r   read_obj   s   


&
$





r<   c                    s  t j| }t jt j| d }d|v rntt j||d |d  tt j||d d5}|	d |	d |	d |	d	 |	d
 |	d |	d |	d
|d  W d    n1 siw   Y  t| d	}d|v r|	d |	d
| d|v rt|d D ])\}}|	d
|d |d |d |d | d |d | d |d | d  qn|d D ]}|	d
|d |d |d  qd|v r|d D ]}|	d
|d |d  qd|v r|d D ]}|	d
|d |d |d  qd|v rmt|d D ]c\}	 d|v sd|v rRd|v r+|d |	 n d|v r9|d |	 n dd fdd tt D  d! }
ndd fd"d tt D  d! }
|	|
 qW d    d S W d    d S 1 sw   Y  d S )#Nr   texture_mapz.pngz.mtlwznewmtl material_0
zKa 1.000000 0.000000 0.000000
zKd 1.000000 1.000000 1.000000
zKs 0.000000 0.000000 0.000000
zTr 0.000000
zillum 0
zNs 0.000000
z
map_Kd {}
z# Create by ModelScope
zmtllib ./{}.mtl
r   r   zv {} {} {} {} {} {}
r   r   zv {} {} {}
r   z	vt {} {}
r   zvn {} {} {}
r   r   r    r   r   c                    s&   g | ]}d   | | | qS )z{}/{}/{}formatr
   ir6   r8   r7   r   r   r      s    zwrite_obj.<locals>.<listcomp>
c                    s   g | ]	}d   | qS )z{}r?   rA   )r6   r   r   r      s    )ospathdirnamesplitextbasenamecv2imwritejoinr!   writer@   	enumerateranger   )	save_pathr;   save_dir	save_namewfrB   vr9   r:   indrowr   rC   r   	write_objc   sz   








 "
"





$rW   皙?      ?      I@c              
   C   s^   t ||  dddgd||  ddgdd||  ||  d| |  ||  gg dgt jS )Nr   r   )r   r   r   r&   r'   r(   r)   )xnr/   r   r   r   
projection   s    *r_   c                 C   s6   t ddd| gddd|gddd|gg dgt jS )Nr   r   r   r   r   r   r\   )r]   yzr   r   r   	translate   s
   "rc   c                 C   sJ   t | t | }}t g dd||dgd| |dgg dgt jS )N)r   r   r   r   r   r`   r&   sincosr'   r(   r)   r   scr   r   r   rotate_x       rj   c                 C   sJ   t | t | }}t |d|dgg d| d|dgg dgt jS )Nr   )r   r   r   r   r`   rd   rg   r   r   r   rotate_y   rk   rl   r]   ra   returnc                 C   s   t j| | dddS )Nr[   Tkeepdim)torchsum)r]   ra   r   r   r   dot   s   rr   r^   c                 C   s   dt | | | |  S )Nr   )rr   )r]   r^   r   r   r   reflect   s   rs   #B;epsc                 C   s   t t jt| | |dS )N)min)rp   sqrtclamprr   r]   ru   r   r   r   length   s   rz   c                 C   s   | t | | S )N)rz   ry   r   r   r   safe_normalize   s   r{   c                 C   sX   t | tjrt|  n| }tj|t|jd dg gdd}t	||
 d S )Nr   r   )axisN.)
isinstancer&   ndarrayrp   
from_numpycudacatonesr,   matmult)mtxpost_mtxposwr   r   r   transform_pos   s   &r   c
                 C   s  t ||}
tj| |
|||gd\}}|r/tj|d |||dd\}}tj|d ||d|	d}nt|d ||\}}tj|d |dd}|tj}||d d d	f d d f }||d d d
f d d f }||d d df d d f }tt	|| || }tj
d	|jd	 tjddd d d f d
d}t|d || \}}|d
 d }t|ddd f d	d
}|| d
| t|  }|| d
| t|  }|||fS )N)
resolutionr}   all)rast_db
diff_attrszlinear-mipmap-linear)filter_modemax_mip_levellinear)r   r   r   r   r   )dtypedevicer         ?.r[   )r   dr	rasterizeinterpolatetexturetyperp   longr{   crossaranger,   int64repeatr   rx   	ones_like)glctxr   r   pos_idxr9   uv_idxtexr   
enable_mipr   pos_cliprast_outrast_out_dbtexctexdcolor_v0v1v2face_normalsface_normal_indicesgb_geometric_normalnormalmaskr   r   r   render   sT   




r   c                 C   s    | dk |dk k}t ||  | S )a  
    Return a tensor where each element has the absolute value taken from the,
    corresponding element of a, with sign taken from the corresponding
    element of b. This is like the standard copysign floating-point operation,
    but is not careful about negative 0 and NaN.

    Args:
        a: source tensor.
        b: tensor whose signs will be used, of the same shape as a.

    Returns:
        Tensor of the same shape as a with the signs of b.
    r   )rp   where)r   bsigns_differr   r   r   	_copysign   s   r   c                 C   s(   t | }| dk}t | | ||< |S )z[
    Returns torch.sqrt(torch.max(0, x))
    but with a zero subgradient where x is 0.
    r   )rp   
zeros_likerw   )r]   retpositive_maskr   r   r   _sqrt_positive_part  s   
r   c                 C   s   |  ddks|  ddkrtd| j d| d }| d }| d }d	td
| | |  }d	td
| | |  }d	td
| | |  }d	td
| | |  }t|| d | d  }t|| d | d  }	t|| d | d  }
t|||	|
fdS )z
    Convert rotations given as rotation matrices to quaternions.

    Args:
        matrix: Rotation matrices as tensor of shape (..., 3, 3).

    Returns:
        quaternions with real part first, as tensor of shape (..., 4).
    r[   r   z Invalid rotation matrix  shape f.).r   r   ).r   r   ).r   r   r   r   ).r   r   ).r   r   ).r   r   ).r   r   ).r   r   ).r   r   )size
ValueErrorr,   r   r   rp   stack)matrixm00m11m22o0r]   ra   rb   o1o2o3r   r   r   matrix_to_quaternion  s   
r   c                 C   s   t j| dddf dddd}t || dddf }d| }d}| |k }t |}t ||  ||   || < d	|| ||  d
  ||< | dddf | S )a  
    Convert rotations given as quaternions to axis/angle.

    Args:
        quaternions: quaternions with real part first,
            as tensor of shape (..., 4).

    Returns:
        Rotations given as a vector in axis angle form, as a tensor
            of shape (..., 3), where the magnitude is the angle
            turned anticlockwise in radians around the vector's
            direction.
    .r   Nr   r[   T)pdimro   gư>r   0   )rp   normatan2abs
empty_likere   )quaternionsnormshalf_anglesanglesru   small_anglessin_half_angles_over_anglesr   r   r   quaternion_to_axis_angle5  s   
r   c                 C   s   t t| S )a{  
    Convert rotations given as rotation matrices to axis/angle.

    Args:
        matrix: Rotation matrices as tensor of shape (..., 3, 3).

    Returns:
        Rotations given as a vector in axis angle form, as a tensor
            of shape (..., 3), where the magnitude is the angle
            turned anticlockwise in radians around the vector's
            direction.
    )r   r   )r   r   r   r   matrix_to_axis_angleR  s   r   d6c                 C   s|   | dddf | dddf }}t j|dd}||| jddd|  }t j|dd}tj||dd}tj|||fddS )	a  
    Converts 6D rotation representation by Zhou et al. [1] to rotation matrix
    using Gram--Schmidt orthogonalisation per Section B of [1].
    Args:
        d6: 6D rotation representation, of size (*, 6)

    Returns:
        batch of rotation matrices of size (*, 3, 3)

    [1] Zhou, Y., Barnes, C., Lu, J., Yang, J., & Li, H.
    On the Continuity of Rotation Representations in Neural Networks.
    IEEE Conference on Computer Vision and Pattern Recognition, 2019.
    Retrieved from http://arxiv.org/abs/1812.07035
    .Nr   r[   )r   Trn   r   )F	normalizerq   rp   r   r   )r   a1a2b1b2b3r   r   r   rotation_6d_to_matrixb  s   "r   )F)rX   rY   rZ   )rt   )rE   rJ   numpyr&   nvdiffrast.torchrp   r   torch.nn.functionalnn
functionalr   r<   rW   r_   rc   rj   rl   Tensorrr   rs   r   rz   r{   r   r   r   r   r   r   r   r   r   r   r   r   <module>   s0   
W
>.