diff --git a/Cargo.lock b/Cargo.lock index 805c9193..23e1d177 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6226,6 +6226,7 @@ name = "processing" version = "0.4.0" dependencies = [ "bevy", + "bytemuck", "js-sys", "processing_audio", "processing_core", diff --git a/Cargo.toml b/Cargo.toml index 5ef3f465..2ddb2b71 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,8 +10,8 @@ workspace = true [features] default = ["wayland", "x11"] -wayland = ["processing_render/wayland"] -x11 = ["processing_render/x11"] +wayland = ["processing_render/wayland", "processing_glfw/wayland"] +x11 = ["processing_render/x11", "processing_glfw/x11"] webcam = ["dep:processing_webcam"] cuda = ["dep:processing_cuda", "processing_cuda/cuda"] @@ -87,9 +87,13 @@ processing_audio = { workspace = true } processing_input = { workspace = true } processing_webcam = { workspace = true, optional = true } processing_cuda = { workspace = true, optional = true } +bytemuck = "1" tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +processing_glfw = { workspace = true } + [target.'cfg(target_arch = "wasm32")'.dependencies] wasm-bindgen-futures = "0.4" js-sys = "0.3" @@ -133,6 +137,10 @@ path = "examples/background_image.rs" name = "update_pixels" path = "examples/update_pixels.rs" +[[example]] +name = "create_graphics" +path = "examples/create_graphics.rs" + [[example]] name = "transforms" path = "examples/transforms.rs" diff --git a/crates/processing_ffi/src/color.rs b/crates/processing_ffi/src/color.rs index ae0ea82a..9c7ab31e 100644 --- a/crates/processing_ffi/src/color.rs +++ b/crates/processing_ffi/src/color.rs @@ -1,5 +1,5 @@ use bevy::color::LinearRgba; -use processing::prelude::color::{ColorMode, ColorSpace}; +use processing::engine::color::{ColorMode, ColorSpace}; /// A color with 4 float components and its color space. #[repr(C)] diff --git a/crates/processing_ffi/src/error.rs b/crates/processing_ffi/src/error.rs index fe8d5edf..a9ac84d4 100644 --- a/crates/processing_ffi/src/error.rs +++ b/crates/processing_ffi/src/error.rs @@ -4,7 +4,7 @@ use std::{ panic, }; -pub(crate) use processing::prelude::error::ProcessingError; +pub(crate) use processing::engine::error::ProcessingError; thread_local! { static LAST_ERROR: RefCell> = const { RefCell::new(None) }; diff --git a/crates/processing_ffi/src/lib.rs b/crates/processing_ffi/src/lib.rs index 2b1e8c79..9ee5b997 100644 --- a/crates/processing_ffi/src/lib.rs +++ b/crates/processing_ffi/src/lib.rs @@ -3,7 +3,7 @@ use bevy::{ prelude::Entity, render::render_resource::{Extent3d, TextureFormat}, }; -use processing::prelude::{error::ProcessingError, shader_value::ShaderValue, *}; +use processing::engine::{error::ProcessingError, shader_value::ShaderValue, *}; use crate::color::Color; @@ -333,12 +333,12 @@ pub extern "C" fn processing_color_mode( error::clear_error(); let graphics_entity = Entity::from_bits(graphics_id); error::check(|| { - let space = processing::prelude::color::ColorSpace::from_u8(space).ok_or_else(|| { - processing::prelude::error::ProcessingError::InvalidArgument(format!( + let space = processing::engine::color::ColorSpace::from_u8(space).ok_or_else(|| { + processing::engine::error::ProcessingError::InvalidArgument(format!( "unknown color space: {space}" )) })?; - let mode = processing::prelude::color::ColorMode::new(space, max1, max2, max3, max_alpha); + let mode = processing::engine::color::ColorMode::new(space, max1, max2, max3, max_alpha); graphics_set_color_mode(graphics_entity, mode) }); } @@ -396,7 +396,7 @@ pub extern "C" fn processing_set_stroke_cap(graphics_id: u64, cap: u8) { error::check(|| { graphics_record_command( graphics_entity, - DrawCommand::StrokeCap(processing::prelude::StrokeCapMode::from(cap)), + DrawCommand::StrokeCap(processing::engine::StrokeCapMode::from(cap)), ) }); } @@ -409,7 +409,7 @@ pub extern "C" fn processing_set_stroke_join(graphics_id: u64, join: u8) { error::check(|| { graphics_record_command( graphics_entity, - DrawCommand::StrokeJoin(processing::prelude::StrokeJoinMode::from(join)), + DrawCommand::StrokeJoin(processing::engine::StrokeJoinMode::from(join)), ) }); } @@ -422,7 +422,7 @@ pub extern "C" fn processing_rect_mode(graphics_id: u64, mode: u8) { error::check(|| { graphics_record_command( graphics_entity, - DrawCommand::RectMode(processing::prelude::ShapeMode::from(mode)), + DrawCommand::RectMode(processing::engine::ShapeMode::from(mode)), ) }); } @@ -435,7 +435,7 @@ pub extern "C" fn processing_ellipse_mode(graphics_id: u64, mode: u8) { error::check(|| { graphics_record_command( graphics_entity, - DrawCommand::EllipseMode(processing::prelude::ShapeMode::from(mode)), + DrawCommand::EllipseMode(processing::engine::ShapeMode::from(mode)), ) }); } @@ -631,7 +631,7 @@ pub extern "C" fn processing_set_blend_mode(graphics_id: u64, mode: u8) { error::clear_error(); let graphics_entity = Entity::from_bits(graphics_id); error::check(|| { - let blend_state = processing::prelude::BlendMode::try_from(mode)?.to_blend_state(); + let blend_state = processing::engine::BlendMode::try_from(mode)?.to_blend_state(); graphics_record_command(graphics_entity, DrawCommand::BlendMode(blend_state)) }); } @@ -828,7 +828,7 @@ pub extern "C" fn processing_arc( h, start, stop, - mode: processing::prelude::ArcMode::from(mode), + mode: processing::engine::ArcMode::from(mode), }, ) }); @@ -1022,7 +1022,7 @@ pub extern "C" fn processing_begin_shape(graphics_id: u64, kind: u8) { graphics_record_command( graphics_entity, DrawCommand::BeginShape { - kind: processing::prelude::ShapeKind::from(kind), + kind: processing::engine::ShapeKind::from(kind), }, ) }); @@ -1827,7 +1827,7 @@ pub extern "C" fn processing_image_mode(graphics_id: u64, mode: u8) { error::check(|| { graphics_record_command( graphics_entity, - DrawCommand::ImageMode(processing::prelude::ShapeMode::from(mode)), + DrawCommand::ImageMode(processing::engine::ShapeMode::from(mode)), ) }); } @@ -4009,8 +4009,8 @@ pub extern "C" fn processing_graphics_tonemapping(graphics_id: u64, mode: u8) { error::clear_error(); error::check(|| { let tonemapping = - processing::prelude::graphics::tonemapping_from_u8(mode).ok_or_else(|| { - processing::prelude::error::ProcessingError::InvalidArgument(format!( + processing::engine::graphics::tonemapping_from_u8(mode).ok_or_else(|| { + processing::engine::error::ProcessingError::InvalidArgument(format!( "unknown tonemapping: {mode}" )) })?; @@ -4348,7 +4348,7 @@ pub extern "C" fn processing_mouse_wheel() -> f32 { error::check(input_mouse_wheel).unwrap_or(0.0) } -fn key_code_from_u32(val: u32) -> processing::prelude::error::Result { +fn key_code_from_u32(val: u32) -> processing::engine::error::Result { match val { PROCESSING_KEY_SPACE => Ok(KeyCode::Space), PROCESSING_KEY_QUOTE => Ok(KeyCode::Quote), diff --git a/crates/processing_node/src/lib.rs b/crates/processing_node/src/lib.rs index 7fb6a8d7..1ce730cf 100644 --- a/crates/processing_node/src/lib.rs +++ b/crates/processing_node/src/lib.rs @@ -12,9 +12,9 @@ use napi::bindgen_prelude::{ }; use napi::{Env, Error, Result}; use napi_derive::napi; -use processing::prelude::color::{ColorMode, ColorSpace}; -use processing::prelude::error::ProcessingError; -use processing::prelude::{shader_value::ShaderValue, *}; +use processing::engine::color::{ColorMode, ColorSpace}; +use processing::engine::error::ProcessingError; +use processing::engine::{shader_value::ShaderValue, *}; use processing_glfw::GlfwContext; fn check(result: std::result::Result) -> Result { @@ -3123,7 +3123,7 @@ pub fn js_mouse_wheel() -> Result { check(input_mouse_wheel()).map(f64::from) } -fn key_code_from_u32(val: u32) -> processing::prelude::error::Result { +fn key_code_from_u32(val: u32) -> processing::engine::error::Result { match val { PROCESSING_KEY_SPACE => Ok(KeyCode::Space), PROCESSING_KEY_QUOTE => Ok(KeyCode::Quote), diff --git a/crates/processing_pyo3/src/color.rs b/crates/processing_pyo3/src/color.rs index 6aef7072..9914ac55 100644 --- a/crates/processing_pyo3/src/color.rs +++ b/crates/processing_pyo3/src/color.rs @@ -6,7 +6,7 @@ use pyo3::{exceptions::PyTypeError, prelude::*, types::PyTuple}; use crate::math::{PyVec3, PyVec4, PyVecIter, hash_f32}; -pub use processing::prelude::color::{ColorMode, ColorSpace}; +pub use processing::engine::color::{ColorMode, ColorSpace}; fn int_maxes(space: &ColorSpace) -> [f32; 4] { match space { diff --git a/crates/processing_pyo3/src/compute.rs b/crates/processing_pyo3/src/compute.rs index 9f7208fb..8bb03629 100644 --- a/crates/processing_pyo3/src/compute.rs +++ b/crates/processing_pyo3/src/compute.rs @@ -1,5 +1,5 @@ use bevy::prelude::Entity; -use processing::prelude::*; +use processing::engine::*; use pyo3::{ exceptions::{PyIndexError, PyRuntimeError, PyTypeError, PyValueError}, prelude::*, @@ -184,7 +184,7 @@ impl Buffer { #[pyo3(signature = (op = "sum"))] pub fn reduce(&self, op: &str) -> PyResult { - use processing::prelude::constants as c; + use processing::engine::constants as c; use processing_render::particles::reduce::{ REDUCE_OP_MAX, REDUCE_OP_MIN, REDUCE_OP_SUM, reduce as reduce_buffer, }; diff --git a/crates/processing_pyo3/src/constants.rs b/crates/processing_pyo3/src/constants.rs index 99486f82..15eeab7d 100644 --- a/crates/processing_pyo3/src/constants.rs +++ b/crates/processing_pyo3/src/constants.rs @@ -1,5 +1,5 @@ -use processing::prelude::BlendMode; -use processing::prelude::constants as c; +use processing::engine::BlendMode; +use processing::engine::constants as c; use pyo3::prelude::*; use pyo3::types::PyModule; diff --git a/crates/processing_pyo3/src/cuda.rs b/crates/processing_pyo3/src/cuda.rs index 6716b297..1da4ce65 100644 --- a/crates/processing_pyo3/src/cuda.rs +++ b/crates/processing_pyo3/src/cuda.rs @@ -1,4 +1,4 @@ -use processing::prelude::image::pixel_size; +use processing::engine::image::pixel_size; use processing_cuda::{cuda_buffer, cuda_write_back, typestr_for_format}; use pyo3::{exceptions::PyRuntimeError, prelude::*, types::PyDict}; diff --git a/crates/processing_pyo3/src/filter.rs b/crates/processing_pyo3/src/filter.rs index c59aeaef..85155668 100644 --- a/crates/processing_pyo3/src/filter.rs +++ b/crates/processing_pyo3/src/filter.rs @@ -1,5 +1,5 @@ use bevy::prelude::Entity; -use processing::prelude::*; +use processing::engine::*; use pyo3::{ exceptions::{PyRuntimeError, PyTypeError, PyValueError}, prelude::*, diff --git a/crates/processing_pyo3/src/gltf.rs b/crates/processing_pyo3/src/gltf.rs index 081c213d..354d51eb 100644 --- a/crates/processing_pyo3/src/gltf.rs +++ b/crates/processing_pyo3/src/gltf.rs @@ -1,5 +1,5 @@ use bevy::prelude::Entity; -use processing::prelude::*; +use processing::engine::*; use pyo3::{exceptions::PyRuntimeError, prelude::*}; use crate::graphics::{Geometry, Light}; diff --git a/crates/processing_pyo3/src/graphics.rs b/crates/processing_pyo3/src/graphics.rs index d3b16919..f363aed2 100644 --- a/crates/processing_pyo3/src/graphics.rs +++ b/crates/processing_pyo3/src/graphics.rs @@ -8,7 +8,7 @@ use bevy::{ prelude::{Entity, Transform}, render::render_resource::{Extent3d, TextureFormat}, }; -use processing::prelude::*; +use processing::engine::*; use pyo3::{ exceptions::{PyRuntimeError, PyValueError}, prelude::*, @@ -1594,7 +1594,7 @@ impl Graphics { } pub fn text_style(&self, style: &str) -> PyResult<()> { - use processing::prelude::TextStyle; + use processing::engine::TextStyle; let style = TextStyle::parse(style) .ok_or_else(|| PyValueError::new_err(format!("unknown text style: {style:?}")))?; graphics_text_style(self.entity, style as u8) @@ -1723,7 +1723,7 @@ impl Graphics { #[pyo3(signature = (h, v=None))] pub fn text_align(&self, h: &str, v: Option<&str>) -> PyResult<()> { - use processing::prelude::{TextAlignH, TextAlignV}; + use processing::engine::{TextAlignH, TextAlignV}; let h = TextAlignH::parse(h).ok_or_else(|| { PyValueError::new_err(format!("unknown horizontal text align: {h:?}")) })?; @@ -1743,7 +1743,7 @@ impl Graphics { } pub fn text_wrap(&self, mode: &str) -> PyResult<()> { - use processing::prelude::TextWrapMode; + use processing::engine::TextWrapMode; let mode = TextWrapMode::parse(mode) .ok_or_else(|| PyValueError::new_err(format!("unknown text wrap mode: {mode:?}")))?; graphics_record_command(self.entity, DrawCommand::TextWrap(mode)) @@ -2333,7 +2333,7 @@ impl Graphics { graphics_no_bloom(self.entity).map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } - #[pyo3(signature = (mode=processing::prelude::constants::PBR_NEUTRAL))] + #[pyo3(signature = (mode=processing::engine::constants::PBR_NEUTRAL))] pub fn tonemapping(&self, mode: &str) -> PyResult<()> { let tonemapping = processing_render::graphics::parse_tonemapping(mode) .ok_or_else(|| PyValueError::new_err(format!("unknown tonemapping {mode:?}")))?; @@ -2774,6 +2774,7 @@ impl Graphics { transform.look_at(target.into_vec3(), Vec3::Y); } graphics_immediate_light(self.entity, kind, transform) + .map(|_| ()) .map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } } diff --git a/crates/processing_pyo3/src/host.rs b/crates/processing_pyo3/src/host.rs index fb7071f7..024bc2ef 100644 --- a/crates/processing_pyo3/src/host.rs +++ b/crates/processing_pyo3/src/host.rs @@ -16,7 +16,7 @@ use std::collections::HashMap; use bevy::prelude::Entity; -use processing::prelude::*; +use processing::engine::*; use processing_render::geometry::AttributeFormat; use pyo3::buffer::PyBuffer; use pyo3::exceptions::{PyRuntimeError, PyValueError}; diff --git a/crates/processing_pyo3/src/input.rs b/crates/processing_pyo3/src/input.rs index 1126d3fb..2233182c 100644 --- a/crates/processing_pyo3/src/input.rs +++ b/crates/processing_pyo3/src/input.rs @@ -1,41 +1,41 @@ use bevy::prelude::Entity; -use processing::prelude::*; +use processing::engine::*; use pyo3::{ exceptions::{PyRuntimeError, PyValueError}, prelude::*, }; pub fn mouse_x(surface: Entity, width: u32) -> PyResult { - let raw = processing::prelude::input_mouse_x(surface) + let raw = processing::engine::input_mouse_x(surface) .map_err(|e| PyRuntimeError::new_err(format!("{e}")))?; Ok(raw.clamp(0.0, width as f32)) } pub fn mouse_y(surface: Entity, height: u32) -> PyResult { - let raw = processing::prelude::input_mouse_y(surface) + let raw = processing::engine::input_mouse_y(surface) .map_err(|e| PyRuntimeError::new_err(format!("{e}")))?; Ok(raw.clamp(0.0, height as f32)) } pub fn pmouse_x(surface: Entity, width: u32) -> PyResult { - let raw = processing::prelude::input_pmouse_x(surface) + let raw = processing::engine::input_pmouse_x(surface) .map_err(|e| PyRuntimeError::new_err(format!("{e}")))?; Ok(raw.clamp(0.0, width as f32)) } pub fn pmouse_y(surface: Entity, height: u32) -> PyResult { - let raw = processing::prelude::input_pmouse_y(surface) + let raw = processing::engine::input_pmouse_y(surface) .map_err(|e| PyRuntimeError::new_err(format!("{e}")))?; Ok(raw.clamp(0.0, height as f32)) } pub fn mouse_is_pressed() -> PyResult { - processing::prelude::input_mouse_is_pressed() + processing::engine::input_mouse_is_pressed() .map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } pub fn mouse_button() -> PyResult> { - processing::prelude::input_mouse_button() + processing::engine::input_mouse_button() .map(|opt| { opt.map(|b| match b { MouseButton::Left => constants::LEFT.to_string(), @@ -48,40 +48,40 @@ pub fn mouse_button() -> PyResult> { } pub fn moved_x() -> PyResult { - processing::prelude::input_moved_x().map_err(|e| PyRuntimeError::new_err(format!("{e}"))) + processing::engine::input_moved_x().map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } pub fn moved_y() -> PyResult { - processing::prelude::input_moved_y().map_err(|e| PyRuntimeError::new_err(format!("{e}"))) + processing::engine::input_moved_y().map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } pub fn mouse_wheel() -> PyResult { - processing::prelude::input_mouse_wheel().map_err(|e| PyRuntimeError::new_err(format!("{e}"))) + processing::engine::input_mouse_wheel().map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } pub fn key_is_pressed() -> PyResult { - processing::prelude::input_key_is_pressed().map_err(|e| PyRuntimeError::new_err(format!("{e}"))) + processing::engine::input_key_is_pressed().map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } pub fn key_is_down(key_code: u32) -> PyResult { let kc = u32_to_key_code(key_code)?; - processing::prelude::input_key_is_down(kc).map_err(|e| PyRuntimeError::new_err(format!("{e}"))) + processing::engine::input_key_is_down(kc).map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } pub fn key_just_pressed(key_code: u32) -> PyResult { let kc = u32_to_key_code(key_code)?; - processing::prelude::input_key_just_pressed(kc) + processing::engine::input_key_just_pressed(kc) .map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } pub fn key() -> PyResult> { - processing::prelude::input_key() + processing::engine::input_key() .map(|opt| opt.map(String::from)) .map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } pub fn key_code() -> PyResult> { - processing::prelude::input_key_code() + processing::engine::input_key_code() .map(|opt| opt.map(key_code_to_u32)) .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 f0235caa..10a5213a 100644 --- a/crates/processing_pyo3/src/lib.rs +++ b/crates/processing_pyo3/src/lib.rs @@ -184,10 +184,10 @@ pub(crate) fn reset_tracked_globals() { fn sync_globals(module: &Bound<'_, PyModule>, globals: &Bound<'_, PyAny>) -> PyResult<()> { let graphics = get_graphics(module)?.ok_or_else(|| PyRuntimeError::new_err("call size() first"))?; - let width = ::processing::prelude::surface_width(graphics.surface.entity) + let width = ::processing::engine::surface_width(graphics.surface.entity) .map_err(|e| PyRuntimeError::new_err(format!("{e}")))?; let width = if width == 0 { graphics.width } else { width }; - let height = ::processing::prelude::surface_height(graphics.surface.entity) + let height = ::processing::engine::surface_height(graphics.surface.entity) .map_err(|e| PyRuntimeError::new_err(format!("{e}")))?; let height = if height == 0 { graphics.height } else { height }; input::sync_globals(globals, graphics.surface.entity, width, height)?; @@ -207,9 +207,9 @@ fn try_call(locals: &Bound<'_, PyAny>, name: &str) -> PyResult<()> { } fn dispatch_event_callbacks(locals: &Bound<'_, PyAny>) -> PyResult<()> { - use processing::prelude::*; + use processing::engine::*; let err = - |e: processing::prelude::error::ProcessingError| PyRuntimeError::new_err(format!("{e}")); + |e: processing::engine::error::ProcessingError| PyRuntimeError::new_err(format!("{e}")); if input_mouse_any_just_pressed().map_err(err)? { try_call(locals, "mouse_pressed")?; @@ -620,7 +620,7 @@ pub mod processing_py { fn load_gltf(module: &Bound<'_, PyModule>, path: &str) -> PyResult { let graphics = get_graphics(module)?.ok_or_else(|| PyRuntimeError::new_err("call size() first"))?; - let entity = ::processing::prelude::gltf_load(graphics.entity, path) + let entity = ::processing::engine::gltf_load(graphics.entity, path) .map_err(|e| PyRuntimeError::new_err(format!("{e}")))?; Ok(Gltf::from_entity(entity)) } @@ -836,7 +836,7 @@ pub mod processing_py { return Ok(false); } - processing::prelude::advance_frame_count() + processing::engine::advance_frame_count() .map_err(|e| PyRuntimeError::new_err(format!("{e}")))?; let windows = collect_windows(module)?; @@ -919,7 +919,7 @@ pub mod processing_py { let Some(graphics) = get_graphics(module)? else { return Ok(()); }; - ::processing::prelude::surface_resize(graphics.surface.entity, w, h) + ::processing::engine::surface_resize(graphics.surface.entity, w, h) .map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } @@ -1162,7 +1162,7 @@ pub mod processing_py { } first_frame = false; - processing::prelude::advance_frame_count() + processing::engine::advance_frame_count() .map_err(|e| PyRuntimeError::new_err(format!("{e}")))?; // One draw() per frame drives every window. Globals target the @@ -1511,7 +1511,7 @@ pub mod processing_py { } #[pyfunction] - #[pyo3(pass_module, signature = (mode=processing::prelude::constants::PBR_NEUTRAL))] + #[pyo3(pass_module, signature = (mode=processing::engine::constants::PBR_NEUTRAL))] fn tonemapping(module: &Bound<'_, PyModule>, mode: &str) -> PyResult<()> { graphics!(module).tonemapping(mode) } @@ -1630,7 +1630,7 @@ pub mod processing_py { }; // The GLFW window is created with the title, but the Window component // (which the per-frame sync applies) defaults otherwise — set it too. - ::processing::prelude::surface_set_title(surface_entity, title.to_string()) + ::processing::engine::surface_set_title(surface_entity, title.to_string()) .map_err(|e| PyRuntimeError::new_err(format!("{e}")))?; let window = Py::new( module.py(), @@ -2198,7 +2198,7 @@ pub mod processing_py { } #[pyfunction] - #[pyo3(pass_module, signature = (cx, cy, w, h, start, stop, mode=processing::prelude::constants::OPEN))] + #[pyo3(pass_module, signature = (cx, cy, w, h, start, stop, mode=processing::engine::constants::OPEN))] fn arc( module: &Bound<'_, PyModule>, cx: f32, @@ -2245,7 +2245,7 @@ pub mod processing_py { } #[pyfunction] - #[pyo3(pass_module, signature = (kind=processing::prelude::constants::POLYGON))] + #[pyo3(pass_module, signature = (kind=processing::engine::constants::POLYGON))] fn begin_shape(module: &Bound<'_, PyModule>, kind: &str) -> PyResult<()> { graphics!(module).begin_shape(kind) } @@ -2426,7 +2426,7 @@ pub mod processing_py { #[pyfunction] #[pyo3(pass_module, signature = (filename=None))] fn save_frame(module: &Bound<'_, PyModule>, filename: Option<&str>) -> PyResult<()> { - let count = ::processing::prelude::frame_count() + let count = ::processing::engine::frame_count() .map_err(|e| PyRuntimeError::new_err(format!("{e}")))?; let name = match filename { Some(f) => substitute_frame_number(f, count), diff --git a/crates/processing_pyo3/src/material.rs b/crates/processing_pyo3/src/material.rs index 95cf57a9..a69224b5 100644 --- a/crates/processing_pyo3/src/material.rs +++ b/crates/processing_pyo3/src/material.rs @@ -1,5 +1,5 @@ use bevy::prelude::Entity; -use processing::prelude::*; +use processing::engine::*; use pyo3::types::{PyDict, PyInt}; use pyo3::{exceptions::PyRuntimeError, prelude::*}; diff --git a/crates/processing_pyo3/src/midi.rs b/crates/processing_pyo3/src/midi.rs index 494b5fee..fa8aa853 100644 --- a/crates/processing_pyo3/src/midi.rs +++ b/crates/processing_pyo3/src/midi.rs @@ -1,4 +1,4 @@ -use processing::prelude::*; +use processing::engine::*; use pyo3::{exceptions::PyRuntimeError, prelude::*}; pub fn connect(port: usize) -> PyResult<()> { diff --git a/crates/processing_pyo3/src/monitor.rs b/crates/processing_pyo3/src/monitor.rs index c4826434..24689076 100644 --- a/crates/processing_pyo3/src/monitor.rs +++ b/crates/processing_pyo3/src/monitor.rs @@ -1,5 +1,5 @@ use bevy::prelude::Entity; -use processing::prelude::*; +use processing::engine::*; use pyo3::{exceptions::PyRuntimeError, prelude::*}; #[pyclass(unsendable)] diff --git a/crates/processing_pyo3/src/particles.rs b/crates/processing_pyo3/src/particles.rs index 788f0d6d..bf0877ca 100644 --- a/crates/processing_pyo3/src/particles.rs +++ b/crates/processing_pyo3/src/particles.rs @@ -1,5 +1,5 @@ use bevy::prelude::Entity; -use processing::prelude::*; +use processing::engine::*; use processing_render::geometry; use pyo3::types::{PyDict, PyTuple}; use pyo3::{ @@ -18,7 +18,7 @@ use processing_render::particles::compact::compact as compact_indices; use crate::compute::{Buffer, Compute}; use crate::graphics::{Geometry, Image}; -use processing::prelude::constants as c; +use processing::engine::constants as c; use processing_render::{ COMBINE_ADD, COMBINE_DIV, COMBINE_MAX, COMBINE_MIN, COMBINE_MUL, COMBINE_POW, COMBINE_SUB, }; diff --git a/crates/processing_pyo3/src/shader.rs b/crates/processing_pyo3/src/shader.rs index 60817010..d61422c6 100644 --- a/crates/processing_pyo3/src/shader.rs +++ b/crates/processing_pyo3/src/shader.rs @@ -1,5 +1,5 @@ use bevy::prelude::Entity; -use processing::prelude::*; +use processing::engine::*; use pyo3::{exceptions::PyRuntimeError, prelude::*}; #[pyclass(unsendable)] diff --git a/crates/processing_pyo3/src/surface.rs b/crates/processing_pyo3/src/surface.rs index 6aa70901..485a7bad 100644 --- a/crates/processing_pyo3/src/surface.rs +++ b/crates/processing_pyo3/src/surface.rs @@ -1,6 +1,6 @@ use bevy::prelude::Entity; use bevy::window::{MonitorSelection, WindowLevel, WindowMode}; -use processing::prelude::*; +use processing::engine::*; use pyo3::{exceptions::PyRuntimeError, prelude::*}; use crate::glfw::GlfwContext; diff --git a/crates/processing_pyo3/src/time.rs b/crates/processing_pyo3/src/time.rs index d638a568..01ba42ea 100644 --- a/crates/processing_pyo3/src/time.rs +++ b/crates/processing_pyo3/src/time.rs @@ -1,15 +1,15 @@ use pyo3::{exceptions::PyRuntimeError, prelude::*}; pub fn frame_count() -> PyResult { - processing::prelude::frame_count().map_err(|e| PyRuntimeError::new_err(format!("{e}"))) + processing::engine::frame_count().map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } pub fn delta_time() -> PyResult { - processing::prelude::delta_time().map_err(|e| PyRuntimeError::new_err(format!("{e}"))) + processing::engine::delta_time().map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } pub fn elapsed_time() -> PyResult { - processing::prelude::elapsed_time().map_err(|e| PyRuntimeError::new_err(format!("{e}"))) + processing::engine::elapsed_time().map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } pub fn sync_globals(globals: &Bound<'_, PyAny>) -> PyResult<()> { diff --git a/crates/processing_render/src/graphics.rs b/crates/processing_render/src/graphics.rs index 436546e7..9c6a852c 100644 --- a/crates/processing_render/src/graphics.rs +++ b/crates/processing_render/src/graphics.rs @@ -33,7 +33,7 @@ use crate::{ image::{Image, create_readback_buffer, pixel_size, pixels_to_bytes}, render::{ BATCH_INDEX_STEP, DrawTransients, RenderState, - command::{CommandBuffer, DrawCommand}, + command::{CommandBuffer, CommandSlot, DrawCommand}, filter, }, surface::Surface, @@ -714,7 +714,7 @@ pub fn flush(app: &mut App, entity: Entity) -> Result<()> { app.update(); let pending = graphics_mut!(app, entity) .get::() - .is_some_and(|buffer| !buffer.commands.is_empty()); + .is_some_and(|buffer| !buffer.is_empty()); if !pending { break; } @@ -726,7 +726,7 @@ pub fn flush(app: &mut App, entity: Entity) -> Result<()> { fn has_commands(app: &App, entity: Entity) -> bool { app.world() .get::(entity) - .is_some_and(|buffer| !buffer.commands.is_empty()) + .is_some_and(|buffer| !buffer.is_empty()) } /// Uploads the canvas pixels `set` wrote since the last upload @@ -1004,6 +1004,16 @@ pub fn record_command( Ok(()) } +pub fn record_command_slot( + In((graphics_entity, cmd)): In<(Entity, DrawCommand)>, + mut graphics_query: Query<&mut CommandBuffer>, +) -> Result { + let mut command_buffer = graphics_query + .get_mut(graphics_entity) + .map_err(|_| ProcessingError::GraphicsNotFound)?; + Ok(command_buffer.push_slot(graphics_entity, cmd)) +} + pub struct ReadbackData { pub bytes: Vec, pub format: TextureFormat, diff --git a/crates/processing_render/src/lib.rs b/crates/processing_render/src/lib.rs index c01747b3..d54f7c04 100644 --- a/crates/processing_render/src/lib.rs +++ b/crates/processing_render/src/lib.rs @@ -762,6 +762,34 @@ pub fn graphics_record_command(graphics_entity: Entity, cmd: DrawCommand) -> err }) } +pub fn graphics_record_command_slot( + graphics_entity: Entity, + cmd: DrawCommand, +) -> error::Result { + app_mut(|app| { + app.world_mut() + .run_system_cached_with(graphics::record_command_slot, (graphics_entity, cmd)) + .unwrap() + }) +} + +pub fn graphics_amend_command( + slot: render::command::CommandSlot, + amend: impl FnOnce(&mut DrawCommand), +) -> error::Result<()> { + app_mut(|app| { + let mut buffer = app + .world_mut() + .get_mut::(slot.graphics()) + .ok_or(error::ProcessingError::GraphicsNotFound)?; + let cmd = buffer.get_mut(slot).ok_or_else(|| { + error::ProcessingError::InvalidArgument("command was already flushed".to_string()) + })?; + amend(cmd); + Ok(()) + }) +} + pub fn graphics_mode_3d(graphics_entity: Entity) -> error::Result<()> { app_mut(|app| { flush(app, graphics_entity)?; @@ -1397,7 +1425,7 @@ pub fn graphics_immediate_light( graphics_entity: Entity, kind: render::command::LightKind, transform: Transform, -) -> error::Result<()> { +) -> error::Result { app_mut(|app| { let light_entity = app .world_mut() @@ -1411,7 +1439,8 @@ pub fn graphics_immediate_light( graphics::record_command, (graphics_entity, DrawCommand::Light(light_entity)), ) - .unwrap() + .unwrap()?; + Ok(light_entity) }) } @@ -2821,11 +2850,28 @@ fn text_query_state( render::primitive::text::OwnedTextParams, text::font::TextContext, )> { - let state = app - .world() + let world = app.world(); + let state = world .get::(graphics_entity) .ok_or(error::ProcessingError::GraphicsNotFound)?; - let params = render::primitive::text::OwnedTextParams::from_render_state(state, max_w, max_h); + // plus unflushed text settings + let mut style = state.style.clone(); + if let Some(buffer) = world.get::(graphics_entity) { + for cmd in buffer.iter() { + match cmd { + DrawCommand::PushStyle => style.push(), + DrawCommand::PopStyle => style.pop(), + cmd => { + style.apply_text(cmd, |font| { + world + .get::(font) + .map(|f| f.family_name.clone()) + }); + } + } + } + } + let params = render::primitive::text::OwnedTextParams::from_style(&style, max_w, max_h); let text_cx = app.world().resource::().clone(); Ok((params, text_cx)) } diff --git a/crates/processing_render/src/render/command.rs b/crates/processing_render/src/render/command.rs index 7e19f613..812e36be 100644 --- a/crates/processing_render/src/render/command.rs +++ b/crates/processing_render/src/render/command.rs @@ -765,21 +765,68 @@ pub enum DrawCommand { #[derive(Debug, Default, Component)] pub struct CommandBuffer { - pub commands: Vec, + commands: Vec, + generation: u64, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct CommandSlot { + graphics: Entity, + index: usize, + generation: u64, +} + +impl CommandSlot { + pub fn graphics(&self) -> Entity { + self.graphics + } } impl CommandBuffer { pub fn new() -> Self { - Self { - commands: Vec::new(), - } + Self::default() } pub fn push(&mut self, cmd: DrawCommand) { self.commands.push(cmd); } + pub fn push_slot(&mut self, graphics: Entity, cmd: DrawCommand) -> CommandSlot { + self.commands.push(cmd); + CommandSlot { + graphics, + index: self.commands.len() - 1, + generation: self.generation, + } + } + + pub fn get_mut(&mut self, slot: CommandSlot) -> Option<&mut DrawCommand> { + if slot.generation != self.generation { + return None; + } + self.commands.get_mut(slot.index) + } + + pub fn is_empty(&self) -> bool { + self.commands.is_empty() + } + + pub fn iter(&self) -> impl Iterator { + self.commands.iter() + } + + pub fn take(&mut self) -> Vec { + self.generation += 1; + std::mem::take(&mut self.commands) + } + + pub fn requeue(&mut self, commands: impl IntoIterator) { + self.generation += 1; + self.commands = commands.into_iter().collect(); + } + pub fn clear(&mut self) { + self.generation += 1; self.commands.clear(); } } diff --git a/crates/processing_render/src/render/mod.rs b/crates/processing_render/src/render/mod.rs index 35ed401c..bf0aec61 100644 --- a/crates/processing_render/src/render/mod.rs +++ b/crates/processing_render/src/render/mod.rs @@ -208,7 +208,7 @@ pub fn flush_draw_commands( } } - let draw_commands = std::mem::take(&mut cmd_buffer.commands); + let draw_commands = cmd_buffer.take(); let mut batch = BatchState::new(graphics_entity, render_layers.clone()); let mut pending = draw_commands.into_iter(); let mut drained = true; @@ -218,6 +218,23 @@ pub fn flush_draw_commands( let opens_pass = |batch: &BatchState| batch.draw_index == 0 && batch.current_mesh.is_none(); match cmd { + DrawCommand::TextFont(_) + | DrawCommand::TextStyle(_) + | DrawCommand::TextWeight(_) + | DrawCommand::TextVariation { .. } + | DrawCommand::ClearTextVariations + | DrawCommand::TextFeature { .. } + | DrawCommand::NoTextFeature { .. } + | DrawCommand::ClearTextFeatures + | DrawCommand::TextSize(_) + | DrawCommand::TextAlign { .. } + | DrawCommand::TextLeading(_) + | DrawCommand::TextWrap(_) + | DrawCommand::TextGlyphColors(_) => { + state.style.apply_text(&cmd, |font| { + p_fonts.get(font).ok().map(|f| f.family_name.clone()) + }); + } DrawCommand::Light(entity) => { if let Ok((light, transform)) = p_lights.get(entity) { let placed = crate::light::place(state.transform.current(), transform); @@ -900,7 +917,7 @@ pub fn flush_draw_commands( } DrawCommand::BackgroundColor(color) => { if !opens_pass(&batch) { - cmd_buffer.commands = std::iter::once(cmd).chain(pending).collect(); + cmd_buffer.requeue(std::iter::once(cmd).chain(pending)); drained = false; break; } @@ -913,7 +930,7 @@ pub fn flush_draw_commands( continue; }; if !opens_pass(&batch) { - cmd_buffer.commands = std::iter::once(cmd).chain(pending).collect(); + cmd_buffer.requeue(std::iter::once(cmd).chain(pending)); drained = false; break; } @@ -1282,71 +1299,6 @@ pub fn flush_draw_commands( &p_material_handles, ); } - DrawCommand::TextFont(font_entity) => { - if let Some(entity) = font_entity { - if let Ok(font) = p_fonts.get(entity) { - state.style.text_font_family = Some(font.family_name.clone()); - } - } else { - state.style.text_font_family = None; - } - } - DrawCommand::TextStyle(style) => { - state.style.text_style = style; - } - DrawCommand::TextWeight(weight) => { - state.style.text_weight = Some(weight); - } - DrawCommand::TextVariation { tag, value } => { - if let Some(existing) = state - .style - .text_variations - .iter_mut() - .find(|(t, _)| *t == tag) - { - existing.1 = value; - } else { - state.style.text_variations.push((tag, value)); - } - } - DrawCommand::ClearTextVariations => { - state.style.text_variations.clear(); - } - DrawCommand::TextFeature { tag, value } => { - if let Some(existing) = state - .style - .text_features - .iter_mut() - .find(|(t, _)| *t == tag) - { - existing.1 = value; - } else { - state.style.text_features.push((tag, value)); - } - } - DrawCommand::NoTextFeature { tag } => { - state.style.text_features.retain(|(t, _)| *t != tag); - } - DrawCommand::ClearTextFeatures => { - state.style.text_features.clear(); - } - DrawCommand::TextSize(size) => { - state.style.text_size = size; - state.style.text_leading = None; - } - DrawCommand::TextAlign { h, v } => { - state.style.text_align_h = h; - state.style.text_align_v = v; - } - DrawCommand::TextLeading(leading) => { - state.style.text_leading = Some(leading); - } - DrawCommand::TextWrap(mode) => { - state.style.text_wrap = mode; - } - DrawCommand::TextGlyphColors(colors) => { - state.style.text_glyph_colors = Some(colors); - } DrawCommand::Text { content, x, diff --git a/crates/processing_render/src/render/primitive/text.rs b/crates/processing_render/src/render/primitive/text.rs index 5cc4ab73..fb8f0567 100644 --- a/crates/processing_render/src/render/primitive/text.rs +++ b/crates/processing_render/src/render/primitive/text.rs @@ -24,6 +24,7 @@ use skrifa::{ outline::{DrawSettings, OutlinePen}, }; +use crate::render::style::Style; use crate::render::{ RenderState, command::{TextAlignH, TextAlignV, TextStyle, TextWrapMode}, @@ -91,19 +92,23 @@ impl OwnedTextParams { /// Snapshot a `RenderState`'s text state. `glyph_colors` is left unset; the /// draw path fills it in, measurement queries don't need it. pub fn from_render_state(state: &RenderState, max_w: Option, max_h: Option) -> Self { + Self::from_style(&state.style, max_w, max_h) + } + + pub fn from_style(style: &Style, max_w: Option, max_h: Option) -> Self { Self { - text_size: state.style.text_size, - align_h: state.style.text_align_h, - align_v: state.style.text_align_v, - leading: state.style.text_leading, + text_size: style.text_size, + align_h: style.text_align_h, + align_v: style.text_align_v, + leading: style.text_leading, max_w, max_h, - wrap: state.style.text_wrap, - font_family: state.style.text_font_family.clone(), - text_style: state.style.text_style, - text_weight: state.style.text_weight, - text_variations: state.style.text_variations.clone(), - text_features: state.style.text_features.clone(), + wrap: style.text_wrap, + font_family: style.text_font_family.clone(), + text_style: style.text_style, + text_weight: style.text_weight, + text_variations: style.text_variations.clone(), + text_features: style.text_features.clone(), glyph_colors: None, } } @@ -473,8 +478,7 @@ pub fn text_to_points( }) } -/// 3D extruded mesh from text outlines: front and back faces plus side walls, -/// in Bevy's Y-up convention. +/// 3D extruded mesh from text outlines: front and back faces plus side walls. pub fn text_to_model( content: &str, x: f32, @@ -610,6 +614,8 @@ pub fn text_to_model( } }); + // built y-up + crate::geometry::mirror_y(&mut mesh); mesh } diff --git a/crates/processing_render/src/render/style.rs b/crates/processing_render/src/render/style.rs index 63495c58..94dab92e 100644 --- a/crates/processing_render/src/render/style.rs +++ b/crates/processing_render/src/render/style.rs @@ -2,7 +2,7 @@ use std::ops::{Deref, DerefMut}; use bevy::{math::Affine2, prelude::*, render::render_resource::BlendState}; -use super::command::{ShapeMode, TextAlignH, TextAlignV, TextStyle, TextWrapMode}; +use super::command::{DrawCommand, ShapeMode, TextAlignH, TextAlignV, TextStyle, TextWrapMode}; use super::material::MaterialKey; use super::primitive::StrokeConfig; @@ -48,6 +48,54 @@ pub struct Style { pub text_glyph_colors: Option>, } +impl Style { + /// False if `cmd` isn't a text setting. + pub fn apply_text( + &mut self, + cmd: &DrawCommand, + font_family: impl FnOnce(Entity) -> Option, + ) -> bool { + match cmd { + DrawCommand::TextFont(Some(font)) => { + if let Some(family) = font_family(*font) { + self.text_font_family = Some(family); + } + } + DrawCommand::TextFont(None) => self.text_font_family = None, + DrawCommand::TextStyle(style) => self.text_style = *style, + DrawCommand::TextWeight(weight) => self.text_weight = Some(*weight), + DrawCommand::TextVariation { tag, value } => { + match self.text_variations.iter_mut().find(|(t, _)| t == tag) { + Some(existing) => existing.1 = *value, + None => self.text_variations.push((*tag, *value)), + } + } + DrawCommand::ClearTextVariations => self.text_variations.clear(), + DrawCommand::TextFeature { tag, value } => { + match self.text_features.iter_mut().find(|(t, _)| t == tag) { + Some(existing) => existing.1 = *value, + None => self.text_features.push((*tag, *value)), + } + } + DrawCommand::NoTextFeature { tag } => self.text_features.retain(|(t, _)| t != tag), + DrawCommand::ClearTextFeatures => self.text_features.clear(), + DrawCommand::TextSize(size) => { + self.text_size = *size; + self.text_leading = None; + } + DrawCommand::TextAlign { h, v } => { + self.text_align_h = *h; + self.text_align_v = *v; + } + DrawCommand::TextLeading(leading) => self.text_leading = Some(*leading), + DrawCommand::TextWrap(mode) => self.text_wrap = *mode, + DrawCommand::TextGlyphColors(colors) => self.text_glyph_colors = Some(colors.clone()), + _ => return false, + } + true + } +} + impl Default for Style { fn default() -> Self { Self { diff --git a/crates/processing_render/src/shader_property.rs b/crates/processing_render/src/shader_property.rs index f42e5a0c..0213b628 100644 --- a/crates/processing_render/src/shader_property.rs +++ b/crates/processing_render/src/shader_property.rs @@ -4,6 +4,7 @@ use bevy_naga_reflect::dynamic_shader::DynamicShader; use bevy_naga_reflect::reflect::ParameterCategory; use crate::compute::{Buffer, Compute, MeshBindingRef}; +use crate::geometry::Geometry; use crate::image::Image as PImage; use crate::material::custom::{apply_field_coerced, apply_reflect_field, shader_value_to_reflect}; use crate::particles::grid::Grid; @@ -30,10 +31,30 @@ fn require_read_only_storage(shader: &DynamicShader, name: &str, kind: &str) -> Ok(()) } -fn bind_compute_mesh(compute: &mut Compute, name: String, value: ShaderValue) -> Result<()> { +fn bind_compute_mesh( + compute: &mut Compute, + name: String, + value: ShaderValue, + geometries: &Query<&Geometry>, + meshes: &mut Assets, +) -> Result<()> { match value { ShaderValue::MeshAttribute(geom, attribute) => { require_read_only_storage(&compute.shader, &name, "mesh attribute")?; + // an attribute binds as its own vertex buffer + let handle = &geometries + .get(geom) + .map_err(|_| ProcessingError::GeometryNotFound)? + .handle; + let mesh = meshes + .get(handle) + .ok_or(ProcessingError::GeometryNotFound)?; + if mesh.binding_count() < mesh.attributes().count() { + meshes + .get_mut(handle) + .ok_or(ProcessingError::GeometryNotFound)? + .deinterleave(); + } compute .mesh_bindings .insert(name, MeshBindingRef::Attribute { geom, attribute }); @@ -155,10 +176,12 @@ pub fn set_property( mut p_buffers: Query<&mut Buffer>, mut p_images: Query<&mut PImage>, grids: Query<&Grid>, + geometries: Query<&Geometry>, + mut meshes: ResMut>, ) -> Result { let shader = if let Ok(compute) = computes.get_mut(entity) { if let ShaderValue::MeshAttribute(..) | ShaderValue::MeshIndex(..) = value { - bind_compute_mesh(compute.into_inner(), name, value)?; + bind_compute_mesh(compute.into_inner(), name, value, &geometries, &mut meshes)?; return Ok(true); } &mut compute.into_inner().shader diff --git a/crates/processing_wasm/src/lib.rs b/crates/processing_wasm/src/lib.rs index 3153b783..61dda412 100644 --- a/crates/processing_wasm/src/lib.rs +++ b/crates/processing_wasm/src/lib.rs @@ -5,9 +5,9 @@ use bevy::color::LinearRgba; use bevy::math::{Vec2, Vec3, Vec4}; use bevy::prelude::Entity; use bevy::render::render_resource::{Extent3d, TextureFormat}; -use processing::prelude::color::{ColorMode, ColorSpace}; -use processing::prelude::error::ProcessingError; -use processing::prelude::*; +use processing::engine::color::{ColorMode, ColorSpace}; +use processing::engine::error::ProcessingError; +use processing::engine::*; use wasm_bindgen::prelude::*; fn check(result: Result) -> Result { @@ -160,12 +160,12 @@ pub fn js_color_mode( ) -> Result<(), JsValue> { let graphics_entity = Entity::from_bits(graphics_id); check((|| { - let space = processing::prelude::color::ColorSpace::from_u8(space).ok_or_else(|| { - processing::prelude::error::ProcessingError::InvalidArgument(format!( + let space = processing::engine::color::ColorSpace::from_u8(space).ok_or_else(|| { + processing::engine::error::ProcessingError::InvalidArgument(format!( "unknown color space: {space}" )) })?; - let mode = processing::prelude::color::ColorMode::new(space, max1, max2, max3, max_alpha); + let mode = processing::engine::color::ColorMode::new(space, max1, max2, max3, max_alpha); graphics_set_color_mode(graphics_entity, mode) })()) } @@ -233,7 +233,7 @@ pub fn js_set_stroke_cap(graphics_id: u64, cap: u8) -> Result<(), JsValue> { let graphics_entity = Entity::from_bits(graphics_id); check(graphics_record_command( graphics_entity, - DrawCommand::StrokeCap(processing::prelude::StrokeCapMode::from(cap)), + DrawCommand::StrokeCap(processing::engine::StrokeCapMode::from(cap)), )) } @@ -242,7 +242,7 @@ pub fn js_set_stroke_join(graphics_id: u64, join: u8) -> Result<(), JsValue> { let graphics_entity = Entity::from_bits(graphics_id); check(graphics_record_command( graphics_entity, - DrawCommand::StrokeJoin(processing::prelude::StrokeJoinMode::from(join)), + DrawCommand::StrokeJoin(processing::engine::StrokeJoinMode::from(join)), )) } @@ -251,7 +251,7 @@ pub fn js_rect_mode(graphics_id: u64, mode: u8) -> Result<(), JsValue> { let graphics_entity = Entity::from_bits(graphics_id); check(graphics_record_command( graphics_entity, - DrawCommand::RectMode(processing::prelude::ShapeMode::from(mode)), + DrawCommand::RectMode(processing::engine::ShapeMode::from(mode)), )) } @@ -260,7 +260,7 @@ pub fn js_ellipse_mode(graphics_id: u64, mode: u8) -> Result<(), JsValue> { let graphics_entity = Entity::from_bits(graphics_id); check(graphics_record_command( graphics_entity, - DrawCommand::EllipseMode(processing::prelude::ShapeMode::from(mode)), + DrawCommand::EllipseMode(processing::engine::ShapeMode::from(mode)), )) } @@ -361,7 +361,7 @@ pub fn js_shear_y(graphics_id: u64, angle: f32) -> Result<(), JsValue> { pub fn js_set_blend_mode(graphics_id: u64, mode: u8) -> Result<(), JsValue> { let graphics_entity = Entity::from_bits(graphics_id); check((|| { - let blend_state = processing::prelude::BlendMode::try_from(mode)?.to_blend_state(); + let blend_state = processing::engine::BlendMode::try_from(mode)?.to_blend_state(); graphics_record_command(graphics_entity, DrawCommand::BlendMode(blend_state)) })()) } @@ -534,7 +534,7 @@ pub fn js_arc( h, start, stop, - mode: processing::prelude::ArcMode::from(mode), + mode: processing::engine::ArcMode::from(mode), }, )) } @@ -698,7 +698,7 @@ pub fn js_begin_shape(graphics_id: u64, kind: u8) -> Result<(), JsValue> { check(graphics_record_command( graphics_entity, DrawCommand::BeginShape { - kind: processing::prelude::ShapeKind::from(kind), + kind: processing::engine::ShapeKind::from(kind), }, )) } @@ -2059,7 +2059,7 @@ pub fn js_mouse_wheel() -> Result { check(input_mouse_wheel()) } -fn key_code_from_u32(val: u32) -> processing::prelude::error::Result { +fn key_code_from_u32(val: u32) -> processing::engine::error::Result { match val { PROCESSING_KEY_SPACE => Ok(KeyCode::Space), PROCESSING_KEY_QUOTE => Ok(KeyCode::Quote), diff --git a/examples/alias_spike.rs b/examples/alias_spike.rs index c76c61b5..d99bdd9b 100644 --- a/examples/alias_spike.rs +++ b/examples/alias_spike.rs @@ -21,57 +21,48 @@ fn main(@builtin(global_invocation_id) gid: vec3) { } "#; -fn f32s(bytes: &[u8]) -> Vec { - bytes - .chunks_exact(4) - .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) - .collect() -} -fn to_bytes(v: &[f32]) -> Vec { - v.iter().flat_map(|f| f.to_le_bytes()).collect() -} +struct AliasSpike; -fn run() -> error::Result<()> { - init(Config::default())?; - let surface = surface_create_offscreen(1, 1, 1.0, TextureFormat::Rgba8Unorm)?; - let _graphics = graphics_create(surface, 1, 1, TextureFormat::Rgba8Unorm)?; +impl Sketch for AliasSpike { + fn settings() -> Settings { + Settings::size(1, 1).headless() + } - let base = [1.0f32, 2.0, 3.0, 4.0]; + fn setup(g: &mut Graphics) -> Result { + let base = [1.0f32, 2.0, 3.0, 4.0]; + let mut two = Compute::new(&Shader::new(TWO_BINDING_SRC)?)?; - let two = compute_create(shader_create(TWO_BINDING_SRC)?)?; - let a_src = buffer_create_with_data(to_bytes(&base))?; - let a_dst = buffer_create_with_data(to_bytes(&[0.0; 4]))?; - compute_set(two, "src", shader_value::ShaderValue::Buffer(a_src))?; - compute_set(two, "dst", shader_value::ShaderValue::Buffer(a_dst))?; - compute_dispatch(two, 1, 1, 1)?; - println!( - "A distinct read+read_write -> {:?}", - f32s(&buffer_read(a_dst)?) - ); + let a_src = Buffer::from_slice(&base)?; + let a_dst = Buffer::from_slice(&[0.0f32; 4])?; + two.set("src", &a_src); + two.set("dst", &a_dst); + two.dispatch(1, 1, 1); + println!("A distinct read+read_write -> {:?}", a_dst.read::()?); - let one = compute_create(shader_create(ONE_BINDING_SRC)?)?; - let c = buffer_create_with_data(to_bytes(&base))?; - compute_set(one, "data", shader_value::ShaderValue::Buffer(c))?; - compute_dispatch(one, 1, 1, 1)?; - println!( - "C single read_write in-place-> {:?} (want [2,4,6,8])", - f32s(&buffer_read(c)?) - ); + let mut one = Compute::new(&Shader::new(ONE_BINDING_SRC)?)?; + let c = Buffer::from_slice(&base)?; + one.set("data", &c); + one.dispatch(1, 1, 1); + println!( + "C single read_write in-place-> {:?} (want [2,4,6,8])", + c.read::()? + ); - let b = buffer_create_with_data(to_bytes(&base))?; - compute_set(two, "src", shader_value::ShaderValue::Buffer(b))?; - compute_set(two, "dst", shader_value::ShaderValue::Buffer(b))?; - println!("B aliased read+read_write -> dispatching (expect fatal Validation Error)..."); - compute_dispatch(two, 1, 1, 1)?; - println!( - "B aliased read+read_write -> {:?} (want [2,4,6,8])", - f32s(&buffer_read(b)?) - ); + let b = Buffer::from_slice(&base)?; + two.set("src", &b); + two.set("dst", &b); + println!("B aliased read+read_write -> dispatching (expect fatal Validation Error)..."); + two.dispatch(1, 1, 1); + println!( + "B aliased read+read_write -> {:?} (want [2,4,6,8])", + b.read::()? + ); - Ok(()) + g.exit(); + Ok(AliasSpike) + } } -fn main() { - run().unwrap(); - exit(0).unwrap(); +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/animated_mesh.rs b/examples/animated_mesh.rs index 8d5f7e84..80f1c8c0 100644 --- a/examples/animated_mesh.rs +++ b/examples/animated_mesh.rs @@ -1,102 +1,71 @@ -use processing_glfw::GlfwContext; - -use bevy::math::{Vec3, Vec4}; use processing::prelude::*; -use processing_render::geometry::Topology; -use processing_render::render::command::DrawCommand; - -fn main() { - match sketch() { - Ok(_) => { - eprintln!("Sketch completed successfully"); - exit(0).unwrap(); - } - Err(e) => { - eprintln!("Sketch error: {:?}", e); - exit(1).unwrap(); - } - }; -} -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(600, 600, false)?; - init(Config::default())?; +const GRID: u32 = 20; +const SPACING: f32 = 10.0; - let width = 600; - let height = 600; - let surface = glfw_ctx.create_surface(width, height, false)?; - let graphics = graphics_create(surface, width, height, TextureFormat::Rgba16Float)?; - - let grid_size = 20; - let spacing = 10.0; - let offset = (grid_size as f32 * spacing) / 2.0; - - let mesh = geometry_create(Topology::TriangleList)?; +struct AnimatedMesh { + mesh: Geometry, + time: f32, +} - for z in 0..grid_size { - for x in 0..grid_size { - let px = x as f32 * spacing - offset; - let pz = z as f32 * spacing - offset; - geometry_color( - mesh, - Vec4::new( - x as f32 / grid_size as f32, - 0.5, - z as f32 / grid_size as f32, - 1.0, - ), - )?; - geometry_normal(mesh, Vec3::new(0.0, -1.0, 0.0))?; - geometry_vertex(mesh, Vec3::new(px, 0.0, pz))?; - } +impl Sketch for AnimatedMesh { + fn settings() -> Settings { + Settings::size(600, 600) } - for z in 0..(grid_size - 1) { - for x in 0..(grid_size - 1) { - let tl = z * grid_size + x; - let tr = tl + 1; - let bl = (z + 1) * grid_size + x; - let br = bl + 1; - - geometry_index(mesh, tl)?; - geometry_index(mesh, bl)?; - geometry_index(mesh, tr)?; - - geometry_index(mesh, tr)?; - geometry_index(mesh, bl)?; - geometry_index(mesh, br)?; + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((150, -150, 150)); + g.camera_look_at((0, 0, 0)); + + let offset = GRID as f32 * SPACING / 2.0; + let mut mesh = Geometry::new(Topology::TriangleList)?; + for z in 0..GRID { + for x in 0..GRID { + let px = x as f32 * SPACING - offset; + let pz = z as f32 * SPACING - offset; + mesh.color((x as f32 / GRID as f32, 0.5, z as f32 / GRID as f32)); + mesh.normal((0, -1, 0)); + mesh.vertex((px, 0.0, pz)); + } } - } - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(150.0, -150.0, 150.0))?; - transform_look_at(graphics, Vec3::new(0.0, 0.0, 0.0))?; + for z in 0..GRID - 1 { + for x in 0..GRID - 1 { + let top_left = z * GRID + x; + let top_right = top_left + 1; + let bottom_left = (z + 1) * GRID + x; + let bottom_right = bottom_left + 1; + mesh.index(top_left); + mesh.index(bottom_left); + mesh.index(top_right); + mesh.index(top_right); + mesh.index(bottom_left); + mesh.index(bottom_right); + } + } - let mut time = 0.0f32; + Ok(AnimatedMesh { mesh, time: 0.0 }) + } - while glfw_ctx.poll_events() { - for z in 0..grid_size { - for x in 0..grid_size { - let idx = z * grid_size + x; - let px = x as f32 * spacing - offset; - let pz = z as f32 * spacing - offset; - let wave = (px * 0.1 + time).sin() * (pz * 0.1 + time).cos() * 20.0; - geometry_set_vertex(mesh, idx, Vec3::new(px, -wave, pz))?; + fn draw(&mut self, g: &mut Graphics) { + let offset = GRID as f32 * SPACING / 2.0; + for z in 0..GRID { + for x in 0..GRID { + let px = x as f32 * SPACING - offset; + let pz = z as f32 * SPACING - offset; + let wave = (px * 0.1 + self.time).sin() * (pz * 0.1 + self.time).cos() * 20.0; + self.mesh.set_vertex(z * GRID + x, (px, -wave, pz)); } } - graphics_begin_draw(graphics)?; - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.05, 0.05, 0.1)), - )?; - graphics_record_command(graphics, DrawCommand::Geometry(mesh))?; - graphics_end_draw(graphics)?; + g.background((0.05, 0.05, 0.1)); + g.model(&self.mesh); - time += 0.05; + self.time += 0.05; } +} - geometry_destroy(mesh)?; - - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/background_image.rs b/examples/background_image.rs index 18c1f1b0..658001af 100644 --- a/examples/background_image.rs +++ b/examples/background_image.rs @@ -1,37 +1,24 @@ -use processing_glfw::GlfwContext; - use processing::prelude::*; -use processing_render::render::command::DrawCommand; -fn main() { - match sketch() { - Ok(_) => { - eprintln!("Sketch completed successfully"); - exit(0).unwrap(); - } - Err(e) => { - eprintln!("Sketch error: {:?}", e); - exit(1).unwrap(); - } - }; +struct BackgroundImage { + logo: Image, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(400, 400, false)?; - init(Config::default())?; - - let width = 400; - let height = 400; - let surface = glfw_ctx.create_surface(width, height, false)?; - let graphics = graphics_create(surface, width, height, TextureFormat::Rgba16Float)?; - let image = image_load("images/logo.png")?; - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; +impl Sketch for BackgroundImage { + fn settings() -> Settings { + Settings::size(400, 400) + } - graphics_record_command(graphics, DrawCommand::BackgroundImage(image))?; + fn setup(_g: &mut Graphics) -> Result { + let logo = Image::load("images/logo.png")?; + Ok(BackgroundImage { logo }) + } - graphics_end_draw(graphics)?; + fn draw(&mut self, g: &mut Graphics) { + g.background_image(&self.logo); } - Ok(()) +} + +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/blend_modes.rs b/examples/blend_modes.rs index e23cb810..9ece9cfe 100644 --- a/examples/blend_modes.rs +++ b/examples/blend_modes.rs @@ -1,8 +1,6 @@ -use processing_glfw::GlfwContext; - use processing::prelude::*; -const MODES: &[BlendMode] = &[ +const MODES: [BlendMode; 10] = [ BlendMode::Blend, BlendMode::Add, BlendMode::Subtract, @@ -15,95 +13,43 @@ const MODES: &[BlendMode] = &[ BlendMode::Replace, ]; -fn main() { - match sketch() { - Ok(_) => exit(0).unwrap(), - Err(e) => { - eprintln!("Error: {e:?}"); - exit(1).unwrap(); - } - } +struct BlendModes { + index: usize, } -fn sketch() -> error::Result<()> { - let width = 500; - let height = 500; - let mut glfw_ctx = GlfwContext::new(width, height, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(width, height, false)?; - let graphics = graphics_create(surface, width, height, TextureFormat::Rgba16Float)?; +impl Sketch for BlendModes { + fn settings() -> Settings { + Settings::size(500, 500) + } - let mut index: usize = 0; + fn setup(_g: &mut Graphics) -> Result { + Ok(BlendModes { index: 0 }) + } - while glfw_ctx.poll_events() { - if input_key_just_pressed(KeyCode::ArrowRight)? || input_key_just_pressed(KeyCode::Space)? { - index = (index + 1) % MODES.len(); - eprintln!("{}", MODES[index].name()); - } else if input_key_just_pressed(KeyCode::ArrowLeft)? { - index = (index + MODES.len() - 1) % MODES.len(); - eprintln!("{}", MODES[index].name()); + fn draw(&mut self, g: &mut Graphics) { + if g.key_just_pressed(Key::Right) || g.key_just_pressed(Key::Space) { + self.index = (self.index + 1) % MODES.len(); + eprintln!("{}", MODES[self.index].name()); + } else if g.key_just_pressed(Key::Left) { + self.index = (self.index + MODES.len() - 1) % MODES.len(); + eprintln!("{}", MODES[self.index].name()); } - graphics_begin_draw(graphics)?; - - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgba(0.15, 0.15, 0.15, 1.0)), - )?; - graphics_record_command(graphics, DrawCommand::NoStroke)?; - graphics_record_command( - graphics, - DrawCommand::BlendMode(MODES[index].to_blend_state()), - )?; + g.background((0.15, 0.15, 0.15)); + g.no_stroke(); + g.blend_mode(MODES[self.index]); - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgba(0.9, 0.2, 0.2, 0.75)), - )?; - graphics_record_command( - graphics, - DrawCommand::Rect { - x: 80.0, - y: 100.0, - w: 200.0, - h: 250.0, - radii: [0.0; 4], - }, - )?; + g.fill((0.9, 0.2, 0.2, 0.75)); + g.rect(80, 100, 200, 250); - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgba(0.2, 0.8, 0.2, 0.75)), - )?; - graphics_record_command( - graphics, - DrawCommand::Rect { - x: 180.0, - y: 80.0, - w: 200.0, - h: 250.0, - radii: [0.0; 4], - }, - )?; + g.fill((0.2, 0.8, 0.2, 0.75)); + g.rect(180, 80, 200, 250); - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgba(0.2, 0.3, 0.9, 0.75)), - )?; - graphics_record_command( - graphics, - DrawCommand::Rect { - x: 130.0, - y: 200.0, - w: 200.0, - h: 200.0, - radii: [0.0; 4], - }, - )?; - - graphics_end_draw(graphics)?; + g.fill((0.2, 0.3, 0.9, 0.75)); + g.rect(130, 200, 200, 200); } +} - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/box.rs b/examples/box.rs index e687228f..f2e08751 100644 --- a/examples/box.rs +++ b/examples/box.rs @@ -1,60 +1,37 @@ -use processing_glfw::GlfwContext; - -use bevy::math::Vec3; use processing::prelude::*; -use processing_render::render::command::DrawCommand; -fn main() { - match sketch() { - Ok(_) => { - eprintln!("Sketch completed successfully"); - exit(0).unwrap(); - } - Err(e) => { - eprintln!("Sketch error: {:?}", e); - exit(1).unwrap(); - } - }; +struct BoxSketch { + cube: Geometry, + angle: f32, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(400, 400, false)?; - init(Config::default())?; - - let width = 400; - let height = 400; - let surface = glfw_ctx.create_surface(width, height, false)?; - let graphics = graphics_create(surface, width, height, TextureFormat::Rgba16Float)?; - let box_geo = geometry_box(100.0, 100.0, 100.0)?; - - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(100.0, -100.0, 300.0))?; - transform_look_at(graphics, Vec3::new(0.0, 0.0, 0.0))?; - - let mut angle: f32 = 0.0; +impl Sketch for BoxSketch { + fn settings() -> Settings { + Settings::size(400, 400) + } - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((100, -100, 300)); + g.camera_look_at((0, 0, 0)); - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.1, 0.1, 0.15)), - )?; + let cube = Geometry::cube(100)?; + Ok(BoxSketch { cube, angle: 0.0 }) + } - graphics_record_command(graphics, DrawCommand::PushMatrix)?; - graphics_record_command( - graphics, - DrawCommand::Rotate { - angle: -angle, - axis: Vec3::Z, - }, - )?; - graphics_record_command(graphics, DrawCommand::Geometry(box_geo))?; - graphics_record_command(graphics, DrawCommand::PopMatrix)?; + fn draw(&mut self, g: &mut Graphics) { + g.background((0.1, 0.1, 0.15)); - graphics_end_draw(graphics)?; + { + let g = g.push(); + g.rotate(-self.angle); + g.model(&self.cube); + } - angle += 0.02; + self.angle += 0.02; } - Ok(()) +} + +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/camera_controllers.rs b/examples/camera_controllers.rs index 16f21bb1..3a902631 100644 --- a/examples/camera_controllers.rs +++ b/examples/camera_controllers.rs @@ -1,104 +1,69 @@ -use processing_glfw::GlfwContext; - -use bevy::math::Vec3; use processing::prelude::*; -use processing_render::render::command::DrawCommand; -fn main() { - match sketch() { - Ok(_) => { - eprintln!("Sketch completed successfully"); - exit(0).unwrap(); - } - Err(e) => { - eprintln!("Sketch error: {:?}", e); - exit(1).unwrap(); - } - }; +struct CameraControllers { + cube: Geometry, + sun: Light, + angle: f32, + mode: u8, } -fn sketch() -> error::Result<()> { - let width = 800; - let height = 600; - let mut glfw_ctx = GlfwContext::new(width, height, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(width, height, false)?; - let graphics = graphics_create(surface, width, height, TextureFormat::Rgba16Float)?; - let box_geo = geometry_box(100.0, 100.0, 100.0)?; +impl Sketch for CameraControllers { + fn settings() -> Settings { + Settings::size(800, 600) + } - graphics_mode_3d(graphics)?; - graphics_orbit_camera(graphics)?; + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.orbit_camera(); - let dir_light = - light_create_directional(graphics, bevy::color::Color::srgb(1.0, 0.98, 0.95), 1_500.0)?; - transform_set_position(dir_light, Vec3::new(300.0, -400.0, 300.0))?; - transform_look_at(dir_light, Vec3::ZERO)?; + let sun = g.create_directional_light((1.0, 0.98, 0.95), 1500); + sun.position((300, -400, 300)).look_at((0, 0, 0)); - let mut angle: f32 = 0.0; - let mut mode = 0u8; + let cube = Geometry::cube(100)?; + Ok(CameraControllers { + cube, + sun, + angle: 0.0, + mode: 0, + }) + } - while glfw_ctx.poll_events() { - if input_key_just_pressed(KeyCode::Digit1)? { - graphics_mode_3d(graphics)?; - graphics_orbit_camera(graphics)?; - mode = 0; + fn draw(&mut self, g: &mut Graphics) { + if g.key_just_pressed(Key::Num1) { + g.mode_3d(); + g.orbit_camera(); + self.mode = 0; } - if input_key_just_pressed(KeyCode::Digit2)? { - graphics_mode_3d(graphics)?; - graphics_free_camera(graphics)?; - mode = 1; + if g.key_just_pressed(Key::Num2) { + g.mode_3d(); + g.free_camera(); + self.mode = 1; } - if input_key_just_pressed(KeyCode::Digit3)? { - graphics_mode_2d(graphics)?; - graphics_pan_camera(graphics)?; - mode = 2; + if g.key_just_pressed(Key::Num3) { + g.mode_2d(); + g.pan_camera(); + self.mode = 2; } - graphics_begin_draw(graphics)?; - graphics_light(graphics, dir_light)?; - - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.05, 0.05, 0.07)), - )?; + g.light(&self.sun); + g.background((0.05, 0.05, 0.07)); - if mode < 2 { - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgb(1.0, 0.85, 0.57)), - )?; - graphics_record_command(graphics, DrawCommand::Roughness(0.3))?; - graphics_record_command(graphics, DrawCommand::Metallic(0.8))?; - graphics_record_command(graphics, DrawCommand::PushMatrix)?; - graphics_record_command( - graphics, - DrawCommand::Rotate { - angle: -angle, - axis: Vec3::Z, - }, - )?; - graphics_record_command(graphics, DrawCommand::Geometry(box_geo))?; - graphics_record_command(graphics, DrawCommand::PopMatrix)?; + if self.mode < 2 { + g.fill((1.0, 0.85, 0.57)); + g.roughness(0.3); + g.metallic(0.8); + let g = g.push(); + g.rotate(-self.angle); + g.model(&self.cube); } else { - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgb(0.8, 0.3, 0.2)), - )?; - graphics_record_command( - graphics, - DrawCommand::Rect { - x: 300.0, - y: 200.0, - w: 200.0, - h: 200.0, - radii: [0.0; 4], - }, - )?; + g.fill((0.8, 0.3, 0.2)); + g.rect(300, 200, 200, 200); } - graphics_end_draw(graphics)?; - angle += 0.02; + self.angle += 0.02; } - Ok(()) +} + +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/compute_readback.rs b/examples/compute_readback.rs index cc160de7..4d3ad42d 100644 --- a/examples/compute_readback.rs +++ b/examples/compute_readback.rs @@ -1,24 +1,6 @@ use processing::prelude::*; -fn main() { - match run() { - Ok(_) => exit(0).unwrap(), - Err(e) => { - eprintln!("{e:?}"); - exit(1).unwrap(); - } - } -} - -fn run() -> error::Result<()> { - init(Config::default())?; - - let surface = surface_create_offscreen(1, 1, 1.0, TextureFormat::Rgba8Unorm)?; - let _graphics = graphics_create(surface, 1, 1, TextureFormat::Rgba8Unorm)?; - - let buf = buffer_create(16)?; - - let shader_src = r#" +const FILL: &str = r#" @group(0) @binding(0) var output: array; @@ -30,21 +12,8 @@ fn main() { output[3] = 4u; } "#; - let shader = shader_create(shader_src)?; - let compute = compute_create(shader)?; - compute_set(compute, "output", shader_value::ShaderValue::Buffer(buf))?; - compute_dispatch(compute, 1, 1, 1)?; - - let data = buffer_read(buf)?; - let values: Vec = data - .chunks_exact(4) - .map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]])) - .collect(); - - assert_eq!(values, vec![1, 2, 3, 4]); - - let double_src = r#" +const DOUBLE: &str = r#" @group(0) @binding(0) var data: array; @@ -53,29 +22,35 @@ fn main(@builtin(global_invocation_id) id: vec3) { data[id.x] = data[id.x] * 2.0; } "#; - let buf2_data: Vec = [1.0f32, 2.0, 3.0, 4.0] - .iter() - .flat_map(|f| f.to_le_bytes()) - .collect(); - let buf2 = buffer_create_with_data(buf2_data)?; - let shader2 = shader_create(double_src)?; - let compute2 = compute_create(shader2)?; - compute_set(compute2, "data", shader_value::ShaderValue::Buffer(buf2))?; - compute_dispatch(compute2, 1, 1, 1)?; - let data2 = buffer_read(buf2)?; - let floats: Vec = data2 - .chunks_exact(4) - .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) - .collect(); - assert_eq!(floats, vec![2.0, 4.0, 6.0, 8.0]); +struct ComputeReadback; - compute_destroy(compute)?; - compute_destroy(compute2)?; - shader_destroy(shader)?; - shader_destroy(shader2)?; - buffer_destroy(buf)?; - buffer_destroy(buf2)?; +impl Sketch for ComputeReadback { + fn settings() -> Settings { + Settings::size(1, 1).headless() + } + + fn setup(g: &mut Graphics) -> Result { + let output = Buffer::new(16)?; + let mut fill = Compute::new(&Shader::new(FILL)?)?; + fill.set("output", &output); + fill.dispatch(1, 1, 1); + let values: Vec = output.read()?; + assert_eq!(values, vec![1, 2, 3, 4]); + + let data = Buffer::from_slice(&[1.0f32, 2.0, 3.0, 4.0])?; + let mut double = Compute::new(&Shader::new(DOUBLE)?)?; + double.set("data", &data); + double.dispatch(1, 1, 1); + let doubled: Vec = data.read()?; + assert_eq!(doubled, vec![2.0, 4.0, 6.0, 8.0]); + + println!("{values:?} {doubled:?}"); + g.exit(); + Ok(ComputeReadback) + } +} - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/create_graphics.rs b/examples/create_graphics.rs new file mode 100644 index 00000000..28656178 --- /dev/null +++ b/examples/create_graphics.rs @@ -0,0 +1,40 @@ +use processing::prelude::*; + +struct CreateGraphics { + pg: Graphics, +} + +impl Sketch for CreateGraphics { + fn settings() -> Settings { + Settings::size(640, 360) + } + + fn setup(_g: &mut Graphics) -> Result { + let pg = Graphics::create(400, 200)?; + Ok(CreateGraphics { pg }) + } + + fn draw(&mut self, g: &mut Graphics) { + let mx = g.mouse_x(); + let my = g.mouse_y(); + + g.fill((0, 12)); + g.rect(0, 0, g.width(), g.height()); + g.fill(255); + g.no_stroke(); + g.ellipse(mx, my, 60, 60); + + let pg = self.pg.begin_draw(); + pg.background(51); + pg.no_fill(); + pg.stroke(255); + pg.ellipse(mx - 120.0, my - 60.0, 60, 60); + pg.end_draw(); + + g.image(&self.pg, 120, 60); + } +} + +fn main() -> Result<()> { + processing::run::() +} diff --git a/examples/curves.rs b/examples/curves.rs index b15ccdff..04d36765 100644 --- a/examples/curves.rs +++ b/examples/curves.rs @@ -1,105 +1,70 @@ -use processing_glfw::GlfwContext; - use processing::prelude::*; -use processing_render::render::command::DrawCommand; -fn main() { - sketch().unwrap(); - exit(0).unwrap(); +struct Curves { + t: f32, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(800, 400, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(800, 400, false)?; - let graphics = graphics_create(surface, 800, 400, TextureFormat::Rgba16Float)?; - - let mut t: f32 = 0.0; - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; +impl Sketch for Curves { + fn settings() -> Settings { + Settings::size(800, 400) + } - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.04, 0.04, 0.06)), - )?; + fn setup(_g: &mut Graphics) -> Result { + Ok(Curves { t: 0.0 }) + } - graphics_record_command(graphics, DrawCommand::NoFill)?; + fn draw(&mut self, g: &mut Graphics) { + let t = self.t; + g.background((0.04, 0.04, 0.06)); + g.no_fill(); - graphics_record_command(graphics, DrawCommand::StrokeWeight(1.5))?; + g.stroke_weight(1.5); for i in 0..20 { - let y_base = 20.0 + i as f32 * 15.0; + let y = 20.0 + i as f32 * 15.0; let phase = t + i as f32 * 0.3; let amp = 30.0 + (i as f32 * 0.5).sin() * 20.0; - let v = 0.3 + (i as f32 / 20.0) * 0.5; - graphics_record_command( - graphics, - DrawCommand::StrokeColor(bevy::color::Color::srgb(v * 0.6, v, (v * 1.2).min(1.0))), - )?; - - graphics_record_command( - graphics, - DrawCommand::Bezier { - x1: 0.0, - y1: y_base, - x2: 250.0, - y2: y_base + amp * phase.sin(), - x3: 550.0, - y3: y_base - amp * (phase * 1.3).cos(), - x4: 800.0, - y4: y_base, - }, - )?; + g.stroke((v * 0.6, v, (v * 1.2).min(1.0))); + g.bezier( + 0, + y, + 250, + y + amp * phase.sin(), + 550, + y - amp * (phase * 1.3).cos(), + 800, + y, + ); } - graphics_record_command(graphics, DrawCommand::StrokeWeight(0.8))?; + g.stroke_weight(0.8); + g.stroke((1.0, 0.6, 0.2, 0.4)); for i in 0..8 { - let y_base = 50.0 + i as f32 * 40.0; + let y = 50.0 + i as f32 * 40.0; let phase = t * 0.7 + i as f32 * 0.5; - - graphics_record_command( - graphics, - DrawCommand::StrokeColor(bevy::color::Color::srgba(1.0, 0.6, 0.2, 0.4)), - )?; - - graphics_record_command( - graphics, - DrawCommand::Curve { - x1: -50.0, - y1: y_base + 40.0 * phase.sin(), - x2: 200.0, - y2: y_base + 30.0 * (phase * 1.2).cos(), - x3: 600.0, - y3: y_base - 30.0 * (phase * 0.8).sin(), - x4: 850.0, - y4: y_base + 20.0 * phase.cos(), - }, - )?; + g.curve( + -50, + y + 40.0 * phase.sin(), + 200, + y + 30.0 * (phase * 1.2).cos(), + 600, + y - 30.0 * (phase * 0.8).sin(), + 850, + y + 20.0 * phase.cos(), + ); } - graphics_record_command(graphics, DrawCommand::StrokeWeight(0.3))?; - graphics_record_command( - graphics, - DrawCommand::StrokeColor(bevy::color::Color::srgba(1.0, 1.0, 1.0, 0.08)), - )?; + g.stroke_weight(0.3); + g.stroke((1.0, 1.0, 1.0, 0.08)); for i in 0..20 { - let y = 20.0 * i as f32; - graphics_record_command( - graphics, - DrawCommand::Line { - x1: 0.0, - y1: y, - x2: 800.0, - y2: y, - }, - )?; + let y = 20 * i; + g.line(0, y, 800, y); } - graphics_end_draw(graphics)?; - t += 0.012; + self.t += 0.012; } +} - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/custom_attribute.rs b/examples/custom_attribute.rs index 3bb2454c..041f6085 100644 --- a/examples/custom_attribute.rs +++ b/examples/custom_attribute.rs @@ -1,72 +1,50 @@ -use processing_glfw::GlfwContext; - -use bevy::math::{Vec3, Vec4}; use processing::prelude::*; -use processing_render::geometry::{AttributeFormat, Topology}; -use processing_render::render::command::DrawCommand; -fn main() { - match sketch() { - Ok(_) => { - eprintln!("Sketch completed successfully"); - exit(0).unwrap(); - } - Err(e) => { - eprintln!("Sketch error: {:?}", e); - exit(1).unwrap(); - } - }; +struct CustomAttribute { + mesh: Geometry, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(600, 600, false)?; - init(Config::default())?; - - let width = 600; - let height = 600; - let surface = glfw_ctx.create_surface(width, height, false)?; - let graphics = graphics_create(surface, width, height, TextureFormat::Rgba16Float)?; - - let custom_attr = geometry_attribute_create("Custom", AttributeFormat::Float)?; +impl Sketch for CustomAttribute { + fn settings() -> Settings { + Settings::size(600, 600) + } - let layout = geometry_layout_create()?; - geometry_layout_add_position(layout)?; - geometry_layout_add_normal(layout)?; - geometry_layout_add_color(layout)?; - geometry_layout_add_attribute(layout, custom_attr)?; + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((0, 0, 200)); + g.camera_look_at((0, 0, 0)); - let mesh = geometry_create_with_layout(layout, Topology::LineStrip)?; + let custom = Attribute::new("Custom", AttributeFormat::Float)?; + let layout = Layout::new()?.position().normal().color().attribute(custom); - geometry_color(mesh, Vec4::new(1.0, 0.0, 0.0, 1.0))?; - geometry_normal(mesh, Vec3::new(0.0, 0.0, 1.0))?; - geometry_attribute_float(mesh, custom_attr, 0.0)?; - geometry_vertex(mesh, Vec3::new(-50.0, 50.0, 0.0))?; + let mut mesh = Geometry::with_layout(&layout, Topology::LineStrip)?; + mesh.color((1.0, 0.0, 0.0)); + mesh.normal((0, 0, 1)); + mesh.attribute(custom, 0.0); + mesh.vertex((-50, 50)); - geometry_color(mesh, Vec4::new(0.0, 1.0, 0.0, 1.0))?; - geometry_attribute_float(mesh, custom_attr, 0.5)?; - geometry_vertex(mesh, Vec3::new(50.0, 50.0, 0.0))?; + mesh.color((0.0, 1.0, 0.0)); + mesh.attribute(custom, 0.5); + mesh.vertex((50, 50)); - geometry_color(mesh, Vec4::new(0.0, 0.0, 1.0, 1.0))?; - geometry_attribute_float(mesh, custom_attr, 1.0)?; - geometry_vertex(mesh, Vec3::new(0.0, -50.0, 0.0))?; + mesh.color((0.0, 0.0, 1.0)); + mesh.attribute(custom, 1.0); + mesh.vertex((0, -50)); - geometry_index(mesh, 0)?; - geometry_index(mesh, 1)?; - geometry_index(mesh, 2)?; - geometry_index(mesh, 0)?; + mesh.index(0); + mesh.index(1); + mesh.index(2); + mesh.index(0); - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(0.0, 0.0, 200.0))?; - transform_look_at(graphics, Vec3::new(0.0, 0.0, 0.0))?; + Ok(CustomAttribute { mesh }) + } - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.1, 0.1, 0.12)), - )?; - graphics_record_command(graphics, DrawCommand::Geometry(mesh))?; - graphics_end_draw(graphics)?; + fn draw(&mut self, g: &mut Graphics) { + g.background((0.1, 0.1, 0.12)); + g.model(&self.mesh); } - Ok(()) +} + +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/custom_material.rs b/examples/custom_material.rs index 533a8124..4441c69d 100644 --- a/examples/custom_material.rs +++ b/examples/custom_material.rs @@ -1,73 +1,47 @@ -use processing_glfw::GlfwContext; - -use bevy::math::Vec3; use processing::prelude::*; -use processing_render::render::command::DrawCommand; -fn main() { - match sketch() { - Ok(_) => { - eprintln!("Sketch completed successfully"); - exit(0).unwrap(); - } - Err(e) => { - eprintln!("Sketch error: {:?}", e); - exit(1).unwrap(); - } - }; +struct CustomMaterial { + cube: Geometry, + material: Material, + angle: f32, } -fn sketch() -> error::Result<()> { - let width = 400; - let height = 400; - let mut glfw_ctx = GlfwContext::new(width, height, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(width, height, false)?; - let graphics = graphics_create(surface, width, height, TextureFormat::Rgba16Float)?; - let box_geo = geometry_box(100.0, 100.0, 100.0)?; - - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(100.0, -100.0, 300.0))?; - transform_look_at(graphics, Vec3::new(0.0, 0.0, 0.0))?; - - let shader = shader_load("shaders/custom_material.wesl")?; - let mat = material_create_custom(shader)?; - material_set( - mat, - "color", - shader_value::ShaderValue::Float4([1.0, 0.2, 0.4, 1.0]), - )?; - - let mut angle = 0.0; - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; +impl Sketch for CustomMaterial { + fn settings() -> Settings { + Settings::size(400, 400) + } - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.1, 0.1, 0.15)), - )?; + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((100, -100, 300)); + g.camera_look_at((0, 0, 0)); + + let shader = Shader::load("shaders/custom_material.wesl")?; + let mut material = Material::new(&shader)?; + material.set("color", (1.0, 0.2, 0.4, 1.0)); + + let cube = Geometry::cube(100)?; + Ok(CustomMaterial { + cube, + material, + angle: 0.0, + }) + } - graphics_record_command(graphics, DrawCommand::PushMatrix)?; - graphics_record_command( - graphics, - DrawCommand::Rotate { - angle: -angle, - axis: Vec3::Z, - }, - )?; - graphics_record_command(graphics, DrawCommand::Material(mat))?; - graphics_record_command(graphics, DrawCommand::Geometry(box_geo))?; - graphics_record_command(graphics, DrawCommand::PopMatrix)?; + fn draw(&mut self, g: &mut Graphics) { + g.background((0.1, 0.1, 0.15)); - graphics_end_draw(graphics)?; + { + let g = g.push(); + g.rotate(-self.angle); + g.material(&self.material); + g.model(&self.cube); + } - angle += 0.02; + self.angle += 0.02; } +} - material_destroy(mat)?; - shader_destroy(shader)?; - - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/filter.rs b/examples/filter.rs index 6dc2fc87..152559df 100644 --- a/examples/filter.rs +++ b/examples/filter.rs @@ -1,93 +1,49 @@ -//! Cycles through all implemented filters. -use std::time::Instant; - -use bevy::color::Color; -use processing_glfw::GlfwContext; - use processing::prelude::*; -use processing_render::render::command::DrawCommand; -use processing_render::shader_value::ShaderValue; - -fn main() { - match sketch() { - Ok(_) => exit(0).unwrap(), - Err(e) => { - eprintln!("Sketch error: {:?}", e); - exit(1).unwrap(); - } - }; -} - -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(400, 400, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(400, 400, false)?; - let graphics = graphics_create(surface, 400, 400, TextureFormat::Rgba16Float)?; - - let palette = [ - (40.0, 40.0, Color::srgb(1.0, 0.2, 0.2)), - (200.0, 40.0, Color::srgb(0.2, 1.0, 0.2)), - (40.0, 200.0, Color::srgb(0.2, 0.4, 1.0)), - (200.0, 200.0, Color::srgb(0.95, 0.85, 0.2)), - ]; - let threshold = filter_threshold()?; - filter_set(threshold, "cutoff", ShaderValue::Float(0.5))?; - let posterize = filter_posterize()?; - filter_set(posterize, "levels", ShaderValue::UInt(4))?; - let blur = filter_blur()?; - filter_set(blur, "radius", ShaderValue::Float(4.0))?; - let filters = [ - filter_invert()?, - filter_gray()?, - threshold, - posterize, - filter_opaque()?, - filter_erode()?, - filter_dilate()?, - blur, - ]; - let start = Instant::now(); - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(Color::srgb(0.1, 0.1, 0.15)), - )?; - graphics_record_command(graphics, DrawCommand::NoStroke)?; - - for &(x, y, color) in &palette { - graphics_record_command(graphics, DrawCommand::Fill(color))?; - graphics_record_command( - graphics, - DrawCommand::Rect { - x, - y, - w: 160.0, - h: 160.0, - radii: [0.0; 4], - }, - )?; - } - - let idx = (start.elapsed().as_secs() / 2) as usize % filters.len(); - graphics_apply_filter(graphics, filters[idx])?; +const FILTERS: [Filter; 8] = [ + Filter::Invert, + Filter::Gray, + Filter::Threshold(0.5), + Filter::Posterize(4), + Filter::Opaque, + Filter::Erode, + Filter::Dilate, + Filter::Blur(4.0), +]; + +struct Filters; + +impl Sketch for Filters { + fn settings() -> Settings { + Settings::size(400, 400) + } - graphics_record_command(graphics, DrawCommand::Fill(Color::srgb(0.0, 0.0, 1.0)))?; - graphics_record_command( - graphics, - DrawCommand::Rect { - x: 160.0, - y: 160.0, - w: 80.0, - h: 80.0, - radii: [0.0; 4], - }, - )?; + fn setup(_g: &mut Graphics) -> Result { + Ok(Filters) + } - graphics_end_draw(graphics)?; + fn draw(&mut self, g: &mut Graphics) { + g.background((0.1, 0.1, 0.15)); + g.no_stroke(); + + g.fill((1.0, 0.2, 0.2)); + g.rect(40, 40, 160, 160); + g.fill((0.2, 1.0, 0.2)); + g.rect(200, 40, 160, 160); + g.fill((0.2, 0.4, 1.0)); + g.rect(40, 200, 160, 160); + g.fill((0.95, 0.85, 0.2)); + g.rect(200, 200, 160, 160); + + let seconds = g.millis() / 1000; + let filter = FILTERS[(seconds / 2) as usize % FILTERS.len()]; + g.filter(filter); + + g.fill((0.0, 0.0, 1.0)); + g.rect(160, 160, 80, 80); } - Ok(()) +} + +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/gltf_load.rs b/examples/gltf_load.rs index 6fd09f42..595ca5c3 100644 --- a/examples/gltf_load.rs +++ b/examples/gltf_load.rs @@ -1,72 +1,48 @@ -use processing_glfw::GlfwContext; - -use bevy::math::Vec3; use processing::prelude::*; -use processing_render::render::command::DrawCommand; -use processing_render::shader_value::ShaderValue; -fn main() { - match sketch() { - Ok(_) => { - eprintln!("Sketch completed successfully"); - exit(0).unwrap(); - } - Err(e) => { - eprintln!("Sketch error: {:?}", e); - exit(1).unwrap(); - } - }; +struct GltfLoad { + duck: Geometry, + skin: Material, + light: Light, } -fn sketch() -> error::Result<()> { - let width = 800; - let height = 600; - let mut glfw_ctx = GlfwContext::new(width, height, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(width, height, false)?; - let graphics = graphics_create(surface, width, height, TextureFormat::Rgba16Float)?; +impl Sketch for GltfLoad { + fn settings() -> Settings { + Settings::size(800, 600) + } - let gltf = gltf_load(graphics, "gltf/Duck.glb")?; - let duck = gltf_geometry(gltf, "LOD3spShape")?; - let duck_mat = gltf_material(gltf, "blinn3-fx")?; + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); - graphics_mode_3d(graphics)?; - gltf_camera(gltf, 0)?; - let light = gltf_light(gltf, 0)?; + let gltf = Gltf::load(g, "gltf/Duck.glb")?; + let duck = gltf.geometry("LOD3spShape")?; + let skin = gltf.material("blinn3-fx")?; + gltf.camera(0)?; + let light = gltf.light(0)?; - let mut frame: u64 = 0; + Ok(GltfLoad { duck, skin, light }) + } - while glfw_ctx.poll_events() { - let t = frame as f32 * 0.02; + fn draw(&mut self, g: &mut Graphics) { + let t = (g.frame_count() - 1) as f32 * 0.02; let radius = 1.5; - let lx = t.cos() * radius; - let ly = -1.5; - let lz = t.sin() * radius; - transform_set_position(light, Vec3::new(lx, ly, lz))?; - transform_look_at(light, Vec3::new(0.0, -0.8, 0.0))?; + self.light + .position((t.cos() * radius, -1.5, t.sin() * radius)) + .look_at((0.0, -0.8, 0.0)); let r = (t * 8.0).sin() * 0.5 + 0.5; - let g = (t * 8.0 + 2.0).sin() * 0.5 + 0.5; + let green = (t * 8.0 + 2.0).sin() * 0.5 + 0.5; let b = (t * 8.0 + 4.0).sin() * 0.5 + 0.5; - material_set(duck_mat, "base_color", ShaderValue::Float4([r, g, b, 1.0]))?; - - graphics_begin_draw(graphics)?; - graphics_light(graphics, light)?; + self.skin.set("base_color", (r, green, b, 1.0)); - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.1, 0.1, 0.12)), - )?; - - graphics_record_command(graphics, DrawCommand::Material(duck_mat))?; - graphics_record_command(graphics, DrawCommand::Geometry(duck))?; - - graphics_end_draw(graphics)?; - - frame += 1; + g.light(&self.light); + g.background((0.1, 0.1, 0.12)); + g.material(&self.skin); + g.model(&self.duck); } +} - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/input.rs b/examples/input.rs index fd335ac7..ea30bf08 100644 --- a/examples/input.rs +++ b/examples/input.rs @@ -1,71 +1,32 @@ -use processing_glfw::GlfwContext; - use processing::prelude::*; -use processing_render::render::command::DrawCommand; - -fn main() { - match sketch() { - Ok(_) => { - eprintln!("Sketch completed successfully"); - exit(0).unwrap(); - } - Err(e) => { - eprintln!("Sketch error: {:?}", e); - exit(1).unwrap(); - } - }; -} - -fn sketch() -> error::Result<()> { - let width = 400; - let height = 400; - let mut glfw_ctx = GlfwContext::new(width, height, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(width, height, false)?; - let graphics = graphics_create(surface, width, height, TextureFormat::Rgba16Float)?; - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; +struct Input; - let mx = input_mouse_x(surface)?; - let my = input_mouse_y(surface)?; +impl Sketch for Input { + fn settings() -> Settings { + Settings::size(400, 400) + } - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.15, 0.15, 0.2)), - )?; + fn setup(_g: &mut Graphics) -> Result { + Ok(Input) + } - if input_mouse_is_pressed()? { - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgb(0.25, 0.15, 0.2)), - )?; - } + fn draw(&mut self, g: &mut Graphics) { + g.background((0.15, 0.15, 0.2)); - if input_mouse_is_pressed()? { - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgb(0.55, 0.25, 0.2)), - )?; + if g.mouse_pressed() { + g.fill((0.55, 0.25, 0.2)); + } else { + g.fill(255); } + g.rect(g.mouse_x() - 25.0, g.mouse_y() - 25.0, 50, 50); - graphics_record_command( - graphics, - DrawCommand::Rect { - x: mx - 25.0, - y: my - 25.0, - w: 50.0, - h: 50.0, - radii: [0.0; 4], - }, - )?; - - if input_key_is_pressed()? && input_key_is_down(KeyCode::Escape)? { - break; + if g.key_down(Key::Escape) { + g.exit(); } - - graphics_end_draw(graphics)?; } - Ok(()) +} + +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/lights.rs b/examples/lights.rs index c5bb3ff7..1213d1c6 100644 --- a/examples/lights.rs +++ b/examples/lights.rs @@ -1,108 +1,71 @@ -use processing_glfw::GlfwContext; - -use bevy::math::Vec3; use processing::prelude::*; -use processing_render::render::command::DrawCommand; -fn main() { - match sketch() { - Ok(_) => { - eprintln!("Sketch completed successfully"); - exit(0).unwrap(); - } - Err(e) => { - eprintln!("Sketch error: {:?}", e); - exit(1).unwrap(); - } - }; +struct Lights { + cube: Geometry, + shiny: Material, + sun: Light, + warm: Light, + cool: Light, + spot: Light, + angle: f32, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(400, 400, false)?; - init(Config::default())?; - - let width = 400; - let height = 400; - let surface = glfw_ctx.create_surface(width, height, false)?; - let graphics = graphics_create(surface, width, height, TextureFormat::Rgba16Float)?; - let box_geo = geometry_box(100.0, 100.0, 100.0)?; - let pbr_mat = material_create_pbr()?; - material_set(pbr_mat, "roughness", shader_value::ShaderValue::Float(0.0))?; - - // create a directional light - let dir_light = - light_create_directional(graphics, bevy::color::Color::srgb(0.35, 0.25, 0.5), 500.0)?; +impl Sketch for Lights { + fn settings() -> Settings { + Settings::size(400, 400) + } - // create a point light - let point_light_a = light_create_point( - graphics, - bevy::color::Color::srgb(1.0, 0.5, 0.25), - 1_000_000.0, - 200.0, - 0.5, - )?; - transform_set_position(point_light_a, Vec3::new(-25.0, -5.0, 51.0))?; - transform_look_at(point_light_a, Vec3::new(0.0, 0.0, 0.0))?; + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((100, -100, 300)); + g.camera_look_at((0, 0, 0)); - // create another point light - let point_light_b = light_create_point( - graphics, - bevy::color::Color::srgb(0.0, 0.5, 0.75), - 2_000_000.0, - 200.0, - 0.25, - )?; - transform_set_position(point_light_b, Vec3::new(0.0, -5.0, 50.5))?; - transform_look_at(point_light_b, Vec3::new(0.0, 0.0, 0.0))?; + let cube = Geometry::cube(100)?; + let mut shiny = Material::pbr()?; + shiny.set("roughness", 0.0); - // and a spot light, too! - let spot_light = light_create_spot( - graphics, - bevy::color::Color::srgb(0.25, 0.8, 0.19), - 15.0 * 1_000_000.0, - 200.0, - 0.84, - 0.0, - core::f32::consts::FRAC_PI_4, - )?; - transform_set_position(spot_light, Vec3::new(40.0, 0.0, 70.0))?; - transform_look_at(spot_light, Vec3::new(0.0, 0.0, 0.0))?; + let sun = g.create_directional_light((0.35, 0.25, 0.5), 500); - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(100.0, -100.0, 300.0))?; - transform_look_at(graphics, Vec3::new(0.0, 0.0, 0.0))?; + let warm = g.create_point_light((1.0, 0.5, 0.25), 1_000_000, 200, 0.5); + warm.position((-25, -5, 51)).look_at((0, 0, 0)); - let mut angle = 0.0; + let cool = g.create_point_light((0.0, 0.5, 0.75), 2_000_000, 200, 0.25); + cool.position((0.0, -5.0, 50.5)).look_at((0, 0, 0)); - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_light(graphics, dir_light)?; - graphics_light(graphics, point_light_a)?; - graphics_light(graphics, point_light_b)?; - graphics_light(graphics, spot_light)?; + let spot = g.create_spot_light((0.25, 0.8, 0.19), 15_000_000, 200, 0.84, 0, QUARTER_PI); + spot.position((40, 0, 70)).look_at((0, 0, 0)); - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.18, 0.20, 0.15)), - )?; + Ok(Lights { + cube, + shiny, + sun, + warm, + cool, + spot, + angle: 0.0, + }) + } - graphics_record_command(graphics, DrawCommand::Fill(bevy::color::Color::WHITE))?; - graphics_record_command(graphics, DrawCommand::Material(pbr_mat))?; + fn draw(&mut self, g: &mut Graphics) { + g.light(&self.sun); + g.light(&self.warm); + g.light(&self.cool); + g.light(&self.spot); - graphics_record_command(graphics, DrawCommand::PushMatrix)?; - graphics_record_command( - graphics, - DrawCommand::Rotate { - angle: -angle, - axis: Vec3::Z, - }, - )?; - graphics_record_command(graphics, DrawCommand::Geometry(box_geo))?; - graphics_record_command(graphics, DrawCommand::PopMatrix)?; + g.background((0.18, 0.20, 0.15)); + g.fill(255); + g.material(&self.shiny); - graphics_end_draw(graphics)?; + { + let g = g.push(); + g.rotate(-self.angle); + g.model(&self.cube); + } - angle += 0.02; + self.angle += 0.02; } - Ok(()) +} + +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/materials.rs b/examples/materials.rs index c7c0294c..6f38559d 100644 --- a/examples/materials.rs +++ b/examples/materials.rs @@ -1,110 +1,72 @@ -use processing_glfw::GlfwContext; - -use bevy::math::{Vec2, Vec3}; use processing::prelude::*; -use processing_render::render::command::DrawCommand; - -fn main() { - match sketch() { - Ok(_) => { - eprintln!("Sketch completed successfully"); - exit(0).unwrap(); - } - Err(e) => { - eprintln!("Sketch error: {:?}", e); - exit(1).unwrap(); - } - }; -} - -fn sketch() -> error::Result<()> { - let width = 800; - let height = 600; - let mut glfw_ctx = GlfwContext::new(width, height, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(width, height, false)?; - let graphics = graphics_create(surface, width, height, TextureFormat::Rgba16Float)?; - let sphere = geometry_sphere(30.0, 32, 18)?; - - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(0.0, 0.0, 600.0))?; - transform_look_at(graphics, Vec3::new(0.0, 0.0, 0.0))?; - - let dir_light = - light_create_directional(graphics, bevy::color::Color::srgb(1.0, 0.98, 0.95), 1_500.0)?; - transform_set_position(dir_light, Vec3::new(300.0, -400.0, 300.0))?; - transform_look_at(dir_light, Vec3::new(0.0, 0.0, 0.0))?; - - let point_light = - light_create_point(graphics, bevy::color::Color::WHITE, 100_000.0, 800.0, 0.0)?; - transform_set_position(point_light, Vec3::new(200.0, -200.0, 400.0))?; - // Grid of materials varying roughness (x) and metallic (y) - let cols = 11; - let rows = 5; - let mut materials = Vec::new(); +const COLS: usize = 11; +const ROWS: usize = 5; +const SPACING: f32 = 70.0; - for row in 0..rows { - for col in 0..cols { - let mat = material_create_pbr()?; - let roughness = col as f32 / (cols - 1) as f32; - let metallic = row as f32 / (rows - 1) as f32; +struct Materials { + sphere: Geometry, + materials: Vec, + sun: Light, + lamp: Light, +} - material_set( - mat, - "roughness", - shader_value::ShaderValue::Float(roughness), - )?; - material_set(mat, "metallic", shader_value::ShaderValue::Float(metallic))?; - materials.push(mat); - } +impl Sketch for Materials { + fn settings() -> Settings { + Settings::size(800, 600) } - let base_color = bevy::color::Color::srgb(1.0, 0.85, 0.57); - let spacing = 70.0; - let offset_x = (cols - 1) as f32 * spacing / 2.0; - let offset_y = (rows - 1) as f32 * spacing / 2.0; - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_light(graphics, dir_light)?; - graphics_light(graphics, point_light)?; - - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.05, 0.05, 0.07)), - )?; - - graphics_record_command(graphics, DrawCommand::Fill(base_color))?; - - for row in 0..rows { - for col in 0..cols { - let mat = materials[row * cols + col]; - - graphics_record_command(graphics, DrawCommand::PushMatrix)?; - graphics_record_command( - graphics, - DrawCommand::Translate( - Vec2::new( - col as f32 * spacing - offset_x, - offset_y - row as f32 * spacing, - ) - .extend(0.0), - ), - )?; - graphics_record_command(graphics, DrawCommand::Material(mat))?; - graphics_record_command(graphics, DrawCommand::Geometry(sphere))?; - graphics_record_command(graphics, DrawCommand::PopMatrix)?; + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((0, 0, 600)); + g.camera_look_at((0, 0, 0)); + + let sun = g.create_directional_light((1.0, 0.98, 0.95), 1500); + sun.position((300, -400, 300)).look_at((0, 0, 0)); + let lamp = g.create_point_light(Color::WHITE, 100_000, 800, 0); + lamp.position((200, -200, 400)); + + let mut materials = Vec::new(); + for row in 0..ROWS { + for col in 0..COLS { + let mut material = Material::pbr()?; + material.set("roughness", col as f32 / (COLS - 1) as f32); + material.set("metallic", row as f32 / (ROWS - 1) as f32); + materials.push(material); } } - graphics_end_draw(graphics)?; + let sphere = Geometry::sphere(30, 32, 18)?; + Ok(Materials { + sphere, + materials, + sun, + lamp, + }) } - for mat in materials { - material_destroy(mat)?; + fn draw(&mut self, g: &mut Graphics) { + g.light(&self.sun); + g.light(&self.lamp); + g.background((0.05, 0.05, 0.07)); + g.fill((1.0, 0.85, 0.57)); + + let offset_x = (COLS - 1) as f32 * SPACING / 2.0; + let offset_y = (ROWS - 1) as f32 * SPACING / 2.0; + for row in 0..ROWS { + for col in 0..COLS { + let g = g.push(); + g.translate(( + col as f32 * SPACING - offset_x, + offset_y - row as f32 * SPACING, + )); + g.material(&self.materials[row * COLS + col]); + g.model(&self.sphere); + } + } } +} - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/midi.rs b/examples/midi.rs index 9113ae35..510f61f4 100644 --- a/examples/midi.rs +++ b/examples/midi.rs @@ -1,7 +1,4 @@ -use bevy::color::{Color, ColorToComponents}; use processing::prelude::*; -use processing_glfw::GlfwContext; -use processing_render::render::command::DrawCommand; const PENTATONIC: [u8; 5] = [0, 3, 5, 7, 10]; const ROOT: u8 = 48; @@ -35,148 +32,115 @@ struct Ripple { color: Color, } -fn main() { - if let Err(e) = sketch() { - eprintln!("Sketch error: {e:?}"); - exit(1).unwrap(); - } - exit(0).unwrap(); +struct Midi { + held: Option, + ripples: Vec, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(WIDTH, HEIGHT, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(WIDTH, HEIGHT, false)?; - let graphics = graphics_create(surface, WIDTH, HEIGHT, TextureFormat::Rgba16Float)?; - - midi_refresh_ports()?; - let ports = midi_list_ports()?; - if ports.is_empty() { - eprintln!("no MIDI output ports found — connect a synth or virtual port and retry"); - return Ok(()); - } - for p in &ports { - println!("{p}"); +impl Midi { + fn play(&mut self, note: u8, x: f32, y: f32) -> Result<()> { + midi::note_on(note, velocity_at_y(y))?; + self.ripples.push(Ripple { + x, + y, + age: 0.0, + color: note_color(note), + }); + self.held = Some(note); + Ok(()) } - midi_connect(0)?; - - let mut held: Option = None; - let mut ripples: Vec = Vec::new(); - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - - let mx = input_mouse_x(surface)?; - let my = input_mouse_y(surface)?; - let pressed = input_mouse_is_pressed()?; - - match (pressed, held) { - (true, None) => { - let note = note_at_x(mx); - let velocity = velocity_at_y(my); - midi_note_on(note, velocity)?; - ripples.push(Ripple { - x: mx, - y: my, - age: 0.0, - color: note_color(note), - }); - held = Some(note); - } + + fn update_notes(&mut self, g: &Graphics) -> Result<()> { + let x = g.mouse_x(); + let y = g.mouse_y(); + match (g.mouse_pressed(), self.held) { + (true, None) => self.play(note_at_x(x), x, y)?, (true, Some(note)) => { - let target = note_at_x(mx); + let target = note_at_x(x); if target != note { - midi_note_off(note)?; - let velocity = velocity_at_y(my); - midi_note_on(target, velocity)?; - ripples.push(Ripple { - x: mx, - y: my, - age: 0.0, - color: note_color(target), - }); - held = Some(target); + midi::note_off(note)?; + self.play(target, x, y)?; } } (false, Some(note)) => { - midi_note_off(note)?; - held = None; + midi::note_off(note)?; + self.held = None; + } + (false, None) => {} + } + Ok(()) + } +} + +impl Sketch for Midi { + fn settings() -> Settings { + Settings::size(WIDTH, HEIGHT) + } + + fn setup(g: &mut Graphics) -> Result { + midi::refresh_ports()?; + let ports = midi::ports()?; + if ports.is_empty() { + eprintln!("no MIDI output ports found — connect a synth or virtual port and retry"); + g.exit(); + } else { + for port in &ports { + println!("{port}"); } - _ => {} + midi::connect(0)?; + } + Ok(Midi { + held: None, + ripples: Vec::new(), + }) + } + + fn draw(&mut self, g: &mut Graphics) { + if let Err(e) = self.update_notes(g) { + eprintln!("midi: {e}"); } - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(Color::srgb(0.04, 0.04, 0.07)), - )?; + g.background((0.04, 0.04, 0.07)); + g.no_stroke(); let octave_w = WIDTH as f32 / OCTAVES as f32; for i in 0..OCTAVES { - let alpha = if i % 2 == 0 { 0.04 } else { 0.0 }; - graphics_record_command( - graphics, - DrawCommand::Fill(Color::srgba(1.0, 1.0, 1.0, alpha)), - )?; - graphics_record_command( - graphics, - DrawCommand::Rect { - x: i as f32 * octave_w, - y: 0.0, - w: octave_w, - h: HEIGHT as f32, - radii: [0.0; 4], - }, - )?; + if i % 2 == 0 { + g.fill((1.0, 1.0, 1.0, 0.04)); + g.rect(i as f32 * octave_w, 0, octave_w, HEIGHT); + } } - ripples.retain_mut(|r| { - r.age += 0.022; - r.age < 1.0 - }); - for r in &ripples { - let size = 24.0 + r.age * 220.0; - let alpha = (1.0 - r.age).powi(2); - let lin = r.color.to_linear().to_f32_array(); - graphics_record_command( - graphics, - DrawCommand::Fill(Color::linear_rgba(lin[0], lin[1], lin[2], alpha)), - )?; - graphics_record_command( - graphics, - DrawCommand::Rect { - x: r.x - size / 2.0, - y: r.y - size / 2.0, - w: size, - h: size, - radii: [size / 2.0; 4], - }, - )?; + for ripple in &mut self.ripples { + ripple.age += 0.022; } + self.ripples.retain(|r| r.age < 1.0); - let preview = note_color(note_at_x(mx)); - graphics_record_command(graphics, DrawCommand::Fill(preview))?; - graphics_record_command( - graphics, - DrawCommand::Rect { - x: mx - 8.0, - y: my - 8.0, - w: 16.0, - h: 16.0, - radii: [8.0; 4], - }, - )?; - - graphics_end_draw(graphics)?; - - if input_key_is_pressed()? && input_key_is_down(KeyCode::Escape)? { - break; + for ripple in &self.ripples { + let size = 24.0 + ripple.age * 220.0; + let alpha = (1.0 - ripple.age).powi(2); + g.fill(ripple.color.with_alpha(alpha)); + g.circle(ripple.x, ripple.y, size); + } + + g.fill(note_color(note_at_x(g.mouse_x()))); + g.circle(g.mouse_x(), g.mouse_y(), 16); + + if g.key_pressed() && g.key_down(Key::Escape) { + g.exit(); } } +} - if let Some(note) = held { - midi_note_off(note)?; +impl Drop for Midi { + fn drop(&mut self) { + if let Some(note) = self.held { + let _ = midi::note_off(note); + } + let _ = midi::disconnect(); } - midi_disconnect()?; - Ok(()) +} + +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/particles_animated.rs b/examples/particles_animated.rs index 6f5d1760..29e50945 100644 --- a/examples/particles_animated.rs +++ b/examples/particles_animated.rs @@ -1,8 +1,4 @@ -use processing_glfw::GlfwContext; - -use bevy::math::Vec3; use processing::prelude::*; -use processing_render::render::command::DrawCommand; const SPIN_SHADER: &str = r#" struct Params { @@ -28,77 +24,71 @@ fn main(@builtin(global_invocation_id) gid: vec3) { } "#; -fn main() { - sketch().unwrap(); - exit(0).unwrap(); +struct ParticlesAnimated { + sun: Light, + sphere: Geometry, + particles: Particles, + pbr: Material, + spin: Compute, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(900, 700, false)?; - init(Config::default())?; +impl Sketch for ParticlesAnimated { + fn settings() -> Settings { + Settings::size(900, 700) + } - let surface = glfw_ctx.create_surface(900, 700, false)?; - let graphics = graphics_create(surface, 900, 700, TextureFormat::Rgba16Float)?; + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((0.0, -8.0, 25.0)); + g.camera_look_at((0, 0, 0)); + + let sun = g.create_directional_light((0.9, 0.85, 0.8), 300.0); + + let sphere = Geometry::sphere(0.25, 12, 8)?; + + let capacity: u32 = 1000; + let mut positions: Vec = Vec::with_capacity(capacity as usize); + for x in 0..10 { + for y in 0..10 { + for z in 0..10 { + positions.push(Vec3::new( + (x as f32 - 4.5) * 1.0, + (y as f32 - 4.5) * 1.0, + (z as f32 - 4.5) * 1.0, + )); + } + } + } - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(0.0, -8.0, 25.0))?; - transform_look_at(graphics, Vec3::new(0.0, 0.0, 0.0))?; + let particles = Particles::new(capacity, &[Attribute::position()])?; + particles.buffer(Attribute::position()).write(&positions); - let light = - light_create_directional(graphics, bevy::color::Color::srgb(0.9, 0.85, 0.8), 300.0)?; + let mut pbr = Material::pbr()?; + pbr.set("roughness", 0.4); - let sphere = geometry_sphere(0.25, 12, 8)?; + let spin = Compute::new(&Shader::new(SPIN_SHADER)?)?; - let capacity: u32 = 1000; - let mut floats: Vec = Vec::with_capacity(capacity as usize * 3); - for x in 0..10 { - for y in 0..10 { - for z in 0..10 { - floats.push((x as f32 - 4.5) * 1.0); - floats.push((y as f32 - 4.5) * 1.0); - floats.push((z as f32 - 4.5) * 1.0); - } - } + Ok(ParticlesAnimated { + sun, + sphere, + particles, + pbr, + spin, + }) } - let bytes: Vec = floats.iter().flat_map(|f| f.to_le_bytes()).collect(); - - let position_attr = geometry_attribute_position(); - let p = particles_create(capacity, vec![position_attr])?; - let position_buf = - particles_buffer(p, position_attr)?.ok_or(error::ProcessingError::ParticlesNotFound)?; - buffer_write(position_buf, bytes)?; - - let pbr = material_create_pbr()?; - material_set(pbr, "roughness", shader_value::ShaderValue::Float(0.4))?; - - let spin_shader = shader_create(SPIN_SHADER)?; - let spin = compute_create(spin_shader)?; - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_light(graphics, light)?; - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.06, 0.06, 0.08)), - )?; - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgb(0.9, 0.5, 0.3)), - )?; - graphics_record_command(graphics, DrawCommand::Material(pbr))?; - graphics_record_command( - graphics, - DrawCommand::Particles { - particles: p, - geometry: Some(sphere), - topology: Default::default(), - }, - )?; - graphics_end_draw(graphics)?; - - compute_set(spin, "dt", shader_value::ShaderValue::Float(0.01))?; - particles_apply(p, spin)?; + + fn draw(&mut self, g: &mut Graphics) { + g.light(&self.sun); + g.background((0.06, 0.06, 0.08)); + g.fill((0.9, 0.5, 0.3)); + g.material(&self.pbr); + g.particles(&self.particles).geometry(&self.sphere); + + self.spin.set("dt", 0.01); + self.particles.apply(&self.spin); } +} - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/particles_basic.rs b/examples/particles_basic.rs index 2a383fc8..f1d9b98f 100644 --- a/examples/particles_basic.rs +++ b/examples/particles_basic.rs @@ -1,74 +1,59 @@ -use processing_glfw::GlfwContext; - -use bevy::math::Vec3; use processing::prelude::*; -use processing_render::render::command::DrawCommand; -fn main() { - sketch().unwrap(); - exit(0).unwrap(); +struct ParticlesBasic { + sun: Light, + sphere: Geometry, + particles: Particles, + pbr: Material, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(900, 700, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(900, 700, false)?; - let graphics = graphics_create(surface, 900, 700, TextureFormat::Rgba16Float)?; +impl Sketch for ParticlesBasic { + fn settings() -> Settings { + Settings::size(900, 700) + } - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(0.0, 0.0, 25.0))?; - transform_look_at(graphics, Vec3::new(0.0, 0.0, 0.0))?; + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((0.0, 0.0, 25.0)); + g.camera_look_at((0, 0, 0)); - let light = - light_create_directional(graphics, bevy::color::Color::srgb(0.9, 0.85, 0.8), 300.0)?; + let sun = g.create_directional_light((0.9, 0.85, 0.8), 300.0); - let sphere = geometry_sphere(0.25, 12, 8)?; + let sphere = Geometry::sphere(0.25, 12, 8)?; - let capacity: u32 = 1000; - let mut floats: Vec = Vec::with_capacity(capacity as usize * 3); - for x in 0..10 { - for y in 0..10 { - for z in 0..10 { - floats.push((x as f32 - 4.5) * 1.0); - floats.push((y as f32 - 4.5) * 1.0); - floats.push((z as f32 - 4.5) * 1.0); + let capacity: u32 = 1000; + let mut positions: Vec = Vec::with_capacity(capacity as usize); + for x in 0..10 { + for y in 0..10 { + for z in 0..10 { + positions.push(Vec3::new(x as f32 - 4.5, y as f32 - 4.5, z as f32 - 4.5)); + } } } - } - let bytes: Vec = floats.iter().flat_map(|f| f.to_le_bytes()).collect(); - let position_attr = geometry_attribute_position(); - let p = particles_create(capacity, vec![position_attr])?; - let position_buf = - particles_buffer(p, position_attr)?.ok_or(error::ProcessingError::ParticlesNotFound)?; - buffer_write(position_buf, bytes)?; + let particles = Particles::new(capacity, &[Attribute::position()])?; + particles.buffer(Attribute::position()).write(&positions); - let pbr = material_create_pbr()?; - material_set(pbr, "roughness", shader_value::ShaderValue::Float(0.4))?; + let mut pbr = Material::pbr()?; + pbr.set("roughness", 0.4); - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_light(graphics, light)?; - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.06, 0.06, 0.08)), - )?; - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgb(0.9, 0.5, 0.3)), - )?; - graphics_record_command(graphics, DrawCommand::Material(pbr))?; - graphics_record_command( - graphics, - DrawCommand::Particles { - particles: p, - geometry: Some(sphere), - topology: Default::default(), - }, - )?; - graphics_end_draw(graphics)?; + Ok(ParticlesBasic { + sun, + sphere, + particles, + pbr, + }) } - Ok(()) + fn draw(&mut self, g: &mut Graphics) { + g.light(&self.sun); + g.background((0.06, 0.06, 0.08)); + g.fill((0.9, 0.5, 0.3)); + g.material(&self.pbr); + g.particles(&self.particles).geometry(&self.sphere); + } +} + +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/particles_colored.rs b/examples/particles_colored.rs index e952f3d2..50a5e7f7 100644 --- a/examples/particles_colored.rs +++ b/examples/particles_colored.rs @@ -1,83 +1,57 @@ -use processing_glfw::GlfwContext; - -use bevy::math::Vec3; use processing::prelude::*; -use processing_render::render::command::DrawCommand; -fn main() { - sketch().unwrap(); - exit(0).unwrap(); +struct ParticlesColored { + sphere: Geometry, + particles: Particles, + material: Material, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(900, 700, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(900, 700, false)?; - let graphics = graphics_create(surface, 900, 700, TextureFormat::Rgba16Float)?; - - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(0.0, -6.0, 18.0))?; - transform_look_at(graphics, Vec3::new(0.0, 0.0, 0.0))?; - - let sphere = geometry_sphere(0.25, 12, 8)?; +impl Sketch for ParticlesColored { + fn settings() -> Settings { + Settings::size(900, 700) + } - let capacity: u32 = 1000; - let mut positions: Vec = Vec::with_capacity(capacity as usize * 3); - let mut colors: Vec = Vec::with_capacity(capacity as usize * 4); - for x in 0..10 { - for y in 0..10 { - for z in 0..10 { - positions.push((x as f32 - 4.5) * 1.0); - positions.push((4.5 - y as f32) * 1.0); - positions.push((z as f32 - 4.5) * 1.0); - colors.push(x as f32 / 9.0); - colors.push(y as f32 / 9.0); - colors.push(z as f32 / 9.0); - colors.push(1.0); + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((0.0, -6.0, 18.0)); + g.camera_look_at((0, 0, 0)); + + let sphere = Geometry::sphere(0.25, 12, 8)?; + + let capacity: u32 = 1000; + let mut positions: Vec = Vec::with_capacity(capacity as usize); + let mut colors: Vec = Vec::with_capacity(capacity as usize); + for x in 0..10 { + for y in 0..10 { + for z in 0..10 { + positions.push(Vec3::new(x as f32 - 4.5, 4.5 - y as f32, z as f32 - 4.5)); + colors.push(Color::rgb(x as f32 / 9.0, y as f32 / 9.0, z as f32 / 9.0)); + } } } - } - let position_attr = geometry_attribute_position(); - let color_attr = geometry_attribute_color(); - let p = particles_create(capacity, vec![position_attr, color_attr])?; - let position_buf = - particles_buffer(p, position_attr)?.ok_or(error::ProcessingError::ParticlesNotFound)?; - let color_buf = - particles_buffer(p, color_attr)?.ok_or(error::ProcessingError::ParticlesNotFound)?; - buffer_write( - position_buf, - positions.iter().flat_map(|f| f.to_le_bytes()).collect(), - )?; - buffer_write( - color_buf, - colors.iter().flat_map(|f| f.to_le_bytes()).collect(), - )?; + let particles = Particles::new(capacity, &[Attribute::position(), Attribute::color()])?; + particles.buffer(Attribute::position()).write(&positions); + let mut color_buf = particles.buffer(Attribute::color()); + color_buf.write(&colors); + + let mut material = Material::unlit()?; + material.albedo_buffer(&color_buf); - let mat = { - let m = material_create_unlit()?; - material_set_albedo_buffer(m, color_buf)?; - m - }; + Ok(ParticlesColored { + sphere, + particles, + material, + }) + } - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.06, 0.06, 0.08)), - )?; - graphics_record_command(graphics, DrawCommand::Material(mat))?; - graphics_record_command( - graphics, - DrawCommand::Particles { - particles: p, - geometry: Some(sphere), - topology: Default::default(), - }, - )?; - graphics_end_draw(graphics)?; + fn draw(&mut self, g: &mut Graphics) { + g.background((0.06, 0.06, 0.08)); + g.material(&self.material); + g.particles(&self.particles).geometry(&self.sphere); } +} - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/particles_colored_pbr.rs b/examples/particles_colored_pbr.rs index 4b121be4..f7664118 100644 --- a/examples/particles_colored_pbr.rs +++ b/examples/particles_colored_pbr.rs @@ -1,87 +1,66 @@ -use processing_glfw::GlfwContext; - -use bevy::math::Vec3; use processing::prelude::*; -use processing_render::render::command::DrawCommand; -fn main() { - sketch().unwrap(); - exit(0).unwrap(); +struct ParticlesColoredPbr { + sun: Light, + sphere: Geometry, + particles: Particles, + material: Material, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(900, 700, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(900, 700, false)?; - let graphics = graphics_create(surface, 900, 700, TextureFormat::Rgba16Float)?; +impl Sketch for ParticlesColoredPbr { + fn settings() -> Settings { + Settings::size(900, 700) + } - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(0.0, -6.0, 18.0))?; - transform_look_at(graphics, Vec3::new(0.0, 0.0, 0.0))?; + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((0.0, -6.0, 18.0)); + g.camera_look_at((0, 0, 0)); - let light = - light_create_directional(graphics, bevy::color::Color::srgb(0.95, 0.9, 0.85), 200.0)?; + let sun = g.create_directional_light((0.95, 0.9, 0.85), 200.0); - let sphere = geometry_sphere(0.3, 16, 12)?; + let sphere = Geometry::sphere(0.3, 16, 12)?; - let capacity: u32 = 512; - let mut positions: Vec = Vec::with_capacity(capacity as usize * 3); - let mut colors: Vec = Vec::with_capacity(capacity as usize * 4); - for x in 0..8 { - for y in 0..8 { - for z in 0..8 { - positions.push((x as f32 - 3.5) * 1.4); - positions.push((3.5 - y as f32) * 1.4); - positions.push((z as f32 - 3.5) * 1.4); - colors.push(x as f32 / 7.0); - colors.push(y as f32 / 7.0); - colors.push(z as f32 / 7.0); - colors.push(1.0); + let capacity: u32 = 512; + let mut positions: Vec = Vec::with_capacity(capacity as usize); + let mut colors: Vec = Vec::with_capacity(capacity as usize); + for x in 0..8 { + for y in 0..8 { + for z in 0..8 { + positions.push(Vec3::new( + (x as f32 - 3.5) * 1.4, + (3.5 - y as f32) * 1.4, + (z as f32 - 3.5) * 1.4, + )); + colors.push(Color::rgb(x as f32 / 7.0, y as f32 / 7.0, z as f32 / 7.0)); + } } } - } - let position_attr = geometry_attribute_position(); - let color_attr = geometry_attribute_color(); - let p = particles_create(capacity, vec![position_attr, color_attr])?; - let position_buf = - particles_buffer(p, position_attr)?.ok_or(error::ProcessingError::ParticlesNotFound)?; - let color_buf = - particles_buffer(p, color_attr)?.ok_or(error::ProcessingError::ParticlesNotFound)?; - buffer_write( - position_buf, - positions.iter().flat_map(|f| f.to_le_bytes()).collect(), - )?; - buffer_write( - color_buf, - colors.iter().flat_map(|f| f.to_le_bytes()).collect(), - )?; + let particles = Particles::new(capacity, &[Attribute::position(), Attribute::color()])?; + particles.buffer(Attribute::position()).write(&positions); + let mut color_buf = particles.buffer(Attribute::color()); + color_buf.write(&colors); - let mat = { - let m = material_create_pbr()?; - material_set_albedo_buffer(m, color_buf)?; - m - }; + let mut material = Material::pbr()?; + material.albedo_buffer(&color_buf); - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_light(graphics, light)?; - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.06, 0.06, 0.08)), - )?; - graphics_record_command(graphics, DrawCommand::Material(mat))?; - graphics_record_command( - graphics, - DrawCommand::Particles { - particles: p, - geometry: Some(sphere), - topology: Default::default(), - }, - )?; - graphics_end_draw(graphics)?; + Ok(ParticlesColoredPbr { + sun, + sphere, + particles, + material, + }) } - Ok(()) + fn draw(&mut self, g: &mut Graphics) { + g.light(&self.sun); + g.background((0.06, 0.06, 0.08)); + g.material(&self.material); + g.particles(&self.particles).geometry(&self.sphere); + } +} + +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/particles_emit.rs b/examples/particles_emit.rs index 83f66909..928085f1 100644 --- a/examples/particles_emit.rs +++ b/examples/particles_emit.rs @@ -1,113 +1,71 @@ -use processing_glfw::GlfwContext; - -use bevy::math::Vec3; use processing::prelude::*; -use processing_render::render::command::DrawCommand; -fn main() { - sketch().unwrap(); - exit(0).unwrap(); +struct ParticlesEmit { + sphere: Geometry, + particles: Particles, + material: Material, + frame: u32, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(900, 700, false)?; - init(Config::default())?; +impl Sketch for ParticlesEmit { + fn settings() -> Settings { + Settings::size(900, 700) + } - let surface = glfw_ctx.create_surface(900, 700, false)?; - let graphics = graphics_create(surface, 900, 700, TextureFormat::Rgba16Float)?; + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((0.0, -4.0, 14.0)); + g.camera_look_at((0, 0, 0)); - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(0.0, -4.0, 14.0))?; - transform_look_at(graphics, Vec3::new(0.0, 0.0, 0.0))?; + let sphere = Geometry::sphere(0.08, 8, 6)?; - let sphere = geometry_sphere(0.08, 8, 6)?; + let capacity: u32 = 2000; + let particles = Particles::new(capacity, &[Attribute::position(), Attribute::color()])?; - let capacity: u32 = 2000; - let position_attr = geometry_attribute_position(); - let color_attr = geometry_attribute_color(); - let p = particles_create(capacity, vec![position_attr, color_attr])?; - let position_buf = - particles_buffer(p, position_attr)?.ok_or(error::ProcessingError::ParticlesNotFound)?; - let color_buf = - particles_buffer(p, color_attr)?.ok_or(error::ProcessingError::ParticlesNotFound)?; + // offscreen until emitted + let far_away = vec![Vec3::splat(1.0e6); capacity as usize]; + particles.buffer(Attribute::position()).write(&far_away); - let init_positions: Vec = (0..capacity * 3).map(|_| 1.0e6).collect(); - buffer_write( - position_buf, - init_positions - .iter() - .flat_map(|f| f.to_le_bytes()) - .collect(), - )?; + let mut material = Material::unlit()?; + material.albedo_buffer(&particles.buffer(Attribute::color())); - let mat = { - let m = material_create_unlit()?; - material_set_albedo_buffer(m, color_buf)?; - m - }; + Ok(ParticlesEmit { + sphere, + particles, + material, + frame: 0, + }) + } - let mut frame: u32 = 0; - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.06, 0.06, 0.08)), - )?; - graphics_record_command(graphics, DrawCommand::Material(mat))?; - graphics_record_command( - graphics, - DrawCommand::Particles { - particles: p, - geometry: Some(sphere), - topology: Default::default(), - }, - )?; - graphics_end_draw(graphics)?; + fn draw(&mut self, g: &mut Graphics) { + g.background((0.06, 0.06, 0.08)); + g.material(&self.material); + g.particles(&self.particles).geometry(&self.sphere); let burst = 4u32; - let mut positions: Vec = Vec::with_capacity(burst as usize * 3); - let mut colors: Vec = Vec::with_capacity(burst as usize * 4); + let mut positions: Vec = Vec::with_capacity(burst as usize); + let mut colors: Vec = Vec::with_capacity(burst as usize); for k in 0..burst { - let i = frame * burst + k; + let i = self.frame * burst + k; let t = i as f32 * 0.05; let radius = 1.5 + (t * 0.02).min(3.0); - let height = -((t * 0.1).sin()) * 2.0; - positions.push(t.cos() * radius); - positions.push(height); - positions.push(t.sin() * radius); + let height = -(t * 0.1).sin() * 2.0; + positions.push(Vec3::new(t.cos() * radius, height, t.sin() * radius)); let h = (i as f32 * 0.012) % 1.0; - let (r, g, b) = hsv_to_rgb(h, 0.85, 1.0); - colors.push(r); - colors.push(g); - colors.push(b); - colors.push(1.0); + colors.push(Color::hsv(h * 360.0, 0.85, 1.0)); } - let position_bytes: Vec = positions.iter().flat_map(|f| f.to_le_bytes()).collect(); - let color_bytes: Vec = colors.iter().flat_map(|f| f.to_le_bytes()).collect(); - particles_emit( - p, + self.particles.emit( burst, - vec![(position_attr, position_bytes), (color_attr, color_bytes)], - )?; - frame += 1; + &[ + (Attribute::position(), &positions), + (Attribute::color(), &colors), + ], + ); + self.frame += 1; } - - Ok(()) } -fn hsv_to_rgb(h: f32, s: f32, v: f32) -> (f32, f32, f32) { - let i = (h * 6.0).floor(); - let f = h * 6.0 - i; - let p = v * (1.0 - s); - let q = v * (1.0 - f * s); - let t = v * (1.0 - (1.0 - f) * s); - match (i as i32) % 6 { - 0 => (v, t, p), - 1 => (q, v, p), - 2 => (p, v, t), - 3 => (p, q, v), - 4 => (t, p, v), - _ => (v, p, q), - } +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/particles_emit_gpu.rs b/examples/particles_emit_gpu.rs index 743ec55d..a78033d7 100644 --- a/examples/particles_emit_gpu.rs +++ b/examples/particles_emit_gpu.rs @@ -1,10 +1,4 @@ -use processing_glfw::GlfwContext; -use std::time::Instant; - -use bevy::math::Vec3; use processing::prelude::*; -use processing_render::geometry::AttributeFormat; -use processing_render::render::command::DrawCommand; const SPAWN_SHADER: &str = r#" struct Spawn { @@ -104,8 +98,8 @@ fn main(@builtin(global_invocation_id) gid: vec3) { position[i * 3u + 1u] = position[i * 3u + 1u] + velocity[i * 3u + 1u] * params.dt; position[i * 3u + 2u] = position[i * 3u + 2u] + velocity[i * 3u + 2u] * params.dt; - let life = clamp(1.0 - age[i] / params.ttl, 0.0, 1.0); - let s = life * life; + let remaining = clamp(1.0 - age[i] / params.ttl, 0.0, 1.0); + let s = remaining * remaining; scale[i * 3u + 0u] = s; scale[i * 3u + 1u] = s; scale[i * 3u + 2u] = s; @@ -114,106 +108,84 @@ fn main(@builtin(global_invocation_id) gid: vec3) { } "#; -fn main() { - sketch().unwrap(); - exit(0).unwrap(); +const BURST: u32 = 120; +const DT: f32 = 1.0 / 60.0; +const TTL: f32 = 2.5; +const GRAVITY: f32 = -9.8; +const SPEED: f32 = 5.0; + +struct ParticlesEmitGpu { + sun: Light, + particle: Geometry, + particles: Particles, + mat: Material, + spawn: Compute, + motion: Compute, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(900, 700, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(900, 700, false)?; - let graphics = graphics_create(surface, 900, 700, TextureFormat::Rgba16Float)?; - - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(0.0, -4.0, 16.0))?; - transform_look_at(graphics, Vec3::new(0.0, -2.0, 0.0))?; - - let light = - light_create_directional(graphics, bevy::color::Color::srgb(0.95, 0.9, 0.85), 800.0)?; - - let particle = geometry_sphere(0.12, 8, 6)?; - - let capacity: u32 = 40000; - let position_attr = geometry_attribute_position(); - let color_attr = geometry_attribute_color(); - let scale_attr = geometry_attribute_scale(); - let life_attr = geometry_attribute_life(); - let velocity_attr = geometry_attribute_create("velocity", AttributeFormat::Float3)?; - let age_attr = geometry_attribute_create("age", AttributeFormat::Float)?; - - let p = particles_create( - capacity, - vec![ - position_attr, - color_attr, - scale_attr, - life_attr, - velocity_attr, - age_attr, - ], - )?; - - let color_buf = - particles_buffer(p, color_attr)?.ok_or(error::ProcessingError::ParticlesNotFound)?; - let mat = { - let m = material_create_pbr()?; - material_set_albedo_buffer(m, color_buf)?; - m - }; - - let spawn_shader = shader_create(SPAWN_SHADER)?; - let spawn = compute_create(spawn_shader)?; - - let motion_shader = shader_create(MOTION_SHADER)?; - let motion = compute_create(motion_shader)?; - - let burst: u32 = 120; - let dt: f32 = 1.0 / 60.0; - let ttl: f32 = 2.5; - let gravity: f32 = -9.8; - let speed: f32 = 5.0; - let start = Instant::now(); - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_light(graphics, light)?; - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.04, 0.04, 0.07)), - )?; - graphics_record_command(graphics, DrawCommand::Material(mat))?; - graphics_record_command( - graphics, - DrawCommand::Particles { - particles: p, - geometry: Some(particle), - topology: Default::default(), - }, - )?; - graphics_end_draw(graphics)?; +impl Sketch for ParticlesEmitGpu { + fn settings() -> Settings { + Settings::size(900, 700) + } - let t = start.elapsed().as_secs_f32(); - let sx = t.cos() * 0.4; - let sz = t.sin() * 0.4; - compute_set( - spawn, - "pos", - shader_value::ShaderValue::Float4([sx, -7.0, sz, 0.0]), + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((0.0, -4.0, 16.0)); + g.camera_look_at((0.0, -2.0, 0.0)); + + let sun = g.create_directional_light((0.95, 0.9, 0.85), 800.0); + + let particle = Geometry::sphere(0.12, 8, 6)?; + + let capacity: u32 = 40000; + let particles = Particles::new( + capacity, + &[ + Attribute::position(), + Attribute::color(), + Attribute::scale(), + Attribute::life(), + Attribute::velocity(), + Attribute::age(), + ], )?; - compute_set( + + let mut mat = Material::pbr()?; + mat.albedo_buffer(&particles.buffer(Attribute::color())); + + let spawn = Compute::new(&Shader::new(SPAWN_SHADER)?)?; + let motion = Compute::new(&Shader::new(MOTION_SHADER)?)?; + + Ok(ParticlesEmitGpu { + sun, + particle, + particles, + mat, spawn, - "speed", - shader_value::ShaderValue::Float4([speed, 0.0, 0.0, 0.0]), - )?; - particles_emit_gpu(p, burst, spawn)?; + motion, + }) + } - compute_set(motion, "dt", shader_value::ShaderValue::Float(dt))?; - compute_set(motion, "ttl", shader_value::ShaderValue::Float(ttl))?; - compute_set(motion, "gravity", shader_value::ShaderValue::Float(gravity))?; - particles_apply(p, motion)?; + fn draw(&mut self, g: &mut Graphics) { + g.light(&self.sun); + g.background((0.04, 0.04, 0.07)); + g.material(&self.mat); + g.particles(&self.particles).geometry(&self.particle); + + let t = g.elapsed_time(); + let sx = t.cos() * 0.4; + let sz = t.sin() * 0.4; + self.spawn.set("pos", (sx, -7.0, sz, 0.0)); + self.spawn.set("speed", (SPEED, 0.0, 0.0, 0.0)); + self.particles.emit_gpu(BURST, &self.spawn); + + self.motion.set("dt", DT); + self.motion.set("ttl", TTL); + self.motion.set("gravity", GRAVITY); + self.particles.apply(&self.motion); } +} - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/particles_from_mesh.rs b/examples/particles_from_mesh.rs index 13a88aac..733839f7 100644 --- a/examples/particles_from_mesh.rs +++ b/examples/particles_from_mesh.rs @@ -1,93 +1,58 @@ -use processing_glfw::GlfwContext; - -use bevy::math::Vec3; use processing::prelude::*; -use processing_render::render::command::DrawCommand; -fn main() { - sketch().unwrap(); - exit(0).unwrap(); +struct ParticlesFromMesh { + sun: Light, + particle: Geometry, + particles: Particles, + material: Material, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(900, 700, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(900, 700, false)?; - let graphics = graphics_create(surface, 900, 700, TextureFormat::Rgba16Float)?; - - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(0.0, -4.0, 18.0))?; - transform_look_at(graphics, Vec3::new(0.0, 0.0, 0.0))?; - - let light = - light_create_directional(graphics, bevy::color::Color::srgb(0.95, 0.9, 0.85), 200.0)?; +impl Sketch for ParticlesFromMesh { + fn settings() -> Settings { + Settings::size(900, 700) + } - let source = geometry_sphere(5.0, 32, 24)?; + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((0.0, -4.0, 18.0)); + g.camera_look_at((0, 0, 0)); - let position_attr = geometry_attribute_position(); - let uv_attr = geometry_attribute_uv(); - let color_attr = geometry_attribute_color(); + let sun = g.create_directional_light((0.95, 0.9, 0.85), 200.0); - let p = particles_create_from_geometry(source, vec![position_attr, uv_attr, color_attr])?; - let uv_buf = particles_buffer(p, uv_attr)?.ok_or(error::ProcessingError::ParticlesNotFound)?; - let color_buf = - particles_buffer(p, color_attr)?.ok_or(error::ProcessingError::ParticlesNotFound)?; + let source = Geometry::sphere(5.0, 32, 24)?; + let particles = Particles::from_geometry( + &source, + &[Attribute::position(), Attribute::uv(), Attribute::color()], + )?; - let uv_bytes = buffer_read(uv_buf)?; - let mut colors: Vec = Vec::with_capacity(uv_bytes.len() * 2); - for chunk in uv_bytes.chunks_exact(8) { - let u = f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]); - let v = f32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]); - let (r, g, b) = hsv_to_rgb(u, 0.85, 1.0); - for f in [r, g, b, 1.0] { - colors.extend_from_slice(&f.to_le_bytes()); + let uvs = particles.buffer(Attribute::uv()).read::()?; + let mut colors: Vec = Vec::with_capacity(uvs.len()); + for uv in &uvs { + colors.push(Color::hsv(uv.x * 360.0, 0.85, 1.0)); } - let _ = v; + let mut color_buf = particles.buffer(Attribute::color()); + color_buf.write(&colors); + + let particle = Geometry::sphere(0.18, 10, 8)?; + let mut material = Material::pbr()?; + material.albedo_buffer(&color_buf); + + Ok(ParticlesFromMesh { + sun, + particle, + particles, + material, + }) } - buffer_write(color_buf, colors)?; - let particle = geometry_sphere(0.18, 10, 8)?; - let mat = { - let m = material_create_pbr()?; - material_set_albedo_buffer(m, color_buf)?; - m - }; - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_light(graphics, light)?; - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.06, 0.06, 0.08)), - )?; - graphics_record_command(graphics, DrawCommand::Material(mat))?; - graphics_record_command( - graphics, - DrawCommand::Particles { - particles: p, - geometry: Some(particle), - topology: Default::default(), - }, - )?; - graphics_end_draw(graphics)?; + fn draw(&mut self, g: &mut Graphics) { + g.light(&self.sun); + g.background((0.06, 0.06, 0.08)); + g.material(&self.material); + g.particles(&self.particles).geometry(&self.particle); } - - Ok(()) } -fn hsv_to_rgb(h: f32, s: f32, v: f32) -> (f32, f32, f32) { - let i = (h * 6.0).floor(); - let f = h * 6.0 - i; - let p = v * (1.0 - s); - let q = v * (1.0 - f * s); - let t = v * (1.0 - (1.0 - f) * s); - match (i as i32).rem_euclid(6) { - 0 => (v, t, p), - 1 => (q, v, p), - 2 => (p, v, t), - 3 => (p, q, v), - 4 => (t, p, v), - _ => (v, p, q), - } +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/particles_lifecycle.rs b/examples/particles_lifecycle.rs index 1677789d..8a66c006 100644 --- a/examples/particles_lifecycle.rs +++ b/examples/particles_lifecycle.rs @@ -1,9 +1,4 @@ -use processing_glfw::GlfwContext; - -use bevy::math::Vec3; use processing::prelude::*; -use processing_render::geometry::AttributeFormat; -use processing_render::render::command::DrawCommand; const AGING_SHADER: &str = r#" @group(0) @binding(0) var age: array; @@ -41,135 +36,97 @@ fn main(@builtin(global_invocation_id) gid: vec3) { } "#; -fn main() { - sketch().unwrap(); - exit(0).unwrap(); +const BURST: u32 = 6; +const DT: f32 = 1.0 / 60.0; +const TTL: f32 = 1.0; + +struct ParticlesLifecycle { + sphere: Geometry, + particles: Particles, + mat: Material, + aging: Compute, + frame: u32, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(900, 700, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(900, 700, false)?; - let graphics = graphics_create(surface, 900, 700, TextureFormat::Rgba16Float)?; - - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(0.0, -2.0, 14.0))?; - transform_look_at(graphics, Vec3::new(0.0, 0.0, 0.0))?; - - let sphere = geometry_sphere(0.1, 8, 6)?; - - let capacity: u32 = 800; - let position_attr = geometry_attribute_position(); - let color_attr = geometry_attribute_color(); - let scale_attr = geometry_attribute_scale(); - let life_attr = geometry_attribute_life(); - let age_attr = geometry_attribute_create("age", AttributeFormat::Float)?; - - let p = particles_create( - capacity, - vec![position_attr, color_attr, scale_attr, life_attr, age_attr], - )?; - let color_buf = - particles_buffer(p, color_attr)?.ok_or(error::ProcessingError::ParticlesNotFound)?; - - let mat = { - let m = material_create_unlit()?; - material_set_albedo_buffer(m, color_buf)?; - m - }; - let aging_shader = shader_create(AGING_SHADER)?; - let aging = compute_create(aging_shader)?; - - let burst: u32 = 6; - let dt: f32 = 1.0 / 60.0; - let ttl: f32 = 1.0; - let mut frame: u32 = 0; - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.04, 0.04, 0.07)), - )?; - graphics_record_command(graphics, DrawCommand::Material(mat))?; - graphics_record_command( - graphics, - DrawCommand::Particles { - particles: p, - geometry: Some(sphere), - topology: Default::default(), - }, +impl Sketch for ParticlesLifecycle { + fn settings() -> Settings { + Settings::size(900, 700) + } + + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((0.0, -2.0, 14.0)); + g.camera_look_at((0, 0, 0)); + + let sphere = Geometry::sphere(0.1, 8, 6)?; + + let capacity: u32 = 800; + let particles = Particles::new( + capacity, + &[ + Attribute::position(), + Attribute::color(), + Attribute::scale(), + Attribute::life(), + Attribute::age(), + ], )?; - graphics_end_draw(graphics)?; - let mut positions: Vec = Vec::with_capacity(burst as usize * 3); - let mut colors: Vec = Vec::with_capacity(burst as usize * 4); - for k in 0..burst { - let i = frame * burst + k; + let mut mat = Material::unlit()?; + mat.albedo_buffer(&particles.buffer(Attribute::color())); + + let aging = Compute::new(&Shader::new(AGING_SHADER)?)?; + + Ok(ParticlesLifecycle { + sphere, + particles, + mat, + aging, + frame: 0, + }) + } + + fn draw(&mut self, g: &mut Graphics) { + g.background((0.04, 0.04, 0.07)); + g.material(&self.mat); + g.particles(&self.particles).geometry(&self.sphere); + + let mut positions: Vec = Vec::with_capacity(BURST as usize); + let mut colors: Vec = Vec::with_capacity(BURST as usize); + let mut scales: Vec = Vec::with_capacity(BURST as usize); + let mut ages: Vec = Vec::with_capacity(BURST as usize); + let mut lives: Vec = Vec::with_capacity(BURST as usize); + for k in 0..BURST { + let i = self.frame * BURST + k; let u = ((i.wrapping_mul(2654435761) >> 8) & 0xFFFF) as f32 / 65535.0; let v = ((i.wrapping_mul(40503) >> 8) & 0xFFFF) as f32 / 65535.0; - let theta = u * std::f32::consts::TAU; + let theta = u * TAU; let r = v * 0.6; - positions.push(theta.cos() * r); - positions.push(-2.5); - positions.push(theta.sin() * r); + positions.push(Vec3::new(theta.cos() * r, -2.5, theta.sin() * r)); let h = (i as f32 * 0.013) % 1.0; - let (cr, cg, cb) = hsv_to_rgb(h, 0.85, 1.0); - colors.push(cr); - colors.push(cg); - colors.push(cb); - colors.push(1.0); + colors.push(Color::hsv(h * 360.0, 0.85, 1.0)); + scales.push(Vec3::new(1.0, 1.0, 1.0)); + ages.push(0.0); + lives.push(1.0); } - let position_bytes: Vec = positions.iter().flat_map(|f| f.to_le_bytes()).collect(); - let color_bytes: Vec = colors.iter().flat_map(|f| f.to_le_bytes()).collect(); - let zero_floats: Vec = (0..burst).flat_map(|_| 0.0_f32.to_le_bytes()).collect(); - let one_floats: Vec = (0..burst).flat_map(|_| 1.0_f32.to_le_bytes()).collect(); - let one_scale: Vec = (0..burst) - .flat_map(|_| { - [1.0_f32, 1.0, 1.0] - .iter() - .flat_map(|f| f.to_le_bytes()) - .collect::>() - }) - .collect(); - particles_emit( - p, - burst, - vec![ - (position_attr, position_bytes), - (color_attr, color_bytes), - (scale_attr, one_scale), - (age_attr, zero_floats), - (life_attr, one_floats), + self.particles.emit( + BURST, + &[ + (Attribute::position(), &positions), + (Attribute::color(), &colors), + (Attribute::scale(), &scales), + (Attribute::age(), &ages), + (Attribute::life(), &lives), ], - )?; + ); - compute_set( - aging, - "params", - shader_value::ShaderValue::Float4([dt, ttl, 0.0, 0.0]), - )?; - particles_apply(p, aging)?; + self.aging.set("params", (DT, TTL, 0.0, 0.0)); + self.particles.apply(&self.aging); - frame += 1; + self.frame += 1; } - - Ok(()) } -fn hsv_to_rgb(h: f32, s: f32, v: f32) -> (f32, f32, f32) { - let i = (h * 6.0).floor(); - let f = h * 6.0 - i; - let p = v * (1.0 - s); - let q = v * (1.0 - f * s); - let t = v * (1.0 - (1.0 - f) * s); - match (i as i32) % 6 { - 0 => (v, t, p), - 1 => (q, v, p), - 2 => (p, v, t), - 3 => (p, q, v), - 4 => (t, p, v), - _ => (v, p, q), - } +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/particles_noise.rs b/examples/particles_noise.rs index 9ab17126..6e89f1da 100644 --- a/examples/particles_noise.rs +++ b/examples/particles_noise.rs @@ -1,97 +1,68 @@ -use processing_glfw::GlfwContext; - -use bevy::math::Vec3; use processing::prelude::*; -use processing_render::render::command::DrawCommand; -fn main() { - sketch().unwrap(); - exit(0).unwrap(); +struct ParticlesNoise { + sun: Light, + particle: Geometry, + particles: Particles, + material: Material, + noise: Compute, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(900, 700, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(900, 700, false)?; - let graphics = graphics_create(surface, 900, 700, TextureFormat::Rgba16Float)?; - - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(0.0, -4.0, 18.0))?; - transform_look_at(graphics, Vec3::new(0.0, 0.0, 0.0))?; +impl Sketch for ParticlesNoise { + fn settings() -> Settings { + Settings::size(900, 700) + } - let light = - light_create_directional(graphics, bevy::color::Color::srgb(0.95, 0.9, 0.85), 200.0)?; + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((0.0, -4.0, 18.0)); + g.camera_look_at((0, 0, 0)); - let source = geometry_sphere(5.0, 32, 24)?; - let position_attr = geometry_attribute_position(); - let uv_attr = geometry_attribute_uv(); - let color_attr = geometry_attribute_color(); - let p = particles_create_from_geometry(source, vec![position_attr, uv_attr, color_attr])?; + let sun = g.create_directional_light((0.95, 0.9, 0.85), 200.0); - let uv_buf = particles_buffer(p, uv_attr)?.ok_or(error::ProcessingError::ParticlesNotFound)?; - let color_buf = - particles_buffer(p, color_attr)?.ok_or(error::ProcessingError::ParticlesNotFound)?; + let source = Geometry::sphere(5.0, 32, 24)?; + let particles = Particles::from_geometry( + &source, + &[Attribute::position(), Attribute::uv(), Attribute::color()], + )?; - let uv_bytes = buffer_read(uv_buf)?; - let mut colors: Vec = Vec::with_capacity(uv_bytes.len() * 2); - for chunk in uv_bytes.chunks_exact(8) { - let u = f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]); - let (r, g, b) = hsv_to_rgb(u, 0.85, 1.0); - for f in [r, g, b, 1.0] { - colors.extend_from_slice(&f.to_le_bytes()); + let uvs = particles.buffer(Attribute::uv()).read::()?; + let mut colors: Vec = Vec::with_capacity(uvs.len()); + for uv in &uvs { + colors.push(Color::hsv(uv.x * 360.0, 0.85, 1.0)); } - } - buffer_write(color_buf, colors)?; + let mut color_buf = particles.buffer(Attribute::color()); + color_buf.write(&colors); - let particle = geometry_sphere(0.18, 10, 8)?; - let mat = { - let m = material_create_pbr()?; - material_set_albedo_buffer(m, color_buf)?; - m - }; - let noise = particles_kernel_noise()?; + let particle = Geometry::sphere(0.18, 10, 8)?; + let mut material = Material::pbr()?; + material.albedo_buffer(&color_buf); - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_light(graphics, light)?; - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.06, 0.06, 0.08)), - )?; - graphics_record_command(graphics, DrawCommand::Material(mat))?; - graphics_record_command( - graphics, - DrawCommand::Particles { - particles: p, - geometry: Some(particle), - topology: Default::default(), - }, - )?; - graphics_end_draw(graphics)?; + let noise = Particles::noise()?; - let t = elapsed_time()?; - compute_set(noise, "scale", shader_value::ShaderValue::Float(0.25))?; - compute_set(noise, "strength", shader_value::ShaderValue::Float(0.02))?; - compute_set(noise, "time", shader_value::ShaderValue::Float(t * 0.5))?; - particles_apply(p, noise)?; + Ok(ParticlesNoise { + sun, + particle, + particles, + material, + noise, + }) } - Ok(()) -} + fn draw(&mut self, g: &mut Graphics) { + g.light(&self.sun); + g.background((0.06, 0.06, 0.08)); + g.material(&self.material); + g.particles(&self.particles).geometry(&self.particle); -fn hsv_to_rgb(h: f32, s: f32, v: f32) -> (f32, f32, f32) { - let i = (h * 6.0).floor(); - let f = h * 6.0 - i; - let p = v * (1.0 - s); - let q = v * (1.0 - f * s); - let t = v * (1.0 - (1.0 - f) * s); - match (i as i32).rem_euclid(6) { - 0 => (v, t, p), - 1 => (q, v, p), - 2 => (p, v, t), - 3 => (p, q, v), - 4 => (t, p, v), - _ => (v, p, q), + let t = g.elapsed_time(); + self.noise.set("scale", 0.25); + self.noise.set("strength", 0.02); + self.noise.set("time", t * 0.5); + self.particles.apply(&self.noise); } } + +fn main() -> Result<()> { + processing::run::() +} diff --git a/examples/particles_oriented.rs b/examples/particles_oriented.rs index bdb784ec..3d553fb6 100644 --- a/examples/particles_oriented.rs +++ b/examples/particles_oriented.rs @@ -1,8 +1,4 @@ -use processing_glfw::GlfwContext; - -use bevy::math::Vec3; use processing::prelude::*; -use processing_render::render::command::DrawCommand; const SPIN_SHADER: &str = r#" @group(0) @binding(0) var rotation: array; @@ -39,107 +35,85 @@ fn main(@builtin(global_invocation_id) gid: vec3) { } "#; -fn main() { - sketch().unwrap(); - exit(0).unwrap(); +struct ParticlesOriented { + sun: Light, + cube: Geometry, + particles: Particles, + pbr: Material, + spin: Compute, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(900, 700, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(900, 700, false)?; - let graphics = graphics_create(surface, 900, 700, TextureFormat::Rgba16Float)?; - - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(0.0, -6.0, 18.0))?; - transform_look_at(graphics, Vec3::new(0.0, 0.0, 0.0))?; - - let light = - light_create_directional(graphics, bevy::color::Color::srgb(0.9, 0.85, 0.8), 300.0)?; - - let cube = geometry_box(0.6, 0.6, 0.6)?; - - let capacity: u32 = 125; - let mut positions: Vec = Vec::with_capacity(capacity as usize * 3); - let mut rotations: Vec = Vec::with_capacity(capacity as usize * 4); - let mut scales: Vec = Vec::with_capacity(capacity as usize * 3); - for x in 0..5 { - for y in 0..5 { - for z in 0..5 { - positions.push((x as f32 - 2.0) * 1.6); - positions.push((2.0 - y as f32) * 1.6); - positions.push((z as f32 - 2.0) * 1.6); - rotations.push(0.0); - rotations.push(0.0); - rotations.push(0.0); - rotations.push(1.0); - let s = 0.5 + ((x + y + z) as f32 * 0.06); - scales.push(s); - scales.push(s); - scales.push(s); +impl Sketch for ParticlesOriented { + fn settings() -> Settings { + Settings::size(900, 700) + } + + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((0.0, -6.0, 18.0)); + g.camera_look_at((0, 0, 0)); + + let sun = g.create_directional_light((0.9, 0.85, 0.8), 300.0); + + let cube = Geometry::cube((0.6, 0.6, 0.6))?; + + let capacity: u32 = 125; + let mut positions: Vec = Vec::with_capacity(capacity as usize); + let mut rotations: Vec = Vec::with_capacity(capacity as usize); + let mut scales: Vec = Vec::with_capacity(capacity as usize); + for x in 0..5 { + for y in 0..5 { + for z in 0..5 { + positions.push(Vec3::new( + (x as f32 - 2.0) * 1.6, + (2.0 - y as f32) * 1.6, + (z as f32 - 2.0) * 1.6, + )); + rotations.push(Vec4::new(0.0, 0.0, 0.0, 1.0)); + let s = 0.5 + ((x + y + z) as f32 * 0.06); + scales.push(Vec3::new(s, s, s)); + } } } - } - let position_attr = geometry_attribute_position(); - let rotation_attr = geometry_attribute_rotation(); - let scale_attr = geometry_attribute_scale(); - let p = particles_create(capacity, vec![position_attr, rotation_attr, scale_attr])?; - let position_buf = - particles_buffer(p, position_attr)?.ok_or(error::ProcessingError::ParticlesNotFound)?; - let rotation_buf = - particles_buffer(p, rotation_attr)?.ok_or(error::ProcessingError::ParticlesNotFound)?; - let scale_buf = - particles_buffer(p, scale_attr)?.ok_or(error::ProcessingError::ParticlesNotFound)?; - buffer_write( - position_buf, - positions.iter().flat_map(|f| f.to_le_bytes()).collect(), - )?; - buffer_write( - rotation_buf, - rotations.iter().flat_map(|f| f.to_le_bytes()).collect(), - )?; - buffer_write( - scale_buf, - scales.iter().flat_map(|f| f.to_le_bytes()).collect(), - )?; - - let pbr = material_create_pbr()?; - material_set(pbr, "roughness", shader_value::ShaderValue::Float(0.4))?; - - let spin_shader = shader_create(SPIN_SHADER)?; - let spin = compute_create(spin_shader)?; - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_light(graphics, light)?; - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.06, 0.06, 0.08)), + let particles = Particles::new( + capacity, + &[ + Attribute::position(), + Attribute::rotation(), + Attribute::scale(), + ], )?; - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgb(0.9, 0.5, 0.3)), - )?; - graphics_record_command(graphics, DrawCommand::Material(pbr))?; - graphics_record_command( - graphics, - DrawCommand::Particles { - particles: p, - geometry: Some(cube), - topology: Default::default(), - }, - )?; - graphics_end_draw(graphics)?; + particles.buffer(Attribute::position()).write(&positions); + particles.buffer(Attribute::rotation()).write(&rotations); + particles.buffer(Attribute::scale()).write(&scales); + + let mut pbr = Material::pbr()?; + pbr.set("roughness", 0.4); - compute_set( + let spin = Compute::new(&Shader::new(SPIN_SHADER)?)?; + + Ok(ParticlesOriented { + sun, + cube, + particles, + pbr, spin, - "params", - shader_value::ShaderValue::Float4([0.015, 0.0, 0.0, 0.0]), - )?; - particles_apply(p, spin)?; + }) + } + + fn draw(&mut self, g: &mut Graphics) { + g.light(&self.sun); + g.background((0.06, 0.06, 0.08)); + g.fill((0.9, 0.5, 0.3)); + g.material(&self.pbr); + g.particles(&self.particles).geometry(&self.cube); + + self.spin.set("params", (0.015, 0.0, 0.0, 0.0)); + self.particles.apply(&self.spin); } +} - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/particles_scatter.rs b/examples/particles_scatter.rs index f1b51961..16d517f0 100644 --- a/examples/particles_scatter.rs +++ b/examples/particles_scatter.rs @@ -1,10 +1,4 @@ -use processing_glfw::GlfwContext; -use std::time::Instant; - -use bevy::math::Vec3; use processing::prelude::*; -use processing_render::geometry::AttributeFormat; -use processing_render::render::command::DrawCommand; const AGE_SHADER: &str = r#" struct Params { dt: f32, ttl: f32, _pad0: f32, _pad1: f32 } @@ -34,91 +28,87 @@ fn main(@builtin(global_invocation_id) gid: vec3) { } "#; -fn main() { - sketch().unwrap(); - exit(0).unwrap(); +const BURST: u32 = 600; +const DT: f32 = 1.0 / 60.0; +const TTL: f32 = 4.0; + +struct ParticlesScatter { + particles: Particles, + particle: Geometry, + // read by the scatter kernel + _source: Geometry, + scatter: Compute, + aging: Compute, + mat: Material, + key: Light, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(900, 700, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(900, 700, false)?; - let graphics = graphics_create(surface, 900, 700, TextureFormat::Rgba16Float)?; - - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(0.0, -0.4, 4.5))?; - transform_look_at(graphics, Vec3::ZERO)?; - - let key = - light_create_directional(graphics, bevy::color::Color::srgb(1.0, 0.95, 0.85), 4500.0)?; - - let source = geometry_sphere(1.2, 96, 48)?; - let scatter = particles_scatter_create(source)?; - - let particle = geometry_sphere(0.005, 6, 4)?; - - let capacity: u32 = 40_000; - let position_attr = geometry_attribute_position(); - let scale_attr = geometry_attribute_scale(); - let life_attr = geometry_attribute_life(); - let age_attr = geometry_attribute_create("age", AttributeFormat::Float)?; - - let p = particles_create( - capacity, - vec![position_attr, scale_attr, life_attr, age_attr], - )?; - - let age_shader = shader_create(AGE_SHADER)?; - let aging = compute_create(age_shader)?; - - let mat = material_create_pbr()?; - material_set( - mat, - "color", - shader_value::ShaderValue::Float4([0.9, 0.85, 1.0, 1.0]), - )?; - - let burst: u32 = 600; - let dt: f32 = 1.0 / 60.0; - let ttl: f32 = 4.0; - let start = Instant::now(); - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_light(graphics, key)?; - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.03, 0.03, 0.05)), - )?; - graphics_record_command(graphics, DrawCommand::Material(mat))?; - graphics_record_command( - graphics, - DrawCommand::Particles { - particles: p, - geometry: Some(particle), - topology: Default::default(), - }, +impl Sketch for ParticlesScatter { + fn settings() -> Settings { + Settings::size(900, 700) + } + + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((0.0, -0.4, 4.5)); + g.camera_look_at((0, 0, 0)); + + let key = g.create_directional_light((1.0, 0.95, 0.85), 4500.0); + + let source = Geometry::sphere(1.2, 96, 48)?; + let scatter = Particles::scatter_surface(&source)?; + + let particle = Geometry::sphere(0.005, 6, 4)?; + + let age = Attribute::new("age", AttributeFormat::Float)?; + let particles = Particles::new( + 40_000, + &[ + Attribute::position(), + Attribute::scale(), + Attribute::life(), + age, + ], )?; - graphics_end_draw(graphics)?; - let t = start.elapsed().as_secs_f32(); + let aging = Compute::new(&Shader::new(AGE_SHADER)?)?; + + let mut mat = Material::pbr()?; + mat.set("color", (0.9, 0.85, 1.0, 1.0)); + + Ok(ParticlesScatter { + particles, + particle, + _source: source, + scatter, + aging, + mat, + key, + }) + } + + fn draw(&mut self, g: &mut Graphics) { + g.light(&self.key); + g.background((0.03, 0.03, 0.05)); + g.material(&self.mat); + g.particles(&self.particles).geometry(&self.particle); + + let t = g.elapsed_time(); let cam_x = (t * 0.25).cos() * 4.5; let cam_z = (t * 0.25).sin() * 4.5; - transform_set_position(graphics, Vec3::new(cam_x, -0.4, cam_z))?; - transform_look_at(graphics, Vec3::ZERO)?; + g.camera_position((cam_x, -0.4, cam_z)); + g.camera_look_at((0, 0, 0)); - compute_set( - scatter, - "seed", - shader_value::ShaderValue::UInt((t * 1000.0) as u32 ^ 0xc0ffeeu32), - )?; - particles_emit_gpu(p, burst, scatter)?; + let seed = (t * 1000.0) as u32 ^ 0xc0ffee; + self.scatter.set("seed", seed); + self.particles.emit_gpu(BURST, &self.scatter); - compute_set(aging, "dt", shader_value::ShaderValue::Float(dt))?; - compute_set(aging, "ttl", shader_value::ShaderValue::Float(ttl))?; - particles_apply(p, aging)?; + self.aging.set("dt", DT); + self.aging.set("ttl", TTL); + self.particles.apply(&self.aging); } +} - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/particles_scatter_volume.rs b/examples/particles_scatter_volume.rs index 0f394077..59a13755 100644 --- a/examples/particles_scatter_volume.rs +++ b/examples/particles_scatter_volume.rs @@ -1,10 +1,4 @@ -use processing_glfw::GlfwContext; -use std::time::Instant; - -use bevy::math::Vec3; use processing::prelude::*; -use processing_render::geometry::AttributeFormat; -use processing_render::render::command::DrawCommand; const AGE_SHADER: &str = r#" struct Params { dt: f32, ttl: f32, _pad0: f32, _pad1: f32 } @@ -34,85 +28,79 @@ fn main(@builtin(global_invocation_id) gid: vec3) { } "#; -fn main() { - sketch().unwrap(); - exit(0).unwrap(); +const BURST: u32 = 250; +const DT: f32 = 1.0 / 60.0; +const TTL: f32 = 5.0; + +struct ParticlesScatterVolume { + particles: Particles, + particle: Geometry, + // read by the scatter kernel + _duck: Geometry, + scatter: Compute, + aging: Compute, + mat: Material, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(600, 400, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(900, 700, false)?; - let graphics = graphics_create(surface, 900, 700, TextureFormat::Rgba16Float)?; - - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(0.0, -100.0, 400.0))?; - transform_look_at(graphics, Vec3::new(0.0, -80.0, 0.0))?; - graphics_orbit_camera(graphics)?; - - let gltf = gltf_load(graphics, "gltf/Duck.glb")?; - let duck = gltf_geometry(gltf, "LOD3spShape")?; - let scatter = particles_scatter_volume_create(duck)?; - - let particle = geometry_sphere(0.15, 4, 3)?; - - let capacity: u32 = 30_000; - let position_attr = geometry_attribute_position(); - let scale_attr = geometry_attribute_scale(); - let life_attr = geometry_attribute_life(); - let age_attr = geometry_attribute_create("age", AttributeFormat::Float)?; - - let p = particles_create( - capacity, - vec![position_attr, scale_attr, life_attr, age_attr], - )?; - - let age_shader = shader_create(AGE_SHADER)?; - let aging = compute_create(age_shader)?; - - let mat = material_create_unlit()?; - material_set( - mat, - "color", - shader_value::ShaderValue::Float4([1.0, 1.0, 1.0, 1.0]), - )?; - - let burst: u32 = 250; - let dt: f32 = 1.0 / 60.0; - let ttl: f32 = 5.0; - let start = Instant::now(); - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.03, 0.03, 0.05)), - )?; - graphics_record_command(graphics, DrawCommand::Material(mat))?; - graphics_record_command( - graphics, - DrawCommand::Particles { - particles: p, - geometry: Some(particle), - topology: Default::default(), - }, +impl Sketch for ParticlesScatterVolume { + fn settings() -> Settings { + Settings::size(900, 700) + } + + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((0, -100, 400)); + g.camera_look_at((0, -80, 0)); + g.orbit_camera(); + + let gltf = Gltf::load(g, "gltf/Duck.glb")?; + let duck = gltf.geometry("LOD3spShape")?; + let scatter = Particles::scatter_volume(&duck)?; + + let particle = Geometry::sphere(0.15, 4, 3)?; + + let age = Attribute::new("age", AttributeFormat::Float)?; + let particles = Particles::new( + 30_000, + &[ + Attribute::position(), + Attribute::scale(), + Attribute::life(), + age, + ], )?; - graphics_end_draw(graphics)?; - let t = start.elapsed().as_secs_f32(); + let aging = Compute::new(&Shader::new(AGE_SHADER)?)?; + + let mut mat = Material::unlit()?; + mat.set("color", (1.0, 1.0, 1.0, 1.0)); - compute_set( + Ok(ParticlesScatterVolume { + particles, + particle, + _duck: duck, scatter, - "seed", - shader_value::ShaderValue::UInt((t * 1000.0) as u32 ^ 0xc0ffeeu32), - )?; - particles_emit_gpu(p, burst, scatter)?; + aging, + mat, + }) + } + + fn draw(&mut self, g: &mut Graphics) { + g.background((0.03, 0.03, 0.05)); + g.material(&self.mat); + g.particles(&self.particles).geometry(&self.particle); - compute_set(aging, "dt", shader_value::ShaderValue::Float(dt))?; - compute_set(aging, "ttl", shader_value::ShaderValue::Float(ttl))?; - particles_apply(p, aging)?; + let t = g.elapsed_time(); + let seed = (t * 1000.0) as u32 ^ 0xc0ffee; + self.scatter.set("seed", seed); + self.particles.emit_gpu(BURST, &self.scatter); + + self.aging.set("dt", DT); + self.aging.set("ttl", TTL); + self.particles.apply(&self.aging); } +} - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/particles_stress.rs b/examples/particles_stress.rs index 006c4902..bad2a8fc 100644 --- a/examples/particles_stress.rs +++ b/examples/particles_stress.rs @@ -1,8 +1,4 @@ -use processing_glfw::GlfwContext; - -use bevy::math::Vec3; use processing::prelude::*; -use processing_render::render::command::DrawCommand; const GRID: u32 = 100; // GRID^3 particles const SPACING: f32 = 1.0; @@ -29,11 +25,6 @@ fn main(@builtin(global_invocation_id) gid: vec3) { } "#; -fn main() { - sketch().unwrap(); - exit(0).unwrap(); -} - fn hash_u32(mut x: u32) -> u32 { x = (x ^ 61).wrapping_add(x >> 16); x = x.wrapping_add(x << 3); @@ -47,100 +38,91 @@ fn hash_unit(seed: u32) -> f32 { (hash_u32(seed) as f32) / (u32::MAX as f32) } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(900, 700, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(900, 700, false)?; - let graphics = graphics_create(surface, 900, 700, TextureFormat::Rgba16Float)?; - - graphics_mode_3d(graphics)?; - let extent = (GRID as f32) * SPACING * 0.5; - transform_set_position(graphics, Vec3::new(0.0, -extent * 0.6, extent * 2.5))?; - transform_look_at(graphics, Vec3::new(0.0, 0.0, 0.0))?; - graphics_orbit_camera(graphics)?; - - let red = light_create_directional(graphics, bevy::color::Color::srgb(1.0, 0.0, 0.0), 1000.0)?; - transform_set_position(red, Vec3::new(1.0, 0.0, 0.0))?; - transform_look_at(red, Vec3::ZERO)?; - - let green = - light_create_directional(graphics, bevy::color::Color::srgb(0.0, 1.0, 0.0), 1000.0)?; - transform_set_position(green, Vec3::new(0.0, -1.0, 0.0))?; - transform_look_at(green, Vec3::ZERO)?; - - let blue = light_create_directional(graphics, bevy::color::Color::srgb(0.0, 0.0, 1.0), 1000.0)?; - transform_set_position(blue, Vec3::new(0.0, 0.0, 1.0))?; - transform_look_at(blue, Vec3::ZERO)?; - - let cube = geometry_box(0.35, 0.35, 0.35)?; - - let capacity = GRID * GRID * GRID; - let position_attr = geometry_attribute_position(); - let color_attr = geometry_attribute_color(); - let p = particles_create(capacity, vec![position_attr, color_attr])?; - - let mut positions: Vec = Vec::with_capacity(capacity as usize * 3); - let mut colors: Vec = Vec::with_capacity(capacity as usize * 4); - let extent_half = (GRID as f32) * SPACING * 0.5; - for i in 0..capacity { - let rx = hash_unit(i.wrapping_mul(2654435761).wrapping_add(0x9E37)); - let ry = hash_unit(i.wrapping_mul(40503).wrapping_add(0x68E1)); - let rz = hash_unit(i.wrapping_mul(2246822519).wrapping_add(0xC2B2)); - positions.push((rx * 2.0 - 1.0) * extent_half); - positions.push((1.0 - ry * 2.0) * extent_half); - positions.push((rz * 2.0 - 1.0) * extent_half); - colors.push(rx); - colors.push(ry); - colors.push(rz); - colors.push(1.0); +struct ParticlesStress { + red: Light, + green: Light, + blue: Light, + cube: Geometry, + particles: Particles, + mat: Material, + spin: Compute, +} + +impl Sketch for ParticlesStress { + fn settings() -> Settings { + Settings::size(900, 700) } - let position_buf = - particles_buffer(p, position_attr)?.ok_or(error::ProcessingError::ParticlesNotFound)?; - let color_buf = - particles_buffer(p, color_attr)?.ok_or(error::ProcessingError::ParticlesNotFound)?; - buffer_write( - position_buf, - positions.iter().flat_map(|f| f.to_le_bytes()).collect(), - )?; - buffer_write( - color_buf, - colors.iter().flat_map(|f| f.to_le_bytes()).collect(), - )?; - - let mat = { - let m = material_create_pbr()?; - material_set_albedo_buffer(m, color_buf)?; - m - }; - let spin_shader = shader_create(SPIN_SHADER)?; - let spin = compute_create(spin_shader)?; - - eprintln!("{capacity} particles"); - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_light(graphics, red)?; - graphics_light(graphics, green)?; - graphics_light(graphics, blue)?; - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.04, 0.04, 0.07)), - )?; - graphics_record_command(graphics, DrawCommand::Material(mat))?; - graphics_record_command( - graphics, - DrawCommand::Particles { - particles: p, - geometry: Some(cube), - topology: Default::default(), - }, - )?; - graphics_end_draw(graphics)?; - - compute_set(spin, "dt", shader_value::ShaderValue::Float(0.003))?; - particles_apply(p, spin)?; + + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + let extent = (GRID as f32) * SPACING * 0.5; + g.camera_position((0.0, -extent * 0.6, extent * 2.5)); + g.camera_look_at((0, 0, 0)); + g.orbit_camera(); + + let red = g.create_directional_light((1.0, 0.0, 0.0), 1000.0); + red.position((1, 0, 0)).look_at((0, 0, 0)); + + let green = g.create_directional_light((0.0, 1.0, 0.0), 1000.0); + green.position((0, -1, 0)).look_at((0, 0, 0)); + + let blue = g.create_directional_light((0.0, 0.0, 1.0), 1000.0); + blue.position((0, 0, 1)).look_at((0, 0, 0)); + + let cube = Geometry::cube((0.35, 0.35, 0.35))?; + + let capacity = GRID * GRID * GRID; + let particles = Particles::new(capacity, &[Attribute::position(), Attribute::color()])?; + + let mut positions: Vec = Vec::with_capacity(capacity as usize); + let mut colors: Vec = Vec::with_capacity(capacity as usize); + let extent_half = (GRID as f32) * SPACING * 0.5; + for i in 0..capacity { + let rx = hash_unit(i.wrapping_mul(2654435761).wrapping_add(0x9E37)); + let ry = hash_unit(i.wrapping_mul(40503).wrapping_add(0x68E1)); + let rz = hash_unit(i.wrapping_mul(2246822519).wrapping_add(0xC2B2)); + positions.push(Vec3::new( + (rx * 2.0 - 1.0) * extent_half, + (1.0 - ry * 2.0) * extent_half, + (rz * 2.0 - 1.0) * extent_half, + )); + colors.push(Color::rgb(rx, ry, rz)); + } + particles.buffer(Attribute::position()).write(&positions); + let mut color_buf = particles.buffer(Attribute::color()); + color_buf.write(&colors); + + let mut mat = Material::pbr()?; + mat.albedo_buffer(&color_buf); + + let spin = Compute::new(&Shader::new(SPIN_SHADER)?)?; + + eprintln!("{capacity} particles"); + + Ok(ParticlesStress { + red, + green, + blue, + cube, + particles, + mat, + spin, + }) } - Ok(()) + fn draw(&mut self, g: &mut Graphics) { + g.light(&self.red); + g.light(&self.green); + g.light(&self.blue); + g.background((0.04, 0.04, 0.07)); + g.material(&self.mat); + g.particles(&self.particles).geometry(&self.cube); + + self.spin.set("dt", 0.003); + self.particles.apply(&self.spin); + } +} + +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/particles_text_whirl.rs b/examples/particles_text_whirl.rs index 3fc13afc..943f459e 100644 --- a/examples/particles_text_whirl.rs +++ b/examples/particles_text_whirl.rs @@ -1,16 +1,10 @@ -use processing_glfw::GlfwContext; -use std::time::Instant; - -use bevy::math::Vec3; use processing::prelude::*; -use processing_render::render::command::{DrawCommand, TextStyle}; const BASE_COUNT: u32 = 6000; const TRAIL_LEN_MIN: u32 = 8; const TRAIL_LEN_MAX: u32 = 150; const TRAIL_LEN: u32 = TRAIL_LEN_MAX; const CAPACITY: u32 = BASE_COUNT * TRAIL_LEN; -const TRAIL_STRIDE: u32 = 1; const NOISE_STRENGTH: f32 = 50.5; const SPHERE_RADIUS: f32 = 1.05; @@ -255,189 +249,148 @@ fn main(@builtin(global_invocation_id) gid: vec3) { } "#; -fn main() { - sketch().unwrap(); - exit(0).unwrap(); +const TEXT_PT: f32 = 700.0; +const EXTRUSION: f32 = 70.0; + +struct TextWhirl { + particles: Particles, + particle: Geometry, + sim: Compute, + fade: Compute, + mat: Material, + // read by the sim kernel + _source: Geometry, + _buffers: Vec, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(1200, 800, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(1200, 800, false)?; - let graphics = graphics_create(surface, 1200, 800, TextureFormat::Rgba16Float)?; - - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(0.0, 0.0, 1700.0))?; - transform_look_at(graphics, Vec3::ZERO)?; - graphics_orbit_camera(graphics)?; - - const TEXT_PT: f32 = 700.0; - const EXTRUSION: f32 = 70.0; - processing_core::app_mut(|app| { - let mut state = app - .world_mut() - .get_mut::(graphics) - .ok_or(error::ProcessingError::GraphicsNotFound)?; - state.style.text_size = TEXT_PT; - Ok(()) - })?; - graphics_record_command(graphics, DrawCommand::TextStyle(TextStyle::Bold))?; - - let text = "processing5"; - let w = graphics_text_width(graphics, text)?; - println!("text width = {w} (size = {TEXT_PT}, extrusion = {EXTRUSION})"); - let mesh = graphics_text_to_model(graphics, text, -w / 2.0, TEXT_PT * 0.4, EXTRUSION)?; - let source = geometry_create_from_mesh(mesh)?; - - let (cdf_bytes, indices_bytes, face_count) = processing_core::app_mut(|app| { - app.world_mut() - .run_system_cached_with(processing_render::particles::prepare_scatter_source, source) - .unwrap() - })?; - let cdf_buf = buffer_create_with_data(cdf_bytes)?; - let idx_buf = buffer_create_with_data(indices_bytes)?; - - let head_pos_buf = buffer_create(BASE_COUNT as u64 * 3 * 4)?; - let anchor_normal_buf = buffer_create(BASE_COUNT as u64 * 3 * 4)?; - let trail_len_buf = buffer_create(BASE_COUNT as u64 * 4)?; - let trail_head_buf = buffer_create(BASE_COUNT as u64 * 4)?; - - let particle = geometry_sphere(SPHERE_RADIUS, 5, 4)?; - - let p = particles_create( - CAPACITY, - vec![ - geometry_attribute_position(), - geometry_attribute_scale(), - geometry_attribute_life(), - geometry_attribute_color(), - ], - )?; - - let sim_src = sim_shader(); - let sim_shader_e = shader_create(&sim_src)?; - let sim = compute_create(sim_shader_e)?; - compute_set( - sim, - "source_position", - shader_value::ShaderValue::MeshAttribute(source, geometry_attribute_position()), - )?; - compute_set( - sim, - "source_indices", - shader_value::ShaderValue::Buffer(idx_buf), - )?; - compute_set(sim, "cdf", shader_value::ShaderValue::Buffer(cdf_buf))?; - compute_set( - sim, - "head_pos", - shader_value::ShaderValue::Buffer(head_pos_buf), - )?; - compute_set( - sim, - "anchor_normal", - shader_value::ShaderValue::Buffer(anchor_normal_buf), - )?; - compute_set( - sim, - "trail_len_buf", - shader_value::ShaderValue::Buffer(trail_len_buf), - )?; - compute_set( - sim, - "trail_head_buf", - shader_value::ShaderValue::Buffer(trail_head_buf), - )?; - compute_set( - sim, - "base_count", - shader_value::ShaderValue::UInt(BASE_COUNT), - )?; - compute_set( - sim, - "trail_len_max", - shader_value::ShaderValue::UInt(TRAIL_LEN_MAX), - )?; - compute_set( - sim, - "trail_len_min", - shader_value::ShaderValue::UInt(TRAIL_LEN_MIN), - )?; - compute_set( - sim, - "face_count", - shader_value::ShaderValue::UInt(face_count), - )?; - compute_set(sim, "seed", shader_value::ShaderValue::UInt(0xc0ffeeu32))?; - compute_set(sim, "noise_scale", shader_value::ShaderValue::Float(0.005))?; - compute_set( - sim, - "noise_strength", - shader_value::ShaderValue::Float(NOISE_STRENGTH), - )?; - compute_set(sim, "step_speed", shader_value::ShaderValue::Float(0.05))?; - - compute_set(sim, "time", shader_value::ShaderValue::Float(0.0))?; - particles_apply(p, sim)?; - - let color_buf = particles_buffer(p, geometry_attribute_color())? - .ok_or(error::ProcessingError::ParticlesNotFound)?; - let mat = material_create_unlit()?; - material_set_albedo_buffer(mat, color_buf)?; - - let fade_shader_e = shader_create(COLOR_FADE)?; - let fade = compute_create(fade_shader_e)?; - compute_set( - fade, - "base_count", - shader_value::ShaderValue::UInt(BASE_COUNT), - )?; - compute_set( - fade, - "trail_len_max", - shader_value::ShaderValue::UInt(TRAIL_LEN_MAX), - )?; - compute_set( - fade, - "trail_len_buf", - shader_value::ShaderValue::Buffer(trail_len_buf), - )?; - compute_set( - fade, - "trail_head_buf", - shader_value::ShaderValue::Buffer(trail_head_buf), - )?; - - particles_apply(p, fade)?; - - let start = Instant::now(); - let mut render_frame: u32 = 0; - while glfw_ctx.poll_events() { - if render_frame % TRAIL_STRIDE == 0 { - let t = start.elapsed().as_secs_f32(); - compute_set(sim, "time", shader_value::ShaderValue::Float(t * 0.015))?; - particles_apply(p, sim)?; - particles_apply(p, fade)?; +impl Sketch for TextWhirl { + fn settings() -> Settings { + Settings::size(1200, 800) + } + + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((0, 0, 1700)); + g.camera_look_at((0, 0, 0)); + g.orbit_camera(); + + g.text_size(TEXT_PT); + g.text_style(TextStyle::Bold); + + let text = "processing5"; + let w = g.text_width(text); + println!("text width = {w} (size = {TEXT_PT}, extrusion = {EXTRUSION})"); + let source = g.text_to_model(text, -w / 2.0, TEXT_PT * 0.4, EXTRUSION)?; + + let positions = source.positions(); + let mut indices = source.indices(); + if indices.is_empty() { + for i in 0..source.vertex_count() { + indices.push(i); + } + } + let face_count = (indices.len() / 3) as u32; + + // area-weighted CDF + let mut cdf = Vec::new(); + let mut total = 0.0; + for face in 0..face_count as usize { + let p0 = positions[indices[face * 3] as usize]; + let p1 = positions[indices[face * 3 + 1] as usize]; + let p2 = positions[indices[face * 3 + 2] as usize]; + let area = 0.5 * (p1 - p0).cross(p2 - p0).length(); + total += area; + cdf.push(total); + } + let inv = 1.0 / total; + for value in cdf.iter_mut() { + *value *= inv; } - render_frame = render_frame.wrapping_add(1); - graphics_begin_draw(graphics)?; - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.02, 0.02, 0.04)), - )?; - graphics_record_command(graphics, DrawCommand::Material(mat))?; - graphics_record_command( - graphics, - DrawCommand::Particles { - particles: p, - geometry: Some(particle), - topology: Default::default(), - }, + let cdf_buf = Buffer::from_slice(&cdf)?; + let idx_buf = Buffer::from_slice(&indices)?; + + let head_pos_buf = Buffer::new(BASE_COUNT as u64 * 3 * 4)?; + let anchor_normal_buf = Buffer::new(BASE_COUNT as u64 * 3 * 4)?; + let trail_len_buf = Buffer::new(BASE_COUNT as u64 * 4)?; + let trail_head_buf = Buffer::new(BASE_COUNT as u64 * 4)?; + + let particle = Geometry::sphere(SPHERE_RADIUS, 5, 4)?; + + let mut particles = Particles::new( + CAPACITY, + &[ + Attribute::position(), + Attribute::scale(), + Attribute::life(), + Attribute::color(), + ], )?; - graphics_end_draw(graphics)?; + + let mut sim = Compute::new(&Shader::new(&sim_shader())?)?; + sim.set( + "source_position", + source.attribute_data(Attribute::position()), + ); + sim.set("source_indices", &idx_buf); + sim.set("cdf", &cdf_buf); + sim.set("head_pos", &head_pos_buf); + sim.set("anchor_normal", &anchor_normal_buf); + sim.set("trail_len_buf", &trail_len_buf); + sim.set("trail_head_buf", &trail_head_buf); + sim.set("base_count", BASE_COUNT); + sim.set("trail_len_max", TRAIL_LEN_MAX); + sim.set("trail_len_min", TRAIL_LEN_MIN); + sim.set("face_count", face_count); + sim.set("seed", 0xc0ffee_u32); + sim.set("noise_scale", 0.005); + sim.set("noise_strength", NOISE_STRENGTH); + sim.set("step_speed", 0.05); + + sim.set("time", 0.0); + particles.apply(&sim); + + let mut mat = Material::unlit()?; + mat.albedo_buffer(&particles.buffer(Attribute::color())); + + let mut fade = Compute::new(&Shader::new(COLOR_FADE)?)?; + fade.set("base_count", BASE_COUNT); + fade.set("trail_len_max", TRAIL_LEN_MAX); + fade.set("trail_len_buf", &trail_len_buf); + fade.set("trail_head_buf", &trail_head_buf); + + particles.apply(&fade); + + Ok(TextWhirl { + particles, + particle, + sim, + fade, + mat, + _source: source, + _buffers: vec![ + cdf_buf, + idx_buf, + head_pos_buf, + anchor_normal_buf, + trail_len_buf, + trail_head_buf, + ], + }) } - Ok(()) + fn draw(&mut self, g: &mut Graphics) { + let t = g.elapsed_time(); + self.sim.set("time", t * 0.015); + self.particles.apply(&self.sim); + self.particles.apply(&self.fade); + + g.background((0.02, 0.02, 0.04)); + g.material(&self.mat); + g.particles(&self.particles).geometry(&self.particle); + } +} + +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/pbr.rs b/examples/pbr.rs index af13268e..6aa32a47 100644 --- a/examples/pbr.rs +++ b/examples/pbr.rs @@ -1,96 +1,56 @@ -use processing_glfw::GlfwContext; - -use bevy::math::{Vec2, Vec3}; use processing::prelude::*; -use processing_render::render::command::DrawCommand; - -fn main() { - match sketch() { - Ok(_) => { - eprintln!("Sketch completed successfully"); - exit(0).unwrap(); - } - Err(e) => { - eprintln!("Sketch error: {:?}", e); - exit(1).unwrap(); - } - }; -} - -fn sketch() -> error::Result<()> { - let width = 800; - let height = 600; - let mut glfw_ctx = GlfwContext::new(width, height, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(width, height, false)?; - let graphics = graphics_create(surface, width, height, TextureFormat::Rgba16Float)?; - - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(0.0, 0.0, 600.0))?; - transform_look_at(graphics, Vec3::new(0.0, 0.0, 0.0))?; - let dir_light = - light_create_directional(graphics, bevy::color::Color::srgb(1.0, 0.98, 0.95), 1_500.0)?; - transform_set_position(dir_light, Vec3::new(300.0, -400.0, 300.0))?; - transform_look_at(dir_light, Vec3::new(0.0, 0.0, 0.0))?; +const COLS: u32 = 11; +const ROWS: u32 = 5; +const SPACING: f32 = 70.0; - let point_light = - light_create_point(graphics, bevy::color::Color::WHITE, 100_000.0, 800.0, 0.0)?; - transform_set_position(point_light, Vec3::new(200.0, -200.0, 400.0))?; - - let cols = 11; - let rows = 5; - let base_color = bevy::color::Color::srgb(1.0, 0.85, 0.57); - let spacing = 70.0; - let offset_x = (cols - 1) as f32 * spacing / 2.0; - let offset_y = (rows - 1) as f32 * spacing / 2.0; - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_light(graphics, dir_light)?; - graphics_light(graphics, point_light)?; +struct Pbr { + sun: Light, + lamp: Light, +} - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.05, 0.05, 0.07)), - )?; +impl Sketch for Pbr { + fn settings() -> Settings { + Settings::size(800, 600) + } - graphics_record_command(graphics, DrawCommand::Fill(base_color))?; + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((0, 0, 600)); + g.camera_look_at((0, 0, 0)); - for row in 0..rows { - for col in 0..cols { - let roughness = col as f32 / (cols - 1) as f32; - let metallic = row as f32 / (rows - 1) as f32; + let sun = g.create_directional_light((1.0, 0.98, 0.95), 1500); + sun.position((300, -400, 300)).look_at((0, 0, 0)); + let lamp = g.create_point_light(Color::WHITE, 100_000, 800, 0); + lamp.position((200, -200, 400)); - graphics_record_command(graphics, DrawCommand::Roughness(roughness))?; - graphics_record_command(graphics, DrawCommand::Metallic(metallic))?; + Ok(Pbr { sun, lamp }) + } - graphics_record_command(graphics, DrawCommand::PushMatrix)?; - graphics_record_command( - graphics, - DrawCommand::Translate( - Vec2::new( - col as f32 * spacing - offset_x, - offset_y - row as f32 * spacing, - ) - .extend(0.0), - ), - )?; - graphics_record_command( - graphics, - DrawCommand::Sphere { - radius: 30.0, - sectors: 32, - stacks: 18, - }, - )?; - graphics_record_command(graphics, DrawCommand::PopMatrix)?; + fn draw(&mut self, g: &mut Graphics) { + g.background((0.05, 0.05, 0.07)); + g.light(&self.sun); + g.light(&self.lamp); + g.fill((1.0, 0.85, 0.57)); + + let offset_x = (COLS - 1) as f32 * SPACING / 2.0; + let offset_y = (ROWS - 1) as f32 * SPACING / 2.0; + for row in 0..ROWS { + for col in 0..COLS { + g.roughness(col as f32 / (COLS - 1) as f32); + g.metallic(row as f32 / (ROWS - 1) as f32); + + let g = g.push(); + g.translate(( + col as f32 * SPACING - offset_x, + offset_y - row as f32 * SPACING, + )); + g.sphere(30).detail(32, 18); } } - - graphics_end_draw(graphics)?; } +} - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/primitives_2d.rs b/examples/primitives_2d.rs index a257777b..770c33df 100644 --- a/examples/primitives_2d.rs +++ b/examples/primitives_2d.rs @@ -1,125 +1,66 @@ -use processing_glfw::GlfwContext; -use std::f32::consts::PI; - use processing::prelude::*; -use processing_render::render::command::DrawCommand; -fn main() { - sketch().unwrap(); - exit(0).unwrap(); +struct Primitives2d { + t: f32, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(600, 600, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(600, 600, false)?; - let graphics = graphics_create(surface, 600, 600, TextureFormat::Rgba16Float)?; - - let mut t: f32 = 0.0; - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; +impl Sketch for Primitives2d { + fn settings() -> Settings { + Settings::size(600, 600) + } - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.95, 0.93, 0.9)), - )?; + fn setup(_g: &mut Graphics) -> Result { + Ok(Primitives2d { t: 0.0 }) + } + fn draw(&mut self, g: &mut Graphics) { + let t = self.t; let cx = 300.0; let cy = 300.0; + g.background((0.95, 0.93, 0.9)); - graphics_record_command(graphics, DrawCommand::NoFill)?; - graphics_record_command(graphics, DrawCommand::StrokeWeight(2.0))?; - + g.no_fill(); + g.stroke_weight(2); for i in 0..12 { let r = 40.0 + i as f32 * 18.0; - let offset = t + i as f32 * 0.15; + let start = t + i as f32 * 0.15; let v = 0.2 + (i as f32 / 12.0) * 0.4; - graphics_record_command( - graphics, - DrawCommand::StrokeColor(bevy::color::Color::srgb(v, v * 0.8, v * 0.6)), - )?; - graphics_record_command( - graphics, - DrawCommand::Arc { - cx, - cy, - w: r * 2.0, - h: r * 2.0, - start: offset, - stop: offset + PI * 1.2, - mode: ArcMode::Open, - }, - )?; + g.stroke((v, v * 0.8, v * 0.6)); + g.arc(cx, cy, r * 2.0, r * 2.0, start, start + PI * 1.2); } - graphics_record_command(graphics, DrawCommand::NoStroke)?; + g.no_stroke(); for i in 0..12 { let r = 40.0 + i as f32 * 18.0; let angle = t + i as f32 * 0.15; - let x = cx + r * angle.cos(); - let y = cy + r * angle.sin(); - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgb(0.85, 0.3 + i as f32 / 24.0, 0.2)), - )?; - graphics_record_command( - graphics, - DrawCommand::Ellipse { - cx: x, - cy: y, - w: 6.0, - h: 6.0, - }, - )?; + g.fill((0.85, 0.3 + i as f32 / 24.0, 0.2)); + g.circle(cx + r * angle.cos(), cy + r * angle.sin(), 6); } - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgba(0.1, 0.1, 0.1, 0.15)), - )?; + g.fill((0.1, 0.1, 0.1, 0.15)); for i in 0..6 { let angle = t * 0.5 + i as f32 * PI / 3.0; - let d = 250.0; - let px = cx + d * angle.cos(); - let py = cy + d * angle.sin(); + let x = cx + 250.0 * angle.cos(); + let y = cy + 250.0 * angle.sin(); let s = 20.0; - graphics_record_command( - graphics, - DrawCommand::Triangle { - x1: px, - y1: py - s, - x2: px - s * 0.866, - y2: py + s * 0.5, - x3: px + s * 0.866, - y3: py + s * 0.5, - }, - )?; + g.triangle( + x, + y - s, + x - s * 0.866, + y + s * 0.5, + x + s * 0.866, + y + s * 0.5, + ); } let d = 15.0 + 5.0 * (t * 3.0).sin(); - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgba(0.9, 0.4, 0.1, 0.4)), - )?; - graphics_record_command( - graphics, - DrawCommand::Quad { - x1: cx, - y1: cy - d, - x2: cx + d, - y2: cy, - x3: cx, - y3: cy + d, - x4: cx - d, - y4: cy, - }, - )?; + g.fill((0.9, 0.4, 0.1, 0.4)); + g.quad(cx, cy - d, cx + d, cy, cx, cy + d, cx - d, cy); - graphics_end_draw(graphics)?; - t += 0.01; + self.t += 0.01; } +} - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/primitives_3d.rs b/examples/primitives_3d.rs index ceda4cd4..1954666c 100644 --- a/examples/primitives_3d.rs +++ b/examples/primitives_3d.rs @@ -1,130 +1,63 @@ -use processing_glfw::GlfwContext; - -use bevy::math::{Vec2, Vec3}; use processing::prelude::*; -use processing_render::render::command::DrawCommand; -fn main() { - sketch().unwrap(); - exit(0).unwrap(); +struct Primitives3d { + t: f32, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(900, 400, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(900, 400, false)?; - let graphics = graphics_create(surface, 900, 400, TextureFormat::Rgba16Float)?; - - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(0.0, -80.0, 800.0))?; - transform_look_at(graphics, Vec3::new(0.0, 0.0, 0.0))?; - - let light = - light_create_directional(graphics, bevy::color::Color::srgb(0.9, 0.85, 0.8), 300.0)?; - - let pbr = material_create_pbr()?; - material_set(pbr, "roughness", shader_value::ShaderValue::Float(0.35))?; - - let mut t: f32 = 0.0; - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_light(graphics, light)?; - - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.06, 0.06, 0.08)), - )?; - - graphics_record_command(graphics, DrawCommand::Fill(bevy::color::Color::WHITE))?; - graphics_record_command(graphics, DrawCommand::Material(pbr))?; +impl Sketch for Primitives3d { + fn settings() -> Settings { + Settings::size(900, 400) + } - let shapes: Vec<(f32, Box DrawCommand>)> = vec![ - ( - -315.0, - Box::new(|_| DrawCommand::Box { - width: 50.0, - height: 50.0, - depth: 50.0, - }), - ), - ( - -225.0, - Box::new(|_| DrawCommand::Sphere { - radius: 30.0, - sectors: 24, - stacks: 16, - }), - ), - ( - -135.0, - Box::new(|_| DrawCommand::Cylinder { - radius: 25.0, - height: 60.0, - detail: 24, - }), - ), - ( - -45.0, - Box::new(|_| DrawCommand::Cone { - radius: 25.0, - height: 60.0, - detail: 24, - }), - ), - ( - 45.0, - Box::new(|_| DrawCommand::Torus { - radius: 30.0, - tube_radius: 10.0, - major_segments: 24, - minor_segments: 16, - }), - ), - ( - 135.0, - Box::new(|_| DrawCommand::Capsule { - radius: 15.0, - length: 40.0, - detail: 24, - }), - ), - ( - 225.0, - Box::new(|_| DrawCommand::ConicalFrustum { - radius_top: 15.0, - radius_bottom: 25.0, - height: 60.0, - detail: 24, - }), - ), - ( - 315.0, - Box::new(|_| DrawCommand::Tetrahedron { radius: 30.0 }), - ), - ]; + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((0, -80, 800)); + g.camera_look_at((0, 0, 0)); + Ok(Primitives3d { t: 0.0 }) + } - for (x_offset, make_cmd) in &shapes { - graphics_record_command(graphics, DrawCommand::PushMatrix)?; - graphics_record_command( - graphics, - DrawCommand::Translate(Vec2::new(*x_offset, 0.0).extend(0.0)), - )?; - graphics_record_command( - graphics, - DrawCommand::Rotate { - angle: -t, - axis: Vec3::Z, - }, - )?; - graphics_record_command(graphics, make_cmd(t))?; - graphics_record_command(graphics, DrawCommand::PopMatrix)?; + fn draw(&mut self, g: &mut Graphics) { + g.background((0.06, 0.06, 0.08)); + g.directional_light((0.9, 0.85, 0.8), 300); + g.fill(255); + g.roughness(0.35); + + for i in 0..8 { + let g = g.push(); + g.translate((-315 + i * 90, 0)); + g.rotate(-self.t); + match i { + 0 => { + g.cube(50); + } + 1 => { + g.sphere(30).detail(24, 16); + } + 2 => { + g.cylinder(25, 60).detail(24); + } + 3 => { + g.cone(25, 60).detail(24); + } + 4 => { + g.torus(30, 10).detail(24, 16); + } + 5 => { + g.capsule(15, 40).detail(24); + } + 6 => { + g.conical_frustum(15, 25, 60).detail(24); + } + _ => { + g.tetrahedron(30); + } + } } - graphics_end_draw(graphics)?; - t += 0.015; + self.t += 0.015; } +} - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/rectangle.rs b/examples/rectangle.rs index 1f75466c..f7db5b28 100644 --- a/examples/rectangle.rs +++ b/examples/rectangle.rs @@ -1,45 +1,21 @@ -use processing_glfw::GlfwContext; - use processing::prelude::*; -use processing_render::render::command::DrawCommand; - -fn main() { - match sketch() { - Ok(_) => { - eprintln!("Sketch completed successfully"); - exit(0).unwrap(); - } - Err(e) => { - eprintln!("Sketch error: {:?}", e); - exit(1).unwrap(); - } - }; -} - -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(400, 400, false)?; - init(Config::default())?; - let width = 400; - let height = 400; - let surface = glfw_ctx.create_surface(width, height, false)?; - let graphics = graphics_create(surface, width, height, TextureFormat::Rgba16Float)?; +struct Rectangle; - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; +impl Sketch for Rectangle { + fn settings() -> Settings { + Settings::size(400, 400) + } - graphics_record_command( - graphics, - DrawCommand::Rect { - x: 10.0, - y: 10.0, - w: 100.0, - h: 100.0, - radii: [0.0, 0.0, 0.0, 0.0], - }, - )?; + fn setup(_g: &mut Graphics) -> Result { + Ok(Rectangle) + } - graphics_end_draw(graphics)?; + fn draw(&mut self, g: &mut Graphics) { + g.rect(10, 10, 100, 100); } - Ok(()) +} + +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/shapes.rs b/examples/shapes.rs index 23820b68..3fc56292 100644 --- a/examples/shapes.rs +++ b/examples/shapes.rs @@ -1,162 +1,74 @@ -use processing_glfw::GlfwContext; -use std::f32::consts::PI; - use processing::prelude::*; -use processing_render::render::command::DrawCommand; -fn main() { - sketch().unwrap(); - exit(0).unwrap(); +struct Shapes { + t: f32, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(600, 600, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(600, 600, false)?; - let graphics = graphics_create(surface, 600, 600, TextureFormat::Rgba16Float)?; - - let mut t: f32 = 0.0; - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; +impl Sketch for Shapes { + fn settings() -> Settings { + Settings::size(600, 600) + } - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.92, 0.90, 0.87)), - )?; + fn setup(_g: &mut Graphics) -> Result { + Ok(Shapes { t: 0.0 }) + } - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgba(0.2, 0.3, 0.5, 0.25)), - )?; - graphics_record_command(graphics, DrawCommand::StrokeWeight(1.5))?; - graphics_record_command( - graphics, - DrawCommand::StrokeColor(bevy::color::Color::srgb(0.15, 0.2, 0.35)), - )?; + fn draw(&mut self, g: &mut Graphics) { + let t = self.t; + g.background((235, 230, 222)); + g.fill((0.2, 0.3, 0.5, 0.25)); + g.stroke_weight(1.5); + g.stroke((38, 51, 89)); let n = 8; - graphics_record_command( - graphics, - DrawCommand::BeginShape { - kind: ShapeKind::Polygon, - }, - )?; - + let blob = g.begin_shape(ShapeKind::Polygon); for i in 0..n + 3 { let idx = (i + n - 1) % n; let angle = idx as f32 * 2.0 * PI / n as f32; let r = 100.0 + 30.0 * (t * 2.0 + idx as f32 * 0.8).sin(); - graphics_record_command( - graphics, - DrawCommand::ShapeCurveVertex { - x: 170.0 + r * angle.cos(), - y: 200.0 + r * angle.sin(), - }, - )?; + blob.curve_vertex(170.0 + r * angle.cos(), 200.0 + r * angle.sin()); } + blob.close(); - graphics_record_command(graphics, DrawCommand::EndShape { close: true })?; - - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgba(0.15, 0.5, 0.3, 0.2)), - )?; - graphics_record_command(graphics, DrawCommand::StrokeWeight(1.0))?; - graphics_record_command( - graphics, - DrawCommand::StrokeColor(bevy::color::Color::srgb(0.1, 0.35, 0.2)), - )?; - - let pcx = 430.0; - let pcy = 200.0; + g.fill((0.15, 0.5, 0.3, 0.2)); + g.stroke_weight(1); + g.stroke((26, 89, 51)); + let cx = 430.0; + let cy = 200.0; let s = 70.0 + 10.0 * (t * 1.5).sin(); - - graphics_record_command( - graphics, - DrawCommand::BeginShape { - kind: ShapeKind::Polygon, - }, - )?; - graphics_record_command(graphics, DrawCommand::ShapeVertex { x: pcx, y: pcy - s })?; - graphics_record_command( - graphics, - DrawCommand::ShapeBezierVertex { - cx1: pcx + s, - cy1: pcy - s, - cx2: pcx + s, - cy2: pcy + s, - x: pcx, - y: pcy + s, - }, - )?; - graphics_record_command( - graphics, - DrawCommand::ShapeBezierVertex { - cx1: pcx - s, - cy1: pcy + s, - cx2: pcx - s, - cy2: pcy - s, - x: pcx, - y: pcy - s, - }, - )?; - graphics_record_command(graphics, DrawCommand::EndShape { close: true })?; - - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgba(0.8, 0.35, 0.1, 0.15)), - )?; - graphics_record_command(graphics, DrawCommand::NoStroke)?; - - graphics_record_command( - graphics, - DrawCommand::BeginShape { - kind: ShapeKind::TriangleFan, - }, - )?; - graphics_record_command(graphics, DrawCommand::ShapeVertex { x: 170.0, y: 450.0 })?; + let lens = g.begin_shape(ShapeKind::Polygon); + lens.vertex(cx, cy - s); + lens.bezier_vertex(cx + s, cy - s, cx + s, cy + s, cx, cy + s); + lens.bezier_vertex(cx - s, cy + s, cx - s, cy - s, cx, cy - s); + lens.close(); + + g.fill((0.8, 0.35, 0.1, 0.15)); + g.no_stroke(); + let fan = g.begin_shape(ShapeKind::TriangleFan); + fan.vertex(170, 450); 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(), - }, - )?; + fan.vertex(170.0 + r * angle.cos(), 450.0 + r * angle.sin()); } - graphics_record_command(graphics, DrawCommand::EndShape { close: true })?; - - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgba(0.5, 0.2, 0.6, 0.2)), - )?; - graphics_record_command(graphics, DrawCommand::StrokeWeight(0.5))?; - graphics_record_command( - graphics, - DrawCommand::StrokeColor(bevy::color::Color::srgba(0.3, 0.1, 0.4, 0.4)), - )?; + fan.close(); - graphics_record_command( - graphics, - DrawCommand::BeginShape { - kind: ShapeKind::TriangleStrip, - }, - )?; + g.fill((0.5, 0.2, 0.6, 0.2)); + g.stroke_weight(0.5); + g.stroke((77, 26, 102, 102)); + let strip = g.begin_shape(ShapeKind::TriangleStrip); 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 })?; + strip.vertex(x, 420.0 + wave); + strip.vertex(x, 480.0 + wave); } - graphics_record_command(graphics, DrawCommand::EndShape { close: false })?; + strip.end(); - graphics_end_draw(graphics)?; - t += 0.02; + self.t += 0.02; } +} - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/stroke_2d.rs b/examples/stroke_2d.rs index 3eafdf54..49ae49d1 100644 --- a/examples/stroke_2d.rs +++ b/examples/stroke_2d.rs @@ -1,66 +1,31 @@ -use processing_glfw::GlfwContext; - use processing::prelude::*; -use processing_render::render::command::DrawCommand; - -fn main() { - sketch().unwrap(); - exit(0).unwrap(); -} - -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(600, 300, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(600, 300, false)?; - let graphics = graphics_create(surface, 600, 300, TextureFormat::Rgba16Float)?; - - let joins = [ - StrokeJoinMode::Round, - StrokeJoinMode::Miter, - StrokeJoinMode::Bevel, - ]; - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; +struct Stroke2d; - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.15, 0.15, 0.2)), - )?; - - graphics_record_command(graphics, DrawCommand::StrokeWeight(12.0))?; +impl Sketch for Stroke2d { + fn settings() -> Settings { + Settings::size(600, 300) + } - for (i, &join) in joins.iter().enumerate() { - let x = 30.0 + i as f32 * 190.0; - let y = 50.0; + fn setup(_g: &mut Graphics) -> Result { + Ok(Stroke2d) + } - graphics_record_command(graphics, DrawCommand::StrokeJoin(join))?; + fn draw(&mut self, g: &mut Graphics) { + g.background((0.15, 0.15, 0.2)); + g.stroke_weight(12); + g.stroke((1.0, 0.9, 0.3)); + let joins = [StrokeJoin::Round, StrokeJoin::Miter, StrokeJoin::Bevel]; + for (i, join) in joins.into_iter().enumerate() { let hue = i as f32 * 0.3; - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgb(0.3 + hue, 0.5, 0.8 - hue)), - )?; - graphics_record_command( - graphics, - DrawCommand::StrokeColor(bevy::color::Color::srgb(1.0, 0.9, 0.3)), - )?; - - graphics_record_command( - graphics, - DrawCommand::Rect { - x, - y, - w: 150.0, - h: 180.0, - radii: [0.0; 4], - }, - )?; + g.stroke_join(join); + g.fill((0.3 + hue, 0.5, 0.8 - hue)); + g.rect(30.0 + i as f32 * 190.0, 50, 150, 180); } - - graphics_end_draw(graphics)?; } +} - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/stroke_3d.rs b/examples/stroke_3d.rs index d2067946..00998327 100644 --- a/examples/stroke_3d.rs +++ b/examples/stroke_3d.rs @@ -1,172 +1,73 @@ -use processing_glfw::GlfwContext; - -use bevy::math::{Vec2, Vec3}; use processing::prelude::*; -use processing_render::render::command::DrawCommand; -fn main() { - sketch().unwrap(); - exit(0).unwrap(); +struct Stroke3d { + angle: f32, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(600, 400, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(600, 400, false)?; - let graphics = graphics_create(surface, 600, 400, TextureFormat::Rgba16Float)?; - - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(200.0, -150.0, 350.0))?; - transform_look_at(graphics, Vec3::new(0.0, 0.0, 0.0))?; - - let light = - light_create_directional(graphics, bevy::color::Color::srgb(0.9, 0.85, 0.8), 800.0)?; - - let mut angle: f32 = 0.0; +impl Sketch for Stroke3d { + fn settings() -> Settings { + Settings::size(600, 400) + } - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_light(graphics, light)?; + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((200, -150, 350)); + g.camera_look_at((0, 0, 0)); + Ok(Stroke3d { angle: 0.0 }) + } - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.08, 0.08, 0.12)), - )?; + fn draw(&mut self, g: &mut Graphics) { + let angle = self.angle; + g.background((0.08, 0.08, 0.12)); + g.directional_light((0.9, 0.85, 0.8), 800); // thin wireframe box - graphics_record_command(graphics, DrawCommand::PushMatrix)?; - graphics_record_command( - graphics, - DrawCommand::Translate(Vec2::new(-80.0, 0.0).extend(0.0)), - )?; - graphics_record_command( - graphics, - DrawCommand::Rotate { - angle: -angle, - axis: Vec3::Z, - }, - )?; - - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgb(0.3, 0.4, 0.7)), - )?; - graphics_record_command( - graphics, - DrawCommand::StrokeColor(bevy::color::Color::srgb(1.0, 1.0, 1.0)), - )?; - graphics_record_command(graphics, DrawCommand::StrokeWeight(1.0))?; - - graphics_record_command( - graphics, - DrawCommand::Box { - width: 60.0, - height: 60.0, - depth: 60.0, - }, - )?; - graphics_record_command(graphics, DrawCommand::PopMatrix)?; + { + let g = g.push(); + g.translate((-80, 0)); + g.rotate(-angle); + g.fill((0.3, 0.4, 0.7)); + g.stroke(255); + g.stroke_weight(1); + g.cube(60); + } // thick wireframe box - graphics_record_command(graphics, DrawCommand::PushMatrix)?; - graphics_record_command(graphics, DrawCommand::Translate(Vec2::ZERO.extend(0.0)))?; - graphics_record_command( - graphics, - DrawCommand::Rotate { - angle: -angle * 0.7, - axis: Vec3::Z, - }, - )?; - - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgb(0.7, 0.3, 0.4)), - )?; - graphics_record_command( - graphics, - DrawCommand::StrokeColor(bevy::color::Color::srgb(1.0, 0.9, 0.2)), - )?; - graphics_record_command(graphics, DrawCommand::StrokeWeight(3.0))?; - - graphics_record_command( - graphics, - DrawCommand::Box { - width: 50.0, - height: 70.0, - depth: 50.0, - }, - )?; - graphics_record_command(graphics, DrawCommand::PopMatrix)?; + { + let g = g.push(); + g.rotate(-angle * 0.7); + g.fill((0.7, 0.3, 0.4)); + g.stroke((1.0, 0.9, 0.2)); + g.stroke_weight(3); + g.cube((50, 70, 50)); + } // thick wireframe sphere - graphics_record_command(graphics, DrawCommand::PushMatrix)?; - graphics_record_command( - graphics, - DrawCommand::Translate(Vec2::new(80.0, 0.0).extend(0.0)), - )?; - graphics_record_command( - graphics, - DrawCommand::Rotate { - angle: -angle * 0.5, - axis: Vec3::Z, - }, - )?; - - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgb(0.3, 0.7, 0.4)), - )?; - graphics_record_command( - graphics, - DrawCommand::StrokeColor(bevy::color::Color::srgb(0.9, 0.4, 1.0)), - )?; - graphics_record_command(graphics, DrawCommand::StrokeWeight(2.0))?; - - graphics_record_command( - graphics, - DrawCommand::Sphere { - radius: 35.0, - sectors: 16, - stacks: 12, - }, - )?; - graphics_record_command(graphics, DrawCommand::PopMatrix)?; - - // wireframe-only sphere (no fill) - graphics_record_command(graphics, DrawCommand::PushMatrix)?; - graphics_record_command( - graphics, - DrawCommand::Translate(Vec2::new(160.0, 0.0).extend(0.0)), - )?; - graphics_record_command( - graphics, - DrawCommand::Rotate { - angle: angle * 0.3, - axis: Vec3::Z, - }, - )?; - - graphics_record_command(graphics, DrawCommand::NoFill)?; - graphics_record_command( - graphics, - DrawCommand::StrokeColor(bevy::color::Color::srgb(0.2, 0.8, 1.0)), - )?; - graphics_record_command(graphics, DrawCommand::StrokeWeight(1.5))?; - - graphics_record_command( - graphics, - DrawCommand::Sphere { - radius: 30.0, - sectors: 24, - stacks: 16, - }, - )?; - graphics_record_command(graphics, DrawCommand::PopMatrix)?; - - graphics_end_draw(graphics)?; - angle += 0.015; + { + let g = g.push(); + g.translate((80, 0)); + g.rotate(-angle * 0.5); + g.fill((0.3, 0.7, 0.4)); + g.stroke((0.9, 0.4, 1.0)); + g.stroke_weight(2); + g.sphere(35).detail(16, 12); + } + + // wireframe-only sphere + { + let g = g.push(); + g.translate((160, 0)); + g.rotate(angle * 0.3); + g.no_fill(); + g.stroke((0.2, 0.8, 1.0)); + g.stroke_weight(1.5); + g.sphere(30).detail(24, 16); + } + + self.angle += 0.015; } +} - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/text.rs b/examples/text.rs index 956a56de..61b04293 100644 --- a/examples/text.rs +++ b/examples/text.rs @@ -1,100 +1,41 @@ -use bevy::prelude::Color; -use processing_glfw::GlfwContext; - use processing::prelude::*; -use processing_render::render::command::DrawCommand; - -fn main() { - match sketch() { - Ok(_) => { - eprintln!("Sketch completed successfully"); - exit(0).unwrap(); - } - Err(e) => { - eprintln!("Sketch error: {:?}", e); - exit(1).unwrap(); - } - }; -} - -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(600, 400, false)?; - init(Config::default())?; - - let width = 600; - let height = 400; - let surface = glfw_ctx.create_surface(width, height, false)?; - let graphics = graphics_create(surface, width, height, TextureFormat::Rgba16Float)?; - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_record_command(graphics, DrawCommand::BackgroundColor(Color::WHITE))?; - graphics_record_command(graphics, DrawCommand::Fill(Color::BLACK))?; - graphics_record_command(graphics, DrawCommand::TextSize(32.0))?; +struct Text; - graphics_record_command( - graphics, - DrawCommand::Text { - content: "Hello, Processing!".to_string(), - x: 50.0, - y: 100.0, - z: 0.0, - max_w: None, - max_h: None, - }, - )?; - - graphics_record_command(graphics, DrawCommand::TextSize(18.0))?; +impl Sketch for Text { + fn settings() -> Settings { + Settings::size(600, 400) + } - graphics_record_command( - graphics, - DrawCommand::Text { - content: "Text rendering with parley + skrifa + lyon".to_string(), - x: 50.0, - y: 160.0, - z: 0.0, - max_w: None, - max_h: None, - }, - )?; + fn setup(_g: &mut Graphics) -> Result { + Ok(Text) + } - graphics_record_command(graphics, DrawCommand::TextSize(16.0))?; + fn draw(&mut self, g: &mut Graphics) { + g.background(255); + g.fill(0); - graphics_record_command( - graphics, - DrawCommand::Text { - content: "This is a longer paragraph of text that should wrap within its bounding box. The text uses parley for layout, skrifa for glyph outlines, and lyon for tessellation.".to_string(), - x: 50.0, - y: 220.0, - z: 0.0, - max_w: Some(300.0), - max_h: Some(200.0), - }, - )?; + g.text_size(32); + g.text("Hello, Processing!", 50, 100); - graphics_record_command( - graphics, - DrawCommand::TextAlign { - h: TextAlignH::Center, - v: TextAlignV::Top, - }, - )?; - graphics_record_command(graphics, DrawCommand::TextSize(24.0))?; + g.text_size(18); + g.text("Text rendering with parley + skrifa + lyon", 50, 160); - graphics_record_command( - graphics, - DrawCommand::Text { - content: "Centered".to_string(), - x: 450.0, - y: 100.0, - z: 0.0, - max_w: Some(200.0), - max_h: None, - }, - )?; + g.text_size(16); + g.text( + "This is a longer paragraph of text that should wrap within its bounding box. \ + The text uses parley for layout, skrifa for glyph outlines, and lyon for tessellation.", + 50, + 220, + ) + .bounds(300, 200); - graphics_end_draw(graphics)?; + g.text_align((TextAlignH::Center, TextAlignV::Top)); + g.text_size(24); + g.text("Centered", 450, 100).max_width(200); } - Ok(()) +} + +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/text_3d.rs b/examples/text_3d.rs index 99abe875..24fdff4c 100644 --- a/examples/text_3d.rs +++ b/examples/text_3d.rs @@ -1,86 +1,60 @@ -use processing_glfw::GlfwContext; - -use bevy::math::{Vec2, Vec3}; use processing::prelude::*; -use processing_render::render::command::DrawCommand; -fn main() { - sketch().unwrap(); - exit(0).unwrap(); +struct Text3d { + word: Geometry, + glow: Material, + sun: Light, + t: f32, } -fn sketch() -> error::Result<()> { - let width = 1200; - let height = 700; - let mut glfw_ctx = GlfwContext::new(width, height, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(width, height, false)?; - let graphics = graphics_create(surface, width, height, TextureFormat::Rgba16Float)?; - - graphics_mode_3d(graphics)?; - transform_set_position(graphics, Vec3::new(0.0, 0.0, 800.0))?; - transform_look_at(graphics, Vec3::new(0.0, 0.0, 0.0))?; - - let dir_light = - light_create_directional(graphics, bevy::color::Color::srgb(0.3, 0.3, 0.4), 2000.0)?; - transform_set_position(dir_light, Vec3::new(200.0, -300.0, 500.0))?; - transform_look_at(dir_light, Vec3::new(0.0, 0.0, 0.0))?; - - let glow = material_create_pbr()?; - material_set(glow, "roughness", shader_value::ShaderValue::Float(0.3))?; - material_set(glow, "metallic", shader_value::ShaderValue::Float(0.5))?; - material_set( - glow, - "emissive", - shader_value::ShaderValue::Float4([2.0, 0.5, 3.0, 1.0]), - )?; - - graphics_record_command(graphics, DrawCommand::TextSize(120.0))?; - graphics_record_command(graphics, DrawCommand::TextStyle(TextStyle::Bold))?; - - // measure width to center the mesh on the origin - let w = graphics_text_width(graphics, "Processing")?; - let mesh = graphics_text_to_model(graphics, "Processing", -w / 2.0, 0.0, 40.0)?; - let geom = geometry_create_from_mesh(mesh)?; - - let mut t: f32 = 0.0; - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; - graphics_light(graphics, dir_light)?; +impl Sketch for Text3d { + fn settings() -> Settings { + Settings::size(1200, 700) + } - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.02, 0.02, 0.03)), - )?; + fn setup(g: &mut Graphics) -> Result { + g.mode_3d(); + g.camera_position((0, 0, 800)); + g.camera_look_at((0, 0, 0)); + + let sun = g.create_directional_light((0.3, 0.3, 0.4), 2000); + sun.position((200, -300, 500)).look_at((0, 0, 0)); + + let mut glow = Material::pbr()?; + glow.set("roughness", 0.3); + glow.set("metallic", 0.5); + glow.set("emissive", (2.0, 0.5, 3.0, 1.0)); + + g.text_size(120); + g.text_style(TextStyle::Bold); + let w = g.text_width("Processing"); + let word = g.text_to_model("Processing", -w / 2.0, 0, 40)?; + + Ok(Text3d { + word, + glow, + sun, + t: 0.0, + }) + } - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgb(0.8, 0.3, 1.0)), - )?; - graphics_record_command(graphics, DrawCommand::Material(glow))?; + fn draw(&mut self, g: &mut Graphics) { + g.light(&self.sun); + g.background((0.02, 0.02, 0.03)); + g.fill((0.8, 0.3, 1.0)); + g.material(&self.glow); - graphics_record_command(graphics, DrawCommand::PushMatrix)?; - graphics_record_command( - graphics, - DrawCommand::Scale(Vec2::new(15.0, 15.0).extend(1.0)), - )?; - graphics_record_command( - graphics, - DrawCommand::Rotate { - angle: -t * 0.3, - axis: Vec3::Z, - }, - )?; - graphics_record_command(graphics, DrawCommand::Geometry(geom))?; - graphics_record_command(graphics, DrawCommand::PopMatrix)?; + { + let g = g.push(); + g.scale((1.5, 1.5)); + g.rotate(-self.t * 0.3); + g.model(&self.word); + } - graphics_end_draw(graphics)?; - t += 0.016; + self.t += 0.016; } +} - material_destroy(glow)?; - - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/transforms.rs b/examples/transforms.rs index 87fb34af..766b7d22 100644 --- a/examples/transforms.rs +++ b/examples/transforms.rs @@ -1,80 +1,36 @@ -use processing_glfw::GlfwContext; - -use bevy::math::{Vec2, Vec3}; use processing::prelude::*; -use processing_render::render::command::DrawCommand; -use std::f32::consts::PI; -fn main() { - sketch().unwrap(); - exit(0).unwrap(); +struct Transforms { + t: f32, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(400, 400, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(400, 400, false)?; - let graphics = graphics_create(surface, 400, 400, TextureFormat::Rgba16Float)?; - - let mut t: f32 = 0.0; +impl Sketch for Transforms { + fn settings() -> Settings { + Settings::size(400, 400) + } - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; + fn setup(_g: &mut Graphics) -> Result { + Ok(Transforms { t: 0.0 }) + } - graphics_record_command( - graphics, - DrawCommand::BackgroundColor(bevy::color::Color::srgb(0.1, 0.1, 0.1)), - )?; + fn draw(&mut self, g: &mut Graphics) { + g.background(25); for i in 0..4 { for j in 0..4 { - graphics_record_command(graphics, DrawCommand::PushMatrix)?; - - graphics_record_command( - graphics, - DrawCommand::Translate( - Vec2::new(50.0 + j as f32 * 100.0, 50.0 + i as f32 * 100.0).extend(0.0), - ), - )?; - - let angle = t + (i + j) as f32 * PI / 8.0; - graphics_record_command( - graphics, - DrawCommand::Rotate { - angle, - axis: Vec3::Z, - }, - )?; - - let s = 0.8 + (t * 2.0 + (i * j) as f32).sin() * 0.2; - graphics_record_command(graphics, DrawCommand::Scale(Vec2::splat(s).extend(1.0)))?; - - let r = j as f32 / 3.0; - let g = i as f32 / 3.0; - graphics_record_command( - graphics, - DrawCommand::Fill(bevy::color::Color::srgb(r, g, 0.8)), - )?; - - graphics_record_command( - graphics, - DrawCommand::Rect { - x: -20.0, - y: -20.0, - w: 40.0, - h: 40.0, - radii: [0.0; 4], - }, - )?; - - graphics_record_command(graphics, DrawCommand::PopMatrix)?; + let g = g.push(); + g.translate((50 + j * 100, 50 + i * 100)); + g.rotate(self.t + (i + j) as f32 * PI / 8.0); + g.scale(0.8 + (self.t * 2.0 + (i * j) as f32).sin() * 0.2); + g.fill((j as f32 / 3.0, i as f32 / 3.0, 0.8)); + g.rect(-20, -20, 40, 40); } } - graphics_end_draw(graphics)?; - t += 0.02; + self.t += 0.02; } +} - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/update_pixels.rs b/examples/update_pixels.rs index 9d8218d7..9cb726f3 100644 --- a/examples/update_pixels.rs +++ b/examples/update_pixels.rs @@ -1,82 +1,60 @@ -use processing_glfw::GlfwContext; - -use bevy::{color::Color, prelude::LinearRgba}; use processing::prelude::*; -fn main() { - match sketch() { - Ok(_) => { - eprintln!("Sketch completed successfully"); - exit(0).unwrap(); - } - Err(e) => { - eprintln!("Sketch error: {:?}", e); - exit(1).unwrap(); - } - }; +struct UpdatePixels { + first_frame: bool, } -fn sketch() -> error::Result<()> { - let mut glfw_ctx = GlfwContext::new(100, 100, false)?; - init(Config::default())?; - - let width = 100; - let height = 100; - let surface = glfw_ctx.create_surface(width, height, false)?; - let graphics = graphics_create(surface, width, height, TextureFormat::Rgba16Float)?; - - let rect_w = 10; - let rect_h = 10; - let red = LinearRgba::new(1.0, 0.0, 0.0, 1.0); - let red_pixels: Vec = vec![red; rect_w * rect_h]; - - let blue = LinearRgba::new(0.0, 0.0, 1.0, 1.0); - let blue_pixels: Vec = vec![blue; rect_w * rect_h]; - - let mut first_frame = true; - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; +impl Sketch for UpdatePixels { + fn settings() -> Settings { + Settings::size(100, 100) + } - graphics_record_command(graphics, DrawCommand::BackgroundColor(Color::BLACK))?; - graphics_flush(graphics)?; - graphics_update_region(graphics, 20, 20, rect_w as u32, rect_h as u32, &red_pixels)?; - graphics_update_region(graphics, 60, 60, rect_w as u32, rect_h as u32, &blue_pixels)?; + fn setup(_g: &mut Graphics) -> Result { + Ok(UpdatePixels { first_frame: true }) + } - graphics_end_draw(graphics)?; + fn draw(&mut self, g: &mut Graphics) { + g.background(0); - if first_frame { - first_frame = false; + let red = vec![Color::rgb(1.0, 0.0, 0.0); 10 * 10]; + let blue = vec![Color::rgb(0.0, 0.0, 1.0); 10 * 10]; + g.set_pixels_region(20, 20, 10, 10, &red).unwrap(); + g.set_pixels_region(60, 60, 10, 10, &blue).unwrap(); - let pixels = graphics_readback(graphics)?; - eprintln!("Total pixels: {}", pixels.len()); + if self.first_frame { + self.first_frame = false; + print_pixels(g); + } + } +} - for y in 0..height { - for x in 0..width { - let idx = (y * width + x) as usize; - if idx < pixels.len() { - let pixel = pixels[idx]; - if pixel.red > 0.5 { - eprint!("R"); - } else if pixel.blue > 0.5 { - eprint!("B"); - } else if pixel.alpha > 0.5 { - eprint!("."); - } else { - eprint!(" "); - } - } - } - eprintln!(); +fn print_pixels(g: &mut Graphics) { + let pixels = g.pixels().unwrap(); + let width = g.pixel_width() as usize; + eprintln!("Total pixels: {}", pixels.len()); + + for row in pixels.chunks(width) { + for pixel in row { + if pixel.red() > 0.5 { + eprint!("R"); + } else if pixel.blue() > 0.5 { + eprint!("B"); + } else if pixel.alpha() > 0.5 { + eprint!("."); + } else { + eprint!(" "); } - - eprintln!("\nSample pixels:"); - eprintln!("(25, 25): {:?}", pixels[25 * width as usize + 25]); - eprintln!("(65, 65): {:?}", pixels[65 * width as usize + 65]); - eprintln!("(0, 0): {:?}", pixels[0]); - eprintln!("(50, 50): {:?}", pixels[50 * width as usize + 50]); } + eprintln!(); } - Ok(()) + eprintln!("\nSample pixels:"); + eprintln!("(25, 25): {:?}", pixels[25 * width + 25]); + eprintln!("(65, 65): {:?}", pixels[65 * width + 65]); + eprintln!("(0, 0): {:?}", pixels[0]); + eprintln!("(50, 50): {:?}", pixels[50 * width + 50]); +} + +fn main() -> Result<()> { + processing::run::() } diff --git a/examples/webcam.rs b/examples/webcam.rs index d2609d75..ad6ce100 100644 --- a/examples/webcam.rs +++ b/examples/webcam.rs @@ -1,50 +1,26 @@ -use processing_glfw::GlfwContext; - use processing::prelude::*; -use processing_render::render::command::DrawCommand; -use processing_webcam::{webcam_create, webcam_destroy, webcam_image, webcam_is_connected}; -fn main() { - match sketch() { - Ok(_) => { - eprintln!("Sketch completed successfully"); - exit(0).unwrap(); - } - Err(e) => { - eprintln!("Sketch error: {:?}", e); - exit(1).unwrap(); - } - }; +struct WebcamSketch { + camera: Webcam, } -fn sketch() -> error::Result<()> { - let width = 640; - let height = 480; - - let mut glfw_ctx = GlfwContext::new(width, height, false)?; - init(Config::default())?; - - let surface = glfw_ctx.create_surface(width, height, false)?; - let graphics = graphics_create(surface, width, height, TextureFormat::Rgba16Float)?; - - let webcam = webcam_create()?; - let mut image_entity = None; - - while glfw_ctx.poll_events() { - graphics_begin_draw(graphics)?; +impl Sketch for WebcamSketch { + fn settings() -> Settings { + Settings::size(640, 480) + } - // Once connected, grab an image entity from the webcam stream - if image_entity.is_none() && webcam_is_connected(webcam)? { - image_entity = Some(webcam_image(webcam)?); - } + fn setup(_g: &mut Graphics) -> Result { + let camera = Webcam::new()?; + Ok(WebcamSketch { camera }) + } - if let Some(img) = image_entity { - graphics_record_command(graphics, DrawCommand::BackgroundImage(img))?; + fn draw(&mut self, g: &mut Graphics) { + if self.camera.connected() { + g.background_image(&self.camera); } - - graphics_end_draw(graphics)?; } +} - webcam_destroy(webcam)?; - Ok(()) +fn main() -> Result<()> { + processing::run::() } diff --git a/src/args.rs b/src/args.rs new file mode 100644 index 00000000..280bd302 --- /dev/null +++ b/src/args.rs @@ -0,0 +1,86 @@ +use bevy::math::{Vec2, Vec3}; + +mod sealed { + pub trait Sealed {} +} + +pub trait Scalar: sealed::Sealed + Copy { + fn to_f32(self) -> f32; +} + +macro_rules! scalar { + ($($t:ty),*) => {$( + impl sealed::Sealed for $t {} + impl Scalar for $t { + #[inline] + fn to_f32(self) -> f32 { + self as f32 + } + } + )*}; +} +scalar!(u8, u16, u32, u64, usize, i8, i16, i32, i64, isize, f32, f64); + +/// `(x, y)`, `(x, y, z)`, `Vec2` or `Vec3`. +pub trait IntoPoint { + fn into_point(self) -> Vec3; +} + +impl IntoPoint for (A, B) { + fn into_point(self) -> Vec3 { + Vec3::new(self.0.to_f32(), self.1.to_f32(), 0.0) + } +} + +impl IntoPoint for (A, B, C) { + fn into_point(self) -> Vec3 { + Vec3::new(self.0.to_f32(), self.1.to_f32(), self.2.to_f32()) + } +} + +impl IntoPoint for Vec2 { + fn into_point(self) -> Vec3 { + self.extend(0.0) + } +} + +impl IntoPoint for Vec3 { + fn into_point(self) -> Vec3 { + self + } +} + +/// One number, `(x, y)` or `(x, y, z)`. +pub trait IntoExtent { + fn into_extent(self) -> Vec3; +} + +impl IntoExtent for T { + fn into_extent(self) -> Vec3 { + Vec3::splat(self.to_f32()) + } +} + +impl IntoExtent for (A, B) { + fn into_extent(self) -> Vec3 { + Vec3::new(self.0.to_f32(), self.1.to_f32(), 1.0) + } +} + +impl IntoExtent for (A, B, C) { + fn into_extent(self) -> Vec3 { + Vec3::new(self.0.to_f32(), self.1.to_f32(), self.2.to_f32()) + } +} + +impl IntoExtent for Vec2 { + fn into_extent(self) -> Vec3 { + self.extend(1.0) + } +} + +impl IntoExtent for Vec3 { + fn into_extent(self) -> Vec3 { + self + } +} diff --git a/src/color.rs b/src/color.rs new file mode 100644 index 00000000..b88a2588 --- /dev/null +++ b/src/color.rs @@ -0,0 +1,297 @@ +use bevy::color::{Alpha, Color as BevyColor, Hsla, Hsva, LinearRgba, Mix, Oklcha, Srgba}; +use processing_render::color::ColorMode; + +pub use processing_render::color::ColorSpace; + +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Color(pub(crate) BevyColor); + +impl Color { + pub const BLACK: Color = Color::rgb(0.0, 0.0, 0.0); + pub const WHITE: Color = Color::rgb(1.0, 1.0, 1.0); + pub const TRANSPARENT: Color = Color::rgba(0.0, 0.0, 0.0, 0.0); + + /// 0-1. + pub const fn rgb(r: f32, g: f32, b: f32) -> Self { + Self::rgba(r, g, b, 1.0) + } + + /// 0-1. + pub const fn rgba(r: f32, g: f32, b: f32, a: f32) -> Self { + Self(BevyColor::Srgba(Srgba::new(r, g, b, a))) + } + + /// 0-255. + pub const fn rgb8(r: u8, g: u8, b: u8) -> Self { + Self::rgba8(r, g, b, 255) + } + + /// 0-255. + pub const fn rgba8(r: u8, g: u8, b: u8, a: u8) -> Self { + Self::rgba( + r as f32 / 255.0, + g as f32 / 255.0, + b as f32 / 255.0, + a as f32 / 255.0, + ) + } + + /// `0xRRGGBB`. + pub const fn hex(rgb: u32) -> Self { + Self::rgb8((rgb >> 16) as u8, (rgb >> 8) as u8, rgb as u8) + } + + /// `0xRRGGBBAA`. + pub const fn hexa(rgba: u32) -> Self { + Self::rgba8( + (rgba >> 24) as u8, + (rgba >> 16) as u8, + (rgba >> 8) as u8, + rgba as u8, + ) + } + + /// Hue in degrees, the rest 0-1. + pub const fn hsl(h: f32, s: f32, l: f32) -> Self { + Self(BevyColor::Hsla(Hsla::new(h, s, l, 1.0))) + } + + /// Hue in degrees, the rest 0-1. + pub const fn hsv(h: f32, s: f32, v: f32) -> Self { + Self(BevyColor::Hsva(Hsva::new(h, s, v, 1.0))) + } + + /// Hue in degrees, chroma 0-~0.4. + pub const fn oklch(l: f32, c: f32, h: f32) -> Self { + Self(BevyColor::Oklcha(Oklcha::new(l, c, h, 1.0))) + } + + pub fn with_alpha(self, alpha: f32) -> Self { + let mut c = self.0; + c.set_alpha(alpha); + Self(c) + } + + /// In Oklab. + pub fn lerp(self, other: Color, t: f32) -> Self { + let a: bevy::color::Oklaba = self.0.into(); + let b: bevy::color::Oklaba = other.0.into(); + Self(a.mix(&b, t).into()) + } + + pub fn red(self) -> f32 { + self.0.to_srgba().red + } + + pub fn green(self) -> f32 { + self.0.to_srgba().green + } + + pub fn blue(self) -> f32 { + self.0.to_srgba().blue + } + + pub fn alpha(self) -> f32 { + self.0.alpha() + } + + pub(crate) fn from_linear(c: LinearRgba) -> Self { + Self(BevyColor::LinearRgba(c)) + } + + pub(crate) fn to_linear(self) -> LinearRgba { + self.0.to_linear() + } +} + +#[derive(Debug, Clone, Copy)] +pub enum Channel { + Int(i64), + Float(f32), +} + +/// Ints 0-255, floats 0-1, unless `color_mode().max(..)` is set. +pub trait IntoChannel: Copy { + fn into_channel(self) -> Channel; +} + +macro_rules! int_channel { + ($($t:ty),*) => {$( + impl IntoChannel for $t { + fn into_channel(self) -> Channel { + Channel::Int(self as i64) + } + } + )*}; +} +int_channel!(u8, u16, u32, u64, usize, i8, i16, i32, i64, isize); + +impl IntoChannel for f32 { + fn into_channel(self) -> Channel { + Channel::Float(self) + } +} + +impl IntoChannel for f64 { + fn into_channel(self) -> Channel { + Channel::Float(self as f32) + } +} + +#[derive(Debug, Clone, Copy)] +pub enum ColorArg { + Color(Color), + Gray(Channel, Option), + Channels([Channel; 3], Option), +} + +impl From for ColorArg { + fn from(c: Color) -> Self { + Self::Color(c) + } +} + +impl From for ColorArg { + fn from(v: A) -> Self { + Self::Gray(v.into_channel(), None) + } +} + +impl From<(A, B)> for ColorArg { + fn from((v, a): (A, B)) -> Self { + Self::Gray(v.into_channel(), Some(a.into_channel())) + } +} + +impl From<(A, B, C)> for ColorArg { + fn from((c1, c2, c3): (A, B, C)) -> Self { + Self::Channels( + [c1.into_channel(), c2.into_channel(), c3.into_channel()], + None, + ) + } +} + +impl From<(A, B, C, D)> + for ColorArg +{ + fn from((c1, c2, c3, a): (A, B, C, D)) -> Self { + Self::Channels( + [c1.into_channel(), c2.into_channel(), c3.into_channel()], + Some(a.into_channel()), + ) + } +} + +pub trait IntoColorMax { + fn into_color_max(self, space: ColorSpace) -> [f32; 4]; +} + +impl IntoColorMax for T { + fn into_color_max(self, _space: ColorSpace) -> [f32; 4] { + [self.to_f32(); 4] + } +} + +impl IntoColorMax for (A, B, C) { + fn into_color_max(self, space: ColorSpace) -> [f32; 4] { + [ + self.0.to_f32(), + self.1.to_f32(), + self.2.to_f32(), + space.default_maxes()[3], + ] + } +} + +impl IntoColorMax + for (A, B, C, D) +{ + fn into_color_max(self, _space: ColorSpace) -> [f32; 4] { + [ + self.0.to_f32(), + self.1.to_f32(), + self.2.to_f32(), + self.3.to_f32(), + ] + } +} + +#[derive(Debug, Clone, Copy, Default)] +pub(crate) struct ColorState { + pub mode: ColorMode, + pub explicit_max: bool, +} + +fn int_maxes(space: ColorSpace) -> [f32; 4] { + match space { + ColorSpace::Srgb | ColorSpace::Linear => [255.0, 255.0, 255.0, 255.0], + ColorSpace::Hsl | ColorSpace::Hsv | ColorSpace::Hwb => [360.0, 100.0, 100.0, 255.0], + ColorSpace::Oklch | ColorSpace::Lch => [100.0, 100.0, 360.0, 255.0], + ColorSpace::Oklab | ColorSpace::Lab | ColorSpace::Xyz => [100.0, 100.0, 100.0, 255.0], + } +} + +impl ColorState { + fn channel(&self, c: Channel, i: usize) -> f32 { + let space = self.mode.space; + let native = space.default_maxes()[i]; + match c { + Channel::Int(v) if self.explicit_max => v as f32 / self.mode.max[i] * native, + Channel::Float(v) if self.explicit_max => v / self.mode.max[i] * native, + Channel::Int(v) => v as f32 / int_maxes(space)[i] * native, + Channel::Float(v) => v, + } + } + + pub fn resolve(&self, arg: ColorArg) -> Color { + let space = self.mode.space; + let alpha = |a: Option| match a { + Some(a) => self.channel(a, 3), + None => space.default_maxes()[3], + }; + match arg { + ColorArg::Color(c) => c, + ColorArg::Gray(v, a) => Color(space.gray(self.channel(v, 0), alpha(a))), + ColorArg::Channels([c1, c2, c3], a) => Color(space.color( + self.channel(c1, 0), + self.channel(c2, 1), + self.channel(c3, 2), + alpha(a), + )), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn srgba(state: &ColorState, arg: impl Into) -> [f32; 4] { + let s = state.resolve(arg.into()).0.to_srgba(); + [s.red, s.green, s.blue, s.alpha] + } + + #[test] + fn ints_are_255_floats_are_unit() { + let st = ColorState::default(); + assert_eq!(srgba(&st, 255), [1.0, 1.0, 1.0, 1.0]); + assert_eq!(srgba(&st, 0.5), [0.5, 0.5, 0.5, 1.0]); + assert_eq!(srgba(&st, (255, 0, 0, 0.5)), [1.0, 0.0, 0.0, 0.5]); + } + + #[test] + fn explicit_max_governs_ints_and_floats() { + let st = ColorState { + mode: ColorMode::with_uniform_max(ColorSpace::Srgb, 100.0), + explicit_max: true, + }; + assert_eq!(srgba(&st, (50, 100.0, 0)), [0.5, 1.0, 0.0, 1.0]); + } + + #[test] + fn hex_round_trip() { + let c = Color::hex(0xFF8000).0.to_srgba(); + assert_eq!([c.red, c.green, c.blue], [1.0, 128.0 / 255.0, 0.0]); + } +} diff --git a/src/draw.rs b/src/draw.rs new file mode 100644 index 00000000..c7b08b3f --- /dev/null +++ b/src/draw.rs @@ -0,0 +1,366 @@ +use std::marker::PhantomData; +use std::ops::{Deref, DerefMut}; + +use bevy::prelude::{Entity, Transform}; +use processing_render::geometry::Topology; +use processing_render::render::command::{ArcMode, CommandSlot, DrawCommand, LightKind}; +use processing_render::{graphics_immediate_light, transform_look_at, transform_set_position}; + +use crate::graphics::expect; +use crate::{Geometry, Graphics, IntoPoint, Scalar}; + +pub struct Rect<'g> { + g: &'g Graphics, + slot: CommandSlot, +} + +impl<'g> Rect<'g> { + pub(crate) fn new(g: &'g Graphics, x: f32, y: f32, w: f32, h: f32) -> Self { + let slot = g.record_slot(DrawCommand::Rect { + x, + y, + w, + h, + radii: [0.0; 4], + }); + Self { g, slot } + } + + pub fn radius(self, r: impl Scalar) -> Self { + self.set_radii([r.to_f32(); 4]) + } + + /// Top-left, top-right, bottom-right, bottom-left. + pub fn radii(self, tl: impl Scalar, tr: impl Scalar, br: impl Scalar, bl: impl Scalar) -> Self { + self.set_radii([tl.to_f32(), tr.to_f32(), br.to_f32(), bl.to_f32()]) + } + + fn set_radii(self, value: [f32; 4]) -> Self { + self.g.amend(self.slot, |cmd| { + let DrawCommand::Rect { radii, .. } = cmd else { + unreachable!() + }; + *radii = value; + }); + self + } +} + +pub struct Arc<'g> { + g: &'g Graphics, + slot: CommandSlot, +} + +impl<'g> Arc<'g> { + pub(crate) fn new(g: &'g Graphics, bounds: [f32; 4], start: f32, stop: f32) -> Self { + let [cx, cy, w, h] = bounds; + let slot = g.record_slot(DrawCommand::Arc { + cx, + cy, + w, + h, + start, + stop, + mode: ArcMode::default(), + }); + Self { g, slot } + } + + pub fn mode(self, value: ArcMode) -> Self { + self.g.amend(self.slot, |cmd| { + let DrawCommand::Arc { mode, .. } = cmd else { + unreachable!() + }; + *mode = value; + }); + self + } +} + +pub struct LightDraw<'g> { + light: Entity, + _g: PhantomData<&'g Graphics>, +} + +impl<'g> LightDraw<'g> { + pub(crate) fn new(g: &'g Graphics, kind: LightKind) -> Self { + let light = expect(graphics_immediate_light( + g.entity, + kind, + Transform::default(), + )); + Self { + light, + _g: PhantomData, + } + } + + pub fn position(self, position: impl IntoPoint) -> Self { + expect(transform_set_position(self.light, position.into_point())); + self + } + + pub fn look_at(self, target: impl IntoPoint) -> Self { + expect(transform_look_at(self.light, target.into_point())); + self + } +} + +pub struct ParticlesDraw<'g> { + g: &'g Graphics, + slot: CommandSlot, +} + +impl<'g> ParticlesDraw<'g> { + pub(crate) fn new(g: &'g Graphics, particles: Entity) -> Self { + let slot = g.record_slot(DrawCommand::Particles { + particles, + geometry: None, + topology: Topology::PointList, + }); + Self { g, slot } + } + + pub fn geometry(self, value: &Geometry) -> Self { + self.g.amend(self.slot, |cmd| { + let DrawCommand::Particles { geometry, .. } = cmd else { + unreachable!() + }; + *geometry = Some(value.0); + }); + self + } + + pub fn topology(self, value: Topology) -> Self { + self.g.amend(self.slot, |cmd| { + let DrawCommand::Particles { topology, .. } = cmd else { + unreachable!() + }; + *topology = value; + }); + self + } +} + +pub struct ImageDraw<'g> { + g: &'g Graphics, + slot: CommandSlot, +} + +impl<'g> ImageDraw<'g> { + pub(crate) fn new(g: &'g Graphics, entity: Entity, x: f32, y: f32) -> Self { + let slot = g.record_slot(DrawCommand::Image { + entity, + dx: x, + dy: y, + d_width: None, + d_height: None, + sx: None, + sy: None, + s_width: None, + s_height: None, + }); + Self { g, slot } + } + + pub fn size(self, w: impl Scalar, h: impl Scalar) -> Self { + let (w, h) = (w.to_f32(), h.to_f32()); + self.g.amend(self.slot, |cmd| { + let DrawCommand::Image { + d_width, d_height, .. + } = cmd + else { + unreachable!() + }; + *d_width = Some(w); + *d_height = Some(h); + }); + self + } + + /// Pixel region of the image. + pub fn source(self, x: impl Scalar, y: impl Scalar, w: impl Scalar, h: impl Scalar) -> Self { + let (x, y, w, h) = (x.to_f32(), y.to_f32(), w.to_f32(), h.to_f32()); + self.g.amend(self.slot, |cmd| { + let DrawCommand::Image { + sx, + sy, + s_width, + s_height, + .. + } = cmd + else { + unreachable!() + }; + *sx = Some(x); + *sy = Some(y); + *s_width = Some(w); + *s_height = Some(h); + }); + self + } +} + +pub struct Text<'g> { + g: &'g Graphics, + slot: CommandSlot, +} + +impl<'g> Text<'g> { + pub(crate) fn new(g: &'g Graphics, content: String, x: f32, y: f32) -> Self { + let slot = g.record_slot(DrawCommand::Text { + content, + x, + y, + z: 0.0, + max_w: None, + max_h: None, + }); + Self { g, slot } + } + + pub fn z(self, value: impl Scalar) -> Self { + let value = value.to_f32(); + self.g.amend(self.slot, |cmd| { + let DrawCommand::Text { z, .. } = cmd else { + unreachable!() + }; + *z = value; + }); + self + } + + pub fn max_width(self, w: impl Scalar) -> Self { + let w = w.to_f32(); + self.g.amend(self.slot, |cmd| { + let DrawCommand::Text { max_w, .. } = cmd else { + unreachable!() + }; + *max_w = Some(w); + }); + self + } + + pub fn bounds(self, w: impl Scalar, h: impl Scalar) -> Self { + let (w, h) = (w.to_f32(), h.to_f32()); + self.g.amend(self.slot, |cmd| { + let DrawCommand::Text { max_w, max_h, .. } = cmd else { + unreachable!() + }; + *max_w = Some(w); + *max_h = Some(h); + }); + self + } +} + +pub struct Detail<'g, const N: usize> { + g: &'g Graphics, + slot: CommandSlot, + size: [f32; 3], + build: fn([f32; 3], [u32; N]) -> DrawCommand, +} + +impl<'g, const N: usize> Detail<'g, N> { + pub(crate) fn new( + g: &'g Graphics, + size: [f32; 3], + detail: [u32; N], + build: fn([f32; 3], [u32; N]) -> DrawCommand, + ) -> Self { + let slot = g.record_slot(build(size, detail)); + Self { + g, + slot, + size, + build, + } + } + + fn set_detail(self, detail: [u32; N]) -> Self { + let rebuilt = (self.build)(self.size, detail); + self.g.amend(self.slot, |cmd| *cmd = rebuilt); + self + } +} + +impl Detail<'_, 1> { + pub fn detail(self, segments: u32) -> Self { + self.set_detail([segments]) + } +} + +impl Detail<'_, 2> { + pub fn detail(self, a: u32, b: u32) -> Self { + self.set_detail([a, b]) + } +} + +/// Pops when dropped. +#[must_use] +pub struct Push<'g> { + g: &'g mut Graphics, +} + +impl<'g> Push<'g> { + pub(crate) fn new(g: &'g mut Graphics) -> Self { + Self { g } + } + + pub fn pop(self) {} +} + +impl Deref for Push<'_> { + type Target = Graphics; + + fn deref(&self) -> &Graphics { + self.g + } +} + +impl DerefMut for Push<'_> { + fn deref_mut(&mut self) -> &mut Graphics { + self.g + } +} + +impl Drop for Push<'_> { + fn drop(&mut self) { + self.g.pop_matrix(); + self.g.pop_style(); + } +} + +/// Ends drawing when dropped. +#[must_use] +pub struct BeginDraw<'g> { + g: &'g mut Graphics, +} + +impl<'g> BeginDraw<'g> { + pub(crate) fn new(g: &'g mut Graphics) -> Self { + Self { g } + } + + pub fn end_draw(self) {} +} + +impl Deref for BeginDraw<'_> { + type Target = Graphics; + + fn deref(&self) -> &Graphics { + self.g + } +} + +impl DerefMut for BeginDraw<'_> { + fn deref_mut(&mut self) -> &mut Graphics { + self.g + } +} + +impl Drop for BeginDraw<'_> { + fn drop(&mut self) { + self.g.end_frame(); + } +} diff --git a/src/engine.rs b/src/engine.rs new file mode 100644 index 00000000..cf6287f8 --- /dev/null +++ b/src/engine.rs @@ -0,0 +1,21 @@ +pub use bevy::input::keyboard::KeyCode; +pub use bevy::input::mouse::MouseButton; +pub use bevy::prelude::default; +pub use bevy::render::render_resource::TextureFormat; +pub use processing_core::{config::*, constants, error}; +pub use processing_input::*; +#[cfg(not(target_arch = "wasm32"))] +pub use processing_midi::{ + midi_connect, midi_disconnect, midi_list_ports, midi_note_off, midi_note_on, midi_play_notes, + midi_refresh_ports, +}; +pub use processing_render::{ + render::command::{ + ArcMode, BlendMode, DrawCommand, LightKind, ShapeKind, ShapeMode, StrokeCapMode, + StrokeJoinMode, TextAlignH, TextAlignV, TextStyle, TextWrapMode, custom_blend_state, + }, + render::filter::Filter, + *, +}; + +pub use crate::{exit, init}; diff --git a/src/filter.rs b/src/filter.rs new file mode 100644 index 00000000..4625f6cc --- /dev/null +++ b/src/filter.rs @@ -0,0 +1,47 @@ +use bevy::prelude::Entity; +use processing_core::error::Result; +use processing_render::shader_value::ShaderValue; +use processing_render::{ + filter_blur, filter_dilate, filter_erode, filter_gray, filter_invert, filter_opaque, + filter_posterize, filter_set, filter_threshold, +}; + +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum Filter { + Invert, + Gray, + /// Cutoff 0-1. + Threshold(f32), + /// Levels 2-255. + Posterize(u32), + /// Radius in pixels. + Blur(f32), + Opaque, + Erode, + Dilate, +} + +impl Filter { + pub(crate) fn entity(self) -> Result { + let (entity, param) = match self { + Filter::Invert => (filter_invert()?, None), + Filter::Gray => (filter_gray()?, None), + Filter::Threshold(cutoff) => ( + filter_threshold()?, + Some(("cutoff", ShaderValue::Float(cutoff))), + ), + Filter::Posterize(levels) => ( + filter_posterize()?, + Some(("levels", ShaderValue::UInt(levels))), + ), + Filter::Blur(radius) => (filter_blur()?, Some(("radius", ShaderValue::Float(radius)))), + Filter::Opaque => (filter_opaque()?, None), + Filter::Erode => (filter_erode()?, None), + Filter::Dilate => (filter_dilate()?, None), + }; + if let Some((name, value)) = param { + filter_set(entity, name, value)?; + } + Ok(entity) + } +} diff --git a/src/geometry.rs b/src/geometry.rs new file mode 100644 index 00000000..8ef790e4 --- /dev/null +++ b/src/geometry.rs @@ -0,0 +1,296 @@ +use bevy::math::{Vec2, Vec3, Vec4}; +use bevy::prelude::Entity; +use processing_core::error::Result; +use processing_render::geometry::{AttributeFormat, Topology}; +use processing_render::shader_value::ShaderValue; +use processing_render::{ + geometry_attribute_age, geometry_attribute_color, geometry_attribute_create, + geometry_attribute_float, geometry_attribute_float2, geometry_attribute_float3, + geometry_attribute_float4, geometry_attribute_life, geometry_attribute_normal, + geometry_attribute_position, geometry_attribute_rotation, geometry_attribute_scale, + geometry_attribute_uv, geometry_attribute_velocity, geometry_box, geometry_color, + geometry_create, geometry_create_with_layout, geometry_destroy, geometry_get_indices, + geometry_get_positions, geometry_grid, geometry_index, geometry_index_count, + geometry_layout_add_attribute, geometry_layout_add_color, geometry_layout_add_normal, + geometry_layout_add_position, geometry_layout_add_uv, geometry_layout_create, + geometry_layout_destroy, geometry_normal, geometry_set_color, geometry_set_normal, + geometry_set_uv, geometry_set_vertex, geometry_sphere, geometry_uv, geometry_vertex, + geometry_vertex_count, +}; + +use crate::color::{ColorArg, ColorState}; +use crate::graphics::expect; +use crate::{IntoExtent, IntoPoint, IntoShaderValue, Scalar}; + +/// A retained mesh, drawn with `g.model(..)`. +#[derive(Debug)] +pub struct Geometry(pub(crate) Entity); + +impl Geometry { + pub fn new(topology: Topology) -> Result { + geometry_create(topology).map(Self) + } + + pub fn with_layout(layout: &Layout, topology: Topology) -> Result { + geometry_create_with_layout(layout.0, topology).map(Self) + } + + pub fn cube(size: impl IntoExtent) -> Result { + let s = size.into_extent(); + geometry_box(s.x, s.y, s.z).map(Self) + } + + pub fn sphere(radius: impl Scalar, sectors: u32, stacks: u32) -> Result { + geometry_sphere(radius.to_f32(), sectors, stacks).map(Self) + } + + pub fn grid(nx: u32, ny: u32, nz: u32, spacing: impl Scalar) -> Result { + geometry_grid(nx, ny, nz, spacing.to_f32()).map(Self) + } + + pub fn vertex(&mut self, position: impl IntoPoint) { + expect(geometry_vertex(self.0, position.into_point())); + } + + pub fn normal(&mut self, normal: impl IntoPoint) { + expect(geometry_normal(self.0, normal.into_point())); + } + + pub fn color(&mut self, color: impl Into) { + expect(geometry_color(self.0, color_vec4(color))); + } + + pub fn uv(&mut self, u: impl Scalar, v: impl Scalar) { + expect(geometry_uv(self.0, u.to_f32(), v.to_f32())); + } + + pub fn attribute(&mut self, attribute: Attribute, value: impl AttributeValue) { + let entity = self.0; + expect(match value.into_value() { + Value::Float(v) => geometry_attribute_float(entity, attribute.0, v), + Value::Float2(v) => geometry_attribute_float2(entity, attribute.0, v.x, v.y), + Value::Float3(v) => geometry_attribute_float3(entity, attribute.0, v.x, v.y, v.z), + Value::Float4(v) => geometry_attribute_float4(entity, attribute.0, v.x, v.y, v.z, v.w), + }); + } + + pub fn index(&mut self, i: u32) { + expect(geometry_index(self.0, i)); + } + + pub fn set_vertex(&mut self, i: u32, position: impl IntoPoint) { + expect(geometry_set_vertex(self.0, i, position.into_point())); + } + + pub fn set_normal(&mut self, i: u32, normal: impl IntoPoint) { + expect(geometry_set_normal(self.0, i, normal.into_point())); + } + + pub fn set_color(&mut self, i: u32, color: impl Into) { + expect(geometry_set_color(self.0, i, color_vec4(color))); + } + + pub fn set_uv(&mut self, i: u32, u: impl Scalar, v: impl Scalar) { + expect(geometry_set_uv( + self.0, + i, + Vec2::new(u.to_f32(), v.to_f32()), + )); + } + + pub fn vertex_count(&self) -> u32 { + expect(geometry_vertex_count(self.0)) + } + + pub fn index_count(&self) -> u32 { + expect(geometry_index_count(self.0)) + } + + pub fn positions(&self) -> Vec { + let count = self.vertex_count() as usize; + let positions = expect(geometry_get_positions(self.0, 0, count)); + positions.into_iter().map(Vec3::from_array).collect() + } + + /// Empty if the mesh has none. + pub fn indices(&self) -> Vec { + let count = self.index_count() as usize; + expect(geometry_get_indices(self.0, 0, count)) + } + + /// For `compute.set(..)`. + pub fn attribute_data(&self, attribute: Attribute) -> GeometryData { + GeometryData(ShaderValue::MeshAttribute(self.0, attribute.0)) + } + + /// For `compute.set(..)`. + pub fn index_data(&self) -> GeometryData { + GeometryData(ShaderValue::MeshIndex(self.0)) + } +} + +impl Drop for Geometry { + fn drop(&mut self) { + let _ = geometry_destroy(self.0); + } +} + +#[derive(Debug)] +pub struct GeometryData(ShaderValue); + +impl IntoShaderValue for GeometryData { + fn into_shader_value(self) -> ShaderValue { + self.0 + } +} + +fn color_vec4(color: impl Into) -> Vec4 { + let c = ColorState::default().resolve(color.into()); + Vec4::new(c.red(), c.green(), c.blue(), c.alpha()) +} + +#[derive(Debug)] +pub struct Layout(Entity); + +impl Layout { + pub fn new() -> Result { + geometry_layout_create().map(Self) + } + + pub fn position(self) -> Self { + expect(geometry_layout_add_position(self.0)); + self + } + + pub fn normal(self) -> Self { + expect(geometry_layout_add_normal(self.0)); + self + } + + pub fn color(self) -> Self { + expect(geometry_layout_add_color(self.0)); + self + } + + pub fn uv(self) -> Self { + expect(geometry_layout_add_uv(self.0)); + self + } + + pub fn attribute(self, attribute: Attribute) -> Self { + expect(geometry_layout_add_attribute(self.0, attribute.0)); + self + } +} + +impl Drop for Layout { + fn drop(&mut self) { + let _ = geometry_layout_destroy(self.0); + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Attribute(pub(crate) Entity); + +impl Attribute { + pub fn new(name: &str, format: AttributeFormat) -> Result { + geometry_attribute_create(name, format).map(Self) + } + + pub fn position() -> Self { + Self(geometry_attribute_position()) + } + + pub fn normal() -> Self { + Self(geometry_attribute_normal()) + } + + pub fn color() -> Self { + Self(geometry_attribute_color()) + } + + pub fn uv() -> Self { + Self(geometry_attribute_uv()) + } + + pub fn rotation() -> Self { + Self(geometry_attribute_rotation()) + } + + pub fn scale() -> Self { + Self(geometry_attribute_scale()) + } + + pub fn life() -> Self { + Self(geometry_attribute_life()) + } + + pub fn velocity() -> Self { + Self(geometry_attribute_velocity()) + } + + pub fn age() -> Self { + Self(geometry_attribute_age()) + } +} + +#[doc(hidden)] +pub enum Value { + Float(f32), + Float2(Vec2), + Float3(Vec3), + Float4(Vec4), +} + +/// A number, or a 2-4 tuple or vector. +pub trait AttributeValue { + #[doc(hidden)] + fn into_value(self) -> Value; +} + +impl AttributeValue for T { + fn into_value(self) -> Value { + Value::Float(self.to_f32()) + } +} + +impl AttributeValue for (A, B) { + fn into_value(self) -> Value { + Value::Float2(Vec2::new(self.0.to_f32(), self.1.to_f32())) + } +} + +impl AttributeValue for (A, B, C) { + fn into_value(self) -> Value { + Value::Float3(Vec3::new(self.0.to_f32(), self.1.to_f32(), self.2.to_f32())) + } +} + +impl AttributeValue for (A, B, C, D) { + fn into_value(self) -> Value { + Value::Float4(Vec4::new( + self.0.to_f32(), + self.1.to_f32(), + self.2.to_f32(), + self.3.to_f32(), + )) + } +} + +impl AttributeValue for Vec2 { + fn into_value(self) -> Value { + Value::Float2(self) + } +} + +impl AttributeValue for Vec3 { + fn into_value(self) -> Value { + Value::Float3(self) + } +} + +impl AttributeValue for Vec4 { + fn into_value(self) -> Value { + Value::Float4(self) + } +} diff --git a/src/gltf.rs b/src/gltf.rs new file mode 100644 index 00000000..a571d1c6 --- /dev/null +++ b/src/gltf.rs @@ -0,0 +1,42 @@ +use bevy::prelude::Entity; +use processing_core::error::Result; +use processing_render::{ + gltf_camera, gltf_geometry, gltf_light, gltf_load, gltf_material, gltf_material_names, + gltf_mesh_names, +}; + +use crate::{Geometry, Graphics, Light, Material}; + +#[derive(Debug)] +pub struct Gltf(Entity); + +impl Gltf { + pub fn load(g: &Graphics, path: &str) -> Result { + gltf_load(g.entity, path).map(Self) + } + + pub fn geometry(&self, name: &str) -> Result { + gltf_geometry(self.0, name).map(Geometry) + } + + pub fn material(&self, name: &str) -> Result { + gltf_material(self.0, name).map(Material) + } + + pub fn mesh_names(&self) -> Result> { + gltf_mesh_names(self.0) + } + + pub fn material_names(&self) -> Result> { + gltf_material_names(self.0) + } + + /// Moves the camera to the scene's camera. + pub fn camera(&self, index: usize) -> Result<()> { + gltf_camera(self.0, index) + } + + pub fn light(&self, index: usize) -> Result { + gltf_light(self.0, index).map(Light) + } +} diff --git a/src/graphics.rs b/src/graphics.rs new file mode 100644 index 00000000..36d799b4 --- /dev/null +++ b/src/graphics.rs @@ -0,0 +1,1036 @@ +use std::cell::{Cell, RefCell}; +use std::fmt::Display; + +use bevy::math::{Affine3A, Vec3, Vec4}; +use bevy::prelude::Entity; +use bevy::render::render_resource::TextureFormat; +use processing_core::error::Result; +use processing_input::{ + input_key, input_key_is_down, input_key_is_pressed, input_key_just_pressed, input_mouse_button, + input_mouse_is_pressed, input_mouse_wheel, input_mouse_x, input_mouse_y, input_moved_x, + input_moved_y, input_pmouse_x, input_pmouse_y, +}; +use processing_render::color::ColorMode; +use processing_render::render::command::{ + BlendMode, CommandSlot, DrawCommand, LightKind, ShapeKind, ShapeMode, StrokeCapMode, + StrokeJoinMode, TextAlignH, TextAlignV, TextStyle, TextWrapMode, +}; +use processing_render::{ + camera_reset, camera_set_center, camera_set_distance, delta_time, elapsed_time, frame_count, + geometry_create_from_mesh, graphics_amend_command, graphics_apply_filter, graphics_begin_draw, + graphics_create, graphics_destroy, graphics_disable_camera_controller, graphics_end_draw, + graphics_flush, graphics_free_camera, graphics_get_matrix, graphics_light, graphics_mode_2d, + graphics_mode_3d, graphics_orbit_camera, graphics_ortho, graphics_pan_camera, + graphics_perspective, graphics_readback, graphics_record_command, graphics_record_command_slot, + graphics_screen_point, graphics_set_color_mode, graphics_text_ascent, graphics_text_descent, + graphics_text_to_model, graphics_text_width, graphics_update, graphics_update_region, + light_create_directional, light_create_point, light_create_spot, light_destroy, + surface_create_offscreen, surface_destroy, surface_physical_height, surface_physical_width, + transform_look_at, transform_set_position, +}; + +use crate::color::{ColorArg, ColorSpace, ColorState, IntoColorMax}; +use crate::draw::{Arc, BeginDraw, Detail, ImageDraw, LightDraw, ParticlesDraw, Push, Rect, Text}; +use crate::input::{Key, MouseButton}; +use crate::shape::Shape; +use crate::{AsImage, Color, Font, IntoExtent, IntoPoint, Scalar}; +use crate::{Buffer, Filter, Geometry, Material, Particles}; + +pub(crate) fn expect(r: Result) -> T { + r.unwrap_or_else(|e| panic!("processing: {e}")) +} + +/// The sketch window, or an offscreen surface. +pub struct Graphics { + pub(crate) entity: Entity, + pub(crate) surface: Entity, + width: u32, + height: u32, + color: Cell, + style_stack: RefCell>, + offscreen: bool, + exit_requested: Cell, +} + +impl Graphics { + pub(crate) fn new(entity: Entity, surface: Entity, width: u32, height: u32) -> Self { + Self { + entity, + surface, + width, + height, + color: Cell::new(ColorState::default()), + style_stack: RefCell::new(Vec::new()), + offscreen: false, + exit_requested: Cell::new(false), + } + } + + /// Processing's `createGraphics`. + pub fn create(width: u32, height: u32) -> Result { + let format = TextureFormat::Rgba8UnormSrgb; + let surface = surface_create_offscreen(width, height, 1.0, format)?; + let entity = graphics_create(surface, width, height, format)?; + let mut g = Self::new(entity, surface, width, height); + g.offscreen = true; + Ok(g) + } + + pub fn begin_draw(&mut self) -> BeginDraw<'_> { + assert!( + self.offscreen, + "processing: begin_draw needs a Graphics::create surface" + ); + self.begin_frame(); + BeginDraw::new(self) + } + + pub(crate) fn record(&self, cmd: DrawCommand) { + expect(graphics_record_command(self.entity, cmd)); + } + + pub(crate) fn record_slot(&self, cmd: DrawCommand) -> CommandSlot { + expect(graphics_record_command_slot(self.entity, cmd)) + } + + pub(crate) fn amend(&self, slot: CommandSlot, amend: impl FnOnce(&mut DrawCommand)) { + expect(graphics_amend_command(slot, amend)); + } + + pub(crate) fn begin_frame(&mut self) { + self.style_stack.get_mut().clear(); + expect(graphics_begin_draw(self.entity)); + } + + pub(crate) fn end_frame(&mut self) { + expect(graphics_end_draw(self.entity)); + } + + pub(crate) fn resolve(&self, color: impl Into) -> bevy::color::Color { + self.color.get().resolve(color.into()).0 + } + + pub fn width(&self) -> f32 { + self.width as f32 + } + + pub fn height(&self) -> f32 { + self.height as f32 + } + + /// In physical pixels. + pub fn pixel_width(&self) -> u32 { + if self.offscreen { + return self.width; + } + expect(surface_physical_width(self.surface)) + } + + /// In physical pixels. + pub fn pixel_height(&self) -> u32 { + if self.offscreen { + return self.height; + } + expect(surface_physical_height(self.surface)) + } + + /// Starts at 1. + pub fn frame_count(&self) -> u32 { + expect(frame_count()) + } + + /// In seconds. + pub fn delta_time(&self) -> f32 { + expect(delta_time()) + } + + /// In seconds. + pub fn elapsed_time(&self) -> f32 { + expect(elapsed_time()) + } + + pub fn millis(&self) -> u32 { + (expect(elapsed_time()) * 1000.0) as u32 + } + + pub fn exit(&self) { + self.exit_requested.set(true); + } + + pub(crate) fn exit_requested(&self) -> bool { + self.exit_requested.get() + } + + pub fn color_mode(&self, space: ColorSpace) -> ColorModeBuilder<'_> { + self.set_color_state(ColorState { + mode: ColorMode::with_defaults(space), + explicit_max: false, + }); + ColorModeBuilder { g: self, space } + } + + pub fn color(&self, color: impl Into) -> Color { + self.color.get().resolve(color.into()) + } + + pub fn background(&self, color: impl Into) { + let c = self.resolve(color); + self.record(DrawCommand::BackgroundColor(c)); + } + + pub fn background_image(&self, image: &impl AsImage) { + self.record(DrawCommand::BackgroundImage(image.image_entity())); + } + + pub fn fill(&self, color: impl Into) { + let c = self.resolve(color); + self.record(DrawCommand::Fill(c)); + } + + pub fn no_fill(&self) { + self.record(DrawCommand::NoFill); + } + + pub fn stroke(&self, color: impl Into) { + let c = self.resolve(color); + self.record(DrawCommand::StrokeColor(c)); + } + + pub fn no_stroke(&self) { + self.record(DrawCommand::NoStroke); + } + + pub fn stroke_weight(&self, weight: impl Scalar) { + self.record(DrawCommand::StrokeWeight(weight.to_f32())); + } + + pub fn stroke_cap(&self, cap: StrokeCapMode) { + self.record(DrawCommand::StrokeCap(cap)); + } + + pub fn stroke_join(&self, join: StrokeJoinMode) { + self.record(DrawCommand::StrokeJoin(join)); + } + + pub fn tint(&self, color: impl Into) { + let c = self.resolve(color); + self.record(DrawCommand::Tint(c)); + } + + pub fn no_tint(&self) { + self.record(DrawCommand::NoTint); + } + + pub fn blend_mode(&self, mode: BlendMode) { + self.record(DrawCommand::BlendMode(mode.to_blend_state())); + } + + pub fn rect_mode(&self, mode: ShapeMode) { + self.record(DrawCommand::RectMode(mode)); + } + + pub fn ellipse_mode(&self, mode: ShapeMode) { + self.record(DrawCommand::EllipseMode(mode)); + } + + pub fn image_mode(&self, mode: ShapeMode) { + self.record(DrawCommand::ImageMode(mode)); + } + + pub fn rect(&self, x: impl Scalar, y: impl Scalar, w: impl Scalar, h: impl Scalar) -> Rect<'_> { + Rect::new(self, x.to_f32(), y.to_f32(), w.to_f32(), h.to_f32()) + } + + pub fn square(&self, x: impl Scalar, y: impl Scalar, size: impl Scalar) -> Rect<'_> { + let s = size.to_f32(); + Rect::new(self, x.to_f32(), y.to_f32(), s, s) + } + + pub fn ellipse(&self, x: impl Scalar, y: impl Scalar, w: impl Scalar, h: impl Scalar) { + self.record(DrawCommand::Ellipse { + cx: x.to_f32(), + cy: y.to_f32(), + w: w.to_f32(), + h: h.to_f32(), + }); + } + + pub fn circle(&self, x: impl Scalar, y: impl Scalar, diameter: impl Scalar) { + let d = diameter.to_f32(); + self.ellipse(x, y, d, d); + } + + pub fn arc( + &self, + x: impl Scalar, + y: impl Scalar, + w: impl Scalar, + h: impl Scalar, + start: impl Scalar, + stop: impl Scalar, + ) -> Arc<'_> { + Arc::new( + self, + [x.to_f32(), y.to_f32(), w.to_f32(), h.to_f32()], + start.to_f32(), + stop.to_f32(), + ) + } + + pub fn line(&self, x1: impl Scalar, y1: impl Scalar, x2: impl Scalar, y2: impl Scalar) { + self.record(DrawCommand::Line { + x1: x1.to_f32(), + y1: y1.to_f32(), + x2: x2.to_f32(), + y2: y2.to_f32(), + }); + } + + pub fn point(&self, x: impl Scalar, y: impl Scalar) { + self.record(DrawCommand::Point { + x: x.to_f32(), + y: y.to_f32(), + }); + } + + pub fn triangle( + &self, + x1: impl Scalar, + y1: impl Scalar, + x2: impl Scalar, + y2: impl Scalar, + x3: impl Scalar, + y3: impl Scalar, + ) { + self.record(DrawCommand::Triangle { + x1: x1.to_f32(), + y1: y1.to_f32(), + x2: x2.to_f32(), + y2: y2.to_f32(), + x3: x3.to_f32(), + y3: y3.to_f32(), + }); + } + + pub fn quad( + &self, + x1: impl Scalar, + y1: impl Scalar, + x2: impl Scalar, + y2: impl Scalar, + x3: impl Scalar, + y3: impl Scalar, + x4: impl Scalar, + y4: impl Scalar, + ) { + self.record(DrawCommand::Quad { + x1: x1.to_f32(), + y1: y1.to_f32(), + x2: x2.to_f32(), + y2: y2.to_f32(), + x3: x3.to_f32(), + y3: y3.to_f32(), + x4: x4.to_f32(), + y4: y4.to_f32(), + }); + } + + pub fn bezier( + &self, + x1: impl Scalar, + y1: impl Scalar, + x2: impl Scalar, + y2: impl Scalar, + x3: impl Scalar, + y3: impl Scalar, + x4: impl Scalar, + y4: impl Scalar, + ) { + self.record(DrawCommand::Bezier { + x1: x1.to_f32(), + y1: y1.to_f32(), + x2: x2.to_f32(), + y2: y2.to_f32(), + x3: x3.to_f32(), + y3: y3.to_f32(), + x4: x4.to_f32(), + y4: y4.to_f32(), + }); + } + + pub fn curve( + &self, + x1: impl Scalar, + y1: impl Scalar, + x2: impl Scalar, + y2: impl Scalar, + x3: impl Scalar, + y3: impl Scalar, + x4: impl Scalar, + y4: impl Scalar, + ) { + self.record(DrawCommand::Curve { + x1: x1.to_f32(), + y1: y1.to_f32(), + x2: x2.to_f32(), + y2: y2.to_f32(), + x3: x3.to_f32(), + y3: y3.to_f32(), + x4: x4.to_f32(), + y4: y4.to_f32(), + }); + } + + pub fn begin_shape(&mut self, kind: ShapeKind) -> Shape<'_> { + Shape::new(self, kind) + } + + pub fn image(&self, image: &impl AsImage, x: impl Scalar, y: impl Scalar) -> ImageDraw<'_> { + ImageDraw::new(self, image.image_entity(), x.to_f32(), y.to_f32()) + } + + pub fn text(&self, content: impl Display, x: impl Scalar, y: impl Scalar) -> Text<'_> { + Text::new(self, content.to_string(), x.to_f32(), y.to_f32()) + } + + pub fn text_font(&self, font: Font) { + self.record(DrawCommand::TextFont(Some(font.0))); + } + + pub fn text_size(&self, size: impl Scalar) { + self.record(DrawCommand::TextSize(size.to_f32())); + } + + pub fn text_leading(&self, leading: impl Scalar) { + self.record(DrawCommand::TextLeading(leading.to_f32())); + } + + pub fn text_align(&self, align: impl Into) { + let TextAlign(h, v) = align.into(); + self.record(DrawCommand::TextAlign { h, v }); + } + + pub fn text_style(&self, style: TextStyle) { + self.record(DrawCommand::TextStyle(style)); + } + + pub fn text_wrap(&self, mode: TextWrapMode) { + self.record(DrawCommand::TextWrap(mode)); + } + + pub fn text_width(&self, content: &str) -> f32 { + expect(graphics_text_width(self.entity, content)) + } + + pub fn text_ascent(&self) -> f32 { + expect(graphics_text_ascent(self.entity)) + } + + pub fn text_descent(&self) -> f32 { + expect(graphics_text_descent(self.entity)) + } + + pub fn push(&mut self) -> Push<'_> { + self.push_style(); + self.push_matrix(); + Push::new(self) + } + + pub fn push_matrix(&self) { + self.record(DrawCommand::PushMatrix); + } + + pub fn pop_matrix(&self) { + self.record(DrawCommand::PopMatrix); + } + + pub fn push_style(&self) { + self.style_stack.borrow_mut().push(self.color.get()); + self.record(DrawCommand::PushStyle); + } + + pub fn pop_style(&self) { + let color = self.style_stack.borrow_mut().pop(); + if let Some(color) = color { + self.set_color_state(color); + } + self.record(DrawCommand::PopStyle); + } + + pub fn translate(&self, offset: impl IntoPoint) { + self.record(DrawCommand::Translate(offset.into_point())); + } + + pub fn rotate(&self, angle: impl Scalar) { + self.rotate_axis(angle, Vec3::Z); + } + + pub fn rotate_x(&self, angle: impl Scalar) { + self.rotate_axis(angle, Vec3::X); + } + + pub fn rotate_y(&self, angle: impl Scalar) { + self.rotate_axis(angle, Vec3::Y); + } + + pub fn rotate_z(&self, angle: impl Scalar) { + self.rotate_axis(angle, Vec3::Z); + } + + pub fn rotate_axis(&self, angle: impl Scalar, axis: impl IntoPoint) { + self.record(DrawCommand::Rotate { + angle: angle.to_f32(), + axis: axis.into_point(), + }); + } + + pub fn scale(&self, factor: impl IntoExtent) { + self.record(DrawCommand::Scale(factor.into_extent())); + } + + pub fn shear_x(&self, angle: impl Scalar) { + self.record(DrawCommand::ShearX { + angle: angle.to_f32(), + }); + } + + pub fn shear_y(&self, angle: impl Scalar) { + self.record(DrawCommand::ShearY { + angle: angle.to_f32(), + }); + } + + pub fn reset_matrix(&self) { + self.record(DrawCommand::ResetMatrix); + } + + pub fn apply_matrix(&self, matrix: Affine3A) { + self.record(DrawCommand::ApplyMatrix(matrix)); + } + + pub fn matrix(&mut self) -> bevy::math::Mat4 { + expect(graphics_get_matrix(self.entity)) + } + + pub fn screen_point(&mut self, point: impl IntoPoint) -> Vec3 { + expect(graphics_screen_point(self.entity, point.into_point())) + } + + pub fn mode_3d(&mut self) { + expect(graphics_mode_3d(self.entity)); + } + + pub fn mode_2d(&mut self) { + expect(graphics_mode_2d(self.entity)); + } + + pub fn cube(&self, size: impl IntoExtent) { + let s = size.into_extent(); + self.record(DrawCommand::Box { + width: s.x, + height: s.y, + depth: s.z, + }); + } + + pub fn sphere(&self, radius: impl Scalar) -> Detail<'_, 2> { + Detail::new( + self, + [radius.to_f32(), 0.0, 0.0], + [32, 16], + |[radius, _, _], [sectors, stacks]| DrawCommand::Sphere { + radius, + sectors, + stacks, + }, + ) + } + + pub fn cylinder(&self, radius: impl Scalar, height: impl Scalar) -> Detail<'_, 1> { + let size = [radius.to_f32(), height.to_f32(), 0.0]; + Detail::new(self, size, [24], |[radius, height, _], [detail]| { + DrawCommand::Cylinder { + radius, + height, + detail, + } + }) + } + + pub fn cone(&self, radius: impl Scalar, height: impl Scalar) -> Detail<'_, 1> { + let size = [radius.to_f32(), height.to_f32(), 0.0]; + Detail::new(self, size, [24], |[radius, height, _], [detail]| { + DrawCommand::Cone { + radius, + height, + detail, + } + }) + } + + pub fn torus(&self, radius: impl Scalar, tube_radius: impl Scalar) -> Detail<'_, 2> { + let size = [radius.to_f32(), tube_radius.to_f32(), 0.0]; + Detail::new( + self, + size, + [32, 16], + |[radius, tube_radius, _], [major, minor]| DrawCommand::Torus { + radius, + tube_radius, + major_segments: major, + minor_segments: minor, + }, + ) + } + + pub fn capsule(&self, radius: impl Scalar, length: impl Scalar) -> Detail<'_, 1> { + let size = [radius.to_f32(), length.to_f32(), 0.0]; + Detail::new(self, size, [16], |[radius, length, _], [detail]| { + DrawCommand::Capsule { + radius, + length, + detail, + } + }) + } + + pub fn conical_frustum( + &self, + radius_top: impl Scalar, + radius_bottom: impl Scalar, + height: impl Scalar, + ) -> Detail<'_, 1> { + let size = [radius_top.to_f32(), radius_bottom.to_f32(), height.to_f32()]; + Detail::new( + self, + size, + [24], + |[radius_top, radius_bottom, height], [detail]| DrawCommand::ConicalFrustum { + radius_top, + radius_bottom, + height, + detail, + }, + ) + } + + pub fn plane(&self, width: impl Scalar, height: impl Scalar) { + self.record(DrawCommand::Plane { + width: width.to_f32(), + height: height.to_f32(), + }); + } + + pub fn tetrahedron(&self, radius: impl Scalar) { + self.record(DrawCommand::Tetrahedron { + radius: radius.to_f32(), + }); + } + + pub fn roughness(&self, value: impl Scalar) { + self.record(DrawCommand::Roughness(value.to_f32())); + } + + pub fn metallic(&self, value: impl Scalar) { + self.record(DrawCommand::Metallic(value.to_f32())); + } + + pub fn emissive(&self, color: impl Into) { + let c = self.resolve(color); + self.record(DrawCommand::Emissive(c)); + } + + pub fn unlit(&self) { + self.record(DrawCommand::Unlit); + } + + pub fn texture(&self, image: &impl AsImage) { + self.record(DrawCommand::Texture(image.image_entity())); + } + + pub fn no_texture(&self) { + self.record(DrawCommand::NoTexture); + } + + pub fn camera_position(&self, eye: impl IntoPoint) { + expect(transform_set_position(self.entity, eye.into_point())); + } + + pub fn camera_look_at(&self, target: impl IntoPoint) { + expect(transform_look_at(self.entity, target.into_point())); + } + + pub fn perspective( + &mut self, + fov: impl Scalar, + aspect: impl Scalar, + near: impl Scalar, + far: impl Scalar, + ) { + let near = near.to_f32(); + expect(graphics_perspective( + self.entity, + fov.to_f32(), + aspect.to_f32(), + near, + far.to_f32(), + Vec4::new(0.0, 0.0, -1.0, -near), + )); + } + + pub fn ortho( + &mut self, + left: impl Scalar, + right: impl Scalar, + bottom: impl Scalar, + top: impl Scalar, + near: impl Scalar, + far: impl Scalar, + ) { + expect(graphics_ortho( + self.entity, + left.to_f32(), + right.to_f32(), + bottom.to_f32(), + top.to_f32(), + near.to_f32(), + far.to_f32(), + )); + } + + pub fn orbit_camera(&self) { + expect(graphics_orbit_camera(self.entity)); + } + + pub fn free_camera(&self) { + expect(graphics_free_camera(self.entity)); + } + + pub fn pan_camera(&self) { + expect(graphics_pan_camera(self.entity)); + } + + pub fn disable_camera(&self) { + expect(graphics_disable_camera_controller(self.entity)); + } + + pub fn camera_distance(&self, distance: impl Scalar) { + expect(camera_set_distance(self.entity, distance.to_f32())); + } + + pub fn camera_center(&self, center: impl IntoPoint) { + expect(camera_set_center(self.entity, center.into_point())); + } + + pub fn camera_reset(&self) { + expect(camera_reset(self.entity)); + } + + pub fn light(&self, light: &Light) { + expect(graphics_light(self.entity, light.0)); + } + + pub fn directional_light( + &self, + color: impl Into, + illuminance: impl Scalar, + ) -> LightDraw<'_> { + let color = self.resolve(color); + LightDraw::new( + self, + LightKind::Directional { + color, + illuminance: illuminance.to_f32(), + }, + ) + } + + pub fn point_light( + &self, + color: impl Into, + intensity: impl Scalar, + range: impl Scalar, + radius: impl Scalar, + ) -> LightDraw<'_> { + let color = self.resolve(color); + LightDraw::new( + self, + LightKind::Point { + color, + intensity: intensity.to_f32(), + range: range.to_f32(), + radius: radius.to_f32(), + }, + ) + } + + pub fn spot_light( + &self, + color: impl Into, + intensity: impl Scalar, + range: impl Scalar, + radius: impl Scalar, + inner_angle: impl Scalar, + outer_angle: impl Scalar, + ) -> LightDraw<'_> { + let color = self.resolve(color); + LightDraw::new( + self, + LightKind::Spot { + color, + intensity: intensity.to_f32(), + range: range.to_f32(), + radius: radius.to_f32(), + inner_angle: inner_angle.to_f32(), + outer_angle: outer_angle.to_f32(), + }, + ) + } + + pub fn create_directional_light( + &self, + color: impl Into, + illuminance: impl Scalar, + ) -> Light { + let c = self.resolve(color); + Light(expect(light_create_directional( + self.entity, + c, + illuminance.to_f32(), + ))) + } + + pub fn create_point_light( + &self, + color: impl Into, + intensity: impl Scalar, + range: impl Scalar, + radius: impl Scalar, + ) -> Light { + let c = self.resolve(color); + Light(expect(light_create_point( + self.entity, + c, + intensity.to_f32(), + range.to_f32(), + radius.to_f32(), + ))) + } + + pub fn create_spot_light( + &self, + color: impl Into, + intensity: impl Scalar, + range: impl Scalar, + radius: impl Scalar, + inner_angle: impl Scalar, + outer_angle: impl Scalar, + ) -> Light { + let c = self.resolve(color); + Light(expect(light_create_spot( + self.entity, + c, + intensity.to_f32(), + range.to_f32(), + radius.to_f32(), + inner_angle.to_f32(), + outer_angle.to_f32(), + ))) + } + + pub fn model(&self, geometry: &Geometry) { + self.record(DrawCommand::Geometry(geometry.0)); + } + + pub fn material(&self, material: &Material) { + self.record(DrawCommand::Material(material.0)); + } + + /// One color per particle. + pub fn fill_buffer(&self, buffer: &Buffer) { + self.record(DrawCommand::FillBuffer(buffer.entity)); + } + + /// Points unless given a geometry. + pub fn particles(&self, particles: &Particles) -> ParticlesDraw<'_> { + ParticlesDraw::new(self, particles.0) + } + + pub fn filter(&mut self, filter: Filter) { + let entity = expect(filter.entity()); + expect(graphics_apply_filter(self.entity, entity)); + } + + pub fn text_to_model( + &self, + content: &str, + x: impl Scalar, + y: impl Scalar, + depth: impl Scalar, + ) -> Result { + let mesh = + graphics_text_to_model(self.entity, content, x.to_f32(), y.to_f32(), depth.to_f32())?; + geometry_create_from_mesh(mesh).map(Geometry) + } + + /// Row-major. + pub fn pixels(&mut self) -> Result> { + Ok(graphics_readback(self.entity)? + .into_iter() + .map(Color::from_linear) + .collect()) + } + + /// `pixels.len()` must be `pixel_width() * pixel_height()`. + pub fn set_pixels(&mut self, pixels: &[Color]) -> Result<()> { + let linear: Vec<_> = pixels.iter().map(|c| c.to_linear()).collect(); + graphics_flush(self.entity)?; + graphics_update(self.entity, &linear) + } + + pub fn set_pixels_region( + &mut self, + x: i32, + y: i32, + w: u32, + h: u32, + pixels: &[Color], + ) -> Result<()> { + let linear: Vec<_> = pixels.iter().map(|c| c.to_linear()).collect(); + graphics_flush(self.entity)?; + graphics_update_region(self.entity, x.into(), y.into(), w, h, &linear) + } + + pub fn mouse_x(&self) -> f32 { + expect(input_mouse_x(self.surface)).clamp(0.0, self.width()) + } + + pub fn mouse_y(&self) -> f32 { + expect(input_mouse_y(self.surface)).clamp(0.0, self.height()) + } + + pub fn pmouse_x(&self) -> f32 { + expect(input_pmouse_x(self.surface)).clamp(0.0, self.width()) + } + + pub fn pmouse_y(&self) -> f32 { + expect(input_pmouse_y(self.surface)).clamp(0.0, self.height()) + } + + pub fn moved_x(&self) -> f32 { + expect(input_moved_x()) + } + + pub fn moved_y(&self) -> f32 { + expect(input_moved_y()) + } + + pub fn mouse_wheel(&self) -> f32 { + expect(input_mouse_wheel()) + } + + pub fn mouse_pressed(&self) -> bool { + expect(input_mouse_is_pressed()) + } + + pub fn mouse_button(&self) -> Option { + expect(input_mouse_button()).map(MouseButton::from) + } + + pub fn key_pressed(&self) -> bool { + expect(input_key_is_pressed()) + } + + pub fn key(&self) -> Option { + expect(input_key()) + } + + pub fn key_code(&self) -> Option { + expect(processing_input::input_key_code()).and_then(Key::from_code) + } + + pub fn key_down(&self, key: Key) -> bool { + expect(input_key_is_down(key.code())) + } + + pub fn key_just_pressed(&self, key: Key) -> bool { + expect(input_key_just_pressed(key.code())) + } + + fn set_color_state(&self, color: ColorState) { + self.color.set(color); + expect(graphics_set_color_mode(self.entity, color.mode)); + } +} + +impl AsImage for Graphics { + fn image_entity(&self) -> Entity { + assert!( + self.offscreen, + "processing: only Graphics::create surfaces can be drawn as images" + ); + self.surface + } +} + +impl Drop for Graphics { + fn drop(&mut self) { + let _ = graphics_destroy(self.entity); + if self.offscreen { + let _ = surface_destroy(self.surface); + } + } +} + +pub struct ColorModeBuilder<'g> { + g: &'g Graphics, + space: ColorSpace, +} + +impl ColorModeBuilder<'_> { + /// `max(255)`, `max((360, 100, 100))` or `max((360, 100, 100, 1))`. + pub fn max(self, max: impl IntoColorMax) -> Self { + let [m1, m2, m3, ma] = max.into_color_max(self.space); + self.g.set_color_state(ColorState { + mode: ColorMode::new(self.space, m1, m2, m3, ma), + explicit_max: true, + }); + self + } +} + +#[derive(Debug, Clone, Copy)] +pub struct TextAlign(TextAlignH, TextAlignV); + +impl From for TextAlign { + fn from(h: TextAlignH) -> Self { + Self(h, TextAlignV::default()) + } +} + +impl From<(TextAlignH, TextAlignV)> for TextAlign { + fn from((h, v): (TextAlignH, TextAlignV)) -> Self { + Self(h, v) + } +} + +#[derive(Debug)] +pub struct Light(pub(crate) Entity); + +impl Light { + pub fn position(&self, position: impl IntoPoint) -> &Self { + expect(transform_set_position(self.0, position.into_point())); + self + } + + pub fn look_at(&self, target: impl IntoPoint) -> &Self { + expect(transform_look_at(self.0, target.into_point())); + self + } +} + +impl Drop for Light { + fn drop(&mut self) { + let _ = light_destroy(self.0); + } +} diff --git a/src/image.rs b/src/image.rs new file mode 100644 index 00000000..8a646126 --- /dev/null +++ b/src/image.rs @@ -0,0 +1,103 @@ +use bevy::prelude::Entity; +use bevy::render::render_resource::{Extent3d, TextureFormat}; +use processing_core::error::Result; +use processing_render::{ + font_create, font_list, font_load, image_create, image_destroy, image_load, image_readback, + image_size, image_update, +}; + +use crate::Color; + +#[derive(Debug)] +pub struct Image { + pub(crate) entity: Entity, + width: u32, + height: u32, +} + +impl Image { + pub fn load(path: &str) -> Result { + let entity = image_load(path)?; + let (width, height) = image_size(entity)?; + Ok(Self { + entity, + width, + height, + }) + } + + /// Transparent. + pub fn create(width: u32, height: u32) -> Result { + let size = Extent3d { + width, + height, + depth_or_array_layers: 1, + }; + let data = vec![0u8; (width * height * 4) as usize]; + let entity = image_create(size, data, TextureFormat::Rgba8UnormSrgb)?; + Ok(Self { + entity, + width, + height, + }) + } + + pub fn width(&self) -> u32 { + self.width + } + + pub fn height(&self) -> u32 { + self.height + } + + /// Row-major. + pub fn pixels(&self) -> Result> { + Ok(image_readback(self.entity)? + .into_iter() + .map(Color::from_linear) + .collect()) + } + + /// `pixels.len()` must be `width * height`. + pub fn set_pixels(&mut self, pixels: &[Color]) -> Result<()> { + let linear: Vec<_> = pixels.iter().map(|c| c.to_linear()).collect(); + image_update(self.entity, &linear) + } +} + +impl Drop for Image { + fn drop(&mut self) { + let _ = image_destroy(self.entity); + } +} + +/// Anything `g.image(..)` can draw. +pub trait AsImage { + #[doc(hidden)] + fn image_entity(&self) -> Entity; +} + +impl AsImage for Image { + fn image_entity(&self) -> Entity { + self.entity + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Font(pub(crate) Entity); + +impl Font { + pub fn load(path: &str) -> Result { + font_load(path).map(Self) + } + + /// An installed font, by family name. + pub fn system(name: &str) -> Result { + font_create(name).map(Self) + } + + /// Installed font families. + pub fn list() -> Result> { + font_list() + } +} diff --git a/src/input.rs b/src/input.rs new file mode 100644 index 00000000..c9c0d9d8 --- /dev/null +++ b/src/input.rs @@ -0,0 +1,68 @@ +use bevy::input::keyboard::KeyCode; +use bevy::input::mouse::MouseButton as BevyMouseButton; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum MouseButton { + Left, + Right, + Middle, + Back, + Forward, + Other(u16), +} + +impl From for MouseButton { + fn from(b: BevyMouseButton) -> Self { + match b { + BevyMouseButton::Left => Self::Left, + BevyMouseButton::Right => Self::Right, + BevyMouseButton::Middle => Self::Middle, + BevyMouseButton::Back => Self::Back, + BevyMouseButton::Forward => Self::Forward, + BevyMouseButton::Other(n) => Self::Other(n), + } + } +} + +macro_rules! keys { + ($($key:ident => $code:ident),* $(,)?) => { + /// By position on a US keyboard. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + pub enum Key { + $($key,)* + } + + impl Key { + pub(crate) fn code(self) -> KeyCode { + match self { + $(Self::$key => KeyCode::$code,)* + } + } + + pub(crate) fn from_code(code: KeyCode) -> Option { + match code { + $(KeyCode::$code => Some(Self::$key),)* + _ => None, + } + } + } + }; +} + +keys!( + A => KeyA, B => KeyB, C => KeyC, D => KeyD, E => KeyE, F => KeyF, G => KeyG, H => KeyH, + I => KeyI, J => KeyJ, K => KeyK, L => KeyL, M => KeyM, N => KeyN, O => KeyO, P => KeyP, + Q => KeyQ, R => KeyR, S => KeyS, T => KeyT, U => KeyU, V => KeyV, W => KeyW, X => KeyX, + Y => KeyY, Z => KeyZ, Num0 => Digit0, Num1 => Digit1, Num2 => Digit2, Num3 => Digit3, + Num4 => Digit4, Num5 => Digit5, Num6 => Digit6, Num7 => Digit7, Num8 => Digit8, Num9 => Digit9, + Up => ArrowUp, Down => ArrowDown, Left => ArrowLeft, Right => ArrowRight, Space => Space, + Enter => Enter, Escape => Escape, Tab => Tab, Backspace => Backspace, Delete => Delete, + Insert => Insert, Home => Home, End => End, PageUp => PageUp, PageDown => PageDown, + ShiftLeft => ShiftLeft, ShiftRight => ShiftRight, ControlLeft => ControlLeft, + ControlRight => ControlRight, AltLeft => AltLeft, AltRight => AltRight, SuperLeft => SuperLeft, + SuperRight => SuperRight, Minus => Minus, Equal => Equal, BracketLeft => BracketLeft, + BracketRight => BracketRight, Backslash => Backslash, Semicolon => Semicolon, Quote => Quote, + Backquote => Backquote, Comma => Comma, Period => Period, Slash => Slash, F1 => F1, F2 => F2, + F3 => F3, F4 => F4, F5 => F5, F6 => F6, F7 => F7, F8 => F8, F9 => F9, F10 => F10, F11 => F11, + F12 => F12, +); diff --git a/src/lib.rs b/src/lib.rs index 7620f21c..f078abaa 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,70 @@ +pub mod engine; +#[cfg(not(target_arch = "wasm32"))] pub mod prelude; +#[cfg(not(target_arch = "wasm32"))] +mod args; +#[cfg(not(target_arch = "wasm32"))] +mod color; +#[cfg(not(target_arch = "wasm32"))] +mod draw; +#[cfg(not(target_arch = "wasm32"))] +mod filter; +#[cfg(not(target_arch = "wasm32"))] +mod geometry; +#[cfg(not(target_arch = "wasm32"))] +mod gltf; +#[cfg(not(target_arch = "wasm32"))] +mod graphics; +#[cfg(not(target_arch = "wasm32"))] +mod image; +#[cfg(not(target_arch = "wasm32"))] +mod input; +#[cfg(not(target_arch = "wasm32"))] +pub mod midi; +#[cfg(not(target_arch = "wasm32"))] +mod particles; +#[cfg(not(target_arch = "wasm32"))] +mod shader; +#[cfg(not(target_arch = "wasm32"))] +mod shape; +#[cfg(not(target_arch = "wasm32"))] +mod sketch; +#[cfg(all(feature = "webcam", not(target_arch = "wasm32")))] +mod webcam; + +#[cfg(all(feature = "webcam", not(target_arch = "wasm32")))] +pub use crate::webcam::Webcam; +#[cfg(not(target_arch = "wasm32"))] +pub use crate::{ + args::{IntoExtent, IntoPoint, Scalar}, + color::{Channel, Color, ColorArg, ColorSpace, IntoChannel, IntoColorMax}, + draw::{Arc, BeginDraw, Detail, ImageDraw, LightDraw, ParticlesDraw, Push, Rect, Text}, + filter::Filter, + geometry::{Attribute, AttributeValue, Geometry, GeometryData, Layout}, + gltf::Gltf, + graphics::{ColorModeBuilder, Graphics, Light, TextAlign}, + image::{AsImage, Font, Image}, + input::{Key, MouseButton}, + particles::{BufferData, Particles}, + shader::{Buffer, BufferElement, Compute, IntoShaderValue, Material, Shader}, + shape::{Contour, Shape}, + sketch::{Settings, Sketch, run}, +}; +pub use bevy::math::{Affine3A, Mat4, Vec2, Vec3, Vec4}; +pub use std::f32::consts::{PI, TAU}; +pub const HALF_PI: f32 = std::f32::consts::FRAC_PI_2; +pub const QUARTER_PI: f32 = std::f32::consts::FRAC_PI_4; +pub const TWO_PI: f32 = TAU; +pub use processing_core::error::ProcessingError as Error; + +pub type Result = std::result::Result; +pub use processing_render::geometry::{AttributeFormat, Topology}; +pub use processing_render::render::command::{ + ArcMode, BlendMode, ShapeKind, ShapeMode, StrokeCapMode as StrokeCap, + StrokeJoinMode as StrokeJoin, TextAlignH, TextAlignV, TextStyle, TextWrapMode, +}; + use std::num::NonZero; use bevy::app::{App, AppExit}; diff --git a/src/midi.rs b/src/midi.rs new file mode 100644 index 00000000..2789b888 --- /dev/null +++ b/src/midi.rs @@ -0,0 +1,31 @@ +use processing_core::error::Result; + +pub fn refresh_ports() -> Result<()> { + processing_midi::midi_refresh_ports() +} + +/// Output port names, indexed as [`connect`] takes them. +pub fn ports() -> Result> { + processing_midi::midi_list_ports() +} + +pub fn connect(port: usize) -> Result<()> { + processing_midi::midi_connect(port) +} + +pub fn disconnect() -> Result<()> { + processing_midi::midi_disconnect() +} + +pub fn note_on(note: u8, velocity: u8) -> Result<()> { + processing_midi::midi_note_on(note, velocity) +} + +pub fn note_off(note: u8) -> Result<()> { + processing_midi::midi_note_off(note) +} + +/// `duration` in milliseconds. +pub fn play_note(note: u8, duration: u64) -> Result<()> { + processing_midi::midi_play_notes(note, duration) +} diff --git a/src/particles.rs b/src/particles.rs new file mode 100644 index 00000000..a4c57618 --- /dev/null +++ b/src/particles.rs @@ -0,0 +1,194 @@ +use bevy::prelude::Entity; +use processing_core::error::{ProcessingError, Result}; +use processing_render::geometry_attribute_info; +use processing_render::particles::{ + particles_apply, particles_capacity, particles_create, particles_create_from_geometry, + particles_destroy, particles_emit, particles_emit_gpu, particles_ensure_attribute, + particles_kernel_age, particles_kernel_attract, particles_kernel_bounds_box, + particles_kernel_bounds_geometry, particles_kernel_bounds_sphere, particles_kernel_drag, + particles_kernel_field, particles_kernel_force, particles_kernel_impulse, + particles_kernel_integrate, particles_kernel_noise, particles_kernel_orient, + particles_kernel_transform, particles_kernel_vortex, particles_scatter_create, + particles_scatter_volume_create, +}; + +use crate::graphics::expect; +use crate::{Attribute, Buffer, BufferElement, Compute, Geometry}; + +/// A slice or `Vec` of [`BufferElement`]s. +pub trait BufferData { + #[doc(hidden)] + fn bytes(&self) -> Vec; + #[doc(hidden)] + fn element(&self) -> ElementInfo; +} + +#[doc(hidden)] +pub struct ElementInfo { + name: &'static str, + float: bool, + components: usize, +} + +impl ElementInfo { + fn of() -> Self { + Self { + name: std::any::type_name::(), + float: T::FLOAT, + components: T::COMPONENTS, + } + } +} + +impl BufferData for [T] { + fn bytes(&self) -> Vec { + T::to_bytes(self) + } + fn element(&self) -> ElementInfo { + ElementInfo::of::() + } +} + +impl BufferData for Vec { + fn bytes(&self) -> Vec { + T::to_bytes(self) + } + fn element(&self) -> ElementInfo { + ElementInfo::of::() + } +} + +impl BufferData for [T; N] { + fn bytes(&self) -> Vec { + T::to_bytes(self) + } + fn element(&self) -> ElementInfo { + ElementInfo::of::() + } +} + +fn check_element(attribute: &Attribute, element: &ElementInfo) -> Result<()> { + let (name, format) = geometry_attribute_info(attribute.0)?; + let components = format as usize; + if element.float && (element.components == 1 || element.components == components) { + return Ok(()); + } + Err(ProcessingError::InvalidArgument(format!( + "can't write {} to {format:?} attribute `{name}`", + element.name + ))) +} + +#[derive(Debug)] +pub struct Particles(pub(crate) Entity); + +impl Particles { + pub fn new(capacity: u32, attributes: &[Attribute]) -> Result { + particles_create(capacity, attributes.iter().map(|a| a.0).collect()).map(Self) + } + + /// One particle per vertex. + pub fn from_geometry(geometry: &Geometry, attributes: &[Attribute]) -> Result { + particles_create_from_geometry(geometry.0, attributes.iter().map(|a| a.0).collect()) + .map(Self) + } + + pub fn capacity(&self) -> u32 { + expect(particles_capacity(self.0)) + } + + /// Adds the attribute if missing. + pub fn buffer(&self, attribute: Attribute) -> Buffer { + Buffer::borrowed(expect(particles_ensure_attribute(self.0, attribute.0))) + } + + pub fn apply(&mut self, compute: &Compute) { + expect(particles_apply(self.0, compute.0)); + } + + /// Replaces the oldest when full. + pub fn emit(&mut self, count: u32, values: &[(Attribute, &dyn BufferData)]) { + let mut data = Vec::with_capacity(values.len()); + for (attribute, v) in values { + expect(check_element(attribute, &v.element())); + data.push((attribute.0, v.bytes())); + } + expect(particles_emit(self.0, count, data)); + } + + pub fn emit_gpu(&mut self, count: u32, compute: &Compute) { + expect(particles_emit_gpu(self.0, count, compute.0)); + } + + pub fn noise() -> Result { + particles_kernel_noise().map(Compute) + } + + pub fn transform() -> Result { + particles_kernel_transform().map(Compute) + } + + pub fn attract() -> Result { + particles_kernel_attract().map(Compute) + } + + pub fn drag() -> Result { + particles_kernel_drag().map(Compute) + } + + pub fn vortex() -> Result { + particles_kernel_vortex().map(Compute) + } + + pub fn force() -> Result { + particles_kernel_force().map(Compute) + } + + pub fn integrate() -> Result { + particles_kernel_integrate().map(Compute) + } + + pub fn age() -> Result { + particles_kernel_age().map(Compute) + } + + pub fn bounds_sphere() -> Result { + particles_kernel_bounds_sphere().map(Compute) + } + + pub fn bounds_box() -> Result { + particles_kernel_bounds_box().map(Compute) + } + + pub fn bounds_geometry(geometry: &Geometry) -> Result { + particles_kernel_bounds_geometry(geometry.0).map(Compute) + } + + pub fn impulse() -> Result { + particles_kernel_impulse().map(Compute) + } + + pub fn orient() -> Result { + particles_kernel_orient().map(Compute) + } + + pub fn field() -> Result { + particles_kernel_field().map(Compute) + } + + /// For [`Particles::emit_gpu`]. + pub fn scatter_surface(geometry: &Geometry) -> Result { + particles_scatter_create(geometry.0).map(Compute) + } + + /// For [`Particles::emit_gpu`]. + pub fn scatter_volume(geometry: &Geometry) -> Result { + particles_scatter_volume_create(geometry.0).map(Compute) + } +} + +impl Drop for Particles { + fn drop(&mut self) { + let _ = particles_destroy(self.0); + } +} diff --git a/src/prelude.rs b/src/prelude.rs index cf6287f8..55e69108 100644 --- a/src/prelude.rs +++ b/src/prelude.rs @@ -1,21 +1,9 @@ -pub use bevy::input::keyboard::KeyCode; -pub use bevy::input::mouse::MouseButton; -pub use bevy::prelude::default; -pub use bevy::render::render_resource::TextureFormat; -pub use processing_core::{config::*, constants, error}; -pub use processing_input::*; -#[cfg(not(target_arch = "wasm32"))] -pub use processing_midi::{ - midi_connect, midi_disconnect, midi_list_ports, midi_note_off, midi_note_on, midi_play_notes, - midi_refresh_ports, +#[cfg(feature = "webcam")] +pub use crate::Webcam; +pub use crate::{ + ArcMode, Attribute, AttributeFormat, BlendMode, Buffer, Color, ColorSpace, Compute, Filter, + Font, Geometry, Gltf, Graphics, HALF_PI, Image, Key, Layout, Light, Mat4, Material, + MouseButton, PI, Particles, QUARTER_PI, Result, Settings, Shader, ShapeKind, ShapeMode, Sketch, + StrokeCap, StrokeJoin, TAU, TWO_PI, TextAlignH, TextAlignV, TextStyle, TextWrapMode, Topology, + Vec2, Vec3, Vec4, midi, }; -pub use processing_render::{ - render::command::{ - ArcMode, BlendMode, DrawCommand, LightKind, ShapeKind, ShapeMode, StrokeCapMode, - StrokeJoinMode, TextAlignH, TextAlignV, TextStyle, TextWrapMode, custom_blend_state, - }, - render::filter::Filter, - *, -}; - -pub use crate::{exit, init}; diff --git a/src/shader.rs b/src/shader.rs new file mode 100644 index 00000000..0a64bf76 --- /dev/null +++ b/src/shader.rs @@ -0,0 +1,298 @@ +use bevy::color::{ColorToComponents, LinearRgba}; +use bevy::math::{Mat4, Vec2, Vec3, Vec4}; +use bevy::prelude::Entity; +use processing_core::error::Result; +use processing_render::shader_value::ShaderValue; +use processing_render::{ + buffer_create, buffer_create_with_data, buffer_destroy, buffer_read, buffer_size, buffer_write, + compute_create, compute_destroy, compute_dispatch, compute_set, material_create_custom, + material_create_pbr, material_create_unlit, material_destroy, material_set, + material_set_albedo_buffer, material_set_double_sided, material_set_emissive_buffer, + shader_create, shader_destroy, shader_load, +}; + +use crate::graphics::expect; +use crate::{AsImage, Color}; + +/// WGSL or WESL. +#[derive(Debug)] +pub struct Shader(pub(crate) Entity); + +impl Shader { + pub fn new(source: &str) -> Result { + shader_create(source).map(Self) + } + + pub fn load(path: &str) -> Result { + shader_load(path).map(Self) + } +} + +impl Drop for Shader { + fn drop(&mut self) { + let _ = shader_destroy(self.0); + } +} + +#[derive(Debug)] +pub struct Material(pub(crate) Entity); + +impl Material { + pub fn pbr() -> Result { + material_create_pbr().map(Self) + } + + pub fn unlit() -> Result { + material_create_unlit().map(Self) + } + + pub fn new(shader: &Shader) -> Result { + material_create_custom(shader.0).map(Self) + } + + pub fn set(&mut self, name: &str, value: impl IntoShaderValue) { + expect(material_set(self.0, name, value.into_shader_value())); + } + + /// One RGBA per particle. + pub fn albedo_buffer(&mut self, buffer: &Buffer) { + expect(material_set_albedo_buffer(self.0, buffer.entity)); + } + + /// One RGBA per particle. + pub fn emissive_buffer(&mut self, buffer: &Buffer) { + expect(material_set_emissive_buffer(self.0, buffer.entity)); + } + + pub fn double_sided(&mut self, value: bool) { + expect(material_set_double_sided(self.0, value)); + } +} + +impl Drop for Material { + fn drop(&mut self) { + let _ = material_destroy(self.0); + } +} + +#[derive(Debug)] +pub struct Buffer { + pub(crate) entity: Entity, + owned: bool, +} + +impl Buffer { + /// Zeroed, `size` in bytes. + pub fn new(size: u64) -> Result { + buffer_create(size).map(Self::owned) + } + + pub fn from_slice(data: &[T]) -> Result { + buffer_create_with_data(T::to_bytes(data)).map(Self::owned) + } + + fn owned(entity: Entity) -> Self { + Self { + entity, + owned: true, + } + } + + /// Not destroyed on drop. + pub(crate) fn borrowed(entity: Entity) -> Self { + Self { + entity, + owned: false, + } + } + + /// In bytes. + pub fn size(&self) -> u64 { + expect(buffer_size(self.entity)) + } + + pub fn write(&mut self, data: &[T]) { + expect(buffer_write(self.entity, T::to_bytes(data))); + } + + pub fn read(&self) -> Result> { + Ok(T::from_bytes(&buffer_read(self.entity)?)) + } +} + +impl Drop for Buffer { + fn drop(&mut self) { + if self.owned { + let _ = buffer_destroy(self.entity); + } + } +} + +mod sealed { + pub trait Sealed {} +} + +/// `f32`, `i32`, `u32`, arrays of 2-4 of them, `Vec2`-`Vec4`, or `Color` (linear RGBA). +pub trait BufferElement: sealed::Sealed + Sized { + #[doc(hidden)] + const FLOAT: bool; + #[doc(hidden)] + const COMPONENTS: usize; + #[doc(hidden)] + fn to_bytes(data: &[Self]) -> Vec; + #[doc(hidden)] + fn from_bytes(bytes: &[u8]) -> Vec; +} + +macro_rules! pod_element { + ($($t:ty => $float:expr, $n:expr);* $(;)?) => {$( + impl sealed::Sealed for $t {} + impl BufferElement for $t { + const FLOAT: bool = $float; + const COMPONENTS: usize = $n; + fn to_bytes(data: &[Self]) -> Vec { + bytemuck::cast_slice(data).to_vec() + } + fn from_bytes(bytes: &[u8]) -> Vec { + bytemuck::pod_collect_to_vec(bytes) + } + } + )*}; +} + +macro_rules! buffer_element { + ($($t:ty => $float:expr),*) => {$( + pod_element!($t => $float, 1; [$t; 2] => $float, 2; [$t; 3] => $float, 3; [$t; 4] => $float, 4); + )*}; +} +buffer_element!(f32 => true, i32 => false, u32 => false); +pod_element!(Vec2 => true, 2; Vec3 => true, 3; Vec4 => true, 4); + +impl sealed::Sealed for Color {} +impl BufferElement for Color { + const FLOAT: bool = true; + const COMPONENTS: usize = 4; + fn to_bytes(data: &[Self]) -> Vec { + let linear: Vec<[f32; 4]> = data.iter().map(|c| c.to_linear().to_f32_array()).collect(); + bytemuck::cast_slice(&linear).to_vec() + } + fn from_bytes(bytes: &[u8]) -> Vec { + bytemuck::pod_collect_to_vec::(bytes) + .into_iter() + .map(|c| Color::from_linear(LinearRgba::from_f32_array(c))) + .collect() + } +} + +#[derive(Debug)] +pub struct Compute(pub(crate) Entity); + +impl Compute { + pub fn new(shader: &Shader) -> Result { + compute_create(shader.0).map(Self) + } + + pub fn set(&mut self, name: &str, value: impl IntoShaderValue) { + expect(compute_set(self.0, name, value.into_shader_value())); + } + + /// Blocks until done. + pub fn dispatch(&mut self, x: u32, y: u32, z: u32) { + expect(compute_dispatch(self.0, x, y, z)); + } +} + +impl Drop for Compute { + fn drop(&mut self) { + let _ = compute_destroy(self.0); + } +} + +pub trait IntoShaderValue { + #[doc(hidden)] + fn into_shader_value(self) -> ShaderValue; +} + +impl IntoShaderValue for f32 { + fn into_shader_value(self) -> ShaderValue { + ShaderValue::Float(self) + } +} + +impl IntoShaderValue for f64 { + fn into_shader_value(self) -> ShaderValue { + ShaderValue::Float(self as f32) + } +} + +impl IntoShaderValue for i32 { + fn into_shader_value(self) -> ShaderValue { + ShaderValue::Int(self) + } +} + +impl IntoShaderValue for u32 { + fn into_shader_value(self) -> ShaderValue { + ShaderValue::UInt(self) + } +} + +impl IntoShaderValue for bool { + fn into_shader_value(self) -> ShaderValue { + ShaderValue::UInt(self as u32) + } +} + +impl IntoShaderValue for (f32, f32) { + fn into_shader_value(self) -> ShaderValue { + ShaderValue::Float2([self.0, self.1]) + } +} + +impl IntoShaderValue for (f32, f32, f32) { + fn into_shader_value(self) -> ShaderValue { + ShaderValue::Float3([self.0, self.1, self.2]) + } +} + +impl IntoShaderValue for (f32, f32, f32, f32) { + fn into_shader_value(self) -> ShaderValue { + ShaderValue::Float4([self.0, self.1, self.2, self.3]) + } +} + +impl IntoShaderValue for Vec2 { + fn into_shader_value(self) -> ShaderValue { + ShaderValue::Float2(self.to_array()) + } +} + +impl IntoShaderValue for Vec3 { + fn into_shader_value(self) -> ShaderValue { + ShaderValue::Float3(self.to_array()) + } +} + +impl IntoShaderValue for Vec4 { + fn into_shader_value(self) -> ShaderValue { + ShaderValue::Float4(self.to_array()) + } +} + +impl IntoShaderValue for Mat4 { + fn into_shader_value(self) -> ShaderValue { + ShaderValue::Mat4(self.to_cols_array()) + } +} + +impl IntoShaderValue for &Buffer { + fn into_shader_value(self) -> ShaderValue { + ShaderValue::Buffer(self.entity) + } +} + +impl IntoShaderValue for &T { + fn into_shader_value(self) -> ShaderValue { + ShaderValue::Texture(self.image_entity()) + } +} diff --git a/src/shape.rs b/src/shape.rs new file mode 100644 index 00000000..5506ce22 --- /dev/null +++ b/src/shape.rs @@ -0,0 +1,114 @@ +use std::ops::{Deref, DerefMut}; + +use processing_render::render::command::{DrawCommand, ShapeKind}; + +use crate::{Graphics, Scalar}; + +/// Ends open when dropped. +#[must_use] +pub struct Shape<'g> { + g: &'g mut Graphics, + close: bool, +} + +impl<'g> Shape<'g> { + pub(crate) fn new(g: &'g mut Graphics, kind: ShapeKind) -> Self { + g.record(DrawCommand::BeginShape { kind }); + Self { g, close: false } + } + + pub fn vertex(&self, x: impl Scalar, y: impl Scalar) { + self.g.record(DrawCommand::ShapeVertex { + x: x.to_f32(), + y: y.to_f32(), + }); + } + + pub fn bezier_vertex( + &self, + cx1: impl Scalar, + cy1: impl Scalar, + cx2: impl Scalar, + cy2: impl Scalar, + x: impl Scalar, + y: impl Scalar, + ) { + self.g.record(DrawCommand::ShapeBezierVertex { + cx1: cx1.to_f32(), + cy1: cy1.to_f32(), + cx2: cx2.to_f32(), + cy2: cy2.to_f32(), + x: x.to_f32(), + y: y.to_f32(), + }); + } + + pub fn quadratic_vertex( + &self, + cx: impl Scalar, + cy: impl Scalar, + x: impl Scalar, + y: impl Scalar, + ) { + self.g.record(DrawCommand::ShapeQuadraticVertex { + cx: cx.to_f32(), + cy: cy.to_f32(), + x: x.to_f32(), + y: y.to_f32(), + }); + } + + pub fn curve_vertex(&self, x: impl Scalar, y: impl Scalar) { + self.g.record(DrawCommand::ShapeCurveVertex { + x: x.to_f32(), + y: y.to_f32(), + }); + } + + /// A hole, ended when dropped. + pub fn contour(&mut self) -> Contour<'_, 'g> { + self.g.record(DrawCommand::BeginContour); + Contour { shape: self } + } + + pub fn end(self) {} + + pub fn close(mut self) { + self.close = true; + } +} + +impl Drop for Shape<'_> { + fn drop(&mut self) { + self.g.record(DrawCommand::EndShape { close: self.close }); + } +} + +#[must_use] +pub struct Contour<'s, 'g> { + shape: &'s mut Shape<'g>, +} + +impl Contour<'_, '_> { + pub fn end(self) {} +} + +impl<'g> Deref for Contour<'_, 'g> { + type Target = Shape<'g>; + + fn deref(&self) -> &Shape<'g> { + self.shape + } +} + +impl<'g> DerefMut for Contour<'_, 'g> { + fn deref_mut(&mut self) -> &mut Shape<'g> { + self.shape + } +} + +impl Drop for Contour<'_, '_> { + fn drop(&mut self) { + self.shape.g.record(DrawCommand::EndContour); + } +} diff --git a/src/sketch.rs b/src/sketch.rs new file mode 100644 index 00000000..3ff9e674 --- /dev/null +++ b/src/sketch.rs @@ -0,0 +1,150 @@ +use std::path::PathBuf; + +use bevy::render::render_resource::TextureFormat; +use processing_core::config::{Config, ConfigKey}; +use processing_core::error::Result; +use processing_glfw::GlfwContext; +use processing_render::{advance_frame_count, graphics_create, surface_set_title}; + +use crate::Graphics; + +#[derive(Debug, Clone)] +pub struct Settings { + width: u32, + height: u32, + title: String, + transparent: bool, + headless: bool, + assets: Option, + log_level: Option, +} + +impl Settings { + pub fn size(width: u32, height: u32) -> Self { + Self { + width, + height, + title: "Processing".to_string(), + transparent: false, + headless: false, + assets: None, + log_level: None, + } + } + + pub fn title(mut self, title: impl Into) -> Self { + self.title = title.into(); + self + } + + pub fn transparent(mut self) -> Self { + self.transparent = true; + self + } + + /// No window; runs until [`Graphics::exit`]. + pub fn headless(mut self) -> Self { + self.headless = true; + self + } + + /// The asset directory. + pub fn assets(mut self, dir: impl Into) -> Self { + self.assets = Some(dir.into()); + self + } + + /// A `tracing` filter, e.g. `"warn"`. + pub fn log_level(mut self, level: impl Into) -> Self { + self.log_level = Some(level.into()); + self + } +} + +impl Default for Settings { + fn default() -> Self { + Self::size(100, 100) + } +} + +pub trait Sketch: Sized { + fn settings() -> Settings { + Settings::default() + } + + fn setup(g: &mut Graphics) -> Result; + + fn draw(&mut self, _g: &mut Graphics) {} +} + +pub fn run() -> Result<()> { + let settings = S::settings(); + let mut window = if settings.headless { + None + } else { + Some(GlfwContext::new( + settings.width, + settings.height, + settings.transparent, + )?) + }; + + let mut config = Config::new(); + if let Some(dir) = &settings.assets { + config.set(ConfigKey::AssetRootPath, dir.to_string_lossy().into_owned()); + } + if let Some(level) = &settings.log_level { + config.set(ConfigKey::LogLevel, level.clone()); + } + crate::init(config)?; + + let result = match &mut window { + Some(window) => { + open_window(window, &settings).and_then(|g| run_frames::(g, || window.poll_events())) + } + None => Graphics::create(settings.width, settings.height) + .and_then(|g| run_frames::(g, || true)), + }; + crate::exit(if result.is_ok() { 0 } else { 1 })?; + result +} + +fn open_window(window: &mut GlfwContext, settings: &Settings) -> Result { + let surface = window.create_surface(settings.width, settings.height, settings.transparent)?; + let entity = graphics_create( + surface, + settings.width, + settings.height, + TextureFormat::Rgba16Float, + )?; + surface_set_title(surface, settings.title.clone())?; + Ok(Graphics::new( + entity, + surface, + settings.width, + settings.height, + )) +} + +fn run_frames(mut g: Graphics, mut poll: impl FnMut() -> bool) -> Result<()> { + if !poll() { + return Ok(()); + } + advance_frame_count()?; + g.begin_frame(); + let mut sketch = S::setup(&mut g)?; + sketch.draw(&mut g); + g.end_frame(); + + while !g.exit_requested() && poll() { + advance_frame_count()?; + g.begin_frame(); + sketch.draw(&mut g); + g.end_frame(); + } + + // handles must drop while the app is alive + drop(sketch); + drop(g); + Ok(()) +} diff --git a/src/webcam.rs b/src/webcam.rs new file mode 100644 index 00000000..b505d126 --- /dev/null +++ b/src/webcam.rs @@ -0,0 +1,38 @@ +use bevy::prelude::Entity; +use processing_core::error::Result; +use processing_webcam::{ + webcam_create, webcam_destroy, webcam_image, webcam_is_connected, webcam_resolution, +}; + +use crate::AsImage; +use crate::graphics::expect; + +/// The default camera. +#[derive(Debug)] +pub struct Webcam(Entity); + +impl Webcam { + pub fn new() -> Result { + webcam_create().map(Self) + } + + pub fn connected(&self) -> bool { + expect(webcam_is_connected(self.0)) + } + + pub fn resolution(&self) -> (u32, u32) { + expect(webcam_resolution(self.0)) + } +} + +impl AsImage for Webcam { + fn image_entity(&self) -> Entity { + expect(webcam_image(self.0)) + } +} + +impl Drop for Webcam { + fn drop(&mut self) { + let _ = webcam_destroy(self.0); + } +}