sim_logic/platform/desktop/
text.rs1use std::{error::Error, fmt};
4
5use sim_engine::{
6 FrameComposer, FramePassOptions, ImageBatchPlacement, ImageSampling, LogicalScreenVector,
7 TextAtlas2d, TextRun2d, WgpuRenderer,
8};
9
10use crate::{
11 ExtractedFrame, ResolvedScreenText,
12 identity::{LogicEntity, WorldGeneration},
13 text::{TextError, TextFont},
14};
15
16#[path = "text/prepared.rs"]
17mod prepared;
18use prepared::DesktopPreparedLine;
19#[path = "text/batches.rs"]
20mod batches;
21pub use batches::DesktopTextUpdates;
22
23#[derive(Debug)]
28pub enum DesktopTextError {
29 Settings {
31 source: LogicEntity,
33 error: TextError,
35 },
36 Engine {
38 source: LogicEntity,
40 error: sim_engine::TextError,
42 },
43 Prepared {
45 source: LogicEntity,
47 error: sim_engine::PreparedTextError,
49 },
50 Batch {
52 source: LogicEntity,
54 error: sim_engine::GlyphError,
56 },
57 BatchSizeOverflow,
59 Allocation {
61 requested_bytes: usize,
63 },
64 InvalidDrawPlan,
66}
67
68impl fmt::Display for DesktopTextError {
69 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70 match self {
71 Self::Settings { source, error } => write!(f, "text {source:?} settings: {error}"),
72 Self::Engine { source, error } => write!(f, "text {source:?} preparation: {error}"),
73 Self::Prepared { source, error } => {
74 write!(f, "text {source:?} prepared layout: {error}")
75 }
76 Self::Batch { source, error } => {
77 write!(f, "text group starting at {source:?}: {error}")
78 }
79 Self::BatchSizeOverflow => f.write_str("text group size exceeds addressable limits"),
80 Self::Allocation { requested_bytes } => {
81 write!(f, "text cache could not reserve {requested_bytes} bytes")
82 }
83 Self::InvalidDrawPlan => f.write_str("text snapshot and desktop cache disagree"),
84 }
85 }
86}
87
88impl Error for DesktopTextError {
89 fn source(&self) -> Option<&(dyn Error + 'static)> {
90 match self {
91 Self::Settings { error, .. } => Some(error),
92 Self::Engine { error, .. } => Some(error),
93 Self::Prepared { error, .. } => Some(error),
94 Self::Batch { error, .. } => Some(error),
95 _ => None,
96 }
97 }
98}
99
100struct FontEntry {
101 font: TextFont,
102 atlas: TextAtlas2d,
103}
104
105struct RunEntry {
106 source: LogicEntity,
107 font: TextFont,
108 run: TextRun2d,
109}
110
111#[derive(Default)]
115pub(super) struct DesktopText {
116 cache: RetainedTextCache<FontEntry, RunEntry>,
117 batches: Vec<batches::BatchEntry>,
118 pub(super) updates: DesktopTextUpdates,
119}
120
121struct RetainedTextCache<Font, Run> {
123 fonts: Vec<Font>,
124 runs: Vec<Run>,
125 live: Vec<u64>,
126 generation: Option<WorldGeneration>,
127 scale_bits: Option<u32>,
128}
129
130impl<Font, Run> Default for RetainedTextCache<Font, Run> {
131 fn default() -> Self {
132 Self {
133 fonts: Vec::new(),
134 runs: Vec::new(),
135 live: Vec::new(),
136 generation: None,
137 scale_bits: None,
138 }
139 }
140}
141
142impl<Font, Run> RetainedTextCache<Font, Run> {
143 fn clear(&mut self) {
144 self.runs.clear();
145 self.fonts.clear();
146 self.live.clear();
147 self.generation = None;
148 self.scale_bits = None;
149 }
150
151 fn begin_frame(
152 &mut self,
153 generation: WorldGeneration,
154 scale: f32,
155 clear_frame_bindings: impl FnOnce(),
156 ) {
157 if self.scale_bits != Some(scale.to_bits()) {
158 if self.scale_bits.is_some() {
161 clear_frame_bindings();
162 }
163 self.clear();
164 self.scale_bits = Some(scale.to_bits());
165 }
166 if self.generation != Some(generation) {
167 self.runs.clear();
168 self.generation = Some(generation);
169 }
170 }
171
172 fn retain_visible_runs(
173 &mut self,
174 labels: impl ExactSizeIterator<Item = (LogicEntity, bool)>,
175 source: impl Fn(&Run) -> LogicEntity,
176 ) -> Result<(), DesktopTextError> {
177 self.live.clear();
178 self.live
179 .try_reserve(labels.len())
180 .map_err(|_| DesktopTextError::Allocation {
181 requested_bytes: labels.len().saturating_mul(size_of::<u64>()),
182 })?;
183 self.live.extend(
184 labels.filter_map(|(source, nonempty)| nonempty.then_some(source.stable_bits())),
185 );
186 self.live.sort_unstable();
187 self.runs
188 .retain(|run| self.live.binary_search(&source(run).stable_bits()).is_ok());
189 Ok(())
190 }
191}
192
193impl DesktopText {
194 pub(super) fn has_runs(&self) -> bool {
195 !self.cache.runs.is_empty()
196 }
197
198 pub(super) fn clear(&mut self) {
199 self.batches.clear();
200 self.cache.clear();
201 self.updates = DesktopTextUpdates::default();
202 }
203
204 pub(super) fn prepare(
205 &mut self,
206 renderer: &mut WgpuRenderer,
207 extracted: &ExtractedFrame,
208 batching: bool,
209 ) -> Result<(), DesktopTextError> {
210 let started = std::time::Instant::now();
211 self.updates = DesktopTextUpdates::default();
212 let scale = renderer.scale_factor() as f32;
213 if self.cache.generation != Some(extracted.world_generation())
214 || self.cache.scale_bits != Some(scale.to_bits())
215 || !batching
216 {
217 self.batches.clear();
218 }
219 self.cache
220 .begin_frame(extracted.world_generation(), scale, || {
221 renderer.clear_frame_cache()
222 });
223 self.cache.retain_visible_runs(
224 extracted.resolved_screen_texts().iter().map(|text| {
225 (
226 text.source(),
227 !text.text().is_empty()
228 && text.visual().clip() != crate::screen::ScreenClip::Empty,
229 )
230 }),
231 |run| run.source,
232 )?;
233 for visual in extracted.resolved_screen_texts() {
234 if !visual.text().is_empty()
235 && visual.visual().clip() != crate::screen::ScreenClip::Empty
236 {
237 self.prepare_one(renderer, visual, scale)?;
238 }
239 }
240 self.updates.source_cpu_time = started.elapsed();
241 if batching {
242 if let Err(error) = self.prepare_batches(renderer, extracted) {
245 self.batches.clear();
246 return Err(error);
247 }
248 }
249 Ok(())
250 }
251
252 fn prepare_one(
253 &mut self,
254 renderer: &WgpuRenderer,
255 visual: &ResolvedScreenText,
256 scale: f32,
257 ) -> Result<(), DesktopTextError> {
258 let source = visual.source();
259 let font = visual.font();
260 let font_index = match self
261 .cache
262 .fonts
263 .binary_search_by_key(&font.slot(), |entry| entry.font.slot())
264 {
265 Ok(index) => index,
266 Err(index) => {
267 self.cache
268 .fonts
269 .try_reserve(1)
270 .map_err(|_| DesktopTextError::Allocation {
271 requested_bytes: size_of::<FontEntry>(),
272 })?;
273 let settings = font.settings();
274 let style = settings
275 .style(scale)
276 .map_err(|error| DesktopTextError::Settings { source, error })?;
277 let atlas = TextAtlas2d::new(
278 renderer,
279 font.face().clone(),
280 style,
281 settings.atlas_budget(),
282 )
283 .map_err(|error| DesktopTextError::Engine { source, error })?;
284 self.cache.fonts.insert(
285 index,
286 FontEntry {
287 font: font.clone(),
288 atlas,
289 },
290 );
291 index
292 }
293 };
294 let atlas = &mut self.cache.fonts[font_index].atlas;
295 let existing = self
296 .cache
297 .runs
298 .binary_search_by_key(&source.stable_bits(), |entry| entry.source.stable_bits());
299 if let Ok(index) = existing {
300 let entry = &self.cache.runs[index];
301 if entry.font == *font && entry.run.text() == visual.text() {
302 return Ok(());
304 }
305 }
306 let prepared = DesktopPreparedLine::new(visual.visual(), scale)
307 .map_err(|error| DesktopTextError::Settings { source, error })?;
308 let shaped = prepared.line();
309 match existing {
310 Ok(index) => {
311 let entry = &mut self.cache.runs[index];
312 if entry.font != *font {
313 let run = atlas
315 .prepare_from_shaped(renderer, shaped, font.settings().layout_budget())
316 .map_err(|error| DesktopTextError::Prepared { source, error })?;
317 *entry = RunEntry {
318 source,
319 font: font.clone(),
320 run,
321 };
322 } else if entry.run.text() != visual.text() {
323 atlas
324 .update_from_shaped(
325 renderer,
326 &mut entry.run,
327 shaped,
328 font.settings().layout_budget(),
329 )
330 .map_err(|error| DesktopTextError::Prepared { source, error })?;
331 }
332 }
333 Err(index) => {
334 self.cache
335 .runs
336 .try_reserve(1)
337 .map_err(|_| DesktopTextError::Allocation {
338 requested_bytes: size_of::<RunEntry>(),
339 })?;
340 let run = atlas
341 .prepare_from_shaped(renderer, shaped, font.settings().layout_budget())
342 .map_err(|error| DesktopTextError::Prepared { source, error })?;
343 self.cache.runs.insert(
344 index,
345 RunEntry {
346 source,
347 font: font.clone(),
348 run,
349 },
350 );
351 }
352 }
353 Ok(())
354 }
355
356 pub(super) fn draw<'a>(
357 &'a self,
358 frame: &mut FrameComposer<'a>,
359 visual: &ResolvedScreenText,
360 options: FramePassOptions,
361 ) -> Result<(), super::images::ScreenPresentationError> {
362 let font_index = self
363 .cache
364 .fonts
365 .binary_search_by_key(&visual.font().slot(), |entry| entry.font.slot())
366 .map_err(|_| DesktopTextError::InvalidDrawPlan)?;
367 let run_index = self
368 .cache
369 .runs
370 .binary_search_by_key(&visual.source().stable_bits(), |entry| {
371 entry.source.stable_bits()
372 })
373 .map_err(|_| DesktopTextError::InvalidDrawPlan)?;
374 let run = &self.cache.runs[run_index];
375 if run.source != visual.source()
376 || run.font != *visual.font()
377 || run.run.text() != visual.text()
378 {
379 return Err(DesktopTextError::InvalidDrawPlan.into());
380 }
381 let position = visual.baseline_origin().to_vec2();
382 let placement = ImageBatchPlacement::new(
383 LogicalScreenVector::new(position.x(), position.y()),
384 visual.tint(),
385 )
386 .map_err(|error| DesktopTextError::Engine {
387 source: visual.source(),
388 error: sim_engine::TextError::Glyph(sim_engine::GlyphError::Image(error)),
389 })?;
390 frame.draw_glyph_run_placed(
391 self.cache.fonts[font_index].atlas.atlas(),
392 run.run.glyph_run(),
393 placement,
394 ImageSampling::Linear,
395 options,
396 )?;
397 Ok(())
398 }
399}
400
401#[cfg(test)]
402#[path = "text/batch_tests.rs"]
403mod batch_tests;
404#[cfg(test)]
405#[path = "text/tests.rs"]
406mod tests;