From e74152740b72ab0c714ea3bcea834f71022950b0 Mon Sep 17 00:00:00 2001 From: Christian Almurr Date: Wed, 18 Nov 2026 10:12:09 +0100 Subject: [PATCH 1/4] feat: camera shadow styles for picture-in-picture Replace the camera's None/Light/Medium/Strong shadow levels with six styles that set darkness, softness and drop distance together, all lit from one soft source above: None, Close, Soft (the old default, kept exactly), Lifted, Floating and Ambient. The scene carries two new optional multipliers, webcamShadowBlur and webcamShadowDistance, that scale the tuned base spread and offset. The compositor plans them once in FrameGeometry and the Metal, D3D11 and wgpu backends read them from there. Scenes without them render exactly as before. Co-Authored-By: Claude Opus 5.5 --- crates/compositor/src/compositor_linux.rs | 4 +- crates/compositor/src/compositor_macos.rs | 7 +- crates/compositor/src/compositor_windows.rs | 7 +- crates/compositor/src/frame_geometry.rs | 54 ++++++++++++ crates/compositor/src/scene.rs | 8 ++ .../ai-edition/RightPanes.layout.test.tsx | 24 +++++- src/components/ai-edition/RightPanes.tsx | 81 ++++++++++++++++-- src/i18n/locales/ar/settings.json | 16 +++- src/i18n/locales/cs/settings.json | 16 +++- src/i18n/locales/de/settings.json | 16 +++- src/i18n/locales/en/settings.json | 16 +++- src/i18n/locales/es/settings.json | 16 +++- src/i18n/locales/fr/settings.json | 16 +++- src/i18n/locales/it/settings.json | 16 +++- src/i18n/locales/ja-JP/settings.json | 16 +++- src/i18n/locales/ko-KR/settings.json | 16 +++- src/i18n/locales/nl/settings.json | 16 +++- src/i18n/locales/pl/settings.json | 16 +++- src/i18n/locales/pt-BR/settings.json | 16 +++- src/i18n/locales/ru/settings.json | 16 +++- src/i18n/locales/tr/settings.json | 16 +++- src/i18n/locales/vi/settings.json | 16 +++- src/i18n/locales/zh-CN/settings.json | 16 +++- src/i18n/locales/zh-TW/settings.json | 16 +++- .../ai-edition/store/editorSettings.test.ts | 28 +++++++ src/lib/ai-edition/store/editorSettings.ts | 17 ++++ src/lib/projectDefaults.ts | 10 +++ src/lib/webcamShadowStyles.test.ts | 70 ++++++++++++++++ src/lib/webcamShadowStyles.ts | 82 +++++++++++++++++++ src/native/sceneDescription.test.ts | 10 +++ src/native/sceneDescription.ts | 6 ++ website/docs/editing-timeline.md | 2 +- .../current/editing-timeline.md | 2 +- .../current/editing-timeline.md | 2 +- .../current/editing-timeline.md | 2 +- .../current/editing-timeline.md | 2 +- .../current/editing-timeline.md | 2 +- .../current/editing-timeline.md | 2 +- .../current/editing-timeline.md | 2 +- 39 files changed, 649 insertions(+), 47 deletions(-) create mode 100644 src/lib/webcamShadowStyles.test.ts create mode 100644 src/lib/webcamShadowStyles.ts diff --git a/crates/compositor/src/compositor_linux.rs b/crates/compositor/src/compositor_linux.rs index 501eb9df02..641a757ddc 100644 --- a/crates/compositor/src/compositor_linux.rs +++ b/crates/compositor/src/compositor_linux.rs @@ -2935,8 +2935,8 @@ impl Compositor { g.w_dst, g.w_px, g.w_radius, - crate::frame_geometry::WEBCAM_SHADOW_SPREAD_FRAC * g.frame_min_px, - [0.0, crate::frame_geometry::WEBCAM_SHADOW_OFFSET_FRAC * g.frame_min_px], + g.webcam_shadow_spread_frac * g.frame_min_px, + [0.0, g.webcam_shadow_offset_frac * g.frame_min_px], crate::frame_geometry::WEBCAM_SHADOW_OPACITY * g.shape_fade * g.webcam_shadow, ); self.make_bind(&cb, None, &dummy) diff --git a/crates/compositor/src/compositor_macos.rs b/crates/compositor/src/compositor_macos.rs index 4e7e98cd6c..60d9108360 100644 --- a/crates/compositor/src/compositor_macos.rs +++ b/crates/compositor/src/compositor_macos.rs @@ -38,8 +38,7 @@ pub use crate::frame_geometry::{ live_params_from_scene, webcam_shape_code, FIXTURE_FRAMES, LayerCB, LiveParams, OUT_H, OUT_W, }; use crate::frame_geometry::{parse_hex, FrameGeometryInput, ShadowCaster, - SCREEN_SHADOW_SPREAD_FRAC, WEBCAM_SHADOW_OFFSET_FRAC, WEBCAM_SHADOW_OPACITY, - WEBCAM_SHADOW_SPREAD_FRAC}; + SCREEN_SHADOW_SPREAD_FRAC, WEBCAM_SHADOW_OPACITY}; use crate::scene::{Scene, SceneBackground, SceneShaderEffect, ShaderEffectTarget, WallpaperMotion}; use anyhow::{anyhow, Result}; use metal::foreign_types::ForeignType; @@ -3083,8 +3082,8 @@ impl Compositor { g.w_dst, g.w_px, g.w_radius, - WEBCAM_SHADOW_SPREAD_FRAC * g.frame_min_px, - [0.0, WEBCAM_SHADOW_OFFSET_FRAC * g.frame_min_px], + g.webcam_shadow_spread_frac * g.frame_min_px, + [0.0, g.webcam_shadow_offset_frac * g.frame_min_px], WEBCAM_SHADOW_OPACITY * g.shape_fade * g.webcam_shadow, ); } diff --git a/crates/compositor/src/compositor_windows.rs b/crates/compositor/src/compositor_windows.rs index 3231bf5d6a..4968a3d300 100644 --- a/crates/compositor/src/compositor_windows.rs +++ b/crates/compositor/src/compositor_windows.rs @@ -12,8 +12,7 @@ use crate::frame_geometry::{ cover_crop_uv, cover_uv_rect, decode_data_uri, ease_in_out_cubic, lerp, lerp4, parse_hex, preset_placements, remap_box, screen_source_rect, timeline, CursorPlacement, FrameParams, Placement, ShadowCaster, SpriteShape, CURSOR_BASE_SIZE_FRAC, FPS, - SCREEN_SHADOW_SPREAD_FRAC, SHADOW_TUNING_REF_PX, WEBCAM_SHADOW_OFFSET_FRAC, - WEBCAM_SHADOW_OPACITY, WEBCAM_SHADOW_SPREAD_FRAC, + SCREEN_SHADOW_SPREAD_FRAC, SHADOW_TUNING_REF_PX, WEBCAM_SHADOW_OPACITY, }; use crate::cursor::CursorTrack; use crate::scene::{ @@ -2858,8 +2857,8 @@ impl Compositor { w_dst, w_px, w_radius, - WEBCAM_SHADOW_SPREAD_FRAC * frame_min_px, - [0.0, WEBCAM_SHADOW_OFFSET_FRAC * frame_min_px], + g.webcam_shadow_spread_frac * frame_min_px, + [0.0, g.webcam_shadow_offset_frac * frame_min_px], strength, ); } diff --git a/crates/compositor/src/frame_geometry.rs b/crates/compositor/src/frame_geometry.rs index 82a67f955c..5feada6152 100644 --- a/crates/compositor/src/frame_geometry.rs +++ b/crates/compositor/src/frame_geometry.rs @@ -457,6 +457,23 @@ pub(crate) const WEBCAM_SHADOW_OFFSET_FRAC: f32 = 12.0 / SHADOW_TUNING_REF_PX; /// la position du slider. Parité avec le preset PiP côté web (`compositeLayout.ts`, /// `rgba(0,0,0,0.35)`), dont l'ombre est elle aussi un forfait fixe et PiP-only. pub(crate) const WEBCAM_SHADOW_OPACITY: f32 = 0.35; +/// Bounds of the camera shadow's softness and drop multipliers (`SceneEffects::webcam_shadow_blur` +/// / `webcam_shadow_distance`). Mirrors `SETTING_BOUNDS` in `src/lib/projectDefaults.ts`: a +/// hand-edited project or an agent cannot push the shadow past what the styles were tuned for. +pub(crate) const WEBCAM_SHADOW_BLUR_RANGE: (f32, f32) = (0.25, 3.0); +pub(crate) const WEBCAM_SHADOW_DISTANCE_RANGE: (f32, f32) = (0.0, 4.0); + +/// The camera shadow's spread and vertical drop, as fractions of the frame's short side. The +/// scene's multipliers scale the tuned base; a scene without them keeps the base exactly. +fn webcam_shadow_extent(effects: Option<&crate::scene::SceneEffects>) -> (f32, f32) { + let multiplier = |value: Option, (lo, hi): (f32, f32)| { + value.filter(|v| v.is_finite()).unwrap_or(1.0).clamp(lo, hi) + }; + let blur = multiplier(effects.and_then(|e| e.webcam_shadow_blur), WEBCAM_SHADOW_BLUR_RANGE); + let distance = + multiplier(effects.and_then(|e| e.webcam_shadow_distance), WEBCAM_SHADOW_DISTANCE_RANGE); + (WEBCAM_SHADOW_SPREAD_FRAC * blur, WEBCAM_SHADOW_OFFSET_FRAC * distance) +} /// Taille de base du curseur, même convention (34 px réglés contre un cadre 1080). pub(crate) const CURSOR_BASE_SIZE_FRAC: f32 = 34.0 / SHADOW_TUNING_REF_PX; @@ -1910,6 +1927,10 @@ pub struct FrameGeometry { pub show_screen: bool, /// Continuous PiP shadow weight through a layout change. pub webcam_shadow: f32, + /// Camera shadow spread (blur extent), fraction of the frame's short side. + pub webcam_shadow_spread_frac: f32, + /// Camera shadow vertical drop, fraction of the frame's short side. + pub webcam_shadow_offset_frac: f32, pub mb_taps: f32, pub mb_amount: f32, pub source_t: f32, @@ -3711,11 +3732,15 @@ pub fn plan_frame(input: &FrameGeometryInput) -> FrameGeometry { Some(sample) => sample.preset != "camera-only" || sample.progress < 1.0, None => scene_preset.as_deref() != Some("camera-only"), }); + let (webcam_shadow_spread_frac, webcam_shadow_offset_frac) = + webcam_shadow_extent(input.scene.map(|scene| &scene.effects)); FrameGeometry { show_screen, webcam_shadow: sampled_layout.as_ref().map(|s| s.webcam_shadow) .unwrap_or_else(|| if matches!(scene_preset.as_deref(), Some("dual-frame") | Some("vertical-stack") | Some("camera-only")) { 0.0 } else { 1.0 }) * input.scene.and_then(|scene| scene.effects.webcam_shadow).unwrap_or(0.6).clamp(0.0, 1.0) / 0.6, + webcam_shadow_spread_frac, + webcam_shadow_offset_frac, scene_preset, mb_taps, mb_amount, @@ -5256,6 +5281,33 @@ mod tests { } } + #[test] + fn webcam_shadow_style_scales_spread_and_drop_and_keeps_old_scenes() { + let mut scene = golden_scene(); + let cfg = crate::config::all().pop().expect("compositor config"); + // A scene from before the styles carries neither multiplier: the tuned base, exactly. + let baseline = plan_frame(&golden_input(&scene, &cfg)); + assert_eq!(baseline.webcam_shadow_spread_frac, WEBCAM_SHADOW_SPREAD_FRAC); + assert_eq!(baseline.webcam_shadow_offset_frac, WEBCAM_SHADOW_OFFSET_FRAC); + + scene.effects.webcam_shadow_blur = Some(2.0); + scene.effects.webcam_shadow_distance = Some(0.5); + let styled = plan_frame(&golden_input(&scene, &cfg)); + assert!((styled.webcam_shadow_spread_frac - WEBCAM_SHADOW_SPREAD_FRAC * 2.0).abs() < 1e-7); + assert!((styled.webcam_shadow_offset_frac - WEBCAM_SHADOW_OFFSET_FRAC * 0.5).abs() < 1e-7); + // The style moves the shadow only: never the camera itself, nor its opacity. + assert_eq!(styled.w_dst, baseline.w_dst); + assert_eq!(styled.webcam_shadow, baseline.webcam_shadow); + + // Out-of-range and non-finite values are held to the tuned range. + scene.effects.webcam_shadow_blur = Some(100.0); + scene.effects.webcam_shadow_distance = Some(f32::NAN); + let clamped = plan_frame(&golden_input(&scene, &cfg)); + let (_, blur_max) = WEBCAM_SHADOW_BLUR_RANGE; + assert!((clamped.webcam_shadow_spread_frac - WEBCAM_SHADOW_SPREAD_FRAC * blur_max).abs() < 1e-7); + assert_eq!(clamped.webcam_shadow_offset_frac, WEBCAM_SHADOW_OFFSET_FRAC); + } + /// Le JSON de la scène zoomée, brut : `tilted_golden_scene` n'en change QUE la /// rotation, et le faire par substitution garantit que les deux scènes ne diffèrent /// pas ailleurs sans qu'on s'en aperçoive. @@ -8674,6 +8726,8 @@ mod tests { show_screen: true, scene_preset: None, webcam_shadow: 1.0, + webcam_shadow_spread_frac: WEBCAM_SHADOW_SPREAD_FRAC, + webcam_shadow_offset_frac: WEBCAM_SHADOW_OFFSET_FRAC, mb_taps: 1.0, mb_amount: 0.0, source_t: 0.0, diff --git a/crates/compositor/src/scene.rs b/crates/compositor/src/scene.rs index b4a5fb11d9..b61fbae64b 100644 --- a/crates/compositor/src/scene.rs +++ b/crates/compositor/src/scene.rs @@ -284,6 +284,14 @@ pub struct SceneEffects { pub shadow: f32, #[serde(default)] pub webcam_shadow: Option, + /// Camera shadow softness, a multiple of the tuned base spread (`WEBCAM_SHADOW_SPREAD_FRAC`). + /// Absent in scenes from before the shadow styles, which keep the base exactly. + #[serde(default)] + pub webcam_shadow_blur: Option, + /// Camera shadow drop distance, a multiple of the tuned base offset + /// (`WEBCAM_SHADOW_OFFSET_FRAC`). Absent = 1, the historical drop. + #[serde(default)] + pub webcam_shadow_distance: Option, /// Slider Roundness, en FRACTION du petit côté du cadre de sortie. /// /// Toute longueur qui traverse ce contrat est une fraction, jamais un nombre de pixels, et diff --git a/src/components/ai-edition/RightPanes.layout.test.tsx b/src/components/ai-edition/RightPanes.layout.test.tsx index f4cd47e9f9..c71139a763 100644 --- a/src/components/ai-edition/RightPanes.layout.test.tsx +++ b/src/components/ai-edition/RightPanes.layout.test.tsx @@ -366,16 +366,34 @@ describe("LayoutPane picture-in-picture camera", () => { expect(stored()).toMatchObject({ webcamAnchor: "top-left" }); }); - it("changes the camera shadow independently of composition shadow", () => { + it("picks a camera shadow style independently of composition shadow", () => { renderLayout(seedProject(true)); const shadow = screen.getByRole("group", { name: "Shadow" }); - expect(within(shadow).getByRole("button", { name: "Medium" })).toHaveAttribute( + expect(within(shadow).getAllByRole("button")).toHaveLength(6); + // Soft is the shadow every project had before the styles. + expect(within(shadow).getByRole("button", { name: "Soft" })).toHaveAttribute( "aria-pressed", "true", ); fireEvent.click(within(shadow).getByRole("button", { name: "None" })); expect(stored()).toMatchObject({ webcamShadowIntensity: 0 }); - fireEvent.click(within(shadow).getByRole("button", { name: "Strong" })); + fireEvent.click(within(shadow).getByRole("button", { name: "Floating" })); + expect(stored()).toMatchObject({ + webcamShadowIntensity: 0.65, + webcamShadowBlur: 2.4, + webcamShadowDistance: 3.5, + }); + expect(stored()).not.toHaveProperty("shadowIntensity", 0.65); + }); + + // A project saved with the earlier Strong level keeps it until a style is picked. + it("presses no style for a combination none of them offers", () => { + const doc = seedProject(true); + renderLayout({ ...doc, legacyEditor: { ...doc.legacyEditor, webcamShadowIntensity: 0.9 } }); + const shadow = screen.getByRole("group", { name: "Shadow" }); + for (const button of within(shadow).getAllByRole("button")) { + expect(button).toHaveAttribute("aria-pressed", "false"); + } expect(stored()).toMatchObject({ webcamShadowIntensity: 0.9 }); }); diff --git a/src/components/ai-edition/RightPanes.tsx b/src/components/ai-edition/RightPanes.tsx index 8cf35e98aa..ea436c4a5d 100644 --- a/src/components/ai-edition/RightPanes.tsx +++ b/src/components/ai-edition/RightPanes.tsx @@ -144,6 +144,13 @@ import { WALLPAPER_THUMB_PATHS, wallpaperStyle, } from "@/lib/wallpaper"; +import { + matchWebcamShadowStyle, + WEBCAM_SHADOW_STYLES, + type WebcamShadowStyle, + type WebcamShadowStyleId, + webcamShadowStylePatch, +} from "@/lib/webcamShadowStyles"; import { isNativeCompositorActive, setNativeParam } from "@/native"; import { SEGMENTATION_HEIGHT, @@ -2938,15 +2945,32 @@ export function LayoutPane() { {isPip ? ( <> {/* A cutout camera has no bubble, so no shadow to tune. */} - {settings.webcamBackgroundMode !== "transparent" - ? namedLevelRow( - ts("effects.shadow"), - SHADOW_LEVELS.map((level) => ({ value: level.value, label: ts(level.labelKey) })), - settings.webcamShadowIntensity, - layoutControlsDisabled, - (webcamShadowIntensity) => void set({ webcamShadowIntensity }), - ) - : null} + {settings.webcamBackgroundMode !== "transparent" ? ( + <> +
{ts("effects.shadow")}
+
+ {/* A project saved with a combination no style offers matches none, and + keeps rendering as stored until a style is picked. */} + + label={ts("effects.shadow")} + display="both" + tiles + columns={3} + options={WEBCAM_SHADOW_STYLES.map((style) => ({ + value: style.id, + label: ts(`layout.cameraShadow.${style.id}`), + title: ts(`layout.cameraShadow.${style.id}Tip`), + icon: , + }))} + value={matchWebcamShadowStyle(settings) ?? ""} + disabled={layoutControlsDisabled} + onChange={(id) => { + if (id !== "") void set(webcamShadowStylePatch(id)); + }} + /> +
+ + ) : null}
{ts("layout.webcamShape")}
@@ -4201,6 +4225,45 @@ const SHADOW_LEVELS = [ /** A labelled row of named levels. A stored value between two levels (an older project, a * preset) presses no button, the way a speed outside the row does. */ +/** A camera tile over the shadow its style casts, at the same proportions as the render: the + * 12×12 tile stands for a 216 px camera in a 1080 frame, so the tuned 32 px spread and 12 px + * drop are 1.78 and 0.67 units here. `currentColor` keeps it legible in both themes. */ +function CameraShadowIcon({ style }: { style: WebcamShadowStyle }) { + const filterId = `camera-shadow-${style.id}`; + const unit = 12 / 216; + return ( + + ); +} + function namedLevelRow( label: string, options: ReadonlyArray<{ value: number; label: string }>, diff --git a/src/i18n/locales/ar/settings.json b/src/i18n/locales/ar/settings.json index 2e599890e4..30a905a121 100644 --- a/src/i18n/locales/ar/settings.json +++ b/src/i18n/locales/ar/settings.json @@ -319,7 +319,21 @@ "webcamBackground": "خلفية الكاميرا", "helpNoWebcam": "لا يحتوي هذا المشروع على كاميرا، لذلك فإن عناصر التحكم في التخطيط معطّلة ويعرض الإعداد المسبق «بدون كاميرا». يُحتفظ بالتخطيط المحفوظ لحين إضافة كاميرا.", "title": "تخطيط الكاميرا", - "noWebcam": "بدون كاميرا" + "noWebcam": "بدون كاميرا", + "cameraShadow": { + "none": "بلا", + "close": "قريب", + "soft": "ناعم", + "lifted": "مرتفع", + "floating": "عائم", + "ambient": "محيطي", + "noneTip": "بلا ظل", + "closeTip": "مستقر على الخلفية: ظل قصير وأغمق", + "softTip": "ارتفاع خفيف مع ظل قصير", + "liftedTip": "مرتفع بوضوح، ويسقط الظل أبعد", + "floatingTip": "عالٍ فوق الخلفية: ظل واسع وخفيف", + "ambientTip": "توهج متساوٍ من كل الجهات، كما تحت سماء غائمة" + } }, "textAnimation": { "slideLeft": "انزلاق لليسار", diff --git a/src/i18n/locales/cs/settings.json b/src/i18n/locales/cs/settings.json index bdfc5bd6e3..09d6394c4d 100644 --- a/src/i18n/locales/cs/settings.json +++ b/src/i18n/locales/cs/settings.json @@ -319,7 +319,21 @@ "webcamBackground": "Pozadí kamery", "helpNoWebcam": "Tento projekt nemá kameru, takže ovládání rozvržení je vypnuto a předvolba zobrazuje „Bez webkamery”. Vaše uložené rozvržení je zachováno pro případ přidání kamery.", "title": "Rozvržení kamery", - "noWebcam": "Bez webkamery" + "noWebcam": "Bez webkamery", + "cameraShadow": { + "none": "Žádný", + "close": "Blízký", + "soft": "Měkký", + "lifted": "Zvednutý", + "floating": "Vznášející se", + "ambient": "Rozptýlený", + "noneTip": "Bez stínu", + "closeTip": "Leží na pozadí: krátký, tmavší stín", + "softTip": "Mírné nadzvednutí s krátkým stínem", + "liftedTip": "Zřetelně zvednutý, stín padá níž", + "floatingTip": "Vysoko nad pozadím: široký, světlý stín", + "ambientTip": "Rovnoměrná záře na všech stranách, jako pod zataženou oblohou" + } }, "textAnimation": { "slideLeft": "Posun doleva", diff --git a/src/i18n/locales/de/settings.json b/src/i18n/locales/de/settings.json index 61707f28eb..83dbadfe34 100644 --- a/src/i18n/locales/de/settings.json +++ b/src/i18n/locales/de/settings.json @@ -319,7 +319,21 @@ "webcamBackground": "Kamera-Hintergrund", "helpNoWebcam": "Dieses Projekt hat keine Kamera, deshalb sind die Layout-Regler aus und die Vorgabe zeigt „Keine Webcam“. Dein gespeichertes Layout bleibt erhalten, falls später eine Kamera dazukommt.", "title": "Kamera-Layout", - "noWebcam": "Keine Webcam" + "noWebcam": "Keine Webcam", + "cameraShadow": { + "none": "Keiner", + "close": "Nah", + "soft": "Weich", + "lifted": "Angehoben", + "floating": "Schwebend", + "ambient": "Umgebung", + "noneTip": "Kein Schatten", + "closeTip": "Liegt auf dem Hintergrund: ein enger, dunklerer Schatten", + "softTip": "Leicht angehoben, mit kurzem Schattenwurf", + "liftedTip": "Deutlich angehoben, der Schatten fällt weiter nach unten", + "floatingTip": "Hoch über dem Hintergrund: ein breiter, heller Schatten", + "ambientTip": "Ein gleichmäßiger Schein auf allen Seiten, wie bei bedecktem Himmel" + } }, "textAnimation": { "slideLeft": "Nach links schieben", diff --git a/src/i18n/locales/en/settings.json b/src/i18n/locales/en/settings.json index 122ff48143..47b3f4faea 100644 --- a/src/i18n/locales/en/settings.json +++ b/src/i18n/locales/en/settings.json @@ -319,7 +319,21 @@ "webcamBackground": "Camera background", "helpNoWebcam": "This project has no camera, so the layout controls are off and the preset reads “No webcam”. Your saved layout is kept for when a camera is added.", "title": "Camera layout", - "noWebcam": "No webcam" + "noWebcam": "No webcam", + "cameraShadow": { + "none": "None", + "close": "Close", + "soft": "Soft", + "lifted": "Lifted", + "floating": "Floating", + "ambient": "Ambient", + "noneTip": "No shadow", + "closeTip": "Resting on the background: a tight, darker shadow", + "softTip": "A gentle lift with a short drop", + "liftedTip": "Clearly raised, the shadow falls further below", + "floatingTip": "High above the background: a wide, light shadow", + "ambientTip": "An even glow on every side, as under an overcast sky" + } }, "textAnimation": { "slideLeft": "Slide left", diff --git a/src/i18n/locales/es/settings.json b/src/i18n/locales/es/settings.json index 7f6ae74928..d677ef9866 100644 --- a/src/i18n/locales/es/settings.json +++ b/src/i18n/locales/es/settings.json @@ -319,7 +319,21 @@ "webcamBackground": "Fondo de la cámara", "helpNoWebcam": "Este proyecto no tiene cámara, así que los controles de diseño están desactivados y el preajuste muestra «Sin cámara». Tu diseño guardado se conserva para cuando añadas una cámara.", "title": "Disposición de cámara", - "noWebcam": "Sin cámara" + "noWebcam": "Sin cámara", + "cameraShadow": { + "none": "Ninguna", + "close": "Cercana", + "soft": "Suave", + "lifted": "Elevada", + "floating": "Flotante", + "ambient": "Ambiental", + "noneTip": "Sin sombra", + "closeTip": "Apoyada en el fondo: una sombra corta y más oscura", + "softTip": "Una ligera elevación con una caída corta", + "liftedTip": "Claramente elevada, la sombra cae más abajo", + "floatingTip": "Muy por encima del fondo: una sombra amplia y ligera", + "ambientTip": "Un brillo uniforme por todos lados, como bajo un cielo nublado" + } }, "textAnimation": { "slideLeft": "Deslizar izquierda", diff --git a/src/i18n/locales/fr/settings.json b/src/i18n/locales/fr/settings.json index 8cee3e8460..7f88c5f80e 100644 --- a/src/i18n/locales/fr/settings.json +++ b/src/i18n/locales/fr/settings.json @@ -319,7 +319,21 @@ "webcamBackground": "Arrière-plan de la caméra", "helpNoWebcam": "Ce projet n’a pas de caméra : les réglages de disposition sont désactivés et le préréglage affiche « Sans webcam ». Votre disposition enregistrée est conservée pour le jour où une caméra sera ajoutée.", "title": "Disposition caméra", - "noWebcam": "Sans webcam" + "noWebcam": "Sans webcam", + "cameraShadow": { + "none": "Aucune", + "close": "Proche", + "soft": "Douce", + "lifted": "Surélevée", + "floating": "Flottante", + "ambient": "Diffuse", + "noneTip": "Pas d’ombre", + "closeTip": "Posée sur le fond : une ombre courte et plus sombre", + "softTip": "Un léger décollement, avec une ombre courte", + "liftedTip": "Nettement surélevée : l’ombre tombe plus bas", + "floatingTip": "Très au-dessus du fond : une ombre large et légère", + "ambientTip": "Une lueur égale tout autour, comme sous un ciel couvert" + } }, "textAnimation": { "slideLeft": "Glisser à gauche", diff --git a/src/i18n/locales/it/settings.json b/src/i18n/locales/it/settings.json index 977040db8d..55a2c6f53a 100644 --- a/src/i18n/locales/it/settings.json +++ b/src/i18n/locales/it/settings.json @@ -319,7 +319,21 @@ "webcamBackground": "Sfondo della fotocamera", "helpNoWebcam": "Questo progetto non ha una webcam, quindi i controlli di layout sono disattivati e il preset mostra «Nessuna webcam». Il layout salvato viene conservato per quando aggiungerai una webcam.", "title": "Disposizione camera", - "noWebcam": "Nessuna webcam" + "noWebcam": "Nessuna webcam", + "cameraShadow": { + "none": "Nessuna", + "close": "Vicina", + "soft": "Morbida", + "lifted": "Sollevata", + "floating": "Fluttuante", + "ambient": "Ambientale", + "noneTip": "Nessuna ombra", + "closeTip": "Appoggiata allo sfondo: un’ombra stretta e più scura", + "softTip": "Un leggero sollevamento con una caduta breve", + "liftedTip": "Chiaramente sollevata, l’ombra cade più in basso", + "floatingTip": "Molto sopra lo sfondo: un’ombra ampia e leggera", + "ambientTip": "Un alone uniforme su ogni lato, come sotto un cielo coperto" + } }, "textAnimation": { "slideLeft": "Scivola a sinistra", diff --git a/src/i18n/locales/ja-JP/settings.json b/src/i18n/locales/ja-JP/settings.json index ec739e70ee..80045d76e6 100644 --- a/src/i18n/locales/ja-JP/settings.json +++ b/src/i18n/locales/ja-JP/settings.json @@ -319,7 +319,21 @@ "webcamBackground": "カメラ背景", "helpNoWebcam": "このプロジェクトにはカメラがないため、レイアウトの設定は無効で、プリセットは「Webカメラなし」と表示されます。保存されたレイアウトは、カメラを追加したときのために保持されます。", "title": "カメラレイアウト", - "noWebcam": "Webカメラなし" + "noWebcam": "Webカメラなし", + "cameraShadow": { + "none": "なし", + "close": "密着", + "soft": "ソフト", + "lifted": "浮き", + "floating": "フロート", + "ambient": "アンビエント", + "noneTip": "影なし", + "closeTip": "背景に接している:短く濃い影", + "softTip": "少し浮いた、短い影", + "liftedTip": "はっきり浮き上がり、影がより下に落ちる", + "floatingTip": "背景から高く離れた:広く淡い影", + "ambientTip": "曇り空の下のように、全方向に均一な柔らかい影" + } }, "textAnimation": { "slideLeft": "左へスライド", diff --git a/src/i18n/locales/ko-KR/settings.json b/src/i18n/locales/ko-KR/settings.json index 12c13cd7f4..279c41f12d 100644 --- a/src/i18n/locales/ko-KR/settings.json +++ b/src/i18n/locales/ko-KR/settings.json @@ -319,7 +319,21 @@ "webcamBackground": "카메라 배경", "helpNoWebcam": "이 프로젝트에는 카메라가 없어 레이아웃 설정이 비활성화되고 프리셋이 “웹캠 없음”으로 표시됩니다. 저장된 레이아웃은 카메라를 추가할 때를 위해 유지됩니다.", "title": "카메라 레이아웃", - "noWebcam": "웹캠 없음" + "noWebcam": "웹캠 없음", + "cameraShadow": { + "none": "없음", + "close": "밀착", + "soft": "부드럽게", + "lifted": "떠 있음", + "floating": "공중", + "ambient": "주변광", + "noneTip": "그림자 없음", + "closeTip": "배경에 붙어 있음: 짧고 더 진한 그림자", + "softTip": "살짝 떠 있고 그림자가 짧게 떨어짐", + "liftedTip": "뚜렷하게 떠 있어 그림자가 더 아래로 떨어짐", + "floatingTip": "배경 위 높이 떠 있음: 넓고 옅은 그림자", + "ambientTip": "흐린 하늘 아래처럼 모든 방향으로 고르게 퍼지는 빛" + } }, "textAnimation": { "slideLeft": "왼쪽 슬라이드", diff --git a/src/i18n/locales/nl/settings.json b/src/i18n/locales/nl/settings.json index 9483b1b27d..f72e7aa985 100644 --- a/src/i18n/locales/nl/settings.json +++ b/src/i18n/locales/nl/settings.json @@ -319,7 +319,21 @@ "webcamBackground": "Camera-achtergrond", "helpNoWebcam": "Dit project heeft geen camera, dus de lay-outbediening staat uit en de preset toont “Geen webcam”. Je opgeslagen lay-out blijft bewaard voor als er een camera wordt toegevoegd.", "title": "Cameralay-out", - "noWebcam": "Geen webcam" + "noWebcam": "Geen webcam", + "cameraShadow": { + "none": "Geen", + "close": "Dichtbij", + "soft": "Zacht", + "lifted": "Opgetild", + "floating": "Zwevend", + "ambient": "Omgeving", + "noneTip": "Geen schaduw", + "closeTip": "Rust op de achtergrond: een korte, donkerdere schaduw", + "softTip": "Licht opgetild, met een korte val", + "liftedTip": "Duidelijk opgetild, de schaduw valt verder naar beneden", + "floatingTip": "Hoog boven de achtergrond: een brede, lichte schaduw", + "ambientTip": "Een gelijkmatige gloed aan alle kanten, als onder een bewolkte lucht" + } }, "textAnimation": { "slideLeft": "Naar links schuiven", diff --git a/src/i18n/locales/pl/settings.json b/src/i18n/locales/pl/settings.json index 1e00b6bcb1..c33cfd7704 100644 --- a/src/i18n/locales/pl/settings.json +++ b/src/i18n/locales/pl/settings.json @@ -319,7 +319,21 @@ "webcamBackground": "Tło kamery", "helpNoWebcam": "Ten projekt nie ma kamery, więc sterowanie układem jest wyłączone, a ustawienie pokazuje „Brak kamery”. Zapisany układ zostanie zachowany na wypadek dodania kamery.", "title": "Układ kamery", - "noWebcam": "Brak kamery" + "noWebcam": "Brak kamery", + "cameraShadow": { + "none": "Brak", + "close": "Bliski", + "soft": "Miękki", + "lifted": "Uniesiony", + "floating": "Unoszący się", + "ambient": "Rozproszony", + "noneTip": "Bez cienia", + "closeTip": "Leży na tle: krótki, ciemniejszy cień", + "softTip": "Lekkie uniesienie z krótkim cieniem", + "liftedTip": "Wyraźnie uniesiony, cień pada niżej", + "floatingTip": "Wysoko nad tłem: szeroki, jasny cień", + "ambientTip": "Równa poświata z każdej strony, jak pod zachmurzonym niebem" + } }, "textAnimation": { "slideLeft": "Przesuń w lewo", diff --git a/src/i18n/locales/pt-BR/settings.json b/src/i18n/locales/pt-BR/settings.json index 65f8c2761a..c4737f2e4d 100644 --- a/src/i18n/locales/pt-BR/settings.json +++ b/src/i18n/locales/pt-BR/settings.json @@ -319,7 +319,21 @@ "webcamBackground": "Plano de fundo da câmera", "helpNoWebcam": "Este projeto não tem câmera, então os controles de layout estão desativados e a predefinição mostra “Sem Webcam”. Seu layout salvo é mantido para quando você adicionar uma câmera.", "title": "Layout da câmera", - "noWebcam": "Sem Webcam" + "noWebcam": "Sem Webcam", + "cameraShadow": { + "none": "Nenhuma", + "close": "Próxima", + "soft": "Suave", + "lifted": "Elevada", + "floating": "Flutuante", + "ambient": "Ambiente", + "noneTip": "Sem sombra", + "closeTip": "Apoiada no fundo: uma sombra curta e mais escura", + "softTip": "Uma leve elevação com uma queda curta", + "liftedTip": "Claramente elevada, a sombra cai mais abaixo", + "floatingTip": "Bem acima do fundo: uma sombra ampla e leve", + "ambientTip": "Um brilho uniforme em todos os lados, como sob um céu nublado" + } }, "textAnimation": { "slideLeft": "Deslizar à Esquerda", diff --git a/src/i18n/locales/ru/settings.json b/src/i18n/locales/ru/settings.json index d548578b61..a6de715eab 100644 --- a/src/i18n/locales/ru/settings.json +++ b/src/i18n/locales/ru/settings.json @@ -319,7 +319,21 @@ "webcamBackground": "Фон камеры", "helpNoWebcam": "В этом проекте нет камеры, поэтому настройки компоновки отключены, а пресет показывает «Без веб-камеры». Сохранённая компоновка останется на случай, если вы добавите камеру.", "title": "Расположение камеры", - "noWebcam": "Без веб-камеры" + "noWebcam": "Без веб-камеры", + "cameraShadow": { + "none": "Нет", + "close": "Близкая", + "soft": "Мягкая", + "lifted": "Приподнятая", + "floating": "Парящая", + "ambient": "Рассеянная", + "noneTip": "Без тени", + "closeTip": "Лежит на фоне: короткая, более тёмная тень", + "softTip": "Лёгкий подъём с короткой тенью", + "liftedTip": "Заметно приподнята, тень падает ниже", + "floatingTip": "Высоко над фоном: широкая, светлая тень", + "ambientTip": "Ровное свечение со всех сторон, как под пасмурным небом" + } }, "textAnimation": { "slideLeft": "Скольжение влево", diff --git a/src/i18n/locales/tr/settings.json b/src/i18n/locales/tr/settings.json index 26842ec8a0..cdf73800d5 100644 --- a/src/i18n/locales/tr/settings.json +++ b/src/i18n/locales/tr/settings.json @@ -319,7 +319,21 @@ "webcamBackground": "Kamera Arka Planı", "helpNoWebcam": "Bu projede kamera yok; bu yüzden yerleşim denetimleri kapalı ve ön ayar “Web kamerası yok” gösteriyor. Kaydettiğiniz yerleşim, bir kamera eklediğinizde kullanılmak üzere korunur.", "title": "Kamera düzeni", - "noWebcam": "Web kamerası yok" + "noWebcam": "Web kamerası yok", + "cameraShadow": { + "none": "Yok", + "close": "Yakın", + "soft": "Yumuşak", + "lifted": "Yükseltilmiş", + "floating": "Yüzen", + "ambient": "Ortam", + "noneTip": "Gölge yok", + "closeTip": "Arka plana yaslanmış: kısa, daha koyu bir gölge", + "softTip": "Kısa düşüşlü hafif bir yükselme", + "liftedTip": "Belirgin şekilde yükseltilmiş, gölge daha aşağı düşer", + "floatingTip": "Arka planın çok üstünde: geniş, açık bir gölge", + "ambientTip": "Kapalı bir gökyüzü altındaki gibi her yanda eşit bir parıltı" + } }, "textAnimation": { "slideLeft": "Sola Kaydırma", diff --git a/src/i18n/locales/vi/settings.json b/src/i18n/locales/vi/settings.json index ff225df50d..f085632e17 100644 --- a/src/i18n/locales/vi/settings.json +++ b/src/i18n/locales/vi/settings.json @@ -319,7 +319,21 @@ "webcamBackground": "Nền máy ảnh", "helpNoWebcam": "Dự án này không có camera nên các tùy chọn bố cục bị tắt và thiết lập sẵn hiển thị “Không có webcam”. Bố cục đã lưu của bạn vẫn được giữ lại cho khi bạn thêm camera.", "title": "Bố cục camera", - "noWebcam": "Không có webcam" + "noWebcam": "Không có webcam", + "cameraShadow": { + "none": "Không", + "close": "Sát", + "soft": "Mềm", + "lifted": "Nâng lên", + "floating": "Lơ lửng", + "ambient": "Khuếch tán", + "noneTip": "Không có bóng", + "closeTip": "Nằm sát nền: bóng ngắn và đậm hơn", + "softTip": "Nâng nhẹ với bóng đổ ngắn", + "liftedTip": "Nâng rõ rệt, bóng đổ xuống thấp hơn", + "floatingTip": "Cao hẳn trên nền: bóng rộng và nhạt", + "ambientTip": "Quầng sáng đều mọi phía, như dưới bầu trời u ám" + } }, "textAnimation": { "slideLeft": "Trượt sang trái", diff --git a/src/i18n/locales/zh-CN/settings.json b/src/i18n/locales/zh-CN/settings.json index 47a62d2ff3..bdbd880fe2 100644 --- a/src/i18n/locales/zh-CN/settings.json +++ b/src/i18n/locales/zh-CN/settings.json @@ -319,7 +319,21 @@ "webcamBackground": "摄像头背景", "helpNoWebcam": "此项目没有摄像头,因此布局控件已禁用,预设显示为“无摄像头”。你保存的布局会保留,以便添加摄像头后使用。", "title": "摄像头布局", - "noWebcam": "无摄像头" + "noWebcam": "无摄像头", + "cameraShadow": { + "none": "无", + "close": "贴近", + "soft": "柔和", + "lifted": "抬起", + "floating": "悬浮", + "ambient": "环境", + "noneTip": "无阴影", + "closeTip": "贴在背景上:短而较深的阴影", + "softTip": "轻微抬起,阴影较短", + "liftedTip": "明显抬起,阴影落得更低", + "floatingTip": "高悬于背景之上:宽而浅的阴影", + "ambientTip": "四周均匀的光晕,如同阴天下" + } }, "textAnimation": { "slideLeft": "向左滑动", diff --git a/src/i18n/locales/zh-TW/settings.json b/src/i18n/locales/zh-TW/settings.json index 9725a48f69..44d12fc8e8 100644 --- a/src/i18n/locales/zh-TW/settings.json +++ b/src/i18n/locales/zh-TW/settings.json @@ -319,7 +319,21 @@ "webcamBackground": "攝影機背景", "helpNoWebcam": "此專案沒有攝影機,因此版面配置控制項已停用,預設顯示為「無網路攝影機」。你儲存的版面配置會保留,以便新增攝影機後使用。", "title": "攝影機版面", - "noWebcam": "無網路攝影機" + "noWebcam": "無網路攝影機", + "cameraShadow": { + "none": "無", + "close": "貼近", + "soft": "柔和", + "lifted": "抬起", + "floating": "懸浮", + "ambient": "環境", + "noneTip": "無陰影", + "closeTip": "貼在背景上:短而較深的陰影", + "softTip": "輕微抬起,陰影較短", + "liftedTip": "明顯抬起,陰影落得更低", + "floatingTip": "高懸於背景之上:寬而淺的陰影", + "ambientTip": "四周均勻的光暈,如同陰天下" + } }, "textAnimation": { "slideLeft": "向左滑動", diff --git a/src/lib/ai-edition/store/editorSettings.test.ts b/src/lib/ai-edition/store/editorSettings.test.ts index a9f8b66646..908c717675 100644 --- a/src/lib/ai-edition/store/editorSettings.test.ts +++ b/src/lib/ai-edition/store/editorSettings.test.ts @@ -62,6 +62,34 @@ describe("getEditorSettings", () => { .webcamShadowIntensity, ).toBe(expected); }); + it("reads the camera shadow's softness and drop as the historical shadow by default", () => { + const snap = getEditorSettings(baseDoc); + expect(snap.webcamShadowBlur).toBe(1); + expect(snap.webcamShadowDistance).toBe(1); + const saved = patchEditorSettings(baseDoc, { + webcamShadowBlur: 2.4, + webcamShadowDistance: 3.5, + }); + const reopened = getEditorSettings(JSON.parse(JSON.stringify(saved))); + expect(reopened.webcamShadowBlur).toBe(2.4); + expect(reopened.webcamShadowDistance).toBe(3.5); + }); + it("bounds the camera shadow's softness and drop", () => { + const read = (legacyEditor: Record) => + getEditorSettings({ ...baseDoc, legacyEditor }); + expect(read({ webcamShadowBlur: 0, webcamShadowDistance: -2 })).toMatchObject({ + webcamShadowBlur: 0.25, + webcamShadowDistance: 0, + }); + expect(read({ webcamShadowBlur: 50, webcamShadowDistance: 50 })).toMatchObject({ + webcamShadowBlur: 3, + webcamShadowDistance: 4, + }); + expect(read({ webcamShadowBlur: "x", webcamShadowDistance: null })).toMatchObject({ + webcamShadowBlur: 1, + webcamShadowDistance: 1, + }); + }); it("returns the defaults when the document has no legacyEditor", () => { const snap = getEditorSettings(baseDoc); expect(snap.wallpaper).toBe(DEFAULT_EDITOR_SETTINGS.wallpaper); diff --git a/src/lib/ai-edition/store/editorSettings.ts b/src/lib/ai-edition/store/editorSettings.ts index b314f6f456..0031f9dac8 100644 --- a/src/lib/ai-edition/store/editorSettings.ts +++ b/src/lib/ai-edition/store/editorSettings.ts @@ -117,6 +117,9 @@ export interface EditorSettingsSnapshot { webcamReactiveZoom: boolean; webcamSizePreset: WebcamSizePreset; webcamShadowIntensity: number; + /** Camera shadow softness and drop, multiples of the tuned shadow. See `webcamShadowStyles.ts`. */ + webcamShadowBlur: number; + webcamShadowDistance: number; /** Where the picture-in-picture camera sits, at a constant distance from the border. */ webcamAnchor: WebcamAnchor; webcamCropRegion: CropRegion; @@ -175,6 +178,8 @@ interface LegacyShape { webcamReactiveZoom?: boolean; webcamSizePreset?: WebcamSizePreset; webcamShadowIntensity?: number; + webcamShadowBlur?: number; + webcamShadowDistance?: number; webcamAnchor?: WebcamAnchor; /** Written by builds that let the camera be dragged anywhere; read as the nearest anchor. */ webcamPosition?: WebcamPosition | null; @@ -311,6 +316,16 @@ export function getEditorSettings(doc: AxcutDocument | null | undefined): Editor "webcamShadowIntensity", defaults.webcamShadowIntensity, ), + webcamShadowBlur: readBounded( + legacy?.webcamShadowBlur, + "webcamShadowBlur", + defaults.webcamShadowBlur, + ), + webcamShadowDistance: readBounded( + legacy?.webcamShadowDistance, + "webcamShadowDistance", + defaults.webcamShadowDistance, + ), webcamReactiveZoom: bool( legacy?.webcamReactiveZoom, DEFAULT_EDITOR_SETTINGS.webcamReactiveZoom, @@ -373,6 +388,8 @@ export interface EditorSettingsPatch { webcamReactiveZoom?: boolean; webcamSizePreset?: WebcamSizePreset; webcamShadowIntensity?: number; + webcamShadowBlur?: number; + webcamShadowDistance?: number; webcamAnchor?: WebcamAnchor; webcamCropRegion?: CropRegion; webcamCropPan?: CropPan; diff --git a/src/lib/projectDefaults.ts b/src/lib/projectDefaults.ts index b99ea63802..612022105a 100644 --- a/src/lib/projectDefaults.ts +++ b/src/lib/projectDefaults.ts @@ -211,6 +211,10 @@ export interface ProjectAppearanceDefaults { webcamReactiveZoom: boolean; webcamSizePreset: number; webcamShadowIntensity: number; + /** Camera shadow softness, a multiple of the tuned spread. See `webcamShadowStyles.ts`. */ + webcamShadowBlur: number; + /** Camera shadow drop, a multiple of the tuned offset. See `webcamShadowStyles.ts`. */ + webcamShadowDistance: number; webcamAnchor: WebcamAnchor; webcamBackgroundMode: "none" | "transparent" | "blur" | "custom"; webcamWallpaper: string; @@ -258,6 +262,8 @@ export const DEFAULT_PROJECT_APPEARANCE: ProjectAppearanceDefaults = { webcamReactiveZoom: true, webcamSizePreset: 40, webcamShadowIntensity: 0.6, + webcamShadowBlur: 1, + webcamShadowDistance: 1, webcamAnchor: "bottom-right", webcamBackgroundMode: "none", webcamWallpaper: "/wallpapers/wallpaper11.jpg", @@ -298,6 +304,10 @@ export const DEFAULT_PROJECT_APPEARANCE: ProjectAppearanceDefaults = { export const SETTING_BOUNDS = { shadowIntensity: [0, 1], webcamShadowIntensity: [0, 1], + // Multiples of the tuned camera shadow; `WEBCAM_SHADOW_BLUR_RANGE` / `_DISTANCE_RANGE` in + // crates/compositor/src/frame_geometry.rs hold the native side to the same range. + webcamShadowBlur: [0.25, 3], + webcamShadowDistance: [0, 4], backgroundBlur: [0, 1], motionBlurAmount: [0, 1], // `ROUNDNESS_SLIDER_MAX_PX` (src/native/paramUnits.ts); a test holds the two together. diff --git a/src/lib/webcamShadowStyles.test.ts b/src/lib/webcamShadowStyles.test.ts new file mode 100644 index 0000000000..246128b78d --- /dev/null +++ b/src/lib/webcamShadowStyles.test.ts @@ -0,0 +1,70 @@ +import { describe, expect, it } from "vitest"; +import { DEFAULT_PROJECT_APPEARANCE, SETTING_BOUNDS } from "./projectDefaults"; +import { + DEFAULT_WEBCAM_SHADOW_STYLE, + matchWebcamShadowStyle, + WEBCAM_SHADOW_STYLES, + webcamShadowStylePatch, +} from "./webcamShadowStyles"; + +const within = (value: number, [lo, hi]: readonly [number, number]) => value >= lo && value <= hi; + +describe("webcam shadow styles", () => { + it("keeps the default style the shadow every project had before the styles", () => { + expect(webcamShadowStylePatch(DEFAULT_WEBCAM_SHADOW_STYLE)).toEqual({ + webcamShadowIntensity: DEFAULT_PROJECT_APPEARANCE.webcamShadowIntensity, + webcamShadowBlur: DEFAULT_PROJECT_APPEARANCE.webcamShadowBlur, + webcamShadowDistance: DEFAULT_PROJECT_APPEARANCE.webcamShadowDistance, + }); + expect( + matchWebcamShadowStyle({ + webcamShadowIntensity: DEFAULT_PROJECT_APPEARANCE.webcamShadowIntensity, + webcamShadowBlur: DEFAULT_PROJECT_APPEARANCE.webcamShadowBlur, + webcamShadowDistance: DEFAULT_PROJECT_APPEARANCE.webcamShadowDistance, + }), + ).toBe("soft"); + }); + + it("stays inside the stored bounds", () => { + for (const style of WEBCAM_SHADOW_STYLES) { + expect(within(style.intensity, SETTING_BOUNDS.webcamShadowIntensity)).toBe(true); + expect(within(style.blur, SETTING_BOUNDS.webcamShadowBlur)).toBe(true); + expect(within(style.distance, SETTING_BOUNDS.webcamShadowDistance)).toBe(true); + } + }); + + it("round-trips every style through its stored values", () => { + for (const style of WEBCAM_SHADOW_STYLES) { + expect(matchWebcamShadowStyle(webcamShadowStylePatch(style.id))).toBe(style.id); + } + }); + + // One light above the scene: the higher the camera floats, the further and wider its shadow. + it("drops and spreads the shadow further as the camera rises", () => { + const order = ["close", "soft", "lifted", "floating"].map( + (id) => WEBCAM_SHADOW_STYLES.find((s) => s.id === id)!, + ); + for (let i = 1; i < order.length; i++) { + expect(order[i].distance).toBeGreaterThan(order[i - 1].distance); + expect(order[i].blur).toBeGreaterThan(order[i - 1].blur); + } + }); + + it("reads any zero intensity as no shadow, and an unknown combination as no style", () => { + expect( + matchWebcamShadowStyle({ + webcamShadowIntensity: 0, + webcamShadowBlur: 3, + webcamShadowDistance: 0, + }), + ).toBe("none"); + // The earlier Strong level. + expect( + matchWebcamShadowStyle({ + webcamShadowIntensity: 0.9, + webcamShadowBlur: 1, + webcamShadowDistance: 1, + }), + ).toBeNull(); + }); +}); diff --git a/src/lib/webcamShadowStyles.ts b/src/lib/webcamShadowStyles.ts new file mode 100644 index 0000000000..4054f660ed --- /dev/null +++ b/src/lib/webcamShadowStyles.ts @@ -0,0 +1,82 @@ +/** + * The picture-in-picture camera's shadow styles. A style is three stored numbers, so a project, + * the agent or a hand edit can still hold any combination inside `SETTING_BOUNDS`; the pane only + * offers the combinations below, chosen by what they look like. + * + * Every style follows the same light: one soft source above the scene. The higher the camera + * floats, the further its shadow drops and the wider it spreads, and the lighter its core reads, + * which is what keeps a large shadow from turning into a dark halo. `ambient` is the exception on + * purpose: an overcast, almost directionless light that lifts the camera without a drop. + * + * - `intensity` is `webcamShadowIntensity`: 0.6 is the historical opacity (35%), and the + * compositor scales linearly from it (`frame_geometry.rs`, `WEBCAM_SHADOW_OPACITY`). + * - `blur` and `distance` multiply the tuned spread (32 px) and drop (12 px), both measured + * against a 1080 px frame and scaled with the output. + * + * `soft` is exactly the shadow every project had before the styles, and stays the default. + * + * Import-free on purpose, like `projectDefaults.ts`. + */ +export type WebcamShadowStyleId = "none" | "close" | "soft" | "lifted" | "floating" | "ambient"; + +export interface WebcamShadowStyle { + id: WebcamShadowStyleId; + intensity: number; + blur: number; + distance: number; +} + +export const WEBCAM_SHADOW_STYLES: readonly WebcamShadowStyle[] = [ + { id: "none", intensity: 0, blur: 1, distance: 1 }, + // Resting on the wallpaper: a tight, darker contact shadow (50%, 16 px, 4 px drop). + { id: "close", intensity: 0.85, blur: 0.5, distance: 0.35 }, + // The historical default (35%, 32 px, 12 px drop). + { id: "soft", intensity: 0.6, blur: 1, distance: 1 }, + // A clear lift off the page (41%, 51 px, 24 px drop). + { id: "lifted", intensity: 0.7, blur: 1.6, distance: 2 }, + // High above it: wide and diffuse, so its core stays light (38%, 77 px, 42 px drop). + { id: "floating", intensity: 0.65, blur: 2.4, distance: 3.5 }, + // Overcast light: an even glow on every side, almost no drop (29%, 64 px, 3 px drop). + { id: "ambient", intensity: 0.5, blur: 2, distance: 0.25 }, +]; + +export const DEFAULT_WEBCAM_SHADOW_STYLE: WebcamShadowStyleId = "soft"; + +/** The stored fields a style writes, ready to patch into the editor settings. */ +export function webcamShadowStylePatch(id: WebcamShadowStyleId): { + webcamShadowIntensity: number; + webcamShadowBlur: number; + webcamShadowDistance: number; +} { + const style = WEBCAM_SHADOW_STYLES.find((s) => s.id === id) ?? WEBCAM_SHADOW_STYLES[2]; + return { + webcamShadowIntensity: style.intensity, + webcamShadowBlur: style.blur, + webcamShadowDistance: style.distance, + }; +} + +const EPSILON = 1e-3; + +/** + * The style the stored values spell, or `null` for a combination no style offers: a project + * saved with the earlier Light / Strong levels, or one an agent tuned by hand. It keeps + * rendering exactly as stored; the pane simply shows no style pressed. + * + * Any zero intensity is `none`: without opacity the spread and drop draw nothing. + */ +export function matchWebcamShadowStyle(values: { + webcamShadowIntensity: number; + webcamShadowBlur: number; + webcamShadowDistance: number; +}): WebcamShadowStyleId | null { + if (values.webcamShadowIntensity <= EPSILON) return "none"; + const match = WEBCAM_SHADOW_STYLES.find( + (s) => + s.id !== "none" && + Math.abs(s.intensity - values.webcamShadowIntensity) < EPSILON && + Math.abs(s.blur - values.webcamShadowBlur) < EPSILON && + Math.abs(s.distance - values.webcamShadowDistance) < EPSILON, + ); + return match?.id ?? null; +} diff --git a/src/native/sceneDescription.test.ts b/src/native/sceneDescription.test.ts index 010ba77084..2850fd398a 100644 --- a/src/native/sceneDescription.test.ts +++ b/src/native/sceneDescription.test.ts @@ -150,6 +150,16 @@ describe("camera shadow scene contract", () => { } expect(buildSceneDescription(makeDoc()).effects.webcamShadow).toBe(0.6); }); + it("serializes the camera shadow's softness and drop, the historical shadow by default", () => { + const scene = buildSceneDescription( + makeDoc({ legacyEditor: { webcamShadowBlur: 2.4, webcamShadowDistance: 3.5 } }), + ); + expect(scene.effects).toMatchObject({ webcamShadowBlur: 2.4, webcamShadowDistance: 3.5 }); + expect(buildSceneDescription(makeDoc()).effects).toMatchObject({ + webcamShadowBlur: 1, + webcamShadowDistance: 1, + }); + }); }); describe("buildSceneDescription.background", () => { diff --git a/src/native/sceneDescription.ts b/src/native/sceneDescription.ts index f5946a44f7..17da1a70ff 100644 --- a/src/native/sceneDescription.ts +++ b/src/native/sceneDescription.ts @@ -438,6 +438,10 @@ export interface SceneEffects { shadow: number; /** Camera shadow strength, 0..1; absent payloads retain the historical medium shadow. */ webcamShadow?: number; + /** Camera shadow softness, a multiple of the tuned spread; absent = 1, the historical one. */ + webcamShadowBlur?: number; + /** Camera shadow drop, a multiple of the tuned offset; absent = 1, the historical one. */ + webcamShadowDistance?: number; /** * Roundness slider, as a fraction of a fixed 1080 px reference (`ROUNDNESS_REFERENCE_PX`). * @@ -1507,6 +1511,8 @@ export function buildSceneDescription( blur: settings.backgroundBlur, shadow: settings.shadowIntensity, webcamShadow: settings.webcamShadowIntensity, + webcamShadowBlur: settings.webcamShadowBlur, + webcamShadowDistance: settings.webcamShadowDistance, // The slider is in pixels of a 1080 reference, whatever the source resolution — // see `roundnessFrac`. No padding and no frame: the footage meets the scene's edges, // with no background to round against, so the corners go square and the stored value diff --git a/website/docs/editing-timeline.md b/website/docs/editing-timeline.md index 464f9adce2..ed87575ca6 100644 --- a/website/docs/editing-timeline.md +++ b/website/docs/editing-timeline.md @@ -31,7 +31,7 @@ A floating icon rail sits over the preview. Five facets: | Facet | What it controls | |---|---| | **Composition** | A background section (image, solid color, or gradient behind your recording; upload your own image or pick from presets), with an **Animation** row (None, Drift, Aurora, Waves) that moves gradients and images alike, and a background blur from 0 to 100%. Then the frame: shadow (None, Light, Medium, Strong), padding, corner roundness, and motion blur. Its **Format** row sets the output shape for preview and export: **Auto** (the default for new projects), which wraps the frame around your recording and camera layout with an even padding border, your clips' own shapes under **Original**, plus 16:9, 9:16, 1:1, 4:3, 4:5, 16:10, and 10:16. | -| **Camera layout** | Webcam composite: picture-in-picture, vertical stack, dual frame, or no webcam. Mirror and "shrink on zoom." For picture-in-picture: camera shape (square, or original: the camera's own proportions, so a portrait camera stays portrait), roundness (fully round, a square camera is a circle), size, and position: one of eight spots along the edge, always the same distance from it. Drag the webcam on the canvas and it snaps to the nearest one. | +| **Camera layout** | Webcam composite: picture-in-picture, vertical stack, dual frame, or no webcam. Mirror and "shrink on zoom." For picture-in-picture: camera shape (square, or original: the camera's own proportions, so a portrait camera stays portrait), roundness (fully round, a square camera is a circle), size, and position: one of eight spots along the edge, always the same distance from it. Drag the webcam on the canvas and it snaps to the nearest one. Its shadow has six styles, from tight to high: None, Close, Soft (the default), Lifted, Floating, and Ambient, an even glow with no drop. | | **Audio** | The output level, applied the same way in the preview and the export. | | **Cursor** | Only meaningful for recordings made in the editable cursor mode, on Windows, macOS, or Linux. Show/hide and auto-hide, the cursor style with its **3D cursor** switch, the cursor types (each type the video shows, drawn as recorded or as the arrow), sliders for size (up to eight times the system cursor), smoothing, and motion blur, click bounce (None, Light, Strong), and **Click impact**, which pushes the screen back on each click under every camera. | | **Transcript** | The aggregated transcript across every clip, editable — see [Transcript editing](./captions.md#transcript-editing). Its **Captions** button turns captions on, styles them, and translates them — see [Captions & transcript](./captions.md#captions). | diff --git a/website/i18n/de/docusaurus-plugin-content-docs/current/editing-timeline.md b/website/i18n/de/docusaurus-plugin-content-docs/current/editing-timeline.md index 394c154441..a7b4d2913b 100644 --- a/website/i18n/de/docusaurus-plugin-content-docs/current/editing-timeline.md +++ b/website/i18n/de/docusaurus-plugin-content-docs/current/editing-timeline.md @@ -31,7 +31,7 @@ Alles Folgende beschreibt den Modus **Edit**: oben eine Vorschau mit anpassbarer | Tab | Was er steuert | |---|---| | **Composition** | Ein Abschnitt für den Hintergrund (Bild, Volltonfarbe oder Verlauf hinter deiner Aufnahme; eigenes Bild hochladen oder eine Vorlage wählen), mit einer Zeile **Animation** (None, Drift, Aurora, Waves), die Verläufe und Bilder gleichermaßen bewegt, und einer Hintergrundunschärfe von 0 bis 100 %. Dann der Rahmen: Schatten (None, Light, Medium, Strong), Innenabstand, Eckenrundung und Bewegungsunschärfe. Die Zeile **Format** legt die Ausgabeform für Vorschau und Export fest: **Auto** (Standard für neue Projekte), bei dem sich das Bild mit einem gleichmäßigen Innenabstand als Rand um deine Aufnahme und das Webcam-Layout legt, die eigenen Formen deiner Clips unter **Original**, dazu 16:9, 9:16, 1:1, 4:3, 4:5, 16:10 und 10:16. | -| **Camera layout** | Webcam-Komposition: Bild-im-Bild, vertikal gestapelt, Doppelrahmen oder keine Webcam. Spiegeln und „Shrink on Zoom“. Für Bild-im-Bild: Kameraform (Quadrat, oder Original: die eigenen Proportionen der Kamera, eine Hochformat-Kamera bleibt also hochkant), Rundung (ganz rund wird eine quadratische Kamera zum Kreis), Größe und Position: einer von acht Plätzen am Rand, immer im gleichen Abstand dazu. Zieh die Webcam auf der Arbeitsfläche, und sie rastet am nächsten Platz ein. | +| **Camera layout** | Webcam-Komposition: Bild-im-Bild, vertikal gestapelt, Doppelrahmen oder keine Webcam. Spiegeln und „Shrink on Zoom“. Für Bild-im-Bild: Kameraform (Quadrat, oder Original: die eigenen Proportionen der Kamera, eine Hochformat-Kamera bleibt also hochkant), Rundung (ganz rund wird eine quadratische Kamera zum Kreis), Größe und Position: einer von acht Plätzen am Rand, immer im gleichen Abstand dazu. Zieh die Webcam auf der Arbeitsfläche, und sie rastet am nächsten Platz ein. Ihr Schatten hat sechs Stile, von eng bis hoch: Keiner, Nah, Weich (Standard), Angehoben, Schwebend und Umgebung, ein gleichmäßiger Schein ohne Schattenwurf. | | **Audio** | Der Ausgabepegel, in Vorschau und Export gleich angewendet. | | **Cursor** | Nur sinnvoll für Aufnahmen im bearbeitbaren Cursormodus, unter Windows, macOS oder Linux. Ein-/Ausblenden und automatisches Ausblenden, der Cursorstil mit seinem Schalter **3D cursor**, die Cursortypen (jeder Typ, den das Video zeigt, wie aufgezeichnet oder als Pfeil gezeichnet), Regler für Größe (bis zum Achtfachen des System-Cursors), Glättung und Bewegungsunschärfe, Klick-Bounce (None, Light, Strong) und **Click impact**, das den Bildschirm bei jedem Klick nach hinten drückt, unter jeder Kamera. | | **Transcript** | Das zusammengeführte Transkript aller Clips, bearbeitbar, siehe [Bearbeitung über das Transkript](./captions.md#transcript-editing). Die Schaltfläche **Captions** darin schaltet Untertitel ein, gestaltet und übersetzt sie, siehe [Untertitel & Transkript](./captions.md#captions). | diff --git a/website/i18n/es/docusaurus-plugin-content-docs/current/editing-timeline.md b/website/i18n/es/docusaurus-plugin-content-docs/current/editing-timeline.md index faf550751f..8836b9194e 100644 --- a/website/i18n/es/docusaurus-plugin-content-docs/current/editing-timeline.md +++ b/website/i18n/es/docusaurus-plugin-content-docs/current/editing-timeline.md @@ -31,7 +31,7 @@ Sobre la vista previa hay una barra flotante de íconos con cinco paneles: | Panel | Qué controla | |---|---| | **Composición** | Una sección de fondo (imagen, color sólido o degradado detrás de tu grabación; sube tu propia imagen o elige un preajuste), con una fila **Animación** (Ninguno, Deriva, Aurora, Ondas) que mueve por igual degradados e imágenes, y un desenfoque de fondo de 0 a 100 %. Luego el cuadro: sombra (Ninguna, Suave, Media, Fuerte), relleno, redondez de las esquinas y desenfoque de movimiento. Su fila **Formato** define la forma de salida para la vista previa y la exportación: **Auto** (la predeterminada en los proyectos nuevos), que ajusta el cuadro alrededor de tu grabación y de la disposición de cámara con un borde de relleno uniforme, las formas propias de tus clips en **Original**, más 16:9, 9:16, 1:1, 4:3, 4:5, 16:10 y 10:16. | -| **Disposición de cámara** | Composición de la cámara web: imagen en imagen, apilado vertical, marco dual o sin cámara. Reflejo y "reducir al ampliar". En imagen en imagen: forma de la cámara (cuadrada, u original: las proporciones propias de la cámara, así que una cámara vertical sigue vertical), redondez (del todo redonda, una cámara cuadrada es un círculo), tamaño y posición: uno de ocho puntos junto al borde, siempre a la misma distancia de él. Arrastra la cámara web sobre el lienzo y se ajusta al punto más cercano. | +| **Disposición de cámara** | Composición de la cámara web: imagen en imagen, apilado vertical, marco dual o sin cámara. Reflejo y "reducir al ampliar". En imagen en imagen: forma de la cámara (cuadrada, u original: las proporciones propias de la cámara, así que una cámara vertical sigue vertical), redondez (del todo redonda, una cámara cuadrada es un círculo), tamaño y posición: uno de ocho puntos junto al borde, siempre a la misma distancia de él. Arrastra la cámara web sobre el lienzo y se ajusta al punto más cercano. Su sombra tiene seis estilos, de pegada a elevada: Ninguna, Cercana, Suave (la predeterminada), Elevada, Flotante y Ambiental, un brillo uniforme sin caída. | | **Audio** | El nivel de salida, que se aplica igual en la vista previa y en la exportación. | | **Cursor** | Solo tiene sentido en grabaciones hechas en el modo de cursor editable, en Windows, macOS o Linux. Mostrar/ocultar y ocultar automáticamente, el estilo del cursor con su interruptor **Cursor 3D**, los tipos de cursor (cada tipo que muestra el video, dibujado tal como se grabó o como la flecha), controles deslizantes de tamaño (hasta ocho veces el cursor del sistema), suavizado y desenfoque de movimiento, el rebote al clic (Ninguno, Suave, Marcado) e **Impacto del clic**, que empuja la pantalla hacia atrás en cada clic con cualquier cámara. | | **Transcripción** | La transcripción conjunta de todos los clips, editable: consulta [Edición de la transcripción](./captions.md#transcript-editing). Su botón **Subtítulos** activa los subtítulos, les da estilo y los traduce: consulta [Subtítulos y transcripción](./captions.md#captions). | diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/current/editing-timeline.md b/website/i18n/fr/docusaurus-plugin-content-docs/current/editing-timeline.md index 0ae8b67e21..ee3bca5ec5 100644 --- a/website/i18n/fr/docusaurus-plugin-content-docs/current/editing-timeline.md +++ b/website/i18n/fr/docusaurus-plugin-content-docs/current/editing-timeline.md @@ -31,7 +31,7 @@ Une barre d'icônes flottante se superpose à l'aperçu. Elle donne accès à ci | Onglet | Ce qu'il contrôle | |---|---| | **Composition** | Une section d'arrière-plan (image, couleur unie ou dégradé derrière votre enregistrement ; importez votre propre image ou choisissez parmi les préréglages), avec une ligne **Animation** (Aucun, Dérive, Aurore, Vagues) qui anime aussi bien les dégradés que les images, et un flou d'arrière-plan de 0 à 100 %. Puis le cadre : l'ombre (Aucune, Légère, Moyenne, Forte), la marge, l'arrondi des coins et le flou de mouvement. Sa ligne **Format** définit la forme de sortie pour l'aperçu et l'export : **Auto** (par défaut pour les nouveaux projets), qui ajuste le cadre autour de votre enregistrement et de la disposition caméra avec une marge égale sur chaque bord, les formes propres à vos clips sous **Original**, plus 16:9, 9:16, 1:1, 4:3, 4:5, 16:10 et 10:16. | -| **Disposition caméra** | La composition de la webcam : incrustation d'image, empilement vertical, double cadre ou sans webcam. Effet miroir et « réduire au zoom ». En incrustation : forme de la caméra (carrée, ou originale : les proportions de la caméra elle-même, une caméra en portrait reste en portrait), arrondi (tout à fait ronde, une caméra carrée devient un cercle), taille et position : l'un des huit emplacements le long du bord, toujours à la même distance de celui-ci. Faites glisser la webcam sur le canevas : elle se cale sur l'emplacement le plus proche. | +| **Disposition caméra** | La composition de la webcam : incrustation d'image, empilement vertical, double cadre ou sans webcam. Effet miroir et « réduire au zoom ». En incrustation : forme de la caméra (carrée, ou originale : les proportions de la caméra elle-même, une caméra en portrait reste en portrait), arrondi (tout à fait ronde, une caméra carrée devient un cercle), taille et position : l'un des huit emplacements le long du bord, toujours à la même distance de celui-ci. Faites glisser la webcam sur le canevas : elle se cale sur l'emplacement le plus proche. Son ombre propose six styles, de la plus proche à la plus haute : Aucune, Proche, Douce (par défaut), Surélevée, Flottante et Diffuse, une lueur égale sans décalage. | | **Audio** | Le niveau de sortie, appliqué de la même façon dans l'aperçu et à l'export. | | **Curseur** | Utile uniquement pour les enregistrements faits en mode curseur éditable, sous Windows, macOS ou Linux. Afficher/masquer et le masquage automatique, le style du curseur avec son interrupteur **Curseur 3D**, les types de curseur (chaque type que montre la vidéo, dessiné tel qu'enregistré ou comme la flèche), des glissières pour la taille (jusqu'à huit fois le curseur système), le lissage et le flou de mouvement, le rebond au clic (Aucun, Léger, Marqué), et **Impact du clic**, qui repousse l'écran à chaque clic, avec toutes les caméras. | | **Transcription** | La transcription agrégée de tous les clips, modifiable : voir [Montage par la transcription](./captions.md#transcript-editing). Son bouton **Sous-titres** active les sous-titres, les met en forme et les traduit : voir [Sous-titres et transcription](./captions.md#captions). | diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/current/editing-timeline.md b/website/i18n/ja/docusaurus-plugin-content-docs/current/editing-timeline.md index 3308e3e7d2..08df889390 100644 --- a/website/i18n/ja/docusaurus-plugin-content-docs/current/editing-timeline.md +++ b/website/i18n/ja/docusaurus-plugin-content-docs/current/editing-timeline.md @@ -31,7 +31,7 @@ keywords: | パネル | 設定できる内容 | |---|---| | **コンポジション** | 背景のセクション(録画の背景に画像、単色、グラデーションを配置。自分の画像を読み込むか、プリセットから選択)。グラデーションにも画像にも同じように動きを付ける**アニメーション**の行(なし、ドリフト、オーロラ、ウェーブ)と、0〜100% の背景のぼかし。続いてフレーム:影(なし、弱、中、強)、余白、角の丸み、モーションブラー。**フォーマット**の行で、プレビューとエクスポートの出力形状を設定します。**自動**(新規プロジェクトの既定)は、録画とカメラレイアウトを均一な余白で囲むようにフレームを合わせます。**元のサイズ**にはクリップ自体の形状が並び、ほかに 16:9、9:16、1:1、4:3、4:5、16:10、10:16 を選べます。 | -| **カメラレイアウト** | ウェブカメラの合成:ピクチャーインピクチャ、縦並び、デュアルフレーム、Webカメラなし。左右反転と「ズーム時に縮小」。ピクチャーインピクチャでは、カメラの形状(正方形、またはオリジナル。オリジナルはカメラ本来の縦横比で、縦向きのカメラは縦向きのまま)、丸み(最大にすると正方形のカメラは円になります)、サイズ、位置(縁に沿った 8 か所のいずれかで、縁からの距離は常に同じ)を設定できます。キャンバス上でウェブカメラをドラッグすると、いちばん近い位置に吸着します。 | +| **カメラレイアウト** | ウェブカメラの合成:ピクチャーインピクチャ、縦並び、デュアルフレーム、Webカメラなし。左右反転と「ズーム時に縮小」。ピクチャーインピクチャでは、カメラの形状(正方形、またはオリジナル。オリジナルはカメラ本来の縦横比で、縦向きのカメラは縦向きのまま)、丸み(最大にすると正方形のカメラは円になります)、サイズ、位置(縁に沿った 8 か所のいずれかで、縁からの距離は常に同じ)を設定できます。キャンバス上でウェブカメラをドラッグすると、いちばん近い位置に吸着します。影は、近いものから高いものまで 6 種類のスタイルから選べます:なし、密着、ソフト(デフォルト)、浮き、フロート、そして落ち影のない均一な光のアンビエント。 | | **オーディオ** | 出力レベル。プレビューとエクスポートに同じように適用されます。 | | **カーソル** | Windows、macOS、Linux で、編集可能なカーソルのモードで録画した場合にのみ意味があります。表示/非表示と自動非表示、**3D カーソル**スイッチを含むカーソルのスタイル、カーソルの種類(動画に現れる種類ごとに、記録どおりに描くか矢印として描くか)、サイズ(システムカーソルの最大 8 倍)・スムージング・モーションブラーのスライダー、クリックバウンス(なし、弱、強)、そして**クリックの押し込み**。これはどのカメラでも、クリックのたびに画面を奥へ押し込みます。 | | **文字起こし** | すべてのクリップをまとめた文字起こしで、編集できます([文字起こしの編集](./captions.md#transcript-editing)を参照)。**字幕**ボタンで字幕をオンにし、スタイルを設定し、翻訳できます([字幕と文字起こし](./captions.md#captions)を参照)。 | diff --git a/website/i18n/pt-BR/docusaurus-plugin-content-docs/current/editing-timeline.md b/website/i18n/pt-BR/docusaurus-plugin-content-docs/current/editing-timeline.md index 4d883a0f9f..31a72e4829 100644 --- a/website/i18n/pt-BR/docusaurus-plugin-content-docs/current/editing-timeline.md +++ b/website/i18n/pt-BR/docusaurus-plugin-content-docs/current/editing-timeline.md @@ -31,7 +31,7 @@ Uma barra flutuante de ícones fica sobre a pré-visualização. São cinco abas | Aba | O que controla | |---|---| | **Composição** | Uma seção de fundo (imagem, cor sólida ou gradiente atrás da gravação; envie sua própria imagem ou escolha uma predefinição), com uma linha **Animação** (Nenhum, Deriva, Aurora, Ondas) que movimenta tanto gradientes quanto imagens, e um desfoque do fundo de 0 a 100%. Depois, o quadro: sombra (Nenhuma, Leve, Média, Forte), espaçamento, arredondamento dos cantos e desfoque de movimento. A linha **Formato** define a proporção de saída da pré-visualização e da exportação: **Auto** (o padrão para projetos novos), que ajusta o quadro em volta da gravação e do layout da câmera com uma borda de espaçamento uniforme, as proporções dos seus clipes em **Original**, além de 16:9, 9:16, 1:1, 4:3, 4:5, 16:10 e 10:16. | -| **Layout da câmera** | Composição da webcam: picture-in-picture, empilhamento vertical, quadro duplo ou sem webcam. Espelhamento e "encolher ao ampliar". No picture-in-picture: formato da câmera (quadrado, ou original: as proporções da própria câmera, então uma câmera vertical continua vertical), arredondamento (toda arredondada, uma câmera quadrada vira um círculo), tamanho e posição: um de oito pontos junto à borda, sempre à mesma distância dela. Arraste a webcam no canvas e ela se encaixa no ponto mais próximo. | +| **Layout da câmera** | Composição da webcam: picture-in-picture, empilhamento vertical, quadro duplo ou sem webcam. Espelhamento e "encolher ao ampliar". No picture-in-picture: formato da câmera (quadrado, ou original: as proporções da própria câmera, então uma câmera vertical continua vertical), arredondamento (toda arredondada, uma câmera quadrada vira um círculo), tamanho e posição: um de oito pontos junto à borda, sempre à mesma distância dela. Arraste a webcam no canvas e ela se encaixa no ponto mais próximo. A sombra tem seis estilos, da mais rente à mais alta: Nenhuma, Próxima, Suave (o padrão), Elevada, Flutuante e Ambiente, um brilho uniforme sem queda. | | **Áudio** | O nível de saída, aplicado da mesma forma na pré-visualização e na exportação. | | **Cursor** | Só faz sentido para gravações feitas no modo de cursor editável, no Windows, no macOS ou no Linux. Mostrar/ocultar e ocultar automaticamente, o estilo do cursor com a chave **Cursor 3D**, os tipos de cursor (cada tipo que o vídeo mostra, desenhado como foi gravado ou como a seta), controles deslizantes de tamanho (até oito vezes o cursor do sistema), suavização e desfoque de movimento, o rebote ao clicar (Nenhum, Leve, Forte) e **Impacto do clique**, que empurra a tela para trás a cada clique, com qualquer câmera. | | **Transcrição** | A transcrição agregada de todos os clipes, editável — veja [Edição da transcrição](./captions.md#transcript-editing). O botão **Legendas** ativa as legendas, define o estilo delas e as traduz — veja [Legendas e transcrição](./captions.md#captions). | diff --git a/website/i18n/zh-CN/docusaurus-plugin-content-docs/current/editing-timeline.md b/website/i18n/zh-CN/docusaurus-plugin-content-docs/current/editing-timeline.md index e508952cbf..05a77ff320 100644 --- a/website/i18n/zh-CN/docusaurus-plugin-content-docs/current/editing-timeline.md +++ b/website/i18n/zh-CN/docusaurus-plugin-content-docs/current/editing-timeline.md @@ -31,7 +31,7 @@ keywords: | 面板 | 控制内容 | |---|---| | **画面合成** | 先是背景部分(在录制画面后面放置图片、纯色或渐变;可以上传自己的图片,也可以从预设中选择),其中的**动画**一行(无、漂移、极光、波浪)让渐变和图片同样动起来,还有 0 到 100% 的背景模糊。然后是画框:阴影(无、轻、中、强)、内边距、圆角和运动模糊。其中的**格式**一行设置预览和导出的输出形状:**自动**(新项目的默认值)让画面包住录制内容和摄像头布局,四周留出均匀的内边距;**原始**下列出片段自身的形状,另外还有 16:9、9:16、1:1、4:3、4:5、16:10 和 10:16。 | -| **摄像头布局** | 摄像头的合成方式:画中画、垂直堆叠、双画框或无摄像头。还有镜像和“缩放时缩小”。画中画下可设置摄像头形状(正方形,或原始:保持摄像头自身的比例,竖屏摄像头仍是竖屏)、圆角(调到最圆时,正方形摄像头就是圆形)、大小和位置:沿边缘的八个位置之一,与边缘的距离始终相同。在画布上拖动摄像头,它会吸附到最近的位置。 | +| **摄像头布局** | 摄像头的合成方式:画中画、垂直堆叠、双画框或无摄像头。还有镜像和“缩放时缩小”。画中画下可设置摄像头形状(正方形,或原始:保持摄像头自身的比例,竖屏摄像头仍是竖屏)、圆角(调到最圆时,正方形摄像头就是圆形)、大小和位置:沿边缘的八个位置之一,与边缘的距离始终相同。在画布上拖动摄像头,它会吸附到最近的位置。它的阴影有六种样式,从贴近到高悬:无、贴近、柔和(默认)、抬起、悬浮,以及没有落影、四周均匀的环境。 | | **音频** | 输出电平,在预览和导出中以相同方式应用。 | | **光标** | 仅对在 Windows、macOS 或 Linux 上以可编辑光标模式录制的内容有意义。包括显示/隐藏和闲置时自动隐藏,带有**3D 光标**开关的光标样式,光标类型(视频中出现的每种类型,可按录制原样绘制或绘制为箭头),大小(最大为系统光标的八倍)、平滑和运动模糊的滑块,点击弹跳(无、轻、强),以及**点击按压**:在任何镜头下,每次点击都会把画面向后推。 | | **转录文本** | 汇总所有片段的转录文本,可以编辑,请参阅[编辑转录文本](./captions.md#transcript-editing)。其中的**字幕**按钮用于开启字幕、设置样式和翻译,请参阅[字幕与转录](./captions.md#captions)。 | diff --git a/website/i18n/zh-TW/docusaurus-plugin-content-docs/current/editing-timeline.md b/website/i18n/zh-TW/docusaurus-plugin-content-docs/current/editing-timeline.md index fe50a8537f..48aac187e3 100644 --- a/website/i18n/zh-TW/docusaurus-plugin-content-docs/current/editing-timeline.md +++ b/website/i18n/zh-TW/docusaurus-plugin-content-docs/current/editing-timeline.md @@ -31,7 +31,7 @@ keywords: | 面板 | 可控制的內容 | |---|---| | **畫面合成** | 背景區塊(在錄影後方放上圖片、純色或漸層;可以上傳自己的圖片或從預設中挑選),其中的**動畫**列(無、漂移、極光、波浪)讓漸層與圖片同樣動起來,還有 0 到 100% 的背景模糊。接著是畫框:陰影(無、輕、中、強)、內邊距、圓角與動態模糊。其中的**格式**列會設定預覽與匯出的輸出形狀:**自動**(新專案的預設值)會讓畫面包住錄影與攝影機版面,四周留出均勻的內邊距;**原始**底下列出片段本身的形狀,另外還有 16:9、9:16、1:1、4:3、4:5、16:10 與 10:16。 | -| **攝影機版面** | 網路攝影機的合成方式:子母畫面、垂直堆疊、雙畫框或無網路攝影機。鏡像與「縮放時縮小」。子母畫面下可設定攝影機形狀(正方形,或原始:保持攝影機本身的比例,直向攝影機仍是直向)、圓角(調到最圓時,正方形攝影機就是圓形)、大小與位置:沿邊緣的八個位置之一,與邊緣的距離始終相同。在畫布上拖曳網路攝影機,它會吸附到最近的位置。 | +| **攝影機版面** | 網路攝影機的合成方式:子母畫面、垂直堆疊、雙畫框或無網路攝影機。鏡像與「縮放時縮小」。子母畫面下可設定攝影機形狀(正方形,或原始:保持攝影機本身的比例,直向攝影機仍是直向)、圓角(調到最圓時,正方形攝影機就是圓形)、大小與位置:沿邊緣的八個位置之一,與邊緣的距離始終相同。在畫布上拖曳網路攝影機,它會吸附到最近的位置。它的陰影有六種樣式,從貼近到高懸:無、貼近、柔和(預設)、抬起、懸浮,以及沒有落影、四周均勻的環境。 | | **音訊** | 輸出音量,在預覽與匯出中以相同方式套用。 | | **游標** | 只對在 Windows、macOS 或 Linux 上以可編輯游標模式錄製的錄影有意義。顯示/隱藏與閒置時自動隱藏,附有**3D 游標**開關的游標樣式,游標類型(影片中出現的每種類型,可依錄製原樣繪製或繪製為箭頭),大小(最大為系統游標的八倍)、平滑與動態模糊的滑桿,點擊彈跳(無、輕、強),以及**點擊按壓**:在任何鏡頭下,每次點擊都會把畫面往後推。 | | **逐字稿** | 彙整所有片段的逐字稿,可以直接編輯,請參閱[逐字稿編輯](./captions.md#transcript-editing)。其中的**字幕**按鈕可以開啟字幕、設定樣式並翻譯,請參閱[字幕與逐字稿](./captions.md#captions)。 | From e6af467c8d0300151b681b2b3f36f9da35f66118 Mon Sep 17 00:00:00 2001 From: Christian Almurr Date: Wed, 18 Nov 2026 10:44:31 +0100 Subject: [PATCH 2/4] feat: customizable camera shadow with presets Turn the camera shadow into presets plus a Customize section: - Six presets (None, Close, Soft, Lifted, Floating, Ambient) shown as tiles that each draw their own shadow. Soft is the historical shadow, value for value. - Customize, a disclosure under the tiles: a position pad where the shadow is dragged (snaps to the axes, arrow keys nudge), then blur, spread, opacity and colour. An edited preset stays pressed with a dot, and Reset brings its values back. The project stores the preset and six values (offset x/y, blur, spread in pixels at 1080, opacity, colour). A project from before reads its strength as the matching opacity of the tuned shadow. The scene sends one webcamShadowStyle, lengths as fractions of 1080 and an sRGB colour; the compositor clamps it, grows or shrinks the caster for spread, and the Metal, D3D11 and wgpu backends draw it in its colour. Co-Authored-By: Claude Opus 5.5 --- crates/compositor/src/compositor_linux.rs | 20 +- crates/compositor/src/compositor_macos.rs | 24 +- crates/compositor/src/compositor_windows.rs | 22 +- crates/compositor/src/frame_geometry.rs | 174 +++++-- crates/compositor/src/scene.rs | 23 +- .../CameraShadowControls.module.css | 321 +++++++++++++ .../ai-edition/CameraShadowControls.tsx | 433 ++++++++++++++++++ .../ai-edition/RightPanes.layout.test.tsx | 80 +++- src/components/ai-edition/RightPanes.tsx | 78 +--- src/i18n/locales/ar/settings.json | 14 +- src/i18n/locales/cs/settings.json | 14 +- src/i18n/locales/de/settings.json | 14 +- src/i18n/locales/en/settings.json | 14 +- src/i18n/locales/es/settings.json | 14 +- src/i18n/locales/fr/settings.json | 14 +- src/i18n/locales/it/settings.json | 14 +- src/i18n/locales/ja-JP/settings.json | 14 +- src/i18n/locales/ko-KR/settings.json | 14 +- src/i18n/locales/nl/settings.json | 14 +- src/i18n/locales/pl/settings.json | 14 +- src/i18n/locales/pt-BR/settings.json | 14 +- src/i18n/locales/ru/settings.json | 14 +- src/i18n/locales/tr/settings.json | 14 +- src/i18n/locales/vi/settings.json | 14 +- src/i18n/locales/zh-CN/settings.json | 14 +- src/i18n/locales/zh-TW/settings.json | 14 +- .../ai-edition/store/editorSettings.test.ts | 106 +++-- src/lib/ai-edition/store/editorSettings.ts | 98 +++- src/lib/projectDefaults.ts | 33 +- src/lib/webcamShadowStyles.test.ts | 116 +++-- src/lib/webcamShadowStyles.ts | 194 +++++--- src/native/sceneDescription.test.ts | 45 +- src/native/sceneDescription.ts | 52 ++- website/docs/editing-timeline.md | 2 +- .../current/editing-timeline.md | 2 +- .../current/editing-timeline.md | 2 +- .../current/editing-timeline.md | 2 +- .../current/editing-timeline.md | 2 +- .../current/editing-timeline.md | 2 +- .../current/editing-timeline.md | 2 +- .../current/editing-timeline.md | 2 +- 41 files changed, 1684 insertions(+), 389 deletions(-) create mode 100644 src/components/ai-edition/CameraShadowControls.module.css create mode 100644 src/components/ai-edition/CameraShadowControls.tsx diff --git a/crates/compositor/src/compositor_linux.rs b/crates/compositor/src/compositor_linux.rs index 641a757ddc..9d9e9b29b7 100644 --- a/crates/compositor/src/compositor_linux.rs +++ b/crates/compositor/src/compositor_linux.rs @@ -1637,6 +1637,7 @@ impl Compositor { spread: f32, offset_px: [f32; 2], opacity: f32, + color: [f32; 3], ) -> LayerCB { let (rw, rh) = (self.render_w as f32, self.render_h as f32); let (sx, sy) = (spread / rw, spread / rh); @@ -1646,7 +1647,7 @@ impl Compositor { quad_px: [size_px[0] + 2.0 * spread, size_px[1] + 2.0 * spread], radius_px: radius, mode: 2.0, - color: [0.0, 0.0, 0.0, opacity], + color: [color[0], color[1], color[2], opacity], fx: [spread, 0.0, 0.0, 0.0], mb: [0.0, 1.0, 1.0, 0.0], ..Default::default() @@ -2740,7 +2741,7 @@ impl Compositor { Some(cb) => cb, None => match g.shadow_caster([rw, rh]) { ShadowCaster::Upright { dst, size_px, radius } => { - self.shadow_cb(dst, size_px, radius, spread, offset, opacity) + self.shadow_cb(dst, size_px, radius, spread, offset, opacity, [0.0; 3]) } ShadowCaster::Tilted { corners, center_px, radius, mask } => self .quad_shadow_cb(&corners, center_px, radius, mask, spread, offset, opacity), @@ -2931,13 +2932,22 @@ impl Compositor { && !is_cutout && g.webcam_shadow > 0.0) .then(|| { - let cb = self.shadow_cb( + let style = g.webcam_shadow_style; + let (caster, caster_px, caster_radius) = crate::frame_geometry::spread_shadow_caster( g.w_dst, g.w_px, g.w_radius, - g.webcam_shadow_spread_frac * g.frame_min_px, - [0.0, g.webcam_shadow_offset_frac * g.frame_min_px], + style.spread_frac * g.frame_min_px, + ); + let cb = self.shadow_cb( + caster, + caster_px, + caster_radius, + (style.blur_frac * g.frame_min_px) + .max(crate::frame_geometry::WEBCAM_SHADOW_MIN_BLUR_PX), + [style.offset_frac[0] * g.frame_min_px, style.offset_frac[1] * g.frame_min_px], crate::frame_geometry::WEBCAM_SHADOW_OPACITY * g.shape_fade * g.webcam_shadow, + style.color, ); self.make_bind(&cb, None, &dummy) }); diff --git a/crates/compositor/src/compositor_macos.rs b/crates/compositor/src/compositor_macos.rs index 60d9108360..627e58a53f 100644 --- a/crates/compositor/src/compositor_macos.rs +++ b/crates/compositor/src/compositor_macos.rs @@ -38,7 +38,8 @@ pub use crate::frame_geometry::{ live_params_from_scene, webcam_shape_code, FIXTURE_FRAMES, LayerCB, LiveParams, OUT_H, OUT_W, }; use crate::frame_geometry::{parse_hex, FrameGeometryInput, ShadowCaster, - SCREEN_SHADOW_SPREAD_FRAC, WEBCAM_SHADOW_OPACITY}; + spread_shadow_caster, SCREEN_SHADOW_SPREAD_FRAC, WEBCAM_SHADOW_MIN_BLUR_PX, + WEBCAM_SHADOW_OPACITY}; use crate::scene::{Scene, SceneBackground, SceneShaderEffect, ShaderEffectTarget, WallpaperMotion}; use anyhow::{anyhow, Result}; use metal::foreign_types::ForeignType; @@ -1319,6 +1320,7 @@ impl Compositor { spread: f32, offset_px: [f32; 2], opacity: f32, + color: [f32; 3], ) { let (rw, rh) = (self.render_w as f32, self.render_h as f32); let (sx, sy) = (spread / rw, spread / rh); @@ -1328,7 +1330,7 @@ impl Compositor { quad_px: [size_px[0] + 2.0 * spread, size_px[1] + 2.0 * spread], radius_px: radius, mode: 2.0, - color: [0.0, 0.0, 0.0, opacity], + color: [color[0], color[1], color[2], opacity], fx: [spread, 0.0, 0.0, 0.0], mb: [0.0, 1.0, 1.0, 0.0], ..Default::default() @@ -2848,7 +2850,7 @@ impl Compositor { } else { match g.shadow_caster([rw, rh]) { ShadowCaster::Upright { dst, size_px, radius } => { - self.draw_shadow(enc, dst, size_px, radius, spread, offset, opacity) + self.draw_shadow(enc, dst, size_px, radius, spread, offset, opacity, [0.0; 3]) } ShadowCaster::Tilted { corners, center_px, radius, mask } => self.draw_quad_shadow( enc, &corners, center_px, radius, mask, spread, offset, opacity, @@ -3077,14 +3079,22 @@ impl Compositor { // garde donc son ombre. let is_cutout = matches!(effect, Some((code, _)) if code == 1.0); if cfg.shadow && g.webcam_shadow > 0.0 && !is_cutout && g.shape_fade > 0.0 { - self.draw_shadow( - enc, + let style = g.webcam_shadow_style; + let (caster, caster_px, caster_radius) = spread_shadow_caster( g.w_dst, g.w_px, g.w_radius, - g.webcam_shadow_spread_frac * g.frame_min_px, - [0.0, g.webcam_shadow_offset_frac * g.frame_min_px], + style.spread_frac * g.frame_min_px, + ); + self.draw_shadow( + enc, + caster, + caster_px, + caster_radius, + (style.blur_frac * g.frame_min_px).max(WEBCAM_SHADOW_MIN_BLUR_PX), + [style.offset_frac[0] * g.frame_min_px, style.offset_frac[1] * g.frame_min_px], WEBCAM_SHADOW_OPACITY * g.shape_fade * g.webcam_shadow, + style.color, ); } diff --git a/crates/compositor/src/compositor_windows.rs b/crates/compositor/src/compositor_windows.rs index 4968a3d300..0faf2bce98 100644 --- a/crates/compositor/src/compositor_windows.rs +++ b/crates/compositor/src/compositor_windows.rs @@ -12,7 +12,8 @@ use crate::frame_geometry::{ cover_crop_uv, cover_uv_rect, decode_data_uri, ease_in_out_cubic, lerp, lerp4, parse_hex, preset_placements, remap_box, screen_source_rect, timeline, CursorPlacement, FrameParams, Placement, ShadowCaster, SpriteShape, CURSOR_BASE_SIZE_FRAC, FPS, - SCREEN_SHADOW_SPREAD_FRAC, SHADOW_TUNING_REF_PX, WEBCAM_SHADOW_OPACITY, + spread_shadow_caster, SCREEN_SHADOW_SPREAD_FRAC, SHADOW_TUNING_REF_PX, + WEBCAM_SHADOW_MIN_BLUR_PX, WEBCAM_SHADOW_OPACITY, }; use crate::cursor::CursorTrack; use crate::scene::{ @@ -2283,6 +2284,7 @@ impl Compositor { spread: f32, offset_px: [f32; 2], opacity: f32, + color: [f32; 3], ) { let sx = spread / self.rw(); let sy = spread / self.rh(); @@ -2293,7 +2295,7 @@ impl Compositor { quad_px: [size_px[0] + 2.0 * spread, size_px[1] + 2.0 * spread], radius_px: radius, mode: 2.0, - color: [0.0, 0.0, 0.0, opacity], + color: [color[0], color[1], color[2], opacity], fx: [spread, 0.0, 0.0, 0.0], mb: [0.0, 1.0, 1.0, 0.0], ..Default::default() @@ -2600,7 +2602,7 @@ impl Compositor { } else { match g.shadow_caster(render_px) { ShadowCaster::Upright { dst, size_px, radius } => { - self.draw_shadow(dst, size_px, radius, spread, offset, opacity) + self.draw_shadow(dst, size_px, radius, spread, offset, opacity, [0.0; 3]) } // Même rayon que le plan incliné lui-même (cf. le dessin du mode 8). ShadowCaster::Tilted { corners, center_px, radius, mask } => self @@ -2853,13 +2855,17 @@ impl Compositor { ) && self.webcam_mask.borrow().is_some(); if cfg.shadow && g.webcam_shadow > 0.0 && !is_cutout && shape_fade > 0.0 { let strength = WEBCAM_SHADOW_OPACITY * shape_fade * g.webcam_shadow; + let style = g.webcam_shadow_style; + let (caster, caster_px, caster_radius) = + spread_shadow_caster(w_dst, w_px, w_radius, style.spread_frac * frame_min_px); self.draw_shadow( - w_dst, - w_px, - w_radius, - g.webcam_shadow_spread_frac * frame_min_px, - [0.0, g.webcam_shadow_offset_frac * frame_min_px], + caster, + caster_px, + caster_radius, + (style.blur_frac * frame_min_px).max(WEBCAM_SHADOW_MIN_BLUR_PX), + [style.offset_frac[0] * frame_min_px, style.offset_frac[1] * frame_min_px], strength, + style.color, ); } // Effet d'arrière-plan : le mode vient de la scène, le masque par pixel de diff --git a/crates/compositor/src/frame_geometry.rs b/crates/compositor/src/frame_geometry.rs index 5feada6152..1583d9ec64 100644 --- a/crates/compositor/src/frame_geometry.rs +++ b/crates/compositor/src/frame_geometry.rs @@ -457,23 +457,84 @@ pub(crate) const WEBCAM_SHADOW_OFFSET_FRAC: f32 = 12.0 / SHADOW_TUNING_REF_PX; /// la position du slider. Parité avec le preset PiP côté web (`compositeLayout.ts`, /// `rgba(0,0,0,0.35)`), dont l'ombre est elle aussi un forfait fixe et PiP-only. pub(crate) const WEBCAM_SHADOW_OPACITY: f32 = 0.35; -/// Bounds of the camera shadow's softness and drop multipliers (`SceneEffects::webcam_shadow_blur` -/// / `webcam_shadow_distance`). Mirrors `SETTING_BOUNDS` in `src/lib/projectDefaults.ts`: a -/// hand-edited project or an agent cannot push the shadow past what the styles were tuned for. -pub(crate) const WEBCAM_SHADOW_BLUR_RANGE: (f32, f32) = (0.25, 3.0); -pub(crate) const WEBCAM_SHADOW_DISTANCE_RANGE: (f32, f32) = (0.0, 4.0); - -/// The camera shadow's spread and vertical drop, as fractions of the frame's short side. The -/// scene's multipliers scale the tuned base; a scene without them keeps the base exactly. -fn webcam_shadow_extent(effects: Option<&crate::scene::SceneEffects>) -> (f32, f32) { - let multiplier = |value: Option, (lo, hi): (f32, f32)| { - value.filter(|v| v.is_finite()).unwrap_or(1.0).clamp(lo, hi) - }; - let blur = multiplier(effects.and_then(|e| e.webcam_shadow_blur), WEBCAM_SHADOW_BLUR_RANGE); - let distance = - multiplier(effects.and_then(|e| e.webcam_shadow_distance), WEBCAM_SHADOW_DISTANCE_RANGE); - (WEBCAM_SHADOW_SPREAD_FRAC * blur, WEBCAM_SHADOW_OFFSET_FRAC * distance) +/// Bounds of the camera shadow, as fractions of the 1080 px reference. They mirror +/// `WEBCAM_SHADOW_BOUNDS` in src/lib/webcamShadowStyles.ts, so a hand-edited project cannot push +/// the shadow off the frame or past what the pane offers. +pub(crate) const WEBCAM_SHADOW_OFFSET_RANGE: (f32, f32) = (-80.0 / SHADOW_TUNING_REF_PX, 80.0 / SHADOW_TUNING_REF_PX); +pub(crate) const WEBCAM_SHADOW_BLUR_RANGE: (f32, f32) = (0.0, 120.0 / SHADOW_TUNING_REF_PX); +pub(crate) const WEBCAM_SHADOW_SPREAD_RANGE: (f32, f32) = (-40.0 / SHADOW_TUNING_REF_PX, 40.0 / SHADOW_TUNING_REF_PX); +/// The shader fades the penumbra with `smoothstep(0, blur, d)`, undefined at a zero width: the +/// sharpest shadow is half a pixel soft, which reads as a hard edge. +pub(crate) const WEBCAM_SHADOW_MIN_BLUR_PX: f32 = 0.5; + +/// The camera shadow as `plan_frame` hands it to the backends: lengths as fractions of the +/// frame's short side, and `strength` as the scene's opacity over `WEBCAM_SHADOW_OPACITY`, the +/// factor the backends already multiply by. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct WebcamShadowPlan { + pub blur_frac: f32, + pub offset_frac: [f32; 2], + pub spread_frac: f32, + pub color: [f32; 3], + pub strength: f32, +} + +impl WebcamShadowPlan { + /// The tuned 35% black shadow every scene had before the presets, at `strength`. + pub(crate) fn tuned(strength: f32) -> Self { + Self { + blur_frac: WEBCAM_SHADOW_SPREAD_FRAC, + offset_frac: [0.0, WEBCAM_SHADOW_OFFSET_FRAC], + spread_frac: 0.0, + color: [0.0, 0.0, 0.0], + strength, + } + } +} + +fn webcam_shadow_plan(effects: Option<&crate::scene::SceneEffects>) -> WebcamShadowPlan { + let finite = |v: f32, fallback: f32| if v.is_finite() { v } else { fallback }; + let clamp = |v: f32, (lo, hi): (f32, f32)| finite(v, 0.0).clamp(lo, hi); + match effects.and_then(|e| e.webcam_shadow_style) { + Some(style) => WebcamShadowPlan { + blur_frac: clamp(style.blur_frac, WEBCAM_SHADOW_BLUR_RANGE), + offset_frac: [ + clamp(style.offset_frac[0], WEBCAM_SHADOW_OFFSET_RANGE), + clamp(style.offset_frac[1], WEBCAM_SHADOW_OFFSET_RANGE), + ], + spread_frac: clamp(style.spread_frac, WEBCAM_SHADOW_SPREAD_RANGE), + color: style.color.map(|c| clamp(c, (0.0, 1.0))), + strength: clamp(style.opacity, (0.0, 1.0)) / WEBCAM_SHADOW_OPACITY, + }, + // `webcam_shadow` was a strength where 0.6 drew the tuned shadow. + None => WebcamShadowPlan::tuned( + effects.and_then(|e| e.webcam_shadow).unwrap_or(0.6).clamp(0.0, 1.0) / 0.6, + ), + } } + +/// The rectangle a camera shadow is cast from: the camera's own, grown (or shrunk, with a +/// negative `spread_px`) on every side, its corners following so a round camera stays round. +/// `dst` is in the render target's normalised units, so its scale per pixel comes from `size_px`. +pub(crate) fn spread_shadow_caster( + dst: [f32; 4], + size_px: [f32; 2], + radius_px: f32, + spread_px: f32, +) -> ([f32; 4], [f32; 2], f32) { + if spread_px == 0.0 || size_px[0] <= 0.0 || size_px[1] <= 0.0 { + return (dst, size_px, radius_px); + } + // Never shrink past a pixel: a negative size would turn the rect inside out. + let spread = spread_px.max(0.5 - size_px[0].min(size_px[1]) / 2.0); + let (ux, uy) = (dst[2] / size_px[0], dst[3] / size_px[1]); + ( + [dst[0] - spread * ux, dst[1] - spread * uy, dst[2] + 2.0 * spread * ux, dst[3] + 2.0 * spread * uy], + [size_px[0] + 2.0 * spread, size_px[1] + 2.0 * spread], + (radius_px + spread).max(0.0), + ) +} + /// Taille de base du curseur, même convention (34 px réglés contre un cadre 1080). pub(crate) const CURSOR_BASE_SIZE_FRAC: f32 = 34.0 / SHADOW_TUNING_REF_PX; @@ -1927,10 +1988,8 @@ pub struct FrameGeometry { pub show_screen: bool, /// Continuous PiP shadow weight through a layout change. pub webcam_shadow: f32, - /// Camera shadow spread (blur extent), fraction of the frame's short side. - pub webcam_shadow_spread_frac: f32, - /// Camera shadow vertical drop, fraction of the frame's short side. - pub webcam_shadow_offset_frac: f32, + /// The camera shadow's look; `webcam_shadow` above carries its strength through layouts. + pub webcam_shadow_style: WebcamShadowPlan, pub mb_taps: f32, pub mb_amount: f32, pub source_t: f32, @@ -3732,15 +3791,13 @@ pub fn plan_frame(input: &FrameGeometryInput) -> FrameGeometry { Some(sample) => sample.preset != "camera-only" || sample.progress < 1.0, None => scene_preset.as_deref() != Some("camera-only"), }); - let (webcam_shadow_spread_frac, webcam_shadow_offset_frac) = - webcam_shadow_extent(input.scene.map(|scene| &scene.effects)); + let webcam_shadow_style = webcam_shadow_plan(input.scene.map(|scene| &scene.effects)); FrameGeometry { show_screen, webcam_shadow: sampled_layout.as_ref().map(|s| s.webcam_shadow) .unwrap_or_else(|| if matches!(scene_preset.as_deref(), Some("dual-frame") | Some("vertical-stack") | Some("camera-only")) { 0.0 } else { 1.0 }) - * input.scene.and_then(|scene| scene.effects.webcam_shadow).unwrap_or(0.6).clamp(0.0, 1.0) / 0.6, - webcam_shadow_spread_frac, - webcam_shadow_offset_frac, + * webcam_shadow_style.strength, + webcam_shadow_style, scene_preset, mb_taps, mb_amount, @@ -5282,30 +5339,58 @@ mod tests { } #[test] - fn webcam_shadow_style_scales_spread_and_drop_and_keeps_old_scenes() { + fn webcam_shadow_style_reaches_the_plan_and_old_scenes_keep_the_tuned_shadow() { let mut scene = golden_scene(); let cfg = crate::config::all().pop().expect("compositor config"); - // A scene from before the styles carries neither multiplier: the tuned base, exactly. + // A scene from before the presets: the tuned shadow, exactly. let baseline = plan_frame(&golden_input(&scene, &cfg)); - assert_eq!(baseline.webcam_shadow_spread_frac, WEBCAM_SHADOW_SPREAD_FRAC); - assert_eq!(baseline.webcam_shadow_offset_frac, WEBCAM_SHADOW_OFFSET_FRAC); - - scene.effects.webcam_shadow_blur = Some(2.0); - scene.effects.webcam_shadow_distance = Some(0.5); + assert_eq!(baseline.webcam_shadow_style, WebcamShadowPlan::tuned(1.0)); + + scene.effects.webcam_shadow_style = Some(crate::scene::SceneWebcamShadow { + offset_frac: [-0.01, 0.03], + blur_frac: 0.08, + spread_frac: -0.01, + opacity: WEBCAM_SHADOW_OPACITY * 2.0, + color: [0.2, 0.4, 0.6], + }); let styled = plan_frame(&golden_input(&scene, &cfg)); - assert!((styled.webcam_shadow_spread_frac - WEBCAM_SHADOW_SPREAD_FRAC * 2.0).abs() < 1e-7); - assert!((styled.webcam_shadow_offset_frac - WEBCAM_SHADOW_OFFSET_FRAC * 0.5).abs() < 1e-7); - // The style moves the shadow only: never the camera itself, nor its opacity. + let s = styled.webcam_shadow_style; + assert_eq!((s.offset_frac, s.blur_frac, s.spread_frac, s.color), ([-0.01, 0.03], 0.08, -0.01, [0.2, 0.4, 0.6])); + // Opacity is a strength over the tuned 35%, which every backend already multiplies by. + assert!((styled.webcam_shadow - baseline.webcam_shadow * 2.0).abs() < 1e-5); + // The shadow never moves the camera itself. assert_eq!(styled.w_dst, baseline.w_dst); - assert_eq!(styled.webcam_shadow, baseline.webcam_shadow); - // Out-of-range and non-finite values are held to the tuned range. - scene.effects.webcam_shadow_blur = Some(100.0); - scene.effects.webcam_shadow_distance = Some(f32::NAN); - let clamped = plan_frame(&golden_input(&scene, &cfg)); - let (_, blur_max) = WEBCAM_SHADOW_BLUR_RANGE; - assert!((clamped.webcam_shadow_spread_frac - WEBCAM_SHADOW_SPREAD_FRAC * blur_max).abs() < 1e-7); - assert_eq!(clamped.webcam_shadow_offset_frac, WEBCAM_SHADOW_OFFSET_FRAC); + // A hand-edited scene is held to the pane's ranges, and a NaN to nothing. + scene.effects.webcam_shadow_style = Some(crate::scene::SceneWebcamShadow { + offset_frac: [5.0, f32::NAN], + blur_frac: -1.0, + spread_frac: 9.0, + opacity: 7.0, + color: [2.0, -1.0, 0.5], + }); + let s = plan_frame(&golden_input(&scene, &cfg)).webcam_shadow_style; + assert_eq!(s.offset_frac, [WEBCAM_SHADOW_OFFSET_RANGE.1, 0.0]); + assert_eq!(s.blur_frac, 0.0); + assert_eq!(s.spread_frac, WEBCAM_SHADOW_SPREAD_RANGE.1); + assert_eq!(s.color, [1.0, 0.0, 0.5]); + assert!((s.strength - 1.0 / WEBCAM_SHADOW_OPACITY).abs() < 1e-5); + } + + #[test] + fn spread_grows_the_caster_on_every_side_and_never_inverts_it() { + // 200x100 px at 0.002 normalised units per pixel. + let dst = [0.5, 0.5, 0.4, 0.2]; + let (d, px, r) = spread_shadow_caster(dst, [200.0, 100.0], 20.0, 10.0); + assert_eq!(px, [220.0, 120.0]); + assert_eq!(r, 30.0); + for (got, want) in d.iter().zip([0.48, 0.48, 0.44, 0.24]) { + assert!((got - want).abs() < 1e-6, "{d:?}"); + } + let (_, px, r) = spread_shadow_caster(dst, [200.0, 100.0], 20.0, -500.0); + assert!(px[1] >= 1.0 - 1e-6 && px[0] > px[1], "{px:?}"); + assert_eq!(r, 0.0); + assert_eq!(spread_shadow_caster(dst, [200.0, 100.0], 20.0, 0.0), (dst, [200.0, 100.0], 20.0)); } /// Le JSON de la scène zoomée, brut : `tilted_golden_scene` n'en change QUE la @@ -8726,8 +8811,7 @@ mod tests { show_screen: true, scene_preset: None, webcam_shadow: 1.0, - webcam_shadow_spread_frac: WEBCAM_SHADOW_SPREAD_FRAC, - webcam_shadow_offset_frac: WEBCAM_SHADOW_OFFSET_FRAC, + webcam_shadow_style: WebcamShadowPlan::tuned(1.0), mb_taps: 1.0, mb_amount: 0.0, source_t: 0.0, diff --git a/crates/compositor/src/scene.rs b/crates/compositor/src/scene.rs index b61fbae64b..63e2835b6b 100644 --- a/crates/compositor/src/scene.rs +++ b/crates/compositor/src/scene.rs @@ -270,6 +270,19 @@ fn blur_amount<'de, D: serde::Deserializer<'de>>(d: D) -> Result }) } +/// The camera's drop shadow. Lengths are fractions of a 1080 px reference, like +/// `roundness_frac`: the native side multiplies them by the frame it draws. +#[derive(Debug, Clone, Copy, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct SceneWebcamShadow { + pub offset_frac: [f32; 2], + pub blur_frac: f32, + pub spread_frac: f32, + pub opacity: f32, + /// sRGB, 0..1 per channel. + pub color: [f32; 3], +} + /// Effets de cadre (padding, blur, ombre, coins, motion blur). #[derive(Debug, Clone, Copy, Deserialize)] #[serde(rename_all = "camelCase")] @@ -284,14 +297,10 @@ pub struct SceneEffects { pub shadow: f32, #[serde(default)] pub webcam_shadow: Option, - /// Camera shadow softness, a multiple of the tuned base spread (`WEBCAM_SHADOW_SPREAD_FRAC`). - /// Absent in scenes from before the shadow styles, which keep the base exactly. - #[serde(default)] - pub webcam_shadow_blur: Option, - /// Camera shadow drop distance, a multiple of the tuned base offset - /// (`WEBCAM_SHADOW_OFFSET_FRAC`). Absent = 1, the historical drop. + /// The PiP camera's drop shadow (`SceneWebcamShadow` in sceneDescription.ts). Absent in + /// scenes from before the presets, which keep the tuned shadow scaled by `webcam_shadow`. #[serde(default)] - pub webcam_shadow_distance: Option, + pub webcam_shadow_style: Option, /// Slider Roundness, en FRACTION du petit côté du cadre de sortie. /// /// Toute longueur qui traverse ce contrat est une fraction, jamais un nombre de pixels, et diff --git a/src/components/ai-edition/CameraShadowControls.module.css b/src/components/ai-edition/CameraShadowControls.module.css new file mode 100644 index 0000000000..fa977ec8cd --- /dev/null +++ b/src/components/ai-edition/CameraShadowControls.module.css @@ -0,0 +1,321 @@ +/* The camera shadow section of the Layout pane. Tokens from design/tokens/v4.css; the one fixed + colour is the stage the previews sit on, a stand-in for the wallpaper: it stays light in both + themes, because a shadow on the editor's own dark surface would show nothing. */ + +.root { + --shadow-stage: #e7ecf2; + --shadow-stage-line: rgb(15 23 42 / 0.08); + --shadow-camera: linear-gradient(160deg, #f8fafc 0%, #cbd5e1 100%); + padding-bottom: 4px; +} +/* In the dark editor a light stage glares; a mid grey still shows a dark shadow plainly. */ +:global(:root[data-theme="dark"]) .root { + --shadow-stage: #9ba5b3; + --shadow-stage-line: rgb(15 23 42 / 0.14); + --shadow-camera: linear-gradient(160deg, #e2e8f0 0%, #aab4c2 100%); +} + +/* ─── preset tiles ──────────────────────────────────────────────────────── */ + +.tileStage { + position: relative; + display: grid; + place-items: center; + width: 52px; + height: 34px; + margin-top: 2px; + border-radius: 7px; + background: var(--shadow-stage); + /* Concentric with the tile's 10px radius across its 3px inset. */ + box-shadow: inset 0 0 0 1px var(--shadow-stage-line); + overflow: hidden; +} + +.tileCamera { + width: 20px; + height: 20px; + border-radius: 6px; + background: var(--shadow-camera); + outline: 1px solid rgb(0 0 0 / 0.1); + outline-offset: -1px; + transition: box-shadow var(--motion-base) var(--ease); +} + +/* Marks the preset an edited shadow was tuned from: a static cue, never motion alone. */ +.editedDot { + position: absolute; + top: 4px; + right: 4px; + width: 6px; + height: 6px; + border-radius: var(--r-pill); + background: var(--accent); + box-shadow: 0 0 0 2px var(--shadow-stage); +} + +/* ─── Customize disclosure ──────────────────────────────────────────────── */ + +.disclosureRow { + display: flex; + align-items: center; + gap: 8px; + margin: 10px var(--sp-4) 0; +} + +.disclosure { + display: inline-flex; + align-items: center; + gap: 6px; + min-height: 32px; + margin-left: -6px; + padding: 0 8px 0 6px; + border: 0; + border-radius: var(--r-sm); + background: transparent; + color: var(--fg-2); + font: 500 13px/1.3 var(--font-body); + cursor: pointer; + transition: background var(--motion-fast) var(--ease), color var(--motion-fast) var(--ease); +} +.disclosure:hover:not(:disabled) { + background: color-mix(in oklab, var(--fg) 6%, transparent); + color: var(--fg); +} +.disclosure:focus-visible { + outline: 2px solid var(--brand); + outline-offset: 1px; +} +.disclosure:disabled { + opacity: 0.5; + cursor: not-allowed; +} + +.chevron { + color: var(--muted); + transition: rotate var(--motion-base) var(--ease); +} +.disclosure[aria-expanded="true"] .chevron { + rotate: 90deg; +} + +.badge { + padding: 1px 6px; + border-radius: var(--r-pill); + background: var(--accent-soft); + color: var(--fg-2); + font: 500 11px/16px var(--font-body); +} + +.reset { + display: inline-flex; + align-items: center; + gap: 4px; + min-height: 28px; + margin-left: auto; + padding: 0 8px; + border: 0; + border-radius: var(--r-sm); + background: transparent; + color: var(--muted); + font: 500 12px/1 var(--font-body); + cursor: pointer; + transition: background var(--motion-fast) var(--ease), color var(--motion-fast) var(--ease), + scale var(--motion-fast) var(--ease); +} +.reset:hover:not(:disabled) { + background: color-mix(in oklab, var(--fg) 6%, transparent); + color: var(--fg); +} +.reset:active:not(:disabled) { + scale: 0.96; +} +.reset:focus-visible { + outline: 2px solid var(--brand); + outline-offset: 1px; +} + +/* Height animates through the grid track, which can go to its content's size without a + measured height; the content fades a beat behind so it never shows clipped mid-way. */ +.collapse { + display: grid; + grid-template-rows: 0fr; + opacity: 0; + transition: grid-template-rows var(--motion-base) var(--ease), opacity var(--motion-fast) var(--ease); +} +.collapse[data-open="true"] { + grid-template-rows: 1fr; + opacity: 1; + transition: grid-template-rows var(--motion-base) var(--ease), + opacity var(--motion-base) var(--ease) 60ms; +} +.collapseInner { + min-height: 0; + overflow: hidden; +} + +/* ─── position pad ──────────────────────────────────────────────────────── */ + +.position { + margin: 8px var(--sp-4) 4px; +} + +.positionHead { + display: flex; + align-items: center; + gap: 6px; + min-height: 20px; + margin-bottom: 6px; +} +.positionLabel { + margin-right: auto; + font: 500 13px/1.3 var(--font-body); + color: var(--fg-2); +} +.readout { + font: 400 12px/1 var(--font-mono); + font-variant-numeric: tabular-nums; + color: var(--muted); +} +.iconButton { + display: grid; + place-items: center; + width: 20px; + height: 20px; + border: 0; + border-radius: var(--r-xs); + background: transparent; + color: var(--muted); + cursor: pointer; +} +.iconButton:hover { + color: var(--fg); + background: var(--border-hi); +} +.iconButton:focus-visible { + outline: 2px solid var(--brand); + outline-offset: 1px; +} + +.pad { + position: relative; + height: 132px; + border-radius: var(--r-md); + background: + radial-gradient(circle, var(--shadow-stage-line) 1px, transparent 1.5px) center / 12px 12px, + var(--shadow-stage); + box-shadow: inset 0 0 0 1px var(--shadow-stage-line); + overflow: hidden; + cursor: grab; + touch-action: none; + user-select: none; +} +.pad[data-dragging="true"] { + cursor: grabbing; +} +.pad[data-disabled="true"] { + opacity: 0.5; + cursor: not-allowed; +} + +/* The axes the position snaps to; one lights up while the drag sits on it. */ +.axisX, +.axisY { + position: absolute; + background: rgb(15 23 42 / 0.1); + transition: background var(--motion-fast) var(--ease); +} +.axisX { + left: 0; + right: 0; + top: 50%; + height: 1px; +} +.axisY { + top: 0; + bottom: 0; + left: 50%; + width: 1px; +} +.axisX[data-snapped="true"], +.axisY[data-snapped="true"] { + background: var(--accent); +} + +.padCamera { + position: absolute; + left: 50%; + top: 50%; + width: 56px; + height: 56px; + margin: -28px 0 0 -28px; + border-radius: 14px; + background: var(--shadow-camera); + outline: 1px solid rgb(0 0 0 / 0.1); + outline-offset: -1px; + /* Glides between presets; follows the pointer exactly while dragged. */ + transition: box-shadow var(--motion-base) var(--ease); +} + +.vector { + position: absolute; + left: 50%; + top: 50%; + overflow: visible; + pointer-events: none; +} +.vector line { + stroke: rgb(15 23 42 / 0.35); + stroke-width: 1; + stroke-dasharray: 2 3; +} + +.handle { + position: absolute; + left: 50%; + top: 50%; + width: 16px; + height: 16px; + margin: -8px 0 0 -8px; + border-radius: var(--r-pill); + background: rgb(255 255 255 / 0.85); + box-shadow: + 0 0 0 1.5px rgb(15 23 42 / 0.55), + 0 1px 3px rgb(15 23 42 / 0.25); + transition: transform var(--motion-base) var(--ease), box-shadow var(--motion-fast) var(--ease); + cursor: inherit; +} +/* A bigger target than the dot, without moving it. */ +.handle::before { + content: ""; + position: absolute; + inset: -12px; + border-radius: inherit; +} +.handle:focus-visible { + outline: none; + box-shadow: + 0 0 0 1.5px rgb(15 23 42 / 0.55), + 0 0 0 4px color-mix(in oklab, var(--brand) 45%, transparent); +} +.pad[data-dragging="true"] .handle, +.pad[data-dragging="true"] .padCamera { + transition: none; +} + +/* ─── colour ────────────────────────────────────────────────────────────── */ + +.colorRow { + margin-top: 0; + padding-top: 4px; +} + +@media (prefers-reduced-motion: reduce) { + .collapse, + .collapse[data-open="true"], + .chevron, + .tileCamera, + .padCamera, + .handle { + transition: none; + } +} diff --git a/src/components/ai-edition/CameraShadowControls.tsx b/src/components/ai-edition/CameraShadowControls.tsx new file mode 100644 index 0000000000..9a395b52cf --- /dev/null +++ b/src/components/ai-edition/CameraShadowControls.tsx @@ -0,0 +1,433 @@ +import { ChevronRight, RotateCcw } from "lucide-react"; +import { + type KeyboardEvent, + type PointerEvent, + useCallback, + useEffect, + useId, + useRef, + useState, +} from "react"; +import { Tooltip, TooltipProvider } from "@/components/ui/tooltip"; +import { useScopedT } from "@/contexts/I18nContext"; +import type { + EditorSettingsPatch, + EditorSettingsSnapshot, +} from "@/lib/ai-edition/store/editorSettings"; +import { + describeWebcamShadow, + WEBCAM_SHADOW_BOUNDS, + WEBCAM_SHADOW_COLORS, + WEBCAM_SHADOW_PRESETS, + type WebcamShadowPresetId, + type WebcamShadowValues, + webcamShadowCss, + webcamShadowPreset, + webcamShadowPresetPatch, +} from "@/lib/webcamShadowStyles"; +import css from "./CameraShadowControls.module.css"; +import { ColorField } from "./ColorField"; +import styles from "./NewEditorShell.module.css"; +import { ChoiceRow, SliderCell } from "./RightPanes"; + +/** Preview scales: what a 1080 px shadow becomes in the tiles and in the position pad. */ +const TILE_SCALE = 0.11; +const PAD_SCALE = 0.42; +/** Within this many pixels of an axis, the position snaps onto it. */ +const SNAP_PX = 3; +const OPEN_KEY = "os-camera-shadow-customize-open"; + +type ShadowSettings = Pick< + EditorSettingsSnapshot, + | "webcamShadowPreset" + | "webcamShadowOffsetX" + | "webcamShadowOffsetY" + | "webcamShadowBlur" + | "webcamShadowSpread" + | "webcamShadowOpacity" + | "webcamShadowColor" +>; + +function valuesOf(settings: ShadowSettings): WebcamShadowValues { + return { + offsetX: settings.webcamShadowOffsetX, + offsetY: settings.webcamShadowOffsetY, + blur: settings.webcamShadowBlur, + spread: settings.webcamShadowSpread, + opacity: settings.webcamShadowOpacity, + color: settings.webcamShadowColor, + }; +} + +function readOpen(): boolean { + try { + return window.localStorage.getItem(OPEN_KEY) === "1"; + } catch { + return false; + } +} + +function writeOpen(open: boolean) { + try { + window.localStorage.setItem(OPEN_KEY, open ? "1" : "0"); + } catch { + // A per-viewer convenience: without storage the section just starts closed. + } +} + +/** + * The picture-in-picture camera's shadow: six presets, then a "Customize" section that tunes + * position, blur, spread, opacity and colour from the one picked. An edited preset stays + * pressed and says so, with a way back to it; a shadow from before the presets that matches + * none of them presses none. + * + * Every drag writes live and records one undo step on release (`setLive` + `commit`); a preset + * or a colour preset is one `set`. + */ +export function CameraShadowControls({ + settings, + disabled, + set, + setLive, + commit, +}: { + settings: ShadowSettings; + disabled: boolean; + set: (patch: EditorSettingsPatch) => unknown; + setLive: (patch: EditorSettingsPatch) => void; + commit: () => unknown; +}) { + const ts = useScopedT("settings"); + const values = valuesOf(settings); + const { preset, edited } = describeWebcamShadow(values, settings.webcamShadowPreset); + const [open, setOpen] = useState(readOpen); + const bodyId = useId(); + + const toggle = () => { + setOpen((was) => { + writeOpen(!was); + return !was; + }); + }; + + /** The patch an edit writes. It keeps the preset it was tuned from, and an edit made while + * there is no shadow at all starts from the default one: moving the blur of an invisible + * shadow would show nothing. */ + const editPatch = (change: Partial): EditorSettingsPatch => { + const startsFromNothing = values.opacity <= 0 && change.opacity === undefined; + const base: WebcamShadowValues = startsFromNothing ? webcamShadowPreset("soft") : values; + const next = { ...base, ...change }; + return { + webcamShadowPreset: startsFromNothing ? "soft" : (preset ?? null), + webcamShadowOffsetX: next.offsetX, + webcamShadowOffsetY: next.offsetY, + webcamShadowBlur: next.blur, + webcamShadowSpread: next.spread, + webcamShadowOpacity: next.opacity, + webcamShadowColor: next.color, + }; + }; + const live = (change: Partial) => setLive(editPatch(change)); + + const label = (id: WebcamShadowPresetId) => ts(`layout.cameraShadow.${id}`); + const base = preset ? webcamShadowPreset(preset) : null; + + return ( +
+
{ts("effects.shadow")}
+
+ + label={ts("effects.shadow")} + display="both" + tiles + columns={3} + options={WEBCAM_SHADOW_PRESETS.map((p) => ({ + value: p.id, + label: label(p.id), + title: ts(`layout.cameraShadow.${p.id}Tip`), + icon: , + }))} + value={preset ?? ""} + disabled={disabled} + onChange={(id) => { + if (id !== "") void set(webcamShadowPresetPatch(id)); + }} + /> +
+ +
+ + {edited && base ? ( + + + + + + ) : null} +
+ +
+
+ live({ offsetX, offsetY })} + onCommit={() => void commit()} + onReset={(offsetX, offsetY) => void set(editPatch({ offsetX, offsetY }))} + /> +
+ live({ blur })} + onCommit={() => void commit()} + /> + live({ spread })} + onCommit={() => void commit()} + /> + live({ opacity: pct / 100 })} + onCommit={() => void commit()} + /> +
+
+ {ts("layout.cameraShadow.color")} + { + if (/^#[0-9a-f]{6}$/i.test(hex)) live({ color: hex.toLowerCase() }); + }} + onCommit={() => void commit()} + /> +
+
+
+
+ ); +} + +/** A preset's picture: a camera on a small stage, casting that preset's shadow. */ +function ShadowTile({ values, edited }: { values: WebcamShadowValues; edited: boolean }) { + return ( +