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
10 changes: 9 additions & 1 deletion crates/processing_pyo3/src/color.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,16 @@ pub(crate) fn extract_color_with_mode(
Ok(space.gray(v, native[3]))
}
2 => {
let v = convert_channel(mode, &args.get_item(0)?, 0)?;
let first = args.get_item(0)?;
let a = convert_channel(mode, &args.get_item(1)?, 3)?;
// a color with its alpha replaced, e.g. `fill(c, 128)`
if let Ok(c) = first.extract::<PyRef<PyColor>>() {
return Ok(c.0.with_alpha(a));
}
if let Ok(s) = first.extract::<String>() {
return Ok(parse_hex(&s)?.with_alpha(a));
}
let v = convert_channel(mode, &first, 0)?;
Ok(space.gray(v, a))
}
3 => {
Expand Down
113 changes: 96 additions & 17 deletions crates/processing_pyo3/src/graphics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -698,13 +698,34 @@ impl Image {
.map_err(|e| PyRuntimeError::new_err(format!("{e}")))
}

/// Read a single pixel as a `Color` (Processing `get`); outside the image it is transparent black.
fn get(&self, x: i64, y: i64) -> PyResult<crate::color::PyColor> {
let p = image_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))]
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 = image_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 = image_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 image it is dropped. Accepts a
Expand Down Expand Up @@ -1073,9 +1094,32 @@ impl Graphics {
self.surface.focused()
}

#[getter]
pub fn pixel_density(&self) -> PyResult<f32> {
self.surface.pixel_density()
/// `pixel_density()` reads the density, `pixel_density(d)` sets it.
#[pyo3(signature = (density=None))]
pub fn pixel_density(&self, py: Python<'_>, density: Option<f32>) -> PyResult<Py<PyAny>> {
let offscreen = image_size(self.surface.entity).is_ok();
match density {
None if offscreen => Ok(1.0f32.into_pyobject(py)?.into_any().unbind()),
None => Ok(self
.surface
.pixel_density()?
.into_pyobject(py)?
.into_any()
.unbind()),
Some(d) if offscreen => {
if d == 1.0 {
Ok(py.None())
} else {
Err(PyValueError::new_err(
"an offscreen Graphics has a pixel density of 1",
))
}
}
Some(d) => {
self.surface.set_pixel_density(d)?;
Ok(py.None())
}
}
}

#[getter]
Expand Down Expand Up @@ -2547,19 +2591,54 @@ impl Graphics {
composite_apply(self.entity, src_entity, code, sr, dr, opacity)
}

/// Copies a source onto this graphics, replacing pixels (Processing `copy`).
/// `src` may be an `Image`, webcam, or `Graphics`. See `blend` for the
/// `src_rect`/`dst_rect` semantics.
#[pyo3(signature = (src, *, src_rect=None, dst_rect=None))]
/// Copies pixels onto this graphics from an `Image`, webcam, `Graphics` or itself.
#[pyo3(signature = (*args, src_rect=None, dst_rect=None))]
pub fn copy(
&self,
src: &Bound<'_, PyAny>,
args: &Bound<'_, PyTuple>,
src_rect: Option<[f32; 4]>,
dst_rect: Option<[f32; 4]>,
) -> PyResult<()> {
let src_entity = src.extract::<ImageRef>()?.texture()?;
let sr = normalize_src_rect(src_entity, src_rect)?;
let (src, rects) = match args.len() {
0 => (None, None),
1 => (Some(args.get_item(0)?), None),
8 => (None, Some(args.extract::<[f32; 8]>()?)),
9 => (
Some(args.get_item(0)?),
Some(args.get_slice(1, 9).extract::<[f32; 8]>()?),
),
_ => {
return Err(pyo3::exceptions::PyTypeError::new_err(
"copy() takes src, or sx, sy, sw, sh, dx, dy, dw, dh, or src followed by those eight",
));
}
};
let (src_rect, dst_rect) = match rects {
Some([sx, sy, sw, sh, dx, dy, dw, dh]) => {
(Some([sx, sy, sw, sh]), Some([dx, dy, dw, dh]))
}
None => (src_rect, dst_rect),
};
let dr = normalize_rect(dst_rect, self.width as f32, self.height as f32);

// this graphics as its own source
let own = match &src {
None => true,
Some(src) => src
.extract::<PyRef<Graphics>>()
.is_ok_and(|g| g.entity == self.entity),
};
if own {
use shader_value::ShaderValue;
let sr = normalize_rect(src_rect, self.width as f32, self.height as f32);
let filter = filter_copy_region().map_err(rt_err)?;
filter_set(filter, "src_rect", ShaderValue::Float4(sr)).map_err(rt_err)?;
filter_set(filter, "dst_rect", ShaderValue::Float4(dr)).map_err(rt_err)?;
return graphics_apply_filter(self.entity, filter).map_err(rt_err);
}

let src_entity = src.unwrap().extract::<ImageRef>()?.texture()?;
let sr = normalize_src_rect(src_entity, src_rect)?;
composite_apply(self.entity, src_entity, COMPOSITE_MODE_REPLACE, sr, dr, 1.0)
}

Expand Down
6 changes: 3 additions & 3 deletions crates/processing_pyo3/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2208,14 +2208,14 @@ pub mod processing_py {
}

#[pyfunction]
#[pyo3(pass_module, signature = (src, *, src_rect=None, dst_rect=None))]
#[pyo3(pass_module, signature = (*args, src_rect=None, dst_rect=None))]
fn copy(
module: &Bound<'_, PyModule>,
src: &Bound<'_, PyAny>,
args: &Bound<'_, PyTuple>,
src_rect: Option<[f32; 4]>,
dst_rect: Option<[f32; 4]>,
) -> PyResult<()> {
graphics!(module).copy(src, src_rect, dst_rect)
graphics!(module).copy(args, src_rect, dst_rect)
}

#[pyfunction]
Expand Down
42 changes: 42 additions & 0 deletions crates/processing_render/src/image.rs
Original file line number Diff line number Diff line change
Expand Up @@ -658,6 +658,48 @@ pub fn cpu_pixels(world: &World, entity: Entity) -> Result<Vec<LinearRgba>> {
)
}

