Skip to content
Open
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
7 changes: 4 additions & 3 deletions crates/processing_pyo3/src/graphics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use bevy::{
render::render_resource::{Extent3d, TextureFormat},
};
use processing::prelude::*;
use processing_render::color::pixel_to_srgba;
use pyo3::{
exceptions::{PyRuntimeError, PyValueError},
prelude::*,
Expand Down Expand Up @@ -37,7 +38,7 @@ fn flatten_floats(args: &Bound<'_, PyTuple>) -> PyResult<Vec<f32>> {
fn pixels_to_pylist(py: Python<'_>, pixels: &[LinearRgba]) -> PyResult<Py<PyList>> {
let colors = pixels
.iter()
.map(|p| crate::color::PyColor(bevy::prelude::Color::Srgba(Srgba::from(*p))));
.map(|p| crate::color::PyColor(bevy::prelude::Color::Srgba(pixel_to_srgba(*p))));
Ok(PyList::new(py, colors)?.unbind())
}

Expand Down Expand Up @@ -702,7 +703,7 @@ impl Image {
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, Srgba::from),
p.map_or(Srgba::NONE, pixel_to_srgba),
)))
}

Expand Down Expand Up @@ -1156,7 +1157,7 @@ impl Graphics {
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, Srgba::from),
p.map_or(Srgba::NONE, pixel_to_srgba),
)))
}

Expand Down
45 changes: 45 additions & 0 deletions crates/processing_render/src/color.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,3 +192,48 @@ mod tests {
assert!((mode.scale(50.0, 2) - 0.5).abs() < 1e-4);
}
}

/// The sRGB color of a pixel read back, snapped to 8-bit when within a quarter step.
pub fn pixel_to_srgba(pixel: LinearRgba) -> Srgba {
fn snap(channel: f32) -> f32 {
let step = (channel * 255.0).round();
if (0.0..=255.0).contains(&step) && (channel * 255.0 - step).abs() < 0.25 {
step / 255.0
} else {
channel
}
}
let srgba = Srgba::from(pixel);
Srgba::new(
snap(srgba.red),
snap(srgba.green),
snap(srgba.blue),
snap(srgba.alpha),
)
}

