phosph-rs 0.4.0

Simple, pretty, multiplatform molecular viewer for chemists.
Documentation
use bevy::{
    input::mouse::{AccumulatedMouseMotion, AccumulatedMouseScroll},
    prelude::*,
};
use std::time::{Duration, Instant};

use super::lights::CameraFollowLight;

/// A plugin that implements an orbiting camera.
/// The camera rotates seamlessly about the origin and can be zoomed in/out.
pub struct OrbitCameraPlugin;

/// Resource to track double-click timing for camera reset
#[derive(Resource)]
struct DoubleClickTracker {
    last_right_click: Option<Instant>,
    double_click_threshold: Duration,
}

impl Default for DoubleClickTracker {
    fn default() -> Self {
        Self {
            last_right_click: None,
            double_click_threshold: Duration::from_millis(500),
        }
    }
}

impl Plugin for OrbitCameraPlugin {
    fn build(&self, app: &mut App) {
        app.init_resource::<DoubleClickTracker>();
        app.add_systems(Startup, spawn_orbit_camera);
        app.add_systems(
            Update,
            (
                reset_camera_on_double_right_click,
                rotate_camera,
                move_camera_origin,
                transform_camera,
                update_camera_follow_lights,
            )
                .chain(),
        );
    }
}

/// Component that defines the behaviour of an orbiting camera.
#[derive(Component)]
pub struct OrbitCamera {
    /// Current rotation of the camera
    rotation: Quat,
    /// Axis for horizontal rotation
    yaw_axis: Vec3,
    /// Axis for vertical rotation
    pitch_axis: Vec3,
    /// Mouse sensitivity for rotation
    sensitivity: f32,
    /// Current distance from the origin
    distance: f32,
    /// Minimum distance from the origin
    min_distance: f32,
    /// Maximum distance from the origin
    max_distance: f32,
    /// Mouse wheel sensitivity for zooming
    zoom_sensitivity: f32,
    origin: Vec3,
    /// Initial state for reset
    initial_rotation: Quat,
    initial_distance: f32,
    initial_origin: Vec3,
}

impl Default for OrbitCamera {
    fn default() -> Self {
        Self {
            rotation: Quat::IDENTITY,
            yaw_axis: Vec3::Y,
            pitch_axis: Vec3::X,
            sensitivity: 0.008,
            distance: 25.0,
            min_distance: 5.0,
            max_distance: 50.0,
            zoom_sensitivity: 0.01,
            origin: Vec3::ZERO,
            initial_rotation: Quat::IDENTITY,
            initial_distance: 25.0,
            initial_origin: Vec3::ZERO,
        }
    }
}

/// Spawns the orbit camera entity with default settings.
fn spawn_orbit_camera(mut commands: Commands) {
    commands.spawn((Camera3d::default(), OrbitCamera::default()));
}

/// System that resets the camera to its initial state on double right-click
fn reset_camera_on_double_right_click(
    mouse_button_input: Res<ButtonInput<MouseButton>>,
    mut tracker: ResMut<DoubleClickTracker>,
    mut query: Query<&mut OrbitCamera>,
) {
    if mouse_button_input.just_pressed(MouseButton::Right) {
        let now = Instant::now();

        if let Some(last_click) = tracker.last_right_click {
            // Check if this is a double-click
            if now.duration_since(last_click) <= tracker.double_click_threshold {
                // Reset the camera to initial state
                for mut camera in query.iter_mut() {
                    // camera.rotation = camera.initial_rotation;
                    // camera.yaw_axis = Vec3::Y;
                    // camera.pitch_axis = Vec3::X;
                    camera.distance = camera.initial_distance;
                    camera.origin = camera.initial_origin;
                }

                // Clear the tracker to prevent triple-click triggering another reset
                tracker.last_right_click = None;
                return;
            }
        }

        // Record this click
        tracker.last_right_click = Some(now);
    }
}

/// System that handles camera rotation based on mouse input
///
/// The camera rotates when the left mouse button is pressed and the mouse is moved.
fn rotate_camera(
    mouse_motion: Res<AccumulatedMouseMotion>,
    mouse_button_input: Res<ButtonInput<MouseButton>>,
    mut query: Query<&mut OrbitCamera>,
) {
    if !mouse_button_input.pressed(MouseButton::Left) {
        return;
    }

    for mut camera in query.iter_mut() {
        // Calculate the mouse movement
        let delta = -mouse_motion.delta * camera.sensitivity;

        // Compute yaw and pitch rotations
        let yaw = Quat::from_axis_angle(camera.yaw_axis, delta.x);
        let pitch = Quat::from_axis_angle(camera.pitch_axis, delta.y);

        // Update cameras yaw and pitch axis
        camera.yaw_axis = yaw * camera.yaw_axis;
        camera.pitch_axis = pitch * camera.pitch_axis;

        // Apply rotations
        camera.rotation = camera.rotation * yaw * pitch;
    }
}

fn transform_camera(
    mut query: Query<(&mut OrbitCamera, &mut Transform)>,
    mouse_wheel: Res<AccumulatedMouseScroll>,
) {
    for (mut camera, mut transform) in query.iter_mut() {
        // Calculate zoom distance
        let zoom = -mouse_wheel.delta.y * camera.zoom_sensitivity;

        // Update camera distance
        camera.distance = camera.distance + zoom;
        camera.distance = camera
            .distance
            .clamp(camera.min_distance, camera.max_distance);

        // Calculate the camera position based on distance and rotation
        let position = camera.rotation * Vec3::Z * camera.distance + camera.origin;

        // Update the transform
        transform.translation = position;
        // Make the camera look at the center (0, 0, 0)
        transform.look_at(camera.origin, camera.rotation * Vec3::Y);
    }
}

fn move_camera_origin(
    mouse_motion: Res<AccumulatedMouseMotion>,
    mouse_button_input: Res<ButtonInput<MouseButton>>,
    mut query: Query<(&mut OrbitCamera, &Transform)>,
) {
    if !mouse_button_input.pressed(MouseButton::Right) {
        return;
    }

    for (mut camera, transform) in query.iter_mut() {
        // Get the camera's right and up vectors
        let right = transform.right();
        let up = transform.up();

        // Scale the movement based on distance (further = faster movement)
        let movement_scale = camera.distance * 0.001;

        // Calculate the movement in world space
        let delta = mouse_motion.delta;
        let movement = -right * delta.x * movement_scale + up * delta.y * movement_scale;

        // Update the origin
        camera.origin += movement;
    }
}

/// System that updates lights to follow the camera position
fn update_camera_follow_lights(
    camera_query: Query<&OrbitCamera>,
    mut light_query: Query<(&CameraFollowLight, &mut Transform)>,
) {
    let Ok(camera) = camera_query.get_single() else {
        return;
    };

    for (follow_light, mut transform) in light_query.iter_mut() {
        // Calculate light position relative to camera rotation
        let light_position = camera.rotation * follow_light.offset + camera.origin;

        // Update the light transform
        transform.translation = light_position;
        transform.look_at(camera.origin, camera.rotation * Vec3::Y);
    }
}