Skip to content

Commit

Permalink
Add Image methods for easy access to a pixel's color (#10392)
Browse files Browse the repository at this point in the history
# 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 <killercup@gmail.com>
Co-authored-by: François <mockersf@gmail.com>
Co-authored-by: ltdk <usr@ltdk.xyz>
  • Loading branch information
4 people authored Oct 7, 2024
1 parent aa56d48 commit 31409eb
Show file tree
Hide file tree
Showing 4 changed files with 596 additions and 2 deletions.
11 changes: 11 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -578,6 +578,17 @@ description = "Renders a glTF mesh in 2D with a custom vertex attribute"
category = "2D Rendering"
wasm = true

[[example]]
name = "cpu_draw"
path = "examples/2d/cpu_draw.rs"
doc-scrape-examples = true

[package.metadata.example.cpu_draw]
name = "CPU Drawing"
description = "Manually read/write the pixels of a texture"
category = "2D Rendering"
wasm = true

[[example]]
name = "sprite"
path = "examples/2d/sprite.rs"
Expand Down
Loading

0 comments on commit 31409eb

Please sign in to comment.