mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-20 22:40:44 +01:00
Merge pull request #67 from storytold/tools/text-alpha
Text: any installed font as a brush alpha or a decal
This commit is contained in:
30 files changed
+759
-11
No files matched your search
+1
-1
@@ -32,7 +32,7 @@ These come from Rust crate dependencies (not files in this repository) and keep
|
||||
| Asset | Used for | Author | Source | License |
|
||||
|---|---|---|---|---|
|
||||
| Phosphor Icons (regular), via the `egui-phosphor` crate (vendored in `vendor/egui-phosphor` for egui 0.37) | Every UI icon (tools, layers, panels) | Phosphor Icons (Helena Zhang, Tobias Fried) | https://phosphoricons.com, https://github.com/amPerl/egui-phosphor | MIT (icons); crate MIT OR Apache-2.0 |
|
||||
| egui default fonts (Ubuntu-Light, Hack, Noto Emoji, emoji-icon-font), via `epaint_default_fonts` | UI text | Canonical / Source Foundry / Google / Jessie Jung | https://github.com/emilk/egui | Ubuntu Font Licence 1.0, MIT + Bitstream Vera License, OFL 1.1, MIT |
|
||||
| egui default fonts (Ubuntu-Light, Hack, Noto Emoji, emoji-icon-font), via `epaint_default_fonts` | UI text; Ubuntu Light and Hack also as the built-in fonts for text alphas and decals | Canonical / Source Foundry / Google / Jessie Jung | https://github.com/emilk/egui | Ubuntu Font Licence 1.0, MIT + Bitstream Vera License, OFL 1.1, MIT |
|
||||
| Only in builds made with `CRAFT_FONTS_DIR`: Inter Regular and SemiBold (desktop and web), from storytold/craft-fonts' Latin catalog (`crates/ui-egui/build.rs`) | Interface text | The Inter Project Authors | https://github.com/storytold/craft-fonts (pinned sources in its `fonts/latin-manifest.txt` and `ATTRIBUTION.md`) | OFL 1.1 |
|
||||
| Only in builds made with `CRAFT_FONTS_DIR`: BIZ UDPGothic Regular (desktop and web), Noto Sans CJK SC Regular (desktop) and Noto Sans Arabic Regular (desktop and web), from storytold/craft-fonts (`crates/ui-egui/build.rs`) | Japanese, Chinese and Arabic UI text | The BIZ UDGothic Project Authors (Morisawa Inc.); The Noto Project Authors | https://github.com/storytold/craft-fonts (pinned sources in its `fonts/manifest.txt` and `ATTRIBUTION.md`) | OFL 1.1 |
|
||||
|
||||
|
||||
Generated
+4
@@ -3896,6 +3896,7 @@ dependencies = [
|
||||
name = "texturecraft-engine"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"epaint_default_fonts",
|
||||
"image",
|
||||
"rayon",
|
||||
"serde",
|
||||
@@ -3949,8 +3950,11 @@ dependencies = [
|
||||
name = "texturecraft-paint"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"epaint_default_fonts",
|
||||
"harfrust",
|
||||
"rayon",
|
||||
"serde",
|
||||
"skrifa 0.44.0",
|
||||
"texturecraft-compose",
|
||||
"texturecraft-core",
|
||||
"texturecraft-geom",
|
||||
|
||||
@@ -32,6 +32,11 @@ serde_json = "1"
|
||||
glam = { version = "0.30", features = ["serde", "bytemuck"] }
|
||||
bytemuck = { version = "1", features = ["derive"] }
|
||||
rayon = "1"
|
||||
# Text alphas: shaping and glyph outlines, the versions egui's text layout already builds.
|
||||
harfrust = "0.12"
|
||||
skrifa = { version = "0.44", default-features = false, features = ["std"] }
|
||||
# The UI's built-in fonts (Ubuntu Light, Hack): text alphas fall back to them without system fonts.
|
||||
epaint_default_fonts = "0.37"
|
||||
log = "0.4"
|
||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "tga", "tiff", "exr", "hdr", "bmp", "webp"] }
|
||||
half = "2"
|
||||
|
||||
+1
-1
@@ -14,7 +14,7 @@ end to end today (engine + UI + automation + tests), not what is planned.
|
||||
| Project and files | 8 | 95% | New project from glTF/GLB, FBX (binary and ASCII, 6.x and 7.x), COLLADA, **USD (usda, usdc, usdz)**, **Alembic (Ogawa)**, OBJ, PLY, STL or built-in meshes (auto-unwrap when UVs are missing; a `.gltf`'s buffers and images and a loose USD layer's textures are read from its folder and kept in the project), **project templates** (built-in and saved from a project), `.tcraft` open/save/save as/save a copy, autosave, recent files, drag and drop, reimport mesh **with strokes preserved on the surface**, image resources, remove unused resources, OBJ, textured GLB and **USD** mesh export, browser open/save/download | HDF5 Alembic; Alembic animation (first sample only) |
|
||||
| Texture sets | 6 | 95% | One set per material, **UDIM / UV tiles** (auto-detected or switched on later with resampling, **a resolution per tile**, one texture per tile at its own size, `$udim` export), list with visibility, sizes 128–8192 with resampling, add/remove channels (19 channel types incl. coat, sheen, anisotropy and scattering), height strength, normal format | Filter radii and height slopes of a tile smaller than its atlas block follow the block |
|
||||
| Layer stack | 16 | 96% | Paint, fill, folder and **instance** layers; 32 per-channel blend modes and opacities; white/black/painted masks with **mask with height**; generator, fill, levels, invert/threshold, color selection, compare, blur, sharpen and HSL effects on masks and layer content; anchor points; smart masks; mask view (Alt+click); duplicate, group, drag to reorder, rename, color tags, copy/cut/paste (also as instance) across sets, flatten, instantiate across sets, save layers as smart materials; **27 library filters** (adjustments, blur/sharpen/high pass, bevel, glow, edge detect, warps, mosaic, baked lighting, material finishes); **geometry masks** (a layer on chosen mesh parts) | A few niche filters of the reference app's catalog |
|
||||
| Painting tools | 14 | 88% | Paint, eraser, projection with image stencils, polygon fill, **path** and **lasso fill**, smudge, clone, color picker, quick mask, Shift+click lines with preview, 2D view painting; size, flow, stroke opacity, spacing, hardness, angle, follow path, jitters, alignment, angle fade, backface culling, lazy mouse, X/Y/Z mirror and **radial symmetry**, pen pressure, procedural and image alphas, **particle brush** | Pen tilt (not exposed by the windowing layer) |
|
||||
| Painting tools | 14 | 88% | Paint, eraser, projection with image stencils, polygon fill, **path** and **lasso fill**, smudge, clone, color picker, quick mask, Shift+click lines with preview, 2D view painting; size, flow, stroke opacity, spacing, hardness, angle, follow path, jitters, alignment, angle fade, backface culling, lazy mouse, X/Y/Z mirror and **radial symmetry**, pen pressure, procedural and image alphas, **text** in any installed font (as an alpha or a decal), **particle brush** | Pen tilt (not exposed by the windowing layer) |
|
||||
| Materials and assets | 8 | 86% | 48 procedural materials (incl. car paint, velvet, brushed steel, skin, wax), 21 smart materials, 18 smart masks, **67 procedural brush alphas**, 22 procedurals, 6 environments plus imported HDR/EXR panoramas, image resources, a user smart material library, a tabbed shelf with search and **drag and drop** onto layers and the viewport | A smaller bundled library than the reference app's |
|
||||
| Baking | 10 | 100% | AO, curvature (also from the normal map), thickness, world normal, position, ID, normal, height, **bent normals, opacity, color map and world-space direction**; **high-poly meshes**, cage, frontal/rear distances, average normals, **match by mesh name**; per-texture-set selection, common and per-map parameters, progress and cancel; high-poly base color textures embedded or in files beside a `.gltf`, FBX or USD layer | — |
|
||||
| Viewport and display | 12 | 95% | PBR with image-based lighting, 6 procedural environments or imported HDR/EXR panoramas with exposure, rotation, blur, opacity, ACES/linear tone mapping, HDR pipeline with bloom, vignette, sharpen and grain, key-light shadows, 4× MSAA plus idle temporal accumulation, channel / mesh-map / mask / UV checker views, 3D and 2D wireframes, brush cursor, axis gizmos, subsurface scattering blur, **depth of field**, saved cameras and cameras from glTF, FBX, COLLADA and USD files, displacement (also in shadows and the path tracers), **path-traced Rendering mode** (F10, on the GPU or the CPU) with environment importance sampling and an edge-aware **denoiser** | Hardware ray tracing |
|
||||
|
||||
@@ -17,6 +17,7 @@ texturecraft-paint = { workspace = true }
|
||||
texturecraft-bake = { workspace = true }
|
||||
texturecraft-formats = { workspace = true }
|
||||
rayon = { workspace = true }
|
||||
epaint_default_fonts = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
|
||||
@@ -73,6 +73,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(crate::smart_masks::specs());
|
||||
v.extend(crate::filter_lib::specs());
|
||||
v.extend(crate::decal_cmds::specs());
|
||||
v.extend(crate::text_cmds::specs());
|
||||
v
|
||||
})
|
||||
}
|
||||
|
||||
@@ -35,6 +35,7 @@ pub mod session;
|
||||
pub mod set_cmds;
|
||||
pub mod smart_masks;
|
||||
pub mod template_cmds;
|
||||
pub mod text_cmds;
|
||||
pub mod tool_cmds;
|
||||
pub mod uv_tile_cmds;
|
||||
pub mod view_cmds;
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
//! Text: an image resource drawn from text in an installed font (or a built-in one), to stamp
|
||||
//! with the brush as its alpha or to place as a decal.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_paint::text::render_text;
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, color_param, f32p, strp};
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!("text.fonts", "List fonts", [], None, "{} — the installed font families with their styles, and the built-in ones", always, |_, _| Ok(fonts())),
|
||||
cmd!(
|
||||
"resource.text",
|
||||
"Add text",
|
||||
[],
|
||||
None,
|
||||
"{text (lines split at \\n), font?: family (text.fonts; default a common sans-serif), style?: e.g. Bold (default Regular), size?: 8..1024 texels per em (default 256), color?: [r,g,b] linear or \"#rrggbb\" (default white), name?} — draws the text as an image resource with an alpha (white for tool.brush {alpha: {image}}, colored for layer.add.decal)",
|
||||
always,
|
||||
add_text
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// Fonts bundled with the app (egui's), used when nothing is installed or in the browser.
|
||||
const BUILT_IN: [(&str, &[u8]); 2] = [("Ubuntu Light", epaint_default_fonts::UBUNTU_LIGHT), ("Hack", epaint_default_fonts::HACK_REGULAR)];
|
||||
/// Families tried, in order, when no font is asked for.
|
||||
const DEFAULT_FAMILIES: [&str; 6] = ["Arial", "Segoe UI", "Helvetica", "Liberation Sans", "DejaVu Sans", "Noto Sans"];
|
||||
/// Largest font file read.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const MAX_FONT_BYTES: u64 = 128 << 20;
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn installed() -> &'static [texturecraft_formats::fonts::FontFace] {
|
||||
static FONTS: std::sync::OnceLock<Vec<texturecraft_formats::fonts::FontFace>> = std::sync::OnceLock::new();
|
||||
FONTS.get_or_init(texturecraft_formats::fonts::system_fonts)
|
||||
}
|
||||
|
||||
fn fonts() -> Value {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let families = {
|
||||
let mut out: Vec<(String, Vec<String>)> = Vec::new();
|
||||
for f in installed() {
|
||||
match out.last_mut() {
|
||||
Some((family, styles)) if *family == f.family => styles.push(f.style.clone()),
|
||||
_ => out.push((f.family.clone(), vec![f.style.clone()])),
|
||||
}
|
||||
}
|
||||
out
|
||||
};
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let families: Vec<(String, Vec<String>)> = Vec::new();
|
||||
json!({
|
||||
"installed": families.into_iter().map(|(family, styles)| json!({"family": family, "styles": styles})).collect::<Vec<_>>(),
|
||||
"builtIn": BUILT_IN.map(|(name, _)| name),
|
||||
})
|
||||
}
|
||||
|
||||
/// The bytes and face index of `family` in `style` (a regular face when the style is missing),
|
||||
/// or the first default family installed, else the built-in font.
|
||||
fn font_bytes(family: Option<&str>, style: Option<&str>) -> Result<(std::borrow::Cow<'static, [u8]>, u32)> {
|
||||
let is = |a: &str, b: &str| a.eq_ignore_ascii_case(b);
|
||||
if let Some((_, bytes)) = BUILT_IN.iter().find(|(name, _)| family.is_some_and(|f| is(f, name))) {
|
||||
return Ok((std::borrow::Cow::Borrowed(bytes), 0));
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let faces = installed();
|
||||
let pick = |family: &str| {
|
||||
let of: Vec<_> = faces.iter().filter(|f| is(&f.family, family)).collect();
|
||||
let regular = ["Regular", "Normal", "Book", "Roman"];
|
||||
let found = style.and_then(|s| of.iter().find(|f| is(&f.style, s)));
|
||||
found.or_else(|| of.iter().find(|f| regular.iter().any(|r| is(&f.style, r)))).or(of.first()).copied()
|
||||
};
|
||||
let face = match family {
|
||||
Some(f) => Some(pick(f).ok_or_else(|| bad("resource.text", format!("no font family `{f}` (see text.fonts)")))?),
|
||||
None => DEFAULT_FAMILIES.iter().find_map(|f| pick(f)),
|
||||
};
|
||||
if let Some(face) = face {
|
||||
let size = std::fs::metadata(&face.path).map(|m| m.len()).unwrap_or(u64::MAX);
|
||||
if size > MAX_FONT_BYTES {
|
||||
return Err(bad("resource.text", format!("{} is too large", face.path.display())));
|
||||
}
|
||||
let bytes = std::fs::read(&face.path).map_err(|e| bad("resource.text", format!("cannot read {}: {e}", face.path.display())))?;
|
||||
return Ok((std::borrow::Cow::Owned(bytes), face.index));
|
||||
}
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let _ = style;
|
||||
match family {
|
||||
Some(f) => Err(bad("resource.text", format!("no font family `{f}` (see text.fonts)"))),
|
||||
None => Ok((std::borrow::Cow::Borrowed(BUILT_IN[0].1), 0)),
|
||||
}
|
||||
}
|
||||
|
||||
fn add_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "resource.text";
|
||||
let text = strp(p, "text").ok_or_else(|| bad(cmd, "`text` is required"))?;
|
||||
let (font, index) = font_bytes(strp(p, "font"), strp(p, "style"))?;
|
||||
let size = f32p(p, "size").unwrap_or(256.0).clamp(8.0, 1024.0);
|
||||
let img = render_text(&font, index, text, size).map_err(|e| bad(cmd, e))?;
|
||||
let rgb = color_param(p, "color").unwrap_or([1.0; 3]).map(|c| (texturecraft_texel::linear_to_srgb(c.clamp(0.0, 1.0)) * 255.0).round() as u8);
|
||||
let png = texturecraft_formats::coverage_png(img.width, img.height, &img.coverage, rgb).map_err(|e| bad(cmd, e.to_string()))?;
|
||||
// The resource is named after the text (its first line, shortened) unless a name is given.
|
||||
let label: String = strp(p, "name").unwrap_or_else(|| text.lines().next().unwrap_or_default()).chars().take(32).collect();
|
||||
let name = s.import_resource_bytes(&format!("Text {}.png", label.trim()), png)?;
|
||||
Ok(json!({ "name": name, "width": img.width, "height": img.height }))
|
||||
}
|
||||
@@ -165,6 +165,28 @@ fn image_resources_fill_layers_and_round_trip() {
|
||||
assert!(s.import_resource_bytes("bad.png", vec![1, 2, 3]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_becomes_a_brush_alpha_and_a_decal() {
|
||||
let mut s = session();
|
||||
let fonts = execute(&mut s, "text.fonts", &Value::Null).unwrap();
|
||||
assert_eq!(fonts["builtIn"][0], "Ubuntu Light");
|
||||
let r = execute(&mut s, "resource.text", &json!({"text": "TEXT\nCRAFT", "font": "ubuntu light", "size": 64})).unwrap();
|
||||
let name = r["name"].as_str().unwrap().to_string();
|
||||
assert_eq!(name, "Text_TEXT.png");
|
||||
assert!(r["width"].as_u64().unwrap() > r["height"].as_u64().unwrap() / 2, "two short lines");
|
||||
// White with the glyphs in alpha.
|
||||
let img = s.images[&name].clone();
|
||||
assert!(img.rgba.iter().any(|t| t[3] > 0.99) && img.rgba.iter().any(|t| t[3] == 0.0) && img.rgba.iter().all(|t| t[0] == 1.0));
|
||||
// As the brush alpha it paints (keeping its proportions), and it places as a decal.
|
||||
execute(&mut s, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap();
|
||||
execute(&mut s, "tool.brush", &json!({"size": 40, "alpha": {"image": name}})).unwrap();
|
||||
assert!(execute(&mut s, "tool.click", &json!({"x": 200, "y": 200})).is_ok());
|
||||
assert!(execute(&mut s, "layer.add.decal", &json!({"image": name})).unwrap()["layer"].as_u64().is_some());
|
||||
for bad in [json!({}), json!({"text": " "}), json!({"text": "x", "font": "No Such Font"})] {
|
||||
assert!(execute(&mut s, "resource.text", &bad).is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn projection_tool_paints_the_stencil_colors() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
//! Installed fonts, for text alphas: the faces (family and style) of every TrueType or OpenType
|
||||
//! file (and collection) in the system's font folders, read from each file's `name` table only,
|
||||
//! so listing hundreds of fonts stays quick. Native only; the browser has no font folders.
|
||||
|
||||
use std::io::{Read, Seek, SeekFrom};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// One face of an installed font file.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub struct FontFace {
|
||||
pub family: String,
|
||||
pub style: String,
|
||||
pub path: PathBuf,
|
||||
/// Face index in a collection (`.ttc`), else 0.
|
||||
pub index: u32,
|
||||
}
|
||||
|
||||
/// Files and faces visited at most (a font folder is never this large, a wrong one may be).
|
||||
const MAX_FILES: usize = 20_000;
|
||||
const MAX_FACES_PER_FILE: u32 = 64;
|
||||
const MAX_NAME_TABLE: u32 = 1 << 20;
|
||||
|
||||
/// The installed fonts' faces, sorted by family then style.
|
||||
pub fn system_fonts() -> Vec<FontFace> {
|
||||
let mut files = Vec::new();
|
||||
for dir in font_dirs() {
|
||||
collect(&dir, 0, &mut files);
|
||||
}
|
||||
let mut faces: Vec<FontFace> = files.iter().flat_map(|p| faces_of(p).unwrap_or_default()).collect();
|
||||
faces.sort();
|
||||
faces.dedup_by(|a, b| a.family == b.family && a.style == b.style);
|
||||
faces
|
||||
}
|
||||
|
||||
fn font_dirs() -> Vec<PathBuf> {
|
||||
let home = std::env::var_os("HOME").map(PathBuf::from);
|
||||
if cfg!(windows) {
|
||||
let mut v = vec![PathBuf::from(std::env::var_os("WINDIR").unwrap_or_else(|| "C:\\Windows".into())).join("Fonts")];
|
||||
v.extend(std::env::var_os("LOCALAPPDATA").map(|d| PathBuf::from(d).join("Microsoft\\Windows\\Fonts")));
|
||||
v
|
||||
} else if cfg!(target_os = "macos") {
|
||||
let mut v = vec![PathBuf::from("/System/Library/Fonts"), PathBuf::from("/Library/Fonts")];
|
||||
v.extend(home.map(|h| h.join("Library/Fonts")));
|
||||
v
|
||||
} else {
|
||||
let mut v = vec![PathBuf::from("/usr/share/fonts"), PathBuf::from("/usr/local/share/fonts")];
|
||||
v.extend(home.iter().flat_map(|h| [h.join(".local/share/fonts"), h.join(".fonts")]));
|
||||
v
|
||||
}
|
||||
}
|
||||
|
||||
/// Font files under `dir` (a few levels deep).
|
||||
fn collect(dir: &Path, depth: usize, out: &mut Vec<PathBuf>) {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return };
|
||||
for e in entries.flatten() {
|
||||
if out.len() >= MAX_FILES {
|
||||
return;
|
||||
}
|
||||
let path = e.path();
|
||||
match e.file_type() {
|
||||
Ok(t) if t.is_dir() && depth < 4 => collect(&path, depth + 1, out),
|
||||
Ok(t) if t.is_file() => {
|
||||
let ext = path.extension().and_then(|x| x.to_str()).unwrap_or_default().to_ascii_lowercase();
|
||||
if matches!(ext.as_str(), "ttf" | "otf" | "ttc" | "otc") {
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The faces of the font file at `path` (each face of a collection).
|
||||
pub fn faces_of(path: &Path) -> std::io::Result<Vec<FontFace>> {
|
||||
let mut f = std::fs::File::open(path)?;
|
||||
let mut at = |offset: u64, len: usize| -> std::io::Result<Vec<u8>> {
|
||||
f.seek(SeekFrom::Start(offset))?;
|
||||
let mut buf = vec![0; len];
|
||||
f.read_exact(&mut buf)?;
|
||||
Ok(buf)
|
||||
};
|
||||
let head = at(0, 12)?;
|
||||
let offsets: Vec<u64> = if head.get(..4) == Some(b"ttcf") {
|
||||
let n = u32_at(&head, 8).unwrap_or(0).min(MAX_FACES_PER_FILE);
|
||||
let table = at(12, 4 * n as usize)?;
|
||||
(0..n as usize).filter_map(|i| u32_at(&table, 4 * i)).map(u64::from).collect()
|
||||
} else {
|
||||
vec![0]
|
||||
};
|
||||
let mut faces = Vec::new();
|
||||
for (index, offset) in offsets.into_iter().enumerate() {
|
||||
let dir = at(offset, 12)?;
|
||||
let tables = at(offset + 12, 16 * usize::from(u16_at(&dir, 4).unwrap_or(0)))?;
|
||||
let Some(rec) = tables.chunks_exact(16).find(|r| r.get(..4) == Some(b"name")) else { continue };
|
||||
let (Some(off), Some(len)) = (u32_at(rec, 8), u32_at(rec, 12)) else { continue };
|
||||
let names = at(u64::from(off), len.min(MAX_NAME_TABLE) as usize)?;
|
||||
let name = |ids: [u16; 2]| ids.iter().find_map(|id| name_string(&names, *id));
|
||||
if let Some(family) = name([16, 1]) {
|
||||
let style = name([17, 2]).unwrap_or_else(|| "Regular".into());
|
||||
faces.push(FontFace { family, style, path: path.to_path_buf(), index: index as u32 });
|
||||
}
|
||||
}
|
||||
Ok(faces)
|
||||
}
|
||||
|
||||
fn u16_at(b: &[u8], o: usize) -> Option<u16> {
|
||||
Some(u16::from_be_bytes(b.get(o..o.checked_add(2)?)?.try_into().ok()?))
|
||||
}
|
||||
|
||||
fn u32_at(b: &[u8], o: usize) -> Option<u32> {
|
||||
Some(u32::from_be_bytes(b.get(o..o.checked_add(4)?)?.try_into().ok()?))
|
||||
}
|
||||
|
||||
/// Name `id` of a `name` table, in English when it has several languages: Windows and Unicode
|
||||
/// records are UTF-16BE, Macintosh ones single-byte (read as Latin-1).
|
||||
fn name_string(t: &[u8], id: u16) -> Option<String> {
|
||||
let (count, base) = (usize::from(u16_at(t, 2)?), usize::from(u16_at(t, 4)?));
|
||||
let mut best: Option<(u8, String)> = None;
|
||||
for r in (0..count).filter_map(|i| t.get(6 + 12 * i..18 + 12 * i)) {
|
||||
let (platform, language, name_id) = (u16_at(r, 0)?, u16_at(r, 4)?, u16_at(r, 6)?);
|
||||
let (len, off) = (usize::from(u16_at(r, 8)?), usize::from(u16_at(r, 10)?));
|
||||
let Some(bytes) = t.get(base + off..base + off + len) else { continue };
|
||||
if name_id != id {
|
||||
continue;
|
||||
}
|
||||
let (rank, s) = match platform {
|
||||
3 | 0 => {
|
||||
let s = String::from_utf16_lossy(&bytes.chunks_exact(2).map(|c| u16::from_be_bytes([c[0], c[1]])).collect::<Vec<_>>());
|
||||
(if language == 0x409 { 0 } else { 1 }, s)
|
||||
}
|
||||
1 => (if language == 0 { 2 } else { 3 }, bytes.iter().map(|b| char::from(*b)).collect()),
|
||||
_ => continue,
|
||||
};
|
||||
let s = s.trim().to_string();
|
||||
if !s.is_empty() && best.as_ref().is_none_or(|(r, _)| rank < *r) {
|
||||
best = Some((rank, s));
|
||||
}
|
||||
}
|
||||
best.map(|(_, s)| s)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A `name` table with the given (platform, language, name id, bytes) records.
|
||||
fn name_table(records: &[(u16, u16, u16, Vec<u8>)]) -> Vec<u8> {
|
||||
let base = 6 + 12 * records.len();
|
||||
let mut t: Vec<u8> = [0u16, records.len() as u16, base as u16].iter().flat_map(|v| v.to_be_bytes()).collect();
|
||||
let mut strings: Vec<u8> = Vec::new();
|
||||
for (platform, language, id, bytes) in records {
|
||||
for v in [*platform, 1, *language, *id, bytes.len() as u16, strings.len() as u16] {
|
||||
t.extend(v.to_be_bytes());
|
||||
}
|
||||
strings.extend(bytes);
|
||||
}
|
||||
t.extend(strings);
|
||||
t
|
||||
}
|
||||
|
||||
fn utf16(s: &str) -> Vec<u8> {
|
||||
s.encode_utf16().flat_map(u16::to_be_bytes).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_prefer_english_windows_records() {
|
||||
let t =
|
||||
name_table(&[(1, 0, 1, b"Mac Name".to_vec()), (3, 0x407, 1, utf16("Deutsch")), (3, 0x409, 1, utf16("Plain Sans")), (3, 0x409, 2, utf16("Bold"))]);
|
||||
assert_eq!(name_string(&t, 1).as_deref(), Some("Plain Sans"));
|
||||
assert_eq!(name_string(&t, 2).as_deref(), Some("Bold"));
|
||||
assert_eq!(name_string(&t, 16), None);
|
||||
// Truncated or hostile tables give nothing rather than panicking.
|
||||
for n in 0..t.len() {
|
||||
let _ = name_string(&t[..n], 1);
|
||||
}
|
||||
assert_eq!(name_string(&[0xff; 64], 1), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn faces_of_a_file_and_garbage() {
|
||||
let dir = std::env::temp_dir().join(format!("tc-fonts-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("font.ttf");
|
||||
// A font file with only a name table: offset table, one table record, the table.
|
||||
let names = name_table(&[(3, 0x409, 1, utf16("Plain Sans")), (3, 0x409, 2, utf16("Italic"))]);
|
||||
let mut file: Vec<u8> = [0x0001_0000u32.to_be_bytes().to_vec(), 1u16.to_be_bytes().to_vec(), vec![0; 6]].concat();
|
||||
file.extend(b"name");
|
||||
file.extend([0u32, 28, names.len() as u32].iter().flat_map(|v| v.to_be_bytes()));
|
||||
file.extend(&names);
|
||||
std::fs::write(&path, &file).unwrap();
|
||||
let faces = faces_of(&path).unwrap();
|
||||
assert_eq!((faces[0].family.as_str(), faces[0].style.as_str(), faces[0].index), ("Plain Sans", "Italic", 0));
|
||||
std::fs::write(&path, b"garbage").unwrap();
|
||||
assert!(faces_of(&path).is_err() || faces_of(&path).unwrap().is_empty());
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,17 @@ pub fn decode_image(bytes: &[u8]) -> Result<DecodedImage> {
|
||||
Ok(DecodedImage { width, height, rgba, srgb })
|
||||
}
|
||||
|
||||
/// PNG bytes of an `rgb` (sRGB) image whose alpha is `coverage` (`width × height`, top row first):
|
||||
/// drawn text as an image resource.
|
||||
pub fn coverage_png(width: u32, height: u32, coverage: &[u8], rgb: [u8; 3]) -> Result<Vec<u8>> {
|
||||
let rgba: Vec<u8> = coverage.iter().flat_map(|a| [rgb[0], rgb[1], rgb[2], *a]).collect();
|
||||
let img = image::RgbaImage::from_raw(width, height, rgba)
|
||||
.ok_or_else(|| FormatError::Invalid(format!("{} coverage values for {width}x{height}", coverage.len())))?;
|
||||
let mut png = Vec::new();
|
||||
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| FormatError::Invalid(e.to_string()))?;
|
||||
Ok(png)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -44,5 +55,8 @@ mod tests {
|
||||
assert!((d.rgba[1][0] - 60.0 / 255.0).abs() < 1e-3);
|
||||
assert!(decode_image(b"not an image").is_err());
|
||||
assert!(decode_image(&png[..png.len() / 2]).is_err());
|
||||
let text = decode_image(&coverage_png(2, 1, &[0, 255], [255; 3]).unwrap()).unwrap();
|
||||
assert_eq!(text.rgba, vec![[1.0, 1.0, 1.0, 0.0], [1.0; 4]]);
|
||||
assert!(coverage_png(2, 2, &[0], [255; 3]).is_err());
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@
|
||||
//! - [`presets`]: the built-in export presets and JSON (de)serialization of user presets.
|
||||
//! - [`project_file`]: the `.tcraft` project zip (project JSON, sparse lossless pixel tiles,
|
||||
//! baked maps, the original mesh and a thumbnail).
|
||||
//! - `fonts`: the installed fonts' families and styles (native only), for text alphas.
|
||||
//!
|
||||
//! Every reader takes untrusted bytes and returns an error, never panics. Byte-based functions
|
||||
//! work everywhere (including the web build); path-based ones are native only.
|
||||
@@ -22,6 +23,8 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
pub mod export;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod fonts;
|
||||
pub mod image_res;
|
||||
pub mod mesh_export;
|
||||
pub mod mesh_import;
|
||||
@@ -31,7 +34,7 @@ pub mod project_file;
|
||||
pub use export::{
|
||||
Dest, ExportInput, ExportOptions, ExportPreset, ExportedFile, FileFormat, MapSpec, Padding, PlannedFile, SourceRef, VirtualMap, list_outputs, render_maps,
|
||||
};
|
||||
pub use image_res::{DecodedImage, decode_image};
|
||||
pub use image_res::{DecodedImage, coverage_png, decode_image};
|
||||
pub use mesh_export::{GlbTextures, UsdExport, UsdFormat, glb_bytes, glb_export_options, obj_bytes, usd_bytes, usd_export_options};
|
||||
pub use mesh_import::{HighPolyMesh, ImportedMesh, MeshFile, MeshReport, import_high_poly_bytes, import_mesh_bytes, self_contained_mesh};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
|
||||
@@ -14,4 +14,9 @@ texturecraft-texel = { workspace = true }
|
||||
texturecraft-geom = { workspace = true }
|
||||
texturecraft-compose = { workspace = true }
|
||||
rayon = { workspace = true }
|
||||
harfrust = { workspace = true }
|
||||
skrifa = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
epaint_default_fonts = { workspace = true }
|
||||
@@ -112,12 +112,15 @@ impl Shape<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// An image as a brush alpha: luminance × alpha over the stamp square (−1..1, y up), 0 outside.
|
||||
/// An image as a brush alpha: luminance × alpha, its longer side across the stamp square (−1..1,
|
||||
/// y up) so it keeps its proportions (a line of text stays a line), 0 outside.
|
||||
pub fn image_alpha(img: &ImageRes, lx: f32, ly: f32) -> f32 {
|
||||
if !(lx.abs() <= 1.0 && ly.abs() <= 1.0) {
|
||||
let aspect = img.width as f32 / img.height.max(1) as f32;
|
||||
let (x, y) = if aspect >= 1.0 { (lx, ly * aspect) } else { (lx / aspect.max(1e-6), ly) };
|
||||
if !(x.abs() <= 1.0 && y.abs() <= 1.0) {
|
||||
return 0.0;
|
||||
}
|
||||
let [r, g, b, a] = img.sample(lx * 0.5 + 0.5, 0.5 - ly * 0.5);
|
||||
let [r, g, b, a] = img.sample(x * 0.5 + 0.5, 0.5 - y * 0.5);
|
||||
((0.2126 * r + 0.7152 * g + 0.0722 * b) * a).clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,8 @@
|
||||
//! see ([`EyeDepth`]); [`commit`] blends the finished stroke into layer pixels. Clone and smudge
|
||||
//! strokes carry channel values ([`pickup`]) instead of painting the tool's material.
|
||||
//! [`path`] samples the Path tool's curves and lasso coverage; [`particles`] runs the particle
|
||||
//! brush; [`alphas`] is the built-in library of procedural brush alphas.
|
||||
//! brush; [`alphas`] is the built-in library of procedural brush alphas; [`text`] draws text for
|
||||
//! text alphas and decals.
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
@@ -18,6 +19,7 @@ pub mod path;
|
||||
pub mod pickup;
|
||||
pub mod raster;
|
||||
pub mod stroke;
|
||||
pub mod text;
|
||||
pub mod visibility;
|
||||
|
||||
pub use brush::{Alignment, BrushAlpha, BrushSettings, Particles, Shape, Symmetry, image_alpha};
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
//! Text as a coverage image, for brush alphas and decals: each line shaped with harfrust
|
||||
//! (kerning, ligatures, joined scripts), drawn from the font's outlines (skrifa) and filled with
|
||||
//! a non-zero scanline rasterizer, lines centered.
|
||||
|
||||
use harfrust::{FontRef, ShapeOptions, ShaperData, UnicodeBuffer};
|
||||
use skrifa::MetadataProvider;
|
||||
use skrifa::instance::{LocationRef, Size};
|
||||
use skrifa::outline::{DrawSettings, OutlinePen};
|
||||
|
||||
/// Longest text drawn (characters).
|
||||
pub const MAX_TEXT_CHARS: usize = 1000;
|
||||
/// Largest side of a text image (texels); bigger layouts are drawn smaller to fit.
|
||||
pub const MAX_TEXT_SIDE: u32 = 4096;
|
||||
/// Vertical samples per texel row.
|
||||
const SUBROWS: usize = 4;
|
||||
|
||||
/// A shaped glyph: its id and pen position (font units).
|
||||
type Placed = (u32, f32, f32);
|
||||
|
||||
/// Coverage 0..=255 per texel, rows top to bottom.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct TextImage {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub coverage: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Draw `text` (one or more lines) with face `index` of `font` at `px` texels per em, cropped to
|
||||
/// the ink with a margin of a tenth of an em.
|
||||
pub fn render_text(font: &[u8], index: u32, text: &str, px: f32) -> Result<TextImage, String> {
|
||||
let text = text.trim_end();
|
||||
if text.trim().is_empty() {
|
||||
return Err("the text is empty".into());
|
||||
}
|
||||
if text.chars().count() > MAX_TEXT_CHARS {
|
||||
return Err(format!("the text is longer than {MAX_TEXT_CHARS} characters"));
|
||||
}
|
||||
let font = FontRef::from_index(font, index).map_err(|e| format!("not a usable font: {e}"))?;
|
||||
// Layout in font units; `scale` turns them into texels.
|
||||
let m = font.metrics(Size::unscaled(), LocationRef::default());
|
||||
let upem = f32::from(m.units_per_em.max(1));
|
||||
let line = (m.ascent - m.descent + m.leading).max(upem * 0.5);
|
||||
let data = ShaperData::new(&font);
|
||||
let shaper = data.shaper(&font).build();
|
||||
let mut lines: Vec<(f32, Vec<Placed>)> = Vec::new();
|
||||
for t in text.lines() {
|
||||
let mut buffer = UnicodeBuffer::new();
|
||||
buffer.push_str(t);
|
||||
buffer.guess_segment_properties();
|
||||
let shaped = shaper.shape(buffer, ShapeOptions::new());
|
||||
let mut x = 0.0;
|
||||
let mut glyphs = Vec::new();
|
||||
for (info, pos) in shaped.glyph_infos().iter().zip(shaped.glyph_positions()) {
|
||||
glyphs.push((info.glyph_id, x + pos.x_offset as f32, pos.y_offset as f32));
|
||||
x += pos.x_advance as f32;
|
||||
}
|
||||
lines.push((x, glyphs));
|
||||
}
|
||||
let widest = lines.iter().map(|(w, _)| *w).fold(0.0, f32::max);
|
||||
let px = px.clamp(4.0, 1024.0);
|
||||
// Outlines in texels (y down) at the shaped positions, lines centered on the widest.
|
||||
let outlines = font.outline_glyphs();
|
||||
let mut pen = Edges { scale: px / upem, ..Edges::default() };
|
||||
for (row, (line_width, glyphs)) in lines.iter().enumerate() {
|
||||
let left = (widest - line_width) * 0.5;
|
||||
for &(id, x, y) in glyphs {
|
||||
let Some(glyph) = outlines.get(skrifa::GlyphId::new(id)) else { continue };
|
||||
pen.origin = ((left + x) * pen.scale, (line * row as f32 - y) * pen.scale);
|
||||
// A glyph that can't be drawn is left out rather than failing the text.
|
||||
let _ = glyph.draw(DrawSettings::unhinted(Size::unscaled(), LocationRef::default()), &mut pen);
|
||||
pen.close();
|
||||
}
|
||||
}
|
||||
// The image is the ink's bounds plus the margin (accents and descenders never clip), scaled
|
||||
// down when that is too large.
|
||||
let points = || pen.edges.iter().flat_map(|e| [(e[0], e[1]), (e[2], e[3])]);
|
||||
let lo = points().fold((f32::MAX, f32::MAX), |a, p| (a.0.min(p.0), a.1.min(p.1)));
|
||||
let hi = points().fold((f32::MIN, f32::MIN), |a, p| (a.0.max(p.0), a.1.max(p.1)));
|
||||
if pen.edges.is_empty() || !(lo.0.is_finite() && hi.0.is_finite() && lo.1.is_finite() && hi.1.is_finite()) {
|
||||
return Err("the font draws nothing for this text".into());
|
||||
}
|
||||
let margin = px * 0.1;
|
||||
let (w, h) = (hi.0 - lo.0 + 2.0 * margin, hi.1 - lo.1 + 2.0 * margin);
|
||||
let fit = (MAX_TEXT_SIDE as f32 / w.max(h)).min(1.0);
|
||||
let edges: Vec<[f32; 4]> = pen
|
||||
.edges
|
||||
.iter()
|
||||
.map(|e| [(e[0] - lo.0 + margin) * fit, (e[1] - lo.1 + margin) * fit, (e[2] - lo.0 + margin) * fit, (e[3] - lo.1 + margin) * fit])
|
||||
.collect();
|
||||
let (width, height) = ((w * fit).ceil().max(1.0) as u32, (h * fit).ceil().max(1.0) as u32);
|
||||
Ok(TextImage { width, height, coverage: fill(&edges, width as usize, height as usize) })
|
||||
}
|
||||
|
||||
/// Line segments (texel space, y down) collected from glyph outlines: font units times `scale`
|
||||
/// from `origin`, curves flattened.
|
||||
#[derive(Default)]
|
||||
struct Edges {
|
||||
scale: f32,
|
||||
origin: (f32, f32),
|
||||
start: (f32, f32),
|
||||
at: (f32, f32),
|
||||
edges: Vec<[f32; 4]>,
|
||||
}
|
||||
|
||||
impl Edges {
|
||||
fn map(&self, x: f32, y: f32) -> (f32, f32) {
|
||||
(self.origin.0 + x * self.scale, self.origin.1 - y * self.scale)
|
||||
}
|
||||
|
||||
fn segment(&mut self, to: (f32, f32)) {
|
||||
if to != self.at {
|
||||
self.edges.push([self.at.0, self.at.1, to.0, to.1]);
|
||||
}
|
||||
self.at = to;
|
||||
}
|
||||
|
||||
/// Flatten a curve given as a point function of t in 0..1, finer for longer curves.
|
||||
fn curve(&mut self, control_length: f32, point: impl Fn(f32) -> (f32, f32)) {
|
||||
let steps = (control_length.sqrt() * 2.0).clamp(2.0, 64.0) as usize;
|
||||
for i in 1..=steps {
|
||||
self.segment(point(i as f32 / steps as f32));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn dist(a: (f32, f32), b: (f32, f32)) -> f32 {
|
||||
(a.0 - b.0).hypot(a.1 - b.1)
|
||||
}
|
||||
|
||||
impl OutlinePen for Edges {
|
||||
fn move_to(&mut self, x: f32, y: f32) {
|
||||
self.close();
|
||||
self.start = self.map(x, y);
|
||||
self.at = self.start;
|
||||
}
|
||||
|
||||
fn line_to(&mut self, x: f32, y: f32) {
|
||||
let p = self.map(x, y);
|
||||
self.segment(p);
|
||||
}
|
||||
|
||||
fn quad_to(&mut self, cx0: f32, cy0: f32, x: f32, y: f32) {
|
||||
let (p0, c, p) = (self.at, self.map(cx0, cy0), self.map(x, y));
|
||||
self.curve(dist(p0, c) + dist(c, p), |t| {
|
||||
let s = 1.0 - t;
|
||||
(s * s * p0.0 + 2.0 * s * t * c.0 + t * t * p.0, s * s * p0.1 + 2.0 * s * t * c.1 + t * t * p.1)
|
||||
});
|
||||
}
|
||||
|
||||
fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, x: f32, y: f32) {
|
||||
let (p0, c0, c1, p) = (self.at, self.map(cx0, cy0), self.map(cx1, cy1), self.map(x, y));
|
||||
self.curve(dist(p0, c0) + dist(c0, c1) + dist(c1, p), |t| {
|
||||
let s = 1.0 - t;
|
||||
let (a, b, c, d) = (s * s * s, 3.0 * s * s * t, 3.0 * s * t * t, t * t * t);
|
||||
(a * p0.0 + b * c0.0 + c * c1.0 + d * p.0, a * p0.1 + b * c0.1 + c * c1.1 + d * p.1)
|
||||
});
|
||||
}
|
||||
|
||||
fn close(&mut self) {
|
||||
self.segment(self.start);
|
||||
}
|
||||
}
|
||||
|
||||
/// Non-zero winding coverage of closed `edges` over a `w × h` grid: [`SUBROWS`] scanlines per
|
||||
/// row, each span's ends spread over the texels they cross.
|
||||
fn fill(edges: &[[f32; 4]], w: usize, h: usize) -> Vec<u8> {
|
||||
let mut acc = vec![0f32; w * h];
|
||||
// Edges by their top, and the ones the current scanline may cross.
|
||||
let mut sorted: Vec<[f32; 4]> = edges.iter().copied().filter(|e| e[1] != e[3]).collect();
|
||||
sorted.sort_by(|a, b| a[1].min(a[3]).total_cmp(&b[1].min(b[3])));
|
||||
let (mut next, mut active) = (0, Vec::new());
|
||||
let mut crossings: Vec<(f32, i32)> = Vec::new();
|
||||
for row in 0..h {
|
||||
for sub in 0..SUBROWS {
|
||||
let y = row as f32 + (sub as f32 + 0.5) / SUBROWS as f32;
|
||||
while let Some(e) = sorted.get(next).filter(|e| e[1].min(e[3]) <= y) {
|
||||
active.push(*e);
|
||||
next += 1;
|
||||
}
|
||||
active.retain(|e| e[1].max(e[3]) > y);
|
||||
crossings.clear();
|
||||
for &[x0, y0, x1, y1] in &active {
|
||||
if (y0 <= y) != (y1 <= y) {
|
||||
crossings.push((x0 + (y - y0) / (y1 - y0) * (x1 - x0), if y1 > y0 { 1 } else { -1 }));
|
||||
}
|
||||
}
|
||||
crossings.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let mut winding = 0;
|
||||
for pair in crossings.windows(2) {
|
||||
winding += pair[0].1;
|
||||
if winding != 0 {
|
||||
span(&mut acc[row * w..(row + 1) * w], pair[0].0, pair[1].0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
acc.iter().map(|c| (c / SUBROWS as f32 * 255.0).round().clamp(0.0, 255.0) as u8).collect()
|
||||
}
|
||||
|
||||
/// Add the covered length of `x0..x1` to each texel of `row`.
|
||||
fn span(row: &mut [f32], x0: f32, x1: f32) {
|
||||
let (x0, x1) = (x0.clamp(0.0, row.len() as f32), x1.clamp(0.0, row.len() as f32));
|
||||
if x1 <= x0 {
|
||||
return;
|
||||
}
|
||||
for (i, c) in row.iter_mut().enumerate().take(x1.ceil() as usize).skip(x0.floor() as usize) {
|
||||
*c += (x1.min(i as f32 + 1.0) - x0.max(i as f32)).max(0.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn spans_spread_partial_texels() {
|
||||
let mut row = [0.0; 4];
|
||||
span(&mut row, 0.5, 2.25);
|
||||
assert_eq!(row, [0.5, 1.0, 0.25, 0.0]);
|
||||
// A square drawn either way round fills the same texels.
|
||||
let square = |cw: bool| {
|
||||
let p = [(1.0, 1.0), (3.0, 1.0), (3.0, 3.0), (1.0, 3.0)];
|
||||
let p: Vec<_> = if cw { p.to_vec() } else { p.iter().rev().copied().collect() };
|
||||
(0..4).map(|i| [p[i].0, p[i].1, p[(i + 1) % 4].0, p[(i + 1) % 4].1]).collect::<Vec<_>>()
|
||||
};
|
||||
let a = fill(&square(true), 4, 4);
|
||||
assert_eq!(a, fill(&square(false), 4, 4));
|
||||
assert_eq!((a[5], a[0], a[3 * 4 + 3]), (255, 0, 0), "inside full, outside empty");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_is_laid_out_and_filled() {
|
||||
let font = epaint_default_fonts::UBUNTU_LIGHT;
|
||||
let one = render_text(font, 0, "H", 64.0).unwrap();
|
||||
let two = render_text(font, 0, "HH", 64.0).unwrap();
|
||||
let lines = render_text(font, 0, "H\nH", 64.0).unwrap();
|
||||
assert!(two.width > one.width && two.height == one.height);
|
||||
assert!(lines.height > one.height && lines.width == one.width, "lines stack");
|
||||
let ink = |t: &TextImage| t.coverage.iter().map(|c| u32::from(*c)).sum::<u32>();
|
||||
assert!(ink(&two) > ink(&one) * 19 / 10 && ink(&two) < ink(&one) * 21 / 10, "two H, twice the ink");
|
||||
assert!(one.coverage.contains(&255) && one.coverage.contains(&0));
|
||||
// The margin stays clear; huge sizes are drawn to fit.
|
||||
assert!(one.coverage[..one.width as usize].iter().all(|c| *c == 0));
|
||||
let big = render_text(font, 0, &"W".repeat(400), 1024.0).unwrap();
|
||||
assert!(big.width <= MAX_TEXT_SIDE && big.height >= 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_input_is_an_error() {
|
||||
assert!(render_text(b"not a font", 0, "Hi", 64.0).is_err());
|
||||
assert!(render_text(b"", 0, " ", 64.0).is_err());
|
||||
assert!(render_text(b"", 0, &"x".repeat(MAX_TEXT_CHARS + 1), 64.0).is_err());
|
||||
}
|
||||
}
|
||||
@@ -1114,7 +1114,8 @@ fn alpha_tile(ui: &mut Ui, on: bool, label: &str, paint: impl FnOnce(&egui::Pain
|
||||
p.rect_stroke(rect, 3.0, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside);
|
||||
}
|
||||
paint(p, Rect::from_center_size(rect.center() - vec2(0.0, 7.0), vec2(40.0, 40.0)));
|
||||
p.text(rect.center_bottom() - vec2(0.0, 6.0), egui::Align2::CENTER_CENTER, label, egui::FontId::proportional(9.5), tk.viewport_text);
|
||||
let name = elided(p, label, 9.5, tk.viewport_text, rect.width() - 4.0);
|
||||
p.galley(rect.center_bottom() - vec2(name.size().x * 0.5, 6.0 + name.size().y * 0.5), name, tk.viewport_text);
|
||||
resp.on_hover_text(label)
|
||||
}
|
||||
|
||||
@@ -1163,6 +1164,62 @@ fn alpha_section(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
}
|
||||
ui.label(RichText::new(tr("More in Assets > Alphas: click one, or drag it here")).size(10.0).color(tk.text_dim));
|
||||
crate::shelf::drop_target(app, ui, &zone.response, crate::shelf::DropZone::Brush);
|
||||
section(ui, "sec_text", tr("Text"), true, |ui| text_section(app, ui));
|
||||
}
|
||||
|
||||
/// Text drawn in a font, as the brush alpha or a decal (`resource.text`).
|
||||
fn text_section(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
if app.ui.text.fonts.is_empty()
|
||||
&& let Some(f) = app.run("text.fonts", Value::Null)
|
||||
{
|
||||
let installed = f["installed"].as_array().into_iter().flatten().map(|v| {
|
||||
let styles = v["styles"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect();
|
||||
(v["family"].as_str().unwrap_or_default().to_string(), styles)
|
||||
});
|
||||
let built_in = f["builtIn"].as_array().into_iter().flatten().filter_map(Value::as_str).map(|n| (n.to_string(), Vec::new()));
|
||||
app.ui.text.fonts = installed.chain(built_in).collect();
|
||||
}
|
||||
// A decal shows the text in the tool's base color; an alpha must stay white.
|
||||
let color = app.session.tool.values.get(&Channel::BaseColor).copied().unwrap_or([1.0; 3]);
|
||||
let t = &mut app.ui.text;
|
||||
ui.add(egui::TextEdit::multiline(&mut t.text).desired_rows(2).desired_width(f32::INFINITY).hint_text(tr("Text")));
|
||||
let shown = if t.font.is_empty() { tr("Default").to_string() } else { t.font.clone() };
|
||||
combo(ui, tr("Font"), shown, |ui| {
|
||||
if ui.selectable_label(t.font.is_empty(), tr("Default")).clicked() {
|
||||
(t.font, t.style) = (String::new(), String::new());
|
||||
}
|
||||
for (family, _) in &t.fonts {
|
||||
if ui.selectable_label(t.font == *family, family).clicked() {
|
||||
(t.font, t.style) = (family.clone(), String::new());
|
||||
}
|
||||
}
|
||||
});
|
||||
let styles = t.fonts.iter().find(|(f, _)| *f == t.font).map(|(_, s)| s.clone()).unwrap_or_default();
|
||||
if styles.len() > 1 {
|
||||
let shown = if t.style.is_empty() { tr("Default").to_string() } else { t.style.clone() };
|
||||
combo(ui, tr("Style"), shown, |ui| {
|
||||
for s in styles {
|
||||
ui.selectable_value(&mut t.style, s.clone(), s);
|
||||
}
|
||||
});
|
||||
}
|
||||
let mut params = json!({"text": t.text, "font": (!t.font.is_empty()).then_some(&t.font), "style": (!t.style.is_empty()).then_some(&t.style)});
|
||||
let ready = !t.text.trim().is_empty();
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
let alpha = ui.add_enabled(ready, egui::Button::new(tr("Use as brush alpha"))).clicked();
|
||||
let decal = ui.add_enabled(ready, egui::Button::new(tr("Place as decal"))).clicked();
|
||||
if decal {
|
||||
params["color"] = json!(color);
|
||||
}
|
||||
if (alpha || decal)
|
||||
&& let Some(name) = app.run("resource.text", params).and_then(|r| r["name"].as_str().map(str::to_string))
|
||||
{
|
||||
match alpha {
|
||||
true => app.run("tool.brush", json!({"alpha": {"image": name}})),
|
||||
false => app.run("layer.add.decal", json!({"image": name})),
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn material_section(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
|
||||
@@ -924,4 +924,9 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Use the operating system's window frame and buttons instead of TextureCraft's own title bar",
|
||||
"استخدام إطار وأزرار نافذة نظام التشغيل بدلاً من شريط عنوان TextureCraft الخاص",
|
||||
),
|
||||
("Text", "نص"),
|
||||
("Font", "الخط"),
|
||||
("Style", "النمط"),
|
||||
("Use as brush alpha", "استخدام كألفا للفرشاة"),
|
||||
("Place as decal", "وضع كملصق"),
|
||||
];
|
||||
@@ -979,4 +979,9 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Use the operating system's window frame and buttons instead of TextureCraft's own title bar",
|
||||
"Fensterrahmen und Fenstertasten des Betriebssystems statt der eigenen Titelleiste von TextureCraft verwenden",
|
||||
),
|
||||
("Text", "Text"),
|
||||
("Font", "Schrift"),
|
||||
("Style", "Schnitt"),
|
||||
("Use as brush alpha", "Als Pinsel-Alpha verwenden"),
|
||||
("Place as decal", "Als Decal platzieren"),
|
||||
];
|
||||
@@ -964,4 +964,9 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Use the operating system's window frame and buttons instead of TextureCraft's own title bar",
|
||||
"Usar el marco y los botones de ventana del sistema operativo en lugar de la barra de título propia de TextureCraft",
|
||||
),
|
||||
("Text", "Texto"),
|
||||
("Font", "Fuente"),
|
||||
("Style", "Estilo"),
|
||||
("Use as brush alpha", "Usar como alfa del pincel"),
|
||||
("Place as decal", "Colocar como calcomanía"),
|
||||
];
|
||||
@@ -979,4 +979,9 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Use the operating system's window frame and buttons instead of TextureCraft's own title bar",
|
||||
"Utiliser le cadre et les boutons de fenêtre du système d'exploitation au lieu de la barre de titre de TextureCraft",
|
||||
),
|
||||
("Text", "Texte"),
|
||||
("Font", "Police"),
|
||||
("Style", "Style"),
|
||||
("Use as brush alpha", "Utiliser comme alpha du pinceau"),
|
||||
("Place as decal", "Placer en décalque"),
|
||||
];
|
||||
@@ -973,4 +973,9 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Use the operating system's window frame and buttons instead of TextureCraft's own title bar",
|
||||
"Usa la cornice e i pulsanti della finestra del sistema operativo invece della barra del titolo di TextureCraft",
|
||||
),
|
||||
("Text", "Testo"),
|
||||
("Font", "Carattere"),
|
||||
("Style", "Stile"),
|
||||
("Use as brush alpha", "Usa come alpha del pennello"),
|
||||
("Place as decal", "Posiziona come decal"),
|
||||
];
|
||||
@@ -946,4 +946,9 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Use the operating system's window frame and buttons instead of TextureCraft's own title bar",
|
||||
"TextureCraft 独自のタイトルバーの代わりに、OS のウィンドウ枠とボタンを使います",
|
||||
),
|
||||
("Text", "テキスト"),
|
||||
("Font", "フォント"),
|
||||
("Style", "スタイル"),
|
||||
("Use as brush alpha", "ブラシのアルファとして使用"),
|
||||
("Place as decal", "デカールとして配置"),
|
||||
];
|
||||
@@ -931,4 +931,9 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Use the operating system's window frame and buttons instead of TextureCraft's own title bar",
|
||||
"TextureCraft 자체 제목 표시줄 대신 운영 체제의 창 테두리와 버튼을 사용합니다",
|
||||
),
|
||||
("Text", "텍스트"),
|
||||
("Font", "글꼴"),
|
||||
("Style", "스타일"),
|
||||
("Use as brush alpha", "브러시 알파로 사용"),
|
||||
("Place as decal", "데칼로 배치"),
|
||||
];
|
||||
@@ -961,4 +961,9 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Use the operating system's window frame and buttons instead of TextureCraft's own title bar",
|
||||
"Usar a moldura e os botões de janela do sistema operacional em vez da barra de título própria do TextureCraft",
|
||||
),
|
||||
("Text", "Texto"),
|
||||
("Font", "Fonte"),
|
||||
("Style", "Estilo"),
|
||||
("Use as brush alpha", "Usar como alpha do pincel"),
|
||||
("Place as decal", "Colocar como decalque"),
|
||||
];
|
||||
@@ -877,4 +877,9 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
"Use the operating system's window frame and buttons instead of TextureCraft's own title bar",
|
||||
"使用操作系统的窗口边框和按钮,而不是 TextureCraft 自己的标题栏",
|
||||
),
|
||||
("Text", "文字"),
|
||||
("Font", "字体"),
|
||||
("Style", "样式"),
|
||||
("Use as brush alpha", "用作笔刷 Alpha"),
|
||||
("Place as decal", "作为贴花放置"),
|
||||
];
|
||||
@@ -15,6 +15,18 @@ pub enum Mode {
|
||||
Rendering,
|
||||
}
|
||||
|
||||
/// The Alpha tab's text: what to draw and in which font (empty: the default font).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct TextUi {
|
||||
pub text: String,
|
||||
pub font: String,
|
||||
pub style: String,
|
||||
/// Installed and built-in families with their styles (`text.fonts`), read when first shown.
|
||||
#[serde(skip)]
|
||||
pub fonts: Vec<(String, Vec<String>)>,
|
||||
}
|
||||
|
||||
/// Rendering mode settings.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
@@ -209,6 +221,8 @@ pub struct UiState {
|
||||
#[serde(default)]
|
||||
pub shelf_tab: usize,
|
||||
pub props_tab: PropsTab,
|
||||
#[serde(default)]
|
||||
pub text: TextUi,
|
||||
/// Layer being renamed and the edit buffer.
|
||||
pub rename: Option<(u64, String)>,
|
||||
pub new_project: NewProject,
|
||||
@@ -263,6 +277,7 @@ impl Default for UiState {
|
||||
shelf_filter: String::new(),
|
||||
shelf_tab: 0,
|
||||
props_tab: PropsTab::Brush,
|
||||
text: TextUi::default(),
|
||||
rename: None,
|
||||
new_project: NewProject::default(),
|
||||
uv_wireframe: true,
|
||||
|
||||
@@ -114,11 +114,18 @@ impl Thumbs {
|
||||
return t.clone();
|
||||
}
|
||||
let n = 64usize;
|
||||
// Letterboxed to keep its proportions, over black where it is transparent.
|
||||
let aspect = img.width as f32 / img.height.max(1) as f32;
|
||||
let (sx, sy) = if aspect >= 1.0 { (1.0, aspect) } else { (1.0 / aspect.max(1e-6), 1.0) };
|
||||
let mut ci = ColorImage::filled([n, n], Color32::BLACK);
|
||||
for y in 0..n {
|
||||
for x in 0..n {
|
||||
let s = img.sample((x as f32 + 0.5) / n as f32, (y as f32 + 0.5) / n as f32);
|
||||
let enc = |v: f32| if img.srgb { (v.clamp(0.0, 1.0) * 255.0) as u8 } else { (linear_to_srgb(v) * 255.0) as u8 };
|
||||
let (u, v) = (((x as f32 + 0.5) / n as f32 - 0.5) * sx + 0.5, ((y as f32 + 0.5) / n as f32 - 0.5) * sy + 0.5);
|
||||
if !((0.0..=1.0).contains(&u) && (0.0..=1.0).contains(&v)) {
|
||||
continue;
|
||||
}
|
||||
let s = img.sample(u, v);
|
||||
let enc = |c: f32| if img.srgb { (c.clamp(0.0, 1.0) * s[3].clamp(0.0, 1.0) * 255.0) as u8 } else { (linear_to_srgb(c * s[3]) * 255.0) as u8 };
|
||||
ci.pixels[y * n + x] = Color32::from_rgb(enc(s[0]), enc(s[1]), enc(s[2]));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -109,7 +109,8 @@ print(call("command.run", {"id": "layer.add.fill", "params": {"color": [0.8, 0.1
|
||||
|
||||
Through `command_run`, every `file.*` command but `file.close` (and `file.reimportMesh` without
|
||||
a `path`) is refused, and so is any command given a `path` or `dir` (`resource.import`,
|
||||
`material.save`, `material.load`, …), in both modes: use the workspace tools below.
|
||||
`material.save`, `material.load`, …), in both modes: use the workspace tools below. `resource.text`
|
||||
takes a font family, not a path: it reads only the system's font folders.
|
||||
|
||||
| Tool | Params | Notes |
|
||||
|---|---|---|
|
||||
|
||||
@@ -14,6 +14,9 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA
|
||||
straight lines, and painting directly in the **2D UV view**.
|
||||
- **Geometry decals:** drop an image on the surface, then move, scale and turn its frame; it stays
|
||||
an editable fill layer.
|
||||
- **Text** in any installed font (or the built-in ones), shaped for every script with kerning and
|
||||
ligatures, one or more lines: stamp it with the brush as its alpha, or place it as a decal in the
|
||||
tool's base color (Properties › Alpha › Text).
|
||||
- **Quick mask** (Y): paint a temporary mask (U to edit, Ctrl+Shift+I to invert) that protects
|
||||
everything outside it while you paint.
|
||||
- **Every channel at once:** base color, metallic, roughness, height, normal, emissive, opacity,
|
||||
|
||||
Reference in new issue
Block a user