Skip to content

Commit

Permalink
Improve API for scaling orthographic cameras (bevyengine#15969)
Browse files Browse the repository at this point in the history
# Objective

Fixes bevyengine#15791.

As raised in bevyengine#11022, scaling orthographic cameras is confusing! In Bevy
0.14, there were multiple completely redundant ways to do this, and no
clear guidance on which to use.

As a result, bevyengine#15075 removed the `scale` field from
`OrthographicProjection` completely, solving the redundancy issue.

However, this resulted in an unintuitive API and a painful migration, as
discussed in bevyengine#15791. Users simply want to change a single parameter to
zoom, rather than deal with the irrelevant details of how the camera is
being scaled.

## Solution

This PR reverts bevyengine#15075, and takes an alternate, more nuanced approach to
the redundancy problem. `ScalingMode::WindowSize` was by far the biggest
offender. This was the default variant, and stored a float that was
*fully* redundant to setting `scale`.

All of the other variants contained meaningful semantic information and
had an intuitive scale. I could have made these unitless, storing an
aspect ratio, but this would have been a worse API and resulted in a
pointlessly painful migration.

In the course of this work I've also:

- improved the documentation to explain that you should just set `scale`
to zoom cameras
- swapped to named fields for all of the variants in `ScalingMode` for
more clarity about the parameter meanings
- substantially improved the `projection_zoom` example
- removed the footgunny `Mul` and `Div` impls for `ScalingMode`,
especially since these no longer have the intended effect on
`ScalingMode::WindowSize`.
- removed a rounding step because this is now redundant 🎉 

## Testing

I've tested these changes as part of my work in the `projection_zoom`
example, and things seem to work fine.

## Migration Guide

`ScalingMode` has been refactored for clarity, especially on how to zoom
orthographic cameras and their projections:

- `ScalingMode::WindowSize` no longer stores a float, and acts as if its
value was 1. Divide your camera's scale by any previous value to achieve
identical results.
- `ScalingMode::FixedVertical` and `FixedHorizontal` now use named
fields.

---------

Co-authored-by: MiniaczQ <[email protected]>
  • Loading branch information
alice-i-cecile and MiniaczQ authored Oct 17, 2024
1 parent 90b5ed6 commit 2bd3282
Show file tree
Hide file tree
Showing 9 changed files with 139 additions and 145 deletions.
4 changes: 3 additions & 1 deletion crates/bevy_gltf/src/loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1398,7 +1398,9 @@ fn load_node(
let orthographic_projection = OrthographicProjection {
near: orthographic.znear(),
far: orthographic.zfar(),
scaling_mode: ScalingMode::FixedHorizontal(xmag),
scaling_mode: ScalingMode::FixedHorizontal {
viewport_width: xmag,
},
..OrthographicProjection::default_3d()
};

Expand Down
143 changes: 57 additions & 86 deletions crates/bevy_render/src/camera/projection.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
use core::{
marker::PhantomData,
ops::{Div, DivAssign, Mul, MulAssign},
};
use core::marker::PhantomData;

use crate::{primitives::Frustum, view::VisibilitySystems};
use bevy_app::{App, Plugin, PostStartup, PostUpdate};
Expand Down Expand Up @@ -269,92 +266,56 @@ impl Default for PerspectiveProjection {

/// Scaling mode for [`OrthographicProjection`].
///
/// The effect of these scaling modes are combined with the [`OrthographicProjection::scale`] property.
///
/// For example, if the scaling mode is `ScalingMode::Fixed { width: 100.0, height: 300 }` and the scale is `2.0`,
/// the projection will be 200 world units wide and 600 world units tall.
///
/// # Examples
///
/// Configure the orthographic projection to two world units per window height:
///
/// ```
/// # use bevy_render::camera::{OrthographicProjection, Projection, ScalingMode};
/// let projection = Projection::Orthographic(OrthographicProjection {
/// scaling_mode: ScalingMode::FixedVertical(2.0),
/// scaling_mode: ScalingMode::FixedVertical { viewport_height: 2.0 },
/// ..OrthographicProjection::default_2d()
/// });
/// ```
#[derive(Debug, Clone, Copy, Reflect, Serialize, Deserialize)]
#[derive(Default, Debug, Clone, Copy, Reflect, Serialize, Deserialize)]
#[reflect(Serialize, Deserialize)]
pub enum ScalingMode {
/// Match the viewport size.
///
/// With a scale of 1, lengths in world units will map 1:1 with the number of pixels used to render it.
/// For example, if we have a 64x64 sprite with a [`Transform::scale`](bevy_transform::prelude::Transform) of 1.0,
/// no custom size and no inherited scale, the sprite will be 64 world units wide and 64 world units tall.
/// When rendered with [`OrthographicProjection::scaling_mode`] set to `WindowSize` when the window scale factor is 1
/// the sprite will be rendered at 64 pixels wide and 64 pixels tall.
///
/// Changing any of these properties will multiplicatively affect the final size.
#[default]
WindowSize,
/// Manually specify the projection's size, ignoring window resizing. The image will stretch.
/// Arguments are in world units.
///
/// Arguments describe the area of the world that is shown (in world units).
Fixed { width: f32, height: f32 },
/// Match the viewport size.
/// The argument is the number of pixels that equals one world unit.
WindowSize(f32),
/// Keeping the aspect ratio while the axes can't be smaller than given minimum.
///
/// Arguments are in world units.
AutoMin { min_width: f32, min_height: f32 },
/// Keeping the aspect ratio while the axes can't be bigger than given maximum.
///
/// Arguments are in world units.
AutoMax { max_width: f32, max_height: f32 },
/// Keep the projection's height constant; width will be adjusted to match aspect ratio.
///
/// The argument is the desired height of the projection in world units.
FixedVertical(f32),
FixedVertical { viewport_height: f32 },
/// Keep the projection's width constant; height will be adjusted to match aspect ratio.
///
/// The argument is the desired width of the projection in world units.
FixedHorizontal(f32),
}

impl Mul<f32> for ScalingMode {
type Output = ScalingMode;

/// Scale the `ScalingMode`. For example, multiplying by 2 makes the viewport twice as large.
fn mul(self, rhs: f32) -> ScalingMode {
match self {
ScalingMode::Fixed { width, height } => ScalingMode::Fixed {
width: width * rhs,
height: height * rhs,
},
ScalingMode::WindowSize(pixels_per_world_unit) => {
ScalingMode::WindowSize(pixels_per_world_unit / rhs)
}
ScalingMode::AutoMin {
min_width,
min_height,
} => ScalingMode::AutoMin {
min_width: min_width * rhs,
min_height: min_height * rhs,
},
ScalingMode::AutoMax {
max_width,
max_height,
} => ScalingMode::AutoMax {
max_width: max_width * rhs,
max_height: max_height * rhs,
},
ScalingMode::FixedVertical(size) => ScalingMode::FixedVertical(size * rhs),
ScalingMode::FixedHorizontal(size) => ScalingMode::FixedHorizontal(size * rhs),
}
}
}

impl MulAssign<f32> for ScalingMode {
fn mul_assign(&mut self, rhs: f32) {
*self = *self * rhs;
}
}

impl Div<f32> for ScalingMode {
type Output = ScalingMode;

/// Scale the `ScalingMode`. For example, dividing by 2 makes the viewport half as large.
fn div(self, rhs: f32) -> ScalingMode {
self * (1.0 / rhs)
}
}

impl DivAssign<f32> for ScalingMode {
fn div_assign(&mut self, rhs: f32) {
*self = *self / rhs;
}
FixedHorizontal { viewport_width: f32 },
}

/// Project a 3D space onto a 2D surface using parallel lines, i.e., unlike [`PerspectiveProjection`],
Expand All @@ -373,7 +334,8 @@ impl DivAssign<f32> for ScalingMode {
/// ```
/// # use bevy_render::camera::{OrthographicProjection, Projection, ScalingMode};
/// let projection = Projection::Orthographic(OrthographicProjection {
/// scaling_mode: ScalingMode::WindowSize(100.0),
/// scaling_mode: ScalingMode::WindowSize,
/// scale: 0.01,
/// ..OrthographicProjection::default_2d()
/// });
/// ```
Expand Down Expand Up @@ -407,8 +369,24 @@ pub struct OrthographicProjection {
pub viewport_origin: Vec2,
/// How the projection will scale to the viewport.
///
/// Defaults to `ScalingMode::WindowSize(1.0)`
/// Defaults to [`ScalingMode::WindowSize`],
/// and works in concert with [`OrthographicProjection::scale`] to determine the final effect.
///
/// For simplicity, zooming should be done by changing [`OrthographicProjection::scale`],
/// rather than changing the parameters of the scaling mode.
pub scaling_mode: ScalingMode,
/// Scales the projection.
///
/// As scale increases, the apparent size of objects decreases, and vice versa.
///
/// Note: scaling can be set by [`scaling_mode`](Self::scaling_mode) as well.
/// This parameter scales on top of that.
///
/// This property is particularly useful in implementing zoom functionality.
///
/// Defaults to `1.0`, which under standard settings corresponds to a 1:1 mapping of world units to rendered pixels.
/// See [`ScalingMode::WindowSize`] for more information.
pub scale: f32,
/// The area that the projection covers relative to `viewport_origin`.
///
/// Bevy's [`camera_system`](crate::camera::camera_system) automatically
Expand Down Expand Up @@ -478,7 +456,7 @@ impl CameraProjection for OrthographicProjection {

fn update(&mut self, width: f32, height: f32) {
let (projection_width, projection_height) = match self.scaling_mode {
ScalingMode::WindowSize(pixel_scale) => (width / pixel_scale, height / pixel_scale),
ScalingMode::WindowSize => (width, height),
ScalingMode::AutoMin {
min_width,
min_height,
Expand All @@ -503,31 +481,23 @@ impl CameraProjection for OrthographicProjection {
(max_width, height * max_width / width)
}
}
ScalingMode::FixedVertical(viewport_height) => {
ScalingMode::FixedVertical { viewport_height } => {
(width * viewport_height / height, viewport_height)
}
ScalingMode::FixedHorizontal(viewport_width) => {
ScalingMode::FixedHorizontal { viewport_width } => {
(viewport_width, height * viewport_width / width)
}
ScalingMode::Fixed { width, height } => (width, height),
};

let mut origin_x = projection_width * self.viewport_origin.x;
let mut origin_y = projection_height * self.viewport_origin.y;

// If projection is based on window pixels,
// ensure we don't end up with fractional pixels!
if let ScalingMode::WindowSize(pixel_scale) = self.scaling_mode {
// round to nearest multiple of `pixel_scale`
origin_x = (origin_x * pixel_scale).round() / pixel_scale;
origin_y = (origin_y * pixel_scale).round() / pixel_scale;
}
let origin_x = projection_width * self.viewport_origin.x;
let origin_y = projection_height * self.viewport_origin.y;

self.area = Rect::new(
-origin_x,
-origin_y,
projection_width - origin_x,
projection_height - origin_y,
self.scale * -origin_x,
self.scale * -origin_y,
self.scale * (projection_width - origin_x),
self.scale * (projection_height - origin_y),
);
}

Expand Down Expand Up @@ -575,10 +545,11 @@ impl OrthographicProjection {
/// objects that are behind it.
pub fn default_3d() -> Self {
OrthographicProjection {
scale: 1.0,
near: 0.0,
far: 1000.0,
viewport_origin: Vec2::new(0.5, 0.5),
scaling_mode: ScalingMode::WindowSize(1.0),
scaling_mode: ScalingMode::WindowSize,
area: Rect::new(-1.0, -1.0, 1.0, 1.0),
}
}
Expand Down
4 changes: 2 additions & 2 deletions examples/2d/pixel_grid_snap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
use bevy::{
prelude::*,
render::{
camera::{RenderTarget, ScalingMode},
camera::RenderTarget,
render_resource::{
Extent3d, TextureDescriptor, TextureDimension, TextureFormat, TextureUsages,
},
Expand Down Expand Up @@ -149,6 +149,6 @@ fn fit_canvas(
for event in resize_events.read() {
let h_scale = event.width / RES_WIDTH as f32;
let v_scale = event.height / RES_HEIGHT as f32;
projection.scaling_mode = ScalingMode::WindowSize(h_scale.min(v_scale).round());
projection.scale = 1. / h_scale.min(v_scale).round();
}
}
16 changes: 12 additions & 4 deletions examples/3d/camera_sub_view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,9 @@ fn setup(
commands.spawn((
Camera3d::default(),
Projection::from(OrthographicProjection {
scaling_mode: ScalingMode::FixedVertical(6.0),
scaling_mode: ScalingMode::FixedVertical {
viewport_height: 6.0,
},
..OrthographicProjection::default_3d()
}),
Camera {
Expand All @@ -161,7 +163,9 @@ fn setup(
commands.spawn((
Camera3d::default(),
Projection::from(OrthographicProjection {
scaling_mode: ScalingMode::FixedVertical(6.0),
scaling_mode: ScalingMode::FixedVertical {
viewport_height: 6.0,
},
..OrthographicProjection::default_3d()
}),
Camera {
Expand All @@ -187,7 +191,9 @@ fn setup(
commands.spawn((
Camera3d::default(),
Projection::from(OrthographicProjection {
scaling_mode: ScalingMode::FixedVertical(6.0),
scaling_mode: ScalingMode::FixedVertical {
viewport_height: 6.0,
},
..OrthographicProjection::default_3d()
}),
Camera {
Expand All @@ -214,7 +220,9 @@ fn setup(
commands.spawn((
Camera3d::default(),
Projection::from(OrthographicProjection {
scaling_mode: ScalingMode::FixedVertical(6.0),
scaling_mode: ScalingMode::FixedVertical {
viewport_height: 6.0,
},
..OrthographicProjection::default_3d()
}),
Camera {
Expand Down
6 changes: 4 additions & 2 deletions examples/3d/orthographic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,10 @@ fn setup(
commands.spawn((
Camera3d::default(),
Projection::from(OrthographicProjection {
// 6 world units per window height.
scaling_mode: ScalingMode::FixedVertical(6.0),
// 6 world units per pixel of window height.
scaling_mode: ScalingMode::FixedVertical {
viewport_height: 6.0,
},
..OrthographicProjection::default_3d()
}),
Transform::from_xyz(5.0, 5.0, 5.0).looking_at(Vec3::ZERO, Vec3::Y),
Expand Down
6 changes: 4 additions & 2 deletions examples/3d/pbr.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! This example shows how to configure Physically Based Rendering (PBR) parameters.
use bevy::{prelude::*, render::camera::ScalingMode};
use bevy::prelude::*;
use bevy::render::camera::ScalingMode;

fn main() {
App::new()
Expand Down Expand Up @@ -110,7 +111,8 @@ fn setup(
Camera3d::default(),
Transform::from_xyz(0.0, 0.0, 8.0).looking_at(Vec3::default(), Vec3::Y),
Projection::from(OrthographicProjection {
scaling_mode: ScalingMode::WindowSize(100.0),
scale: 100.,
scaling_mode: ScalingMode::WindowSize,
..OrthographicProjection::default_3d()
}),
EnvironmentMapLight {
Expand Down
Loading

0 comments on commit 2bd3282

Please sign in to comment.