Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 28 additions & 7 deletions crates/processing_pyo3/src/graphics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1196,13 +1196,34 @@ impl Graphics {
write_png_file(filename, raw.width, raw.height, &rgba)
}

/// Read a single pixel as a `Color` (Processing `get`).
pub fn get(&self, x: i64, y: i64) -> PyResult<crate::color::PyColor> {
let p = graphics_get_pixel(self.entity, x, y)
.map_err(|e| PyRuntimeError::new_err(format!("{e}")))?;
Ok(crate::color::PyColor(bevy::prelude::Color::Srgba(
p.map_or(Srgba::NONE, pixel_to_srgba),
)))
/// `get(x, y)` reads one pixel as a `Color`; `get(x, y, w, h)` copies a block into a new `Image`.
#[pyo3(signature = (x, y, w=None, h=None))]
pub fn get(
&self,
py: Python<'_>,
x: i64,
y: i64,
w: Option<u32>,
h: Option<u32>,
) -> PyResult<Py<PyAny>> {
match (w, h) {
(Some(w), Some(h)) => {
let entity = graphics_get_region(self.entity, x, y, w, h)
.map_err(|e| PyRuntimeError::new_err(format!("{e}")))?;
Ok(Py::new(py, Image::wrap(entity))?.into_any())
}
(None, None) => {
let p = graphics_get_pixel(self.entity, x, y)
.map_err(|e| PyRuntimeError::new_err(format!("{e}")))?;
let color = crate::color::PyColor(bevy::prelude::Color::Srgba(
p.map_or(Srgba::NONE, pixel_to_srgba),
));
Ok(Py::new(py, color)?.into_any())
}
_ => Err(pyo3::exceptions::PyTypeError::new_err(
"get() takes x, y or x, y, w, h",
)),
}
}

/// Write a single pixel (Processing `set`); outside the canvas it is dropped.
Expand Down
12 changes: 9 additions & 3 deletions crates/processing_pyo3/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2733,9 +2733,15 @@ pub mod processing_py {
}

#[pyfunction]
#[pyo3(pass_module)]
fn get(module: &Bound<'_, PyModule>, x: i64, y: i64) -> PyResult<PyColor> {
graphics!(module).get(x, y)
#[pyo3(pass_module, signature = (x, y, w=None, h=None))]
fn get(
module: &Bound<'_, PyModule>,
x: i64,
y: i64,
w: Option<u32>,
h: Option<u32>,
) -> PyResult<Py<PyAny>> {
graphics!(module).get(module.py(), x, y, w, h)
}

#[pyfunction]
Expand Down
94 changes: 94 additions & 0 deletions crates/processing_render/src/destroy.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
//! Deferred destroy: a destroy waits until every command buffer has drained.

use bevy::prelude::*;
use processing_core::error::Result;

use crate::render::command::CommandBuffer;

type Destroy = Box<dyn FnOnce(&mut World) -> Result<()> + Send + Sync>;

/// Destroys waiting for the queued draw commands to run.
#[derive(Resource, Default)]
pub struct PendingDestroys(Vec<Destroy>);

/// Whether any graphics still has draw commands to run.
fn commands_queued(world: &mut World) -> bool {
world
.query::<&CommandBuffer>()
.iter(world)
.any(|buffer| !buffer.commands.is_empty())
}

/// Runs `destroy` now, or once the queued draw commands have run.
pub fn request(
world: &mut World,
destroy: impl FnOnce(&mut World) -> Result<()> + Send + Sync + 'static,
) -> Result<()> {
if commands_queued(world) {
world
.get_resource_or_insert_with(PendingDestroys::default)
.0
.push(Box::new(destroy));
Ok(())
} else {
destroy(world)
}
}

/// Runs the waiting destroys if no draw command can still reference them.
pub fn run_pending(world: &mut World) {
if !world.contains_resource::<PendingDestroys>() || commands_queued(world) {
return;
}
let pending = std::mem::take(&mut world.resource_mut::<PendingDestroys>().0);
for destroy in pending {
if let Err(error) = destroy(world) {
debug!("deferred destroy failed: {error}");
}
}
}

#[cfg(test)]
mod tests {
use super::*;
use crate::render::command::DrawCommand;

#[derive(Component)]
struct Thing;

fn despawn(entity: Entity) -> impl FnOnce(&mut World) -> Result<()> + Send + Sync {
move |world| {
world.despawn(entity);
Ok(())
}
}

#[test]
fn a_destroy_runs_at_once_when_nothing_is_queued() {
let mut world = World::new();
world.spawn(CommandBuffer::new());
let thing = world.spawn(Thing).id();
request(&mut world, despawn(thing)).unwrap();
assert!(world.get_entity(thing).is_err());
}

#[test]
fn a_destroy_waits_for_queued_commands() {
let mut world = World::new();
let mut buffer = CommandBuffer::new();
buffer.push(DrawCommand::NoStroke);
let graphics = world.spawn(buffer).id();
let thing = world.spawn(Thing).id();

request(&mut world, despawn(thing)).unwrap();
run_pending(&mut world);
assert!(
world.get_entity(thing).is_ok(),
"still referenced by queued commands"
);

world.get_mut::<CommandBuffer>(graphics).unwrap().clear();
run_pending(&mut world);
assert!(world.get_entity(thing).is_err());
}
}
97 changes: 92 additions & 5 deletions crates/processing_render/src/graphics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -762,6 +762,7 @@ pub fn flush(app: &mut App, entity: Entity) -> Result<()> {
}
}
graphics_mut!(app, entity).remove::<Flush>();
crate::destroy::run_pending(app.world_mut());
Ok(())
}