/// The bytes of a `width` x `height` block at (`x`, `y`) in the image's format.
pub fn cpu_region(
world: &World,
entity: Entity,
x: i64,
y: i64,
width: u32,
height: u32,
) -> Result<(Vec<u8>, TextureFormat)> {
let p_image = world
.get::<Image>(entity)
.ok_or(ProcessingError::ImageNotFound)?;
let size = p_image.size;
let format = p_image.texture_format;
let data = world
.resource::<Assets<bevy::image::Image>>()
.get(&p_image.handle)
.and_then(|image| image.data.as_deref())
.ok_or(ProcessingError::ImageNotFound)?;
let px_size = pixel_size(format)?;
let stride = size.width as usize * px_size;
check_len(data.len(), stride, size, format)?;

let mut region = vec![0u8; width as usize * height as usize * px_size];
// the columns of the block that fall inside the image
let x0 = x.clamp(0, size.width as i64);
let x1 = (x + width as i64).clamp(0, size.width as i64);
if x0 < x1 {
let run = (x1 - x0) as usize * px_size;
for row in 0..height as i64 {
let src_y = y + row;
if src_y < 0 || src_y >= size.height as i64 {
continue;
}
let src = src_y as usize * stride + x0 as usize * px_size;
let dst = (row as usize * width as usize + (x0 - x) as usize) * px_size;
region[dst..dst + run].copy_from_slice(&data[src..src + run]);
}
}
Ok((region, format))
}

