Skip to main content

oa/ui/
detection_overlay.rs

1//! Completion-safe GPU boxes and labels for image/video views.
2//!
3//! Geometry is normalized to the source image. Rectangle and glyph records
4//! are compact host-upload adapters; native GPU inference/NMS can write the
5//! same [`crate::Detection`] record layout without changing the display
6//! consumer. A three-slot completion-tracked ring prevents the CPU from
7//! overwriting records still consumed by a previous GPU frame.
8//!
9//! Typical use from a live source:
10//! ```ignore
11//! let mut overlay = DetectionOverlay::create(&runtime, Default::default())?;
12//! overlay.update(&items, &atlas)?;
13//! // … draw image into destination …
14//! overlay.draw(&mut ui, &atlas, destination, clip)?;
15//! // after submission:
16//! overlay.mark_consumed(&completion)?;
17//! ```
18//!
19//! Donor: `oacpp/source/cpp/include/oa/ui/detectionOverlay.h`.
20
21pub use crate::ui::type_gen::DetectionOverlayConfig;
22use crate::{
23	Color, Error, Event, Result, Runtime,
24	ui::{
25		FontId, GlyphBuffer, GlyphInstance, PixelRect, TextAtlas, TextLayout, TextLayoutConfig, Ui,
26	},
27	vision::{Detection, DetectionBuffer},
28};
29
30const RING_SIZE: usize = 3;
31
32/// One detection record with its display label.
33#[derive(Clone, Debug)]
34pub struct DetectionOverlayItem {
35	pub detection: Detection,
36	pub label: String,
37}
38
39impl Default for DetectionOverlayConfig {
40	fn default() -> Self {
41		Self {
42			max_detections: 256,
43			max_glyphs: 8192,
44			thickness_pixels: 3.0,
45			font_size: 18.0,
46			label_padding_x: 4.0,
47			label_padding_y: 2.0,
48			box_color: Color::success(),
49			label_text_color: Color {
50				r: 0.0,
51				g: 0.0,
52				b: 0.0,
53				a: 1.0,
54			},
55			show_labels: true,
56		}
57	}
58}
59
60struct OverlaySlot {
61	detections: DetectionBuffer,
62	glyphs: GlyphBuffer,
63}
64
65impl OverlaySlot {
66	fn is_ready(&self) -> Result<bool> {
67		Ok(self.detections.is_ready()? && self.glyphs.is_ready()?)
68	}
69}
70
71/// Ring-buffered detection box and label overlay.
72///
73/// Constructed by [`DetectionOverlay::create`]; records are uploaded through
74/// the non-blocking [`DetectionOverlay::update`], composed into a `Ui` frame
75/// through [`DetectionOverlay::draw`], and released back for overwrite through
76/// [`DetectionOverlay::mark_consumed`].
77pub struct DetectionOverlay {
78	config: DetectionOverlayConfig,
79	slots: Vec<OverlaySlot>,
80	active_slot: Option<usize>,
81	next_slot: usize,
82	count: u32,
83}
84
85impl DetectionOverlay {
86	/// Allocate the three-slot detection and glyph upload ring.
87	///
88	/// # Errors
89	///
90	/// Returns an error when either capacity is zero or allocation fails.
91	pub fn create(runtime: &Runtime, config: DetectionOverlayConfig) -> Result<Self> {
92		if config.max_detections == 0 || config.max_glyphs == 0 {
93			return Err(Error::invalid_argument(
94				"oa::ui::DetectionOverlay: capacities must be non-zero",
95			));
96		}
97		let mut slots = Vec::with_capacity(RING_SIZE);
98		for _ in 0..RING_SIZE {
99			slots.push(OverlaySlot {
100				detections: DetectionBuffer::create_host_upload_on(runtime, config.max_detections)?,
101				glyphs: GlyphBuffer::create_host_upload_on(runtime, config.max_glyphs)?,
102			});
103		}
104		Ok(Self {
105			config,
106			slots,
107			active_slot: None,
108			next_slot: 0,
109			count: 0,
110		})
111	}
112
113	/// Upload `items` into the first ready ring slot without blocking.
114	///
115	/// Non-finite detection geometry is rejected and zero-extent boxes are
116	/// skipped; remaining fields are clamped to `[0, 1]` and a zero
117	/// `color_rgba` receives the configured box color.
118	///
119	/// # Errors
120	///
121	/// Returns an error when `items` exceeds `max_detections`, shaped labels
122	/// exceed `max_glyphs`, geometry is non-finite, or all three upload slots
123	/// are still consumed by in-flight frames.
124	pub fn update(&mut self, items: &[DetectionOverlayItem], atlas: &TextAtlas) -> Result<()> {
125		if items.len() > usize::try_from(self.config.max_detections).unwrap_or(usize::MAX) {
126			return Err(Error::resource_exhausted(
127				"oa::ui::DetectionOverlay: detection capacity exceeded",
128			));
129		}
130		let mut selected = None;
131		for offset in 0..RING_SIZE {
132			let index = (self.next_slot + offset) % RING_SIZE;
133			if self.slots[index].is_ready()? {
134				selected = Some(index);
135				break;
136			}
137		}
138		let Some(index) = selected else {
139			return Err(Error::not_ready(
140				"oa::ui::DetectionOverlay: all upload slots are in flight",
141			));
142		};
143
144		let mut detections = Vec::with_capacity(items.len());
145		let mut glyphs = Vec::with_capacity(
146			usize::try_from(self.config.max_glyphs)
147				.unwrap_or(usize::MAX)
148				.min(items.len() * 24),
149		);
150		for item in items {
151			if !is_finite(&item.detection) {
152				return Err(Error::invalid_argument(
153					"oa::ui::DetectionOverlay: non-finite detection geometry",
154				));
155			}
156			let detection = canonicalize(&item.detection, self.config.box_color.to_u32());
157			if detection.width <= 0.0 || detection.height <= 0.0 {
158				continue;
159			}
160			detections.push(detection);
161			append_label(atlas, &self.config, &detection, &item.label, &mut glyphs)?;
162		}
163		if glyphs.len() > usize::try_from(self.config.max_glyphs).unwrap_or(usize::MAX) {
164			return Err(Error::resource_exhausted(
165				"oa::ui::DetectionOverlay: glyph capacity exceeded",
166			));
167		}
168
169		let slot = &mut self.slots[index];
170		slot.detections.upload(&detections)?;
171		slot.glyphs.upload(&glyphs)?;
172		self.active_slot = Some(index);
173		self.next_slot = (index + 1) % RING_SIZE;
174		self.count = u32::try_from(detections.len())
175			.map_err(|_| Error::invalid_argument("detection count exceeds u32"))?;
176		Ok(())
177	}
178
179	/// Emit the active slot's box outlines and glyph batch into `ui` through
180	/// its shared coverage atlas.
181	///
182	/// `destination` maps normalized source-image geometry into the compose
183	/// image; `clip` bounds rasterization.
184	pub fn draw(&self, ui: &mut Ui, destination: PixelRect, clip: PixelRect) -> Result<()> {
185		let Some(index) = self.active_slot else {
186			return Ok(());
187		};
188		let slot = &self.slots[index];
189		ui.rect_outlines(
190			&slot.detections,
191			destination,
192			clip,
193			self.config.box_color,
194			self.config.thickness_pixels.round().max(1.0) as u32,
195		)?;
196		ui.glyphs(&slot.glyphs, destination, clip)
197	}
198
199	/// Pin `completion` on the active slot so its records cannot be
200	/// overwritten until the consuming frame completes.
201	///
202	/// # Errors
203	///
204	/// Returns an error when `completion` does not belong to the owning
205	/// runtime.
206	pub fn mark_consumed(&mut self, completion: &Event) -> Result<()> {
207		let Some(index) = self.active_slot else {
208			return Ok(());
209		};
210		let slot = &mut self.slots[index];
211		slot.detections.mark_consumed(completion)?;
212		slot.glyphs.mark_consumed(completion)
213	}
214
215	/// Return the number of records written by the last [`update`](Self::update).
216	pub const fn count(&self) -> u32 {
217		self.count
218	}
219}
220
221fn canonicalize(detection: &Detection, fallback_color: u32) -> Detection {
222	Detection {
223		center_x: detection.center_x.clamp(0.0, 1.0),
224		center_y: detection.center_y.clamp(0.0, 1.0),
225		width: detection.width.clamp(0.0, 1.0),
226		height: detection.height.clamp(0.0, 1.0),
227		confidence: detection.confidence.clamp(0.0, 1.0),
228		class_id: detection.class_id,
229		color_rgba: if detection.color_rgba == 0 {
230			fallback_color
231		} else {
232			detection.color_rgba
233		},
234		track_id: detection.track_id,
235	}
236}
237
238fn is_finite(detection: &Detection) -> bool {
239	detection.center_x.is_finite()
240		&& detection.center_y.is_finite()
241		&& detection.width.is_finite()
242		&& detection.height.is_finite()
243		&& detection.confidence.is_finite()
244}
245
246// Emit the label background box followed by one glyph quad per shaped
247// codepoint. The background uses zero atlas extents — the draw kernel clamps
248// to the atlas' corner texel, which is reserved as opaque coverage.
249fn append_label(
250	atlas: &TextAtlas,
251	config: &DetectionOverlayConfig,
252	detection: &Detection,
253	label: &str,
254	glyphs: &mut Vec<GlyphInstance>,
255) -> Result<()> {
256	if !config.show_labels || label.is_empty() {
257		return Ok(());
258	}
259	let anchor_x = detection.center_x - detection.width * 0.5;
260	let anchor_y = detection.center_y - detection.height * 0.5;
261	let layout_config = TextLayoutConfig {
262		font: FontId::Sans,
263		size: config.font_size,
264		..TextLayoutConfig::default()
265	};
266	let positioned = TextLayout::shape(
267		atlas,
268		label,
269		[0.0, 0.0],
270		layout_config,
271		config.label_text_color,
272	)?;
273	if positioned.is_empty() {
274		return Ok(());
275	}
276	let text_width = positioned.last().map_or(0.0, |item| {
277		let advance = atlas
278			.find_glyph(item.font, item.codepoint, config.font_size)
279			.map_or(0.0, |glyph| {
280				glyph.advance * (config.font_size / glyph.raster_size)
281			});
282		item.x + advance
283	});
284	let mut text_top = 1.0e9_f32;
285	let mut text_bottom = -1.0e9_f32;
286	for item in &positioned {
287		let Some(glyph) = atlas.find_glyph(item.font, item.codepoint, config.font_size) else {
288			continue;
289		};
290		let scale = config.font_size / glyph.raster_size;
291		let glyph_top = -glyph.bearing_y * scale;
292		text_top = text_top.min(glyph_top);
293		text_bottom = text_bottom.max(glyph_top + glyph.ink_h * scale);
294	}
295	if text_bottom <= text_top {
296		return Ok(());
297	}
298
299	let label_width = text_width + config.label_padding_x * 2.0;
300	let label_height = config.font_size + config.label_padding_y * 2.0;
301	let text_height = text_bottom - text_top;
302	let baseline = -label_height + (label_height - text_height) * 0.5 - text_top;
303	glyphs.push(GlyphInstance {
304		anchor_x,
305		anchor_y,
306		offset_x: 0.0,
307		offset_y: -label_height,
308		width: label_width,
309		height: label_height,
310		color: detection.color_rgba,
311		..GlyphInstance::default()
312	});
313
314	for item in &positioned {
315		let Some(glyph) = atlas.find_glyph(item.font, item.codepoint, config.font_size) else {
316			continue;
317		};
318		let scale = config.font_size / glyph.raster_size;
319		glyphs.push(GlyphInstance {
320			anchor_x,
321			anchor_y,
322			offset_x: config.label_padding_x + item.x + glyph.bearing_x * scale,
323			offset_y: baseline - glyph.bearing_y * scale,
324			width: glyph.atlas_w * scale,
325			height: glyph.atlas_h * scale,
326			atlas_x: glyph.atlas_x as u32,
327			atlas_y: glyph.atlas_y as u32,
328			atlas_w: glyph.atlas_w as u32,
329			atlas_h: glyph.atlas_h as u32,
330			color: config.label_text_color.to_u32(),
331			flags: 0,
332		});
333	}
334	Ok(())
335}