"""도형 세상(Shape World): 이 튜토리얼의 모든 실습이 쓰는 작은 객체 탐지 데이터.

무엇을 하나
  - 장면(scene) 하나 = 원 · 사각형 · 삼각형 1 – 4개. 위치 · 크기 · 색은 무작위.
  - 장면은 0 – 1 로 정규화한 좌표로 적어 두므로, 같은 장면을 어떤 해상도(64, 96, 128 …)로도 그릴 수 있다.
  - 정답(target) 은 박스 (cx, cy, w, h) 와 클래스 번호, 그리고 (13장에서 쓰는) 객체별 마스크.

실행
  python rf_shapes.py        # 표본 그림 shapes_world.png 저장, 배열 모양 출력 (1초 남짓)

2장부터의 실습 파일이 이 파일의 ShapesDataset · collate · draw_boxes 를 가져다 쓴다.
필요한 패키지는 numpy · torch · matplotlib 뿐이다.
"""

from __future__ import annotations

import numpy as np
import torch

# --8<-- [start:classes]
CLASS_NAMES = ["circle", "rectangle", "triangle"]  # 클래스 번호 0, 1, 2
CLASS_NAMES_KO = ["원", "사각형", "삼각형"]
NUM_CLASSES = len(CLASS_NAMES)
# --8<-- [end:classes]

# 도형에 칠할 색 (RGB, 0 – 1). 배경(어두운 회색)과 잘 구별되는 밝은 색만 쓴다.
PALETTE = np.array(
    [
        [0.95, 0.35, 0.35],  # 빨강
        [0.98, 0.65, 0.20],  # 주황
        [0.95, 0.90, 0.30],  # 노랑
        [0.40, 0.85, 0.45],  # 초록
        [0.30, 0.80, 0.90],  # 하늘
        [0.45, 0.55, 0.98],  # 파랑
        [0.80, 0.50, 0.95],  # 보라
        [0.95, 0.95, 0.95],  # 흰색
    ],
    dtype=np.float32,
)


def box_overlap_np(a, b):
    """정규화 (cx, cy, w, h) 박스 두 개의 (IoU, 작은 박스가 가려진 비율).

    장면을 만들 때 겹침을 제한하는 데만 쓴다 (IoU 의 정식 구현은 2장).
    """
    ax0, ay0, ax1, ay1 = a[0] - a[2] / 2, a[1] - a[3] / 2, a[0] + a[2] / 2, a[1] + a[3] / 2
    bx0, by0, bx1, by1 = b[0] - b[2] / 2, b[1] - b[3] / 2, b[0] + b[2] / 2, b[1] + b[3] / 2
    iw = max(0.0, min(ax1, bx1) - max(ax0, bx0))
    ih = max(0.0, min(ay1, by1) - max(ay0, by0))
    inter = iw * ih
    union = a[2] * a[3] + b[2] * b[3] - inter
    return inter / union, inter / min(a[2] * a[3], b[2] * b[3])


# --8<-- [start:scene]
def sample_scene(rng: np.random.Generator, min_objects: int = 1, max_objects: int = 4, max_iou: float = 0.2,
                 max_covered: float = 0.35):
    """장면 하나를 뽑는다. 돌려주는 값은 객체 목록이고, 객체 하나는 다음 사전이다.

    {"cls": 클래스 번호, "box": (cx, cy, w, h) — 모두 0 – 1 로 정규화, "color": RGB}

    - 크기는 그림 한 변의 0.14 – 0.42 배. 원은 w = h, 사각형 · 삼각형은 w 와 h 를 따로 뽑는다.
    - 도형이 그림 밖으로 나가지 않게 중심을 뽑는다.
    - 이미 놓인 도형과 IoU 가 max_iou 를 넘거나, 둘 중 작은 쪽이 max_covered 넘게 가려지면 다시 뽑는다
      (살짝 겹치는 것은 허용하되, 다른 도형에 묻혀 안 보이는 객체는 만들지 않는다).
    """
    count = int(rng.integers(min_objects, max_objects + 1))
    objects = []
    for _ in range(count):
        for _attempt in range(50):
            cls = int(rng.integers(0, NUM_CLASSES))
            w = float(rng.uniform(0.14, 0.42))
            h = w if cls == 0 else float(rng.uniform(0.14, 0.42))
            cx = float(rng.uniform(w / 2 + 0.02, 1 - w / 2 - 0.02))
            cy = float(rng.uniform(h / 2 + 0.02, 1 - h / 2 - 0.02))
            box = (cx, cy, w, h)
            overlaps = [box_overlap_np(box, other["box"]) for other in objects]
            if all(iou <= max_iou and covered <= max_covered for iou, covered in overlaps):
                color = PALETTE[int(rng.integers(0, len(PALETTE)))]
                objects.append({"cls": cls, "box": box, "color": color})
                break
    return objects
