1use std::marker::PhantomData;
2use std::rc::Rc;
3
4use crate::texture::{TextureFormat, TextureRect, TextureRef, get_format_bytes_per_pixel};
5use crate::{Ui, sys};
6
7use super::state::{
8 current_context_font_atlas, custom_rect_nonce_is_active, font_atlas_state,
9 register_custom_rect_nonce, unregister_custom_rect_nonce,
10};
11use super::{FontAtlas, FontAtlasTexture};
12
13#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
18pub struct CustomRectId {
19 raw: sys::ImFontAtlasRectId,
20 atlas: *mut sys::ImFontAtlas,
21 atlas_stamp: u64,
22 generation: u64,
23 nonce: u64,
24 _not_send_sync: PhantomData<Rc<()>>,
25}
26
27impl CustomRectId {
28 fn from_raw_parts(raw: sys::ImFontAtlasRectId, atlas: *mut sys::ImFontAtlas) -> Self {
29 assert!(raw >= 0, "CustomRectId requires a valid native ID");
30 let (state, nonce) = register_custom_rect_nonce(atlas, raw);
31 Self {
32 raw,
33 atlas,
34 atlas_stamp: state.stamp,
35 generation: state.custom_rect_generation,
36 nonce,
37 _not_send_sync: PhantomData,
38 }
39 }
40}
41
42#[derive(Copy, Clone, Debug)]
44pub struct CustomRectData<'data> {
45 size: [u16; 2],
46 format: TextureFormat,
47 pixels: &'data [u8],
48}
49
50impl<'data> CustomRectData<'data> {
51 pub fn rgba32(size: [u16; 2], pixels: &'data [u8]) -> Self {
53 Self::new(size, TextureFormat::RGBA32, pixels)
54 }
55
56 pub fn alpha8(size: [u16; 2], pixels: &'data [u8]) -> Self {
58 Self::new(size, TextureFormat::Alpha8, pixels)
59 }
60
61 fn new(size: [u16; 2], format: TextureFormat, pixels: &'data [u8]) -> Self {
62 assert!(
63 size[0] > 0 && size[1] > 0,
64 "CustomRectData dimensions must be positive"
65 );
66 let expected = usize::from(size[0])
67 .checked_mul(usize::from(size[1]))
68 .and_then(|pixels| pixels.checked_mul(get_format_bytes_per_pixel(format)))
69 .expect("CustomRectData byte length overflowed usize");
70 assert_eq!(
71 pixels.len(),
72 expected,
73 "CustomRectData pixel byte count does not match its size and format"
74 );
75 Self {
76 size,
77 format,
78 pixels,
79 }
80 }
81
82 pub fn size(&self) -> [u16; 2] {
84 self.size
85 }
86
87 pub fn format(&self) -> TextureFormat {
89 self.format
90 }
91}
92
93#[derive(Debug)]
98pub struct CustomRectSnapshot<'scope> {
99 atlas: *mut sys::ImFontAtlas,
100 texture: sys::ImTextureRef,
101 _texture_lease: Option<FontAtlasTexture<'scope>>,
102 pixels: TextureRect,
103 uv0: [f32; 2],
104 uv1: [f32; 2],
105}
106
107impl<'scope> CustomRectSnapshot<'scope> {
108 pub fn texture(&self) -> TextureRef<'_> {
110 TextureRef::from_font_atlas_raw(self.atlas, self.texture)
111 }
112
113 pub fn pixels(&self) -> TextureRect {
115 self.pixels
116 }
117
118 pub fn uv0(&self) -> [f32; 2] {
120 self.uv0
121 }
122
123 pub fn uv1(&self) -> [f32; 2] {
125 self.uv1
126 }
127}
128
129fn validate_for_atlas(
130 id: CustomRectId,
131 atlas: *mut sys::ImFontAtlas,
132 caller: &str,
133) -> Option<sys::ImFontAtlasRectId> {
134 assert!(
135 std::ptr::addr_eq(id.atlas.cast_const(), atlas.cast_const()),
136 "{caller} received a CustomRectId from a different font atlas"
137 );
138 let state = font_atlas_state(atlas);
139 assert_eq!(
140 id.atlas_stamp, state.stamp,
141 "{caller} received a CustomRectId from a destroyed or reused font atlas"
142 );
143 assert_eq!(
144 id.generation, state.custom_rect_generation,
145 "{caller} received a stale CustomRectId invalidated by font atlas mutation"
146 );
147 custom_rect_nonce_is_active(atlas, id.raw, id.nonce).then_some(id.raw)
148}
149
150fn get_native_rect(
151 atlas: *mut sys::ImFontAtlas,
152 id: CustomRectId,
153 caller: &str,
154) -> Option<sys::ImFontAtlasRect> {
155 let raw_id = validate_for_atlas(id, atlas, caller)?;
156 let mut rect = sys::ImFontAtlasRect::default();
157 if unsafe { sys::ImFontAtlas_GetCustomRect(atlas, raw_id, &mut rect) } {
158 Some(rect)
159 } else {
160 None
161 }
162}
163
164unsafe fn snapshot_from_native<'scope>(
165 atlas: *mut sys::ImFontAtlas,
166 rect: sys::ImFontAtlasRect,
167 texture_lease: Option<FontAtlasTexture<'scope>>,
168) -> CustomRectSnapshot<'scope> {
169 CustomRectSnapshot {
170 atlas,
171 texture: unsafe { (*atlas).TexRef },
172 _texture_lease: texture_lease,
173 pixels: TextureRect {
174 x: rect.x,
175 y: rect.y,
176 w: rect.w,
177 h: rect.h,
178 },
179 uv0: [rect.uv0.x, rect.uv0.y],
180 uv1: [rect.uv1.x, rect.uv1.y],
181 }
182}
183
184impl FontAtlas {
185 #[doc(alias = "AddCustomRect")]
189 pub fn add_custom_rect(&self, data: CustomRectData<'_>) -> Option<CustomRectId> {
190 self.assert_mutation_allowed("FontAtlas::add_custom_rect()");
191 self.assert_custom_rect_write_supported(data, "FontAtlas::add_custom_rect()");
192 let atlas = self.raw();
193 let mut rect = sys::ImFontAtlasRect::default();
194 let raw_id = unsafe {
195 sys::ImFontAtlas_AddCustomRect(
196 atlas,
197 i32::from(data.size[0]),
198 i32::from(data.size[1]),
199 &mut rect,
200 )
201 };
202 if raw_id < 0 {
203 return None;
204 }
205
206 self.write_native_rect(rect, data);
207 Some(CustomRectId::from_raw_parts(raw_id, atlas))
208 }
209
210 pub fn write_custom_rect(&self, id: CustomRectId, data: CustomRectData<'_>) -> bool {
214 self.assert_mutation_allowed("FontAtlas::write_custom_rect()");
215 self.assert_custom_rect_write_supported(data, "FontAtlas::write_custom_rect()");
216 let Some(rect) = get_native_rect(self.raw(), id, "FontAtlas::write_custom_rect()") else {
217 return false;
218 };
219 assert_eq!(
220 data.size,
221 [rect.w, rect.h],
222 "FontAtlas::write_custom_rect() data size must match the allocated rectangle"
223 );
224 self.write_native_rect(rect, data);
225 true
226 }
227
228 #[doc(alias = "RemoveCustomRect")]
232 pub fn remove_custom_rect(&self, id: CustomRectId) -> bool {
233 self.assert_mutation_allowed("FontAtlas::remove_custom_rect()");
234 let atlas = self.raw();
235 let Some(raw_id) = validate_for_atlas(id, atlas, "FontAtlas::remove_custom_rect()") else {
236 return false;
237 };
238 let exists = unsafe { sys::ImFontAtlas_GetCustomRect(atlas, raw_id, std::ptr::null_mut()) };
239 if exists {
240 unsafe { sys::ImFontAtlas_RemoveCustomRect(atlas, raw_id) };
241 }
242 unregister_custom_rect_nonce(atlas, raw_id, id.nonce);
243 exists
244 }
245
246 #[doc(alias = "GetCustomRect")]
249 pub fn custom_rect(&self, id: CustomRectId) -> Option<CustomRectSnapshot<'_>> {
250 let atlas = self.raw();
251 let rect = get_native_rect(atlas, id, "FontAtlas::custom_rect()")?;
252 let texture_lease = self.tex_data_internal();
253 Some(unsafe { snapshot_from_native(atlas, rect, texture_lease) })
254 }
255
256 fn assert_custom_rect_write_supported(&self, data: CustomRectData<'_>, caller: &str) {
257 let atlas = self.raw();
258 unsafe {
259 let texture = (*atlas).TexData;
260 let destination_format = if texture.is_null() {
261 TextureFormat::from((*atlas).TexDesiredFormat)
262 } else {
263 TextureFormat::from((*texture).Format)
264 };
265 assert!(
266 data.format != TextureFormat::RGBA32 || destination_format == TextureFormat::RGBA32,
267 "{caller} cannot store RGBA32 pixels in an Alpha8 font atlas; use an RGBA32 atlas or alpha8 custom-rectangle data"
268 );
269 assert!(
270 (*atlas).RendererHasTextures
271 || texture.is_null()
272 || (*texture).Status != sys::ImTextureStatus_OK,
273 "{caller} cannot update an already-uploaded legacy font atlas; enable a renderer with RENDERER_HAS_TEXTURES or rebuild and fully re-upload the atlas"
274 );
275 }
276 }
277
278 fn write_native_rect(&self, rect: sys::ImFontAtlasRect, data: CustomRectData<'_>) {
279 let atlas = self.raw();
280 unsafe {
281 let texture = (*atlas).TexData;
282 assert!(
283 !texture.is_null() && !(*texture).Pixels.is_null(),
284 "custom rectangle requires allocated atlas texture pixels"
285 );
286 assert!(
287 (*texture).Status != sys::ImTextureStatus_WantDestroy
288 && (*texture).Status != sys::ImTextureStatus_Destroyed,
289 "custom rectangle texture is not writable in its current status"
290 );
291
292 let texture_width = usize::try_from((*texture).Width)
293 .expect("font atlas texture width must be non-negative");
294 let texture_height = usize::try_from((*texture).Height)
295 .expect("font atlas texture height must be non-negative");
296 let destination_bpp = usize::try_from((*texture).BytesPerPixel)
297 .expect("font atlas texture bytes per pixel must be non-negative");
298 assert_eq!(
299 destination_bpp,
300 get_format_bytes_per_pixel(TextureFormat::from((*texture).Format)),
301 "font atlas texture format and bytes-per-pixel metadata disagree"
302 );
303 let x = usize::from(rect.x);
304 let y = usize::from(rect.y);
305 let width = usize::from(rect.w);
306 let height = usize::from(rect.h);
307 assert!(
308 x.checked_add(width).is_some_and(|end| end <= texture_width)
309 && y.checked_add(height)
310 .is_some_and(|end| end <= texture_height),
311 "custom rectangle exceeds the current atlas texture"
312 );
313
314 let source_bpp = get_format_bytes_per_pixel(data.format);
315 let source_pitch = width
316 .checked_mul(source_bpp)
317 .expect("custom rectangle source pitch overflowed usize");
318 let destination_pitch = texture_width
319 .checked_mul(destination_bpp)
320 .expect("font atlas texture pitch overflowed usize");
321 let destination_offset = y
322 .checked_mul(texture_width)
323 .and_then(|offset| offset.checked_add(x))
324 .and_then(|offset| offset.checked_mul(destination_bpp))
325 .expect("custom rectangle destination offset overflowed usize");
326 let destination = (*texture).Pixels.add(destination_offset);
327 let destination_format = TextureFormat::from((*texture).Format);
328 for row in 0..height {
329 let source_row = data.pixels.as_ptr().add(row * source_pitch);
330 let destination_row = destination.add(row * destination_pitch);
331 match (data.format, destination_format) {
332 (TextureFormat::RGBA32, TextureFormat::RGBA32)
333 | (TextureFormat::Alpha8, TextureFormat::Alpha8) => {
334 std::ptr::copy_nonoverlapping(source_row, destination_row, source_pitch);
335 }
336 (TextureFormat::Alpha8, TextureFormat::RGBA32) => {
337 for column in 0..width {
338 let alpha = *source_row.add(column);
339 let pixel = destination_row.add(column * 4);
340 std::ptr::copy_nonoverlapping(
341 [255, 255, 255, alpha].as_ptr(),
342 pixel,
343 4,
344 );
345 }
346 }
347 (TextureFormat::RGBA32, TextureFormat::Alpha8) => unreachable!(
348 "RGBA32 to Alpha8 custom-rectangle writes are rejected before mutation"
349 ),
350 }
351 }
352 if data.format == TextureFormat::RGBA32 {
353 (*atlas).TexPixelsUseColors = true;
354 (*texture).UseColors = true;
355 }
356 if (*atlas).RendererHasTextures {
357 sys::igImFontAtlasTextureBlockQueueUpload(
358 atlas,
359 texture,
360 i32::from(rect.x),
361 i32::from(rect.y),
362 i32::from(rect.w),
363 i32::from(rect.h),
364 );
365 }
366 }
367 }
368}
369
370impl Ui {
371 pub fn custom_rect(&self, id: CustomRectId) -> Option<CustomRectSnapshot<'_>> {
373 self.run_with_bound_context(|| {
374 let atlas = current_context_font_atlas("Ui::custom_rect()");
375 let rect = get_native_rect(atlas, id, "Ui::custom_rect()")?;
376 Some(unsafe { snapshot_from_native(atlas, rect, None) })
377 })
378 }
379
380 pub fn image_custom_rect(&self, id: CustomRectId, size: [f32; 2]) -> bool {
384 let Some(rect) = self.custom_rect(id) else {
385 return false;
386 };
387 self.image_config(rect.texture(), size)
388 .uv0(rect.uv0())
389 .uv1(rect.uv1())
390 .build();
391 true
392 }
393}
394
395#[cfg(test)]
396mod tests {
397 use super::*;
398
399 #[test]
400 fn custom_rect_writes_pixels_and_queues_exact_updates() {
401 let ctx = crate::Context::create();
402 let pixels = [
403 255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255,
404 ];
405 let id = ctx
406 .font_atlas()
407 .add_custom_rect(CustomRectData::rgba32([2, 2], &pixels))
408 .expect("the custom rectangle should fit");
409
410 let snapshot = ctx
411 .font_atlas()
412 .custom_rect(id)
413 .expect("the custom rectangle should resolve");
414 assert_eq!(snapshot.pixels().w, 2);
415 assert_eq!(snapshot.pixels().h, 2);
416
417 let rect = snapshot.pixels();
418 drop(snapshot);
419 let atlas = ctx.font_atlas();
420 unsafe {
421 (*atlas.raw()).RendererHasTextures = true;
422 (*(*atlas.raw()).TexData).Status = sys::ImTextureStatus_OK;
423 }
424
425 let replacement = [7u8; 16];
426 assert!(atlas.write_custom_rect(id, CustomRectData::rgba32([2, 2], &replacement)));
427 let updates: Vec<_> = atlas
428 .tex_data_internal()
429 .expect("atlas texture should remain available")
430 .updates()
431 .collect();
432 assert_eq!(updates.last().copied(), Some(rect));
433 }
434
435 #[test]
436 fn custom_rect_snapshot_leases_its_texture_until_drop() {
437 let ctx = crate::Context::create();
438 let atlas = ctx.font_atlas();
439 let id = atlas
440 .add_custom_rect(CustomRectData::alpha8([1, 1], &[0x7f]))
441 .expect("the custom rectangle should fit");
442 let snapshot = atlas
443 .custom_rect(id)
444 .expect("the custom rectangle should resolve");
445
446 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
447 let _ = atlas.write_custom_rect(id, CustomRectData::alpha8([1, 1], &[0xff]));
448 }));
449 assert!(result.is_err());
450
451 drop(snapshot);
452 assert!(atlas.write_custom_rect(id, CustomRectData::alpha8([1, 1], &[0xff])));
453 }
454
455 #[test]
456 fn custom_rect_rejects_updates_after_a_legacy_upload() {
457 let ctx = crate::Context::create();
458 let id = ctx
459 .font_atlas()
460 .add_custom_rect(CustomRectData::alpha8([1, 1], &[0x7f]))
461 .expect("the custom rectangle should fit");
462 let legacy = ctx
463 .font_atlas()
464 .try_claim_legacy_renderer()
465 .expect("the test models a legacy renderer");
466 unsafe {
467 legacy.set_texture_id(crate::TextureId::new(17));
469 }
470
471 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
472 let _ = ctx
473 .font_atlas()
474 .write_custom_rect(id, CustomRectData::alpha8([1, 1], &[0xff]));
475 }));
476 assert!(result.is_err());
477 }
478
479 #[test]
480 fn custom_rect_rejects_rgba_data_for_an_alpha_atlas_before_reading_alignment() {
481 let ctx = crate::Context::create();
482 let atlas = ctx.font_atlas();
483 unsafe { (*atlas.raw()).TexDesiredFormat = sys::ImTextureFormat_Alpha8 };
484 let legacy = atlas
485 .try_claim_legacy_renderer()
486 .expect("the test requires a legacy font atlas");
487 legacy.build();
488 assert_eq!(
489 legacy
490 .tex_data()
491 .expect("atlas texture should exist")
492 .format(),
493 TextureFormat::Alpha8
494 );
495
496 let storage = [0u8; 8];
497 let alignment = std::mem::align_of::<u32>();
498 let offset = (0..alignment)
499 .find(|offset| (storage.as_ptr() as usize + offset) % alignment != 0)
500 .expect("one of the first u32-alignment offsets must be unaligned");
501 let unaligned_rgba = &storage[offset..offset + 4];
502 assert_ne!((unaligned_rgba.as_ptr() as usize) % alignment, 0);
503 let builder = unsafe { (*atlas.raw()).Builder };
504 assert!(!builder.is_null());
505 let rect_count_before = unsafe { (*builder).RectsIndex.Size };
506 let texture_status_before = unsafe { (*(*atlas.raw()).TexData).Status };
507 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
508 let _ = atlas.add_custom_rect(CustomRectData::rgba32([1, 1], unaligned_rgba));
509 }));
510 let panic = result.expect_err("RGBA32 data must be rejected before FFI");
511 let message = panic
512 .downcast_ref::<String>()
513 .map(String::as_str)
514 .or_else(|| panic.downcast_ref::<&str>().copied())
515 .unwrap_or_default();
516 assert!(message.contains("cannot store RGBA32 pixels in an Alpha8 font atlas"));
517 assert_eq!(unsafe { (*builder).RectsIndex.Size }, rect_count_before);
518 assert_eq!(
519 unsafe { (*(*atlas.raw()).TexData).Status },
520 texture_status_before
521 );
522 }
523
524 #[test]
525 fn custom_rect_converts_alpha_pixels_to_rgba() {
526 let ctx = crate::Context::create();
527 let id = ctx
528 .font_atlas()
529 .add_custom_rect(CustomRectData::alpha8([1, 1], &[0x7f]))
530 .expect("the custom rectangle should fit");
531 let rect = ctx
532 .font_atlas()
533 .custom_rect(id)
534 .expect("the custom rectangle should resolve")
535 .pixels();
536 let legacy = ctx
537 .font_atlas()
538 .try_claim_legacy_renderer()
539 .expect("the test requires a legacy font atlas");
540 let texture = legacy.tex_data().expect("atlas texture should exist");
541 let pixel = texture
542 .pixels_at(u32::from(rect.x), u32::from(rect.y))
543 .expect("custom rectangle pixel should be addressable");
544 assert_eq!(&pixel[..4], &[255, 255, 255, 0x7f]);
545 }
546
547 #[test]
548 fn removed_and_cross_atlas_custom_rect_ids_are_rejected() {
549 let ctx_a = crate::Context::create();
550 let id = ctx_a
551 .font_atlas()
552 .add_custom_rect(CustomRectData::alpha8([1, 1], &[255]))
553 .expect("the custom rectangle should fit");
554 assert!(ctx_a.font_atlas().remove_custom_rect(id));
555 assert!(!ctx_a.font_atlas().remove_custom_rect(id));
556 let suspended_a = ctx_a.suspend_or_panic();
557
558 let ctx_b = crate::Context::create();
559 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
560 let _ = ctx_b.font_atlas().custom_rect(id);
561 }));
562 assert!(result.is_err());
563
564 drop(ctx_b);
565 drop(suspended_a);
566 }
567
568 #[test]
569 fn removed_custom_rect_id_does_not_revive_after_native_generation_wrap() {
570 let ctx = crate::Context::create();
571 let atlas = ctx.font_atlas();
572 let data = CustomRectData::alpha8([1, 1], &[255]);
573
574 let generation_zero = atlas
575 .add_custom_rect(data)
576 .expect("the initial custom rectangle should fit");
577 assert!(atlas.remove_custom_rect(generation_zero));
578
579 let stale = atlas
580 .add_custom_rect(data)
581 .expect("the reusable custom rectangle should fit");
582 assert!(atlas.remove_custom_rect(stale));
583
584 for _ in 0..1022 {
585 let current = atlas
586 .add_custom_rect(data)
587 .expect("the recycled custom rectangle should fit");
588 assert!(atlas.remove_custom_rect(current));
589 }
590
591 let replacement = atlas
592 .add_custom_rect(data)
593 .expect("the wrapped custom rectangle should fit");
594 assert_eq!(
595 stale.raw, replacement.raw,
596 "the test must exercise native ID reuse after its 10-bit generation wraps"
597 );
598 assert!(atlas.custom_rect(stale).is_none());
599 assert!(!atlas.write_custom_rect(stale, data));
600 assert!(!atlas.remove_custom_rect(stale));
601 assert!(atlas.custom_rect(replacement).is_some());
602 }
603
604 #[test]
605 fn custom_rect_data_requires_an_exact_pixel_count() {
606 assert!(std::panic::catch_unwind(|| CustomRectData::rgba32([2, 2], &[0; 15])).is_err());
607 }
608
609 #[test]
610 fn custom_rect_id_survives_repacking_but_not_builder_clear() {
611 let ctx = crate::Context::create();
612 let discarded = ctx
613 .font_atlas()
614 .add_custom_rect(CustomRectData::alpha8([32, 32], &[255; 32 * 32]))
615 .expect("the first custom rectangle should fit");
616 let retained = ctx
617 .font_atlas()
618 .add_custom_rect(CustomRectData::alpha8([16, 16], &[127; 16 * 16]))
619 .expect("the second custom rectangle should fit");
620 assert!(ctx.font_atlas().remove_custom_rect(discarded));
621 ctx.font_atlas().compact_cache();
622 assert!(ctx.font_atlas().custom_rect(retained).is_some());
623
624 ctx.font_atlas().clear_fonts();
625 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
626 let _ = ctx.font_atlas().custom_rect(retained);
627 }));
628 assert!(result.is_err());
629 }
630
631 #[test]
632 fn ui_draws_custom_rect_from_a_fresh_frame_snapshot() {
633 let mut ctx = crate::Context::create();
634 let id = ctx
635 .font_atlas()
636 .add_custom_rect(CustomRectData::rgba32([1, 1], &[255, 0, 0, 255]))
637 .expect("the custom rectangle should fit");
638 ctx.font_atlas()
639 .try_claim_legacy_renderer()
640 .expect("legacy renderer font atlas should be available")
641 .build();
642 ctx.io_mut().set_display_size([128.0, 128.0]);
643 ctx.io_mut().set_delta_time(1.0 / 60.0);
644
645 assert!(ctx.frame().image_custom_rect(id, [8.0, 8.0]));
646 let _ = ctx.render_legacy();
647 }
648}