native2d: Vektor-Text (Glyph-Umrisse als Dreiecke, instanziert, drehbar) statt SVG-Overlay fuer einfache Texte
This commit is contained in:
1 parent
8c3655956c
commit
d663d6615c
11 files changed
+783
-5
No files matched your search
Generated
+41
@@ -1312,6 +1312,12 @@ dependencies = [
|
||||
"miniz_oxide",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "float_next_after"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8bf7cc16383c4b8d58b9905a8509f02926ce3058053c056376248d958c9df1e8"
|
||||
|
||||
[[package]]
|
||||
name = "fnv"
|
||||
version = "1.0.7"
|
||||
@@ -2633,6 +2639,38 @@ version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"
|
||||
|
||||
[[package]]
|
||||
name = "lyon_geom"
|
||||
version = "1.0.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4336502e29e32af93cf2dad2214ed6003c17ceb5bd499df77b1de663b9042b92"
|
||||
dependencies = [
|
||||
"arrayvec",
|
||||
"euclid",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lyon_path"
|
||||
version = "1.0.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5c463f9c428b7fc5ec885dcd39ce4aa61e29111d0e33483f6f98c74e89d8621e"
|
||||
dependencies = [
|
||||
"lyon_geom",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lyon_tessellation"
|
||||
version = "1.0.22"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "43b8dcf906637ecef61b3c0740c7a4e7f27caeb31257cfac0cc579ce15be6005"
|
||||
dependencies = [
|
||||
"float_next_after",
|
||||
"lyon_path",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "markup5ever"
|
||||
version = "0.38.0"
|
||||
@@ -3952,13 +3990,16 @@ dependencies = [
|
||||
"bytemuck",
|
||||
"console_error_panic_hook",
|
||||
"env_logger",
|
||||
"fontdb",
|
||||
"glyphon",
|
||||
"image",
|
||||
"js-sys",
|
||||
"lyon_tessellation",
|
||||
"naga",
|
||||
"pollster",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"ttf-parser",
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
"web-sys",
|
||||
|
||||
@@ -32,7 +32,7 @@ default = []
|
||||
# Laufzeit dynamisch), rendert aber nur mit einer aktiven Grafik-Session.
|
||||
# glyphon = GPU-Glyphen-Atlas fuer ECHTE TrueType-Schrift (cosmic-text) —
|
||||
# gehoert bewusst in die GPU-Schicht, die serde-only-Default-Schicht bleibt fontfrei.
|
||||
render = ["dep:wgpu", "dep:bytemuck", "dep:pollster", "dep:glyphon"]
|
||||
render = ["dep:wgpu", "dep:bytemuck", "dep:pollster", "dep:glyphon", "dep:fontdb", "dep:ttf-parser", "dep:lyon_tessellation"]
|
||||
|
||||
# Fenster-Spike (winit) inkl. lauffaehigem Binary. Braucht Wayland/X11 + eine
|
||||
# Display-Session zur visuellen Verifikation.
|
||||
@@ -75,6 +75,12 @@ pollster = { version = "0.4", optional = true }
|
||||
# Echte TrueType-Glyphen ueber einen GPU-Atlas (cosmic-text + etagere). Version
|
||||
# an wgpu gekoppelt: die 0.11er-Reihe ist die zu wgpu 29 passende.
|
||||
glyphon = { version = "0.11", optional = true }
|
||||
# Vektor-Text (src/vtext.rs): Systemschrift suchen (fontdb), Glyphen-Umrisse lesen
|
||||
# (ttf-parser) und einmal je Glyphe zu Dreiecken tessellieren (lyon). Versionen an
|
||||
# die von cosmic-text/glyphon bereits genutzten gekoppelt (keine Duplikate).
|
||||
fontdb = { version = "0.23", optional = true }
|
||||
ttf-parser = { version = "0.25", optional = true }
|
||||
lyon_tessellation = { version = "1", optional = true }
|
||||
|
||||
# --- Headless-PNG-Export (nur mit Feature "headless") ------------------------
|
||||
# Nur der PNG-Codec noetig (kein volles Format-Universum) -> default-features aus.
|
||||
|
||||
@@ -64,6 +64,88 @@ fn fs_main() -> @location(0) vec4<f32> {
|
||||
}
|
||||
"#;
|
||||
|
||||
/// Vektor-Text: Glyphen-Dreiecke (em-Einheiten) pro Instanz positioniert, skaliert
|
||||
/// und gedreht. `pos` ist relativ zur Ansichtsmitte (f64 → f32 auf der CPU).
|
||||
const TEXT_WGSL: &str = r#"
|
||||
struct Globals {
|
||||
view_proj : mat4x4<f32>,
|
||||
color : vec4<f32>,
|
||||
viewport_px : vec2<f32>,
|
||||
stroke_px : f32,
|
||||
stroke_scale : f32,
|
||||
};
|
||||
@group(0) @binding(0) var<uniform> globals : Globals;
|
||||
|
||||
struct VsIn {
|
||||
@location(0) g : vec2<f32>, // Glyphenpunkt in em (Y nach oben)
|
||||
@location(1) pos : vec2<f32>, // Textanker (Bildschirm-Raum, relativ zur Ansichtsmitte)
|
||||
@location(2) scale : f32, // em → Bildschirm-Einheiten (= Schrifthoehe)
|
||||
@location(3) xoff : f32, // X-Versatz der Glyphe in em (Vorschub)
|
||||
@location(4) cs : vec2<f32>, // (cos, sin) der Bildschirm-Drehung
|
||||
@location(5) color : vec4<f32>,
|
||||
};
|
||||
struct VsOut {
|
||||
@builtin(position) p : vec4<f32>,
|
||||
@location(0) color : vec4<f32>,
|
||||
};
|
||||
|
||||
@vertex
|
||||
fn vs_main(in : VsIn) -> VsOut {
|
||||
let lx = (in.xoff + in.g.x) * in.scale;
|
||||
let ly = -in.g.y * in.scale;
|
||||
let x = lx * in.cs.x - ly * in.cs.y;
|
||||
let y = lx * in.cs.y + ly * in.cs.x;
|
||||
var o : VsOut;
|
||||
o.p = globals.view_proj * vec4<f32>(in.pos + vec2<f32>(x, y), 0.0, 1.0);
|
||||
o.color = in.color;
|
||||
return o;
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn fs_main(in : VsOut) -> @location(0) vec4<f32> {
|
||||
return in.color;
|
||||
}
|
||||
"#;
|
||||
|
||||
/// Text-Eingabe aus der Webview (Bildschirm-Raum, doppelte Genauigkeit).
|
||||
#[derive(Clone, Debug, serde::Deserialize)]
|
||||
pub struct TextIn {
|
||||
pub id: u32,
|
||||
pub x: f64,
|
||||
pub y: f64,
|
||||
/// Schrifthoehe (= em) in Bildschirm-Einheiten.
|
||||
pub size: f64,
|
||||
/// Drehung in Bildschirm-Raum (Radiant, im Uhrzeigersinn positiv).
|
||||
pub angle: f64,
|
||||
pub color: [f32; 4],
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
struct TextItem {
|
||||
x: f64,
|
||||
y: f64,
|
||||
size: f64,
|
||||
cs: [f32; 2],
|
||||
color: [f32; 4],
|
||||
glyphs: Vec<(u16, f32)>,
|
||||
width_em: f32,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Pod, Zeroable)]
|
||||
struct TextInst {
|
||||
pos: [f32; 2],
|
||||
scale: f32,
|
||||
xoff: f32,
|
||||
cs: [f32; 2],
|
||||
color: [f32; 4],
|
||||
}
|
||||
|
||||
/// Obergrenze gleichzeitig gezeichneter Texte; darueber bleiben die groessten.
|
||||
const MAX_VISIBLE_TEXTS: usize = 6000;
|
||||
/// Texte unter dieser Hoehe (Geraete-px) werden nicht gezeichnet.
|
||||
const MIN_TEXT_PX: f64 = 2.0;
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Pod, Zeroable)]
|
||||
struct Globals {
|
||||
@@ -124,6 +206,13 @@ pub struct ChunkRenderer {
|
||||
msaa: Option<(wgpu::Texture, (u32, u32))>,
|
||||
format: wgpu::TextureFormat,
|
||||
pub clear: [f64; 3],
|
||||
// --- Vektor-Text ---
|
||||
text_pipeline: wgpu::RenderPipeline,
|
||||
font: Option<crate::vtext::VectorFont>,
|
||||
texts: HashMap<u32, TextItem>,
|
||||
glyph_vbo: Option<wgpu::Buffer>,
|
||||
glyph_ibo: Option<wgpu::Buffer>,
|
||||
inst_buf: Option<(wgpu::Buffer, u64)>,
|
||||
}
|
||||
|
||||
/// Aspekt-korrigierte Grenzen (left,right,bottom,top) wie `orthoBounds`.
|
||||
@@ -242,7 +331,53 @@ impl ChunkRenderer {
|
||||
},
|
||||
"chunks.line.pipeline",
|
||||
);
|
||||
let text_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("chunks.text"),
|
||||
source: wgpu::ShaderSource::Wgsl(TEXT_WGSL.into()),
|
||||
});
|
||||
let text_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("chunks.text.pipeline"),
|
||||
layout: Some(&pipeline_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &text_module,
|
||||
entry_point: Some("vs_main"),
|
||||
buffers: &[
|
||||
wgpu::VertexBufferLayout {
|
||||
array_stride: 8,
|
||||
step_mode: wgpu::VertexStepMode::Vertex,
|
||||
attributes: &wgpu::vertex_attr_array![0 => Float32x2],
|
||||
},
|
||||
wgpu::VertexBufferLayout {
|
||||
array_stride: std::mem::size_of::<TextInst>() as u64,
|
||||
step_mode: wgpu::VertexStepMode::Instance,
|
||||
attributes: &wgpu::vertex_attr_array![1 => Float32x2, 2 => Float32, 3 => Float32, 4 => Float32x2, 5 => Float32x4],
|
||||
},
|
||||
],
|
||||
compilation_options: Default::default(),
|
||||
},
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &text_module,
|
||||
entry_point: Some("fs_main"),
|
||||
targets: &[Some(target.clone())],
|
||||
compilation_options: Default::default(),
|
||||
}),
|
||||
primitive: wgpu::PrimitiveState {
|
||||
topology: wgpu::PrimitiveTopology::TriangleList,
|
||||
cull_mode: None,
|
||||
..Default::default()
|
||||
},
|
||||
depth_stencil: None,
|
||||
multisample: wgpu::MultisampleState { count: SAMPLE_COUNT, mask: !0, alpha_to_coverage_enabled: false },
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
});
|
||||
Self {
|
||||
text_pipeline,
|
||||
font: None,
|
||||
texts: HashMap::new(),
|
||||
glyph_vbo: None,
|
||||
glyph_ibo: None,
|
||||
inst_buf: None,
|
||||
fill_pipeline,
|
||||
line_pipeline,
|
||||
bind_group_layout,
|
||||
@@ -275,6 +410,89 @@ impl ChunkRenderer {
|
||||
}
|
||||
}
|
||||
|
||||
/// Texte einfuegen/ersetzen bzw. entfernen. `false`, wenn keine Schrift
|
||||
/// verfuegbar ist (die Webview zeichnet die Texte dann selbst).
|
||||
pub fn set_texts(&mut self, upsert: Vec<TextIn>, remove: &[u32]) -> bool {
|
||||
if self.font.is_none() {
|
||||
self.font = crate::vtext::VectorFont::system();
|
||||
}
|
||||
let Some(font) = self.font.as_ref() else { return false };
|
||||
for id in remove {
|
||||
self.texts.remove(id);
|
||||
}
|
||||
for t in upsert {
|
||||
let (glyphs, width_em) = font.shape(&t.text);
|
||||
self.texts.insert(
|
||||
t.id,
|
||||
TextItem {
|
||||
x: t.x,
|
||||
y: t.y,
|
||||
size: t.size,
|
||||
cs: [t.angle.cos() as f32, t.angle.sin() as f32],
|
||||
color: t.color,
|
||||
glyphs,
|
||||
width_em,
|
||||
},
|
||||
);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
pub fn text_count(&self) -> usize {
|
||||
self.texts.len()
|
||||
}
|
||||
|
||||
/// Sichtbare Texte dieses Frames als nach Glyphe gruppierte Instanzen.
|
||||
/// Rueckgabe: Instanzen (nach Glyph-ID sortiert) + Gruppen (gid, Instanzbereich).
|
||||
fn build_text_instances(
|
||||
&mut self,
|
||||
bounds: (f64, f64, f64, f64),
|
||||
px_per_unit: f64,
|
||||
) -> (Vec<TextInst>, Vec<(u16, std::ops::Range<u32>)>) {
|
||||
let Some(font) = self.font.as_mut() else { return (Vec::new(), Vec::new()) };
|
||||
let (left, right, bottom, top) = bounds;
|
||||
let (cx, cy) = ((left + right) / 2.0, (top + bottom) / 2.0);
|
||||
let mut vis: Vec<u32> = Vec::new();
|
||||
for (id, t) in &self.texts {
|
||||
if t.size * px_per_unit < MIN_TEXT_PX {
|
||||
continue;
|
||||
}
|
||||
let reach = t.size * (t.width_em as f64 + 1.0);
|
||||
if t.x + reach < left || t.x - reach > right || t.y + reach < top || t.y - reach > bottom {
|
||||
continue;
|
||||
}
|
||||
vis.push(*id);
|
||||
}
|
||||
if vis.len() > MAX_VISIBLE_TEXTS {
|
||||
// Nur die groessten behalten (wie bei Karten: wichtige Beschriftungen bleiben).
|
||||
let mut sizes: Vec<f64> = vis.iter().map(|id| self.texts[id].size).collect();
|
||||
let k = vis.len() - MAX_VISIBLE_TEXTS;
|
||||
sizes.select_nth_unstable_by(k, |a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
|
||||
let threshold = sizes[k];
|
||||
vis.retain(|id| self.texts[id].size >= threshold);
|
||||
}
|
||||
let mut tmp: Vec<(u16, TextInst)> = Vec::new();
|
||||
for id in &vis {
|
||||
let t = &self.texts[id];
|
||||
let pos = [(t.x - cx) as f32, (t.y - cy) as f32];
|
||||
for &(gid, xoff) in &t.glyphs {
|
||||
if font.mesh(gid).is_none() {
|
||||
continue;
|
||||
}
|
||||
tmp.push((gid, TextInst { pos, scale: t.size as f32, xoff, cs: t.cs, color: t.color }));
|
||||
}
|
||||
}
|
||||
tmp.sort_by_key(|(g, _)| *g);
|
||||
let mut groups: Vec<(u16, std::ops::Range<u32>)> = Vec::new();
|
||||
for (i, (g, _)) in tmp.iter().enumerate() {
|
||||
match groups.last_mut() {
|
||||
Some((lg, r)) if lg == g => r.end = i as u32 + 1,
|
||||
_ => groups.push((*g, i as u32..i as u32 + 1)),
|
||||
}
|
||||
}
|
||||
(tmp.into_iter().map(|(_, i)| i).collect(), groups)
|
||||
}
|
||||
|
||||
pub fn set_layout(&mut self, layout: Vec<ChunkGeom>) {
|
||||
self.layout = layout;
|
||||
}
|
||||
@@ -330,6 +548,52 @@ impl ChunkRenderer {
|
||||
}
|
||||
}
|
||||
|
||||
// Vektor-Text dieses Frames (sichtbare Texte, nach Glyphe gruppiert).
|
||||
let (text_insts, text_groups) = self.build_text_instances(bounds, meet);
|
||||
let text_block = blocks.len() as u32;
|
||||
if !text_groups.is_empty() {
|
||||
let centre = [(bounds.0 + bounds.1) / 2.0, (bounds.3 + bounds.2) / 2.0];
|
||||
blocks.push(Globals {
|
||||
view_proj: projection(bounds, centre),
|
||||
color: [0.0; 4],
|
||||
viewport_px: vp,
|
||||
stroke_px: 0.0,
|
||||
stroke_scale: 1.0,
|
||||
});
|
||||
// Glyphen-Mesh-Puffer neu aufbauen, wenn neue Glyphen dazukamen.
|
||||
if let Some(font) = self.font.as_mut() {
|
||||
if font.dirty || self.glyph_vbo.is_none() {
|
||||
self.glyph_vbo = Some(device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("chunks.glyph.vbo"),
|
||||
contents: bytemuck::cast_slice(&font.verts),
|
||||
usage: wgpu::BufferUsages::VERTEX,
|
||||
}));
|
||||
self.glyph_ibo = Some(device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("chunks.glyph.ibo"),
|
||||
contents: bytemuck::cast_slice(&font.indices),
|
||||
usage: wgpu::BufferUsages::INDEX,
|
||||
}));
|
||||
font.dirty = false;
|
||||
}
|
||||
}
|
||||
let need = (text_insts.len() * std::mem::size_of::<TextInst>()) as u64;
|
||||
if self.inst_buf.as_ref().map_or(true, |b| b.1 < need) {
|
||||
let cap = need.next_power_of_two().max(64 * 1024);
|
||||
self.inst_buf = Some((
|
||||
device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("chunks.text.inst"),
|
||||
size: cap,
|
||||
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
}),
|
||||
cap,
|
||||
));
|
||||
}
|
||||
if let Some((buf, _)) = &self.inst_buf {
|
||||
queue.write_buffer(buf, 0, bytemuck::cast_slice(&text_insts));
|
||||
}
|
||||
}
|
||||
|
||||
// Uniform-Puffer bei Bedarf vergroessern, dann einmal schreiben.
|
||||
let need = stride * blocks.len().max(1) as u64;
|
||||
if self.uniform.as_ref().map_or(true, |u| u.2 < need) {
|
||||
@@ -434,6 +698,25 @@ impl ChunkRenderer {
|
||||
block += 1;
|
||||
}
|
||||
}
|
||||
// Text zuoberst.
|
||||
if let (false, Some(vbo), Some(ibo), Some((inst, _)), Some(font)) = (
|
||||
text_groups.is_empty(),
|
||||
&self.glyph_vbo,
|
||||
&self.glyph_ibo,
|
||||
&self.inst_buf,
|
||||
self.font.as_ref(),
|
||||
) {
|
||||
pass.set_pipeline(&self.text_pipeline);
|
||||
pass.set_bind_group(0, ubind, &[text_block * stride as u32]);
|
||||
pass.set_vertex_buffer(0, vbo.slice(..));
|
||||
pass.set_vertex_buffer(1, inst.slice(..));
|
||||
pass.set_index_buffer(ibo.slice(..), wgpu::IndexFormat::Uint32);
|
||||
for (gid, range) in &text_groups {
|
||||
if let Some(m) = font.mesh_info(*gid) {
|
||||
pass.draw_indexed(m.first_index..m.first_index + m.index_count, 0, range.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
queue.submit(Some(enc.finish()));
|
||||
}
|
||||
|
||||
@@ -25,6 +25,10 @@ pub mod gpu;
|
||||
#[cfg(feature = "render")]
|
||||
pub mod chunks;
|
||||
|
||||
// Vektor-Text (Glyphen-Umrisse → Dreiecke, instanziert, drehbar).
|
||||
#[cfg(feature = "render")]
|
||||
pub mod vtext;
|
||||
|
||||
// Browser-Bindings (wasm32 + WebGPU), nur mit Feature "web". Setzt "render" voraus
|
||||
// (dieselbe GPU-Schicht wie das native Fenster), fuegt aber KEINE winit-Abhaengigkeit
|
||||
// hinzu — die Canvas dient direkt als wgpu-Surface.
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
// Vektor-Text: Glyphen-Umrisse einer Systemschrift werden EINMAL je Glyphe zu
|
||||
// Dreiecken tesselliert (lyon) und danach instanziert gezeichnet — mit beliebiger
|
||||
// Position, Groesse und DREHUNG (der Glyphen-Atlas-Text aus `glyphon` kann nicht
|
||||
// drehen, Katastertexte sind aber oft gedreht).
|
||||
//
|
||||
// Bewusst einfach: Zeichenfolge → Glyph-IDs + Vorschub (hmtx), KEIN Kerning, kein
|
||||
// komplexes Shaping (CAD-Beschriftungen: Zahlen, Strassen-/Flurnamen).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use lyon_tessellation::geom::point;
|
||||
use lyon_tessellation::path::Path;
|
||||
use lyon_tessellation::{BuffersBuilder, FillOptions, FillRule, FillTessellator, FillVertex, VertexBuffers};
|
||||
|
||||
/// Indexbereich eines Glyphen-Meshes im gemeinsamen Index-Puffer.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct GlyphMesh {
|
||||
pub first_index: u32,
|
||||
pub index_count: u32,
|
||||
}
|
||||
|
||||
pub struct VectorFont {
|
||||
data: Arc<Vec<u8>>,
|
||||
index: u32,
|
||||
units_per_em: f32,
|
||||
/// Gemeinsamer Vertex-/Index-Puffer aller bisher tessellierten Glyphen (em-Einheiten, Y nach oben).
|
||||
pub verts: Vec<[f32; 2]>,
|
||||
pub indices: Vec<u32>,
|
||||
meshes: HashMap<u16, GlyphMesh>,
|
||||
/// true, sobald `verts`/`indices` seit dem letzten Hochladen gewachsen sind.
|
||||
pub dirty: bool,
|
||||
}
|
||||
|
||||
struct PathSink {
|
||||
b: lyon_tessellation::path::path::Builder,
|
||||
open: bool,
|
||||
s: f32,
|
||||
}
|
||||
|
||||
impl ttf_parser::OutlineBuilder for PathSink {
|
||||
fn move_to(&mut self, x: f32, y: f32) {
|
||||
if self.open {
|
||||
self.b.end(true);
|
||||
}
|
||||
self.b.begin(point(x * self.s, y * self.s));
|
||||
self.open = true;
|
||||
}
|
||||
fn line_to(&mut self, x: f32, y: f32) {
|
||||
self.b.line_to(point(x * self.s, y * self.s));
|
||||
}
|
||||
fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
|
||||
self.b.quadratic_bezier_to(point(x1 * self.s, y1 * self.s), point(x * self.s, y * self.s));
|
||||
}
|
||||
fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
|
||||
self.b.cubic_bezier_to(
|
||||
point(x1 * self.s, y1 * self.s),
|
||||
point(x2 * self.s, y2 * self.s),
|
||||
point(x * self.s, y * self.s),
|
||||
);
|
||||
}
|
||||
fn close(&mut self) {
|
||||
if self.open {
|
||||
self.b.end(true);
|
||||
self.open = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl VectorFont {
|
||||
/// Sucht eine Systemschrift (Inter, sonst Sans-Serif, sonst irgendeine).
|
||||
pub fn system() -> Option<Self> {
|
||||
let mut db = fontdb::Database::new();
|
||||
db.load_system_fonts();
|
||||
let q = fontdb::Query {
|
||||
families: &[
|
||||
fontdb::Family::Name("Inter"),
|
||||
fontdb::Family::Name("Helvetica Neue"),
|
||||
fontdb::Family::Name("Helvetica"),
|
||||
fontdb::Family::Name("Arial"),
|
||||
fontdb::Family::SansSerif,
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
let id = db.query(&q).or_else(|| db.faces().next().map(|f| f.id))?;
|
||||
let (data, index) = db.with_face_data(id, |d, i| (d.to_vec(), i))?;
|
||||
Self::from_bytes(data, index)
|
||||
}
|
||||
|
||||
pub fn from_bytes(data: Vec<u8>, index: u32) -> Option<Self> {
|
||||
let upem = {
|
||||
let face = ttf_parser::Face::parse(&data, index).ok()?;
|
||||
face.units_per_em() as f32
|
||||
};
|
||||
if upem <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
Some(Self {
|
||||
data: Arc::new(data),
|
||||
index,
|
||||
units_per_em: upem,
|
||||
verts: Vec::new(),
|
||||
indices: Vec::new(),
|
||||
meshes: HashMap::new(),
|
||||
dirty: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Zeichen → (Glyph-ID, X-Versatz der Glyphe in em) plus Gesamtbreite in em.
|
||||
pub fn shape(&self, text: &str) -> (Vec<(u16, f32)>, f32) {
|
||||
let Ok(face) = ttf_parser::Face::parse(&self.data, self.index) else {
|
||||
return (Vec::new(), 0.0);
|
||||
};
|
||||
let mut out = Vec::with_capacity(text.len());
|
||||
let mut x = 0.0f32;
|
||||
for ch in text.chars() {
|
||||
let gid = face.glyph_index(ch).unwrap_or(ttf_parser::GlyphId(0));
|
||||
let adv = face.glyph_hor_advance(gid).unwrap_or((self.units_per_em * 0.5) as u16) as f32 / self.units_per_em;
|
||||
if ch != ' ' && ch != '\u{a0}' {
|
||||
out.push((gid.0, x));
|
||||
}
|
||||
x += adv;
|
||||
}
|
||||
(out, x)
|
||||
}
|
||||
|
||||
/// Bereits tesselliertes Mesh einer Glyphe (nur lesend).
|
||||
pub fn mesh_info(&self, gid: u16) -> Option<GlyphMesh> {
|
||||
self.meshes.get(&gid).copied().filter(|m| m.index_count > 0)
|
||||
}
|
||||
|
||||
/// Mesh einer Glyphe (beim ersten Bedarf tesselliert). Leere Glyphen → `None`.
|
||||
pub fn mesh(&mut self, gid: u16) -> Option<GlyphMesh> {
|
||||
if let Some(m) = self.meshes.get(&gid) {
|
||||
return if m.index_count == 0 { None } else { Some(*m) };
|
||||
}
|
||||
let mesh = self.tessellate(gid);
|
||||
self.meshes.insert(gid, mesh);
|
||||
if mesh.index_count == 0 { None } else { Some(mesh) }
|
||||
}
|
||||
|
||||
fn tessellate(&mut self, gid: u16) -> GlyphMesh {
|
||||
let empty = GlyphMesh { first_index: self.indices.len() as u32, index_count: 0 };
|
||||
let Ok(face) = ttf_parser::Face::parse(&self.data, self.index) else {
|
||||
return empty;
|
||||
};
|
||||
let mut sink = PathSink { b: Path::builder(), open: false, s: 1.0 / self.units_per_em };
|
||||
if face.outline_glyph(ttf_parser::GlyphId(gid), &mut sink).is_none() {
|
||||
return empty;
|
||||
}
|
||||
if sink.open {
|
||||
sink.b.end(true);
|
||||
}
|
||||
let path = sink.b.build();
|
||||
let mut buffers: VertexBuffers<[f32; 2], u32> = VertexBuffers::new();
|
||||
let mut tess = FillTessellator::new();
|
||||
// Toleranz in em: 0.0003 em ≈ 0.06 px bei 200 px Schrift.
|
||||
let opts = FillOptions::tolerance(0.0003).with_fill_rule(FillRule::NonZero);
|
||||
if tess
|
||||
.tessellate_path(&path, &opts, &mut BuffersBuilder::new(&mut buffers, |v: FillVertex| v.position().to_array()))
|
||||
.is_err()
|
||||
|| buffers.indices.is_empty()
|
||||
{
|
||||
return empty;
|
||||
}
|
||||
let base = self.verts.len() as u32;
|
||||
let first_index = self.indices.len() as u32;
|
||||
self.verts.extend_from_slice(&buffers.vertices);
|
||||
self.indices.extend(buffers.indices.iter().map(|i| i + base));
|
||||
self.dirty = true;
|
||||
GlyphMesh { first_index, index_count: buffers.indices.len() as u32 }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn shapes_and_tessellates_a_glyph_if_a_system_font_exists() {
|
||||
let Some(mut font) = VectorFont::system() else {
|
||||
eprintln!("keine Systemschrift – Test uebersprungen");
|
||||
return;
|
||||
};
|
||||
let (glyphs, width) = font.shape("AB 1");
|
||||
assert_eq!(glyphs.len(), 3, "Leerzeichen erzeugt keine Glyphe");
|
||||
assert!(width > 1.0 && width < 4.0, "Breite in em plausibel: {width}");
|
||||
let m = font.mesh(glyphs[0].0).expect("A hat einen Umriss");
|
||||
assert!(m.index_count >= 3 && m.index_count % 3 == 0);
|
||||
assert!(font.verts.iter().all(|v| v[0].abs() < 2.0 && v[1].abs() < 2.0), "em-normalisiert");
|
||||
// Zweiter Zugriff liefert dasselbe Mesh ohne neu zu tessellieren.
|
||||
let n = font.indices.len();
|
||||
assert_eq!(font.mesh(glyphs[0].0).unwrap().first_index, m.first_index);
|
||||
assert_eq!(font.indices.len(), n);
|
||||
}
|
||||
}
|
||||
@@ -138,6 +138,22 @@ fn native2d_layout(app: tauri::AppHandle, layout: serde_json::Value, delete: Vec
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Vektor-Texte (Delta): `upsert` = Eintraege, `remove` = IDs. Liefert `false`, wenn
|
||||
/// keine Schrift gefunden wurde (dann zeichnet die Webview die Texte selbst).
|
||||
#[tauri::command]
|
||||
fn native2d_texts(app: tauri::AppHandle, upsert: serde_json::Value, remove: Vec<u32>) -> Result<bool, String> {
|
||||
#[cfg(all(feature = "native2d", target_os = "macos"))]
|
||||
{
|
||||
let upsert = serde_json::from_value(upsert).map_err(|e| e.to_string())?;
|
||||
return Ok(native_embed::set_texts(&app, upsert, remove));
|
||||
}
|
||||
#[cfg(not(all(feature = "native2d", target_os = "macos")))]
|
||||
{
|
||||
let _ = (app, upsert, remove);
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn native2d_frame(app: tauri::AppHandle, view: serde_json::Value, paper_scale: f64, clear: Option<[f64; 3]>) -> Result<(), String> {
|
||||
#[cfg(all(feature = "native2d", target_os = "macos"))]
|
||||
@@ -202,6 +218,7 @@ pub fn run() {
|
||||
native2d_upload,
|
||||
native2d_layout,
|
||||
native2d_frame,
|
||||
native2d_texts,
|
||||
push_native_scene,
|
||||
push_native_walls,
|
||||
acquire_project_lock,
|
||||
@@ -216,6 +233,7 @@ pub fn run() {
|
||||
native2d_upload,
|
||||
native2d_layout,
|
||||
native2d_frame,
|
||||
native2d_texts,
|
||||
acquire_project_lock,
|
||||
release_project_lock
|
||||
]);
|
||||
|
||||
@@ -17,7 +17,7 @@ use objc2_foundation::{NSPoint, NSRect, NSSize, NSString};
|
||||
use raw_window_handle::{
|
||||
AppKitDisplayHandle, AppKitWindowHandle, RawDisplayHandle, RawWindowHandle,
|
||||
};
|
||||
use render2d::chunks::{ChunkGeom, ChunkRenderer, View};
|
||||
use render2d::chunks::{ChunkGeom, ChunkRenderer, TextIn, View};
|
||||
use tauri::{AppHandle, Manager};
|
||||
|
||||
struct Embedded {
|
||||
@@ -214,3 +214,16 @@ pub fn hide(app: &AppHandle) {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Texte einfuegen/entfernen und neu zeichnen. `false` = keine Schrift verfuegbar
|
||||
/// (die Webview zeichnet die Texte dann weiter im SVG-Overlay).
|
||||
pub fn set_texts(app: &AppHandle, upsert: Vec<TextIn>, remove: Vec<u32>) -> bool {
|
||||
match app.state::<EmbedState>().0.lock().unwrap().as_mut() {
|
||||
Some(e) => {
|
||||
let ok = e.renderer.set_texts(upsert, &remove);
|
||||
draw(e);
|
||||
ok
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user