re_types/archetypes/
annotation_context.rs

1// DO NOT EDIT! This file was auto-generated by crates/build/re_types_builder/src/codegen/rust/api.rs
2// Based on "crates/store/re_types/definitions/rerun/archetypes/annotation_context.fbs".
3
4#![allow(unused_braces)]
5#![allow(unused_imports)]
6#![allow(unused_parens)]
7#![allow(clippy::allow_attributes)]
8#![allow(clippy::clone_on_copy)]
9#![allow(clippy::cloned_instead_of_copied)]
10#![allow(clippy::map_flatten)]
11#![allow(clippy::needless_question_mark)]
12#![allow(clippy::new_without_default)]
13#![allow(clippy::redundant_closure)]
14#![allow(clippy::too_many_arguments)]
15#![allow(clippy::too_many_lines)]
16#![allow(clippy::wildcard_imports)]
17
18use ::re_types_core::SerializationResult;
19use ::re_types_core::try_serialize_field;
20use ::re_types_core::{ComponentBatch as _, SerializedComponentBatch};
21use ::re_types_core::{ComponentDescriptor, ComponentType};
22use ::re_types_core::{DeserializationError, DeserializationResult};
23
24/// **Archetype**: The annotation context provides additional information on how to display entities.
25///
26/// Entities can use [`components::ClassId`][crate::components::ClassId]s and [`components::KeypointId`][crate::components::KeypointId]s to provide annotations, and
27/// the labels and colors will be looked up in the appropriate
28/// annotation context. We use the *first* annotation context we find in the
29/// path-hierarchy when searching up through the ancestors of a given entity
30/// path.
31///
32/// See also [`datatypes::ClassDescription`][crate::datatypes::ClassDescription].
33///
34/// ⚠️ **This type is _unstable_ and may change significantly in a way that the data won't be backwards compatible.**
35///
36/// ## Example
37///
38/// ### Segmentation
39/// ```ignore
40/// use ndarray::{Array, ShapeBuilder as _, s};
41///
42/// fn main() -> Result<(), Box<dyn std::error::Error>> {
43///     let rec = rerun::RecordingStreamBuilder::new("rerun_example_annotation_context_segmentation")
44///         .spawn()?;
45///
46///     // create an annotation context to describe the classes
47///     rec.log_static(
48///         "segmentation",
49///         &rerun::AnnotationContext::new([
50///             (1, "red", rerun::Rgba32::from_rgb(255, 0, 0)),
51///             (2, "green", rerun::Rgba32::from_rgb(0, 255, 0)),
52///         ]),
53///     )?;
54///
55///     // create a segmentation image
56///     let mut data = Array::<u8, _>::zeros((200, 300).f());
57///     data.slice_mut(s![50..100, 50..120]).fill(1);
58///     data.slice_mut(s![100..180, 130..280]).fill(2);
59///
60///     rec.log(
61///         "segmentation/image",
62///         &rerun::SegmentationImage::try_from(data)?,
63///     )?;
64///
65///     Ok(())
66/// }
67/// ```
68/// <center>
69/// <picture>
70///   <source media="(max-width: 480px)" srcset="https://static.rerun.io/annotation_context_segmentation/6c9e88fc9d44a08031cadd444c2e58a985cc1208/480w.png">
71///   <source media="(max-width: 768px)" srcset="https://static.rerun.io/annotation_context_segmentation/6c9e88fc9d44a08031cadd444c2e58a985cc1208/768w.png">
72///   <source media="(max-width: 1024px)" srcset="https://static.rerun.io/annotation_context_segmentation/6c9e88fc9d44a08031cadd444c2e58a985cc1208/1024w.png">
73///   <source media="(max-width: 1200px)" srcset="https://static.rerun.io/annotation_context_segmentation/6c9e88fc9d44a08031cadd444c2e58a985cc1208/1200w.png">
74///   <img src="https://static.rerun.io/annotation_context_segmentation/6c9e88fc9d44a08031cadd444c2e58a985cc1208/full.png" width="640">
75/// </picture>
76/// </center>
77#[derive(Clone, Debug, PartialEq, Default)]
78pub struct AnnotationContext {
79    /// List of class descriptions, mapping class indices to class names, colors etc.
80    pub context: Option<SerializedComponentBatch>,
81}
82
83impl AnnotationContext {
84    /// Returns the [`ComponentDescriptor`] for [`Self::context`].
85    ///
86    /// The corresponding component is [`crate::components::AnnotationContext`].
87    #[inline]
88    pub fn descriptor_context() -> ComponentDescriptor {
89        ComponentDescriptor {
90            archetype: Some("rerun.archetypes.AnnotationContext".into()),
91            component: "AnnotationContext:context".into(),
92            component_type: Some("rerun.components.AnnotationContext".into()),
93        }
94    }
95}
96
97static REQUIRED_COMPONENTS: std::sync::LazyLock<[ComponentDescriptor; 1usize]> =
98    std::sync::LazyLock::new(|| [AnnotationContext::descriptor_context()]);
99
100static RECOMMENDED_COMPONENTS: std::sync::LazyLock<[ComponentDescriptor; 0usize]> =
101    std::sync::LazyLock::new(|| []);
102
103static OPTIONAL_COMPONENTS: std::sync::LazyLock<[ComponentDescriptor; 0usize]> =
104    std::sync::LazyLock::new(|| []);
105
106static ALL_COMPONENTS: std::sync::LazyLock<[ComponentDescriptor; 1usize]> =
107    std::sync::LazyLock::new(|| [AnnotationContext::descriptor_context()]);
108
109impl AnnotationContext {
110    /// The total number of components in the archetype: 1 required, 0 recommended, 0 optional
111    pub const NUM_COMPONENTS: usize = 1usize;
112}
113
114impl ::re_types_core::Archetype for AnnotationContext {
115    #[inline]
116    fn name() -> ::re_types_core::ArchetypeName {
117        "rerun.archetypes.AnnotationContext".into()
118    }
119
120    #[inline]
121    fn display_name() -> &'static str {
122        "Annotation context"
123    }
124
125    #[inline]
126    fn required_components() -> ::std::borrow::Cow<'static, [ComponentDescriptor]> {
127        REQUIRED_COMPONENTS.as_slice().into()
128    }
129
130    #[inline]
131    fn recommended_components() -> ::std::borrow::Cow<'static, [ComponentDescriptor]> {
132        RECOMMENDED_COMPONENTS.as_slice().into()
133    }
134
135    #[inline]
136    fn optional_components() -> ::std::borrow::Cow<'static, [ComponentDescriptor]> {
137        OPTIONAL_COMPONENTS.as_slice().into()
138    }
139
140    #[inline]
141    fn all_components() -> ::std::borrow::Cow<'static, [ComponentDescriptor]> {
142        ALL_COMPONENTS.as_slice().into()
143    }
144
145    #[inline]
146    fn from_arrow_components(
147        arrow_data: impl IntoIterator<Item = (ComponentDescriptor, arrow::array::ArrayRef)>,
148    ) -> DeserializationResult<Self> {
149        re_tracing::profile_function!();
150        use ::re_types_core::{Loggable as _, ResultExt as _};
151        let arrays_by_descr: ::nohash_hasher::IntMap<_, _> = arrow_data.into_iter().collect();
152        let context = arrays_by_descr
153            .get(&Self::descriptor_context())
154            .map(|array| SerializedComponentBatch::new(array.clone(), Self::descriptor_context()));
155        Ok(Self { context })
156    }
157}
158
159impl ::re_types_core::AsComponents for AnnotationContext {
160    #[inline]
161    fn as_serialized_batches(&self) -> Vec<SerializedComponentBatch> {
162        use ::re_types_core::Archetype as _;
163        std::iter::once(self.context.clone()).flatten().collect()
164    }
165}
166
167impl ::re_types_core::ArchetypeReflectionMarker for AnnotationContext {}
168
169impl AnnotationContext {
170    /// Create a new `AnnotationContext`.
171    #[inline]
172    pub fn new(context: impl Into<crate::components::AnnotationContext>) -> Self {
173        Self {
174            context: try_serialize_field(Self::descriptor_context(), [context]),
175        }
176    }
177
178    /// Update only some specific fields of a `AnnotationContext`.
179    #[inline]
180    pub fn update_fields() -> Self {
181        Self::default()
182    }
183
184    /// Clear all the fields of a `AnnotationContext`.
185    #[inline]
186    pub fn clear_fields() -> Self {
187        use ::re_types_core::Loggable as _;
188        Self {
189            context: Some(SerializedComponentBatch::new(
190                crate::components::AnnotationContext::arrow_empty(),
191                Self::descriptor_context(),
192            )),
193        }
194    }
195
196    /// Partitions the component data into multiple sub-batches.
197    ///
198    /// Specifically, this transforms the existing [`SerializedComponentBatch`]es data into [`SerializedComponentColumn`]s
199    /// instead, via [`SerializedComponentBatch::partitioned`].
200    ///
201    /// This makes it possible to use `RecordingStream::send_columns` to send columnar data directly into Rerun.
202    ///
203    /// The specified `lengths` must sum to the total length of the component batch.
204    ///
205    /// [`SerializedComponentColumn`]: [::re_types_core::SerializedComponentColumn]
206    #[inline]
207    pub fn columns<I>(
208        self,
209        _lengths: I,
210    ) -> SerializationResult<impl Iterator<Item = ::re_types_core::SerializedComponentColumn>>
211    where
212        I: IntoIterator<Item = usize> + Clone,
213    {
214        let columns = [self
215            .context
216            .map(|context| context.partitioned(_lengths.clone()))
217            .transpose()?];
218        Ok(columns.into_iter().flatten())
219    }
220
221    /// Helper to partition the component data into unit-length sub-batches.
222    ///
223    /// This is semantically similar to calling [`Self::columns`] with `std::iter::take(1).repeat(n)`,
224    /// where `n` is automatically guessed.
225    #[inline]
226    pub fn columns_of_unit_batches(
227        self,
228    ) -> SerializationResult<impl Iterator<Item = ::re_types_core::SerializedComponentColumn>> {
229        let len_context = self.context.as_ref().map(|b| b.array.len());
230        let len = None.or(len_context).unwrap_or(0);
231        self.columns(std::iter::repeat_n(1, len))
232    }
233
234    /// List of class descriptions, mapping class indices to class names, colors etc.
235    #[inline]
236    pub fn with_context(
237        mut self,
238        context: impl Into<crate::components::AnnotationContext>,
239    ) -> Self {
240        self.context = try_serialize_field(Self::descriptor_context(), [context]);
241        self
242    }
243
244    /// This method makes it possible to pack multiple [`crate::components::AnnotationContext`] in a single component batch.
245    ///
246    /// This only makes sense when used in conjunction with [`Self::columns`]. [`Self::with_context`] should
247    /// be used when logging a single row's worth of data.
248    #[inline]
249    pub fn with_many_context(
250        mut self,
251        context: impl IntoIterator<Item = impl Into<crate::components::AnnotationContext>>,
252    ) -> Self {
253        self.context = try_serialize_field(Self::descriptor_context(), context);
254        self
255    }
256}
257
258impl ::re_byte_size::SizeBytes for AnnotationContext {
259    #[inline]
260    fn heap_size_bytes(&self) -> u64 {
261        self.context.heap_size_bytes()
262    }
263}