Skip to main content

pixel_grid_snap/
pixel_grid_snap.rs

1//! Shows how to create graphics that snap to the pixel grid by rendering to a texture in 2D
2
3use bevy::{
4    camera::visibility::RenderLayers, camera::RenderTarget, color::palettes::css::GRAY, prelude::*,
5    render::render_resource::TextureFormat, window::WindowResized,
6};
7
8/// In-game resolution width.
9const RES_WIDTH: u32 = 160;
10
11/// In-game resolution height.
12const RES_HEIGHT: u32 = 90;
13
14/// Default render layers for pixel-perfect rendering.
15/// You can skip adding this component, as this is the default.
16const PIXEL_PERFECT_LAYERS: RenderLayers = RenderLayers::layer(0);
17
18/// Render layers for high-resolution rendering.
19const HIGH_RES_LAYERS: RenderLayers = RenderLayers::layer(1);
20
21fn main() {
22    App::new()
23        .add_plugins(DefaultPlugins.set(ImagePlugin::default_nearest()))
24        .add_systems(Startup, (setup_camera, setup_sprite, setup_mesh))
25        .add_systems(Update, (rotate, fit_canvas))
26        .run();
27}
28
29/// Low-resolution texture that contains the pixel-perfect world.
30/// Canvas itself is rendered to the high-resolution world.
31#[derive(Component)]
32struct Canvas;
33
34/// Camera that renders the pixel-perfect world to the [`Canvas`].
35#[derive(Component)]
36struct InGameCamera;
37
38/// Camera that renders the [`Canvas`] (and other graphics on [`HIGH_RES_LAYERS`]) to the screen.
39#[derive(Component)]
40struct OuterCamera;
41
42#[derive(Component)]
43struct Rotate;
44
45fn setup_sprite(mut commands: Commands, asset_server: Res<AssetServer>) {
46    // The sample sprite that will be rendered to the pixel-perfect canvas
47    commands.spawn((
48        Sprite::from_image(asset_server.load("pixel/bevy_pixel_dark.png")),
49        Transform::from_xyz(-45., 20., 2.),
50        Rotate,
51        PIXEL_PERFECT_LAYERS,
52    ));
53
54    // The sample sprite that will be rendered to the high-res "outer world"
55    commands.spawn((
56        Sprite::from_image(asset_server.load("pixel/bevy_pixel_light.png")),
57        Transform::from_xyz(-45., -20., 2.),
58        Rotate,
59        HIGH_RES_LAYERS,
60    ));
61}
62
63/// Spawns a capsule mesh on the pixel-perfect layer.
64fn setup_mesh(
65    mut commands: Commands,
66    mut meshes: ResMut<Assets<Mesh>>,
67    mut materials: ResMut<Assets<ColorMaterial>>,
68) {
69    commands.spawn((
70        Mesh2d(meshes.add(Capsule2d::default())),
71        MeshMaterial2d(materials.add(Color::BLACK)),
72        Transform::from_xyz(25., 0., 2.).with_scale(Vec3::splat(32.)),
73        Rotate,
74        PIXEL_PERFECT_LAYERS,
75    ));
76}
77
78fn setup_camera(mut commands: Commands, mut images: ResMut<Assets<Image>>) {
79    // This Image serves as a canvas representing the low-resolution game screen
80    let canvas =
81        Image::new_target_texture(RES_WIDTH, RES_HEIGHT, TextureFormat::Bgra8UnormSrgb, None);
82
83    let image_handle = images.add(canvas);
84
85    // This camera renders whatever is on `PIXEL_PERFECT_LAYERS` to the canvas
86    commands.spawn((
87        Camera2d,
88        Camera {
89            // Render before the "main pass" camera
90            order: -1,
91            clear_color: ClearColorConfig::Custom(GRAY.into()),
92            ..default()
93        },
94        RenderTarget::Image(image_handle.clone().into()),
95        Msaa::Off,
96        InGameCamera,
97        PIXEL_PERFECT_LAYERS,
98    ));
99
100    // Spawn the canvas
101    commands.spawn((Sprite::from_image(image_handle), Canvas, HIGH_RES_LAYERS));
102
103    // The "outer" camera renders whatever is on `HIGH_RES_LAYERS` to the screen.
104    // here, the canvas and one of the sample sprites will be rendered by this camera
105    commands.spawn((Camera2d, Msaa::Off, OuterCamera, HIGH_RES_LAYERS));
106}
107
108/// Rotates entities to demonstrate grid snapping.
109fn rotate(time: Res<Time>, mut transforms: Query<&mut Transform, With<Rotate>>) {
110    for mut transform in &mut transforms {
111        let dt = time.delta_secs();
112        transform.rotate_z(dt);
113    }
114}
115
116/// Scales camera projection to fit the window (integer multiples only).
117fn fit_canvas(
118    mut resize_messages: MessageReader<WindowResized>,
119    mut projection: Single<&mut Projection, With<OuterCamera>>,
120) {
121    let Projection::Orthographic(projection) = &mut **projection else {
122        return;
123    };
124    for window_resized in resize_messages.read() {
125        let h_scale = window_resized.width / RES_WIDTH as f32;
126        let v_scale = window_resized.height / RES_HEIGHT as f32;
127        projection.scale = 1. / h_scale.min(v_scale).floor();
128    }
129}