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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions crates/processing_ffi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1135,7 +1135,7 @@ pub extern "C" fn processing_end_contour(graphics_id: u64) {
pub unsafe extern "C" fn processing_load_font(path_ptr: *const std::ffi::c_char) -> u64 {
error::clear_error();
let path = unsafe { std::ffi::CStr::from_ptr(path_ptr) }.to_string_lossy();
error::check(|| font_load(&path).map(|e| e.to_bits())).unwrap_or(0)
error::check(|| font_load(&path, None).map(|e| e.to_bits())).unwrap_or(0)
}

/// Create a font handle from an existing font family name.
Expand All @@ -1147,7 +1147,7 @@ pub unsafe extern "C" fn processing_load_font(path_ptr: *const std::ffi::c_char)
pub unsafe extern "C" fn processing_create_font(name_ptr: *const std::ffi::c_char) -> u64 {
error::clear_error();
let name = unsafe { std::ffi::CStr::from_ptr(name_ptr) }.to_string_lossy();
error::check(|| font_create(&name).map(|e| e.to_bits())).unwrap_or(0)
error::check(|| font_create(&name, None).map(|e| e.to_bits())).unwrap_or(0)
}

/// Query the number of variable font axes for a font.
Expand Down
4 changes: 2 additions & 2 deletions crates/processing_node/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -924,12 +924,12 @@ pub fn js_end_contour(graphics_id: BigInt) -> Result<()> {

#[napi(js_name = "loadFont")]
pub fn js_load_font(path: String) -> Result<BigInt> {
check(font_load(&path)).map(id)
check(font_load(&path, None)).map(id)
}

#[napi(js_name = "createFont")]
pub fn js_create_font(name: String) -> Result<BigInt> {
check(font_create(&name)).map(id)
check(font_create(&name, None)).map(id)
}

#[napi(js_name = "fontVariationCount")]
Expand Down
41 changes: 41 additions & 0 deletions crates/processing_pyo3/processing_py/math.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Processing math methods and vector/quaternion types."""
import math as _math
import random as _random
from decimal import Decimal as _Decimal
from .processing_py import math as _native_math

# extend native math so glob imports work
Expand Down Expand Up @@ -149,6 +150,46 @@ def random_seed(seed):
_random.seed(seed)


def _nf(num, left, right, group=False, plus=""):
if isinstance(num, (list, tuple)):
return [_nf(n, left, right, group, plus) for n in num]
if num != num or num in (float("inf"), float("-inf")):
return str(num)
sign = "-" if num < 0 else plus
num = abs(num)
if right is not None:
text = f"{num:.{int(right)}f}"
elif float(num).is_integer():
text = str(int(num))
else:
text = format(_Decimal(repr(float(num))), "f")
whole, _, fraction = text.partition(".")
whole = whole.zfill(int(left or 0))
if group:
whole = f"{int(whole):,}"
return sign + whole + ("." + fraction if fraction else "")


def nf(num, left=None, right=None):
"""Number to text: at least `left` digits before the point (zero padded), exactly `right` after."""
return _nf(num, left, right)


def nfc(num, right=None):
"""Like `nf()`, with commas between thousands."""
return _nf(num, None, right, group=True)


def nfp(num, left=None, right=None):
"""Like `nf()`, with a `+` in front of positive numbers."""
return _nf(num, left, right, plus="+")


def nfs(num, left=None, right=None):
"""Like `nf()`, with a space in front of positive numbers."""
return _nf(num, left, right, plus=" ")


def bezier_point(a, b, c, d, t):
u = 1.0 - t
return a * u * u * u + 3 * b * t * u * u + 3 * c * t * t * u + d * t * t * t
Expand Down
52 changes: 41 additions & 11 deletions crates/processing_pyo3/src/graphics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1823,14 +1823,18 @@ impl Graphics {

// --- Font ---

pub fn load_font(&self, path: &str) -> PyResult<Font> {
font_load(path)
/// `size` is the text size `text_font(font)` sets along with the font.
#[pyo3(signature = (path, size=None))]
pub fn load_font(&self, path: &str, size: Option<f32>) -> PyResult<Font> {
font_load(path, size)
.map(|entity| Font { entity })
.map_err(|e| PyRuntimeError::new_err(format!("{e}")))
}

pub fn create_font(&self, name: &str) -> PyResult<Font> {
font_create(name)
/// `size` is the text size `text_font(font)` sets along with the font.
#[pyo3(signature = (name, size=None))]
pub fn create_font(&self, name: &str, size: Option<f32>) -> PyResult<Font> {
font_create(name, size)
.map(|entity| Font { entity })
.map_err(|e| PyRuntimeError::new_err(format!("{e}")))
}
Expand All @@ -1839,10 +1843,29 @@ impl Graphics {
font_list().map_err(|e| PyRuntimeError::new_err(format!("{e}")))
}

#[pyo3(signature = (font=None))]
pub fn text_font(&self, font: Option<&Font>) -> PyResult<()> {
graphics_text_font(self.entity, font.map(|f| f.entity))
.map_err(|e| PyRuntimeError::new_err(format!("{e}")))
/// `font` is a `Font` or a family name; `None` restores the default font.
#[pyo3(signature = (font=None, size=None))]
pub fn text_font(&self, font: Option<&Bound<'_, PyAny>>, size: Option<f32>) -> PyResult<()> {
let result = match font {
None => graphics_text_font(self.entity, None),
Some(font) => {
if let Ok(name) = font.extract::<String>() {
graphics_text_font_family(self.entity, &name)
} else {
let font = font.cast::<Font>().map_err(|_| {
pyo3::exceptions::PyTypeError::new_err(
"text_font() expects a Font or a font name",
)
})?;
graphics_text_font(self.entity, Some(font.borrow().entity))
}
}
};
result.map_err(|e| PyRuntimeError::new_err(format!("{e}")))?;
match size {
Some(size) => self.text_size(Some(size)).map(|_| ()),
None => Ok(()),
}
}

// --- Text ---
Expand Down Expand Up @@ -2022,9 +2045,16 @@ impl Graphics {
.map_err(|e| PyRuntimeError::new_err(format!("{e}")))
}

pub fn text_size(&self, size: f32) -> PyResult<()> {
graphics_record_command(self.entity, DrawCommand::TextSize(size))
.map_err(|e| PyRuntimeError::new_err(format!("{e}")))
/// Sets the text size; with no argument, returns the current one.
#[pyo3(signature = (size=None))]
pub fn text_size(&self, size: Option<f32>) -> PyResult<Option<f32>> {
match size {
Some(size) => {
graphics_record_command(self.entity, DrawCommand::TextSize(size)).map(|_| None)
}
None => graphics_text_size(self.entity).map(Some),
}
.map_err(|e| PyRuntimeError::new_err(format!("{e}")))
}

#[pyo3(signature = (h, v=None))]
Expand Down
26 changes: 15 additions & 11 deletions crates/processing_pyo3/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2255,8 +2255,8 @@ pub mod processing_py {
}

#[pyfunction]
#[pyo3(pass_module)]
fn text_size(module: &Bound<'_, PyModule>, size: f32) -> PyResult<()> {
#[pyo3(pass_module, signature = (size=None))]
fn text_size(module: &Bound<'_, PyModule>, size: Option<f32>) -> PyResult<Option<f32>> {
graphics!(module).text_size(size)
}

Expand All @@ -2273,9 +2273,13 @@ pub mod processing_py {
}

#[pyfunction]
#[pyo3(pass_module, signature = (font=None))]
fn text_font(module: &Bound<'_, PyModule>, font: Option<&Font>) -> PyResult<()> {
graphics!(module).text_font(font)
#[pyo3(pass_module, signature = (font=None, size=None))]
fn text_font(
module: &Bound<'_, PyModule>,
font: Option<&Bound<'_, PyAny>>,
size: Option<f32>,
) -> PyResult<()> {
graphics!(module).text_font(font, size)
}

#[pyfunction]
Expand Down Expand Up @@ -2377,15 +2381,15 @@ pub mod processing_py {
}

#[pyfunction]
#[pyo3(pass_module)]
fn load_font(module: &Bound<'_, PyModule>, path: &str) -> PyResult<Font> {
graphics!(module).load_font(path)
#[pyo3(pass_module, signature = (path, size=None))]
fn load_font(module: &Bound<'_, PyModule>, path: &str, size: Option<f32>) -> PyResult<Font> {
graphics!(module).load_font(path, size)
}

#[pyfunction]
#[pyo3(pass_module)]
fn create_font(module: &Bound<'_, PyModule>, name: &str) -> PyResult<Font> {
graphics!(module).create_font(name)
#[pyo3(pass_module, signature = (name, size=None))]
fn create_font(module: &Bound<'_, PyModule>, name: &str, size: Option<f32>) -> PyResult<Font> {
graphics!(module).create_font(name, size)
}

#[pyfunction]
Expand Down
67 changes: 59 additions & 8 deletions crates/processing_render/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2727,38 +2727,67 @@ pub fn compute_destroy(entity: Entity) -> error::Result<()> {
///
/// Reading fonts from the filesystem is not available on wasm; callers should
/// register font bytes through another path there.
pub fn font_load(path: &str) -> error::Result<Entity> {
pub fn font_load(path: &str, size: Option<f32>) -> error::Result<Entity> {
use text::font::{Font, TextContext};

#[cfg(target_arch = "wasm32")]
{
let _ = path;
let _ = (path, size);
return Err(error::ProcessingError::FontLoadError(
"loading fonts from a file is not supported on wasm".to_string(),
));
}

#[cfg(not(target_arch = "wasm32"))]
{
let data = std::fs::read(path)
.map_err(|e| error::ProcessingError::FontLoadError(format!("{}: {}", path, e)))?;
use bevy::asset::{AssetPath, io::AssetSourceId};
use processing_core::config::{Config, ConfigKey};

app_mut(|app| {
// read through the asset server, so paths resolve like images do
let asset_path = AssetPath::parse(path);
let source = match app
.world()
.resource::<Config>()
.get(ConfigKey::AssetRootPath)
{
Some(_) => AssetSourceId::from("assets_directory"),
None => asset_path.source().clone_owned(),
};
let server = app.world().resource::<AssetServer>().clone();
let failed = |e: &dyn std::fmt::Display| {
error::ProcessingError::FontLoadError(format!("{path}: {e}"))
};
let data = bevy::tasks::block_on(async {
let source = server.get_source(source).map_err(|e| failed(&e))?;
let mut reader = source
.reader()
.read(asset_path.path())
.await
.map_err(|e| failed(&e))?;
let mut data = Vec::new();
reader
.read_to_end(&mut data)
.await
.map_err(|e| failed(&e))?;
error::Result::Ok(data)
})?;

let text_cx = app.world().resource::<TextContext>().clone();
let family_name =
text_cx
.load_font(data)
.ok_or(error::ProcessingError::FontLoadError(
"Could not determine font family name".to_string(),
))?;
let entity = app.world_mut().spawn(Font { family_name }).id();
let entity = app.world_mut().spawn(Font { family_name, size }).id();
Ok(entity)
})
}
}

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

app_mut(|app| {
Expand All @@ -2767,7 +2796,7 @@ pub fn font_create(name: &str) -> error::Result<Entity> {
warn!("font {name:?} is not installed, using the default font");
DEFAULT_FONT_FAMILY.to_string()
});
let entity = app.world_mut().spawn(Font { family_name }).id();
let entity = app.world_mut().spawn(Font { family_name, size }).id();
Ok(entity)
})
}
Expand Down Expand Up @@ -2824,6 +2853,28 @@ pub fn graphics_text_font(
graphics_record_command(graphics_entity, DrawCommand::TextFont(font_entity))
}

/// Sets the font by family name; an unknown family falls back to the default font.
pub fn graphics_text_font_family(graphics_entity: Entity, name: &str) -> error::Result<()> {
use text::font::{DEFAULT_FONT_FAMILY, TextContext};

let family = app_mut(|app| {
let text_cx = app.world().resource::<TextContext>().clone();
Ok(text_cx.resolve_family(name).unwrap_or_else(|| {
warn_once!("font {name:?} is not installed, using the default font");
DEFAULT_FONT_FAMILY.to_string()
}))
})?;
graphics_record_command(graphics_entity, DrawCommand::TextFontFamily(family))
}

/// The current text size, including changes queued this frame.
pub fn graphics_text_size(graphics_entity: Entity) -> error::Result<f32> {
app_mut(|app| {
let (params, _) = text_query_state(app, graphics_entity, None, None)?;
Ok(params.text_size)
})
}

pub fn graphics_text_style(graphics_entity: Entity, style: u8) -> error::Result<()> {
use render::command::TextStyle;
graphics_record_command(
Expand Down Expand Up @@ -2924,7 +2975,7 @@ fn text_query_state(
cmd => render::apply_text_style_command(&mut style, cmd.clone(), |entity| {
world
.get::<text::font::Font>(entity)
.map(|f| f.family_name.clone())
.map(|f| (f.family_name.clone(), f.size))
}),
}
}
Expand Down
1 change: 1 addition & 0 deletions crates/processing_render/src/render/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -758,6 +758,7 @@ pub enum DrawCommand {
radius: f32,
},
TextFont(Option<Entity>),
TextFontFamily(String),
TextStyle(TextStyle),
TextWeight(f32),
TextVariation {
Expand Down
16 changes: 13 additions & 3 deletions crates/processing_render/src/render/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,18 +123,24 @@ impl BatchState {
pub(crate) fn apply_text_style_command(
style: &mut StyleStack,
cmd: DrawCommand,
font_family: impl Fn(Entity) -> Option<String>,
font: impl Fn(Entity) -> Option<(String, Option<f32>)>,
) {
match cmd {
DrawCommand::TextFont(font_entity) => {
if let Some(entity) = font_entity {
if let Some(family) = font_family(entity) {
if let Some((family, size)) = font(entity) {
style.text_font_family = Some(family);
// a sized font brings its size, as in Processing
if let Some(size) = size {
style.text_size = size;
style.text_leading = None;
}
}
} else {
style.text_font_family = None;
}
}
DrawCommand::TextFontFamily(family) => style.text_font_family = Some(family),
DrawCommand::TextStyle(text_style) => style.text_style = text_style,
DrawCommand::TextWeight(weight) => style.text_weight = Some(weight),
DrawCommand::TextVariation { tag, value } => {
Expand Down Expand Up @@ -1324,6 +1330,7 @@ pub fn flush_draw_commands(
);
}
cmd @ (DrawCommand::TextFont(_)
| DrawCommand::TextFontFamily(_)
| DrawCommand::TextStyle(_)
| DrawCommand::TextWeight(_)
| DrawCommand::TextVariation { .. }
Expand All @@ -1337,7 +1344,10 @@ pub fn flush_draw_commands(
| DrawCommand::TextWrap(_)
| DrawCommand::TextGlyphColors(_)) => {
apply_text_style_command(&mut state.style, cmd, |entity| {
p_fonts.get(entity).ok().map(|f| f.family_name.clone())
p_fonts
.get(entity)
.ok()
.map(|f| (f.family_name.clone(), f.size))
});
}
DrawCommand::Text {
Expand Down
Loading
Loading