Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

refactor(rendering): replace zoom easing engine with spring timeline

Richie McIlroy48cdaa728317
diff --git a/crates/rendering/src/coord.rs b/crates/rendering/src/coord.rs
index 2f067f11b..e5ce71d85 100644
--- a/crates/rendering/src/coord.rs
+++ b/crates/rendering/src/coord.rs
@@ -108,16 +108,12 @@ impl Coord<CroppedDisplaySpace> {
resolution_base: XY<u32>,
) -> Coord<FrameSpace> {
let crop = ProjectUniforms::get_crop(options, project);
- let output_size = ProjectUniforms::get_output_size(options, project, resolution_base);
let padding_offset = ProjectUniforms::display_offset(options, project, resolution_base);
-
- let output_size = XY::new(output_size.0, output_size.1).map(|v| v as f64);
+ let display_size = ProjectUniforms::display_size(options, project, resolution_base);
let position_ratio = self.coord / crop.size.map(|v| v as f64);
- Coord::new(
- padding_offset.coord + (output_size - padding_offset.coord * 2.0) * position_ratio,
- )
+ Coord::new(padding_offset.coord + display_size.coord * position_ratio)
}
}
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index f5b3edb9c..763b77788 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -1,7 +1,7 @@
use anyhow::Result;
use cap_project::{
- AspectRatio, CameraShape, CameraXPosition, CameraYPosition, ClipOffsets, CornerStyle, Crop,
- CursorEvents, CursorType, MaskKind, ProjectConfiguration, RecordingMeta, SceneMode,
+ AspectRatio, Camera, CameraShape, CameraXPosition, CameraYPosition, ClipOffsets, CornerStyle,
+ Crop, CursorEvents, CursorType, MaskKind, ProjectConfiguration, RecordingMeta, SceneMode,
StudioRecordingMeta, XY,
};
use composite_frame::CompositeVideoFrameUniforms;
@@ -46,7 +46,7 @@ pub mod spring_mass_damper;
mod text;
pub mod yuv_converter;
mod zoom;
-pub mod zoom_focus_interpolation;
+mod zoom_spring;
pub use coord::*;
pub use decoder::{DecodedFrame, DecoderStatus, DecoderType, PixelFormat};
@@ -68,7 +68,7 @@ use mask::interpolate_masks;
use scene::*;
use text::{PreparedText, prepare_texts};
use zoom::*;
-pub use zoom_focus_interpolation::ZoomFocusInterpolator;
+pub use zoom_spring::ZoomTransformTimeline;
#[derive(Debug, Clone, serde::Serialize)]
pub struct Nv12RenderStartupBreakdownMs {
@@ -581,24 +581,9 @@ pub async fn render_video_to_channel(
})
.collect();
- let mut zoom_focus_interpolators: Vec<ZoomFocusInterpolator> = render_segments
+ let mut zoom_timelines: Vec<ZoomTransformTimeline> = render_segments
.iter()
- .zip(precomputed_cursor_timelines.iter())
- .map(|(segment, precomputed_cursor)| {
- ZoomFocusInterpolator::new_with_precomputed_cursor(
- &segment.cursor,
- cursor_smoothing,
- click_spring,
- project.screen_movement_spring,
- duration,
- project
- .timeline
- .as_ref()
- .map(|t| t.zoom_segments.as_slice())
- .unwrap_or(&[]),
- Some(precomputed_cursor.clone()),
- )
- })
+ .map(|segment| ZoomTransformTimeline::from_project(project, &segment.cursor, duration))
.collect();
let mut frame_number = 0;
@@ -656,7 +641,7 @@ pub async fn render_video_to_channel(
let segment_clip_index = segment.recording_clip as usize;
let zoom_until = (current_frame_number as f32 + 1.0) / fps as f32;
- zoom_focus_interpolators[segment_clip_index].ensure_precomputed_until(zoom_until);
+ zoom_timelines[segment_clip_index].ensure_precomputed_until(zoom_until);
let segment_frames =
if let Some((pf_num, _pf_time, pf_clip, pf_result)) = prefetched_decode.take() {
@@ -692,7 +677,7 @@ pub async fn render_video_to_channel(
if let Some(segment_frames) = segment_frames {
consecutive_failures = 0;
- let zoom_focus_interp = &zoom_focus_interpolators[segment_clip_index];
+ let zoom_timeline = &zoom_timelines[segment_clip_index];
let precomputed_cursor = &precomputed_cursor_timelines[segment_clip_index];
let uniforms = ProjectUniforms::new_with_precomputed_cursor(
@@ -704,7 +689,7 @@ pub async fn render_video_to_channel(
&render_segment.cursor,
&segment_frames,
duration,
- zoom_focus_interp,
+ zoom_timeline,
precomputed_cursor,
);
@@ -933,27 +918,12 @@ pub async fn render_video_to_channel_nv12(
.collect();
let zoom_build_start = Instant::now();
- let mut zoom_focus_interpolators: Vec<ZoomFocusInterpolator> = render_segments
+ let mut zoom_timelines: Vec<ZoomTransformTimeline> = render_segments
.iter()
- .zip(precomputed_cursor_timelines.iter())
- .map(|(segment, precomputed_cursor)| {
- ZoomFocusInterpolator::new_with_precomputed_cursor(
- &segment.cursor,
- cursor_smoothing,
- click_spring,
- project.screen_movement_spring,
- duration,
- project
- .timeline
- .as_ref()
- .map(|t| t.zoom_segments.as_slice())
- .unwrap_or(&[]),
- Some(precomputed_cursor.clone()),
- )
- })
+ .map(|segment| ZoomTransformTimeline::from_project(project, &segment.cursor, duration))
.collect();
- for interp in &mut zoom_focus_interpolators {
- interp.ensure_precomputed_until(duration as f32 + 1.0);
+ for timeline in &mut zoom_timelines {
+ timeline.precompute();
}
let zoom_focus_interpolators_construct_ms = zoom_build_start.elapsed().as_millis() as u64;
@@ -1021,7 +991,7 @@ pub async fn render_video_to_channel_nv12(
let zoom_pre_start = Instant::now();
let zoom_until = (current_frame_number as f32 + 1.0) / fps as f32;
- zoom_focus_interpolators[segment_clip_index].ensure_precomputed_until(zoom_until);
+ zoom_timelines[segment_clip_index].ensure_precomputed_until(zoom_until);
let this_zoom_pre_ms = zoom_pre_start.elapsed().as_millis() as u64;
let decode_wall_start = Instant::now();
@@ -1060,7 +1030,7 @@ pub async fn render_video_to_channel_nv12(
if let Some(segment_frames) = segment_frames {
consecutive_failures = 0;
- let zoom_focus_interp = &zoom_focus_interpolators[segment_clip_index];
+ let zoom_timeline = &zoom_timelines[segment_clip_index];
let precomputed_cursor = &precomputed_cursor_timelines[segment_clip_index];
let uniforms = ProjectUniforms::new_with_precomputed_cursor(
@@ -1072,7 +1042,7 @@ pub async fn render_video_to_channel_nv12(
&render_segment.cursor,
&segment_frames,
duration,
- zoom_focus_interp,
+ zoom_timeline,
precomputed_cursor,
);
@@ -1562,6 +1532,10 @@ impl RenderVideoConstants {
let adapter_name = shared.adapter.get_info().name;
+ if shared.is_software_adapter {
+ frame_pipeline::note_software_adapter_in_use();
+ }
+
Ok(Self {
_instance: shared.instance,
_adapter: shared.adapter,
@@ -1588,6 +1562,9 @@ impl RenderVideoConstants {
background_textures: Arc<BackgroundTextureCache>,
) -> Self {
let adapter_name = shared.adapter.get_info().name;
+ if shared.is_software_adapter {
+ frame_pipeline::note_software_adapter_in_use();
+ }
Self {
_instance: shared.instance,
_adapter: shared.adapter,
@@ -1695,6 +1672,10 @@ impl RenderVideoConstants {
let background_textures = Arc::new(BackgroundTextureCache::default());
+ if is_software_adapter {
+ frame_pipeline::note_software_adapter_in_use();
+ }
+
Ok(Self {
_instance: instance,
_adapter: adapter,
@@ -1750,6 +1731,11 @@ pub struct SplitLayoutComputed {
/// 0..1 morph amount; the layers lerp from their normal layout toward these
/// panes by this factor, giving the fade in/out at segment boundaries.
pub factor: f64,
+ /// 0..1 share of the split that is the floating-cards variant (always
+ /// <= `factor`). The pane targets above already blend toward the padded
+ /// cards by it; the uniform builders use it to keep rounding/shadow chrome
+ /// alive on the cards instead of fading it out like classic split-screen.
+ pub floating: f64,
}
fn lerp_f32(a: f32, b: f32, t: f32) -> f32 {
@@ -1805,6 +1791,36 @@ fn inset_crop_bounds(bounds: [f32; 4], frame_size: [f32; 2], inset: f32) -> [f32
[x0 + inset_x, y0 + inset_y, x1 - inset_x, y1 - inset_y]
}
+/// Top-left of the camera rect in output px. `manual_position` (normalized
+/// center, clamped fully in-frame) overrides the corner/edge `position` enum.
+fn compute_camera_position(
+ camera: &Camera,
+ output_size: [f32; 2],
+ subject_size: [f32; 2],
+ camera_padding: f32,
+) -> [f32; 2] {
+ if let Some(manual) = camera.manual_position {
+ let x = manual.x as f32 * output_size[0] - subject_size[0] / 2.0;
+ let y = manual.y as f32 * output_size[1] - subject_size[1] / 2.0;
+ return [
+ x.clamp(0.0, (output_size[0] - subject_size[0]).max(0.0)),
+ y.clamp(0.0, (output_size[1] - subject_size[1]).max(0.0)),
+ ];
+ }
+
+ let x = match &camera.position.x {
+ CameraXPosition::Left => camera_padding,
+ CameraXPosition::Center => output_size[0] / 2.0 - subject_size[0] / 2.0,
+ CameraXPosition::Right => output_size[0] - camera_padding - subject_size[0],
+ };
+ let y = match &camera.position.y {
+ CameraYPosition::Top => camera_padding,
+ CameraYPosition::Bottom => output_size[1] - subject_size[1] - camera_padding,
+ };
+
+ [x, y]
+}
+
/// Largest centred crop of `src` (origin+size, frame px) matching `target_aspect`
/// (aspect-fill, no letterboxing), then tightened by `zoom` (>=1 zooms in) and
/// recentred on the normalized `focal` point, clamped to stay inside `src`.
@@ -2125,6 +2141,22 @@ const CAMERA_EDGE_CROP_INSET_PX: f32 = 2.0;
/// top/bottom instead.
const SPLIT_STACK_ASPECT_THRESHOLD: f32 = 1.0;
+/// Floating split layout ([`SceneMode::Floating`]): outer padding around the
+/// cards AND the gap between them, as a fraction of the output's smaller axis.
+/// Mirrored in the editor overlay (SplitScreenOverlay.tsx) so its drag panes
+/// line up with the rendered cards.
+const FLOATING_PADDING_FRAC: f32 = 0.05;
+/// Share of the content span (after padding + gap) given to the camera card
+/// when the cards sit side-by-side. The remainder goes to the screen card.
+const FLOATING_CAMERA_FRAC: f32 = 0.30;
+/// As above when the cards stack vertically (portrait/narrow outputs).
+const FLOATING_CAMERA_FRAC_STACKED: f32 = 0.40;
+/// Corner radius of both floating cards as a fraction of the output's smaller
+/// axis. The mode supplies its own radius (instead of the background/camera
+/// rounding settings, which are tuned for full-frame and PiP sizes) so the two
+/// cards always share one corner language out of the box.
+const FLOATING_ROUNDING_FRAC: f32 = 0.028;
+
const SCREEN_MAX_PADDING: f64 = 0.4;
const MOTION_BLUR_BASELINE_FPS: f32 = 60.0;
@@ -2207,7 +2239,25 @@ impl MotionBlurDescriptor {
}
}
+/// Final rendered placement of the display and camera layers in output-frame
+/// pixels ([x0, y0, x1, y1]), used by the editor preview for hit-testing the
+/// on-canvas move/resize overlays.
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub struct FrameLayout {
+ pub display: [f32; 4],
+ pub camera: Option<[f32; 4]>,
+ pub output_size: [u32; 2],
+}
+
impl ProjectUniforms {
+ pub fn frame_layout(&self) -> FrameLayout {
+ FrameLayout {
+ display: self.display.target_bounds,
+ camera: self.camera.as_ref().map(|c| c.target_bounds),
+ output_size: [self.output_size.0, self.output_size.1],
+ }
+ }
+
fn auto_padding_factor(project: &ProjectConfiguration) -> f64 {
project.background.padding / 100.0 * SCREEN_MAX_PADDING
}
@@ -2304,6 +2354,29 @@ impl ProjectUniforms {
options: &RenderOptions,
project: &ProjectConfiguration,
resolution_base: XY<u32>,
+ ) -> Coord<FrameSpace> {
+ let base = Self::display_base_offset(options, project, resolution_base);
+
+ let Some(position) = project.background.display_position else {
+ return base;
+ };
+
+ let output_size = Self::get_output_size(options, project, resolution_base);
+ // The center may sit anywhere in-frame, so the display can overhang
+ // the edges (revealing background) but can never be dragged fully
+ // out of view.
+ let delta = XY::new(
+ (position.x.clamp(0.0, 1.0) - 0.5) * output_size.0 as f64,
+ (position.y.clamp(0.0, 1.0) - 0.5) * output_size.1 as f64,
+ );
+
+ Coord::new(base.coord + delta)
+ }
+
+ fn display_base_offset(
+ options: &RenderOptions,
+ project: &ProjectConfiguration,
+ resolution_base: XY<u32>,
) -> Coord<FrameSpace> {
let output_size = Self::get_output_size(options, project, resolution_base);
let output_size = XY::new(output_size.0 as f64, output_size.1 as f64);
@@ -2383,7 +2456,7 @@ impl ProjectUniforms {
let output_size = Self::get_output_size(options, project, resolution_base);
let output_size = XY::new(output_size.0 as f64, output_size.1 as f64);
- let display_offset = Self::display_offset(options, project, resolution_base);
+ let display_offset = Self::display_base_offset(options, project, resolution_base);
let end = Coord::new(output_size) - display_offset;
@@ -2394,9 +2467,8 @@ impl ProjectUniforms {
zoom: &InterpolatedZoom,
display_offset: Coord<FrameSpace>,
display_size: Coord<FrameSpace>,
- output_size: XY<f64>,
) -> (Coord<FrameSpace>, Coord<FrameSpace>) {
- let base_end = Coord::new(output_size) - display_offset;
+ let base_end = display_offset + display_size;
let zoom_start = Coord::new(zoom.bounds.top_left * display_size.coord);
let zoom_end = Coord::new((zoom.bounds.bottom_right - 1.0) * display_size.coord);
let start = display_offset + zoom_start;
@@ -2579,7 +2651,7 @@ impl ProjectUniforms {
cursor_events: &CursorEvents,
segment_frames: &DecodedSegmentFrames,
total_duration: f64,
- zoom_focus_interpolator: &ZoomFocusInterpolator,
+ zoom_timeline: &ZoomTransformTimeline,
) -> Self {
let cursor_smoothing = (!project.cursor.raw).then_some(SpringMassDamperSimulationConfig {
tension: project.cursor.tension,
@@ -2609,7 +2681,7 @@ impl ProjectUniforms {
cursor_events,
segment_frames,
total_duration,
- zoom_focus_interpolator,
+ zoom_timeline,
&cursor_interp_fn,
)
}
@@ -2624,7 +2696,7 @@ impl ProjectUniforms {
cursor_events: &CursorEvents,
segment_frames: &DecodedSegmentFrames,
total_duration: f64,
- zoom_focus_interpolator: &ZoomFocusInterpolator,
+ zoom_timeline: &ZoomTransformTimeline,
precomputed_cursor: &PrecomputedCursorTimeline,
) -> Self {
let cursor_interp_fn = |time: f32| -> Option<InterpolatedCursorPosition> {
@@ -2640,7 +2712,7 @@ impl ProjectUniforms {
cursor_events,
segment_frames,
total_duration,
- zoom_focus_interpolator,
+ zoom_timeline,
&cursor_interp_fn,
)
}
@@ -2655,7 +2727,7 @@ impl ProjectUniforms {
_cursor_events: &CursorEvents,
segment_frames: &DecodedSegmentFrames,
total_duration: f64,
- zoom_focus_interpolator: &ZoomFocusInterpolator,
+ zoom_timeline: &ZoomTransformTimeline,
cursor_interp_fn: &dyn Fn(f32) -> Option<InterpolatedCursorPosition>,
) -> Self {
let options = &constants.options;
@@ -2710,156 +2782,29 @@ impl ProjectUniforms {
0.0
};
- let zoom_segments = project
- .timeline
- .as_ref()
- .map(|t| t.zoom_segments.as_slice())
- .unwrap_or(&[]);
-
let scene_segments = project
.timeline
.as_ref()
.map(|t| t.scene_segments.as_slice())
.unwrap_or(&[]);
- let segments_cursor = SegmentsCursor::new(frame_time as f64, zoom_segments);
- let prev_segments_cursor = SegmentsCursor::new(prev_frame_time as f64, zoom_segments);
- let recording_time_for_zoom_focus_interpolate = segments_cursor
- .segment
- .filter(|s| matches!(s.mode, cap_project::ZoomMode::Auto))
- .map(|s| current_recording_time.min(s.end as f32))
- .unwrap_or(current_recording_time);
- let prev_recording_time_for_zoom_focus_interpolate = prev_segments_cursor
- .segment
- .filter(|s| matches!(s.mode, cap_project::ZoomMode::Auto))
- .map(|s| prev_recording_time.min(s.end as f32))
- .unwrap_or(prev_recording_time);
- let zoom_focus =
- zoom_focus_interpolator.interpolate(recording_time_for_zoom_focus_interpolate);
- let prev_zoom_focus =
- zoom_focus_interpolator.interpolate(prev_recording_time_for_zoom_focus_interpolate);
-
- let display_cursor_coord = |coord: XY<f64>| {
- if coord.x.is_finite() && coord.y.is_finite() {
- Some(Coord::<RawDisplayUVSpace>::new(XY::new(
- coord.x.clamp(0.0, 1.0),
- coord.y.clamp(0.0, 1.0),
- )))
- } else {
- None
- }
- };
-
- let actual_cursor_coord = interpolated_cursor
- .as_ref()
- .and_then(|c| display_cursor_coord(c.position.coord));
-
- let prev_actual_cursor_coord = prev_interpolated_cursor
- .as_ref()
- .and_then(|c| display_cursor_coord(c.position.coord));
-
- let segment_end_focus = segments_cursor
- .prev_segment
- .filter(|_| segments_cursor.segment.is_none())
- .map(|prev| {
- let boundary_recording_time = (current_recording_time as f64
- - (frame_time as f64 - prev.end))
- .clamp(0.0, prev.end) as f32;
- zoom_focus_interpolator.interpolate(boundary_recording_time)
- });
- let segment_end_cursor = segments_cursor
- .prev_segment
- .filter(|_| segments_cursor.segment.is_none())
- .and_then(|prev| {
- let boundary_recording_time = (current_recording_time as f64
- - (frame_time as f64 - prev.end))
- .clamp(0.0, prev.end) as f32;
- cursor_interp_fn(boundary_recording_time)
- })
- .and_then(|c| display_cursor_coord(c.position.coord));
-
- let zoom = InterpolatedZoom::new_with_cursor_and_end_focus(
- segments_cursor,
- zoom_focus,
- actual_cursor_coord,
- segment_end_focus,
- segment_end_cursor,
- );
-
- let prev_segment_end_focus = prev_segments_cursor
- .prev_segment
- .filter(|_| prev_segments_cursor.segment.is_none())
- .map(|prev| {
- let boundary_recording_time = (prev_recording_time as f64
- - (prev_frame_time as f64 - prev.end))
- .clamp(0.0, prev.end) as f32;
- zoom_focus_interpolator.interpolate(boundary_recording_time)
- });
- let prev_segment_end_cursor = prev_segments_cursor
- .prev_segment
- .filter(|_| prev_segments_cursor.segment.is_none())
- .and_then(|prev| {
- let boundary_recording_time = (prev_recording_time as f64
- - (prev_frame_time as f64 - prev.end))
- .clamp(0.0, prev.end) as f32;
- cursor_interp_fn(boundary_recording_time)
- })
- .and_then(|c| display_cursor_coord(c.position.coord));
-
- let prev_zoom = InterpolatedZoom::new_with_cursor_and_end_focus(
- prev_segments_cursor,
- prev_zoom_focus,
- prev_actual_cursor_coord,
- prev_segment_end_focus,
- prev_segment_end_cursor,
- );
+ // All zoom transforms come from the precomputed spring timeline
+ // (TIMELINE-time domain). The old easing construction — and the
+ // segment_end_focus/segment_end_cursor plumbing that patched its
+ // boundary discontinuities — is gone: the spring is continuous across
+ // segment starts, ends and re-aims by construction.
+ let zoom = zoom_timeline.sample(frame_time);
+ let prev_zoom = zoom_timeline.sample(prev_frame_time);
let motion_sample_frames = frame_number.min(DISPLAY_MOTION_SAMPLE_FRAMES);
let motion_frame_delta = motion_sample_frames as f32 / fps_f32;
let motion_prev_frame_time = (frame_time - motion_frame_delta).max(0.0);
- let motion_prev_recording_time = (current_recording_time - motion_frame_delta).max(0.0);
let motion_frame_span = if has_previous {
((frame_time - motion_prev_frame_time) * fps_f32).max(1.0)
} else {
1.0
};
- let motion_prev_segments_cursor =
- SegmentsCursor::new(motion_prev_frame_time as f64, zoom_segments);
- let motion_prev_recording_time_for_zoom_focus_interpolate = motion_prev_segments_cursor
- .segment
- .filter(|s| matches!(s.mode, cap_project::ZoomMode::Auto))
- .map(|s| motion_prev_recording_time.min(s.end as f32))
- .unwrap_or(motion_prev_recording_time);
- let motion_prev_zoom_focus = zoom_focus_interpolator
- .interpolate(motion_prev_recording_time_for_zoom_focus_interpolate);
- let motion_prev_actual_cursor_coord = cursor_interp_fn(motion_prev_recording_time)
- .and_then(|c| display_cursor_coord(c.position.coord));
- let motion_prev_segment_end_focus = motion_prev_segments_cursor
- .prev_segment
- .filter(|_| motion_prev_segments_cursor.segment.is_none())
- .map(|prev| {
- let boundary_recording_time = (motion_prev_recording_time as f64
- - (motion_prev_frame_time as f64 - prev.end))
- .clamp(0.0, prev.end) as f32;
- zoom_focus_interpolator.interpolate(boundary_recording_time)
- });
- let motion_prev_segment_end_cursor = motion_prev_segments_cursor
- .prev_segment
- .filter(|_| motion_prev_segments_cursor.segment.is_none())
- .and_then(|prev| {
- let boundary_recording_time = (motion_prev_recording_time as f64
- - (motion_prev_frame_time as f64 - prev.end))
- .clamp(0.0, prev.end) as f32;
- cursor_interp_fn(boundary_recording_time)
- })
- .and_then(|c| display_cursor_coord(c.position.coord));
- let motion_prev_zoom = InterpolatedZoom::new_with_cursor_and_end_focus(
- motion_prev_segments_cursor,
- motion_prev_zoom_focus,
- motion_prev_actual_cursor_coord,
- motion_prev_segment_end_focus,
- motion_prev_segment_end_cursor,
- );
+ let motion_prev_zoom = zoom_timeline.sample(motion_prev_frame_time);
let scene =
InterpolatedScene::new(SceneSegmentsCursor::new(frame_time as f64, scene_segments));
@@ -2881,7 +2826,7 @@ impl ProjectUniforms {
let horizontal =
(out_w / out_h.max(f32::EPSILON)) >= SPLIT_STACK_ASPECT_THRESHOLD;
- let (screen_target, camera_target) = if horizontal {
+ let (screen_full, camera_full) = if horizontal {
let mid = out_w * 0.5;
([0.0, 0.0, mid, out_h], [mid, 0.0, out_w, out_h])
} else {
@@ -2889,10 +2834,40 @@ impl ProjectUniforms {
([0.0, 0.0, out_w, mid], [0.0, mid, out_w, out_h])
};
+ // Floating variant: the panes become padded cards floating
+ // over the background instead of full-bleed halves.
+ let pad = out_w.min(out_h) * FLOATING_PADDING_FRAC;
+ let (screen_card, camera_card) = if horizontal {
+ let content_w = (out_w - pad * 3.0).max(2.0);
+ let camera_w = content_w * FLOATING_CAMERA_FRAC;
+ (
+ [pad, pad, pad + (content_w - camera_w), out_h - pad],
+ [out_w - pad - camera_w, pad, out_w - pad, out_h - pad],
+ )
+ } else {
+ let content_h = (out_h - pad * 3.0).max(2.0);
+ let camera_h = content_h * FLOATING_CAMERA_FRAC_STACKED;
+ (
+ [pad, pad, out_w - pad, pad + (content_h - camera_h)],
+ [pad, out_h - pad - camera_h, out_w - pad, out_h - pad],
+ )
+ };
+
+ // Blend the halves toward the floating cards by the share
+ // of the split that is the floating variant, so back-to-back
+ // splitScreen <-> floating segments morph smoothly.
+ let card_share = if scene.split_factor > f64::EPSILON {
+ (scene.floating_factor / scene.split_factor).clamp(0.0, 1.0) as f32
+ } else {
+ 0.0
+ };
+ let screen_target = lerp_bounds(screen_full, screen_card, card_share);
+ let camera_target = lerp_bounds(camera_full, camera_card, card_share);
+
let params = scene_segments
.iter()
.find(|s| {
- matches!(s.mode, SceneMode::SplitScreen)
+ matches!(s.mode, SceneMode::SplitScreen | SceneMode::Floating)
&& (frame_time as f64) >= s.start - s.transition_in.max(0.0)
&& (frame_time as f64) < s.end + s.transition_out.max(0.0)
})
@@ -2950,6 +2925,7 @@ impl ProjectUniforms {
screen,
camera,
factor: scene.split_factor,
+ floating: scene.floating_factor,
}
})
} else {
@@ -2972,21 +2948,31 @@ impl ProjectUniforms {
let display_offset = Self::display_offset(options, project, resolution_base);
let display_size = Self::display_size(options, project, resolution_base);
- let (start, end) =
- Self::display_bounds(&zoom, display_offset, display_size, output_size);
+ let (start, end) = Self::display_bounds(&zoom, display_offset, display_size);
let (prev_start, prev_end) =
- Self::display_bounds(&motion_prev_zoom, display_offset, display_size, output_size);
+ Self::display_bounds(&motion_prev_zoom, display_offset, display_size);
let scene_blur_strength = (scene.screen_blur as f32 * 0.8).min(1.2);
- let display_motion = Self::compute_display_motion_blur(
- MotionBounds::new(start, end),
- MotionBounds::new(prev_start, prev_end),
- has_previous,
- normalized_screen_motion,
- scene_blur_strength,
- motion_frame_span,
- );
+ // An instant-animation zoom snap is a deliberate hard cut; the
+ // bounds delta across it is not motion, so blurring it would smear
+ // a single frame. Suppress display blur whenever the timeline
+ // snapped inside the sampling window.
+ let zoom_snapped_in_window =
+ zoom_timeline.snapped_within(motion_prev_frame_time, frame_time);
+
+ let display_motion = if zoom_snapped_in_window {
+ MotionBlurComputation::none()
+ } else {
+ Self::compute_display_motion_blur(
+ MotionBounds::new(start, end),
+ MotionBounds::new(prev_start, prev_end),
+ has_previous,
+ normalized_screen_motion,
+ scene_blur_strength,
+ motion_frame_span,
+ )
+ };
let descriptor = display_motion.descriptor;
let display_parent_motion_px = display_motion.parent_movement_px;
@@ -3001,7 +2987,14 @@ impl ProjectUniforms {
crop_end.y as f32,
];
let split_t = split_layout.as_ref().map_or(0.0, |s| s.factor as f32);
+ let floating_t = split_layout.as_ref().map_or(0.0, |s| s.floating as f32);
let split_fade = 1.0 - split_t;
+ // Classic split-screen fades the rounding/shadow chrome out as the
+ // pane goes full-bleed; the floating variant keeps it on its card,
+ // so the chrome follows 1 - (split_t - floating_t).
+ let chrome_fade = (1.0 - split_t + floating_t).clamp(0.0, 1.0);
+ let floating_rounding_px =
+ output_size.x.min(output_size.y) as f32 * FLOATING_ROUNDING_FRAC;
let final_target_bounds = split_layout.as_ref().map_or(base_target_bounds, |s| {
lerp_bounds(base_target_bounds, s.screen.target, split_t)
});
@@ -3026,7 +3019,8 @@ impl ProjectUniforms {
target_size: final_target_size,
rounding_px: (project.background.rounding / 100.0 * 0.5 * final_min_axis)
as f32
- * split_fade,
+ * split_fade
+ + floating_rounding_px * floating_t,
rounding_type: rounding_type_value(project.background.rounding_type),
mirror_x: 0.0,
motion_blur_vector: descriptor.movement_vector_uv,
@@ -3037,7 +3031,7 @@ impl ProjectUniforms {
descriptor.zoom_amount,
0.0,
],
- shadow: project.background.shadow * split_fade,
+ shadow: project.background.shadow * chrome_fade,
shadow_size: project
.background
.advanced_shadow
@@ -3048,7 +3042,7 @@ impl ProjectUniforms {
.advanced_shadow
.as_ref()
.map_or(18.0, |s| s.opacity)
- * split_fade,
+ * chrome_fade,
shadow_blur: project
.background
.advanced_shadow
@@ -3132,19 +3126,12 @@ impl ProjectUniforms {
let prev_size = camera_size_for(prev_zoomed_size);
let position_for = |subject_size: [f32; 2]| {
- let x = match &project.camera.position.x {
- CameraXPosition::Left => camera_padding,
- CameraXPosition::Center => output_size[0] / 2.0 - subject_size[0] / 2.0,
- CameraXPosition::Right => output_size[0] - camera_padding - subject_size[0],
- };
- let y = match &project.camera.position.y {
- CameraYPosition::Top => camera_padding,
- CameraYPosition::Bottom => {
- output_size[1] - subject_size[1] - camera_padding
- }
- };
-
- [x, y]
+ compute_camera_position(
+ &project.camera,
+ output_size,
+ subject_size,
+ camera_padding,
+ )
};
let position = position_for(size);
@@ -3184,12 +3171,21 @@ impl ProjectUniforms {
)),
);
- let camera_descriptor = Self::compute_camera_motion_blur(
- current_bounds,
- prev_bounds,
- has_previous,
- normalized_screen_motion,
- );
+ // Camera size rides the zoom activity spring, so a zoom snap
+ // also jumps the camera rect — suppress blur across snaps here
+ // for the same reason as the display layer.
+ let camera_snapped_in_window =
+ zoom_timeline.snapped_within(prev_frame_time, frame_time);
+ let camera_descriptor = if camera_snapped_in_window {
+ MotionBlurDescriptor::none()
+ } else {
+ Self::compute_camera_motion_blur(
+ current_bounds,
+ prev_bounds,
+ has_previous,
+ normalized_screen_motion,
+ )
+ };
let crop_bounds = match project.camera.shape {
CameraShape::Source => [0.0, 0.0, frame_size[0], frame_size[1]],
@@ -3210,7 +3206,11 @@ impl ProjectUniforms {
// t == 0 it reproduces the shape crop (square center-crop /
// source), at t == 1 it is the aspect-fill split crop.
let split_t = split_layout.as_ref().map_or(0.0, |s| s.factor as f32);
+ let floating_t = split_layout.as_ref().map_or(0.0, |s| s.floating as f32);
let split_fade = 1.0 - split_t;
+ // Same chrome rule as the display layer: classic split strips
+ // rounding/shadow, the floating card keeps them.
+ let chrome_fade = (1.0 - split_t + floating_t).clamp(0.0, 1.0);
let final_target_bounds = snap_bounds_to_output_pixels(
split_layout.as_ref().map_or(target_bounds, |s| {
lerp_bounds(target_bounds, s.camera.target, split_t)
@@ -3238,7 +3238,8 @@ impl ProjectUniforms {
rounding_px: project.camera.rounding / 100.0
* 0.5
* final_target_size[0].min(final_target_size[1])
- * split_fade,
+ * split_fade
+ + min_axis * FLOATING_ROUNDING_FRAC * floating_t,
rounding_type: rounding_type_value(project.camera.rounding_type),
mirror_x: if project.camera.mirror { 1.0 } else { 0.0 },
motion_blur_vector: camera_descriptor.movement_vector_uv,
@@ -3249,7 +3250,7 @@ impl ProjectUniforms {
camera_descriptor.zoom_amount,
0.0,
],
- shadow: project.camera.shadow * split_fade,
+ shadow: project.camera.shadow * chrome_fade,
shadow_size: project
.camera
.advanced_shadow
@@ -3260,7 +3261,7 @@ impl ProjectUniforms {
.advanced_shadow
.as_ref()
.map_or(18.0, |s| s.opacity)
- * split_fade,
+ * chrome_fade,
shadow_blur: project
.camera
.advanced_shadow
@@ -3532,6 +3533,105 @@ mod tests {
assert!((size.y - 1080.0).abs() <= 1.0);
}
+ #[test]
+ fn display_position_translates_and_can_overhang_edges() {
+ let options = render_options(1920, 1080);
+ let mut project = ProjectConfiguration::default();
+ project.background.padding = 50.0;
+ project.background.display_position = Some(XY::new(0.0, 1.0));
+
+ let resolution_base = XY::new(2688, 1512);
+ let offset = ProjectUniforms::display_offset(&options, &project, resolution_base);
+ let size = ProjectUniforms::display_size(&options, &project, resolution_base);
+
+ // Base (centered) offset is (384, 216); centering on the left/bottom
+ // frame edges leaves half the display overhanging on each axis.
+ assert_eq!(offset.coord, XY::new(-960.0, 972.0));
+ // Position never changes the display size.
+ assert_eq!(size.coord, XY::new(1920.0, 1080.0));
+ }
+
+ #[test]
+ fn display_position_center_matches_legacy_centered_layout() {
+ let options = render_options(1920, 1080);
+ let mut legacy = ProjectConfiguration::default();
+ legacy.background.padding = 50.0;
+ let mut positioned = legacy.clone();
+ positioned.background.display_position = Some(XY::new(0.5, 0.5));
+
+ let resolution_base = XY::new(2688, 1512);
+
+ assert_eq!(
+ ProjectUniforms::display_offset(&options, &legacy, resolution_base).coord,
+ ProjectUniforms::display_offset(&options, &positioned, resolution_base).coord,
+ );
+ }
+
+ #[test]
+ fn display_position_shifts_display_even_without_padding() {
+ let options = render_options(1920, 1080);
+ let mut project = ProjectConfiguration::default();
+ project.background.padding = 0.0;
+ project.background.display_position = Some(XY::new(0.25, 0.5));
+
+ let offset = ProjectUniforms::display_offset(&options, &project, XY::new(1920, 1080));
+
+ assert_eq!(offset.coord, XY::new(-480.0, 0.0));
+ }
+
+ #[test]
+ fn display_position_center_is_clamped_to_frame() {
+ let options = render_options(1920, 1080);
+ let mut wild = ProjectConfiguration {
+ aspect_ratio: Some(AspectRatio::Vertical),
+ ..ProjectConfiguration::default()
+ };
+ wild.background.display_position = Some(XY::new(-5.0, 7.0));
+ let mut edge = wild.clone();
+ edge.background.display_position = Some(XY::new(0.0, 1.0));
+
+ let (width, height) = ProjectUniforms::get_base_size(&options, &wild);
+ let resolution_base = XY::new(width, height);
+
+ assert_eq!(
+ ProjectUniforms::display_offset(&options, &wild, resolution_base).coord,
+ ProjectUniforms::display_offset(&options, &edge, resolution_base).coord,
+ );
+ }
+
+ #[test]
+ fn manual_camera_position_centers_rect() {
+ let camera = Camera {
+ manual_position: Some(XY::new(0.5, 0.5)),
+ ..Camera::default()
+ };
+
+ let position = compute_camera_position(&camera, [1920.0, 1080.0], [400.0, 400.0], 50.0);
+
+ assert_eq!(position, [760.0, 340.0]);
+ }
+
+ #[test]
+ fn manual_camera_position_clamps_fully_on_screen() {
+ let camera = Camera {
+ manual_position: Some(XY::new(1.0, 1.0)),
+ ..Camera::default()
+ };
+
+ let position = compute_camera_position(&camera, [1920.0, 1080.0], [400.0, 400.0], 50.0);
+
+ assert_eq!(position, [1520.0, 680.0]);
+ }
+
+ #[test]
+ fn camera_without_manual_position_uses_legacy_enum_layout() {
+ let camera = Camera::default(); // Right / Bottom
+
+ let position = compute_camera_position(&camera, [1920.0, 1080.0], [400.0, 400.0], 50.0);
+
+ assert_eq!(position, [1470.0, 630.0]);
+ }
+
#[test]
fn display_zoom_out_motion_blur_is_subtle() {
let previous = motion_bounds(XY::new(-960.0, -540.0), XY::new(2880.0, 1620.0));
diff --git a/crates/rendering/src/zoom.rs b/crates/rendering/src/zoom.rs
index b4cc391c3..2d9e91c8c 100644
--- a/crates/rendering/src/zoom.rs
+++ b/crates/rendering/src/zoom.rs
@@ -1,54 +1,9 @@
-use cap_project::{XY, ZoomSegment};
-
-use crate::{Coord, RawDisplayUVSpace};
-
-pub const ZOOM_DURATION: f64 = 1.0;
-
-const SCREEN_SPRING_STIFFNESS: f64 = 200.0;
-const SCREEN_SPRING_DAMPING: f64 = 40.0;
-const SCREEN_SPRING_MASS: f64 = 2.25;
-
-#[derive(Debug, Clone, Copy)]
-pub struct SegmentsCursor<'a> {
- time: f64,
- pub segment: Option<&'a ZoomSegment>,
- pub prev_segment: Option<&'a ZoomSegment>,
- segments: &'a [ZoomSegment],
-}
-
-impl<'a> SegmentsCursor<'a> {
- pub fn new(time: f64, segments: &'a [ZoomSegment]) -> Self {
- match segments
- .iter()
- .position(|s| time > s.start && time <= s.end)
- {
- Some(segment_index) => SegmentsCursor {
- time,
- segment: Some(&segments[segment_index]),
- prev_segment: if segment_index > 0 {
- Some(&segments[segment_index - 1])
- } else {
- None
- },
- segments,
- },
- None => {
- let prev = segments
- .iter()
- .enumerate()
- .rev()
- .find(|(_, s)| s.end <= time);
- SegmentsCursor {
- time,
- segment: None,
- prev_segment: prev.map(|(_, s)| s),
- segments,
- }
- }
- }
- }
-}
+use cap_project::XY;
+/// Bounds of the (possibly zoomed) display rect, expressed as a scale of the
+/// unzoomed display: `(0,0)-(1,1)` means no zoom, while a zoomed-in view
+/// expands the rect beyond the unit square so the visible viewport becomes a
+/// sub-region of the source frame.
#[derive(Debug, PartialEq, Clone, Copy)]
pub struct SegmentBounds {
pub top_left: XY<f64>,
@@ -56,45 +11,45 @@ pub struct SegmentBounds {
}
impl SegmentBounds {
- pub fn from_segment_with_cursor_constraint(
- segment: &ZoomSegment,
- zoom_focus: Coord<RawDisplayUVSpace>,
- _actual_cursor: Option<Coord<RawDisplayUVSpace>>,
- ) -> Self {
- let is_auto_mode = matches!(segment.mode, cap_project::ZoomMode::Auto);
+ pub fn new(top_left: XY<f64>, bottom_right: XY<f64>) -> Self {
+ Self {
+ top_left,
+ bottom_right,
+ }
+ }
- let focus_pos = match segment.mode {
- cap_project::ZoomMode::Auto => (zoom_focus.x, zoom_focus.y),
- cap_project::ZoomMode::Manual { x, y } => (x as f64, y as f64),
- };
+ pub fn default() -> Self {
+ SegmentBounds::new(XY::new(0.0, 0.0), XY::new(1.0, 1.0))
+ }
- let (effective_zoom, viewport_center) = if is_auto_mode {
- let center =
- Self::calculate_follow_center(focus_pos, segment.amount, segment.edge_snap_ratio);
- (segment.amount, center)
+ /// Build bounds from a zoom `amount` (>= 1) and a normalized center in
+ /// [0, 1] "travel space": 0 pins the visible viewport flush to the
+ /// left/top edge, 1 flush to the right/bottom edge, 0.5 centers it.
+ /// Inputs are clamped so the resulting viewport is always contained in
+ /// the source frame (the geometric in-bounds guarantee that replaced the
+ /// old `ensure_cursor_visible*` post-correction).
+ pub fn from_amount_center(amount: f64, center: XY<f64>) -> Self {
+ let amount = if amount.is_finite() {
+ amount.max(1.0)
} else {
- (segment.amount, focus_pos)
+ 1.0
};
+ let center = XY::new(clamp_unit(center.x), clamp_unit(center.y));
- let scaled_center = [
- viewport_center.0 * effective_zoom,
- viewport_center.1 * effective_zoom,
- ];
- let center_diff = [
- scaled_center[0] - viewport_center.0,
- scaled_center[1] - viewport_center.1,
- ];
+ // Same formula the easing-based `from_segment_with_cursor_constraint`
+ // used: scale about the origin, then translate so `center` maps across
+ // the valid travel range.
+ let center_diff = XY::new(center.x * amount - center.x, center.y * amount - center.y);
SegmentBounds::new(
- XY::new(0.0 - center_diff[0], 0.0 - center_diff[1]),
- XY::new(
- effective_zoom - center_diff[0],
- effective_zoom - center_diff[1],
- ),
+ XY::new(0.0 - center_diff.x, 0.0 - center_diff.y),
+ XY::new(amount - center_diff.x, amount - center_diff.y),
)
}
- fn snap_to_edges(scalar: f64, snap_ratio: f64) -> f64 {
+ /// Remaps a scalar in [0,1] so values inside the outer `snap_ratio` band
+ /// stick to the edges: [r, 1-r] -> [0, 1], clamped.
+ pub(crate) fn snap_to_edges(scalar: f64, snap_ratio: f64) -> f64 {
if snap_ratio <= 0.0 {
return scalar;
}
@@ -106,17 +61,20 @@ impl SegmentBounds {
((scalar - lo) / (hi - lo)).clamp(0.0, 1.0)
}
- fn calculate_follow_center(
- cursor_pos: (f64, f64),
+ /// Maps a focus position (UV space) to a `from_amount_center`-space center
+ /// for auto zooms: edge-snap each axis, then compress into the band that
+ /// keeps a comfortable margin around the focus at the given zoom amount.
+ pub(crate) fn calculate_follow_center(
+ focus_pos: (f64, f64),
zoom_amount: f64,
edge_snap_ratio: f64,
) -> (f64, f64) {
let snapped = (
- Self::snap_to_edges(cursor_pos.0, edge_snap_ratio),
- Self::snap_to_edges(cursor_pos.1, edge_snap_ratio),
+ Self::snap_to_edges(focus_pos.0, edge_snap_ratio),
+ Self::snap_to_edges(focus_pos.1, edge_snap_ratio),
);
- let viewport_half = 0.5 / zoom_amount;
+ let viewport_half = 0.5 / zoom_amount.max(1.0);
let min_center = viewport_half;
let max_center = 1.0 - viewport_half;
@@ -125,1041 +83,127 @@ impl SegmentBounds {
(min_center + snapped.1 * (max_center - min_center)).clamp(min_center, max_center),
)
}
+}
- pub fn new(top_left: XY<f64>, bottom_right: XY<f64>) -> Self {
- Self {
- top_left,
- bottom_right,
- }
- }
-
- pub fn default() -> Self {
- SegmentBounds::new(XY::new(0.0, 0.0), XY::new(1.0, 1.0))
+fn clamp_unit(v: f64) -> f64 {
+ if v.is_finite() {
+ v.clamp(0.0, 1.0)
+ } else {
+ 0.5
}
}
+/// A sampled zoom transform. Produced by `ZoomTransformTimeline::sample`.
#[derive(Debug, Clone, Copy)]
pub struct InterpolatedZoom {
- // the ratio of current zoom to the maximum amount for the current segment
+ /// Smoothed 0..1 "zoom activity": the spring-driven response to whether
+ /// any zoom segment is active. Reaches 1 once a zoom has fully engaged
+ /// and returns to 0 at rest. Consumers (e.g. camera scale-during-zoom)
+ /// must not assume monotonicity within a segment; it is always clamped
+ /// to [0, 1].
pub t: f64,
pub bounds: SegmentBounds,
}
-fn spring_ease(t: f32) -> f32 {
- if t <= 0.0 {
- return 0.0;
- }
- if t >= 1.0 {
- return 1.0;
- }
-
- let omega0 = (SCREEN_SPRING_STIFFNESS / SCREEN_SPRING_MASS).sqrt() as f32;
- let zeta = (SCREEN_SPRING_DAMPING
- / (2.0 * (SCREEN_SPRING_STIFFNESS * SCREEN_SPRING_MASS).sqrt())) as f32;
-
- if zeta < 1.0 {
- let omega_d = omega0 * (1.0 - zeta * zeta).sqrt();
- let decay = (-zeta * omega0 * t).exp();
- 1.0 - decay * ((omega_d * t).cos() + (zeta * omega0 / omega_d) * (omega_d * t).sin())
- } else {
- let decay = (-omega0 * t).exp();
- 1.0 - decay * (1.0 + omega0 * t)
- }
-}
-
-fn spring_ease_out(t: f32) -> f32 {
- if t <= 0.0 {
- return 0.0;
- }
- if t >= 1.0 {
- return 1.0;
- }
-
- let omega0 = (SCREEN_SPRING_STIFFNESS / SCREEN_SPRING_MASS).sqrt() as f32 * 0.9;
- let zeta = (SCREEN_SPRING_DAMPING
- / (2.0 * (SCREEN_SPRING_STIFFNESS * SCREEN_SPRING_MASS).sqrt())) as f32
- * 1.15;
-
- if zeta < 1.0 {
- let omega_d = omega0 * (1.0 - zeta * zeta).sqrt();
- let decay = (-zeta * omega0 * t).exp();
- 1.0 - decay * ((omega_d * t).cos() + (zeta * omega0 / omega_d) * (omega_d * t).sin())
- } else {
- let decay = (-omega0 * t).exp();
- 1.0 - decay * (1.0 + omega0 * t)
- }
-}
-
-fn instant_ease(t: f32) -> f32 {
- if t <= 0.0 { 0.0 } else { 1.0 }
-}
-
impl InterpolatedZoom {
- pub fn new(cursor: SegmentsCursor, interpolated_cursor: Coord<RawDisplayUVSpace>) -> Self {
- Self::new_with_cursor(cursor, interpolated_cursor, None)
- }
-
- pub fn new_with_cursor(
- cursor: SegmentsCursor,
- zoom_focus: Coord<RawDisplayUVSpace>,
- actual_cursor: Option<Coord<RawDisplayUVSpace>>,
- ) -> Self {
- Self::new_with_cursor_and_end_focus(cursor, zoom_focus, actual_cursor, None, None)
- }
-
- pub fn new_with_cursor_and_end_focus(
- cursor: SegmentsCursor,
- zoom_focus: Coord<RawDisplayUVSpace>,
- actual_cursor: Option<Coord<RawDisplayUVSpace>>,
- segment_end_focus: Option<Coord<RawDisplayUVSpace>>,
- segment_end_cursor: Option<Coord<RawDisplayUVSpace>>,
- ) -> Self {
- let use_instant = cursor.segment.map(|s| s.instant_animation).unwrap_or(false);
- if use_instant {
- Self::new_with_easing_and_cursor(
- cursor,
- zoom_focus,
- actual_cursor,
- segment_end_focus,
- segment_end_cursor,
- instant_ease,
- instant_ease,
- )
- } else {
- Self::new_with_easing_and_cursor(
- cursor,
- zoom_focus,
- actual_cursor,
- segment_end_focus,
- segment_end_cursor,
- spring_ease,
- spring_ease_out,
- )
- }
- }
-
pub fn display_amount(&self) -> f64 {
(self.bounds.bottom_right - self.bounds.top_left).x
}
-
- fn new_with_easing_and_cursor(
- cursor: SegmentsCursor,
- zoom_focus: Coord<RawDisplayUVSpace>,
- actual_cursor: Option<Coord<RawDisplayUVSpace>>,
- segment_end_focus: Option<Coord<RawDisplayUVSpace>>,
- segment_end_cursor: Option<Coord<RawDisplayUVSpace>>,
- ease_in: impl Fn(f32) -> f32 + Copy,
- ease_out: impl Fn(f32) -> f32 + Copy,
- ) -> InterpolatedZoom {
- let default = SegmentBounds::default();
-
- let result = match (cursor.prev_segment, cursor.segment) {
- (Some(prev_segment), None) => {
- let raw_t = t_clamp((cursor.time - prev_segment.end) / ZOOM_DURATION);
- let ease_val = ease_out(raw_t as f32) as f64;
-
- let ramp = (raw_t * 5.0).min(1.0);
- let ramp_smooth = ramp * ramp * (3.0 - 2.0 * ramp);
- let zoom_t = ease_val * ramp_smooth;
-
- let is_auto_zoom_out = matches!(prev_segment.mode, cap_project::ZoomMode::Auto);
- let focus_for_bounds = if is_auto_zoom_out {
- segment_end_focus.unwrap_or(zoom_focus)
- } else {
- zoom_focus
- };
- let cursor_for_bounds = if is_auto_zoom_out {
- segment_end_cursor.or(actual_cursor)
- } else {
- None
- };
-
- if is_auto_zoom_out {
- let bounds = SegmentBounds::from_segment_with_cursor_constraint(
- prev_segment,
- focus_for_bounds,
- cursor_for_bounds,
- );
- let bounds = if let Some(cursor_coord) = cursor_for_bounds {
- Self { t: 1.0, bounds }
- .ensure_cursor_visible_gentle((cursor_coord.x, cursor_coord.y))
- .bounds
- } else {
- bounds
- };
-
- return Self {
- t: 1.0 - zoom_t,
- bounds: SegmentBounds::new(
- bounds.top_left * (1.0 - zoom_t) + default.top_left * zoom_t,
- bounds.bottom_right * (1.0 - zoom_t) + default.bottom_right * zoom_t,
- ),
- };
- }
-
- let eased_amount = prev_segment.amount * (1.0 - zoom_t) + 1.0 * zoom_t;
-
- if eased_amount <= 1.001 {
- return Self {
- t: 0.0,
- bounds: default,
- };
- }
-
- let eased_segment = ZoomSegment {
- amount: eased_amount,
- ..prev_segment.clone()
- };
- let bounds = SegmentBounds::from_segment_with_cursor_constraint(
- &eased_segment,
- focus_for_bounds,
- cursor_for_bounds,
- );
- let bounds = if let Some(cursor_coord) = cursor_for_bounds {
- Self { t: 1.0, bounds }
- .ensure_cursor_visible((cursor_coord.x, cursor_coord.y))
- .bounds
- } else {
- bounds
- };
-
- Self {
- t: 1.0 - zoom_t,
- bounds,
- }
- }
- (None, Some(segment)) => {
- let t =
- ease_in(t_clamp((cursor.time - segment.start) / ZOOM_DURATION) as f32) as f64;
-
- Self {
- t,
- bounds: {
- let segment_bounds = SegmentBounds::from_segment_with_cursor_constraint(
- segment,
- zoom_focus,
- actual_cursor,
- );
-
- SegmentBounds::new(
- default.top_left * (1.0 - t) + segment_bounds.top_left * t,
- default.bottom_right * (1.0 - t) + segment_bounds.bottom_right * t,
- )
- },
- }
- }
- (Some(prev_segment), Some(segment)) => {
- let prev_segment_bounds = SegmentBounds::from_segment_with_cursor_constraint(
- prev_segment,
- zoom_focus,
- actual_cursor,
- );
- let segment_bounds = SegmentBounds::from_segment_with_cursor_constraint(
- segment,
- zoom_focus,
- actual_cursor,
- );
-
- let zoom_t =
- ease_in(t_clamp((cursor.time - segment.start) / ZOOM_DURATION) as f32) as f64;
-
- if segment.start == prev_segment.end {
- Self {
- t: 1.0,
- bounds: SegmentBounds::new(
- prev_segment_bounds.top_left * (1.0 - zoom_t)
- + segment_bounds.top_left * zoom_t,
- prev_segment_bounds.bottom_right * (1.0 - zoom_t)
- + segment_bounds.bottom_right * zoom_t,
- ),
- }
- } else if segment.start - prev_segment.end < ZOOM_DURATION {
- let min = InterpolatedZoom::new_with_easing_and_cursor(
- SegmentsCursor::new(segment.start, cursor.segments),
- zoom_focus,
- actual_cursor,
- segment_end_focus,
- segment_end_cursor,
- ease_in,
- ease_out,
- );
-
- Self {
- t: (min.t * (1.0 - zoom_t)) + zoom_t,
- bounds: {
- let max = segment_bounds;
-
- SegmentBounds::new(
- min.bounds.top_left * (1.0 - zoom_t) + max.top_left * zoom_t,
- min.bounds.bottom_right * (1.0 - zoom_t)
- + max.bottom_right * zoom_t,
- )
- },
- }
- } else {
- Self {
- t: zoom_t,
- bounds: SegmentBounds::new(
- default.top_left * (1.0 - zoom_t) + segment_bounds.top_left * zoom_t,
- default.bottom_right * (1.0 - zoom_t)
- + segment_bounds.bottom_right * zoom_t,
- ),
- }
- }
- }
- _ => Self {
- t: 0.0,
- bounds: default,
- },
- };
-
- if cursor
- .segment
- .is_some_and(|s| matches!(s.mode, cap_project::ZoomMode::Auto))
- && let Some(cursor_coord) = actual_cursor
- {
- return result.ensure_cursor_visible_gentle((cursor_coord.x, cursor_coord.y));
- }
-
- result
- }
-}
-
-impl InterpolatedZoom {
- fn ensure_cursor_visible_gentle(self, cursor_pos: (f64, f64)) -> Self {
- let current_zoom = self.bounds.bottom_right.x - self.bounds.top_left.x;
-
- if current_zoom <= 1.001 {
- return self;
- }
-
- let viewport_size = 1.0 / current_zoom;
- let viewport_left = -self.bounds.top_left.x / current_zoom;
- let viewport_right = viewport_left + viewport_size;
- let viewport_top = -self.bounds.top_left.y / current_zoom;
- let viewport_bottom = viewport_top + viewport_size;
-
- let margin = viewport_size * 0.12;
-
- let inner_left = viewport_left + margin;
- let inner_right = viewport_right - margin;
- let inner_top = viewport_top + margin;
- let inner_bottom = viewport_bottom - margin;
-
- if cursor_pos.0 >= inner_left
- && cursor_pos.0 <= inner_right
- && cursor_pos.1 >= inner_top
- && cursor_pos.1 <= inner_bottom
- {
- return self;
- }
-
- let mut new_left = viewport_left;
- let mut new_top = viewport_top;
-
- if cursor_pos.0 < inner_left {
- new_left = cursor_pos.0 - margin;
- } else if cursor_pos.0 > inner_right {
- new_left = cursor_pos.0 - viewport_size + margin;
- }
-
- if cursor_pos.1 < inner_top {
- new_top = cursor_pos.1 - margin;
- } else if cursor_pos.1 > inner_bottom {
- new_top = cursor_pos.1 - viewport_size + margin;
- }
-
- new_left = new_left.clamp(0.0, 1.0 - viewport_size);
- new_top = new_top.clamp(0.0, 1.0 - viewport_size);
-
- let new_tl_x = -new_left * current_zoom;
- let new_tl_y = -new_top * current_zoom;
-
- Self {
- t: self.t,
- bounds: SegmentBounds::new(
- XY::new(new_tl_x, new_tl_y),
- XY::new(new_tl_x + current_zoom, new_tl_y + current_zoom),
- ),
- }
- }
-
- fn ensure_cursor_visible(self, cursor_pos: (f64, f64)) -> Self {
- let current_zoom = self.bounds.bottom_right.x - self.bounds.top_left.x;
-
- if current_zoom <= 1.001 {
- return self;
- }
-
- let viewport_size = 1.0 / current_zoom;
- let viewport_left = -self.bounds.top_left.x / current_zoom;
- let viewport_right = viewport_left + viewport_size;
- let viewport_top = -self.bounds.top_left.y / current_zoom;
- let viewport_bottom = viewport_top + viewport_size;
-
- let margin_ratio = 0.15;
- let margin = viewport_size * margin_ratio;
-
- let inner_left = viewport_left + margin;
- let inner_right = viewport_right - margin;
- let inner_top = viewport_top + margin;
- let inner_bottom = viewport_bottom - margin;
-
- let cursor_in_safe_zone = cursor_pos.0 >= inner_left
- && cursor_pos.0 <= inner_right
- && cursor_pos.1 >= inner_top
- && cursor_pos.1 <= inner_bottom;
-
- if cursor_in_safe_zone {
- return self;
- }
-
- let target_margin = viewport_size * margin_ratio;
-
- let mut new_viewport_left = viewport_left;
- let mut new_viewport_top = viewport_top;
-
- if cursor_pos.0 < inner_left {
- new_viewport_left = cursor_pos.0 - target_margin;
- } else if cursor_pos.0 > inner_right {
- new_viewport_left = cursor_pos.0 - viewport_size + target_margin;
- }
-
- if cursor_pos.1 < inner_top {
- new_viewport_top = cursor_pos.1 - target_margin;
- } else if cursor_pos.1 > inner_bottom {
- new_viewport_top = cursor_pos.1 - viewport_size + target_margin;
- }
-
- new_viewport_left = new_viewport_left.clamp(0.0, 1.0 - viewport_size);
- new_viewport_top = new_viewport_top.clamp(0.0, 1.0 - viewport_size);
-
- let new_viewport_right = new_viewport_left + viewport_size;
- let new_viewport_bottom = new_viewport_top + viewport_size;
-
- let cursor_now_visible = cursor_pos.0 >= new_viewport_left
- && cursor_pos.0 <= new_viewport_right
- && cursor_pos.1 >= new_viewport_top
- && cursor_pos.1 <= new_viewport_bottom;
-
- if cursor_now_visible {
- let new_top_left_x = -new_viewport_left * current_zoom;
- let new_top_left_y = -new_viewport_top * current_zoom;
-
- return Self {
- t: self.t,
- bounds: SegmentBounds::new(
- XY::new(new_top_left_x, new_top_left_y),
- XY::new(new_top_left_x + current_zoom, new_top_left_y + current_zoom),
- ),
- };
- }
-
- let required_margin = 0.1;
- let dist_from_left = (cursor_pos.0 - required_margin).max(0.0);
- let dist_from_right = (1.0 - cursor_pos.0 - required_margin).max(0.0);
- let dist_from_top = (cursor_pos.1 - required_margin).max(0.0);
- let dist_from_bottom = (1.0 - cursor_pos.1 - required_margin).max(0.0);
-
- let effective_dist_x = dist_from_left.min(dist_from_right).max(0.001);
- let effective_dist_y = dist_from_top.min(dist_from_bottom).max(0.001);
-
- let max_zoom_x = 0.5 / effective_dist_x;
- let max_zoom_y = 0.5 / effective_dist_y;
-
- let max_zoom_for_cursor = max_zoom_x.min(max_zoom_y).max(1.0);
- let new_zoom = current_zoom.min(max_zoom_for_cursor);
-
- let new_viewport_size = 1.0 / new_zoom;
- let new_margin = new_viewport_size * margin_ratio;
-
- let final_viewport_left = if cursor_pos.0 - new_margin <= 0.0 {
- 0.0
- } else if cursor_pos.0 + new_margin >= 1.0 {
- 1.0 - new_viewport_size
- } else {
- (cursor_pos.0 - new_viewport_size / 2.0).clamp(0.0, 1.0 - new_viewport_size)
- };
-
- let final_viewport_top = if cursor_pos.1 - new_margin <= 0.0 {
- 0.0
- } else if cursor_pos.1 + new_margin >= 1.0 {
- 1.0 - new_viewport_size
- } else {
- (cursor_pos.1 - new_viewport_size / 2.0).clamp(0.0, 1.0 - new_viewport_size)
- };
-
- let new_top_left_x = -final_viewport_left * new_zoom;
- let new_top_left_y = -final_viewport_top * new_zoom;
-
- Self {
- t: self.t,
- bounds: SegmentBounds::new(
- XY::new(new_top_left_x, new_top_left_y),
- XY::new(new_top_left_x + new_zoom, new_top_left_y + new_zoom),
- ),
- }
- }
-}
-
-fn t_clamp(v: f64) -> f64 {
- v.clamp(0.0, 1.0)
}
#[cfg(test)]
mod test {
- use cap_project::{GlideDirection, ZoomMode, ZoomSegment};
-
use super::*;
- // Custom macro for floating-point near equality
+ // The old easing-based tests (segment ramps, ensure_cursor_visible*) were
+ // removed together with the state machine they exercised; the spring
+ // timeline that replaced it is covered in `zoom_spring.rs`. These tests
+ // pin down the pure geometry that survived the rework.
+
macro_rules! assert_f64_near {
($left:expr, $right:expr, $label:literal) => {
let left = $left;
let right = $right;
assert!(
- (left - right).abs() < 1e-6,
- "{}: `(left ~ right)` \n left: `{:?}`, \n right: `{:?}`",
+ (left - right).abs() < 1e-9,
+ "{}: left `{:?}` != right `{:?}`",
$label,
left,
right
)
};
- ($left:expr, $right:expr) => {
- assert_f64_near!($left, $right, "assertion failed");
- };
- }
-
- fn c<'a>(time: f64, segments: &'a [ZoomSegment]) -> SegmentsCursor<'a> {
- SegmentsCursor::new(time, segments)
- }
-
- fn test_interp((time, segments): (f64, &[ZoomSegment]), expected: InterpolatedZoom) {
- let actual = InterpolatedZoom::new_with_easing_and_cursor(
- c(time, segments),
- Default::default(),
- None,
- None,
- None,
- |t| t,
- |t| t,
- );
-
- assert_f64_near!(actual.t, expected.t, "t");
-
- let a = &actual.bounds;
- let e = &expected.bounds;
-
- assert_f64_near!(a.top_left.x, e.top_left.x, "bounds.top_left.x");
- assert_f64_near!(a.top_left.y, e.top_left.y, "bounds.top_left.y");
- assert_f64_near!(a.bottom_right.x, e.bottom_right.x, "bounds.bottom_right.x");
- assert_f64_near!(a.bottom_right.y, e.bottom_right.y, "bounds.bottom_right.y");
- }
-
- fn test_segment(start: f64, end: f64, amount: f64, x: f64, y: f64) -> ZoomSegment {
- ZoomSegment {
- start,
- end,
- amount,
- mode: ZoomMode::Manual {
- x: x as f32,
- y: y as f32,
- },
- glide_direction: GlideDirection::default(),
- glide_speed: 0.05,
- instant_animation: false,
- edge_snap_ratio: 0.075,
- }
- }
-
- fn test_auto_segment(start: f64, end: f64, amount: f64) -> ZoomSegment {
- ZoomSegment {
- start,
- end,
- amount,
- mode: ZoomMode::Auto,
- glide_direction: GlideDirection::default(),
- glide_speed: 0.5,
- instant_animation: false,
- edge_snap_ratio: 0.25,
- }
- }
-
- #[test]
- fn one_segment() {
- let segments = vec![test_segment(2.0, 4.0, 2.0, 0.5, 0.5)];
-
- test_interp(
- (0.0, &segments),
- InterpolatedZoom {
- t: 0.0,
- bounds: SegmentBounds::default(),
- },
- );
- test_interp(
- (2.0, &segments),
- InterpolatedZoom {
- t: 0.0,
- bounds: SegmentBounds::default(),
- },
- );
- test_interp(
- (2.0 + ZOOM_DURATION * 0.1, &segments),
- InterpolatedZoom {
- t: 0.1,
- bounds: SegmentBounds::new(XY::new(-0.05, -0.05), XY::new(1.05, 1.05)),
- },
- );
- test_interp(
- (2.0 + ZOOM_DURATION * 0.9, &segments),
- InterpolatedZoom {
- t: 0.9,
- bounds: SegmentBounds::new(XY::new(-0.45, -0.45), XY::new(1.45, 1.45)),
- },
- );
- test_interp(
- (2.0 + ZOOM_DURATION, &segments),
- InterpolatedZoom {
- t: 1.0,
- bounds: SegmentBounds::new(XY::new(-0.5, -0.5), XY::new(1.5, 1.5)),
- },
- );
- test_interp(
- (4.0, &segments),
- InterpolatedZoom {
- t: 1.0,
- bounds: SegmentBounds::new(XY::new(-0.5, -0.5), XY::new(1.5, 1.5)),
- },
- );
- test_interp(
- (4.0 + ZOOM_DURATION * 0.2, &segments),
- InterpolatedZoom {
- t: 0.8,
- bounds: SegmentBounds::new(XY::new(-0.4, -0.4), XY::new(1.4, 1.4)),
- },
- );
- test_interp(
- (4.0 + ZOOM_DURATION * 0.8, &segments),
- InterpolatedZoom {
- t: 0.2,
- bounds: SegmentBounds::new(XY::new(-0.1, -0.1), XY::new(1.1, 1.1)),
- },
- );
- test_interp(
- (4.0 + ZOOM_DURATION, &segments),
- InterpolatedZoom {
- t: 0.0,
- bounds: SegmentBounds::new(XY::new(0.0, 0.0), XY::new(1.0, 1.0)),
- },
- );
}
#[test]
- fn two_segments_no_gap() {
- let segments = vec![
- test_segment(2.0, 4.0, 2.0, 0.0, 0.0),
- test_segment(4.0, 6.0, 4.0, 0.5, 0.5),
- ];
-
- test_interp(
- (4.0, &segments),
- InterpolatedZoom {
- t: 1.0,
- bounds: SegmentBounds::new(XY::new(0.0, 0.0), XY::new(2.0, 2.0)),
- },
- );
- test_interp(
- (4.0 + ZOOM_DURATION * 0.2, &segments),
- InterpolatedZoom {
- t: 1.0,
- bounds: SegmentBounds::new(XY::new(-0.3, -0.3), XY::new(2.1, 2.1)),
- },
- );
- test_interp(
- (4.0 + ZOOM_DURATION * 0.8, &segments),
- InterpolatedZoom {
- t: 1.0,
- bounds: SegmentBounds::new(XY::new(-1.2, -1.2), XY::new(2.4, 2.4)),
- },
- );
- test_interp(
- (4.0 + ZOOM_DURATION, &segments),
- InterpolatedZoom {
- t: 1.0,
- bounds: SegmentBounds::new(XY::new(-1.5, -1.5), XY::new(2.5, 2.5)),
- },
- );
+ fn from_amount_center_identity_at_amount_one() {
+ let bounds = SegmentBounds::from_amount_center(1.0, XY::new(0.3, 0.9));
+ assert_f64_near!(bounds.top_left.x, 0.0, "top_left.x");
+ assert_f64_near!(bounds.top_left.y, 0.0, "top_left.y");
+ assert_f64_near!(bounds.bottom_right.x, 1.0, "bottom_right.x");
+ assert_f64_near!(bounds.bottom_right.y, 1.0, "bottom_right.y");
}
#[test]
- fn two_segments_small_gap() {
- let segments = vec![
- test_segment(2.0, 4.0, 2.0, 0.5, 0.5),
- test_segment(4.0 + ZOOM_DURATION * 0.75, 6.0, 4.0, 0.5, 0.5),
- ];
-
- test_interp(
- (4.0, &segments),
- InterpolatedZoom {
- t: 1.0,
- bounds: SegmentBounds::new(XY::new(-0.5, -0.5), XY::new(1.5, 1.5)),
- },
- );
- test_interp(
- (4.0 + ZOOM_DURATION * 0.5, &segments),
- InterpolatedZoom {
- t: 0.5,
- bounds: SegmentBounds::new(XY::new(-0.25, -0.25), XY::new(1.25, 1.25)),
- },
- );
- test_interp(
- (4.0 + ZOOM_DURATION * 0.75, &segments),
- InterpolatedZoom {
- t: 0.25,
- bounds: SegmentBounds::new(XY::new(-0.125, -0.125), XY::new(1.125, 1.125)),
- },
- );
- test_interp(
- (4.0 + ZOOM_DURATION * (0.75 + 0.5), &segments),
- InterpolatedZoom {
- t: 0.625,
- bounds: SegmentBounds::new(XY::new(-0.8125, -0.8125), XY::new(1.8125, 1.8125)),
- },
- );
- test_interp(
- (4.0 + ZOOM_DURATION * (0.75 + 1.0), &segments),
- InterpolatedZoom {
- t: 1.0,
- bounds: SegmentBounds::new(XY::new(-1.5, -1.5), XY::new(2.5, 2.5)),
- },
- );
+ fn from_amount_center_centered() {
+ let bounds = SegmentBounds::from_amount_center(2.0, XY::new(0.5, 0.5));
+ assert_f64_near!(bounds.top_left.x, -0.5, "top_left.x");
+ assert_f64_near!(bounds.top_left.y, -0.5, "top_left.y");
+ assert_f64_near!(bounds.bottom_right.x, 1.5, "bottom_right.x");
+ assert_f64_near!(bounds.bottom_right.y, 1.5, "bottom_right.y");
}
#[test]
- fn two_segments_large_gap() {
- let segments = vec![
- test_segment(2.0, 4.0, 2.0, 0.5, 0.5),
- test_segment(7.0, 9.0, 4.0, 0.0, 0.0),
- ];
-
- test_interp(
- (4.0, &segments),
- InterpolatedZoom {
- t: 1.0,
- bounds: SegmentBounds::new(XY::new(-0.5, -0.5), XY::new(1.5, 1.5)),
- },
- );
- test_interp(
- (4.0 + ZOOM_DURATION * 0.5, &segments),
- InterpolatedZoom {
- t: 0.5,
- bounds: SegmentBounds::new(XY::new(-0.25, -0.25), XY::new(1.25, 1.25)),
- },
- );
- test_interp(
- (4.0 + ZOOM_DURATION, &segments),
- InterpolatedZoom {
- t: 0.0,
- bounds: SegmentBounds::new(XY::new(0.0, 0.0), XY::new(1.0, 1.0)),
- },
- );
- test_interp(
- (7.0, &segments),
- InterpolatedZoom {
- t: 0.0,
- bounds: SegmentBounds::new(XY::new(0.0, 0.0), XY::new(1.0, 1.0)),
- },
- );
- test_interp(
- (7.0 + ZOOM_DURATION * 0.5, &segments),
- InterpolatedZoom {
- t: 0.5,
- bounds: SegmentBounds::new(XY::new(0.0, 0.0), XY::new(2.5, 2.5)),
- },
- );
- test_interp(
- (7.0 + ZOOM_DURATION * 1.0, &segments),
- InterpolatedZoom {
- t: 1.0,
- bounds: SegmentBounds::new(XY::new(0.0, 0.0), XY::new(4.0, 4.0)),
- },
- );
- }
-
- fn cursor_is_visible_in_zoom(zoom: &InterpolatedZoom, cursor_pos: (f64, f64)) -> bool {
- let current_zoom = zoom.bounds.bottom_right.x - zoom.bounds.top_left.x;
- if current_zoom <= 1.001 {
- return cursor_pos.0 >= 0.0
- && cursor_pos.0 <= 1.0
- && cursor_pos.1 >= 0.0
- && cursor_pos.1 <= 1.0;
+ fn from_amount_center_edges_stay_in_bounds() {
+ // center 0 -> viewport flush left/top, center 1 -> flush right/bottom.
+ for amount in [1.0, 1.5, 2.0, 3.0, 4.5] {
+ for c in [0.0, 0.25, 0.5, 0.75, 1.0] {
+ let bounds = SegmentBounds::from_amount_center(amount, XY::new(c, c));
+ // Display must cover the whole output: top_left <= 0 and
+ // bottom_right >= 1 on both axes.
+ assert!(bounds.top_left.x <= 1e-9, "tl.x for a={amount} c={c}");
+ assert!(bounds.top_left.y <= 1e-9, "tl.y for a={amount} c={c}");
+ assert!(
+ bounds.bottom_right.x >= 1.0 - 1e-9,
+ "br.x for a={amount} c={c}"
+ );
+ assert!(
+ bounds.bottom_right.y >= 1.0 - 1e-9,
+ "br.y for a={amount} c={c}"
+ );
+ }
}
-
- let viewport_size = 1.0 / current_zoom;
- let viewport_left = -zoom.bounds.top_left.x / current_zoom;
- let viewport_right = viewport_left + viewport_size;
- let viewport_top = -zoom.bounds.top_left.y / current_zoom;
- let viewport_bottom = viewport_top + viewport_size;
-
- let margin = 1e-9;
- cursor_pos.0 >= viewport_left - margin
- && cursor_pos.0 <= viewport_right + margin
- && cursor_pos.1 >= viewport_top + margin
- && cursor_pos.1 <= viewport_bottom + margin
- }
-
- #[test]
- fn ensure_cursor_visible_keeps_cursor_in_view() {
- let zoom = InterpolatedZoom {
- t: 1.0,
- bounds: SegmentBounds::new(XY::new(-0.5, -0.5), XY::new(1.5, 1.5)),
- };
-
- let cursor_outside_right = (0.9, 0.5);
- let result = zoom.ensure_cursor_visible(cursor_outside_right);
- assert!(
- cursor_is_visible_in_zoom(&result, cursor_outside_right),
- "Cursor should be visible after ensure_cursor_visible"
- );
-
- let cursor_outside_bottom = (0.5, 0.9);
- let result = zoom.ensure_cursor_visible(cursor_outside_bottom);
- assert!(
- cursor_is_visible_in_zoom(&result, cursor_outside_bottom),
- "Cursor should be visible after ensure_cursor_visible"
- );
-
- let cursor_outside_corner = (0.9, 0.9);
- let result = zoom.ensure_cursor_visible(cursor_outside_corner);
- assert!(
- cursor_is_visible_in_zoom(&result, cursor_outside_corner),
- "Cursor should be visible after ensure_cursor_visible"
- );
-
- let cursor_at_edge = (0.95, 0.95);
- let result = zoom.ensure_cursor_visible(cursor_at_edge);
- assert!(
- cursor_is_visible_in_zoom(&result, cursor_at_edge),
- "Cursor at edge should be visible after ensure_cursor_visible"
- );
}
#[test]
- fn ensure_cursor_visible_handles_extreme_positions() {
- let zoom = InterpolatedZoom {
- t: 1.0,
- bounds: SegmentBounds::new(XY::new(-0.5, -0.5), XY::new(1.5, 1.5)),
- };
-
- let test_positions = [
- (0.05, 0.5),
- (0.95, 0.5),
- (0.5, 0.05),
- (0.5, 0.95),
- (0.05, 0.05),
- (0.95, 0.95),
- (0.05, 0.95),
- (0.95, 0.05),
- ];
-
- for cursor_pos in test_positions {
- let result = zoom.ensure_cursor_visible(cursor_pos);
- assert!(
- cursor_is_visible_in_zoom(&result, cursor_pos),
- "Cursor at {cursor_pos:?} should be visible"
- );
- }
+ fn from_amount_center_clamps_bad_inputs() {
+ let bounds = SegmentBounds::from_amount_center(0.25, XY::new(-4.0, 7.0));
+ // amount below 1 clamps to identity scale; centers clamp into [0,1].
+ assert_f64_near!(bounds.bottom_right.x - bounds.top_left.x, 1.0, "width");
+ let nan_bounds = SegmentBounds::from_amount_center(f64::NAN, XY::new(f64::NAN, 0.5));
+ assert!(nan_bounds.top_left.x.is_finite());
+ assert!(nan_bounds.bottom_right.y.is_finite());
}
#[test]
- fn ensure_cursor_visible_handles_interpolated_bounds() {
- let zoom = InterpolatedZoom {
- t: 0.5,
- bounds: SegmentBounds::new(XY::new(-0.25, -0.25), XY::new(1.25, 1.25)),
- };
+ fn follow_center_maps_focus_across_band() {
+ // Center focus stays centered.
+ let (cx, cy) = SegmentBounds::calculate_follow_center((0.5, 0.5), 2.0, 0.0);
+ assert!((cx - 0.5).abs() < 1e-6);
+ assert!((cy - 0.5).abs() < 1e-6);
- let cursor_pos = (0.85, 0.85);
- let result = zoom.ensure_cursor_visible(cursor_pos);
- assert!(
- cursor_is_visible_in_zoom(&result, cursor_pos),
- "Cursor should be visible in interpolated zoom state"
- );
+ // Extreme focus clamps to the band edge for the zoom amount.
+ let (left, _) = SegmentBounds::calculate_follow_center((0.0, 0.5), 2.0, 0.0);
+ assert!((left - 0.25).abs() < 1e-6);
+ let (right, _) = SegmentBounds::calculate_follow_center((1.0, 0.5), 2.0, 0.0);
+ assert!((right - 0.75).abs() < 1e-6);
}
#[test]
- fn gentle_visibility_keeps_context_near_edges() {
+ fn display_amount_is_zoom_scale() {
let zoom = InterpolatedZoom {
t: 1.0,
- bounds: SegmentBounds::new(XY::new(-0.25, -0.25), XY::new(1.25, 1.25)),
+ bounds: SegmentBounds::from_amount_center(2.5, XY::new(0.4, 0.6)),
};
-
- let cursor_pos = (0.9, 0.5);
- let result = zoom.ensure_cursor_visible_gentle(cursor_pos);
- let current_zoom = result.bounds.bottom_right.x - result.bounds.top_left.x;
- let viewport_size = 1.0 / current_zoom;
- let viewport_right = -result.bounds.top_left.x / current_zoom + viewport_size;
-
- assert!(cursor_pos.0 <= viewport_right - viewport_size * 0.119);
- }
-
- #[test]
- fn auto_zoom_out_interpolates_from_end_bounds() {
- let segments = vec![test_auto_segment(2.0, 4.0, 2.0)];
- let focus = Coord::<RawDisplayUVSpace>::new(XY::new(0.9, 0.5));
-
- let current = InterpolatedZoom::new_with_easing_and_cursor(
- c(4.0 + ZOOM_DURATION * 0.5, &segments),
- focus,
- Some(focus),
- Some(focus),
- Some(focus),
- |t| t,
- |t| t,
- );
-
- assert_f64_near!(current.bounds.top_left.x, -0.46);
- assert_f64_near!(current.bounds.bottom_right.x, 1.04);
- }
-
- #[test]
- fn auto_zoom_out_boundary_keeps_corrected_end_bounds() {
- let segments = vec![test_auto_segment(2.0, 4.0, 2.0)];
- let focus = Coord::<RawDisplayUVSpace>::new(XY::new(0.9, 0.5));
-
- let at_boundary = InterpolatedZoom::new_with_easing_and_cursor(
- c(4.0, &segments),
- focus,
- Some(focus),
- None,
- None,
- |t| t,
- |t| t,
- );
- let just_after = InterpolatedZoom::new_with_easing_and_cursor(
- c(4.0 + 1e-9, &segments),
- focus,
- Some(focus),
- Some(focus),
- Some(focus),
- |t| t,
- |t| t,
- );
-
- assert!((just_after.bounds.top_left.x - at_boundary.bounds.top_left.x).abs() < 1e-6);
- assert!(
- (just_after.bounds.bottom_right.x - at_boundary.bounds.bottom_right.x).abs() < 1e-6
- );
- }
-
- #[test]
- fn zoom_out_boundary_is_continuous() {
- let segments = vec![test_segment(2.0, 4.0, 2.0, 0.5, 0.5)];
-
- let at_boundary = InterpolatedZoom::new_with_easing_and_cursor(
- c(4.0, &segments),
- Default::default(),
- None,
- None,
- None,
- |t| t,
- |t| t,
- );
-
- let epsilon = 1e-9;
- let just_after = InterpolatedZoom::new_with_easing_and_cursor(
- c(4.0 + epsilon, &segments),
- Default::default(),
- None,
- None,
- None,
- |t| t,
- |t| t,
- );
-
- let dx_tl = (just_after.bounds.top_left.x - at_boundary.bounds.top_left.x).abs();
- let dy_tl = (just_after.bounds.top_left.y - at_boundary.bounds.top_left.y).abs();
- let dx_br = (just_after.bounds.bottom_right.x - at_boundary.bounds.bottom_right.x).abs();
- let dy_br = (just_after.bounds.bottom_right.y - at_boundary.bounds.bottom_right.y).abs();
-
- let max_jump = dx_tl.max(dy_tl).max(dx_br).max(dy_br);
- assert!(
- max_jump < 1e-4,
- "Bounds jumped {max_jump} at segment boundary; expected near-zero"
- );
- }
-
- #[test]
- fn manual_zoom_out_boundary_ignores_cursor_position() {
- let segments = vec![test_segment(2.0, 4.0, 4.0, 0.9, 0.1)];
- let cursor = Coord::<RawDisplayUVSpace>::new(XY::new(0.5, 0.5));
-
- let at_boundary = InterpolatedZoom::new_with_easing_and_cursor(
- c(4.0, &segments),
- Default::default(),
- Some(cursor),
- None,
- None,
- |t| t,
- |t| t,
- );
-
- let just_after = InterpolatedZoom::new_with_easing_and_cursor(
- c(4.0 + 1e-9, &segments),
- Default::default(),
- Some(cursor),
- None,
- None,
- |t| t,
- |t| t,
- );
-
- let dx_tl = (just_after.bounds.top_left.x - at_boundary.bounds.top_left.x).abs();
- let dy_tl = (just_after.bounds.top_left.y - at_boundary.bounds.top_left.y).abs();
- let dx_br = (just_after.bounds.bottom_right.x - at_boundary.bounds.bottom_right.x).abs();
- let dy_br = (just_after.bounds.bottom_right.y - at_boundary.bounds.bottom_right.y).abs();
-
- let max_jump = dx_tl.max(dy_tl).max(dx_br).max(dy_br);
- assert!(
- max_jump < 1e-4,
- "Manual zoom-out jumped {max_jump} toward cursor at segment boundary"
- );
- }
-
- #[test]
- fn zoom_out_early_frames_are_smooth() {
- let segments = vec![test_segment(2.0, 4.0, 2.0, 0.5, 0.5)];
-
- let dt = ZOOM_DURATION * 0.01;
- let mut prev = InterpolatedZoom::new_with_easing_and_cursor(
- c(4.0, &segments),
- Default::default(),
- None,
- None,
- None,
- |t| t,
- |t| t,
- );
-
- for i in 1..=20 {
- let time = 4.0 + dt * i as f64;
- let current = InterpolatedZoom::new_with_easing_and_cursor(
- c(time, &segments),
- Default::default(),
- None,
- None,
- None,
- |t| t,
- |t| t,
- );
-
- let dx = (current.bounds.top_left.x - prev.bounds.top_left.x).abs();
- let dy = (current.bounds.top_left.y - prev.bounds.top_left.y).abs();
- assert!(
- dx < 0.02 && dy < 0.02,
- "Frame jump at step {i} (t={time:.4}): dx={dx:.6} dy={dy:.6}"
- );
-
- prev = current;
- }
+ assert!((zoom.display_amount() - 2.5).abs() < 1e-9);
}
}
diff --git a/crates/rendering/src/zoom_focus_interpolation.rs b/crates/rendering/src/zoom_focus_interpolation.rs
deleted file mode 100644
index c58ccd495..000000000
--- a/crates/rendering/src/zoom_focus_interpolation.rs
+++ /dev/null
@@ -1,662 +0,0 @@
-use cap_project::{ClickSpringConfig, CursorEvents, ScreenMovementSpring, XY, ZoomSegment};
-
-use crate::{
- Coord, RawDisplayUVSpace,
- cursor_interpolation::PrecomputedCursorTimeline,
- spring_mass_damper::{SpringMassDamperSimulation, SpringMassDamperSimulationConfig},
-};
-
-struct ZoomFocusPrecomputeSim {
- sim: SpringMassDamperSimulation,
- last_integrated_ms: f64,
-}
-
-const SAMPLE_INTERVAL_MS: f64 = 8.0;
-const CLUSTER_WIDTH_RATIO: f64 = 0.5;
-const CLUSTER_HEIGHT_RATIO: f64 = 0.7;
-
-#[derive(Clone)]
-struct SmoothedFocusEvent {
- time: f64,
- position: XY<f32>,
-}
-
-struct ClickCluster {
- min_x: f64,
- max_x: f64,
- min_y: f64,
- max_y: f64,
- start_time_ms: f64,
- last_time_ms: f64,
-}
-
-impl ClickCluster {
- fn new(x: f64, y: f64, time_ms: f64) -> Self {
- Self {
- min_x: x,
- max_x: x,
- min_y: y,
- max_y: y,
- start_time_ms: time_ms,
- last_time_ms: time_ms,
- }
- }
-
- fn can_add(&self, x: f64, y: f64, max_w: f64, max_h: f64) -> bool {
- let new_w = self.max_x.max(x) - self.min_x.min(x);
- let new_h = self.max_y.max(y) - self.min_y.min(y);
- new_w <= max_w && new_h <= max_h
- }
-
- fn add(&mut self, x: f64, y: f64, time_ms: f64) {
- self.min_x = self.min_x.min(x);
- self.max_x = self.max_x.max(x);
- self.min_y = self.min_y.min(y);
- self.max_y = self.max_y.max(y);
- self.last_time_ms = time_ms;
- }
-
- fn center(&self) -> (f64, f64) {
- (
- (self.min_x + self.max_x) / 2.0,
- (self.min_y + self.max_y) / 2.0,
- )
- }
-}
-
-fn cursor_position_at(moves: &[cap_project::CursorMoveEvent], time_ms: f64) -> Option<(f64, f64)> {
- if moves.is_empty() {
- return None;
- }
-
- if time_ms <= moves[0].time_ms {
- return Some((moves[0].x, moves[0].y));
- }
-
- if let Some(last) = moves.last()
- && time_ms >= last.time_ms
- {
- return Some((last.x, last.y));
- }
-
- let idx = moves.partition_point(|m| m.time_ms <= time_ms);
- if idx == 0 {
- return Some((moves[0].x, moves[0].y));
- }
-
- let prev = &moves[idx - 1];
- let next = &moves[idx.min(moves.len() - 1)];
- let dt = next.time_ms - prev.time_ms;
-
- if dt > 66.67 {
- return Some((prev.x, prev.y));
- }
-
- let t = if dt > 1e-9 {
- ((time_ms - prev.time_ms) / dt).clamp(0.0, 1.0)
- } else {
- 0.0
- };
-
- Some((
- prev.x + (next.x - prev.x) * t,
- prev.y + (next.y - prev.y) * t,
- ))
-}
-
-fn build_clusters(
- cursor_events: &CursorEvents,
- segment_start_secs: f64,
- segment_end_secs: f64,
- zoom_amount: f64,
-) -> Vec<ClickCluster> {
- let start_ms = segment_start_secs * 1000.0;
- let end_ms = segment_end_secs * 1000.0;
- let cluster_w = CLUSTER_WIDTH_RATIO / zoom_amount;
- let cluster_h = CLUSTER_HEIGHT_RATIO / zoom_amount;
-
- let click_positions: Vec<(f64, f64, f64)> = cursor_events
- .clicks
- .iter()
- .filter(|click| click.down && click.time_ms >= start_ms && click.time_ms <= end_ms)
- .filter_map(|click| {
- cursor_position_at(&cursor_events.moves, click.time_ms)
- .map(|(x, y)| (click.time_ms, x, y))
- })
- .collect();
-
- if !click_positions.is_empty() {
- let mut clusters = Vec::new();
- let (first_time, first_x, first_y) = click_positions[0];
- let mut current = ClickCluster::new(first_x, first_y, first_time);
-
- for &(time_ms, x, y) in &click_positions[1..] {
- if time_ms - current.last_time_ms <= 2_500.0
- && current.can_add(x, y, cluster_w, cluster_h)
- {
- current.add(x, y, time_ms);
- } else {
- clusters.push(current);
- current = ClickCluster::new(x, y, time_ms);
- }
- }
-
- clusters.push(current);
- return clusters;
- }
-
- let events_in_range: Vec<&cap_project::CursorMoveEvent> = cursor_events
- .moves
- .iter()
- .filter(|m| m.time_ms >= start_ms && m.time_ms <= end_ms)
- .collect();
-
- if events_in_range.is_empty() {
- let fallback = cursor_events
- .moves
- .iter()
- .rev()
- .find(|m| m.time_ms <= start_ms)
- .or_else(|| cursor_events.moves.iter().find(|m| m.time_ms >= start_ms));
-
- if let Some(evt) = fallback {
- return vec![ClickCluster::new(evt.x, evt.y, evt.time_ms)];
- }
- return vec![];
- }
-
- let mut clusters = Vec::new();
- let first = events_in_range[0];
- let mut current = ClickCluster::new(first.x, first.y, first.time_ms);
-
- for evt in &events_in_range[1..] {
- if current.can_add(evt.x, evt.y, cluster_w, cluster_h) {
- current.add(evt.x, evt.y, evt.time_ms);
- } else {
- clusters.push(current);
- current = ClickCluster::new(evt.x, evt.y, evt.time_ms);
- }
- }
- clusters.push(current);
-
- clusters
-}
-
-fn cluster_center_at_time(clusters: &[ClickCluster], time_ms: f64) -> Option<(f64, f64)> {
- clusters
- .iter()
- .rev()
- .find(|c| c.start_time_ms <= time_ms)
- .or_else(|| clusters.first())
- .map(|c| c.center())
-}
-
-struct SegmentClusters {
- start_secs: f64,
- end_secs: f64,
- zoom_amount: f64,
- clusters: Vec<ClickCluster>,
-}
-
-pub struct ZoomFocusInterpolator {
- events: Option<Vec<SmoothedFocusEvent>>,
- precompute_sim: Option<ZoomFocusPrecomputeSim>,
- cursor_events: std::sync::Arc<CursorEvents>,
- precomputed_cursor: Option<std::sync::Arc<PrecomputedCursorTimeline>>,
- _cursor_smoothing: Option<SpringMassDamperSimulationConfig>,
- _click_spring: ClickSpringConfig,
- screen_spring: ScreenMovementSpring,
- duration_secs: f64,
- segment_clusters: Vec<SegmentClusters>,
-}
-
-impl ZoomFocusInterpolator {
- pub fn new(
- cursor_events: &CursorEvents,
- cursor_smoothing: Option<SpringMassDamperSimulationConfig>,
- click_spring: ClickSpringConfig,
- screen_spring: ScreenMovementSpring,
- duration_secs: f64,
- zoom_segments: &[ZoomSegment],
- ) -> Self {
- Self::new_with_precomputed_cursor(
- cursor_events,
- cursor_smoothing,
- click_spring,
- screen_spring,
- duration_secs,
- zoom_segments,
- None,
- )
- }
-
- pub fn new_with_precomputed_cursor(
- cursor_events: &CursorEvents,
- cursor_smoothing: Option<SpringMassDamperSimulationConfig>,
- click_spring: ClickSpringConfig,
- screen_spring: ScreenMovementSpring,
- duration_secs: f64,
- zoom_segments: &[ZoomSegment],
- precomputed_cursor: Option<std::sync::Arc<PrecomputedCursorTimeline>>,
- ) -> Self {
- let segment_clusters = Self::build_segment_clusters(cursor_events, zoom_segments);
- let precomputed_cursor = if segment_clusters.is_empty() {
- precomputed_cursor
- } else {
- precomputed_cursor.or_else(|| {
- cursor_smoothing.map(|smoothing| {
- std::sync::Arc::new(PrecomputedCursorTimeline::new(
- cursor_events,
- Some(smoothing),
- Some(click_spring),
- ))
- })
- })
- };
- Self {
- events: None,
- precompute_sim: None,
- cursor_events: std::sync::Arc::new(cursor_events.clone()),
- precomputed_cursor,
- _cursor_smoothing: cursor_smoothing,
- _click_spring: click_spring,
- screen_spring,
- duration_secs,
- segment_clusters,
- }
- }
-
- pub fn new_arc(
- cursor_events: std::sync::Arc<CursorEvents>,
- cursor_smoothing: Option<SpringMassDamperSimulationConfig>,
- click_spring: ClickSpringConfig,
- screen_spring: ScreenMovementSpring,
- duration_secs: f64,
- zoom_segments: &[ZoomSegment],
- ) -> Self {
- Self::new_arc_with_precomputed_cursor(
- cursor_events,
- cursor_smoothing,
- click_spring,
- screen_spring,
- duration_secs,
- zoom_segments,
- None,
- )
- }
-
- pub fn new_arc_with_precomputed_cursor(
- cursor_events: std::sync::Arc<CursorEvents>,
- cursor_smoothing: Option<SpringMassDamperSimulationConfig>,
- click_spring: ClickSpringConfig,
- screen_spring: ScreenMovementSpring,
- duration_secs: f64,
- zoom_segments: &[ZoomSegment],
- precomputed_cursor: Option<std::sync::Arc<PrecomputedCursorTimeline>>,
- ) -> Self {
- let segment_clusters = Self::build_segment_clusters(cursor_events.as_ref(), zoom_segments);
- let precomputed_cursor = if segment_clusters.is_empty() {
- precomputed_cursor
- } else {
- precomputed_cursor.or_else(|| {
- cursor_smoothing.map(|smoothing| {
- std::sync::Arc::new(PrecomputedCursorTimeline::new(
- cursor_events.as_ref(),
- Some(smoothing),
- Some(click_spring),
- ))
- })
- })
- };
- Self {
- events: None,
- precompute_sim: None,
- cursor_events,
- precomputed_cursor,
- _cursor_smoothing: cursor_smoothing,
- _click_spring: click_spring,
- screen_spring,
- duration_secs,
- segment_clusters,
- }
- }
-
- fn build_segment_clusters(
- cursor_events: &CursorEvents,
- zoom_segments: &[ZoomSegment],
- ) -> Vec<SegmentClusters> {
- zoom_segments
- .iter()
- .filter(|s| matches!(s.mode, cap_project::ZoomMode::Auto))
- .map(|s| SegmentClusters {
- start_secs: s.start,
- end_secs: s.end,
- zoom_amount: s.amount,
- clusters: build_clusters(cursor_events, s.start, s.end, s.amount),
- })
- .collect()
- }
-
- fn zoom_amount_at(&self, time_secs: f64) -> f64 {
- self.segment_clusters
- .iter()
- .find(|sc| time_secs >= sc.start_secs && time_secs <= sc.end_secs)
- .map(|sc| sc.zoom_amount)
- .unwrap_or(1.0)
- }
-
- fn cluster_focus_at(&self, time_secs: f64) -> Option<(f64, f64)> {
- let time_ms = time_secs * 1000.0;
- self.segment_clusters
- .iter()
- .find(|sc| time_secs >= sc.start_secs && time_secs <= sc.end_secs)
- .and_then(|sc| cluster_center_at_time(&sc.clusters, time_ms))
- }
-
- fn focus_target_at(&self, time_secs: f32) -> XY<f32> {
- if let Some(pos) = self.smoothed_cursor_position_at(time_secs) {
- return pos;
- }
-
- if let Some(pos) = Self::raw_cursor_position_at(&self.cursor_events, time_secs) {
- return pos;
- }
-
- if let Some((cx, cy)) = self.cluster_focus_at(time_secs as f64) {
- return XY::new(cx.clamp(0.0, 1.0) as f32, cy.clamp(0.0, 1.0) as f32);
- }
-
- XY::new(0.5, 0.5)
- }
-
- fn smoothed_cursor_position_at(&self, time_secs: f32) -> Option<XY<f32>> {
- self.precomputed_cursor
- .as_ref()
- .and_then(|cursor| cursor.interpolate(time_secs))
- .and_then(|cursor| {
- let x = cursor.position.coord.x;
- let y = cursor.position.coord.y;
- (x.is_finite() && y.is_finite())
- .then(|| XY::new(x.clamp(0.0, 1.0) as f32, y.clamp(0.0, 1.0) as f32))
- })
- }
-
- fn raw_cursor_position_at(cursor_events: &CursorEvents, time_secs: f32) -> Option<XY<f32>> {
- let moves = &cursor_events.moves;
- if moves.is_empty() {
- return None;
- }
-
- let time_ms = time_secs as f64 * 1000.0;
-
- if time_ms <= moves[0].time_ms {
- return Some(XY::new(
- moves[0].x.clamp(0.0, 1.0) as f32,
- moves[0].y.clamp(0.0, 1.0) as f32,
- ));
- }
-
- if let Some(last) = moves.last()
- && time_ms >= last.time_ms
- {
- return Some(XY::new(
- last.x.clamp(0.0, 1.0) as f32,
- last.y.clamp(0.0, 1.0) as f32,
- ));
- }
-
- let idx = moves.partition_point(|m| m.time_ms <= time_ms);
- if idx == 0 {
- return Some(XY::new(
- moves[0].x.clamp(0.0, 1.0) as f32,
- moves[0].y.clamp(0.0, 1.0) as f32,
- ));
- }
-
- let prev = &moves[idx - 1];
- let next = &moves[idx.min(moves.len() - 1)];
- let dt = next.time_ms - prev.time_ms;
-
- const IDLE_GAP_MS: f64 = 66.67;
- if dt > IDLE_GAP_MS {
- return Some(XY::new(
- prev.x.clamp(0.0, 1.0) as f32,
- prev.y.clamp(0.0, 1.0) as f32,
- ));
- }
-
- let t = if dt > 1e-9 {
- ((time_ms - prev.time_ms) / dt) as f32
- } else {
- 0.0
- };
- Some(XY::new(
- (prev.x as f32 + (next.x as f32 - prev.x as f32) * t).clamp(0.0, 1.0),
- (prev.y as f32 + (next.y as f32 - prev.y as f32) * t).clamp(0.0, 1.0),
- ))
- }
-
- pub fn ensure_precomputed_until(&mut self, time_secs: f32) {
- let duration_ms = self.duration_secs * 1000.0;
- let need_ms = (f64::from(time_secs) * 1000.0).clamp(0.0, duration_ms);
-
- if self.cursor_events.moves.is_empty() {
- if self.events.is_none() {
- self.events = Some(vec![]);
- }
- return;
- }
-
- if let Some(ref events) = self.events
- && let Some(last) = events.last()
- && last.time + f64::EPSILON >= need_ms
- {
- return;
- }
-
- if self.events.is_none() {
- let spring_config = SpringMassDamperSimulationConfig {
- tension: self.screen_spring.stiffness,
- mass: self.screen_spring.mass,
- friction: self.screen_spring.damping,
- };
- let mut sim = SpringMassDamperSimulation::new(spring_config);
- let initial_pos = self.focus_target_at(0.0);
- sim.set_position(initial_pos);
- sim.set_velocity(XY::new(0.0, 0.0));
- sim.set_target_position(initial_pos);
- self.events = Some(vec![SmoothedFocusEvent {
- time: 0.0,
- position: initial_pos,
- }]);
- self.precompute_sim = Some(ZoomFocusPrecomputeSim {
- sim,
- last_integrated_ms: 0.0,
- });
- }
-
- loop {
- let (next_ms, step_ms) = {
- let Some(ps) = self.precompute_sim.as_ref() else {
- break;
- };
- if ps.last_integrated_ms + f64::EPSILON >= need_ms {
- break;
- }
- let next_ms = (ps.last_integrated_ms + SAMPLE_INTERVAL_MS).min(duration_ms);
- if next_ms <= ps.last_integrated_ms + f64::EPSILON {
- break;
- }
- let step_ms = next_ms - ps.last_integrated_ms;
- (next_ms, step_ms)
- };
- let time_secs = (next_ms / 1000.0) as f32;
- let target = self.focus_target_at(time_secs);
- let zoom_amount = self.zoom_amount_at(next_ms / 1000.0);
- let Some(ps) = self.precompute_sim.as_mut() else {
- break;
- };
- let Some(events) = self.events.as_mut() else {
- break;
- };
- ps.sim.set_target_position(target);
- ps.sim.run(step_ms as f32);
-
- let viewport_half = (0.5 / zoom_amount) as f32;
- let max_lag = (viewport_half * 0.65).clamp(0.12, 0.28);
- let dx = ps.sim.position.x - target.x;
- let dy = ps.sim.position.y - target.y;
- let dist_sq = dx * dx + dy * dy;
- if dist_sq > max_lag * max_lag {
- let dist = dist_sq.sqrt();
- let scale = max_lag / dist;
- ps.sim
- .set_position(XY::new(target.x + dx * scale, target.y + dy * scale));
- ps.sim.set_velocity(XY::new(
- ps.sim.velocity.x * scale,
- ps.sim.velocity.y * scale,
- ));
- }
-
- ps.last_integrated_ms = next_ms;
- events.push(SmoothedFocusEvent {
- time: next_ms,
- position: XY::new(
- ps.sim.position.x.clamp(0.0, 1.0),
- ps.sim.position.y.clamp(0.0, 1.0),
- ),
- });
- }
-
- if let Some(ps) = self.precompute_sim.as_ref()
- && ps.last_integrated_ms + f64::EPSILON >= duration_ms
- {
- self.precompute_sim = None;
- }
- }
-
- pub fn precompute(&mut self) {
- self.ensure_precomputed_until(self.duration_secs as f32);
- }
-
- pub fn interpolate(&self, time_secs: f32) -> Coord<RawDisplayUVSpace> {
- let time_ms = (time_secs * 1000.0) as f64;
-
- if self.cursor_events.moves.is_empty() {
- return Coord::new(XY::new(0.5, 0.5));
- }
-
- if let Some(ref events) = self.events {
- self.interpolate_from_events(events, time_ms)
- } else {
- self.interpolate_direct(time_secs)
- }
- }
-
- fn interpolate_direct(&self, time_secs: f32) -> Coord<RawDisplayUVSpace> {
- let target = self.focus_target_at(time_secs);
- Coord::new(XY::new(target.x as f64, target.y as f64))
- }
-
- fn interpolate_from_events(
- &self,
- events: &[SmoothedFocusEvent],
- time_ms: f64,
- ) -> Coord<RawDisplayUVSpace> {
- if events.is_empty() {
- return Coord::new(XY::new(0.5, 0.5));
- }
-
- if time_ms <= events[0].time {
- let pos = events[0].position;
- return Coord::new(XY::new(pos.x as f64, pos.y as f64));
- }
-
- if let Some(last) = events.last()
- && time_ms >= last.time
- {
- return Coord::new(XY::new(last.position.x as f64, last.position.y as f64));
- }
-
- let idx = events
- .binary_search_by(|e| {
- e.time
- .partial_cmp(&time_ms)
- .unwrap_or(std::cmp::Ordering::Less)
- })
- .unwrap_or_else(|i| i.saturating_sub(1));
-
- let curr = &events[idx];
- let next = events.get(idx + 1).unwrap_or(curr);
-
- if (next.time - curr.time).abs() < f64::EPSILON {
- return Coord::new(XY::new(curr.position.x as f64, curr.position.y as f64));
- }
-
- let t = ((time_ms - curr.time) / (next.time - curr.time)).clamp(0.0, 1.0) as f32;
-
- let lerped = XY::new(
- curr.position.x + (next.position.x - curr.position.x) * t,
- curr.position.y + (next.position.y - curr.position.y) * t,
- );
-
- Coord::new(XY::new(lerped.x as f64, lerped.y as f64))
- }
-}
-
-#[cfg(test)]
-mod tests {
- use cap_project::{ClickSpringConfig, CursorMoveEvent, GlideDirection, ZoomMode};
-
- use super::*;
-
- fn move_event(time_ms: f64, x: f64, y: f64) -> CursorMoveEvent {
- CursorMoveEvent {
- active_modifiers: vec![],
- cursor_id: "default".to_string(),
- time_ms,
- x,
- y,
- }
- }
-
- #[test]
- fn focus_uses_smoothed_cursor_timeline() {
- let cursor = CursorEvents {
- moves: vec![
- move_event(0.0, 0.1, 0.5),
- move_event(100.0, 0.9, 0.5),
- move_event(200.0, 0.9, 0.5),
- ],
- clicks: vec![],
- };
- let smoothing = SpringMassDamperSimulationConfig {
- tension: 470.0,
- mass: 3.0,
- friction: 70.0,
- };
- let zoom_segments = vec![ZoomSegment {
- start: 0.0,
- end: 0.3,
- amount: 2.0,
- mode: ZoomMode::Auto,
- glide_direction: GlideDirection::None,
- glide_speed: 0.5,
- instant_animation: false,
- edge_snap_ratio: 0.25,
- }];
- let interpolator = ZoomFocusInterpolator::new(
- &cursor,
- Some(smoothing),
- ClickSpringConfig::default(),
- ScreenMovementSpring::default(),
- 0.3,
- &zoom_segments,
- );
-
- let target = interpolator.focus_target_at(0.116);
-
- assert!(target.x > 0.1);
- assert!(target.x < 0.9);
- }
-}