Skip to main content

oa/vision/
detection.rs

1//! GPU-consumable object-detection result values.
2//!
3//! [`Detection`] is the 32-byte packed record layout shared by host reference
4//! providers, GPU postprocess kernels, and render consumers. Geometry is
5//! normalized to the source image so camera/view transforms remain GPU-side.
6//! [`DetectionBuffer`] is a fixed-capacity host-upload ring slot: records are
7//! replaced through [`DetectionBuffer::upload`] while
8//! [`DetectionBuffer::mark_consumed`] pins the exact [`Event`] a GPU consumer
9//! must complete before the next overwrite.
10//!
11//! Donor: `oacpp/source/cpp/include/oa/vision/detection.h`.
12
13use std::mem::{offset_of, size_of};
14
15use crate::{Error, Event, Matrix, Result, Runtime, runtime::RuntimeHandle};
16
17/// One GPU-consumable detection record, exactly 32 bytes.
18///
19/// `color_rgba` is an optional per-instance display color in `0xRRGGBBAA`;
20/// zero selects the overlay style fallback and preserves compatibility with
21/// older producers. `track_id` is a stable identity for trackers; rendering
22/// ignores it while postprocess and interaction code retain the same record
23/// layout across frames.
24#[repr(C)]
25#[derive(Clone, Copy, Debug, Default, PartialEq)]
26pub struct Detection {
27	pub center_x: f32,
28	pub center_y: f32,
29	pub width: f32,
30	pub height: f32,
31	pub confidence: f32,
32	pub class_id: u32,
33	pub color_rgba: u32,
34	pub track_id: u32,
35}
36
37const _: () = assert!(size_of::<Detection>() == 32);
38const _: () = assert!(offset_of!(Detection, color_rgba) == 24);
39const _: () = assert!(offset_of!(Detection, track_id) == 28);
40
41/// A fixed-capacity GPU-consumable detection buffer.
42///
43/// Construction requires an [`Runtime`]; dropping the buffer never waits —
44/// the runtime's retirement service keeps submitted resources alive through
45/// completion.
46pub struct DetectionBuffer {
47	runtime: RuntimeHandle,
48	storage: Matrix,
49	consumer: Option<Event>,
50	count: u32,
51	capacity: u32,
52}
53
54impl DetectionBuffer {
55	pub fn create_host_upload(capacity: u32) -> Result<Self> {
56		Self::create_host_upload_on(&Runtime::current()?, capacity)
57	}
58
59	/// Allocate a host-uploadable buffer for `capacity` detection records.
60	///
61	/// Native GPU postprocess producers use the same record layout and
62	/// consumer API.
63	///
64	/// # Errors
65	///
66	/// Returns an error when `capacity` is zero, the capacity byte extent
67	/// overflows, or allocation fails.
68	pub fn create_host_upload_on(runtime: &Runtime, capacity: u32) -> Result<Self> {
69		if capacity == 0 {
70			return Err(Error::invalid_argument(
71				"oa::vision::DetectionBuffer::create_host_upload: capacity must be non-zero",
72			));
73		}
74		let byte_len = usize::try_from(capacity)
75			.ok()
76			.and_then(|count| count.checked_mul(size_of::<Detection>()))
77			.ok_or_else(|| {
78				Error::invalid_argument(
79					"oa::vision::DetectionBuffer::create_host_upload: capacity byte extent overflows usize",
80				)
81			})?;
82		let storage = Matrix::new_from_slice_on(runtime, [byte_len], &vec![0_u8; byte_len])?;
83		Ok(Self {
84			runtime: runtime.handle(),
85			storage,
86			consumer: None,
87			count: 0,
88			capacity,
89		})
90	}
91
92	/// Replace the current records.
93	///
94	/// # Errors
95	///
96	/// Returns [`crate::ErrorKind::NotReady`] while a previous render
97	/// submission still consumes this slot,
98	/// [`crate::ErrorKind::ResourceExhausted`] when `detections` exceeds
99	/// capacity, or an upload error.
100	pub fn upload(&mut self, detections: &[Detection]) -> Result<()> {
101		if !self.is_ready()? {
102			return Err(Error::not_ready(
103				"oa::vision::DetectionBuffer::upload: buffer is still consumed by the GPU",
104			));
105		}
106		if detections.len() > usize::try_from(self.capacity).unwrap_or(usize::MAX) {
107			return Err(Error::resource_exhausted(
108				"oa::vision::DetectionBuffer::upload: detection count exceeds capacity",
109			));
110		}
111		let used = std::mem::size_of_val(detections);
112		let mut bytes = vec![0_u8; self.storage.num_elements()];
113		if used > 0 {
114			// SAFETY: `Detection` is `repr(C)`, plain data with a statically
115			// checked layout; the used prefix never exceeds the byte capacity.
116			let source = unsafe { std::slice::from_raw_parts(detections.as_ptr().cast::<u8>(), used) };
117			bytes[..used].copy_from_slice(source);
118		}
119		self.storage.write_values::<u8>(&bytes)?;
120		self.count = u32::try_from(detections.len())
121			.map_err(|_| Error::invalid_argument("detection count exceeds u32"))?;
122		self.consumer = None;
123		Ok(())
124	}
125
126	/// Pin `completion` as the event that must complete before the next
127	/// [`upload`](Self::upload).
128	///
129	/// # Errors
130	///
131	/// Returns an error when `completion` does not belong to this buffer's
132	/// runtime or completion cannot be queried.
133	pub fn mark_consumed(&mut self, completion: &Event) -> Result<()> {
134		if !self.runtime.owns_event(completion) {
135			return Err(Error::invalid_argument(
136				"oa::vision::DetectionBuffer::mark_consumed requires an event from its runtime",
137			));
138		}
139		self.consumer = if completion.is_complete()? {
140			None
141		} else {
142			Some(completion.clone())
143		};
144		Ok(())
145	}
146
147	/// Return whether no pinned consumer event is still in flight.
148	///
149	/// # Errors
150	///
151	/// Returns an error when consumer completion cannot be queried.
152	pub fn is_ready(&self) -> Result<bool> {
153		match &self.consumer {
154			Some(completion) => completion.is_complete(),
155			None => Ok(true),
156		}
157	}
158
159	/// Return the number of records written by the last [`upload`](Self::upload).
160	pub const fn count(&self) -> u32 {
161		self.count
162	}
163
164	/// Return the record capacity fixed at creation.
165	pub const fn capacity(&self) -> u32 {
166		self.capacity
167	}
168
169	/// Bindless storage-buffer descriptor index for UI/render consumers.
170	pub(crate) fn bindless_index(&self) -> Result<u32> {
171		self
172			.runtime
173			.storage_descriptor_index(self.storage.storage())
174	}
175
176	/// The packed record storage retained by UI draw commands.
177	pub(crate) const fn storage(&self) -> &Matrix {
178		&self.storage
179	}
180
181	/// The runtime that owns this buffer's storage.
182	pub(crate) const fn runtime(&self) -> &RuntimeHandle {
183		&self.runtime
184	}
185}