From 50f5451b6bc8cb185c43d0ecfe62c693a939fe0d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?charlotte=20=F0=9F=8C=B8?= Date: Sun, 15 Nov 2026 22:08:35 -0800 Subject: [PATCH] Fixes for manual vertex and stroke/fills. --- crates/processing_core/src/constants.rs | 3 +- crates/processing_ffi/src/lib.rs | 31 +- crates/processing_node/src/lib.rs | 22 +- crates/processing_pyo3/src/constants.rs | 1 + crates/processing_pyo3/src/graphics.rs | 110 ++- crates/processing_pyo3/src/lib.rs | 38 +- crates/processing_render/src/graphics.rs | 8 + crates/processing_render/src/lib.rs | 1 + .../processing_render/src/render/command.rs | 56 +- crates/processing_render/src/render/line.rs | 276 ++++++ crates/processing_render/src/render/line.wgsl | 164 ++++ .../processing_render/src/render/material.rs | 34 + .../src/render/mesh_builder.rs | 134 ++- crates/processing_render/src/render/mod.rs | 419 +++++--- .../src/render/primitive/mod.rs | 55 +- .../src/render/primitive/shape.rs | 923 +++++++++++------- crates/processing_render/src/render/style.rs | 3 + crates/processing_wasm/src/lib.rs | 23 +- examples/shapes.rs | 58 +- src/prelude.rs | 3 +- 20 files changed, 1700 insertions(+), 662 deletions(-) create mode 100644 crates/processing_render/src/render/line.rs create mode 100644 crates/processing_render/src/render/line.wgsl diff --git a/crates/processing_core/src/constants.rs b/crates/processing_core/src/constants.rs index b818b781..28a4ba04 100644 --- a/crates/processing_core/src/constants.rs +++ b/crates/processing_core/src/constants.rs @@ -32,7 +32,8 @@ pub const TOP: &str = "top"; // vertical text align pub const BOTTOM: &str = "bottom"; pub const BASELINE: &str = "baseline"; -pub const NORMAL: &str = "normal"; // text style +pub const NORMAL: &str = "normal"; // text style, texture mode +pub const IMAGE: &str = "image"; // texture mode pub const ITALIC: &str = "italic"; pub const BOLD: &str = "bold"; pub const BOLD_ITALIC: &str = "bold_italic"; diff --git a/crates/processing_ffi/src/lib.rs b/crates/processing_ffi/src/lib.rs index 0288b042..b0b153ef 100644 --- a/crates/processing_ffi/src/lib.rs +++ b/crates/processing_ffi/src/lib.rs @@ -1041,7 +1041,15 @@ pub extern "C" fn processing_end_shape(graphics_id: u64, close: bool) { pub extern "C" fn processing_vertex(graphics_id: u64, x: f32, y: f32) { error::clear_error(); let graphics_entity = Entity::from_bits(graphics_id); - error::check(|| graphics_record_command(graphics_entity, DrawCommand::ShapeVertex { x, y })); + error::check(|| { + graphics_record_command( + graphics_entity, + DrawCommand::ShapeVertex { + position: Vec3::new(x, y, 0.0), + uv: None, + }, + ) + }); } /// Add a cubic bezier vertex to the current shape. @@ -1061,12 +1069,9 @@ pub extern "C" fn processing_bezier_vertex( graphics_record_command( graphics_entity, DrawCommand::ShapeBezierVertex { - cx1, - cy1, - cx2, - cy2, - x, - y, + c1: Vec3::new(cx1, cy1, 0.0), + c2: Vec3::new(cx2, cy2, 0.0), + to: Vec3::new(x, y, 0.0), }, ) }); @@ -1080,7 +1085,10 @@ pub extern "C" fn processing_quadratic_vertex(graphics_id: u64, cx: f32, cy: f32 error::check(|| { graphics_record_command( graphics_entity, - DrawCommand::ShapeQuadraticVertex { cx, cy, x, y }, + DrawCommand::ShapeQuadraticVertex { + c: Vec3::new(cx, cy, 0.0), + to: Vec3::new(x, y, 0.0), + }, ) }); } @@ -1091,7 +1099,12 @@ pub extern "C" fn processing_curve_vertex(graphics_id: u64, x: f32, y: f32) { error::clear_error(); let graphics_entity = Entity::from_bits(graphics_id); error::check(|| { - graphics_record_command(graphics_entity, DrawCommand::ShapeCurveVertex { x, y }) + graphics_record_command( + graphics_entity, + DrawCommand::ShapeCurveVertex { + to: Vec3::new(x, y, 0.0), + }, + ) }); } diff --git a/crates/processing_node/src/lib.rs b/crates/processing_node/src/lib.rs index 8c02503f..34d9b2f9 100644 --- a/crates/processing_node/src/lib.rs +++ b/crates/processing_node/src/lib.rs @@ -865,8 +865,8 @@ pub fn js_vertex(graphics_id: BigInt, x: f64, y: f64) -> Result<()> { record( graphics_id, DrawCommand::ShapeVertex { - x: x as f32, - y: y as f32, + position: vec3(x, y, 0.0), + uv: None, }, ) } @@ -884,12 +884,9 @@ pub fn js_bezier_vertex( record( graphics_id, DrawCommand::ShapeBezierVertex { - cx1: cx1 as f32, - cy1: cy1 as f32, - cx2: cx2 as f32, - cy2: cy2 as f32, - x: x as f32, - y: y as f32, + c1: vec3(cx1, cy1, 0.0), + c2: vec3(cx2, cy2, 0.0), + to: vec3(x, y, 0.0), }, ) } @@ -899,10 +896,8 @@ pub fn js_quadratic_vertex(graphics_id: BigInt, cx: f64, cy: f64, x: f64, y: f64 record( graphics_id, DrawCommand::ShapeQuadraticVertex { - cx: cx as f32, - cy: cy as f32, - x: x as f32, - y: y as f32, + c: vec3(cx, cy, 0.0), + to: vec3(x, y, 0.0), }, ) } @@ -912,8 +907,7 @@ pub fn js_curve_vertex(graphics_id: BigInt, x: f64, y: f64) -> Result<()> { record( graphics_id, DrawCommand::ShapeCurveVertex { - x: x as f32, - y: y as f32, + to: vec3(x, y, 0.0), }, ) } diff --git a/crates/processing_pyo3/src/constants.rs b/crates/processing_pyo3/src/constants.rs index b3b789eb..5d6ae744 100644 --- a/crates/processing_pyo3/src/constants.rs +++ b/crates/processing_pyo3/src/constants.rs @@ -41,6 +41,7 @@ pub fn register(m: &Bound<'_, PyModule>) -> PyResult<()> { // text align (LEFT/RIGHT/CENTER above), style, and wrap constants add!(m, TOP, BOTTOM, BASELINE); add!(m, NORMAL, ITALIC, BOLD, BOLD_ITALIC); + add!(m, IMAGE); add!(m, WORD, CHAR); add!(m, NEAREST, CLAMP, REPEAT, MIRROR); add!(m, SRGB, LINEAR, HSL, HSV, HWB, OKLAB, OKLCH, LAB, LCH, XYZ); diff --git a/crates/processing_pyo3/src/graphics.rs b/crates/processing_pyo3/src/graphics.rs index 53d03ccf..2202aa29 100644 --- a/crates/processing_pyo3/src/graphics.rs +++ b/crates/processing_pyo3/src/graphics.rs @@ -4,7 +4,7 @@ use crate::input; use crate::math::{Vec3Like, extract_vec2, extract_vec3}; use bevy::{ color::{ColorToPacked, LinearRgba, Srgba}, - math::{Affine3A, Mat4, Vec3, Vec4}, + math::{Affine3A, Mat4, Vec2, Vec3, Vec4}, prelude::{Entity, Transform}, render::render_resource::{Extent3d, TextureFormat}, }; @@ -1683,11 +1683,44 @@ impl Graphics { .map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } - pub fn vertex(&self, x: f32, y: f32) -> PyResult<()> { - graphics_record_command(self.entity, DrawCommand::ShapeVertex { x, y }) + /// `vertex(x, y)`, `vertex(x, y, z)`, `vertex(x, y, u, v)` or `vertex(x, y, z, u, v)`. + #[pyo3(signature = (x, y, *args))] + pub fn vertex(&self, x: f32, y: f32, args: &Bound<'_, PyTuple>) -> PyResult<()> { + let rest: Vec = args.extract()?; + let (position, uv) = match rest[..] { + [] => (Vec3::new(x, y, 0.0), None), + [z] => (Vec3::new(x, y, z), None), + [u, v] => (Vec3::new(x, y, 0.0), Some(Vec2::new(u, v))), + [z, u, v] => (Vec3::new(x, y, z), Some(Vec2::new(u, v))), + _ => { + return Err(pyo3::exceptions::PyTypeError::new_err( + "vertex() takes x, y or x, y, z, optionally followed by u, v", + )); + } + }; + graphics_record_command(self.entity, DrawCommand::ShapeVertex { position, uv }) + .map_err(|e| PyRuntimeError::new_err(format!("{e}"))) + } + + /// The normal of the vertices that follow in the current shape. + #[pyo3(signature = (*args))] + pub fn normal(&self, args: &Bound<'_, PyTuple>) -> PyResult<()> { + let normal = extract_vec3(args)?; + graphics_record_command(self.entity, DrawCommand::ShapeNormal(normal)) + .map_err(|e| PyRuntimeError::new_err(format!("{e}"))) + } + + /// `IMAGE` reads `vertex()` texture coordinates in pixels of the texture, `NORMAL` from 0 to 1. + pub fn texture_mode(&self, mode: &str) -> PyResult<()> { + let mode = processing::prelude::TextureMode::parse(mode) + .ok_or_else(|| PyValueError::new_err(format!("unknown texture mode: {mode:?}")))?; + graphics_record_command(self.entity, DrawCommand::TextureMode(mode)) .map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } + /// Two control points and an end point: six numbers, or nine in 3D (`x, y, z` each). + #[pyo3(signature = (cx1, cy1, cx2, cy2, x, y, *args))] + #[allow(clippy::too_many_arguments)] pub fn bezier_vertex( &self, cx1: f32, @@ -1696,34 +1729,67 @@ impl Graphics { cy2: f32, x: f32, y: f32, + args: &Bound<'_, PyTuple>, ) -> PyResult<()> { - graphics_record_command( - self.entity, - DrawCommand::ShapeBezierVertex { - cx1, - cy1, - cx2, - cy2, - x, - y, - }, - ) - .map_err(|e| PyRuntimeError::new_err(format!("{e}"))) + let rest: Vec = args.extract()?; + let [c1, c2, to] = match rest[..] { + [] => [ + Vec3::new(cx1, cy1, 0.0), + Vec3::new(cx2, cy2, 0.0), + Vec3::new(x, y, 0.0), + ], + // nine numbers read as three points + [a, b, c] => [ + Vec3::new(cx1, cy1, cx2), + Vec3::new(cy2, x, y), + Vec3::new(a, b, c), + ], + _ => { + return Err(pyo3::exceptions::PyTypeError::new_err( + "bezier_vertex() takes 6 numbers, or 9 in 3D", + )); + } + }; + graphics_record_command(self.entity, DrawCommand::ShapeBezierVertex { c1, c2, to }) + .map_err(|e| PyRuntimeError::new_err(format!("{e}"))) + } + + /// A control point and an end point: four numbers, or six in 3D (`x, y, z` each). + #[pyo3(signature = (cx, cy, x, y, *args))] + pub fn quadratic_vertex( + &self, + cx: f32, + cy: f32, + x: f32, + y: f32, + args: &Bound<'_, PyTuple>, + ) -> PyResult<()> { + let rest: Vec = args.extract()?; + let [c, to] = match rest[..] { + [] => [Vec3::new(cx, cy, 0.0), Vec3::new(x, y, 0.0)], + // six numbers read as two points + [a, b] => [Vec3::new(cx, cy, x), Vec3::new(y, a, b)], + _ => { + return Err(pyo3::exceptions::PyTypeError::new_err( + "quadratic_vertex() takes 4 numbers, or 6 in 3D", + )); + } + }; + graphics_record_command(self.entity, DrawCommand::ShapeQuadraticVertex { c, to }) + .map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } - pub fn quadratic_vertex(&self, cx: f32, cy: f32, x: f32, y: f32) -> PyResult<()> { + #[pyo3(signature = (x, y, z=0.0))] + pub fn curve_vertex(&self, x: f32, y: f32, z: f32) -> PyResult<()> { graphics_record_command( self.entity, - DrawCommand::ShapeQuadraticVertex { cx, cy, x, y }, + DrawCommand::ShapeCurveVertex { + to: Vec3::new(x, y, z), + }, ) .map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } - pub fn curve_vertex(&self, x: f32, y: f32) -> PyResult<()> { - graphics_record_command(self.entity, DrawCommand::ShapeCurveVertex { x, y }) - .map_err(|e| PyRuntimeError::new_err(format!("{e}"))) - } - pub fn begin_contour(&self) -> PyResult<()> { graphics_record_command(self.entity, DrawCommand::BeginContour) .map_err(|e| PyRuntimeError::new_err(format!("{e}"))) diff --git a/crates/processing_pyo3/src/lib.rs b/crates/processing_pyo3/src/lib.rs index 7826e980..2af14b2f 100644 --- a/crates/processing_pyo3/src/lib.rs +++ b/crates/processing_pyo3/src/lib.rs @@ -2605,13 +2605,31 @@ pub mod processing_py { } #[pyfunction] - #[pyo3(pass_module)] - fn vertex(module: &Bound<'_, PyModule>, x: f32, y: f32) -> PyResult<()> { - graphics!(module).vertex(x, y) + #[pyo3(pass_module, signature = (x, y, *args))] + fn vertex( + module: &Bound<'_, PyModule>, + x: f32, + y: f32, + args: &Bound<'_, PyTuple>, + ) -> PyResult<()> { + graphics!(module).vertex(x, y, args) + } + + #[pyfunction] + #[pyo3(pass_module, signature = (*args))] + fn normal(module: &Bound<'_, PyModule>, args: &Bound<'_, PyTuple>) -> PyResult<()> { + graphics!(module).normal(args) } #[pyfunction] #[pyo3(pass_module)] + fn texture_mode(module: &Bound<'_, PyModule>, mode: &str) -> PyResult<()> { + graphics!(module).texture_mode(mode) + } + + #[pyfunction] + #[pyo3(pass_module, signature = (cx1, cy1, cx2, cy2, x, y, *args))] + #[allow(clippy::too_many_arguments)] fn bezier_vertex( module: &Bound<'_, PyModule>, cx1: f32, @@ -2620,26 +2638,28 @@ pub mod processing_py { cy2: f32, x: f32, y: f32, + args: &Bound<'_, PyTuple>, ) -> PyResult<()> { - graphics!(module).bezier_vertex(cx1, cy1, cx2, cy2, x, y) + graphics!(module).bezier_vertex(cx1, cy1, cx2, cy2, x, y, args) } #[pyfunction] - #[pyo3(pass_module)] + #[pyo3(pass_module, signature = (cx, cy, x, y, *args))] fn quadratic_vertex( module: &Bound<'_, PyModule>, cx: f32, cy: f32, x: f32, y: f32, + args: &Bound<'_, PyTuple>, ) -> PyResult<()> { - graphics!(module).quadratic_vertex(cx, cy, x, y) + graphics!(module).quadratic_vertex(cx, cy, x, y, args) } #[pyfunction] - #[pyo3(pass_module)] - fn curve_vertex(module: &Bound<'_, PyModule>, x: f32, y: f32) -> PyResult<()> { - graphics!(module).curve_vertex(x, y) + #[pyo3(pass_module, signature = (x, y, z=0.0))] + fn curve_vertex(module: &Bound<'_, PyModule>, x: f32, y: f32, z: f32) -> PyResult<()> { + graphics!(module).curve_vertex(x, y, z) } #[pyfunction] diff --git a/crates/processing_render/src/graphics.rs b/crates/processing_render/src/graphics.rs index f7b9eff8..c8eab929 100644 --- a/crates/processing_render/src/graphics.rs +++ b/crates/processing_render/src/graphics.rs @@ -458,8 +458,12 @@ pub fn mode_3d( In(entity): In, mut projections: Query<&mut Projection>, mut transforms: Query<&mut Transform>, + mut states: Query<&mut RenderState>, sizes: Query<&SurfaceSize>, ) -> Result<()> { + if let Ok(mut state) = states.get_mut(entity) { + state.three_d = true; + } let SurfaceSize(width, height) = sizes .get(entity) .map_err(|_| ProcessingError::GraphicsNotFound)?; @@ -504,8 +508,12 @@ pub fn mode_2d( In(entity): In, mut projections: Query<&mut Projection>, mut transforms: Query<&mut Transform>, + mut states: Query<&mut RenderState>, sizes: Query<&SurfaceSize>, ) -> Result<()> { + if let Ok(mut state) = states.get_mut(entity) { + state.three_d = false; + } let SurfaceSize(width, height) = sizes .get(entity) .map_err(|_| ProcessingError::GraphicsNotFound)?; diff --git a/crates/processing_render/src/lib.rs b/crates/processing_render/src/lib.rs index e6322a88..7d706a27 100644 --- a/crates/processing_render/src/lib.rs +++ b/crates/processing_render/src/lib.rs @@ -99,6 +99,7 @@ impl Plugin for ProcessingRenderPlugin { bevy::camera_controller::pan_camera::PanCameraPlugin, text::font::TextPlugin, )) + .add_plugins(render::line::LineMaterialPlugin) .add_plugins(ci::CiPlugin); // Processing strokes every edge of a shape, so the wireframe pass never culls diff --git a/crates/processing_render/src/render/command.rs b/crates/processing_render/src/render/command.rs index 179e078d..054b5677 100644 --- a/crates/processing_render/src/render/command.rs +++ b/crates/processing_render/src/render/command.rs @@ -225,6 +225,36 @@ impl ArcMode { } } +/// How `vertex(x, y, u, v)` texture coordinates are read. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +#[repr(u8)] +pub enum TextureMode { + /// in pixels of the texture + #[default] + Image = 0, + /// from 0 to 1 + Normal = 1, +} + +impl From for TextureMode { + fn from(v: u8) -> Self { + match v { + 1 => Self::Normal, + _ => Self::default(), + } + } +} + +impl TextureMode { + pub fn parse(s: &str) -> Option { + match () { + _ if s.eq_ignore_ascii_case(consts::IMAGE) => Some(Self::Image), + _ if s.eq_ignore_ascii_case(consts::NORMAL) => Some(Self::Normal), + _ => None, + } + } +} + #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] #[repr(u8)] pub enum ShapeMode { @@ -636,27 +666,25 @@ pub enum DrawCommand { close: bool, }, ShapeVertex { - x: f32, - y: f32, + position: Vec3, + /// texture coordinate, in the current texture mode + uv: Option, }, ShapeBezierVertex { - cx1: f32, - cy1: f32, - cx2: f32, - cy2: f32, - x: f32, - y: f32, + c1: Vec3, + c2: Vec3, + to: Vec3, }, ShapeQuadraticVertex { - cx: f32, - cy: f32, - x: f32, - y: f32, + c: Vec3, + to: Vec3, }, ShapeCurveVertex { - x: f32, - y: f32, + to: Vec3, }, + /// The normal of the vertices that follow in this shape. + ShapeNormal(Vec3), + TextureMode(TextureMode), BeginContour, EndContour, PushMatrix, diff --git a/crates/processing_render/src/render/line.rs b/crates/processing_render/src/render/line.rs new file mode 100644 index 00000000..7fc4d137 --- /dev/null +++ b/crates/processing_render/src/render/line.rs @@ -0,0 +1,276 @@ +//! Strokes in 3D: line segments drawn as camera-facing capsules by one material. + +use bevy::asset::RenderAssetUsages; +use bevy::asset::embedded_asset; +use bevy::material::descriptor::RenderPipelineDescriptor; +use bevy::material::specialize::SpecializedMeshPipelineError; +use bevy::mesh::{Indices, MeshVertexAttribute, MeshVertexBufferLayoutRef, PrimitiveTopology}; +use bevy::pbr::{Material, MaterialPipeline, MaterialPipelineKey, MaterialPlugin}; +use bevy::prelude::*; +use bevy::render::render_resource::{AsBindGroup, BlendState, ShaderType, VertexFormat}; +use bevy::shader::{ShaderDefVal, ShaderRef}; + +/// The far end of the segment a vertex belongs to. +pub const ATTRIBUTE_OTHER_END: MeshVertexAttribute = + MeshVertexAttribute::new("Line_OtherEnd", 742_915_301, VertexFormat::Float32x3); + +/// Side, end, weight at this end, weight at the other end. +pub const ATTRIBUTE_LINE_PARAMS: MeshVertexAttribute = + MeshVertexAttribute::new("Line_Params", 742_915_302, VertexFormat::Float32x4); + +/// The color at the far end, for an end the near plane cuts. +pub const ATTRIBUTE_OTHER_COLOR: MeshVertexAttribute = + MeshVertexAttribute::new("Line_OtherColor", 742_915_303, VertexFormat::Float32x4); + +const SHADER: &str = "embedded://processing_render/render/line.wgsl"; + +pub struct LineMaterialPlugin; + +impl Plugin for LineMaterialPlugin { + fn build(&self, app: &mut App) { + embedded_asset!(app, "line.wgsl"); + app.add_plugins(MaterialPlugin::::default()); + + let mut materials = app.world_mut().resource_mut::>(); + let handles = LineMaterials { + opaque: materials.add(LineMaterial::new(false, None)), + blended: materials.add(LineMaterial::new(true, None)), + }; + app.insert_resource(handles); + } +} + +/// The materials strokes share when no blend mode is set. +#[derive(Resource)] +pub struct LineMaterials { + pub opaque: Handle, + /// for strokes with a translucent color + pub blended: Handle, +} + +#[derive(Clone, Copy, Debug, ShaderType)] +pub struct LineUniform { + /// 0 keeps the weight in pixels; 1 scales it with distance + pub perspective: u32, + /// the fraction of its distance a stroke is pulled toward the camera + pub depth_bias: f32, +} + +#[derive(Asset, TypePath, AsBindGroup, Debug, Clone)] +#[bind_group_data(LineMaterialKey)] +pub struct LineMaterial { + #[uniform(0)] + pub uniform: LineUniform, + pub blended: bool, + /// a `blend_mode()` other than the default + pub blend_state: Option, +} + +#[derive(Eq, PartialEq, Hash, Copy, Clone)] +pub struct LineMaterialKey { + blended: bool, + blend_state: Option, +} + +impl From<&LineMaterial> for LineMaterialKey { + fn from(material: &LineMaterial) -> Self { + Self { + blended: material.is_blended(), + blend_state: material.blend_state, + } + } +} + +impl LineMaterial { + pub fn new(blended: bool, blend_state: Option) -> Self { + Self { + uniform: LineUniform { + perspective: 0, + depth_bias: 1e-3, + }, + blended, + blend_state, + } + } + + fn is_blended(&self) -> bool { + self.blended || self.blend_state.is_some() + } +} + +impl Material for LineMaterial { + fn vertex_shader() -> ShaderRef { + SHADER.into() + } + + fn fragment_shader() -> ShaderRef { + SHADER.into() + } + + fn alpha_mode(&self) -> AlphaMode { + if self.is_blended() { + AlphaMode::Blend + } else { + // edges are antialiased by sample mask, not alpha + AlphaMode::Opaque + } + } + + fn enable_prepass() -> bool { + false + } + + fn enable_shadows() -> bool { + false + } + + fn specialize( + _pipeline: &MaterialPipeline, + descriptor: &mut RenderPipelineDescriptor, + layout: &MeshVertexBufferLayoutRef, + key: MaterialPipelineKey, + ) -> Result<(), SpecializedMeshPipelineError> { + let vertex_layout = layout.0.get_layout(&[ + Mesh::ATTRIBUTE_POSITION.at_shader_location(0), + ATTRIBUTE_OTHER_END.at_shader_location(1), + ATTRIBUTE_LINE_PARAMS.at_shader_location(2), + Mesh::ATTRIBUTE_COLOR.at_shader_location(3), + ATTRIBUTE_OTHER_COLOR.at_shader_location(4), + ])?; + descriptor.vertex.buffers = vertex_layout; + // the quads face the camera whichever way the segment runs + descriptor.primitive.cull_mode = None; + + // one source for both stages + let def = if key.bind_group_data.blended { + ShaderDefVal::from("LINE_BLENDED") + } else { + ShaderDefVal::UInt("MSAA_SAMPLES".into(), key.mesh_key.msaa_samples()) + }; + descriptor.vertex.shader_defs.push(def.clone()); + if let Some(fragment) = &mut descriptor.fragment { + fragment.shader_defs.push(def); + if let Some(blend_state) = key.bind_group_data.blend_state { + for target in fragment.targets.iter_mut().flatten() { + target.blend = Some(blend_state); + } + } + } + Ok(()) + } +} + +/// One end of a stroke segment. +#[derive(Debug, Clone, Copy)] +pub struct LineEnd { + pub position: Vec3, + pub color: Color, + pub weight: f32, +} + +/// The vertex data of a mesh of segments. +#[derive(Default)] +struct Segments { + positions: Vec<[f32; 3]>, + other_ends: Vec<[f32; 3]>, + params: Vec<[f32; 4]>, + colors: Vec<[f32; 4]>, + other_colors: Vec<[f32; 4]>, + indices: Vec, +} + +impl Segments { + fn push(&mut self, start: LineEnd, finish: LineEnd, weight_scale: f32) { + let base = self.positions.len() as u32; + for (end, this, other) in [(0.0, start, finish), (1.0, finish, start)] { + let color = this.color.to_linear().to_f32_array(); + let other_color = other.color.to_linear().to_f32_array(); + for side in [-1.0, 1.0] { + self.positions.push(this.position.to_array()); + self.other_ends.push(other.position.to_array()); + self.params.push([ + side, + end, + this.weight * weight_scale, + other.weight * weight_scale, + ]); + self.colors.push(color); + self.other_colors.push(other_color); + } + } + self.indices + .extend([0, 1, 2, 2, 1, 3].map(|i: u32| base + i)); + } + + fn build(self) -> Option { + if self.indices.is_empty() { + return None; + } + Some( + Mesh::new( + PrimitiveTopology::TriangleList, + RenderAssetUsages::default(), + ) + .with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, self.positions) + .with_inserted_attribute(ATTRIBUTE_OTHER_END, self.other_ends) + .with_inserted_attribute(ATTRIBUTE_LINE_PARAMS, self.params) + .with_inserted_attribute(Mesh::ATTRIBUTE_COLOR, self.colors) + .with_inserted_attribute(ATTRIBUTE_OTHER_COLOR, self.other_colors) + .with_inserted_indices(Indices::U32(self.indices)), + ) + } +} + +/// Strokes being accumulated; translucent ones go to a mesh of their own. +pub struct LineMesh { + opaque: Segments, + blended: Segments, + /// physical pixels per unit of stroke weight + weight_scale: f32, +} + +impl LineMesh { + pub fn new(weight_scale: f32) -> Self { + Self { + opaque: Segments::default(), + blended: Segments::default(), + weight_scale, + } + } + + pub fn is_empty(&self) -> bool { + self.opaque.indices.is_empty() && self.blended.indices.is_empty() + } + + /// A segment from `start` to `finish`; color and weight blend along it. + pub fn segment(&mut self, start: LineEnd, finish: LineEnd) { + let ends = [&start, &finish]; + // invisible or non-finite + if ends + .iter() + .all(|end| end.weight <= 0.0 || end.color.alpha() <= 0.0) + || ends + .iter() + .any(|end| !end.position.is_finite() || !end.weight.is_finite()) + { + return; + } + let translucent = ends.iter().any(|end| end.color.alpha() < 1.0); + let segments = if translucent { + &mut self.blended + } else { + &mut self.opaque + }; + segments.push(start, finish, self.weight_scale); + } + + /// A dot as wide as its weight. + pub fn point(&mut self, at: LineEnd) { + self.segment(at, at); + } + + /// The opaque and the translucent segments, each as a mesh if there are any. + pub fn build(self) -> (Option, Option) { + (self.opaque.build(), self.blended.build()) + } +} diff --git a/crates/processing_render/src/render/line.wgsl b/crates/processing_render/src/render/line.wgsl new file mode 100644 index 00000000..550b4c4d --- /dev/null +++ b/crates/processing_render/src/render/line.wgsl @@ -0,0 +1,164 @@ +// stroke segments drawn as camera-facing capsules, widened in screen space with round ends +#import bevy_pbr::mesh_functions::get_world_from_local +#import bevy_pbr::mesh_view_bindings::view + +struct LineMaterial { + // 0 keeps the weight in pixels; 1 scales it with distance + perspective: u32, + // the fraction of its distance a stroke is pulled toward the camera + depth_bias: f32, +}; +@group(#{MATERIAL_BIND_GROUP}) @binding(0) var material: LineMaterial; + +struct Vertex { + @builtin(instance_index) instance_index: u32, + // this vertex's end of the segment + @location(0) position: vec3, + // the other end + @location(1) other: vec3, + // side (-1 or 1), end (0 = start, 1 = finish), weight at this end, weight at the other end + @location(2) params: vec4, + @location(3) color: vec4, + @location(4) other_color: vec4, +}; + +struct VertexOutput { + @builtin(position) clip_position: vec4, + @location(0) color: vec4, + // pixels along the segment from its start, and pixels across it + @location(1) @interpolate(linear) along_across: vec2, + // the segment's length in pixels + @location(2) @interpolate(flat) segment_length: f32, + // half the width in pixels at the start and at the finish + @location(3) @interpolate(flat) half_widths: vec2, +}; + +const EPSILON: f32 = 4.88e-04; + +// clip position with P3D's stroke depth bias +fn clip_position(world_from_local: mat4x4, position: vec3) -> vec4 { + var view_position = view.view_from_world * world_from_local * vec4(position, 1.0); + // orthographic + if view.clip_from_view[3][3] == 1.0 { + view_position.z += material.depth_bias * abs(view_position.z); + } else { + view_position = vec4(view_position.xyz * (1.0 - material.depth_bias), view_position.w); + } + return view.clip_from_view * view_position; +} + +// how far `a` moves toward `b` to reach the near plane; 0 when it stays +fn near_plane_cut(a: vec4, b: vec4) -> f32 { + if a.z > a.w && b.z <= b.w { + let distance_a = a.z - a.w; + let distance_b = b.z - b.w; + return distance_a / (distance_a - distance_b) + EPSILON; + } + return 0.0; +} + +// half the stroke width in pixels at a clip-space point +fn half_width_pixels(weight: f32, clip_w: f32) -> f32 { + if material.perspective == 0u { + return weight * 0.5; + } + // pixels per world unit at this depth + let scale = abs(view.clip_from_view[1][1]) * view.viewport.w * 0.5 / max(clip_w, EPSILON); + return weight * 0.5 * scale; +} + +@vertex +fn vertex(vertex: Vertex) -> VertexOutput { + let world_from_local = get_world_from_local(vertex.instance_index); + let unclipped_this = clip_position(world_from_local, vertex.position); + let unclipped_other = clip_position(world_from_local, vertex.other); + + // an end behind the near plane moves onto it, with the color and weight there + let cut_this = near_plane_cut(unclipped_this, unclipped_other); + let cut_other = near_plane_cut(unclipped_other, unclipped_this); + let clip_this = mix(unclipped_this, unclipped_other, cut_this); + let clip_other = mix(unclipped_other, unclipped_this, cut_other); + let weight_this = mix(vertex.params.z, vertex.params.w, cut_this); + let weight_other = mix(vertex.params.w, vertex.params.z, cut_other); + + let half_viewport = view.viewport.zw * 0.5; + let screen_this = clip_this.xy / clip_this.w * half_viewport; + let screen_other = clip_other.xy / clip_other.w * half_viewport; + + let side = vertex.params.x; + let is_finish = vertex.params.y; + + var toward_other = screen_other - screen_this; + let segment_length = length(toward_other); + if segment_length > 1e-4 { + toward_other = toward_other / segment_length; + } else { + // a point: any direction makes a square that the fragment shader rounds into a dot + toward_other = vec2(1.0 - 2.0 * is_finish, 0.0); + } + // from the segment's start to its finish, the same for all four vertices + let direction = toward_other * (1.0 - 2.0 * is_finish); + let normal = vec2(-direction.y, direction.x); + + let half_width_this = half_width_pixels(weight_this, clip_this.w); + let half_width_other = half_width_pixels(weight_other, clip_other.w); + // the quad covers the wider end, plus a pixel for the antialiased edge + let reach = max(half_width_this, half_width_other) + 1.0; + let offset = normal * side * reach - toward_other * reach; + + var out: VertexOutput; + out.clip_position = vec4( + clip_this.xy + offset / half_viewport * clip_this.w, + clip_this.z, + clip_this.w, + ); + out.color = mix(vertex.color, vertex.other_color, cut_this); + out.along_across = vec2(mix(-reach, segment_length + reach, is_finish), side * reach); + out.segment_length = segment_length; + out.half_widths = mix( + vec2(half_width_this, half_width_other), + vec2(half_width_other, half_width_this), + is_finish, + ); + return out; +} + +struct FragmentOutput { + @location(0) color: vec4, +#ifndef LINE_BLENDED + @builtin(sample_mask) sample_mask: u32, +#endif +}; + +@fragment +fn fragment(in: VertexOutput) -> FragmentOutput { + let along = in.along_across.x; + let across = in.along_across.y; + + // distance to the center line rounds the ends + let nearest = clamp(along, 0.0, in.segment_length); + let distance = length(vec2(along - nearest, across)); + let half_width = mix( + in.half_widths.x, + in.half_widths.y, + nearest / max(in.segment_length, 1e-4), + ); + let coverage = 1.0 - smoothstep(half_width - 0.5, half_width + 0.5, distance); + + var out: FragmentOutput; +#ifdef LINE_BLENDED + if coverage <= 0.0 { + discard; + } + out.color = vec4(in.color.rgb, in.color.a * coverage); +#else + // coverage becomes an MSAA sample mask + let samples = u32(round(coverage * f32(#{MSAA_SAMPLES}))); + if samples == 0u { + discard; + } + out.color = in.color; + out.sample_mask = (1u << samples) - 1u; +#endif + return out; +} diff --git a/crates/processing_render/src/render/material.rs b/crates/processing_render/src/render/material.rs index 41849180..45809290 100644 --- a/crates/processing_render/src/render/material.rs +++ b/crates/processing_render/src/render/material.rs @@ -30,6 +30,8 @@ pub enum MaterialKey { blend_state: Option, /// blend even with an opaque albedo (e.g. translucent vertex colors) transparent: bool, + /// light both faces, like P3D + two_sided: bool, }, Custom { entity: Entity, @@ -46,6 +48,7 @@ pub struct PbrFields { pub uv_transform: Affine2, pub blend_state: Option, pub transparent: bool, + pub two_sided: bool, } impl Default for PbrFields { @@ -59,6 +62,7 @@ impl Default for PbrFields { uv_transform: Affine2::IDENTITY, blend_state: None, transparent: false, + two_sided: false, } } } @@ -74,6 +78,7 @@ impl From for MaterialKey { uv_transform: f.uv_transform, blend_state: f.blend_state, transparent: f.transparent, + two_sided: f.two_sided, } } } @@ -90,9 +95,11 @@ impl MaterialKey { uv_transform, blend_state, transparent, + two_sided, } => PbrFields { albedo: *albedo, transparent: *transparent, + two_sided: *two_sided, roughness: *roughness, metallic: *metallic, emissive: *emissive, @@ -165,6 +172,31 @@ impl MaterialKey { } } + /// Whether the material samples a texture set with `texture()`. + pub fn has_texture(&self) -> bool { + match self { + MaterialKey::Color { + background_image, .. + } => background_image.is_some(), + MaterialKey::Pbr { + base_color_texture, .. + } => base_color_texture.is_some(), + MaterialKey::Custom { .. } => false, + } + } + + /// The key with both faces lit; unlit keys are unchanged. + pub fn two_sided(self) -> MaterialKey { + match self { + MaterialKey::Pbr { .. } => { + let mut pbr = self.as_pbr(); + pbr.two_sided = true; + pbr.into() + } + other => other, + } + } + pub fn blend_state(&self) -> Option { match self { MaterialKey::Color { blend_state, .. } => *blend_state, @@ -202,6 +234,7 @@ impl MaterialKey { uv_transform, blend_state, transparent, + two_sided, } => { let base_color = Color::srgba( albedo[0] as f32 / 255.0, @@ -213,6 +246,7 @@ impl MaterialKey { base_color, unlit: false, cull_mode: None, + double_sided: *two_sided, alpha_mode: if blend_state.is_some() || albedo[3] < 255 || *transparent { AlphaMode::Blend } else { diff --git a/crates/processing_render/src/render/mesh_builder.rs b/crates/processing_render/src/render/mesh_builder.rs index a3aa1563..41031f6e 100644 --- a/crates/processing_render/src/render/mesh_builder.rs +++ b/crates/processing_render/src/render/mesh_builder.rs @@ -9,46 +9,124 @@ use lyon::tessellation::{ }, }; +/// One vertex of a batch mesh; the color is linear. +#[derive(Debug, Clone, Copy)] +pub struct MeshVertex { + pub position: [f32; 3], + pub color: [f32; 4], + pub normal: [f32; 3], + pub uv: [f32; 2], +} + +impl MeshVertex { + /// A vertex in the z = 0 plane. + fn flat(x: f32, y: f32, color: [f32; 4]) -> Self { + Self { + position: [x, y, 0.0], + color, + normal: [0.0, 0.0, 1.0], + uv: [0.0, 0.0], + } + } +} + +/// Where a tessellated vertex gets its data from. +enum Source<'a> { + /// one color + Color([f32; 4]), + /// linear rgba from the path's first four attributes + PathColors, + /// built from the tessellated position and the path's interpolated attributes + Mapped(&'a dyn Fn(lyon::math::Point, &[f32]) -> MeshVertex), +} + pub struct MeshBuilder<'a> { mesh: &'a mut Mesh, - color: Color, - begin_vertex_count: u32, + source: Source<'a>, + /// where the mesh stood when the tessellation began, to undo a failed one + begin_vertex_count: usize, + begin_index_count: usize, + reverse_winding: bool, } impl<'a> MeshBuilder<'a> { pub fn new(mesh: &'a mut Mesh, color: Color) -> Self { Self { mesh, - color, + source: Source::Color(color.to_linear().to_f32_array()), + begin_vertex_count: 0, + begin_index_count: 0, + reverse_winding: false, + } + } + + /// Colors come from the path's attributes, interpolated across the shape. + pub fn with_path_colors(mesh: &'a mut Mesh) -> Self { + Self { + mesh, + source: Source::PathColors, begin_vertex_count: 0, + begin_index_count: 0, + reverse_winding: false, } } - fn push_vertex(&mut self, position: [f32; 3]) -> VertexId { + /// Every vertex is built by `map` from its position and interpolated attributes. + pub fn with_vertex_map( + mesh: &'a mut Mesh, + map: &'a dyn Fn(lyon::math::Point, &[f32]) -> MeshVertex, + ) -> Self { + Self { + mesh, + source: Source::Mapped(map), + begin_vertex_count: 0, + begin_index_count: 0, + reverse_winding: false, + } + } + + /// Emits each triangle wound the other way. + pub fn reversed(mut self) -> Self { + self.reverse_winding = true; + self + } + + fn vertex(&self, position: lyon::math::Point, attributes: &[f32]) -> MeshVertex { + match (&self.source, attributes) { + (Source::Color(color), _) => MeshVertex::flat(position.x, position.y, *color), + (Source::PathColors, [r, g, b, a, ..]) => { + MeshVertex::flat(position.x, position.y, [*r, *g, *b, *a]) + } + (Source::PathColors, _) => MeshVertex::flat(position.x, position.y, [1.0; 4]), + (Source::Mapped(map), attributes) => map(position, attributes), + } + } + + fn push_vertex(&mut self, vertex: MeshVertex) -> VertexId { let id = VertexId::from_usize(self.vertex_count()); if let Some(VertexAttributeValues::Float32x3(positions)) = self.mesh.attribute_mut(Mesh::ATTRIBUTE_POSITION) { - positions.push(position); + positions.push(vertex.position); } if let Some(VertexAttributeValues::Float32x4(colors)) = self.mesh.attribute_mut(Mesh::ATTRIBUTE_COLOR) { - colors.push(self.color.to_linear().to_f32_array()); + colors.push(vertex.color); } if let Some(VertexAttributeValues::Float32x3(normals)) = self.mesh.attribute_mut(Mesh::ATTRIBUTE_NORMAL) { - normals.push([0.0, 0.0, 1.0]); // flat normal for 2d + normals.push(vertex.normal); } if let Some(VertexAttributeValues::Float32x2(uvs)) = self.mesh.attribute_mut(Mesh::ATTRIBUTE_UV_0) { - uvs.push([0.0, 0.0]); + uvs.push(vertex.uv); } id @@ -73,35 +151,55 @@ impl<'a> MeshBuilder<'a> { impl<'a> GeometryBuilder for MeshBuilder<'a> { fn begin_geometry(&mut self) { - self.begin_vertex_count = self.vertex_count() as u32; + self.begin_vertex_count = self.vertex_count(); + self.begin_index_count = match self.mesh.indices() { + Some(indices) => indices.len(), + None => 0, + }; } fn add_triangle(&mut self, a: VertexId, b: VertexId, c: VertexId) { + let (b, c) = if self.reverse_winding { (c, b) } else { (b, c) }; self.push_index(a.to_usize() as u32); self.push_index(b.to_usize() as u32); self.push_index(c.to_usize() as u32); } + /// Drops what a failed tessellation added, leaving the rest of the batch intact. fn abort_geometry(&mut self) { - todo!("Implement abort_geometry if needed"); + let vertices = self.begin_vertex_count; + for (_, values) in self.mesh.attributes_mut() { + match values { + VertexAttributeValues::Float32x2(values) => values.truncate(vertices), + VertexAttributeValues::Float32x3(values) => values.truncate(vertices), + VertexAttributeValues::Float32x4(values) => values.truncate(vertices), + _ => {} + } + } + if let Some(Indices::U32(indices)) = self.mesh.indices_mut() { + indices.truncate(self.begin_index_count); + } } } impl<'a> FillGeometryBuilder for MeshBuilder<'a> { - fn add_fill_vertex(&mut self, vertex: FillVertex) -> Result { - let pos = vertex.position(); - let position = [pos.x, pos.y, 0.0]; - Ok(self.push_vertex(position)) + fn add_fill_vertex( + &mut self, + mut vertex: FillVertex, + ) -> Result { + let position = vertex.position(); + let vertex = self.vertex(position, vertex.interpolated_attributes()); + Ok(self.push_vertex(vertex)) } } impl<'a> StrokeGeometryBuilder for MeshBuilder<'a> { fn add_stroke_vertex( &mut self, - vertex: StrokeVertex, + mut vertex: StrokeVertex, ) -> Result { - let pos = vertex.position(); - let position = [pos.x, pos.y, 0.0]; - Ok(self.push_vertex(position)) + let position = vertex.position(); + let vertex = self.vertex(position, vertex.interpolated_attributes()); + Ok(self.push_vertex(vertex)) } } diff --git a/crates/processing_render/src/render/mod.rs b/crates/processing_render/src/render/mod.rs index 7e53a9db..249874d8 100644 --- a/crates/processing_render/src/render/mod.rs +++ b/crates/processing_render/src/render/mod.rs @@ -1,5 +1,6 @@ pub mod command; pub mod filter; +pub mod line; pub mod material; pub mod mesh_builder; pub mod primitive; @@ -22,13 +23,14 @@ use bevy::{ render::render_resource::BlendState, window::WindowRef, }; -use command::{CommandBuffer, DrawCommand, ShapeMode}; +use command::{CommandBuffer, DrawCommand, ShapeMode, TextureMode}; +use line::{LineMaterial, LineMaterials, LineMesh}; use material::{MaterialKey, ProcessingExtendedMaterial}; use primitive::{ - ShapeBuilder, TessellationMode, VertexType, arc_fill, arc_stroke, bezier, box_mesh, - build_direct_fill, build_direct_stroke, build_polygon_fill, build_polygon_stroke, capsule_mesh, - cone_mesh, conical_frustum_mesh, curve, cylinder_mesh, ellipse, empty_mesh, line, plane_mesh, - quad, sphere_mesh, tetrahedron_mesh, torus_mesh, triangle, + ShapeBuilder, TessellationMode, VertexStyle, VertexType, arc_fill, arc_stroke, bezier, + box_mesh, build_shape_fill, build_shape_lines, build_shape_stroke, capsule_mesh, cone_mesh, + conical_frustum_mesh, curve, cylinder_mesh, ellipse, empty_mesh, line, plane_mesh, quad, + sphere_mesh, tetrahedron_mesh, torus_mesh, triangle, }; use style::{Fill, StyleStack}; use transform::TransformStack; @@ -72,12 +74,23 @@ pub struct RenderResources<'w, 's> { meshes: ResMut<'w, Assets>, materials: ResMut<'w, Assets>, custom_materials: ResMut<'w, Assets>, + line_materials: Res<'w, LineMaterials>, + line_material_assets: ResMut<'w, Assets>, + canvas_sizes: Query< + 'w, + 's, + ( + &'static crate::graphics::Graphics, + Option<&'static crate::graphics::SurfaceSize>, + ), + >, particles_materials: ResMut<'w, Assets>, particle_buffers: Query<'w, 's, &'static crate::compute::Buffer>, } struct BatchState { current_mesh: Option, + lines: Option, material_key: Option, transform: Affine3A, draw_index: u32, @@ -85,10 +98,18 @@ struct BatchState { graphics_entity: Entity, } +/// Camera-facing strokes that share a transform and a blend mode. +struct LineBatch { + mesh: LineMesh, + transform: Affine3A, + blend_state: Option, +} + impl BatchState { fn new(graphics_entity: Entity, render_layers: RenderLayers) -> Self { Self { current_mesh: None, + lines: None, material_key: None, transform: Affine3A::IDENTITY, draw_index: 0, @@ -155,6 +176,12 @@ pub struct RenderState { pub shape_builder: Option, /// Like Processing, every frame starts with a fresh depth buffer pub clear_depth: bool, + /// set by `mode_3d`; shape strokes face the camera + pub three_d: bool, + /// set by `normal()` inside a shape, for the vertices that follow + pub shape_normal: Option, + /// outside the style stack, like P3D + pub texture_mode: TextureMode, } impl RenderState { @@ -164,6 +191,9 @@ impl RenderState { transform: TransformStack::new(), shape_builder: None, clear_depth: true, + three_d: false, + shape_normal: None, + texture_mode: TextureMode::default(), } } @@ -171,6 +201,9 @@ impl RenderState { self.style = StyleStack::new(); self.transform = TransformStack::new(); self.shape_builder = None; + self.three_d = false; + self.shape_normal = None; + self.texture_mode = TextureMode::default(); } pub fn begin_frame(&mut self) { @@ -278,8 +311,9 @@ pub fn flush_draw_commands( while let Some(cmd) = pending.next() { // check whether we are the first flush after a present - let opens_pass = - |batch: &BatchState| batch.draw_index == 0 && batch.current_mesh.is_none(); + let opens_pass = |batch: &BatchState| { + batch.draw_index == 0 && batch.current_mesh.is_none() && batch.lines.is_none() + }; match cmd { DrawCommand::Light(entity) => { if let Ok((light, transform)) = p_lights.get(entity) { @@ -336,7 +370,10 @@ pub fn flush_draw_commands( state.style.material_key = pbr.into(); } DrawCommand::Texture(entity) => { + state.style.texture_size = None; if let Ok(img) = p_images.get(entity) { + state.style.texture_size = + Some(Vec2::new(img.size.width as f32, img.size.height as f32)); // a texture leaves the material lit or unlit as it was match &mut state.style.material_key { MaterialKey::Color { @@ -356,25 +393,31 @@ pub fn flush_draw_commands( } } } - DrawCommand::NoTexture => match &mut state.style.material_key { - MaterialKey::Color { - transparent, - background_image, - .. - } => { - *background_image = None; - *transparent = false; - } - MaterialKey::Pbr { - base_color_texture, - transparent, - .. - } => { - *base_color_texture = None; - *transparent = false; + DrawCommand::TextureMode(mode) => { + state.texture_mode = mode; + } + DrawCommand::NoTexture => { + state.style.texture_size = None; + match &mut state.style.material_key { + MaterialKey::Color { + transparent, + background_image, + .. + } => { + *background_image = None; + *transparent = false; + } + MaterialKey::Pbr { + base_color_texture, + transparent, + .. + } => { + *base_color_texture = None; + *transparent = false; + } + MaterialKey::Custom { .. } => {} } - MaterialKey::Custom { .. } => {} - }, + } DrawCommand::TextureTransform(transform) => match &mut state.style.material_key { MaterialKey::Color { uv_transform, .. } => *uv_transform = transform, key => { @@ -601,13 +644,9 @@ pub fn flush_draw_commands( ); } DrawCommand::Point { x, y } => { - if let Some((color, d)) = state.style.stroke() { - let material_key = material_key_with_color( - &state.style.material_key, - color, - state.style.blend_state, - ); - + if let Some((color, d)) = state.style.stroke() + && let Some(material_key) = material_key_with_colors(&state, &[color]) + { if needs_batch(&batch, &state, &material_key) { start_batch( &mut res, @@ -748,39 +787,33 @@ pub fn flush_draw_commands( } DrawCommand::BeginShape { kind } => { state.shape_builder = Some(ShapeBuilder::new(kind)); + state.shape_normal = None; } - DrawCommand::ShapeVertex { x, y } => { + DrawCommand::ShapeNormal(normal) => { + state.shape_normal = normal.try_normalize(); + } + DrawCommand::ShapeVertex { position, uv } => { + let style = vertex_style(&state, uv); if let Some(ref mut sb) = state.shape_builder { - sb.push_vertex(VertexType::Normal(x, y)); + sb.push_vertex(VertexType::Normal(position), style); } } - DrawCommand::ShapeBezierVertex { - cx1, - cy1, - cx2, - cy2, - x, - y, - } => { + DrawCommand::ShapeBezierVertex { c1, c2, to } => { + let style = vertex_style(&state, None); if let Some(ref mut sb) = state.shape_builder { - sb.push_vertex(VertexType::CubicBezier { - cx1, - cy1, - cx2, - cy2, - x, - y, - }); + sb.push_vertex(VertexType::CubicBezier { c1, c2, to }, style); } } - DrawCommand::ShapeQuadraticVertex { cx, cy, x, y } => { + DrawCommand::ShapeQuadraticVertex { c, to } => { + let style = vertex_style(&state, None); if let Some(ref mut sb) = state.shape_builder { - sb.push_vertex(VertexType::QuadraticBezier { cx, cy, x, y }); + sb.push_vertex(VertexType::QuadraticBezier { c, to }, style); } } - DrawCommand::ShapeCurveVertex { x, y } => { + DrawCommand::ShapeCurveVertex { to } => { + let style = vertex_style(&state, None); if let Some(ref mut sb) = state.shape_builder { - sb.push_vertex(VertexType::CurveVertex(x, y)); + sb.push_vertex(VertexType::CurveVertex(to), style); } } DrawCommand::BeginContour => { @@ -796,111 +829,40 @@ pub fn flush_draw_commands( DrawCommand::EndShape { close } => { if let Some(sb) = state.shape_builder.take() { let stroke_config = state.style.stroke_config; - use crate::render::command::ShapeKind; - - match sb.kind { - ShapeKind::Polygon => { - add_fill( - &mut res, - &mut batch, - &state, - |mesh, color| { - build_polygon_fill(mesh, &sb, close, color, &stroke_config) - }, - &p_material_handles, - ); - add_stroke( - &mut res, - &mut batch, - &state, - |mesh, color, weight| { - build_polygon_stroke( - mesh, - &sb, - close, - color, - weight, - &stroke_config, - ) - }, - &p_material_handles, - ); + // a shape that leaves the z = 0 plane is in space whatever the mode + let in_space = state.three_d || !sb.is_flat(); + let matrix_scale = matrix_scale(state.transform.current()); + + let textured = state.style.material_key.has_texture(); + if (state.style.fill.color().is_some() || textured) + && let Some(key) = material_key_with_colors(&state, &sb.fill_colors()) + { + // a lit shape in space is lit on both faces + let key = if in_space { key.two_sided() } else { key }; + if needs_batch(&batch, &state, &key) { + start_batch(&mut res, &mut batch, &state, key, &p_material_handles); } - ShapeKind::Points => { - if let Some((color, d)) = state.style.stroke() { - let material_key = material_key_with_color( - &state.style.material_key, - color, - state.style.blend_state, - ); - if needs_batch(&batch, &state, &material_key) { - start_batch( - &mut res, - &mut batch, - &state, - material_key, - &p_material_handles, - ); - } - if let Some(ref mut mesh) = batch.current_mesh { - for v in &sb.contours[0].vertices { - if let VertexType::Normal(x, y) = v { - ellipse( - mesh, - *x, - *y, - d, - d, - color, - TessellationMode::Fill, - &stroke_config, - ); - } - } - } - } + if let Some(ref mut mesh) = batch.current_mesh { + build_shape_fill(mesh, &sb, close, in_space, matrix_scale); } - ShapeKind::Lines => { - add_stroke( - &mut res, - &mut batch, - &state, - |mesh, color, weight| { - build_direct_stroke( - mesh, - &sb, - color, - weight, - &stroke_config, - ) - }, - &p_material_handles, - ); + } + + if state.style.stroke_color.is_some() && in_space { + // in space a stroke faces the camera + build_shape_lines( + line_batch(&mut res, &mut batch, &state), + &sb, + close, + matrix_scale, + ); + } else if state.style.stroke_color.is_some() + && let Some(key) = material_key_with_colors(&state, &sb.stroke_colors()) + { + if needs_batch(&batch, &state, &key) { + start_batch(&mut res, &mut batch, &state, key, &p_material_handles); } - _ => { - // Triangles, TriangleFan, TriangleStrip, Quads, QuadStrip - add_fill( - &mut res, - &mut batch, - &state, - |mesh, color| build_direct_fill(mesh, &sb, color), - &p_material_handles, - ); - add_stroke( - &mut res, - &mut batch, - &state, - |mesh, color, weight| { - build_direct_stroke( - mesh, - &sb, - color, - weight, - &stroke_config, - ) - }, - &p_material_handles, - ); + if let Some(ref mut mesh) = batch.current_mesh { + build_shape_stroke(mesh, &sb, close, &stroke_config); } } } @@ -1453,6 +1415,7 @@ pub fn flush_draw_commands( } flush_batch(&mut res, &mut batch, &p_material_handles); + flush_lines(&mut res, &mut batch); // a pass cut short by a mid-frame `background()` is wiped by the next one, so it // must not reach the window @@ -1637,6 +1600,53 @@ fn particles_fill_material( Some(handle.untyped()) } +/// The style a vertex is added with. +fn vertex_style(state: &RenderState, uv: Option) -> VertexStyle { + let style = &state.style; + // only a texture the current material still has counts + let texture_size = style + .texture_size + .filter(|_| style.material_key.has_texture()); + let fill = if style.material_key.has_texture() { + // a textured vertex takes the tint, not the fill + style.tint_color.unwrap_or(Color::WHITE) + } else { + style.fill.color().unwrap_or(Color::NONE) + }; + let uv = uv.map(|uv| match (state.texture_mode, texture_size) { + (TextureMode::Image, Some(size)) => uv / size, + _ => uv, + }); + VertexStyle { + fill, + stroke: style.stroke_color.unwrap_or(Color::NONE), + weight: match style.stroke_color { + Some(_) => style.stroke_weight, + None => 0.0, + }, + normal: state.shape_normal, + uv, + } +} + +/// The material key for vertex-colored geometry; `None` without colors. +fn material_key_with_colors(state: &RenderState, colors: &[Color]) -> Option { + if colors.is_empty() { + return None; + } + // vertex colors carry the color + let key = material_key_with_color( + &state.style.material_key, + Color::WHITE, + state.style.blend_state, + ); + Some(if colors.iter().any(|color| color.alpha() < 1.0) { + key.transparent() + } else { + key + }) +} + fn material_key_with_fill(state: &RenderState) -> MaterialKey { let color = state.style.fill.color().unwrap_or(Color::WHITE); material_key_with_color(&state.style.material_key, color, state.style.blend_state) @@ -1652,8 +1662,9 @@ fn add_fill( let Some(color) = state.style.fill.color() else { return; }; - let material_key = - material_key_with_color(&state.style.material_key, color, state.style.blend_state); + let Some(material_key) = material_key_with_colors(state, &[color]) else { + return; + }; if needs_batch(batch, state, &material_key) { start_batch(res, batch, state, material_key, material_handles); @@ -1691,8 +1702,9 @@ fn add_stroke_weighted( 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); + let Some(material_key) = material_key_with_colors(state, &[color]) else { + return; + }; if needs_batch(batch, state, &material_key) { start_batch(res, batch, state, material_key, material_handles); @@ -1703,6 +1715,93 @@ fn add_stroke_weighted( } } +/// How much a matrix scales lengths: the cube root of its volume scale. +fn matrix_scale(transform: Affine3A) -> f32 { + transform.matrix3.determinant().abs().cbrt() +} + +/// The line mesh strokes are appended to. +fn line_batch<'a>( + res: &mut RenderResources, + batch: &'a mut BatchState, + state: &RenderState, +) -> &'a mut LineMesh { + let transform = state.transform.current(); + let blend_state = state.style.blend_state; + if batch + .lines + .as_ref() + .is_some_and(|lines| lines.transform != transform || lines.blend_state != blend_state) + { + flush_lines(res, batch); + } + let pixel_density = res + .canvas_sizes + .get(batch.graphics_entity) + .ok() + .and_then(|(graphics, logical)| { + logical.map(|size| graphics.size.width as f32 / size.0.max(1) as f32) + }) + .unwrap_or(1.0); + let transform_scale = matrix_scale(transform); + &mut batch + .lines + .get_or_insert_with(|| LineBatch { + mesh: LineMesh::new(pixel_density * transform_scale), + transform, + blend_state, + }) + .mesh +} + +/// Spawns the accumulated strokes. +fn flush_lines(res: &mut RenderResources, batch: &mut BatchState) { + let Some(lines) = batch.lines.take() else { + return; + }; + if lines.mesh.is_empty() { + return; + } + // layered at flush, above the fills batched so far + let (scale, rotation, translation) = lines.transform.to_scale_rotation_translation(); + let transform = Transform { + translation: translation + Vec3::new(0.0, 0.0, layer_z(batch.draw_index)), + rotation, + scale, + }; + batch.draw_index += 1; + + let (opaque, blended) = lines.mesh.build(); + let materials = match lines.blend_state { + None => [ + res.line_materials.opaque.clone(), + res.line_materials.blended.clone(), + ], + // a blend mode applies to every segment + Some(blend_state) => { + let material = res + .line_material_assets + .add(LineMaterial::new(true, Some(blend_state))); + [material.clone(), material] + } + }; + for (mesh, material) in [opaque, blended].into_iter().zip(materials) { + let Some(mesh) = mesh else { + continue; + }; + res.commands.spawn(( + Mesh3d(res.meshes.add(mesh)), + MeshMaterial3d(material), + transform, + FlushTransient(batch.graphics_entity), + batch.render_layers.clone(), + bevy::light::NotShadowCaster, + // the bounds of the endpoints leave out the stroke's width + NoFrustumCulling, + )); + } +} + /// 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()) diff --git a/crates/processing_render/src/render/primitive/mod.rs b/crates/processing_render/src/render/primitive/mod.rs index c4f20d63..e7b61f26 100644 --- a/crates/processing_render/src/render/primitive/mod.rs +++ b/crates/processing_render/src/render/primitive/mod.rs @@ -21,14 +21,13 @@ pub use line::line; use lyon::{ path::Path, tessellation::{ - FillOptions, FillTessellator, LineCap, LineJoin, StrokeOptions, StrokeTessellator, + FillOptions, FillRule, FillTessellator, LineCap, LineJoin, StrokeOptions, StrokeTessellator, }, }; pub use quad::quad; pub use rect::rect; pub use shape::{ - ShapeBuilder, VertexType, build_direct_fill, build_direct_stroke, build_polygon_fill, - build_polygon_stroke, + ShapeBuilder, VertexStyle, VertexType, build_shape_fill, build_shape_lines, build_shape_stroke, }; pub use shape3d::{ box_mesh, capsule_mesh, cone_mesh, conical_frustum_mesh, cylinder_mesh, grid_mesh, plane_mesh, @@ -37,7 +36,7 @@ pub use shape3d::{ pub use triangle::triangle; use super::command::{StrokeCapMode, StrokeJoinMode}; -use super::mesh_builder::MeshBuilder; +use super::mesh_builder::{MeshBuilder, MeshVertex}; pub enum TessellationMode { Fill, @@ -95,7 +94,7 @@ pub fn tessellate_path( let mut tessellator = FillTessellator::new(); tessellator .tessellate_path(path, &FillOptions::default(), &mut builder) - .expect("Failed to tessellate fill"); + .unwrap_or_else(|error| debug!("shape not tessellated: {error:?}")); } TessellationMode::Stroke(weight) => { let mut tessellator = StrokeTessellator::new(); @@ -106,11 +105,55 @@ pub fn tessellate_path( tessellator .tessellate_path(path, &options, &mut builder) - .expect("Failed to tessellate stroke"); + .unwrap_or_else(|error| debug!("shape not tessellated: {error:?}")); } } } +/// How wide a path with per-vertex colors is stroked. +#[derive(Debug, Clone, Copy)] +pub enum StrokeWeight { + Constant(f32), + /// the path's fifth attribute, interpolated along each segment + PerVertex, +} + +/// Fills a path through a vertex map. +pub fn tessellate_mapped_fill( + mesh: &mut Mesh, + path: &Path, + map: &dyn Fn(lyon::math::Point, &[f32]) -> MeshVertex, +) { + // the tessellator winds its triangles against the plane normal the vertices carry + let mut builder = MeshBuilder::with_vertex_map(mesh, map).reversed(); + // like P3D, an overlap is filled and a hole is a contour wound the other way + let options = FillOptions::default().with_fill_rule(FillRule::NonZero); + FillTessellator::new() + .tessellate_with_ids(path.id_iter(), path, Some(path), &options, &mut builder) + .unwrap_or_else(|error| debug!("shape not tessellated: {error:?}")); +} + +/// Strokes a path whose endpoints carry linear [r, g, b, a] and a weight. +pub fn tessellate_colored_stroke( + mesh: &mut Mesh, + path: &Path, + weight: StrokeWeight, + stroke_config: &StrokeConfig, +) { + let options = StrokeOptions::default() + .with_line_cap(stroke_config.line_cap.to_lyon()) + .with_line_join(stroke_config.line_join.to_lyon()); + let options = match weight { + StrokeWeight::Constant(weight) => options.with_line_width(weight), + // the attribute scales the line width + StrokeWeight::PerVertex => options.with_line_width(1.0).with_variable_line_width(4), + }; + let mut builder = MeshBuilder::with_path_colors(mesh); + StrokeTessellator::new() + .tessellate_with_ids(path.id_iter(), path, Some(path), &options, &mut builder) + .unwrap_or_else(|error| debug!("shape not tessellated: {error:?}")); +} + pub fn empty_mesh() -> Mesh { let mut mesh = Mesh::new( PrimitiveTopology::TriangleList, diff --git a/crates/processing_render/src/render/primitive/shape.rs b/crates/processing_render/src/render/primitive/shape.rs index 5cc5a459..e4f4cf07 100644 --- a/crates/processing_render/src/render/primitive/shape.rs +++ b/crates/processing_render/src/render/primitive/shape.rs @@ -5,31 +5,85 @@ use bevy::{ use lyon::{geom::Point, path::Path}; use crate::render::command::ShapeKind; -use crate::render::primitive::{StrokeConfig, TessellationMode, tessellate_path}; +use crate::render::line::{LineEnd, LineMesh}; +use crate::render::mesh_builder::MeshVertex; +use crate::render::primitive::{ + StrokeConfig, StrokeWeight, TessellationMode, tessellate_colored_stroke, tessellate_mapped_fill, +}; #[derive(Debug, Clone)] pub enum VertexType { - Normal(f32, f32), - CubicBezier { - cx1: f32, - cy1: f32, - cx2: f32, - cy2: f32, - x: f32, - y: f32, - }, - QuadraticBezier { - cx: f32, - cy: f32, - x: f32, - y: f32, - }, - CurveVertex(f32, f32), + Normal(Vec3), + CubicBezier { c1: Vec3, c2: Vec3, to: Vec3 }, + QuadraticBezier { c: Vec3, to: Vec3 }, + CurveVertex(Vec3), +} + +impl VertexType { + /// Every point of the vertex, control points included. + fn points(&self) -> impl Iterator { + let points = match *self { + VertexType::Normal(to) | VertexType::CurveVertex(to) => [None, None, Some(to)], + VertexType::QuadraticBezier { c, to } => [None, Some(c), Some(to)], + VertexType::CubicBezier { c1, c2, to } => [Some(c1), Some(c2), Some(to)], + }; + points.into_iter().flatten() + } +} + +/// What was current when a vertex was added. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct VertexStyle { + /// the tint when textured; transparent with no fill + pub fill: Color, + /// transparent when the vertex was added with no stroke + pub stroke: Color, + pub weight: f32, + /// `None` takes the normal of the face + pub normal: Option, + /// normalized; `None` takes the shape kind's default + pub uv: Option, +} + +/// A zero-width stroke tessellates to NaN vertices. +const MIN_VERTEX_WEIGHT: f32 = 1e-3; + +impl VertexStyle { + fn fill_color(&self) -> [f32; 4] { + self.fill.to_linear().to_f32_array() + } + + /// Color, then the weight the tessellator scales the line by. + fn stroke_attributes(&self) -> [f32; 5] { + let [r, g, b, a] = self.stroke.to_linear().to_f32_array(); + [r, g, b, a, self.weight.max(MIN_VERTEX_WEIGHT)] + } + + /// The style a fraction `t` of the way to `other`. + fn mix(&self, other: &VertexStyle, t: f32) -> VertexStyle { + let color = |a: Color, b: Color| Color::from(a.to_linear().mix(&b.to_linear(), t)); + VertexStyle { + fill: color(self.fill, other.fill), + stroke: color(self.stroke, other.stroke), + weight: self.weight + (other.weight - self.weight) * t, + normal: match (self.normal, other.normal) { + (Some(a), Some(b)) => Some(a.lerp(b, t).normalize_or(a)), + (normal, _) => normal, + }, + // a missing texture coordinate counts as (0, 0) + uv: match (self.uv, other.uv) { + (None, None) => None, + (a, b) => Some(a.unwrap_or(Vec2::ZERO).lerp(b.unwrap_or(Vec2::ZERO), t)), + }, + } + } } #[derive(Debug, Clone)] pub struct Contour { pub vertices: Vec, + /// one per vertex + pub styles: Vec, } #[derive(Debug, Clone)] @@ -45,63 +99,385 @@ impl ShapeBuilder { kind, contours: vec![Contour { vertices: Vec::new(), + styles: Vec::new(), }], in_contour: false, } } - pub fn push_vertex(&mut self, vt: VertexType) { + pub fn push_vertex(&mut self, vt: VertexType, style: VertexStyle) { let contour = if self.in_contour { self.contours.last_mut().unwrap() } else { &mut self.contours[0] }; contour.vertices.push(vt); + contour.styles.push(style); } pub fn begin_contour(&mut self) { self.in_contour = true; self.contours.push(Contour { vertices: Vec::new(), + styles: Vec::new(), }); } pub fn end_contour(&mut self) { self.in_contour = false; } + + fn points(&self) -> impl Iterator { + self.contours + .iter() + .flat_map(|contour| contour.vertices.iter().flat_map(VertexType::points)) + } + + /// Whether every point, control points included, lies in the z = 0 plane. + pub fn is_flat(&self) -> bool { + self.points().all(|point| point.z == 0.0) + } + + fn is_finite(&self) -> bool { + self.points().all(Vec3::is_finite) + } + + fn styles(&self) -> impl Iterator { + self.contours.iter().flat_map(|contour| &contour.styles) + } + + pub fn fill_colors(&self) -> Vec { + self.styles().map(|style| style.fill).collect() + } + + pub fn stroke_colors(&self) -> Vec { + self.styles().map(|style| style.stroke).collect() + } +} + +/// The plane a polygon is tessellated in. +struct Plane { + origin: Vec3, + u: Vec3, + v: Vec3, + normal: Vec3, +} + +impl Plane { + /// The plane 2D shapes are drawn in. + const XY: Plane = Plane { + origin: Vec3::ZERO, + u: Vec3::X, + v: Vec3::Y, + normal: Vec3::Z, + }; + + fn of(builder: &ShapeBuilder) -> Plane { + if builder.is_flat() { + return Plane::XY; + } + + // Newell's method: the normal of the plane that best fits the drawn outline + let outline: Vec = flatten_contour(&builder.contours[0], 1.0) + .into_iter() + .map(|(point, _)| point) + .collect(); + let mut normal = Vec3::ZERO; + for (i, a) in outline.iter().enumerate() { + let b = outline[(i + 1) % outline.len()]; + normal += Vec3::new( + (a.y - b.y) * (a.z + b.z), + (a.z - b.z) * (a.x + b.x), + (a.x - b.x) * (a.y + b.y), + ); + } + let Some(normal) = normal.try_normalize() else { + return Plane::XY; + }; + // the same plane whichever way the outline winds + let leading = [normal.z, normal.y, normal.x] + .into_iter() + .find(|component| *component != 0.0) + .unwrap_or(1.0); + let normal = if leading < 0.0 { -normal } else { normal }; + let (u, v) = normal.any_orthonormal_pair(); + Plane { + origin: outline.first().copied().unwrap_or(Vec3::ZERO), + u, + v, + normal, + } + } + + fn is_xy(&self) -> bool { + self.origin == Vec3::ZERO && self.u == Vec3::X && self.v == Vec3::Y + } + + /// The point in the plane's coordinates, and its height off the plane. + fn project(&self, point: Vec3) -> (Point, f32) { + let offset = point - self.origin; + ( + Point::new(offset.dot(self.u), offset.dot(self.v)), + offset.dot(self.normal), + ) + } + + fn lift(&self, point: Point, height: f32) -> Vec3 { + self.origin + self.u * point.x + self.v * point.y + self.normal * height + } } -pub fn build_polygon_fill( +/// The weight shared by all the styles, or per-vertex weights when they differ. +fn stroke_weight<'a>(styles: impl IntoIterator) -> StrokeWeight { + let mut styles = styles.into_iter(); + let Some(first) = styles.next() else { + return StrokeWeight::Constant(0.0); + }; + if styles.all(|style| style.weight == first.weight) { + StrokeWeight::Constant(first.weight) + } else { + StrokeWeight::PerVertex + } +} + +/// Whether a stroke of this weight draws anything. +fn is_visible(weight: StrokeWeight) -> bool { + !matches!(weight, StrokeWeight::Constant(w) if w <= 0.0 || w.is_nan()) +} + +/// Fills a shape of any kind with per-vertex styles. +pub fn build_shape_fill( mesh: &mut Mesh, builder: &ShapeBuilder, close: bool, - color: Color, - stroke_config: &StrokeConfig, + in_space: bool, + matrix_scale: f32, ) { - let path = build_polygon_path(builder, close); - tessellate_path(mesh, &path, color, TessellationMode::Fill, stroke_config); + if !builder.is_finite() { + return; + } + if builder.kind != ShapeKind::Polygon { + for primitive in shape_primitives(builder) { + push_primitive(mesh, &primitive, in_space); + } + return; + } + + let plane = Plane::of(builder); + // off the xy plane, curves are flattened before tessellating + let flattened; + let builder = if plane.is_xy() { + builder + } else { + flattened = ShapeBuilder { + kind: builder.kind, + in_contour: false, + contours: builder + .contours + .iter() + .map(|contour| { + let (vertices, styles) = flatten_contour(contour, matrix_scale) + .into_iter() + .map(|(point, style)| (VertexType::Normal(point), style)) + .unzip(); + Contour { vertices, styles } + }) + .collect(), + }; + &flattened + }; + // color, height off the plane, texture coordinate, normal + let path = build_polygon_path(builder, close, &plane, |style, height| { + let [r, g, b, a] = style.fill_color(); + let uv = style.uv.unwrap_or(Vec2::ZERO); + let normal = style.normal.unwrap_or(plane.normal); + vec![r, g, b, a, height, uv.x, uv.y, normal.x, normal.y, normal.z] + }); + tessellate_mapped_fill(mesh, &path, &|point, attributes| match *attributes { + [r, g, b, a, height, u, v, nx, ny, nz] => MeshVertex { + position: plane.lift(point, height).to_array(), + color: [r, g, b, a], + normal: Vec3::new(nx, ny, nz).normalize_or(plane.normal).to_array(), + uv: [u, v], + }, + _ => MeshVertex { + position: plane.lift(point, 0.0).to_array(), + color: [1.0; 4], + normal: plane.normal.to_array(), + uv: [0.0, 0.0], + }, + }); } -pub fn build_polygon_stroke( +/// Strokes a 2D shape of any kind as ribbons in its plane. +pub fn build_shape_stroke( mesh: &mut Mesh, builder: &ShapeBuilder, close: bool, - color: Color, - weight: f32, stroke_config: &StrokeConfig, ) { - let path = build_polygon_path(builder, close); - tessellate_path( - mesh, - &path, - color, - TessellationMode::Stroke(weight), - stroke_config, - ); + if !builder.is_finite() { + return; + } + if builder.kind == ShapeKind::Polygon { + let weight = stroke_weight(builder.styles()); + if is_visible(weight) { + let path = build_polygon_path(builder, close, &Plane::XY, |style, _| { + style.stroke_attributes().to_vec() + }); + tessellate_colored_stroke(mesh, &path, weight, stroke_config); + } + return; + } + for primitive in shape_primitives(builder) { + let styles = &primitive.styles[..primitive.len]; + let weight = stroke_weight(styles); + if !is_visible(weight) { + continue; + } + if let [point] = *primitive.points() { + // a point is a dot as wide as its stroke + let style = styles[0]; + super::ellipse( + mesh, + point.x, + point.y, + style.weight, + style.weight, + style.stroke, + TessellationMode::Fill, + stroke_config, + ); + continue; + } + let mut pb = Path::builder_with_attributes(5); + for (i, (point, style)) in primitive.points().iter().zip(styles).enumerate() { + let attributes = style.stroke_attributes(); + if i == 0 { + pb.begin(Point::new(point.x, point.y), &attributes); + } else { + pb.line_to(Point::new(point.x, point.y), &attributes); + } + } + pb.end(primitive.len > 2); + tessellate_colored_stroke(mesh, &pb.build(), weight, stroke_config); + } +} + +/// The most segments a curve is flattened into. +const MAX_CURVE_STEPS: usize = 24; +/// About how long each segment is on screen. +const CURVE_STEP_PIXELS: f32 = 4.0; + +/// How many segments a curve gets, from the length of its control polygon on screen. +fn curve_steps(control_polygon: &[Vec3], matrix_scale: f32) -> usize { + let length: f32 = control_polygon + .windows(2) + .map(|pair| pair[0].distance(pair[1])) + .sum(); + let steps = (length * matrix_scale / CURVE_STEP_PIXELS).ceil(); + // a NaN or tiny length still gets one segment + (steps as usize).clamp(1, MAX_CURVE_STEPS) } -fn build_polygon_path(builder: &ShapeBuilder, close: bool) -> Path { - let mut pb = Path::builder(); +/// Appends a shape's stroke as camera-facing segments. +pub fn build_shape_lines( + lines: &mut LineMesh, + builder: &ShapeBuilder, + close: bool, + matrix_scale: f32, +) { + if !builder.is_finite() { + return; + } + let end = |position: Vec3, style: &VertexStyle| LineEnd { + position, + color: style.stroke, + weight: style.weight, + }; + + if builder.kind != ShapeKind::Polygon { + for primitive in shape_primitives(builder) { + let ends: Vec = primitive + .points() + .iter() + .zip(&primitive.styles) + .map(|(point, style)| end(*point, style)) + .collect(); + match ends.as_slice() { + [point] => lines.point(*point), + [start, finish] => lines.segment(*start, *finish), + ends => { + for i in 0..ends.len() { + lines.segment(ends[i], ends[(i + 1) % ends.len()]); + } + } + } + } + return; + } + + for (contour_idx, contour) in builder.contours.iter().enumerate() { + let ends: Vec = flatten_contour(contour, matrix_scale) + .iter() + .map(|(position, style)| end(*position, style)) + .collect(); + for pair in ends.windows(2) { + lines.segment(pair[0], pair[1]); + } + if (close || contour_idx > 0) && ends.len() > 2 { + lines.segment(ends[ends.len() - 1], ends[0]); + } + } +} + +/// A contour with its curves flattened and styles interpolated. +fn flatten_contour(contour: &Contour, matrix_scale: f32) -> Vec<(Vec3, VertexStyle)> { + let mut flat: Vec<(Vec3, VertexStyle)> = Vec::new(); + for (vertex, style) in expand_curve_vertices(&contour.vertices, &contour.styles) { + let to = vertex.points().last().unwrap_or(Vec3::ZERO); + match (vertex, flat.last().copied()) { + (VertexType::CubicBezier { c1, c2, .. }, Some((from, from_style))) => { + let steps = curve_steps(&[from, c1, c2, to], matrix_scale); + for step in 1..=steps { + let t = step as f32 / steps as f32; + let u = 1.0 - t; + let position = from * (u * u * u) + + c1 * (3.0 * u * u * t) + + c2 * (3.0 * u * t * t) + + to * (t * t * t); + flat.push((position, from_style.mix(&style, t))); + } + } + (VertexType::QuadraticBezier { c, .. }, Some((from, from_style))) => { + let steps = curve_steps(&[from, c, to], matrix_scale); + for step in 1..=steps { + let t = step as f32 / steps as f32; + let u = 1.0 - t; + let position = from * (u * u) + c * (2.0 * u * t) + to * (t * t); + flat.push((position, from_style.mix(&style, t))); + } + } + // a curve with nothing before it has no start + (VertexType::CubicBezier { .. } | VertexType::QuadraticBezier { .. }, None) => {} + _ => flat.push((to, style)), + } + } + flat +} + +/// The outline of a polygon shape in `plane`. +fn build_polygon_path( + builder: &ShapeBuilder, + close: bool, + plane: &Plane, + attributes: impl Fn(&VertexStyle, f32) -> Vec, +) -> Path { + let num_attributes = builder + .styles() + .next() + .map_or(0, |style| attributes(style, 0.0).len()); + let mut pb = Path::builder_with_attributes(num_attributes); for (contour_idx, contour) in builder.contours.iter().enumerate() { if contour.vertices.is_empty() { @@ -109,39 +485,37 @@ fn build_polygon_path(builder: &ShapeBuilder, close: bool) -> Path { } // collect curve vertices and convert to bezier segments - let expanded = expand_curve_vertices(&contour.vertices); + let expanded = expand_curve_vertices(&contour.vertices, &contour.styles); let mut started = false; - for vt in &expanded { - match vt { - VertexType::Normal(x, y) => { + for (vt, style) in &expanded { + match *vt { + VertexType::Normal(to) => { + let (to, height) = plane.project(to); + let attributes = attributes(style, height); if !started { - pb.begin(Point::new(*x, *y)); + pb.begin(to, &attributes); started = true; } else { - pb.line_to(Point::new(*x, *y)); + pb.line_to(to, &attributes); } } - VertexType::CubicBezier { - cx1, - cy1, - cx2, - cy2, - x, - y, - } => { + VertexType::CubicBezier { c1, c2, to } => { if started { + let (to, height) = plane.project(to); pb.cubic_bezier_to( - Point::new(*cx1, *cy1), - Point::new(*cx2, *cy2), - Point::new(*x, *y), + plane.project(c1).0, + plane.project(c2).0, + to, + &attributes(style, height), ); } } - VertexType::QuadraticBezier { cx, cy, x, y } => { + VertexType::QuadraticBezier { c, to } => { if started { - pb.quadratic_bezier_to(Point::new(*cx, *cy), Point::new(*x, *y)); + let (to, height) = plane.project(to); + pb.quadratic_bezier_to(plane.project(c).0, to, &attributes(style, height)); } } VertexType::CurveVertex(..) => { @@ -159,31 +533,25 @@ fn build_polygon_path(builder: &ShapeBuilder, close: bool) -> Path { pb.build() } -/// expand curveVertex entries into cubic bezier segments using catmull-rom to Bezier conversion. -/// non-curve vertices are passed through unchanged. -fn expand_curve_vertices(vertices: &[VertexType]) -> Vec { - // If no curve vertices, return as-is - if !vertices - .iter() - .any(|v| matches!(v, VertexType::CurveVertex(..))) - { - return vertices.to_vec(); - } - +/// Expands curve vertices into cubic beziers (Catmull-Rom); every vertex keeps its style. +fn expand_curve_vertices( + vertices: &[VertexType], + styles: &[VertexStyle], +) -> Vec<(VertexType, VertexStyle)> { let mut result = Vec::new(); - let mut curve_points: Vec<(f32, f32)> = Vec::new(); + let mut curve_points: Vec<(Vec3, VertexStyle)> = Vec::new(); - for vt in vertices { + for (vt, style) in vertices.iter().zip(styles) { match vt { - VertexType::CurveVertex(x, y) => { - curve_points.push((*x, *y)); + VertexType::CurveVertex(point) => { + curve_points.push((*point, *style)); } _ => { if !curve_points.is_empty() { flush_curve_points(&curve_points, &mut result); curve_points.clear(); } - result.push(vt.clone()); + result.push((vt.clone(), *style)); } } } @@ -196,345 +564,150 @@ fn expand_curve_vertices(vertices: &[VertexType]) -> Vec { } // convert a sequence of Catmull-Rom curve points into bezier segments. -fn flush_curve_points(points: &[(f32, f32)], result: &mut Vec) { +fn flush_curve_points(points: &[(Vec3, VertexStyle)], result: &mut Vec<(VertexType, VertexStyle)>) { if points.len() < 4 { // not enough for a curve segment, emit as normal vertices - for &(x, y) in &points[1..points.len().saturating_sub(1).max(1)] { - result.push(VertexType::Normal(x, y)); + for &(point, style) in &points[1..points.len().saturating_sub(1).max(1)] { + result.push((VertexType::Normal(point), style)); } return; } // first drawn point is points[1] - result.push(VertexType::Normal(points[1].0, points[1].1)); + result.push((VertexType::Normal(points[1].0), points[1].1)); for i in 0..points.len() - 3 { - let p0 = points[i]; - let p1 = points[i + 1]; - let p2 = points[i + 2]; - let p3 = points[i + 3]; + let p0 = points[i].0; + let p1 = points[i + 1].0; + let (p2, style) = points[i + 2]; + let p3 = points[i + 3].0; // catmull-Rom to cubic bezier conversion // see https://en.wikipedia.org/wiki/Catmull%E2%80%93Rom_spline#Converting_to_B%C3%A9zier_curve - let cp1x = p1.0 + (p2.0 - p0.0) / 6.0; - let cp1y = p1.1 + (p2.1 - p0.1) / 6.0; - let cp2x = p2.0 - (p3.0 - p1.0) / 6.0; - let cp2y = p2.1 - (p3.1 - p1.1) / 6.0; - - result.push(VertexType::CubicBezier { - cx1: cp1x, - cy1: cp1y, - cx2: cp2x, - cy2: cp2y, - x: p2.0, - y: p2.1, - }); + result.push(( + VertexType::CubicBezier { + c1: p1 + (p2 - p0) / 6.0, + c2: p2 - (p3 - p1) / 6.0, + to: p2, + }, + style, + )); } } -/// Build direct mesh geometry for non-polygon shape kinds -pub fn build_direct_fill(mesh: &mut Mesh, builder: &ShapeBuilder, color: Color) { - let vertices: Vec<(f32, f32)> = builder.contours[0] - .vertices - .iter() - .filter_map(|v| match v { - VertexType::Normal(x, y) => Some((*x, *y)), - _ => None, - }) - .collect(); +/// One point, line, triangle or quad of a non-polygon shape, with the style of each vertex. +#[derive(Debug, Clone, Copy)] +struct ShapePrimitive { + points: [Vec3; 4], + styles: [VertexStyle; 4], + len: usize, +} - match builder.kind { - ShapeKind::Triangles => { - for chunk in vertices.as_chunks::<3>().0 { - push_triangle( - mesh, color, chunk[0].0, chunk[0].1, chunk[1].0, chunk[1].1, chunk[2].0, - chunk[2].1, - ); - } - } - ShapeKind::TriangleFan if vertices.len() >= 3 => { - let hub = vertices[0]; - for i in 1..vertices.len() - 1 { - push_triangle( - mesh, - color, - hub.0, - hub.1, - vertices[i].0, - vertices[i].1, - vertices[i + 1].0, - vertices[i + 1].1, - ); - } - } - ShapeKind::TriangleStrip => { - for i in 0..vertices.len().saturating_sub(2) { - if i % 2 == 0 { - push_triangle( - mesh, - color, - vertices[i].0, - vertices[i].1, - vertices[i + 1].0, - vertices[i + 1].1, - vertices[i + 2].0, - vertices[i + 2].1, - ); - } else { - // Reverse winding for odd triangles - push_triangle( - mesh, - color, - vertices[i + 1].0, - vertices[i + 1].1, - vertices[i].0, - vertices[i].1, - vertices[i + 2].0, - vertices[i + 2].1, - ); - } - } +impl ShapePrimitive { + fn new(vertices: &[(Vec3, VertexStyle)]) -> Self { + let mut points = [Vec3::ZERO; 4]; + let mut styles = [vertices[0].1; 4]; + for (i, (point, style)) in vertices.iter().enumerate() { + points[i] = *point; + styles[i] = *style; } - ShapeKind::Quads => { - for chunk in vertices.as_chunks::<4>().0 { - push_quad( - mesh, color, chunk[0].0, chunk[0].1, chunk[1].0, chunk[1].1, chunk[2].0, - chunk[2].1, chunk[3].0, chunk[3].1, - ); - } + Self { + points, + styles, + len: vertices.len(), } - ShapeKind::QuadStrip => { - let mut i = 0; - while i + 3 < vertices.len() { - push_quad( - mesh, - color, - vertices[i].0, - vertices[i].1, - vertices[i + 1].0, - vertices[i + 1].1, - vertices[i + 3].0, - vertices[i + 3].1, - vertices[i + 2].0, - vertices[i + 2].1, - ); - i += 2; - } + } + + fn points(&self) -> &[Vec3] { + &self.points[..self.len] + } + + /// The face normal: from the winding for a shape in space, +z for a flat 2D shape. + fn normal(&self, in_space: bool) -> Vec3 { + let points = self.points(); + if !in_space || points.len() < 3 { + return Vec3::Z; } - _ => {} + (points[1] - points[0]) + .cross(points[2] - points[0]) + .normalize_or(Vec3::Z) } } -/// Build stroke outlines for non-polygon shape kinds. -pub fn build_direct_stroke( - mesh: &mut Mesh, - builder: &ShapeBuilder, - color: Color, - weight: f32, - stroke_config: &StrokeConfig, -) { - let vertices: Vec<(f32, f32)> = builder.contours[0] +/// Splits a non-polygon shape into its primitives. +fn shape_primitives(builder: &ShapeBuilder) -> Vec { + let contour = &builder.contours[0]; + let v: Vec<(Vec3, VertexStyle)> = contour .vertices .iter() - .filter_map(|v| match v { - VertexType::Normal(x, y) => Some((*x, *y)), + .zip(&contour.styles) + .filter_map(|(vertex, style)| match vertex { + VertexType::Normal(point) => Some((*point, *style)), _ => None, }) .collect(); + let mut primitives = Vec::new(); match builder.kind { + ShapeKind::Points => { + for vertex in &v { + primitives.push(ShapePrimitive::new(&[*vertex])); + } + } ShapeKind::Lines => { - for chunk in vertices.as_chunks::<2>().0 { - let mut pb = Path::builder(); - pb.begin(Point::new(chunk[0].0, chunk[0].1)); - pb.line_to(Point::new(chunk[1].0, chunk[1].1)); - pb.end(false); - tessellate_path( - mesh, - &pb.build(), - color, - TessellationMode::Stroke(weight), - stroke_config, - ); + for i in (1..v.len()).step_by(2) { + primitives.push(ShapePrimitive::new(&[v[i - 1], v[i]])); } } ShapeKind::Triangles => { - for chunk in vertices.as_chunks::<3>().0 { - stroke_polygon( - mesh, - &[chunk[0], chunk[1], chunk[2]], - true, - color, - weight, - stroke_config, - ); + for i in (2..v.len()).step_by(3) { + primitives.push(ShapePrimitive::new(&[v[i - 2], v[i - 1], v[i]])); } } - ShapeKind::TriangleFan if vertices.len() >= 3 => { - let hub = vertices[0]; - for i in 1..vertices.len() - 1 { - stroke_polygon( - mesh, - &[hub, vertices[i], vertices[i + 1]], - true, - color, - weight, - stroke_config, - ); + ShapeKind::TriangleFan => { + for i in 2..v.len() { + primitives.push(ShapePrimitive::new(&[v[0], v[i - 1], v[i]])); } } ShapeKind::TriangleStrip => { - for i in 0..vertices.len().saturating_sub(2) { - if i % 2 == 0 { - stroke_polygon( - mesh, - &[vertices[i], vertices[i + 1], vertices[i + 2]], - true, - color, - weight, - stroke_config, - ); + for i in 2..v.len() { + // odd triangles are reversed to keep the winding + primitives.push(if i % 2 == 0 { + ShapePrimitive::new(&[v[i - 2], v[i - 1], v[i]]) } else { - stroke_polygon( - mesh, - &[vertices[i + 1], vertices[i], vertices[i + 2]], - true, - color, - weight, - stroke_config, - ); - } + ShapePrimitive::new(&[v[i - 1], v[i - 2], v[i]]) + }); } } ShapeKind::Quads => { - for chunk in vertices.as_chunks::<4>().0 { - stroke_polygon( - mesh, - &[chunk[0], chunk[1], chunk[2], chunk[3]], - true, - color, - weight, - stroke_config, - ); + for i in (3..v.len()).step_by(4) { + primitives.push(ShapePrimitive::new(&[v[i - 3], v[i - 2], v[i - 1], v[i]])); } } ShapeKind::QuadStrip => { - let mut i = 0; - while i + 3 < vertices.len() { - stroke_polygon( - mesh, - &[ - vertices[i], - vertices[i + 1], - vertices[i + 3], - vertices[i + 2], - ], - true, - color, - weight, - stroke_config, - ); - i += 2; + for i in (3..v.len()).step_by(2) { + primitives.push(ShapePrimitive::new(&[v[i - 3], v[i - 2], v[i], v[i - 1]])); } } - _ => {} + ShapeKind::Polygon => {} } + primitives } -fn stroke_polygon( - mesh: &mut Mesh, - verts: &[(f32, f32)], - close: bool, - color: Color, - weight: f32, - stroke_config: &StrokeConfig, -) { - if verts.is_empty() { - return; - } - let mut pb = Path::builder(); - pb.begin(Point::new(verts[0].0, verts[0].1)); - for v in &verts[1..] { - pb.line_to(Point::new(v.0, v.1)); - } - pb.end(close); - tessellate_path( - mesh, - &pb.build(), - color, - TessellationMode::Stroke(weight), - stroke_config, - ); -} +// texture coordinates for vertices that have none +const TRIANGLE_UVS: [[f32; 2]; 3] = [[0.0, 0.0], [1.0, 0.0], [0.5, 1.0]]; +const QUAD_UVS: [[f32; 2]; 4] = [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]; -fn push_triangle( - mesh: &mut Mesh, - color: Color, - x1: f32, - y1: f32, - x2: f32, - y2: f32, - x3: f32, - y3: f32, -) { - let base_idx = if let Some(VertexAttributeValues::Float32x3(positions)) = - mesh.attribute(Mesh::ATTRIBUTE_POSITION) - { - positions.len() as u32 - } else { - 0 +/// Appends a triangle or quad with its vertices' colors, normals and texture coordinates. +fn push_primitive(mesh: &mut Mesh, primitive: &ShapePrimitive, in_space: bool) { + let (default_uvs, triangles): (&[[f32; 2]], &[u32]) = match primitive.len { + 3 => (&TRIANGLE_UVS, &[0, 1, 2]), + 4 => (&QUAD_UVS, &[0, 1, 2, 0, 2, 3]), + _ => return, }; + let face_normal = primitive.normal(in_space); + let styles = &primitive.styles[..primitive.len]; - if let Some(VertexAttributeValues::Float32x3(positions)) = - mesh.attribute_mut(Mesh::ATTRIBUTE_POSITION) - { - positions.push([x1, y1, 0.0]); - positions.push([x2, y2, 0.0]); - positions.push([x3, y3, 0.0]); - } - - let color_array = color.to_linear().to_f32_array(); - if let Some(VertexAttributeValues::Float32x4(colors)) = - mesh.attribute_mut(Mesh::ATTRIBUTE_COLOR) - { - for _ in 0..3 { - colors.push(color_array); - } - } - - if let Some(VertexAttributeValues::Float32x3(normals)) = - mesh.attribute_mut(Mesh::ATTRIBUTE_NORMAL) - { - for _ in 0..3 { - normals.push([0.0, 0.0, 1.0]); - } - } - - if let Some(VertexAttributeValues::Float32x2(uvs)) = mesh.attribute_mut(Mesh::ATTRIBUTE_UV_0) { - uvs.push([0.0, 0.0]); - uvs.push([1.0, 0.0]); - uvs.push([0.5, 1.0]); - } - - if let Some(Indices::U32(indices)) = mesh.indices_mut() { - indices.push(base_idx); - indices.push(base_idx + 1); - indices.push(base_idx + 2); - } -} - -fn push_quad( - mesh: &mut Mesh, - color: Color, - x1: f32, - y1: f32, - x2: f32, - y2: f32, - x3: f32, - y3: f32, - x4: f32, - y4: f32, -) { let base_idx = if let Some(VertexAttributeValues::Float32x3(positions)) = mesh.attribute(Mesh::ATTRIBUTE_POSITION) { @@ -546,43 +719,35 @@ fn push_quad( if let Some(VertexAttributeValues::Float32x3(positions)) = mesh.attribute_mut(Mesh::ATTRIBUTE_POSITION) { - positions.push([x1, y1, 0.0]); - positions.push([x2, y2, 0.0]); - positions.push([x3, y3, 0.0]); - positions.push([x4, y4, 0.0]); + positions.extend(primitive.points().iter().map(|point| point.to_array())); } - let color_array = color.to_linear().to_f32_array(); if let Some(VertexAttributeValues::Float32x4(colors)) = mesh.attribute_mut(Mesh::ATTRIBUTE_COLOR) { - for _ in 0..4 { - colors.push(color_array); - } + colors.extend(styles.iter().map(VertexStyle::fill_color)); } if let Some(VertexAttributeValues::Float32x3(normals)) = mesh.attribute_mut(Mesh::ATTRIBUTE_NORMAL) { - for _ in 0..4 { - normals.push([0.0, 0.0, 1.0]); - } + normals.extend( + styles + .iter() + .map(|style| style.normal.unwrap_or(face_normal).to_array()), + ); } if let Some(VertexAttributeValues::Float32x2(uvs)) = mesh.attribute_mut(Mesh::ATTRIBUTE_UV_0) { - uvs.push([0.0, 0.0]); - uvs.push([1.0, 0.0]); - uvs.push([1.0, 1.0]); - uvs.push([0.0, 1.0]); + uvs.extend( + styles + .iter() + .zip(default_uvs) + .map(|(style, default)| style.uv.map_or(*default, |uv| uv.to_array())), + ); } if let Some(Indices::U32(indices)) = mesh.indices_mut() { - indices.push(base_idx); - indices.push(base_idx + 1); - indices.push(base_idx + 2); - - indices.push(base_idx); - indices.push(base_idx + 2); - indices.push(base_idx + 3); + indices.extend(triangles.iter().map(|i| base_idx + i)); } } diff --git a/crates/processing_render/src/render/style.rs b/crates/processing_render/src/render/style.rs index d42c9e7e..15793ad3 100644 --- a/crates/processing_render/src/render/style.rs +++ b/crates/processing_render/src/render/style.rs @@ -33,6 +33,8 @@ pub struct Style { pub blend_state: Option, pub tint_color: Option, pub image_mode: ShapeMode, + /// the size of the current texture, which `TextureMode::Image` coordinates are in + pub texture_size: Option, pub rect_mode: ShapeMode, pub ellipse_mode: ShapeMode, pub text_font_family: Option, @@ -72,6 +74,7 @@ impl Default for Style { blend_state: None, tint_color: None, image_mode: ShapeMode::Corner, + texture_size: None, rect_mode: ShapeMode::Corner, ellipse_mode: ShapeMode::Center, text_font_family: None, diff --git a/crates/processing_wasm/src/lib.rs b/crates/processing_wasm/src/lib.rs index aa829776..897e8409 100644 --- a/crates/processing_wasm/src/lib.rs +++ b/crates/processing_wasm/src/lib.rs @@ -717,7 +717,10 @@ pub fn js_vertex(graphics_id: u64, x: f32, y: f32) -> Result<(), JsValue> { let graphics_entity = Entity::from_bits(graphics_id); check(graphics_record_command( graphics_entity, - DrawCommand::ShapeVertex { x, y }, + DrawCommand::ShapeVertex { + position: Vec3::new(x, y, 0.0), + uv: None, + }, )) } @@ -735,12 +738,9 @@ pub fn js_bezier_vertex( check(graphics_record_command( graphics_entity, DrawCommand::ShapeBezierVertex { - cx1, - cy1, - cx2, - cy2, - x, - y, + c1: Vec3::new(cx1, cy1, 0.0), + c2: Vec3::new(cx2, cy2, 0.0), + to: Vec3::new(x, y, 0.0), }, )) } @@ -756,7 +756,10 @@ pub fn js_quadratic_vertex( let graphics_entity = Entity::from_bits(graphics_id); check(graphics_record_command( graphics_entity, - DrawCommand::ShapeQuadraticVertex { cx, cy, x, y }, + DrawCommand::ShapeQuadraticVertex { + c: Vec3::new(cx, cy, 0.0), + to: Vec3::new(x, y, 0.0), + }, )) } @@ -765,7 +768,9 @@ pub fn js_curve_vertex(graphics_id: u64, x: f32, y: f32) -> Result<(), JsValue> let graphics_entity = Entity::from_bits(graphics_id); check(graphics_record_command( graphics_entity, - DrawCommand::ShapeCurveVertex { x, y }, + DrawCommand::ShapeCurveVertex { + to: Vec3::new(x, y, 0.0), + }, )) } diff --git a/examples/shapes.rs b/examples/shapes.rs index 23820b68..3e915613 100644 --- a/examples/shapes.rs +++ b/examples/shapes.rs @@ -1,6 +1,7 @@ use processing_glfw::GlfwContext; use std::f32::consts::PI; +use bevy::math::Vec3; use processing::prelude::*; use processing_render::render::command::DrawCommand; @@ -51,8 +52,7 @@ fn sketch() -> error::Result<()> { graphics_record_command( graphics, DrawCommand::ShapeCurveVertex { - x: 170.0 + r * angle.cos(), - y: 200.0 + r * angle.sin(), + to: Vec3::new(170.0 + r * angle.cos(), 200.0 + r * angle.sin(), 0.0), }, )?; } @@ -79,27 +79,27 @@ fn sketch() -> error::Result<()> { kind: ShapeKind::Polygon, }, )?; - graphics_record_command(graphics, DrawCommand::ShapeVertex { x: pcx, y: pcy - s })?; + graphics_record_command( + graphics, + DrawCommand::ShapeVertex { + position: Vec3::new(pcx, pcy - s, 0.0), + uv: None, + }, + )?; graphics_record_command( graphics, DrawCommand::ShapeBezierVertex { - cx1: pcx + s, - cy1: pcy - s, - cx2: pcx + s, - cy2: pcy + s, - x: pcx, - y: pcy + s, + c1: Vec3::new(pcx + s, pcy - s, 0.0), + c2: Vec3::new(pcx + s, pcy + s, 0.0), + to: Vec3::new(pcx, pcy + s, 0.0), }, )?; graphics_record_command( graphics, DrawCommand::ShapeBezierVertex { - cx1: pcx - s, - cy1: pcy + s, - cx2: pcx - s, - cy2: pcy - s, - x: pcx, - y: pcy - s, + c1: Vec3::new(pcx - s, pcy + s, 0.0), + c2: Vec3::new(pcx - s, pcy - s, 0.0), + to: Vec3::new(pcx, pcy - s, 0.0), }, )?; graphics_record_command(graphics, DrawCommand::EndShape { close: true })?; @@ -116,15 +116,21 @@ fn sketch() -> error::Result<()> { kind: ShapeKind::TriangleFan, }, )?; - graphics_record_command(graphics, DrawCommand::ShapeVertex { x: 170.0, y: 450.0 })?; + graphics_record_command( + graphics, + DrawCommand::ShapeVertex { + position: Vec3::new(170.0, 450.0, 0.0), + uv: None, + }, + )?; for i in 0..=16 { let angle = i as f32 * 2.0 * PI / 16.0; let r = 60.0 + 20.0 * (t * 3.0 + angle * 2.0).sin(); graphics_record_command( graphics, DrawCommand::ShapeVertex { - x: 170.0 + r * angle.cos(), - y: 450.0 + r * angle.sin(), + position: Vec3::new(170.0 + r * angle.cos(), 450.0 + r * angle.sin(), 0.0), + uv: None, }, )?; } @@ -149,8 +155,20 @@ fn sketch() -> error::Result<()> { for i in 0..16 { let x = 320.0 + i as f32 * 17.0; let wave = 30.0 * (t * 2.0 + i as f32 * 0.4).sin(); - graphics_record_command(graphics, DrawCommand::ShapeVertex { x, y: 420.0 + wave })?; - graphics_record_command(graphics, DrawCommand::ShapeVertex { x, y: 480.0 + wave })?; + graphics_record_command( + graphics, + DrawCommand::ShapeVertex { + position: Vec3::new(x, 420.0 + wave, 0.0), + uv: None, + }, + )?; + graphics_record_command( + graphics, + DrawCommand::ShapeVertex { + position: Vec3::new(x, 480.0 + wave, 0.0), + uv: None, + }, + )?; } graphics_record_command(graphics, DrawCommand::EndShape { close: false })?; diff --git a/src/prelude.rs b/src/prelude.rs index 3275728d..22b4b160 100644 --- a/src/prelude.rs +++ b/src/prelude.rs @@ -13,7 +13,8 @@ pub use processing_midi::{ pub use processing_render::{ render::command::{ ArcMode, BlendMode, DrawCommand, LightKind, ShapeKind, ShapeMode, StrokeCapMode, - StrokeJoinMode, TextAlignH, TextAlignV, TextStyle, TextWrapMode, custom_blend_state, + StrokeJoinMode, TextAlignH, TextAlignV, TextStyle, TextWrapMode, TextureMode, + custom_blend_state, }, render::filter::Filter, *,