/// A CPU buffer that disagrees with the image size would make row math index out of bounds
fn check_len(len: usize, stride: usize, size: Extent3d, format: TextureFormat) -> Result<()> {
let expected = stride * size.height as usize;
Expand Down
47 changes: 36 additions & 11 deletions crates/processing_render/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -638,6 +638,7 @@ builtin_filter!(filter_erode, ERODE);
builtin_filter!(filter_dilate, DILATE);
builtin_filter!(filter_composite, COMPOSITE);
builtin_filter!(filter_feedback, FEEDBACK);
builtin_filter!(filter_copy_region, COPY_REGION);

pub fn filter_set_passes(entity: Entity, passes: u32) -> error::Result<()> {
app_mut(|app| {
Expand Down Expand Up @@ -1244,6 +1245,34 @@ pub fn image_get_pixel(entity: Entity, x: i64, y: i64) -> error::Result<Option<L
})
}

/// A new image holding the block at (`x`, `y`).
pub fn image_get_region(
entity: Entity,
x: i64,
y: i64,
width: u32,
height: u32,
) -> error::Result<Entity> {
if width == 0 || height == 0 {
return Err(error::ProcessingError::InvalidArgument(
"a sub-image needs a width and height above zero".to_string(),
));
}
app_mut(|app| {
image::sync_cpu(app, entity)?;
let (data, format) = image::cpu_region(app.world(), entity, x, y, width, height)?;
let size = Extent3d {
width,
height,
depth_or_array_layers: 1,
};
Ok(app
.world_mut()
.run_system_cached_with(image::create, (size, data, format))
.unwrap())
})
}

/// The image's pixels; served from the CPU copy unless the GPU wrote the texture
pub fn image_readback(entity: Entity) -> error::Result<Vec<LinearRgba>> {
app_mut(|app| {
Expand Down Expand Up @@ -2705,21 +2734,17 @@ pub fn font_load(path: &str) -> error::Result<Entity> {
}
}

/// Create a font handle from an existing font family name.
/// Create a font handle for a family name; an unknown family falls back to the default font.
pub fn font_create(name: &str) -> error::Result<Entity> {
use text::font::{Font, TextContext};
use text::font::{DEFAULT_FONT_FAMILY, Font, TextContext};

app_mut(|app| {
let text_cx = app.world().resource::<TextContext>().clone();
if !text_cx.has_font(name) {
return Err(error::ProcessingError::FontNotFound);
}
let entity = app
.world_mut()
.spawn(Font {
family_name: name.to_string(),
})
.id();
let family_name = text_cx.resolve_family(name).unwrap_or_else(|| {
warn!("font {name:?} is not installed, using the default font");
DEFAULT_FONT_FAMILY.to_string()
});
let entity = app.world_mut().spawn(Font { family_name }).id();
Ok(entity)
})
}
Expand Down
1 change: 1 addition & 0 deletions crates/processing_render/src/render/filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ pub mod builtin {
pub const BLUR: &str = include_str!("filters/blur.wgsl");
pub const COMPOSITE: &str = include_str!("filters/composite.wgsl");
pub const FEEDBACK: &str = include_str!("filters/feedback.wgsl");
pub const COPY_REGION: &str = include_str!("filters/copy_region.wgsl");
}

#[derive(Component)]
Expand Down
20 changes: 20 additions & 0 deletions crates/processing_render/src/render/filters/copy_region.wgsl
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// Copies one rectangle of the surface onto another; rects are normalized (x0, y0, x1, y1).
import processing::filter::{sample, FullscreenVertexOutput};

struct CopyRegionParams {
src_rect: vec4<f32>,
dst_rect: vec4<f32>,
}

@group(1) @binding(0) var<uniform> copy_region: CopyRegionParams;

@fragment
fn fragment(in: FullscreenVertexOutput) -> @location(0) vec4<f32> {
let dmin = copy_region.dst_rect.xy;
let dmax = copy_region.dst_rect.zw;
if (in.uv.x < dmin.x || in.uv.y < dmin.y || in.uv.x > dmax.x || in.uv.y > dmax.y) {
return sample(in.uv);
}
let local = (in.uv - dmin) / max(dmax - dmin, vec2<f32>(1e-6));
return sample(mix(copy_region.src_rect.xy, copy_region.src_rect.zw, local));
}
12 changes: 12 additions & 0 deletions crates/processing_render/src/text/font.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,18 @@ impl TextContext {
let mut inner = self.inner.lock().unwrap();
inner.font_cx.collection.family_id(name).is_some()
}

/// The installed family for a name, resolving generic names such as `sans-serif`.
pub fn resolve_family(&self, name: &str) -> Option<String> {
let mut inner = self.inner.lock().unwrap();
let collection = &mut inner.font_cx.collection;
if let Some(id) = collection.family_id(name) {
return collection.family_name(id).map(str::to_string);
}
let generic = fontique::GenericFamily::parse(name)?;
let id = collection.generic_families(generic).next()?;
collection.family_name(id).map(str::to_string)
}
}

impl Default for TextContext {
Expand Down
Loading