sdf_text/text.rs
1//! The `Text` member — a port of lib3's `src/sdf-text/Text.js`.
2//!
3//! In the JS this is a `THREE.Object3D` subclass whose eleven layout properties
4//! are installed by a loop over `LAYOUT_DEFAULTS` that generates a getter and a
5//! setter for each, the setter comparing with `!==` and setting `_needsSync`.
6//! There is no metaprogramming here, so the accessors are written out; the
7//! behaviour is the same, and the comparison is `!=` on the same values.
8//!
9//! Two things the JS does that this deliberately does **not**:
10//!
11//! - it does not extend an `Object3D`. `sdf-text` has no `three-rs` dependency
12//! (see the README's dependency note), and nothing in steps 1–3 reads the
13//! transform. When `BatchedText` lands — step 5 — it will need
14//! `matrix_world`, and that is the point at which `Text` should become an
15//! `Object3D`. Until then, pretending to be a scene node would be a lie about
16//! what works.
17//! - `color` is three numbers, not a `THREE.Color`. The JS `Color` applies
18//! `SRGBToLinear` on `set(hex)` because `ColorManagement` is on by default,
19//! and getting that conversion wrong is a uniform colour shift over every
20//! glyph (plan §5.3). That conversion belongs with the renderer step that
21//! actually consumes it, so this field is documented as *linear* and left for
22//! the caller to fill.
23//!
24//! # Opacity write-through
25//!
26//! `set opacity` is the one setter that does not dirty the layout: it returns
27//! early on an unchanged value and otherwise forwards to
28//! `BatchedText.setOpacityAt(memberId, value)`, which writes one entry of a
29//! per-glyph instanced attribute. `BatchedText` is step 5 and is not in this
30//! crate, so the write-through target is the [`OpacitySink`] trait — one method,
31//! the same signature. That keeps the semantics the ported layer-6 test checks
32//! (write-through happens, exactly once, with the member id; and the layout is
33//! not invalidated) testable now, and makes `BatchedText` a drop-in later.
34
35use std::cell::RefCell;
36use std::rc::Rc;
37
38use crate::text_builder::{
39 empty_render_info, layout_text, layout_text_vector, Anchor, LayoutParams, LineHeight,
40 TextAlign, TextRenderInfo,
41};
42use crate::vector_font::VectorFont;
43
44/// lib3's `LAYOUT_DEFAULTS` object. It is [`LayoutParams::default`]; this
45/// function exists so the name from the JS is findable.
46pub fn layout_defaults() -> LayoutParams {
47 LayoutParams::default()
48}
49
50/// What `Text::set_opacity` writes through to — `BatchedText.setOpacityAt` in
51/// the JS.
52pub trait OpacitySink {
53 /// Writes one member's opacity into the batch's per-glyph attribute.
54 fn set_opacity_at(&mut self, member_id: usize, opacity: f64);
55}
56
57/// A text member — a port of lib3's `Text`. See the module doc for how this
58/// differs from the JS `Object3D` subclass it ports.
59pub struct Text {
60 /// Member colour, **linear**, default white. See the module doc.
61 pub color: [f64; 3],
62
63 opacity: f64,
64 needs_sync: bool,
65 text_render_info: Option<TextRenderInfo>,
66 batched_text: Option<Rc<RefCell<dyn OpacitySink>>>,
67 /// `None` until the member joins a batch (`-1` in the JS).
68 member_id: Option<usize>,
69
70 /// Vector-outline mode: layout uses real font metrics instead of canvas.
71 /// Both this and the font are set by the owning `BatchedText`.
72 vector_mode: bool,
73 vector_font: Option<Rc<VectorFont>>,
74
75 params: LayoutParams,
76
77 /// Not in the JS. Counts the layouts actually performed, so a test can tell
78 /// "`sync` returned the same object" from "`sync` recomputed an equal one" —
79 /// the JS test asserts object identity, which `PartialEq` cannot express.
80 layouts_performed: u64,
81}
82
83impl Default for Text {
84 fn default() -> Self {
85 Text::new()
86 }
87}
88
89impl Text {
90 /// `new Text()` — every layout property at its `LAYOUT_DEFAULTS` value, and
91 /// `_needsSync = true`, so the first `sync` always lays out.
92 pub fn new() -> Self {
93 Text {
94 color: [1.0, 1.0, 1.0],
95 opacity: 1.0,
96 needs_sync: true,
97 text_render_info: None,
98 batched_text: None,
99 member_id: None,
100 vector_mode: false,
101 vector_font: None,
102 params: LayoutParams::default(),
103 layouts_performed: 0,
104 }
105 }
106
107 // ── Layout properties ──────────────────────────────────────────────────
108 //
109 // One pair each, all with the same shape: the setter compares first and only
110 // dirties when the value actually changed.
111
112 /// The string to lay out.
113 pub fn text(&self) -> &str {
114 &self.params.text
115 }
116
117 /// Sets the string to lay out — `text.text = value`.
118 pub fn set_text(&mut self, value: impl Into<String>) {
119 let value = value.into();
120 if self.params.text != value {
121 self.params.text = value;
122 self.needs_sync = true;
123 }
124 }
125
126 /// Font size, world units.
127 pub fn font_size(&self) -> f64 {
128 self.params.font_size
129 }
130
131 /// Sets the font size — `text.fontSize = value`.
132 pub fn set_font_size(&mut self, value: f64) {
133 if self.params.font_size != value {
134 self.params.font_size = value;
135 self.needs_sync = true;
136 }
137 }
138
139 /// CSS font family. Canvas layout only; vector layout never reads it.
140 pub fn font_family(&self) -> &str {
141 &self.params.font_family
142 }
143
144 /// Sets the CSS font family — `text.fontFamily = value`.
145 pub fn set_font_family(&mut self, value: impl Into<String>) {
146 let value = value.into();
147 if self.params.font_family != value {
148 self.params.font_family = value;
149 self.needs_sync = true;
150 }
151 }
152
153 /// CSS font weight. Canvas layout only.
154 pub fn font_weight(&self) -> &str {
155 &self.params.font_weight
156 }
157
158 /// Sets the CSS font weight — `text.fontWeight = value`.
159 pub fn set_font_weight(&mut self, value: impl Into<String>) {
160 let value = value.into();
161 if self.params.font_weight != value {
162 self.params.font_weight = value;
163 self.needs_sync = true;
164 }
165 }
166
167 /// CSS font style. Canvas layout only.
168 pub fn font_style(&self) -> &str {
169 &self.params.font_style
170 }
171
172 /// Sets the CSS font style — `text.fontStyle = value`.
173 pub fn set_font_style(&mut self, value: impl Into<String>) {
174 let value = value.into();
175 if self.params.font_style != value {
176 self.params.font_style = value;
177 self.needs_sync = true;
178 }
179 }
180
181 /// Extra space added per glyph. See the module's asymmetric-spacing note.
182 pub fn letter_spacing(&self) -> f64 {
183 self.params.letter_spacing
184 }
185
186 /// Sets the letter spacing — `text.letterSpacing = value`.
187 pub fn set_letter_spacing(&mut self, value: f64) {
188 if self.params.letter_spacing != value {
189 self.params.letter_spacing = value;
190 self.needs_sync = true;
191 }
192 }
193
194 /// Line height, as [`LineHeight`].
195 pub fn line_height(&self) -> LineHeight {
196 self.params.line_height
197 }
198
199 /// Sets the line height — `text.lineHeight = value`.
200 pub fn set_line_height(&mut self, value: LineHeight) {
201 if self.params.line_height != value {
202 self.params.line_height = value;
203 self.needs_sync = true;
204 }
205 }
206
207 /// Horizontal anchor.
208 pub fn anchor_x(&self) -> &Anchor {
209 &self.params.anchor_x
210 }
211
212 /// Sets the horizontal anchor — `text.anchorX = value`.
213 pub fn set_anchor_x(&mut self, value: Anchor) {
214 if self.params.anchor_x != value {
215 self.params.anchor_x = value;
216 self.needs_sync = true;
217 }
218 }
219
220 /// Vertical anchor.
221 pub fn anchor_y(&self) -> &Anchor {
222 &self.params.anchor_y
223 }
224
225 /// Sets the vertical anchor — `text.anchorY = value`.
226 pub fn set_anchor_y(&mut self, value: Anchor) {
227 if self.params.anchor_y != value {
228 self.params.anchor_y = value;
229 self.needs_sync = true;
230 }
231 }
232
233 /// Multi-line alignment.
234 pub fn text_align(&self) -> TextAlign {
235 self.params.text_align
236 }
237
238 /// Sets the text alignment — `text.textAlign = value`.
239 pub fn set_text_align(&mut self, value: TextAlign) {
240 if self.params.text_align != value {
241 self.params.text_align = value;
242 self.needs_sync = true;
243 }
244 }
245
246 /// Line-wrap width, world units. `f64::INFINITY` by default (no wrap).
247 pub fn max_width(&self) -> f64 {
248 self.params.max_width
249 }
250
251 /// Sets the line-wrap width — `text.maxWidth = value`.
252 pub fn set_max_width(&mut self, value: f64) {
253 if self.params.max_width != value {
254 self.params.max_width = value;
255 self.needs_sync = true;
256 }
257 }
258
259 // ── The rest of the surface ────────────────────────────────────────────
260
261 /// The most recent layout, or `None` before the first [`Text::sync`].
262 pub fn text_render_info(&self) -> Option<&TextRenderInfo> {
263 self.text_render_info.as_ref()
264 }
265
266 #[doc(hidden)]
267 pub fn needs_sync(&self) -> bool {
268 self.needs_sync
269 }
270
271 /// `text._needsSync = true` — the owning `BatchedText` sets this directly in
272 /// `addText` and `resetAtlas`. Not a JS *method*: in JS `_needsSync` is just
273 /// a field the batch reaches into, and Rust privacy needs a door for it.
274 pub(crate) fn mark_needs_sync(&mut self) {
275 self.needs_sync = true;
276 }
277
278 /// How many layouts have actually run. Not in the JS — see the field doc.
279 #[doc(hidden)]
280 pub fn layouts_performed(&self) -> u64 {
281 self.layouts_performed
282 }
283
284 /// Whole-text opacity (0..1).
285 pub fn opacity(&self) -> f64 {
286 self.opacity
287 }
288
289 /// Does **not** trigger re-layout; writes through to the owning batch's
290 /// per-glyph opacity attribute when batched.
291 pub fn set_opacity(&mut self, value: f64) {
292 if self.opacity == value {
293 return;
294 }
295 self.opacity = value;
296 if let (Some(batch), Some(member_id)) = (self.batched_text.as_ref(), self.member_id) {
297 batch.borrow_mut().set_opacity_at(member_id, value);
298 }
299 }
300
301 /// `_batchedText` / `_memberId`, set by the owning batch. Both are needed
302 /// before `set_opacity` writes anything through.
303 #[doc(hidden)]
304 pub fn attach_to_batch(&mut self, batch: Rc<RefCell<dyn OpacitySink>>, member_id: usize) {
305 self.batched_text = Some(batch);
306 self.member_id = Some(member_id);
307 }
308
309 #[doc(hidden)]
310 pub fn detach_from_batch(&mut self) {
311 self.batched_text = None;
312 self.member_id = None;
313 }
314
315 /// `None` when the member has not joined a batch (`-1` in the JS).
316 pub fn member_id(&self) -> Option<usize> {
317 self.member_id
318 }
319
320 /// `_vectorMode` / `_vectorFont`. Passing `None` for the font while the mode
321 /// is on is the "still loading" state `sync` has a branch for.
322 pub fn set_vector_mode(&mut self, on: bool) {
323 self.vector_mode = on;
324 }
325
326 /// Whether vector-outline layout is on.
327 pub fn vector_mode(&self) -> bool {
328 self.vector_mode
329 }
330
331 /// `_vectorFont`, set by the owning `BatchedText`.
332 pub fn set_vector_font(&mut self, font: Option<Rc<VectorFont>>) {
333 self.vector_font = font;
334 }
335
336 /// `sync(callback, renderer)` — lay out the glyphs, unless a cached layout is
337 /// still valid.
338 ///
339 /// The callback is a JS idiom for "the layout may be asynchronous"; it never
340 /// is, so it is dropped. The renderer argument was already unused in the JS.
341 ///
342 /// Note the vector-mode-without-a-font branch: it installs an empty layout
343 /// and returns **without clearing the dirty flag**, so the next `sync` after
344 /// the font arrives re-lays out. It also does not touch
345 /// `layouts_performed`, because no layout happened.
346 pub fn sync(&mut self) -> &TextRenderInfo {
347 // The `if let` form clippy suggests here ties the returned borrow's
348 // lifetime to a region that (per NLL) also covers the later
349 // `self.text_render_info = Some(...)` assignment below, which the
350 // borrow checker then rejects; the is_some()+unwrap() form does not.
351 #[allow(clippy::unnecessary_unwrap)]
352 if !self.needs_sync && self.text_render_info.is_some() {
353 return self
354 .text_render_info
355 .as_ref()
356 .expect("sdf-text: text_render_info.is_some() was just checked");
357 }
358
359 let params = self.params.clone();
360
361 if self.vector_mode {
362 match self.vector_font.clone() {
363 None => {
364 // Font still loading — stay dirty so we re-layout once it
365 // arrives.
366 self.text_render_info = Some(empty_render_info(params));
367 return self
368 .text_render_info
369 .as_ref()
370 .expect("sdf-text: text_render_info was set on the line above");
371 }
372 Some(font) => {
373 self.text_render_info = Some(layout_text_vector(params, Some(&font)));
374 }
375 }
376 } else {
377 self.text_render_info = Some(layout_text(params));
378 }
379
380 self.layouts_performed += 1;
381 self.needs_sync = false;
382 self.text_render_info
383 .as_ref()
384 .expect("sdf-text: text_render_info was set by the branch above")
385 }
386}