#[cfg(test)]
mod pixel_tests {
use super::*;

#[test]
fn eight_bit_colors_survive_a_half_float_canvas() {
for byte in 0..=255u8 {
let want = byte as f32 / 255.0;
let linear = LinearRgba::from(Srgba::new(want, want, want, 1.0));
// what an Rgba16Float target keeps of the channel
let stored = half::f16::from_f32(linear.red).to_f32();
let read = pixel_to_srgba(LinearRgba::new(stored, stored, stored, 1.0));
assert_eq!(read.red, want, "byte {byte}");
}
}

#[test]
fn values_between_steps_are_kept() {
let srgba = Srgba::new(0.3, 2.5, -0.1, 1.0);
let read = pixel_to_srgba(LinearRgba::from(srgba));
assert!((read.red - 0.3).abs() < 1e-5);
assert!((read.green - 2.5).abs() < 1e-4);
assert!(read.blue < 0.0);
}
}
54 changes: 38 additions & 16 deletions crates/processing_render/src/render/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -601,8 +601,7 @@ pub fn flush_draw_commands(
);
}
DrawCommand::Point { x, y } => {
if let Some(color) = state.style.stroke_color {
let d = state.style.stroke_weight;
if let Some((color, d)) = state.style.stroke() {
let material_key = material_key_with_color(
&state.style.material_key,
color,
Expand Down Expand Up @@ -828,8 +827,7 @@ pub fn flush_draw_commands(
);
}
ShapeKind::Points => {
if let Some(color) = state.style.stroke_color {
let d = state.style.stroke_weight;
if let Some((color, d)) = state.style.stroke() {
let material_key = material_key_with_color(
&state.style.material_key,
color,
Expand Down Expand Up @@ -1428,11 +1426,12 @@ pub fn flush_draw_commands(
);

if let Some(weight) = stroke_weight {
add_stroke(
add_stroke_weighted(
&mut res,
&mut batch,
&state,
|mesh, color, _| {
weight,
|mesh, color, weight| {
// per-glyph fill colors don't apply to the stroke
let mut params = text_params.as_params();
params.glyph_colors = None;
Expand Down Expand Up @@ -1671,11 +1670,27 @@ fn add_stroke(
state: &RenderState,
tessellate: impl FnOnce(&mut Mesh, Color, f32),
material_handles: &Query<&UntypedMaterial>,
) {
let weight = state.style.stroke_weight;
add_stroke_weighted(res, batch, state, weight, tessellate, material_handles);
}

/// A stroke in the current stroke color at `stroke_weight`; a weight of zero draws nothing.
fn add_stroke_weighted(
res: &mut RenderResources,
batch: &mut BatchState,
state: &RenderState,
stroke_weight: f32,
tessellate: impl FnOnce(&mut Mesh, Color, f32),
material_handles: &Query<&UntypedMaterial>,
) {
let Some(color) = state.style.stroke_color else {
return;
};
let stroke_weight = state.style.stroke_weight;
// a zero-width stroke tessellates to NaN vertices, which cull the whole batch
if stroke_weight <= 0.0 || stroke_weight.is_nan() {
return;
}
let material_key =
material_key_with_color(&state.style.material_key, color, state.style.blend_state);

Expand All @@ -1688,12 +1703,19 @@ fn add_stroke(
}
}

/// Nothing to draw; the mesh allocator also rejects a zero-size mesh.
fn mesh_is_empty(mesh: &Mesh) -> bool {
mesh.count_vertices() == 0 || mesh.indices().is_some_and(|indices| indices.is_empty())
}

fn flush_batch(
res: &mut RenderResources,
batch: &mut BatchState,
material_handles: &Query<&UntypedMaterial>,
) {
if let Some(mesh) = batch.current_mesh.take() {
if let Some(mesh) = batch.current_mesh.take()
&& !mesh_is_empty(&mesh)
{
let z_offset = layer_z(batch.draw_index);
spawn_mesh(res, batch, mesh, z_offset, material_handles);
batch.draw_index += 1;
Expand Down Expand Up @@ -1755,16 +1777,20 @@ fn draw_mesh3d(
) {
flush_batch(res, batch, material_handles);

if res.meshes.get(&draw.mesh).is_some_and(mesh_is_empty) {
return;
}

let (color, stroke) = match draw.paint {
MeshPaint::Surface { edges } => {
let color = match state.style.fill {
Fill::None => None,
Fill::Color(color) => Some(color),
Fill::Buffer(_) => Some(Color::WHITE),
};
(color, edges.zip(state.style.stroke_color))
(color, edges.zip(state.style.stroke()))
}
MeshPaint::Lines => (state.style.stroke_color, None),
MeshPaint::Lines => (state.style.stroke().map(|(color, _)| color), None),
};
if color.is_none() && stroke.is_none() {
return;
Expand Down Expand Up @@ -1845,16 +1871,12 @@ fn draw_mesh3d(
if let Some(material_handle) = material_handle {
entity.insert(UntypedMaterial(material_handle));
}
if let Some((edges, color)) = stroke {
if let Some((edges, (color, weight))) = stroke {
entity.insert((
Wireframe,
WireframeColor { color },
WireframeLineWidth {
width: if draw.hairline {
1.0
} else {
state.style.stroke_weight
},
width: if draw.hairline { 1.0 } else { weight },
},
edges,
));
Expand Down
8 changes: 8 additions & 0 deletions crates/processing_render/src/render/style.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,14 @@ pub struct Style {
pub text_glyph_colors: Option<Vec<Color>>,
}

impl Style {
/// The stroke color and weight, or `None` when there is nothing to stroke.
pub fn stroke(&self) -> Option<(Color, f32)> {
let color = self.stroke_color?;
(self.stroke_weight > 0.0).then_some((color, self.stroke_weight))
}
}

impl Default for Style {
fn default() -> Self {
Self {
Expand Down
Loading