Skip to content

Commit 4881633

Browse files
andriyDevpull[bot]
authored andcommitted
Fix off-by-one error on Image::get_color_at and Image::set_color_at. (#16475)
# Objective - Fixes #16474. ## Solution - Check that the pixel x,y,z is less than width,height,depth. - Classic off-by-one. ## Testing - Added a test.
1 parent f79e4f3 commit 4881633

File tree

1 file changed

+27
-3
lines changed

1 file changed

+27
-3
lines changed

crates/bevy_image/src/image.rs

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -944,19 +944,19 @@ impl Image {
944944
let pixel_size = self.texture_descriptor.format.pixel_size();
945945
let pixel_offset = match self.texture_descriptor.dimension {
946946
TextureDimension::D3 => {
947-
if coords.x > width || coords.y > height || coords.z > depth {
947+
if coords.x >= width || coords.y >= height || coords.z >= depth {
948948
return None;
949949
}
950950
coords.z * height * width + coords.y * width + coords.x
951951
}
952952
TextureDimension::D2 => {
953-
if coords.x > width || coords.y > height {
953+
if coords.x >= width || coords.y >= height {
954954
return None;
955955
}
956956
coords.y * width + coords.x
957957
}
958958
TextureDimension::D1 => {
959-
if coords.x > width {
959+
if coords.x >= width {
960960
return None;
961961
}
962962
coords.x
@@ -1573,4 +1573,28 @@ mod test {
15731573
assert_eq!(UVec2::ONE, image.size());
15741574
assert_eq!(Vec2::ONE, image.size_f32());
15751575
}
1576+
1577+
#[test]
1578+
fn on_edge_pixel_is_invalid() {
1579+
let image = Image::new_fill(
1580+
Extent3d {
1581+
width: 5,
1582+
height: 10,
1583+
depth_or_array_layers: 1,
1584+
},
1585+
TextureDimension::D2,
1586+
&[0, 0, 0, 255],
1587+
TextureFormat::Rgba8Unorm,
1588+
RenderAssetUsages::MAIN_WORLD,
1589+
);
1590+
assert!(matches!(image.get_color_at(4, 9), Ok(Color::BLACK)));
1591+
assert!(matches!(
1592+
image.get_color_at(0, 10),
1593+
Err(TextureAccessError::OutOfBounds { x: 0, y: 10, z: 0 })
1594+
));
1595+
assert!(matches!(
1596+
image.get_color_at(5, 10),
1597+
Err(TextureAccessError::OutOfBounds { x: 5, y: 10, z: 0 })
1598+
));
1599+
}
15761600
}

0 commit comments

Comments
 (0)