# --8<-- [end:scene]


# --8<-- [start:render]
def shape_mask(cls: int, box, size: int) -> np.ndarray:
    """객체 하나가 차지하는 픽셀을 True 로 표시한 (size, size) 배열.

    픽셀 (행 i, 열 j) 의 중심 좌표는 ((j + 0.5) / size, (i + 0.5) / size) 이다. 그 점이 도형 안이면 True.
    """
    cx, cy, w, h = box
    coords = (np.arange(size, dtype=np.float32) + 0.5) / size
    x = coords[None, :]  # (1, size): 열마다의 x 좌표
    y = coords[:, None]  # (size, 1): 행마다의 y 좌표
    if cls == 0:  # 원: 중심에서의 거리가 반지름 이하
        return ((x - cx) / (w / 2)) ** 2 + ((y - cy) / (h / 2)) ** 2 <= 1.0
    inside_box = (np.abs(x - cx) <= w / 2) & (np.abs(y - cy) <= h / 2)
    if cls == 1:  # 사각형: 박스 안 전부
        return inside_box
    # 삼각형: 꼭짓점이 위에 있는 이등변 삼각형. 위에서 t(0 – 1)만큼 내려온 높이에서 폭이 t·w 이다.
    t = (y - (cy - h / 2)) / h
    return inside_box & (np.abs(x - cx) <= t * w / 2)


def render_scene(objects, size: int = 96, rng: np.random.Generator | None = None):
    """장면을 size × size 그림으로 그린다.

    돌려주는 값: image (3, size, size) float32 0 – 1, masks (객체 수, size, size) bool.
    뒤에 놓인 객체가 앞의 객체를 덮으므로, masks 는 "실제로 보이는 부분" 만 True 이다.
    """
    image = np.full((3, size, size), 0.12, dtype=np.float32)  # 어두운 회색 배경
    if rng is not None:
        image += rng.normal(0.0, 0.03, size=image.shape).astype(np.float32)  # 배경 잡음
    masks = np.zeros((len(objects), size, size), dtype=bool)
    for k, obj in enumerate(objects):
        mask = shape_mask(obj["cls"], obj["box"], size)
        masks[:k] &= ~mask  # 먼저 그린 객체는 이번 객체에 가려진 만큼 빼 준다
        masks[k] = mask
        image[:, mask] = obj["color"][:, None]
    if rng is not None:
        image += rng.normal(0.0, 0.02, size=image.shape).astype(np.float32)  # 도형 위에도 약한 잡음
    return np.clip(image, 0.0, 1.0), masks
# --8<-- [end:render]


# --8<-- [start:dataset]
class ShapesDataset(torch.utils.data.Dataset):
    """도형 세상 데이터셋. 만들 때 그림을 모두 그려 메모리에 둔다 (uint8).

    - images: (n, 3, size, size) uint8 — 꺼낼 때 0 – 1 의 float 로 바꾼다.
    - targets[i]: {"boxes": (객체 수, 4) float32 — 정규화 (cx, cy, w, h),
                   "labels": (객체 수,) int64,
                   "masks": (객체 수, size, size) bool — with_masks=True 일 때만}
    seed 가 같으면 언제나 같은 데이터가 나온다. 학습용 · 검증용은 seed 를 다르게 준다.
    """

    def __init__(self, n: int, size: int = 96, seed: int = 0, min_objects: int = 1, max_objects: int = 4,
                 with_masks: bool = False):
        self.size = size
        self.scenes = []
        images = np.zeros((n, 3, size, size), dtype=np.uint8)
        self.targets = []
        for i in range(n):
            rng = np.random.default_rng([seed, i])  # 그림마다 따로 정해진 난수 → 순서와 무관하게 재현
            objects = sample_scene(rng, min_objects, max_objects)
            image, masks = render_scene(objects, size, rng)
            images[i] = np.round(image * 255).astype(np.uint8)
            target = {
                "boxes": torch.tensor([obj["box"] for obj in objects], dtype=torch.float32).reshape(-1, 4),
                "labels": torch.tensor([obj["cls"] for obj in objects], dtype=torch.int64),
            }
            if with_masks:
                target["masks"] = torch.from_numpy(masks)
            self.scenes.append(objects)
            self.targets.append(target)
        self.images = torch.from_numpy(images)

    def __len__(self) -> int:
        return len(self.targets)

    def __getitem__(self, index: int):
        return self.images[index].float() / 255.0, self.targets[index]


