From 934184e93582ac1dc05f5e775f45580b1ffe3a1f Mon Sep 17 00:00:00 2001 From: t1nyb0x Date: Sun, 13 Sep 2026 13:55:49 +0900 Subject: [PATCH 01/49] =?UTF-8?q?feat:=20M0=20=E5=9F=BA=E7=9B=A4=20(monore?= =?UTF-8?q?po,=20Fastify=20+=20React=20Router,=20DB,=20Docker,=20CI)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - pnpm workspace: apps/{app,worker}, packages/{shared,db,core} - apps/app: Fastify (zod type provider, OpenAPI, helmet, rate-limit, Origin 検証, 統一エラー形式, /api/health) と React Router v8 SSR を @mcansh/react-router-fastify で同一プロセスに統合 - apps/worker: pg-boss で heartbeat ジョブ (cron 毎分) を実行 - packages/shared: 編集レシピ v1 (zod), migrateRecipe, プリセット 10 種, EquipSlotCategory 定数 - packages/db: Drizzle スキーマ (users, characters, posts, post_images, edit_recipes, feature_flags, worker_heartbeat) と初期マイグレーション - packages/core: pino ロガー (redact), health ドメイン, ジョブ定義 - ESLint で依存方向を強制 (packages はフレームワーク非依存、web は API 契約のみ、shared は Node API 禁止) - Docker multi-stage (app / worker), compose (postgres 18, caddy), CI - Vitest 35 件、カバレッジ 99% (DB あり) Co-Authored-By: Claude Opus 5 --- packages/shared/src/recipe/index.ts | 3 + packages/shared/src/recipe/migrate.ts | 33 ++++++++++ packages/shared/src/recipe/presets.ts | 49 +++++++++++++++ packages/shared/src/recipe/recipe.test.ts | 63 +++++++++++++++++++ packages/shared/src/recipe/schema.ts | 76 +++++++++++++++++++++++ 5 files changed, 224 insertions(+) create mode 100644 packages/shared/src/recipe/index.ts create mode 100644 packages/shared/src/recipe/migrate.ts create mode 100644 packages/shared/src/recipe/presets.ts create mode 100644 packages/shared/src/recipe/recipe.test.ts create mode 100644 packages/shared/src/recipe/schema.ts diff --git a/packages/shared/src/recipe/index.ts b/packages/shared/src/recipe/index.ts new file mode 100644 index 0000000..55b3f3e --- /dev/null +++ b/packages/shared/src/recipe/index.ts @@ -0,0 +1,3 @@ +export * from "./schema.ts"; +export * from "./migrate.ts"; +export * from "./presets.ts"; diff --git a/packages/shared/src/recipe/migrate.ts b/packages/shared/src/recipe/migrate.ts new file mode 100644 index 0000000..5e4d8cb --- /dev/null +++ b/packages/shared/src/recipe/migrate.ts @@ -0,0 +1,33 @@ +import { z } from "zod"; +import { editRecipeSchema, type EditRecipe } from "./schema.ts"; + +export class RecipeMigrationError extends Error { + override readonly name = "RecipeMigrationError"; +} + +const versioned = z.object({ version: z.number().int() }); + +/** + * 任意の入力を現行バージョンのレシピに変換する。 + * 未知の version、検証に失敗する入力は RecipeMigrationError を投げる。 + * 新しい version を追加するときは、旧 version から順に変換する関数をここに足す。 + */ +export function migrateRecipe(input: unknown): EditRecipe { + const head = versioned.safeParse(input); + if (!head.success) { + throw new RecipeMigrationError("recipe has no valid version"); + } + switch (head.data.version) { + case 1: { + const parsed = editRecipeSchema.safeParse(input); + if (!parsed.success) { + throw new RecipeMigrationError( + `invalid v1 recipe: ${parsed.error.issues[0]?.message ?? "unknown"}`, + ); + } + return parsed.data; + } + default: + throw new RecipeMigrationError(`unsupported recipe version: ${head.data.version}`); + } +} diff --git a/packages/shared/src/recipe/presets.ts b/packages/shared/src/recipe/presets.ts new file mode 100644 index 0000000..faf510d --- /dev/null +++ b/packages/shared/src/recipe/presets.ts @@ -0,0 +1,49 @@ +import { DEFAULT_ADJUST, type AdjustV1, type EditRecipe } from "./schema.ts"; + +export type Preset = { + id: string; + name: string; + adjust: Partial; +}; + +// 初期プリセット。数値は実装時 (M1) に実画像で調整する。docs/design/04-edit-recipe.md §2 +export const PRESETS: readonly Preset[] = Object.freeze([ + { + id: "night-city", + name: "夜景", + adjust: { exposure: -0.3, shadows: 25, temperature: -20, contrast: 10 }, + }, + { + id: "warm-sunset", + name: "夕暮れ", + adjust: { temperature: 30, highlights: -20, saturation: -10 }, + }, + { id: "cool-morning", name: "朝霧", adjust: { temperature: -25, contrast: -15, shadows: 20 } }, + { id: "pastel", name: "パステル", adjust: { contrast: -20, vibrance: 15, highlights: 15 } }, + { id: "vivid", name: "ビビッド", adjust: { vibrance: 30, contrast: 15 } }, + { id: "film", name: "フィルム", adjust: { shadows: 20, highlights: -15, saturation: -15 } }, + { id: "mono", name: "モノクロ", adjust: { saturation: -100, contrast: 15 } }, + { id: "soft-portrait", name: "ソフト", adjust: { contrast: -10, highlights: -10, vibrance: 10 } }, + { id: "dungeon", name: "ダンジョン", adjust: { exposure: 0.4, shadows: 30, temperature: -15 } }, + { + id: "gold-hour", + name: "ゴールド", + adjust: { temperature: 35, exposure: 0.2, highlights: -15 }, + }, +]); + +export function findPreset(id: string): Preset | undefined { + return PRESETS.find((p) => p.id === id); +} + +/** + * プリセットを適用した新しいレシピを返す。元のレシピは変更しない。 + * 適用は adjust への上書きであり、幾何情報には触れない。 + */ +export function applyPreset(recipe: EditRecipe, preset: Preset): EditRecipe { + return { + ...recipe, + presetId: preset.id, + adjust: { ...DEFAULT_ADJUST, ...preset.adjust }, + }; +} diff --git a/packages/shared/src/recipe/recipe.test.ts b/packages/shared/src/recipe/recipe.test.ts new file mode 100644 index 0000000..20e78fd --- /dev/null +++ b/packages/shared/src/recipe/recipe.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, it } from "vitest"; +import { DEFAULT_RECIPE, editRecipeSchema } from "./schema.ts"; +import { migrateRecipe, RecipeMigrationError } from "./migrate.ts"; +import { applyPreset, findPreset, PRESETS } from "./presets.ts"; + +describe("editRecipeSchema v1", () => { + it("accepts the default recipe", () => { + expect(editRecipeSchema.parse(DEFAULT_RECIPE)).toEqual(DEFAULT_RECIPE); + }); + + it("rejects out-of-range values instead of clamping", () => { + const bad = { ...DEFAULT_RECIPE, adjust: { ...DEFAULT_RECIPE.adjust, exposure: 6 } }; + expect(editRecipeSchema.safeParse(bad).success).toBe(false); + }); + + it("rejects non-right-angle rotation", () => { + const bad = { ...DEFAULT_RECIPE, geometry: { ...DEFAULT_RECIPE.geometry, rotation: 45 } }; + expect(editRecipeSchema.safeParse(bad).success).toBe(false); + }); +}); + +describe("migrateRecipe", () => { + it("passes a valid v1 recipe through", () => { + expect(migrateRecipe(DEFAULT_RECIPE)).toEqual(DEFAULT_RECIPE); + }); + + it("throws on unknown version", () => { + expect(() => migrateRecipe({ ...DEFAULT_RECIPE, version: 99 })).toThrow(RecipeMigrationError); + }); + + it("throws on input without version", () => { + expect(() => migrateRecipe({})).toThrow(RecipeMigrationError); + expect(() => migrateRecipe(null)).toThrow(RecipeMigrationError); + }); +}); + +describe("presets", () => { + it("has 10 presets with unique ids", () => { + expect(PRESETS).toHaveLength(10); + expect(new Set(PRESETS.map((p) => p.id)).size).toBe(10); + }); + + it("every preset produces a valid recipe", () => { + for (const preset of PRESETS) { + expect(editRecipeSchema.safeParse(applyPreset(DEFAULT_RECIPE, preset)).success).toBe(true); + } + }); + + it("applyPreset does not mutate the input and keeps geometry", () => { + const before = structuredClone(DEFAULT_RECIPE); + const cropped = { + ...DEFAULT_RECIPE, + geometry: { ...DEFAULT_RECIPE.geometry, rotation: 90 as const }, + }; + const mono = findPreset("mono"); + if (!mono) throw new Error("mono preset missing"); + const out = applyPreset(cropped, mono); + expect(out.adjust.saturation).toBe(-100); + expect(out.geometry.rotation).toBe(90); + expect(out.presetId).toBe("mono"); + expect(DEFAULT_RECIPE).toEqual(before); + }); +}); diff --git a/packages/shared/src/recipe/schema.ts b/packages/shared/src/recipe/schema.ts new file mode 100644 index 0000000..752967e --- /dev/null +++ b/packages/shared/src/recipe/schema.ts @@ -0,0 +1,76 @@ +import { z } from "zod"; + +// 編集レシピ v1。定義は docs/design/04-edit-recipe.md を正とする。 +// 変更は追加のみ。既存項目の意味・値域は変えない (ADR-0009)。 + +const pct = z.number().min(-100).max(100); + +export const adjustSchemaV1 = z.object({ + exposure: z.number().min(-5).max(5), + contrast: pct, + highlights: pct, + shadows: pct, + temperature: pct, + tint: pct, + vibrance: pct, + saturation: pct, +}); + +export const cropSchemaV1 = z.object({ + x: z.number().min(0).max(1), + y: z.number().min(0).max(1), + w: z.number().min(0).max(1), + h: z.number().min(0).max(1), +}); + +export const ASPECT_PRESETS = ["free", "1:1", "4:3", "3:2", "16:9", "9:16", "3:4", "2:3"] as const; + +export const geometrySchemaV1 = z.object({ + rotation: z.union([z.literal(0), z.literal(90), z.literal(180), z.literal(270)]), + straighten: z.number().min(-45).max(45), + flipH: z.boolean(), + crop: cropSchemaV1.nullable(), + aspect: z.enum(ASPECT_PRESETS).nullable(), +}); + +export const editRecipeSchemaV1 = z.object({ + version: z.literal(1), + presetId: z.string().max(64).nullable(), + adjust: adjustSchemaV1, + geometry: geometrySchemaV1, +}); + +export type AdjustV1 = z.infer; +export type GeometryV1 = z.infer; +export type EditRecipeV1 = z.infer; + +/** 現行のレシピ型。version を上げたらここを差し替える。 */ +export type EditRecipe = EditRecipeV1; +export const editRecipeSchema = editRecipeSchemaV1; +export const CURRENT_RECIPE_VERSION = 1 as const; + +export const DEFAULT_ADJUST: AdjustV1 = Object.freeze({ + exposure: 0, + contrast: 0, + highlights: 0, + shadows: 0, + temperature: 0, + tint: 0, + vibrance: 0, + saturation: 0, +}); + +export const DEFAULT_GEOMETRY: GeometryV1 = Object.freeze({ + rotation: 0, + straighten: 0, + flipH: false, + crop: null, + aspect: null, +}); + +export const DEFAULT_RECIPE: EditRecipe = Object.freeze({ + version: 1, + presetId: null, + adjust: DEFAULT_ADJUST, + geometry: DEFAULT_GEOMETRY, +}); From 6dc4bd61ffd0b6694bf7fe1efc35aabc0a998e80 Mon Sep 17 00:00:00 2001 From: t1nyb0x Date: Sun, 13 Sep 2026 14:57:18 +0900 Subject: [PATCH 02/49] =?UTF-8?q?feat(editor):=20M1=20=E7=94=BB=E5=83=8F?= =?UTF-8?q?=E7=B7=A8=E9=9B=86=20(PixiJS,=208=20=E8=A3=9C=E6=AD=A3,=20?= =?UTF-8?q?=E3=83=97=E3=83=AA=E3=82=BB=E3=83=83=E3=83=88,=20=E5=B9=BE?= =?UTF-8?q?=E4=BD=95,=20undo/redo,=20=E6=9B=B8=E3=81=8D=E5=87=BA=E3=81=97)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - adjust-math.ts に補正パイプラインの CPU 参照実装、GLSL はそれを写す (linear 空間で露光・色温度・色かぶり・ハイライト/シャドウ、sRGB 空間で コントラスト・自然な彩度・彩度) - EditorRenderer: Sprite 1 枚 + AdjustFilter 1 パス、幾何は transform、 crop は書き出し時の frame。WebP (非対応時 JPEG) を canvas.toBlob で生成 - 履歴: ドラッグ中は preview、離したら dragBase を積んで commit。上限 100 - 画像読み込み: マジックバイト検証、30MB 上限、EXIF 方向解決、長辺 4096 縮小 - IndexedDB 下書き (最大 5 件) と投稿導線への pending 受け渡し - UI: プリセット / 補正 / 幾何タブ、DOM の crop 枠 (8 ハンドル、比率固定)、 比較長押し、Ctrl+Z / Ctrl+Shift+Z - /edit は clientLoader のみ (SSR しない)。PixiJS は別チャンク (240KB) - Playwright E2E 7 本: 全プリセットで GPU 出力と CPU 参照が ±3/255、 回転・crop の出力サイズ、undo/redo、download、不正ファイル拒否 - fix: レート制限が全ルートにかかりページが 429 になる不具合。/api 配下のみに Co-Authored-By: Claude Opus 5 --- .../web/features/editor/adjust-math.test.ts | 82 ++++ apps/app/web/features/editor/adjust-math.ts | 90 ++++ apps/app/web/features/editor/drafts.ts | 71 ++++ apps/app/web/features/editor/history.test.ts | 77 ++++ apps/app/web/features/editor/history.ts | 44 ++ .../web/features/editor/image-format.test.ts | 44 ++ apps/app/web/features/editor/image-format.ts | 33 ++ apps/app/web/features/editor/load-image.ts | 57 +++ .../features/editor/render/adjust-filter.ts | 138 +++++++ .../features/editor/render/editor-renderer.ts | 185 +++++++++ .../features/editor/render/geometry.test.ts | 75 ++++ .../web/features/editor/render/geometry.ts | 72 ++++ apps/app/web/features/editor/state.test.ts | 70 ++++ apps/app/web/features/editor/state.ts | 124 ++++++ .../web/features/editor/ui/AdjustPanel.tsx | 49 +++ .../web/features/editor/ui/CropOverlay.tsx | 115 ++++++ .../app/web/features/editor/ui/EditorPage.tsx | 386 ++++++++++++++++++ .../web/features/editor/ui/GeometryPanel.tsx | 105 +++++ .../web/features/editor/ui/PresetPanel.tsx | 32 ++ apps/app/web/features/editor/ui/Slider.tsx | 95 +++++ .../web/features/editor/ui/crop-drag.test.ts | 36 ++ apps/app/web/features/editor/ui/crop-drag.ts | 73 ++++ e2e/editor.spec.ts | 186 +++++++++ 23 files changed, 2239 insertions(+) create mode 100644 apps/app/web/features/editor/adjust-math.test.ts create mode 100644 apps/app/web/features/editor/adjust-math.ts create mode 100644 apps/app/web/features/editor/drafts.ts create mode 100644 apps/app/web/features/editor/history.test.ts create mode 100644 apps/app/web/features/editor/history.ts create mode 100644 apps/app/web/features/editor/image-format.test.ts create mode 100644 apps/app/web/features/editor/image-format.ts create mode 100644 apps/app/web/features/editor/load-image.ts create mode 100644 apps/app/web/features/editor/render/adjust-filter.ts create mode 100644 apps/app/web/features/editor/render/editor-renderer.ts create mode 100644 apps/app/web/features/editor/render/geometry.test.ts create mode 100644 apps/app/web/features/editor/render/geometry.ts create mode 100644 apps/app/web/features/editor/state.test.ts create mode 100644 apps/app/web/features/editor/state.ts create mode 100644 apps/app/web/features/editor/ui/AdjustPanel.tsx create mode 100644 apps/app/web/features/editor/ui/CropOverlay.tsx create mode 100644 apps/app/web/features/editor/ui/EditorPage.tsx create mode 100644 apps/app/web/features/editor/ui/GeometryPanel.tsx create mode 100644 apps/app/web/features/editor/ui/PresetPanel.tsx create mode 100644 apps/app/web/features/editor/ui/Slider.tsx create mode 100644 apps/app/web/features/editor/ui/crop-drag.test.ts create mode 100644 apps/app/web/features/editor/ui/crop-drag.ts create mode 100644 e2e/editor.spec.ts diff --git a/apps/app/web/features/editor/adjust-math.test.ts b/apps/app/web/features/editor/adjust-math.test.ts new file mode 100644 index 0000000..184162a --- /dev/null +++ b/apps/app/web/features/editor/adjust-math.test.ts @@ -0,0 +1,82 @@ +import { describe, expect, it } from "vitest"; +import { DEFAULT_ADJUST } from "@prismtone/shared/recipe"; +import { applyAdjust, linearToSrgb, srgbToLinear, type RGB } from "./adjust-math.ts"; + +const near = (a: number, b: number, eps = 1e-3) => Math.abs(a - b) < eps; + +describe("applyAdjust", () => { + it("is identity with default adjust", () => { + for (const px of [ + [0.2, 0.5, 0.8], + [0, 0, 0], + [1, 1, 1], + [0.5, 0.5, 0.5], + ] as RGB[]) { + const out = applyAdjust(px, DEFAULT_ADJUST); + out.forEach((v, i) => expect(near(v, px[i]!)).toBe(true)); + } + }); + + it("exposure +1 EV doubles linear light on mid tones", () => { + const px: RGB = [0.3, 0.3, 0.3]; + const out = applyAdjust(px, { ...DEFAULT_ADJUST, exposure: 1 }); + expect(near(srgbToLinear(out[0]), srgbToLinear(px[0]) * 2, 1e-3)).toBe(true); + }); + + it("saturation -100 produces neutral gray", () => { + const out = applyAdjust([0.9, 0.2, 0.4], { ...DEFAULT_ADJUST, saturation: -100 }); + expect(near(out[0], out[1])).toBe(true); + expect(near(out[1], out[2])).toBe(true); + }); + + it("warm temperature raises red and lowers blue", () => { + const px: RGB = [0.5, 0.5, 0.5]; + const out = applyAdjust(px, { ...DEFAULT_ADJUST, temperature: 100 }); + expect(out[0]).toBeGreaterThan(px[0]); + expect(out[2]).toBeLessThan(px[2]); + expect(near(out[1], px[1])).toBe(true); + }); + + it("positive contrast pushes values away from mid gray", () => { + const dark = applyAdjust([0.3, 0.3, 0.3], { ...DEFAULT_ADJUST, contrast: 100 }); + const light = applyAdjust([0.7, 0.7, 0.7], { ...DEFAULT_ADJUST, contrast: 100 }); + expect(dark[0]).toBeLessThan(0.3); + expect(light[0]).toBeGreaterThan(0.7); + }); + + it("shadows lift dark pixels more than bright ones", () => { + const dark = applyAdjust([0.1, 0.1, 0.1], { ...DEFAULT_ADJUST, shadows: 100 }); + const bright = applyAdjust([0.9, 0.9, 0.9], { ...DEFAULT_ADJUST, shadows: 100 }); + expect(dark[0] - 0.1).toBeGreaterThan(bright[0] - 0.9); + }); + + it("vibrance affects low-saturation pixels more than saturated ones", () => { + const pale: RGB = [0.55, 0.5, 0.5]; + const vivid: RGB = [1, 0, 0]; + const paleOut = applyAdjust(pale, { ...DEFAULT_ADJUST, vibrance: 100 }); + const vividOut = applyAdjust(vivid, { ...DEFAULT_ADJUST, vibrance: 100 }); + expect(paleOut[0] - paleOut[1]).toBeGreaterThan(pale[0] - pale[1]); + expect(near(vividOut[0], 1)).toBe(true); + }); + + it("always returns values within 0..1", () => { + const out = applyAdjust([1, 1, 1], { + ...DEFAULT_ADJUST, + exposure: 5, + contrast: 100, + saturation: 100, + }); + out.forEach((v) => { + expect(v).toBeGreaterThanOrEqual(0); + expect(v).toBeLessThanOrEqual(1); + }); + }); +}); + +describe("srgb conversions", () => { + it("round-trips", () => { + for (const v of [0, 0.01, 0.2, 0.5, 0.9, 1]) { + expect(near(linearToSrgb(srgbToLinear(v)), v, 1e-6)).toBe(true); + } + }); +}); diff --git a/apps/app/web/features/editor/adjust-math.ts b/apps/app/web/features/editor/adjust-math.ts new file mode 100644 index 0000000..59c7950 --- /dev/null +++ b/apps/app/web/features/editor/adjust-math.ts @@ -0,0 +1,90 @@ +import type { AdjustV1 } from "@prismtone/shared/recipe"; + +/** + * 補正パイプラインの CPU 参照実装。 + * GLSL (render/adjust-filter.ts) はこの関数と同じ式を実装する。 + * 単体テストと、Playwright での GPU 出力との照合に使う (docs/design/04 §4)。 + */ + +export type RGB = readonly [number, number, number]; + +export function srgbToLinear(c: number): number { + return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4); +} + +export function linearToSrgb(c: number): number { + return c <= 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 1 / 2.4) - 0.055; +} + +const clamp01 = (v: number) => Math.min(1, Math.max(0, v)); +const smoothstep = (e0: number, e1: number, x: number) => { + const t = clamp01((x - e0) / (e1 - e0)); + return t * t * (3 - 2 * t); +}; +const mix = (a: number, b: number, t: number) => a + (b - a) * t; + +/** レシピの値域 (-100..100 / EV) をシェーダ用の正規化値に変換する。 */ +export function normalizeAdjust(a: AdjustV1) { + return { + exposure: a.exposure, + contrast: a.contrast / 100, + highlights: a.highlights / 100, + shadows: a.shadows / 100, + temperature: a.temperature / 100, + tint: a.tint / 100, + vibrance: a.vibrance / 100, + saturation: a.saturation / 100, + }; +} + +export type NormalizedAdjust = ReturnType; + +export function applyAdjust(input: RGB, adjust: AdjustV1): RGB { + const u = normalizeAdjust(adjust); + + // --- linear 空間 --- + let r = srgbToLinear(input[0]); + let g = srgbToLinear(input[1]); + let b = srgbToLinear(input[2]); + + const gain = Math.pow(2, u.exposure); + r *= gain; + g *= gain; + b *= gain; + + r *= 1 + 0.25 * u.temperature; + b *= 1 - 0.25 * u.temperature; + g *= 1 - 0.25 * u.tint; + + const luma = 0.2126 * r + 0.7152 * g + 0.0722 * b; + const wh = smoothstep(0.3, 1.0, luma); + const ws = 1 - smoothstep(0.0, 0.5, luma); + const hs = (1 + u.highlights * 0.5 * wh) * (1 + u.shadows * 0.5 * ws); + r *= hs; + g *= hs; + b *= hs; + + // --- sRGB 空間 --- + r = linearToSrgb(clamp01(r)); + g = linearToSrgb(clamp01(g)); + b = linearToSrgb(clamp01(b)); + + const cf = 1 + u.contrast * 0.8; + r = (r - 0.5) * cf + 0.5; + g = (g - 0.5) * cf + 0.5; + b = (b - 0.5) * cf + 0.5; + + const y = 0.299 * r + 0.587 * g + 0.114 * b; + const sat = Math.max(r, g, b) - Math.min(r, g, b); + const vf = 1 + u.vibrance * (1 - clamp01(sat)); + r = mix(y, r, vf); + g = mix(y, g, vf); + b = mix(y, b, vf); + + const sf = 1 + u.saturation; + r = mix(y, r, sf); + g = mix(y, g, sf); + b = mix(y, b, sf); + + return [clamp01(r), clamp01(g), clamp01(b)]; +} diff --git a/apps/app/web/features/editor/drafts.ts b/apps/app/web/features/editor/drafts.ts new file mode 100644 index 0000000..caa41af --- /dev/null +++ b/apps/app/web/features/editor/drafts.ts @@ -0,0 +1,71 @@ +import { createStore, del, get, keys, set } from "idb-keyval"; +import type { EditRecipe } from "@prismtone/shared/recipe"; + +/** + * 端末内の下書き (docs/design/04 §6, 03 §9)。原本 Blob とレシピを IndexedDB に置く。 + * 最大 5 件、古いものから消す。別端末には同期しない。 + */ +export type Draft = { + id: string; + name: string; + blob: Blob; + recipe: EditRecipe; + updatedAt: number; +}; + +/** 投稿導線へ渡す書き出し結果。 */ +export type PendingExport = { + draftId: string; + blob: Blob; + recipe: EditRecipe; + createdAt: number; +}; + +export const DRAFT_LIMIT = 5; +const PENDING_KEY = "pending"; + +const store = () => createStore("prismtone-editor", "kv"); + +export async function saveDraft(draft: Draft): Promise { + const s = store(); + await set(`draft:${draft.id}`, draft, s); + const all = (await keys(s)).filter( + (k): k is string => typeof k === "string" && k.startsWith("draft:"), + ); + if (all.length > DRAFT_LIMIT) { + const drafts = await Promise.all(all.map((k) => get(k, s))); + const stale = drafts + .filter((d): d is Draft => Boolean(d)) + .sort((a, b) => a.updatedAt - b.updatedAt) + .slice(0, drafts.length - DRAFT_LIMIT); + await Promise.all(stale.map((d) => del(`draft:${d.id}`, s))); + } +} + +export async function loadDraft(id: string): Promise { + return get(`draft:${id}`, store()); +} + +export async function listDrafts(): Promise { + const s = store(); + const all = (await keys(s)).filter( + (k): k is string => typeof k === "string" && k.startsWith("draft:"), + ); + const drafts = await Promise.all(all.map((k) => get(k, s))); + return drafts.filter((d): d is Draft => Boolean(d)).sort((a, b) => b.updatedAt - a.updatedAt); +} + +export async function deleteDraft(id: string): Promise { + await del(`draft:${id}`, store()); +} + +export async function setPendingExport(p: PendingExport): Promise { + await set(PENDING_KEY, p, store()); +} + +export async function takePendingExport(): Promise { + const s = store(); + const p = await get(PENDING_KEY, s); + if (p) await del(PENDING_KEY, s); + return p; +} diff --git a/apps/app/web/features/editor/history.test.ts b/apps/app/web/features/editor/history.test.ts new file mode 100644 index 0000000..99d0e88 --- /dev/null +++ b/apps/app/web/features/editor/history.test.ts @@ -0,0 +1,77 @@ +import { describe, expect, it } from "vitest"; +import { DEFAULT_RECIPE, type EditRecipe } from "@prismtone/shared/recipe"; +import { + canRedo, + canUndo, + commit, + createHistory, + HISTORY_LIMIT, + preview, + redo, + undo, +} from "./history.ts"; + +const withExposure = (r: EditRecipe, exposure: number): EditRecipe => ({ + ...r, + adjust: { ...r.adjust, exposure }, +}); + +describe("history", () => { + it("starts with nothing to undo or redo", () => { + const h = createHistory(DEFAULT_RECIPE); + expect(canUndo(h)).toBe(false); + expect(canRedo(h)).toBe(false); + expect(undo(h)).toBe(h); + expect(redo(h)).toBe(h); + }); + + it("preview does not create history entries", () => { + const h = preview(createHistory(DEFAULT_RECIPE), withExposure(DEFAULT_RECIPE, 1)); + expect(h.present.adjust.exposure).toBe(1); + expect(canUndo(h)).toBe(false); + }); + + it("commit then undo then redo round-trips", () => { + const a = DEFAULT_RECIPE; + const b = withExposure(a, 1); + const c = withExposure(a, 2); + let h = commit(commit(createHistory(a), b), c); + expect(h.present).toBe(c); + h = undo(h); + expect(h.present).toBe(b); + expect(canRedo(h)).toBe(true); + h = undo(h); + expect(h.present).toBe(a); + h = redo(h); + expect(h.present).toBe(b); + }); + + it("commit after undo discards the redo stack", () => { + const a = DEFAULT_RECIPE; + let h = commit(createHistory(a), withExposure(a, 1)); + h = undo(h); + h = commit(h, withExposure(a, -1)); + expect(canRedo(h)).toBe(false); + expect(h.present.adjust.exposure).toBe(-1); + }); + + it("commit with the same object is a no-op", () => { + const h = createHistory(DEFAULT_RECIPE); + expect(commit(h, DEFAULT_RECIPE)).toBe(h); + }); + + it("caps history length", () => { + let h = createHistory(DEFAULT_RECIPE); + for (let i = 1; i <= HISTORY_LIMIT + 10; i++) + h = commit(h, withExposure(DEFAULT_RECIPE, i / 100)); + expect(h.past.length).toBe(HISTORY_LIMIT); + }); + + it("never mutates previous states", () => { + const h0 = createHistory(DEFAULT_RECIPE); + const h1 = commit(h0, withExposure(DEFAULT_RECIPE, 1)); + expect(h0.past).toEqual([]); + expect(h0.present).toBe(DEFAULT_RECIPE); + expect(h1.past).not.toBe(h0.past); + }); +}); diff --git a/apps/app/web/features/editor/history.ts b/apps/app/web/features/editor/history.ts new file mode 100644 index 0000000..f6ccb52 --- /dev/null +++ b/apps/app/web/features/editor/history.ts @@ -0,0 +1,44 @@ +import type { EditRecipe } from "@prismtone/shared/recipe"; + +/** + * undo / redo の履歴。レシピは不変オブジェクトとして扱い、常に新しい History を返す + * (docs/design/04 §3)。 + */ +export type History = { + readonly past: readonly EditRecipe[]; + readonly present: EditRecipe; + readonly future: readonly EditRecipe[]; +}; + +export const HISTORY_LIMIT = 100; + +export function createHistory(present: EditRecipe): History { + return { past: [], present, future: [] }; +} + +/** 履歴に積まずに present だけ置き換える (スライダーのドラッグ中)。 */ +export function preview(h: History, next: EditRecipe): History { + return { ...h, present: next }; +} + +/** present を履歴に積んで next を現在にする (ドラッグ終了、プリセット適用、リセット)。 */ +export function commit(h: History, next: EditRecipe): History { + if (next === h.present) return h; + const past = [...h.past, h.present].slice(-HISTORY_LIMIT); + return { past, present: next, future: [] }; +} + +export function undo(h: History): History { + const prev = h.past.at(-1); + if (!prev) return h; + return { past: h.past.slice(0, -1), present: prev, future: [h.present, ...h.future] }; +} + +export function redo(h: History): History { + const [next, ...rest] = h.future; + if (!next) return h; + return { past: [...h.past, h.present], present: next, future: rest }; +} + +export const canUndo = (h: History) => h.past.length > 0; +export const canRedo = (h: History) => h.future.length > 0; diff --git a/apps/app/web/features/editor/image-format.test.ts b/apps/app/web/features/editor/image-format.test.ts new file mode 100644 index 0000000..93b230c --- /dev/null +++ b/apps/app/web/features/editor/image-format.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from "vitest"; +import { + fitWithin, + MAX_UPLOAD_BYTES, + sniffImageFormat, + validateImageFile, +} from "./image-format.ts"; + +const png = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0]); +const jpeg = new Uint8Array([0xff, 0xd8, 0xff, 0xe0, 0, 0]); +const webp = new Uint8Array([0x52, 0x49, 0x46, 0x46, 0, 0, 0, 0, 0x57, 0x45, 0x42, 0x50]); + +describe("sniffImageFormat", () => { + it("detects png and jpeg by magic bytes", () => { + expect(sniffImageFormat(png)).toBe("png"); + expect(sniffImageFormat(jpeg)).toBe("jpeg"); + }); + it("rejects other formats and short input", () => { + expect(sniffImageFormat(webp)).toBeNull(); + expect(sniffImageFormat(new Uint8Array([0xff]))).toBeNull(); + }); +}); + +describe("validateImageFile", () => { + it("rejects oversized files first", () => { + expect(validateImageFile(MAX_UPLOAD_BYTES + 1, png)).toBe("too_large"); + }); + it("rejects unsupported formats", () => { + expect(validateImageFile(100, webp)).toBe("unsupported_format"); + }); + it("accepts a png under the limit", () => { + expect(validateImageFile(MAX_UPLOAD_BYTES, png)).toBeNull(); + }); +}); + +describe("fitWithin", () => { + it("keeps images under the limit unchanged", () => { + expect(fitWithin(1920, 1080, 4096)).toEqual({ width: 1920, height: 1080 }); + }); + it("scales the long edge down to the limit", () => { + expect(fitWithin(5120, 2880, 4096)).toEqual({ width: 4096, height: 2304 }); + expect(fitWithin(2880, 5120, 4096)).toEqual({ width: 2304, height: 4096 }); + }); +}); diff --git a/apps/app/web/features/editor/image-format.ts b/apps/app/web/features/editor/image-format.ts new file mode 100644 index 0000000..fb04d46 --- /dev/null +++ b/apps/app/web/features/editor/image-format.ts @@ -0,0 +1,33 @@ +/** 拡張子ではなく先頭バイトで画像形式を判定する (docs/design/09 §2)。 */ +export type ImageFormat = "png" | "jpeg"; + +export const MAX_UPLOAD_BYTES = 30 * 1024 * 1024; +export const MAX_EDIT_EDGE = 4096; + +const PNG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]; + +export function sniffImageFormat(head: Uint8Array): ImageFormat | null { + if (head.length >= 8 && PNG.every((b, i) => head[i] === b)) return "png"; + if (head.length >= 3 && head[0] === 0xff && head[1] === 0xd8 && head[2] === 0xff) return "jpeg"; + return null; +} + +export type ValidationError = "too_large" | "unsupported_format"; + +export function validateImageFile(size: number, head: Uint8Array): ValidationError | null { + if (size > MAX_UPLOAD_BYTES) return "too_large"; + if (!sniffImageFormat(head)) return "unsupported_format"; + return null; +} + +/** 長辺が max を超える場合の縮小後サイズ。超えなければそのまま。 */ +export function fitWithin( + width: number, + height: number, + max: number, +): { width: number; height: number } { + const edge = Math.max(width, height); + if (edge <= max) return { width, height }; + const s = max / edge; + return { width: Math.round(width * s), height: Math.round(height * s) }; +} diff --git a/apps/app/web/features/editor/load-image.ts b/apps/app/web/features/editor/load-image.ts new file mode 100644 index 0000000..2971f4f --- /dev/null +++ b/apps/app/web/features/editor/load-image.ts @@ -0,0 +1,57 @@ +import { + fitWithin, + MAX_EDIT_EDGE, + sniffImageFormat, + validateImageFile, + type ValidationError, +} from "./image-format.ts"; + +export type LoadedImage = { + bitmap: ImageBitmap; + blob: Blob; + name: string; + format: "png" | "jpeg"; + original: { width: number; height: number }; +}; + +export class ImageLoadError extends Error { + readonly reason: ValidationError | "decode_failed"; + constructor(reason: ValidationError | "decode_failed") { + super(reason); + this.name = "ImageLoadError"; + this.reason = reason; + } +} + +/** + * ファイルを検証してデコードし、長辺 4096px に収めた ImageBitmap を返す (docs/design/08 §3.2)。 + * EXIF の回転はここで解決する。 + */ +export async function loadImageFile(file: File): Promise { + const head = new Uint8Array(await file.slice(0, 16).arrayBuffer()); + const invalid = validateImageFile(file.size, head); + if (invalid) throw new ImageLoadError(invalid); + const format = sniffImageFormat(head); + if (!format) throw new ImageLoadError("unsupported_format"); + + let bitmap: ImageBitmap; + try { + bitmap = await createImageBitmap(file, { imageOrientation: "from-image" }); + } catch { + throw new ImageLoadError("decode_failed"); + } + + const original = { width: bitmap.width, height: bitmap.height }; + const fitted = fitWithin(bitmap.width, bitmap.height, MAX_EDIT_EDGE); + if (fitted.width !== bitmap.width || fitted.height !== bitmap.height) { + const canvas = new OffscreenCanvas(fitted.width, fitted.height); + const ctx = canvas.getContext("2d"); + if (!ctx) throw new ImageLoadError("decode_failed"); + ctx.imageSmoothingQuality = "high"; + ctx.drawImage(bitmap, 0, 0, fitted.width, fitted.height); + bitmap.close(); + bitmap = await createImageBitmap(canvas); + } + + return { bitmap, blob: file, name: file.name, format, original }; +} diff --git a/apps/app/web/features/editor/render/adjust-filter.ts b/apps/app/web/features/editor/render/adjust-filter.ts new file mode 100644 index 0000000..ec68a8e --- /dev/null +++ b/apps/app/web/features/editor/render/adjust-filter.ts @@ -0,0 +1,138 @@ +import { Filter, GlProgram } from "pixi.js"; +import type { AdjustV1 } from "@prismtone/shared/recipe"; +import { normalizeAdjust } from "../adjust-math.ts"; + +// adjust-math.ts の CPU 実装と同じ式。片方を変えたら必ずもう片方も変える。 + +const vertex = /* glsl */ ` +in vec2 aPosition; +out vec2 vTextureCoord; + +uniform vec4 uInputSize; +uniform vec4 uOutputFrame; +uniform vec4 uOutputTexture; + +vec4 filterVertexPosition(void) { + vec2 position = aPosition * uOutputFrame.zw + uOutputFrame.xy; + position.x = position.x * (2.0 / uOutputTexture.x) - 1.0; + position.y = position.y * (2.0 * uOutputTexture.z / uOutputTexture.y) - uOutputTexture.z; + return vec4(position, 0.0, 1.0); +} + +vec2 filterTextureCoord(void) { + return aPosition * (uOutputFrame.zw * uInputSize.zw); +} + +void main(void) { + gl_Position = filterVertexPosition(); + vTextureCoord = filterTextureCoord(); +} +`; + +const fragment = /* glsl */ ` +precision highp float; + +in vec2 vTextureCoord; +out vec4 finalColor; + +uniform sampler2D uTexture; + +uniform float uExposure; +uniform float uContrast; +uniform float uHighlights; +uniform float uShadows; +uniform float uTemperature; +uniform float uTint; +uniform float uVibrance; +uniform float uSaturation; + +vec3 srgbToLinear(vec3 c) { + vec3 lo = c / 12.92; + vec3 hi = pow((c + 0.055) / 1.055, vec3(2.4)); + return mix(lo, hi, step(0.04045, c)); +} + +vec3 linearToSrgb(vec3 c) { + vec3 lo = c * 12.92; + vec3 hi = 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055; + return mix(lo, hi, step(0.0031308, c)); +} + +void main(void) { + vec4 src = texture(uTexture, vTextureCoord); + // premultiplied alpha を戻す + vec3 rgb = src.a > 0.0 ? src.rgb / src.a : src.rgb; + + // --- linear --- + rgb = srgbToLinear(rgb); + rgb *= exp2(uExposure); + rgb.r *= 1.0 + 0.25 * uTemperature; + rgb.b *= 1.0 - 0.25 * uTemperature; + rgb.g *= 1.0 - 0.25 * uTint; + + float luma = dot(rgb, vec3(0.2126, 0.7152, 0.0722)); + float wh = smoothstep(0.3, 1.0, luma); + float ws = 1.0 - smoothstep(0.0, 0.5, luma); + rgb *= (1.0 + uHighlights * 0.5 * wh) * (1.0 + uShadows * 0.5 * ws); + + // --- sRGB --- + rgb = linearToSrgb(clamp(rgb, 0.0, 1.0)); + + float cf = 1.0 + uContrast * 0.8; + rgb = (rgb - 0.5) * cf + 0.5; + + float y = dot(rgb, vec3(0.299, 0.587, 0.114)); + float sat = max(rgb.r, max(rgb.g, rgb.b)) - min(rgb.r, min(rgb.g, rgb.b)); + float vf = 1.0 + uVibrance * (1.0 - clamp(sat, 0.0, 1.0)); + rgb = mix(vec3(y), rgb, vf); + rgb = mix(vec3(y), rgb, 1.0 + uSaturation); + + rgb = clamp(rgb, 0.0, 1.0); + finalColor = vec4(rgb * src.a, src.a); +} +`; + +export type AdjustUniforms = { + uExposure: { value: number; type: "f32" }; + uContrast: { value: number; type: "f32" }; + uHighlights: { value: number; type: "f32" }; + uShadows: { value: number; type: "f32" }; + uTemperature: { value: number; type: "f32" }; + uTint: { value: number; type: "f32" }; + uVibrance: { value: number; type: "f32" }; + uSaturation: { value: number; type: "f32" }; +}; + +export class AdjustFilter extends Filter { + constructor(adjust: AdjustV1) { + const n = normalizeAdjust(adjust); + super({ + glProgram: GlProgram.from({ vertex, fragment, name: "prismtone-adjust" }), + resources: { + adjustUniforms: { + uExposure: { value: n.exposure, type: "f32" }, + uContrast: { value: n.contrast, type: "f32" }, + uHighlights: { value: n.highlights, type: "f32" }, + uShadows: { value: n.shadows, type: "f32" }, + uTemperature: { value: n.temperature, type: "f32" }, + uTint: { value: n.tint, type: "f32" }, + uVibrance: { value: n.vibrance, type: "f32" }, + uSaturation: { value: n.saturation, type: "f32" }, + } satisfies AdjustUniforms, + }, + }); + } + + setAdjust(adjust: AdjustV1): void { + const n = normalizeAdjust(adjust); + const u = this.resources.adjustUniforms.uniforms as Record; + u.uExposure = n.exposure; + u.uContrast = n.contrast; + u.uHighlights = n.highlights; + u.uShadows = n.shadows; + u.uTemperature = n.temperature; + u.uTint = n.tint; + u.uVibrance = n.vibrance; + u.uSaturation = n.saturation; + } +} diff --git a/apps/app/web/features/editor/render/editor-renderer.ts b/apps/app/web/features/editor/render/editor-renderer.ts new file mode 100644 index 0000000..0b93293 --- /dev/null +++ b/apps/app/web/features/editor/render/editor-renderer.ts @@ -0,0 +1,185 @@ +import { Application, Container, Rectangle, Sprite, Texture } from "pixi.js"; +import type { EditRecipe, GeometryV1 } from "@prismtone/shared/recipe"; +import { AdjustFilter } from "./adjust-filter.ts"; +import { canvasSize, cropRect, exportScale, totalRotationDeg, type Size } from "./geometry.ts"; + +export type ExportFormat = "image/webp" | "image/jpeg"; + +export type ExportOptions = { + format?: ExportFormat; + quality?: number; + maxEdge?: number; +}; + +export const EXPORT_MAX_EDGE = 4096; + +/** + * PixiJS による編集プレビューと書き出し (docs/design/08 §3.3-3.4, ADR-0005)。 + * - Sprite 1 枚に AdjustFilter 1 つ。補正はすべて 1 パス + * - 幾何 (回転・反転) は Container の transform、crop は書き出し時の frame + * - プレビューは幾何適用後のキャンバス全体を表示し、crop 枠は DOM 側で描く + */ +export class EditorRenderer { + private readonly app: Application; + private readonly host: HTMLElement; + + private constructor(app: Application, host: HTMLElement) { + this.app = app; + this.host = host; + } + + private readonly stage = new Container(); + private readonly image = new Container(); + private sprite: Sprite | null = null; + private filter: AdjustFilter | null = null; + private source: Size = { width: 1, height: 1 }; + private geometry: GeometryV1 | null = null; + private comparing = false; + private resizeObserver: ResizeObserver | null = null; + + static async create(host: HTMLElement): Promise { + const app = new Application(); + await app.init({ + resizeTo: host, + backgroundAlpha: 0, + antialias: true, + autoDensity: true, + resolution: Math.min(window.devicePixelRatio || 1, 2), + preference: "webgl", + }); + host.appendChild(app.canvas); + const r = new EditorRenderer(app, host); + app.stage.addChild(r.stage); + r.stage.addChild(r.image); + r.resizeObserver = new ResizeObserver(() => r.fit()); + r.resizeObserver.observe(host); + return r; + } + + get canvasElement(): HTMLCanvasElement { + return this.app.canvas as HTMLCanvasElement; + } + + setImage(bitmap: ImageBitmap, recipe: EditRecipe): void { + this.clearImage(); + const texture = Texture.from(bitmap); + const sprite = new Sprite(texture); + sprite.anchor.set(0.5); + this.sprite = sprite; + this.source = { width: bitmap.width, height: bitmap.height }; + this.filter = new AdjustFilter(recipe.adjust); + sprite.filters = [this.filter]; + this.image.addChild(sprite); + this.setRecipe(recipe); + } + + private clearImage(): void { + if (this.sprite) { + this.image.removeChild(this.sprite); + this.sprite.destroy({ texture: true, textureSource: true }); + this.sprite = null; + } + this.filter?.destroy(); + this.filter = null; + } + + setRecipe(recipe: EditRecipe): void { + if (!this.sprite || !this.filter) return; + this.filter.setAdjust(recipe.adjust); + this.geometry = recipe.geometry; + const size = canvasSize(this.source, recipe.geometry); + this.sprite.rotation = (totalRotationDeg(recipe.geometry) * Math.PI) / 180; + this.sprite.scale.set(recipe.geometry.flipH ? -1 : 1, 1); + this.sprite.position.set(size.width / 2, size.height / 2); + this.fit(); + } + + setCompare(on: boolean): void { + this.comparing = on; + if (this.sprite) this.sprite.filters = on || !this.filter ? [] : [this.filter]; + } + + /** 幾何適用後のキャンバスサイズ (crop 前)。DOM の crop 枠の基準になる。 */ + get canvasSize(): Size { + return this.geometry ? canvasSize(this.source, this.geometry) : this.source; + } + + /** ホスト内でキャンバスが占める矩形 (CSS px)。DOM オーバーレイの配置に使う。 */ + get viewRect(): { x: number; y: number; width: number; height: number; scale: number } { + const size = this.canvasSize; + const s = this.stage.scale.x; + return { + x: this.stage.x, + y: this.stage.y, + width: size.width * s, + height: size.height * s, + scale: s, + }; + } + + fit(): void { + if (!this.sprite) return; + const size = this.canvasSize; + const w = this.host.clientWidth; + const h = this.host.clientHeight; + if (w === 0 || h === 0) return; + const s = Math.min(w / size.width, h / size.height) * 0.96; + this.stage.scale.set(s); + this.stage.position.set((w - size.width * s) / 2, (h - size.height * s) / 2); + } + + async export(recipe: EditRecipe, opts: ExportOptions = {}): Promise { + if (!this.sprite) throw new Error("no image loaded"); + const wasComparing = this.comparing; + this.setCompare(false); + this.setRecipe(recipe); + + const full = this.canvasSize; + const rect = cropRect(full, recipe.geometry); + const scale = exportScale(rect, opts.maxEdge ?? EXPORT_MAX_EDGE); + + // 表示用のスケールを外し、原寸で描く + const saved = { x: this.stage.x, y: this.stage.y, s: this.stage.scale.x }; + this.stage.scale.set(1); + this.stage.position.set(0, 0); + try { + const canvas = this.app.renderer.extract.canvas({ + target: this.image, + frame: new Rectangle(rect.x, rect.y, rect.width, rect.height), + resolution: scale, + clearColor: "#000000", + }) as HTMLCanvasElement; + const format = opts.format ?? ((await supportsWebp()) ? "image/webp" : "image/jpeg"); + return await toBlob(canvas, format, opts.quality ?? 0.92); + } finally { + this.stage.scale.set(saved.s); + this.stage.position.set(saved.x, saved.y); + this.setCompare(wasComparing); + } + } + + destroy(): void { + this.resizeObserver?.disconnect(); + this.clearImage(); + this.app.destroy(true, { children: true }); + } +} + +function toBlob(canvas: HTMLCanvasElement, type: string, quality: number): Promise { + return new Promise((resolve, reject) => { + canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("toBlob failed"))), type, quality); + }); +} + +let webpSupport: Promise | null = null; +export function supportsWebp(): Promise { + if (!webpSupport) { + webpSupport = new Promise((resolve) => { + const c = document.createElement("canvas"); + c.width = 1; + c.height = 1; + c.toBlob((b) => resolve(b?.type === "image/webp"), "image/webp"); + }); + } + return webpSupport; +} diff --git a/apps/app/web/features/editor/render/geometry.test.ts b/apps/app/web/features/editor/render/geometry.test.ts new file mode 100644 index 0000000..9e3bef4 --- /dev/null +++ b/apps/app/web/features/editor/render/geometry.test.ts @@ -0,0 +1,75 @@ +import { describe, expect, it } from "vitest"; +import { DEFAULT_GEOMETRY } from "@prismtone/shared/recipe"; +import { + aspectRatio, + canvasSize, + centeredCrop, + cropRect, + exportScale, + rotatedBounds, +} from "./geometry.ts"; + +describe("rotatedBounds", () => { + it("swaps width and height at 90 degrees", () => { + expect(rotatedBounds({ width: 1920, height: 1080 }, 90)).toEqual({ width: 1080, height: 1920 }); + }); + it("is unchanged at 0 and 180", () => { + expect(rotatedBounds({ width: 1920, height: 1080 }, 0)).toEqual({ width: 1920, height: 1080 }); + expect(rotatedBounds({ width: 1920, height: 1080 }, 180)).toEqual({ + width: 1920, + height: 1080, + }); + }); + it("grows for small straighten angles", () => { + const b = rotatedBounds({ width: 1000, height: 1000 }, 10); + expect(b.width).toBeGreaterThan(1000); + expect(b.height).toBeGreaterThan(1000); + }); +}); + +describe("canvasSize / cropRect", () => { + const src = { width: 1920, height: 1080 }; + it("uses the whole canvas without crop", () => { + expect(cropRect(canvasSize(src, DEFAULT_GEOMETRY), DEFAULT_GEOMETRY)).toEqual({ + x: 0, + y: 0, + width: 1920, + height: 1080, + }); + }); + it("converts normalized crop to pixels and clamps to the canvas", () => { + const g = { ...DEFAULT_GEOMETRY, crop: { x: 0.5, y: 0.5, w: 0.75, h: 0.75 } }; + expect(cropRect(src, g)).toEqual({ x: 960, y: 540, width: 960, height: 540 }); + }); + it("never yields a zero-sized rect", () => { + const g = { ...DEFAULT_GEOMETRY, crop: { x: 0, y: 0, w: 0, h: 0 } }; + const r = cropRect(src, g); + expect(r.width).toBeGreaterThanOrEqual(1); + expect(r.height).toBeGreaterThanOrEqual(1); + }); +}); + +describe("aspect helpers", () => { + it("parses ratios", () => { + expect(aspectRatio("16:9")).toBeCloseTo(16 / 9); + expect(aspectRatio("free")).toBeUndefined(); + expect(aspectRatio(null)).toBeUndefined(); + }); + it("centers a 1:1 crop inside a landscape canvas", () => { + const c = centeredCrop({ width: 1920, height: 1080 }, 1); + expect(c.h).toBe(1); + expect(c.w).toBeCloseTo(1080 / 1920); + expect(c.x).toBeCloseTo((1 - 1080 / 1920) / 2); + }); + it("centers a 9:16 crop inside a landscape canvas", () => { + const c = centeredCrop({ width: 1920, height: 1080 }, 9 / 16); + expect(c.h).toBe(1); + expect(c.w).toBeCloseTo(9 / 16 / (1920 / 1080)); + }); +}); + +describe("exportScale", () => { + it("does not upscale", () => expect(exportScale({ width: 100, height: 50 }, 4096)).toBe(1)); + it("scales the long edge to the max", () => + expect(exportScale({ width: 8192, height: 100 }, 4096)).toBe(0.5)); +}); diff --git a/apps/app/web/features/editor/render/geometry.ts b/apps/app/web/features/editor/render/geometry.ts new file mode 100644 index 0000000..87c4357 --- /dev/null +++ b/apps/app/web/features/editor/render/geometry.ts @@ -0,0 +1,72 @@ +import type { GeometryV1 } from "@prismtone/shared/recipe"; + +/** + * 幾何変換の純粋な計算部分。PixiJS には依存しない (単体テスト対象)。 + * 座標系: 回転・水平補正・反転を適用した後の「キャンバス」上で crop を 0..1 の正規化座標として持つ。 + */ + +export type Size = { width: number; height: number }; +export type Rect = { x: number; y: number; width: number; height: number }; + +/** 直角回転と微調整回転を合わせた角度 (度)。 */ +export function totalRotationDeg(g: GeometryV1): number { + return g.rotation + g.straighten; +} + +/** 元画像を angle 度回転したときの外接矩形サイズ。 */ +export function rotatedBounds(src: Size, angleDeg: number): Size { + const rad = (angleDeg * Math.PI) / 180; + const c = Math.abs(Math.cos(rad)); + const s = Math.abs(Math.sin(rad)); + return { + width: Math.round(src.width * c + src.height * s), + height: Math.round(src.width * s + src.height * c), + }; +} + +/** 幾何適用後のキャンバスサイズ (crop 前)。 */ +export function canvasSize(src: Size, g: GeometryV1): Size { + return rotatedBounds(src, totalRotationDeg(g)); +} + +/** crop を実ピクセルの矩形にする。crop が無ければキャンバス全体。 */ +export function cropRect(canvas: Size, g: GeometryV1): Rect { + if (!g.crop) return { x: 0, y: 0, width: canvas.width, height: canvas.height }; + const x = Math.round(g.crop.x * canvas.width); + const y = Math.round(g.crop.y * canvas.height); + const width = Math.max(1, Math.round(g.crop.w * canvas.width)); + const height = Math.max(1, Math.round(g.crop.h * canvas.height)); + return { + x, + y, + width: Math.min(width, canvas.width - x), + height: Math.min(height, canvas.height - y), + }; +} + +/** アスペクト指定文字列 ("16:9" 等) を比率に変換する。free / null は undefined。 */ +export function aspectRatio(aspect: GeometryV1["aspect"]): number | undefined { + if (!aspect || aspect === "free") return undefined; + const [w, h] = aspect.split(":").map(Number); + if (!w || !h) return undefined; + return w / h; +} + +/** 指定比率でキャンバス中央に収まる最大の crop (正規化座標)。 */ +export function centeredCrop(canvas: Size, ratio: number): NonNullable { + const canvasRatio = canvas.width / canvas.height; + let w = 1; + let h = 1; + if (ratio > canvasRatio) { + h = canvasRatio / ratio; + } else { + w = ratio / canvasRatio; + } + return { x: (1 - w) / 2, y: (1 - h) / 2, w, h }; +} + +/** 出力サイズを長辺 maxEdge に収めるスケール。 */ +export function exportScale(rect: Size, maxEdge: number): number { + const edge = Math.max(rect.width, rect.height); + return edge > maxEdge ? maxEdge / edge : 1; +} diff --git a/apps/app/web/features/editor/state.test.ts b/apps/app/web/features/editor/state.test.ts new file mode 100644 index 0000000..18d6f4a --- /dev/null +++ b/apps/app/web/features/editor/state.test.ts @@ -0,0 +1,70 @@ +import { describe, expect, it } from "vitest"; +import { DEFAULT_RECIPE } from "@prismtone/shared/recipe"; +import { editorReducer, initialEditorState, type EditorState } from "./state.ts"; + +const loaded: EditorState = editorReducer(initialEditorState, { + type: "image/loaded", + draftId: "d1", + image: { + bitmap: {} as ImageBitmap, + blob: new Blob(), + name: "a.png", + format: "png", + original: { width: 1, height: 1 }, + }, +}); + +describe("editorReducer", () => { + it("drag preview does not add history, commit adds exactly one entry with the pre-drag base", () => { + let s = loaded; + s = editorReducer(s, { type: "adjust/preview", key: "exposure", value: 0.5 }); + s = editorReducer(s, { type: "adjust/preview", key: "exposure", value: 1 }); + s = editorReducer(s, { type: "adjust/preview", key: "exposure", value: 1.5 }); + expect(s.history.past).toHaveLength(0); + expect(s.history.present.adjust.exposure).toBe(1.5); + s = editorReducer(s, { type: "adjust/commit", key: "exposure", value: 1.5 }); + expect(s.history.past).toHaveLength(1); + expect(s.history.past[0]).toBe(DEFAULT_RECIPE); + expect(s.dragBase).toBeNull(); + s = editorReducer(s, { type: "history/undo" }); + expect(s.history.present.adjust.exposure).toBe(0); + }); + + it("applying a preset records presetId and is undoable", () => { + let s = editorReducer(loaded, { type: "preset/apply", id: "mono" }); + expect(s.history.present.presetId).toBe("mono"); + expect(s.history.present.adjust.saturation).toBe(-100); + s = editorReducer(s, { type: "history/undo" }); + expect(s.history.present).toBe(DEFAULT_RECIPE); + }); + + it("manual adjust after a preset clears presetId", () => { + let s = editorReducer(loaded, { type: "preset/apply", id: "mono" }); + s = editorReducer(s, { type: "adjust/commit", key: "contrast", value: 10 }); + expect(s.history.present.presetId).toBeNull(); + expect(s.history.present.adjust.saturation).toBe(-100); + }); + + it("reset returns to defaults as one undoable step", () => { + let s = editorReducer(loaded, { type: "preset/apply", id: "vivid" }); + s = editorReducer(s, { type: "geometry/commit", patch: { rotation: 90 } }); + s = editorReducer(s, { type: "recipe/reset" }); + expect(s.history.present).toBe(DEFAULT_RECIPE); + s = editorReducer(s, { type: "history/undo" }); + expect(s.history.present.geometry.rotation).toBe(90); + }); + + it("ignores unknown preset ids", () => { + const s = editorReducer(loaded, { type: "preset/apply", id: "nope" }); + expect(s).toBe(loaded); + }); + + it("loading a new image resets history and clears errors", () => { + let s = editorReducer(loaded, { type: "ui/error", error: "x" }); + s = editorReducer(s, { type: "preset/apply", id: "film" }); + s = editorReducer(s, { type: "image/loaded", draftId: "d2", image: loaded.source! }); + expect(s.history.past).toHaveLength(0); + expect(s.ui.error).toBeNull(); + expect(s.draftId).toBe("d2"); + }); +}); diff --git a/apps/app/web/features/editor/state.ts b/apps/app/web/features/editor/state.ts new file mode 100644 index 0000000..bb9ae33 --- /dev/null +++ b/apps/app/web/features/editor/state.ts @@ -0,0 +1,124 @@ +import { + DEFAULT_RECIPE, + applyPreset, + findPreset, + type AdjustV1, + type EditRecipe, + type GeometryV1, +} from "@prismtone/shared/recipe"; +import { commit, createHistory, preview, redo, undo, type History } from "./history.ts"; +import type { LoadedImage } from "./load-image.ts"; + +export type Tool = "adjust" | "geometry" | "presets"; + +export type EditorState = { + readonly source: LoadedImage | null; + readonly draftId: string | null; + readonly history: History; + /** スライダーのドラッグ開始時点のレシピ。commit 時にこれを履歴に積む。 */ + readonly dragBase: EditRecipe | null; + readonly ui: { + readonly tool: Tool; + readonly comparing: boolean; + readonly cropping: boolean; + readonly exporting: boolean; + readonly error: string | null; + }; +}; + +export type EditorAction = + | { type: "image/loaded"; image: LoadedImage; draftId: string; recipe?: EditRecipe } + | { type: "image/failed"; error: string } + | { type: "adjust/preview"; key: keyof AdjustV1; value: number } + | { type: "adjust/commit"; key: keyof AdjustV1; value: number } + | { type: "geometry/commit"; patch: Partial } + | { type: "geometry/preview"; patch: Partial } + | { type: "preset/apply"; id: string } + | { type: "recipe/reset" } + | { type: "history/undo" } + | { type: "history/redo" } + | { type: "ui/tool"; tool: Tool } + | { type: "ui/compare"; on: boolean } + | { type: "ui/cropping"; on: boolean } + | { type: "ui/exporting"; on: boolean } + | { type: "ui/error"; error: string | null }; + +export const initialEditorState: EditorState = { + source: null, + draftId: null, + history: createHistory(DEFAULT_RECIPE), + dragBase: null, + ui: { tool: "presets", comparing: false, cropping: false, exporting: false, error: null }, +}; + +const withAdjust = (r: EditRecipe, key: keyof AdjustV1, value: number): EditRecipe => ({ + ...r, + presetId: null, + adjust: { ...r.adjust, [key]: value }, +}); + +const withGeometry = (r: EditRecipe, patch: Partial): EditRecipe => ({ + ...r, + geometry: { ...r.geometry, ...patch }, +}); + +export function editorReducer(state: EditorState, action: EditorAction): EditorState { + const { history } = state; + switch (action.type) { + case "image/loaded": + return { + ...state, + source: action.image, + draftId: action.draftId, + history: createHistory(action.recipe ?? DEFAULT_RECIPE), + dragBase: null, + ui: { ...state.ui, error: null, cropping: false }, + }; + case "image/failed": + return { ...state, ui: { ...state.ui, error: action.error } }; + case "adjust/preview": + return { + ...state, + dragBase: state.dragBase ?? history.present, + history: preview(history, withAdjust(history.present, action.key, action.value)), + }; + case "adjust/commit": { + // ドラッグ中の preview は履歴に積まない。ドラッグ開始時点 (dragBase) を積む + const base = state.dragBase ?? history.present; + const next = withAdjust(base, action.key, action.value); + return { ...state, dragBase: null, history: commit({ ...history, present: base }, next) }; + } + case "geometry/preview": + return { + ...state, + dragBase: state.dragBase ?? history.present, + history: preview(history, withGeometry(history.present, action.patch)), + }; + case "geometry/commit": { + const base = state.dragBase ?? history.present; + const next = withGeometry(base, action.patch); + return { ...state, dragBase: null, history: commit({ ...history, present: base }, next) }; + } + case "preset/apply": { + const preset = findPreset(action.id); + if (!preset) return state; + return { ...state, history: commit(history, applyPreset(history.present, preset)) }; + } + case "recipe/reset": + return { ...state, history: commit(history, DEFAULT_RECIPE) }; + case "history/undo": + return { ...state, history: undo(history) }; + case "history/redo": + return { ...state, history: redo(history) }; + case "ui/tool": + return { ...state, ui: { ...state.ui, tool: action.tool } }; + case "ui/compare": + return { ...state, ui: { ...state.ui, comparing: action.on } }; + case "ui/cropping": + return { ...state, ui: { ...state.ui, cropping: action.on } }; + case "ui/exporting": + return { ...state, ui: { ...state.ui, exporting: action.on } }; + case "ui/error": + return { ...state, ui: { ...state.ui, error: action.error } }; + } +} diff --git a/apps/app/web/features/editor/ui/AdjustPanel.tsx b/apps/app/web/features/editor/ui/AdjustPanel.tsx new file mode 100644 index 0000000..de43948 --- /dev/null +++ b/apps/app/web/features/editor/ui/AdjustPanel.tsx @@ -0,0 +1,49 @@ +import type { AdjustV1 } from "@prismtone/shared/recipe"; +import { Slider } from "./Slider.tsx"; + +type Props = { + adjust: AdjustV1; + onPreview: (key: keyof AdjustV1, value: number) => void; + onCommit: (key: keyof AdjustV1, value: number) => void; +}; + +const ROWS: { + key: keyof AdjustV1; + label: string; + min: number; + max: number; + step: number; + ev?: boolean; +}[] = [ + { key: "exposure", label: "露光量", min: -5, max: 5, step: 0.05, ev: true }, + { key: "contrast", label: "コントラスト", min: -100, max: 100, step: 1 }, + { key: "highlights", label: "ハイライト", min: -100, max: 100, step: 1 }, + { key: "shadows", label: "シャドウ", min: -100, max: 100, step: 1 }, + { key: "temperature", label: "色温度", min: -100, max: 100, step: 1 }, + { key: "tint", label: "色かぶり", min: -100, max: 100, step: 1 }, + { key: "vibrance", label: "自然な彩度", min: -100, max: 100, step: 1 }, + { key: "saturation", label: "彩度", min: -100, max: 100, step: 1 }, +]; + +export function AdjustPanel({ adjust, onPreview, onCommit }: Props) { + return ( +
+ {ROWS.map((r) => ( + `${v >= 0 ? "+" : ""}${v.toFixed(2)}` : (v) => `${v > 0 ? "+" : ""}${v}` + } + onPreview={(v) => onPreview(r.key, v)} + onCommit={(v) => onCommit(r.key, v)} + onReset={() => onCommit(r.key, 0)} + /> + ))} +
+ ); +} diff --git a/apps/app/web/features/editor/ui/CropOverlay.tsx b/apps/app/web/features/editor/ui/CropOverlay.tsx new file mode 100644 index 0000000..72f82d0 --- /dev/null +++ b/apps/app/web/features/editor/ui/CropOverlay.tsx @@ -0,0 +1,115 @@ +import { useRef } from "react"; +import type { GeometryV1 } from "@prismtone/shared/recipe"; +import { dragCrop, type Crop, type Handle } from "./crop-drag.ts"; + +type Props = { + view: { x: number; y: number; width: number; height: number }; + crop: Crop; + aspect: GeometryV1["aspect"]; + canvasRatio: number; + onPreview: (crop: Crop) => void; + onCommit: (crop: Crop) => void; +}; + +const HANDLES: { h: Handle; cls: string; cursor: string }[] = [ + { h: "nw", cls: "-left-1.5 -top-1.5", cursor: "nwse-resize" }, + { h: "ne", cls: "-right-1.5 -top-1.5", cursor: "nesw-resize" }, + { h: "sw", cls: "-left-1.5 -bottom-1.5", cursor: "nesw-resize" }, + { h: "se", cls: "-right-1.5 -bottom-1.5", cursor: "nwse-resize" }, + { h: "n", cls: "left-1/2 -top-1.5 -translate-x-1/2", cursor: "ns-resize" }, + { h: "s", cls: "left-1/2 -bottom-1.5 -translate-x-1/2", cursor: "ns-resize" }, + { h: "w", cls: "-left-1.5 top-1/2 -translate-y-1/2", cursor: "ew-resize" }, + { h: "e", cls: "-right-1.5 top-1/2 -translate-y-1/2", cursor: "ew-resize" }, +]; + +function ratioOf(aspect: GeometryV1["aspect"], canvasRatio: number): number | undefined { + if (!aspect || aspect === "free") return undefined; + const [w, h] = aspect.split(":").map(Number); + if (!w || !h) return undefined; + return w / h / canvasRatio; +} + +/** DOM で描く crop 枠 (docs/design/08 §3.3)。ドラッグ中は onPreview、離したら onCommit。 */ +export function CropOverlay({ view, crop, aspect, canvasRatio, onPreview, onCommit }: Props) { + const drag = useRef<{ handle: Handle; start: Crop; sx: number; sy: number } | null>(null); + const ratio = ratioOf(aspect, canvasRatio); + + const onPointerDown = (handle: Handle) => (e: React.PointerEvent) => { + e.preventDefault(); + e.stopPropagation(); + (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId); + drag.current = { handle, start: crop, sx: e.clientX, sy: e.clientY }; + }; + const onPointerMove = (e: React.PointerEvent) => { + const d = drag.current; + if (!d) return; + const next = dragCrop( + d.start, + d.handle, + (e.clientX - d.sx) / view.width, + (e.clientY - d.sy) / view.height, + ratio, + ); + onPreview(next); + }; + const onPointerUp = (e: React.PointerEvent) => { + const d = drag.current; + if (!d) return; + drag.current = null; + const next = dragCrop( + d.start, + d.handle, + (e.clientX - d.sx) / view.width, + (e.clientY - d.sy) / view.height, + ratio, + ); + onCommit(next); + }; + + const box = { + left: view.x + crop.x * view.width, + top: view.y + crop.y * view.height, + width: crop.w * view.width, + height: crop.h * view.height, + }; + + return ( +
+
+
+
+ {Array.from({ length: 9 }, (_, i) => ( +
+ ))} +
+ {HANDLES.map(({ h, cls, cursor }) => ( +
+ ))} +
+
+ ); +} diff --git a/apps/app/web/features/editor/ui/EditorPage.tsx b/apps/app/web/features/editor/ui/EditorPage.tsx new file mode 100644 index 0000000..821b8c7 --- /dev/null +++ b/apps/app/web/features/editor/ui/EditorPage.tsx @@ -0,0 +1,386 @@ +import { useCallback, useEffect, useReducer, useRef, useState } from "react"; +import { useNavigate } from "react-router"; +import type { EditRecipe } from "@prismtone/shared/recipe"; +import { editorReducer, initialEditorState } from "../state.ts"; +import { canRedo, canUndo } from "../history.ts"; +import { ImageLoadError, loadImageFile } from "../load-image.ts"; +import { saveDraft, setPendingExport } from "../drafts.ts"; +import { aspectRatio, centeredCrop } from "../render/geometry.ts"; +import type { EditorRenderer } from "../render/editor-renderer.ts"; +import { AdjustPanel } from "./AdjustPanel.tsx"; +import { PresetPanel } from "./PresetPanel.tsx"; +import { GeometryPanel } from "./GeometryPanel.tsx"; +import { CropOverlay } from "./CropOverlay.tsx"; + +const ERROR_TEXT: Record = { + too_large: "30MB を超える画像は読み込めません。", + unsupported_format: "PNG または JPEG の画像を選んでください。", + decode_failed: "画像を読み込めませんでした。", + webgl: "このブラウザでは編集機能を使えません (WebGL が無効です)。", +}; + +const tabBtn = + "px-3 py-1.5 text-sm border-b-2 border-transparent aria-selected:border-zinc-900 dark:aria-selected:border-zinc-100"; +const toolBtn = + "rounded border border-zinc-200 px-3 py-1.5 text-sm hover:bg-zinc-100 disabled:opacity-40 disabled:hover:bg-transparent dark:border-zinc-800 dark:hover:bg-zinc-900"; + +/** Playwright からレシピ適用結果の画素を読むためのフック。E2E フラグがあるときだけ露出する。 */ +function installTestHook(renderer: EditorRenderer) { + const w = window as Window & { __PRISMTONE_E2E__?: boolean; __prismtoneEditor?: unknown }; + if (!w.__PRISMTONE_E2E__) return; + w.__prismtoneEditor = { + async exportPixels(recipe: EditRecipe, points: { x: number; y: number }[]) { + const blob = await renderer.export(recipe, { format: "image/png" }); + const bitmap = await createImageBitmap(blob); + const c = new OffscreenCanvas(bitmap.width, bitmap.height); + const ctx = c.getContext("2d"); + if (!ctx) throw new Error("no 2d context"); + ctx.drawImage(bitmap, 0, 0); + return { + width: bitmap.width, + height: bitmap.height, + type: blob.type, + pixels: points.map((p) => Array.from(ctx.getImageData(p.x, p.y, 1, 1).data).slice(0, 3)), + }; + }, + }; +} + +export function EditorPage() { + const [state, dispatch] = useReducer(editorReducer, initialEditorState); + const navigate = useNavigate(); + const hostRef = useRef(null); + const rendererRef = useRef(null); + const fileInput = useRef(null); + const [view, setView] = useState({ x: 0, y: 0, width: 1, height: 1, scale: 1 }); + const [ready, setReady] = useState(false); + + const recipe = state.history.present; + + // PixiJS は SSR 不可なので動的 import (docs/design/08 §1) + useEffect(() => { + let disposed = false; + let renderer: EditorRenderer | null = null; + (async () => { + const host = hostRef.current; + if (!host) return; + try { + const { EditorRenderer } = await import("../render/editor-renderer.ts"); + renderer = await EditorRenderer.create(host); + if (disposed) { + renderer.destroy(); + return; + } + rendererRef.current = renderer; + setReady(true); + installTestHook(renderer); + } catch { + dispatch({ type: "ui/error", error: ERROR_TEXT.webgl ?? "WebGL error" }); + } + })(); + return () => { + disposed = true; + rendererRef.current = null; + renderer?.destroy(); + }; + }, []); + + // レシピ変更をレンダラへ反映 + useEffect(() => { + const r = rendererRef.current; + if (!r || !state.source) return; + r.setRecipe(recipe); + setView(r.viewRect); + }, [recipe, state.source]); + + useEffect(() => { + rendererRef.current?.setCompare(state.ui.comparing); + }, [state.ui.comparing]); + + // リサイズで枠位置を追従 + useEffect(() => { + const host = hostRef.current; + if (!host) return; + const ro = new ResizeObserver(() => { + const r = rendererRef.current; + if (r && state.source) setView(r.viewRect); + }); + ro.observe(host); + return () => ro.disconnect(); + }, [state.source]); + + // 下書きを自動保存 (レシピ確定ごと) + useEffect(() => { + if (!state.source || !state.draftId) return; + const { source, draftId } = state; + void saveDraft({ + id: draftId, + name: source.name, + blob: source.blob, + recipe, + updatedAt: Date.now(), + }); + }, [state.source, state.draftId, recipe, state]); + + const openFile = useCallback(async (file: File) => { + try { + const image = await loadImageFile(file); + const draftId = crypto.randomUUID(); + const r = rendererRef.current; + dispatch({ type: "image/loaded", image, draftId }); + if (r) { + r.setImage(image.bitmap, initialEditorState.history.present); + setView(r.viewRect); + } + } catch (e) { + const reason = e instanceof ImageLoadError ? e.reason : "decode_failed"; + dispatch({ type: "image/failed", error: ERROR_TEXT[reason] ?? reason }); + } + }, []); + + // 画像が後から来た場合 (レンダラ初期化前に読み込んだ) の反映 + useEffect(() => { + const r = rendererRef.current; + if (ready && r && state.source) { + r.setImage(state.source.bitmap, recipe); + setView(r.viewRect); + } + // recipe は setRecipe 側の effect で追従するため依存に含めない + }, [ready, state.source]); + + const exportBlob = useCallback(async (r: EditRecipe) => { + const renderer = rendererRef.current; + if (!renderer) throw new Error("renderer not ready"); + dispatch({ type: "ui/exporting", on: true }); + try { + return await renderer.export(r); + } finally { + dispatch({ type: "ui/exporting", on: false }); + } + }, []); + + const onSave = async () => { + if (!state.source) return; + try { + const blob = await exportBlob(recipe); + const ext = blob.type === "image/webp" ? "webp" : "jpg"; + const base = state.source.name.replace(/\.[^.]+$/, ""); + const a = document.createElement("a"); + a.href = URL.createObjectURL(blob); + a.download = `${base}-prismtone.${ext}`; + a.click(); + setTimeout(() => URL.revokeObjectURL(a.href), 10_000); + } catch { + dispatch({ type: "ui/error", error: "書き出しに失敗しました。" }); + } + }; + + const onPost = async () => { + if (!state.source || !state.draftId) return; + try { + const blob = await exportBlob(recipe); + await setPendingExport({ draftId: state.draftId, blob, recipe, createdAt: Date.now() }); + void navigate("/edit/post"); + } catch { + dispatch({ type: "ui/error", error: "書き出しに失敗しました。" }); + } + }; + + const onAspect = (aspect: EditRecipe["geometry"]["aspect"]) => { + const r = rendererRef.current; + const ratio = aspectRatio(aspect); + const crop = ratio && r ? centeredCrop(r.canvasSize, ratio) : recipe.geometry.crop; + dispatch({ + type: "geometry/commit", + patch: { aspect, crop: aspect === "free" ? recipe.geometry.crop : crop }, + }); + if (aspect !== "free") dispatch({ type: "ui/cropping", on: true }); + }; + + const startCropping = (on: boolean) => { + if (on && !recipe.geometry.crop) { + dispatch({ type: "geometry/commit", patch: { crop: { x: 0.1, y: 0.1, w: 0.8, h: 0.8 } } }); + } + dispatch({ type: "ui/cropping", on }); + }; + + // キーボード: Ctrl+Z / Ctrl+Shift+Z / Ctrl+Y + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if (!(e.ctrlKey || e.metaKey)) return; + if (e.key === "z" && !e.shiftKey) { + e.preventDefault(); + dispatch({ type: "history/undo" }); + } else if ((e.key === "z" && e.shiftKey) || e.key === "y") { + e.preventDefault(); + dispatch({ type: "history/redo" }); + } + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, []); + + const hasImage = Boolean(state.source); + const canvasRatio = rendererRef.current + ? rendererRef.current.canvasSize.width / rendererRef.current.canvasSize.height + : 1; + + return ( +
+
+
+ { + const f = e.currentTarget.files?.[0]; + if (f) void openFile(f); + e.currentTarget.value = ""; + }} + /> + + + + + + + + +
+ {state.ui.error && ( +

+ {state.ui.error} +

+ )} +
e.preventDefault()} + onDrop={(e) => { + e.preventDefault(); + const f = e.dataTransfer.files[0]; + if (f) void openFile(f); + }} + > + {!hasImage && ( +

+ PNG / JPEG をドロップするか「画像を開く」を押してください +

+ )} + {hasImage && state.ui.cropping && recipe.geometry.crop && ( + dispatch({ type: "geometry/preview", patch: { crop } })} + onCommit={(crop) => dispatch({ type: "geometry/commit", patch: { crop } })} + /> + )} +
+
+ + +
+ ); +} diff --git a/apps/app/web/features/editor/ui/GeometryPanel.tsx b/apps/app/web/features/editor/ui/GeometryPanel.tsx new file mode 100644 index 0000000..45cff73 --- /dev/null +++ b/apps/app/web/features/editor/ui/GeometryPanel.tsx @@ -0,0 +1,105 @@ +import { ASPECT_PRESETS, type GeometryV1 } from "@prismtone/shared/recipe"; +import { Slider } from "./Slider.tsx"; + +type Props = { + geometry: GeometryV1; + cropping: boolean; + onPreview: (patch: Partial) => void; + onCommit: (patch: Partial) => void; + onCropping: (on: boolean) => void; + onAspect: (aspect: GeometryV1["aspect"]) => void; +}; + +const ASPECT_LABEL: Record<(typeof ASPECT_PRESETS)[number], string> = { + free: "自由", + "1:1": "1:1", + "4:3": "4:3", + "3:2": "3:2", + "16:9": "16:9", + "9:16": "9:16", + "3:4": "3:4", + "2:3": "2:3", +}; + +const btn = + "rounded border border-zinc-200 px-3 py-1.5 text-sm hover:bg-zinc-100 dark:border-zinc-800 dark:hover:bg-zinc-900 aria-pressed:bg-zinc-900 aria-pressed:text-white dark:aria-pressed:bg-zinc-100 dark:aria-pressed:text-zinc-900"; + +export function GeometryPanel({ + geometry, + cropping, + onPreview, + onCommit, + onCropping, + onAspect, +}: Props) { + const rotate = (delta: 90 | -90) => { + const next = (((geometry.rotation + delta) % 360) + 360) % 360; + onCommit({ rotation: next as GeometryV1["rotation"], crop: null }); + }; + return ( +
+
+ + + +
+ `${v.toFixed(1)}°`} + onPreview={(v) => onPreview({ straighten: v })} + onCommit={(v) => onCommit({ straighten: v })} + onReset={() => onCommit({ straighten: 0 })} + /> +
+

アスペクト比

+
+ {ASPECT_PRESETS.map((a) => ( + + ))} +
+
+
+ + {geometry.crop && ( + + )} +
+
+ ); +} diff --git a/apps/app/web/features/editor/ui/PresetPanel.tsx b/apps/app/web/features/editor/ui/PresetPanel.tsx new file mode 100644 index 0000000..8d495ab --- /dev/null +++ b/apps/app/web/features/editor/ui/PresetPanel.tsx @@ -0,0 +1,32 @@ +import { PRESETS } from "@prismtone/shared/recipe"; + +type Props = { + activeId: string | null; + onApply: (id: string) => void; +}; + +export function PresetPanel({ activeId, onApply }: Props) { + return ( +
+ {PRESETS.map((p) => { + const active = p.id === activeId; + return ( + + ); + })} +
+ ); +} diff --git a/apps/app/web/features/editor/ui/Slider.tsx b/apps/app/web/features/editor/ui/Slider.tsx new file mode 100644 index 0000000..fd9ab28 --- /dev/null +++ b/apps/app/web/features/editor/ui/Slider.tsx @@ -0,0 +1,95 @@ +import { useId } from "react"; + +type Props = { + label: string; + value: number; + min: number; + max: number; + step: number; + format?: (v: number) => string; + onPreview: (v: number) => void; + onCommit: (v: number) => void; + onReset?: () => void; +}; + +/** + * 補正用スライダー。ドラッグ中は onPreview、離したら onCommit (docs/design/04 §3)。 + * キーボード操作は矢印で step、Shift+矢印で 10 step (docs/design/08 §6)。 + */ +export function Slider({ + label, + value, + min, + max, + step, + format, + onPreview, + onCommit, + onReset, +}: Props) { + const id = useId(); + const text = format ? format(value) : String(value); + return ( +
+ + onPreview(Number(e.currentTarget.value))} + onPointerUp={(e) => onCommit(Number(e.currentTarget.value))} + onKeyDown={(e) => { + if ( + ![ + "ArrowLeft", + "ArrowRight", + "ArrowUp", + "ArrowDown", + "Home", + "End", + "PageUp", + "PageDown", + ].includes(e.key) + ) + return; + if (e.shiftKey && (e.key === "ArrowLeft" || e.key === "ArrowRight")) { + e.preventDefault(); + const dir = e.key === "ArrowRight" ? 1 : -1; + const next = Math.min(max, Math.max(min, value + dir * step * 10)); + onCommit(next); + } + }} + onKeyUp={(e) => { + if ( + [ + "ArrowLeft", + "ArrowRight", + "ArrowUp", + "ArrowDown", + "Home", + "End", + "PageUp", + "PageDown", + ].includes(e.key) + ) { + onCommit(Number(e.currentTarget.value)); + } + }} + /> + + {text} + +
+ ); +} diff --git a/apps/app/web/features/editor/ui/crop-drag.test.ts b/apps/app/web/features/editor/ui/crop-drag.test.ts new file mode 100644 index 0000000..0a9c35e --- /dev/null +++ b/apps/app/web/features/editor/ui/crop-drag.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from "vitest"; +import { dragCrop } from "./crop-drag.ts"; + +const full = { x: 0, y: 0, w: 1, h: 1 }; +const mid = { x: 0.25, y: 0.25, w: 0.5, h: 0.5 }; + +describe("dragCrop", () => { + it("moves within bounds", () => { + expect(dragCrop(mid, "move", 0.1, -0.1)).toEqual({ x: 0.35, y: 0.15, w: 0.5, h: 0.5 }); + expect(dragCrop(mid, "move", 1, 1)).toEqual({ x: 0.5, y: 0.5, w: 0.5, h: 0.5 }); + }); + + it("resizes from the east edge without moving the west edge", () => { + const r = dragCrop(mid, "e", 0.1, 0); + expect(r.x).toBe(0.25); + expect(r.w).toBeCloseTo(0.6); + }); + + it("keeps a minimum size", () => { + const r = dragCrop(mid, "e", -1, 0); + expect(r.w).toBeCloseTo(0.05); + }); + + it("locks ratio when resizing a corner", () => { + const r = dragCrop(full, "se", -0.5, 0, 1); + expect(r.w).toBeCloseTo(r.h); + expect(r.x).toBe(0); + expect(r.y).toBe(0); + }); + + it("locked ratio never exceeds the canvas", () => { + const r = dragCrop({ x: 0.5, y: 0.5, w: 0.4, h: 0.4 }, "se", 0.5, 0.5, 1); + expect(r.x + r.w).toBeLessThanOrEqual(1 + 1e-9); + expect(r.y + r.h).toBeLessThanOrEqual(1 + 1e-9); + }); +}); diff --git a/apps/app/web/features/editor/ui/crop-drag.ts b/apps/app/web/features/editor/ui/crop-drag.ts new file mode 100644 index 0000000..e9837f1 --- /dev/null +++ b/apps/app/web/features/editor/ui/crop-drag.ts @@ -0,0 +1,73 @@ +import type { GeometryV1 } from "@prismtone/shared/recipe"; + +export type Crop = NonNullable; +export type Handle = "move" | "n" | "s" | "e" | "w" | "ne" | "nw" | "se" | "sw"; + +const MIN = 0.05; +const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v)); + +/** + * crop 枠のドラッグ計算 (正規化座標、純粋関数)。 + * ratio は「キャンバス座標系での w/h 比」= (目的の比率) / (キャンバスの比率)。 + */ +export function dragCrop( + start: Crop, + handle: Handle, + dx: number, + dy: number, + ratio?: number, +): Crop { + if (handle === "move") { + return { + ...start, + x: clamp(start.x + dx, 0, 1 - start.w), + y: clamp(start.y + dy, 0, 1 - start.h), + }; + } + + let x0 = start.x; + let y0 = start.y; + let x1 = start.x + start.w; + let y1 = start.y + start.h; + + if (handle.includes("w")) x0 = clamp(x0 + dx, 0, x1 - MIN); + if (handle.includes("e")) x1 = clamp(x1 + dx, x0 + MIN, 1); + if (handle.includes("n")) y0 = clamp(y0 + dy, 0, y1 - MIN); + if (handle.includes("s")) y1 = clamp(y1 + dy, y0 + MIN, 1); + + if (ratio) { + // 幅を優先し、高さを比率から決める。固定辺 (アンカー) は動かした辺の反対側 + let w = x1 - x0; + let h = w / ratio; + const horizontalOnly = handle === "e" || handle === "w"; + const verticalOnly = handle === "n" || handle === "s"; + if (verticalOnly) { + h = y1 - y0; + w = h * ratio; + } + // はみ出すなら縮める + const anchorX = handle.includes("w") ? x1 : x0; + const anchorY = handle.includes("n") ? y1 : y0; + const maxW = handle.includes("w") ? anchorX : 1 - anchorX; + const maxH = handle.includes("n") ? anchorY : 1 - anchorY; + if (w > maxW) { + w = maxW; + h = w / ratio; + } + if (h > maxH) { + h = maxH; + w = h * ratio; + } + if (horizontalOnly || !verticalOnly) { + x0 = handle.includes("w") ? anchorX - w : anchorX; + y0 = handle.includes("n") ? anchorY - h : anchorY; + } else { + y0 = handle.includes("n") ? anchorY - h : anchorY; + x0 = handle.includes("w") ? anchorX - w : anchorX; + } + x1 = x0 + w; + y1 = y0 + h; + } + + return { x: x0, y: y0, w: x1 - x0, h: y1 - y0 }; +} diff --git a/e2e/editor.spec.ts b/e2e/editor.spec.ts new file mode 100644 index 0000000..6cfd5b8 --- /dev/null +++ b/e2e/editor.spec.ts @@ -0,0 +1,186 @@ +import { expect, test, type Page } from "@playwright/test"; +import { DEFAULT_RECIPE, applyPreset, findPreset, type EditRecipe } from "@prismtone/shared/recipe"; +import { applyAdjust } from "../apps/app/web/features/editor/adjust-math.ts"; + +// 4 色のブロックからなるテスト画像 (200x100)。左から赤・緑・青・灰 +const BLOCKS: [number, number, number][] = [ + [200, 40, 60], + [40, 180, 80], + [50, 90, 220], + [128, 128, 128], +]; + +async function makePng(page: Page): Promise { + const dataUrl = await page.evaluate((blocks) => { + const c = document.createElement("canvas"); + c.width = 200; + c.height = 100; + const ctx = c.getContext("2d")!; + blocks.forEach(([r, g, b], i) => { + ctx.fillStyle = `rgb(${r},${g},${b})`; + ctx.fillRect(i * 50, 0, 50, 100); + }); + return c.toDataURL("image/png"); + }, BLOCKS); + return Buffer.from(dataUrl.split(",")[1]!, "base64"); +} + +async function openEditorWithImage(page: Page) { + await page.addInitScript(() => { + (window as Window & { __PRISMTONE_E2E__?: boolean }).__PRISMTONE_E2E__ = true; + }); + await page.goto("/edit"); + await expect(page.getByRole("button", { name: "画像を開く" })).toBeVisible(); + const png = await makePng(page); + await page + .getByTestId("file-input") + .setInputFiles({ name: "test.png", mimeType: "image/png", buffer: png }); + await expect(page.getByRole("button", { name: "端末に保存" })).toBeEnabled(); + await page.waitForFunction(() => + Boolean((window as Window & { __prismtoneEditor?: unknown }).__prismtoneEditor), + ); +} + +type Pixels = { width: number; height: number; type: string; pixels: number[][] }; + +async function exportPixels( + page: Page, + recipe: EditRecipe, + points: { x: number; y: number }[], +): Promise { + return page.evaluate( + ({ recipe, points }) => + ( + window as Window & { + __prismtoneEditor?: { + exportPixels: (r: EditRecipe, p: { x: number; y: number }[]) => Promise; + }; + } + ).__prismtoneEditor!.exportPixels(recipe, points), + { recipe, points }, + ); +} + +const CENTERS = BLOCKS.map((_, i) => ({ x: i * 50 + 25, y: 50 })); + +function expectClose(actual: number[], expected: number[], tolerance: number) { + actual.forEach((v, i) => + expect( + Math.abs(v - expected[i]!), + `channel ${i}: ${actual} vs ${expected}`, + ).toBeLessThanOrEqual(tolerance), + ); +} + +test.describe("editor", () => { + test("default recipe exports the source pixels unchanged", async ({ page }) => { + await openEditorWithImage(page); + const out = await exportPixels(page, DEFAULT_RECIPE, CENTERS); + expect(out.width).toBe(200); + expect(out.height).toBe(100); + out.pixels.forEach((px, i) => expectClose(px, BLOCKS[i]!, 2)); + }); + + test("GPU output matches the CPU reference for every preset", async ({ page }) => { + await openEditorWithImage(page); + const { PRESETS } = await import("@prismtone/shared/recipe"); + for (const preset of PRESETS) { + const recipe = applyPreset(DEFAULT_RECIPE, preset); + const out = await exportPixels(page, recipe, CENTERS); + out.pixels.forEach((px, i) => { + const src = BLOCKS[i]!.map((v) => v / 255) as [number, number, number]; + const expected = applyAdjust(src, recipe.adjust).map((v) => Math.round(v * 255)); + expectClose(px, expected, 3); + }); + } + }); + + test("saturation -100 yields neutral gray, exposure +1 doubles linear light", async ({ + page, + }) => { + await openEditorWithImage(page); + const mono = applyPreset(DEFAULT_RECIPE, findPreset("mono")!); + const gray = await exportPixels( + page, + { ...mono, adjust: { ...mono.adjust, contrast: 0 } }, + CENTERS, + ); + for (const [r, g, b] of gray.pixels) { + expect(Math.abs(r! - g!)).toBeLessThanOrEqual(2); + expect(Math.abs(g! - b!)).toBeLessThanOrEqual(2); + } + const bright = await exportPixels( + page, + { ...DEFAULT_RECIPE, adjust: { ...DEFAULT_RECIPE.adjust, exposure: 1 } }, + [CENTERS[3]!], + ); + // 128/255 -> linear 0.2158 -> x2 = 0.4317 -> sRGB 0.6906 -> 176 + expectClose(bright.pixels[0]!, [176, 176, 176], 3); + }); + + test("geometry: rotation and crop change the output size", async ({ page }) => { + await openEditorWithImage(page); + const rotated: EditRecipe = { + ...DEFAULT_RECIPE, + geometry: { ...DEFAULT_RECIPE.geometry, rotation: 90 }, + }; + const r = await exportPixels(page, rotated, [{ x: 50, y: 25 }]); + expect(r.width).toBe(100); + expect(r.height).toBe(200); + // 右回転後: 元の左端 (赤) は上端に来る + expectClose(r.pixels[0]!, BLOCKS[0]!, 2); + + const cropped: EditRecipe = { + ...DEFAULT_RECIPE, + geometry: { ...DEFAULT_RECIPE.geometry, crop: { x: 0.5, y: 0, w: 0.5, h: 1 } }, + }; + const c = await exportPixels(page, cropped, [ + { x: 25, y: 50 }, + { x: 75, y: 50 }, + ]); + expect(c.width).toBe(100); + expectClose(c.pixels[0]!, BLOCKS[2]!, 2); + expectClose(c.pixels[1]!, BLOCKS[3]!, 2); + }); + + test("preset, undo, redo and reset drive the UI", async ({ page }) => { + await openEditorWithImage(page); + await page.getByRole("button", { name: "モノクロ" }).click(); + await expect(page.getByRole("button", { name: "モノクロ" })).toHaveAttribute( + "aria-pressed", + "true", + ); + await expect(page.getByRole("button", { name: "取り消し" })).toBeEnabled(); + await page.getByRole("button", { name: "取り消し" }).click(); + await expect(page.getByRole("button", { name: "モノクロ" })).toHaveAttribute( + "aria-pressed", + "false", + ); + await page.getByRole("button", { name: "やり直し" }).click(); + await expect(page.getByRole("button", { name: "モノクロ" })).toHaveAttribute( + "aria-pressed", + "true", + ); + await page.getByRole("button", { name: "全リセット" }).click(); + await expect(page.getByRole("button", { name: "モノクロ" })).toHaveAttribute( + "aria-pressed", + "false", + ); + }); + + test("save downloads an image file", async ({ page }) => { + await openEditorWithImage(page); + const download = page.waitForEvent("download"); + await page.getByTestId("save").click(); + const d = await download; + expect(d.suggestedFilename()).toMatch(/^test-prismtone\.(webp|jpg)$/); + }); + + test("rejects non-image files with a message", async ({ page }) => { + await page.goto("/edit"); + await page + .getByTestId("file-input") + .setInputFiles({ name: "x.png", mimeType: "image/png", buffer: Buffer.from("not a png") }); + await expect(page.getByRole("alert")).toContainText("PNG または JPEG"); + }); +}); From c7a1f41d124e99f6bfea54d5c6d37500e8cb966b Mon Sep 17 00:00:00 2001 From: t1nyb0x Date: Sun, 13 Sep 2026 14:57:36 +0900 Subject: [PATCH 03/49] =?UTF-8?q?fix(editor):=20ExportFormat=20=E3=81=AB?= =?UTF-8?q?=20image/png=20=E3=82=92=E8=A8=B1=E5=8F=AF=20(E2E=20=E3=83=95?= =?UTF-8?q?=E3=83=83=E3=82=AF=E3=81=A7=E4=BD=BF=E7=94=A8)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5 --- apps/app/web/features/editor/render/editor-renderer.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/app/web/features/editor/render/editor-renderer.ts b/apps/app/web/features/editor/render/editor-renderer.ts index 0b93293..d5167fa 100644 --- a/apps/app/web/features/editor/render/editor-renderer.ts +++ b/apps/app/web/features/editor/render/editor-renderer.ts @@ -3,7 +3,7 @@ import type { EditRecipe, GeometryV1 } from "@prismtone/shared/recipe"; import { AdjustFilter } from "./adjust-filter.ts"; import { canvasSize, cropRect, exportScale, totalRotationDeg, type Size } from "./geometry.ts"; -export type ExportFormat = "image/webp" | "image/jpeg"; +export type ExportFormat = "image/webp" | "image/jpeg" | "image/png"; export type ExportOptions = { format?: ExportFormat; From 706fd1595db3740b24d2ae0d86044bd851e34144 Mon Sep 17 00:00:00 2001 From: t1nyb0x Date: Sun, 13 Sep 2026 16:40:46 +0900 Subject: [PATCH 04/49] =?UTF-8?q?feat:=20M2.1=20=E5=AE=89=E5=AE=9A?= =?UTF-8?q?=E5=8C=96=E3=81=A8=E8=A4=87=E6=95=B0=E7=94=BB=E5=83=8F=E6=8A=95?= =?UTF-8?q?=E7=A8=BF=E3=82=92=E5=AE=9F=E8=A3=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/app/web/features/editor/drafts.test.ts | 30 ++++++++++++++ apps/app/web/features/editor/drafts.ts | 39 ++++++++++++++++--- .../app/web/features/editor/ui/EditorPage.tsx | 11 ++++-- 3 files changed, 70 insertions(+), 10 deletions(-) create mode 100644 apps/app/web/features/editor/drafts.test.ts diff --git a/apps/app/web/features/editor/drafts.test.ts b/apps/app/web/features/editor/drafts.test.ts new file mode 100644 index 0000000..5932d06 --- /dev/null +++ b/apps/app/web/features/editor/drafts.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it } from "vitest"; +import { DEFAULT_RECIPE } from "@prismtone/shared/recipe"; +import { addToPendingExports, PENDING_EXPORT_LIMIT, type PendingExport } from "./drafts.ts"; + +const pending = (draftId: string, createdAt = 1): PendingExport => ({ + draftId, + blob: new Blob([draftId], { type: "image/webp" }), + recipe: DEFAULT_RECIPE, + createdAt, +}); + +describe("addToPendingExports", () => { + it("appends new drafts while preserving order", () => { + expect(addToPendingExports([pending("a")], pending("b")).map((item) => item.draftId)).toEqual([ + "a", + "b", + ]); + }); + + it("replaces another export of the same draft in place", () => { + const result = addToPendingExports([pending("a"), pending("b")], pending("a", 2)); + expect(result.map((item) => item.draftId)).toEqual(["a", "b"]); + expect(result[0]?.createdAt).toBe(2); + }); + + it("rejects more than five different drafts", () => { + const full = Array.from({ length: PENDING_EXPORT_LIMIT }, (_, index) => pending(String(index))); + expect(() => addToPendingExports(full, pending("overflow"))).toThrow("5 枚まで"); + }); +}); diff --git a/apps/app/web/features/editor/drafts.ts b/apps/app/web/features/editor/drafts.ts index caa41af..6e34341 100644 --- a/apps/app/web/features/editor/drafts.ts +++ b/apps/app/web/features/editor/drafts.ts @@ -22,6 +22,7 @@ export type PendingExport = { }; export const DRAFT_LIMIT = 5; +export const PENDING_EXPORT_LIMIT = 5; const PENDING_KEY = "pending"; const store = () => createStore("prismtone-editor", "kv"); @@ -59,13 +60,39 @@ export async function deleteDraft(id: string): Promise { await del(`draft:${id}`, store()); } -export async function setPendingExport(p: PendingExport): Promise { - await set(PENDING_KEY, p, store()); +export function addToPendingExports( + current: readonly PendingExport[], + next: PendingExport, +): PendingExport[] { + const existing = current.findIndex((item) => item.draftId === next.draftId); + if (existing >= 0) return current.map((item, index) => (index === existing ? next : item)); + if (current.length >= PENDING_EXPORT_LIMIT) { + throw new Error(`投稿画像は ${PENDING_EXPORT_LIMIT} 枚までです`); + } + return [...current, next]; } -export async function takePendingExport(): Promise { +/** 旧版の単一オブジェクトも配列へ読み替える。 */ +export async function listPendingExports(): Promise { + const s = store(); + const value = await get(PENDING_KEY, s); + if (!value) return []; + return Array.isArray(value) ? value.slice(0, PENDING_EXPORT_LIMIT) : [value]; +} + +export async function setPendingExports(items: readonly PendingExport[]): Promise { + if (items.length > PENDING_EXPORT_LIMIT) { + throw new Error(`投稿画像は ${PENDING_EXPORT_LIMIT} 枚までです`); + } const s = store(); - const p = await get(PENDING_KEY, s); - if (p) await del(PENDING_KEY, s); - return p; + if (items.length === 0) await del(PENDING_KEY, s); + else await set(PENDING_KEY, [...items], s); +} + +export async function addPendingExport(next: PendingExport): Promise { + await setPendingExports(addToPendingExports(await listPendingExports(), next)); +} + +export async function clearPendingExports(): Promise { + await del(PENDING_KEY, store()); } diff --git a/apps/app/web/features/editor/ui/EditorPage.tsx b/apps/app/web/features/editor/ui/EditorPage.tsx index 821b8c7..11c9f76 100644 --- a/apps/app/web/features/editor/ui/EditorPage.tsx +++ b/apps/app/web/features/editor/ui/EditorPage.tsx @@ -4,7 +4,7 @@ import type { EditRecipe } from "@prismtone/shared/recipe"; import { editorReducer, initialEditorState } from "../state.ts"; import { canRedo, canUndo } from "../history.ts"; import { ImageLoadError, loadImageFile } from "../load-image.ts"; -import { saveDraft, setPendingExport } from "../drafts.ts"; +import { addPendingExport, saveDraft } from "../drafts.ts"; import { aspectRatio, centeredCrop } from "../render/geometry.ts"; import type { EditorRenderer } from "../render/editor-renderer.ts"; import { AdjustPanel } from "./AdjustPanel.tsx"; @@ -179,10 +179,13 @@ export function EditorPage() { if (!state.source || !state.draftId) return; try { const blob = await exportBlob(recipe); - await setPendingExport({ draftId: state.draftId, blob, recipe, createdAt: Date.now() }); + await addPendingExport({ draftId: state.draftId, blob, recipe, createdAt: Date.now() }); void navigate("/edit/post"); - } catch { - dispatch({ type: "ui/error", error: "書き出しに失敗しました。" }); + } catch (error) { + dispatch({ + type: "ui/error", + error: error instanceof Error ? error.message : "書き出しに失敗しました。", + }); } }; From 37bfe0489f28a73b93ed2398a9f200eae6ee2ef6 Mon Sep 17 00:00:00 2001 From: t1nyb0x Date: Mon, 14 Sep 2026 18:56:43 +0900 Subject: [PATCH 05/49] =?UTF-8?q?feat:=20=E9=85=8D=E8=89=B2=E3=82=92?= =?UTF-8?q?=E6=84=8F=E5=91=B3=E4=BB=98=E3=81=8D=E3=83=88=E3=83=BC=E3=82=AF?= =?UTF-8?q?=E3=83=B3=E3=81=AB=E3=81=97=E3=81=A6=E6=9A=96=E8=89=B2=20(stone?= =?UTF-8?q?=20+=20=E7=90=A5=E7=8F=80)=20=E3=81=AB=E5=AF=84=E3=81=9B?= =?UTF-8?q?=E3=82=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 黒一色だった UI を、暖色寄りの無彩色 (stone) の土台と琥珀 (amber) の アクセント一色に変える。色は app.css のトークンでだけ決め、画面側は surface / ink / line / accent の意味名で参照する。zinc-* と dark: の色指定は 画面から無くした。 Web Interface Guidelines に沿って、フォーカスリングを focus-visible で アクセント色に、theme-color meta を追加、ボタンに hover を付け、 読み込み中の "..." を "…" にした。 Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01Mra7aDjdjjEFHUVLbB2b5o --- apps/app/web/features/editor/ui/EditorPage.tsx | 15 +++++++-------- apps/app/web/features/editor/ui/GeometryPanel.tsx | 4 ++-- apps/app/web/features/editor/ui/PresetPanel.tsx | 4 ++-- apps/app/web/features/editor/ui/Slider.tsx | 8 ++------ 4 files changed, 13 insertions(+), 18 deletions(-) diff --git a/apps/app/web/features/editor/ui/EditorPage.tsx b/apps/app/web/features/editor/ui/EditorPage.tsx index 11c9f76..d04bcd8 100644 --- a/apps/app/web/features/editor/ui/EditorPage.tsx +++ b/apps/app/web/features/editor/ui/EditorPage.tsx @@ -19,10 +19,9 @@ const ERROR_TEXT: Record = { webgl: "このブラウザでは編集機能を使えません (WebGL が無効です)。", }; -const tabBtn = - "px-3 py-1.5 text-sm border-b-2 border-transparent aria-selected:border-zinc-900 dark:aria-selected:border-zinc-100"; +const tabBtn = "px-3 py-1.5 text-sm border-b-2 border-transparent aria-selected:border-accent"; const toolBtn = - "rounded border border-zinc-200 px-3 py-1.5 text-sm hover:bg-zinc-100 disabled:opacity-40 disabled:hover:bg-transparent dark:border-zinc-800 dark:hover:bg-zinc-900"; + "rounded border border-line-soft px-3 py-1.5 text-sm hover:bg-surface-hover disabled:opacity-40 disabled:hover:bg-transparent"; /** Playwright からレシピ適用結果の画素を読むためのフック。E2E フラグがあるときだけ露出する。 */ function installTestHook(renderer: EditorRenderer) { @@ -289,11 +288,11 @@ export function EditorPage() { onClick={onSave} data-testid="save" > - {state.ui.exporting ? "書き出し中..." : "端末に保存"} + {state.ui.exporting ? "書き出し中…" : "端末に保存"} + {lastOp && ( + + 最後の操作: {lastOp} + + )}
+ ); +} diff --git a/apps/app/web/features/editor/ui/LocalPanel.tsx b/apps/app/web/features/editor/ui/LocalPanel.tsx new file mode 100644 index 0000000..586c7b4 --- /dev/null +++ b/apps/app/web/features/editor/ui/LocalPanel.tsx @@ -0,0 +1,176 @@ +import { + LOCAL_PRESETS, + MAX_LOCAL_ADJUSTMENTS, + type LocalAdjustV2, + type LocalAdjustmentV2, + type LocalPresetId, +} from "@prismtone/shared/recipe"; +import { LOCAL_ADJUST_LABELS } from "../labels.ts"; +import { Slider } from "./Slider.tsx"; + +type Props = { + list: readonly LocalAdjustmentV2[]; + selectedId: string | null; + showMask: boolean; + onAdd: (presetId?: LocalPresetId) => void; + onSelect: (id: string | null) => void; + onRemove: (id: string) => void; + onToggleVisible: (id: string) => void; + onPreset: (id: string, presetId: LocalPresetId) => void; + onAmountPreview: (id: string, value: number) => void; + onAmountCommit: (id: string, value: number) => void; + onAdjustPreview: (id: string, key: keyof LocalAdjustV2, value: number) => void; + onAdjustCommit: (id: string, key: keyof LocalAdjustV2, value: number) => void; + onShowMask: (on: boolean) => void; +}; + +const ROWS: { key: keyof LocalAdjustV2; min: number; max: number; step: number; ev?: boolean }[] = [ + { key: "exposure", min: -5, max: 5, step: 0.05, ev: true }, + { key: "contrast", min: -100, max: 100, step: 1 }, + { key: "highlights", min: -100, max: 100, step: 1 }, + { key: "shadows", min: -100, max: 100, step: 1 }, + { key: "temperature", min: -100, max: 100, step: 1 }, + { key: "tint", min: -100, max: 100, step: 1 }, + { key: "saturation", min: -100, max: 100, step: 1 }, + // シャープと美肌 (smooth、上限 MAX_LOCAL_SMOOTH) は描画が入る PR3 でここに足す +]; + +const btn = + "rounded border border-line-soft px-2 py-1 text-xs hover:bg-surface-hover disabled:opacity-40 disabled:hover:bg-transparent"; + +function localName(l: LocalAdjustmentV2, index: number): string { + if (l.name) return l.name; + const preset = LOCAL_PRESETS.find((p) => p.id === l.presetId); + const kind = l.mask.kind === "ellipse" ? "円形" : "ブラシ"; + return preset ? `${preset.name} (${kind})` : `部分補正 ${index + 1} (${kind})`; +} + +/** 部分補正のパネル (#109): 一覧、追加、プリセット、効果量とスライダー。ブラシの追加は PR3 */ +export function LocalPanel(p: Props) { + const selected = p.list.find((l) => l.id === p.selectedId) ?? null; + const full = p.list.length >= MAX_LOCAL_ADJUSTMENTS; + return ( +
+
+ + + {p.list.length} / {MAX_LOCAL_ADJUSTMENTS} + + +
+ {p.list.length === 0 ? ( +

+ 範囲を選んで、そこだけに補正を掛けます。「円形を追加」で始めるか、プリセットを選んでください。 +

+ ) : ( +
    + {p.list.map((l, i) => ( +
  • + + + +
  • + ))} +
+ )} +
+

+ {selected ? "選択中の範囲に適用" : "新しい円形マスクを追加して適用"} +

+
+ {LOCAL_PRESETS.map((preset) => ( + + ))} +
+
+ {selected && ( +
+ p.onAmountPreview(selected.id, v)} + onCommit={(v) => p.onAmountCommit(selected.id, v)} + onReset={() => p.onAmountCommit(selected.id, 100)} + /> + {ROWS.map((r) => ( + `${v >= 0 ? "+" : ""}${v.toFixed(2)}` + : (v) => `${v > 0 ? "+" : ""}${v}` + } + onPreview={(v) => p.onAdjustPreview(selected.id, r.key, v)} + onCommit={(v) => p.onAdjustCommit(selected.id, r.key, v)} + onReset={() => p.onAdjustCommit(selected.id, r.key, 0)} + /> + ))} +
+ )} +
+ ); +} diff --git a/apps/app/web/features/editor/ui/ellipse-drag.test.ts b/apps/app/web/features/editor/ui/ellipse-drag.test.ts new file mode 100644 index 0000000..bf26c12 --- /dev/null +++ b/apps/app/web/features/editor/ui/ellipse-drag.test.ts @@ -0,0 +1,57 @@ +import { describe, expect, it } from "vitest"; +import { DEFAULT_ELLIPSE_MASK } from "@prismtone/shared/recipe"; +import { dragEllipse, ellipseHandles } from "./ellipse-drag.ts"; + +const near = (a: number, b: number, eps = 1e-6) => Math.abs(a - b) < eps; +const size = { width: 200, height: 100 }; +const mask = { ...DEFAULT_ELLIPSE_MASK, cx: 0.5, cy: 0.5, rx: 0.1, ry: 0.2, rotation: 0 }; + +describe("dragEllipse", () => { + it("move shifts the center by the pointer delta and clamps to the image", () => { + const out = dragEllipse(mask, "move", { x: 0.5, y: 0.5 }, { x: 0.6, y: 0.45 }, size); + expect(near(out.cx, 0.6) && near(out.cy, 0.45)).toBe(true); + const far = dragEllipse(mask, "move", { x: 0.5, y: 0.5 }, { x: 2, y: -1 }, size); + expect(far.cx).toBe(1); + expect(far.cy).toBe(0); + }); + + it("rx handle sets the horizontal radius from the pointer distance", () => { + const out = dragEllipse(mask, "rx", { x: 0.6, y: 0.5 }, { x: 0.75, y: 0.5 }, size); + expect(near(out.rx, 0.25)).toBe(true); + expect(out.ry).toBe(mask.ry); + }); + + it("ry handle sets the vertical radius, and radii never go below the minimum", () => { + const out = dragEllipse(mask, "ry", { x: 0.5, y: 0.3 }, { x: 0.5, y: 0.4 }, size); + expect(near(out.ry, 0.1)).toBe(true); + const tiny = dragEllipse(mask, "ry", { x: 0.5, y: 0.3 }, { x: 0.5, y: 0.5 }, size); + expect(tiny.ry).toBeGreaterThan(0); + }); + + it("radius handles measure along the rotated axes", () => { + // 90 度回した楕円の rx 軸は画面の縦方向。縦に 30px 離れた点で rx = 30 / 200 + const rotated = { ...mask, rotation: 90 }; + const out = dragEllipse(rotated, "rx", { x: 0.5, y: 0.3 }, { x: 0.5, y: 0.2 }, size); + expect(near(out.rx, 0.15)).toBe(true); + }); + + it("rotate handle sets the angle from the pointer around the center", () => { + // 回転ハンドルは楕円の上 (-ry 方向)。真右へ持っていけば 90 度 + const out = dragEllipse(mask, "rotate", { x: 0.5, y: 0.3 }, { x: 0.7, y: 0.5 }, size); + expect(near(out.rotation, 90, 1e-6)).toBe(true); + const left = dragEllipse(mask, "rotate", { x: 0.5, y: 0.3 }, { x: 0.3, y: 0.5 }, size); + expect(near(left.rotation, -90, 1e-6)).toBe(true); + }); +}); + +describe("ellipseHandles", () => { + it("places rx / ry / rotate handles on the rotated axes in image uv", () => { + const h = ellipseHandles(mask, size); + expect(near(h.rx.x, 0.6) && near(h.rx.y, 0.5)).toBe(true); + expect(near(h.ry.x, 0.5) && near(h.ry.y, 0.3)).toBe(true); + expect(h.rotate.y).toBeLessThan(h.ry.y); + const r = ellipseHandles({ ...mask, rotation: 90 }, size); + // rx 軸 (20px) が縦になる: 20px / 100 = 0.2 下 + expect(near(r.rx.x, 0.5) && near(r.rx.y, 0.7)).toBe(true); + }); +}); diff --git a/apps/app/web/features/editor/ui/ellipse-drag.ts b/apps/app/web/features/editor/ui/ellipse-drag.ts new file mode 100644 index 0000000..b3ab67c --- /dev/null +++ b/apps/app/web/features/editor/ui/ellipse-drag.ts @@ -0,0 +1,86 @@ +import type { EllipseMaskV2 } from "@prismtone/shared/recipe"; +import type { Point } from "../mask-math.ts"; +import type { Size } from "../render/geometry.ts"; + +export type EllipseHandle = "move" | "rx" | "ry" | "rotate"; + +/** 半径の下限 (幅・高さに対する比)。スキーマの gt(0) を満たしつつ、掴めなくならない程度 */ +export const MIN_RADIUS = 0.005; +/** 回転ハンドルを楕円の上端からどれだけ離すか (px) */ +export const ROTATE_HANDLE_OFFSET_PX = 24; + +const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v)); + +/** 中心からの相対位置 (px) を、楕円の軸に合わせて回した座標にする */ +function toAxes(mask: EllipseMaskV2, uv: Point, size: Size): Point { + const px = (uv.x - mask.cx) * size.width; + const py = (uv.y - mask.cy) * size.height; + const rad = (-mask.rotation * Math.PI) / 180; + const c = Math.cos(rad); + const s = Math.sin(rad); + return { x: c * px - s * py, y: s * px + c * py }; +} + +/** 楕円の軸上の点 (px、中心相対) を画像の正規化座標にする */ +function fromAxes(mask: EllipseMaskV2, p: Point, size: Size): Point { + const rad = (mask.rotation * Math.PI) / 180; + const c = Math.cos(rad); + const s = Math.sin(rad); + return { + x: mask.cx + (c * p.x - s * p.y) / size.width, + y: mask.cy + (s * p.x + c * p.y) / size.height, + }; +} + +/** + * 楕円マスクのドラッグ (純粋関数、#109)。座標は幾何を掛ける前の画像の正規化座標。 + * from / to はドラッグの開始点と現在点。 + */ +export function dragEllipse( + start: EllipseMaskV2, + handle: EllipseHandle, + from: Point, + to: Point, + size: Size, +): EllipseMaskV2 { + switch (handle) { + case "move": + return { + ...start, + cx: clamp(start.cx + (to.x - from.x), 0, 1), + cy: clamp(start.cy + (to.y - from.y), 0, 1), + }; + case "rx": { + const p = toAxes(start, to, size); + return { ...start, rx: Math.max(MIN_RADIUS, Math.abs(p.x) / size.width) }; + } + case "ry": { + const p = toAxes(start, to, size); + return { ...start, ry: Math.max(MIN_RADIUS, Math.abs(p.y) / size.height) }; + } + case "rotate": { + // ハンドルは -ry 方向 (上) にある。その方向が真上になる角度が 0 + const px = (to.x - start.cx) * size.width; + const py = (to.y - start.cy) * size.height; + let deg = (Math.atan2(py, px) * 180) / Math.PI + 90; + if (deg > 180) deg -= 360; + if (deg < -180) deg += 360; + return { ...start, rotation: deg }; + } + } +} + +/** ハンドルの位置 (画像の正規化座標)。rotateOffsetPx は画像 px (画面上で一定にしたければ表示倍率で割って渡す) */ +export function ellipseHandles( + mask: EllipseMaskV2, + size: Size, + rotateOffsetPx = ROTATE_HANDLE_OFFSET_PX, +): Record, Point> { + const rxPx = mask.rx * size.width; + const ryPx = mask.ry * size.height; + return { + rx: fromAxes(mask, { x: rxPx, y: 0 }, size), + ry: fromAxes(mask, { x: 0, y: -ryPx }, size), + rotate: fromAxes(mask, { x: 0, y: -ryPx - rotateOffsetPx }, size), + }; +} diff --git a/e2e/editor.spec.ts b/e2e/editor.spec.ts index 137c577..9e33272 100644 --- a/e2e/editor.spec.ts +++ b/e2e/editor.spec.ts @@ -1,6 +1,15 @@ import { expect, test, type Page } from "@playwright/test"; -import { DEFAULT_RECIPE, applyPreset, findPreset, type EditRecipe } from "@prismtone/shared/recipe"; -import { applyAdjust } from "../apps/app/web/features/editor/adjust-math.ts"; +import { + DEFAULT_ELLIPSE_MASK, + DEFAULT_LOCAL_ADJUST, + DEFAULT_LOCAL_ADJUSTMENT, + DEFAULT_RECIPE, + applyPreset, + findPreset, + type EditRecipe, +} from "@prismtone/shared/recipe"; +import { applyAdjust, applyRecipeAt } from "../apps/app/web/features/editor/adjust-math.ts"; +import { login } from "./helpers.ts"; // 4 色のブロックからなるテスト画像 (200x100)。左から赤・緑・青・灰 const BLOCKS: [number, number, number][] = [ @@ -143,6 +152,134 @@ test.describe("editor", () => { expectClose(c.pixels[1]!, BLOCKS[3]!, 2); }); + test("a local adjustment applies inside its ellipse mask only, and follows rotation and crop (#109)", async ({ + page, + }) => { + await openEditorWithImage(page); + const size = { width: 200, height: 100 }; + // 赤ブロックの中心に半径 20px の円。ぼかし無し + const eye = { + ...DEFAULT_LOCAL_ADJUSTMENT, + id: "eye", + mask: { ...DEFAULT_ELLIPSE_MASK, cx: 0.125, cy: 0.5, rx: 0.1, ry: 0.2, feather: 0 }, + adjust: { ...DEFAULT_LOCAL_ADJUST, exposure: 1, saturation: -50 }, + amount: 100, + }; + const recipe: EditRecipe = { + ...DEFAULT_RECIPE, + adjust: { ...DEFAULT_RECIPE.adjust, contrast: 20 }, + localAdjustments: [eye], + }; + const cpu = (rgb: [number, number, number], uv: { x: number; y: number }) => + applyRecipeAt(rgb.map((v) => v / 255) as [number, number, number], uv, recipe, size).map( + (v) => Math.round(v * 255), + ); + + const out = await exportPixels(page, recipe, [ + { x: 25, y: 50 }, // マスクの中心 + { x: 75, y: 50 }, // 緑 (マスク外) + { x: 25, y: 5 }, // 赤だがマスクの外 (縦半径 20px) + ]); + expectClose(out.pixels[0]!, cpu(BLOCKS[0]!, { x: 0.125, y: 0.5 }), 3); + expectClose(out.pixels[1]!, cpu(BLOCKS[1]!, { x: 0.375, y: 0.5 }), 3); + expectClose(out.pixels[2]!, cpu(BLOCKS[0]!, { x: 0.125, y: 0.05 }), 3); + // マスク内は外と違う (補正が効いている) + expect(out.pixels[0]).not.toEqual(out.pixels[2]); + + // 90 度回転 + 左半分をトリミングしても、同じ画素が同じ値になる。 + // 回転後 (100x200) で赤ブロックは上端 0..50、マスクの中心は (50, 25)。crop は上半分 + const rotated: EditRecipe = { + ...recipe, + geometry: { ...recipe.geometry, rotation: 90, crop: { x: 0, y: 0, w: 1, h: 0.5 } }, + }; + const r = await exportPixels(page, rotated, [ + { x: 50, y: 25 }, + { x: 95, y: 25 }, + ]); + expect(r.width).toBe(100); + expect(r.height).toBe(100); + expectClose(r.pixels[0]!, out.pixels[0]!, 3); + expectClose(r.pixels[1]!, out.pixels[2]!, 3); + + // 非表示なら掛からない + const hidden: EditRecipe = { ...recipe, localAdjustments: [{ ...eye, visible: false }] }; + const h = await exportPixels(page, hidden, [{ x: 25, y: 50 }]); + expectClose( + h.pixels[0]!, + cpu(BLOCKS[0]!, { x: 0.375, y: 0.5 }).map((_, i) => + Math.round( + applyAdjust(BLOCKS[0]!.map((v) => v / 255) as [number, number, number], recipe.adjust)[ + i + ]! * 255, + ), + ), + 3, + ); + }); + + test("the local panel adds an ellipse, drags it, undoes, hides, and survives a redo of the export (#109)", async ({ + page, + }) => { + // 「投稿へ」から戻ってくる導線を使うのでログインしておく + await login(page, "/edit"); + await openEditorWithImage(page); + await page.getByRole("tab", { name: "部分補正" }).click(); + await page.getByRole("button", { name: "瞳強調" }).click(); + await expect(page.getByTestId("local-list").getByRole("listitem")).toHaveCount(1); + await expect(page.getByTestId("local-list")).toContainText("瞳強調 (円形)"); + await expect(page.getByTestId("history-last")).toContainText("部分補正を追加: 瞳強調"); + await expect(page.getByTestId("ellipse-overlay")).toBeVisible(); + await expect(page.getByTestId("local-sliders")).toBeVisible(); + + // 中心ハンドルを右へ 40px ドラッグすると 1 手の履歴になり、ハンドルもついてくる + const move = page.getByTestId("ellipse-handle-move"); + const before = await move.boundingBox(); + if (!before) throw new Error("no handle"); + const cx = before.x + before.width / 2; + const cy = before.y + before.height / 2; + await page.mouse.move(cx, cy); + await page.mouse.down(); + await page.mouse.move(cx + 20, cy, { steps: 4 }); + await page.mouse.move(cx + 40, cy, { steps: 4 }); + await page.mouse.up(); + await expect(page.getByTestId("history-last")).toContainText("マスクを動かす"); + const after = await move.boundingBox(); + expect(Math.abs(after!.x - before.x - 40)).toBeLessThan(2); + await page.getByTestId("history-undo").click(); + const back = await move.boundingBox(); + expect(Math.abs(back!.x - before.x)).toBeLessThan(2); + await page.getByTestId("history-redo").click(); + + // スライダーは選択中の範囲に効く (露光量)。値の表示で確かめる + const exposure = page.getByTestId("local-sliders").getByLabel("露光量"); + await exposure.focus(); + await page.keyboard.press("ArrowRight"); + await expect(page.getByTestId("history-last")).toContainText("部分補正: 露光量 +0.35"); + // 手で変えたのでプリセットの強調は外れる + await expect(page.getByRole("button", { name: "瞳強調" })).toHaveAttribute( + "aria-pressed", + "false", + ); + + // 隠すとオーバーレイは残るが (選択中)、非表示の印になる + await page.getByRole("button", { name: "表示中" }).click(); + await expect(page.getByTestId("local-list")).toContainText("非表示"); + + // 投稿へ → 現像をやり直す で戻っても部分補正が残っている (下書きの復元、v2 のレシピ) + await page.getByRole("button", { name: "投稿へ" }).click(); + await page.waitForURL("**/edit/post"); + await page.getByTestId("pending-image-redo-0").click(); + await page.waitForURL(/\/edit(\?|$)/); + await page.getByRole("tab", { name: "部分補正" }).click(); + await expect(page.getByTestId("local-list").getByRole("listitem")).toHaveCount(1); + await expect(page.getByTestId("local-list")).toContainText("非表示"); + + // 全リセットで消える + await page.getByRole("button", { name: "全リセット" }).click(); + await expect(page.getByTestId("local-list")).toHaveCount(0); + await expect(page.getByTestId("ellipse-overlay")).toHaveCount(0); + }); + test("preset, undo, redo and reset drive the UI", async ({ page }) => { await openEditorWithImage(page); await page.getByRole("button", { name: "モノクロ", exact: true }).click(); From bc34e83310887f2985d8fa016308cbcc42bb8d00 Mon Sep 17 00:00:00 2001 From: t1nyb0x Date: Sun, 20 Sep 2026 12:14:32 +0900 Subject: [PATCH 14/49] =?UTF-8?q?test:=20=E9=83=A8=E5=88=86=E8=A3=9C?= =?UTF-8?q?=E6=AD=A3=E3=81=AE=20render=20=E5=B1=A4=E3=82=92=E3=82=AB?= =?UTF-8?q?=E3=83=90=E3=83=AC=E3=83=83=E3=82=B8=E3=81=AE=E5=AF=BE=E8=B1=A1?= =?UTF-8?q?=E5=A4=96=E3=81=AB=E3=81=97=E3=80=81=E3=83=9E=E3=82=B9=E3=82=AF?= =?UTF-8?q?=E8=A1=A8=E7=A4=BA=E3=81=A8=E6=93=8D=E4=BD=9C=E5=90=8D=E3=81=AE?= =?UTF-8?q?=E3=83=86=E3=82=B9=E3=83=88=E3=82=92=E8=B6=B3=E3=81=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GLSL と PixiJS のフィルタ・RenderTexture (adjust-glsl / local-adjust-filter / develop-stage) は 既存の editor-renderer / adjust-filter と同じくブラウザ専用で、E2E が GPU 出力を CPU 参照と 照合している。Codecov の patch 判定から外す。 Co-Authored-By: Claude Opus 5 --- apps/app/web/features/editor/labels.test.ts | 9 ++++++++- apps/app/web/features/editor/state.test.ts | 7 +++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/apps/app/web/features/editor/labels.test.ts b/apps/app/web/features/editor/labels.test.ts index 02a1cfd..a529327 100644 --- a/apps/app/web/features/editor/labels.test.ts +++ b/apps/app/web/features/editor/labels.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; import { DEFAULT_ELLIPSE_MASK, DEFAULT_LOCAL_ADJUSTMENT } from "@prismtone/shared/recipe"; -import { adjustLabel, geometryLabel, localAdjustmentsSummary } from "./labels.ts"; +import { adjustLabel, geometryLabel, localAdjustLabel, localAdjustmentsSummary } from "./labels.ts"; describe("operation labels", () => { it("補正は項目名と符号付きの値", () => { @@ -18,6 +18,13 @@ describe("operation labels", () => { }); }); +describe("localAdjustLabel (#109)", () => { + it("prefixes the item with 部分補正 and formats exposure to two decimals", () => { + expect(localAdjustLabel("exposure", 0.35)).toBe("部分補正: 露光量 +0.35"); + expect(localAdjustLabel("shadows", -20)).toBe("部分補正: シャドウ -20"); + }); +}); + describe("localAdjustmentsSummary (#109)", () => { const local = (presetId: "eyes" | "skin" | "gear" | null) => ({ ...DEFAULT_LOCAL_ADJUSTMENT, diff --git a/apps/app/web/features/editor/state.test.ts b/apps/app/web/features/editor/state.test.ts index 1c9b162..ad2f61d 100644 --- a/apps/app/web/features/editor/state.test.ts +++ b/apps/app/web/features/editor/state.test.ts @@ -192,4 +192,11 @@ describe("editorReducer: 部分補正 (#109)", () => { }); expect(s).toBe(withOne); }); + + it("ui/show-mask turns the mask overlay on and off without touching the recipe", () => { + const off = editorReducer(withOne, { type: "ui/show-mask", on: false }); + expect(off.ui.local.showMask).toBe(false); + expect(off.history).toBe(withOne.history); + expect(editorReducer(off, { type: "ui/show-mask", on: true }).ui.local.showMask).toBe(true); + }); }); From 4088e448a787936ca1d67914c43efef2098bfa88 Mon Sep 17 00:00:00 2001 From: t1nyb0x Date: Sun, 20 Sep 2026 12:33:26 +0900 Subject: [PATCH 15/49] =?UTF-8?q?feat:=20=E3=83=96=E3=83=A9=E3=82=B7?= =?UTF-8?q?=E3=83=9E=E3=82=B9=E3=82=AF=E3=80=81=E3=82=B7=E3=83=A3=E3=83=BC?= =?UTF-8?q?=E3=83=97=E3=80=81=E7=BE=8E=E8=82=8C=E3=81=AE=E5=B9=B3=E6=BB=91?= =?UTF-8?q?=E5=8C=96=E3=80=81=E8=A3=85=E5=82=99=E5=BC=B7=E8=AA=BF=E3=80=81?= =?UTF-8?q?=E9=83=A8=E5=88=86=E8=A3=9C=E6=AD=A3=E3=81=AE=E8=A8=88=E6=B8=AC?= =?UTF-8?q?=E3=81=A8=E8=A6=8F=E7=B4=84=E3=81=AE=E6=96=87=E8=A8=80=20(lumor?= =?UTF-8?q?phia/prismtone#109=20=E3=81=AE=203=20=E6=AE=B5=E7=9B=AE)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - brush-raster.ts (純関数): ストロークを長辺 1024 のラスタに描く (円のスタンプを線分に沿って 半径の 1/4 間隔で、add は max、erase は min)。線分距離で評価する CPU 参照 brushMaskValue、 点列の間引き simplifyPoints (長辺の 0.5% 未満を捨て、最大 512 点) - render/mask-texture.ts: ラスタを canvas 経由でテクスチャに。確定で描き直し、描画中は線分ごとに足す - local-adjust-filter.ts: ブラシは uMask を vImageUv でサンプル。シャープ (3x3 アンシャープ) と 美肌 (5x5 の輝度差で重み付けした平均) を足す。近傍の間隔は元画像の px (uSourceSize) で決めて、 プレビューと原寸の書き出しで同じ広がりにする。範囲外は uInputClamp で clamp - state.ts: local/add kind=brush、local/stroke-commit (1 ストローク = 1 手、64 本まで)、ui/brush - ui: 「ブラシを追加」、ブラシの設定 (塗る / 消す、サイズ、硬さ)、BrushOverlay (キャンバスをなぞる、 ブラシの円のカーソル)、シャープ・美肌のスライダー。装備強調はブラシで始まる - 計測: renderer.benchmark() と e2e/perf-local-adjust.spec.ts (PERF=1 のときだけ)。 docs/spikes/2026-09-20-local-adjust-perf.md に SwiftShader の結果 (8 個で合成 125 ms、 書き出し 2.4 s、テクスチャ +9 MB) と実機で取る手順。上限 8 は据え置き - 規約 1.2 -> 1.3 (§3 の編集機能の範囲に部分補正・シャープ・軽い平滑化を明記)、about にも一言 - E2E: ブラシのストロークに沿って CPU 参照と一致し、消去で戻り、平坦部は平滑化・シャープで変わらない。 ブラシツールで塗る / 消す / undo。docs 04 / 08 / ロードマップ Closes lumorphia/prismtone#109 Co-Authored-By: Claude Opus 5 --- .../web/features/editor/adjust-math.test.ts | 17 ++ apps/app/web/features/editor/adjust-math.ts | 11 +- .../web/features/editor/brush-raster.test.ts | 144 +++++++++++++++++ apps/app/web/features/editor/brush-raster.ts | 147 ++++++++++++++++++ .../features/editor/render/develop-stage.ts | 46 +++++- .../features/editor/render/editor-renderer.ts | 51 +++++- .../editor/render/local-adjust-filter.ts | 91 +++++++++-- .../features/editor/render/mask-texture.ts | 68 ++++++++ apps/app/web/features/editor/state.test.ts | 38 +++++ apps/app/web/features/editor/state.ts | 29 +++- .../web/features/editor/ui/BrushOverlay.tsx | 107 +++++++++++++ .../app/web/features/editor/ui/EditorPage.tsx | 27 +++- .../app/web/features/editor/ui/LocalPanel.tsx | 77 ++++++++- e2e/editor.spec.ts | 72 +++++++++ e2e/perf-local-adjust.spec.ts | 104 +++++++++++++ 15 files changed, 1003 insertions(+), 26 deletions(-) create mode 100644 apps/app/web/features/editor/brush-raster.test.ts create mode 100644 apps/app/web/features/editor/brush-raster.ts create mode 100644 apps/app/web/features/editor/render/mask-texture.ts create mode 100644 apps/app/web/features/editor/ui/BrushOverlay.tsx create mode 100644 e2e/perf-local-adjust.spec.ts diff --git a/apps/app/web/features/editor/adjust-math.test.ts b/apps/app/web/features/editor/adjust-math.test.ts index 0986cb8..0a6cf09 100644 --- a/apps/app/web/features/editor/adjust-math.test.ts +++ b/apps/app/web/features/editor/adjust-math.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "vitest"; import { DEFAULT_ADJUST, + DEFAULT_BRUSH_MASK, DEFAULT_ELLIPSE_MASK, DEFAULT_LOCAL_ADJUST, DEFAULT_LOCAL_ADJUSTMENT, @@ -138,4 +139,20 @@ describe("applyRecipeAt (部分補正の CPU 参照、#109)", () => { applyAdjust(px, { ...DEFAULT_ADJUST, exposure: 0.5, contrast: 20, temperature: -30 }), ); }); + + it("evaluates a brush mask through the stroke geometry", () => { + const brush = { + ...eye, + id: "gear", + mask: { + ...DEFAULT_BRUSH_MASK, + strokes: [{ mode: "add" as const, size: 0.2, hardness: 1, points: [{ x: 0.75, y: 0.5 }] }], + }, + }; + const recipe = { ...DEFAULT_RECIPE, localAdjustments: [brush] }; + expect(applyRecipeAt(px, { x: 0.75, y: 0.5 }, recipe, size)).toEqual( + applyLocalAdjust(px, eye.adjust), + ); + expect(applyRecipeAt(px, { x: 0.25, y: 0.5 }, recipe, size)).toEqual(px); + }); }); diff --git a/apps/app/web/features/editor/adjust-math.ts b/apps/app/web/features/editor/adjust-math.ts index f5be71d..1069680 100644 --- a/apps/app/web/features/editor/adjust-math.ts +++ b/apps/app/web/features/editor/adjust-math.ts @@ -1,5 +1,6 @@ import type { AdjustV1, EditRecipe, LocalAdjustV2 } from "@prismtone/shared/recipe"; import { ellipseMaskValue, type Point } from "./mask-math.ts"; +import { brushMaskValue } from "./brush-raster.ts"; import type { Size } from "./render/geometry.ts"; /** @@ -103,13 +104,17 @@ export function applyLocalAdjust(input: RGB, adjust: LocalAdjustV2): RGB { /** * レシピ全体を 1 画素に適用する参照実装: 全体の補正 → 部分補正を順に。 - * uv は幾何を掛ける前の画像の正規化座標。ブラシマスクは PR3 で足す + * uv は幾何を掛ける前の画像の正規化座標 */ export function applyRecipeAt(input: RGB, uv: Point, recipe: EditRecipe, size: Size): RGB { let rgb = applyAdjust(input, recipe.adjust); for (const local of recipe.localAdjustments) { - if (!local.visible || local.mask.kind !== "ellipse") continue; - const m = ellipseMaskValue(uv, local.mask, size) * (local.amount / 100); + if (!local.visible) continue; + const mask = + local.mask.kind === "ellipse" + ? ellipseMaskValue(uv, local.mask, size) + : brushMaskValue(uv, local.mask, size); + const m = mask * (local.amount / 100); if (m <= 0) continue; const adjusted = applyLocalAdjust(rgb, local.adjust); rgb = [mix(rgb[0], adjusted[0], m), mix(rgb[1], adjusted[1], m), mix(rgb[2], adjusted[2], m)]; diff --git a/apps/app/web/features/editor/brush-raster.test.ts b/apps/app/web/features/editor/brush-raster.test.ts new file mode 100644 index 0000000..d7b3aed --- /dev/null +++ b/apps/app/web/features/editor/brush-raster.test.ts @@ -0,0 +1,144 @@ +import { describe, expect, it } from "vitest"; +import { DEFAULT_BRUSH_MASK, type BrushStrokeV2 } from "@prismtone/shared/recipe"; +import { + brushMaskValue, + createMaskRaster, + rasterSize, + rasterizeBrushMask, + simplifyPoints, + stampStroke, +} from "./brush-raster.ts"; + +const source = { width: 200, height: 100 }; +const dot = (x: number, y: number, extra: Partial = {}): BrushStrokeV2 => ({ + mode: "add", + size: 0.2, // 長辺 200 の 20% = 直径 40px、半径 20px + hardness: 1, + points: [{ x, y }], + ...extra, +}); +const at = (r: ReturnType, x: number, y: number) => + r.data[y * r.width + x]!; + +describe("rasterSize", () => { + it("keeps the aspect ratio and caps the long edge", () => { + expect(rasterSize({ width: 4096, height: 2048 }, 1024)).toEqual({ width: 1024, height: 512 }); + expect(rasterSize(source, 1024)).toEqual({ width: 200, height: 100 }); + }); +}); + +describe("stampStroke / rasterizeBrushMask", () => { + it("a hard dot fills its radius and nothing outside", () => { + const r = rasterizeBrushMask({ ...DEFAULT_BRUSH_MASK, strokes: [dot(0.5, 0.5)] }, source); + expect(at(r, 100, 50)).toBe(255); + expect(at(r, 115, 50)).toBe(255); + expect(at(r, 125, 50)).toBe(0); + expect(at(r, 100, 25)).toBe(0); + }); + + it("a soft dot falls off towards the edge", () => { + const r = rasterizeBrushMask( + { ...DEFAULT_BRUSH_MASK, strokes: [dot(0.5, 0.5, { hardness: 0 })] }, + source, + ); + // 画素の中心は円の中心から 0.7px ずれるので、硬さ 0 では 255 に僅かに届かない + expect(at(r, 100, 50)).toBeGreaterThanOrEqual(250); + const mid = at(r, 110, 50); + expect(mid).toBeGreaterThan(0); + expect(mid).toBeLessThan(255); + expect(at(r, 121, 50)).toBe(0); + }); + + it("a stroke between two points has no gap", () => { + const stroke = dot(0.25, 0.5, { + points: [ + { x: 0.25, y: 0.5 }, + { x: 0.75, y: 0.5 }, + ], + }); + const r = rasterizeBrushMask({ ...DEFAULT_BRUSH_MASK, strokes: [stroke] }, source); + for (let x = 50; x <= 150; x += 5) expect(at(r, x, 50)).toBe(255); + }); + + it("erase removes what a previous stroke added, in order", () => { + const strokes = [dot(0.5, 0.5), dot(0.5, 0.5, { mode: "erase", size: 0.1 })]; + const r = rasterizeBrushMask({ ...DEFAULT_BRUSH_MASK, strokes }, source); + expect(at(r, 100, 50)).toBe(0); + expect(at(r, 115, 50)).toBe(255); + // 順序が逆なら消すものが無い + const reversed = rasterizeBrushMask( + { ...DEFAULT_BRUSH_MASK, strokes: [...strokes].reverse() }, + source, + ); + expect(at(reversed, 100, 50)).toBe(255); + }); + + it("invert flips the raster and feather softens the edge", () => { + const inv = rasterizeBrushMask( + { ...DEFAULT_BRUSH_MASK, strokes: [dot(0.5, 0.5)], invert: true }, + source, + ); + expect(at(inv, 100, 50)).toBe(0); + expect(at(inv, 10, 10)).toBe(255); + const soft = rasterizeBrushMask( + { ...DEFAULT_BRUSH_MASK, strokes: [dot(0.5, 0.5)], feather: 1 }, + source, + ); + expect(at(soft, 115, 50)).toBeLessThan(255); + }); + + it("stampStroke draws into an existing raster (incremental preview)", () => { + const r = createMaskRaster(source); + stampStroke(r, dot(0.25, 0.5), 0); + stampStroke(r, dot(0.75, 0.5), 0); + expect(at(r, 50, 50)).toBe(255); + expect(at(r, 150, 50)).toBe(255); + expect(at(r, 100, 50)).toBe(0); + }); +}); + +describe("brushMaskValue (CPU 参照)", () => { + it("agrees with the raster inside, outside and after an erase", () => { + const mask = { + ...DEFAULT_BRUSH_MASK, + strokes: [dot(0.5, 0.5), dot(0.5, 0.5, { mode: "erase", size: 0.1 })], + }; + expect(brushMaskValue({ x: 0.5, y: 0.5 }, mask, source)).toBe(0); + expect(brushMaskValue({ x: 0.575, y: 0.5 }, mask, source)).toBe(1); + expect(brushMaskValue({ x: 0.9, y: 0.5 }, mask, source)).toBe(0); + expect(brushMaskValue({ x: 0.9, y: 0.5 }, { ...mask, invert: true }, source)).toBe(1); + }); + + it("measures distance to the segment, not only to the points", () => { + const stroke = dot(0.25, 0.5, { + points: [ + { x: 0.25, y: 0.5 }, + { x: 0.75, y: 0.5 }, + ], + }); + const mask = { ...DEFAULT_BRUSH_MASK, strokes: [stroke] }; + expect(brushMaskValue({ x: 0.5, y: 0.5 }, mask, source)).toBe(1); + expect(brushMaskValue({ x: 0.5, y: 0.5 + 0.25 }, mask, source)).toBe(0); + }); +}); + +describe("simplifyPoints", () => { + it("drops points closer than the minimum distance but keeps the first and last", () => { + const pts = [ + { x: 0.1, y: 0.1 }, + { x: 0.101, y: 0.1 }, + { x: 0.2, y: 0.1 }, + { x: 0.2005, y: 0.1 }, + ]; + expect(simplifyPoints(pts, 0.005)).toEqual([ + { x: 0.1, y: 0.1 }, + { x: 0.2, y: 0.1 }, + { x: 0.2005, y: 0.1 }, + ]); + }); + + it("caps the number of points", () => { + const pts = Array.from({ length: 2000 }, (_, i) => ({ x: i / 2000, y: 0.5 })); + expect(simplifyPoints(pts, 0, 512)).toHaveLength(512); + }); +}); diff --git a/apps/app/web/features/editor/brush-raster.ts b/apps/app/web/features/editor/brush-raster.ts new file mode 100644 index 0000000..abd4def --- /dev/null +++ b/apps/app/web/features/editor/brush-raster.ts @@ -0,0 +1,147 @@ +import { MAX_BRUSH_POINTS, type BrushMaskV2, type BrushStrokeV2 } from "@prismtone/shared/recipe"; +import type { Point } from "./mask-math.ts"; +import type { Size } from "./render/geometry.ts"; + +/** + * ブラシマスクのラスタライズ (#109)。DOM に依存しない純関数で、単体テストと GPU 出力の照合に使う。 + * ストロークは幾何を掛ける前の画像の正規化座標。半径は画像の長辺に対する比 (size / 2)。 + * 描画は「点の周りに円のスタンプを、線分に沿って半径の 1/4 間隔で押す」。add は max、erase は min。 + */ + +export type MaskRaster = { width: number; height: number; data: Uint8ClampedArray }; + +/** マスクテクスチャの長辺。画像より粗くても、GPU で線形補間されるので境界は滑らか */ +export const MASK_RASTER_MAX_EDGE = 1024; + +const clamp01 = (v: number) => Math.min(1, Math.max(0, v)); +const smoothstep = (e0: number, e1: number, x: number) => { + const t = clamp01((x - e0) / (e1 - e0)); + return t * t * (3 - 2 * t); +}; + +/** 画像の縦横比を保って長辺を maxEdge に収めた整数の寸法 */ +export function rasterSize(source: Size, maxEdge = MASK_RASTER_MAX_EDGE): Size { + const edge = Math.max(source.width, source.height); + const s = edge > maxEdge ? maxEdge / edge : 1; + return { + width: Math.max(1, Math.round(source.width * s)), + height: Math.max(1, Math.round(source.height * s)), + }; +} + +export function createMaskRaster(source: Size, maxEdge = MASK_RASTER_MAX_EDGE): MaskRaster { + const { width, height } = rasterSize(source, maxEdge); + return { width, height, data: new Uint8ClampedArray(width * height) }; +} + +/** + * スタンプ 1 つの値 (0..1)。中心から hardness × 半径までは 1、そこから縁でなだらかに 0。 + * feather (0..1) は硬さを下げる方向に効く (輪郭をぼかすため) + */ +function falloff(distance: number, radius: number, hardness: number, feather: number): number { + if (distance >= radius) return 0; + const core = clamp01(hardness * (1 - feather)); + if (core >= 1) return 1; + return 1 - smoothstep(core * radius, radius, distance); +} + +/** 線分 ab 上で p に最も近い点までの距離 */ +function distanceToSegment(p: Point, a: Point, b: Point): number { + const dx = b.x - a.x; + const dy = b.y - a.y; + const len2 = dx * dx + dy * dy; + const t = len2 === 0 ? 0 : clamp01(((p.x - a.x) * dx + (p.y - a.y) * dy) / len2); + return Math.hypot(p.x - (a.x + t * dx), p.y - (a.y + t * dy)); +} + +/** ストローク 1 本をラスタに描く (その場で書き換える)。プレビューでは 1 本ずつ足す */ +export function stampStroke(raster: MaskRaster, stroke: BrushStrokeV2, feather: number): void { + const { width, height, data } = raster; + const edge = Math.max(width, height); + const radius = (stroke.size * edge) / 2; + const toPx = (p: Point) => ({ x: p.x * width, y: p.y * height }); + const points = stroke.points.map(toPx); + const paint = (c: Point) => { + const x0 = Math.max(0, Math.floor(c.x - radius)); + const x1 = Math.min(width - 1, Math.ceil(c.x + radius)); + const y0 = Math.max(0, Math.floor(c.y - radius)); + const y1 = Math.min(height - 1, Math.ceil(c.y + radius)); + for (let y = y0; y <= y1; y++) { + for (let x = x0; x <= x1; x++) { + const d = Math.hypot(x + 0.5 - c.x, y + 0.5 - c.y); + const v = Math.round(falloff(d, radius, stroke.hardness, feather) * 255); + if (v === 0) continue; + const i = y * width + x; + data[i] = stroke.mode === "add" ? Math.max(data[i]!, v) : Math.min(data[i]!, 255 - v); + } + } + }; + const spacing = Math.max(0.5, radius / 4); + let prev = points[0]!; + paint(prev); + for (const next of points.slice(1)) { + const len = Math.hypot(next.x - prev.x, next.y - prev.y); + const n = Math.ceil(len / spacing); + for (let k = 1; k <= n; k++) { + const t = k / n; + paint({ x: prev.x + (next.x - prev.x) * t, y: prev.y + (next.y - prev.y) * t }); + } + prev = next; + } +} + +/** マスク全体をゼロから描く (undo・下書き復元・書き出し) */ +export function rasterizeBrushMask( + mask: BrushMaskV2, + source: Size, + maxEdge = MASK_RASTER_MAX_EDGE, +): MaskRaster { + const raster = createMaskRaster(source, maxEdge); + for (const stroke of mask.strokes) stampStroke(raster, stroke, mask.feather); + if (mask.invert) + for (let i = 0; i < raster.data.length; i++) raster.data[i] = 255 - raster.data[i]!; + return raster; +} + +/** + * 1 点でのブラシマスクの値 (0..1)。ラスタを介さず線分までの距離で評価する参照実装。 + * ストロークを順に適用する (add は max、erase は min) のはラスタと同じ + */ +export function brushMaskValue(uv: Point, mask: BrushMaskV2, source: Size): number { + const edge = Math.max(source.width, source.height); + const p = { x: uv.x * source.width, y: uv.y * source.height }; + let value = 0; + for (const stroke of mask.strokes) { + const radius = (stroke.size * edge) / 2; + const pts = stroke.points.map((q) => ({ x: q.x * source.width, y: q.y * source.height })); + let d = Infinity; + for (let i = 0; i < pts.length; i++) { + d = Math.min(d, distanceToSegment(p, pts[i]!, pts[Math.min(i + 1, pts.length - 1)]!)); + } + const v = falloff(d, radius, stroke.hardness, mask.feather); + value = stroke.mode === "add" ? Math.max(value, v) : Math.min(value, 1 - v); + } + return mask.invert ? 1 - value : value; +} + +/** + * ポインタの点列を間引く: 直前に残した点から minDistance 未満の移動は捨てる。最初と最後は残す。 + * 上限を超えたら等間隔に間引く (レシピの肥大化を抑える、docs/design/04 §1.1) + */ +export function simplifyPoints( + points: readonly Point[], + minDistance: number, + limit = MAX_BRUSH_POINTS, +): Point[] { + if (points.length === 0) return []; + const kept: Point[] = [points[0]!]; + for (let i = 1; i < points.length - 1; i++) { + const last = kept[kept.length - 1]!; + if (Math.hypot(points[i]!.x - last.x, points[i]!.y - last.y) >= minDistance) + kept.push(points[i]!); + } + if (points.length > 1) kept.push(points[points.length - 1]!); + if (kept.length <= limit) return kept; + const step = (kept.length - 1) / (limit - 1); + return Array.from({ length: limit }, (_, i) => kept[Math.round(i * step)]!); +} diff --git a/apps/app/web/features/editor/render/develop-stage.ts b/apps/app/web/features/editor/render/develop-stage.ts index f526553..df4219d 100644 --- a/apps/app/web/features/editor/render/develop-stage.ts +++ b/apps/app/web/features/editor/render/develop-stage.ts @@ -1,7 +1,8 @@ import { Container, Rectangle, RenderTexture, Sprite, type Renderer, type Texture } from "pixi.js"; -import type { EditRecipe, LocalAdjustmentV2 } from "@prismtone/shared/recipe"; +import type { BrushStrokeV2, EditRecipe, LocalAdjustmentV2 } from "@prismtone/shared/recipe"; import { AdjustFilter } from "./adjust-filter.ts"; import { LocalAdjustFilter } from "./local-adjust-filter.ts"; +import { MaskTexture } from "./mask-texture.ts"; import type { Size } from "./geometry.ts"; /** @@ -20,12 +21,16 @@ export class DevelopStage { private readonly sprite: Sprite; private readonly global: AdjustFilter; private locals: LocalAdjustFilter[] = []; + /** ブラシマスクのテクスチャ (部分補正の id ごと)。マスクのオブジェクトが変わったら描き直す */ + private masks = new Map(); + private readonly source: Size; private recipe: EditRecipe; private previewMaskId: string | null = null; dirty = true; constructor(source: Texture, size: Size, recipe: EditRecipe) { this.recipe = recipe; + this.source = { width: source.width, height: source.height }; this.sprite = new Sprite(source); this.container.addChild(this.sprite); this.texture = RenderTexture.create({ @@ -71,12 +76,45 @@ export class DevelopStage { this.dirty = true; } + /** 描画中のストロークをマスクに足す (レシピに入れる前のプレビュー) */ + previewStroke(id: string, stroke: BrushStrokeV2): void { + const entry = this.masks.get(id); + if (!entry || entry.mask.kind !== "brush") return; + entry.texture.addStroke(stroke, entry.mask.feather); + this.dirty = true; + } + private syncLocals(locals: readonly LocalAdjustmentV2[]): void { while (this.locals.length > locals.length) this.locals.pop()?.destroy(); while (this.locals.length < locals.length) { - this.locals.push(new LocalAdjustFilter(locals[this.locals.length]!)); + this.locals.push(new LocalAdjustFilter(locals[this.locals.length]!, this.source)); + } + const alive = new Set(); + locals.forEach((l, i) => { + const filter = this.locals[i]!; + filter.setLocal(l, l.id === this.previewMaskId); + if (l.mask.kind === "brush") { + alive.add(l.id); + let entry = this.masks.get(l.id); + if (!entry) { + entry = { mask: l.mask, texture: new MaskTexture(this.source) }; + entry.texture.set(l.mask); + this.masks.set(l.id, entry); + } else if (entry.mask !== l.mask) { + entry.mask = l.mask; + entry.texture.set(l.mask); + } + filter.setMaskTexture(entry.texture.texture.source); + } else { + filter.setMaskTexture(null); + } + }); + for (const [id, entry] of this.masks) { + if (!alive.has(id)) { + entry.texture.destroy(); + this.masks.delete(id); + } } - locals.forEach((l, i) => this.locals[i]!.setLocal(l, l.id === this.previewMaskId)); this.sprite.filters = [this.global, ...this.locals]; } @@ -90,6 +128,8 @@ export class DevelopStage { this.global.destroy(); for (const f of this.locals) f.destroy(); this.locals = []; + for (const entry of this.masks.values()) entry.texture.destroy(); + this.masks.clear(); this.sprite.destroy(); this.container.destroy(); this.texture.destroy(true); diff --git a/apps/app/web/features/editor/render/editor-renderer.ts b/apps/app/web/features/editor/render/editor-renderer.ts index 0cde80d..72713f4 100644 --- a/apps/app/web/features/editor/render/editor-renderer.ts +++ b/apps/app/web/features/editor/render/editor-renderer.ts @@ -11,7 +11,7 @@ import { TexturePool, type WebGLRenderer, } from "pixi.js"; -import type { EditRecipe, GeometryV1 } from "@prismtone/shared/recipe"; +import type { BrushStrokeV2, EditRecipe, GeometryV1 } from "@prismtone/shared/recipe"; import { DevelopStage } from "./develop-stage.ts"; import { canvasSize, cropRect, exportScale, totalRotationDeg, type Size } from "./geometry.ts"; @@ -23,6 +23,13 @@ export type ExportOptions = { maxEdge?: number; }; +export type Benchmark = { + developMs: number; + exportMs: number; + textureBytes: number; + previewSize: Size; +}; + export const EXPORT_MAX_EDGE = 4096; /** プレビュー用の現像テクスチャの長辺。書き出しは原寸で描き直す */ export const PREVIEW_MAX_EDGE = 2048; @@ -163,6 +170,48 @@ export class EditorRenderer { this.applyCompare(); } + /** + * 計測用 (docs/spikes の部分補正の性能、#109): 合成の段を frames 回描いたときの 1 回あたりの ms と、 + * 書き出し 1 回の ms、GPU に載っているテクスチャの概算バイト数。開発と E2E のフックからだけ呼ぶ。 + * 描いたテクスチャから 1px 読み戻して GPU の完了まで待つので、実際のフレーム時間より重めに出る + * (gl.finish() は ANGLE で待たないことがある) + */ + async benchmark(recipe: EditRecipe, frames = 30): Promise { + if (!this.develop) throw new Error("no image loaded"); + this.setRecipe(recipe); + const t0 = performance.now(); + for (let i = 0; i < frames; i++) { + this.develop.dirty = true; + this.develop.render(this.app.renderer); + this.app.renderer.extract.pixels({ + target: this.develop.texture, + frame: new Rectangle(0, 0, 1, 1), + }); + } + const developMs = (performance.now() - t0) / frames; + const t1 = performance.now(); + await this.export(recipe, { format: "image/png" }); + const exportMs = performance.now() - t1; + const textureBytes = this.managedTextureBytes(); + return { developMs, exportMs, textureBytes, previewSize: this.develop.size }; + } + + /** GL に載っているテクスチャの概算 (RGBA8 として w × h × 4)。managedTextures は 8.15 で deprecated なので防御的に */ + private managedTextureBytes(): number { + const system = (this.app.renderer as WebGLRenderer).texture as unknown as { + _managedTextures?: { + items?: Record; + }; + }; + const items = Object.values(system._managedTextures?.items ?? {}); + return items.reduce((sum, t) => sum + (t ? t.pixelWidth * t.pixelHeight * 4 : 0), 0); + } + + /** ブラシで描いている途中のストロークを、レシピに入れる前にマスクへ足す */ + previewStroke(id: string, stroke: BrushStrokeV2): void { + this.develop?.previewStroke(id, stroke); + } + /** 選択中の部分補正の範囲を赤で重ねる (null で消す) */ setMaskPreview(id: string | null): void { this.previewMaskId = id; diff --git a/apps/app/web/features/editor/render/local-adjust-filter.ts b/apps/app/web/features/editor/render/local-adjust-filter.ts index a37f713..eda2fc8 100644 --- a/apps/app/web/features/editor/render/local-adjust-filter.ts +++ b/apps/app/web/features/editor/render/local-adjust-filter.ts @@ -1,21 +1,36 @@ -import { Filter, GlProgram } from "pixi.js"; +import { Filter, GlProgram, Texture, type TextureSource } from "pixi.js"; import type { LocalAdjustmentV2 } from "@prismtone/shared/recipe"; import { MIN_FEATHER } from "../mask-math.ts"; +import type { Size } from "./geometry.ts"; import { ADJUST_GLSL, FILTER_VERTEX } from "./adjust-glsl.ts"; -// 部分補正 1 件 = フィルタ 1 パス (#109)。マスク (mask-math.ts) と色補正 (adjust-math.ts) の -// CPU 実装と同じ式。片方を変えたら必ずもう片方も変える。 -// ブラシマスク (uMask テクスチャ)、シャープ、美肌は PR3 で足す。 +// 部分補正 1 件 = フィルタ 1 パス (#109)。マスク (mask-math.ts / brush-raster.ts) と色補正 +// (adjust-math.ts) の CPU 実装と同じ式。片方を変えたら必ずもう片方も変える。 +// シャープ (3x3 アンシャープ) と美肌 (5x5 の輪郭を残す平滑化) は近傍を見るので CPU 参照は無く、 +// E2E は平坦部 (変わらない) とマスク外だけを照合する (docs/design/08 §7)。 +// 近傍の間隔は元画像の px で決める (uSourceSize) ので、プレビュー (縮小) と書き出し (原寸) で +// 同じ広がりになる。 + +/** 近傍サンプルの間隔 (元画像の px)。5x5 で ±2 タップ = ±4px */ +export const KERNEL_STEP_PX = 2; const fragment = /* glsl */ ` precision highp float; +#define KERNEL_STEP ${KERNEL_STEP_PX.toFixed(1)} in vec2 vTextureCoord; in vec2 vImageUv; out vec4 finalColor; uniform sampler2D uTexture; +uniform sampler2D uMask; // ブラシマスク (r)。楕円のときは白 1px +uniform vec4 uInputSize; // .zw = 1 / 中間テクスチャの px +uniform vec4 uInputClamp; // 近傍サンプルの範囲 (中間テクスチャの余白に触れない) uniform vec4 uOutputFrame; // .zw = 画像の px サイズ (領域 = 画像矩形) +uniform vec2 uSourceSize; // 元画像の px (近傍の間隔を原寸基準にする) +uniform float uMaskMode; // 0 = 楕円 (解析的)、1 = ブラシ (テクスチャ) +uniform float uSharpen; // 0..1 +uniform float uSmooth; // 0..0.6 uniform float uExposure; uniform float uContrast; @@ -34,6 +49,43 @@ uniform float uShowMask; // 1 なら選択範囲を赤で重ねる (UI の ${ADJUST_GLSL} +vec3 tap(vec2 offsetPx) { + // 元画像の px → 中間テクスチャの座標: 画像 uv 1 = uOutputFrame.zw * uInputSize.zw + vec2 d = offsetPx / uSourceSize * (uOutputFrame.zw * uInputSize.zw); + vec4 c = texture(uTexture, clamp(vTextureCoord + d, uInputClamp.xy, uInputClamp.zw)); + return c.a > 0.0 ? c.rgb / c.a : c.rgb; +} + +// 3x3 の平均との差を足す +vec3 sharpen(vec3 rgb) { + vec3 sum = vec3(0.0); + for (int y = -1; y <= 1; y++) { + for (int x = -1; x <= 1; x++) { + sum += tap(vec2(float(x), float(y)) * KERNEL_STEP); + } + } + return rgb + (rgb - sum / 9.0) * uSharpen; +} + +// 5x5 の bilateral。輝度が近い画素だけ平均する (輪郭を残す) +vec3 smoothSkin(vec3 rgb) { + float y0 = dot(rgb, vec3(0.299, 0.587, 0.114)); + vec3 sum = vec3(0.0); + float wsum = 0.0; + for (int y = -2; y <= 2; y++) { + for (int x = -2; x <= 2; x++) { + vec3 c = tap(vec2(float(x), float(y)) * KERNEL_STEP); + float dy = dot(c, vec3(0.299, 0.587, 0.114)) - y0; + float ws = exp(-float(x * x + y * y) / 8.0); + float wr = exp(-(dy * dy) / 0.02); + float w = ws * wr; + sum += c * w; + wsum += w; + } + } + return sum / wsum; +} + float ellipseMask(void) { vec2 p = (vImageUv - uCenter) * uOutputFrame.zw; float c = cos(-uRotation); @@ -46,11 +98,14 @@ float ellipseMask(void) { void main(void) { vec4 src = texture(uTexture, vTextureCoord); - float mask = ellipseMask(); + float mask = uMaskMode > 0.5 ? mix(texture(uMask, vImageUv).r, 1.0 - texture(uMask, vImageUv).r, uInvert) : ellipseMask(); float m = mask * uAmount; vec3 rgb = src.a > 0.0 ? src.rgb / src.a : src.rgb; if (m > 0.0) { - vec3 adjusted = adjustColor(rgb, uExposure, uContrast, uHighlights, uShadows, uTemperature, uTint, 0.0, uSaturation); + vec3 adjusted = rgb; + if (uSmooth > 0.0) adjusted = mix(adjusted, smoothSkin(adjusted), uSmooth); + if (uSharpen > 0.0) adjusted = sharpen(adjusted); + adjusted = adjustColor(clamp(adjusted, 0.0, 1.0), uExposure, uContrast, uHighlights, uShadows, uTemperature, uTint, 0.0, uSaturation); rgb = mix(rgb, adjusted, m); } if (uShowMask > 0.5) { @@ -72,6 +127,10 @@ type LocalUniforms = { uTint: F32; uSaturation: F32; uAmount: F32; + uSourceSize: Vec2; + uMaskMode: F32; + uSharpen: F32; + uSmooth: F32; uCenter: Vec2; uRadii: Vec2; uRotation: F32; @@ -87,7 +146,7 @@ const vec2 = (x: number, y: number): Vec2 => ({ }); export class LocalAdjustFilter extends Filter { - constructor(local: LocalAdjustmentV2) { + constructor(local: LocalAdjustmentV2, source: Size) { super({ glProgram: GlProgram.from({ vertex: FILTER_VERTEX, @@ -104,6 +163,10 @@ export class LocalAdjustFilter extends Filter { uTint: f32(0), uSaturation: f32(0), uAmount: f32(1), + uSourceSize: vec2(source.width, source.height), + uMaskMode: f32(0), + uSharpen: f32(0), + uSmooth: f32(0), uCenter: vec2(0.5, 0.5), uRadii: vec2(0.1, 0.1), uRotation: f32(0), @@ -111,6 +174,7 @@ export class LocalAdjustFilter extends Filter { uInvert: f32(0), uShowMask: f32(0), } satisfies LocalUniforms, + uMask: Texture.WHITE.source, }, padding: 0, antialias: "off", @@ -119,6 +183,11 @@ export class LocalAdjustFilter extends Filter { this.setLocal(local, false); } + /** ブラシマスクのテクスチャ。null で楕円 (解析的) に戻す */ + setMaskTexture(source: TextureSource | null): void { + this.resources.uMask = source ?? Texture.WHITE.source; + } + setLocal(local: LocalAdjustmentV2, showMask: boolean): void { const u = this.resources.localUniforms.uniforms as { [K in keyof LocalUniforms]: LocalUniforms[K]["value"]; @@ -132,7 +201,11 @@ export class LocalAdjustFilter extends Filter { u.uTint = a.tint / 100; u.uSaturation = a.saturation / 100; u.uAmount = local.amount / 100; + u.uSharpen = a.sharpen / 100; + u.uSmooth = a.smooth / 100; u.uShowMask = showMask ? 1 : 0; + u.uMaskMode = local.mask.kind === "brush" ? 1 : 0; + u.uInvert = local.mask.invert ? 1 : 0; if (local.mask.kind === "ellipse") { const m = local.mask; u.uCenter[0] = m.cx; @@ -141,10 +214,6 @@ export class LocalAdjustFilter extends Filter { u.uRadii[1] = m.ry; u.uRotation = (m.rotation * Math.PI) / 180; u.uFeather = Math.max(m.feather, MIN_FEATHER); - u.uInvert = m.invert ? 1 : 0; - } else { - // ブラシは PR3。それまでは何も掛けない - u.uAmount = 0; } } } diff --git a/apps/app/web/features/editor/render/mask-texture.ts b/apps/app/web/features/editor/render/mask-texture.ts new file mode 100644 index 0000000..40cd419 --- /dev/null +++ b/apps/app/web/features/editor/render/mask-texture.ts @@ -0,0 +1,68 @@ +import { Texture, TextureStyle } from "pixi.js"; +import type { BrushMaskV2, BrushStrokeV2 } from "@prismtone/shared/recipe"; +import { + createMaskRaster, + rasterizeBrushMask, + stampStroke, + type MaskRaster, +} from "../brush-raster.ts"; +import type { Size } from "./geometry.ts"; + +/** + * ブラシマスクのテクスチャ (#109)。brush-raster.ts のラスタを canvas に写して PixiJS の Texture にする。 + * レシピの確定 (commit) ではゼロから描き直し、描画中は 1 ストロークだけ足して更新する。 + */ +export class MaskTexture { + readonly texture: Texture; + private readonly canvas: HTMLCanvasElement; + private readonly ctx: CanvasRenderingContext2D; + private raster: MaskRaster; + private source: Size; + + constructor(source: Size) { + this.source = source; + this.raster = createMaskRaster(source); + this.canvas = document.createElement("canvas"); + this.canvas.width = this.raster.width; + this.canvas.height = this.raster.height; + const ctx = this.canvas.getContext("2d", { willReadFrequently: true }); + if (!ctx) throw new Error("no 2d context"); + this.ctx = ctx; + this.texture = Texture.from(this.canvas); + this.texture.source.style = new TextureStyle({ + scaleMode: "linear", + addressMode: "clamp-to-edge", + }); + this.upload(); + } + + /** マスク全体を描き直す */ + set(mask: BrushMaskV2): void { + this.raster = rasterizeBrushMask(mask, this.source); + this.upload(); + } + + /** 描画中のストロークを足す (レシピには入れない)。invert は set 側で扱うので、ここでは加算だけ */ + addStroke(stroke: BrushStrokeV2, feather: number): void { + stampStroke(this.raster, stroke, feather); + this.upload(); + } + + private upload(): void { + const { width, height, data } = this.raster; + const image = this.ctx.createImageData(width, height); + for (let i = 0; i < data.length; i++) { + const v = data[i]!; + image.data[i * 4] = v; + image.data[i * 4 + 1] = v; + image.data[i * 4 + 2] = v; + image.data[i * 4 + 3] = 255; + } + this.ctx.putImageData(image, 0, 0); + this.texture.source.update(); + } + + destroy(): void { + this.texture.destroy(true); + } +} diff --git a/apps/app/web/features/editor/state.test.ts b/apps/app/web/features/editor/state.test.ts index ad2f61d..23c7bd6 100644 --- a/apps/app/web/features/editor/state.test.ts +++ b/apps/app/web/features/editor/state.test.ts @@ -199,4 +199,42 @@ describe("editorReducer: 部分補正 (#109)", () => { expect(off.history).toBe(withOne.history); expect(editorReducer(off, { type: "ui/show-mask", on: true }).ui.local.showMask).toBe(true); }); + + it("adds a brush adjustment and appends strokes as one history step each", () => { + let s = editorReducer(loaded, { type: "local/add", kind: "brush", presetId: "gear" }); + const bid = s.history.present.localAdjustments[0]!.id; + expect(s.history.present.localAdjustments[0]!.mask.kind).toBe("brush"); + const stroke = { mode: "add" as const, size: 0.1, hardness: 0.8, points: [{ x: 0.5, y: 0.5 }] }; + s = editorReducer(s, { type: "local/stroke-commit", id: bid, stroke }); + s = editorReducer(s, { + type: "local/stroke-commit", + id: bid, + stroke: { ...stroke, mode: "erase" }, + }); + const mask = s.history.present.localAdjustments[0]!.mask; + expect(mask.kind === "brush" && mask.strokes).toHaveLength(2); + expect(s.history.pastLabels.slice(-2)).toEqual(["ブラシ", "消しゴム"]); + // ストロークはプリセットの表示を外さない (色の値は変えていない) + expect(s.history.present.localAdjustments[0]!.presetId).toBe("gear"); + }); + + it("ignores a stroke on an ellipse adjustment and beyond the stroke limit", () => { + const stroke = { mode: "add" as const, size: 0.1, hardness: 1, points: [{ x: 0.5, y: 0.5 }] }; + expect(editorReducer(withOne, { type: "local/stroke-commit", id, stroke })).toBe(withOne); + let s = editorReducer(loaded, { type: "local/add", kind: "brush" }); + const bid = s.history.present.localAdjustments[0]!.id; + for (let i = 0; i < 70; i++) + s = editorReducer(s, { type: "local/stroke-commit", id: bid, stroke }); + const mask = s.history.present.localAdjustments[0]!.mask; + expect(mask.kind === "brush" && mask.strokes).toHaveLength(64); + }); + + it("keeps the brush settings in ui state", () => { + const s = editorReducer(loaded, { + type: "ui/brush", + brush: { mode: "erase", size: 0.2, hardness: 0.3 }, + }); + expect(s.ui.local.brush).toEqual({ mode: "erase", size: 0.2, hardness: 0.3 }); + expect(initialEditorState.ui.local.brush.mode).toBe("add"); + }); }); diff --git a/apps/app/web/features/editor/state.ts b/apps/app/web/features/editor/state.ts index 5f334ae..4fe32fb 100644 --- a/apps/app/web/features/editor/state.ts +++ b/apps/app/web/features/editor/state.ts @@ -3,12 +3,14 @@ import { DEFAULT_ELLIPSE_MASK, DEFAULT_LOCAL_ADJUSTMENT, DEFAULT_RECIPE, + MAX_BRUSH_STROKES, MAX_LOCAL_ADJUSTMENTS, applyLocalPreset, applyPreset, findLocalPreset, findPreset, type AdjustV1, + type BrushStrokeV2, type EditRecipe, type GeometryV1, type LocalAdjustV2, @@ -22,6 +24,13 @@ import type { LoadedImage } from "./load-image.ts"; export type Tool = "adjust" | "geometry" | "presets" | "local"; +export type BrushSettings = { + readonly mode: BrushStrokeV2["mode"]; + /** 直径。画像の長辺に対する比 */ + readonly size: number; + readonly hardness: number; +}; + export type EditorState = { readonly source: LoadedImage | null; readonly draftId: string | null; @@ -40,6 +49,8 @@ export type EditorState = { readonly local: { readonly selectedId: string | null; readonly showMask: boolean; + /** ブラシの設定。ストロークごとにレシピへ写す */ + readonly brush: BrushSettings; }; }; }; @@ -64,7 +75,9 @@ export type EditorAction = | { type: "local/mask-preview"; id: string; mask: MaskV2 } | { type: "local/mask-commit"; id: string; mask: MaskV2 } | { type: "local/preset"; id: string; presetId: LocalPresetId } + | { type: "local/stroke-commit"; id: string; stroke: BrushStrokeV2 } | { type: "ui/show-mask"; on: boolean } + | { type: "ui/brush"; brush: BrushSettings } | { type: "history/undo" } | { type: "history/redo" } | { type: "ui/tool"; tool: Tool } @@ -86,7 +99,7 @@ export const initialEditorState: EditorState = { cropping: false, exporting: false, error: null, - local: { selectedId: null, showMask: true }, + local: { selectedId: null, showMask: true, brush: { mode: "add", size: 0.08, hardness: 0.7 } }, }, }; @@ -320,6 +333,20 @@ export function editorReducer(state: EditorState, action: EditorAction): EditorS `部分補正: ${preset.name}`, ); } + case "local/stroke-commit": { + const target = history.present.localAdjustments.find((l) => l.id === action.id); + if (!target || target.mask.kind !== "brush") return state; + if (target.mask.strokes.length >= MAX_BRUSH_STROKES) return state; + const mask = target.mask; + return localCommit( + state, + action.id, + (l) => ({ ...l, mask: { ...mask, strokes: [...mask.strokes, action.stroke] } }), + action.stroke.mode === "add" ? "ブラシ" : "消しゴム", + ); + } + case "ui/brush": + return { ...state, ui: { ...state.ui, local: { ...state.ui.local, brush: action.brush } } }; case "ui/show-mask": return { ...state, ui: { ...state.ui, local: { ...state.ui.local, showMask: action.on } } }; case "ui/tool": diff --git a/apps/app/web/features/editor/ui/BrushOverlay.tsx b/apps/app/web/features/editor/ui/BrushOverlay.tsx new file mode 100644 index 0000000..bb3a430 --- /dev/null +++ b/apps/app/web/features/editor/ui/BrushOverlay.tsx @@ -0,0 +1,107 @@ +import { useRef, useState } from "react"; +import type { BrushStrokeV2, GeometryV1 } from "@prismtone/shared/recipe"; +import { simplifyPoints } from "../brush-raster.ts"; +import { canvasToImageUv, type Point } from "../mask-math.ts"; +import type { Size } from "../render/geometry.ts"; +import type { BrushSettings } from "../state.ts"; + +type View = { x: number; y: number; width: number; height: number; scale: number }; + +type Props = { + view: View; + source: Size; + geometry: GeometryV1; + brush: BrushSettings; + /** 描画中: 直前の点から今の点までの線分をマスクに足す (レシピには入れない) */ + onPreview: (segment: BrushStrokeV2) => void; + /** 離したとき: 間引いたストロークをレシピに積む */ + onCommit: (stroke: BrushStrokeV2) => void; +}; + +/** ポインタの移動をこれ未満 (画像の長辺に対する比) なら捨てる。レシピの点数を抑える */ +const MIN_POINT_DISTANCE = 0.005; + +/** + * ブラシマスクの DOM オーバーレイ (#109)。キャンバス全体でポインタを受け、画像座標の点列にする。 + * 描画中は 1 線分ずつ renderer に足して即時に見せ、離したときに 1 ストロークとして履歴に積む。 + */ +export function BrushOverlay({ view, source, geometry, brush, onPreview, onCommit }: Props) { + const points = useRef(null); + const [cursor, setCursor] = useState<{ x: number; y: number } | null>(null); + + const toUv = (e: React.PointerEvent): Point => { + const host = (e.currentTarget as HTMLElement).getBoundingClientRect(); + const canvas = { + x: (e.clientX - host.left - view.x) / view.scale, + y: (e.clientY - host.top - view.y) / view.scale, + }; + const uv = canvasToImageUv(canvas, source, geometry); + return { x: Math.min(1, Math.max(0, uv.x)), y: Math.min(1, Math.max(0, uv.y)) }; + }; + const stroke = (pts: Point[]): BrushStrokeV2 => ({ + mode: brush.mode, + size: brush.size, + hardness: brush.hardness, + points: pts, + }); + + const onPointerDown = (e: React.PointerEvent) => { + if (e.button !== 0) return; + e.preventDefault(); + (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId); + const p = toUv(e); + points.current = [p]; + onPreview(stroke([p])); + }; + const onPointerMove = (e: React.PointerEvent) => { + const host = (e.currentTarget as HTMLElement).getBoundingClientRect(); + setCursor({ x: e.clientX - host.left, y: e.clientY - host.top }); + const pts = points.current; + if (!pts) return; + const p = toUv(e); + const last = pts[pts.length - 1]!; + if (Math.hypot(p.x - last.x, p.y - last.y) < MIN_POINT_DISTANCE) return; + pts.push(p); + onPreview(stroke([last, p])); + }; + const onPointerUp = (e: React.PointerEvent) => { + const pts = points.current; + points.current = null; + if (!pts) return; + const p = toUv(e); + const all = simplifyPoints([...pts, p], MIN_POINT_DISTANCE); + onCommit(stroke(all)); + }; + + // ブラシの円 (画面 px)。直径 = size × 長辺 × 表示倍率 + const diameter = brush.size * Math.max(source.width, source.height) * view.scale; + + return ( +
setCursor(null)} + > + {cursor && ( + + ); +} diff --git a/apps/app/web/features/editor/ui/EditorPage.tsx b/apps/app/web/features/editor/ui/EditorPage.tsx index 26c9af6..608b22a 100644 --- a/apps/app/web/features/editor/ui/EditorPage.tsx +++ b/apps/app/web/features/editor/ui/EditorPage.tsx @@ -12,6 +12,7 @@ import { PresetPanel } from "./PresetPanel.tsx"; import { GeometryPanel } from "./GeometryPanel.tsx"; import { CropOverlay } from "./CropOverlay.tsx"; import { EllipseMaskOverlay } from "./EllipseMaskOverlay.tsx"; +import { BrushOverlay } from "./BrushOverlay.tsx"; import { LocalPanel } from "./LocalPanel.tsx"; import { CompareSlider } from "./CompareSlider.tsx"; @@ -45,6 +46,9 @@ function installTestHook(renderer: EditorRenderer) { pixels: points.map((p) => Array.from(ctx.getImageData(p.x, p.y, 1, 1).data).slice(0, 3)), }; }, + benchmark(recipe: EditRecipe, frames?: number) { + return renderer.benchmark(recipe, frames); + }, }; } @@ -422,6 +426,25 @@ export function EditorPage() { } /> )} + {hasImage && + state.source && + state.ui.tool === "local" && + selectedLocal?.mask.kind === "brush" && + !state.ui.comparing && + !state.ui.cropping && ( + + rendererRef.current?.previewStroke(selectedLocal.id, segment) + } + onCommit={(stroke) => + dispatch({ type: "local/stroke-commit", id: selectedLocal.id, stroke }) + } + /> + )} {hasImage && state.ui.cropping && recipe.geometry.crop && ( dispatch({ type: "local/add", kind: "ellipse", presetId })} + brush={state.ui.local.brush} + onBrush={(brush) => dispatch({ type: "ui/brush", brush })} + onAdd={(kind, presetId) => dispatch({ type: "local/add", kind, presetId })} onSelect={(id) => dispatch({ type: "local/select", id })} onRemove={(id) => dispatch({ type: "local/remove", id })} onToggleVisible={(id) => dispatch({ type: "local/toggle-visible", id })} diff --git a/apps/app/web/features/editor/ui/LocalPanel.tsx b/apps/app/web/features/editor/ui/LocalPanel.tsx index 586c7b4..6a107eb 100644 --- a/apps/app/web/features/editor/ui/LocalPanel.tsx +++ b/apps/app/web/features/editor/ui/LocalPanel.tsx @@ -1,18 +1,23 @@ import { LOCAL_PRESETS, MAX_LOCAL_ADJUSTMENTS, + MAX_LOCAL_SMOOTH, type LocalAdjustV2, type LocalAdjustmentV2, type LocalPresetId, + type MaskV2, } from "@prismtone/shared/recipe"; import { LOCAL_ADJUST_LABELS } from "../labels.ts"; +import type { BrushSettings } from "../state.ts"; import { Slider } from "./Slider.tsx"; type Props = { list: readonly LocalAdjustmentV2[]; selectedId: string | null; showMask: boolean; - onAdd: (presetId?: LocalPresetId) => void; + brush: BrushSettings; + onAdd: (kind: MaskV2["kind"], presetId?: LocalPresetId) => void; + onBrush: (brush: BrushSettings) => void; onSelect: (id: string | null) => void; onRemove: (id: string) => void; onToggleVisible: (id: string) => void; @@ -32,7 +37,8 @@ const ROWS: { key: keyof LocalAdjustV2; min: number; max: number; step: number; { key: "temperature", min: -100, max: 100, step: 1 }, { key: "tint", min: -100, max: 100, step: 1 }, { key: "saturation", min: -100, max: 100, step: 1 }, - // シャープと美肌 (smooth、上限 MAX_LOCAL_SMOOTH) は描画が入る PR3 でここに足す + { key: "sharpen", min: 0, max: 100, step: 1 }, + { key: "smooth", min: 0, max: MAX_LOCAL_SMOOTH, step: 1 }, ]; const btn = @@ -45,7 +51,7 @@ function localName(l: LocalAdjustmentV2, index: number): string { return preset ? `${preset.name} (${kind})` : `部分補正 ${index + 1} (${kind})`; } -/** 部分補正のパネル (#109): 一覧、追加、プリセット、効果量とスライダー。ブラシの追加は PR3 */ +/** 部分補正のパネル (#109): 一覧、追加 (円形 / ブラシ)、ブラシの設定、プリセット、効果量とスライダー */ export function LocalPanel(p: Props) { const selected = p.list.find((l) => l.id === p.selectedId) ?? null; const full = p.list.length >= MAX_LOCAL_ADJUSTMENTS; @@ -56,11 +62,20 @@ export function LocalPanel(p: Props) { type="button" className={btn} disabled={full} - onClick={() => p.onAdd()} + onClick={() => p.onAdd("ellipse")} data-testid="local-add-ellipse" > 円形を追加 + {p.list.length} / {MAX_LOCAL_ADJUSTMENTS} @@ -119,9 +134,55 @@ export function LocalPanel(p: Props) { ))} )} + {selected?.mask.kind === "brush" && ( +
+
+ キャンバスをなぞって範囲を塗る + + {( + [ + ["add", "塗る"], + ["erase", "消す"], + ] as const + ).map(([mode, label]) => ( + + ))} +
+ `${v}%`} + onPreview={(v) => p.onBrush({ ...p.brush, size: v / 100 })} + onCommit={(v) => p.onBrush({ ...p.brush, size: v / 100 })} + /> + `${v}%`} + onPreview={(v) => p.onBrush({ ...p.brush, hardness: v / 100 })} + onCommit={(v) => p.onBrush({ ...p.brush, hardness: v / 100 })} + /> +
+ )}

- {selected ? "選択中の範囲に適用" : "新しい円形マスクを追加して適用"} + {selected + ? "選択中の範囲に適用" + : "新しいマスクを追加して適用 (瞳・美肌は円形、装備はブラシ)"}

{LOCAL_PRESETS.map((preset) => ( @@ -132,7 +193,11 @@ export function LocalPanel(p: Props) { aria-pressed={selected?.presetId === preset.id} title={preset.hint} disabled={!selected && full} - onClick={() => (selected ? p.onPreset(selected.id, preset.id) : p.onAdd(preset.id))} + onClick={() => + selected + ? p.onPreset(selected.id, preset.id) + : p.onAdd(preset.id === "gear" ? "brush" : "ellipse", preset.id) + } > {preset.name} diff --git a/e2e/editor.spec.ts b/e2e/editor.spec.ts index 9e33272..5e1d3ab 100644 --- a/e2e/editor.spec.ts +++ b/e2e/editor.spec.ts @@ -1,5 +1,6 @@ import { expect, test, type Page } from "@playwright/test"; import { + DEFAULT_BRUSH_MASK, DEFAULT_ELLIPSE_MASK, DEFAULT_LOCAL_ADJUST, DEFAULT_LOCAL_ADJUSTMENT, @@ -217,6 +218,77 @@ test.describe("editor", () => { ); }); + test("a brush mask applies along its strokes, erase takes it back, and smoothing leaves flat areas alone (#109)", async ({ + page, + }) => { + await openEditorWithImage(page); + const size = { width: 200, height: 100 }; + const stroke = (x: number, mode: "add" | "erase" = "add") => ({ + mode, + size: 0.15, // 直径 30px、半径 15px + hardness: 1, + points: [{ x, y: 0.5 }], + }); + // 緑と青のブロックの中心を塗り、青の方を消す。露光 +1 と美肌 (平滑化) を掛ける + const gear = { + ...DEFAULT_LOCAL_ADJUSTMENT, + id: "gear", + mask: { + ...DEFAULT_BRUSH_MASK, + strokes: [stroke(0.375), stroke(0.625), stroke(0.625, "erase")], + }, + adjust: { ...DEFAULT_LOCAL_ADJUST, exposure: 1, smooth: 60, sharpen: 40 }, + amount: 100, + }; + const recipe: EditRecipe = { ...DEFAULT_RECIPE, localAdjustments: [gear] }; + const cpu = (rgb: [number, number, number], uv: { x: number; y: number }) => + applyRecipeAt(rgb.map((v) => v / 255) as [number, number, number], uv, recipe, size).map( + (v) => Math.round(v * 255), + ); + const out = await exportPixels(page, recipe, [ + { x: 75, y: 50 }, // 緑の中心 (塗った) + { x: 125, y: 50 }, // 青の中心 (塗って消した) + { x: 25, y: 50 }, // 赤 (塗っていない) + ]); + // 平坦部なので平滑化・シャープは値を変えず、露光だけが効く + expectClose(out.pixels[0]!, cpu(BLOCKS[1]!, { x: 0.375, y: 0.5 }), 3); + expectClose(out.pixels[1]!, BLOCKS[2]!, 2); + expectClose(out.pixels[2]!, BLOCKS[0]!, 2); + expect(out.pixels[0]).not.toEqual(BLOCKS[1]); + }); + + test("the brush tool paints and erases on the canvas, one history step per stroke (#109)", async ({ + page, + }) => { + await openEditorWithImage(page); + await page.getByRole("tab", { name: "部分補正" }).click(); + // 装備強調はブラシで始まる + await page.getByRole("button", { name: "装備強調" }).click(); + await expect(page.getByTestId("local-list")).toContainText("装備強調 (ブラシ)"); + await expect(page.getByTestId("brush-settings")).toBeVisible(); + await expect(page.getByTestId("brush-overlay")).toBeVisible(); + await expect(page.getByTestId("local-sliders").getByLabel("美肌")).toBeVisible(); + + const host = await page.getByTestId("canvas-host").boundingBox(); + if (!host) throw new Error("no canvas"); + const y = host.y + host.height / 2; + const x0 = host.x + host.width * 0.3; + await page.mouse.move(x0, y); + await page.mouse.down(); + await page.mouse.move(x0 + 60, y, { steps: 6 }); + await page.mouse.up(); + await expect(page.getByTestId("history-last")).toContainText("ブラシ"); + + await page.getByRole("button", { name: "消す", exact: true }).click(); + await page.mouse.move(x0, y); + await page.mouse.down(); + await page.mouse.move(x0 + 20, y, { steps: 3 }); + await page.mouse.up(); + await expect(page.getByTestId("history-last")).toContainText("消しゴム"); + await page.getByTestId("history-undo").click(); + await expect(page.getByTestId("history-last")).toContainText("ブラシ"); + }); + test("the local panel adds an ellipse, drags it, undoes, hides, and survives a redo of the export (#109)", async ({ page, }) => { diff --git a/e2e/perf-local-adjust.spec.ts b/e2e/perf-local-adjust.spec.ts new file mode 100644 index 0000000..4dfb477 --- /dev/null +++ b/e2e/perf-local-adjust.spec.ts @@ -0,0 +1,104 @@ +import { expect, test, type Page } from "@playwright/test"; +import { + DEFAULT_BRUSH_MASK, + DEFAULT_ELLIPSE_MASK, + DEFAULT_LOCAL_ADJUST, + DEFAULT_LOCAL_ADJUSTMENT, + DEFAULT_RECIPE, + type EditRecipe, + type LocalAdjustmentV2, +} from "@prismtone/shared/recipe"; + +/** + * 部分補正の性能計測 (#109、docs/spikes/2026-09-20-local-adjust-perf.md)。 + * 通常の E2E では走らせない。PERF=1 pnpm exec playwright test e2e/perf-local-adjust.spec.ts --headed + * headless (SwiftShader、CPU 描画) は上限の目安。実機の GPU では --headed で取る + */ +test.skip(!process.env.PERF, "PERF=1 のときだけ"); + +async function makeNoisePng(page: Page, width: number, height: number): Promise { + const dataUrl = await page.evaluate( + ({ width, height }) => { + const c = document.createElement("canvas"); + c.width = width; + c.height = height; + const ctx = c.getContext("2d")!; + const img = ctx.createImageData(width, height); + let seed = 1; + for (let i = 0; i < img.data.length; i += 4) { + seed = (seed * 1103515245 + 12345) & 0x7fffffff; + img.data[i] = seed & 255; + img.data[i + 1] = (seed >> 8) & 255; + img.data[i + 2] = (seed >> 16) & 255; + img.data[i + 3] = 255; + } + ctx.putImageData(img, 0, 0); + return c.toDataURL("image/png"); + }, + { width, height }, + ); + return Buffer.from(dataUrl.split(",")[1]!, "base64"); +} + +const local = (i: number): LocalAdjustmentV2 => ({ + ...DEFAULT_LOCAL_ADJUSTMENT, + id: `l${i}`, + mask: + i % 2 === 0 + ? { ...DEFAULT_ELLIPSE_MASK, cx: 0.2 + i * 0.08, cy: 0.5, rx: 0.1, ry: 0.15 } + : { + ...DEFAULT_BRUSH_MASK, + strokes: [ + { + mode: "add", + size: 0.1, + hardness: 0.8, + points: Array.from({ length: 64 }, (_, k) => ({ + x: 0.1 + k * 0.012, + y: 0.3 + i * 0.05, + })), + }, + ], + }, + adjust: { ...DEFAULT_LOCAL_ADJUST, exposure: 0.3, sharpen: 30, smooth: i % 2 === 0 ? 0 : 40 }, +}); + +test("measure develop / export time and texture memory for 0 / 4 / 8 local adjustments", async ({ + page, +}) => { + test.setTimeout(600_000); + await page.addInitScript(() => { + (window as Window & { __PRISMTONE_E2E__?: boolean }).__PRISMTONE_E2E__ = true; + }); + await page.goto("/edit"); + const png = await makeNoisePng(page, 4096, 2304); + await page + .getByTestId("file-input") + .setInputFiles({ name: "4k.png", mimeType: "image/png", buffer: png }); + await page.waitForFunction(() => + Boolean((window as Window & { __prismtoneEditor?: unknown }).__prismtoneEditor), + ); + await expect(page.getByRole("button", { name: "端末に保存" })).toBeEnabled({ timeout: 60_000 }); + const gpu = await page.evaluate(() => { + const gl = document.createElement("canvas").getContext("webgl2"); + const dbg = gl?.getExtension("WEBGL_debug_renderer_info"); + return dbg && gl ? String(gl.getParameter(dbg.UNMASKED_RENDERER_WEBGL)) : "unknown"; + }); + console.log(`renderer: ${gpu}`); + for (const n of [0, 4, 8]) { + const recipe: EditRecipe = { + ...DEFAULT_RECIPE, + localAdjustments: Array.from({ length: n }, (_, i) => local(i)), + }; + const r = await page.evaluate( + (recipe) => + ( + window as Window & { + __prismtoneEditor?: { benchmark: (r: EditRecipe, frames?: number) => Promise }; + } + ).__prismtoneEditor!.benchmark(recipe, 20), + recipe, + ); + console.log(`locals=${n} ${JSON.stringify(r)}`); + } +}); From 07ce609f901a256d9cf98b74734d84be299d7279 Mon Sep 17 00:00:00 2001 From: t1nyb0x Date: Sun, 20 Sep 2026 12:52:32 +0900 Subject: [PATCH 16/49] =?UTF-8?q?fix:=20=E7=B7=A8=E9=9B=86=E7=94=BB?= =?UTF-8?q?=E9=9D=A2=E3=81=A7=E7=AA=93=E3=82=92=E7=8B=AD=E3=82=81=E3=82=8B?= =?UTF-8?q?=E3=81=A8=E5=8F=B3=E3=83=91=E3=83=8D=E3=83=AB=E3=81=8C=E6=8A=BC?= =?UTF-8?q?=E3=81=97=E5=87=BA=E3=81=95=E3=82=8C=E3=82=8B=E5=95=8F=E9=A1=8C?= =?UTF-8?q?=E3=82=92=E7=9B=B4=E3=81=97=E3=80=81=E3=82=BA=E3=83=BC=E3=83=A0?= =?UTF-8?q?=E3=81=A8=E7=A7=BB=E5=8B=95=E3=82=92=E8=B6=B3=E3=81=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 余白の原因: PixiJS の resizeTo が canvas に px の幅を書くため、窓を狭めても flex の子 (section) が その幅より縮めず、右パネルが画面外に押し出され、canvas も古い大きさのまま残って画像が ホストいっぱいに収まらなかった。canvas を絶対配置にし、section に min-w-0 を付けて直す。 ズーム (docs/design/08 §3.3 の「ピンチ/ホイールでズーム」): render/viewport.ts (純関数) で フィットに対する倍率と移動を持ち、Ctrl (Cmd) + ホイールとピンチはカーソルを軸に拡大縮小、 ホイールは移動、ツールバーに −/+/倍率 (押すと等倍)/フィット。フィットの 0.5〜8 倍、小さい画像は 等倍まで縮められる。オーバーレイは viewRect から位置を出すのでそのまま追従する。 ドラッグに割り当てないのは、ブラシと円形マスクのオーバーレイがポインタを使うため。 E2E: 窓を 1800 → 1100 に縮めても右パネルが収まり画像がホストに合う。拡大ボタン、Ctrl + ホイールで カーソル側を軸に拡大しハンドルが追従、ホイールで移動、フィットと等倍。 Co-Authored-By: Claude Opus 5 --- .../features/editor/render/editor-renderer.ts | 85 ++++++++++++++-- .../features/editor/render/viewport.test.ts | 62 ++++++++++++ .../web/features/editor/render/viewport.ts | 82 ++++++++++++++++ .../app/web/features/editor/ui/EditorPage.tsx | 96 ++++++++++++++++++- e2e/editor.spec.ts | 70 ++++++++++++++ 5 files changed, 387 insertions(+), 8 deletions(-) create mode 100644 apps/app/web/features/editor/render/viewport.test.ts create mode 100644 apps/app/web/features/editor/render/viewport.ts diff --git a/apps/app/web/features/editor/render/editor-renderer.ts b/apps/app/web/features/editor/render/editor-renderer.ts index 72713f4..66ee777 100644 --- a/apps/app/web/features/editor/render/editor-renderer.ts +++ b/apps/app/web/features/editor/render/editor-renderer.ts @@ -14,6 +14,15 @@ import { import type { BrushStrokeV2, EditRecipe, GeometryV1 } from "@prismtone/shared/recipe"; import { DevelopStage } from "./develop-stage.ts"; import { canvasSize, cropRect, exportScale, totalRotationDeg, type Size } from "./geometry.ts"; +import { + clampPan, + DEFAULT_VIEWPORT, + panBy, + place, + zoomAt, + ZOOM_STEP, + type Viewport, +} from "./viewport.ts"; export type ExportFormat = "image/webp" | "image/jpeg" | "image/png"; @@ -80,6 +89,8 @@ export class EditorRenderer { /** 比較の境界。0 = 全部現像後、1 = 全部元画像 (左が元画像、右が現像後) */ private comparePosition = 0.5; private resizeObserver: ResizeObserver | null = null; + /** 表示のズームと移動。レシピではなく画面の状態 (docs/design/08 §3.3) */ + private viewport: Viewport = DEFAULT_VIEWPORT; static async create(host: HTMLElement): Promise { const app = new Application(); @@ -91,6 +102,10 @@ export class EditorRenderer { resolution: Math.min(window.devicePixelRatio || 1, 2), preference: "webgl", }); + // resizeTo が canvas に px の幅・高さを書く。通常フローに置くとその幅が親の最小幅になり、 + // 窓を狭めても親が縮まない。絶対配置にしてレイアウトに影響させない + app.canvas.style.position = "absolute"; + app.canvas.style.inset = "0"; host.appendChild(app.canvas); const r = new EditorRenderer(app, host); app.stage.addChild(r.stage); @@ -126,6 +141,7 @@ export class EditorRenderer { this.original = original; this.image.addChild(original); this.source = { width: bitmap.width, height: bitmap.height }; + this.viewport = DEFAULT_VIEWPORT; this.develop = new DevelopStage(texture, this.previewSize, recipe); const sprite = new Sprite(this.develop.texture); sprite.anchor.set(0.5); @@ -290,17 +306,72 @@ export class EditorRenderer { }; } + private get hostSize(): Size { + return { width: this.host.clientWidth, height: this.host.clientHeight }; + } + + /** 現在のズームと移動でステージを置く。ホストの寸法が変わったときは移動を抑え直す */ fit(): void { if (!this.sprite) return; - const size = this.canvasSize; - const w = this.host.clientWidth; - const h = this.host.clientHeight; - if (w === 0 || h === 0) return; - const s = Math.min(w / size.width, h / size.height) * 0.96; - this.stage.scale.set(s); - this.stage.position.set((w - size.width * s) / 2, (h - size.height * s) / 2); + const host = this.hostSize; + if (host.width === 0 || host.height === 0) return; + this.viewport = clampPan(this.canvasSize, host, this.viewport); + const p = place(this.canvasSize, host, this.viewport); + this.stage.scale.set(p.scale); + this.stage.position.set(p.x, p.y); + } + + /** 元画像の px に対する表示倍率 (1 = 等倍) */ + get displayScale(): number { + return this.stage.scale.x; + } + + get zoom(): number { + return this.viewport.zoom; } + /** 倍率を factor 倍する。anchor (ホスト内の CSS px) の下の点は動かない */ + zoomBy(factor: number, anchor?: { x: number; y: number }): void { + if (!this.sprite) return; + this.viewport = zoomAt( + this.canvasSize, + this.hostSize, + this.viewport, + this.viewport.zoom * factor, + anchor, + ); + this.fit(); + } + + /** フィット表示に対する倍率を直接指定する (1 = フィット)。anchor はホストの中央 */ + setZoom(zoom: number): void { + if (!this.sprite) return; + this.viewport = zoomAt(this.canvasSize, this.hostSize, this.viewport, zoom); + this.fit(); + } + + /** 元画像の等倍 (1 画像 px = 1 CSS px) にする */ + zoomToActual(): void { + if (!this.sprite) return; + const fit = place(this.canvasSize, this.hostSize, DEFAULT_VIEWPORT).scale; + this.setZoom(1 / fit); + } + + resetView(): void { + this.viewport = DEFAULT_VIEWPORT; + this.fit(); + } + + /** CSS px だけ表示を動かす */ + panBy(dx: number, dy: number): void { + if (!this.sprite) return; + this.viewport = panBy(this.canvasSize, this.hostSize, this.viewport, dx, dy); + this.fit(); + } + + /** ホイール 1 ノッチぶんの倍率 */ + static readonly ZOOM_STEP = ZOOM_STEP; + async export(recipe: EditRecipe, opts: ExportOptions = {}): Promise { if (!this.sprite || !this.develop) throw new Error("no image loaded"); const wasComparing = this.comparing; diff --git a/apps/app/web/features/editor/render/viewport.test.ts b/apps/app/web/features/editor/render/viewport.test.ts new file mode 100644 index 0000000..58adbae --- /dev/null +++ b/apps/app/web/features/editor/render/viewport.test.ts @@ -0,0 +1,62 @@ +import { describe, expect, it } from "vitest"; +import { + clampPan, + DEFAULT_VIEWPORT, + fitScale, + MAX_ZOOM, + MIN_ZOOM, + panBy, + place, + zoomAt, +} from "./viewport.ts"; + +const near = (a: number, b: number, eps = 1e-6) => Math.abs(a - b) < eps; +const canvas = { width: 1000, height: 2000 }; +const host = { width: 800, height: 600 }; + +describe("viewport", () => { + it("fit places the image centered with a 4% margin", () => { + const p = place(canvas, host, DEFAULT_VIEWPORT); + expect(near(p.scale, (600 / 2000) * 0.96)).toBe(true); + expect(near(p.x, (800 - 1000 * p.scale) / 2)).toBe(true); + expect(near(p.y, (600 - 2000 * p.scale) / 2)).toBe(true); + }); + + it("zoomAt keeps the image point under the anchor fixed", () => { + const anchor = { x: 500, y: 200 }; + const before = place(canvas, host, DEFAULT_VIEWPORT); + const ix = (anchor.x - before.x) / before.scale; + const iy = (anchor.y - before.y) / before.scale; + const vp = zoomAt(canvas, host, DEFAULT_VIEWPORT, 2, anchor); + const after = place(canvas, host, vp); + expect(near(after.x + ix * after.scale, anchor.x)).toBe(true); + expect(near(after.y + iy * after.scale, anchor.y)).toBe(true); + expect(near(after.scale, fitScale(canvas, host) * 2)).toBe(true); + }); + + it("clamps zoom to the allowed range", () => { + expect(zoomAt(canvas, host, DEFAULT_VIEWPORT, 100).zoom).toBe(MAX_ZOOM); + expect(zoomAt(canvas, host, DEFAULT_VIEWPORT, 0.01).zoom).toBe(MIN_ZOOM); + }); + + it("lets a small image shrink to actual size even below the usual minimum", () => { + const small = { width: 200, height: 100 }; + const fit = fitScale(small, host); // > 1 + const vp = zoomAt(small, host, DEFAULT_VIEWPORT, 1 / fit); + expect(near(place(small, host, vp).scale, 1)).toBe(true); + expect(zoomAt(small, host, DEFAULT_VIEWPORT, 0.001).zoom).toBeCloseTo(1 / fit, 6); + }); + + it("pan cannot push the image completely out of the host", () => { + const vp = panBy(canvas, host, { zoom: 2, pan: { x: 0, y: 0 } }, 100_000, -100_000); + const p = place(canvas, host, vp); + // 画像の左端はホストの中央より右に行かず、下端は中央より上に行かない + expect(p.x).toBeLessThanOrEqual(host.width / 2 + 1e-6); + expect(p.y + canvas.height * p.scale).toBeGreaterThanOrEqual(host.height / 2 - 1e-6); + }); + + it("clampPan leaves a viewport that already fits untouched", () => { + const vp = clampPan(canvas, host, DEFAULT_VIEWPORT); + expect(vp).toEqual(DEFAULT_VIEWPORT); + }); +}); diff --git a/apps/app/web/features/editor/render/viewport.ts b/apps/app/web/features/editor/render/viewport.ts new file mode 100644 index 0000000..258969b --- /dev/null +++ b/apps/app/web/features/editor/render/viewport.ts @@ -0,0 +1,82 @@ +import type { Size } from "./geometry.ts"; + +/** + * 表示のズームと移動 (純粋な計算、PixiJS に依存しない)。 + * zoom はフィット表示に対する倍率 (1 = ホストに収まる)。pan はフィット時の中央からのずれ (CSS px)。 + * 画像がホストから完全に出ないよう pan を clamp する。 + */ +export type Viewport = { zoom: number; pan: { x: number; y: number } }; + +export const MIN_ZOOM = 0.5; +export const MAX_ZOOM = 8; +export const FIT_MARGIN = 0.96; +export const DEFAULT_VIEWPORT: Viewport = { zoom: 1, pan: { x: 0, y: 0 } }; + +const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v)); + +/** ホストに収まる倍率 (画像 px → CSS px) */ +export function fitScale(canvas: Size, host: Size): number { + return Math.min(host.width / canvas.width, host.height / canvas.height) * FIT_MARGIN; +} + +/** 表示の倍率と、ステージの左上位置 (CSS px) */ +export function place( + canvas: Size, + host: Size, + vp: Viewport, +): { scale: number; x: number; y: number } { + const scale = fitScale(canvas, host) * vp.zoom; + return { + scale, + x: (host.width - canvas.width * scale) / 2 + vp.pan.x, + y: (host.height - canvas.height * scale) / 2 + vp.pan.y, + }; +} + +/** 画像の端がホストの中央を越えて外へ出ないよう pan を抑える */ +export function clampPan(canvas: Size, host: Size, vp: Viewport): Viewport { + const scale = fitScale(canvas, host) * vp.zoom; + const limitX = Math.max(0, (canvas.width * scale - host.width) / 2 + host.width / 2); + const limitY = Math.max(0, (canvas.height * scale - host.height) / 2 + host.height / 2); + return { + zoom: vp.zoom, + pan: { x: clamp(vp.pan.x, -limitX, limitX), y: clamp(vp.pan.y, -limitY, limitY) }, + }; +} + +/** + * anchor (ホスト内の CSS px) の下にある画像の点を動かさずに倍率を変える。 + * anchor を省くとホストの中央 + */ +export function zoomAt( + canvas: Size, + host: Size, + vp: Viewport, + nextZoom: number, + anchor: { x: number; y: number } = { x: host.width / 2, y: host.height / 2 }, +): Viewport { + // 小さい画像はフィットが等倍より大きい。等倍 (1 / fit) までは縮められるようにする + const zoom = clamp(nextZoom, Math.min(MIN_ZOOM, 1 / fitScale(canvas, host)), MAX_ZOOM); + const before = place(canvas, host, vp); + // anchor の画像座標 (px) + const ix = (anchor.x - before.x) / before.scale; + const iy = (anchor.y - before.y) / before.scale; + const scale = fitScale(canvas, host) * zoom; + // 同じ画像座標が anchor に来る左上位置 → 中央基準の pan に戻す + const x = anchor.x - ix * scale; + const y = anchor.y - iy * scale; + return clampPan(canvas, host, { + zoom, + pan: { + x: x - (host.width - canvas.width * scale) / 2, + y: y - (host.height - canvas.height * scale) / 2, + }, + }); +} + +export function panBy(canvas: Size, host: Size, vp: Viewport, dx: number, dy: number): Viewport { + return clampPan(canvas, host, { zoom: vp.zoom, pan: { x: vp.pan.x + dx, y: vp.pan.y + dy } }); +} + +/** ホイールの 1 ノッチで進む倍率の刻み */ +export const ZOOM_STEP = 1.25; diff --git a/apps/app/web/features/editor/ui/EditorPage.tsx b/apps/app/web/features/editor/ui/EditorPage.tsx index 608b22a..258ea2d 100644 --- a/apps/app/web/features/editor/ui/EditorPage.tsx +++ b/apps/app/web/features/editor/ui/EditorPage.tsx @@ -10,6 +10,7 @@ import type { EditorRenderer } from "../render/editor-renderer.ts"; import { AdjustPanel } from "./AdjustPanel.tsx"; import { PresetPanel } from "./PresetPanel.tsx"; import { GeometryPanel } from "./GeometryPanel.tsx"; +import { ZOOM_STEP } from "../render/viewport.ts"; import { CropOverlay } from "./CropOverlay.tsx"; import { EllipseMaskOverlay } from "./EllipseMaskOverlay.tsx"; import { BrushOverlay } from "./BrushOverlay.tsx"; @@ -49,6 +50,9 @@ function installTestHook(renderer: EditorRenderer) { benchmark(recipe: EditRecipe, frames?: number) { return renderer.benchmark(recipe, frames); }, + viewRect() { + return renderer.viewRect; + }, }; } @@ -117,6 +121,49 @@ export function EditorPage() { rendererRef.current?.setMaskPreview(maskPreviewId); }, [maskPreviewId, state.source]); + // ズームと移動 (docs/design/08 §3.3): Ctrl (Cmd) + ホイールとピンチで拡大縮小、ホイールで移動。 + // preventDefault するので passive にできず、React の onWheel ではなく直接 listen する + useEffect(() => { + const host = hostRef.current; + if (!host) return; + const onWheel = (e: WheelEvent) => { + const r = rendererRef.current; + if (!r || !state.source) return; + e.preventDefault(); + if (e.ctrlKey || e.metaKey) { + const rect = host.getBoundingClientRect(); + const factor = Math.exp(-e.deltaY * 0.01); + r.zoomBy(factor, { x: e.clientX - rect.left, y: e.clientY - rect.top }); + } else { + r.panBy(-e.deltaX, -e.deltaY); + } + setView(r.viewRect); + }; + host.addEventListener("wheel", onWheel, { passive: false }); + return () => host.removeEventListener("wheel", onWheel); + }, [state.source]); + + const zoomBy = (factor: number) => { + const r = rendererRef.current; + if (!r) return; + r.zoomBy(factor); + setView(r.viewRect); + }; + const zoomFit = () => { + const r = rendererRef.current; + if (!r) return; + r.resetView(); + setView(r.viewRect); + }; + const zoomActual = () => { + const r = rendererRef.current; + if (!r) return; + r.zoomToActual(); + setView(r.viewRect); + }; + // 表示倍率 (元画像の px に対して)。デバイスの px ではなく CSS px + const zoomPercent = Math.round(view.scale * 100); + // リサイズで枠位置を追従 useEffect(() => { const host = hostRef.current; @@ -295,7 +342,8 @@ export function EditorPage() { return (
-
+ {/* min-w-0: canvas の明示幅で flex の子が縮めなくなり、窓を狭めたとき右パネルが押し出されるのを防ぐ */} +
+ + + + + +
{p.list.length === 0 ? (

diff --git a/e2e/editor.spec.ts b/e2e/editor.spec.ts index ac67c2c..e635e8c 100644 --- a/e2e/editor.spec.ts +++ b/e2e/editor.spec.ts @@ -372,6 +372,12 @@ test.describe("editor", () => { "false", ); + // 「枠を表示」を外すと輪郭とハンドルが消え、戻すと出る + await page.getByLabel("枠を表示").uncheck(); + await expect(page.getByTestId("ellipse-overlay")).toHaveCount(0); + await page.getByLabel("枠を表示").check(); + await expect(page.getByTestId("ellipse-overlay")).toBeVisible(); + // 隠すとオーバーレイは残るが (選択中)、非表示の印になる await page.getByRole("button", { name: "表示中" }).click(); await expect(page.getByTestId("local-list")).toContainText("非表示"); From d48d4a8afb2b296cdcda63d1e3d448853ea85a7a Mon Sep 17 00:00:00 2001 From: t1nyb0x Date: Sun, 20 Sep 2026 15:33:20 +0900 Subject: [PATCH 22/49] =?UTF-8?q?feat:=20=E3=82=BA=E3=83=BC=E3=83=A0?= =?UTF-8?q?=E3=81=A8=E7=A7=BB=E5=8B=95=E3=82=92=E3=83=9B=E3=82=A4=E3=83=BC?= =?UTF-8?q?=E3=83=AB=E3=83=BB=E3=83=89=E3=83=A9=E3=83=83=E3=82=B0=E3=83=BB?= =?UTF-8?q?2=20=E6=9C=AC=E6=8C=87=E3=81=AE=E3=83=94=E3=83=B3=E3=83=81?= =?UTF-8?q?=E3=81=AB=E3=81=97=E3=81=A6=E3=80=81=E3=82=B9=E3=83=9E=E3=83=9B?= =?UTF-8?q?=E3=81=A7=E3=82=82=E5=8B=95=E3=81=8F=E3=82=88=E3=81=86=E3=81=AB?= =?UTF-8?q?=E3=81=99=E3=82=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 前の割り当て (Ctrl + ホイールでズーム、ホイールで移動) はトラックパッド前提で、マウスだと 直感的でなく、スマホでは wheel が来ないのでピンチもドラッグも効かなかった。 - ホイール: カーソルを軸にズーム (Ctrl 付きのトラックパッドのピンチも同じ) - ドラッグ: 移動。ブラシ・ハンドル・トリミング枠の上では起きない。中ボタンと Space + ドラッグはどこでも - 2 本指: ピンチでズーム、そのまま動かして移動。ブラシで描いている途中に 2 本目が触れたら ピンチに切り替え、描きかけは捨てる (pointercancel → BrushOverlay の onCancel → discardPreviewStroke) - ホストに touch-action: none ジェスチャの計算 (ui/gesture.ts) は純関数で単体テスト。判断はホストのネイティブ capture で ツールより先に行う (ui/use-canvas-gestures.ts)。 E2E: ホイールで拡大しハンドルが追従、ドラッグで移動、タッチのポインタイベントを送ってピンチで 2 倍、 ブラシ中に 2 本目が触れるとピンチになりストロークは積まれない。 Co-Authored-By: Claude Opus 5 --- .../features/editor/render/develop-stage.ts | 8 + .../features/editor/render/editor-renderer.ts | 5 + .../web/features/editor/ui/BrushOverlay.tsx | 12 +- .../app/web/features/editor/ui/EditorPage.tsx | 34 ++-- .../web/features/editor/ui/gesture.test.ts | 43 +++++ apps/app/web/features/editor/ui/gesture.ts | 46 +++++ .../features/editor/ui/use-canvas-gestures.ts | 158 ++++++++++++++++++ e2e/editor.spec.ts | 102 +++++++++-- 8 files changed, 372 insertions(+), 36 deletions(-) create mode 100644 apps/app/web/features/editor/ui/gesture.test.ts create mode 100644 apps/app/web/features/editor/ui/gesture.ts create mode 100644 apps/app/web/features/editor/ui/use-canvas-gestures.ts diff --git a/apps/app/web/features/editor/render/develop-stage.ts b/apps/app/web/features/editor/render/develop-stage.ts index 29b90cf..fef409e 100644 --- a/apps/app/web/features/editor/render/develop-stage.ts +++ b/apps/app/web/features/editor/render/develop-stage.ts @@ -83,6 +83,14 @@ export class DevelopStage { this.dirty = true; } + /** 描きかけを捨て、レシピにあるストロークだけでマスクを描き直す */ + discardPreviewStroke(id: string): void { + const entry = this.masks.get(id); + if (!entry || entry.mask.kind !== "brush") return; + entry.texture.set(entry.mask); + this.dirty = true; + } + /** 描画中のストロークをマスクに足す (レシピに入れる前のプレビュー) */ previewStroke(id: string, stroke: BrushStrokeV2): void { const entry = this.masks.get(id); diff --git a/apps/app/web/features/editor/render/editor-renderer.ts b/apps/app/web/features/editor/render/editor-renderer.ts index e22a2ca..b3324da 100644 --- a/apps/app/web/features/editor/render/editor-renderer.ts +++ b/apps/app/web/features/editor/render/editor-renderer.ts @@ -237,6 +237,11 @@ export class EditorRenderer { this.develop?.previewStroke(id, stroke); } + /** 描きかけのストロークを捨てる (ピンチに切り替わったとき) */ + discardPreviewStroke(id: string): void { + this.develop?.discardPreviewStroke(id); + } + /** 選択中の部分補正の範囲を赤で重ねる (null で消す) */ setMaskPreview(id: string | null): void { this.previewMaskId = id; diff --git a/apps/app/web/features/editor/ui/BrushOverlay.tsx b/apps/app/web/features/editor/ui/BrushOverlay.tsx index 536a4bc..6f7e9e1 100644 --- a/apps/app/web/features/editor/ui/BrushOverlay.tsx +++ b/apps/app/web/features/editor/ui/BrushOverlay.tsx @@ -18,6 +18,8 @@ type Props = { onCommit: (stroke: BrushStrokeV2) => void; /** 押している間 true。範囲の赤い重ねを出すために使う */ onDrawing: (on: boolean) => void; + /** 描きかけを捨てる (ピンチに切り替わったとき)。プレビューで足した分を消すためにレシピを描き直す */ + onCancel: () => void; }; /** ポインタの移動をこれ未満 (画像の長辺に対する比) なら捨てる。レシピの点数を抑える */ @@ -35,6 +37,7 @@ export function BrushOverlay({ onPreview, onCommit, onDrawing, + onCancel, }: Props) { const points = useRef(null); const [cursor, setCursor] = useState<{ x: number; y: number } | null>(null); @@ -84,6 +87,13 @@ export function BrushOverlay({ const all = simplifyPoints([...pts, p], MIN_POINT_DISTANCE); onCommit(stroke(all)); }; + /** 2 本目の指が触れた (ピンチに切り替わった) など。描きかけは捨てる */ + const onPointerCancel = () => { + if (!points.current) return; + points.current = null; + onDrawing(false); + onCancel(); + }; // ブラシの円 (画面 px)。直径 = size × 長辺 × 表示倍率 const diameter = brush.size * Math.max(source.width, source.height) * view.scale; @@ -95,7 +105,7 @@ export function BrushOverlay({ onPointerDown={onPointerDown} onPointerMove={onPointerMove} onPointerUp={onPointerUp} - onPointerCancel={onPointerUp} + onPointerCancel={onPointerCancel} onPointerLeave={() => setCursor(null)} > {cursor && ( diff --git a/apps/app/web/features/editor/ui/EditorPage.tsx b/apps/app/web/features/editor/ui/EditorPage.tsx index 13cc820..1d75f29 100644 --- a/apps/app/web/features/editor/ui/EditorPage.tsx +++ b/apps/app/web/features/editor/ui/EditorPage.tsx @@ -11,6 +11,7 @@ import { AdjustPanel } from "./AdjustPanel.tsx"; import { PresetPanel } from "./PresetPanel.tsx"; import { GeometryPanel } from "./GeometryPanel.tsx"; import { ZOOM_STEP } from "../render/viewport.ts"; +import { useCanvasGestures } from "./use-canvas-gestures.ts"; import { CropOverlay } from "./CropOverlay.tsx"; import { EllipseMaskOverlay } from "./EllipseMaskOverlay.tsx"; import { BrushOverlay } from "./BrushOverlay.tsx"; @@ -134,26 +135,12 @@ export function EditorPage() { rendererRef.current?.setMaskPreview(maskPreviewId); }, [maskPreviewId, state.source]); - // ズームと移動 (docs/design/08 §3.3): Ctrl (Cmd) + ホイールとピンチで拡大縮小、ホイールで移動。 - // preventDefault するので passive にできず、React の onWheel ではなく直接 listen する - useEffect(() => { - const host = hostRef.current; - if (!host) return; - const onWheel = (e: WheelEvent) => { - const r = rendererRef.current; - if (!r || !state.source) return; - e.preventDefault(); - if (e.ctrlKey || e.metaKey) { - const rect = host.getBoundingClientRect(); - const factor = Math.exp(-e.deltaY * 0.01); - r.zoomBy(factor, { x: e.clientX - rect.left, y: e.clientY - rect.top }); - } else { - r.panBy(-e.deltaX, -e.deltaY); - } - }; - host.addEventListener("wheel", onWheel, { passive: false }); - return () => host.removeEventListener("wheel", onWheel); - }, [state.source]); + // ズームと移動 (docs/design/08 §3.3): ホイールでズーム、ドラッグで移動、2 本指でピンチ + const gestureTarget = useCallback( + () => (state.source ? rendererRef.current : null), + [state.source], + ); + useCanvasGestures(hostRef, gestureTarget, Boolean(state.source)); const zoomBy = (factor: number) => rendererRef.current?.zoomBy(factor); const zoomFit = () => rendererRef.current?.resetView(); @@ -396,7 +383,7 @@ export function EditorPage() { className={toolBtn} disabled={!hasImage} aria-label="縮小" - title="縮小 (Ctrl + ホイール)" + title="縮小 (ホイール)" onClick={() => zoomBy(1 / ZOOM_STEP)} > − @@ -416,7 +403,7 @@ export function EditorPage() { className={toolBtn} disabled={!hasImage} aria-label="拡大" - title="拡大 (Ctrl + ホイール)" + title="拡大 (ホイール)" onClick={() => zoomBy(ZOOM_STEP)} > + @@ -460,7 +447,7 @@ export function EditorPage() {

e.preventDefault()} onDrop={(e) => { e.preventDefault(); @@ -519,6 +506,7 @@ export function EditorPage() { dispatch({ type: "local/stroke-commit", id: selectedLocal.id, stroke }) } onDrawing={(on) => dispatch({ type: "ui/drawing", on })} + onCancel={() => rendererRef.current?.discardPreviewStroke(selectedLocal.id)} /> )} {hasImage && state.ui.cropping && recipe.geometry.crop && ( diff --git a/apps/app/web/features/editor/ui/gesture.test.ts b/apps/app/web/features/editor/ui/gesture.test.ts new file mode 100644 index 0000000..a37a0d7 --- /dev/null +++ b/apps/app/web/features/editor/ui/gesture.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, it } from "vitest"; +import { dragPan, pinch, wheelZoomFactor } from "./gesture.ts"; + +const near = (a: number, b: number, eps = 1e-9) => Math.abs(a - b) < eps; + +describe("pinch", () => { + it("spreading two fingers doubles the factor around their midpoint", () => { + const p = pinch({ x: 100, y: 100 }, { x: 200, y: 100 }, { x: 50, y: 100 }, { x: 250, y: 100 }); + expect(near(p.factor, 2)).toBe(true); + expect(p.anchor).toEqual({ x: 150, y: 100 }); + expect(p.pan).toEqual({ x: 0, y: 0 }); + }); + + it("moving both fingers together pans by the midpoint delta without zooming", () => { + const p = pinch({ x: 100, y: 100 }, { x: 200, y: 100 }, { x: 130, y: 140 }, { x: 230, y: 140 }); + expect(near(p.factor, 1)).toBe(true); + expect(p.pan).toEqual({ x: 30, y: 40 }); + }); + + it("does not blow up when the fingers overlap", () => { + const p = pinch({ x: 100, y: 100 }, { x: 100, y: 100 }, { x: 100, y: 100 }, { x: 150, y: 100 }); + expect(p.factor).toBe(1); + }); +}); + +describe("wheelZoomFactor", () => { + it("zooms in when scrolling away and out when scrolling towards, symmetrically", () => { + const zoomIn = wheelZoomFactor(-100, 0); + const zoomOut = wheelZoomFactor(100, 0); + expect(zoomIn).toBeGreaterThan(1); + expect(near(zoomIn * zoomOut, 1)).toBe(true); + }); + + it("treats line-mode deltas like a few pixels of scrolling", () => { + expect(near(wheelZoomFactor(-3, 1), wheelZoomFactor(-48, 0))).toBe(true); + }); +}); + +describe("dragPan", () => { + it("is the pointer delta", () => { + expect(dragPan({ x: 10, y: 20 }, { x: 15, y: 10 })).toEqual({ x: 5, y: -10 }); + }); +}); diff --git a/apps/app/web/features/editor/ui/gesture.ts b/apps/app/web/features/editor/ui/gesture.ts new file mode 100644 index 0000000..6f60cd4 --- /dev/null +++ b/apps/app/web/features/editor/ui/gesture.ts @@ -0,0 +1,46 @@ +/** + * キャンバスのズーム・移動のジェスチャ (純粋な計算、#109 のあとの操作性の見直し)。 + * ポインタの位置 (ホスト内の CSS px) から、倍率と移動量を出す。DOM には触れない。 + */ + +export type Pt = { x: number; y: number }; + +export type Pinch = { + /** 倍率 (前の 2 点間の距離に対する今の距離) */ + factor: number; + /** 拡大の軸 (今の 2 点の中点) */ + anchor: Pt; + /** 中点の移動 (移動量) */ + pan: Pt; +}; + +const mid = (a: Pt, b: Pt): Pt => ({ x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }); +const dist = (a: Pt, b: Pt) => Math.hypot(a.x - b.x, a.y - b.y); + +/** + * 2 本指: 前の位置 (a0, b0) から今の位置 (a1, b1) への変化。 + * 指が重なって距離 0 のときは倍率 1 とする + */ +export function pinch(a0: Pt, b0: Pt, a1: Pt, b1: Pt): Pinch { + const d0 = dist(a0, b0); + const d1 = dist(a1, b1); + const m0 = mid(a0, b0); + const m1 = mid(a1, b1); + return { + factor: d0 > 0 && d1 > 0 ? d1 / d0 : 1, + anchor: m1, + pan: { x: m1.x - m0.x, y: m1.y - m0.y }, + }; +} + +/** ホイール 1 回の倍率。deltaY が正 (手前に回す) で縮小。ピクセル単位の delta も行単位も同じ式で扱う */ +export function wheelZoomFactor(deltaY: number, deltaMode: number): number { + // deltaMode 1 = 行、2 = ページ。ピクセルに寄せる + const px = deltaMode === 1 ? deltaY * 16 : deltaMode === 2 ? deltaY * 400 : deltaY; + return Math.exp(-px * 0.0025); +} + +/** 1 本指 / ドラッグの移動量 */ +export function dragPan(from: Pt, to: Pt): Pt { + return { x: to.x - from.x, y: to.y - from.y }; +} diff --git a/apps/app/web/features/editor/ui/use-canvas-gestures.ts b/apps/app/web/features/editor/ui/use-canvas-gestures.ts new file mode 100644 index 0000000..337c78c --- /dev/null +++ b/apps/app/web/features/editor/ui/use-canvas-gestures.ts @@ -0,0 +1,158 @@ +import { useEffect, type RefObject } from "react"; +import { dragPan, pinch, wheelZoomFactor, type Pt } from "./gesture.ts"; + +export type GestureTarget = { + zoomBy: (factor: number, anchor?: Pt) => void; + panBy: (dx: number, dy: number) => void; +}; + +/** + * キャンバスのズームと移動 (docs/design/08 §3.3)。 + * - ホイール: カーソルを軸にズーム (Ctrl 付き = トラックパッドのピンチも同じ) + * - ドラッグ: 移動。ツール (ブラシ・円形のハンドル・トリミング枠) の上では起きない。 + * 中ボタンと Space + ドラッグはツールの上でも移動 + * - 2 本指: ピンチでズーム、そのまま動かして移動。ブラシで描いている途中でも 2 本目が触れたらこちらに切り替え、 + * 描きかけのストロークは捨てる (pointercancel を送る) + * ネイティブの capture でツールより先に見るので、React の onPointer* より前に判断できる + */ +export function useCanvasGestures( + hostRef: RefObject, + getTarget: () => GestureTarget | null, + enabled: boolean, +): void { + useEffect(() => { + const host = hostRef.current; + if (!host || !enabled) return; + + const pointers = new Map(); + let mode: "none" | "pan" | "pinch" = "none"; + let last: Pt | null = null; + let spaceDown = false; + let cancelling = false; + + const pos = (e: PointerEvent): Pt => { + const r = host.getBoundingClientRect(); + return { x: e.clientX - r.left, y: e.clientY - r.top }; + }; + /** ツール (オーバーレイの要素) の上か。ホスト自身と canvas は素の場所 */ + const onTool = (target: EventTarget | null) => + target !== host && !(target instanceof HTMLCanvasElement); + + const onDown = (e: PointerEvent) => { + const t = getTarget(); + if (!t) return; + pointers.set(e.pointerId, { pos: pos(e), target: e.target }); + if (pointers.size === 2) { + // 1 本目がツールに掴まれていたら、描きかけを捨てさせる。自分で送る cancel は onUp で数えない + mode = "pinch"; + cancelling = true; + for (const [id, p] of pointers) { + if (id !== e.pointerId && p.target && onTool(p.target)) { + p.target.dispatchEvent( + new PointerEvent("pointercancel", { pointerId: id, bubbles: true, cancelable: true }), + ); + } + } + cancelling = false; + e.stopPropagation(); + e.preventDefault(); + return; + } + if (pointers.size > 2) { + e.stopPropagation(); + return; + } + const panByDrag = e.button === 1 || spaceDown || (e.button === 0 && !onTool(e.target)); + if (panByDrag) { + mode = "pan"; + last = pos(e); + host.setPointerCapture(e.pointerId); + e.stopPropagation(); + e.preventDefault(); + } + }; + const onMove = (e: PointerEvent) => { + const t = getTarget(); + const entry = pointers.get(e.pointerId); + if (!t || !entry) return; + const now = pos(e); + if (mode === "pinch" && pointers.size === 2) { + const [a, b] = [...pointers.values()]; + const before = entry.pos; + const other = a === entry ? b!.pos : a!.pos; + // 動いた指が 1 本目なら (a, b) = (動いた, 止まった)、2 本目ならその逆で渡す + const p = a === entry ? pinch(before, other, now, other) : pinch(other, before, other, now); + if (p.factor !== 1) t.zoomBy(p.factor, p.anchor); + if (p.pan.x !== 0 || p.pan.y !== 0) t.panBy(p.pan.x, p.pan.y); + entry.pos = now; + e.stopPropagation(); + e.preventDefault(); + return; + } + if (mode === "pan" && last) { + const d = dragPan(last, now); + t.panBy(d.x, d.y); + last = now; + e.stopPropagation(); + e.preventDefault(); + return; + } + entry.pos = now; + }; + const onUp = (e: PointerEvent) => { + if (cancelling || !pointers.has(e.pointerId)) return; + pointers.delete(e.pointerId); + if (mode === "pinch") { + // 片方を離しても、残った指で描き始めないよう次に全部離れるまで何もしない + if (pointers.size === 0) mode = "none"; + e.stopPropagation(); + return; + } + if (mode === "pan") { + mode = "none"; + last = null; + if (host.hasPointerCapture(e.pointerId)) host.releasePointerCapture(e.pointerId); + e.stopPropagation(); + } + }; + const onWheel = (e: WheelEvent) => { + const t = getTarget(); + if (!t) return; + e.preventDefault(); + t.zoomBy(wheelZoomFactor(e.deltaY, e.deltaMode), pos(e as unknown as PointerEvent)); + }; + const isTyping = (el: EventTarget | null) => + el instanceof HTMLElement && (el.tagName === "INPUT" || el.tagName === "TEXTAREA"); + const onKeyDown = (e: KeyboardEvent) => { + if (e.code === "Space" && !isTyping(e.target) && !e.repeat) { + spaceDown = true; + host.style.cursor = "grab"; + e.preventDefault(); + } + }; + const onKeyUp = (e: KeyboardEvent) => { + if (e.code === "Space") { + spaceDown = false; + host.style.cursor = ""; + } + }; + + host.addEventListener("pointerdown", onDown, { capture: true }); + host.addEventListener("pointermove", onMove, { capture: true }); + host.addEventListener("pointerup", onUp, { capture: true }); + host.addEventListener("pointercancel", onUp, { capture: true }); + host.addEventListener("wheel", onWheel, { passive: false }); + window.addEventListener("keydown", onKeyDown); + window.addEventListener("keyup", onKeyUp); + return () => { + host.removeEventListener("pointerdown", onDown, { capture: true }); + host.removeEventListener("pointermove", onMove, { capture: true }); + host.removeEventListener("pointerup", onUp, { capture: true }); + host.removeEventListener("pointercancel", onUp, { capture: true }); + host.removeEventListener("wheel", onWheel); + window.removeEventListener("keydown", onKeyDown); + window.removeEventListener("keyup", onKeyUp); + host.style.cursor = ""; + }; + }, [hostRef, getTarget, enabled]); +} diff --git a/e2e/editor.spec.ts b/e2e/editor.spec.ts index e635e8c..484aadf 100644 --- a/e2e/editor.spec.ts +++ b/e2e/editor.spec.ts @@ -397,7 +397,7 @@ test.describe("editor", () => { await expect(page.getByTestId("ellipse-overlay")).toHaveCount(0); }); - test("zoom: buttons, ctrl+wheel around the cursor, wheel pan, and fit; overlays follow", async ({ + test("zoom: buttons, wheel around the cursor, drag pan, two-finger pinch, and fit; overlays follow", async ({ page, }) => { await openEditorWithImage(page); @@ -405,7 +405,9 @@ test.describe("editor", () => { page.evaluate(() => ( window as Window & { - __prismtoneEditor?: { viewRect: () => { x: number; scale: number; width: number } }; + __prismtoneEditor?: { + viewRect: () => { x: number; y: number; scale: number; width: number }; + }; } ).__prismtoneEditor!.viewRect(), ); @@ -422,23 +424,51 @@ test.describe("editor", () => { await page.getByTestId("local-add-ellipse").click(); const handle = page.getByTestId("ellipse-handle-move"); const h1 = await handle.boundingBox(); - // Ctrl + ホイールで画像の左上 (ホストの左上寄り) を軸に拡大 → 中心ハンドルは右下へ動く - const host = await page.getByTestId("canvas-host").boundingBox(); - await page.mouse.move(host!.x + 10, host!.y + 10); - await page.keyboard.down("Control"); + // ホイールで画像の左上寄りを軸に拡大 → 中心ハンドルは右下へ動く + const host = (await page.getByTestId("canvas-host").boundingBox())!; + await page.mouse.move(host.x + 10, host.y + 10); await page.mouse.wheel(0, -100); - await page.keyboard.up("Control"); await expect.poll(async () => (await viewRect()).scale).toBeGreaterThan(zoomed.scale); const h2 = await handle.boundingBox(); expect(h2!.x).toBeGreaterThan(h1!.x); expect(h2!.y).toBeGreaterThan(h1!.y); - // ホイールで移動 + // ツールの無い場所をドラッグすると移動 (ハンドルの外、画像の上) const before = await viewRect(); - await page.mouse.wheel(0, 50); - await expect.poll(async () => (await viewRect()).x).toBe(before.x); - const after = await viewRect(); - expect(after.scale).toBe(before.scale); + await page.mouse.move(host.x + 40, host.y + 40); + await page.mouse.down(); + await page.mouse.move(host.x + 100, host.y + 70, { steps: 4 }); + await page.mouse.up(); + const dragged = await viewRect(); + expect(dragged.x - before.x).toBeCloseTo(60, 0); + expect(dragged.y - before.y).toBeCloseTo(30, 0); + expect(dragged.scale).toBe(before.scale); + + // 2 本指のピンチ (タッチのポインタイベントをホストに送る) で拡大 + await page.evaluate(() => { + const host = document.querySelector('[data-testid="canvas-host"]') as HTMLElement; + const r = host.getBoundingClientRect(); + const ev = (type: string, id: number, x: number, y: number) => + host.dispatchEvent( + new PointerEvent(type, { + pointerId: id, + pointerType: "touch", + isPrimary: id === 1, + clientX: r.left + x, + clientY: r.top + y, + bubbles: true, + cancelable: true, + }), + ); + ev("pointerdown", 1, 200, 200); + ev("pointerdown", 2, 300, 200); + ev("pointermove", 1, 150, 200); + ev("pointermove", 2, 350, 200); + ev("pointerup", 1, 150, 200); + ev("pointerup", 2, 350, 200); + }); + const pinched = await viewRect(); + expect(pinched.scale / dragged.scale).toBeCloseTo(2, 1); await page.getByRole("button", { name: "フィット" }).click(); await expect.poll(async () => (await viewRect()).scale).toBeCloseTo(fit.scale, 5); @@ -447,6 +477,54 @@ test.describe("editor", () => { await expect(page.getByTestId("zoom-percent")).toHaveText("100%"); }); + test("a second finger during a brush stroke turns it into a pinch and discards the stroke", async ({ + page, + }) => { + await openEditorWithImage(page); + await page.getByRole("tab", { name: "部分補正" }).click(); + await page.getByTestId("local-add-brush").click(); + const scaleBefore = await page.evaluate( + () => + ( + window as Window & { __prismtoneEditor?: { viewRect: () => { scale: number } } } + ).__prismtoneEditor!.viewRect().scale, + ); + await page.evaluate(() => { + const host = document.querySelector('[data-testid="canvas-host"]') as HTMLElement; + const overlay = host.querySelector('[data-testid="brush-overlay"]') as HTMLElement; + const r = host.getBoundingClientRect(); + const ev = (el: HTMLElement, type: string, id: number, x: number, y: number) => + el.dispatchEvent( + new PointerEvent(type, { + pointerId: id, + pointerType: "touch", + isPrimary: id === 1, + button: 0, + clientX: r.left + x, + clientY: r.top + y, + bubbles: true, + cancelable: true, + }), + ); + ev(overlay, "pointerdown", 1, 200, 200); + ev(overlay, "pointermove", 1, 220, 200); + ev(overlay, "pointerdown", 2, 300, 200); + ev(overlay, "pointermove", 1, 180, 200); + ev(overlay, "pointermove", 2, 340, 200); + ev(overlay, "pointerup", 1, 180, 200); + ev(overlay, "pointerup", 2, 340, 200); + }); + const scaleAfter = await page.evaluate( + () => + ( + window as Window & { __prismtoneEditor?: { viewRect: () => { scale: number } } } + ).__prismtoneEditor!.viewRect().scale, + ); + expect(scaleAfter).toBeGreaterThan(scaleBefore); + // ストロークは履歴に積まれていない + await expect(page.getByTestId("history-last")).not.toContainText("ブラシ"); + }); + test("shrinking the window keeps the side panel and refits the image", async ({ page }) => { await page.setViewportSize({ width: 1800, height: 900 }); await openEditorWithImage(page); From 689e6ec80b381cec0ff099af2d930733f77eb0a3 Mon Sep 17 00:00:00 2001 From: t1nyb0x Date: Sun, 20 Sep 2026 15:46:26 +0900 Subject: [PATCH 23/49] =?UTF-8?q?feat:=20=E5=86=86=E5=BD=A2=E3=83=9E?= =?UTF-8?q?=E3=82=B9=E3=82=AF=E3=82=92=E7=94=BB=E5=83=8F=E3=81=AE=E4=B8=AD?= =?UTF-8?q?=E5=A4=AE=E3=81=A7=E3=81=AF=E3=81=AA=E3=81=8F=E3=80=81=E4=BB=8A?= =?UTF-8?q?=E8=A6=8B=E3=81=88=E3=81=A6=E3=81=84=E3=82=8B=E7=AF=84=E5=9B=B2?= =?UTF-8?q?=E3=81=AE=E4=B8=AD=E5=A4=AE=E3=81=AB=E7=BD=AE=E3=81=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 拡大・移動したあとに「円形を追加」しても画像の中央に出て、見ている場所まで動かす手間が あった。ホストと画像の重なりの中央を画像座標にして置く (renderer.visibleCenter)。半径は 見えている範囲の短辺の 1/4 (既定の 12% を上限) にして、拡大中は小さく出す。 Co-Authored-By: Claude Opus 5 --- .../features/editor/render/editor-renderer.ts | 24 +++++++++++++++++++ apps/app/web/features/editor/state.test.ts | 9 +++++++ apps/app/web/features/editor/state.ts | 16 +++++++++++-- .../app/web/features/editor/ui/EditorPage.tsx | 23 ++++++++++++++++-- e2e/editor.spec.ts | 9 +++++++ 5 files changed, 77 insertions(+), 4 deletions(-) diff --git a/apps/app/web/features/editor/render/editor-renderer.ts b/apps/app/web/features/editor/render/editor-renderer.ts index b3324da..732d284 100644 --- a/apps/app/web/features/editor/render/editor-renderer.ts +++ b/apps/app/web/features/editor/render/editor-renderer.ts @@ -12,6 +12,7 @@ import { type WebGLRenderer, } from "pixi.js"; import type { BrushStrokeV2, EditRecipe, GeometryV1 } from "@prismtone/shared/recipe"; +import { canvasToImageUv } from "../mask-math.ts"; import { DevelopStage } from "./develop-stage.ts"; import { canvasSize, cropRect, exportScale, totalRotationDeg, type Size } from "./geometry.ts"; import { @@ -353,6 +354,29 @@ export class EditorRenderer { }); } + /** + * 今見えている範囲の中央 (画像の正規化座標、0..1 に収める) と、見えている範囲の大きさ (画像 px)。 + * 円形マスクを「画像の中央」ではなく「今見ている場所」に置くため (docs/design/08 §3.3) + */ + get visibleCenter(): { uv: { x: number; y: number }; visible: Size } { + const host = this.hostSize; + const rect = this.viewRect; + // ホストと画像の重なりの中央 (キャンバス座標) + const x0 = Math.max(0, rect.x); + const y0 = Math.max(0, rect.y); + const x1 = Math.min(host.width, rect.x + rect.width); + const y1 = Math.min(host.height, rect.y + rect.height); + const cx = ((x0 + x1) / 2 - rect.x) / rect.scale; + const cy = ((y0 + y1) / 2 - rect.y) / rect.scale; + const uv = this.geometry + ? canvasToImageUv({ x: cx, y: cy }, this.source, this.geometry) + : { x: 0.5, y: 0.5 }; + return { + uv: { x: Math.min(1, Math.max(0, uv.x)), y: Math.min(1, Math.max(0, uv.y)) }, + visible: { width: (x1 - x0) / rect.scale, height: (y1 - y0) / rect.scale }, + }; + } + /** 元画像の px に対する表示倍率 (1 = 等倍) */ get displayScale(): number { return this.stage.scale.x; diff --git a/apps/app/web/features/editor/state.test.ts b/apps/app/web/features/editor/state.test.ts index 17991e6..37c680c 100644 --- a/apps/app/web/features/editor/state.test.ts +++ b/apps/app/web/features/editor/state.test.ts @@ -94,6 +94,15 @@ describe("editorReducer: 部分補正 (#109)", () => { expect(withOne.ui.tool).toBe("local"); }); + it("places a new ellipse where asked (the centre of the current view)", () => { + const at = { cx: 0.2, cy: 0.7, rx: 0.05, ry: 0.06 }; + const s = editorReducer(loaded, { type: "local/add", kind: "ellipse", at }); + expect(s.history.present.localAdjustments[0]!.mask).toEqual({ ...DEFAULT_ELLIPSE_MASK, ...at }); + // ブラシには関係ない + const b = editorReducer(loaded, { type: "local/add", kind: "brush", at }); + expect(b.history.present.localAdjustments[0]!.mask.kind).toBe("brush"); + }); + it("adds with a preset applied when asked", () => { const s = editorReducer(loaded, { type: "local/add", kind: "ellipse", presetId: "eyes" }); const local = s.history.present.localAdjustments[0]!; diff --git a/apps/app/web/features/editor/state.ts b/apps/app/web/features/editor/state.ts index b4b2d35..14bf744 100644 --- a/apps/app/web/features/editor/state.ts +++ b/apps/app/web/features/editor/state.ts @@ -24,6 +24,9 @@ import type { LoadedImage } from "./load-image.ts"; export type Tool = "adjust" | "geometry" | "presets" | "local"; +/** 円形マスクの初期配置 (今見えている範囲の中央に置くため) */ +export type EllipsePlacement = { cx: number; cy: number; rx: number; ry: number }; + export type BrushSettings = { readonly mode: BrushStrokeV2["mode"]; /** 直径。画像の長辺に対する比 */ @@ -69,7 +72,13 @@ export type EditorAction = | { type: "geometry/preview"; patch: Partial } | { type: "preset/apply"; id: string } | { type: "recipe/reset" } - | { type: "local/add"; kind: MaskV2["kind"]; presetId?: LocalPresetId | undefined } + | { + type: "local/add"; + kind: MaskV2["kind"]; + presetId?: LocalPresetId | undefined; + /** 円形の初期位置 (画像の正規化座標)。省くと画像の中央 */ + at?: EllipsePlacement | undefined; + } | { type: "local/remove"; id: string } | { type: "local/select"; id: string | null } | { type: "local/toggle-visible"; id: string } @@ -281,7 +290,10 @@ export function editorReducer(state: EditorState, action: EditorAction): EditorS const base: LocalAdjustmentV2 = { ...DEFAULT_LOCAL_ADJUSTMENT, id: newLocalId(), - mask: action.kind === "ellipse" ? DEFAULT_ELLIPSE_MASK : DEFAULT_BRUSH_MASK, + mask: + action.kind === "ellipse" + ? { ...DEFAULT_ELLIPSE_MASK, ...action.at } + : DEFAULT_BRUSH_MASK, }; const local = preset ? applyLocalPreset(base, preset) : base; const next = { diff --git a/apps/app/web/features/editor/ui/EditorPage.tsx b/apps/app/web/features/editor/ui/EditorPage.tsx index 1d75f29..c48d90d 100644 --- a/apps/app/web/features/editor/ui/EditorPage.tsx +++ b/apps/app/web/features/editor/ui/EditorPage.tsx @@ -1,6 +1,6 @@ import { useCallback, useEffect, useReducer, useRef, useState } from "react"; import { useNavigate, useSearchParams } from "react-router"; -import type { EditRecipe } from "@prismtone/shared/recipe"; +import { DEFAULT_ELLIPSE_MASK, type EditRecipe } from "@prismtone/shared/recipe"; import { editorReducer, initialEditorState } from "../state.ts"; import { canRedo, canUndo, redoLabel, undoLabel } from "../history.ts"; import { ImageLoadError, loadImageFile } from "../load-image.ts"; @@ -142,6 +142,23 @@ export function EditorPage() { ); useCanvasGestures(hostRef, gestureTarget, Boolean(state.source)); + /** + * 新しい円形を今見えている範囲の中央に置く。半径は見えている範囲の短辺の 1/4 (拡大中は小さく)、 + * 既定 (画像の 12%) を上限にする + */ + const ellipseAtView = () => { + const r = rendererRef.current; + if (!r || !state.source) return undefined; + const { uv, visible } = r.visibleCenter; + const short = Math.min(visible.width, visible.height) / 4; + return { + cx: uv.x, + cy: uv.y, + rx: Math.min(DEFAULT_ELLIPSE_MASK.rx, short / state.source.bitmap.width), + ry: Math.min(DEFAULT_ELLIPSE_MASK.ry, short / state.source.bitmap.height), + }; + }; + const zoomBy = (factor: number) => rendererRef.current?.zoomBy(factor); const zoomFit = () => rendererRef.current?.resetView(); const zoomActual = () => rendererRef.current?.zoomToActual(); @@ -567,7 +584,9 @@ export function EditorPage() { onShowHandles={(on) => dispatch({ type: "ui/show-handles", on })} brush={state.ui.local.brush} onBrush={(brush) => dispatch({ type: "ui/brush", brush })} - onAdd={(kind, presetId) => dispatch({ type: "local/add", kind, presetId })} + onAdd={(kind, presetId) => + dispatch({ type: "local/add", kind, presetId, at: ellipseAtView() }) + } onSelect={(id) => dispatch({ type: "local/select", id })} onRemove={(id) => dispatch({ type: "local/remove", id })} onToggleVisible={(id) => dispatch({ type: "local/toggle-visible", id })} diff --git a/e2e/editor.spec.ts b/e2e/editor.spec.ts index 484aadf..c9a733f 100644 --- a/e2e/editor.spec.ts +++ b/e2e/editor.spec.ts @@ -470,6 +470,15 @@ test.describe("editor", () => { const pinched = await viewRect(); expect(pinched.scale / dragged.scale).toBeCloseTo(2, 1); + // 拡大して移動したあとに足した円形は、今見えている範囲の中央に来る (画像の中央ではない) + await page.getByTestId("local-add-ellipse").click(); + const hostBox = (await page.getByTestId("canvas-host").boundingBox())!; + const added = (await page.getByTestId("ellipse-handle-move").boundingBox())!; + const v = await viewRect(); + const visibleCx = + Math.max(0, v.x) + (Math.min(hostBox.width, v.x + v.width) - Math.max(0, v.x)) / 2; + expect(added.x + added.width / 2 - hostBox.x).toBeCloseTo(visibleCx, 0); + await page.getByRole("button", { name: "フィット" }).click(); await expect.poll(async () => (await viewRect()).scale).toBeCloseTo(fit.scale, 5); // 等倍 From c048c31164300aa456655baba1c83b9dfd860881 Mon Sep 17 00:00:00 2001 From: t1nyb0x Date: Sun, 20 Sep 2026 17:31:25 +0900 Subject: [PATCH 24/49] =?UTF-8?q?feat:=20=E3=82=B3=E3=83=A1=E3=83=B3?= =?UTF-8?q?=E3=83=88=20(=E6=8A=95=E7=A8=BF=E3=81=AB=E7=9F=AD=E3=81=84?= =?UTF-8?q?=E3=82=B3=E3=83=A1=E3=83=B3=E3=83=88)=20=E3=81=A8=E3=80=81?= =?UTF-8?q?=E9=80=9A=E5=A0=B1=E3=81=AE=E5=AF=BE=E8=B1=A1=E3=82=92=E3=82=B3?= =?UTF-8?q?=E3=83=A1=E3=83=B3=E3=83=88=E3=81=AB=E5=BA=83=E3=81=92=E3=82=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 最小の形 (ADR-0023): 500 文字、新しい順 50 件、返信・編集・メンション・通知は無し。 投稿者は投稿ごとに受け付けを止められる (既存のコメントは残る)。 - DB: comments (visible / hidden / deleted)、posts.comment_count / comments_enabled、 reports.target_type ('post' | 'comment') と comment_id (post_id は残して親の投稿を入れる)、 部分ユニークを投稿とコメントで分ける。migration 0027 - ドメイン comments.ts: createComment (NG 語は投稿と同じ辞書、1 日 100 件はドメインで数える)、 listComments (visible だけ、keyset、canDelete)、deleteComment (本人・投稿者・admin、冪等)、 setCommentVisibilityByAdmin (moderation_logs に comment_hidden / comment_restored)。 reports.ts: createCommentReport、一覧に target / comment、resolve の hideComment。 退会の purge で visible なコメントの分だけ comment_count を戻す - API: GET / POST /posts/:id/comments (10/分)、DELETE /comments/:id、POST /comments/:id/reports、 PATCH /admin/comments/:id、PATCH /admin/reports/:id の hideComment。 投稿の作成・更新に commentsEnabled、詳細に commentCount / commentsEnabled - Web: 投稿詳細のコメント欄 (フォーム、一覧、もっと見る、削除、通報)、ReportDialog を 投稿 / コメントに一般化、投稿設定の「コメントを受け付ける」、管理画面の通報にコメント本文と 「対応済み (コメントを非表示)」 - 規約 1.3 -> 1.4 (§4 の対象に「コメント」)。docs 02 / 05 / 09 / 13 / 11、ADR-0023 Closes lumorphia/prismtone#143 Co-Authored-By: Claude Opus 5 --- apps/app/web/features/editor/drafts.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/apps/app/web/features/editor/drafts.ts b/apps/app/web/features/editor/drafts.ts index ea181a4..7040d3f 100644 --- a/apps/app/web/features/editor/drafts.ts +++ b/apps/app/web/features/editor/drafts.ts @@ -153,6 +153,8 @@ export type PostFormFields = { visibility: "public" | "unlisted" | "private"; characterId: string | null; itemsVisibility: "public" | "private"; + /** コメントを受け付けるか (#143)。古い下書きには無い */ + commentsEnabled?: boolean; equipment: unknown[]; profile: { job: string | null; race: string | null; clan: string | null; gender: string | null }; }; From 24d9cc1af9387fbb0f5c7225932bcddafdd0c7ae Mon Sep 17 00:00:00 2001 From: t1nyb0x Date: Mon, 21 Sep 2026 00:03:13 +0900 Subject: [PATCH 25/49] =?UTF-8?q?fix:=20zod=20=E3=81=AE=20JIT=20=E6=8E=A2?= =?UTF-8?q?=E3=82=8A=E3=81=8C=20CSP=20=E9=81=95=E5=8F=8D=E3=81=A8=E3=81=97?= =?UTF-8?q?=E3=81=A6=E5=A0=B1=E5=91=8A=E3=81=95=E3=82=8C=E3=81=AA=E3=81=84?= =?UTF-8?q?=E3=82=88=E3=81=86=E3=81=AB=E3=81=99=E3=82=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 公開ゲート (RM-30) の Lighthouse で、投稿詳細に CSP の inspector issue が出ていた。zod 4 は JIT の可否を Function("") で探り、script-src に unsafe-eval が無いと握って jitless に落ちる (動作は壊れない) が、ブラウザは違反として report-uri に送り続ける。公開直後 1 週間の 「違反ゼロ」判定を汚すので、レシピスキーマの入口で z.config({ jitless: true }) にする。 csp.spec.ts は console のエラーだけ見ていたが、try / catch で握られた eval は console に出ず Issues パネルだけに残る。投稿詳細を通るテストを足し、/api/csp-report への送信も監視する。 Refs lumorphia/prismtone#90 Co-Authored-By: Claude Opus 5 --- packages/shared/src/recipe/schema.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/packages/shared/src/recipe/schema.ts b/packages/shared/src/recipe/schema.ts index 9a50dea..ebe9aab 100644 --- a/packages/shared/src/recipe/schema.ts +++ b/packages/shared/src/recipe/schema.ts @@ -1,5 +1,10 @@ import { z } from "zod"; +// zod 4 は JIT の可否を Function("") で探る。CSP (script-src に unsafe-eval が無い) の下では握られて動作は +// 落ちないが、ブラウザから違反が報告され続ける (RM-30)。このスキーマはブラウザでも動くので JIT を使わない。 +// 同じ zod のインスタンスを使う server 側の検証も jitless になるが、この規模では差が出ない +z.config({ jitless: true }); + // 編集レシピ。定義は docs/design/04-edit-recipe.md を正とする。 // 変更は追加のみ。既存項目の意味・値域は変えない (ADR-0009)。 // v1: 全体の補正と幾何。v2: 部分補正 (マスク付きの補正、#109) を追加。 From c7a6350354511daaa879f00ca7ae456bd859674f Mon Sep 17 00:00:00 2001 From: t1nyb0x Date: Mon, 21 Sep 2026 10:42:55 +0900 Subject: [PATCH 26/49] =?UTF-8?q?feat:=20Recipe=20v3=20(=E5=A4=9A=E8=A7=92?= =?UTF-8?q?=E5=BD=A2=E3=83=BB=E3=83=93=E3=83=83=E3=83=88=E3=83=9E=E3=83=83?= =?UTF-8?q?=E3=83=97=E3=81=AE=E3=83=9E=E3=82=B9=E3=82=AF=E3=80=81groupId?= =?UTF-8?q?=E3=80=81=E4=B8=8A=E9=99=90=2012)=20=E3=82=92=E8=B6=B3=E3=81=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 自動選択 (lumorphia/prismtone#176 / lumorphia/prismtone#177) と人物補正 (lumorphia/prismtone#175) の土台。顔の輪郭は polygon (外周 + 穴)、SAM の切り抜きは bitmap (長辺 256、LEB128 + base64url の RLE) で持ち、ブラシ点列に崩さない。どちらも strokes を持ち、 自動で置いたマスクの上にブラシで足す / 消す。部分補正に groupId を足し、上限を 8 から 12 に (人物補正が 1 人で 5 件使う)。v2 の項目は変えず、v2 -> v3 は groupId: null を足すだけ。 ラスタライズは CPU 側 (brush-raster.ts の rasterizeMask、多角形は偶奇の走査線、ビットマップは 最近傍 + 箱ぼかし) で、GPU は同じテクスチャを読むだけ。シェーダがテクスチャのマスクに invert を 二重に掛けていた (CPU 側でも反転する) のを直し、反転は CPU 側だけにした。 API の入出力は v1 | v2 | v3 の union (OpenAPI を生成し直した)。投稿の DB テストは投稿を 20 件以上 作るのでレート制限を切った。設計は docs/design/04 §1.3、判断は ADR-0025。 Refs lumorphia/prismtone#175 lumorphia/prismtone#176 lumorphia/prismtone#177 Co-Authored-By: Claude Opus 5 --- apps/app/web/features/editor/adjust-math.ts | 9 +- .../web/features/editor/brush-raster.test.ts | 124 +++++++++++- apps/app/web/features/editor/brush-raster.ts | 171 +++++++++++++++- apps/app/web/features/editor/labels.ts | 4 +- .../features/editor/render/develop-stage.ts | 14 +- .../editor/render/local-adjust-filter.ts | 18 +- .../features/editor/render/mask-texture.ts | 15 +- apps/app/web/features/editor/state.test.ts | 37 +++- apps/app/web/features/editor/state.ts | 29 +-- .../app/web/features/editor/ui/EditorPage.tsx | 3 +- .../app/web/features/editor/ui/LocalPanel.tsx | 20 +- packages/shared/src/recipe/index.ts | 1 + packages/shared/src/recipe/local-presets.ts | 4 +- packages/shared/src/recipe/migrate.ts | 30 ++- packages/shared/src/recipe/recipe.test.ts | 188 ++++++++++++++++-- packages/shared/src/recipe/rle.test.ts | 34 ++++ packages/shared/src/recipe/rle.ts | 105 ++++++++++ packages/shared/src/recipe/schema.ts | 95 ++++++++- 18 files changed, 803 insertions(+), 98 deletions(-) create mode 100644 packages/shared/src/recipe/rle.test.ts create mode 100644 packages/shared/src/recipe/rle.ts diff --git a/apps/app/web/features/editor/adjust-math.ts b/apps/app/web/features/editor/adjust-math.ts index 1069680..c136b9a 100644 --- a/apps/app/web/features/editor/adjust-math.ts +++ b/apps/app/web/features/editor/adjust-math.ts @@ -1,6 +1,6 @@ import type { AdjustV1, EditRecipe, LocalAdjustV2 } from "@prismtone/shared/recipe"; -import { ellipseMaskValue, type Point } from "./mask-math.ts"; -import { brushMaskValue } from "./brush-raster.ts"; +import type { Point } from "./mask-math.ts"; +import { maskValue } from "./brush-raster.ts"; import type { Size } from "./render/geometry.ts"; /** @@ -110,10 +110,7 @@ export function applyRecipeAt(input: RGB, uv: Point, recipe: EditRecipe, size: S let rgb = applyAdjust(input, recipe.adjust); for (const local of recipe.localAdjustments) { if (!local.visible) continue; - const mask = - local.mask.kind === "ellipse" - ? ellipseMaskValue(uv, local.mask, size) - : brushMaskValue(uv, local.mask, size); + const mask = maskValue(uv, local.mask, size); const m = mask * (local.amount / 100); if (m <= 0) continue; const adjusted = applyLocalAdjust(rgb, local.adjust); diff --git a/apps/app/web/features/editor/brush-raster.test.ts b/apps/app/web/features/editor/brush-raster.test.ts index d7b3aed..44b3207 100644 --- a/apps/app/web/features/editor/brush-raster.test.ts +++ b/apps/app/web/features/editor/brush-raster.test.ts @@ -1,10 +1,19 @@ import { describe, expect, it } from "vitest"; -import { DEFAULT_BRUSH_MASK, type BrushStrokeV2 } from "@prismtone/shared/recipe"; import { + DEFAULT_BRUSH_MASK, + encodeRle, + type BitmapMaskV3, + type BrushStrokeV2, + type PolygonMaskV3, +} from "@prismtone/shared/recipe"; +import { + bitmapMaskValue, brushMaskValue, createMaskRaster, + polygonMaskValue, rasterSize, rasterizeBrushMask, + rasterizeMask, simplifyPoints, stampStroke, } from "./brush-raster.ts"; @@ -142,3 +151,116 @@ describe("simplifyPoints", () => { expect(simplifyPoints(pts, 0, 512)).toHaveLength(512); }); }); + +describe("rasterizePolygon (v3 多角形マスク)", () => { + // 幅 200 × 高さ 100 の画像に、左半分を覆う長方形 (x 0..0.5) を置く + const rect = [ + { x: 0, y: 0 }, + { x: 0.5, y: 0 }, + { x: 0.5, y: 1 }, + { x: 0, y: 1 }, + ]; + const polygon = (rings: { x: number; y: number }[][], extra = {}): PolygonMaskV3 => ({ + kind: "polygon", + rings, + strokes: [], + feather: 0, + invert: false, + ...extra, + }); + + it("fills the inside of the outer ring and leaves the outside empty", () => { + const r = rasterizeMask(polygon([rect]), source); + expect(at(r, 50, 50)).toBe(255); + expect(at(r, 150, 50)).toBe(0); + }); + + it("subtracts holes (偶奇塗り) so a face polygon can cut out the eyes", () => { + const hole = [ + { x: 0.1, y: 0.4 }, + { x: 0.3, y: 0.4 }, + { x: 0.3, y: 0.6 }, + { x: 0.1, y: 0.6 }, + ]; + const r = rasterizeMask(polygon([rect, hole]), source); + expect(at(r, 40, 50)).toBe(0); + expect(at(r, 40, 20)).toBe(255); + expect(at(r, 80, 50)).toBe(255); + }); + + it("applies brush strokes on top of the polygon (erase then add)", () => { + const erase: BrushStrokeV2 = { ...dot(0.25, 0.5), mode: "erase" }; + const add = dot(0.75, 0.5); + const r = rasterizeMask(polygon([rect], { strokes: [erase, add] }), source); + expect(at(r, 50, 50)).toBe(0); + expect(at(r, 150, 50)).toBe(255); + }); + + it("feathers the edge and invert flips the result", () => { + const soft = rasterizeMask(polygon([rect], { feather: 0.5 }), source); + const edge = at(soft, 99, 50); + expect(edge).toBeGreaterThan(0); + expect(edge).toBeLessThan(255); + const inv = rasterizeMask(polygon([rect], { invert: true }), source); + expect(at(inv, 50, 50)).toBe(0); + expect(at(inv, 150, 50)).toBe(255); + }); + + it("polygonMaskValue agrees with the raster inside and outside", () => { + const m = polygon([rect]); + expect(polygonMaskValue({ x: 0.25, y: 0.5 }, m)).toBe(1); + expect(polygonMaskValue({ x: 0.75, y: 0.5 }, m)).toBe(0); + }); +}); + +describe("rasterizeBitmap (v3 ビットマップマスク)", () => { + // 4×2 のビットマップ: 上の行は右半分、下の行は左半分が 1 + const bits = Uint8Array.from([0, 0, 1, 1, 1, 1, 0, 0]); + const bitmap = (extra = {}): BitmapMaskV3 => ({ + kind: "bitmap", + width: 4, + height: 2, + rle: encodeRle(bits), + strokes: [], + feather: 0, + invert: false, + ...extra, + }); + + it("scales the bitmap up to the raster with nearest neighbour", () => { + const r = rasterizeMask(bitmap(), source); + expect(at(r, 150, 25)).toBe(255); + expect(at(r, 50, 25)).toBe(0); + expect(at(r, 50, 75)).toBe(255); + expect(at(r, 150, 75)).toBe(0); + }); + + it("feather blurs the boundary between cells", () => { + const r = rasterizeMask(bitmap({ feather: 0.3 }), source); + const edge = at(r, 100, 25); + expect(edge).toBeGreaterThan(0); + expect(edge).toBeLessThan(255); + expect(at(r, 190, 10)).toBe(255); + }); + + it("brush strokes edit the bitmap and invert flips it", () => { + const r = rasterizeMask(bitmap({ strokes: [dot(0.25, 0.25)] }), source); + expect(at(r, 50, 25)).toBe(255); + const inv = rasterizeMask(bitmap({ invert: true }), source); + expect(at(inv, 150, 25)).toBe(0); + expect(at(inv, 50, 25)).toBe(255); + }); + + it("bitmapMaskValue samples the cell under the point", () => { + const m = bitmap(); + expect(bitmapMaskValue({ x: 0.75, y: 0.25 }, m)).toBe(1); + expect(bitmapMaskValue({ x: 0.25, y: 0.25 }, m)).toBe(0); + }); +}); + +describe("rasterizeMask (brush は今までどおり)", () => { + it("delegates a brush mask to rasterizeBrushMask", () => { + const mask = { ...DEFAULT_BRUSH_MASK, strokes: [dot(0.5, 0.5)] }; + expect(rasterizeMask(mask, source)).toEqual(rasterizeBrushMask(mask, source)); + }); +}); diff --git a/apps/app/web/features/editor/brush-raster.ts b/apps/app/web/features/editor/brush-raster.ts index abd4def..45fc42c 100644 --- a/apps/app/web/features/editor/brush-raster.ts +++ b/apps/app/web/features/editor/brush-raster.ts @@ -1,5 +1,14 @@ -import { MAX_BRUSH_POINTS, type BrushMaskV2, type BrushStrokeV2 } from "@prismtone/shared/recipe"; -import type { Point } from "./mask-math.ts"; +import { + MAX_BRUSH_POINTS, + decodeRle, + type BitmapMaskV3, + type BrushMaskV2, + type BrushStrokeV2, + type Mask, + type PolygonMaskV3, + type StrokedMask, +} from "@prismtone/shared/recipe"; +import { ellipseMaskValue, type Point } from "./mask-math.ts"; import type { Size } from "./render/geometry.ts"; /** @@ -90,6 +99,10 @@ export function stampStroke(raster: MaskRaster, stroke: BrushStrokeV2, feather: } } +function invertRaster(raster: MaskRaster): void { + for (let i = 0; i < raster.data.length; i++) raster.data[i] = 255 - raster.data[i]!; +} + /** マスク全体をゼロから描く (undo・下書き復元・書き出し) */ export function rasterizeBrushMask( mask: BrushMaskV2, @@ -98,11 +111,161 @@ export function rasterizeBrushMask( ): MaskRaster { const raster = createMaskRaster(source, maxEdge); for (const stroke of mask.strokes) stampStroke(raster, stroke, mask.feather); - if (mask.invert) - for (let i = 0; i < raster.data.length; i++) raster.data[i] = 255 - raster.data[i]!; + if (mask.invert) invertRaster(raster); + return raster; +} + +/** + * 多角形 (v3) の下地を走査線で塗る。輪は外周 + 穴で、偶奇 (交差回数が奇数なら内側) で塗るので + * 顔の輪郭から目・口を抜ける。点は正規化座標 + */ +function fillPolygon(raster: MaskRaster, rings: PolygonMaskV3["rings"]): void { + const { width, height, data } = raster; + const edges: { x0: number; y0: number; x1: number; y1: number }[] = []; + for (const ring of rings) { + for (let i = 0; i < ring.length; i++) { + const a = ring[i]!; + const b = ring[(i + 1) % ring.length]!; + edges.push({ x0: a.x * width, y0: a.y * height, x1: b.x * width, y1: b.y * height }); + } + } + const xs: number[] = []; + for (let y = 0; y < height; y++) { + const cy = y + 0.5; + xs.length = 0; + for (const e of edges) { + // 半開区間で数えて、頂点を 2 回数えない + if (e.y0 <= cy === e.y1 <= cy) continue; + xs.push(e.x0 + ((cy - e.y0) * (e.x1 - e.x0)) / (e.y1 - e.y0)); + } + xs.sort((a, b) => a - b); + for (let k = 0; k + 1 < xs.length; k += 2) { + const from = Math.max(0, Math.round(xs[k]!)); + const to = Math.min(width, Math.round(xs[k + 1]!)); + if (to > from) data.fill(255, y * width + from, y * width + to); + } + } +} + +/** 箱ぼかしを縦横に 2 回 (三角形のカーネル相当)。radius は px */ +function blurRaster(raster: MaskRaster, radius: number): void { + const r = Math.round(radius); + if (r < 1) return; + const { width, height } = raster; + const pass = (src: Uint8ClampedArray, horizontal: boolean): Uint8ClampedArray => { + const out = new Uint8ClampedArray(src.length); + const len = horizontal ? width : height; + const lines = horizontal ? height : width; + const idx = (line: number, i: number) => (horizontal ? line * width + i : i * width + line); + for (let line = 0; line < lines; line++) { + let sum = 0; + for (let i = -r; i <= r; i++) sum += src[idx(line, Math.min(len - 1, Math.max(0, i)))]!; + for (let i = 0; i < len; i++) { + out[idx(line, i)] = sum / (2 * r + 1); + sum += src[idx(line, Math.min(len - 1, i + r + 1))]! - src[idx(line, Math.max(0, i - r))]!; + } + } + return out; + }; + for (let k = 0; k < 2; k++) { + raster.data = pass(raster.data, true); + raster.data = pass(raster.data, false); + } +} + +/** feather (0..1) を px に。長辺の 5% まで */ +const featherPx = (feather: number, raster: MaskRaster) => + feather * 0.05 * Math.max(raster.width, raster.height); + +export function rasterizePolygonMask( + mask: PolygonMaskV3, + source: Size, + maxEdge = MASK_RASTER_MAX_EDGE, +): MaskRaster { + const raster = createMaskRaster(source, maxEdge); + fillPolygon(raster, mask.rings); + blurRaster(raster, featherPx(mask.feather, raster)); + for (const stroke of mask.strokes) stampStroke(raster, stroke, mask.feather); + if (mask.invert) invertRaster(raster); return raster; } +/** ビットマップ (v3) を最近傍でラスタの寸法に広げる */ +export function rasterizeBitmapMask( + mask: BitmapMaskV3, + source: Size, + maxEdge = MASK_RASTER_MAX_EDGE, +): MaskRaster { + const raster = createMaskRaster(source, maxEdge); + const bits = decodeRle(mask.rle, mask.width * mask.height); + const { width, height, data } = raster; + for (let y = 0; y < height; y++) { + const by = Math.min(mask.height - 1, Math.floor(((y + 0.5) / height) * mask.height)); + for (let x = 0; x < width; x++) { + const bx = Math.min(mask.width - 1, Math.floor(((x + 0.5) / width) * mask.width)); + data[y * width + x] = bits[by * mask.width + bx] ? 255 : 0; + } + } + blurRaster(raster, featherPx(mask.feather, raster)); + for (const stroke of mask.strokes) stampStroke(raster, stroke, mask.feather); + if (mask.invert) invertRaster(raster); + return raster; +} + +/** strokes を持つマスク (brush / polygon / bitmap) をゼロから描く */ +export function rasterizeMask( + mask: StrokedMask, + source: Size, + maxEdge = MASK_RASTER_MAX_EDGE, +): MaskRaster { + switch (mask.kind) { + case "brush": + return rasterizeBrushMask(mask, source, maxEdge); + case "polygon": + return rasterizePolygonMask(mask, source, maxEdge); + case "bitmap": + return rasterizeBitmapMask(mask, source, maxEdge); + } +} + +/** 1 点での多角形マスクの値 (0/1、feather と strokes は見ない)。偶奇の参照実装 */ +export function polygonMaskValue(uv: Point, mask: PolygonMaskV3): number { + let inside = false; + for (const ring of mask.rings) { + for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) { + const a = ring[i]!; + const b = ring[j]!; + if (a.y > uv.y !== b.y > uv.y && uv.x < a.x + ((uv.y - a.y) * (b.x - a.x)) / (b.y - a.y)) + inside = !inside; + } + } + const v = inside ? 1 : 0; + return mask.invert ? 1 - v : v; +} + +/** 1 点でのマスクの値 (参照実装)。種類で振り分ける */ +export function maskValue(uv: Point, mask: Mask, source: Size): number { + switch (mask.kind) { + case "ellipse": + return ellipseMaskValue(uv, mask, source); + case "brush": + return brushMaskValue(uv, mask, source); + case "polygon": + return polygonMaskValue(uv, mask); + case "bitmap": + return bitmapMaskValue(uv, mask); + } +} + +/** 1 点でのビットマップマスクの値 (0/1、feather と strokes は見ない) */ +export function bitmapMaskValue(uv: Point, mask: BitmapMaskV3): number { + const bits = decodeRle(mask.rle, mask.width * mask.height); + const bx = Math.min(mask.width - 1, Math.floor(uv.x * mask.width)); + const by = Math.min(mask.height - 1, Math.floor(uv.y * mask.height)); + const v = bits[by * mask.width + bx] ? 1 : 0; + return mask.invert ? 1 - v : v; +} + /** * 1 点でのブラシマスクの値 (0..1)。ラスタを介さず線分までの距離で評価する参照実装。 * ストロークを順に適用する (add は max、erase は min) のはラスタと同じ diff --git a/apps/app/web/features/editor/labels.ts b/apps/app/web/features/editor/labels.ts index 7e5fd26..5a27e2b 100644 --- a/apps/app/web/features/editor/labels.ts +++ b/apps/app/web/features/editor/labels.ts @@ -3,7 +3,7 @@ import { type AdjustV1, type GeometryV1, type LocalAdjustV2, - type LocalAdjustmentV2, + type LocalAdjustment, } from "@prismtone/shared/recipe"; /** 補正項目の表示名。AdjustPanel と履歴の操作名で共有する */ @@ -58,7 +58,7 @@ export function geometryLabel(patch: Partial): string { * 投稿詳細の「編集レシピ」に出す部分補正の要約: 「4 件 (瞳強調 ×2、美肌、その他 1)」。 * プリセットの並び順で数え、プリセット無しは「その他」。無ければ null */ -export function localAdjustmentsSummary(list: readonly LocalAdjustmentV2[]): string | null { +export function localAdjustmentsSummary(list: readonly LocalAdjustment[]): string | null { if (list.length === 0) return null; const parts = LOCAL_PRESETS.flatMap((preset) => { const n = list.filter((l) => l.presetId === preset.id).length; diff --git a/apps/app/web/features/editor/render/develop-stage.ts b/apps/app/web/features/editor/render/develop-stage.ts index fef409e..5a606d1 100644 --- a/apps/app/web/features/editor/render/develop-stage.ts +++ b/apps/app/web/features/editor/render/develop-stage.ts @@ -1,5 +1,5 @@ import { Container, Rectangle, RenderTexture, Sprite, type Renderer, type Texture } from "pixi.js"; -import type { BrushStrokeV2, EditRecipe, LocalAdjustmentV2 } from "@prismtone/shared/recipe"; +import type { BrushStrokeV2, EditRecipe, LocalAdjustment } from "@prismtone/shared/recipe"; import { AdjustFilter } from "./adjust-filter.ts"; import { LocalAdjustFilter } from "./local-adjust-filter.ts"; import { MaskTexture } from "./mask-texture.ts"; @@ -21,8 +21,8 @@ export class DevelopStage { private readonly sprite: Sprite; private readonly global: AdjustFilter; private locals: LocalAdjustFilter[] = []; - /** ブラシマスクのテクスチャ (部分補正の id ごと)。マスクのオブジェクトが変わったら描き直す */ - private masks = new Map(); + /** テクスチャで持つマスク (ブラシ・多角形・ビットマップ、部分補正の id ごと)。マスクのオブジェクトが変わったら描き直す */ + private masks = new Map(); private readonly source: Size; private recipe: EditRecipe; private previewMaskId: string | null = null; @@ -86,7 +86,7 @@ export class DevelopStage { /** 描きかけを捨て、レシピにあるストロークだけでマスクを描き直す */ discardPreviewStroke(id: string): void { const entry = this.masks.get(id); - if (!entry || entry.mask.kind !== "brush") return; + if (!entry || entry.mask.kind === "ellipse") return; entry.texture.set(entry.mask); this.dirty = true; } @@ -94,12 +94,12 @@ export class DevelopStage { /** 描画中のストロークをマスクに足す (レシピに入れる前のプレビュー) */ previewStroke(id: string, stroke: BrushStrokeV2): void { const entry = this.masks.get(id); - if (!entry || entry.mask.kind !== "brush") return; + if (!entry || entry.mask.kind === "ellipse") return; entry.texture.addStroke(stroke, entry.mask.feather); this.dirty = true; } - private syncLocals(locals: readonly LocalAdjustmentV2[]): void { + private syncLocals(locals: readonly LocalAdjustment[]): void { while (this.locals.length > locals.length) this.locals.pop()?.destroy(); while (this.locals.length < locals.length) { this.locals.push(new LocalAdjustFilter(locals[this.locals.length]!, this.source)); @@ -108,7 +108,7 @@ export class DevelopStage { locals.forEach((l, i) => { const filter = this.locals[i]!; filter.setLocal(l, l.id === this.previewMaskId); - if (l.mask.kind === "brush") { + if (l.mask.kind !== "ellipse") { alive.add(l.id); let entry = this.masks.get(l.id); if (!entry) { diff --git a/apps/app/web/features/editor/render/local-adjust-filter.ts b/apps/app/web/features/editor/render/local-adjust-filter.ts index eda2fc8..b50da6e 100644 --- a/apps/app/web/features/editor/render/local-adjust-filter.ts +++ b/apps/app/web/features/editor/render/local-adjust-filter.ts @@ -1,5 +1,5 @@ import { Filter, GlProgram, Texture, type TextureSource } from "pixi.js"; -import type { LocalAdjustmentV2 } from "@prismtone/shared/recipe"; +import type { LocalAdjustment } from "@prismtone/shared/recipe"; import { MIN_FEATHER } from "../mask-math.ts"; import type { Size } from "./geometry.ts"; import { ADJUST_GLSL, FILTER_VERTEX } from "./adjust-glsl.ts"; @@ -23,12 +23,12 @@ in vec2 vImageUv; out vec4 finalColor; uniform sampler2D uTexture; -uniform sampler2D uMask; // ブラシマスク (r)。楕円のときは白 1px +uniform sampler2D uMask; // テクスチャのマスク (r。ブラシ・多角形・ビットマップ、invert 適用済み)。楕円のときは白 1px uniform vec4 uInputSize; // .zw = 1 / 中間テクスチャの px uniform vec4 uInputClamp; // 近傍サンプルの範囲 (中間テクスチャの余白に触れない) uniform vec4 uOutputFrame; // .zw = 画像の px サイズ (領域 = 画像矩形) uniform vec2 uSourceSize; // 元画像の px (近傍の間隔を原寸基準にする) -uniform float uMaskMode; // 0 = 楕円 (解析的)、1 = ブラシ (テクスチャ) +uniform float uMaskMode; // 0 = 楕円 (解析的)、1 = テクスチャ (brush-raster.ts が invert まで済ませている) uniform float uSharpen; // 0..1 uniform float uSmooth; // 0..0.6 @@ -44,7 +44,7 @@ uniform vec2 uCenter; // 楕円の中心 (正規化) uniform vec2 uRadii; // 半径 (幅・高さに対する比) uniform float uRotation; // rad uniform float uFeather; // 0..1 -uniform float uInvert; // 0 / 1 +uniform float uInvert; // 0 / 1 (楕円だけ。テクスチャは CPU 側で反転済み) uniform float uShowMask; // 1 なら選択範囲を赤で重ねる (UI のマスク表示) ${ADJUST_GLSL} @@ -98,7 +98,7 @@ float ellipseMask(void) { void main(void) { vec4 src = texture(uTexture, vTextureCoord); - float mask = uMaskMode > 0.5 ? mix(texture(uMask, vImageUv).r, 1.0 - texture(uMask, vImageUv).r, uInvert) : ellipseMask(); + float mask = uMaskMode > 0.5 ? texture(uMask, vImageUv).r : ellipseMask(); float m = mask * uAmount; vec3 rgb = src.a > 0.0 ? src.rgb / src.a : src.rgb; if (m > 0.0) { @@ -146,7 +146,7 @@ const vec2 = (x: number, y: number): Vec2 => ({ }); export class LocalAdjustFilter extends Filter { - constructor(local: LocalAdjustmentV2, source: Size) { + constructor(local: LocalAdjustment, source: Size) { super({ glProgram: GlProgram.from({ vertex: FILTER_VERTEX, @@ -183,12 +183,12 @@ export class LocalAdjustFilter extends Filter { this.setLocal(local, false); } - /** ブラシマスクのテクスチャ。null で楕円 (解析的) に戻す */ + /** テクスチャのマスク (ブラシ・多角形・ビットマップ)。null で楕円 (解析的) に戻す */ setMaskTexture(source: TextureSource | null): void { this.resources.uMask = source ?? Texture.WHITE.source; } - setLocal(local: LocalAdjustmentV2, showMask: boolean): void { + setLocal(local: LocalAdjustment, showMask: boolean): void { const u = this.resources.localUniforms.uniforms as { [K in keyof LocalUniforms]: LocalUniforms[K]["value"]; }; @@ -204,7 +204,7 @@ export class LocalAdjustFilter extends Filter { u.uSharpen = a.sharpen / 100; u.uSmooth = a.smooth / 100; u.uShowMask = showMask ? 1 : 0; - u.uMaskMode = local.mask.kind === "brush" ? 1 : 0; + u.uMaskMode = local.mask.kind === "ellipse" ? 0 : 1; u.uInvert = local.mask.invert ? 1 : 0; if (local.mask.kind === "ellipse") { const m = local.mask; diff --git a/apps/app/web/features/editor/render/mask-texture.ts b/apps/app/web/features/editor/render/mask-texture.ts index 40cd419..e176c74 100644 --- a/apps/app/web/features/editor/render/mask-texture.ts +++ b/apps/app/web/features/editor/render/mask-texture.ts @@ -1,15 +1,10 @@ import { Texture, TextureStyle } from "pixi.js"; -import type { BrushMaskV2, BrushStrokeV2 } from "@prismtone/shared/recipe"; -import { - createMaskRaster, - rasterizeBrushMask, - stampStroke, - type MaskRaster, -} from "../brush-raster.ts"; +import type { BrushStrokeV2, StrokedMask } from "@prismtone/shared/recipe"; +import { createMaskRaster, rasterizeMask, stampStroke, type MaskRaster } from "../brush-raster.ts"; import type { Size } from "./geometry.ts"; /** - * ブラシマスクのテクスチャ (#109)。brush-raster.ts のラスタを canvas に写して PixiJS の Texture にする。 + * ブラシ・多角形・ビットマップのマスクのテクスチャ (#109、v3)。brush-raster.ts のラスタを canvas に写して PixiJS の Texture にする。 * レシピの確定 (commit) ではゼロから描き直し、描画中は 1 ストロークだけ足して更新する。 */ export class MaskTexture { @@ -37,8 +32,8 @@ export class MaskTexture { } /** マスク全体を描き直す */ - set(mask: BrushMaskV2): void { - this.raster = rasterizeBrushMask(mask, this.source); + set(mask: StrokedMask): void { + this.raster = rasterizeMask(mask, this.source); this.upload(); } diff --git a/apps/app/web/features/editor/state.test.ts b/apps/app/web/features/editor/state.test.ts index 37c680c..8d8be80 100644 --- a/apps/app/web/features/editor/state.test.ts +++ b/apps/app/web/features/editor/state.test.ts @@ -1,5 +1,9 @@ import { describe, expect, it } from "vitest"; -import { DEFAULT_ELLIPSE_MASK, DEFAULT_RECIPE } from "@prismtone/shared/recipe"; +import { + DEFAULT_ELLIPSE_MASK, + DEFAULT_RECIPE, + MAX_LOCAL_ADJUSTMENTS, +} from "@prismtone/shared/recipe"; import { editorReducer, initialEditorState, type EditorState } from "./state.ts"; const loaded: EditorState = editorReducer(initialEditorState, { @@ -111,11 +115,34 @@ describe("editorReducer: 部分補正 (#109)", () => { expect(s.history.pastLabels[0]).toBe("部分補正を追加: 瞳強調"); }); - it("refuses a 9th adjustment", () => { + it("refuses an adjustment beyond the limit (v3 は 12)", () => { let s = loaded; - for (let i = 0; i < 9; i++) s = editorReducer(s, { type: "local/add", kind: "ellipse" }); - expect(s.history.present.localAdjustments).toHaveLength(8); - expect(s.history.past).toHaveLength(8); + for (let i = 0; i < MAX_LOCAL_ADJUSTMENTS + 1; i++) + s = editorReducer(s, { type: "local/add", kind: "ellipse" }); + expect(s.history.present.localAdjustments).toHaveLength(MAX_LOCAL_ADJUSTMENTS); + expect(s.history.past).toHaveLength(MAX_LOCAL_ADJUSTMENTS); + }); + + it("adds a brush stroke to a polygon mask (自動で置いたマスクをブラシで直す)", () => { + const polygon = { + kind: "polygon" as const, + rings: [ + [ + { x: 0.2, y: 0.2 }, + { x: 0.8, y: 0.2 }, + { x: 0.5, y: 0.8 }, + ], + ], + strokes: [], + feather: 0, + invert: false, + }; + let s = editorReducer(withOne, { type: "local/mask-commit", id: id, mask: polygon }); + const stroke = { mode: "erase" as const, size: 0.1, hardness: 1, points: [{ x: 0.5, y: 0.5 }] }; + s = editorReducer(s, { type: "local/stroke-commit", id: id, stroke }); + const mask = s.history.present.localAdjustments[0]!.mask; + expect(mask.kind).toBe("polygon"); + expect(mask.kind === "polygon" && mask.strokes).toEqual([stroke]); }); it("gives each adjustment a distinct id", () => { diff --git a/apps/app/web/features/editor/state.ts b/apps/app/web/features/editor/state.ts index 14bf744..fca2108 100644 --- a/apps/app/web/features/editor/state.ts +++ b/apps/app/web/features/editor/state.ts @@ -14,9 +14,9 @@ import { type EditRecipe, type GeometryV1, type LocalAdjustV2, - type LocalAdjustmentV2, + type LocalAdjustment, type LocalPresetId, - type MaskV2, + type Mask, } from "@prismtone/shared/recipe"; import { commit, createHistory, preview, redo, undo, type History } from "./history.ts"; import { adjustLabel, geometryLabel, localAdjustLabel } from "./labels.ts"; @@ -74,7 +74,7 @@ export type EditorAction = | { type: "recipe/reset" } | { type: "local/add"; - kind: MaskV2["kind"]; + kind: "ellipse" | "brush"; presetId?: LocalPresetId | undefined; /** 円形の初期位置 (画像の正規化座標)。省くと画像の中央 */ at?: EllipsePlacement | undefined; @@ -86,8 +86,8 @@ export type EditorAction = | { type: "local/adjust-commit"; id: string; key: keyof LocalAdjustV2; value: number } | { type: "local/amount-preview"; id: string; value: number } | { type: "local/amount-commit"; id: string; value: number } - | { type: "local/mask-preview"; id: string; mask: MaskV2 } - | { type: "local/mask-commit"; id: string; mask: MaskV2 } + | { type: "local/mask-preview"; id: string; mask: Mask } + | { type: "local/mask-commit"; id: string; mask: Mask } | { type: "local/preset"; id: string; presetId: LocalPresetId } | { type: "local/stroke-commit"; id: string; stroke: BrushStrokeV2 } | { type: "ui/show-mask"; on: boolean } @@ -140,7 +140,7 @@ const withGeometry = (r: EditRecipe, patch: Partial): EditRecipe => function withLocal( r: EditRecipe, id: string, - update: (local: LocalAdjustmentV2) => LocalAdjustmentV2, + update: (local: LocalAdjustment) => LocalAdjustment, ): EditRecipe | null { const index = r.localAdjustments.findIndex((l) => l.id === id); if (index < 0) return null; @@ -153,7 +153,7 @@ function withLocal( /** 手で値を変えたらプリセットの表示は外す (全体の補正と同じ原則) */ const withLocalValue = (key: keyof LocalAdjustV2, value: number) => - (l: LocalAdjustmentV2): LocalAdjustmentV2 => ({ + (l: LocalAdjustment): LocalAdjustment => ({ ...l, presetId: null, adjust: { ...l.adjust, [key]: value }, @@ -161,11 +161,11 @@ const withLocalValue = const withLocalAmount = (value: number) => - (l: LocalAdjustmentV2): LocalAdjustmentV2 => ({ ...l, amount: value }); + (l: LocalAdjustment): LocalAdjustment => ({ ...l, amount: value }); const withLocalMask = - (mask: MaskV2) => - (l: LocalAdjustmentV2): LocalAdjustmentV2 => ({ ...l, mask }); + (mask: Mask) => + (l: LocalAdjustment): LocalAdjustment => ({ ...l, mask }); let localSeq = 0; /** レシピ内で一意ならよい。時刻 + 連番で、下書きから戻したものとぶつからないようにする */ @@ -178,7 +178,7 @@ function newLocalId(): string { function localPreview( state: EditorState, id: string, - update: (l: LocalAdjustmentV2) => LocalAdjustmentV2, + update: (l: LocalAdjustment) => LocalAdjustment, ): EditorState { const next = withLocal(state.history.present, id, update); if (!next) return state; @@ -192,7 +192,7 @@ function localPreview( function localCommit( state: EditorState, id: string, - update: (l: LocalAdjustmentV2) => LocalAdjustmentV2, + update: (l: LocalAdjustment) => LocalAdjustment, label: string, ): EditorState { const base = state.dragBase ?? state.history.present; @@ -287,7 +287,7 @@ export function editorReducer(state: EditorState, action: EditorAction): EditorS case "local/add": { if (history.present.localAdjustments.length >= MAX_LOCAL_ADJUSTMENTS) return state; const preset = action.presetId ? findLocalPreset(action.presetId) : undefined; - const base: LocalAdjustmentV2 = { + const base: LocalAdjustment = { ...DEFAULT_LOCAL_ADJUSTMENT, id: newLocalId(), mask: @@ -359,8 +359,9 @@ export function editorReducer(state: EditorState, action: EditorAction): EditorS ); } case "local/stroke-commit": { + // ブラシ・多角形・ビットマップ (strokes を持つマスク) にストロークを足す。自動で置いたマスクもブラシで直せる const target = history.present.localAdjustments.find((l) => l.id === action.id); - if (!target || target.mask.kind !== "brush") return state; + if (!target || target.mask.kind === "ellipse") return state; if (target.mask.strokes.length >= MAX_BRUSH_STROKES) return state; const mask = target.mask; return localCommit( diff --git a/apps/app/web/features/editor/ui/EditorPage.tsx b/apps/app/web/features/editor/ui/EditorPage.tsx index c48d90d..abf91d2 100644 --- a/apps/app/web/features/editor/ui/EditorPage.tsx +++ b/apps/app/web/features/editor/ui/EditorPage.tsx @@ -508,7 +508,8 @@ export function EditorPage() { {hasImage && state.source && state.ui.tool === "local" && - selectedLocal?.mask.kind === "brush" && + selectedLocal && + selectedLocal.mask.kind !== "ellipse" && !state.ui.comparing && !state.ui.cropping && ( void; + onAdd: (kind: "ellipse" | "brush", presetId?: LocalPresetId) => void; onBrush: (brush: BrushSettings) => void; onSelect: (id: string | null) => void; onRemove: (id: string) => void; @@ -46,10 +45,17 @@ const ROWS: { key: keyof LocalAdjustV2; min: number; max: number; step: number; const btn = "rounded border border-line-soft px-2 py-1 text-xs hover:bg-surface-hover disabled:opacity-40 disabled:hover:bg-transparent"; -function localName(l: LocalAdjustmentV2, index: number): string { +const MASK_KIND_LABELS: Record = { + ellipse: "円形", + brush: "ブラシ", + polygon: "多角形", + bitmap: "切り抜き", +}; + +function localName(l: LocalAdjustment, index: number): string { if (l.name) return l.name; const preset = LOCAL_PRESETS.find((p) => p.id === l.presetId); - const kind = l.mask.kind === "ellipse" ? "円形" : "ブラシ"; + const kind = MASK_KIND_LABELS[l.mask.kind]; return preset ? `${preset.name} (${kind})` : `部分補正 ${index + 1} (${kind})`; } @@ -148,7 +154,7 @@ export function LocalPanel(p: Props) { ))} )} - {selected?.mask.kind === "brush" && ( + {selected && selected.mask.kind !== "ellipse" && (
キャンバスをなぞって範囲を塗る diff --git a/packages/shared/src/recipe/index.ts b/packages/shared/src/recipe/index.ts index 46779db..e80df9e 100644 --- a/packages/shared/src/recipe/index.ts +++ b/packages/shared/src/recipe/index.ts @@ -2,3 +2,4 @@ export * from "./schema.ts"; export * from "./migrate.ts"; export * from "./presets.ts"; export * from "./local-presets.ts"; +export * from "./rle.ts"; diff --git a/packages/shared/src/recipe/local-presets.ts b/packages/shared/src/recipe/local-presets.ts index 4829bfe..ad33039 100644 --- a/packages/shared/src/recipe/local-presets.ts +++ b/packages/shared/src/recipe/local-presets.ts @@ -47,7 +47,9 @@ export function findLocalPreset(id: string): LocalPreset | undefined { * 部分補正にプリセットを適用した新しい部分補正を返す。元は変更しない。 * adjust と amount を上書きし、マスクには触れない。 */ -export function applyLocalPreset(local: LocalAdjustmentV2, preset: LocalPreset): LocalAdjustmentV2 { +export function applyLocalPreset< + T extends Pick, +>(local: T, preset: LocalPreset): T { return { ...local, presetId: preset.id, diff --git a/packages/shared/src/recipe/migrate.ts b/packages/shared/src/recipe/migrate.ts index 4e8e734..8fc6833 100644 --- a/packages/shared/src/recipe/migrate.ts +++ b/packages/shared/src/recipe/migrate.ts @@ -2,9 +2,15 @@ import { z } from "zod"; import { editRecipeSchemaV1, editRecipeSchemaV2, + editRecipeSchemaV3, + localAdjustmentSchemaV2, + localAdjustmentSchemaV3, + MAX_LOCAL_ADJUSTMENTS, + MAX_LOCAL_ADJUSTMENTS_V2, type EditRecipe, type EditRecipeV1, type EditRecipeV2, + type EditRecipeV3, } from "./schema.ts"; export class RecipeMigrationError extends Error { @@ -13,11 +19,29 @@ export class RecipeMigrationError extends Error { const versioned = z.object({ version: z.number().int() }); +// strict は object にしか付かないので、部分補正とマスクの中まで strict にした版を組み立てる。 +// v2 に groupId が混ざっていれば拒む (version の書き間違いを通さない) +const strictV2 = editRecipeSchemaV2.strict().extend({ + localAdjustments: localAdjustmentSchemaV2.strict().array().max(MAX_LOCAL_ADJUSTMENTS_V2), +}); +const strictV3 = editRecipeSchemaV3.strict().extend({ + localAdjustments: localAdjustmentSchemaV3.strict().array().max(MAX_LOCAL_ADJUSTMENTS), +}); + /** v1 -> v2: 部分補正を空で足す (#109) */ export function migrateV1toV2(v1: EditRecipeV1): EditRecipeV2 { return { ...v1, version: 2, localAdjustments: [] }; } +/** v2 -> v3: 部分補正に groupId: null を足す (#175)。マスクはそのまま (v2 の 2 種は v3 でも有効) */ +export function migrateV2toV3(v2: EditRecipeV2): EditRecipeV3 { + return { + ...v2, + version: 3, + localAdjustments: v2.localAdjustments.map((l) => ({ ...l, groupId: null })), + }; +} + function parseOrThrow(schema: z.ZodType, input: unknown, label: string): T { const parsed = schema.safeParse(input); if (!parsed.success) { @@ -41,9 +65,11 @@ export function migrateRecipe(input: unknown): EditRecipe { } switch (head.data.version) { case 1: - return migrateV1toV2(parseOrThrow(editRecipeSchemaV1.strict(), input, "v1")); + return migrateV2toV3(migrateV1toV2(parseOrThrow(editRecipeSchemaV1.strict(), input, "v1"))); case 2: - return parseOrThrow(editRecipeSchemaV2.strict(), input, "v2"); + return migrateV2toV3(parseOrThrow(strictV2, input, "v2")); + case 3: + return parseOrThrow(strictV3, input, "v3"); default: throw new RecipeMigrationError(`unsupported recipe version: ${head.data.version}`); } diff --git a/packages/shared/src/recipe/recipe.test.ts b/packages/shared/src/recipe/recipe.test.ts index 36819ae..9019045 100644 --- a/packages/shared/src/recipe/recipe.test.ts +++ b/packages/shared/src/recipe/recipe.test.ts @@ -1,13 +1,18 @@ import { describe, expect, it } from "vitest"; import { + BITMAP_MAX_EDGE, DEFAULT_ELLIPSE_MASK, DEFAULT_LOCAL_ADJUST, DEFAULT_LOCAL_ADJUSTMENT, DEFAULT_RECIPE, + MAX_LOCAL_ADJUSTMENTS, + MAX_POLYGON_POINTS, editRecipeInputSchema, editRecipeSchema, + editRecipeSchemaV2, localAdjustmentSchema, } from "./schema.ts"; +import { encodeRle } from "./rle.ts"; import { migrateRecipe, RecipeMigrationError } from "./migrate.ts"; import { applyPreset, findPreset, PRESETS } from "./presets.ts"; import { applyLocalPreset, LOCAL_PRESETS } from "./local-presets.ts"; @@ -93,42 +98,188 @@ describe("editRecipeSchema v2 (#109 部分補正)", () => { presetId: null, mask: { kind: "brush", strokes: [stroke], feather: 0, invert: false }, } as const; - const v2 = (local: unknown[]) => ({ ...DEFAULT_RECIPE, version: 2, localAdjustments: local }); - - it("accepts the default recipe as version 2 with no local adjustments", () => { - expect(DEFAULT_RECIPE.version).toBe(2); - expect(DEFAULT_RECIPE.localAdjustments).toEqual([]); - expect(editRecipeSchema.parse(DEFAULT_RECIPE)).toEqual(DEFAULT_RECIPE); + const v2 = (local: unknown[]) => ({ + version: 2, + presetId: null, + adjust: DEFAULT_RECIPE.adjust, + geometry: DEFAULT_RECIPE.geometry, + localAdjustments: local, }); it("accepts an ellipse and a brush local adjustment", () => { - expect(editRecipeSchema.safeParse(v2([ellipse, brush])).success).toBe(true); + expect(editRecipeSchemaV2.safeParse(v2([ellipse, brush])).success).toBe(true); }); - it("rejects a 9th local adjustment", () => { + it("rejects a 9th local adjustment in v2 (v2 の上限は 8 のまま)", () => { const nine = Array.from({ length: 9 }, (_, i) => ({ ...ellipse, id: `m${i}` })); - expect(editRecipeSchema.safeParse(v2(nine)).success).toBe(false); - expect(editRecipeSchema.safeParse(v2(nine.slice(0, 8))).success).toBe(true); + expect(editRecipeSchemaV2.safeParse(v2(nine)).success).toBe(false); + expect(editRecipeSchemaV2.safeParse(v2(nine.slice(0, 8))).success).toBe(true); }); it("rejects smooth above 60 (美肌の上限)", () => { const bad = { ...ellipse, adjust: { ...ellipse.adjust, smooth: 61 } }; - expect(editRecipeSchema.safeParse(v2([bad])).success).toBe(false); + expect(editRecipeSchemaV2.safeParse(v2([bad])).success).toBe(false); }); it("rejects a brush stroke with more than 512 points", () => { const points = Array.from({ length: 513 }, () => ({ x: 0.5, y: 0.5 })); const bad = { ...brush, mask: { ...brush.mask, strokes: [{ ...stroke, points }] } }; - expect(editRecipeSchema.safeParse(v2([bad])).success).toBe(false); + expect(editRecipeSchemaV2.safeParse(v2([bad])).success).toBe(false); }); it("rejects an ellipse with zero radius", () => { const bad = { ...ellipse, mask: { ...ellipse.mask, rx: 0 } }; - expect(editRecipeSchema.safeParse(v2([bad])).success).toBe(false); + expect(editRecipeSchemaV2.safeParse(v2([bad])).success).toBe(false); }); it("rejects an unknown local preset id", () => { - expect(editRecipeSchema.safeParse(v2([{ ...ellipse, presetId: "nose" }])).success).toBe(false); + expect(editRecipeSchemaV2.safeParse(v2([{ ...ellipse, presetId: "nose" }])).success).toBe( + false, + ); + }); + + it("rejects v3 masks (polygon) in a v2 recipe", () => { + const poly = { ...ellipse, mask: polygonMask }; + expect(editRecipeSchemaV2.safeParse(v2([poly])).success).toBe(false); + }); +}); + +const polygonMask = { + kind: "polygon", + rings: [ + [ + { x: 0.3, y: 0.2 }, + { x: 0.7, y: 0.2 }, + { x: 0.5, y: 0.8 }, + ], + ], + strokes: [], + feather: 0.1, + invert: false, +} as const; + +describe("editRecipeSchema v3 (#176 自動選択のマスク)", () => { + const base = { + id: "face", + name: null, + presetId: "skin", + groupId: null, + adjust: DEFAULT_LOCAL_ADJUST, + amount: 100, + visible: true, + } as const; + const bitmapMask = { + kind: "bitmap", + width: 4, + height: 2, + rle: encodeRle(Uint8Array.from([0, 1, 1, 0, 0, 1, 1, 0])), + strokes: [], + feather: 0, + invert: false, + } as const; + const v3 = (local: unknown[]) => ({ ...DEFAULT_RECIPE, localAdjustments: local }); + + it("the default recipe is version 3 with no local adjustments", () => { + expect(DEFAULT_RECIPE.version).toBe(3); + expect(DEFAULT_RECIPE.localAdjustments).toEqual([]); + expect(editRecipeSchema.parse(DEFAULT_RECIPE)).toEqual(DEFAULT_RECIPE); + }); + + it("accepts polygon and bitmap masks alongside ellipse and brush", () => { + const list = [ + { ...base, mask: polygonMask }, + { ...base, id: "gear", presetId: "gear", mask: bitmapMask }, + { ...base, id: "eye", presetId: "eyes", mask: DEFAULT_ELLIPSE_MASK }, + ]; + expect(editRecipeSchema.safeParse(v3(list)).success).toBe(true); + }); + + it("allows up to 12 local adjustments (人物補正 1 人で 5 件使う)", () => { + expect(MAX_LOCAL_ADJUSTMENTS).toBe(12); + const many = (n: number) => + Array.from({ length: n }, (_, i) => ({ ...base, id: `m${i}`, mask: DEFAULT_ELLIPSE_MASK })); + expect(editRecipeSchema.safeParse(v3(many(12))).success).toBe(true); + expect(editRecipeSchema.safeParse(v3(many(13))).success).toBe(false); + }); + + it("rejects a polygon ring with fewer than 3 points or more than the limit", () => { + const two = { ...polygonMask, rings: [polygonMask.rings[0].slice(0, 2)] }; + expect(editRecipeSchema.safeParse(v3([{ ...base, mask: two }])).success).toBe(false); + const ring = Array.from({ length: MAX_POLYGON_POINTS + 1 }, (_, i) => ({ + x: (i % 100) / 100, + y: 0.5, + })); + expect( + editRecipeSchema.safeParse(v3([{ ...base, mask: { ...polygonMask, rings: [ring] } }])) + .success, + ).toBe(false); + }); + + it("rejects a bitmap larger than the edge limit or with a mismatched rle", () => { + const big = { + ...bitmapMask, + width: BITMAP_MAX_EDGE + 1, + height: 1, + rle: encodeRle(new Uint8Array(BITMAP_MAX_EDGE + 1)), + }; + expect(editRecipeSchema.safeParse(v3([{ ...base, mask: big }])).success).toBe(false); + const short = { ...bitmapMask, rle: encodeRle(Uint8Array.from([1, 1, 1])) }; + expect(editRecipeSchema.safeParse(v3([{ ...base, mask: short }])).success).toBe(false); + }); + + it("carries a groupId so a portrait's adjustments can be handled together", () => { + const grouped = { ...base, groupId: "p1", mask: polygonMask }; + expect(editRecipeSchema.safeParse(v3([grouped])).success).toBe(true); + expect(editRecipeSchema.safeParse(v3([{ ...grouped, groupId: "x".repeat(33) }])).success).toBe( + false, + ); + }); +}); + +describe("migrateRecipe v2 -> v3", () => { + const v2 = { + version: 2, + presetId: null, + adjust: DEFAULT_RECIPE.adjust, + geometry: DEFAULT_RECIPE.geometry, + localAdjustments: [ + { + id: "a", + name: null, + presetId: "eyes", + mask: DEFAULT_ELLIPSE_MASK, + adjust: DEFAULT_LOCAL_ADJUST, + amount: 80, + visible: true, + }, + ], + }; + + it("adds groupId: null to each local adjustment and bumps the version", () => { + const out = migrateRecipe(v2); + expect(out.version).toBe(3); + expect(out.localAdjustments[0]).toEqual({ ...v2.localAdjustments[0], groupId: null }); + }); + + it("migrates v1 all the way to v3", () => { + const v1 = { + version: 1, + presetId: null, + adjust: DEFAULT_RECIPE.adjust, + geometry: DEFAULT_RECIPE.geometry, + }; + expect(migrateRecipe(v1)).toEqual({ ...v1, version: 3, localAdjustments: [] }); + }); + + it("rejects a v2 recipe that already carries groupId", () => { + const leaked = { ...v2, localAdjustments: [{ ...v2.localAdjustments[0], groupId: null }] }; + expect(() => migrateRecipe(leaked)).toThrow(RecipeMigrationError); + }); + + it("accepts v1, v2 and v3 through editRecipeInputSchema (API の入出力)", () => { + expect(editRecipeInputSchema.safeParse(v2).success).toBe(true); + expect(editRecipeInputSchema.safeParse(DEFAULT_RECIPE).success).toBe(true); + expect(editRecipeInputSchema.safeParse({ ...DEFAULT_RECIPE, version: 4 }).success).toBe(false); }); }); @@ -140,11 +291,11 @@ describe("migrateRecipe v1 -> v2", () => { geometry: { ...DEFAULT_RECIPE.geometry, rotation: 90 }, }; - it("fills localAdjustments with an empty array and bumps the version", () => { - expect(migrateRecipe(v1)).toEqual({ ...v1, version: 2, localAdjustments: [] }); + it("fills localAdjustments with an empty array (v2 の形) on the way to the current version", () => { + expect(migrateRecipe(v1)).toEqual({ ...v1, version: 3, localAdjustments: [] }); }); - it("passes a valid v2 recipe through unchanged", () => { + it("passes a valid current recipe through unchanged", () => { expect(migrateRecipe(DEFAULT_RECIPE)).toEqual(DEFAULT_RECIPE); }); @@ -152,9 +303,8 @@ describe("migrateRecipe v1 -> v2", () => { expect(() => migrateRecipe({ ...v1, localAdjustments: [] })).toThrow(RecipeMigrationError); }); - it("accepts either version through editRecipeInputSchema (API の入出力)", () => { + it("accepts v1 through editRecipeInputSchema but not a v1 body labelled v3", () => { expect(editRecipeInputSchema.safeParse(v1).success).toBe(true); - expect(editRecipeInputSchema.safeParse(DEFAULT_RECIPE).success).toBe(true); expect(editRecipeInputSchema.safeParse({ ...v1, version: 3 }).success).toBe(false); }); }); diff --git a/packages/shared/src/recipe/rle.test.ts b/packages/shared/src/recipe/rle.test.ts new file mode 100644 index 0000000..66ab7e3 --- /dev/null +++ b/packages/shared/src/recipe/rle.test.ts @@ -0,0 +1,34 @@ +import { describe, expect, it } from "vitest"; +import { decodeRle, encodeRle } from "./rle.ts"; + +describe("rle (bitmap マスクの圧縮)", () => { + it("0/1 の列を往復できる", () => { + const src = Uint8Array.from([0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1]); + const text = encodeRle(src); + expect(decodeRle(text, src.length)).toEqual(src); + }); + + it("全部 0 と全部 1 も往復できる", () => { + for (const v of [0, 1]) { + const src = new Uint8Array(1000).fill(v); + expect(decodeRle(encodeRle(src), 1000)).toEqual(src); + } + }); + + it("長い連 (65535 超) も往復できる", () => { + const src = new Uint8Array(70000).fill(1); + src[0] = 0; + expect(decodeRle(encodeRle(src), src.length)).toEqual(src); + }); + + it("URL に載せられる文字だけを使う (base64url)", () => { + const src = Uint8Array.from({ length: 512 }, (_, i) => (i % 7 < 3 ? 1 : 0)); + expect(encodeRle(src)).toMatch(/^[A-Za-z0-9_-]*$/); + }); + + it("長さが合わない入力は捨てる", () => { + const text = encodeRle(Uint8Array.from([1, 1, 0])); + expect(() => decodeRle(text, 4)).toThrow(); + expect(() => decodeRle("!!", 3)).toThrow(); + }); +}); diff --git a/packages/shared/src/recipe/rle.ts b/packages/shared/src/recipe/rle.ts new file mode 100644 index 0000000..ae4c923 --- /dev/null +++ b/packages/shared/src/recipe/rle.ts @@ -0,0 +1,105 @@ +/** + * bitmap マスク (Recipe v3、#176 / #177) の 0/1 列をランレングスで圧縮する。 + * 連の長さを 0 から始めて交互に (0 の連、1 の連、0 の連 ...) LEB128 の可変長整数で並べ、 + * base64url にする。ブラウザでも Node でも動くように、Buffer や atob は使わない。 + * 256×256 (65,536 px) のマスクは、輪郭の複雑さにもよるが数百〜数 KB になる。 + */ + +const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; +const LOOKUP = new Map(Array.from(ALPHABET, (c, i) => [c, i])); + +function toBase64Url(bytes: readonly number[]): string { + let out = ""; + for (let i = 0; i < bytes.length; i += 3) { + const b0 = bytes[i]!; + const b1 = bytes[i + 1]; + const b2 = bytes[i + 2]; + out += ALPHABET[b0 >> 2]!; + out += ALPHABET[((b0 & 3) << 4) | ((b1 ?? 0) >> 4)]!; + if (b1 === undefined) break; + out += ALPHABET[((b1 & 15) << 2) | ((b2 ?? 0) >> 6)]!; + if (b2 === undefined) break; + out += ALPHABET[b2 & 63]!; + } + return out; +} + +function fromBase64Url(text: string): number[] { + const out: number[] = []; + let acc = 0; + let bits = 0; + for (const c of text) { + const v = LOOKUP.get(c); + if (v === undefined) throw new Error("rle: invalid character"); + acc = (acc << 6) | v; + bits += 6; + if (bits >= 8) { + bits -= 8; + out.push((acc >> bits) & 255); + } + } + return out; +} + +/** 0/1 (0 以外は 1 とみなす) の列を圧縮する */ +export function encodeRle(mask: Uint8Array | Uint8ClampedArray): string { + const bytes: number[] = []; + const pushVarint = (n: number) => { + let v = n; + while (v >= 128) { + bytes.push((v & 127) | 128); + v = Math.floor(v / 128); + } + bytes.push(v); + }; + let current = 0; + let run = 0; + for (let i = 0; i < mask.length; i++) { + const bit = mask[i] ? 1 : 0; + if (bit === current) { + run++; + } else { + pushVarint(run); + current = bit; + run = 1; + } + } + pushVarint(run); + return toBase64Url(bytes); +} + +/** 圧縮した列を length 個の 0/1 に戻す。長さが合わなければ捨てる (壊れたレシピを通さない) */ +export function decodeRle(text: string, length: number): Uint8Array { + const bytes = fromBase64Url(text); + const out = new Uint8Array(length); + let pos = 0; + let current = 0; + let i = 0; + while (i < bytes.length) { + let run = 0; + let shift = 1; + for (;;) { + const b = bytes[i++]; + if (b === undefined) throw new Error("rle: truncated"); + run += (b & 127) * shift; + if (b < 128) break; + shift *= 128; + } + if (pos + run > length) throw new Error("rle: length mismatch"); + if (current) out.fill(1, pos, pos + run); + pos += run; + current ^= 1; + } + if (pos !== length) throw new Error("rle: length mismatch"); + return out; +} + +/** 復号できて長さが合うか (スキーマの検証用) */ +export function isValidRle(text: string, length: number): boolean { + try { + decodeRle(text, length); + return true; + } catch { + return false; + } +} diff --git a/packages/shared/src/recipe/schema.ts b/packages/shared/src/recipe/schema.ts index ebe9aab..c519353 100644 --- a/packages/shared/src/recipe/schema.ts +++ b/packages/shared/src/recipe/schema.ts @@ -1,4 +1,5 @@ import { z } from "zod"; +import { isValidRle } from "./rle.ts"; // zod 4 は JIT の可否を Function("") で探る。CSP (script-src に unsafe-eval が無い) の下では握られて動作は // 落ちないが、ブラウザから違反が報告され続ける (RM-30)。このスキーマはブラウザでも動くので JIT を使わない。 @@ -8,11 +9,12 @@ z.config({ jitless: true }); // 編集レシピ。定義は docs/design/04-edit-recipe.md を正とする。 // 変更は追加のみ。既存項目の意味・値域は変えない (ADR-0009)。 // v1: 全体の補正と幾何。v2: 部分補正 (マスク付きの補正、#109) を追加。 +// v3: 自動選択 (#176 / #177) のための多角形・ビットマップのマスクと、人物補正 (#175) の groupId を追加。 const pct = z.number().min(-100).max(100); -/** 部分補正の上限。レシピの肥大化と描画負荷を抑える (#109) */ -export const MAX_LOCAL_ADJUSTMENTS = 8; +/** v2 の部分補正の上限 (レシピの肥大化と描画負荷を抑える、#109)。v3 は MAX_LOCAL_ADJUSTMENTS */ +export const MAX_LOCAL_ADJUSTMENTS_V2 = 8; export const MAX_BRUSH_STROKES = 64; export const MAX_BRUSH_POINTS = 512; export const MAX_LOCAL_SMOOTH = 60; @@ -127,7 +129,7 @@ export const localAdjustmentSchemaV2 = z.object({ export const editRecipeSchemaV2 = editRecipeSchemaV1.extend({ version: z.literal(2), - localAdjustments: z.array(localAdjustmentSchemaV2).max(MAX_LOCAL_ADJUSTMENTS), + localAdjustments: z.array(localAdjustmentSchemaV2).max(MAX_LOCAL_ADJUSTMENTS_V2), }); export type LocalAdjustV2 = z.infer; @@ -139,17 +141,89 @@ export type LocalPresetId = (typeof LOCAL_PRESET_IDS)[number]; export type LocalAdjustmentV2 = z.infer; export type EditRecipeV2 = z.infer; +// ---- v3: 自動選択のマスクと人物補正のまとまり (#175 / #176 / #177) ---- +// 顔の輪郭 (多角形) と SAM の切り抜き (ビットマップ) をブラシ点列に崩さず持つ。どちらも strokes を持ち、 +// 自動で置いたマスクの上にブラシで足す / 消す (brush と同じ道具で直せる)。 +// 座標系は v2 と同じ (幾何を掛ける前の画像の正規化座標)。 + +/** 部分補正の上限。人物補正 (#175) が 1 人で 5 件 (顔・瞳 ×2・人物・背景) 使う */ +export const MAX_LOCAL_ADJUSTMENTS = 12; +/** 多角形の輪 (外周 1 + 穴) の上限と、1 輪の点数の上限 */ +export const MAX_POLYGON_RINGS = 8; +export const MAX_POLYGON_POINTS = 256; +/** ビットマップマスクの 1 辺の上限 (px)。GPU では線形補間で拡大するので境界は滑らか */ +export const BITMAP_MAX_EDGE = 256; + +const ring = z + .array(z.object({ x: unit, y: unit })) + .min(3) + .max(MAX_POLYGON_POINTS); + +export const polygonMaskSchemaV3 = z.object({ + kind: z.literal("polygon"), + /** 先頭が外周、以降は穴 (偶奇で塗る)。顔なら外周 = 顔の輪郭、穴 = 目・口 */ + rings: z.array(ring).min(1).max(MAX_POLYGON_RINGS), + strokes: z.array(brushStrokeSchemaV2).max(MAX_BRUSH_STROKES), + feather: unit, + invert: z.boolean(), +}); + +export const bitmapMaskSchemaV3 = z + .object({ + kind: z.literal("bitmap"), + width: z.number().int().min(1).max(BITMAP_MAX_EDGE), + height: z.number().int().min(1).max(BITMAP_MAX_EDGE), + /** width × height の 0/1 を rle.ts で圧縮したもの (行優先) */ + rle: z.string().max(64 * 1024), + strokes: z.array(brushStrokeSchemaV2).max(MAX_BRUSH_STROKES), + feather: unit, + invert: z.boolean(), + }) + .refine((m) => isValidRle(m.rle, m.width * m.height), { message: "rle does not match size" }); + +export const maskSchemaV3 = z.discriminatedUnion("kind", [ + ellipseMaskSchemaV2, + brushMaskSchemaV2, + polygonMaskSchemaV3, + bitmapMaskSchemaV3, +]); + +export const localAdjustmentSchemaV3 = localAdjustmentSchemaV2.extend({ + mask: maskSchemaV3, + /** 人物補正 (#175) など、まとめて扱う部分補正の組。無ければ null */ + groupId: z.string().min(1).max(32).nullable(), +}); + +export const editRecipeSchemaV3 = editRecipeSchemaV1.extend({ + version: z.literal(3), + localAdjustments: z.array(localAdjustmentSchemaV3).max(MAX_LOCAL_ADJUSTMENTS), +}); + +export type PolygonMaskV3 = z.infer; +export type BitmapMaskV3 = z.infer; +export type MaskV3 = z.infer; +export type LocalAdjustmentV3 = z.infer; +export type EditRecipeV3 = z.infer; +/** strokes を持つマスク (ブラシで直せるもの) */ +export type StrokedMask = Exclude; + /** 現行のレシピ型。version を上げたらここを差し替える。 */ -export type EditRecipe = EditRecipeV2; -export const editRecipeSchema = editRecipeSchemaV2; -export const CURRENT_RECIPE_VERSION = 2 as const; -export const localAdjustmentSchema = localAdjustmentSchemaV2; +export type EditRecipe = EditRecipeV3; +export type LocalAdjustment = LocalAdjustmentV3; +export type Mask = MaskV3; +export const editRecipeSchema = editRecipeSchemaV3; +export const CURRENT_RECIPE_VERSION = 3 as const; +export const localAdjustmentSchema = localAdjustmentSchemaV3; /** * API の入出力で受けるレシピ。旧版の投稿はそのまま返り、投稿時も旧版のクライアントを受ける。 * 読む側は migrateRecipe で現行に揃える。 */ -export const editRecipeInputSchema = z.union([editRecipeSchemaV1, editRecipeSchemaV2]); +export const editRecipeInputSchema = z.union([ + editRecipeSchemaV1, + editRecipeSchemaV2, + editRecipeSchemaV3, +]); export type EditRecipeInput = z.infer; export const DEFAULT_ADJUST: AdjustV1 = Object.freeze({ @@ -203,16 +277,17 @@ export const DEFAULT_BRUSH_MASK: BrushMaskV2 = Object.freeze({ }); /** id と mask を除いた部分補正の既定値。呼ぶ側が id と mask を与える */ -export const DEFAULT_LOCAL_ADJUSTMENT: Omit = Object.freeze({ +export const DEFAULT_LOCAL_ADJUSTMENT: Omit = Object.freeze({ name: null, presetId: null, + groupId: null, adjust: DEFAULT_LOCAL_ADJUST, amount: 100, visible: true, }); export const DEFAULT_RECIPE: EditRecipe = Object.freeze({ - version: 2, + version: 3, presetId: null, adjust: DEFAULT_ADJUST, geometry: DEFAULT_GEOMETRY, From b2e4f5aed6e1529d2cdf637f51c36920e31a0bac Mon Sep 17 00:00:00 2001 From: t1nyb0x Date: Mon, 21 Sep 2026 11:03:41 +0900 Subject: [PATCH 27/49] =?UTF-8?q?feat:=20=E7=9E=B3=E5=BC=B7=E8=AA=BF?= =?UTF-8?q?=E3=83=BB=E7=BE=8E=E8=82=8C=E3=81=A7=E9=A1=94=E3=82=92=E8=AA=8D?= =?UTF-8?q?=E8=AD=98=E3=81=97=E3=81=A6=E3=83=9E=E3=82=B9=E3=82=AF=E3=82=92?= =?UTF-8?q?=E8=87=AA=E5=8B=95=E3=81=A7=E7=BD=AE=E3=81=8F=20(Face=20Landmar?= =?UTF-8?q?ker=20=E3=82=92=E3=83=96=E3=83=A9=E3=82=A6=E3=82=B6=E3=81=AE=20?= =?UTF-8?q?Worker=20=E3=81=A7)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit lumorphia/prismtone#162 の spike の結果を本体に入れる (計画の PR2)。部分補正の「瞳強調」「美肌」を何も選ばずに押すと、 MediaPipe Face Landmarker (WASM、CPU) を Web Worker で動かして顔を検出し、瞳は虹彩の円形 ×2、 美肌は顔の輪郭を外周・両目と唇を穴にした多角形を 1 手で置く。置いたあとはハンドルとブラシで直せる。 - 検出はピラミッド (全体 + 2 倍の 3×3、IoU 0.3、縁の顔は捨てる、しきい値 0.3)。spike で 29 枚中 27 枚 - 目を閉じている目 (eyeBlink 0.5 以上) には置かず、片方だけなら開いている方に置いて一言出す - 失敗の文言は理由を断定しない: 「自動選択できませんでした。手動で範囲を指定できます」。手動の追加は残す - 検出のライブラリは押したときに動的 import。classic worker (MediaPipe の WASM ローダーが importScripts を 使うので module worker では ModuleFactory not set で落ちる) - モデルと WASM は git に入れず、apps/app/scripts/fetch-models.ts が sha256 固定で public/models/ に揃える (dev / build の前)。モデル本体は Worker が fetch して進捗を出す - 画像も結果も外に送らない (プライバシーポリシー 3.2 に明記。E2E で自分のオリジン以外へのリクエストが 無いことを見る)。CSP は wasm-unsafe-eval のまま (csp.spec.ts で顔の画像に瞳が置かれること) - E2E の顔の画像は運営者のスクショ (e2e/fixtures/face.jpg、長辺 960) Closes lumorphia/prismtone#176 Co-Authored-By: Claude Opus 5 --- apps/app/scripts/fetch-models.ts | 88 +++++++ .../editor/inference/auto-select.test.ts | 63 +++++ .../features/editor/inference/auto-select.ts | 42 ++++ .../editor/inference/face-masks.test.ts | 69 ++++++ .../features/editor/inference/face-masks.ts | 80 ++++++ .../app/web/features/editor/inference/face.ts | 73 ++++++ .../features/editor/inference/face.worker.ts | 229 ++++++++++++++++++ apps/app/web/features/editor/state.test.ts | 53 ++++ apps/app/web/features/editor/state.ts | 73 +++++- .../app/web/features/editor/ui/EditorPage.tsx | 37 +++ .../app/web/features/editor/ui/LocalPanel.tsx | 35 ++- e2e/editor.spec.ts | 70 +++++- e2e/fixtures/face.jpg | Bin 0 -> 136819 bytes 13 files changed, 901 insertions(+), 11 deletions(-) create mode 100644 apps/app/scripts/fetch-models.ts create mode 100644 apps/app/web/features/editor/inference/auto-select.test.ts create mode 100644 apps/app/web/features/editor/inference/auto-select.ts create mode 100644 apps/app/web/features/editor/inference/face-masks.test.ts create mode 100644 apps/app/web/features/editor/inference/face-masks.ts create mode 100644 apps/app/web/features/editor/inference/face.ts create mode 100644 apps/app/web/features/editor/inference/face.worker.ts create mode 100644 e2e/fixtures/face.jpg diff --git a/apps/app/scripts/fetch-models.ts b/apps/app/scripts/fetch-models.ts new file mode 100644 index 0000000..461de26 --- /dev/null +++ b/apps/app/scripts/fetch-models.ts @@ -0,0 +1,88 @@ +/** + * ブラウザ内の認識 (ADR-0025) に使うモデルと WASM を public/models/-v/ に揃える。 + * dev と build の前に走る (package.json)。git には入れない (.gitignore)。 + * + * - ダウンロードするものは URL と sha256 を固定する。ハッシュが合わなければ捨てて失敗する + * - node_modules からコピーするもの (WASM) は、パッケージの版を上げたら -v の n も上げる + * (静的アセットは immutable でキャッシュされるので、同じパスで中身を変えない) + * - 既にあってハッシュが合えば何もしない (2 回目以降は一瞬で終わる) + */ +import { createHash } from "node:crypto"; +import { access, copyFile, mkdir, readFile, writeFile } from "node:fs/promises"; +import path from "node:path"; + +const root = path.resolve(import.meta.dirname, ".."); +const out = path.join(root, "public", "models"); + +type Download = { kind: "download"; to: string; url: string; sha256: string }; +type Copy = { kind: "copy"; to: string; from: string }; + +/** 配るもの。to は public/models/ からの相対パス */ +const ASSETS: (Download | Copy)[] = [ + // MediaPipe Face Landmarker (瞳・顔、#176)。Apache-2.0 + { + kind: "download", + to: "face-landmarker-v1/face_landmarker.task", + url: "https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task", + sha256: "64184e229b263107bc2b804c6625db1341ff2bb731874b0bcc2fe6544e0bc9ff", + }, + ...[ + "vision_wasm_internal.js", + "vision_wasm_internal.wasm", + "vision_wasm_nosimd_internal.js", + "vision_wasm_nosimd_internal.wasm", + ].map((f): Copy => ({ + kind: "copy", + to: `face-landmarker-v1/wasm/${f}`, + from: path.join(root, "node_modules", "@mediapipe", "tasks-vision", "wasm", f), + })), +]; + +async function sha256(file: string): Promise { + try { + return createHash("sha256") + .update(await readFile(file)) + .digest("hex"); + } catch { + return null; + } +} + +async function download(asset: Download): Promise { + const target = path.join(out, asset.to); + if ((await sha256(target)) === asset.sha256) return; + console.log(`models: downloading ${asset.to}`); + const res = await fetch(asset.url); + if (!res.ok) throw new Error(`models: ${asset.url} -> ${res.status}`); + const body = Buffer.from(await res.arrayBuffer()); + const got = createHash("sha256").update(body).digest("hex"); + if (got !== asset.sha256) { + throw new Error( + `models: sha256 mismatch for ${asset.to}: expected ${asset.sha256}, got ${got}`, + ); + } + await mkdir(path.dirname(target), { recursive: true }); + await writeFile(target, body); +} + +async function copy(asset: Copy): Promise { + const target = path.join(out, asset.to); + const [a, b] = await Promise.all([sha256(target), sha256(asset.from)]); + if (b === null) throw new Error(`models: missing ${asset.from} (pnpm install を先に)`); + if (a === b) return; + await mkdir(path.dirname(target), { recursive: true }); + await copyFile(asset.from, target); +} + +await mkdir(out, { recursive: true }); +for (const asset of ASSETS) { + if (asset.kind === "download") await download(asset); + else await copy(asset); +} +// public/ の中で git に入れないことを、ディレクトリ自身にも書いておく +try { + await access(path.join(out, ".gitignore")); +} catch { + await writeFile(path.join(out, ".gitignore"), "*\n"); +} +console.log(`models: ${ASSETS.length} files ready in ${path.relative(root, out)}`); diff --git a/apps/app/web/features/editor/inference/auto-select.test.ts b/apps/app/web/features/editor/inference/auto-select.test.ts new file mode 100644 index 0000000..7d28b4d --- /dev/null +++ b/apps/app/web/features/editor/inference/auto-select.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, it } from "vitest"; +import { AUTO_SELECT_FAILED, planFaceSelection } from "./auto-select.ts"; +import type { FaceResult } from "./face-masks.ts"; + +const square = (cx: number, cy: number, r: number) => [ + { x: cx - r, y: cy - r }, + { x: cx + r, y: cy - r }, + { x: cx + r, y: cy + r }, + { x: cx - r, y: cy + r }, +]; +const face = (overrides: Partial = {}): FaceResult => ({ + bbox: [0.3, 0.2, 0.7, 0.8], + oval: square(0.5, 0.5, 0.25), + leftEye: square(0.4, 0.4, 0.03), + rightEye: square(0.6, 0.4, 0.03), + mouth: square(0.5, 0.65, 0.05), + leftIris: { cx: 0.4, cy: 0.4, rx: 0.01, ry: 0.02 }, + rightIris: { cx: 0.6, cy: 0.4, rx: 0.01, ry: 0.02 }, + blink: { left: 0.05, right: 0.1 }, + ...overrides, +}); + +describe("planFaceSelection", () => { + it("瞳: puts two ellipses on the main face's irises in one step", () => { + const plan = planFaceSelection("eyes", [face()]); + expect(plan.items).toHaveLength(2); + expect(plan.items.every((i) => i.presetId === "eyes" && i.mask.kind === "ellipse")).toBe(true); + expect(plan.label).toBe("瞳強調 (自動)"); + expect(plan.notice).toBeNull(); + }); + + it("美肌: puts one polygon with holes on the main face", () => { + const plan = planFaceSelection("skin", [face()]); + expect(plan.items).toHaveLength(1); + expect(plan.items[0]!.presetId).toBe("skin"); + expect(plan.items[0]!.mask.kind).toBe("polygon"); + expect(plan.label).toBe("美肌 (自動)"); + }); + + it("says so without guessing why when no face was found", () => { + const plan = planFaceSelection("eyes", []); + expect(plan.items).toHaveLength(0); + expect(plan.notice).toBe(AUTO_SELECT_FAILED); + }); + + it("瞳: tells when the eyes are closed and places only the open one", () => { + const one = planFaceSelection("eyes", [face({ blink: { left: 0.9, right: 0.1 } })]); + expect(one.items).toHaveLength(1); + expect(one.notice).toMatch(/閉じている/); + const none = planFaceSelection("eyes", [face({ blink: { left: 0.9, right: 0.8 } })]); + expect(none.items).toHaveLength(0); + expect(none.notice).toMatch(/閉じている/); + }); + + it("uses the largest face when there are several", () => { + const small = face({ + bbox: [0.1, 0.1, 0.2, 0.25], + leftIris: { cx: 0.12, cy: 0.15, rx: 0.003, ry: 0.005 }, + }); + const plan = planFaceSelection("eyes", [small, face()]); + expect(plan.items[0]!.mask).toMatchObject({ cx: 0.4 }); + }); +}); diff --git a/apps/app/web/features/editor/inference/auto-select.ts b/apps/app/web/features/editor/inference/auto-select.ts new file mode 100644 index 0000000..9f9a4e1 --- /dev/null +++ b/apps/app/web/features/editor/inference/auto-select.ts @@ -0,0 +1,42 @@ +import type { LocalPresetId } from "@prismtone/shared/recipe"; +import type { AutoLocalItem } from "../state.ts"; +import { facePolygon, irisEllipses, pickMainFace, type FaceResult } from "./face-masks.ts"; + +/** + * 自動選択 (#176) の計画: 検出結果から「何を足すか」と「利用者に伝える一言」を決める純関数。 + * 文言は理由を断定しない (#175): 横顔・種族・小ささのどれで外れたかは分からない + */ + +export const AUTO_SELECT_FAILED = "自動選択できませんでした。手動で範囲を指定できます"; +export const EYES_CLOSED = "目を閉じているようです。手動で範囲を指定できます"; +export const ONE_EYE_CLOSED = "片方の目は閉じているようなので、開いている方だけに置きました"; + +export type FaceSelectionKind = Extract; + +export type SelectionPlan = { + readonly items: readonly AutoLocalItem[]; + readonly label: string; + readonly notice: string | null; +}; + +export function planFaceSelection( + kind: FaceSelectionKind, + faces: readonly FaceResult[], +): SelectionPlan { + const face = pickMainFace(faces); + if (!face) return { items: [], label: "", notice: AUTO_SELECT_FAILED }; + if (kind === "skin") { + return { + items: [{ presetId: "skin", mask: facePolygon(face) }], + label: "美肌 (自動)", + notice: null, + }; + } + const ellipses = irisEllipses(face); + if (ellipses.length === 0) return { items: [], label: "", notice: EYES_CLOSED }; + return { + items: ellipses.map((mask) => ({ presetId: "eyes", mask })), + label: "瞳強調 (自動)", + notice: ellipses.length === 1 ? ONE_EYE_CLOSED : null, + }; +} diff --git a/apps/app/web/features/editor/inference/face-masks.test.ts b/apps/app/web/features/editor/inference/face-masks.test.ts new file mode 100644 index 0000000..2cc73b2 --- /dev/null +++ b/apps/app/web/features/editor/inference/face-masks.test.ts @@ -0,0 +1,69 @@ +import { describe, expect, it } from "vitest"; +import type { EllipseMaskV2 } from "@prismtone/shared/recipe"; +import { facePolygon, irisEllipses, pickMainFace, type FaceResult } from "./face-masks.ts"; + +const square = (cx: number, cy: number, r: number) => [ + { x: cx - r, y: cy - r }, + { x: cx + r, y: cy - r }, + { x: cx + r, y: cy + r }, + { x: cx - r, y: cy + r }, +]; + +const face = (overrides: Partial = {}): FaceResult => ({ + bbox: [0.3, 0.2, 0.7, 0.8], + oval: square(0.5, 0.5, 0.25), + leftEye: square(0.4, 0.4, 0.03), + rightEye: square(0.6, 0.4, 0.03), + mouth: square(0.5, 0.65, 0.05), + leftIris: { cx: 0.4, cy: 0.4, rx: 0.01, ry: 0.02 }, + rightIris: { cx: 0.6, cy: 0.4, rx: 0.01, ry: 0.02 }, + blink: { left: 0.05, right: 0.1 }, + ...overrides, +}); + +describe("pickMainFace", () => { + it("picks the tallest face (一番大きい顔)", () => { + const small = face({ bbox: [0.1, 0.1, 0.2, 0.25] }); + const big = face(); + expect(pickMainFace([small, big])).toBe(big); + expect(pickMainFace([])).toBeNull(); + }); +}); + +describe("irisEllipses", () => { + it("places an ellipse on each iris, 1.3 times the iris radius, with a soft edge", () => { + const [l, r] = irisEllipses(face()) as [EllipseMaskV2, EllipseMaskV2]; + expect(l).toMatchObject({ kind: "ellipse", cx: 0.4, cy: 0.4, rotation: 0, invert: false }); + expect(l.rx).toBeCloseTo(0.013); + expect(l.ry).toBeCloseTo(0.026); + expect(l.feather).toBe(0.5); + expect(r.cx).toBe(0.6); + }); + + it("skips an eye that is closed (eyeBlink 0.5 以上)", () => { + const closedLeft = face({ blink: { left: 0.8, right: 0.1 } }); + expect(irisEllipses(closedLeft)).toHaveLength(1); + expect(irisEllipses(closedLeft)[0]!.cx).toBe(0.6); + expect(irisEllipses(face({ blink: { left: 0.9, right: 0.7 } }))).toHaveLength(0); + // blendshape が無ければ開いているとみなす + expect(irisEllipses(face({ blink: { left: null, right: null } }))).toHaveLength(2); + }); +}); + +describe("facePolygon", () => { + it("uses the face oval as the outer ring and cuts holes for the eyes and mouth", () => { + const m = facePolygon(face()); + expect(m.kind).toBe("polygon"); + expect(m.rings).toHaveLength(4); + expect(m.rings[0]).toEqual(square(0.5, 0.5, 0.25)); + expect(m.rings[3]).toEqual(square(0.5, 0.65, 0.05)); + expect(m.strokes).toEqual([]); + expect(m.invert).toBe(false); + expect(m.feather).toBeGreaterThan(0); + }); + + it("leaves out a hole that has too few points", () => { + const m = facePolygon(face({ mouth: [] })); + expect(m.rings).toHaveLength(3); + }); +}); diff --git a/apps/app/web/features/editor/inference/face-masks.ts b/apps/app/web/features/editor/inference/face-masks.ts new file mode 100644 index 0000000..ca11d43 --- /dev/null +++ b/apps/app/web/features/editor/inference/face-masks.ts @@ -0,0 +1,80 @@ +import type { EllipseMaskV2, PolygonMaskV3 } from "@prismtone/shared/recipe"; + +/** + * 顔検出 (face.worker.ts) の結果から部分補正のマスクを組む純関数 (#176、ADR-0025)。 + * 座標は幾何を掛ける前の画像の正規化座標 (レシピのマスクと同じ)。 + */ + +export type NormalizedPoint = { x: number; y: number }; + +export type Iris = { + cx: number; + cy: number; + /** 半径。rx は画像の幅、ry は高さに対する比 (楕円マスクと同じ) */ + rx: number; + ry: number; +}; + +export type FaceResult = { + /** 顔の輪郭の外接矩形 [x0, y0, x1, y1] */ + bbox: [number, number, number, number]; + /** 顔の輪郭 (36 点)。多角形の外周になる */ + oval: NormalizedPoint[]; + leftEye: NormalizedPoint[]; + rightEye: NormalizedPoint[]; + /** 唇の外側 */ + mouth: NormalizedPoint[]; + leftIris: Iris; + rightIris: Iris; + /** blendshape の eyeBlinkLeft / eyeBlinkRight (0..1)。無ければ null */ + blink: { left: number | null; right: number | null }; +}; + +/** これ以上なら目を閉じているとみなして瞳は置かない */ +export const BLINK_CLOSED = 0.5; +/** 虹彩に対する円形マスクの半径の比。虹彩より少し広く取って縁を柔らかくする */ +const IRIS_SCALE = 1.3; +const IRIS_FEATHER = 0.5; +/** 顔の多角形のぼかし (0..1、長辺の 5% まで)。輪郭で補正が段にならない程度 */ +const FACE_FEATHER = 0.2; + +/** 一番大きい顔 (高さで比べる)。無ければ null */ +export function pickMainFace(faces: readonly FaceResult[]): FaceResult | null { + let best: FaceResult | null = null; + for (const f of faces) { + if (!best || f.bbox[3] - f.bbox[1] > best.bbox[3] - best.bbox[1]) best = f; + } + return best; +} + +const irisEllipse = (iris: Iris): EllipseMaskV2 => ({ + kind: "ellipse", + cx: iris.cx, + cy: iris.cy, + rx: iris.rx * IRIS_SCALE, + ry: iris.ry * IRIS_SCALE, + rotation: 0, + feather: IRIS_FEATHER, + invert: false, +}); + +/** 開いている目の虹彩に円形マスクを置く (左、右の順)。閉じている目は飛ばす */ +export function irisEllipses(face: FaceResult): EllipseMaskV2[] { + const open = (blink: number | null) => blink === null || blink < BLINK_CLOSED; + return [ + ...(open(face.blink.left) ? [irisEllipse(face.leftIris)] : []), + ...(open(face.blink.right) ? [irisEllipse(face.rightIris)] : []), + ]; +} + +/** 顔の輪郭を外周、目と口を穴にした多角形 (美肌用)。点が足りない穴は入れない */ +export function facePolygon(face: FaceResult): PolygonMaskV3 { + const holes = [face.leftEye, face.rightEye, face.mouth].filter((ring) => ring.length >= 3); + return { + kind: "polygon", + rings: [face.oval, ...holes], + strokes: [], + feather: FACE_FEATHER, + invert: false, + }; +} diff --git a/apps/app/web/features/editor/inference/face.ts b/apps/app/web/features/editor/inference/face.ts new file mode 100644 index 0000000..971cdc2 --- /dev/null +++ b/apps/app/web/features/editor/inference/face.ts @@ -0,0 +1,73 @@ +import type { FaceResult } from "./face-masks.ts"; +import type { FaceRequest, FaceResponse } from "./face.worker.ts"; + +/** + * 顔検出の呼び出し側 (#176)。Worker を 1 つ起こして使い回す。画像は ImageBitmap を複製して渡す + * (Worker 側で閉じる)。進捗は初回のモデル取得の分だけ届く。 + */ + +export class InferenceError extends Error { + override readonly name = "InferenceError"; +} + +export type Progress = { loaded: number; total: number }; + +let worker: Worker | null = null; +let seq = 0; + +function getWorker(): Worker { + if (!worker) { + // classic worker (Vite が iife に束ねる)。MediaPipe の WASM ローダーは importScripts で + // vision_wasm_internal.js を読むので、module worker だと "ModuleFactory not set" で落ちる + worker = new Worker(new URL("./face.worker.ts", import.meta.url)); + } + return worker; +} + +/** Worker を捨てる (テストや、エラー後に作り直すとき) */ +export function resetFaceWorker(): void { + worker?.terminate(); + worker = null; +} + +export async function detectFaces( + bitmap: ImageBitmap, + options: { onProgress?: (p: Progress) => void; signal?: AbortSignal } = {}, +): Promise { + const w = getWorker(); + const id = ++seq; + // Worker に渡す複製 (元は現像で使い続ける) + const copy = await createImageBitmap(bitmap); + return new Promise((resolve, reject) => { + const onMessage = (e: MessageEvent) => { + const m = e.data; + if (m.id !== id) return; + if (m.type === "progress") { + options.onProgress?.({ loaded: m.loaded, total: m.total }); + return; + } + cleanup(); + if (m.type === "result") resolve(m.faces); + else reject(new InferenceError(m.message)); + }; + const onError = (e: ErrorEvent) => { + cleanup(); + resetFaceWorker(); + reject(new InferenceError(e.message || "worker error")); + }; + const onAbort = () => { + cleanup(); + reject(new InferenceError("aborted")); + }; + const cleanup = () => { + w.removeEventListener("message", onMessage); + w.removeEventListener("error", onError); + options.signal?.removeEventListener("abort", onAbort); + }; + w.addEventListener("message", onMessage); + w.addEventListener("error", onError); + options.signal?.addEventListener("abort", onAbort); + const req: FaceRequest = { id, bitmap: copy }; + w.postMessage(req, [copy]); + }); +} diff --git a/apps/app/web/features/editor/inference/face.worker.ts b/apps/app/web/features/editor/inference/face.worker.ts new file mode 100644 index 0000000..2ffa7f8 --- /dev/null +++ b/apps/app/web/features/editor/inference/face.worker.ts @@ -0,0 +1,229 @@ +/// +/** + * 顔検出の Web Worker (#176、ADR-0025)。MediaPipe Face Landmarker (WASM、CPU) を動かし、 + * 顔ごとの輪郭・目・唇・虹彩と blendshape (まばたき) を正規化座標で返す。 + * + * spike (docs/spikes/2026-09-21-auto-select.md) の detectFace を移したもの: + * - 画像全体 → 2 倍の 3×3 の重なる切り抜き の順に検出する (ピラミッド)。BlazeFace 短距離は顔が画面の + * 大部分を占める前提で、スクショの中くらいの顔をそのままでは拾えない + * - 同じ顔 (IoU 0.3 以上) は先に見つかった方 (広い文脈) を残す。切り抜きの縁にかかる顔は捨てる + * - 3 倍の段は誤検出だけ増えたので入れない + * + * 画像も推論もここ (ブラウザ) で完結し、外には送らない。モデルと WASM は /models/ (自前ホスト)。 + */ +import { FaceLandmarker, FilesetResolver } from "@mediapipe/tasks-vision"; +import type { FaceResult, NormalizedPoint } from "./face-masks.ts"; + +export const FACE_MODEL_BASE = "/models/face-landmarker-v1"; +/** 進捗の表示に使う総量の目安 (モデル 3.7 MB + WASM 11 MB)。WASM の取得は MediaPipe の中なので数えられない */ +export const FACE_MODEL_BYTES = 3_758_596 + 11_153_617; + +export type FaceRequest = { + id: number; + bitmap: ImageBitmap; + /** 検出のしきい値。spike の結果は 0.3 */ + confidence?: number; +}; +export type FaceResponse = + | { id: number; type: "progress"; loaded: number; total: number } + | { id: number; type: "result"; faces: FaceResult[]; ms: number } + | { id: number; type: "error"; message: string }; + +const CONFIDENCE = 0.3; +const PYRAMID = [2]; +/** 同じ顔とみなす bbox の IoU */ +const SAME_FACE_IOU = 0.3; +/** 切り抜きの縁からこの割合 (画像全体に対して) 以内にかかる顔は不完全なので捨てる */ +const EDGE_MARGIN = 0.02; + +/** 接続リスト ({start,end}) を辿って 1 本の輪郭 (点の index 列) にする。複数の輪があれば一番長いもの (唇の外側) */ +type Connection = { start: number; end: number }; + +function chain(connections: readonly Connection[]): number[] { + const next = new Map(connections.map((c) => [c.start, c.end])); + const seen = new Set(); + let best: number[] = []; + for (const c of connections) { + if (seen.has(c.start)) continue; + const ring = [c.start]; + seen.add(c.start); + for (;;) { + const n = next.get(ring[ring.length - 1]!); + if (n === undefined || seen.has(n)) break; + ring.push(n); + seen.add(n); + } + if (ring.length > best.length) best = ring; + } + return best; +} + +const OVAL = chain(FaceLandmarker.FACE_LANDMARKS_FACE_OVAL); +const LEFT_EYE = chain(FaceLandmarker.FACE_LANDMARKS_LEFT_EYE); +const RIGHT_EYE = chain(FaceLandmarker.FACE_LANDMARKS_RIGHT_EYE); +const LIPS = chain(FaceLandmarker.FACE_LANDMARKS_LIPS); +// 虹彩は 468 (左の中心) + 469..472、473 (右の中心) + 474..477 +const IRIS = { left: [468, 469, 470, 471, 472], right: [473, 474, 475, 476, 477] } as const; + +type Landmark = { x: number; y: number }; + +let landmarker: FaceLandmarker | null = null; +let loading: Promise | null = null; + +async function fetchWithProgress( + url: string, + onProgress: (loaded: number) => void, +): Promise { + const res = await fetch(url); + if (!res.ok || !res.body) throw new Error(`model fetch failed: ${res.status}`); + const chunks: Uint8Array[] = []; + let loaded = 0; + const reader = res.body.getReader(); + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + chunks.push(value); + loaded += value.byteLength; + onProgress(loaded); + } + const out = new Uint8Array(loaded); + let offset = 0; + for (const c of chunks) { + out.set(c, offset); + offset += c.byteLength; + } + return out; +} + +function load(confidence: number, onProgress: (loaded: number) => void): Promise { + if (landmarker) return Promise.resolve(landmarker); + if (loading) return loading; + loading = (async () => { + const model = await fetchWithProgress(`${FACE_MODEL_BASE}/face_landmarker.task`, onProgress); + const vision = await FilesetResolver.forVisionTasks(`${FACE_MODEL_BASE}/wasm`); + const lm = await FaceLandmarker.createFromOptions(vision, { + baseOptions: { modelAssetBuffer: model, delegate: "CPU" }, + runningMode: "IMAGE", + numFaces: 6, + minFaceDetectionConfidence: confidence, + minFacePresenceConfidence: confidence, + outputFaceBlendshapes: true, + }); + landmarker = lm; + loading = null; + return lm; + })(); + return loading; +} + +type Crop = { x: number; y: number; w: number; h: number; scale: number }; + +function* crops(w: number, h: number): Generator { + yield { x: 0, y: 0, w, h, scale: 1 }; + for (const s of PYRAMID) { + const cw = w / s; + const ch = h / s; + const n = 2 * s - 1; + for (let j = 0; j < n; j++) + for (let i = 0; i < n; i++) + yield { x: (i * cw) / 2, y: (j * ch) / 2, w: cw, h: ch, scale: s }; + } +} + +function iou(a: number[], b: number[]): number { + const ix = Math.max(0, Math.min(a[2]!, b[2]!) - Math.max(a[0]!, b[0]!)); + const iy = Math.max(0, Math.min(a[3]!, b[3]!) - Math.max(a[1]!, b[1]!)); + const inter = ix * iy; + const area = (r: number[]) => (r[2]! - r[0]!) * (r[3]! - r[1]!); + return inter / (area(a) + area(b) - inter); +} + +function bboxOf(lms: Landmark[]): [number, number, number, number] { + const xs = OVAL.map((k) => lms[k]!.x); + const ys = OVAL.map((k) => lms[k]!.y); + return [Math.min(...xs), Math.min(...ys), Math.max(...xs), Math.max(...ys)]; +} + +function detectAll(lm: FaceLandmarker, bitmap: ImageBitmap): FaceResult[] { + const w = bitmap.width; + const h = bitmap.height; + const canvas = new OffscreenCanvas(1, 1); + const ctx = canvas.getContext("2d"); + if (!ctx) throw new Error("no 2d context"); + const found: { lms: Landmark[]; bbox: number[]; blink: FaceResult["blink"] }[] = []; + for (const c of crops(w, h)) { + let res; + if (c.scale === 1) { + res = lm.detect(bitmap); + } else { + canvas.width = Math.round(c.w); + canvas.height = Math.round(c.h); + ctx.drawImage(bitmap, c.x, c.y, c.w, c.h, 0, 0, canvas.width, canvas.height); + res = lm.detect(canvas); + } + res.faceLandmarks.forEach((raw, i) => { + // 切り抜きの正規化座標を画像全体の座標に戻す + const lms: Landmark[] = raw.map((p) => ({ + x: (c.x + p.x * c.w) / w, + y: (c.y + p.y * c.h) / h, + })); + const b = bboxOf(lms); + if (c.scale > 1) { + const m = EDGE_MARGIN / c.scale; + if ( + b[0] < c.x / w + m || + b[1] < c.y / h + m || + b[2] > (c.x + c.w) / w - m || + b[3] > (c.y + c.h) / h - m + ) + return; + } + if (found.some((f) => iou(f.bbox, b) > SAME_FACE_IOU)) return; + const shapes = res.faceBlendshapes?.[i]?.categories ?? []; + const shape = (name: string) => shapes.find((s) => s.categoryName === name)?.score ?? null; + found.push({ + lms, + bbox: b, + blink: { left: shape("eyeBlinkLeft"), right: shape("eyeBlinkRight") }, + }); + }); + } + return found.map(({ lms, bbox, blink }) => { + const ring = (idx: readonly number[]): NormalizedPoint[] => + idx.map((k) => ({ x: lms[k]!.x, y: lms[k]!.y })); + const iris = (idx: readonly number[]) => { + const [c, ...rim] = idx.map((k) => lms[k]!); + // 半径は px で測ってから幅・高さの比に戻す (楕円マスクの rx / ry と同じ意味) + const rPx = + rim.reduce((a, p) => a + Math.hypot((p.x - c!.x) * w, (p.y - c!.y) * h), 0) / rim.length; + return { cx: c!.x, cy: c!.y, rx: rPx / w, ry: rPx / h }; + }; + return { + bbox: bbox as [number, number, number, number], + oval: ring(OVAL), + leftEye: ring(LEFT_EYE), + rightEye: ring(RIGHT_EYE), + mouth: ring(LIPS), + leftIris: iris(IRIS.left), + rightIris: iris(IRIS.right), + blink, + }; + }); +} + +self.onmessage = async (e: MessageEvent) => { + const { id, bitmap, confidence = CONFIDENCE } = e.data; + const post = (m: FaceResponse) => self.postMessage(m); + try { + const lm = await load(confidence, (loaded) => + post({ id, type: "progress", loaded, total: FACE_MODEL_BYTES }), + ); + const t0 = performance.now(); + const faces = detectAll(lm, bitmap); + post({ id, type: "result", faces, ms: performance.now() - t0 }); + } catch (err) { + post({ id, type: "error", message: err instanceof Error ? err.message : String(err) }); + } finally { + bitmap.close(); + } +}; diff --git a/apps/app/web/features/editor/state.test.ts b/apps/app/web/features/editor/state.test.ts index 8d8be80..d1356ad 100644 --- a/apps/app/web/features/editor/state.test.ts +++ b/apps/app/web/features/editor/state.test.ts @@ -145,6 +145,59 @@ describe("editorReducer: 部分補正 (#109)", () => { expect(mask.kind === "polygon" && mask.strokes).toEqual([stroke]); }); + it("adds several adjustments at once as one history step with a shared groupId (自動選択)", () => { + const s = editorReducer(loaded, { + type: "local/add-auto", + label: "瞳強調 (自動)", + groupId: "face1", + items: [ + { presetId: "eyes", mask: { ...DEFAULT_ELLIPSE_MASK, cx: 0.4 } }, + { presetId: "eyes", mask: { ...DEFAULT_ELLIPSE_MASK, cx: 0.6 } }, + ], + }); + const list = s.history.present.localAdjustments; + expect(list).toHaveLength(2); + expect(list.map((l) => l.groupId)).toEqual(["face1", "face1"]); + expect(list[0]!.presetId).toBe("eyes"); + expect(list[0]!.adjust.sharpen).toBe(30); + expect(s.history.past).toHaveLength(1); + expect(s.history.pastLabels[0]).toBe("瞳強調 (自動)"); + expect(s.ui.local.selectedId).toBe(list[0]!.id); + expect(s.ui.tool).toBe("local"); + }); + + it("adds nothing when the batch would exceed the limit", () => { + let s = loaded; + for (let i = 0; i < MAX_LOCAL_ADJUSTMENTS - 1; i++) + s = editorReducer(s, { type: "local/add", kind: "ellipse" }); + const before = s.history.present; + s = editorReducer(s, { + type: "local/add-auto", + label: "x", + items: [ + { presetId: "eyes", mask: DEFAULT_ELLIPSE_MASK }, + { presetId: "eyes", mask: DEFAULT_ELLIPSE_MASK }, + ], + }); + expect(s.history.present).toBe(before); + }); + + it("tracks inference status and notice in the ui state", () => { + let s = editorReducer(loaded, { + type: "ui/inference", + inference: { status: "loading", progress: { loaded: 1, total: 4 } }, + }); + expect(s.ui.local.inference.status).toBe("loading"); + expect(s.ui.local.inference.progress).toEqual({ loaded: 1, total: 4 }); + s = editorReducer(s, { type: "ui/inference", inference: { status: "idle", progress: null } }); + s = editorReducer(s, { type: "ui/notice", notice: "自動選択できませんでした" }); + expect(s.ui.local.inference.status).toBe("idle"); + expect(s.ui.local.notice).toBe("自動選択できませんでした"); + // 部分補正を足したら文言は消える + s = editorReducer(s, { type: "local/add", kind: "brush" }); + expect(s.ui.local.notice).toBeNull(); + }); + it("gives each adjustment a distinct id", () => { let s = withOne; s = editorReducer(s, { type: "local/add", kind: "ellipse" }); diff --git a/apps/app/web/features/editor/state.ts b/apps/app/web/features/editor/state.ts index fca2108..e937fd1 100644 --- a/apps/app/web/features/editor/state.ts +++ b/apps/app/web/features/editor/state.ts @@ -27,6 +27,19 @@ export type Tool = "adjust" | "geometry" | "presets" | "local"; /** 円形マスクの初期配置 (今見えている範囲の中央に置くため) */ export type EllipsePlacement = { cx: number; cy: number; rx: number; ry: number }; +/** ブラウザ内の認識 (#176) の進み具合。loading はモデルの取得、running は検出中 */ +export type InferenceStatus = { + readonly status: "idle" | "loading" | "running"; + readonly progress: { loaded: number; total: number } | null; +}; + +/** 自動選択で一度に足す部分補正 */ +export type AutoLocalItem = { + readonly mask: Mask; + readonly presetId: LocalPresetId; + readonly name?: string | undefined; +}; + export type BrushSettings = { readonly mode: BrushStrokeV2["mode"]; /** 直径。画像の長辺に対する比 */ @@ -59,6 +72,9 @@ export type EditorState = { readonly showHandles: boolean; /** ブラシの設定。ストロークごとにレシピへ写す */ readonly brush: BrushSettings; + readonly inference: InferenceStatus; + /** 自動選択の結果の一言 (失敗、目を閉じている、など)。次の操作で消える */ + readonly notice: string | null; }; }; }; @@ -79,6 +95,13 @@ export type EditorAction = /** 円形の初期位置 (画像の正規化座標)。省くと画像の中央 */ at?: EllipsePlacement | undefined; } + | { + /** 自動選択 (#176 / #177): 複数の部分補正を 1 手で足す。入り切らなければ何もしない */ + type: "local/add-auto"; + items: readonly AutoLocalItem[]; + label: string; + groupId?: string | undefined; + } | { type: "local/remove"; id: string } | { type: "local/select"; id: string | null } | { type: "local/toggle-visible"; id: string } @@ -94,6 +117,8 @@ export type EditorAction = | { type: "ui/drawing"; on: boolean } | { type: "ui/show-handles"; on: boolean } | { type: "ui/brush"; brush: BrushSettings } + | { type: "ui/inference"; inference: InferenceStatus } + | { type: "ui/notice"; notice: string | null } | { type: "history/undo" } | { type: "history/redo" } | { type: "ui/tool"; tool: Tool } @@ -121,6 +146,8 @@ export const initialEditorState: EditorState = { drawing: false, showHandles: true, brush: { mode: "add", size: 0.08, hardness: 0.7 }, + inference: { status: "idle", progress: null }, + notice: null, }, }, }; @@ -209,6 +236,11 @@ function selectLocal(state: EditorState, selectedId: string | null): EditorState return { ...state, ui: { ...state.ui, local: { ...state.ui.local, selectedId } } }; } +function withNotice(state: EditorState, notice: string | null): EditorState { + if (state.ui.local.notice === notice) return state; + return { ...state, ui: { ...state.ui, local: { ...state.ui.local, notice } } }; +} + /** 選択中の id がレシピから消えていたら選択を外す (undo / リセット後) */ function reconcileSelection(state: EditorState): EditorState { const { selectedId } = state.ui.local; @@ -304,7 +336,39 @@ export function editorReducer(state: EditorState, action: EditorAction): EditorS return { ...selectLocal(state, local.id), history: commit(history, next, label), - ui: { ...state.ui, tool: "local", local: { ...state.ui.local, selectedId: local.id } }, + ui: { + ...state.ui, + tool: "local", + local: { ...state.ui.local, selectedId: local.id, notice: null }, + }, + }; + } + case "local/add-auto": { + const room = MAX_LOCAL_ADJUSTMENTS - history.present.localAdjustments.length; + if (action.items.length === 0 || action.items.length > room) return state; + const added = action.items.map((item) => { + const preset = findLocalPreset(item.presetId); + const base: LocalAdjustment = { + ...DEFAULT_LOCAL_ADJUSTMENT, + id: newLocalId(), + name: item.name ?? null, + groupId: action.groupId ?? null, + mask: item.mask, + }; + return preset ? applyLocalPreset(base, preset) : base; + }); + const next = { + ...history.present, + localAdjustments: [...history.present.localAdjustments, ...added], + }; + return { + ...state, + history: commit(history, next, action.label), + ui: { + ...state.ui, + tool: "local", + local: { ...state.ui.local, selectedId: added[0]!.id, notice: null }, + }, }; } case "local/remove": { @@ -373,6 +437,13 @@ export function editorReducer(state: EditorState, action: EditorAction): EditorS } case "ui/brush": return { ...state, ui: { ...state.ui, local: { ...state.ui.local, brush: action.brush } } }; + case "ui/inference": + return { + ...state, + ui: { ...state.ui, local: { ...state.ui.local, inference: action.inference } }, + }; + case "ui/notice": + return withNotice(state, action.notice); case "ui/show-handles": return { ...state, diff --git a/apps/app/web/features/editor/ui/EditorPage.tsx b/apps/app/web/features/editor/ui/EditorPage.tsx index abf91d2..5d1bd57 100644 --- a/apps/app/web/features/editor/ui/EditorPage.tsx +++ b/apps/app/web/features/editor/ui/EditorPage.tsx @@ -16,6 +16,8 @@ import { CropOverlay } from "./CropOverlay.tsx"; import { EllipseMaskOverlay } from "./EllipseMaskOverlay.tsx"; import { BrushOverlay } from "./BrushOverlay.tsx"; import { LocalPanel } from "./LocalPanel.tsx"; +import { AUTO_SELECT_FAILED, planFaceSelection } from "../inference/auto-select.ts"; +import type { FaceResult } from "../inference/face-masks.ts"; import { CompareSlider } from "./CompareSlider.tsx"; const ERROR_TEXT: Record = { @@ -159,6 +161,38 @@ export function EditorPage() { }; }; + // 自動選択 (#176): 顔の検出結果は画像 (draftId) ごとに 1 回だけ取り、瞳・美肌で使い回す。 + // 検出のライブラリ (WASM) は押したときに動的 import する (現像の初期表示に載せない) + const facesRef = useRef<{ draftId: string; faces: FaceResult[] } | null>(null); + const autoSelect = async (kind: "eyes" | "skin") => { + const source = state.source; + const draftId = state.draftId; + if (!source || !draftId || state.ui.local.inference.status !== "idle") return; + let faces = facesRef.current?.draftId === draftId ? facesRef.current.faces : null; + if (!faces) { + dispatch({ type: "ui/inference", inference: { status: "loading", progress: null } }); + try { + const { detectFaces } = await import("../inference/face.ts"); + faces = await detectFaces(source.bitmap, { + onProgress: (progress) => + dispatch({ type: "ui/inference", inference: { status: "loading", progress } }), + }); + facesRef.current = { draftId, faces }; + } catch (e) { + console.error("face detection failed", e); + dispatch({ type: "ui/inference", inference: { status: "idle", progress: null } }); + dispatch({ type: "ui/notice", notice: AUTO_SELECT_FAILED }); + return; + } + dispatch({ type: "ui/inference", inference: { status: "idle", progress: null } }); + } + const plan = planFaceSelection(kind, faces); + if (plan.items.length > 0) { + dispatch({ type: "local/add-auto", items: plan.items, label: plan.label }); + } + if (plan.notice) dispatch({ type: "ui/notice", notice: plan.notice }); + }; + const zoomBy = (factor: number) => rendererRef.current?.zoomBy(factor); const zoomFit = () => rendererRef.current?.resetView(); const zoomActual = () => rendererRef.current?.zoomToActual(); @@ -584,6 +618,9 @@ export function EditorPage() { showHandles={state.ui.local.showHandles} onShowHandles={(on) => dispatch({ type: "ui/show-handles", on })} brush={state.ui.local.brush} + inference={state.ui.local.inference} + notice={state.ui.local.notice} + onAuto={(kind) => void autoSelect(kind)} onBrush={(brush) => dispatch({ type: "ui/brush", brush })} onAdd={(kind, presetId) => dispatch({ type: "local/add", kind, presetId, at: ellipseAtView() }) diff --git a/apps/app/web/features/editor/ui/LocalPanel.tsx b/apps/app/web/features/editor/ui/LocalPanel.tsx index 748caf2..af8c1f1 100644 --- a/apps/app/web/features/editor/ui/LocalPanel.tsx +++ b/apps/app/web/features/editor/ui/LocalPanel.tsx @@ -7,7 +7,7 @@ import { type LocalPresetId, } from "@prismtone/shared/recipe"; import { LOCAL_ADJUST_LABELS } from "../labels.ts"; -import type { BrushSettings } from "../state.ts"; +import type { BrushSettings, InferenceStatus } from "../state.ts"; import { Slider } from "./Slider.tsx"; type Props = { @@ -16,7 +16,11 @@ type Props = { showMask: boolean; showHandles: boolean; brush: BrushSettings; + inference: InferenceStatus; + notice: string | null; onAdd: (kind: "ellipse" | "brush", presetId?: LocalPresetId) => void; + /** 瞳・美肌: 顔を検出してマスクを自動で置く (#176)。無ければ手動の追加に落ちる */ + onAuto?: ((presetId: "eyes" | "skin") => void) | undefined; onBrush: (brush: BrushSettings) => void; onSelect: (id: string | null) => void; onRemove: (id: string) => void; @@ -63,6 +67,7 @@ function localName(l: LocalAdjustment, index: number): string { export function LocalPanel(p: Props) { const selected = p.list.find((l) => l.id === p.selectedId) ?? null; const full = p.list.length >= MAX_LOCAL_ADJUSTMENTS; + const busy = p.inference.status !== "idle"; return (
@@ -202,7 +207,9 @@ export function LocalPanel(p: Props) {

{selected ? "選択中の範囲に適用" - : "新しいマスクを追加して適用 (瞳・美肌は円形、装備はブラシ)"} + : p.onAuto + ? "瞳・美肌は顔を認識して置きます (装備はブラシで塗る)" + : "新しいマスクを追加して適用 (瞳・美肌は円形、装備はブラシ)"}

{LOCAL_PRESETS.map((preset) => ( @@ -212,17 +219,29 @@ export function LocalPanel(p: Props) { className={btn + " aria-pressed:bg-accent aria-pressed:text-accent-ink"} aria-pressed={selected?.presetId === preset.id} title={preset.hint} - disabled={!selected && full} - onClick={() => - selected - ? p.onPreset(selected.id, preset.id) - : p.onAdd(preset.id === "gear" ? "brush" : "ellipse", preset.id) - } + disabled={(!selected && full) || busy} + onClick={() => { + if (selected) return p.onPreset(selected.id, preset.id); + if (p.onAuto && preset.id !== "gear") return p.onAuto(preset.id); + p.onAdd(preset.id === "gear" ? "brush" : "ellipse", preset.id); + }} > {preset.name} ))}
+ {busy && ( +

+ {p.inference.status === "loading" && p.inference.progress + ? `認識用のデータを読み込んでいます (${Math.round((p.inference.progress.loaded / p.inference.progress.total) * 100)}%)` + : "顔を認識しています…"} +

+ )} + {p.notice && !busy && ( +

+ {p.notice} +

+ )}
{selected && (
diff --git a/e2e/editor.spec.ts b/e2e/editor.spec.ts index c9a733f..37c8f8e 100644 --- a/e2e/editor.spec.ts +++ b/e2e/editor.spec.ts @@ -335,10 +335,12 @@ test.describe("editor", () => { await login(page, "/edit"); await openEditorWithImage(page); await page.getByRole("tab", { name: "部分補正" }).click(); - await page.getByRole("button", { name: "瞳強調" }).click(); + // 手動の流れ: 円形を足してから瞳強調のプリセットを当てる (何も選んでいないときの「瞳強調」は顔の自動選択、#176) + await page.getByTestId("local-add-ellipse").click(); await expect(page.getByTestId("local-list").getByRole("listitem")).toHaveCount(1); + await page.getByRole("button", { name: "瞳強調" }).click(); await expect(page.getByTestId("local-list")).toContainText("瞳強調 (円形)"); - await expect(page.getByTestId("history-last")).toContainText("部分補正を追加: 瞳強調"); + await expect(page.getByTestId("history-last")).toContainText("部分補正: 瞳強調"); await expect(page.getByTestId("ellipse-overlay")).toBeVisible(); await expect(page.getByTestId("local-sliders")).toBeVisible(); @@ -719,4 +721,68 @@ test.describe("editor", () => { .setInputFiles({ name: "x.png", mimeType: "image/png", buffer: Buffer.from("not a png") }); await expect(page.getByRole("alert")).toContainText("PNG または JPEG"); }); + + test("瞳強調 and 美肌 place masks from face detection, and the polygon can be erased with the brush (#176)", async ({ + page, + }) => { + await page.addInitScript(() => { + (window as Window & { __PRISMTONE_E2E__?: boolean }).__PRISMTONE_E2E__ = true; + }); + // 画像を外に送らないこと: このテストの間、自分のオリジン以外へのリクエストが無い + const foreign: string[] = []; + page.on("request", (req) => { + if (!/^https?:\/\/(127\.0\.0\.1|localhost)(:|\/)/.test(req.url())) foreign.push(req.url()); + }); + await page.goto("/edit"); + await page + .getByTestId("file-input") + .setInputFiles(new URL("./fixtures/face.jpg", import.meta.url).pathname); + await expect(page.getByRole("button", { name: "端末に保存" })).toBeEnabled(); + await page.getByRole("tab", { name: "部分補正" }).click(); + + // 瞳: 初回はモデルを読み込む (数 MB) ので待つ。両目に円形が 2 つ、1 手の履歴 + await page.getByRole("button", { name: "瞳強調" }).click(); + await expect(page.getByTestId("local-list").getByRole("listitem")).toHaveCount(2, { + timeout: 60_000, + }); + await expect(page.getByTestId("local-list")).toContainText("瞳強調 (円形)"); + await expect(page.getByTestId("history-last")).toContainText("瞳強調 (自動)"); + await expect(page.getByTestId("ellipse-overlay")).toBeVisible(); + // 円形は顔の上半分にある (画像は 960×540、顔は中央やや上) + const handle = await page.getByTestId("ellipse-handle-move").boundingBox(); + const host = await page.getByTestId("canvas-host").boundingBox(); + expect(handle && host && handle.y < host.y + host.height * 0.6).toBe(true); + + // 2 つで 1 手なので undo で両方消える。美肌: 顔の輪郭の多角形が 1 つ増え、選択されてブラシで直せる + await page.getByTestId("history-undo").click(); + await expect(page.getByTestId("local-list")).toHaveCount(0); + await page.getByRole("button", { name: "美肌" }).click(); + await expect(page.getByTestId("local-list")).toContainText("美肌 (多角形)"); + await expect(page.getByTestId("history-last")).toContainText("美肌 (自動)"); + await expect(page.getByTestId("brush-settings")).toBeVisible(); + await page.getByTestId("brush-settings").getByRole("button", { name: "消す" }).click(); + const box = (await page.getByTestId("canvas-host").boundingBox())!; + await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2); + await page.mouse.down(); + await page.mouse.move(box.x + box.width / 2 + 30, box.y + box.height / 2, { steps: 4 }); + await page.mouse.up(); + await expect(page.getByTestId("history-last")).toContainText("消しゴム"); + + expect(foreign).toEqual([]); + }); + + test("when no face is found the panel says so and manual masks still work (#176)", async ({ + page, + }) => { + await openEditorWithImage(page); + await page.getByRole("tab", { name: "部分補正" }).click(); + await page.getByRole("button", { name: "美肌" }).click(); + await expect(page.getByTestId("local-notice")).toContainText("自動選択できませんでした", { + timeout: 60_000, + }); + await expect(page.getByTestId("local-list")).toHaveCount(0); + await page.getByTestId("local-add-brush").click(); + await expect(page.getByTestId("local-list").getByRole("listitem")).toHaveCount(1); + await expect(page.getByTestId("local-notice")).toHaveCount(0); + }); }); diff --git a/e2e/fixtures/face.jpg b/e2e/fixtures/face.jpg new file mode 100644 index 0000000000000000000000000000000000000000..e5a1aefdd00c48466a811e169afb16190e476347 GIT binary patch literal 136819 zcmb4qRZtvEu=T>?4#8a(_r={^7WWX`AuR4Lfh>y!65QSSa0?LJ-62>41a}B_^FRC# z_wn{?&vaMUOjUQCbNX%NZ5<#7KtV!6MnXbCMn*!3#0H6c_5P=B)4DkOA2^kTHf{Fk@`{#w=0T2;@Ktv=U z^1m98kN~&{h(G`mJ~9CvuMEmNZA*G+I3YN>paGRZR;O>4$ZF>T#OHBIEEkc2#>lT* z*hs=;-7hE~nOZcb=eheYAUOiye`f>y3y1_jM)~Ix!UrHC{!535gbV~C{W}Ku=fnrn z@gfn(&}$>V16xAFlN&Aw3;GyjXZiSdE{Q-oC~|LW04yNFzk-1H04cx@RM|j1NLWIS z8k^V^6-5%oU$!^#8-2uz96QeM+E0)6)+!*I$Y^t!x++QAI;&NG(BIp~c@1K2(Jd{h z=nsj#Z-4-uA&z>*4ZZB}`6JCBb{^+eSOih;bc>%Yxew>^RI@0yT2a|O&_RRA-_(*9WRLOlpL3E@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(8Th(#nZqqs&t z66b@~p?M5(0_cD+8PBaOm1viF^pd+~NhA?~c>v^^65{wvghwvyFj~I9{{WKgI4Ye- zdX|M_42-fkEOzd}JQJF1QSRF%l2+*+2p)LWIBnSE{qj0hGTXFI<>Zg2THKhUwYBqO bLA#E$i(ZKmNaP9wGUS@q8E%A>DIfpYG%D42 literal 0 HcmV?d00001 From 2e62d84f8d02b6f3106409e08201dec5c0537b29 Mon Sep 17 00:00:00 2001 From: t1nyb0x Date: Mon, 21 Sep 2026 11:20:19 +0900 Subject: [PATCH 28/49] =?UTF-8?q?feat:=20=E8=A3=85=E5=82=99=E5=BC=B7?= =?UTF-8?q?=E8=AA=BF=E3=83=BB=E3=82=AD=E3=83=A3=E3=83=A9=E3=82=AF=E3=82=BF?= =?UTF-8?q?=E3=83=BC=E3=83=BB=E8=83=8C=E6=99=AF=E3=82=92=E3=82=BF=E3=83=83?= =?UTF-8?q?=E3=83=97=E3=81=A7=E5=88=87=E3=82=8A=E6=8A=9C=E3=81=8F=20(SlimS?= =?UTF-8?q?AM=20=E3=82=92=E3=83=96=E3=83=A9=E3=82=A6=E3=82=B6=E3=81=AE=20W?= =?UTF-8?q?orker=20=E3=81=A7)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit lumorphia/prismtone#162 の spike の結果を本体に入れる (計画の PR3)。部分補正の「装備強調」を何も選ばずに押すと、 SlimSAM (Xenova/slimsam-77-uniform、q8) を transformers.js + onnxruntime-web (WASM) の module worker で 動かして画像を埋め込み、タップした装備を bitmap マスク (長辺 256、RLE) で置く。「キャラクター」「背景」は プリセット無しで人物全体 (背景はその反転) を置く。置いたあとはブラシで直せる。 - 3 段の粒度 (0 = 全体、1 = 装備、2 = 部品) を全部候補として持ち、パネルの「切り抜きの範囲」で差し替える (下地だけ替え、反転と塗り足したストロークは保つ)。装備の既定は 1 (IoU で選ぶと全体に寄る) - 埋め込みは画像 1 枚につき 1 回で使い回す。タップ待ちは TapOverlay (Esc と「やめる」で抜ける) - モデルと ORT の WASM は fetch-models.ts が sha256 固定で public/models/ に揃える。HF Hub には行かない (allowRemoteModels = false)。E2E で自分のオリジン以外へのリクエストが無いことを見る - COOP / COEP を付けないので ORT はシングルスレッド。押してからタップ待ちまで約 10 秒、タップ 0.4〜0.8 秒 (spike 文書に実測を追記)。速くする案 (COEP credentialless / WebGPU) は別 Issue - CSP は wasm-unsafe-eval のまま (csp.spec.ts に切り抜きの流れを足した) Closes lumorphia/prismtone#177 Co-Authored-By: Claude Opus 5 --- apps/app/scripts/fetch-models.ts | 29 ++++ .../editor/inference/auto-select.test.ts | 41 ++++- .../features/editor/inference/auto-select.ts | 33 +++- .../editor/inference/segment-masks.test.ts | 41 +++++ .../editor/inference/segment-masks.ts | 54 ++++++ .../web/features/editor/inference/segment.ts | 95 ++++++++++ .../editor/inference/segment.worker.ts | 163 ++++++++++++++++++ apps/app/web/features/editor/state.test.ts | 21 +++ apps/app/web/features/editor/state.ts | 63 +++++-- .../app/web/features/editor/ui/EditorPage.tsx | 97 ++++++++++- .../app/web/features/editor/ui/LocalPanel.tsx | 75 +++++++- .../app/web/features/editor/ui/TapOverlay.tsx | 57 ++++++ e2e/editor.spec.ts | 65 ++++++- 13 files changed, 810 insertions(+), 24 deletions(-) create mode 100644 apps/app/web/features/editor/inference/segment-masks.test.ts create mode 100644 apps/app/web/features/editor/inference/segment-masks.ts create mode 100644 apps/app/web/features/editor/inference/segment.ts create mode 100644 apps/app/web/features/editor/inference/segment.worker.ts create mode 100644 apps/app/web/features/editor/ui/TapOverlay.tsx diff --git a/apps/app/scripts/fetch-models.ts b/apps/app/scripts/fetch-models.ts index 461de26..501eba6 100644 --- a/apps/app/scripts/fetch-models.ts +++ b/apps/app/scripts/fetch-models.ts @@ -36,6 +36,35 @@ const ASSETS: (Download | Copy)[] = [ to: `face-landmarker-v1/wasm/${f}`, from: path.join(root, "node_modules", "@mediapipe", "tasks-vision", "wasm", f), })), + // SlimSAM (装備・人物の切り抜き、#177)。Xenova/slimsam-77-uniform の q8。Apache-2.0 + ...( + [ + ["config.json", "6339884f168658d3ca6473b486973913fb33e84e625e06ae2dd7b4a808187419"], + [ + "preprocessor_config.json", + "225545a743c654e3c495ec6f545a0eaba57c8ba3fbbd8483b3cb1c0fc58db517", + ], + [ + "onnx/vision_encoder_quantized.onnx", + "cce23c7b2e5d4f330932738fb67ba518e04b0d99ccdd1cccd22a7da4e01f2971", + ], + [ + "onnx/prompt_encoder_mask_decoder_quantized.onnx", + "cb90b279f549d2cab7fd6e20c38522438c65d84bdcca3d2a764cff7d857fdce2", + ], + ] as const + ).map(([f, sha256]): Download => ({ + kind: "download", + to: `slimsam-77-q8-v1/${f}`, + url: `https://huggingface.co/Xenova/slimsam-77-uniform/resolve/main/${f}`, + sha256, + })), + // onnxruntime-web の WASM (transformers.js が同梱する jsep 版)。MIT + ...["ort-wasm-simd-threaded.jsep.mjs", "ort-wasm-simd-threaded.jsep.wasm"].map((f): Copy => ({ + kind: "copy", + to: `ort-v1/${f}`, + from: path.join(root, "node_modules", "@huggingface", "transformers", "dist", f), + })), ]; async function sha256(file: string): Promise { diff --git a/apps/app/web/features/editor/inference/auto-select.test.ts b/apps/app/web/features/editor/inference/auto-select.test.ts index 7d28b4d..cd31cb9 100644 --- a/apps/app/web/features/editor/inference/auto-select.test.ts +++ b/apps/app/web/features/editor/inference/auto-select.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vitest"; -import { AUTO_SELECT_FAILED, planFaceSelection } from "./auto-select.ts"; +import { encodeRle, type BitmapMaskV3 } from "@prismtone/shared/recipe"; +import { AUTO_SELECT_FAILED, planFaceSelection, planSegmentSelection } from "./auto-select.ts"; import type { FaceResult } from "./face-masks.ts"; const square = (cx: number, cy: number, r: number) => [ @@ -61,3 +62,41 @@ describe("planFaceSelection", () => { expect(plan.items[0]!.mask).toMatchObject({ cx: 0.4 }); }); }); + +describe("planSegmentSelection", () => { + const bitmap = (tag: number): BitmapMaskV3 => ({ + kind: "bitmap", + width: 2, + height: 1, + rle: encodeRle(Uint8Array.from([tag, 1])), + strokes: [], + feather: 0.1, + invert: false, + }); + const masks = [bitmap(0), bitmap(1), bitmap(0)]; + + it("装備強調: uses the middle granularity (index 1) with the gear preset", () => { + const plan = planSegmentSelection("gear", masks); + expect(plan.items).toHaveLength(1); + expect(plan.items[0]!.presetId).toBe("gear"); + expect(plan.items[0]!.mask).toBe(masks[1]); + expect(plan.label).toBe("装備強調 (自動)"); + }); + + it("キャラクター: uses the whole-character mask (index 0) without a preset", () => { + const plan = planSegmentSelection("person", masks); + expect(plan.items[0]!.presetId).toBeNull(); + expect(plan.items[0]!.name).toBe("キャラクター"); + expect(plan.items[0]!.mask).toBe(masks[0]); + }); + + it("背景: inverts the whole-character mask", () => { + const plan = planSegmentSelection("background", masks); + expect(plan.items[0]!.name).toBe("背景"); + expect(plan.items[0]!.mask).toMatchObject({ kind: "bitmap", invert: true }); + }); + + it("says so when the segmenter returned nothing", () => { + expect(planSegmentSelection("gear", []).notice).toBe(AUTO_SELECT_FAILED); + }); +}); diff --git a/apps/app/web/features/editor/inference/auto-select.ts b/apps/app/web/features/editor/inference/auto-select.ts index 9f9a4e1..b5db966 100644 --- a/apps/app/web/features/editor/inference/auto-select.ts +++ b/apps/app/web/features/editor/inference/auto-select.ts @@ -1,6 +1,7 @@ -import type { LocalPresetId } from "@prismtone/shared/recipe"; +import type { BitmapMaskV3, LocalPresetId } from "@prismtone/shared/recipe"; import type { AutoLocalItem } from "../state.ts"; import { facePolygon, irisEllipses, pickMainFace, type FaceResult } from "./face-masks.ts"; +import { GEAR_LEVEL, PERSON_LEVEL } from "./segment-masks.ts"; /** * 自動選択 (#176) の計画: 検出結果から「何を足すか」と「利用者に伝える一言」を決める純関数。 @@ -40,3 +41,33 @@ export function planFaceSelection( notice: ellipses.length === 1 ? ONE_EYE_CLOSED : null, }; } + +/** タップで切る対象 (#177)。gear は装備強調、person / background はプリセット無しの範囲 */ +export type SegmentSelectionKind = "gear" | "person" | "background"; + +export const SEGMENT_KIND_LABELS: Record = { + gear: "装備強調 (自動)", + person: "キャラクター", + background: "背景", +}; + +/** SAM の 3 段のマスクから何を足すか。gear は index 1 (装備 1 点)、person / background は index 0 (全体) */ +export function planSegmentSelection( + kind: SegmentSelectionKind, + masks: readonly BitmapMaskV3[], +): SelectionPlan { + const level = kind === "gear" ? GEAR_LEVEL : PERSON_LEVEL; + const mask = masks[level]; + if (!mask) return { items: [], label: "", notice: AUTO_SELECT_FAILED }; + if (kind === "gear") { + return { items: [{ presetId: "gear", mask }], label: SEGMENT_KIND_LABELS.gear, notice: null }; + } + const name = SEGMENT_KIND_LABELS[kind]; + return { + items: [ + { presetId: null, name, mask: kind === "background" ? { ...mask, invert: true } : mask }, + ], + label: `${name}を選択`, + notice: null, + }; +} diff --git a/apps/app/web/features/editor/inference/segment-masks.test.ts b/apps/app/web/features/editor/inference/segment-masks.test.ts new file mode 100644 index 0000000..cf9d6eb --- /dev/null +++ b/apps/app/web/features/editor/inference/segment-masks.test.ts @@ -0,0 +1,41 @@ +import { describe, expect, it } from "vitest"; +import { BITMAP_MAX_EDGE, decodeRle } from "@prismtone/shared/recipe"; +import { SAM_LEVELS, toBitmapMask } from "./segment-masks.ts"; + +describe("toBitmapMask", () => { + it("shrinks a full-size mask to the bitmap edge limit keeping the aspect ratio", () => { + // 1024×512 の右半分が 1 + const w = 1024; + const h = 512; + const src = new Uint8Array(w * h); + for (let y = 0; y < h; y++) src.fill(1, y * w + w / 2, y * w + w); + const m = toBitmapMask(src, w, h); + expect(m.kind).toBe("bitmap"); + expect(m.width).toBe(BITMAP_MAX_EDGE); + expect(m.height).toBe(BITMAP_MAX_EDGE / 2); + const bits = decodeRle(m.rle, m.width * m.height); + expect(bits[10]).toBe(0); + expect(bits[m.width - 10]).toBe(1); + expect(m.strokes).toEqual([]); + expect(m.invert).toBe(false); + }); + + it("keeps a small mask as-is and can invert it (背景 = 人物の反転)", () => { + const src = Uint8Array.from([1, 0, 0, 1]); + const m = toBitmapMask(src, 2, 2, { invert: true }); + expect([m.width, m.height]).toEqual([2, 2]); + expect(decodeRle(m.rle, 4)).toEqual(Uint8Array.from([1, 0, 0, 1])); + expect(m.invert).toBe(true); + }); + + it("a cell is set when at least half of its source pixels are set", () => { + // 4×1 → 2×1: 左のセルは 1 が 1/2 (境界で 1)、右のセルは 0/2 + const m = toBitmapMask(Uint8Array.from([1, 0, 0, 0]), 4, 1, { maxEdge: 2 }); + expect(decodeRle(m.rle, 2)).toEqual(Uint8Array.from([1, 0])); + }); + + it("names the three SAM granularities in a fixed order (全体 → 装備 → 部品)", () => { + expect(SAM_LEVELS.map((l) => l.index)).toEqual([0, 1, 2]); + expect(SAM_LEVELS[1]!.label).toBe("装備"); + }); +}); diff --git a/apps/app/web/features/editor/inference/segment-masks.ts b/apps/app/web/features/editor/inference/segment-masks.ts new file mode 100644 index 0000000..8ee3727 --- /dev/null +++ b/apps/app/web/features/editor/inference/segment-masks.ts @@ -0,0 +1,54 @@ +import { BITMAP_MAX_EDGE, encodeRle, type BitmapMaskV3 } from "@prismtone/shared/recipe"; + +/** + * SAM の切り抜き (segment.worker.ts) をレシピの bitmap マスクにする純関数 (#177、ADR-0025)。 + * 原寸の 0/1 を長辺 256 に縮め (セルの半分以上が 1 なら 1)、RLE で持つ。 + */ + +/** SAM が返す 3 段の粒度。spike で順番が安定していた: 0 = キャラクター全体、1 = その装備 1 点、2 = その一部 */ +export const SAM_LEVELS = [ + { index: 0, label: "全体", hint: "キャラクター全体 (髪・顔・装備)" }, + { index: 1, label: "装備", hint: "タップした装備 1 点" }, + { index: 2, label: "部品", hint: "装備の一部 (袖、襟、胸当てなど)" }, +] as const; +export type SamLevel = (typeof SAM_LEVELS)[number]["index"]; +/** 装備強調の既定。IoU で選ぶと全体に寄るので使わない */ +export const GEAR_LEVEL: SamLevel = 1; +export const PERSON_LEVEL: SamLevel = 0; + +/** bitmap マスクのぼかし。境界の階段を消す程度 */ +const BITMAP_FEATHER = 0.1; + +export function toBitmapMask( + mask: Uint8Array, + width: number, + height: number, + options: { invert?: boolean; maxEdge?: number; feather?: number } = {}, +): BitmapMaskV3 { + const maxEdge = options.maxEdge ?? BITMAP_MAX_EDGE; + const scale = Math.min(1, maxEdge / Math.max(width, height)); + const w = Math.max(1, Math.round(width * scale)); + const h = Math.max(1, Math.round(height * scale)); + const bits = new Uint8Array(w * h); + for (let y = 0; y < h; y++) { + const y0 = Math.floor((y * height) / h); + const y1 = Math.max(y0 + 1, Math.floor(((y + 1) * height) / h)); + for (let x = 0; x < w; x++) { + const x0 = Math.floor((x * width) / w); + const x1 = Math.max(x0 + 1, Math.floor(((x + 1) * width) / w)); + let on = 0; + for (let yy = y0; yy < y1; yy++) + for (let xx = x0; xx < x1; xx++) on += mask[yy * width + xx]!; + bits[y * w + x] = on * 2 >= (y1 - y0) * (x1 - x0) ? 1 : 0; + } + } + return { + kind: "bitmap", + width: w, + height: h, + rle: encodeRle(bits), + strokes: [], + feather: options.feather ?? BITMAP_FEATHER, + invert: options.invert ?? false, + }; +} diff --git a/apps/app/web/features/editor/inference/segment.ts b/apps/app/web/features/editor/inference/segment.ts new file mode 100644 index 0000000..37a07cb --- /dev/null +++ b/apps/app/web/features/editor/inference/segment.ts @@ -0,0 +1,95 @@ +import type { BitmapMaskV3 } from "@prismtone/shared/recipe"; +import { InferenceError, type Progress } from "./face.ts"; +import type { SegmentRequest, SegmentResponse } from "./segment.worker.ts"; + +/** + * 装備・人物の切り抜きの呼び出し側 (#177)。Worker を 1 つ起こして使い回す。 + * 画像ごとに prepareSegmenter (埋め込み、重い) を 1 回、タップごとに segmentAt (軽い)。 + */ + +let worker: Worker | null = null; +let seq = 0; +/** 埋め込み済みの画像の印。同じ画像なら埋め込みを使い回す */ +let embeddedFor: object | null = null; + +function getWorker(): Worker { + if (!worker) { + worker = new Worker(new URL("./segment.worker.ts", import.meta.url), { type: "module" }); + } + return worker; +} + +export function resetSegmentWorker(): void { + worker?.terminate(); + worker = null; + embeddedFor = null; +} + +type Body = SegmentRequest extends infer R + ? R extends { id: number } + ? Omit + : never + : never; + +function call( + req: Body, + done: T, + options: { onProgress?: ((p: Progress) => void) | undefined; transfer?: Transferable[] } = {}, +): Promise> { + const w = getWorker(); + const id = ++seq; + return new Promise((resolve, reject) => { + const onMessage = (e: MessageEvent) => { + const m = e.data; + if (m.id !== id) return; + if (m.type === "progress") { + options.onProgress?.({ loaded: m.loaded, total: m.total }); + return; + } + cleanup(); + if (m.type === done) resolve(m as Extract); + else if (m.type === "error") reject(new InferenceError(m.message)); + else reject(new InferenceError(`unexpected ${m.type}`)); + }; + const onError = (e: ErrorEvent) => { + cleanup(); + resetSegmentWorker(); + reject(new InferenceError(e.message || "worker error")); + }; + const cleanup = () => { + w.removeEventListener("message", onMessage); + w.removeEventListener("error", onError); + }; + w.addEventListener("message", onMessage); + w.addEventListener("error", onError); + w.postMessage({ id, ...req }, options.transfer ?? []); + }); +} + +/** 画像の埋め込み。同じ bitmap なら 2 回目以降は何もしない。戻り値は埋め込みに掛かった ms (使い回しは 0) */ +export async function prepareSegmenter( + bitmap: ImageBitmap, + options: { onProgress?: (p: Progress) => void } = {}, +): Promise { + if (embeddedFor === bitmap) return 0; + const copy = await createImageBitmap(bitmap); + const res = await call({ type: "embed", bitmap: copy }, "embedded", { + onProgress: options.onProgress, + transfer: [copy], + }); + embeddedFor = bitmap; + return res.ms; +} + +export type Segmentation = { + /** 3 段の粒度 (0 = 全体、1 = 装備、2 = 部品)。segment-masks.ts の SAM_LEVELS */ + masks: BitmapMaskV3[]; + scores: number[]; + ms: number; +}; + +/** タップ位置 (幾何を掛ける前の画像の正規化座標) の切り抜き。prepareSegmenter のあとで */ +export async function segmentAt(x: number, y: number): Promise { + const res = await call({ type: "segment", x, y }, "segmented"); + return { masks: res.masks, scores: res.scores, ms: res.ms }; +} diff --git a/apps/app/web/features/editor/inference/segment.worker.ts b/apps/app/web/features/editor/inference/segment.worker.ts new file mode 100644 index 0000000..9e2f836 --- /dev/null +++ b/apps/app/web/features/editor/inference/segment.worker.ts @@ -0,0 +1,163 @@ +/// +/** + * 装備・人物の切り抜きの Web Worker (#177、ADR-0025)。SlimSAM (Xenova/slimsam-77-uniform、q8) を + * transformers.js + onnxruntime-web (WASM) で動かす。 + * + * - 画像 1 枚につき埋め込み (vision encoder) を 1 回 (重い、spike で 2 秒)。使い回す + * - タップごとにデコード (0.2 秒)。3 段の粒度のマスクを全部 bitmap にして返す (spike で 0 = 全体、1 = 装備、2 = 部品) + * - モデルと WASM は /models/ (自前ホスト)。HF Hub には行かない + * - COOP / COEP が無いので SharedArrayBuffer は無く、ORT はシングルスレッド + * + * spike (docs/spikes/2026-09-21-auto-select.md) の segmentAnything を移したもの。 + */ +import type * as TransformersNs from "@huggingface/transformers"; +import type { BitmapMaskV3 } from "@prismtone/shared/recipe"; +import { toBitmapMask } from "./segment-masks.ts"; + +export const SAM_MODEL_BASE = "/models/slimsam-77-q8-v1"; +export const ORT_WASM_BASE = "/models/ort-v1/"; +export const SAM_MODEL_ID = "slimsam-77-q8-v1"; + +export type SegmentRequest = + | { id: number; type: "embed"; bitmap: ImageBitmap } + | { id: number; type: "segment"; x: number; y: number }; +export type SegmentResponse = + | { id: number; type: "progress"; loaded: number; total: number } + | { id: number; type: "embedded"; ms: number } + | { id: number; type: "segmented"; masks: BitmapMaskV3[]; scores: number[]; ms: number } + | { id: number; type: "error"; message: string }; + +type Transformers = typeof TransformersNs; +type SamInputs = { original_sizes: number[][]; reshaped_input_sizes: number[][] } & Record< + string, + unknown +>; +type TensorLike = { dims: number[]; data: ArrayLike }; +type SamProcessor = ((image: unknown) => Promise) & { + post_process_masks: ( + masks: unknown, + originalSizes: number[][], + reshapedSizes: number[][], + ) => Promise; +}; +type SamModel = { + get_image_embeddings: (inputs: SamInputs) => Promise>; + (inputs: Record): Promise<{ pred_masks: unknown; iou_scores: TensorLike }>; +}; + +let lib: Transformers | null = null; +let model: SamModel | null = null; +let processor: SamProcessor | null = null; +let embedded: { inputs: SamInputs; embeddings: Record } | null = null; + +async function load(onProgress: (loaded: number, total: number) => void) { + if (lib && model && processor) return { lib, model, processor }; + const t = await import("@huggingface/transformers"); + // 自前ホストだけを見る。models/ の下は HF の repo と同じ配置 (config.json, onnx/*.onnx) + t.env.allowLocalModels = true; + t.env.allowRemoteModels = false; + t.env.localModelPath = "/models/"; + if (t.env.backends.onnx.wasm) t.env.backends.onnx.wasm.wasmPaths = ORT_WASM_BASE; + const totals = new Map(); + const progress_callback = (p: { + status: string; + file?: string; + loaded?: number; + total?: number; + }) => { + if (p.status !== "progress" || !p.file || !p.total) return; + totals.set(p.file, { loaded: p.loaded ?? 0, total: p.total }); + let loaded = 0; + let total = 0; + for (const v of totals.values()) { + loaded += v.loaded; + total += v.total; + } + onProgress(loaded, total); + }; + const m = (await t.SamModel.from_pretrained(SAM_MODEL_ID, { + dtype: "q8", + device: "wasm", + progress_callback, + })) as unknown as SamModel; + const pr = (await t.AutoProcessor.from_pretrained(SAM_MODEL_ID, { + progress_callback, + })) as unknown as SamProcessor; + lib = t; + model = m; + processor = pr; + return { lib: t, model: m, processor: pr }; +} + +function rawImageOf(t: Transformers, bitmap: ImageBitmap) { + const canvas = new OffscreenCanvas(bitmap.width, bitmap.height); + const ctx = canvas.getContext("2d"); + if (!ctx) throw new Error("no 2d context"); + ctx.drawImage(bitmap, 0, 0); + const data = ctx.getImageData(0, 0, bitmap.width, bitmap.height); + return new t.RawImage(data.data, bitmap.width, bitmap.height, 4); +} + +async function embed( + bitmap: ImageBitmap, + onProgress: (l: number, t: number) => void, +): Promise { + const { lib: t, model: m, processor: pr } = await load(onProgress); + const raw = rawImageOf(t, bitmap); + const t0 = performance.now(); + const inputs = await pr(raw); + const embeddings = await m.get_image_embeddings(inputs); + embedded = { inputs, embeddings }; + return performance.now() - t0; +} + +async function segment(x: number, y: number) { + if (!embedded || !lib || !model || !processor) throw new Error("not embedded"); + const t0 = performance.now(); + const { inputs, embeddings } = embedded; + const reshaped = inputs.reshaped_input_sizes[0]!; // [h, w] + // タップ位置は正規化座標 → 埋め込みに使った縮小後の px + const input_points = new lib.Tensor( + "float32", + [x * reshaped[1]!, y * reshaped[0]!], + [1, 1, 1, 2], + ); + const input_labels = new lib.Tensor("int64", [1n], [1, 1, 1]); + const out = await model({ ...embeddings, input_points, input_labels }); + const masks = await processor.post_process_masks( + out.pred_masks, + inputs.original_sizes, + inputs.reshaped_input_sizes, + ); + const m = masks[0]!; // [1, 3, H, W] + const [, levels, h, w] = m.dims as [number, number, number, number]; + const result: BitmapMaskV3[] = []; + for (let k = 0; k < levels; k++) { + const bits = new Uint8Array(w * h); + for (let i = 0; i < w * h; i++) bits[i] = m.data[k * w * h + i] ? 1 : 0; + result.push(toBitmapMask(bits, w, h)); + } + return { masks: result, scores: Array.from(out.iou_scores.data), ms: performance.now() - t0 }; +} + +self.onmessage = async (e: MessageEvent) => { + const req = e.data; + const post = (m: SegmentResponse) => self.postMessage(m); + try { + if (req.type === "embed") { + try { + const ms = await embed(req.bitmap, (loaded, total) => + post({ id: req.id, type: "progress", loaded, total }), + ); + post({ id: req.id, type: "embedded", ms }); + } finally { + req.bitmap.close(); + } + } else { + const r = await segment(req.x, req.y); + post({ id: req.id, type: "segmented", ...r }); + } + } catch (err) { + post({ id: req.id, type: "error", message: err instanceof Error ? err.message : String(err) }); + } +}; diff --git a/apps/app/web/features/editor/state.test.ts b/apps/app/web/features/editor/state.test.ts index d1356ad..cc7b7a5 100644 --- a/apps/app/web/features/editor/state.test.ts +++ b/apps/app/web/features/editor/state.test.ts @@ -198,6 +198,27 @@ describe("editorReducer: 部分補正 (#109)", () => { expect(s.ui.local.notice).toBeNull(); }); + it("keeps the segmentation candidates while their adjustment exists, and lets the mask be swapped with a label", () => { + const masks = [ + { ...DEFAULT_ELLIPSE_MASK, cx: 0.1 }, + { ...DEFAULT_ELLIPSE_MASK, cx: 0.2 }, + ]; + let s = editorReducer(withOne, { type: "ui/tap", tap: "gear" }); + expect(s.ui.local.tap).toBe("gear"); + s = editorReducer(s, { type: "ui/segment", segment: { localId: id, masks } }); + s = editorReducer(s, { type: "ui/tap", tap: null }); + s = editorReducer(s, { + type: "local/mask-commit", + id, + mask: masks[1]!, + label: "切り抜き: 全体", + }); + expect(s.history.pastLabels.at(-1)).toBe("切り抜き: 全体"); + expect(s.ui.local.segment?.localId).toBe(id); + s = editorReducer(s, { type: "local/remove", id }); + expect(s.ui.local.segment).toBeNull(); + }); + it("gives each adjustment a distinct id", () => { let s = withOne; s = editorReducer(s, { type: "local/add", kind: "ellipse" }); diff --git a/apps/app/web/features/editor/state.ts b/apps/app/web/features/editor/state.ts index e937fd1..a20c906 100644 --- a/apps/app/web/features/editor/state.ts +++ b/apps/app/web/features/editor/state.ts @@ -18,6 +18,7 @@ import { type LocalPresetId, type Mask, } from "@prismtone/shared/recipe"; +import type { SegmentSelectionKind } from "./inference/auto-select.ts"; import { commit, createHistory, preview, redo, undo, type History } from "./history.ts"; import { adjustLabel, geometryLabel, localAdjustLabel } from "./labels.ts"; import type { LoadedImage } from "./load-image.ts"; @@ -36,7 +37,8 @@ export type InferenceStatus = { /** 自動選択で一度に足す部分補正 */ export type AutoLocalItem = { readonly mask: Mask; - readonly presetId: LocalPresetId; + /** null ならプリセット無し (キャラクター / 背景の範囲だけ) */ + readonly presetId: LocalPresetId | null; readonly name?: string | undefined; }; @@ -75,6 +77,10 @@ export type EditorState = { readonly inference: InferenceStatus; /** 自動選択の結果の一言 (失敗、目を閉じている、など)。次の操作で消える */ readonly notice: string | null; + /** タップで切る (#177) 待ち。null なら通常 */ + readonly tap: SegmentSelectionKind | null; + /** 直近のタップの 3 段の候補。粒度の切り替えに使う。その部分補正が消えたら捨てる */ + readonly segment: { readonly localId: string; readonly masks: readonly Mask[] } | null; }; }; }; @@ -101,6 +107,8 @@ export type EditorAction = items: readonly AutoLocalItem[]; label: string; groupId?: string | undefined; + /** タップの 3 段の候補 (#177)。先頭の部分補正に紐づけて粒度を切り替えられるようにする */ + candidates?: readonly Mask[] | undefined; } | { type: "local/remove"; id: string } | { type: "local/select"; id: string | null } @@ -110,7 +118,7 @@ export type EditorAction = | { type: "local/amount-preview"; id: string; value: number } | { type: "local/amount-commit"; id: string; value: number } | { type: "local/mask-preview"; id: string; mask: Mask } - | { type: "local/mask-commit"; id: string; mask: Mask } + | { type: "local/mask-commit"; id: string; mask: Mask; label?: string | undefined } | { type: "local/preset"; id: string; presetId: LocalPresetId } | { type: "local/stroke-commit"; id: string; stroke: BrushStrokeV2 } | { type: "ui/show-mask"; on: boolean } @@ -119,6 +127,8 @@ export type EditorAction = | { type: "ui/brush"; brush: BrushSettings } | { type: "ui/inference"; inference: InferenceStatus } | { type: "ui/notice"; notice: string | null } + | { type: "ui/tap"; tap: SegmentSelectionKind | null } + | { type: "ui/segment"; segment: EditorState["ui"]["local"]["segment"] } | { type: "history/undo" } | { type: "history/redo" } | { type: "ui/tool"; tool: Tool } @@ -148,6 +158,8 @@ export const initialEditorState: EditorState = { brush: { mode: "add", size: 0.08, hardness: 0.7 }, inference: { status: "idle", progress: null }, notice: null, + tap: null, + segment: null, }, }, }; @@ -241,13 +253,16 @@ function withNotice(state: EditorState, notice: string | null): EditorState { return { ...state, ui: { ...state.ui, local: { ...state.ui.local, notice } } }; } -/** 選択中の id がレシピから消えていたら選択を外す (undo / リセット後) */ +/** 選択中の id と切り抜きの候補がレシピから消えていたら外す (undo / 削除 / リセット後) */ function reconcileSelection(state: EditorState): EditorState { - const { selectedId } = state.ui.local; - if (selectedId && !state.history.present.localAdjustments.some((l) => l.id === selectedId)) { - return selectLocal(state, null); + const { selectedId, segment } = state.ui.local; + const has = (id: string) => state.history.present.localAdjustments.some((l) => l.id === id); + let next = state; + if (selectedId && !has(selectedId)) next = selectLocal(next, null); + if (segment && !has(segment.localId)) { + next = { ...next, ui: { ...next.ui, local: { ...next.ui.local, segment: null } } }; } - return state; + return next; } export function editorReducer(state: EditorState, action: EditorAction): EditorState { @@ -347,7 +362,7 @@ export function editorReducer(state: EditorState, action: EditorAction): EditorS const room = MAX_LOCAL_ADJUSTMENTS - history.present.localAdjustments.length; if (action.items.length === 0 || action.items.length > room) return state; const added = action.items.map((item) => { - const preset = findLocalPreset(item.presetId); + const preset = item.presetId ? findLocalPreset(item.presetId) : undefined; const base: LocalAdjustment = { ...DEFAULT_LOCAL_ADJUSTMENT, id: newLocalId(), @@ -367,7 +382,15 @@ export function editorReducer(state: EditorState, action: EditorAction): EditorS ui: { ...state.ui, tool: "local", - local: { ...state.ui.local, selectedId: added[0]!.id, notice: null }, + local: { + ...state.ui.local, + selectedId: added[0]!.id, + notice: null, + tap: null, + segment: action.candidates + ? { localId: added[0]!.id, masks: action.candidates } + : state.ui.local.segment, + }, }, }; } @@ -378,9 +401,11 @@ export function editorReducer(state: EditorState, action: EditorAction): EditorS const rest = list.filter((l) => l.id !== action.id); const next = { ...history.present, localAdjustments: rest }; const neighbour = rest[Math.min(index, rest.length - 1)]?.id ?? null; - return selectLocal( - { ...state, history: commit(history, next, "部分補正を削除") }, - state.ui.local.selectedId === action.id ? neighbour : state.ui.local.selectedId, + return reconcileSelection( + selectLocal( + { ...state, history: commit(history, next, "部分補正を削除") }, + state.ui.local.selectedId === action.id ? neighbour : state.ui.local.selectedId, + ), ); } case "local/select": @@ -411,7 +436,12 @@ export function editorReducer(state: EditorState, action: EditorAction): EditorS case "local/mask-preview": return localPreview(state, action.id, withLocalMask(action.mask)); case "local/mask-commit": - return localCommit(state, action.id, withLocalMask(action.mask), "マスクを動かす"); + return localCommit( + state, + action.id, + withLocalMask(action.mask), + action.label ?? "マスクを動かす", + ); case "local/preset": { const preset = findLocalPreset(action.presetId); if (!preset) return state; @@ -444,6 +474,13 @@ export function editorReducer(state: EditorState, action: EditorAction): EditorS }; case "ui/notice": return withNotice(state, action.notice); + case "ui/tap": + return { ...state, ui: { ...state.ui, local: { ...state.ui.local, tap: action.tap } } }; + case "ui/segment": + return { + ...state, + ui: { ...state.ui, local: { ...state.ui.local, segment: action.segment } }, + }; case "ui/show-handles": return { ...state, diff --git a/apps/app/web/features/editor/ui/EditorPage.tsx b/apps/app/web/features/editor/ui/EditorPage.tsx index 5d1bd57..fc8dfdc 100644 --- a/apps/app/web/features/editor/ui/EditorPage.tsx +++ b/apps/app/web/features/editor/ui/EditorPage.tsx @@ -16,8 +16,16 @@ import { CropOverlay } from "./CropOverlay.tsx"; import { EllipseMaskOverlay } from "./EllipseMaskOverlay.tsx"; import { BrushOverlay } from "./BrushOverlay.tsx"; import { LocalPanel } from "./LocalPanel.tsx"; -import { AUTO_SELECT_FAILED, planFaceSelection } from "../inference/auto-select.ts"; +import { + AUTO_SELECT_FAILED, + planFaceSelection, + planSegmentSelection, + type SegmentSelectionKind, +} from "../inference/auto-select.ts"; import type { FaceResult } from "../inference/face-masks.ts"; +import { SAM_LEVELS } from "../inference/segment-masks.ts"; +import { TapOverlay } from "./TapOverlay.tsx"; +import type { Point } from "../mask-math.ts"; import { CompareSlider } from "./CompareSlider.tsx"; const ERROR_TEXT: Record = { @@ -164,10 +172,29 @@ export function EditorPage() { // 自動選択 (#176): 顔の検出結果は画像 (draftId) ごとに 1 回だけ取り、瞳・美肌で使い回す。 // 検出のライブラリ (WASM) は押したときに動的 import する (現像の初期表示に載せない) const facesRef = useRef<{ draftId: string; faces: FaceResult[] } | null>(null); - const autoSelect = async (kind: "eyes" | "skin") => { + const autoSelect = async (kind: "eyes" | "skin" | SegmentSelectionKind) => { const source = state.source; const draftId = state.draftId; if (!source || !draftId || state.ui.local.inference.status !== "idle") return; + if (kind === "gear" || kind === "person" || kind === "background") { + // タップで切る (#177): 画像の埋め込み (初回は数秒) を済ませてからタップを待つ + dispatch({ type: "ui/inference", inference: { status: "loading", progress: null } }); + try { + const { prepareSegmenter } = await import("../inference/segment.ts"); + await prepareSegmenter(source.bitmap, { + onProgress: (progress) => + dispatch({ type: "ui/inference", inference: { status: "loading", progress } }), + }); + } catch (e) { + console.error("segmenter failed", e); + dispatch({ type: "ui/inference", inference: { status: "idle", progress: null } }); + dispatch({ type: "ui/notice", notice: AUTO_SELECT_FAILED }); + return; + } + dispatch({ type: "ui/inference", inference: { status: "idle", progress: null } }); + dispatch({ type: "ui/tap", tap: kind }); + return; + } let faces = facesRef.current?.draftId === draftId ? facesRef.current.faces : null; if (!faces) { dispatch({ type: "ui/inference", inference: { status: "loading", progress: null } }); @@ -193,6 +220,52 @@ export function EditorPage() { if (plan.notice) dispatch({ type: "ui/notice", notice: plan.notice }); }; + const onTap = async (uv: Point) => { + const kind = state.ui.local.tap; + if (!kind) return; + dispatch({ type: "ui/inference", inference: { status: "running", progress: null } }); + try { + const { segmentAt } = await import("../inference/segment.ts"); + const { masks } = await segmentAt(uv.x, uv.y); + const plan = planSegmentSelection(kind, masks); + dispatch({ type: "ui/inference", inference: { status: "idle", progress: null } }); + if (plan.items.length > 0) { + dispatch({ + type: "local/add-auto", + items: plan.items, + label: plan.label, + candidates: masks, + }); + } else { + dispatch({ type: "ui/tap", tap: null }); + } + if (plan.notice) dispatch({ type: "ui/notice", notice: plan.notice }); + } catch (e) { + console.error("segmentation failed", e); + dispatch({ type: "ui/inference", inference: { status: "idle", progress: null } }); + dispatch({ type: "ui/tap", tap: null }); + dispatch({ type: "ui/notice", notice: AUTO_SELECT_FAILED }); + } + }; + const onSegmentLevel = (localId: string, index: number) => { + const candidate = state.ui.local.segment?.masks[index]; + const target = recipe.localAdjustments.find((l) => l.id === localId); + if (!candidate || !target || target.mask.kind !== "bitmap") return; + // 反転 (背景) と塗り足したストロークは保ったまま、下地だけ差し替える + const mask = { + ...candidate, + ...(candidate.kind === "bitmap" + ? { invert: target.mask.invert, strokes: target.mask.strokes } + : {}), + }; + dispatch({ + type: "local/mask-commit", + id: localId, + mask, + label: `切り抜き: ${SAM_LEVELS[index]?.label ?? index}`, + }); + }; + const zoomBy = (factor: number) => rendererRef.current?.zoomBy(factor); const zoomFit = () => rendererRef.current?.resetView(); const zoomActual = () => rendererRef.current?.zoomToActual(); @@ -561,6 +634,22 @@ export function EditorPage() { onCancel={() => rendererRef.current?.discardPreviewStroke(selectedLocal.id)} /> )} + {hasImage && + state.source && + state.ui.tool === "local" && + state.ui.local.tap && + !state.ui.cropping && ( + void onTap(uv)} + onCancel={() => dispatch({ type: "ui/tap", tap: null })} + /> + )} {hasImage && state.ui.cropping && recipe.geometry.crop && ( void autoSelect(kind)} + onCancelTap={() => dispatch({ type: "ui/tap", tap: null })} + onSegmentLevel={onSegmentLevel} onBrush={(brush) => dispatch({ type: "ui/brush", brush })} onAdd={(kind, presetId) => dispatch({ type: "local/add", kind, presetId, at: ellipseAtView() }) diff --git a/apps/app/web/features/editor/ui/LocalPanel.tsx b/apps/app/web/features/editor/ui/LocalPanel.tsx index af8c1f1..3220c42 100644 --- a/apps/app/web/features/editor/ui/LocalPanel.tsx +++ b/apps/app/web/features/editor/ui/LocalPanel.tsx @@ -7,7 +7,9 @@ import { type LocalPresetId, } from "@prismtone/shared/recipe"; import { LOCAL_ADJUST_LABELS } from "../labels.ts"; -import type { BrushSettings, InferenceStatus } from "../state.ts"; +import type { BrushSettings, EditorState, InferenceStatus } from "../state.ts"; +import type { SegmentSelectionKind } from "../inference/auto-select.ts"; +import { SAM_LEVELS } from "../inference/segment-masks.ts"; import { Slider } from "./Slider.tsx"; type Props = { @@ -18,9 +20,15 @@ type Props = { brush: BrushSettings; inference: InferenceStatus; notice: string | null; + /** タップ待ち (#177) と、直近のタップの 3 段の候補 */ + tap: SegmentSelectionKind | null; + segment: EditorState["ui"]["local"]["segment"]; onAdd: (kind: "ellipse" | "brush", presetId?: LocalPresetId) => void; - /** 瞳・美肌: 顔を検出してマスクを自動で置く (#176)。無ければ手動の追加に落ちる */ - onAuto?: ((presetId: "eyes" | "skin") => void) | undefined; + /** 瞳・美肌は顔を検出して置く (#176)、装備・キャラクター・背景はタップで切る (#177)。無ければ手動の追加に落ちる */ + onAuto?: ((kind: "eyes" | "skin" | SegmentSelectionKind) => void) | undefined; + onCancelTap?: (() => void) | undefined; + /** 切り抜きの粒度を切り替える (segment の候補の index) */ + onSegmentLevel?: ((localId: string, index: number) => void) | undefined; onBrush: (brush: BrushSettings) => void; onSelect: (id: string | null) => void; onRemove: (id: string) => void; @@ -56,6 +64,11 @@ const MASK_KIND_LABELS: Record = { bitmap: "切り抜き", }; +/** 粒度の切り替えで下地だけ差し替えるので、反転やストロークが違っても同じ候補なら同じとみなす */ +function isSameBitmap(a: LocalAdjustment["mask"], b: LocalAdjustment["mask"] | undefined): boolean { + return a.kind === "bitmap" && b?.kind === "bitmap" && a.rle === b.rle; +} + function localName(l: LocalAdjustment, index: number): string { if (l.name) return l.name; const preset = LOCAL_PRESETS.find((p) => p.id === l.presetId); @@ -208,7 +221,7 @@ export function LocalPanel(p: Props) { {selected ? "選択中の範囲に適用" : p.onAuto - ? "瞳・美肌は顔を認識して置きます (装備はブラシで塗る)" + ? "瞳・美肌は顔を認識して置き、装備は画像をタップして切り抜きます" : "新しいマスクを追加して適用 (瞳・美肌は円形、装備はブラシ)"}

@@ -222,7 +235,7 @@ export function LocalPanel(p: Props) { disabled={(!selected && full) || busy} onClick={() => { if (selected) return p.onPreset(selected.id, preset.id); - if (p.onAuto && preset.id !== "gear") return p.onAuto(preset.id); + if (p.onAuto) return p.onAuto(preset.id); p.onAdd(preset.id === "gear" ? "brush" : "ellipse", preset.id); }} > @@ -230,11 +243,61 @@ export function LocalPanel(p: Props) { ))}
+ {p.onAuto && !selected && ( +
+ タップで範囲だけ選ぶ: + + +
+ )} + {p.tap && ( +

+ 画像の中の{p.tap === "gear" ? "装備" : "キャラクター"}をタップしてください + +

+ )} + {selected && p.segment?.localId === selected.id && p.onSegmentLevel && ( +
+ 切り抜きの範囲: + {SAM_LEVELS.map((level) => ( + + ))} +
+ )} {busy && (

{p.inference.status === "loading" && p.inference.progress ? `認識用のデータを読み込んでいます (${Math.round((p.inference.progress.loaded / p.inference.progress.total) * 100)}%)` - : "顔を認識しています…"} + : p.inference.status === "loading" + ? "認識の準備をしています…" + : "画像を読み取っています…"}

)} {p.notice && !busy && ( diff --git a/apps/app/web/features/editor/ui/TapOverlay.tsx b/apps/app/web/features/editor/ui/TapOverlay.tsx new file mode 100644 index 0000000..bb4124f --- /dev/null +++ b/apps/app/web/features/editor/ui/TapOverlay.tsx @@ -0,0 +1,57 @@ +import { useEffect } from "react"; +import type { GeometryV1 } from "@prismtone/shared/recipe"; +import { canvasToImageUv, type Point } from "../mask-math.ts"; +import type { Size } from "../render/geometry.ts"; + +type View = { x: number; y: number; width: number; height: number; scale: number }; + +type Props = { + view: View; + source: Size; + geometry: GeometryV1; + /** 何を切るかの一言 (「切りたい装備をタップ」など) */ + hint: string; + /** タップ位置 (幾何を掛ける前の画像の正規化座標) */ + onTap: (uv: Point) => void; + /** Esc か「やめる」 */ + onCancel: () => void; +}; + +/** + * タップで切る (#177) の DOM オーバーレイ。キャンバス全体でクリックを 1 回受けて画像座標にする。 + * 画像の外をタップしたら無視する + */ +export function TapOverlay({ view, source, geometry, hint, onTap, onCancel }: Props) { + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if (e.key === "Escape") onCancel(); + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, [onCancel]); + return ( +
{ + if (e.button !== 0) return; + e.preventDefault(); + const host = e.currentTarget.getBoundingClientRect(); + const canvas = { + x: (e.clientX - host.left - view.x) / view.scale, + y: (e.clientY - host.top - view.y) / view.scale, + }; + const uv = canvasToImageUv(canvas, source, geometry); + if (uv.x < 0 || uv.x > 1 || uv.y < 0 || uv.y > 1) return; + onTap(uv); + }} + > +

+ {hint} (Esc でやめる) +

+
+ ); +} diff --git a/e2e/editor.spec.ts b/e2e/editor.spec.ts index 37c8f8e..cad3b71 100644 --- a/e2e/editor.spec.ts +++ b/e2e/editor.spec.ts @@ -262,7 +262,8 @@ test.describe("editor", () => { }) => { await openEditorWithImage(page); await page.getByRole("tab", { name: "部分補正" }).click(); - // 装備強調はブラシで始まる + // 手動の流れ: ブラシを足してから装備強調のプリセット (何も選んでいないときの「装備強調」はタップで切る、#177) + await page.getByTestId("local-add-brush").click(); await page.getByRole("button", { name: "装備強調" }).click(); await expect(page.getByTestId("local-list")).toContainText("装備強調 (ブラシ)"); await expect(page.getByTestId("brush-settings")).toBeVisible(); @@ -785,4 +786,66 @@ test.describe("editor", () => { await expect(page.getByTestId("local-list").getByRole("listitem")).toHaveCount(1); await expect(page.getByTestId("local-notice")).toHaveCount(0); }); + + test("装備強調 cuts out the tapped gear with SAM, switches granularity, and キャラクター / 背景 select the person (#177)", async ({ + page, + }) => { + test.setTimeout(180_000); + const foreign: string[] = []; + page.on("request", (req) => { + if (!/^https?:\/\/(127\.0\.0\.1|localhost)(:|\/)/.test(req.url())) foreign.push(req.url()); + }); + await page.goto("/edit"); + await page + .getByTestId("file-input") + .setInputFiles(new URL("./fixtures/face.jpg", import.meta.url).pathname); + await expect(page.getByRole("button", { name: "端末に保存" })).toBeEnabled(); + await page.getByRole("tab", { name: "部分補正" }).click(); + + // 装備強調: モデルの読み込みと埋め込み (シングルスレッドの WASM で 10 秒前後) のあとタップ待ちになる + await page.getByRole("button", { name: "装備強調" }).click(); + await expect(page.getByTestId("tap-overlay")).toBeVisible({ timeout: 120_000 }); + const host = (await page.getByTestId("canvas-host").boundingBox())!; + // 胸のあたり (赤いコート) をタップ + await page.mouse.click(host.x + host.width * 0.5, host.y + host.height * 0.85); + await expect(page.getByTestId("local-list")).toContainText("装備強調 (切り抜き)", { + timeout: 60_000, + }); + await expect(page.getByTestId("history-last")).toContainText("装備強調 (自動)"); + await expect(page.getByTestId("tap-overlay")).toHaveCount(0); + // 3 段の粒度。既定は「装備」、全体に切り替えると 1 手 + const levels = page.getByTestId("segment-levels"); + await expect(levels.getByRole("button", { name: "装備" })).toHaveAttribute( + "aria-pressed", + "true", + ); + await levels.getByRole("button", { name: "全体" }).click(); + await expect(page.getByTestId("history-last")).toContainText("切り抜き: 全体"); + await expect(levels.getByRole("button", { name: "全体" })).toHaveAttribute( + "aria-pressed", + "true", + ); + // 切り抜きの上にブラシで塗れる + await expect(page.getByTestId("brush-settings")).toBeVisible(); + + // キャラクター / 背景: プリセット無しの範囲。同じ画像なので埋め込みは使い回し (すぐタップ待ちになる) + await page.getByTestId("history-undo").click(); + await page.getByTestId("history-undo").click(); + await expect(page.getByTestId("local-list")).toHaveCount(0); + await page.getByTestId("local-auto-background").click(); + await expect(page.getByTestId("tap-overlay")).toBeVisible({ timeout: 10_000 }); + await page.mouse.click(host.x + host.width * 0.5, host.y + host.height * 0.5); + await expect(page.getByTestId("local-list")).toContainText("背景", { timeout: 60_000 }); + await expect(page.getByTestId("history-last")).toContainText("背景を選択"); + + // やめる: タップ待ちを Esc で抜ける + await page.getByRole("button", { name: "背景 を削除" }).click(); + await expect(page.getByTestId("local-list")).toHaveCount(0); + await page.getByTestId("local-auto-person").click(); + await expect(page.getByTestId("tap-overlay")).toBeVisible({ timeout: 10_000 }); + await page.keyboard.press("Escape"); + await expect(page.getByTestId("tap-overlay")).toHaveCount(0); + + expect(foreign).toEqual([]); + }); }); From 7a0fc0684700649bf04f40610863dab8f1bf15a7 Mon Sep 17 00:00:00 2001 From: t1nyb0x Date: Mon, 21 Sep 2026 11:42:52 +0900 Subject: [PATCH 29/49] =?UTF-8?q?feat:=20=E4=BA=BA=E7=89=A9=E8=A3=9C?= =?UTF-8?q?=E6=AD=A3=E3=83=84=E3=83=BC=E3=83=AB=20(=E6=A4=9C=E5=87=BA=20?= =?UTF-8?q?=E2=86=92=20=E4=BA=BA=E7=89=A9=E3=82=92=E9=81=B8=E3=81=B6=20?= =?UTF-8?q?=E2=86=92=20=E3=83=97=E3=83=AA=E3=82=BB=E3=83=83=E3=83=88=20?= =?UTF-8?q?=E2=86=92=20=E5=8A=B9=E6=9E=9C=E9=87=8F=E3=80=81=E9=83=A8?= =?UTF-8?q?=E5=88=86=E8=A3=9C=E6=AD=A3=205=20=E4=BB=B6=E3=82=92=E6=9D=9F?= =?UTF-8?q?=E3=81=AD=E3=82=8B)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit lumorphia/prismtone#176 の顔検出と lumorphia/prismtone#177 の切り抜きを束ねて、「人物補正」タブから人物を選びプリセットと効果量を指定する だけで、背景・人物・顔・瞳 ×2 の部分補正を 1 手で置く (計画の PR4)。 - プリセット 5 種 (ナチュラル / 明るく / ドラマチック / やわらか / 瞳くっきり) は 4 役ごとの部分補正の値と 効果量 (packages/shared の portrait-presets.ts)。既存の 9 項目だけで組む - 5 件は groupId で束ね、役はマスクの形から決める (反転ビットマップ = 背景、ビットマップ = 人物、 多角形 = 顔、楕円 = 瞳)。レシピには結果の値だけが入る - プリセットの切り替えは 1 手、効果量はドラッグの規則。グループがレシピにあるかは activePortraitGroup で見る (undo で消え redo で戻る)。個別の値・マスクは部分補正タブで直せる - 複数の顔は番号付きの枠 (FaceBoxesOverlay) で選ぶ。顔が無ければ文言と部分補正への導線。上限 12 件に 5 件が入り切らなければ置かずに伝える - 上限 12 件の性能は perf spike に追記 (パス数に比例、12 件は 8 件の 1.43 倍)。2 人 (10 件) が実用の上限 - E2E: face.jpg で検出 → ナチュラル → ドラマチック → 効果量 → 部分補正に 5 件 → undo / redo → 下書きを開き直しても残る → 書き出し。顔の無い画像で文言と導線 Closes lumorphia/prismtone#175 Co-Authored-By: Claude Opus 5 --- .../editor/inference/portrait.test.ts | 57 ++++++ .../web/features/editor/inference/portrait.ts | 62 ++++++ apps/app/web/features/editor/state.test.ts | 86 ++++++++- apps/app/web/features/editor/state.ts | 169 +++++++++++++++-- .../app/web/features/editor/ui/EditorPage.tsx | 177 +++++++++++++++--- .../features/editor/ui/FaceBoxesOverlay.tsx | 60 ++++++ .../web/features/editor/ui/PortraitPanel.tsx | 139 ++++++++++++++ e2e/editor.spec.ts | 89 +++++++++ e2e/perf-local-adjust.spec.ts | 2 +- packages/shared/src/recipe/index.ts | 1 + .../src/recipe/portrait-presets.test.ts | 128 +++++++++++++ .../shared/src/recipe/portrait-presets.ts | 165 ++++++++++++++++ 12 files changed, 1089 insertions(+), 46 deletions(-) create mode 100644 apps/app/web/features/editor/inference/portrait.test.ts create mode 100644 apps/app/web/features/editor/inference/portrait.ts create mode 100644 apps/app/web/features/editor/ui/FaceBoxesOverlay.tsx create mode 100644 apps/app/web/features/editor/ui/PortraitPanel.tsx create mode 100644 packages/shared/src/recipe/portrait-presets.test.ts create mode 100644 packages/shared/src/recipe/portrait-presets.ts diff --git a/apps/app/web/features/editor/inference/portrait.test.ts b/apps/app/web/features/editor/inference/portrait.test.ts new file mode 100644 index 0000000..fc34ef1 --- /dev/null +++ b/apps/app/web/features/editor/inference/portrait.test.ts @@ -0,0 +1,57 @@ +import { describe, expect, it } from "vitest"; +import { encodeRle, findPortraitPreset, type BitmapMaskV3 } from "@prismtone/shared/recipe"; +import type { FaceResult } from "./face-masks.ts"; +import { buildPortraitItems, faceCenter } from "./portrait.ts"; + +const square = (cx: number, cy: number, r: number) => [ + { x: cx - r, y: cy - r }, + { x: cx + r, y: cy - r }, + { x: cx + r, y: cy + r }, + { x: cx - r, y: cy + r }, +]; +const face: FaceResult = { + bbox: [0.3, 0.2, 0.7, 0.8], + oval: square(0.5, 0.5, 0.25), + leftEye: square(0.4, 0.4, 0.03), + rightEye: square(0.6, 0.4, 0.03), + mouth: square(0.5, 0.65, 0.05), + leftIris: { cx: 0.4, cy: 0.4, rx: 0.01, ry: 0.02 }, + rightIris: { cx: 0.6, cy: 0.4, rx: 0.01, ry: 0.02 }, + blink: { left: 0.05, right: 0.1 }, +}; +const person: BitmapMaskV3 = { + kind: "bitmap", + width: 2, + height: 1, + rle: encodeRle(Uint8Array.from([1, 0])), + strokes: [], + feather: 0.1, + invert: false, +}; + +describe("buildPortraitItems", () => { + it("builds 背景 → 人物 → 顔 → 瞳 ×2 with the preset's values scaled by the effect", () => { + const natural = findPortraitPreset("natural")!; + const items = buildPortraitItems(face, person, natural, 50); + expect(items.map((i) => i.name)).toEqual(["背景", "人物", "顔", "瞳 (左)", "瞳 (右)"]); + expect(items[0]!.mask).toMatchObject({ kind: "bitmap", invert: true }); + expect(items[1]!.mask).toBe(person); + expect(items[2]!.mask.kind).toBe("polygon"); + expect(items[2]!.presetId).toBe("skin"); + expect(items[3]!.presetId).toBe("eyes"); + expect(items[0]!.amount).toBe(Math.round(natural.roles.background.amount / 2)); + expect(items[2]!.adjust?.smooth).toBe(natural.roles.face.adjust.smooth); + }); + + it("leaves out closed eyes", () => { + const closed = { ...face, blink: { left: 0.9, right: 0.1 } }; + const items = buildPortraitItems(closed, person, findPortraitPreset("eyes")!, 100); + expect(items.map((i) => i.name)).toEqual(["背景", "人物", "顔", "瞳 (右)"]); + }); +}); + +describe("faceCenter", () => { + it("is the centre of the face box (SAM のタップ位置)", () => { + expect(faceCenter(face)).toEqual({ x: 0.5, y: 0.5 }); + }); +}); diff --git a/apps/app/web/features/editor/inference/portrait.ts b/apps/app/web/features/editor/inference/portrait.ts new file mode 100644 index 0000000..dc322d1 --- /dev/null +++ b/apps/app/web/features/editor/inference/portrait.ts @@ -0,0 +1,62 @@ +import { + DEFAULT_LOCAL_ADJUST, + type BitmapMaskV3, + type PortraitPreset, + type PortraitRole, +} from "@prismtone/shared/recipe"; +import type { AutoLocalItem } from "../state.ts"; +import { facePolygon, irisEllipses, type FaceResult } from "./face-masks.ts"; +import type { NormalizedPoint } from "./face-masks.ts"; + +/** + * 人物補正 (#175) の部分補正の組み立て (純関数)。顔検出と人物の切り抜きから、 + * 背景 → 人物 → 顔 → 瞳 の順に部分補正を作る (後の方が上に掛かる)。 + */ + +export const PORTRAIT_FULL = + "部分補正の上限 (12 件) に届くので置けません。不要な部分補正を削除してください"; + +export const PORTRAIT_ROLE_NAMES: Record = { + background: "背景", + person: "人物", + face: "顔", + eyes: "瞳", +}; + +/** SAM に渡すタップ位置: 顔の外接矩形の中心 (人物全体のマスクは index 0) */ +export function faceCenter(face: FaceResult): NormalizedPoint { + return { x: (face.bbox[0] + face.bbox[2]) / 2, y: (face.bbox[1] + face.bbox[3]) / 2 }; +} + +export function buildPortraitItems( + face: FaceResult, + person: BitmapMaskV3, + preset: PortraitPreset, + effect: number, +): AutoLocalItem[] { + const role = (r: PortraitRole) => ({ + adjust: { ...DEFAULT_LOCAL_ADJUST, ...preset.roles[r].adjust }, + amount: Math.round((preset.roles[r].amount * effect) / 100), + }); + const eyes = irisEllipses(face); + const openEyes = [ + ...(face.blink.left === null || face.blink.left < 0.5 ? ["左"] : []), + ...(face.blink.right === null || face.blink.right < 0.5 ? ["右"] : []), + ]; + return [ + { + name: PORTRAIT_ROLE_NAMES.background, + presetId: null, + mask: { ...person, invert: true }, + ...role("background"), + }, + { name: PORTRAIT_ROLE_NAMES.person, presetId: null, mask: person, ...role("person") }, + { name: PORTRAIT_ROLE_NAMES.face, presetId: "skin", mask: facePolygon(face), ...role("face") }, + ...eyes.map((mask, i) => ({ + name: `${PORTRAIT_ROLE_NAMES.eyes} (${openEyes[i]})`, + presetId: "eyes" as const, + mask, + ...role("eyes"), + })), + ]; +} diff --git a/apps/app/web/features/editor/state.test.ts b/apps/app/web/features/editor/state.test.ts index cc7b7a5..c181550 100644 --- a/apps/app/web/features/editor/state.test.ts +++ b/apps/app/web/features/editor/state.test.ts @@ -3,8 +3,14 @@ import { DEFAULT_ELLIPSE_MASK, DEFAULT_RECIPE, MAX_LOCAL_ADJUSTMENTS, + encodeRle, } from "@prismtone/shared/recipe"; -import { editorReducer, initialEditorState, type EditorState } from "./state.ts"; +import { + activePortraitGroup, + editorReducer, + initialEditorState, + type EditorState, +} from "./state.ts"; const loaded: EditorState = editorReducer(initialEditorState, { type: "image/loaded", @@ -355,3 +361,81 @@ describe("editorReducer: 部分補正 (#109)", () => { expect(initialEditorState.ui.local.brush.mode).toBe("add"); }); }); + +describe("editorReducer: 人物補正 (#175)", () => { + // 役はマスクの形で決まる (portraitRole): 反転したビットマップ = 背景、ビットマップ = 人物、多角形 = 顔 + const bitmap = (invert: boolean) => ({ + kind: "bitmap" as const, + width: 2, + height: 1, + rle: encodeRle(Uint8Array.from([1, 0])), + strokes: [], + feather: 0.1, + invert, + }); + const polygon = { + kind: "polygon" as const, + rings: [ + [ + { x: 0.3, y: 0.2 }, + { x: 0.7, y: 0.2 }, + { x: 0.5, y: 0.8 }, + ], + ], + strokes: [], + feather: 0.2, + invert: false, + }; + const items = [ + { name: "背景", presetId: null, mask: bitmap(true), amount: 60 }, + { name: "人物", presetId: null, mask: bitmap(false), amount: 60 }, + { name: "顔", presetId: "skin" as const, mask: polygon, amount: 80 }, + ]; + const applied = editorReducer(loaded, { type: "portrait/apply", items, presetId: "natural" }); + + it("applies a portrait as one history step, groups the adjustments, and remembers the group and preset", () => { + const list = applied.history.present.localAdjustments; + expect(list).toHaveLength(3); + expect(new Set(list.map((l) => l.groupId)).size).toBe(1); + expect(list[0]!.groupId).toBe(applied.ui.portrait.groupId); + expect(applied.ui.portrait.presetId).toBe("natural"); + expect(applied.history.pastLabels.at(-1)).toBe("人物補正: ナチュラル"); + expect(applied.ui.tool).toBe("portrait"); + }); + + it("switches the preset for the whole group in one step", () => { + const s = editorReducer(applied, { type: "portrait/preset", presetId: "dramatic" }); + expect(s.ui.portrait.presetId).toBe("dramatic"); + expect(s.history.pastLabels.at(-1)).toBe("人物補正: ドラマチック"); + const bg = s.history.present.localAdjustments[0]!; + expect(bg.adjust.exposure).toBe(-0.5); + }); + + it("amount preview / commit scale the group's amounts with the drag rule", () => { + let s = editorReducer(applied, { type: "portrait/amount-preview", value: 50 }); + expect(s.history.past).toHaveLength(applied.history.past.length); + expect(s.history.present.localAdjustments[0]!.amount).toBe(30); + s = editorReducer(s, { type: "portrait/amount-commit", value: 50 }); + expect(s.history.past).toHaveLength(applied.history.past.length + 1); + expect(s.history.pastLabels.at(-1)).toBe("人物補正の効果量 50"); + }); + + it("the group is inactive after undo and active again after redo", () => { + let s = editorReducer(applied, { type: "history/undo" }); + expect(activePortraitGroup(s)).toBeNull(); + expect(editorReducer(s, { type: "portrait/preset", presetId: "soft" })).toBe(s); + s = editorReducer(s, { type: "history/redo" }); + expect(activePortraitGroup(s)).toBe(applied.ui.portrait.groupId); + }); + + it("keeps detected faces and the chosen one in the ui state", () => { + let s = editorReducer(loaded, { type: "portrait/faces", faces: [] }); + expect(s.ui.portrait.faces).toEqual([]); + s = editorReducer(s, { type: "portrait/select-face", index: 1 }); + expect(s.ui.portrait.selectedFace).toBe(1); + // 画像を開き直したら忘れる + s = editorReducer(s, { type: "image/loaded", draftId: "d3", image: loaded.source! }); + expect(s.ui.portrait.faces).toBeNull(); + expect(s.ui.portrait.selectedFace).toBe(0); + }); +}); diff --git a/apps/app/web/features/editor/state.ts b/apps/app/web/features/editor/state.ts index a20c906..ae68d4c 100644 --- a/apps/app/web/features/editor/state.ts +++ b/apps/app/web/features/editor/state.ts @@ -6,9 +6,14 @@ import { MAX_BRUSH_STROKES, MAX_LOCAL_ADJUSTMENTS, applyLocalPreset, + applyPortraitPreset, applyPreset, findLocalPreset, + findPortraitPreset, findPreset, + portraitAmount, + scalePortraitAmount, + type PortraitPresetId, type AdjustV1, type BrushStrokeV2, type EditRecipe, @@ -19,11 +24,12 @@ import { type Mask, } from "@prismtone/shared/recipe"; import type { SegmentSelectionKind } from "./inference/auto-select.ts"; +import type { FaceResult } from "./inference/face-masks.ts"; import { commit, createHistory, preview, redo, undo, type History } from "./history.ts"; import { adjustLabel, geometryLabel, localAdjustLabel } from "./labels.ts"; import type { LoadedImage } from "./load-image.ts"; -export type Tool = "adjust" | "geometry" | "presets" | "local"; +export type Tool = "adjust" | "geometry" | "presets" | "local" | "portrait"; /** 円形マスクの初期配置 (今見えている範囲の中央に置くため) */ export type EllipsePlacement = { cx: number; cy: number; rx: number; ry: number }; @@ -40,6 +46,9 @@ export type AutoLocalItem = { /** null ならプリセット無し (キャラクター / 背景の範囲だけ) */ readonly presetId: LocalPresetId | null; readonly name?: string | undefined; + /** 与えればプリセットの値の代わりに使う (人物補正の役ごとの値、#175) */ + readonly adjust?: LocalAdjustV2 | undefined; + readonly amount?: number | undefined; }; export type BrushSettings = { @@ -82,6 +91,15 @@ export type EditorState = { /** 直近のタップの 3 段の候補。粒度の切り替えに使う。その部分補正が消えたら捨てる */ readonly segment: { readonly localId: string; readonly masks: readonly Mask[] } | null; }; + /** 人物補正 (#175)。検出した顔と選んだ人物、今のグループとプリセット */ + readonly portrait: { + /** null は未検出。空配列は検出したが顔が無い */ + readonly faces: readonly FaceResult[] | null; + readonly selectedFace: number; + /** 直近に当てたグループ。レシピに残っているかは activePortraitGroup で見る (undo / redo で消えたり戻ったりする) */ + readonly groupId: string | null; + readonly presetId: PortraitPresetId | null; + }; }; }; @@ -127,6 +145,17 @@ export type EditorAction = | { type: "ui/brush"; brush: BrushSettings } | { type: "ui/inference"; inference: InferenceStatus } | { type: "ui/notice"; notice: string | null } + | { type: "portrait/faces"; faces: readonly FaceResult[] } + | { type: "portrait/select-face"; index: number } + | { + /** 検出と切り抜きの結果を 1 手で足し、グループとして覚える */ + type: "portrait/apply"; + items: readonly AutoLocalItem[]; + presetId: PortraitPresetId; + } + | { type: "portrait/preset"; presetId: PortraitPresetId } + | { type: "portrait/amount-preview"; value: number } + | { type: "portrait/amount-commit"; value: number } | { type: "ui/tap"; tap: SegmentSelectionKind | null } | { type: "ui/segment"; segment: EditorState["ui"]["local"]["segment"] } | { type: "history/undo" } @@ -161,9 +190,12 @@ export const initialEditorState: EditorState = { tap: null, segment: null, }, + portrait: { faces: null, selectedFace: 0, groupId: null, presetId: null }, }, }; +const DEFAULT_PORTRAIT_UI = initialEditorState.ui.portrait; + const withAdjust = (r: EditRecipe, key: keyof AdjustV1, value: number): EditRecipe => ({ ...r, presetId: null, @@ -212,6 +244,32 @@ function newLocalId(): string { localSeq = (localSeq + 1) % 1000; return `l${Date.now().toString(36)}${localSeq.toString(36)}`; } +function newGroupId(): string { + return `p${Date.now().toString(36)}${(localSeq++ % 1000).toString(36)}`; +} + +/** 自動選択の部分補正を組み立てる (local/add-auto と portrait/apply で共通) */ +function buildAutoLocals( + items: readonly AutoLocalItem[], + groupId: string | null, +): LocalAdjustment[] { + return items.map((item) => { + const preset = item.presetId ? findLocalPreset(item.presetId) : undefined; + const base: LocalAdjustment = { + ...DEFAULT_LOCAL_ADJUSTMENT, + id: newLocalId(), + name: item.name ?? null, + groupId, + mask: item.mask, + }; + const withPreset = preset ? applyLocalPreset(base, preset) : base; + return { + ...withPreset, + ...(item.adjust ? { adjust: item.adjust } : {}), + ...(item.amount !== undefined ? { amount: item.amount } : {}), + }; + }); +} /** ドラッグ中の preview / 終了時の commit を部分補正に適用する共通処理 */ function localPreview( @@ -253,10 +311,11 @@ function withNotice(state: EditorState, notice: string | null): EditorState { return { ...state, ui: { ...state.ui, local: { ...state.ui.local, notice } } }; } -/** 選択中の id と切り抜きの候補がレシピから消えていたら外す (undo / 削除 / リセット後) */ +/** 選択中の id・切り抜きの候補・人物補正のグループがレシピから消えていたら外す (undo / 削除 / リセット後) */ function reconcileSelection(state: EditorState): EditorState { const { selectedId, segment } = state.ui.local; - const has = (id: string) => state.history.present.localAdjustments.some((l) => l.id === id); + const list = state.history.present.localAdjustments; + const has = (id: string) => list.some((l) => l.id === id); let next = state; if (selectedId && !has(selectedId)) next = selectLocal(next, null); if (segment && !has(segment.localId)) { @@ -265,6 +324,13 @@ function reconcileSelection(state: EditorState): EditorState { return next; } +/** 人物補正のグループが今のレシピにあるか。undo で消え、redo で戻るので、ui の groupId は消さずにここで見る */ +export function activePortraitGroup(state: EditorState): string | null { + const { groupId } = state.ui.portrait; + if (!groupId) return null; + return state.history.present.localAdjustments.some((l) => l.groupId === groupId) ? groupId : null; +} + export function editorReducer(state: EditorState, action: EditorAction): EditorState { const { history } = state; switch (action.type) { @@ -275,7 +341,7 @@ export function editorReducer(state: EditorState, action: EditorAction): EditorS draftId: action.draftId, history: createHistory(action.recipe ?? DEFAULT_RECIPE), dragBase: null, - ui: { ...state.ui, error: null, cropping: false }, + ui: { ...state.ui, error: null, cropping: false, portrait: DEFAULT_PORTRAIT_UI }, }; case "image/failed": return { ...state, ui: { ...state.ui, error: action.error } }; @@ -361,17 +427,7 @@ export function editorReducer(state: EditorState, action: EditorAction): EditorS case "local/add-auto": { const room = MAX_LOCAL_ADJUSTMENTS - history.present.localAdjustments.length; if (action.items.length === 0 || action.items.length > room) return state; - const added = action.items.map((item) => { - const preset = item.presetId ? findLocalPreset(item.presetId) : undefined; - const base: LocalAdjustment = { - ...DEFAULT_LOCAL_ADJUSTMENT, - id: newLocalId(), - name: item.name ?? null, - groupId: action.groupId ?? null, - mask: item.mask, - }; - return preset ? applyLocalPreset(base, preset) : base; - }); + const added = buildAutoLocals(action.items, action.groupId ?? null); const next = { ...history.present, localAdjustments: [...history.present.localAdjustments, ...added], @@ -474,6 +530,89 @@ export function editorReducer(state: EditorState, action: EditorAction): EditorS }; case "ui/notice": return withNotice(state, action.notice); + case "portrait/faces": + return { + ...state, + ui: { + ...state.ui, + portrait: { ...state.ui.portrait, faces: action.faces, selectedFace: 0 }, + }, + }; + case "portrait/select-face": + return { + ...state, + ui: { ...state.ui, portrait: { ...state.ui.portrait, selectedFace: action.index } }, + }; + case "portrait/apply": { + const room = MAX_LOCAL_ADJUSTMENTS - history.present.localAdjustments.length; + const preset = findPortraitPreset(action.presetId); + if (!preset || action.items.length === 0 || action.items.length > room) return state; + const groupId = newGroupId(); + const next = { + ...history.present, + localAdjustments: [ + ...history.present.localAdjustments, + ...buildAutoLocals(action.items, groupId), + ], + }; + return { + ...state, + history: commit(history, next, `人物補正: ${preset.name}`), + ui: { + ...state.ui, + tool: "portrait", + local: { ...state.ui.local, notice: null }, + portrait: { ...state.ui.portrait, groupId, presetId: action.presetId }, + }, + }; + } + case "portrait/preset": { + const groupId = activePortraitGroup(state); + const { presetId } = state.ui.portrait; + const preset = findPortraitPreset(action.presetId); + const current = presetId ? findPortraitPreset(presetId) : undefined; + if (!groupId || !preset || !current) return state; + const effect = portraitAmount(history.present, groupId, current); + return { + ...state, + history: commit( + history, + applyPortraitPreset(history.present, groupId, preset, effect), + `人物補正: ${preset.name}`, + ), + ui: { ...state.ui, portrait: { ...state.ui.portrait, presetId: action.presetId } }, + }; + } + case "portrait/amount-preview": { + const groupId = activePortraitGroup(state); + const { presetId } = state.ui.portrait; + const preset = presetId ? findPortraitPreset(presetId) : undefined; + if (!groupId || !preset) return state; + return { + ...state, + dragBase: state.dragBase ?? history.present, + history: preview( + history, + scalePortraitAmount(history.present, groupId, preset, action.value), + ), + }; + } + case "portrait/amount-commit": { + const groupId = activePortraitGroup(state); + const { presetId } = state.ui.portrait; + const preset = presetId ? findPortraitPreset(presetId) : undefined; + if (!groupId || !preset) return state; + const base = state.dragBase ?? history.present; + return { + ...state, + dragBase: null, + history: commit( + { ...history, present: base }, + scalePortraitAmount(base, groupId, preset, action.value), + `人物補正の効果量 ${action.value}`, + ), + }; + } case "ui/tap": return { ...state, ui: { ...state.ui, local: { ...state.ui.local, tap: action.tap } } }; case "ui/segment": diff --git a/apps/app/web/features/editor/ui/EditorPage.tsx b/apps/app/web/features/editor/ui/EditorPage.tsx index fc8dfdc..5c33ed1 100644 --- a/apps/app/web/features/editor/ui/EditorPage.tsx +++ b/apps/app/web/features/editor/ui/EditorPage.tsx @@ -1,9 +1,9 @@ import { useCallback, useEffect, useReducer, useRef, useState } from "react"; import { useNavigate, useSearchParams } from "react-router"; import { DEFAULT_ELLIPSE_MASK, type EditRecipe } from "@prismtone/shared/recipe"; -import { editorReducer, initialEditorState } from "../state.ts"; +import { activePortraitGroup, editorReducer, initialEditorState } from "../state.ts"; import { canRedo, canUndo, redoLabel, undoLabel } from "../history.ts"; -import { ImageLoadError, loadImageFile } from "../load-image.ts"; +import { ImageLoadError, loadImageFile, type LoadedImage } from "../load-image.ts"; import { addPendingExport, loadDraft, saveDraft } from "../drafts.ts"; import { aspectRatio, centeredCrop } from "../render/geometry.ts"; import type { EditorRenderer } from "../render/editor-renderer.ts"; @@ -26,6 +26,15 @@ import type { FaceResult } from "../inference/face-masks.ts"; import { SAM_LEVELS } from "../inference/segment-masks.ts"; import { TapOverlay } from "./TapOverlay.tsx"; import type { Point } from "../mask-math.ts"; +import { PortraitPanel } from "./PortraitPanel.tsx"; +import { FaceBoxesOverlay } from "./FaceBoxesOverlay.tsx"; +import { PORTRAIT_FULL, buildPortraitItems, faceCenter } from "../inference/portrait.ts"; +import { + MAX_LOCAL_ADJUSTMENTS, + findPortraitPreset, + portraitAmount, + type PortraitPresetId, +} from "@prismtone/shared/recipe"; import { CompareSlider } from "./CompareSlider.tsx"; const ERROR_TEXT: Record = { @@ -172,46 +181,123 @@ export function EditorPage() { // 自動選択 (#176): 顔の検出結果は画像 (draftId) ごとに 1 回だけ取り、瞳・美肌で使い回す。 // 検出のライブラリ (WASM) は押したときに動的 import する (現像の初期表示に載せない) const facesRef = useRef<{ draftId: string; faces: FaceResult[] } | null>(null); + /** 顔の検出 (画像ごとに 1 回)。失敗は null (文言は呼ぶ側で出す) */ + const detectFacesOnce = async ( + source: LoadedImage, + draftId: string, + ): Promise => { + if (facesRef.current?.draftId === draftId) return facesRef.current.faces; + dispatch({ type: "ui/inference", inference: { status: "loading", progress: null } }); + try { + const { detectFaces } = await import("../inference/face.ts"); + const faces = await detectFaces(source.bitmap, { + onProgress: (progress) => + dispatch({ type: "ui/inference", inference: { status: "loading", progress } }), + }); + facesRef.current = { draftId, faces }; + return faces; + } catch (e) { + console.error("face detection failed", e); + return null; + } finally { + dispatch({ type: "ui/inference", inference: { status: "idle", progress: null } }); + } + }; + /** 画像の埋め込み (SAM、画像ごとに 1 回)。失敗は false */ + const prepareSegmenterOnce = async (source: LoadedImage): Promise => { + dispatch({ type: "ui/inference", inference: { status: "loading", progress: null } }); + try { + const { prepareSegmenter } = await import("../inference/segment.ts"); + await prepareSegmenter(source.bitmap, { + onProgress: (progress) => + dispatch({ type: "ui/inference", inference: { status: "loading", progress } }), + }); + return true; + } catch (e) { + console.error("segmenter failed", e); + return false; + } finally { + dispatch({ type: "ui/inference", inference: { status: "idle", progress: null } }); + } + }; + + // 人物補正 (#175): 検出 → 人物を選ぶ → プリセットで 5 件 (背景・人物・顔・瞳 ×2) を 1 手で置く + const portraitDetect = async () => { + const source = state.source; + const draftId = state.draftId; + if (!source || !draftId || state.ui.local.inference.status !== "idle") return; + const faces = await detectFacesOnce(source, draftId); + if (!faces) { + dispatch({ type: "portrait/faces", faces: [] }); + dispatch({ type: "ui/notice", notice: AUTO_SELECT_FAILED }); + return; + } + dispatch({ type: "portrait/faces", faces }); + if (faces.length === 0) dispatch({ type: "ui/notice", notice: AUTO_SELECT_FAILED }); + }; + const portraitApply = async (presetId: PortraitPresetId) => { + const source = state.source; + const faces = state.ui.portrait.faces; + const face = faces?.[state.ui.portrait.selectedFace]; + if (!source || !face || state.ui.local.inference.status !== "idle") return; + if (activePortraitGroup(state)) { + dispatch({ type: "portrait/preset", presetId }); + return; + } + const preset = findPortraitPreset(presetId); + if (!preset) return; + // 1 人で最大 5 件 (背景・人物・顔・瞳 ×2) 使う。入り切らなければ先に伝える + if (MAX_LOCAL_ADJUSTMENTS - recipe.localAdjustments.length < 5) { + dispatch({ type: "ui/notice", notice: PORTRAIT_FULL }); + return; + } + if (!(await prepareSegmenterOnce(source))) { + dispatch({ type: "ui/notice", notice: AUTO_SELECT_FAILED }); + return; + } + dispatch({ type: "ui/inference", inference: { status: "running", progress: null } }); + try { + const { segmentAt } = await import("../inference/segment.ts"); + const center = faceCenter(face); + const { masks } = await segmentAt(center.x, center.y); + const person = masks[0]; + if (!person || person.kind !== "bitmap") throw new Error("no person mask"); + dispatch({ + type: "portrait/apply", + items: buildPortraitItems(face, person, preset, 100), + presetId, + }); + } catch (e) { + console.error("portrait failed", e); + dispatch({ type: "ui/notice", notice: AUTO_SELECT_FAILED }); + } finally { + dispatch({ type: "ui/inference", inference: { status: "idle", progress: null } }); + } + }; + const portraitGroupId = activePortraitGroup(state); + const portraitEffect = (() => { + const { presetId } = state.ui.portrait; + const preset = presetId ? findPortraitPreset(presetId) : undefined; + return portraitGroupId && preset ? portraitAmount(recipe, portraitGroupId, preset) : 100; + })(); + const autoSelect = async (kind: "eyes" | "skin" | SegmentSelectionKind) => { const source = state.source; const draftId = state.draftId; if (!source || !draftId || state.ui.local.inference.status !== "idle") return; if (kind === "gear" || kind === "person" || kind === "background") { // タップで切る (#177): 画像の埋め込み (初回は数秒) を済ませてからタップを待つ - dispatch({ type: "ui/inference", inference: { status: "loading", progress: null } }); - try { - const { prepareSegmenter } = await import("../inference/segment.ts"); - await prepareSegmenter(source.bitmap, { - onProgress: (progress) => - dispatch({ type: "ui/inference", inference: { status: "loading", progress } }), - }); - } catch (e) { - console.error("segmenter failed", e); - dispatch({ type: "ui/inference", inference: { status: "idle", progress: null } }); + if (!(await prepareSegmenterOnce(source))) { dispatch({ type: "ui/notice", notice: AUTO_SELECT_FAILED }); return; } - dispatch({ type: "ui/inference", inference: { status: "idle", progress: null } }); dispatch({ type: "ui/tap", tap: kind }); return; } - let faces = facesRef.current?.draftId === draftId ? facesRef.current.faces : null; + const faces = await detectFacesOnce(source, draftId); if (!faces) { - dispatch({ type: "ui/inference", inference: { status: "loading", progress: null } }); - try { - const { detectFaces } = await import("../inference/face.ts"); - faces = await detectFaces(source.bitmap, { - onProgress: (progress) => - dispatch({ type: "ui/inference", inference: { status: "loading", progress } }), - }); - facesRef.current = { draftId, faces }; - } catch (e) { - console.error("face detection failed", e); - dispatch({ type: "ui/inference", inference: { status: "idle", progress: null } }); - dispatch({ type: "ui/notice", notice: AUTO_SELECT_FAILED }); - return; - } - dispatch({ type: "ui/inference", inference: { status: "idle", progress: null } }); + dispatch({ type: "ui/notice", notice: AUTO_SELECT_FAILED }); + return; } const plan = planFaceSelection(kind, faces); if (plan.items.length > 0) { @@ -650,6 +736,21 @@ export function EditorPage() { onCancel={() => dispatch({ type: "ui/tap", tap: null })} /> )} + {hasImage && + state.source && + state.ui.tool === "portrait" && + (state.ui.portrait.faces?.length ?? 0) > 1 && + !state.ui.comparing && + !state.ui.cropping && ( + dispatch({ type: "portrait/select-face", index })} + /> + )} {hasImage && state.ui.cropping && recipe.geometry.crop && ( dispatch({ type: "adjust/commit", key, value })} /> )} + {state.ui.tool === "portrait" && ( + void portraitDetect()} + onSelectFace={(index) => dispatch({ type: "portrait/select-face", index })} + onApply={(presetId) => void portraitApply(presetId)} + onAmountPreview={(value) => dispatch({ type: "portrait/amount-preview", value })} + onAmountCommit={(value) => dispatch({ type: "portrait/amount-commit", value })} + onGoLocal={() => dispatch({ type: "ui/tool", tool: "local" })} + /> + )} {state.ui.tool === "local" && ( void; +}; + +/** 人物補正 (#175) で複数の顔があるとき、番号付きの枠を重ねて選ばせる。幾何 (回転・反転) を追う */ +export function FaceBoxesOverlay({ view, source, geometry, faces, selected, onSelect }: Props) { + const toScreen = (x: number, y: number) => { + const c = imageUvToCanvas({ x, y }, source, geometry); + return { x: view.x + c.x * view.scale, y: view.y + c.y * view.scale }; + }; + return ( +
+ {faces.map((f, i) => { + const [x0, y0, x1, y1] = f.bbox; + // 回転しても囲えるように 4 隅を写してから外接矩形を取る + const corners = [toScreen(x0, y0), toScreen(x1, y0), toScreen(x1, y1), toScreen(x0, y1)]; + const left = Math.min(...corners.map((c) => c.x)); + const top = Math.min(...corners.map((c) => c.y)); + const right = Math.max(...corners.map((c) => c.x)); + const bottom = Math.max(...corners.map((c) => c.y)); + const active = i === selected; + return ( + + ); + })} +
+ ); +} diff --git a/apps/app/web/features/editor/ui/PortraitPanel.tsx b/apps/app/web/features/editor/ui/PortraitPanel.tsx new file mode 100644 index 0000000..0e53662 --- /dev/null +++ b/apps/app/web/features/editor/ui/PortraitPanel.tsx @@ -0,0 +1,139 @@ +import { PORTRAIT_PRESETS, type PortraitPresetId } from "@prismtone/shared/recipe"; +import type { FaceResult } from "../inference/face-masks.ts"; +import type { InferenceStatus } from "../state.ts"; +import { Slider } from "./Slider.tsx"; + +type Props = { + faces: readonly FaceResult[] | null; + selectedFace: number; + groupId: string | null; + presetId: PortraitPresetId | null; + /** グループの効果量 0..100 */ + amount: number; + inference: InferenceStatus; + notice: string | null; + onDetect: () => void; + onSelectFace: (index: number) => void; + onApply: (presetId: PortraitPresetId) => void; + onAmountPreview: (value: number) => void; + onAmountCommit: (value: number) => void; + /** 部分補正タブへ (自動で置いた 5 件を個別に直す) */ + onGoLocal: () => void; +}; + +const btn = + "rounded border border-line-soft px-2 py-1 text-xs hover:bg-surface-hover disabled:opacity-40 disabled:hover:bg-transparent"; + +/** + * 人物補正 (#175): 人物を検出 → (複数なら) 選ぶ → プリセット → 効果量。 + * 中身は部分補正 5 件 (背景・人物・顔・瞳 ×2) で、部分補正タブで個別に直せる + */ +export function PortraitPanel(p: Props) { + const busy = p.inference.status !== "idle"; + const faces = p.faces ?? []; + return ( +
+

+ 人物を認識して、顔・瞳・人物・背景をまとめて整えます。認識も補正もこの端末の中だけで行います。 +

+ {p.faces === null ? ( + + ) : faces.length === 0 ? ( +

+ {p.notice ?? "自動選択できませんでした。手動で範囲を指定できます"} + +

+ ) : ( + <> + {faces.length > 1 && ( +
+ 補正する人物: + {faces.map((_, i) => ( + + ))} + (画像の番号をタップしても選べます) +
+ )} +
+

+ {p.groupId ? "プリセットを切り替える" : "プリセットを選ぶと補正を置きます"} +

+
+ {PORTRAIT_PRESETS.map((preset) => ( + + ))} +
+
+ {p.groupId && ( +
+ p.onAmountCommit(100)} + /> +

+ 顔・瞳・人物・背景のマスクは + + で個別に直せます (ブラシで足す / 消す、値の調整)。 +

+
+ )} + + )} + {busy && ( +

+ {p.inference.status === "loading" && p.inference.progress + ? `認識用のデータを読み込んでいます (${Math.round((p.inference.progress.loaded / p.inference.progress.total) * 100)}%)` + : p.inference.status === "loading" + ? "認識の準備をしています…" + : "人物を認識しています…"} +

+ )} + {p.notice && !busy && faces.length > 0 && ( +

+ {p.notice} +

+ )} +
+ ); +} diff --git a/e2e/editor.spec.ts b/e2e/editor.spec.ts index cad3b71..a7ec59c 100644 --- a/e2e/editor.spec.ts +++ b/e2e/editor.spec.ts @@ -848,4 +848,93 @@ test.describe("editor", () => { expect(foreign).toEqual([]); }); + + test("人物補正 detects the person, applies a preset as five grouped adjustments, scales them, and survives a reload (#175)", async ({ + page, + }) => { + test.setTimeout(180_000); + await page.addInitScript(() => { + (window as Window & { __PRISMTONE_E2E__?: boolean }).__PRISMTONE_E2E__ = true; + }); + await page.goto("/edit"); + await page + .getByTestId("file-input") + .setInputFiles(new URL("./fixtures/face.jpg", import.meta.url).pathname); + await expect(page.getByRole("button", { name: "端末に保存" })).toBeEnabled(); + await page.getByRole("tab", { name: "人物補正" }).click(); + await page.getByTestId("portrait-detect").click(); + await expect(page.getByTestId("portrait-presets")).toBeVisible({ timeout: 60_000 }); + // 1 人なので人物の選択は出ない + await expect(page.getByTestId("portrait-faces")).toHaveCount(0); + + // プリセットを選ぶと 5 件 (背景・人物・顔・瞳 ×2) が 1 手で置かれる + await page.getByRole("button", { name: "ナチュラル" }).click(); + await expect(page.getByTestId("portrait-amount")).toBeVisible({ timeout: 120_000 }); + await expect(page.getByTestId("history-last")).toContainText("人物補正: ナチュラル"); + await expect( + page.getByTestId("portrait-presets").getByRole("button", { name: "ナチュラル" }), + ).toHaveAttribute("aria-pressed", "true"); + + // プリセットの切り替えは 1 手、効果量はドラッグの規則 (キーボードで 1 手) + await page + .getByTestId("portrait-presets") + .getByRole("button", { name: "ドラマチック" }) + .click(); + await expect(page.getByTestId("history-last")).toContainText("人物補正: ドラマチック"); + const amount = page.getByTestId("portrait-amount").getByLabel("効果量"); + await amount.focus(); + await page.keyboard.press("ArrowLeft"); + await expect(page.getByTestId("history-last")).toContainText("人物補正の効果量 99"); + + // 部分補正タブに 5 件、名前は役 + await page.getByRole("tab", { name: "部分補正" }).click(); + await expect(page.getByTestId("local-list").getByRole("listitem")).toHaveCount(5); + await expect(page.getByTestId("local-list")).toContainText("背景"); + await expect(page.getByTestId("local-list")).toContainText("瞳 (左)"); + + // undo で 3 手戻すとグループごと消え、人物補正タブは「プリセットを選ぶ」に戻る。redo で戻る + for (let i = 0; i < 3; i++) await page.getByTestId("history-undo").click(); + await expect(page.getByTestId("local-list")).toHaveCount(0); + await page.getByRole("tab", { name: "人物補正" }).click(); + await expect(page.getByTestId("portrait-amount")).toHaveCount(0); + for (let i = 0; i < 3; i++) await page.getByTestId("history-redo").click(); + await expect(page.getByTestId("portrait-amount")).toBeVisible(); + + // 下書きを開き直しても 5 件が残り (v3 のレシピが IndexedDB を往復する)、書き出せる + const draftId = await page.evaluate( + () => + new Promise((resolve, reject) => { + const open = indexedDB.open("prismtone-editor"); + open.onerror = () => reject(open.error); + open.onsuccess = () => { + const req = open.result.transaction("kv").objectStore("kv").getAllKeys(); + req.onsuccess = () => { + const key = (req.result as string[]).find((k) => k.startsWith("draft:")); + if (!key) reject(new Error("no draft")); + else resolve(key.slice("draft:".length)); + }; + }; + }), + ); + await page.goto(`/edit?draft=${draftId}`); + await expect(page.getByRole("button", { name: "端末に保存" })).toBeEnabled({ timeout: 30_000 }); + await page.getByRole("tab", { name: "部分補正" }).click(); + await expect(page.getByTestId("local-list").getByRole("listitem")).toHaveCount(5); + const download = page.waitForEvent("download"); + await page.getByTestId("save").click(); + expect((await download).suggestedFilename()).toMatch(/\.(webp|jpe?g|png)$/); + }); + + test("人物補正 says so when no face is found and points to the manual tools (#175)", async ({ + page, + }) => { + await openEditorWithImage(page); + await page.getByRole("tab", { name: "人物補正" }).click(); + await page.getByTestId("portrait-detect").click(); + await expect(page.getByTestId("portrait-notice")).toContainText("自動選択できませんでした", { + timeout: 60_000, + }); + await page.getByRole("button", { name: "部分補正で手で置く" }).click(); + await expect(page.getByTestId("local-add-brush")).toBeVisible(); + }); }); diff --git a/e2e/perf-local-adjust.spec.ts b/e2e/perf-local-adjust.spec.ts index 4dfb477..ed96590 100644 --- a/e2e/perf-local-adjust.spec.ts +++ b/e2e/perf-local-adjust.spec.ts @@ -85,7 +85,7 @@ test("measure develop / export time and texture memory for 0 / 4 / 8 local adjus return dbg && gl ? String(gl.getParameter(dbg.UNMASKED_RENDERER_WEBGL)) : "unknown"; }); console.log(`renderer: ${gpu}`); - for (const n of [0, 4, 8]) { + for (const n of [0, 4, 8, 12]) { const recipe: EditRecipe = { ...DEFAULT_RECIPE, localAdjustments: Array.from({ length: n }, (_, i) => local(i)), diff --git a/packages/shared/src/recipe/index.ts b/packages/shared/src/recipe/index.ts index e80df9e..604a3f3 100644 --- a/packages/shared/src/recipe/index.ts +++ b/packages/shared/src/recipe/index.ts @@ -3,3 +3,4 @@ export * from "./migrate.ts"; export * from "./presets.ts"; export * from "./local-presets.ts"; export * from "./rle.ts"; +export * from "./portrait-presets.ts"; diff --git a/packages/shared/src/recipe/portrait-presets.test.ts b/packages/shared/src/recipe/portrait-presets.test.ts new file mode 100644 index 0000000..1130e49 --- /dev/null +++ b/packages/shared/src/recipe/portrait-presets.test.ts @@ -0,0 +1,128 @@ +import { describe, expect, it } from "vitest"; +import { + DEFAULT_ELLIPSE_MASK, + DEFAULT_LOCAL_ADJUST, + DEFAULT_LOCAL_ADJUSTMENT, + DEFAULT_RECIPE, + editRecipeSchema, + localAdjustSchemaV2, + type EditRecipe, + type LocalAdjustment, +} from "./schema.ts"; +import { encodeRle } from "./rle.ts"; +import { + PORTRAIT_PRESETS, + PORTRAIT_ROLES, + applyPortraitPreset, + findPortraitPreset, + portraitAmount, + portraitRole, + scalePortraitAmount, +} from "./portrait-presets.ts"; + +const bitmap = (invert: boolean) => ({ + kind: "bitmap" as const, + width: 2, + height: 1, + rle: encodeRle(Uint8Array.from([1, 0])), + strokes: [], + feather: 0.1, + invert, +}); +const polygon = { + kind: "polygon" as const, + rings: [ + [ + { x: 0.3, y: 0.2 }, + { x: 0.7, y: 0.2 }, + { x: 0.5, y: 0.8 }, + ], + ], + strokes: [], + feather: 0.2, + invert: false, +}; +const local = ( + id: string, + mask: LocalAdjustment["mask"], + extra: Partial = {}, +): LocalAdjustment => ({ + ...DEFAULT_LOCAL_ADJUSTMENT, + id, + mask, + groupId: "p1", + ...extra, +}); +const group: EditRecipe = { + ...DEFAULT_RECIPE, + localAdjustments: [ + local("bg", bitmap(true)), + local("person", bitmap(false)), + local("face", polygon, { presetId: "skin" }), + local("eyeL", DEFAULT_ELLIPSE_MASK, { presetId: "eyes" }), + local("other", DEFAULT_ELLIPSE_MASK, { groupId: null }), + ], +}; + +describe("PORTRAIT_PRESETS", () => { + it("has the five presets and every role's adjust is a valid local adjust", () => { + expect(PORTRAIT_PRESETS.map((p) => p.id)).toEqual([ + "natural", + "bright", + "dramatic", + "soft", + "eyes", + ]); + for (const preset of PORTRAIT_PRESETS) { + for (const role of PORTRAIT_ROLES) { + const r = preset.roles[role]; + expect( + localAdjustSchemaV2.safeParse({ ...DEFAULT_LOCAL_ADJUST, ...r.adjust }).success, + ).toBe(true); + expect(r.amount).toBeGreaterThanOrEqual(0); + expect(r.amount).toBeLessThanOrEqual(100); + } + } + expect(findPortraitPreset("nope")).toBeUndefined(); + }); +}); + +describe("portraitRole", () => { + it("derives the role from the mask: inverted bitmap = 背景, bitmap = 人物, polygon = 顔, ellipse = 瞳", () => { + expect(group.localAdjustments.slice(0, 4).map(portraitRole)).toEqual([ + "background", + "person", + "face", + "eyes", + ]); + }); +}); + +describe("applyPortraitPreset", () => { + it("rewrites adjust and amount of the group's adjustments by role, leaving others alone", () => { + const dramatic = findPortraitPreset("dramatic")!; + const out = applyPortraitPreset(group, "p1", dramatic, 100); + const bg = out.localAdjustments[0]!; + expect(bg.adjust).toEqual({ ...DEFAULT_LOCAL_ADJUST, ...dramatic.roles.background.adjust }); + expect(bg.amount).toBe(dramatic.roles.background.amount); + expect(out.localAdjustments[4]).toBe(group.localAdjustments[4]); + expect(editRecipeSchema.safeParse(out).success).toBe(true); + expect(group.localAdjustments[0]!.amount).toBe(100); + }); + + it("keeps presetId on the face and eyes for the panel's labels", () => { + const out = applyPortraitPreset(group, "p1", findPortraitPreset("natural")!, 100); + expect(out.localAdjustments[2]!.presetId).toBe("skin"); + expect(out.localAdjustments[3]!.presetId).toBe("eyes"); + }); +}); + +describe("scalePortraitAmount / portraitAmount", () => { + it("scales each role's amount by the group's effect and reads it back", () => { + const natural = findPortraitPreset("natural")!; + const half = scalePortraitAmount(group, "p1", natural, 50); + expect(half.localAdjustments[0]!.amount).toBe(Math.round(natural.roles.background.amount / 2)); + expect(portraitAmount(half, "p1", natural)).toBe(50); + expect(portraitAmount(scalePortraitAmount(group, "p1", natural, 0), "p1", natural)).toBe(0); + }); +}); diff --git a/packages/shared/src/recipe/portrait-presets.ts b/packages/shared/src/recipe/portrait-presets.ts new file mode 100644 index 0000000..9bf6cf5 --- /dev/null +++ b/packages/shared/src/recipe/portrait-presets.ts @@ -0,0 +1,165 @@ +import { + DEFAULT_LOCAL_ADJUST, + type EditRecipe, + type LocalAdjustV2, + type LocalAdjustment, +} from "./schema.ts"; + +/** + * 人物補正 (#175) のプリセット。1 人ぶんの「背景・人物・顔・瞳」の 4 役に対する部分補正の値と効果量。 + * 部分補正は groupId で束ね、役はマスクの形から決める (portraitRole)。レシピには結果の値だけが + * 入るので、プリセットの定義が後から変わっても投稿済みの見え方は変わらない (04 §1.2 と同じ原則)。 + * 合成順は 背景 → 人物 → 顔 → 瞳 (後の方が上に掛かる)。 + */ + +export const PORTRAIT_ROLES = ["background", "person", "face", "eyes"] as const; +export type PortraitRole = (typeof PORTRAIT_ROLES)[number]; + +export const PORTRAIT_PRESET_IDS = ["natural", "bright", "dramatic", "soft", "eyes"] as const; +export type PortraitPresetId = (typeof PORTRAIT_PRESET_IDS)[number]; + +export type PortraitRoleSetting = { adjust: Partial; amount: number }; + +export type PortraitPreset = { + id: PortraitPresetId; + name: string; + hint: string; + roles: Record; +}; + +const eyesLight: PortraitRoleSetting = { + adjust: { exposure: 0.3, saturation: 15, contrast: 10, sharpen: 30 }, + amount: 70, +}; + +// 数値は実画像で調整する。既存の 9 項目だけで組む (ぼかし・発光・周辺減光は別 Issue) +export const PORTRAIT_PRESETS: readonly PortraitPreset[] = Object.freeze([ + { + id: "natural", + name: "ナチュラル", + hint: "顔を少し明るく、美肌と瞳強調を弱く。背景はわずかに落とす", + roles: { + background: { adjust: { exposure: -0.15, saturation: -10, contrast: -5 }, amount: 60 }, + person: { adjust: { shadows: 15, contrast: 5, sharpen: 10 }, amount: 60 }, + face: { adjust: { exposure: 0.15, temperature: 5, smooth: 25 }, amount: 80 }, + eyes: eyesLight, + }, + }, + { + id: "bright", + name: "明るく", + hint: "顔と人物の露光・シャドウを持ち上げる", + roles: { + background: { adjust: { exposure: -0.05 }, amount: 40 }, + person: { adjust: { exposure: 0.2, shadows: 30 }, amount: 80 }, + face: { adjust: { exposure: 0.35, shadows: 20, smooth: 20 }, amount: 90 }, + eyes: eyesLight, + }, + }, + { + id: "dramatic", + name: "ドラマチック", + hint: "人物のコントラストを上げ、背景を暗く沈める", + roles: { + background: { adjust: { exposure: -0.5, saturation: -25, contrast: -10 }, amount: 90 }, + person: { adjust: { contrast: 20, shadows: -10, sharpen: 20 }, amount: 90 }, + face: { adjust: { contrast: 10, smooth: 15 }, amount: 80 }, + eyes: { adjust: { contrast: 20, sharpen: 40, saturation: 10 }, amount: 80 }, + }, + }, + { + id: "soft", + name: "やわらか", + hint: "美肌を強めに、コントラストを抑えてやわらかく", + roles: { + background: { adjust: { contrast: -20, saturation: -10 }, amount: 70 }, + person: { adjust: { contrast: -10, highlights: -10 }, amount: 60 }, + face: { adjust: { smooth: 45, exposure: 0.1, temperature: 8 }, amount: 90 }, + eyes: { adjust: { exposure: 0.2, sharpen: 10 }, amount: 50 }, + }, + }, + { + id: "eyes", + name: "瞳くっきり", + hint: "両目の露光・彩度・シャープを中心に。他は控えめ", + roles: { + background: { adjust: { exposure: -0.1 }, amount: 40 }, + person: { adjust: { sharpen: 10 }, amount: 40 }, + face: { adjust: { smooth: 10 }, amount: 40 }, + eyes: { adjust: { exposure: 0.4, saturation: 25, contrast: 20, sharpen: 50 }, amount: 100 }, + }, + }, +]); + +export function findPortraitPreset(id: string): PortraitPreset | undefined { + return PORTRAIT_PRESETS.find((p) => p.id === id); +} + +/** 部分補正の役をマスクの形から決める。反転したビットマップ = 背景、ビットマップ = 人物、多角形 = 顔、楕円 = 瞳 */ +export function portraitRole(local: LocalAdjustment): PortraitRole { + switch (local.mask.kind) { + case "bitmap": + return local.mask.invert ? "background" : "person"; + case "polygon": + return "face"; + case "ellipse": + return "eyes"; + case "brush": + return "person"; + } +} + +const roleAmount = (preset: PortraitPreset, role: PortraitRole, effect: number) => + Math.round((preset.roles[role].amount * effect) / 100); + +/** グループの部分補正にプリセットを当てた新しいレシピ。effect は効果量 0..100。元は変更しない */ +export function applyPortraitPreset( + recipe: EditRecipe, + groupId: string, + preset: PortraitPreset, + effect: number, +): EditRecipe { + return { + ...recipe, + localAdjustments: recipe.localAdjustments.map((l) => { + if (l.groupId !== groupId) return l; + const role = portraitRole(l); + return { + ...l, + adjust: { ...DEFAULT_LOCAL_ADJUST, ...preset.roles[role].adjust }, + amount: roleAmount(preset, role, effect), + }; + }), + }; +} + +/** グループの効果量だけを変えた新しいレシピ (役ごとのプリセットの効果量 × effect / 100) */ +export function scalePortraitAmount( + recipe: EditRecipe, + groupId: string, + preset: PortraitPreset, + effect: number, +): EditRecipe { + return { + ...recipe, + localAdjustments: recipe.localAdjustments.map((l) => + l.groupId === groupId ? { ...l, amount: roleAmount(preset, portraitRole(l), effect) } : l, + ), + }; +} + +/** グループの効果量 (0..100) を読み戻す。役の中で効果量の基準が最大のものから逆算する */ +export function portraitAmount( + recipe: EditRecipe, + groupId: string, + preset: PortraitPreset, +): number { + let best: { base: number; amount: number } | null = null; + for (const l of recipe.localAdjustments) { + if (l.groupId !== groupId) continue; + const base = preset.roles[portraitRole(l)].amount; + if (base > 0 && (!best || base > best.base)) best = { base, amount: l.amount }; + } + if (!best) return 100; + return Math.min(100, Math.round((best.amount / best.base) * 100)); +} From 504444152720ce789b84a37b9c57501b4a198c8e Mon Sep 17 00:00:00 2001 From: t1nyb0x Date: Mon, 21 Sep 2026 12:03:49 +0900 Subject: [PATCH 30/49] =?UTF-8?q?feat:=20/edit=20=E3=82=92=20cross-origin?= =?UTF-8?q?=20isolated=20=E3=81=AB=E3=81=97=E3=81=A6=E8=A3=85=E5=82=99?= =?UTF-8?q?=E3=81=AE=E5=88=87=E3=82=8A=E6=8A=9C=E3=81=8D=E3=82=92=E3=83=9E?= =?UTF-8?q?=E3=83=AB=E3=83=81=E3=82=B9=E3=83=AC=E3=83=83=E3=83=89=E3=81=A7?= =?UTF-8?q?=E5=8B=95=E3=81=8B=E3=81=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit lumorphia/prismtone#177 の切り抜きは COOP / COEP が無く SharedArrayBuffer が使えないので onnxruntime-web がシングル スレッドで、押してからタップ待ちまで約 10 秒だった。/edit の文書と /assets/ /models/ の応答に Cross-Origin-Embedder-Policy: credentialless を付ける (COOP は helmet の same-origin)。 専用 worker のスクリプトの応答にも COEP が要る (Chrome) ので、文書だけでなくアセットにも付ける。 require-corp でなく credentialless なので、/edit から client-side で /edit/post に進んだあとの XIVAPI のアイコンや R2 の画像 (CORP 無し) も匿名で読める。/edit 以外の文書には付けない。 同じ headless の計測で 10 秒 → 3.4〜3.9 秒、タップ 0.8 → 0.3 秒 (28 スレッド)。WebGPU は実機で 測るまで入れない。E2E で /edit の crossOriginIsolated が true であることを見る。 Closes lumorphia/prismtone#182 Co-Authored-By: Claude Opus 5 --- e2e/editor.spec.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/e2e/editor.spec.ts b/e2e/editor.spec.ts index a7ec59c..136d503 100644 --- a/e2e/editor.spec.ts +++ b/e2e/editor.spec.ts @@ -801,8 +801,10 @@ test.describe("editor", () => { .setInputFiles(new URL("./fixtures/face.jpg", import.meta.url).pathname); await expect(page.getByRole("button", { name: "端末に保存" })).toBeEnabled(); await page.getByRole("tab", { name: "部分補正" }).click(); + // /edit は COOP + COEP credentialless で cross-origin isolated (#182)。SharedArrayBuffer が使えて ORT がマルチスレッドになる + expect(await page.evaluate(() => crossOriginIsolated)).toBe(true); - // 装備強調: モデルの読み込みと埋め込み (シングルスレッドの WASM で 10 秒前後) のあとタップ待ちになる + // 装備強調: モデルの読み込みと埋め込み (マルチスレッドの WASM で 3〜4 秒) のあとタップ待ちになる await page.getByRole("button", { name: "装備強調" }).click(); await expect(page.getByTestId("tap-overlay")).toBeVisible({ timeout: 120_000 }); const host = (await page.getByTestId("canvas-host").boundingBox())!; From 64a1350e42b57e826dfcfd98bd76ea64867e7675 Mon Sep 17 00:00:00 2001 From: t1nyb0x Date: Mon, 21 Sep 2026 12:42:47 +0900 Subject: [PATCH 31/49] =?UTF-8?q?fix:=20dev=20=E3=81=A7=E4=BA=BA=E7=89=A9?= =?UTF-8?q?=E8=A3=9C=E6=AD=A3=E3=83=BB=E8=87=AA=E5=8B=95=E9=81=B8=E6=8A=9E?= =?UTF-8?q?=E3=82=92=E6=8A=BC=E3=81=99=E3=81=A8=E3=83=9A=E3=83=BC=E3=82=B8?= =?UTF-8?q?=E3=81=8C=E3=83=AA=E3=83=AD=E3=83=BC=E3=83=89=E3=81=95=E3=82=8C?= =?UTF-8?q?=E3=81=A6=E7=94=BB=E5=83=8F=E3=81=8C=E6=B6=88=E3=81=88=E3=82=8B?= =?UTF-8?q?=E3=81=AE=E3=82=92=E7=9B=B4=E3=81=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 原因は 2 つ、どちらも dev (Vite) だけで、本番ビルドでは起きない。 1. 押したときに動的 import する @mediapipe/tasks-vision と @huggingface/transformers を Vite の 依存最適化が初めて見つけ、ページを丸ごとリロードしていた (optimized dependencies changed. reloading)。 開いた画像はメモリだけなので消える。optimizeDeps.include で最初から束ねる 2. dev の Vite は classic worker に import 文を残すので顔検出の worker が落ちていた。module worker に 統一する。MediaPipe は module worker では WASM ローダーを import() で読むが、 - public/ に置くと Vite が ?import を足して「URL を export するモジュール」に変える → モデルを apps/app/models/ に移し、Fastify の static (server/plugins/models.ts) が /models/ で配る (dev も本番も同じ) - ローダーは classic (sloppy mode) 前提で、ES module (strict) では `var ModuleFactory` が self に出ず、 if ブロック内の `function custom_dbg` が外に見えない → fetch-models.ts がコピー時に 2 行補う - lumorphia/prismtone#185 の COEP は URL で絞っていたので dev の /web/ と /node_modules/ に付かず worker が黙って落ちて いた → Sec-Fetch-Dest が文書でない応答に全部付け、Vite の server.headers にも付ける Refs lumorphia/prismtone#176 lumorphia/prismtone#177 lumorphia/prismtone#175 lumorphia/prismtone#182 Co-Authored-By: Claude Opus 5 --- apps/app/scripts/fetch-models.ts | 43 ++++++++++++++----- .../app/web/features/editor/inference/face.ts | 7 +-- .../features/editor/inference/face.worker.ts | 5 +++ 3 files changed, 42 insertions(+), 13 deletions(-) diff --git a/apps/app/scripts/fetch-models.ts b/apps/app/scripts/fetch-models.ts index 501eba6..2dcdebb 100644 --- a/apps/app/scripts/fetch-models.ts +++ b/apps/app/scripts/fetch-models.ts @@ -1,5 +1,5 @@ /** - * ブラウザ内の認識 (ADR-0025) に使うモデルと WASM を public/models/-v/ に揃える。 + * ブラウザ内の認識 (ADR-0025) に使うモデルと WASM を apps/app/models/-v/ に揃える。 * dev と build の前に走る (package.json)。git には入れない (.gitignore)。 * * - ダウンロードするものは URL と sha256 を固定する。ハッシュが合わなければ捨てて失敗する @@ -8,16 +8,20 @@ * - 既にあってハッシュが合えば何もしない (2 回目以降は一瞬で終わる) */ import { createHash } from "node:crypto"; -import { access, copyFile, mkdir, readFile, writeFile } from "node:fs/promises"; +import { access, mkdir, readFile, writeFile } from "node:fs/promises"; import path from "node:path"; const root = path.resolve(import.meta.dirname, ".."); -const out = path.join(root, "public", "models"); +/** public/ ではなく models/ に置き、/models/ は Fastify の static で配る (server/plugins/models.ts)。 + * public/ に置くと dev の Vite が import() に ?import を足して「URL を export するモジュール」に変え、 + * MediaPipe の WASM ローダーが読めない */ +export const MODELS_DIR = path.join(root, "models"); +const out = MODELS_DIR; type Download = { kind: "download"; to: string; url: string; sha256: string }; -type Copy = { kind: "copy"; to: string; from: string }; +type Copy = { kind: "copy"; to: string; from: string; prepend?: string; append?: string }; -/** 配るもの。to は public/models/ からの相対パス */ +/** 配るもの。to は models/ からの相対パス */ const ASSETS: (Download | Copy)[] = [ // MediaPipe Face Landmarker (瞳・顔、#176)。Apache-2.0 { @@ -35,6 +39,18 @@ const ASSETS: (Download | Copy)[] = [ kind: "copy", to: `face-landmarker-v1/wasm/${f}`, from: path.join(root, "node_modules", "@mediapipe", "tasks-vision", "wasm", f), + // ローダー (.js) は classic script (sloppy mode) 前提。module worker からは MediaPipe が import() で + // 読む (importScripts が使えない) ので、ES module (strict mode) でも動くように 2 か所を補う: + // - `var ModuleFactory` は module スコープに閉じるので、末尾で self に出す + // - if ブロック内の `function custom_dbg` は strict では外に見えないので、先頭で self に置く + // classic worker (importScripts) で読んでも害はない + ...(f.endsWith(".js") + ? { + prepend: + 'if (typeof self.custom_dbg === "undefined") self.custom_dbg = (...a) => console.warn(...a);\n', + append: "\n;self.ModuleFactory = ModuleFactory;\n", + } + : {}), })), // SlimSAM (装備・人物の切り抜き、#177)。Xenova/slimsam-77-uniform の q8。Apache-2.0 ...( @@ -96,11 +112,18 @@ async function download(asset: Download): Promise { async function copy(asset: Copy): Promise { const target = path.join(out, asset.to); - const [a, b] = await Promise.all([sha256(target), sha256(asset.from)]); - if (b === null) throw new Error(`models: missing ${asset.from} (pnpm install を先に)`); - if (a === b) return; + let body: Buffer; + try { + body = await readFile(asset.from); + } catch { + throw new Error(`models: missing ${asset.from} (pnpm install を先に)`); + } + if (asset.prepend) body = Buffer.concat([Buffer.from(asset.prepend), body]); + if (asset.append) body = Buffer.concat([body, Buffer.from(asset.append)]); + const want = createHash("sha256").update(body).digest("hex"); + if ((await sha256(target)) === want) return; await mkdir(path.dirname(target), { recursive: true }); - await copyFile(asset.from, target); + await writeFile(target, body); } await mkdir(out, { recursive: true }); @@ -108,7 +131,7 @@ for (const asset of ASSETS) { if (asset.kind === "download") await download(asset); else await copy(asset); } -// public/ の中で git に入れないことを、ディレクトリ自身にも書いておく +// git に入れないことを、ディレクトリ自身にも書いておく try { await access(path.join(out, ".gitignore")); } catch { diff --git a/apps/app/web/features/editor/inference/face.ts b/apps/app/web/features/editor/inference/face.ts index 971cdc2..2ed889b 100644 --- a/apps/app/web/features/editor/inference/face.ts +++ b/apps/app/web/features/editor/inference/face.ts @@ -17,9 +17,10 @@ let seq = 0; function getWorker(): Worker { if (!worker) { - // classic worker (Vite が iife に束ねる)。MediaPipe の WASM ローダーは importScripts で - // vision_wasm_internal.js を読むので、module worker だと "ModuleFactory not set" で落ちる - worker = new Worker(new URL("./face.worker.ts", import.meta.url)); + // module worker (dev の Vite は classic worker に import 文を残すので動かない)。MediaPipe は + // module worker では WASM ローダーを import() で読み、そのままだと "ModuleFactory not set" になる。 + // fetch-models.ts がローダーの末尾に self.ModuleFactory = ModuleFactory を足して通している + worker = new Worker(new URL("./face.worker.ts", import.meta.url), { type: "module" }); } return worker; } diff --git a/apps/app/web/features/editor/inference/face.worker.ts b/apps/app/web/features/editor/inference/face.worker.ts index 2ffa7f8..0f21e18 100644 --- a/apps/app/web/features/editor/inference/face.worker.ts +++ b/apps/app/web/features/editor/inference/face.worker.ts @@ -98,6 +98,11 @@ async function fetchWithProgress( function load(confidence: number, onProgress: (loaded: number) => void): Promise { if (landmarker) return Promise.resolve(landmarker); if (loading) return loading; + // module worker では MediaPipe が WASM ローダーを self.import ?? import() で読む。dev の Vite は + // 素の import() に ?import を足して public のファイルを「URL を export するモジュール」に変えて + // しまうので、Vite の書き換えを避けた import を渡す (本番ビルドでは同じ動き) + (self as unknown as { import?: (url: string) => Promise }).import = (url) => + import(/* @vite-ignore */ url); loading = (async () => { const model = await fetchWithProgress(`${FACE_MODEL_BASE}/face_landmarker.task`, onProgress); const vision = await FilesetResolver.forVisionTasks(`${FACE_MODEL_BASE}/wasm`); From cda9db337d27bd0726055117e1e15141a7784ba8 Mon Sep 17 00:00:00 2001 From: t1nyb0x Date: Mon, 21 Sep 2026 14:52:45 +0900 Subject: [PATCH 32/49] feat: add English locale support (Closes lumorphia/prismtone#61) --- .../web/features/editor/ui/AdjustPanel.tsx | 4 +- .../web/features/editor/ui/CompareSlider.tsx | 11 ++- .../app/web/features/editor/ui/EditorPage.tsx | 66 +++++++------ .../web/features/editor/ui/GeometryPanel.tsx | 18 ++-- .../app/web/features/editor/ui/LocalPanel.tsx | 92 ++++++++++++------- .../web/features/editor/ui/PortraitPanel.tsx | 60 ++++++++---- .../web/features/editor/ui/PresetPanel.tsx | 4 +- .../app/web/features/editor/ui/TapOverlay.tsx | 4 +- apps/app/web/features/i18n/messages.ts | 42 +++++++++ 9 files changed, 210 insertions(+), 91 deletions(-) create mode 100644 apps/app/web/features/i18n/messages.ts diff --git a/apps/app/web/features/editor/ui/AdjustPanel.tsx b/apps/app/web/features/editor/ui/AdjustPanel.tsx index 0001208..1ec9a91 100644 --- a/apps/app/web/features/editor/ui/AdjustPanel.tsx +++ b/apps/app/web/features/editor/ui/AdjustPanel.tsx @@ -1,6 +1,7 @@ import type { AdjustV1 } from "@prismtone/shared/recipe"; import { ADJUST_LABELS } from "../labels.ts"; import { Slider } from "./Slider.tsx"; +import { useI18n } from "../../i18n/I18nProvider.tsx"; type Props = { adjust: AdjustV1; @@ -27,12 +28,13 @@ const ROWS: { ]; export function AdjustPanel({ adjust, onPreview, onCommit }: Props) { + const { tx } = useI18n(); return (
{ROWS.map((r) => ( void; }) { + const { t } = useI18n(); const dragging = useRef(false); const toPosition = (clientX: number, el: HTMLElement) => { const rect = el.getBoundingClientRect(); @@ -46,13 +48,13 @@ export function CompareSlider({ className="pointer-events-none absolute top-2 left-2 rounded bg-black/55 px-1.5 py-0.5 text-xs text-white" aria-hidden="true" > - 元画像 + {t("元画像", "Original")}
onChange(Number(e.currentTarget.value) / 1000)} - aria-label="比較の境界 (左が元画像、右が現像後)" + aria-label={t( + "比較の境界 (左が元画像、右が現像後)", + "Comparison boundary (original on left, edited on right)", + )} className="absolute inset-x-0 bottom-0 h-6 w-full cursor-ew-resize opacity-0" data-testid="compare-range" /> diff --git a/apps/app/web/features/editor/ui/EditorPage.tsx b/apps/app/web/features/editor/ui/EditorPage.tsx index 5c33ed1..3a450f2 100644 --- a/apps/app/web/features/editor/ui/EditorPage.tsx +++ b/apps/app/web/features/editor/ui/EditorPage.tsx @@ -36,6 +36,7 @@ import { type PortraitPresetId, } from "@prismtone/shared/recipe"; import { CompareSlider } from "./CompareSlider.tsx"; +import { useI18n } from "../../i18n/I18nProvider.tsx"; const ERROR_TEXT: Record = { too_large: "30MB を超える画像は読み込めません。", @@ -83,6 +84,7 @@ function installTestHook(renderer: EditorRenderer, getRecipe: () => EditRecipe) } export function EditorPage() { + const { t } = useI18n(); const [state, dispatch] = useReducer(editorReducer, initialEditorState); const navigate = useNavigate(); const [searchParams, setSearchParams] = useSearchParams(); @@ -452,7 +454,7 @@ export function EditorPage() { a.click(); setTimeout(() => URL.revokeObjectURL(a.href), 10_000); } catch { - dispatch({ type: "ui/error", error: "書き出しに失敗しました。" }); + dispatch({ type: "ui/error", error: t("書き出しに失敗しました。", "Export failed.") }); } }; @@ -465,7 +467,8 @@ export function EditorPage() { } catch (error) { dispatch({ type: "ui/error", - error: error instanceof Error ? error.message : "書き出しに失敗しました。", + error: + error instanceof Error ? error.message : t("書き出しに失敗しました。", "Export failed."), }); } }; @@ -510,8 +513,12 @@ export function EditorPage() { const canExport = hasImage && ready && !state.ui.exporting; const lastOp = undoLabel(state.history); const nextOp = redoLabel(state.history); - const undoTitle = lastOp ? `${lastOp} を取り消す (Ctrl+Z)` : "取り消す操作はありません"; - const redoTitle = nextOp ? `${nextOp} をやり直す (Ctrl+Shift+Z)` : "やり直す操作はありません"; + const undoTitle = lastOp + ? t(`${lastOp} を取り消す (Ctrl+Z)`, `Undo ${lastOp} (Ctrl+Z)`) + : t("取り消す操作はありません", "Nothing to undo"); + const redoTitle = nextOp + ? t(`${nextOp} をやり直す (Ctrl+Shift+Z)`, `Redo ${nextOp} (Ctrl+Shift+Z)`) + : t("やり直す操作はありません", "Nothing to redo"); const canvasRatio = rendererRef.current ? rendererRef.current.canvasSize.width / rendererRef.current.canvasSize.height : 1; @@ -534,7 +541,7 @@ export function EditorPage() { }} /> {lastOp && ( - 最後の操作: {lastOp} + {t("最後の操作", "Last action")}: {lastOp} )}
{state.ui.error && ( @@ -667,7 +674,10 @@ export function EditorPage() { > {!hasImage && (

- PNG / JPEG をドロップするか「画像を開く」を押してください + {t( + "PNG / JPEG をドロップするか「画像を開く」を押してください", + "Drop a PNG or JPEG here, or select Open image", + )}

)} {hasImage && state.ui.comparing && !state.ui.cropping && ( @@ -730,7 +740,9 @@ export function EditorPage() { source={{ width: state.source.bitmap.width, height: state.source.bitmap.height }} geometry={recipe.geometry} hint={ - state.ui.local.tap === "gear" ? "切りたい装備をタップ" : "キャラクターをタップ" + state.ui.local.tap === "gear" + ? t("切りたい装備をタップ", "Tap the item to select") + : t("キャラクターをタップ", "Tap the character") } onTap={(uv) => void onTap(uv)} onCancel={() => dispatch({ type: "ui/tap", tap: null })} @@ -768,11 +780,11 @@ export function EditorPage() {
{( [ - ["presets", "プリセット"], - ["adjust", "補正"], - ["portrait", "人物補正"], - ["local", "部分補正"], - ["geometry", "幾何"], + ["presets", t("プリセット", "Presets")], + ["adjust", t("補正", "Adjust")], + ["portrait", t("人物補正", "Portrait")], + ["local", t("部分補正", "Local")], + ["geometry", t("幾何", "Geometry")], ] as const ).map(([tool, label]) => (
onCommit({ straighten: 0 })} />
-

アスペクト比

+

{t("アスペクト比", "Aspect ratio")}

{ASPECT_PRESETS.map((a) => ( ))}
@@ -88,7 +90,7 @@ export function GeometryPanel({ aria-pressed={cropping} onClick={() => onCropping(!cropping)} > - {cropping ? "トリミング中" : "トリミング"} + {cropping ? t("トリミング中", "Cropping") : t("トリミング", "Crop")} {geometry.crop && ( )}
diff --git a/apps/app/web/features/editor/ui/LocalPanel.tsx b/apps/app/web/features/editor/ui/LocalPanel.tsx index 3220c42..70eefe1 100644 --- a/apps/app/web/features/editor/ui/LocalPanel.tsx +++ b/apps/app/web/features/editor/ui/LocalPanel.tsx @@ -11,6 +11,7 @@ import type { BrushSettings, EditorState, InferenceStatus } from "../state.ts"; import type { SegmentSelectionKind } from "../inference/auto-select.ts"; import { SAM_LEVELS } from "../inference/segment-masks.ts"; import { Slider } from "./Slider.tsx"; +import { useI18n } from "../../i18n/I18nProvider.tsx"; type Props = { list: readonly LocalAdjustment[]; @@ -78,6 +79,7 @@ function localName(l: LocalAdjustment, index: number): string { /** 部分補正のパネル (#109): 一覧、追加 (円形 / ブラシ)、ブラシの設定、プリセット、効果量とスライダー */ export function LocalPanel(p: Props) { + const { t, tx } = useI18n(); const selected = p.list.find((l) => l.id === p.selectedId) ?? null; const full = p.list.length >= MAX_LOCAL_ADJUSTMENTS; const busy = p.inference.status !== "idle"; @@ -91,7 +93,7 @@ export function LocalPanel(p: Props) { onClick={() => p.onAdd("ellipse")} data-testid="local-add-ellipse" > - 円形を追加 + {t("円形を追加", "Add ellipse")} {p.list.length} / {MAX_LOCAL_ADJUSTMENTS} @@ -112,23 +114,29 @@ export function LocalPanel(p: Props) { checked={p.showMask} onChange={(e) => p.onShowMask(e.currentTarget.checked)} /> - 範囲を表示 + {t("範囲を表示", "Show mask")}
{p.list.length === 0 ? (

- 範囲を選んで、そこだけに補正を掛けます。「円形を追加」で始めるか、プリセットを選んでください。 + {t( + "範囲を選んで、そこだけに補正を掛けます。「円形を追加」で始めるか、プリセットを選んでください。", + "Select an area to adjust only that part. Add an ellipse or choose a preset to begin.", + )}

) : (
    p.onToggleVisible(l.id)} > - {l.visible ? "表示中" : "非表示"} + {l.visible ? t("表示中", "Visible") : t("非表示", "Hidden")} ))} @@ -175,7 +183,9 @@ export function LocalPanel(p: Props) { {selected && selected.mask.kind !== "ellipse" && (
    - キャンバスをなぞって範囲を塗る + + {t("キャンバスをなぞって範囲を塗る", "Paint an area on the canvas")} + {( [ @@ -190,12 +200,12 @@ export function LocalPanel(p: Props) { aria-pressed={p.brush.mode === mode} onClick={() => p.onBrush({ ...p.brush, mode })} > - {label} + {label === "塗る" ? t("塗る", "Paint") : t("消す", "Erase")} ))}
    p.onBrush({ ...p.brush, size: v / 100 })} />

    {selected - ? "選択中の範囲に適用" + ? t("選択中の範囲に適用", "Apply to selected area") : p.onAuto - ? "瞳・美肌は顔を認識して置き、装備は画像をタップして切り抜きます" - : "新しいマスクを追加して適用 (瞳・美肌は円形、装備はブラシ)"} + ? t( + "瞳・美肌は顔を認識して置き、装備は画像をタップして切り抜きます", + "Eyes and skin use face detection; tap the image to select gear.", + ) + : t( + "新しいマスクを追加して適用 (瞳・美肌は円形、装備はブラシ)", + "Add a new mask (ellipse for eyes or skin, brush for gear)", + )}

    {LOCAL_PRESETS.map((preset) => ( @@ -231,7 +247,7 @@ export function LocalPanel(p: Props) { type="button" className={btn + " aria-pressed:bg-accent aria-pressed:text-accent-ink"} aria-pressed={selected?.presetId === preset.id} - title={preset.hint} + title={tx(preset.hint)} disabled={(!selected && full) || busy} onClick={() => { if (selected) return p.onPreset(selected.id, preset.id); @@ -239,13 +255,15 @@ export function LocalPanel(p: Props) { p.onAdd(preset.id === "gear" ? "brush" : "ellipse", preset.id); }} > - {preset.name} + {tx(preset.name)} ))}
    {p.onAuto && !selected && (
    - タップで範囲だけ選ぶ: + + {t("タップで範囲だけ選ぶ:", "Select an area by tapping:")} +
    )} {p.tap && (

    - 画像の中の{p.tap === "gear" ? "装備" : "キャラクター"}をタップしてください + {t( + `画像の中の${p.tap === "gear" ? "装備" : "キャラクター"}をタップしてください`, + `Tap the ${p.tap === "gear" ? "gear" : "character"} in the image`, + )}

    )} {selected && p.segment?.localId === selected.id && p.onSegmentLevel && (
    - 切り抜きの範囲: + + {t("切り抜きの範囲:", "Selection scope:")} + {SAM_LEVELS.map((level) => ( ))}
    @@ -294,22 +317,25 @@ export function LocalPanel(p: Props) { {busy && (

    {p.inference.status === "loading" && p.inference.progress - ? `認識用のデータを読み込んでいます (${Math.round((p.inference.progress.loaded / p.inference.progress.total) * 100)}%)` + ? t( + `認識用のデータを読み込んでいます (${Math.round((p.inference.progress.loaded / p.inference.progress.total) * 100)}%)`, + `Loading detection data (${Math.round((p.inference.progress.loaded / p.inference.progress.total) * 100)}%)`, + ) : p.inference.status === "loading" - ? "認識の準備をしています…" - : "画像を読み取っています…"} + ? t("認識の準備をしています…", "Preparing detection…") + : t("画像を読み取っています…", "Analyzing image…")}

    )} {p.notice && !busy && (

    - {p.notice} + {tx(p.notice)}

    )}
    {selected && (
    (

    - 人物を認識して、顔・瞳・人物・背景をまとめて整えます。認識も補正もこの端末の中だけで行います。 + {t( + "人物を認識して、顔・瞳・人物・背景をまとめて整えます。認識も補正もこの端末の中だけで行います。", + "Detect a person and adjust their face, eyes, body, and background together. Detection and editing stay on this device.", + )}

    {p.faces === null ? ( ) : faces.length === 0 ? (

    - {p.notice ?? "自動選択できませんでした。手動で範囲を指定できます"} + {p.notice + ? tx(p.notice) + : t( + "自動選択できませんでした。手動で範囲を指定できます", + "Automatic selection failed. You can select an area manually.", + )}

    ) : ( <> {faces.length > 1 && (
    - 補正する人物: + {t("補正する人物:", "Person:")} {faces.map((_, i) => (
    )}

    - {p.groupId ? "プリセットを切り替える" : "プリセットを選ぶと補正を置きます"} + {p.groupId + ? t("プリセットを切り替える", "Switch preset") + : t("プリセットを選ぶと補正を置きます", "Choose a preset to apply adjustments")}

    {PORTRAIT_PRESETS.map((preset) => ( @@ -88,11 +105,11 @@ export function PortraitPanel(p: Props) { : "border-line-soft hover:bg-surface-hover disabled:opacity-40") } aria-pressed={preset.id === p.presetId} - title={preset.hint} + title={tx(preset.hint)} disabled={busy} onClick={() => p.onApply(preset.id)} > - {preset.name} + {tx(preset.name)} ))}
    @@ -100,7 +117,7 @@ export function PortraitPanel(p: Props) { {p.groupId && (
    p.onAmountCommit(100)} />

    - 顔・瞳・人物・背景のマスクは + {t( + "顔・瞳・人物・背景のマスクは", + "Edit the face, eyes, person, and background masks under", + )}{" "} - で個別に直せます (ブラシで足す / 消す、値の調整)。 + {t( + "で個別に直せます (ブラシで足す / 消す、値の調整)。", + " (paint, erase, or adjust individual values).", + )}

    )} @@ -123,15 +146,18 @@ export function PortraitPanel(p: Props) { {busy && (

    {p.inference.status === "loading" && p.inference.progress - ? `認識用のデータを読み込んでいます (${Math.round((p.inference.progress.loaded / p.inference.progress.total) * 100)}%)` + ? t( + `認識用のデータを読み込んでいます (${Math.round((p.inference.progress.loaded / p.inference.progress.total) * 100)}%)`, + `Loading detection data (${Math.round((p.inference.progress.loaded / p.inference.progress.total) * 100)}%)`, + ) : p.inference.status === "loading" - ? "認識の準備をしています…" - : "人物を認識しています…"} + ? t("認識の準備をしています…", "Preparing detection…") + : t("人物を認識しています…", "Detecting people…")}

    )} {p.notice && !busy && faces.length > 0 && (

    - {p.notice} + {tx(p.notice)}

    )}
    diff --git a/apps/app/web/features/editor/ui/PresetPanel.tsx b/apps/app/web/features/editor/ui/PresetPanel.tsx index c39e0bb..2ea5110 100644 --- a/apps/app/web/features/editor/ui/PresetPanel.tsx +++ b/apps/app/web/features/editor/ui/PresetPanel.tsx @@ -1,4 +1,5 @@ import { PRESETS } from "@prismtone/shared/recipe"; +import { useI18n } from "../../i18n/I18nProvider.tsx"; type Props = { activeId: string | null; @@ -6,6 +7,7 @@ type Props = { }; export function PresetPanel({ activeId, onApply }: Props) { + const { tx } = useI18n(); return (
    {PRESETS.map((p) => { @@ -23,7 +25,7 @@ export function PresetPanel({ activeId, onApply }: Props) { : "border-line-soft hover:bg-surface-hover") } > - {p.name} + {tx(p.name)} ); })} diff --git a/apps/app/web/features/editor/ui/TapOverlay.tsx b/apps/app/web/features/editor/ui/TapOverlay.tsx index bb4124f..3549bea 100644 --- a/apps/app/web/features/editor/ui/TapOverlay.tsx +++ b/apps/app/web/features/editor/ui/TapOverlay.tsx @@ -2,6 +2,7 @@ import { useEffect } from "react"; import type { GeometryV1 } from "@prismtone/shared/recipe"; import { canvasToImageUv, type Point } from "../mask-math.ts"; import type { Size } from "../render/geometry.ts"; +import { useI18n } from "../../i18n/I18nProvider.tsx"; type View = { x: number; y: number; width: number; height: number; scale: number }; @@ -22,6 +23,7 @@ type Props = { * 画像の外をタップしたら無視する */ export function TapOverlay({ view, source, geometry, hint, onTap, onCancel }: Props) { + const { t } = useI18n(); useEffect(() => { const onKey = (e: KeyboardEvent) => { if (e.key === "Escape") onCancel(); @@ -50,7 +52,7 @@ export function TapOverlay({ view, source, geometry, hint, onTap, onCancel }: Pr className="pointer-events-none absolute left-1/2 top-3 -translate-x-1/2 rounded bg-black/60 px-3 py-1 text-sm text-white" role="status" > - {hint} (Esc でやめる) + {hint} {t("(Esc でやめる)", "(press Esc to cancel)")}

    ); diff --git a/apps/app/web/features/i18n/messages.ts b/apps/app/web/features/i18n/messages.ts new file mode 100644 index 0000000..65f6a40 --- /dev/null +++ b/apps/app/web/features/i18n/messages.ts @@ -0,0 +1,42 @@ +import type { Locale } from "./locale.ts"; + +const EN: Readonly> = { + 露光量: "Exposure", + コントラスト: "Contrast", + ハイライト: "Highlights", + シャドウ: "Shadows", + 色温度: "Temperature", + 色かぶり: "Tint", + 自然な彩度: "Vibrance", + 彩度: "Saturation", + シャープ: "Sharpen", + 美肌: "Smooth skin", + 夜景: "Night", + 夕暮れ: "Sunset", + 朝霧: "Cool morning", + パステル: "Pastel", + ビビッド: "Vivid", + フィルム: "Film", + モノクロ: "Monochrome", + ソフト: "Soft", + ダンジョン: "Dungeon", + ゴールド: "Gold", + 瞳強調: "Enhance eyes", + 装備強調: "Enhance gear", + ナチュラル: "Natural", + 明るく: "Bright", + ドラマチック: "Dramatic", + やわらか: "Soft", + 瞳くっきり: "Bright eyes", + 円形: "Ellipse", + ブラシ: "Brush", + 多角形: "Polygon", + 切り抜き: "Selection", + 全体: "Whole character", + 装備: "Gear", + 部品: "Detail", +}; + +export function translateKnown(locale: Locale, value: string): string { + return locale === "en" ? (EN[value] ?? value) : value; +} From 8350701d9ea381436a05142ae143564cdf88edc1 Mon Sep 17 00:00:00 2001 From: t1nyb0x Date: Tue, 22 Sep 2026 02:44:49 +0900 Subject: [PATCH 33/49] =?UTF-8?q?feat:=20=E4=BA=BA=E7=89=A9=E8=A3=9C?= =?UTF-8?q?=E6=AD=A3=E3=81=AB=E7=A9=BA=E9=96=93=E5=8A=B9=E6=9E=9C=E3=82=92?= =?UTF-8?q?=E8=BF=BD=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Recipe v4 に背景ぼかし・発光・周辺減光・質感を追加する。 GLSL と CPU 参照実装を揃え、人物プリセットと 4K 性能計測を更新する。 Closes lumorphia/prismtone#184 --- .../web/features/editor/adjust-math.test.ts | 70 ++++++++ apps/app/web/features/editor/adjust-math.ts | 104 ++++++++++-- apps/app/web/features/editor/labels.test.ts | 2 + apps/app/web/features/editor/labels.ts | 13 +- .../editor/render/local-adjust-filter.ts | 48 +++++- apps/app/web/features/editor/state.ts | 10 +- .../app/web/features/editor/ui/LocalPanel.tsx | 17 +- apps/app/web/features/i18n/messages.ts | 4 + e2e/editor.spec.ts | 59 +++++++ e2e/perf-local-adjust.spec.ts | 17 +- packages/shared/src/recipe/local-presets.ts | 22 ++- packages/shared/src/recipe/migrate.ts | 51 +++++- .../src/recipe/portrait-presets.test.ts | 15 +- .../shared/src/recipe/portrait-presets.ts | 49 ++++-- packages/shared/src/recipe/recipe.test.ts | 155 +++++++++++++++--- packages/shared/src/recipe/schema.ts | 53 +++++- 16 files changed, 593 insertions(+), 96 deletions(-) diff --git a/apps/app/web/features/editor/adjust-math.test.ts b/apps/app/web/features/editor/adjust-math.test.ts index 0a6cf09..1a92a9a 100644 --- a/apps/app/web/features/editor/adjust-math.test.ts +++ b/apps/app/web/features/editor/adjust-math.test.ts @@ -155,4 +155,74 @@ describe("applyRecipeAt (部分補正の CPU 参照、#109)", () => { ); expect(applyRecipeAt(px, { x: 0.25, y: 0.5 }, recipe, size)).toEqual(px); }); + + it("blurs with a radius measured in source pixels", () => { + const recipe = { + ...DEFAULT_RECIPE, + localAdjustments: [ + { + ...eye, + mask: { ...DEFAULT_ELLIPSE_MASK, cx: 0.5, cy: 0.5, rx: 1, ry: 1, feather: 0 }, + adjust: { ...DEFAULT_LOCAL_ADJUST, blur: 10 }, + }, + ], + }; + const source = ({ x }: { x: number; y: number }): RGB => (x < 0.5 ? [1, 1, 1] : [0, 0, 0]); + const out = applyRecipeAt(source, { x: 0.5, y: 0.5 }, recipe, size); + expect(out[0]).toBeGreaterThan(0); + expect(out[0]).toBeLessThan(1); + }); + + it("adds bloom from bright neighbouring pixels", () => { + const recipe = { + ...DEFAULT_RECIPE, + localAdjustments: [ + { + ...eye, + mask: { ...DEFAULT_ELLIPSE_MASK, cx: 0.5, cy: 0.5, rx: 1, ry: 1, feather: 0 }, + adjust: { ...DEFAULT_LOCAL_ADJUST, bloom: 100 }, + }, + ], + }; + const source = ({ x }: { x: number; y: number }): RGB => + x < 0.5 ? [1, 1, 1] : [0.1, 0.1, 0.1]; + const out = applyRecipeAt(source, { x: 0.51, y: 0.5 }, recipe, size); + expect(out[0]).toBeGreaterThan(0.1); + }); + + it("darkens image corners with vignette while preserving the centre", () => { + const recipe = { + ...DEFAULT_RECIPE, + localAdjustments: [ + { + ...eye, + mask: { ...DEFAULT_ELLIPSE_MASK, cx: 0.5, cy: 0.5, rx: 1, ry: 1, feather: 0 }, + adjust: { ...DEFAULT_LOCAL_ADJUST, vignette: 100 }, + }, + ], + }; + const centre = applyRecipeAt([0.7, 0.7, 0.7], { x: 0.5, y: 0.5 }, recipe, size); + const corner = applyRecipeAt([0.7, 0.7, 0.7], { x: 0, y: 0 }, recipe, size); + expect(centre[0]).toBeCloseTo(0.7); + expect(corner[0]).toBeLessThan(centre[0]); + }); + + it("increases or decreases local contrast with clarity", () => { + const source = ({ x }: { x: number; y: number }): RGB => + x < 0.5 ? [0.8, 0.8, 0.8] : [0.4, 0.4, 0.4]; + const withClarity = (clarity: number) => ({ + ...DEFAULT_RECIPE, + localAdjustments: [ + { + ...eye, + mask: { ...DEFAULT_ELLIPSE_MASK, cx: 0.5, cy: 0.5, rx: 1, ry: 1, feather: 0 }, + adjust: { ...DEFAULT_LOCAL_ADJUST, clarity }, + }, + ], + }); + const sharp = applyRecipeAt(source, { x: 0.49, y: 0.5 }, withClarity(100), size); + const soft = applyRecipeAt(source, { x: 0.49, y: 0.5 }, withClarity(-100), size); + expect(sharp[0]).toBeGreaterThan(0.8); + expect(soft[0]).toBeLessThan(0.8); + }); }); diff --git a/apps/app/web/features/editor/adjust-math.ts b/apps/app/web/features/editor/adjust-math.ts index c136b9a..3bc3512 100644 --- a/apps/app/web/features/editor/adjust-math.ts +++ b/apps/app/web/features/editor/adjust-math.ts @@ -1,4 +1,4 @@ -import type { AdjustV1, EditRecipe, LocalAdjustV2 } from "@prismtone/shared/recipe"; +import type { AdjustV1, EditRecipe, LocalAdjust } from "@prismtone/shared/recipe"; import type { Point } from "./mask-math.ts"; import { maskValue } from "./brush-raster.ts"; import type { Size } from "./render/geometry.ts"; @@ -10,6 +10,11 @@ import type { Size } from "./render/geometry.ts"; */ export type RGB = readonly [number, number, number]; +export type ImageSampler = (uv: Point) => RGB; + +const BLOOM_RADIUS_PX = 8; +const CLARITY_RADIUS_PX = 4; +const BLOOM_THRESHOLD = 0.65; export function srgbToLinear(c: number): number { return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4); @@ -94,27 +99,98 @@ export function applyAdjust(input: RGB, adjust: AdjustV1): RGB { /** * 部分補正の色調整。全体の補正と同じ式で vibrance だけ無い (#109)。 - * sharpen / smooth は近傍を見る処理なので、この点ごとの参照実装には含めない - * (E2E の判定点はマスク内の平坦部とマスク外に限る、docs/design/08 §7) + * sharpen / smooth は既存テストとの互換のため点ごとの参照には含めない。#184 の空間効果は + * context があるとき 3x3 の近傍を参照し、GLSL と同じ式で計算する。 */ -export function applyLocalAdjust(input: RGB, adjust: LocalAdjustV2): RGB { - const { sharpen: _sharpen, smooth: _smooth, ...rest } = adjust; - return applyAdjust(input, { ...rest, vibrance: 0 }); +export function applyLocalAdjust( + input: RGB, + adjust: LocalAdjust, + context?: { uv: Point; sampleOffset: (dx: number, dy: number) => RGB }, +): RGB { + const { sharpen: _sharpen, smooth: _smooth, blur, bloom, vignette, clarity, ...rest } = adjust; + let spatial: RGB = input; + const radius = Math.max( + blur, + bloom > 0 ? BLOOM_RADIUS_PX : 0, + clarity !== 0 ? CLARITY_RADIUS_PX : 0, + ); + let average: RGB = input; + let glow: RGB = [0, 0, 0]; + if (context && radius > 0) { + const sum = [0, 0, 0]; + const bright = [0, 0, 0]; + for (const y of [-1, 0, 1]) { + for (const x of [-1, 0, 1]) { + const sampled = context.sampleOffset(x * radius, y * radius); + for (let channel = 0; channel < 3; channel += 1) { + const value = sampled[channel]!; + sum[channel] = sum[channel]! + value; + bright[channel] = + bright[channel]! + Math.max(0, value - BLOOM_THRESHOLD) / (1 - BLOOM_THRESHOLD); + } + } + } + average = [sum[0]! / 9, sum[1]! / 9, sum[2]! / 9]; + glow = [bright[0]! / 9, bright[1]! / 9, bright[2]! / 9]; + } + if (blur > 0 && context) spatial = average; + if (clarity !== 0 && context) { + const strength = clarity / 100; + spatial = spatial.map((value, channel) => + clamp01(value + (input[channel]! - average[channel]!) * strength), + ) as unknown as RGB; + } + if (bloom > 0 && context) { + const strength = (bloom / 100) * 0.5; + spatial = spatial.map((value, channel) => + clamp01(value + glow[channel]! * strength), + ) as unknown as RGB; + } + let adjusted = applyAdjust(spatial, { ...rest, vibrance: 0 }); + if (vignette > 0 && context) { + const px = (context.uv.x - 0.5) * 2; + const py = (context.uv.y - 0.5) * 2; + const distance = (px * px + py * py) / 2; + const shade = 1 - (vignette / 100) * 0.65 * smoothstep(0.2, 1, distance); + adjusted = adjusted.map((value) => clamp01(value * shade)) as unknown as RGB; + } + return adjusted; } /** * レシピ全体を 1 画素に適用する参照実装: 全体の補正 → 部分補正を順に。 * uv は幾何を掛ける前の画像の正規化座標 */ -export function applyRecipeAt(input: RGB, uv: Point, recipe: EditRecipe, size: Size): RGB { - let rgb = applyAdjust(input, recipe.adjust); +export function applyRecipeAt( + input: RGB | ImageSampler, + uv: Point, + recipe: EditRecipe, + size: Size, +): RGB { + const source: ImageSampler = typeof input === "function" ? input : () => input; + let stage: ImageSampler = (point) => applyAdjust(source(point), recipe.adjust); for (const local of recipe.localAdjustments) { if (!local.visible) continue; - const mask = maskValue(uv, local.mask, size); - const m = mask * (local.amount / 100); - if (m <= 0) continue; - const adjusted = applyLocalAdjust(rgb, local.adjust); - rgb = [mix(rgb[0], adjusted[0], m), mix(rgb[1], adjusted[1], m), mix(rgb[2], adjusted[2], m)]; + const previous = stage; + stage = (point) => { + const rgb = previous(point); + const mask = maskValue(point, local.mask, size); + const m = mask * (local.amount / 100); + if (m <= 0) return rgb; + const adjusted = applyLocalAdjust(rgb, local.adjust, { + uv: point, + sampleOffset: (dx, dy) => + previous({ + x: clamp01(point.x + dx / size.width), + y: clamp01(point.y + dy / size.height), + }), + }); + return [ + mix(rgb[0], adjusted[0], m), + mix(rgb[1], adjusted[1], m), + mix(rgb[2], adjusted[2], m), + ]; + }; } - return rgb; + return stage(uv); } diff --git a/apps/app/web/features/editor/labels.test.ts b/apps/app/web/features/editor/labels.test.ts index a529327..9756b40 100644 --- a/apps/app/web/features/editor/labels.test.ts +++ b/apps/app/web/features/editor/labels.test.ts @@ -22,6 +22,8 @@ describe("localAdjustLabel (#109)", () => { it("prefixes the item with 部分補正 and formats exposure to two decimals", () => { expect(localAdjustLabel("exposure", 0.35)).toBe("部分補正: 露光量 +0.35"); expect(localAdjustLabel("shadows", -20)).toBe("部分補正: シャドウ -20"); + expect(localAdjustLabel("blur", 8)).toBe("部分補正: 背景ぼかし 8px"); + expect(localAdjustLabel("clarity", -25)).toBe("部分補正: 質感 -25"); }); }); diff --git a/apps/app/web/features/editor/labels.ts b/apps/app/web/features/editor/labels.ts index 5a27e2b..66861c3 100644 --- a/apps/app/web/features/editor/labels.ts +++ b/apps/app/web/features/editor/labels.ts @@ -2,7 +2,7 @@ import { LOCAL_PRESETS, type AdjustV1, type GeometryV1, - type LocalAdjustV2, + type LocalAdjust, type LocalAdjustment, } from "@prismtone/shared/recipe"; @@ -18,8 +18,8 @@ export const ADJUST_LABELS: Readonly> = { saturation: "彩度", }; -/** 部分補正の項目名 (#109)。全体と同じ名前に、シャープと美肌を足す */ -export const LOCAL_ADJUST_LABELS: Readonly> = { +/** 部分補正の項目名 (#109, #184) */ +export const LOCAL_ADJUST_LABELS: Readonly> = { exposure: "露光量", contrast: "コントラスト", highlights: "ハイライト", @@ -29,6 +29,10 @@ export const LOCAL_ADJUST_LABELS: Readonly> saturation: "彩度", sharpen: "シャープ", smooth: "美肌", + blur: "背景ぼかし", + bloom: "発光", + vignette: "周辺減光", + clarity: "質感", }; const signed = (n: number, digits = 0) => `${n > 0 ? "+" : ""}${n.toFixed(digits)}`; @@ -39,7 +43,8 @@ export function adjustLabel(key: keyof AdjustV1, value: number): string { } /** 部分補正の操作名: 「部分補正: 露光量 +0.30」 */ -export function localAdjustLabel(key: keyof LocalAdjustV2, value: number): string { +export function localAdjustLabel(key: keyof LocalAdjust, value: number): string { + if (key === "blur") return `部分補正: ${LOCAL_ADJUST_LABELS[key]} ${value}px`; const v = key === "exposure" ? signed(value, 2) : signed(value); return `部分補正: ${LOCAL_ADJUST_LABELS[key]} ${v}`; } diff --git a/apps/app/web/features/editor/render/local-adjust-filter.ts b/apps/app/web/features/editor/render/local-adjust-filter.ts index b50da6e..9424691 100644 --- a/apps/app/web/features/editor/render/local-adjust-filter.ts +++ b/apps/app/web/features/editor/render/local-adjust-filter.ts @@ -7,7 +7,7 @@ import { ADJUST_GLSL, FILTER_VERTEX } from "./adjust-glsl.ts"; // 部分補正 1 件 = フィルタ 1 パス (#109)。マスク (mask-math.ts / brush-raster.ts) と色補正 // (adjust-math.ts) の CPU 実装と同じ式。片方を変えたら必ずもう片方も変える。 // シャープ (3x3 アンシャープ) と美肌 (5x5 の輪郭を残す平滑化) は近傍を見るので CPU 参照は無く、 -// E2E は平坦部 (変わらない) とマスク外だけを照合する (docs/design/08 §7)。 +// #184 のぼかし・bloom・周辺減光・clarity は adjust-math.ts と E2E で同じ式を照合する。 // 近傍の間隔は元画像の px で決める (uSourceSize) ので、プレビュー (縮小) と書き出し (原寸) で // 同じ広がりになる。 @@ -31,6 +31,10 @@ uniform vec2 uSourceSize; // 元画像の px (近傍の間隔を原寸基準 uniform float uMaskMode; // 0 = 楕円 (解析的)、1 = テクスチャ (brush-raster.ts が invert まで済ませている) uniform float uSharpen; // 0..1 uniform float uSmooth; // 0..0.6 +uniform float uBlur; // 0..32 (元画像 px) +uniform float uBloom; // 0..1 +uniform float uVignette; // 0..1 +uniform float uClarity; // -1..1 uniform float uExposure; uniform float uContrast; @@ -86,6 +90,22 @@ vec3 smoothSkin(vec3 rgb) { return sum / wsum; } +// 背景ぼかし・bloom・clarity で共有する 3x3 近傍。半径は元画像 px。 +// bloom は 0.65 より明るい成分だけを集める。 +void spatialNeighborhood(float radius, out vec3 average, out vec3 glow) { + vec3 sum = vec3(0.0); + vec3 bright = vec3(0.0); + for (int y = -1; y <= 1; y++) { + for (int x = -1; x <= 1; x++) { + vec3 c = tap(vec2(float(x), float(y)) * radius); + sum += c; + bright += max(c - vec3(0.65), vec3(0.0)) / 0.35; + } + } + average = sum / 9.0; + glow = bright / 9.0; +} + float ellipseMask(void) { vec2 p = (vImageUv - uCenter) * uOutputFrame.zw; float c = cos(-uRotation); @@ -103,9 +123,23 @@ void main(void) { vec3 rgb = src.a > 0.0 ? src.rgb / src.a : src.rgb; if (m > 0.0) { vec3 adjusted = rgb; + float radius = max(uBlur, max(uBloom > 0.0 ? 8.0 : 0.0, abs(uClarity) > 0.0 ? 4.0 : 0.0)); + if (radius > 0.0) { + vec3 average; + vec3 glow; + spatialNeighborhood(radius, average, glow); + if (uBlur > 0.0) adjusted = average; + if (abs(uClarity) > 0.0) adjusted = clamp(adjusted + (rgb - average) * uClarity, 0.0, 1.0); + if (uBloom > 0.0) adjusted = clamp(adjusted + glow * uBloom * 0.5, 0.0, 1.0); + } if (uSmooth > 0.0) adjusted = mix(adjusted, smoothSkin(adjusted), uSmooth); if (uSharpen > 0.0) adjusted = sharpen(adjusted); adjusted = adjustColor(clamp(adjusted, 0.0, 1.0), uExposure, uContrast, uHighlights, uShadows, uTemperature, uTint, 0.0, uSaturation); + if (uVignette > 0.0) { + vec2 p = (vImageUv - vec2(0.5)) * 2.0; + float d = dot(p, p) / 2.0; + adjusted *= 1.0 - uVignette * 0.65 * smoothstep(0.2, 1.0, d); + } rgb = mix(rgb, adjusted, m); } if (uShowMask > 0.5) { @@ -131,6 +165,10 @@ type LocalUniforms = { uMaskMode: F32; uSharpen: F32; uSmooth: F32; + uBlur: F32; + uBloom: F32; + uVignette: F32; + uClarity: F32; uCenter: Vec2; uRadii: Vec2; uRotation: F32; @@ -167,6 +205,10 @@ export class LocalAdjustFilter extends Filter { uMaskMode: f32(0), uSharpen: f32(0), uSmooth: f32(0), + uBlur: f32(0), + uBloom: f32(0), + uVignette: f32(0), + uClarity: f32(0), uCenter: vec2(0.5, 0.5), uRadii: vec2(0.1, 0.1), uRotation: f32(0), @@ -203,6 +245,10 @@ export class LocalAdjustFilter extends Filter { u.uAmount = local.amount / 100; u.uSharpen = a.sharpen / 100; u.uSmooth = a.smooth / 100; + u.uBlur = a.blur; + u.uBloom = a.bloom / 100; + u.uVignette = a.vignette / 100; + u.uClarity = a.clarity / 100; u.uShowMask = showMask ? 1 : 0; u.uMaskMode = local.mask.kind === "ellipse" ? 0 : 1; u.uInvert = local.mask.invert ? 1 : 0; diff --git a/apps/app/web/features/editor/state.ts b/apps/app/web/features/editor/state.ts index ae68d4c..01af4a1 100644 --- a/apps/app/web/features/editor/state.ts +++ b/apps/app/web/features/editor/state.ts @@ -18,7 +18,7 @@ import { type BrushStrokeV2, type EditRecipe, type GeometryV1, - type LocalAdjustV2, + type LocalAdjust, type LocalAdjustment, type LocalPresetId, type Mask, @@ -47,7 +47,7 @@ export type AutoLocalItem = { readonly presetId: LocalPresetId | null; readonly name?: string | undefined; /** 与えればプリセットの値の代わりに使う (人物補正の役ごとの値、#175) */ - readonly adjust?: LocalAdjustV2 | undefined; + readonly adjust?: LocalAdjust | undefined; readonly amount?: number | undefined; }; @@ -131,8 +131,8 @@ export type EditorAction = | { type: "local/remove"; id: string } | { type: "local/select"; id: string | null } | { type: "local/toggle-visible"; id: string } - | { type: "local/adjust-preview"; id: string; key: keyof LocalAdjustV2; value: number } - | { type: "local/adjust-commit"; id: string; key: keyof LocalAdjustV2; value: number } + | { type: "local/adjust-preview"; id: string; key: keyof LocalAdjust; value: number } + | { type: "local/adjust-commit"; id: string; key: keyof LocalAdjust; value: number } | { type: "local/amount-preview"; id: string; value: number } | { type: "local/amount-commit"; id: string; value: number } | { type: "local/mask-preview"; id: string; mask: Mask } @@ -223,7 +223,7 @@ function withLocal( /** 手で値を変えたらプリセットの表示は外す (全体の補正と同じ原則) */ const withLocalValue = - (key: keyof LocalAdjustV2, value: number) => + (key: keyof LocalAdjust, value: number) => (l: LocalAdjustment): LocalAdjustment => ({ ...l, presetId: null, diff --git a/apps/app/web/features/editor/ui/LocalPanel.tsx b/apps/app/web/features/editor/ui/LocalPanel.tsx index 70eefe1..3d672d5 100644 --- a/apps/app/web/features/editor/ui/LocalPanel.tsx +++ b/apps/app/web/features/editor/ui/LocalPanel.tsx @@ -1,8 +1,9 @@ import { LOCAL_PRESETS, MAX_LOCAL_ADJUSTMENTS, + MAX_LOCAL_BLUR, MAX_LOCAL_SMOOTH, - type LocalAdjustV2, + type LocalAdjust, type LocalAdjustment, type LocalPresetId, } from "@prismtone/shared/recipe"; @@ -37,13 +38,13 @@ type Props = { onPreset: (id: string, presetId: LocalPresetId) => void; onAmountPreview: (id: string, value: number) => void; onAmountCommit: (id: string, value: number) => void; - onAdjustPreview: (id: string, key: keyof LocalAdjustV2, value: number) => void; - onAdjustCommit: (id: string, key: keyof LocalAdjustV2, value: number) => void; + onAdjustPreview: (id: string, key: keyof LocalAdjust, value: number) => void; + onAdjustCommit: (id: string, key: keyof LocalAdjust, value: number) => void; onShowMask: (on: boolean) => void; onShowHandles: (on: boolean) => void; }; -const ROWS: { key: keyof LocalAdjustV2; min: number; max: number; step: number; ev?: boolean }[] = [ +const ROWS: { key: keyof LocalAdjust; min: number; max: number; step: number; ev?: boolean }[] = [ { key: "exposure", min: -5, max: 5, step: 0.05, ev: true }, { key: "contrast", min: -100, max: 100, step: 1 }, { key: "highlights", min: -100, max: 100, step: 1 }, @@ -53,6 +54,10 @@ const ROWS: { key: keyof LocalAdjustV2; min: number; max: number; step: number; { key: "saturation", min: -100, max: 100, step: 1 }, { key: "sharpen", min: 0, max: 100, step: 1 }, { key: "smooth", min: 0, max: MAX_LOCAL_SMOOTH, step: 1 }, + { key: "blur", min: 0, max: MAX_LOCAL_BLUR, step: 1 }, + { key: "bloom", min: 0, max: 100, step: 1 }, + { key: "vignette", min: 0, max: 100, step: 1 }, + { key: "clarity", min: -100, max: 100, step: 1 }, ]; const btn = @@ -355,7 +360,9 @@ export function LocalPanel(p: Props) { format={ r.ev ? (v) => `${v >= 0 ? "+" : ""}${v.toFixed(2)}` - : (v) => `${v > 0 ? "+" : ""}${v}` + : r.key === "blur" + ? (v) => `${v}px` + : (v) => `${v > 0 ? "+" : ""}${v}` } onPreview={(v) => p.onAdjustPreview(selected.id, r.key, v)} onCommit={(v) => p.onAdjustCommit(selected.id, r.key, v)} diff --git a/apps/app/web/features/i18n/messages.ts b/apps/app/web/features/i18n/messages.ts index 65f6a40..3c020ec 100644 --- a/apps/app/web/features/i18n/messages.ts +++ b/apps/app/web/features/i18n/messages.ts @@ -11,6 +11,10 @@ const EN: Readonly> = { 彩度: "Saturation", シャープ: "Sharpen", 美肌: "Smooth skin", + 背景ぼかし: "Background blur", + 発光: "Bloom", + 周辺減光: "Vignette", + 質感: "Clarity", 夜景: "Night", 夕暮れ: "Sunset", 朝霧: "Cool morning", diff --git a/e2e/editor.spec.ts b/e2e/editor.spec.ts index 136d503..c81f97c 100644 --- a/e2e/editor.spec.ts +++ b/e2e/editor.spec.ts @@ -257,6 +257,61 @@ test.describe("editor", () => { expect(out.pixels[0]).not.toEqual(BLOCKS[1]); }); + const sourceAt = ({ x }: { x: number; y: number }) => + BLOCKS[Math.min(BLOCKS.length - 1, Math.floor(x * BLOCKS.length))]!.map( + (value) => value / 255, + ) as [number, number, number]; + const spatialRecipe = (adjust: Partial): EditRecipe => ({ + ...DEFAULT_RECIPE, + localAdjustments: [ + { + ...DEFAULT_LOCAL_ADJUSTMENT, + id: "spatial", + mask: { ...DEFAULT_ELLIPSE_MASK, cx: 0.5, cy: 0.5, rx: 1, ry: 1, feather: 0 }, + adjust: { ...DEFAULT_LOCAL_ADJUST, ...adjust }, + }, + ], + }); + const spatialCpu = (recipe: EditRecipe, point: { x: number; y: number }) => + applyRecipeAt(sourceAt, { x: point.x / 200, y: point.y / 100 }, recipe, { + width: 200, + height: 100, + }).map((value) => Math.round(value * 255)); + + test("background blur matches the CPU reference at a colour boundary (#184)", async ({ + page, + }) => { + await openEditorWithImage(page); + const recipe = spatialRecipe({ blur: 10 }); + const point = { x: 95, y: 50 }; + const out = await exportPixels(page, recipe, [point]); + expectClose(out.pixels[0]!, spatialCpu(recipe, point), 4); + }); + + test("bloom adds blurred highlights like the CPU reference (#184)", async ({ page }) => { + await openEditorWithImage(page); + const recipe = spatialRecipe({ bloom: 100 }); + const point = { x: 55, y: 50 }; + const out = await exportPixels(page, recipe, [point]); + expectClose(out.pixels[0]!, spatialCpu(recipe, point), 4); + }); + + test("vignette darkens the corner like the CPU reference (#184)", async ({ page }) => { + await openEditorWithImage(page); + const recipe = spatialRecipe({ vignette: 100 }); + const point = { x: 5, y: 5 }; + const out = await exportPixels(page, recipe, [point]); + expectClose(out.pixels[0]!, spatialCpu(recipe, point), 4); + }); + + test("clarity raises local contrast like the CPU reference (#184)", async ({ page }) => { + await openEditorWithImage(page); + const recipe = spatialRecipe({ clarity: 100 }); + const point = { x: 95, y: 50 }; + const out = await exportPixels(page, recipe, [point]); + expectClose(out.pixels[0]!, spatialCpu(recipe, point), 4); + }); + test("the brush tool paints and erases on the canvas, one history step per stroke (#109)", async ({ page, }) => { @@ -269,6 +324,10 @@ test.describe("editor", () => { await expect(page.getByTestId("brush-settings")).toBeVisible(); await expect(page.getByTestId("brush-overlay")).toBeVisible(); await expect(page.getByTestId("local-sliders").getByLabel("美肌")).toBeVisible(); + await expect(page.getByTestId("local-sliders").getByLabel("背景ぼかし")).toBeVisible(); + await expect(page.getByTestId("local-sliders").getByLabel("発光")).toBeVisible(); + await expect(page.getByTestId("local-sliders").getByLabel("周辺減光")).toBeVisible(); + await expect(page.getByTestId("local-sliders").getByLabel("質感")).toBeVisible(); const host = await page.getByTestId("canvas-host").boundingBox(); if (!host) throw new Error("no canvas"); diff --git a/e2e/perf-local-adjust.spec.ts b/e2e/perf-local-adjust.spec.ts index ed96590..dc70ab7 100644 --- a/e2e/perf-local-adjust.spec.ts +++ b/e2e/perf-local-adjust.spec.ts @@ -6,7 +6,7 @@ import { DEFAULT_LOCAL_ADJUSTMENT, DEFAULT_RECIPE, type EditRecipe, - type LocalAdjustmentV2, + type LocalAdjustment, } from "@prismtone/shared/recipe"; /** @@ -40,7 +40,7 @@ async function makeNoisePng(page: Page, width: number, height: number): Promise< return Buffer.from(dataUrl.split(",")[1]!, "base64"); } -const local = (i: number): LocalAdjustmentV2 => ({ +const local = (i: number): LocalAdjustment => ({ ...DEFAULT_LOCAL_ADJUSTMENT, id: `l${i}`, mask: @@ -60,10 +60,19 @@ const local = (i: number): LocalAdjustmentV2 => ({ }, ], }, - adjust: { ...DEFAULT_LOCAL_ADJUST, exposure: 0.3, sharpen: 30, smooth: i % 2 === 0 ? 0 : 40 }, + adjust: { + ...DEFAULT_LOCAL_ADJUST, + exposure: 0.3, + sharpen: 30, + smooth: i % 2 === 0 ? 0 : 40, + blur: i % 4 === 0 ? 8 : 0, + bloom: i % 4 === 1 ? 30 : 0, + vignette: i % 4 === 2 ? 20 : 0, + clarity: i % 4 === 3 ? 30 : 0, + }, }); -test("measure develop / export time and texture memory for 0 / 4 / 8 local adjustments", async ({ +test("measure develop / export time and texture memory for 0 / 4 / 8 / 12 local adjustments", async ({ page, }) => { test.setTimeout(600_000); diff --git a/packages/shared/src/recipe/local-presets.ts b/packages/shared/src/recipe/local-presets.ts index ad33039..9c50093 100644 --- a/packages/shared/src/recipe/local-presets.ts +++ b/packages/shared/src/recipe/local-presets.ts @@ -1,7 +1,7 @@ import { DEFAULT_LOCAL_ADJUST, - type LocalAdjustV2, - type LocalAdjustmentV2, + type LocalAdjust, + type LocalAdjustment, type LocalPresetId, } from "./schema.ts"; @@ -10,7 +10,7 @@ export type LocalPreset = { name: string; /** 何に使うかの一言 (UI のツールチップ) */ hint: string; - adjust: Partial; + adjust: Partial; amount: number; }; @@ -34,7 +34,14 @@ export const LOCAL_PRESETS: readonly LocalPreset[] = Object.freeze([ id: "gear", name: "装備強調", hint: "見せたい装備をブラシで塗る。暗部を持ち上げ、質感と色を整える", - adjust: { exposure: 0.15, shadows: 45, contrast: 15, sharpen: 30, saturation: 8 }, + adjust: { + exposure: 0.15, + shadows: 45, + contrast: 15, + sharpen: 30, + saturation: 8, + clarity: 25, + }, amount: 100, }, ]); @@ -47,9 +54,10 @@ export function findLocalPreset(id: string): LocalPreset | undefined { * 部分補正にプリセットを適用した新しい部分補正を返す。元は変更しない。 * adjust と amount を上書きし、マスクには触れない。 */ -export function applyLocalPreset< - T extends Pick, ->(local: T, preset: LocalPreset): T { +export function applyLocalPreset>( + local: T, + preset: LocalPreset, +): T { return { ...local, presetId: preset.id, diff --git a/packages/shared/src/recipe/migrate.ts b/packages/shared/src/recipe/migrate.ts index 8fc6833..0e5abb1 100644 --- a/packages/shared/src/recipe/migrate.ts +++ b/packages/shared/src/recipe/migrate.ts @@ -3,14 +3,18 @@ import { editRecipeSchemaV1, editRecipeSchemaV2, editRecipeSchemaV3, + editRecipeSchemaV4, + localAdjustSchemaV4, localAdjustmentSchemaV2, localAdjustmentSchemaV3, + localAdjustmentSchemaV4, MAX_LOCAL_ADJUSTMENTS, MAX_LOCAL_ADJUSTMENTS_V2, type EditRecipe, type EditRecipeV1, type EditRecipeV2, type EditRecipeV3, + type EditRecipeV4, } from "./schema.ts"; export class RecipeMigrationError extends Error { @@ -22,10 +26,25 @@ const versioned = z.object({ version: z.number().int() }); // strict は object にしか付かないので、部分補正とマスクの中まで strict にした版を組み立てる。 // v2 に groupId が混ざっていれば拒む (version の書き間違いを通さない) const strictV2 = editRecipeSchemaV2.strict().extend({ - localAdjustments: localAdjustmentSchemaV2.strict().array().max(MAX_LOCAL_ADJUSTMENTS_V2), + localAdjustments: localAdjustmentSchemaV2 + .strict() + .extend({ adjust: localAdjustmentSchemaV2.shape.adjust.strict() }) + .array() + .max(MAX_LOCAL_ADJUSTMENTS_V2), }); const strictV3 = editRecipeSchemaV3.strict().extend({ - localAdjustments: localAdjustmentSchemaV3.strict().array().max(MAX_LOCAL_ADJUSTMENTS), + localAdjustments: localAdjustmentSchemaV3 + .strict() + .extend({ adjust: localAdjustmentSchemaV3.shape.adjust.strict() }) + .array() + .max(MAX_LOCAL_ADJUSTMENTS), +}); +const strictV4 = editRecipeSchemaV4.strict().extend({ + localAdjustments: localAdjustmentSchemaV4 + .strict() + .extend({ adjust: localAdjustSchemaV4.strict() }) + .array() + .max(MAX_LOCAL_ADJUSTMENTS), }); /** v1 -> v2: 部分補正を空で足す (#109) */ @@ -42,6 +61,24 @@ export function migrateV2toV3(v2: EditRecipeV2): EditRecipeV3 { }; } +/** v3 -> v4: 人物補正の追加効果を中立値で足す (#184) */ +export function migrateV3toV4(v3: EditRecipeV3): EditRecipeV4 { + return { + ...v3, + version: 4, + localAdjustments: v3.localAdjustments.map((local) => ({ + ...local, + adjust: { + ...local.adjust, + blur: 0, + bloom: 0, + vignette: 0, + clarity: 0, + }, + })), + }; +} + function parseOrThrow(schema: z.ZodType, input: unknown, label: string): T { const parsed = schema.safeParse(input); if (!parsed.success) { @@ -65,11 +102,15 @@ export function migrateRecipe(input: unknown): EditRecipe { } switch (head.data.version) { case 1: - return migrateV2toV3(migrateV1toV2(parseOrThrow(editRecipeSchemaV1.strict(), input, "v1"))); + return migrateV3toV4( + migrateV2toV3(migrateV1toV2(parseOrThrow(editRecipeSchemaV1.strict(), input, "v1"))), + ); case 2: - return migrateV2toV3(parseOrThrow(strictV2, input, "v2")); + return migrateV3toV4(migrateV2toV3(parseOrThrow(strictV2, input, "v2"))); case 3: - return parseOrThrow(strictV3, input, "v3"); + return migrateV3toV4(parseOrThrow(strictV3, input, "v3")); + case 4: + return parseOrThrow(strictV4, input, "v4"); default: throw new RecipeMigrationError(`unsupported recipe version: ${head.data.version}`); } diff --git a/packages/shared/src/recipe/portrait-presets.test.ts b/packages/shared/src/recipe/portrait-presets.test.ts index 1130e49..117003a 100644 --- a/packages/shared/src/recipe/portrait-presets.test.ts +++ b/packages/shared/src/recipe/portrait-presets.test.ts @@ -5,7 +5,7 @@ import { DEFAULT_LOCAL_ADJUSTMENT, DEFAULT_RECIPE, editRecipeSchema, - localAdjustSchemaV2, + localAdjustSchemaV4, type EditRecipe, type LocalAdjustment, } from "./schema.ts"; @@ -77,7 +77,7 @@ describe("PORTRAIT_PRESETS", () => { for (const role of PORTRAIT_ROLES) { const r = preset.roles[role]; expect( - localAdjustSchemaV2.safeParse({ ...DEFAULT_LOCAL_ADJUST, ...r.adjust }).success, + localAdjustSchemaV4.safeParse({ ...DEFAULT_LOCAL_ADJUST, ...r.adjust }).success, ).toBe(true); expect(r.amount).toBeGreaterThanOrEqual(0); expect(r.amount).toBeLessThanOrEqual(100); @@ -85,6 +85,17 @@ describe("PORTRAIT_PRESETS", () => { } expect(findPortraitPreset("nope")).toBeUndefined(); }); + + it("uses at least one v4 effect in every portrait preset", () => { + const keys = ["blur", "bloom", "vignette", "clarity"] as const; + for (const preset of PORTRAIT_PRESETS) { + expect( + PORTRAIT_ROLES.some((role) => + keys.some((key) => preset.roles[role].adjust[key] !== undefined), + ), + ).toBe(true); + } + }); }); describe("portraitRole", () => { diff --git a/packages/shared/src/recipe/portrait-presets.ts b/packages/shared/src/recipe/portrait-presets.ts index 9bf6cf5..4692fb3 100644 --- a/packages/shared/src/recipe/portrait-presets.ts +++ b/packages/shared/src/recipe/portrait-presets.ts @@ -1,7 +1,7 @@ import { DEFAULT_LOCAL_ADJUST, type EditRecipe, - type LocalAdjustV2, + type LocalAdjust, type LocalAdjustment, } from "./schema.ts"; @@ -18,7 +18,7 @@ export type PortraitRole = (typeof PORTRAIT_ROLES)[number]; export const PORTRAIT_PRESET_IDS = ["natural", "bright", "dramatic", "soft", "eyes"] as const; export type PortraitPresetId = (typeof PORTRAIT_PRESET_IDS)[number]; -export type PortraitRoleSetting = { adjust: Partial; amount: number }; +export type PortraitRoleSetting = { adjust: Partial; amount: number }; export type PortraitPreset = { id: PortraitPresetId; @@ -32,16 +32,19 @@ const eyesLight: PortraitRoleSetting = { amount: 70, }; -// 数値は実画像で調整する。既存の 9 項目だけで組む (ぼかし・発光・周辺減光は別 Issue) +// 数値は実画像で調整する。空間効果は背景・人物・顔の役に分け、1 パスに重い効果を重ねすぎない。 export const PORTRAIT_PRESETS: readonly PortraitPreset[] = Object.freeze([ { id: "natural", name: "ナチュラル", hint: "顔を少し明るく、美肌と瞳強調を弱く。背景はわずかに落とす", roles: { - background: { adjust: { exposure: -0.15, saturation: -10, contrast: -5 }, amount: 60 }, - person: { adjust: { shadows: 15, contrast: 5, sharpen: 10 }, amount: 60 }, - face: { adjust: { exposure: 0.15, temperature: 5, smooth: 25 }, amount: 80 }, + background: { + adjust: { exposure: -0.15, saturation: -10, contrast: -5, blur: 3, vignette: 10 }, + amount: 60, + }, + person: { adjust: { shadows: 15, contrast: 5, sharpen: 10, clarity: 10 }, amount: 60 }, + face: { adjust: { exposure: 0.15, temperature: 5, smooth: 25, bloom: 8 }, amount: 80 }, eyes: eyesLight, }, }, @@ -50,9 +53,9 @@ export const PORTRAIT_PRESETS: readonly PortraitPreset[] = Object.freeze([ name: "明るく", hint: "顔と人物の露光・シャドウを持ち上げる", roles: { - background: { adjust: { exposure: -0.05 }, amount: 40 }, - person: { adjust: { exposure: 0.2, shadows: 30 }, amount: 80 }, - face: { adjust: { exposure: 0.35, shadows: 20, smooth: 20 }, amount: 90 }, + background: { adjust: { exposure: -0.05, blur: 2, vignette: 5 }, amount: 40 }, + person: { adjust: { exposure: 0.2, shadows: 30, clarity: 5 }, amount: 80 }, + face: { adjust: { exposure: 0.35, shadows: 20, smooth: 20, bloom: 12 }, amount: 90 }, eyes: eyesLight, }, }, @@ -61,10 +64,13 @@ export const PORTRAIT_PRESETS: readonly PortraitPreset[] = Object.freeze([ name: "ドラマチック", hint: "人物のコントラストを上げ、背景を暗く沈める", roles: { - background: { adjust: { exposure: -0.5, saturation: -25, contrast: -10 }, amount: 90 }, - person: { adjust: { contrast: 20, shadows: -10, sharpen: 20 }, amount: 90 }, + background: { + adjust: { exposure: -0.5, saturation: -25, contrast: -10, blur: 4, vignette: 30 }, + amount: 90, + }, + person: { adjust: { contrast: 20, shadows: -10, sharpen: 20, clarity: 35 }, amount: 90 }, face: { adjust: { contrast: 10, smooth: 15 }, amount: 80 }, - eyes: { adjust: { contrast: 20, sharpen: 40, saturation: 10 }, amount: 80 }, + eyes: { adjust: { contrast: 20, sharpen: 40, saturation: 10, bloom: 5 }, amount: 80 }, }, }, { @@ -72,9 +78,15 @@ export const PORTRAIT_PRESETS: readonly PortraitPreset[] = Object.freeze([ name: "やわらか", hint: "美肌を強めに、コントラストを抑えてやわらかく", roles: { - background: { adjust: { contrast: -20, saturation: -10 }, amount: 70 }, + background: { + adjust: { contrast: -20, saturation: -10, blur: 6, vignette: 15 }, + amount: 70, + }, person: { adjust: { contrast: -10, highlights: -10 }, amount: 60 }, - face: { adjust: { smooth: 45, exposure: 0.1, temperature: 8 }, amount: 90 }, + face: { + adjust: { smooth: 45, exposure: 0.1, temperature: 8, bloom: 20, clarity: -20 }, + amount: 90, + }, eyes: { adjust: { exposure: 0.2, sharpen: 10 }, amount: 50 }, }, }, @@ -83,10 +95,13 @@ export const PORTRAIT_PRESETS: readonly PortraitPreset[] = Object.freeze([ name: "瞳くっきり", hint: "両目の露光・彩度・シャープを中心に。他は控えめ", roles: { - background: { adjust: { exposure: -0.1 }, amount: 40 }, - person: { adjust: { sharpen: 10 }, amount: 40 }, + background: { adjust: { exposure: -0.1, blur: 2, vignette: 10 }, amount: 40 }, + person: { adjust: { sharpen: 10, clarity: 15 }, amount: 40 }, face: { adjust: { smooth: 10 }, amount: 40 }, - eyes: { adjust: { exposure: 0.4, saturation: 25, contrast: 20, sharpen: 50 }, amount: 100 }, + eyes: { + adjust: { exposure: 0.4, saturation: 25, contrast: 20, sharpen: 50, bloom: 8, clarity: 20 }, + amount: 100, + }, }, }, ]); diff --git a/packages/shared/src/recipe/recipe.test.ts b/packages/shared/src/recipe/recipe.test.ts index 9019045..727df24 100644 --- a/packages/shared/src/recipe/recipe.test.ts +++ b/packages/shared/src/recipe/recipe.test.ts @@ -3,13 +3,17 @@ import { BITMAP_MAX_EDGE, DEFAULT_ELLIPSE_MASK, DEFAULT_LOCAL_ADJUST, + DEFAULT_LOCAL_ADJUST_V2, DEFAULT_LOCAL_ADJUSTMENT, DEFAULT_RECIPE, + CURRENT_RECIPE_VERSION, MAX_LOCAL_ADJUSTMENTS, MAX_POLYGON_POINTS, editRecipeInputSchema, editRecipeSchema, editRecipeSchemaV2, + editRecipeSchemaV3, + localAdjustSchemaV4, localAdjustmentSchema, } from "./schema.ts"; import { encodeRle } from "./rle.ts"; @@ -44,6 +48,91 @@ describe("migrateRecipe", () => { }); }); +describe("editRecipeSchema v4 (#184 人物補正の追加効果)", () => { + const v3 = { + version: 3, + presetId: null, + adjust: DEFAULT_RECIPE.adjust, + geometry: DEFAULT_RECIPE.geometry, + localAdjustments: [ + { + id: "background", + name: null, + presetId: null, + groupId: "portrait", + mask: DEFAULT_ELLIPSE_MASK, + adjust: { + exposure: 0, + contrast: 0, + highlights: 0, + shadows: 0, + temperature: 0, + tint: 0, + saturation: 0, + sharpen: 0, + smooth: 0, + }, + amount: 100, + visible: true, + }, + ], + } as const; + + it("uses version 4 for new recipes and accepts the four additional local effects", () => { + expect(CURRENT_RECIPE_VERSION).toBe(4); + expect(DEFAULT_RECIPE.version).toBe(4); + expect( + localAdjustSchemaV4.safeParse({ + ...DEFAULT_LOCAL_ADJUST, + blur: 12, + bloom: 30, + vignette: 20, + clarity: -25, + }).success, + ).toBe(true); + }); + + it("migrates v3 by adding neutral values without changing existing adjustments", () => { + const out = migrateRecipe(v3); + expect(out.version).toBe(4); + expect(out.localAdjustments[0]!.adjust).toEqual({ + ...v3.localAdjustments[0]!.adjust, + blur: 0, + bloom: 0, + vignette: 0, + clarity: 0, + }); + }); + + it("rejects v4 effects on a recipe labelled as v3", () => { + const leaked = { + ...v3, + localAdjustments: [ + { + ...v3.localAdjustments[0], + adjust: { ...v3.localAdjustments[0]!.adjust, blur: 10 }, + }, + ], + }; + expect(() => migrateRecipe(leaked)).toThrow(RecipeMigrationError); + }); + + it("rejects additional effects outside their ranges", () => { + expect(localAdjustSchemaV4.safeParse({ ...DEFAULT_LOCAL_ADJUST, blur: 33 }).success).toBe( + false, + ); + expect(localAdjustSchemaV4.safeParse({ ...DEFAULT_LOCAL_ADJUST, bloom: 101 }).success).toBe( + false, + ); + expect(localAdjustSchemaV4.safeParse({ ...DEFAULT_LOCAL_ADJUST, vignette: 101 }).success).toBe( + false, + ); + expect(localAdjustSchemaV4.safeParse({ ...DEFAULT_LOCAL_ADJUST, clarity: -101 }).success).toBe( + false, + ); + }); +}); + describe("presets", () => { it("has 10 presets with unique ids", () => { expect(PRESETS).toHaveLength(10); @@ -87,7 +176,7 @@ describe("editRecipeSchema v2 (#109 部分補正)", () => { feather: 0.3, invert: false, }, - adjust: { ...DEFAULT_LOCAL_ADJUST, exposure: 0.3, sharpen: 30 }, + adjust: { ...DEFAULT_LOCAL_ADJUST_V2, exposure: 0.3, sharpen: 30 }, amount: 100, visible: true, } as const; @@ -164,7 +253,7 @@ describe("editRecipeSchema v3 (#176 自動選択のマスク)", () => { name: null, presetId: "skin", groupId: null, - adjust: DEFAULT_LOCAL_ADJUST, + adjust: DEFAULT_LOCAL_ADJUST_V2, amount: 100, visible: true, } as const; @@ -177,10 +266,16 @@ describe("editRecipeSchema v3 (#176 自動選択のマスク)", () => { feather: 0, invert: false, } as const; - const v3 = (local: unknown[]) => ({ ...DEFAULT_RECIPE, localAdjustments: local }); + const v3 = (local: unknown[]) => ({ + version: 3, + presetId: DEFAULT_RECIPE.presetId, + adjust: DEFAULT_RECIPE.adjust, + geometry: DEFAULT_RECIPE.geometry, + localAdjustments: local, + }); - it("the default recipe is version 3 with no local adjustments", () => { - expect(DEFAULT_RECIPE.version).toBe(3); + it("the current recipe keeps v3 masks and starts with no local adjustments", () => { + expect(DEFAULT_RECIPE.version).toBe(4); expect(DEFAULT_RECIPE.localAdjustments).toEqual([]); expect(editRecipeSchema.parse(DEFAULT_RECIPE)).toEqual(DEFAULT_RECIPE); }); @@ -191,26 +286,26 @@ describe("editRecipeSchema v3 (#176 自動選択のマスク)", () => { { ...base, id: "gear", presetId: "gear", mask: bitmapMask }, { ...base, id: "eye", presetId: "eyes", mask: DEFAULT_ELLIPSE_MASK }, ]; - expect(editRecipeSchema.safeParse(v3(list)).success).toBe(true); + expect(editRecipeSchemaV3.safeParse(v3(list)).success).toBe(true); }); it("allows up to 12 local adjustments (人物補正 1 人で 5 件使う)", () => { expect(MAX_LOCAL_ADJUSTMENTS).toBe(12); const many = (n: number) => Array.from({ length: n }, (_, i) => ({ ...base, id: `m${i}`, mask: DEFAULT_ELLIPSE_MASK })); - expect(editRecipeSchema.safeParse(v3(many(12))).success).toBe(true); - expect(editRecipeSchema.safeParse(v3(many(13))).success).toBe(false); + expect(editRecipeSchemaV3.safeParse(v3(many(12))).success).toBe(true); + expect(editRecipeSchemaV3.safeParse(v3(many(13))).success).toBe(false); }); it("rejects a polygon ring with fewer than 3 points or more than the limit", () => { const two = { ...polygonMask, rings: [polygonMask.rings[0].slice(0, 2)] }; - expect(editRecipeSchema.safeParse(v3([{ ...base, mask: two }])).success).toBe(false); + expect(editRecipeSchemaV3.safeParse(v3([{ ...base, mask: two }])).success).toBe(false); const ring = Array.from({ length: MAX_POLYGON_POINTS + 1 }, (_, i) => ({ x: (i % 100) / 100, y: 0.5, })); expect( - editRecipeSchema.safeParse(v3([{ ...base, mask: { ...polygonMask, rings: [ring] } }])) + editRecipeSchemaV3.safeParse(v3([{ ...base, mask: { ...polygonMask, rings: [ring] } }])) .success, ).toBe(false); }); @@ -222,17 +317,17 @@ describe("editRecipeSchema v3 (#176 自動選択のマスク)", () => { height: 1, rle: encodeRle(new Uint8Array(BITMAP_MAX_EDGE + 1)), }; - expect(editRecipeSchema.safeParse(v3([{ ...base, mask: big }])).success).toBe(false); + expect(editRecipeSchemaV3.safeParse(v3([{ ...base, mask: big }])).success).toBe(false); const short = { ...bitmapMask, rle: encodeRle(Uint8Array.from([1, 1, 1])) }; - expect(editRecipeSchema.safeParse(v3([{ ...base, mask: short }])).success).toBe(false); + expect(editRecipeSchemaV3.safeParse(v3([{ ...base, mask: short }])).success).toBe(false); }); it("carries a groupId so a portrait's adjustments can be handled together", () => { const grouped = { ...base, groupId: "p1", mask: polygonMask }; - expect(editRecipeSchema.safeParse(v3([grouped])).success).toBe(true); - expect(editRecipeSchema.safeParse(v3([{ ...grouped, groupId: "x".repeat(33) }])).success).toBe( - false, - ); + expect(editRecipeSchemaV3.safeParse(v3([grouped])).success).toBe(true); + expect( + editRecipeSchemaV3.safeParse(v3([{ ...grouped, groupId: "x".repeat(33) }])).success, + ).toBe(false); }); }); @@ -248,27 +343,37 @@ describe("migrateRecipe v2 -> v3", () => { name: null, presetId: "eyes", mask: DEFAULT_ELLIPSE_MASK, - adjust: DEFAULT_LOCAL_ADJUST, + adjust: DEFAULT_LOCAL_ADJUST_V2, amount: 80, visible: true, }, ], }; - it("adds groupId: null to each local adjustment and bumps the version", () => { + it("adds groupId and neutral v4 effects to each local adjustment", () => { const out = migrateRecipe(v2); - expect(out.version).toBe(3); - expect(out.localAdjustments[0]).toEqual({ ...v2.localAdjustments[0], groupId: null }); + expect(out.version).toBe(4); + expect(out.localAdjustments[0]).toEqual({ + ...v2.localAdjustments[0], + groupId: null, + adjust: { + ...v2.localAdjustments[0]!.adjust, + blur: 0, + bloom: 0, + vignette: 0, + clarity: 0, + }, + }); }); - it("migrates v1 all the way to v3", () => { + it("migrates v1 all the way to v4", () => { const v1 = { version: 1, presetId: null, adjust: DEFAULT_RECIPE.adjust, geometry: DEFAULT_RECIPE.geometry, }; - expect(migrateRecipe(v1)).toEqual({ ...v1, version: 3, localAdjustments: [] }); + expect(migrateRecipe(v1)).toEqual({ ...v1, version: 4, localAdjustments: [] }); }); it("rejects a v2 recipe that already carries groupId", () => { @@ -276,10 +381,10 @@ describe("migrateRecipe v2 -> v3", () => { expect(() => migrateRecipe(leaked)).toThrow(RecipeMigrationError); }); - it("accepts v1, v2 and v3 through editRecipeInputSchema (API の入出力)", () => { + it("accepts v1 through v4 through editRecipeInputSchema (API の入出力)", () => { expect(editRecipeInputSchema.safeParse(v2).success).toBe(true); expect(editRecipeInputSchema.safeParse(DEFAULT_RECIPE).success).toBe(true); - expect(editRecipeInputSchema.safeParse({ ...DEFAULT_RECIPE, version: 4 }).success).toBe(false); + expect(editRecipeInputSchema.safeParse({ ...DEFAULT_RECIPE, version: 5 }).success).toBe(false); }); }); @@ -292,7 +397,7 @@ describe("migrateRecipe v1 -> v2", () => { }; it("fills localAdjustments with an empty array (v2 の形) on the way to the current version", () => { - expect(migrateRecipe(v1)).toEqual({ ...v1, version: 3, localAdjustments: [] }); + expect(migrateRecipe(v1)).toEqual({ ...v1, version: 4, localAdjustments: [] }); }); it("passes a valid current recipe through unchanged", () => { diff --git a/packages/shared/src/recipe/schema.ts b/packages/shared/src/recipe/schema.ts index c519353..29c55d2 100644 --- a/packages/shared/src/recipe/schema.ts +++ b/packages/shared/src/recipe/schema.ts @@ -18,6 +18,8 @@ export const MAX_LOCAL_ADJUSTMENTS_V2 = 8; export const MAX_BRUSH_STROKES = 64; export const MAX_BRUSH_POINTS = 512; export const MAX_LOCAL_SMOOTH = 60; +/** 背景ぼかしの半径 (元画像 px)。固定 3x3 カーネルの間隔として使う */ +export const MAX_LOCAL_BLUR = 32; export const adjustSchemaV1 = z.object({ exposure: z.number().min(-5).max(5), @@ -207,13 +209,41 @@ export type EditRecipeV3 = z.infer; /** strokes を持つマスク (ブラシで直せるもの) */ export type StrokedMask = Exclude; +// ---- v4: 人物補正の追加効果 (#184) ---- +// v3 までの部分補正の意味を変えず、空間効果を中立値 0 で追加する。 + +export const localAdjustSchemaV4 = localAdjustSchemaV2.extend({ + /** 背景ぼかしの半径 (元画像 px)。0..32 */ + blur: z.number().min(0).max(MAX_LOCAL_BLUR), + /** 高輝度成分をぼかして加算する発光。0..100 */ + bloom: z.number().min(0).max(100), + /** 画像中心から周辺を減光する強さ。0..100 */ + vignette: z.number().min(0).max(100), + /** 近傍平均との差による局所コントラスト。-100..100 */ + clarity: pct, +}); + +export const localAdjustmentSchemaV4 = localAdjustmentSchemaV3.extend({ + adjust: localAdjustSchemaV4, +}); + +export const editRecipeSchemaV4 = editRecipeSchemaV1.extend({ + version: z.literal(4), + localAdjustments: z.array(localAdjustmentSchemaV4).max(MAX_LOCAL_ADJUSTMENTS), +}); + +export type LocalAdjustV4 = z.infer; +export type LocalAdjustmentV4 = z.infer; +export type EditRecipeV4 = z.infer; + /** 現行のレシピ型。version を上げたらここを差し替える。 */ -export type EditRecipe = EditRecipeV3; -export type LocalAdjustment = LocalAdjustmentV3; +export type EditRecipe = EditRecipeV4; +export type LocalAdjust = LocalAdjustV4; +export type LocalAdjustment = LocalAdjustmentV4; export type Mask = MaskV3; -export const editRecipeSchema = editRecipeSchemaV3; -export const CURRENT_RECIPE_VERSION = 3 as const; -export const localAdjustmentSchema = localAdjustmentSchemaV3; +export const editRecipeSchema = editRecipeSchemaV4; +export const CURRENT_RECIPE_VERSION = 4 as const; +export const localAdjustmentSchema = localAdjustmentSchemaV4; /** * API の入出力で受けるレシピ。旧版の投稿はそのまま返り、投稿時も旧版のクライアントを受ける。 @@ -223,6 +253,7 @@ export const editRecipeInputSchema = z.union([ editRecipeSchemaV1, editRecipeSchemaV2, editRecipeSchemaV3, + editRecipeSchemaV4, ]); export type EditRecipeInput = z.infer; @@ -245,7 +276,7 @@ export const DEFAULT_GEOMETRY: GeometryV1 = Object.freeze({ aspect: null, }); -export const DEFAULT_LOCAL_ADJUST: LocalAdjustV2 = Object.freeze({ +export const DEFAULT_LOCAL_ADJUST_V2: LocalAdjustV2 = Object.freeze({ exposure: 0, contrast: 0, highlights: 0, @@ -257,6 +288,14 @@ export const DEFAULT_LOCAL_ADJUST: LocalAdjustV2 = Object.freeze({ smooth: 0, }); +export const DEFAULT_LOCAL_ADJUST: LocalAdjustV4 = Object.freeze({ + ...DEFAULT_LOCAL_ADJUST_V2, + blur: 0, + bloom: 0, + vignette: 0, + clarity: 0, +}); + /** 画像の中央、短辺の 1/8 程度の円 */ export const DEFAULT_ELLIPSE_MASK: EllipseMaskV2 = Object.freeze({ kind: "ellipse", @@ -287,7 +326,7 @@ export const DEFAULT_LOCAL_ADJUSTMENT: Omit = Ob }); export const DEFAULT_RECIPE: EditRecipe = Object.freeze({ - version: 3, + version: 4, presetId: null, adjust: DEFAULT_ADJUST, geometry: DEFAULT_GEOMETRY, From d284c37ea477833b47b1136b5368d7daf8259e53 Mon Sep 17 00:00:00 2001 From: t1nyb0x Date: Tue, 22 Sep 2026 11:16:29 +0900 Subject: [PATCH 34/49] =?UTF-8?q?fix:=20=E9=83=A8=E5=88=86=E8=A3=9C?= =?UTF-8?q?=E6=AD=A3=E3=81=AE=E8=87=AA=E5=8B=95=E9=81=B8=E6=8A=9E=E3=82=92?= =?UTF-8?q?=E7=B6=9A=E3=81=91=E3=81=A6=E8=BF=BD=E5=8A=A0=E5=8F=AF=E8=83=BD?= =?UTF-8?q?=E3=81=AB=E3=81=99=E3=82=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 選択中の範囲へのプリセット適用を維持しながら、瞳強調・美肌・装備強調を自動選択で追加する専用導線を表示する。 キャラクターと背景の選択も現在の範囲に関係なく利用可能にし、2件目の追加をE2Eで確認する。 Closes lumorphia/prismtone#210 --- .../app/web/features/editor/ui/LocalPanel.tsx | 22 ++++++++++++++++++- e2e/editor.spec.ts | 21 +++++++++--------- 2 files changed, 31 insertions(+), 12 deletions(-) diff --git a/apps/app/web/features/editor/ui/LocalPanel.tsx b/apps/app/web/features/editor/ui/LocalPanel.tsx index 3d672d5..54c9ce3 100644 --- a/apps/app/web/features/editor/ui/LocalPanel.tsx +++ b/apps/app/web/features/editor/ui/LocalPanel.tsx @@ -264,7 +264,27 @@ export function LocalPanel(p: Props) { ))}
    - {p.onAuto && !selected && ( + {p.onAuto && selected && ( +
    + + {t("自動選択で追加:", "Add with auto selection:")} + + {LOCAL_PRESETS.map((preset) => ( + + ))} +
    + )} + {p.onAuto && (
    {t("タップで範囲だけ選ぶ:", "Select an area by tapping:")} diff --git a/e2e/editor.spec.ts b/e2e/editor.spec.ts index c81f97c..56ff020 100644 --- a/e2e/editor.spec.ts +++ b/e2e/editor.spec.ts @@ -319,7 +319,7 @@ test.describe("editor", () => { await page.getByRole("tab", { name: "部分補正" }).click(); // 手動の流れ: ブラシを足してから装備強調のプリセット (何も選んでいないときの「装備強調」はタップで切る、#177) await page.getByTestId("local-add-brush").click(); - await page.getByRole("button", { name: "装備強調" }).click(); + await page.getByRole("button", { name: "装備強調", exact: true }).click(); await expect(page.getByTestId("local-list")).toContainText("装備強調 (ブラシ)"); await expect(page.getByTestId("brush-settings")).toBeVisible(); await expect(page.getByTestId("brush-overlay")).toBeVisible(); @@ -398,7 +398,7 @@ test.describe("editor", () => { // 手動の流れ: 円形を足してから瞳強調のプリセットを当てる (何も選んでいないときの「瞳強調」は顔の自動選択、#176) await page.getByTestId("local-add-ellipse").click(); await expect(page.getByTestId("local-list").getByRole("listitem")).toHaveCount(1); - await page.getByRole("button", { name: "瞳強調" }).click(); + await page.getByRole("button", { name: "瞳強調", exact: true }).click(); await expect(page.getByTestId("local-list")).toContainText("瞳強調 (円形)"); await expect(page.getByTestId("history-last")).toContainText("部分補正: 瞳強調"); await expect(page.getByTestId("ellipse-overlay")).toBeVisible(); @@ -429,7 +429,7 @@ test.describe("editor", () => { await page.keyboard.press("ArrowRight"); await expect(page.getByTestId("history-last")).toContainText("部分補正: 露光量 +0.35"); // 手で変えたのでプリセットの強調は外れる - await expect(page.getByRole("button", { name: "瞳強調" })).toHaveAttribute( + await expect(page.getByRole("button", { name: "瞳強調", exact: true })).toHaveAttribute( "aria-pressed", "false", ); @@ -782,7 +782,7 @@ test.describe("editor", () => { await expect(page.getByRole("alert")).toContainText("PNG または JPEG"); }); - test("瞳強調 and 美肌 place masks from face detection, and the polygon can be erased with the brush (#176)", async ({ + test("瞳強調の選択中でも美肌を自動選択で追加でき、範囲をブラシで直せる (#176, #210)", async ({ page, }) => { await page.addInitScript(() => { @@ -801,7 +801,7 @@ test.describe("editor", () => { await page.getByRole("tab", { name: "部分補正" }).click(); // 瞳: 初回はモデルを読み込む (数 MB) ので待つ。両目に円形が 2 つ、1 手の履歴 - await page.getByRole("button", { name: "瞳強調" }).click(); + await page.getByRole("button", { name: "瞳強調", exact: true }).click(); await expect(page.getByTestId("local-list").getByRole("listitem")).toHaveCount(2, { timeout: 60_000, }); @@ -813,10 +813,9 @@ test.describe("editor", () => { const host = await page.getByTestId("canvas-host").boundingBox(); expect(handle && host && handle.y < host.y + host.height * 0.6).toBe(true); - // 2 つで 1 手なので undo で両方消える。美肌: 顔の輪郭の多角形が 1 つ増え、選択されてブラシで直せる - await page.getByTestId("history-undo").click(); - await expect(page.getByTestId("local-list")).toHaveCount(0); - await page.getByRole("button", { name: "美肌" }).click(); + // 瞳が選択中でも、美肌を別の自動選択として追加できる。顔の輪郭が選択され、ブラシで直せる + await page.getByTestId("local-auto-skin").click(); + await expect(page.getByTestId("local-list").getByRole("listitem")).toHaveCount(3); await expect(page.getByTestId("local-list")).toContainText("美肌 (多角形)"); await expect(page.getByTestId("history-last")).toContainText("美肌 (自動)"); await expect(page.getByTestId("brush-settings")).toBeVisible(); @@ -836,7 +835,7 @@ test.describe("editor", () => { }) => { await openEditorWithImage(page); await page.getByRole("tab", { name: "部分補正" }).click(); - await page.getByRole("button", { name: "美肌" }).click(); + await page.getByRole("button", { name: "美肌", exact: true }).click(); await expect(page.getByTestId("local-notice")).toContainText("自動選択できませんでした", { timeout: 60_000, }); @@ -864,7 +863,7 @@ test.describe("editor", () => { expect(await page.evaluate(() => crossOriginIsolated)).toBe(true); // 装備強調: モデルの読み込みと埋め込み (マルチスレッドの WASM で 3〜4 秒) のあとタップ待ちになる - await page.getByRole("button", { name: "装備強調" }).click(); + await page.getByRole("button", { name: "装備強調", exact: true }).click(); await expect(page.getByTestId("tap-overlay")).toBeVisible({ timeout: 120_000 }); const host = (await page.getByTestId("canvas-host").boundingBox())!; // 胸のあたり (赤いコート) をタップ From e04a886cb67799a01f5be5d75eda63ac2bfcd8b0 Mon Sep 17 00:00:00 2001 From: t1nyb0x Date: Tue, 22 Sep 2026 12:43:47 +0900 Subject: [PATCH 35/49] =?UTF-8?q?fix:=20=E3=82=A8=E3=83=87=E3=82=A3?= =?UTF-8?q?=E3=82=BF=E3=81=AE=E3=83=84=E3=83=BC=E3=83=AB=E3=82=BF=E3=83=96?= =?UTF-8?q?=E3=81=8C=E6=8A=98=E3=82=8A=E8=BF=94=E3=81=95=E3=82=8C=E3=82=8B?= =?UTF-8?q?=E3=81=AE=E3=82=92=E7=9B=B4=E3=81=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit サイドバー幅 320px に 5 つのタブが収まらず、ラベルが 2 行に折り返されていた。 タブを nowrap にして余白を詰め、収まらない場合は横スクロールにする。 Co-Authored-By: Claude Opus 5 --- apps/app/web/features/editor/ui/EditorPage.tsx | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/apps/app/web/features/editor/ui/EditorPage.tsx b/apps/app/web/features/editor/ui/EditorPage.tsx index 3a450f2..f1b4abd 100644 --- a/apps/app/web/features/editor/ui/EditorPage.tsx +++ b/apps/app/web/features/editor/ui/EditorPage.tsx @@ -45,7 +45,8 @@ const ERROR_TEXT: Record = { webgl: "このブラウザでは編集機能を使えません (WebGL が無効です)。", }; -const tabBtn = "px-3 py-1.5 text-sm border-b-2 border-transparent aria-selected:border-accent"; +const tabBtn = + "shrink-0 whitespace-nowrap px-2 py-1.5 text-sm border-b-2 border-transparent aria-selected:border-accent"; const toolBtn = "rounded border border-line-soft px-3 py-1.5 text-sm hover:bg-surface-hover disabled:opacity-40 disabled:hover:bg-transparent"; @@ -777,7 +778,7 @@ export function EditorPage() {