Skip to content

Commit 31409eb

Browse files
inodentrykillercupmockersfclarfonthey
authored
Add Image methods for easy access to a pixel's color (#10392)
# Objective If you want to draw / generate images from the CPU, such as: - to create procedurally-generated assets - for games whose artstyle is best implemented by poking pixels directly from the CPU, instead of using shaders It is currently very unergonomic to do in Bevy, because you have to deal with the raw bytes inside `image.data`, take care of the pixel format, etc. ## Solution This PR adds some helper methods to `Image` for pixel manipulation. These methods allow you to use Bevy's user-friendly `Color` struct to read and write the colors of pixels, at arbitrary coordinates (specified as `UVec3` to support any texture dimension). They handle encoding/decoding to the `Image`s `TextureFormat`, incl. any sRGB conversion. While we are at it, also add methods to help with direct access to the raw bytes. It is now easy to compute the offset where the bytes of a specific pixel coordinate are found, or to just get a Rust slice to access them. Caveat: `Color` roundtrips are obviously going to be lossy for non-float `TextureFormat`s. Using `set_color_at` followed by `get_color_at` will return a different value, due to the data conversions involved (such as `f32` -> `u8` -> `f32` for the common `Rgba8UnormSrgb` texture format). Be careful when comparing colors (such as checking for a color you wrote before)! Also adding a new example: `cpu_draw` (under `2d`), to showcase these new APIs. --- ## Changelog ### Added - `Image` APIs for easy access to the colors of specific pixels. --------- Co-authored-by: Pascal Hertleif <[email protected]> Co-authored-by: François <[email protected]> Co-authored-by: ltdk <[email protected]>
1 parent aa56d48 commit 31409eb

File tree

4 files changed

+596
-2
lines changed

4 files changed

+596
-2
lines changed

Cargo.toml

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -578,6 +578,17 @@ description = "Renders a glTF mesh in 2D with a custom vertex attribute"
578578
category = "2D Rendering"
579579
wasm = true
580580

581+
[[example]]
582+
name = "cpu_draw"
583+
path = "examples/2d/cpu_draw.rs"
584+
doc-scrape-examples = true
585+
586+
[package.metadata.example.cpu_draw]
587+
name = "CPU Drawing"
588+
description = "Manually read/write the pixels of a texture"
589+
category = "2D Rendering"
590+
wasm = true
591+
581592
[[example]]
582593
name = "sprite"
583594
path = "examples/2d/sprite.rs"

0 commit comments

Comments
 (0)