Expand Down Expand Up @@ -875,6 +876,43 @@ fn pixel_scale(app: &App, entity: Entity) -> Result<(u32, u32, f64, f64)> {
))
}

/// The color of logical pixel (`lx`, `ly`), an alpha-weighted average of its physical pixels.
fn logical_pixel(
data: &[u8],
format: TextureFormat,
(pw, ph): (usize, usize),
(sx, sy): (f64, f64),
lx: i64,
ly: i64,
) -> Result<LinearRgba> {
let px_size = pixel_size(format)?;
let px0 = ((lx as f64 * sx) as usize).min(pw - 1);
let py0 = ((ly as f64 * sy) as usize).min(ph - 1);
let px1 = (((lx + 1) as f64 * sx) as usize).clamp(px0 + 1, pw);
let py1 = (((ly + 1) as f64 * sy) as usize).clamp(py0 + 1, ph);
let mut sum = [0.0f32; 4];
for py in py0..py1 {
for px in px0..px1 {
let at = (py * pw + px) * px_size;
let p = crate::image::decode_pixel(&data[at..at + px_size], format)?;
sum[0] += p.red * p.alpha;
sum[1] += p.green * p.alpha;
sum[2] += p.blue * p.alpha;
sum[3] += p.alpha;
}
}
if sum[3] <= 0.0 {
return Ok(LinearRgba::NONE);
}
let count = ((px1 - px0) * (py1 - py0)) as f32;
Ok(LinearRgba::new(
sum[0] / sum[3],
sum[1] / sum[3],
sum[2] / sum[3],
sum[3] / count,
))
}

/// The pixel at logical (`x`, `y`); `None` outside the canvas
pub fn get_pixel(app: &mut App, entity: Entity, x: i64, y: i64) -> Result<Option<LinearRgba>> {
let (lw, lh, sx, sy) = pixel_scale(app, entity)?;
Expand All @@ -889,11 +927,60 @@ pub fn get_pixel(app: &mut App, entity: Entity, x: i64, y: i64) -> Result<Option
let Some(data) = graphics.pixels.as_deref() else {
return Ok(None);
};
let px_size = pixel_size(graphics.texture_format)?;
let px = ((x as f64 * sx) as usize).min(graphics.size.width as usize - 1);
let py = ((y as f64 * sy) as usize).min(graphics.size.height as usize - 1);
let at = (py * graphics.size.width as usize + px) * px_size;
crate::image::decode_pixel(&data[at..at + px_size], graphics.texture_format).map(Some)
let physical = (graphics.size.width as usize, graphics.size.height as usize);
logical_pixel(data, graphics.texture_format, physical, (sx, sy), x, y).map(Some)
}

