import torch


def rotated_box_to_poly(rotated_boxes: torch.Tensor):
    """ Transform rotated boxes to polygons
    Args:
        rotated_boxes (Tensor): (x, y, w, h, a) with shape (n, 5)
    Return:
        polys (Tensor): 4 corner points (x, y) of polygons with shape (n, 4, 2)
    """
    cs = torch.cos(rotated_boxes[:, 4])
    ss = torch.sin(rotated_boxes[:, 4])
    w = rotated_boxes[:, 2] - 1
    h = rotated_boxes[:, 3] - 1

    x_ctr = rotated_boxes[:, 0]
    y_ctr = rotated_boxes[:, 1]
    x1 = x_ctr + cs * (w / 2.0) - ss * (-h / 2.0)
    x2 = x_ctr + cs * (w / 2.0) - ss * (h / 2.0)
    x3 = x_ctr + cs * (-w / 2.0) - ss * (h / 2.0)
    x4 = x_ctr + cs * (-w / 2.0) - ss * (-h / 2.0)

    y1 = y_ctr + ss * (w / 2.0) + cs * (-h / 2.0)
    y2 = y_ctr + ss * (w / 2.0) + cs * (h / 2.0)
    y3 = y_ctr + ss * (-w / 2.0) + cs * (h / 2.0)
    y4 = y_ctr + ss * (-w / 2.0) + cs * (-h / 2.0)

    polys = torch.stack([x1, y1, x2, y2, x3, y3, x4, y4], dim=-1)
    polys = polys.reshape(-1, 4, 2)  # to (n, 4, 2)

    return polys