1use std::cell::RefCell;
2use std::collections::HashMap;
3use std::fmt;
4use std::num::NonZeroU64;
5use std::rc::Rc;
6use std::sync::Arc;
7
8use crate::render::snapshot::{
9 CapturedTextureOperation, PendingTextureRequest, RendererConsumerError,
10 ResolvedSnapshotTexture, SnapshotError, SnapshotTextureId, TextureFeedback,
11 TextureFeedbackResult, TextureOp, TextureRequestKind,
12};
13use crate::sys;
14use crate::texture::{
15 ManagedTextureError, ManagedTextureId, ManagedTextureMut, ManagedTextureMutationError,
16 ManagedTextureRef, OwnedTextureData, TextureData, TextureDataError, TextureStatus,
17};
18
19use super::binding::CTX_MUTEX;
20use super::texture_sync::{TextureSyncQueue, cumulative_update_rect, update_pending_create};
21use super::{Context, ContextId};
22
23pub(crate) type SharedTextureRegistry = Rc<RefCell<ManagedTextureRegistry>>;
24
25#[derive(Debug)]
26pub(crate) struct FontAtlasSnapshotTarget {
27 atlas: *mut sys::ImFontAtlas,
28 context: ContextId,
29 textures: Vec<FontAtlasTextureTarget>,
30}
31
32#[derive(Copy, Clone, Debug)]
33pub(crate) struct FontAtlasTextureTarget {
34 id: SnapshotTextureId,
35 texture: *mut sys::ImTextureData,
36}
37
38impl FontAtlasSnapshotTarget {
39 pub(crate) fn new(
40 atlas: *mut sys::ImFontAtlas,
41 context: ContextId,
42 textures: Vec<FontAtlasTextureTarget>,
43 ) -> Self {
44 Self {
45 atlas,
46 context,
47 textures,
48 }
49 }
50
51 pub(crate) fn resolve(
52 &self,
53 native: *const sys::ImTextureData,
54 ) -> Option<ResolvedSnapshotTexture> {
55 self.textures
56 .iter()
57 .find(|target| std::ptr::eq(native, target.texture.cast_const()))
58 .map(|target| ResolvedSnapshotTexture { id: target.id })
59 }
60
61 fn find(&self, id: SnapshotTextureId) -> Option<FontAtlasTextureTarget> {
62 self.textures.iter().find(|target| target.id == id).copied()
63 }
64
65 pub(crate) fn record_request_reference(&self, id: SnapshotTextureId, epoch: u64) {
66 crate::fonts::record_font_atlas_texture_reference(self.atlas, id, epoch);
67 }
68
69 fn identity_is_known(&self, id: SnapshotTextureId) -> bool {
70 matches!(id, SnapshotTextureId::FontAtlas { context, .. } if context == self.context)
71 && crate::fonts::font_atlas_texture_identity_is_known(self.atlas, id)
72 }
73
74 pub(crate) fn prune_tombstones(&self, watermark: u64) {
75 crate::fonts::prune_font_atlas_texture_tombstones(self.atlas, self.context, watermark);
76 }
77
78 pub(crate) fn reset_renderer_bindings(&self) {
79 for target in &self.textures {
80 let texture = unsafe { TextureData::from_raw(target.texture) };
81 if texture.ref_count() != 1 || texture.status() == TextureStatus::Destroyed {
82 continue;
83 }
84 unsafe {
85 texture.set_status(TextureStatus::Destroyed);
88 }
89 }
90 crate::fonts::mark_font_atlas_renderer_reset(self.atlas);
91 }
92}
93
94impl FontAtlasTextureTarget {
95 pub(crate) fn new(id: SnapshotTextureId, texture: *mut sys::ImTextureData) -> Self {
96 Self { id, texture }
97 }
98}
99
100pub(crate) struct ManagedTextureRegistry {
101 context: ContextId,
102 slots: Vec<TextureSlot>,
103 reusable: Vec<u32>,
104 frame_removals: Vec<u32>,
105 by_native: HashMap<usize, ManagedTextureId>,
106 native_refresh_generation: u64,
107 sync: TextureSyncQueue,
108}
109
110enum TextureSlot {
111 Active(TextureEntry),
112 Retiring(TextureEntry),
113 NativeExposed {
114 entry: TextureEntry,
115 release_after_refresh: u64,
116 },
117 Retired {
118 generation: NonZeroU64,
119 },
120 Exhausted,
121}
122
123struct TextureEntry {
124 retire_after_frame: bool,
125 generation: NonZeroU64,
126 last_reference_epoch: u64,
127 destroy_ack_epoch: Option<u64>,
128 texture: OwnedTextureData,
129}
130
131impl fmt::Debug for ManagedTextureRegistry {
132 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
133 let active = self
134 .slots
135 .iter()
136 .filter(|slot| matches!(slot, TextureSlot::Active(_)))
137 .count();
138 let retiring = self
139 .slots
140 .iter()
141 .filter(|slot| matches!(slot, TextureSlot::Retiring(_)))
142 .count();
143 let native_exposed = self
144 .slots
145 .iter()
146 .filter(|slot| matches!(slot, TextureSlot::NativeExposed { .. }))
147 .count();
148 formatter
149 .debug_struct("ManagedTextureRegistry")
150 .field("context", &self.context)
151 .field("active", &active)
152 .field("retire_after_frame", &self.frame_removals.len())
153 .field("retiring", &retiring)
154 .field("native_exposed", &native_exposed)
155 .field("slot_count", &self.slots.len())
156 .finish()
157 }
158}
159
160impl ManagedTextureRegistry {
161 pub(crate) fn new(context: ContextId) -> SharedTextureRegistry {
162 Rc::new(RefCell::new(Self {
163 context,
164 slots: Vec::new(),
165 reusable: Vec::new(),
166 frame_removals: Vec::new(),
167 by_native: HashMap::new(),
168 native_refresh_generation: 0,
169 sync: TextureSyncQueue::default(),
170 }))
171 }
172
173 fn validate_context(&self, id: ManagedTextureId) -> Result<(), ManagedTextureError> {
174 if id.context_id() == self.context {
175 Ok(())
176 } else {
177 Err(ManagedTextureError::ForeignContext {
178 expected: self.context,
179 actual: id.context_id(),
180 })
181 }
182 }
183
184 fn slot(&self, id: ManagedTextureId) -> Result<&TextureSlot, ManagedTextureError> {
185 self.validate_context(id)?;
186 let slot = self
187 .slots
188 .get(id.slot() as usize)
189 .ok_or(ManagedTextureError::UnknownSlot(id))?;
190 let generation = match slot {
191 TextureSlot::Active(entry)
192 | TextureSlot::Retiring(entry)
193 | TextureSlot::NativeExposed { entry, .. } => entry.generation,
194 TextureSlot::Retired { generation } => *generation,
195 TextureSlot::Exhausted => return Err(ManagedTextureError::AlreadyRemoved(id)),
196 };
197 if generation != id.generation() {
198 return Err(ManagedTextureError::StaleGeneration(id));
199 }
200 Ok(slot)
201 }
202
203 fn active_entry(&self, id: ManagedTextureId) -> Result<&TextureEntry, ManagedTextureError> {
204 match self.slot(id)? {
205 TextureSlot::Active(entry) if !entry.retire_after_frame => Ok(entry),
206 TextureSlot::Active(_) | TextureSlot::Retiring(_) => {
207 Err(ManagedTextureError::Retiring(id))
208 }
209 TextureSlot::NativeExposed { .. }
210 | TextureSlot::Retired { .. }
211 | TextureSlot::Exhausted => Err(ManagedTextureError::AlreadyRemoved(id)),
212 }
213 }
214
215 fn active_entry_mut(
216 &mut self,
217 id: ManagedTextureId,
218 ) -> Result<&mut TextureEntry, ManagedTextureError> {
219 self.active_entry(id)?;
220 let TextureSlot::Active(entry) = &mut self.slots[id.slot() as usize] else {
221 unreachable!("validated active texture slot changed without a mutable alias")
222 };
223 Ok(entry)
224 }
225
226 fn allocate_slot(&mut self) -> (u32, NonZeroU64) {
227 while let Some(slot_index) = self.reusable.pop() {
228 let slot = &mut self.slots[slot_index as usize];
229 let TextureSlot::Retired { generation } = slot else {
230 debug_assert!(false, "reusable texture slot was not retired");
231 continue;
232 };
233 let Some(next) = generation.get().checked_add(1).and_then(NonZeroU64::new) else {
234 *slot = TextureSlot::Exhausted;
235 continue;
236 };
237 return (slot_index, next);
238 }
239
240 let slot_index = u32::try_from(self.slots.len())
241 .expect("managed texture registry exhausted its slot identity space");
242 (slot_index, NonZeroU64::MIN)
243 }
244
245 fn register(&mut self, mut texture: OwnedTextureData, watermark: u64) -> ManagedTextureId {
246 self.reap_destroyed(watermark);
247 let (slot_index, generation) = self.allocate_slot();
248 let id = ManagedTextureId::new(self.context, slot_index, generation);
249 let native = texture.as_mut().as_raw_mut();
250 assert_eq!(
251 texture.ref_count(),
252 0,
253 "Context::register_texture() received texture data already owned by native state"
254 );
255 unsafe {
256 sys::igRegisterUserTexture(native);
257 }
258 let entry = TextureEntry {
259 retire_after_frame: false,
260 generation,
261 last_reference_epoch: 0,
262 destroy_ack_epoch: None,
263 texture,
264 };
265 if slot_index as usize == self.slots.len() {
266 self.slots.push(TextureSlot::Active(entry));
267 } else {
268 self.slots[slot_index as usize] = TextureSlot::Active(entry);
269 }
270 let previous = self.by_native.insert(native as usize, id);
271 assert!(
272 previous.is_none(),
273 "native texture allocation was registered twice"
274 );
275 id
276 }
277
278 pub(crate) fn resolve(
279 &self,
280 id: ManagedTextureId,
281 ) -> Result<sys::ImTextureRef, ManagedTextureError> {
282 let entry = self.active_entry(id)?;
283 Ok(sys::ImTextureRef {
284 _TexData: entry.texture.as_raw() as *mut sys::ImTextureData,
285 _TexID: 0 as sys::ImTextureID,
286 })
287 }
288
289 pub(crate) fn id_for_native(
290 &self,
291 native: *const sys::ImTextureData,
292 ) -> Option<ManagedTextureId> {
293 self.by_native.get(&(native as usize)).copied()
294 }
295
296 pub(crate) fn resolve_snapshot_texture(
297 &self,
298 native: *const sys::ImTextureData,
299 atlas: &FontAtlasSnapshotTarget,
300 ) -> Result<ResolvedSnapshotTexture, SnapshotError> {
301 if let Some(id) = self.id_for_native(native) {
302 match self.slot(id)? {
303 TextureSlot::Active(_) | TextureSlot::Retiring(_) => {}
304 TextureSlot::NativeExposed { .. }
305 | TextureSlot::Retired { .. }
306 | TextureSlot::Exhausted => {
307 return Err(ManagedTextureError::AlreadyRemoved(id).into());
308 }
309 }
310 return Ok(ResolvedSnapshotTexture {
311 id: SnapshotTextureId::User(id),
312 });
313 }
314 if let Some(resolved) = atlas.resolve(native) {
315 return Ok(resolved);
316 }
317 Err(SnapshotError::UnknownManagedTexture)
318 }
319
320 pub(crate) fn record_snapshot_references(
321 &mut self,
322 ids: &std::collections::HashSet<ManagedTextureId>,
323 epoch: u64,
324 ) -> Result<(), ManagedTextureError> {
325 for id in ids {
326 match self.slot(*id)? {
327 TextureSlot::Active(_) | TextureSlot::Retiring(_) => {}
328 TextureSlot::NativeExposed { .. }
329 | TextureSlot::Retired { .. }
330 | TextureSlot::Exhausted => {
331 return Err(ManagedTextureError::AlreadyRemoved(*id));
332 }
333 }
334 }
335 for id in ids {
336 let slot = &mut self.slots[id.slot() as usize];
337 let entry = match slot {
338 TextureSlot::Active(entry) | TextureSlot::Retiring(entry) => entry,
339 TextureSlot::NativeExposed { .. }
340 | TextureSlot::Retired { .. }
341 | TextureSlot::Exhausted => unreachable!(),
342 };
343 entry.last_reference_epoch = entry.last_reference_epoch.max(epoch);
344 }
345 Ok(())
346 }
347
348 fn with_texture<R>(
349 &self,
350 id: ManagedTextureId,
351 f: impl for<'texture> FnOnce(ManagedTextureRef<'texture>) -> R,
352 ) -> Result<R, ManagedTextureError> {
353 let entry = self.active_entry(id)?;
354 Ok(f(ManagedTextureRef::new(&entry.texture)))
355 }
356
357 fn with_texture_mut<R>(
358 &mut self,
359 id: ManagedTextureId,
360 f: impl for<'texture> FnOnce(ManagedTextureMut<'texture>) -> R,
361 ) -> Result<R, ManagedTextureError> {
362 let entry = self.active_entry_mut(id)?;
363 Ok(f(ManagedTextureMut::new(&mut entry.texture)))
364 }
365
366 pub(crate) fn stage_snapshot_operations(
367 &mut self,
368 requests: &[CapturedTextureOperation],
369 atlas: &FontAtlasSnapshotTarget,
370 ) -> Result<Vec<PendingTextureRequest>, SnapshotError> {
371 let mut staged = Vec::with_capacity(requests.len());
374 for request in requests.iter() {
375 let native = match request.texture {
376 SnapshotTextureId::User(id) => match self.slot(id)? {
377 TextureSlot::Active(entry) | TextureSlot::Retiring(entry) => {
378 entry.texture.as_raw()
379 }
380 _ => return Err(ManagedTextureError::AlreadyRemoved(id).into()),
381 },
382 SnapshotTextureId::FontAtlas { .. } => atlas
383 .find(request.texture)
384 .ok_or(SnapshotError::UnknownManagedTexture)?
385 .texture
386 .cast_const(),
387 };
388 let texture = unsafe { TextureData::from_raw(native.cast_mut()) };
389 let mut operation = Arc::clone(&request.op);
390 if let Some(create) = self
391 .sync
392 .operation(request.texture)
393 .and_then(|previous| update_pending_create(previous, operation.as_ref()))
394 {
395 operation = Arc::new(create);
396 } else if let TextureOp::Update {
397 format,
398 width,
399 height,
400 rects,
401 } = operation.as_ref()
402 {
403 let previous_update = self
404 .sync
405 .operation(request.texture)
406 .filter(|previous| matches!(previous, TextureOp::Update { .. }));
407 if previous_update.is_none() && rects.len() == 1 {
408 staged.push((request.texture, native, operation));
409 continue;
410 }
411 let previous = previous_update.unwrap_or(operation.as_ref());
412 let rect = cumulative_update_rect(previous, operation.as_ref()).ok_or(
413 SnapshotError::TextureFullUpdateOutOfRange {
414 id: request.texture,
415 width: *width,
416 height: *height,
417 },
418 )?;
419 let pixels = texture
420 .pixels()
421 .ok_or(SnapshotError::TexturePixelsMissing {
422 id: request.texture,
423 status: texture.status(),
424 })?;
425 let upload = crate::render::snapshot::copy_upload_rect(
426 pixels,
427 *width,
428 *height,
429 texture.raw_bytes_per_pixel_i32() as usize,
430 rect,
431 )
432 .ok_or(SnapshotError::TextureInvalidLayout {
433 id: request.texture,
434 width: texture.raw_width_i32(),
435 height: texture.raw_height_i32(),
436 bpp: texture.raw_bytes_per_pixel_i32(),
437 })?;
438 operation = Arc::new(TextureOp::Update {
439 format: *format,
440 width: *width,
441 height: *height,
442 rects: vec![upload],
443 });
444 }
445 staged.push((request.texture, native, operation));
446 }
447 for (id, native, operation) in staged {
448 let destroy = matches!(operation.as_ref(), TextureOp::Destroy);
449 self.sync.stage(id, operation);
450 let texture = unsafe { TextureData::from_raw(native.cast_mut()) };
451 texture.claim_managed_queue();
452 if !destroy {
453 unsafe {
454 texture.set_status(TextureStatus::OK);
455 }
456 }
457 if matches!(id, SnapshotTextureId::FontAtlas { .. }) {
458 crate::fonts::mark_font_atlas_texture_staged(atlas.atlas);
459 }
460 }
461 Ok(self.sync.requests())
462 }
463
464 fn remove(
465 &mut self,
466 id: ManagedTextureId,
467 watermark: u64,
468 retain_frame: bool,
469 ) -> Result<(), ManagedTextureError> {
470 self.reap_destroyed(watermark);
471 let entry = self.active_entry_mut(id).map_err(|error| match error {
472 ManagedTextureError::Retiring(_) => ManagedTextureError::AlreadyRetiring(id),
473 other => other,
474 })?;
475 if retain_frame {
476 entry.retire_after_frame = true;
479 self.frame_removals.push(id.slot());
480 } else {
481 self.begin_retirement(id.slot() as usize, watermark);
482 }
483 Ok(())
484 }
485
486 pub(super) fn finish_frame_removals(&mut self, watermark: u64) {
487 while let Some(index) = self.frame_removals.pop() {
488 self.begin_retirement(index as usize, watermark);
489 }
490 }
491
492 fn begin_retirement(&mut self, slot_index: usize, watermark: u64) {
493 let TextureSlot::Active(mut entry) =
494 std::mem::replace(&mut self.slots[slot_index], TextureSlot::Exhausted)
495 else {
496 unreachable!("texture awaiting retirement must still be registered")
497 };
498 let has_renderer_binding =
499 !entry.texture.tex_id().is_null() || !entry.texture.backend_user_data().is_null();
500 let has_outstanding_reference = entry.last_reference_epoch > watermark;
501 let queue_owned = unsafe { !(*entry.texture.as_raw()).QueueUserData.is_null() };
502 if has_renderer_binding || has_outstanding_reference || queue_owned {
503 mark_want_destroy(&mut entry.texture);
504 self.slots[slot_index] = TextureSlot::Retiring(entry);
505 } else {
506 self.unregister_and_expose(slot_index, entry);
507 }
508 }
509
510 pub(crate) fn apply_snapshot_feedback(
511 &mut self,
512 feedback: &[TextureFeedback],
513 atlas: &FontAtlasSnapshotTarget,
514 epoch: u64,
515 ) -> Result<usize, RendererConsumerError> {
516 let mut applied = 0;
517 for item in feedback {
518 let key = item.key();
519 if matches!(
520 item.result(),
521 TextureFeedbackResult::Superseded | TextureFeedbackResult::Retry
522 ) {
523 continue;
524 }
525 match key.texture {
526 SnapshotTextureId::User(id) => match self.slot(id)? {
527 TextureSlot::Active(_) => {
528 if item.result() == TextureFeedbackResult::Destroyed {
529 return Err(RendererConsumerError::InvalidFeedbackTransition {
530 texture: key.texture,
531 });
532 }
533 }
534 TextureSlot::Retiring(_) => {}
535 TextureSlot::NativeExposed { .. }
536 | TextureSlot::Retired { .. }
537 | TextureSlot::Exhausted => {
538 return Err(ManagedTextureError::AlreadyRemoved(id).into());
539 }
540 },
541 SnapshotTextureId::FontAtlas { .. } => {
542 if !atlas.identity_is_known(key.texture) {
543 return Err(RendererConsumerError::StaleFontAtlas);
544 }
545 }
546 }
547 match (key.kind, item.result()) {
548 (
549 TextureRequestKind::Create | TextureRequestKind::Update,
550 TextureFeedbackResult::Uploaded { texture_id },
551 ) if !texture_id.is_null() => {}
552 (TextureRequestKind::Destroy, TextureFeedbackResult::Destroyed) => {}
553 _ => {
554 return Err(RendererConsumerError::InvalidFeedbackTransition {
555 texture: key.texture,
556 });
557 }
558 }
559 }
560
561 for item in feedback {
562 let key = item.key();
563 if matches!(
564 item.result(),
565 TextureFeedbackResult::Superseded | TextureFeedbackResult::Retry
566 ) {
567 continue;
568 }
569 let native = match key.texture {
570 SnapshotTextureId::User(id) => match &self.slots[id.slot() as usize] {
571 TextureSlot::Active(entry) | TextureSlot::Retiring(entry) => {
572 entry.texture.as_raw()
573 }
574 _ => unreachable!("feedback identities were validated"),
575 },
576 SnapshotTextureId::FontAtlas { .. } => {
577 let Some(target) = atlas.find(key.texture) else {
578 continue;
579 };
580 target.texture.cast_const()
581 }
582 };
583 let texture = unsafe { TextureData::from_raw(native.cast_mut()) };
584 let expected_status = if key.kind == TextureRequestKind::Destroy {
587 TextureStatus::WantDestroy
588 } else {
589 TextureStatus::OK
590 };
591 if texture.status() != expected_status
592 || !self.sync.acknowledge(key.texture, key.revision)
593 {
594 continue;
595 }
596 match item.result() {
597 TextureFeedbackResult::Uploaded { texture_id } => unsafe {
598 texture.set_tex_id(texture_id);
599 },
600 TextureFeedbackResult::Destroyed => {
601 unsafe {
602 texture.set_status(TextureStatus::Destroyed);
603 }
604 if let SnapshotTextureId::User(id) = key.texture {
605 if let TextureSlot::Retiring(entry) = &mut self.slots[id.slot() as usize] {
606 entry.destroy_ack_epoch = Some(epoch);
607 }
608 }
609 self.sync.forget(key.texture);
610 }
611 TextureFeedbackResult::Superseded | TextureFeedbackResult::Retry => unreachable!(),
612 }
613 applied += 1;
614 }
615 Ok(applied)
616 }
617
618 pub(crate) fn reap_destroyed(&mut self, watermark: u64) {
619 let ready = self
620 .slots
621 .iter()
622 .enumerate()
623 .filter_map(|(index, slot)| match slot {
624 TextureSlot::Retiring(entry)
625 if entry.texture.status() == TextureStatus::Destroyed
626 && entry.texture.tex_id().is_null()
627 && entry.texture.backend_user_data().is_null()
628 && entry
629 .destroy_ack_epoch
630 .is_some_and(|epoch| epoch <= watermark)
631 && entry.last_reference_epoch <= watermark =>
632 {
633 Some(index)
634 }
635 _ => None,
636 })
637 .collect::<Vec<_>>();
638
639 for slot_index in ready {
640 let generation = match &self.slots[slot_index] {
641 TextureSlot::Retiring(entry) => entry.generation,
642 _ => continue,
643 };
644 let placeholder = TextureSlot::Retired { generation };
645 let TextureSlot::Retiring(entry) =
646 std::mem::replace(&mut self.slots[slot_index], placeholder)
647 else {
648 continue;
649 };
650 self.unregister_and_expose(slot_index, entry);
651 }
652 }
653
654 pub(crate) fn reset_renderer_bindings(&mut self, watermark: u64) {
655 self.sync.clear();
656 for slot in &mut self.slots {
657 let (entry, retiring) = match slot {
658 TextureSlot::Active(entry) => (entry, false),
659 TextureSlot::Retiring(entry) => (entry, true),
660 TextureSlot::NativeExposed { .. }
661 | TextureSlot::Retired { .. }
662 | TextureSlot::Exhausted => continue,
663 };
664 if entry.texture.status() == TextureStatus::Destroyed {
665 if retiring {
666 entry.destroy_ack_epoch = Some(watermark);
667 }
668 continue;
669 }
670 unsafe {
671 entry.texture.set_status(TextureStatus::Destroyed);
674 }
675 if retiring {
676 entry.destroy_ack_epoch = Some(watermark);
677 }
678 }
679 self.reap_destroyed(watermark);
680 }
681
682 fn unregister_and_expose(&mut self, slot_index: usize, mut entry: TextureEntry) {
683 let native = entry.texture.as_mut().as_raw_mut();
684 unsafe {
685 sys::igUnregisterUserTexture(native);
686 }
687 self.by_native.remove(&(native as usize));
688 let release_after_refresh = self
689 .native_refresh_generation
690 .checked_add(1)
691 .expect("native texture-list refresh generation exhausted");
692 self.slots[slot_index] = TextureSlot::NativeExposed {
693 entry,
694 release_after_refresh,
695 };
696 }
697
698 pub(crate) fn observe_native_texture_list_refresh(&mut self) {
699 self.native_refresh_generation = self
700 .native_refresh_generation
701 .checked_add(1)
702 .expect("native texture-list refresh generation exhausted");
703 let ready = self
704 .slots
705 .iter()
706 .enumerate()
707 .filter_map(|(index, slot)| match slot {
708 TextureSlot::NativeExposed {
709 release_after_refresh,
710 ..
711 } if *release_after_refresh <= self.native_refresh_generation => Some(index),
712 _ => None,
713 })
714 .collect::<Vec<_>>();
715 for slot_index in ready {
716 let generation = match &self.slots[slot_index] {
717 TextureSlot::NativeExposed { entry, .. } => entry.generation,
718 _ => continue,
719 };
720 let previous = std::mem::replace(
721 &mut self.slots[slot_index],
722 TextureSlot::Retired { generation },
723 );
724 let TextureSlot::NativeExposed { entry, .. } = previous else {
725 unreachable!("native-exposed texture changed without a mutable alias")
726 };
727 drop(entry);
728 self.reusable
729 .push(u32::try_from(slot_index).expect("texture slot index must fit u32"));
730 }
731 }
732
733 pub(super) fn prepare_teardown(&mut self) {
734 let registered = self
735 .slots
736 .iter()
737 .enumerate()
738 .filter_map(|(index, slot)| {
739 matches!(slot, TextureSlot::Active(_) | TextureSlot::Retiring(_)).then_some(index)
740 })
741 .collect::<Vec<_>>();
742 for slot_index in registered {
743 let generation = match &self.slots[slot_index] {
744 TextureSlot::Active(entry) | TextureSlot::Retiring(entry) => entry.generation,
745 _ => continue,
746 };
747 let previous = std::mem::replace(
748 &mut self.slots[slot_index],
749 TextureSlot::Retired { generation },
750 );
751 let entry = match previous {
752 TextureSlot::Active(entry) | TextureSlot::Retiring(entry) => entry,
753 _ => unreachable!("registered texture changed without a mutable alias"),
754 };
755 self.unregister_and_expose(slot_index, entry);
756 }
757 self.by_native.clear();
758 self.reusable.clear();
759 self.frame_removals.clear();
760 }
761
762 pub(super) fn release_after_native_destroy(&mut self) {
763 self.by_native.clear();
764 self.reusable.clear();
765 self.slots.clear();
766 }
767}
768
769fn mark_want_destroy(texture: &mut TextureData) {
770 unsafe {
771 (*texture.as_raw_mut()).WantDestroyNextFrame = true;
772 sys::ImTextureData_SetStatus(texture.as_raw_mut(), sys::ImTextureStatus_WantDestroy);
773 }
774}
775
776impl Context {
777 pub fn register_texture(&mut self, texture: OwnedTextureData) -> ManagedTextureId {
779 let _guard = CTX_MUTEX.lock();
780 self.assert_current_context("Context::register_texture()");
781 let watermark = self.snapshot_hub.completion_watermark();
782 self.texture_registry
783 .borrow_mut()
784 .register(texture, watermark)
785 }
786
787 pub fn with_texture<R>(
799 &self,
800 id: ManagedTextureId,
801 f: impl for<'texture> FnOnce(ManagedTextureRef<'texture>) -> R,
802 ) -> Result<R, ManagedTextureError> {
803 let _guard = CTX_MUTEX.lock();
804 self.assert_current_context("Context::with_texture()");
805 self.texture_registry.borrow().with_texture(id, f)
806 }
807
808 pub fn with_texture_mut<R>(
822 &mut self,
823 id: ManagedTextureId,
824 f: impl for<'texture> FnOnce(ManagedTextureMut<'texture>) -> R,
825 ) -> Result<R, ManagedTextureError> {
826 let _guard = CTX_MUTEX.lock();
827 self.assert_current_context("Context::with_texture_mut()");
828 self.texture_registry.borrow_mut().with_texture_mut(id, f)
829 }
830
831 pub fn try_with_texture_mut<R>(
862 &mut self,
863 id: ManagedTextureId,
864 f: impl for<'texture> FnOnce(ManagedTextureMut<'texture>) -> Result<R, TextureDataError>,
865 ) -> Result<R, ManagedTextureMutationError> {
866 self.with_texture_mut(id, f)
867 .map_err(ManagedTextureMutationError::Access)?
868 .map_err(ManagedTextureMutationError::Data)
869 }
870
871 pub fn remove_texture(&mut self, id: ManagedTextureId) -> Result<(), ManagedTextureError> {
876 let _guard = CTX_MUTEX.lock();
877 self.assert_current_context("Context::remove_texture()");
878 let watermark = self.snapshot_hub.completion_watermark();
879 let retain_frame =
880 self.frame_lifecycle_state_unlocked() != super::FrameLifecycleState::Idle;
881 self.texture_registry
882 .borrow_mut()
883 .remove(id, watermark, retain_frame)
884 }
885
886 pub(crate) fn collect_retired_textures(&mut self) {
887 let watermark = self.snapshot_hub.completion_watermark();
888 self.texture_registry.borrow_mut().reap_destroyed(watermark);
889 }
890}
891
892#[cfg(test)]
893mod tests {
894 use super::*;
895 use crate::context::snapshot_hub::SnapshotHub;
896 use crate::texture::{TextureFormat, TextureId};
897
898 fn texture() -> OwnedTextureData {
899 OwnedTextureData::from_pixels(TextureFormat::RGBA32, 1, 1, &[1, 2, 3, 4]).unwrap()
900 }
901
902 #[test]
903 fn native_debug_ids_do_not_participate_in_managed_identity() {
904 let mut context = Context::create();
905 let first = texture();
906 let second = texture();
907 assert_eq!(first.native_unique_id(), 0);
908 assert_eq!(second.native_unique_id(), 0);
909 let first_id = context.register_texture(first);
910 let second_id = context.register_texture(second);
911 assert_ne!(first_id, second_id);
912 assert_eq!(first_id.context_id(), context.id());
913 assert_eq!(second_id.context_id(), context.id());
914 }
915
916 #[test]
917 fn foreign_and_reused_handles_fail_before_native_access() {
918 let mut context_a = Context::create();
919 let first_id = context_a.register_texture(texture());
920 let suspended_a = context_a.suspend_or_panic();
921 let mut context_b = Context::create();
922 assert!(matches!(
923 context_b.with_texture(first_id, |_| ()),
924 Err(ManagedTextureError::ForeignContext { .. })
925 ));
926 assert!(matches!(
927 context_b.try_with_texture_mut(first_id, |mut texture| {
928 texture.replace_pixels(&[4, 3, 2, 1])
929 }),
930 Err(ManagedTextureMutationError::Access(
931 ManagedTextureError::ForeignContext { .. }
932 ))
933 ));
934 drop(context_b);
935 let mut context_a = suspended_a.activate().expect("Context A should reactivate");
936 context_a.remove_texture(first_id).expect("unused texture");
937 assert_eq!(
938 context_a.try_with_texture_mut(first_id, |mut texture| {
939 texture.replace_pixels(&[4, 3, 2, 1])
940 }),
941 Err(ManagedTextureMutationError::Access(
942 ManagedTextureError::AlreadyRemoved(first_id)
943 ))
944 );
945 let before_refresh_id = context_a.register_texture(texture());
946 assert_ne!(
947 before_refresh_id.slot(),
948 first_id.slot(),
949 "a native-exposed allocation must not be reused before the texture list refreshes"
950 );
951 context_a
952 .texture_registry
953 .borrow_mut()
954 .observe_native_texture_list_refresh();
955 let replacement_id = context_a.register_texture(texture());
956 assert_eq!(replacement_id.slot(), first_id.slot());
957 assert_ne!(replacement_id.generation(), first_id.generation());
958 assert_eq!(
959 context_a.with_texture(first_id, |_| ()),
960 Err(ManagedTextureError::StaleGeneration(first_id))
961 );
962 }
963
964 #[test]
965 fn managed_queue_marker_is_idempotent_and_cleared_by_destroy_feedback() {
966 let mut context = Context::create();
967 let id = context.register_texture(texture());
968 let native = context
969 .texture_registry
970 .borrow()
971 .active_entry(id)
972 .expect("registered texture")
973 .texture
974 .as_raw()
975 .cast_mut();
976 let atlas = FontAtlasSnapshotTarget::new(std::ptr::null_mut(), context.id(), Vec::new());
977 let create = Arc::new(TextureOp::Create {
978 format: TextureFormat::RGBA32,
979 width: 1,
980 height: 1,
981 row_pitch: 4,
982 pixels: vec![1, 2, 3, 4],
983 });
984 let captured = vec![CapturedTextureOperation {
985 texture: SnapshotTextureId::User(id),
986 op: create,
987 }];
988
989 {
990 let mut registry = context.texture_registry.borrow_mut();
991 let pending = registry
992 .stage_snapshot_operations(&captured, &atlas)
993 .expect("create request should claim the managed queue");
994 let first_revision = pending[0].revision;
995 let pending = registry
996 .stage_snapshot_operations(&[], &atlas)
997 .expect("claiming the same managed queue must be idempotent");
998 assert_eq!(pending[0].revision, first_revision);
999 }
1000 unsafe {
1001 assert_eq!((*native).QueueUserData, native.cast());
1002 }
1003
1004 {
1005 let mut registry = context.texture_registry.borrow_mut();
1006 let entry = registry.active_entry_mut(id).expect("active texture");
1007 unsafe {
1008 entry.texture.set_tex_id(TextureId::new(73));
1009 entry.texture.set_status(TextureStatus::OK);
1010 }
1011 registry
1012 .remove(id, 0, false)
1013 .expect("bound texture should retire");
1014 }
1015
1016 let captured = vec![CapturedTextureOperation {
1017 texture: SnapshotTextureId::User(id),
1018 op: Arc::new(TextureOp::Destroy),
1019 }];
1020 let destroy = context
1021 .texture_registry
1022 .borrow_mut()
1023 .stage_snapshot_operations(&captured, &atlas)
1024 .expect("destroy request should remain queue-owned");
1025
1026 let mut hub = SnapshotHub::new(context.id());
1027 let generation = hub
1028 .validate_consumer_admission()
1029 .expect("fresh snapshot hub should admit a renderer");
1030 let consumer = hub.commit_synchronous_consumer_admission(generation);
1031 let (epoch, requests) = hub
1032 .begin_synchronous(&consumer, destroy, &atlas)
1033 .expect("destroy request should enter a synchronous epoch");
1034 let feedback = requests[0]
1035 .destroyed()
1036 .expect("destroy request should produce matching feedback");
1037 context
1038 .texture_registry
1039 .borrow_mut()
1040 .apply_snapshot_feedback(&[feedback], &atlas, epoch.sequence())
1041 .expect("matching destroy feedback should reconcile");
1042
1043 unsafe {
1044 assert!((*native).QueueUserData.is_null());
1045 }
1046 }
1047
1048 #[test]
1049 fn destroy_status_without_request_bound_ack_cannot_reap_allocation() {
1050 let mut context = Context::create();
1051 let id = context.register_texture(texture());
1052 let native = {
1053 let mut registry = context.texture_registry.borrow_mut();
1054 let entry = registry.active_entry_mut(id).expect("active texture");
1055 let texture = &mut entry.texture;
1056 unsafe {
1057 texture.set_tex_id(TextureId::new(91));
1059 texture.set_status(TextureStatus::OK);
1060 }
1061 texture.as_raw_mut()
1062 };
1063 context.remove_texture(id).expect("begin retirement");
1064 assert_eq!(
1065 context.remove_texture(id),
1066 Err(ManagedTextureError::AlreadyRetiring(id))
1067 );
1068 assert_eq!(
1069 context.texture_registry.borrow().id_for_native(native),
1070 Some(id)
1071 );
1072 unsafe {
1073 TextureData::from_raw(native).set_status(TextureStatus::Destroyed);
1075 }
1076 context.collect_retired_textures();
1077 assert_eq!(
1078 context.texture_registry.borrow().id_for_native(native),
1079 Some(id),
1080 "native status alone must not impersonate request-bound feedback"
1081 );
1082 {
1083 let mut registry = context.texture_registry.borrow_mut();
1084 let TextureSlot::Retiring(entry) = &mut registry.slots[id.slot() as usize] else {
1085 panic!("texture should still be retiring");
1086 };
1087 entry.destroy_ack_epoch = Some(0);
1088 }
1089 context.collect_retired_textures();
1090 assert_eq!(
1091 context.texture_registry.borrow().id_for_native(native),
1092 None
1093 );
1094 }
1095
1096 #[test]
1097 fn removed_storage_outlives_the_cached_native_texture_list() {
1098 let mut context = Context::create();
1099 context.io_mut().set_display_size([128.0, 128.0]);
1100 context.io_mut().set_delta_time(1.0 / 60.0);
1101 context
1102 .font_atlas()
1103 .try_claim_legacy_renderer()
1104 .expect("legacy renderer font atlas should be available")
1105 .build();
1106 let id = context.register_texture(texture());
1107 let native = context
1108 .texture_registry
1109 .borrow()
1110 .active_entry(id)
1111 .expect("registered texture")
1112 .texture
1113 .as_raw();
1114
1115 drop(context.begin_frame());
1116 let platform_io = unsafe { &*context.platform_io_ptr("test") };
1117 assert!((0..platform_io.Textures.Size).any(|index| unsafe {
1118 std::ptr::eq(
1119 *platform_io.Textures.Data.add(index as usize),
1120 native.cast_mut(),
1121 )
1122 }));
1123
1124 context.remove_texture(id).expect("unused texture");
1125 assert!(matches!(
1126 &context.texture_registry.borrow().slots[id.slot() as usize],
1127 TextureSlot::NativeExposed { entry, .. }
1128 if std::ptr::eq(entry.texture.as_raw(), native)
1129 ));
1130
1131 drop(context.begin_frame());
1132 assert!(matches!(
1133 &context.texture_registry.borrow().slots[id.slot() as usize],
1134 TextureSlot::Retired { generation } if *generation == id.generation()
1135 ));
1136 }
1137}