Skip to content

Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.

refactor(breathe): the two bake modes are named once, BREATHE_PIXEL and BREATHE_SMOOTH unpacked from curation.BREATHE_MODES, and every mode branch in breathe, curation, breath_beat and sway and in the curator's store.js and breathe.js reads those names instead of retyping "smooth" and "pixel"

Soohong Kimac18484a7e64
diff --git a/sprite_gen/curate/curation.py b/sprite_gen/curate/curation.py
index 7cc421d..bbe51e6 100644
--- a/sprite_gen/curate/curation.py
+++ b/sprite_gen/curate/curation.py
@@ -225,7 +225,7 @@ BREATHE_LAG_MAX = 0.45
# 큰 일러·영상 프레임용 — 머리를 자리·바이트 그대로 두고 가슴에서 둥글게 숨쉬게 한다
# (`sprite_gen.effects.breathe`). smooth 의 기본 진폭은 일러에 맞게 작다 — 가슴 가운데가 목 아래
# 몸통 높이의 0.85 % 오른다 (흉상 일러에서 화면 높이 약 0.5 %, 화면 크기로 봐도 숨이 세지 않다).
-BREATHE_MODES = ("pixel", "smooth")
+BREATHE_PIXEL, BREATHE_SMOOTH = BREATHE_MODES = ("pixel", "smooth")
BREATHE_SMOOTH_DEPTH = 0.0085
# smooth 의 가슴 부풂 — 가슴 가운데에서 이 비율만큼 넓어지고, 바깥으로 갈수록 무게만큼 준다.
BREATHE_SMOOTH_DEPTH_X = 0.028
@@ -338,7 +338,7 @@ def state_breathe(curation: dict[str, Any] | None, state: str) -> dict[str, Any]
raise SystemExit(
f"curation: states.{state}.breathe.mode = {mode!r} 를 모른다 — "
f"{' | '.join(BREATHE_MODES)} 중 하나다 (생략하면 pixel). 조용히 pixel 로 굽지 않는다.")
- smooth = mode == "smooth"
+ smooth = mode == BREATHE_SMOOTH
# pixel 의 둥근 가슴·양팔 가로 — 생략(None)·0 은 꺼짐. 하나라도 0 보다 크면 그 줄은 round 장을 굽는다.
amps = {}
for name in BREATHE_ROUND_KEYS:
diff --git a/sprite_gen/effects/breath_beat.py b/sprite_gen/effects/breath_beat.py
index c4d8f05..017529b 100644
--- a/sprite_gen/effects/breath_beat.py
+++ b/sprite_gen/effects/breath_beat.py
@@ -27,7 +27,7 @@ from typing import Any
from PIL import Image
from sprite_gen._deps import np
-from sprite_gen.curate.curation import BREATHE_BREATHS_MAX
+from sprite_gen.curate.curation import BREATHE_BREATHS_MAX, BREATHE_SMOOTH
from sprite_gen.effects import breathe
from sprite_gen.video import auto_motion
@@ -61,7 +61,7 @@ def _corr(a: np.ndarray, b: np.ndarray) -> float:
def _row(beat: dict, n: int, hands: np.ndarray, body: np.ndarray, lift: float, inhale: float) -> dict[str, Any]:
"""한 박자 후보의 점수와 조건 — 그 박자와 들숨 몫으로 굽기가 쓸 위상과 곡선에서."""
- phases = breathe.fit_breathe_pattern(n, {"mode": "smooth", "inhale": inhale, **beat})
+ phases = breathe.fit_breathe_pattern(n, {"mode": BREATHE_SMOOTH, "inhale": inhale, **beat})
w = np.asarray([breathe.smooth_wave(p, inhale) for p in phases])
peaks = [i for i in range(n) if w[i] > PEAK_LEVEL and w[i] >= w[i - 1] and w[i] >= w[(i + 1) % n]]
margin = min(lift * w[p] - max(hands[(p + j) % n] for j in range(-NEAR, NEAR + 1)) for p in peaks)
diff --git a/sprite_gen/effects/breathe.py b/sprite_gen/effects/breathe.py
index bdbc1e2..de5ceb7 100644
--- a/sprite_gen/effects/breathe.py
+++ b/sprite_gen/effects/breathe.py
@@ -89,8 +89,9 @@ from PIL import Image
from sprite_gen._deps import np
from sprite_gen.effects.anatomy import Anatomy, analyze
-from sprite_gen.curate.curation import (BREATHE_MODES, BREATHE_RANGE_KEYS, BREATHE_SMOOTH_DEPTH, BREATHE_SMOOTH_DEPTH_X,
- BREATHE_SMOOTH_SHAPE, normalize_transform, state_breathe)
+from sprite_gen.curate.curation import (BREATHE_MODES, BREATHE_PIXEL, BREATHE_RANGE_KEYS, BREATHE_SMOOTH,
+ BREATHE_SMOOTH_DEPTH, BREATHE_SMOOTH_DEPTH_X, BREATHE_SMOOTH_SHAPE,
+ normalize_transform, state_breathe)
from sprite_gen.frames.extract import BORDER_MIN_FRACTION, FRAME_SIDES, own_border, solid_alpha_bbox
from sprite_gen.frames.folder import cycle_frame_ms, open_frames, publish, reference_frame
@@ -232,7 +233,7 @@ def breathe_range(anat: Anatomy, cfg: dict) -> dict[str, tuple[float, float]]:
bounds = _bounds(cfg)
if bounds is not None:
return {"width": bounds[0], "height": bounds[1]}
- if breathe_mode(cfg) == "smooth":
+ if breathe_mode(cfg) == BREATHE_SMOOTH:
depth, swell = _smooth_depths(cfg)
return {"width": (0.0, swell), "height": (0.0, depth)}
_, norm = envelope(anat)
@@ -519,7 +520,7 @@ def breathe_mode(cfg: dict) -> str:
"""cfg 의 굽기 방식 — 생략은 pixel. 모르는 값을 조용히 pixel 로 굽지 않는다."""
mode = cfg.get("mode")
if mode is None:
- return "pixel"
+ return BREATHE_PIXEL
if not isinstance(mode, str) or mode not in BREATHE_MODES:
raise SystemExit(f"breathe: mode {mode!r} 를 모른다 — {' | '.join(BREATHE_MODES)} 중 하나다.")
return mode
@@ -1131,7 +1132,7 @@ def row_pins(anat: Anatomy, cfg: dict, frame: Image.Image, hold: np.ndarray | No
f"칸이 맞는다.")
masks[flag] = mask if mask.dtype != bool and flag != "--hold-mask" else mask.astype(bool)
hold, front, back = masks["--hold-mask"], masks["--props-mask"], masks["--props-behind-mask"]
- smooth, rounded = breathe_mode(cfg) == "smooth", pixel_round(cfg)
+ smooth, rounded = breathe_mode(cfg) == BREATHE_SMOOTH, pixel_round(cfg)
if not (smooth or rounded):
raise SystemExit("breathe: 고정 칸(--hold-mask)·쥔 물건(--props-mask, --props-behind-mask)은 변위장으로 굽는 줄의 것이다 — "
"mode smooth, 또는 pixel 의 둥근 가슴(chest_round·arms_x). pixel 봉투 스쿼시는 가로줄을 통째로 옮겨 칸을 "
@@ -1230,7 +1231,7 @@ def _pinned(pins: Pins | None, box, x: np.ndarray, y: np.ndarray, dx: np.ndarray
def pixel_round(cfg: dict) -> bool:
"""이 줄이 둥근 가슴 장을 굽나 — pixel 이고 `chest_round`·`arms_x` 중 하나가 0 보다 크다 (생략·0 은 봉투 스쿼시)."""
- return breathe_mode(cfg) == "pixel" and bool(cfg.get("chest_round") or cfg.get("arms_x"))
+ return breathe_mode(cfg) == BREATHE_PIXEL and bool(cfg.get("chest_round") or cfg.get("arms_x"))
def round_displacement(anat: Anatomy, cfg: dict, x: np.ndarray, y: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
@@ -1836,7 +1837,7 @@ def _pixel_depths(cfg: dict) -> tuple[float, float | None]:
def _row_refusals(cfg: dict, anat: Anatomy, pins: Pins | None = None) -> None:
"""줄이 굽기 전에 거부되는 까닭 — 해부와 설정(과 고정 칸·쥔 물건)에만 달려 줄에 한 번 본다 (칸마다 다시 재지 않는다)."""
- if breathe_mode(cfg) == "smooth":
+ if breathe_mode(cfg) == BREATHE_SMOOTH:
_smooth_refusals(cfg, anat, pins)
return
if pixel_round(cfg):
@@ -1867,7 +1868,7 @@ def _bake_phase_pieces(frame: Image.Image, cfg: dict, phase: float, anat: Anatom
pins: Pins | None = None) -> tuple[Image.Image, list[int], list[int]]:
"""`_bake_phase` 와 그 칸에서 조각 번호 순의 가려진 칸 수·지어낸 칸 수 (쥔 물건은 pixel 의 둥근 가슴만 받는다 — 다른 줄은
빈 목록). `bake_breathe_sequence` 의 `record`."""
- if breathe_mode(cfg) == "smooth":
+ if breathe_mode(cfg) == BREATHE_SMOOTH:
return _smooth_warp(frame, anat, cfg, phase, pins), [], []
if pixel_round(cfg):
return _round_warp(frame, anat, cfg, phase, pins)
@@ -2120,7 +2121,7 @@ def run(*, frames: str, out: str, mode: str | None = None, depth: float | None =
raise SystemExit("breathe: --avoid-region 은 숨 박자를 이 칸들에서 고른다 — 루프의 한 토막(--loop-cells·--start-cell)은 "
"그 루프의 박자를 잇는다. 박자는 루프의 칸에서 골라 그 값을 주라")
cfg = _cli_breathe(raw)
- if avoid_region is not None and breathe_mode(cfg) != "smooth":
+ if avoid_region is not None and breathe_mode(cfg) != BREATHE_SMOOTH:
raise SystemExit("breathe: --avoid-region 은 smooth 의 것이다 (--mode smooth) — pixel 숨은 진행파라 첫 칸이 쉼이 아니다")
folder = open_frames(src_dir, out_dir, "breathe") # 무엇을 만들거나 지우기 전에 — 실경로와 폴더 동일성으로 본다
images = folder.images
diff --git a/sprite_gen/serve/curator/src/breathe.js b/sprite_gen/serve/curator/src/breathe.js
index d5a3f6a..1ba0926 100644
--- a/sprite_gen/serve/curator/src/breathe.js
+++ b/sprite_gen/serve/curator/src/breathe.js
@@ -29,6 +29,9 @@ const BREATHE_LAG_MAX = 0.45;
const BREATHE_WAVE_PEAK = 0.9008738286182177;
const BREATHE_RANGE_KEYS = ["width_min", "width_max", "height_min", "height_max"];
const BREATHE_RANGE_MAX = 0.20;
+// 굽기 방식 — 파이썬 curation.BREATHE_MODES 미러. 생략 = pixel. store.js 의 읽기 검사도 이 이름들을 쓴다.
+const BREATHE_MODES = ["pixel", "smooth"];
+const BREATHE_SMOOTH = BREATHE_MODES[1];
// 그림 자체의 테두리 — 파이썬 frames.extract.FRAME_SIDES·BORDER_MIN_FRACTION 미러 (거절 문구가 쓴다).
const BREATHE_SIDES = ["top", "left", "right"];
const BREATHE_SIDE_NAMES = { top: "위", left: "왼쪽", right: "오른쪽" };
@@ -131,7 +134,7 @@ function breatheGains(anat, cfg) {
function breatheRange(anat, cfg) {
const bounds = breatheBounds(cfg);
if (bounds) return bounds;
- if (cfg.mode === "smooth") {
+ if (cfg.mode === BREATHE_SMOOTH) {
return { width: [0, cfg.depth_x == null ? 0.028 : Number(cfg.depth_x)],
height: [0, cfg.depth == null ? 0.0085 : Number(cfg.depth)] };
}
@@ -335,7 +338,7 @@ function breatheComposite(base, cfg, phase) {
// smooth 줄은 미러가 없다 — 쌍선형 사잇값은 브라우저와 파이썬의 부동소수가 같은 바이트를
// 낸다고 보장할 수 없다. pixel 워프로 그리면 굽기와 다른 숨을 보여 주므로 거부한다
// (미리보기는 원본과 알림, 영상 내보내기는 중단). 결과는 compose 나 `sprite-gen breathe` 로 본다.
- if (cfg && cfg.mode === "smooth") {
+ if (cfg && cfg.mode === BREATHE_SMOOTH) {
throw new BreatheRefused(
"smooth 줄은 큐레이터가 따라 그리지 않는다 — 결과는 compose(GIF·아틀라스)나 `sprite-gen breathe` 로 본다.");
}
diff --git a/sprite_gen/serve/curator/src/store.js b/sprite_gen/serve/curator/src/store.js
index 3106158..cab60e6 100644
--- a/sprite_gen/serve/curator/src/store.js
+++ b/sprite_gen/serve/curator/src/store.js
@@ -11,8 +11,6 @@ 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], chest_tilt: [-60.0, 60.0], chest_bias: [-0.9, 0.9], chest_dir: [-90.0, 90.0], chest_x: [-1.0, 1.0], chest_bias_y: [-0.9, 0.9], chest_flat: [0.0, 0.9], inhale: [0.2, 0.8] };
@@ -24,7 +22,7 @@ const BREATHE_ROUND_MAX = 0.20;
const BREATHE_ROUND_SHAPE = ["chest_y", "chest_rx", "chest_ry", "chest_tilt", "chest_bias", "chest_x", "chest_bias_y", "inhale"];
function breatheRound(raw) {
- return raw.mode !== "smooth"
+ return raw.mode !== BREATHE_SMOOTH
&& BREATHE_ROUND_KEYS.some((k) => raw[k] != null && isNumericScalar(raw[k]) && Number(raw[k]) > 0);
}
@@ -34,14 +32,14 @@ function breatheRangeProblems(raw) {
// 모르는 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) {
+ if (raw.mode === BREATHE_SMOOTH && raw.lag != null && Number(raw.lag) !== 0) {
bad.push(`lag=${JSON.stringify(raw.lag)} (smooth 에는 lag 가 없다)`);
}
// 둥근 가슴 값 — null 은 생략과 같다. smooth 줄에 있거나 범위 밖이면 굽기가 거부한다.
const rounded = breatheRound(raw);
for (const key of BREATHE_ROUND_KEYS) {
if (raw[key] == null) continue;
- if (raw.mode === "smooth") { bad.push(`${key} (pixel 의 둥근 가슴 값)`); continue; }
+ if (raw.mode === BREATHE_SMOOTH) { bad.push(`${key} (pixel 의 둥근 가슴 값)`); continue; }
const v = isNumericScalar(raw[key]) ? Number(raw[key]) : NaN;
if (!Number.isFinite(v) || v < 0 || v > BREATHE_ROUND_MAX) bad.push(`${key}=${JSON.stringify(raw[key])}`);
}
@@ -53,7 +51,7 @@ function breatheRangeProblems(raw) {
// 모양 값은 smooth 만 쓴다 — 둥근 가슴 줄은 가슴 타원 키만. 그 밖의 pixel 줄에 있으면 굽기가 거부하고, 읽는 줄은 범위를 본다.
for (const [key, [lo, hi]] of Object.entries(BREATHE_SMOOTH_SHAPE_RANGES)) {
if (raw[key] === undefined) continue;
- if (raw.mode !== "smooth" && !(rounded && BREATHE_ROUND_SHAPE.includes(key))) {
+ if (raw.mode !== BREATHE_SMOOTH && !(rounded && BREATHE_ROUND_SHAPE.includes(key))) {
bad.push(`${key} (smooth 만 쓰는 모양 값)`);
continue;
}
@@ -63,7 +61,7 @@ function breatheRangeProblems(raw) {
// 들숨 꼭대기 칸(smooth·둥근 가슴): 1 부터 커지는 정수, 서로 두 칸 이상 — 파이썬 state_breathe 미러.
if (raw.breath_peaks !== undefined) {
const p = raw.breath_peaks;
- const ok = (raw.mode === "smooth" || rounded) && Array.isArray(p) && p.length > 0 && p.every(Number.isInteger)
+ const ok = (raw.mode === BREATHE_SMOOTH || rounded) && Array.isArray(p) && p.length > 0 && p.every(Number.isInteger)
&& p[0] >= 1 && p.every((v, i) => i === 0 || v - p[i - 1] >= 2)
&& (raw.breaths == null || Number(raw.breaths) === p.length);
if (!ok) bad.push(`breath_peaks=${JSON.stringify(p)}`);
@@ -72,13 +70,13 @@ function breatheRangeProblems(raw) {
// state_breathe 미러 (curation.BREATHE_STRETCH_KEYS).
const intAt = (v) => isNumericScalar(v) && Number.isInteger(Number(v));
// null 은 생략과 같다(줄이 곧 루프) — 단 pixel 줄에서는 키가 있는 것만으로 굽기가 거부한다.
- if (raw.loop_cells !== undefined && ((raw.mode !== "smooth" && !rounded)
+ if (raw.loop_cells !== undefined && ((raw.mode !== BREATHE_SMOOTH && !rounded)
|| (raw.loop_cells !== null && (!intAt(raw.loop_cells) || Number(raw.loop_cells) < 2)))) {
bad.push(`loop_cells=${JSON.stringify(raw.loop_cells)}`);
}
if (raw.start_cell !== undefined) {
const loop = intAt(raw.loop_cells) ? Number(raw.loop_cells) : Infinity;
- const ok = (raw.mode === "smooth" || rounded) && intAt(raw.start_cell) && Number(raw.start_cell) >= 0
+ const ok = (raw.mode === BREATHE_SMOOTH || rounded) && intAt(raw.start_cell) && Number(raw.start_cell) >= 0
&& Number(raw.start_cell) < loop;
if (!ok) bad.push(`start_cell=${JSON.stringify(raw.start_cell)}`);
}
@@ -697,7 +695,7 @@ function seedEntries() {
// 없고, 아래 pixel 정규화를 태우면 첫 autosave 가 pixel 기본값(depth 0.06, lag 0.1)을
// 채워 넣어 smooth 줄의 진폭을 바꾸고 굽기가 lag 로 거부하게 된다.
// 둥근 가슴 pixel 줄도 같다 — 아래 pixel 정규화는 chest_round·arms_x 를 버리고 depth·lag 를 채워 넣는다.
- ? rawBreathe.mode === "smooth" || breatheRound(rawBreathe) ? JSON.parse(JSON.stringify(rawBreathe))
+ ? rawBreathe.mode === BREATHE_SMOOTH || breatheRound(rawBreathe) ? JSON.parse(JSON.stringify(rawBreathe))
// `depth` 생략은 굽기에서 0.06 이다. `Number(undefined)` = NaN 이고
// `JSON.stringify(NaN)` 은 `null` 이라, 기본값 분기가 없으면 첫 autosave 가
// 사이드카에 `depth: null` 을 박아 **굽기가 죽는다** (validator 실측 2026-07-26).
diff --git a/sprite_gen/video/sway.py b/sprite_gen/video/sway.py
index 3e4d90d..6964dfa 100644
--- a/sprite_gen/video/sway.py
+++ b/sprite_gen/video/sway.py
@@ -189,7 +189,7 @@ from typing import Any
from PIL import Image
from sprite_gen._deps import np
-from sprite_gen.curate.curation import BREATHE_SMOOTH_SHAPE_RANGES, state_breathe
+from sprite_gen.curate.curation import BREATHE_PIXEL, BREATHE_SMOOTH, BREATHE_SMOOTH_SHAPE_RANGES, state_breathe
from sprite_gen.effects import breathe as breathe_mod
from sprite_gen.effects.anatomy import Anatomy
from sprite_gen.frames import folder as folder_mod
@@ -1251,8 +1251,8 @@ def read_breath(path: Path, lag: float | None, *, verb: str = VERB) -> Breath:
and isinstance((report.get("resolved") or {}).get("anatomy"), dict)):
raise SystemExit(f"{verb}: --breathe {path}: not a Breathe layer's record — sprite-gen breathe writes config, phases "
"and resolved.anatomy into breathe.json")
- mode = report["config"].get("mode") or "pixel"
- if mode != "smooth":
+ mode = report["config"].get("mode") or BREATHE_PIXEL
+ if mode != BREATHE_SMOOTH:
raise SystemExit(f"{verb}: --breathe {path}: a {mode} breath — the part follows a smooth breath, which rests at the "
"first cell (a pixel breath's travelling wave moves it)")
try:
diff --git a/tests/effects/test_breathe_smooth_curator.py b/tests/effects/test_breathe_smooth_curator.py
index fa2bbc6..b46c35b 100644
--- a/tests/effects/test_breathe_smooth_curator.py
+++ b/tests/effects/test_breathe_smooth_curator.py
@@ -109,7 +109,7 @@ def test_the_mirrored_modes_are_the_same_list() -> None:
from sprite_gen.curate import curation as C
from sprite_gen.serve.serve_curation import CURATOR_DIR
- js = (CURATOR_DIR / "src" / "store.js").read_text(encoding="utf-8")
+ js = (CURATOR_DIR / "src" / "breathe.js").read_text(encoding="utf-8")
m = re.search(r"const BREATHE_MODES = \[(.*?)\];", js)
assert m, "BREATHE_MODES 가 미러에 없다"
assert [k.strip().strip('"') for k in m.group(1).split(",")] == list(C.BREATHE_MODES)