/// A new `width` x `height` image of the logical block at (`x`, `y`).
pub fn get_region(
app: &mut App,
entity: Entity,
x: i64,
y: i64,
width: u32,
height: u32,
) -> Result<Entity> {
if width == 0 || height == 0 {
return Err(ProcessingError::InvalidArgument(
"a sub-image needs a width and height above zero".to_string(),
));
}
let (lw, lh, sx, sy) = pixel_scale(app, entity)?;
ensure_pixels(app, entity)?;
let graphics = app
.world()
.get::<Graphics>(entity)
.ok_or(ProcessingError::GraphicsNotFound)?;
let data = graphics
.pixels
.as_deref()
.ok_or(ProcessingError::GraphicsNotFound)?;
let format = graphics.texture_format;
let (pw, ph) = (graphics.size.width as usize, graphics.size.height as usize);

let mut pixels = Vec::with_capacity(width as usize * height as usize);
for row in 0..height as i64 {
for col in 0..width as i64 {
let (lx, ly) = (x + col, y + row);
if lx < 0 || ly < 0 || lx >= lw as i64 || ly >= lh as i64 {
pixels.push(LinearRgba::NONE);
continue;
}
pixels.push(logical_pixel(data, format, (pw, ph), (sx, sy), lx, ly)?);
}
}

let format = TextureFormat::Rgba8UnormSrgb;
let bytes = pixels_to_bytes(&pixels, format)?;
let size = Extent3d {
width,
height,
depth_or_array_layers: 1,
};
Ok(app
.world_mut()
.run_system_cached_with(crate::image::create, (size, bytes, format))
.unwrap())
}

/// Sets the pixel at logical (`x`, `y`), which covers a block of physical pixels
Expand Down
52 changes: 37 additions & 15 deletions crates/processing_render/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ pub mod camera;
pub mod ci;
pub mod color;
pub mod compute;
pub mod destroy;
pub mod geometry;
pub mod gltf;
pub mod graphics;
Expand Down Expand Up @@ -692,6 +693,17 @@ pub fn graphics_update(graphics_entity: Entity, pixels: &[LinearRgba]) -> error:
})
}

/// A new image of the logical block at (`x`, `y`) of the surface.
pub fn graphics_get_region(
graphics_entity: Entity,
x: i64,
y: i64,
width: u32,
height: u32,
) -> error::Result<Entity> {
app_mut(|app| graphics::get_region(app, graphics_entity, x, y, width, height))
}

/// Update a region of the graphics surface with new pixel data.
/// The pixel at logical (`x`, `y`); `None` outside the surface, where Processing's `get` is
/// transparent black
Expand Down Expand Up @@ -1349,9 +1361,11 @@ pub fn image_set_sampler(entity: Entity, filter: u8, wrap_x: u8, wrap_y: u8) ->
/// Destroy an existing image and free its resources.
pub fn image_destroy(entity: Entity) -> error::Result<()> {
app_mut(|app| {
app.world_mut()
.run_system_cached_with(image::destroy, entity)
.unwrap()
destroy::request(app.world_mut(), move |world| {
world
.run_system_cached_with(image::destroy, entity)
.unwrap()
})
})
}

Expand Down Expand Up @@ -1457,9 +1471,11 @@ pub fn graphics_immediate_light(

pub fn light_destroy(entity: Entity) -> error::Result<()> {
app_mut(|app| {
app.world_mut()
.run_system_cached_with(light::destroy, entity)
.unwrap()
destroy::request(app.world_mut(), move |world| {
world
.run_system_cached_with(light::destroy, entity)
.unwrap()
})
})
}

Expand Down Expand Up @@ -1766,9 +1782,11 @@ pub fn geometry_get_indices(entity: Entity, start: usize, end: usize) -> error::

pub fn geometry_destroy(entity: Entity) -> error::Result<()> {
app_mut(|app| {
app.world_mut()
.run_system_cached_with(geometry::destroy, entity)
.unwrap()
destroy::request(app.world_mut(), move |world| {
world
.run_system_cached_with(geometry::destroy, entity)
.unwrap()
})
})
}

Expand Down Expand Up @@ -2126,9 +2144,11 @@ pub fn material_set_custom_blend(

pub fn material_destroy(entity: Entity) -> error::Result<()> {
app_mut(|app| {
app.world_mut()
.run_system_cached_with(material::destroy, entity)
.unwrap()
destroy::request(app.world_mut(), move |world| {
world
.run_system_cached_with(material::destroy, entity)
.unwrap()
})
})
}

Expand Down Expand Up @@ -2590,9 +2610,11 @@ fn buffer_read_range(entity: Entity, offset: u64, len: u64) -> error::Result<Vec

pub fn buffer_destroy(entity: Entity) -> error::Result<()> {
app_mut(|app| {
app.world_mut()
.run_system_cached_with(compute::destroy_buffer, entity)
.unwrap()
destroy::request(app.world_mut(), move |world| {
world
.run_system_cached_with(compute::destroy_buffer, entity)
.unwrap()
})
})
}

Expand Down
Loading
Loading