def collate(batch):
    """그림은 한 텐서로 쌓고, 정답은 그림마다 객체 수가 달라 목록으로 둔다."""
    images = torch.stack([image for image, _ in batch])
    targets = [target for _, target in batch]
    return images, targets


def make_loader(dataset: ShapesDataset, batch_size: int, shuffle: bool, seed: int = 0):
    generator = torch.Generator().manual_seed(seed)
    return torch.utils.data.DataLoader(
        dataset, batch_size=batch_size, shuffle=shuffle, collate_fn=collate, generator=generator, drop_last=shuffle
    )
# --8<-- [end:dataset]


# --8<-- [start:draw]
def draw_boxes(ax, image, boxes=None, labels=None, scores=None, color="#39ff14", linestyle="-", linewidth=1.8,
               fontsize=7):
    """matplotlib 축 ax 에 그림과 박스를 그린다.

    image: (3, H, W) 텐서 · 배열 (0 – 1). boxes: (n, 4) 정규화 (cx, cy, w, h). labels: 클래스 번호. scores: 점수.
    """
    import matplotlib.patches as patches

    image = np.asarray(image)
    height, width = image.shape[1:]
    ax.imshow(np.transpose(image, (1, 2, 0)), interpolation="nearest")
    ax.set_xticks([])
    ax.set_yticks([])
    if boxes is None:
        return
    boxes = np.asarray(boxes, dtype=np.float32).reshape(-1, 4)
    for k, (cx, cy, w, h) in enumerate(boxes):
        x0, y0 = (cx - w / 2) * width - 0.5, (cy - h / 2) * height - 0.5  # imshow 는 픽셀 중심이 정수 좌표
        ax.add_patch(
            patches.Rectangle((x0, y0), w * width, h * height, fill=False, edgecolor=color, linewidth=linewidth,
                              linestyle=linestyle)
        )
        if labels is not None:
            text = CLASS_NAMES[int(labels[k])]
            if scores is not None:
                text += f" {float(scores[k]):.2f}"
            ax.text(x0 + 1, max(y0 - 1.5, 3), text, color=color, fontsize=fontsize, fontweight="bold")
# --8<-- [end:draw]


def main():
    import matplotlib

    matplotlib.use("Agg")
    import matplotlib.pyplot as plt

    dataset = ShapesDataset(8, size=96, seed=0, with_masks=True)
    image, target = dataset[0]
    print("그림", tuple(image.shape), image.dtype, "값 범위", round(float(image.min()), 2), round(float(image.max()), 2))
    print("박스 (cx, cy, w, h)", [[round(v, 3) for v in box] for box in target["boxes"].tolist()])
    print("클래스", target["labels"].tolist(), "→", [CLASS_NAMES_KO[c] for c in target["labels"].tolist()])
    print("마스크", tuple(target["masks"].shape), target["masks"].dtype)
    counts = [len(t["labels"]) for t in dataset.targets]
    print("그림마다의 객체 수", counts)

    fig, axes = plt.subplots(1, 8, figsize=(16, 2.25))
    for ax, (img, tgt) in zip(axes, dataset):
        draw_boxes(ax, img, tgt["boxes"], tgt["labels"])
    fig.tight_layout(pad=0.3)
    fig.savefig("shapes_world.png", dpi=90)
    print("shapes_world.png 저장")


if __name__ == "__main__":
    main()
