Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
feat(breathe): a smooth mode for large illustrations and video frames — the chest swells from its centre, the shoulders follow a little late, the head and neck stay byte for byte; `sprite-gen breathe` lays either mode over a folder of frames
Soohong Kimcfbf5d37ccea
diff --git a/docs/README.md b/docs/README.mdindex 4c9b312..b7cb32d 100644--- a/docs/README.md+++ b/docs/README.md@@ -42,7 +42,7 @@ flowchart LR| **A · atlas rows** — one still becomes a runtime sprite sheet | [run-contract.md](run-contract.md) | `prepare` → `gen` / `gen-set` → `extract` → `compose-atlas`; optional `curation` and recompose || **B · video → loop** — one still becomes transparent motion loops | [video-pipeline.md](video-pipeline.md) | `video-canvas` → `video` (or `video-prompt` and a video MCP on your agent) → `video-frames` → `video-loop`, `video-set`, `video-cycle-align`, `video-follow` (`video-follow-inspect` shows every cell of it and moves nothing), `video-set-sheet` (a set's directions on one sheet, on one ground line), `video-stop` (a walk or run that stops, from the clip's own start played backwards); `handed-check` for an item on one side || **C · utilities** — imported images in, clean cuts out | [sheet-slicing.md](sheet-slicing.md) | `cutout`, `slice-sheet`, `ui-kit`, `unpack-atlas` |-| **D · post-processing** — finished sheets, refined | [recolor.md](recolor.md) | `recolor`, `recolor-palette`, `compose-layers`, breathing (compose), `export-pngs`, `export-aseprite` |+| **D · post-processing** — finished sheets, refined | [recolor.md](recolor.md) | `recolor`, `recolor-palette`, `compose-layers`, breathing (compose, or `breathe` on a folder of frames), `export-pngs`, `export-aseprite` || **E · asset tools** — independent background, shadow and motion tools | [asset-tools.md](asset-tools.md) | `background-tile`, `shadow`, `inspect-motion` || **S · scene** — optional composition of existing assets | [scene.md](scene.md) | `scene-render`, `scene-inspect` |diff --git a/sprite_gen/_modules.py b/sprite_gen/_modules.pyindex faedf34..790cbeb 100644--- a/sprite_gen/_modules.py+++ b/sprite_gen/_modules.py@@ -112,8 +112,8 @@ PIPELINES: list[dict[str, object]] = [TOOL_GROUPS: list[dict[str, object]] = [{"key": "C", "name": "utilities", "verbs": ["cutout", "slice-sheet", "ui-kit", "unpack-atlas"],"chain": "cutout · slice-sheet · ui-kit · unpack-atlas (each stands alone)", "doc": "docs/sheet-slicing.md"},- {"key": "D", "name": "post-processing", "verbs": ["recolor", "recolor-palette", "compose-layers", "export-pngs", "export-aseprite"],- "chain": "recolor · compose-layers · export-pngs · export-aseprite", "doc": "docs/recolor.md"},+ {"key": "D", "name": "post-processing", "verbs": ["recolor", "recolor-palette", "compose-layers", "breathe", "export-pngs", "export-aseprite"],+ "chain": "recolor · compose-layers · breathe · export-pngs · export-aseprite", "doc": "docs/recolor.md"},{"key": "E", "name": "asset tools", "verbs": ["background-tile", "shadow", "inspect-motion"],"chain": "background-tile · shadow · inspect-motion (independent; no generation required)", "doc": "docs/asset-tools.md"},]diff --git a/sprite_gen/cli.py b/sprite_gen/cli.pyindex afa64dd..bed62f9 100644--- a/sprite_gen/cli.py+++ b/sprite_gen/cli.py@@ -31,7 +31,7 @@ from sprite_gen.video import compare as video_comparefrom sprite_gen.video import restoration as video_restorationfrom sprite_gen.video import source as video_sourcefrom sprite_gen.video import rife_install-from sprite_gen.effects import recolor, shadow+from sprite_gen.effects import breathe, recolor, shadowfrom sprite_gen.scene import render, inspect_scenefrom sprite_gen.serve import serve_compose, serve_curationfrom sprite_gen.spec import migrate_breathe, migrate_request@@ -438,6 +438,13 @@ COMMANDS: dict[str, tuple[str, Callable[[argparse.ArgumentParser], None], Callabrecolor.add_palette_arguments,recolor.run_palette,),+ # The Breathe layer for frames that are not a curation run (a video loop's cells): the sidecar's values, its+ # normalization and its bake, so the same values give the same bytes either way.+ "breathe": (+ "Lay the Breathe layer over a folder of loop frames: pixel (default) or smooth (large illustrations, video frames).",+ breathe.add_arguments,+ breathe.run,+ ),"inspect": ("Inspect sprite rows for frame-count, identity, and motion defects.", _add_inspect, inspect.run),"score": ("Score a sprite inspect report and emit correction hints.", _add_score, score.run),"correction-loop": (diff --git a/sprite_gen/curate/curation.py b/sprite_gen/curate/curation.pyindex 7427c52..0dca6cc 100644--- a/sprite_gen/curate/curation.py+++ b/sprite_gen/curate/curation.py@@ -220,6 +220,21 @@ def curation_path(run_dir: Path) -> Path:BREATHE_DEPTH_MAX = 0.20BREATHE_BREATHS_MAX = 8BREATHE_LAG_MAX = 0.45+# 굽기 방식. pixel(기본, `mode` 생략)은 정수 행·열 사상이라 도트 격자를 지키고, smooth 는+# 큰 일러·영상 프레임용 — 머리를 자리·바이트 그대로 두고 몸통만 쌍선형으로 들어 올린다+# (`sprite_gen.effects.breathe`). smooth 의 기본 진폭은 일러에 맞게 작다 — 어깨선이 목 아래+# 몸통 높이의 0.85 % 오른다 (흉상 일러에서 화면 높이 약 0.5 %, 화면 크기로 봐도 숨이 세지 않다).+BREATHE_MODES = ("pixel", "smooth")+BREATHE_SMOOTH_DEPTH = 0.0085+# smooth 의 가슴 부풂 — 가슴 가운데에서 이 비율만큼 넓어지고, 바깥으로 갈수록 무게만큼 준다.+BREATHE_SMOOTH_DEPTH_X = 0.028+# smooth 의 모양 (기본값과 허용 범위). chest_y: 가슴 가운데 높이 (목 아래 몸통 비율),+# chest_rx: 가슴 무게 가로 반지름 (몸통 반폭의 배), chest_ry: 세로 반지름 (목 아래 몸통 비율),+# shoulder: 어깨가 오르는 양 (가슴의 배), shoulder_lag: 어깨가 늦는 정도 (한 호흡 비율, 1/π 미만이라+# 시간이 되감기지 않는다).+BREATHE_SMOOTH_SHAPE = {"chest_y": 0.31, "chest_rx": 0.83, "chest_ry": 0.28, "shoulder": 0.5, "shoulder_lag": 0.08}+BREATHE_SMOOTH_SHAPE_RANGES = {"chest_y": (0.05, 0.95), "chest_rx": (0.2, 3.0), "chest_ry": (0.05, 1.5),+ "shoulder": (0.0, 1.5), "shoulder_lag": (0.0, 0.3)}RETIRED_BREATHE_KEYS = {"splits": "분할선은 봉투 경계로 대체됐다 — 경계는 자동 검출되고 `rigid_row` 로만 덮어쓴다",@@ -254,7 +269,13 @@ def state_breathe(curation: dict[str, Any] | None, state: str) -> dict[str, Any]반환: {"depth": float, "depth_x": float|None, "breaths": int, "lag": float,"rigid_row": int|None, "anatomy": dict|None}depth_x: 가로 독립 진폭 — None = depth 따름(레거시), 0 = 가로 항등.- compose/GIF 가 재생 시퀀스 위에 결정론으로 굽는다 — 디스크 프레임 불변."""+ compose/GIF 가 재생 시퀀스 위에 결정론으로 굽는다 — 디스크 프레임 불변.++ `mode` 를 적은 사이드카만 반환에 `mode` 가 실린다 — 안 적은 사이드카(지금까지의 전부)는+ 정규화 결과도 굽기도 이전과 바이트 같다. smooth 는 `lag` 가 없고(진행파는 첫 칸을 움직인다),+ `depth` 생략은 `BREATHE_SMOOTH_DEPTH`, `depth_x` 생략은 `BREATHE_SMOOTH_DEPTH_X` 이며, 모양 값+ (`BREATHE_SMOOTH_SHAPE` 의 키)이 기본값과 함께 실린다. 모양 값은 smooth 만 쓴다 — pixel 줄에+ 있으면 조용히 무시하지 않고 거부한다."""if not curation:return Noneentry = curation.get("states", {}).get(state)@@ -269,16 +290,27 @@ def state_breathe(curation: dict[str, Any] | None, state: str) -> dict[str, Any]f"{detail}\n"f" 마이그레이션: `sprite-gen migrate-breathe <run-dir> --apply` 또는 해당 키를 지우고 "f"`depth`(기본 0.06)·`breaths`·`lag`(기본 0.10) 로 다시 적어라. 조용히 변환하지 않는다.")+ mode = raw.get("mode")+ if mode is not None and (not isinstance(mode, str) or mode not in BREATHE_MODES):+ raise SystemExit(+ f"curation: states.{state}.breathe.mode = {mode!r} 를 모른다 — "+ f"{' | '.join(BREATHE_MODES)} 중 하나다 (생략하면 pixel). 조용히 pixel 로 굽지 않는다.")+ smooth = mode == "smooth"+ stray = sorted(k for k in BREATHE_SMOOTH_SHAPE if k in raw)+ if stray and not smooth:+ raise SystemExit(+ f"curation: states.{state}.breathe 의 {', '.join(stray)} 는 smooth 의 모양 값이다 — "+ f"pixel 은 쓰지 않는다. `mode: \"smooth\"` 를 적거나 그 키를 지워라. 조용히 무시하지 않는다.")# 형변환 계약(미러와 동일해야 한다): depth/lag 는 실수(숫자 문자열 허용),# breaths/rigid_row 는 **정수여야 한다**. 2.7 을 조용히 2 로 깎으면 프리뷰(반올림 3)와# 갈리고, "요청 그대로 적용된다" 는 문서도 거짓이 된다 (validator 실측 2026-07-25).try:- depth = float(raw.get("depth", 0.06))+ depth = float(raw.get("depth", BREATHE_SMOOTH_DEPTH if smooth else 0.06))# 가로 독립 진폭 (2026-07-30 가로/세로 분리): None = depth 따름(레거시 동일),# 0 = 가로 사상 항등. depth 와 달리 0 이 유효하다 — "가로만 끄기" 가 정당한 상태다.raw_dx = raw.get("depth_x")depth_x = None if raw_dx is None else float(raw_dx)- lag = float(raw.get("lag", 0.10))+ lag = float(raw.get("lag", 0.0 if smooth else 0.10))breaths = _exact_int("breaths", raw.get("breaths", 1), state)except (TypeError, ValueError) as exc:# 폐기 키는 요란하게 거부하면서 형식 오류만 조용히 호흡을 꺼버리면 계약이 어긋난다@@ -313,9 +345,34 @@ def state_breathe(curation: dict[str, Any] | None, state: str) -> dict[str, Any]if torso_half is not None:torso_half = _exact_int("torso_half", torso_half, state)frozen = raw.get("anatomy")- return {"depth": depth, "depth_x": depth_x, "breaths": breaths, "lag": lag,- "rigid_row": rigid_row, "axis_x": axis_x, "torso_half": torso_half,- "anatomy": frozen if isinstance(frozen, dict) else None}+ if smooth:+ # 진행파(lag)는 윗행의 위상을 늦춰 위상 0 인 칸도 움직인다 — smooth 의 첫 칸은 원본+ # 그대로여야 루프와 묶음의 이음이 안 바뀐다. 0 아닌 lag 를 조용히 버리지 않는다.+ if lag != 0.0:+ raise SystemExit(+ f"curation: states.{state}.breathe.lag = {raw.get('lag')!r} — smooth 에는 진행파가 없다. "+ f"위상 0 인 칸이 원본 그대로여야 루프·묶음 이음이 안 바뀐다. lag 를 지워라.")+ shape = {}+ for name, default in BREATHE_SMOOTH_SHAPE.items():+ given = raw.get(name, default)+ try:+ value = float(given)+ except (TypeError, ValueError):+ raise SystemExit(f"curation: states.{state}.breathe.{name} 를 숫자로 못 읽는다: {given!r}")+ lo, hi = BREATHE_SMOOTH_SHAPE_RANGES[name]+ if not lo <= value <= hi:+ raise SystemExit(+ f"curation: states.{state}.breathe.{name} = {given!r} 가 범위 [{lo}, {hi}] 밖이다. "+ f"조용히 깎지 않는다 — 사이드카를 고쳐라.")+ shape[name] = value+ return {"mode": mode, "depth": depth,+ "depth_x": BREATHE_SMOOTH_DEPTH_X if depth_x is None else depth_x,+ "breaths": breaths, **shape, "rigid_row": rigid_row, "axis_x": axis_x,+ "torso_half": torso_half, "anatomy": frozen if isinstance(frozen, dict) else None}+ cfg = {"depth": depth, "depth_x": depth_x, "breaths": breaths, "lag": lag,+ "rigid_row": rigid_row, "axis_x": axis_x, "torso_half": torso_half,+ "anatomy": frozen if isinstance(frozen, dict) else None}+ return cfg if mode is None else {"mode": mode, **cfg}def edit_index(curation: dict[str, Any] | None, state: str, index: int) -> int:diff --git a/sprite_gen/effects/anatomy.py b/sprite_gen/effects/anatomy.pyindex 88f352a..e5d0b9a 100644--- a/sprite_gen/effects/anatomy.py+++ b/sprite_gen/effects/anatomy.py@@ -57,6 +57,14 @@ class Anatomy:torso_source: str = "auto" # "auto" | "manual" — 보호 램프 앵커가 갈린다 (breathe.protect)face: tuple[int, int] | None = Nonewarnings: tuple[str, ...] = field(default=())+ # 잰 프레임의 콘텐츠 bbox 왼쪽 위 (캔버스 좌표). 사이드카·manifest 에는 싣지 않는다+ # (`as_dict` 밖) — 굽기가 기준 프레임에서 매번 다시 재므로 캐시할 값이 아니다. smooth 는+ # 줄 전체를 이 자리에 놓는다: 칸마다 머리 윗선이 흔들려도 경계는 기준 칸의 자리다.+ origin: tuple[int, int] | None = field(default=None, compare=False)+ # 강체 경계 행에서 몸통 축을 지나는 불투명 구간 (콘텐츠 bbox 기준 열, 양 끝 포함) — 목의+ # 가로 자리. `origin` 처럼 사이드카에 싣지 않는다. smooth 가 목 너비만 붙잡고 그 옆 어깨는+ # 놓아 주는 데 쓴다 (목이 몸통 축에서 비켜 있는 그림도 있다 — 긴 머리가 무게중심을 끈다).+ neck_span: tuple[int, int] | None = field(default=None, compare=False)@propertydef has_appendage(self) -> bool:@@ -100,6 +108,31 @@ def axis_x(image: Image.Image, box: tuple[int, int, int, int]) -> int:_axis_centroid = axis_x+def center_run(px, box: tuple[int, int, int, int], cx: int, y: int) -> tuple[int, int] | None:+ """캔버스 행 `y` 에서 몸통 축을 지나는(축이 비었으면 축에 가장 가까운) 불투명 연속 구간 —+ box 상대 열 (lo, hi), 양 끝 포함. 그 행이 비었으면 None."""+ x0, _y0, x1, _y1 = box+ width = x1 - x0+ seed = None+ if px[x0 + cx, y][3] >= ALPHA_SOLID:+ seed = cx+ else:+ best = None+ for i in range(width):+ if px[x0 + i, y][3] >= ALPHA_SOLID and (best is None or abs(i - cx) < abs(best - cx)):+ best = i+ seed = best+ if seed is None:+ return None+ lo = seed+ while lo > 0 and px[x0 + lo - 1, y][3] >= ALPHA_SOLID:+ lo -= 1+ hi = seed+ while hi < width - 1 and px[x0 + hi + 1, y][3] >= ALPHA_SOLID:+ hi += 1+ return lo, hi++def width_profile(image: Image.Image, box: tuple[int, int, int, int], cx: int) -> list[int]:"""행별 '몸통 중심 런' 폭.@@ -107,29 +140,10 @@ def width_profile(image: Image.Image, box: tuple[int, int, int, int], cx: int) -몸통 축을 지나는 **연속 런**만 재면 떨어져 있는 부속이 배제된다 — 실루엣의국소 두께를 세로축으로 샘플링한 것과 같다."""px = image.load()- x0, y0, x1, y1 = box- width = x1 - x0out: list[int] = []- for y in range(y0, y1):- seed = None- if px[x0 + cx, y][3] >= ALPHA_SOLID:- seed = cx- else:- best = None- for i in range(width):- if px[x0 + i, y][3] >= ALPHA_SOLID and (best is None or abs(i - cx) < abs(best - cx)):- best = i- seed = best- if seed is None:- out.append(0)- continue- lo = seed- while lo > 0 and px[x0 + lo - 1, y][3] >= ALPHA_SOLID:- lo -= 1- hi = seed- while hi < width - 1 and px[x0 + hi + 1, y][3] >= ALPHA_SOLID:- hi += 1- out.append(hi - lo + 1)+ for y in range(box[1], box[3]):+ run = center_run(px, box, cx, y)+ out.append(0 if run is None else run[1] - run[0] + 1)return out@@ -321,4 +335,5 @@ def analyze(image: Image.Image, rigid_row: int | None = None,return Anatomy(width=w, height=h, axis_x=cx, neck_row=neck_row, neck_source=neck_source,rigid_row=auto_rigid, rigid_source=rigid_source, basis_row=basis_row,torso_half=torso, max_half=max_half, torso_source=torso_source, face=face,- warnings=tuple(warnings))+ warnings=tuple(warnings), origin=(x0, y0),+ neck_span=center_run(image.load(), box, cx, y0 + min(h - 1, auto_rigid)))diff --git a/sprite_gen/effects/breathe.py b/sprite_gen/effects/breathe.pyindex 8c934b0..fa22841 100644--- a/sprite_gen/effects/breathe.py+++ b/sprite_gen/effects/breathe.py@@ -42,16 +42,39 @@ AI 개입 0 — 같은 입력이면 항상 같은 출력.(구 테이크 방식 — exhale 프레임을 raw 테이크로 굽고 전체 재추출 — 은 v1.56.31 에서폐기: 깜빡임×호흡 조합 불가 + 적용마다 수 분 + 팔레트 드리프트. 봉투 방식은 그 셋 중무엇도 해소하지 않으므로 되돌릴 근거가 없다.)++## smooth 모드 (큰 일러·영상 프레임)++위 불변식은 도트 그림의 것이다. 큰 일러에서는 같은 워프가 머리를 통째로 오르내리게 하고+(발이 고정이라 몸통이 늘면 그 위가 다 뜬다), 정수 행 복제가 칸마다 떨림으로 읽힌다. 가로줄을+통째로 올리는 것도 숨이 아니다 — 어깨와 가슴이 같이 올라 위아래로만 움직이는 것처럼 보인다.+`mode: "smooth"` 는 같은 해부를 쓰되 2차원 변위장 하나를 굽는다:++ 가슴: 몸통 축 위 가슴 가운데의 타원 cos² 무게로 depth x 기준 높이만큼 오르고 depth_x 만큼 부푼다+ 어깨: 어깨선 좌우가 가슴 오름의 shoulder 배만큼, shoulder_lag 만큼 늦게 오른다+ 목 밴드(강체 경계 ~ 어깨선)에서 켜지고 콘텐츠 맨 아래에서 꺼진다++정사상(원본 점의 내용이 가는 자리)의 역을 고정점 반복으로 풀어 쌍선형으로 뜬다(곱한 알파).+강체 경계 위(목·턱 위)와 무게 밖은 원본 바이트 그대로다. 한 호흡은 0 에서 시작해 들숨(INHALE)에+1, 날숨에 0 으로 돌아오는 한쪽 혹이고 어깨의 늦음도 양 끝에서 0 이라, 위상 0 인 칸은 원본과+바이트 같다. 가슴 무게가 몸통 안에서 0 으로 떨어져 화면 변에 닿은 그림도 밖으로 밀리지 않는다.+줄 전체가 기준 칸(첫 칸)에서 잰 해부와 그 자리를 쓴다 — 영상 루프의 머리 윗선이 칸마다 흔들려도+경계는 움직이지 않는다."""from __future__ import annotations+import argparse+import jsonimport math+from pathlib import Path+import numpy as npfrom PIL import Imagefrom sprite_gen.effects.anatomy import Anatomy, analyze-from sprite_gen.curate.curation import normalize_transform+from sprite_gen.curate.curation import (BREATHE_MODES, BREATHE_SMOOTH_DEPTH, BREATHE_SMOOTH_DEPTH_X,+ BREATHE_SMOOTH_SHAPE, normalize_transform, state_breathe)from sprite_gen.frames.extract import solid_alpha_bbox# 강체 경계에서 변형 강도가 0 이 되기까지의 테이퍼 반폭 (콘텐츠 높이 비율).@@ -67,6 +90,14 @@ DEFAULT_DEPTH = 0.06DEFAULT_LAG = 0.10# 한 호흡이 부드럽게 읽히려면 필요한 최소 프레임 수 (프레임을 찍어낼 때의 권고치).SMOOTH_CYCLE_FRAMES = 6+# smooth 모드 — 들숨이 한 호흡에서 차지하는 비율 (들숨이 날숨보다 짧다).+INHALE = 0.40+DEFAULT_SMOOTH_DEPTH = BREATHE_SMOOTH_DEPTH+DEFAULT_SMOOTH_DEPTH_X = BREATHE_SMOOTH_DEPTH_X+SMOOTH_SHAPE = dict(BREATHE_SMOOTH_SHAPE)+# smooth 의 어깨 혹 — 몸통 축에서 좌우로 몸통 반폭의 이 배 자리, 가로 반지름도 몸통 반폭 비율.+SHOULDER_X = 0.55+SHOULDER_RX = 0.45# ── 파형 ────────────────────────────────────────────────────────────@@ -377,6 +408,219 @@ def _warp(frame: Image.Image, anat: Anatomy, depth: float, lag: float, t: float,return out+# ── smooth 모드 (큰 일러·영상 프레임) ───────────────────────────────++def breathe_mode(cfg: dict) -> str:+ """cfg 의 굽기 방식 — 생략은 pixel. 모르는 값을 조용히 pixel 로 굽지 않는다."""+ mode = cfg.get("mode")+ if mode is None:+ return "pixel"+ if not isinstance(mode, str) or mode not in BREATHE_MODES:+ raise SystemExit(f"breathe: mode {mode!r} 를 모른다 — {' | '.join(BREATHE_MODES)} 중 하나다.")+ return mode+++def smooth_wave(t: float) -> float:+ """smooth 의 한 호흡 — 위상 0 에서 0, 들숨 끝(INHALE)에 1, 날숨 끝에 다시 0.++ pixel 의 `wave` 는 위아래로 흔드는 사인이고 진행파 지연까지 있어 위상 0 에서도 윗행이+ 움직인다. 여기는 쉼(0)에서 올랐다 돌아오기만 하는 한쪽 혹이고, 양 끝과 정점에서 기울기가+ 0 이라 루프 이음에서 꺾이지 않는다."""+ t = t % 1.0+ g = 0.5 * t / INHALE if t < INHALE else 0.5 + 0.5 * (t - INHALE) / (1.0 - INHALE)+ return 0.5 - 0.5 * math.cos(2.0 * math.pi * g)+++def smooth_shoulder_wave(t: float, lag: float) -> float:+ """어깨의 호흡 — 가슴보다 `lag` 만큼 늦게 정점에 닿되 위상 0 과 1 에서는 가슴과 같이 0.++ `wave(t - lag)` 로 늦추면 위상 0 에서 어깨가 아직 날숨 끝에 걸려 있어 첫 칸이 원본이 아니게+ 된다. 시간을 `t - lag·sin(πt)` 로 휘면 양 끝은 그대로 두고 가운데만 늦출 수 있다 (lag < 1/π+ 이면 단조라 되감기지 않는다)."""+ t = t % 1.0+ return smooth_wave(t - lag * math.sin(math.pi * t))+++def smooth_band(anat: Anatomy) -> tuple[float, float]:+ """(강체 경계, 목 밴드 끝) — 콘텐츠 bbox 기준 행. 그 사이가 목 밴드다: 경계에서 0 이던 움직임이+ 여기서 켜진다(목 너비 안은 밴드 끝까지 천천히). 폭은 pixel 테이퍼의 전폭(경계 위아래 각 TAPER)이고+ 전부 경계 **아래**에 둔다 — 경계 위(목·턱 위)는 한 픽셀도 움직이지 않아야 한다."""+ top = float(anat.rigid_row)+ return top, top + 2.0 * max(1.5, TAPER * anat.height)+++def smooth_shoulder_row(anat: Anatomy) -> float:+ """어깨선 (콘텐츠 bbox 기준 행) — 어깨 혹의 가운데, 목 밴드의 위 4할."""+ top, end = smooth_band(anat)+ return top + 0.4 * (end - top)+++def _neck(anat: Anatomy) -> tuple[float, float]:+ """(목 가운데 열, 목 반폭) — 해부가 강체 경계 행에서 잰 구간. 손으로 만든 해부처럼 구간이+ 없으면 몸통 축에 몸통 반폭의 1/4 로 둔다."""+ if anat.neck_span is not None:+ lo, hi = anat.neck_span+ return 0.5 * (lo + hi + 1), max(1.0, 0.5 * (hi - lo + 1))+ return anat.axis_x + 0.5, max(1.0, 0.25 * anat.torso_half)+++def _shape(cfg: dict) -> dict:+ return {k: (SMOOTH_SHAPE[k] if cfg.get(k) is None else float(cfg[k])) for k in SMOOTH_SHAPE}+++def smooth_chest(anat: Anatomy, cfg: dict) -> tuple[float, float]:+ """가슴 가운데 (콘텐츠 bbox 기준 x, y) — 몸통 축 위, 목 아래 몸통의 `chest_y` 비율 높이."""+ top = float(anat.rigid_row)+ return anat.axis_x + 0.5, top + _shape(cfg)["chest_y"] * (anat.height - top)+++def _smoothstep_array(a: float, b: float, x: np.ndarray) -> np.ndarray:+ if b <= a:+ return (x >= b).astype(np.float64)+ u = np.clip((x - a) / (b - a), 0.0, 1.0)+ return u * u * (3.0 - 2.0 * u)+++def smooth_displacement(anat: Anatomy, cfg: dict, x: np.ndarray, y: np.ndarray,+ chest: float, shoulders: float) -> tuple[np.ndarray, np.ndarray]:+ """콘텐츠 bbox 기준 점 (x, y) 의 내용이 가는 변위 (dx, dy) — 정사상, 위로 오르면 dy < 0.++ 가슴: 가운데에 놓인 타원(가로 chest_rx × 몸통 반폭, 세로 chest_ry × 목 아래 몸통)의 cos² 무게로+ `depth × 기준 높이` 만큼 오르고, 그 안이 가운데에서 바깥으로 `depth_x` 만큼 부푼다.+ 어깨: 목 밴드 높이, 몸통 축에서 좌우로 몸통 반폭의 SHOULDER_X 배 자리에 놓인 둥근 혹 둘이+ 가슴 오름의 `shoulder` 배만큼 오른다 — 가슴 무게가 이미 덮은 자리는 그만큼 덜 (가운데가 두 번+ 오르지 않게). 목과 어깨 사이(옷깃)는 어느 혹에도 안 들어 그대로다.+ 고정: 강체 경계 위는 0. 목 너비 안은 목 밴드 전체에 걸쳐 천천히 켜지고(목은 거의 그대로), 그+ 밖은 밴드의 0.15 만에(눌림이 행당 상한을 넘지 않는 한) 켜진다 — 목 옆에 높이 붙은 어깨도 숨을+ 쉰다. 콘텐츠 맨 아래에서 다시 0 이다 (발바닥 고정)."""+ shape = _shape(cfg)+ top, band_end = smooth_band(anat)+ band = band_end - top+ height = float(anat.height)+ torso = float(anat.torso_half)+ cx, cy = smooth_chest(anat, cfg)+ neck_x, neck_half = _neck(anat)+ rx = shape["chest_rx"] * torso+ ry = shape["chest_ry"] * (height - top)+ r = np.sqrt(((x - cx) / rx) ** 2 + ((y - cy) / ry) ** 2)+ w_chest = np.where(r < 1.0, np.cos(0.5 * np.pi * np.minimum(r, 1.0)) ** 2, 0.0)+ neckness = 1.0 - _smoothstep_array(neck_half, 1.5 * neck_half, np.abs(x - neck_x))+ across = np.minimum(1.0, np.abs(np.abs(x - cx) - SHOULDER_X * torso) / (SHOULDER_RX * torso))+ down = np.minimum(1.0, np.abs(y - smooth_shoulder_row(anat)) / (1.4 * band)) # 양 어깨 높이가 달라도+ w_shoulder = np.cos(0.5 * np.pi * down) ** 2 * np.cos(0.5 * np.pi * across) ** 2+ lift = float(cfg.get("depth") if cfg.get("depth") is not None else DEFAULT_SMOOTH_DEPTH) * anat.basis_rows+ swell = float(cfg.get("depth_x") if cfg.get("depth_x") is not None else DEFAULT_SMOOTH_DEPTH_X)+ # 어깨가 켜지는 구간은 오르는 양의 8배 이상 — 더 짧으면 그 사이가 행당 상한 넘게 눌린다.+ quick = max(0.15 * band, 8.0 * shape["shoulder"] * lift)+ u = np.clip((y - top) / (quick + (band - quick) * neckness), 0.0, 1.0) if band > quick else \+ np.clip((y - top) / quick, 0.0, 1.0)+ guard = u * u * (3.0 - 2.0 * u) * (1.0 - _smoothstep_array(height - 0.5 * band, height, y))+ rise = lift * (chest * w_chest + shape["shoulder"] * shoulders * w_shoulder * (1.0 - w_chest))+ puff = swell * chest * w_chest+ return puff * (x - cx) * guard, (puff * (y - cy) - rise) * guard+++def smooth_strain(anat: Anatomy, cfg: dict) -> tuple[float, float]:+ """(행당 최대 변형, 최소 면적비) — 가슴과 어깨가 함께 정점일 때의 변위장 기울기에서.++ 행당 변형은 늘고 주는 성분(∂dx/∂x, ∂dy/∂y)의 최대다 — pixel 의 행당 변형과 같은 뜻. 목 옆에서+ 어깨가 오르며 생기는 비틀림(옆 칸끼리 오르는 양의 차)은 늘고 줄지 않으니 여기 세지 않고,+ 대신 사상이 접히지 않는지를 면적비 det(I + ∇D) 로 본다."""+ ys = np.arange(anat.height, dtype=np.float64) + 0.5+ xs = np.arange(anat.width, dtype=np.float64) + 0.5+ if ys.size < 2 or xs.size < 2:+ return 0.0, 1.0+ gx, gy = np.meshgrid(xs, ys)+ dx, dy = smooth_displacement(anat, cfg, gx, gy, 1.0, 1.0)+ dxy, dxx = np.gradient(dx)+ dyy, dyx = np.gradient(dy)+ stretch = float(max(np.abs(dxx).max(), np.abs(dyy).max()))+ area = float(((1.0 + dxx) * (1.0 + dyy) - dxy * dyx).min())+ return stretch, area+++def _smooth_warp(frame: Image.Image, anat: Anatomy, cfg: dict, t: float) -> Image.Image:+ """smooth 의 한 위상 — 캔버스 크기 불변, 강체 경계 위와 발바닥 고정.++ 정사상(원본 점 p 의 내용이 p + D(p) 로 간다)의 역을 고정점 반복(q = o - D(q))으로 풀고, 그+ 자리를 곱한 알파에서 쌍선형으로 뜬다. 변위가 행당 상한(MAX_ROW_STRAIN) 아래라 반복은+ 수축이다. 움직이지 않는 픽셀(경계 위, 무게 밖)은 원본 바이트를 그대로 둔다 — 곱하고 나누는+ 왕복조차 거치지 않는다."""+ rgba = frame.convert("RGBA")+ chest = smooth_wave(t)+ shoulders = smooth_shoulder_wave(t, _shape(cfg)["shoulder_lag"])+ box = solid_alpha_bbox(rgba)+ if not box or (chest == 0.0 and shoulders == 0.0):+ return rgba # 위상 0 — 원본 그대로 (바이트)+ if anat.origin is not None:+ # 줄의 기준 칸에서 잰 자리 — 해부가 한 벌이듯 경계·축·발바닥의 자리도 한 벌이다.+ # 영상 루프는 머리 윗선이 칸마다 흔들려, 칸마다 다시 놓으면 경계 위 행이 움직인다.+ box = (anat.origin[0], anat.origin[1],+ anat.origin[0] + anat.width, anat.origin[1] + anat.height)+ src = np.asarray(rgba)+ canvas_h, canvas_w = src.shape[:2]+ # 움직일 수 있는 행: 강체 경계 아래 ~ 콘텐츠 맨 아래 (그 밖은 변위가 0 이다).+ y_lo = max(0, int(math.floor(box[1] + anat.rigid_row)))+ y_hi = min(canvas_h, box[1] + anat.height)+ if y_hi <= y_lo:+ return rgba+ oy, ox = np.mgrid[y_lo:y_hi, 0:canvas_w].astype(np.float64)+ oy += 0.5 - box[1] # 콘텐츠 bbox 기준 픽셀 중심+ ox += 0.5 - box[0]++ def field(x, y):+ return smooth_displacement(anat, cfg, x, y, chest, shoulders)++ # 밀려 나가는 내용 — 원본 픽셀 중심이 가는 자리가 캔버스 밖이면 조용히 자르지 않는다.+ fx, fy = field(ox, oy)+ land_x, land_y = ox + fx + box[0], oy + fy + box[1]+ gone = (land_x < 0.0) | (land_x >= canvas_w) | (land_y < 0.0) | (land_y >= canvas_h)+ clipped = int(np.count_nonzero(src[y_lo:y_hi, :, 3][gone]))+ if clipped:+ raise SystemExit(+ f"breathe(smooth): 가슴 부풂이 불투명 픽셀 {clipped}개를 셀 밖으로 민다 "+ f"(셀 {canvas_w}x{canvas_h}, 콘텐츠 {box[0]},{box[1]}-{box[2]},{box[3]}). "+ f"chest_rx 나 depth_x 를 줄여라 — 기본 모양은 가슴 무게가 몸통 안에서 0 이 된다.")+ qx, qy = ox.copy(), oy.copy()+ for _ in range(8):+ dx, dy = field(qx, qy)+ qx, qy = ox - dx, oy - dy+ moved = (qx != ox) | (qy != oy)+ if not moved.any():+ return rgba+ pm = src.astype(np.float64) / 255.0+ pm[..., :3] *= pm[..., 3:4]+ sx = qx[moved] + box[0] - 0.5 # 캔버스 인덱스 좌표+ sy = qy[moved] + box[1] - 0.5+ x0, y0 = np.floor(sx).astype(np.int64), np.floor(sy).astype(np.int64)+ ax, ay = (sx - x0)[:, None], (sy - y0)[:, None]+ x0c, x1c = np.clip(x0, 0, canvas_w - 1), np.clip(x0 + 1, 0, canvas_w - 1)+ y0c, y1c = np.clip(y0, 0, canvas_h - 1), np.clip(y0 + 1, 0, canvas_h - 1)+ val = ((pm[y0c, x0c] * (1.0 - ax) + pm[y0c, x1c] * ax) * (1.0 - ay)+ + (pm[y1c, x0c] * (1.0 - ax) + pm[y1c, x1c] * ax) * ay)+ alpha = val[:, 3:4]+ rgb = np.where(alpha > 0.0, val[:, :3] / np.maximum(alpha, 1e-12), 0.0)+ out = src.copy()+ region = out[y_lo:y_hi]+ region[moved] = np.clip(np.floor(np.concatenate([rgb, alpha], axis=1) * 255.0 + 0.5), 0, 255).astype(np.uint8)+ return Image.fromarray(out, "RGBA")+++def _smooth_phase_frame(frame: Image.Image, cfg: dict, phase: float, anat: Anatomy) -> Image.Image:+ lag = cfg.get("lag")+ if lag is not None and float(lag) != 0.0:+ # 진행파는 윗행 위상을 늦춰 위상 0 인 칸도 움직인다 — 조용히 버리지 않는다.+ raise SystemExit(f"breathe(smooth): lag {lag} — smooth 에는 진행파가 없다. 위상 0 인 칸이 원본 "+ f"그대로여야 루프·묶음 이음이 안 바뀐다. lag 를 지워라 (어깨가 늦는 건 shoulder_lag).")+ strain, area = smooth_strain(anat, cfg)+ if strain > MAX_ROW_STRAIN or area < 1.0 - MAX_ROW_STRAIN:+ raise SystemExit(+ f"breathe(smooth): 행당 변형 {strain:.3f}·최소 면적비 {area:.3f} — 상한 {MAX_ROW_STRAIN} 을 넘는다. "+ f"가슴·어깨가 오르는 만큼을 목 밴드와 가슴 무게가 못 받는다 (강체 경계 {anat.rigid_row}/{anat.height}, "+ f"기준 {anat.basis_rows}행). depth·depth_x 를 낮추거나 chest_rx·chest_ry 를 넓혀라. 조용히 깎지 않는다.")+ return _smooth_warp(frame, anat, cfg, phase)++# ── 해부 결과 얼리기 / 자가 복구 ────────────────────────────────────def _fnv1a(data: bytes) -> int:@@ -583,9 +827,12 @@ def phase_frame(frame: Image.Image, cfg: dict, phase: float,"""프레임에 호흡 위상 하나(0 <= phase < 1)를 적용.`anat` 를 주면 그것을 쓴다 — 줄 전체가 한 벌을 공유해야 하므로 호출자가 한 번- 확정해 넘기는 게 정석이다. 생략하면 이 프레임을 기준으로 확정한다 (단발 호출용)."""+ 확정해 넘기는 게 정석이다. 생략하면 이 프레임을 기준으로 확정한다 (단발 호출용).+ `cfg["mode"]` 가 smooth 면 smooth 로 굽는다 — GIF·아틀라스·레이어·CLI 가 모두 여기를 탄다."""if anat is None:anat = resolve_anatomy(frame, cfg)+ if breathe_mode(cfg) == "smooth":+ return _smooth_phase_frame(frame, cfg, phase, anat)depth = float(cfg.get("depth", DEFAULT_DEPTH))raw_dx = cfg.get("depth_x")depth_x = None if raw_dx is None else float(raw_dx)@@ -611,3 +858,85 @@ def bake_breathe_sequence(images: list[Image.Image], cfg: dict) -> tuple[list[Imphases = fit_breathe_pattern(len(images), cfg)anat = resolve_anatomy(images[0], cfg) # 줄 전체가 한 벌을 공유한다return [phase_frame(images[i], cfg, phases[i], anat) for i in range(len(images))], phases+++# ── CLI: 프레임 폴더에 굽기 (`sprite-gen breathe`) ─────────────────++def add_arguments(parser: argparse.ArgumentParser) -> None:+ parser.add_argument("frames", help="folder of the loop's frames (*.png, played in name order)")+ parser.add_argument("out", help="new folder for the breathing frames (same names) and breathe.json")+ parser.add_argument("--mode", choices=BREATHE_MODES, default=None,+ help="pixel (default): integer rows and columns, for pixel art; smooth: the head stays "+ "in place, the body rises smoothly, for large illustrations and video frames")+ parser.add_argument("--depth", type=float, default=None,+ help="how far the body rises, as a share of its height below the neck "+ f"(default {DEFAULT_DEPTH} pixel, {DEFAULT_SMOOTH_DEPTH} smooth)")+ parser.add_argument("--depth-x", type=float, default=None,+ help=f"sideways swell (pixel: follows --depth; smooth: the chest puffs out by this share, "+ f"default {DEFAULT_SMOOTH_DEPTH_X})")+ parser.add_argument("--breaths", type=int, default=None, help="breaths per loop (default 1)")+ parser.add_argument("--lag", type=float, default=None, help=f"pixel only: travelling-wave lag (default {DEFAULT_LAG})")+ parser.add_argument("--rigid-row", type=int, default=None,+ help="the row the head starts below, counted from the top of the figure (default: measured)")+ shape = parser.add_argument_group("smooth shape (defaults in parentheses)")+ shape.add_argument("--chest-y", type=float, default=None,+ help=f"chest centre height, a share of the body below the neck ({SMOOTH_SHAPE['chest_y']})")+ shape.add_argument("--chest-rx", type=float, default=None,+ help=f"chest weight's half width, times the torso half width ({SMOOTH_SHAPE['chest_rx']})")+ shape.add_argument("--chest-ry", type=float, default=None,+ help=f"chest weight's half height, a share of the body below the neck ({SMOOTH_SHAPE['chest_ry']})")+ shape.add_argument("--shoulder", type=float, default=None,+ help=f"how far the shoulders rise, times the chest's ({SMOOTH_SHAPE['shoulder']})")+ shape.add_argument("--shoulder-lag", type=float, default=None,+ help=f"how late the shoulders peak, a share of one breath ({SMOOTH_SHAPE['shoulder_lag']})")+++def run(*, frames: str, out: str, mode: str | None = None, depth: float | None = None,+ depth_x: float | None = None, breaths: int | None = None, lag: float | None = None,+ rigid_row: int | None = None, chest_y: float | None = None, chest_rx: float | None = None,+ chest_ry: float | None = None, shoulder: float | None = None, shoulder_lag: float | None = None) -> int:+ """프레임 폴더에 Breathe 레이어를 굽는다 — 큐레이션 사이드카 `breathe` 와 같은 값, 같은 정규화,+ 같은 굽기(`bake_breathe_sequence`). 영상 루프의 칸처럼 큐레이션 런이 아닌 프레임이 이 길로 온다."""+ src_dir, out_dir = Path(frames), Path(out)+ raw = {k: v for k, v in (("mode", mode), ("depth", depth), ("depth_x", depth_x), ("breaths", breaths),+ ("lag", lag), ("rigid_row", rigid_row), ("chest_y", chest_y), ("chest_rx", chest_rx),+ ("chest_ry", chest_ry), ("shoulder", shoulder), ("shoulder_lag", shoulder_lag))+ if v is not None}+ try:+ cfg = state_breathe({"states": {"frames": {"breathe": raw}}}, "frames")+ except SystemExit as exc:+ raise SystemExit(f"breathe: 사이드카와 같은 검사에서 거부됐다 — {exc}")+ paths = sorted(src_dir.glob("*.png"))+ if not paths:+ raise SystemExit(f"breathe: {src_dir} 에 PNG 프레임이 없다")+ if out_dir.resolve() == src_dir.resolve():+ raise SystemExit("breathe: out 이 frames 와 같은 폴더다 — 원본 프레임 위에 덮어쓰지 않는다")+ if out_dir.exists() and any(out_dir.iterdir()):+ raise SystemExit(f"breathe: {out_dir} 가 비어 있지 않다 — 새 폴더를 주라")+ images = []+ for path in paths:+ with Image.open(path) as opened:+ images.append(opened.convert("RGBA"))+ if len({im.size for im in images}) != 1:+ raise SystemExit(f"breathe: 프레임 크기가 서로 다르다 — {sorted({im.size for im in images})}")+ resolved = anatomy_report(images, cfg)+ baked, phases = bake_breathe_sequence(images, cfg)+ # 다 굽고 나서 한 번에 내놓는다 — 굽기가 중간에 거부되면 반쯤 찬 폴더를 남기지 않는다.+ staging = out_dir.parent / f".{out_dir.name}.partial"+ if staging.exists():+ for stale in staging.iterdir():+ stale.unlink()+ staging.rmdir()+ staging.mkdir(parents=True)+ for path, frame in zip(paths, baked):+ frame.save(staging / path.name)+ report = {"frames": len(paths), "source": str(src_dir), "config": cfg, "phases": phases,+ "resolved": resolved}+ (staging / "breathe.json").write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n",+ encoding="utf-8")+ if out_dir.exists():+ out_dir.rmdir()+ staging.rename(out_dir)+ print(f"breathe: {len(paths)} frames, {breathe_mode(cfg)}, depth {cfg['depth']}, "+ f"breaths {cfg['breaths']} -> {out_dir}")+ return 0diff --git a/sprite_gen/serve/curator/src/breathe.js b/sprite_gen/serve/curator/src/breathe.jsindex b8a55f4..07e9113 100644--- a/sprite_gen/serve/curator/src/breathe.js+++ b/sprite_gen/serve/curator/src/breathe.js@@ -4,6 +4,7 @@//// 호흡은 프레임 선택(깜빡임)과 직교하는 변조 레이어다 (maintainer 확정 2026-07-18).// truth = entries[state].breathe = {depth, breaths, lag, rigid_row, anatomy} | null.+// `mode: "smooth"` 줄은 미러하지 않는다 — breatheComposite 가 거부한다 (아래).//// **검출은 여기서 하지 않는다** (maintainer 결정 2026-07-25 b안). 목 병목·대칭 눈쌍·부속// 판정은 서버(`sprite_gen/anatomy.py`)가 GET /api/breathe-anatomy 로 한 번 돌려@@ -239,6 +240,13 @@ function breatheComposite(base, cfg, phase) {out.height = h;const ctx = out.getContext("2d");ctx.imageSmoothingEnabled = false;+ // smooth 줄은 미러가 없다 — 쌍선형 사잇값은 브라우저와 파이썬의 부동소수가 같은 바이트를+ // 낸다고 보장할 수 없다. pixel 워프로 그리면 굽기와 다른 숨을 보여 주므로 거부한다+ // (미리보기는 원본과 알림, 영상 내보내기는 중단). 결과는 compose 나 `sprite-gen breathe` 로 본다.+ if (cfg && cfg.mode === "smooth") {+ throw new BreatheRefused(+ "smooth 줄은 큐레이터가 따라 그리지 않는다 — 결과는 compose(GIF·아틀라스)나 `sprite-gen breathe` 로 본다.");+ }const anat = cfg && cfg.anatomy;// `rigid_row` 는 사람의 의도(입력)이고 `anatomy` 는 거기서 파생된 캐시다. 굽기는 둘이// 어긋나면 재검출해 의도를 따르는데(`resolve_anatomy` 의 stale_override), 미러는 검출을diff --git a/sprite_gen/serve/curator/src/store.js b/sprite_gen/serve/curator/src/store.jsindex f5e6ac5..98a660c 100644--- a/sprite_gen/serve/curator/src/store.js+++ b/sprite_gen/serve/curator/src/store.js@@ -11,9 +11,27 @@ function isNumericScalar(v) {return typeof v === "string" && /^\s*[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?\s*$/.test(v);}+// 굽기 방식 — 파이썬 curation.BREATHE_MODES 미러. 생략 = pixel.+const BREATHE_MODES = ["pixel", "smooth"];+// smooth 모양 값의 허용 범위 — 파이썬 curation.BREATHE_SMOOTH_SHAPE_RANGES 미러.+const BREATHE_SMOOTH_SHAPE_RANGES = { chest_y: [0.05, 0.95], chest_rx: [0.2, 3.0], chest_ry: [0.05, 1.5], shoulder: [0.0, 1.5], shoulder_lag: [0.0, 0.3] };+function breatheRangeProblems(raw) {const bounds = [["depth", 0.005, 0.20, 0.06], ["breaths", 1, 8, 1], ["lag", 0, 0.45, 0.1]];const bad = [];+ // 모르는 mode 는 굽기가 거부한다 — 여기서도 원본을 지키고 알린다 (pixel 로 읽어 되쓰지 않는다).+ if (raw.mode != null && !BREATHE_MODES.includes(raw.mode)) bad.push(`mode=${JSON.stringify(raw.mode)}`);+ // smooth 에는 진행파가 없다 — 0 아닌 lag 는 굽기가 거부한다 (파이썬 state_breathe 미러).+ if (raw.mode === "smooth" && raw.lag != null && Number(raw.lag) !== 0) {+ bad.push(`lag=${JSON.stringify(raw.lag)} (smooth 에는 lag 가 없다)`);+ }+ // 모양 값은 smooth 만 쓴다 — pixel 줄에 있으면 굽기가 거부하고, smooth 줄은 범위를 본다.+ for (const [key, [lo, hi]] of Object.entries(BREATHE_SMOOTH_SHAPE_RANGES)) {+ if (raw[key] === undefined) continue;+ if (raw.mode !== "smooth") { bad.push(`${key} (smooth 만 쓰는 모양 값)`); continue; }+ const v = isNumericScalar(raw[key]) ? Number(raw[key]) : NaN;+ if (!Number.isFinite(v) || v < lo || v > hi) bad.push(`${key}=${JSON.stringify(raw[key])}`);+ }for (const [key, lo, hi, dflt] of bounds) {// 생략(undefined)은 기본값. 명시적 null 은 굽기가 `float(None)` 으로 거부하므로// **키와 무관하게** 여기서도 문제로 본다 — `Number(null) = 0` 이라 하한이 0 인 `lag`@@ -610,15 +628,21 @@ function seedEntries() {// 켜짐/꺼짐이 반대가 되고 첫 autosave 가 설정을 지운다 (validator note 2026-07-26).// 명시적 `null` 은 키와 무관하게 위 범위 검사에 걸려 여기 안 온다.breathe: rawBreathe && !retired.length && !outOfRange.length+ // smooth 줄은 적힌 그대로 들고 있다. 미러가 없어 미리보기도 편집 결과도 굽기와 맞출 수+ // 없고, 아래 pixel 정규화를 태우면 첫 autosave 가 pixel 기본값(depth 0.06, lag 0.1)을+ // 채워 넣어 smooth 줄의 진폭을 바꾸고 굽기가 lag 로 거부하게 된다.+ ? rawBreathe.mode === "smooth" ? JSON.parse(JSON.stringify(rawBreathe))// `depth` 생략은 굽기에서 0.06 이다. `Number(undefined)` = NaN 이고// `JSON.stringify(NaN)` 은 `null` 이라, 기본값 분기가 없으면 첫 autosave 가// 사이드카에 `depth: null` 을 박아 **굽기가 죽는다** (validator 실측 2026-07-26).- ? { depth: rawBreathe.depth == null ? 0.06 : Number(rawBreathe.depth),+ : { depth: rawBreathe.depth == null ? 0.06 : Number(rawBreathe.depth),// 위에서 정수 검증을 통과했으므로 반올림이 필요 없다 — 반올림하면 굽기와 갈린다breaths: Number(rawBreathe.breaths == null ? 1 : rawBreathe.breaths),lag: Number(rawBreathe.lag == null ? 0.1 : rawBreathe.lag),rigid_row: rawBreathe.rigid_row == null ? null : Number(rawBreathe.rigid_row),- anatomy: rawBreathe.anatomy || null }+ anatomy: rawBreathe.anatomy || null,+ // 적힌 `mode: "pixel"` 은 그대로 되쓴다 — 생략과 같은 뜻이지만 사용자가 쓴 키다.+ ...(rawBreathe.mode != null ? { mode: rawBreathe.mode } : {}) }: null };}// 폐기 스키마가 하나라도 있으면 조용히 넘어가지 않는다 — 사용자가 마이그레이션을diff --git a/tests/effects/test_breathe_smooth.py b/tests/effects/test_breathe_smooth.pyindex b61c557..f331079 100644--- a/tests/effects/test_breathe_smooth.py+++ b/tests/effects/test_breathe_smooth.py@@ -93,7 +93,8 @@ def _mark_row(frame: Image.Image, near: float, column: int, reach: int = 4) -> f"""`near` 근처 어두운 선의 무게중심 행 (소수) — 한 열 위에서 어두움으로 가중."""a = np.asarray(frame.convert("RGBA"), np.float64)lo, hi = int(near) - reach, int(near) + reach + 1- col = a[lo:hi, column, :3].mean(axis=1)+ alpha = a[lo:hi, column, 3:4] / 255.0 # 몸통 색 위에 얹어 읽는다 — 투명은 어둡지 않다+ col = (a[lo:hi, column, :3] * alpha + np.array(BODY[:3]) * (1.0 - alpha)).mean(axis=1)weight = np.clip(sum(BODY[:3]) / 3.0 - col, 0.0, None) # 몸통 색 = 0, 표시선 쪽으로 선형assert weight.sum() > 0, "표시선을 못 찾았다"return float((weight * np.arange(lo, hi)).sum() / weight.sum())@@ -166,7 +167,7 @@ def _marked(h: int = 120, **raw):box = solid_alpha_bbox(src)rows = {"chest": box[1] + int(round(chest_y)), "shoulder": box[1] + int(round(shoulder))}cols = {"axis": box[0] + anat.axis_x,- "tip": box[0] + anat.axis_x + int(0.9 * anat.torso_half), # 어깨 끝 쪽+ "tip": box[0] + anat.axis_x + int(B.SHOULDER_X * anat.torso_half), # 어깨 자리"side": box[0] + anat.axis_x - int(0.95 * anat.torso_half)} # 가슴 무게 밖return src, anat, cfg, rows, cols@@ -205,6 +206,23 @@ def test_it_is_not_a_whole_row_moving_up(h: int) -> None:f"어깨 끝이 {tip:.2f}px — 가슴({center:.2f}px)의 shoulder {cfg['shoulder']} 배쯤 달싹여야 한다"+def test_the_neck_holds_while_the_shoulder_beside_it_breathes() -> None:+ """목은 목 너비만 붙잡는다 — 강체 경계 바로 아래, 목 가운데는 거의 그대로지만 같은 높이의 목+ 바로 옆(어깨)은 이미 숨을 쉰다. 행 전체를 오래 붙잡으면 목 옆에 높이 붙은 어깨가 묶인다."""+ src = _bust(1000)+ anat = analyze(src)+ cfg = _cfg({"mode": "smooth"}) # 기본 모양·진폭+ lo, hi = anat.neck_span+ top, end = B.smooth_band(anat)+ y = np.array([top + 0.25 * (end - top)])+ lift = cfg["depth"] * anat.basis_rows+ _, neck = B.smooth_displacement(anat, cfg, np.array([0.5 * (lo + hi + 1)]), y, 1.0, 1.0)+ _, beside = B.smooth_displacement(anat, cfg, np.array([hi + 0.8 * (hi - lo + 1)]), y, 1.0, 1.0)+ assert -neck[0] < 0.05 * lift, f"목 가운데가 {-neck[0]:.2f}px 오른다 — 목은 거의 그대로여야 한다"+ assert -beside[0] > 0.6 * cfg["shoulder"] * lift, \+ f"목 옆 어깨가 {-beside[0]:.2f}px — 가슴({lift:.2f}px)의 shoulder 배 가까이 올라야 한다"++def test_the_shoulders_follow_the_chest_a_little_late() -> None:src, anat, cfg, rows, cols = _marked()lift = cfg["depth"] * anat.basis_rows@@ -240,15 +258,16 @@ def test_no_seam_or_tear_between_the_head_and_the_body(h: int) -> None:cfg = _cfg(_smooth())for phase in (0.25, B.INHALE, 0.6):got = np.asarray(B.phase_frame(src, cfg, phase, anat)).astype(int)- for column in (box[0] + anat.axis_x, box[0] + anat.axis_x + int(0.9 * anat.torso_half)):+ for column in (box[0] + anat.axis_x, box[0] + anat.axis_x + int(B.SHOULDER_X * anat.torso_half)):red = got[box[1]:box[3], column, 0] # 정수리부터 발끝까지 — 경계를 가로지른다red = red[got[box[1]:box[3], column, 3] == 255]steps = np.diff(red)assert steps.min() >= 0, f"위상 {phase} {column}열: 기울기가 거꾸로 섰다 — 행이 접혔다"assert steps.max() <= slope * (1 + B.MAX_ROW_STRAIN) + 1.0, \f"위상 {phase} {column}열: 한 행에 {steps.max()} 뛰었다 — 이음새(행 빠짐)다"- for y in range(box[1], box[3]): # 몸통 안이 끊기지 않는다- alpha = got[y, :, 3]+ inner = int(np.ceil(h * 0.46 + cfg["depth"] * anat.basis_rows)) + 2+ for y in range(inner, box[3]): # 몸통 안이 끊기지 않는다 (윗변은 어깨가+ alpha = got[y, :, 3] # 들리며 모양이 바뀌는 자리라 뺀다)inside = np.nonzero(alpha)[0]if inside.size:run = alpha[inside[0]:inside[-1] + 1]@@ -372,11 +391,27 @@ def test_a_swell_reaching_past_the_canvas_is_still_refused() -> None:pixel 과 같이 조용히 자르지 않고 멈춘다. 기본 모양에서는 생기지 않는다(위 시험)."""src = _bust(margin=0.0)with pytest.raises(SystemExit, match="셀 밖"):- B.phase_frame(src, _cfg(_smooth(chest_rx=2.5, depth_x=0.1)), B.INHALE)- roomy = _bust(margin=0.12)- got = B.phase_frame(roomy, _cfg(_smooth(depth_x=0.05)), B.INHALE)- before, after = solid_alpha_bbox(roomy), solid_alpha_bbox(got)- assert after[2] - after[0] > before[2] - before[0], "depth_x 를 줬는데 가슴이 안 넓어졌다"+ B.phase_frame(src, _cfg(_smooth(depth=0.01, chest_rx=2.5, depth_x=0.05)), B.INHALE)+ # 가슴 안에 그은 세로선은 depth_x 만큼 가운데에서 바깥으로 밀린다 (실루엣 밖 변은 그대로).+ probe = _bust(margin=0.12, gradient=False)+ anat = analyze(probe)+ cfg = _cfg(_smooth(depth=0.01, depth_x=0.05))+ box = solid_alpha_bbox(probe)+ cx, cy = B.smooth_chest(anat, cfg)+ row = box[1] + int(cy)+ a = np.asarray(probe).copy()+ col = box[0] + int(cx + 0.4 * cfg["chest_rx"] * anat.torso_half)+ a[row - 4:row + 5, col] = MARK+ roomy = Image.fromarray(a, "RGBA")+ still = np.asarray(B.phase_frame(roomy, {**cfg, "depth_x": 0.0}, B.INHALE, anat), np.float64)+ puffed = np.asarray(B.phase_frame(roomy, cfg, B.INHALE, anat), np.float64)++ def centre(img):+ line = img[row, col - 4:col + 5, :3].mean(axis=1)+ weight = np.clip(sum(BODY[:3]) / 3.0 - line, 0.0, None)+ return float((weight * np.arange(col - 4, col + 5)).sum() / weight.sum())++ assert centre(puffed) - centre(still) > 0.2, "depth_x 를 줬는데 가슴이 안 부풀었다"def test_a_strain_past_the_cap_is_refused() -> None: