re_types/archetypes/
encoded_image.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/encoded_image.fbs".
3
4#![allow(unused_imports)]
5#![allow(unused_parens)]
6#![allow(clippy::clone_on_copy)]
7#![allow(clippy::cloned_instead_of_copied)]
8#![allow(clippy::map_flatten)]
9#![allow(clippy::needless_question_mark)]
10#![allow(clippy::new_without_default)]
11#![allow(clippy::redundant_closure)]
12#![allow(clippy::too_many_arguments)]
13#![allow(clippy::too_many_lines)]
14
15use ::re_types_core::try_serialize_field;
16use ::re_types_core::SerializationResult;
17use ::re_types_core::{ComponentBatch as _, SerializedComponentBatch};
18use ::re_types_core::{ComponentDescriptor, ComponentName};
19use ::re_types_core::{DeserializationError, DeserializationResult};
20
21/// **Archetype**: An image encoded as e.g. a JPEG or PNG.
22///
23/// Rerun also supports uncompressed images with the [`archetypes::Image`][crate::archetypes::Image].
24/// For images that refer to video frames see [`archetypes::VideoFrameReference`][crate::archetypes::VideoFrameReference].
25///
26/// ## Example
27///
28/// ### `encoded_image`:
29/// ```ignore
30/// fn main() -> Result<(), Box<dyn std::error::Error>> {
31///     let rec = rerun::RecordingStreamBuilder::new("rerun_example_encoded_image").spawn()?;
32///
33///     let image = include_bytes!("ferris.png");
34///
35///     rec.log(
36///         "image",
37///         &rerun::EncodedImage::from_file_contents(image.to_vec()),
38///     )?;
39///
40///     Ok(())
41/// }
42/// ```
43#[derive(Clone, Debug, PartialEq, Default)]
44pub struct EncodedImage {
45    /// The encoded content of some image file, e.g. a PNG or JPEG.
46    pub blob: Option<SerializedComponentBatch>,
47
48    /// The Media Type of the asset.
49    ///
50    /// Supported values:
51    /// * `image/jpeg`
52    /// * `image/png`
53    ///
54    /// If omitted, the viewer will try to guess from the data blob.
55    /// If it cannot guess, it won't be able to render the asset.
56    pub media_type: Option<SerializedComponentBatch>,
57
58    /// Opacity of the image, useful for layering several images.
59    ///
60    /// Defaults to 1.0 (fully opaque).
61    pub opacity: Option<SerializedComponentBatch>,
62
63    /// An optional floating point value that specifies the 2D drawing order.
64    ///
65    /// Objects with higher values are drawn on top of those with lower values.
66    pub draw_order: Option<SerializedComponentBatch>,
67}
68
69impl EncodedImage {
70    /// Returns the [`ComponentDescriptor`] for [`Self::blob`].
71    #[inline]
72    pub fn descriptor_blob() -> ComponentDescriptor {
73        ComponentDescriptor {
74            archetype_name: Some("rerun.archetypes.EncodedImage".into()),
75            component_name: "rerun.components.Blob".into(),
76            archetype_field_name: Some("blob".into()),
77        }
78    }
79
80    /// Returns the [`ComponentDescriptor`] for [`Self::media_type`].
81    #[inline]
82    pub fn descriptor_media_type() -> ComponentDescriptor {
83        ComponentDescriptor {
84            archetype_name: Some("rerun.archetypes.EncodedImage".into()),
85            component_name: "rerun.components.MediaType".into(),
86            archetype_field_name: Some("media_type".into()),
87        }
88    }
89
90    /// Returns the [`ComponentDescriptor`] for [`Self::opacity`].
91    #[inline]
92    pub fn descriptor_opacity() -> ComponentDescriptor {
93        ComponentDescriptor {
94            archetype_name: Some("rerun.archetypes.EncodedImage".into()),
95            component_name: "rerun.components.Opacity".into(),
96            archetype_field_name: Some("opacity".into()),
97        }
98    }
99
100    /// Returns the [`ComponentDescriptor`] for [`Self::draw_order`].
101    #[inline]
102    pub fn descriptor_draw_order() -> ComponentDescriptor {
103        ComponentDescriptor {
104            archetype_name: Some("rerun.archetypes.EncodedImage".into()),
105            component_name: "rerun.components.DrawOrder".into(),
106            archetype_field_name: Some("draw_order".into()),
107        }
108    }
109
110    /// Returns the [`ComponentDescriptor`] for the associated indicator component.
111    #[inline]
112    pub fn descriptor_indicator() -> ComponentDescriptor {
113        ComponentDescriptor {
114            archetype_name: Some("rerun.archetypes.EncodedImage".into()),
115            component_name: "rerun.components.EncodedImageIndicator".into(),
116            archetype_field_name: None,
117        }
118    }
119}
120
121static REQUIRED_COMPONENTS: once_cell::sync::Lazy<[ComponentDescriptor; 1usize]> =
122    once_cell::sync::Lazy::new(|| [EncodedImage::descriptor_blob()]);
123
124static RECOMMENDED_COMPONENTS: once_cell::sync::Lazy<[ComponentDescriptor; 2usize]> =
125    once_cell::sync::Lazy::new(|| {
126        [
127            EncodedImage::descriptor_media_type(),
128            EncodedImage::descriptor_indicator(),
129        ]
130    });
131
132static OPTIONAL_COMPONENTS: once_cell::sync::Lazy<[ComponentDescriptor; 2usize]> =
133    once_cell::sync::Lazy::new(|| {
134        [
135            EncodedImage::descriptor_opacity(),
136            EncodedImage::descriptor_draw_order(),
137        ]
138    });
139
140static ALL_COMPONENTS: once_cell::sync::Lazy<[ComponentDescriptor; 5usize]> =
141    once_cell::sync::Lazy::new(|| {
142        [
143            EncodedImage::descriptor_blob(),
144            EncodedImage::descriptor_media_type(),
145            EncodedImage::descriptor_indicator(),
146            EncodedImage::descriptor_opacity(),
147            EncodedImage::descriptor_draw_order(),
148        ]
149    });
150
151impl EncodedImage {
152    /// The total number of components in the archetype: 1 required, 2 recommended, 2 optional
153    pub const NUM_COMPONENTS: usize = 5usize;
154}
155
156/// Indicator component for the [`EncodedImage`] [`::re_types_core::Archetype`]
157pub type EncodedImageIndicator = ::re_types_core::GenericIndicatorComponent<EncodedImage>;
158
159impl ::re_types_core::Archetype for EncodedImage {
160    type Indicator = EncodedImageIndicator;
161
162    #[inline]
163    fn name() -> ::re_types_core::ArchetypeName {
164        "rerun.archetypes.EncodedImage".into()
165    }
166
167    #[inline]
168    fn display_name() -> &'static str {
169        "Encoded image"
170    }
171
172    #[inline]
173    fn indicator() -> SerializedComponentBatch {
174        #[allow(clippy::unwrap_used)]
175        EncodedImageIndicator::DEFAULT.serialized().unwrap()
176    }
177
178    #[inline]
179    fn required_components() -> ::std::borrow::Cow<'static, [ComponentDescriptor]> {
180        REQUIRED_COMPONENTS.as_slice().into()
181    }
182
183    #[inline]
184    fn recommended_components() -> ::std::borrow::Cow<'static, [ComponentDescriptor]> {
185        RECOMMENDED_COMPONENTS.as_slice().into()
186    }
187
188    #[inline]
189    fn optional_components() -> ::std::borrow::Cow<'static, [ComponentDescriptor]> {
190        OPTIONAL_COMPONENTS.as_slice().into()
191    }
192
193    #[inline]
194    fn all_components() -> ::std::borrow::Cow<'static, [ComponentDescriptor]> {
195        ALL_COMPONENTS.as_slice().into()
196    }
197
198    #[inline]
199    fn from_arrow_components(
200        arrow_data: impl IntoIterator<Item = (ComponentDescriptor, arrow::array::ArrayRef)>,
201    ) -> DeserializationResult<Self> {
202        re_tracing::profile_function!();
203        use ::re_types_core::{Loggable as _, ResultExt as _};
204        let arrays_by_descr: ::nohash_hasher::IntMap<_, _> = arrow_data.into_iter().collect();
205        let blob = arrays_by_descr
206            .get(&Self::descriptor_blob())
207            .map(|array| SerializedComponentBatch::new(array.clone(), Self::descriptor_blob()));
208        let media_type = arrays_by_descr
209            .get(&Self::descriptor_media_type())
210            .map(|array| {
211                SerializedComponentBatch::new(array.clone(), Self::descriptor_media_type())
212            });
213        let opacity = arrays_by_descr
214            .get(&Self::descriptor_opacity())
215            .map(|array| SerializedComponentBatch::new(array.clone(), Self::descriptor_opacity()));
216        let draw_order = arrays_by_descr
217            .get(&Self::descriptor_draw_order())
218            .map(|array| {
219                SerializedComponentBatch::new(array.clone(), Self::descriptor_draw_order())
220            });
221        Ok(Self {
222            blob,
223            media_type,
224            opacity,
225            draw_order,
226        })
227    }
228}
229
230impl ::re_types_core::AsComponents for EncodedImage {
231    #[inline]
232    fn as_serialized_batches(&self) -> Vec<SerializedComponentBatch> {
233        use ::re_types_core::Archetype as _;
234        [
235            Some(Self::indicator()),
236            self.blob.clone(),
237            self.media_type.clone(),
238            self.opacity.clone(),
239            self.draw_order.clone(),
240        ]
241        .into_iter()
242        .flatten()
243        .collect()
244    }
245}
246
247impl ::re_types_core::ArchetypeReflectionMarker for EncodedImage {}
248
249impl EncodedImage {
250    /// Create a new `EncodedImage`.
251    #[inline]
252    pub fn new(blob: impl Into<crate::components::Blob>) -> Self {
253        Self {
254            blob: try_serialize_field(Self::descriptor_blob(), [blob]),
255            media_type: None,
256            opacity: None,
257            draw_order: None,
258        }
259    }
260
261    /// Update only some specific fields of a `EncodedImage`.
262    #[inline]
263    pub fn update_fields() -> Self {
264        Self::default()
265    }
266
267    /// Clear all the fields of a `EncodedImage`.
268    #[inline]
269    pub fn clear_fields() -> Self {
270        use ::re_types_core::Loggable as _;
271        Self {
272            blob: Some(SerializedComponentBatch::new(
273                crate::components::Blob::arrow_empty(),
274                Self::descriptor_blob(),
275            )),
276            media_type: Some(SerializedComponentBatch::new(
277                crate::components::MediaType::arrow_empty(),
278                Self::descriptor_media_type(),
279            )),
280            opacity: Some(SerializedComponentBatch::new(
281                crate::components::Opacity::arrow_empty(),
282                Self::descriptor_opacity(),
283            )),
284            draw_order: Some(SerializedComponentBatch::new(
285                crate::components::DrawOrder::arrow_empty(),
286                Self::descriptor_draw_order(),
287            )),
288        }
289    }
290
291    /// Partitions the component data into multiple sub-batches.
292    ///
293    /// Specifically, this transforms the existing [`SerializedComponentBatch`]es data into [`SerializedComponentColumn`]s
294    /// instead, via [`SerializedComponentBatch::partitioned`].
295    ///
296    /// This makes it possible to use `RecordingStream::send_columns` to send columnar data directly into Rerun.
297    ///
298    /// The specified `lengths` must sum to the total length of the component batch.
299    ///
300    /// [`SerializedComponentColumn`]: [::re_types_core::SerializedComponentColumn]
301    #[inline]
302    pub fn columns<I>(
303        self,
304        _lengths: I,
305    ) -> SerializationResult<impl Iterator<Item = ::re_types_core::SerializedComponentColumn>>
306    where
307        I: IntoIterator<Item = usize> + Clone,
308    {
309        let columns = [
310            self.blob
311                .map(|blob| blob.partitioned(_lengths.clone()))
312                .transpose()?,
313            self.media_type
314                .map(|media_type| media_type.partitioned(_lengths.clone()))
315                .transpose()?,
316            self.opacity
317                .map(|opacity| opacity.partitioned(_lengths.clone()))
318                .transpose()?,
319            self.draw_order
320                .map(|draw_order| draw_order.partitioned(_lengths.clone()))
321                .transpose()?,
322        ];
323        Ok(columns
324            .into_iter()
325            .flatten()
326            .chain([::re_types_core::indicator_column::<Self>(
327                _lengths.into_iter().count(),
328            )?]))
329    }
330
331    /// Helper to partition the component data into unit-length sub-batches.
332    ///
333    /// This is semantically similar to calling [`Self::columns`] with `std::iter::take(1).repeat(n)`,
334    /// where `n` is automatically guessed.
335    #[inline]
336    pub fn columns_of_unit_batches(
337        self,
338    ) -> SerializationResult<impl Iterator<Item = ::re_types_core::SerializedComponentColumn>> {
339        let len_blob = self.blob.as_ref().map(|b| b.array.len());
340        let len_media_type = self.media_type.as_ref().map(|b| b.array.len());
341        let len_opacity = self.opacity.as_ref().map(|b| b.array.len());
342        let len_draw_order = self.draw_order.as_ref().map(|b| b.array.len());
343        let len = None
344            .or(len_blob)
345            .or(len_media_type)
346            .or(len_opacity)
347            .or(len_draw_order)
348            .unwrap_or(0);
349        self.columns(std::iter::repeat(1).take(len))
350    }
351
352    /// The encoded content of some image file, e.g. a PNG or JPEG.
353    #[inline]
354    pub fn with_blob(mut self, blob: impl Into<crate::components::Blob>) -> Self {
355        self.blob = try_serialize_field(Self::descriptor_blob(), [blob]);
356        self
357    }
358
359    /// This method makes it possible to pack multiple [`crate::components::Blob`] in a single component batch.
360    ///
361    /// This only makes sense when used in conjunction with [`Self::columns`]. [`Self::with_blob`] should
362    /// be used when logging a single row's worth of data.
363    #[inline]
364    pub fn with_many_blob(
365        mut self,
366        blob: impl IntoIterator<Item = impl Into<crate::components::Blob>>,
367    ) -> Self {
368        self.blob = try_serialize_field(Self::descriptor_blob(), blob);
369        self
370    }
371
372    /// The Media Type of the asset.
373    ///
374    /// Supported values:
375    /// * `image/jpeg`
376    /// * `image/png`
377    ///
378    /// If omitted, the viewer will try to guess from the data blob.
379    /// If it cannot guess, it won't be able to render the asset.
380    #[inline]
381    pub fn with_media_type(mut self, media_type: impl Into<crate::components::MediaType>) -> Self {
382        self.media_type = try_serialize_field(Self::descriptor_media_type(), [media_type]);
383        self
384    }
385
386    /// This method makes it possible to pack multiple [`crate::components::MediaType`] in a single component batch.
387    ///
388    /// This only makes sense when used in conjunction with [`Self::columns`]. [`Self::with_media_type`] should
389    /// be used when logging a single row's worth of data.
390    #[inline]
391    pub fn with_many_media_type(
392        mut self,
393        media_type: impl IntoIterator<Item = impl Into<crate::components::MediaType>>,
394    ) -> Self {
395        self.media_type = try_serialize_field(Self::descriptor_media_type(), media_type);
396        self
397    }
398
399    /// Opacity of the image, useful for layering several images.
400    ///
401    /// Defaults to 1.0 (fully opaque).
402    #[inline]
403    pub fn with_opacity(mut self, opacity: impl Into<crate::components::Opacity>) -> Self {
404        self.opacity = try_serialize_field(Self::descriptor_opacity(), [opacity]);
405        self
406    }
407
408    /// This method makes it possible to pack multiple [`crate::components::Opacity`] in a single component batch.
409    ///
410    /// This only makes sense when used in conjunction with [`Self::columns`]. [`Self::with_opacity`] should
411    /// be used when logging a single row's worth of data.
412    #[inline]
413    pub fn with_many_opacity(
414        mut self,
415        opacity: impl IntoIterator<Item = impl Into<crate::components::Opacity>>,
416    ) -> Self {
417        self.opacity = try_serialize_field(Self::descriptor_opacity(), opacity);
418        self
419    }
420
421    /// An optional floating point value that specifies the 2D drawing order.
422    ///
423    /// Objects with higher values are drawn on top of those with lower values.
424    #[inline]
425    pub fn with_draw_order(mut self, draw_order: impl Into<crate::components::DrawOrder>) -> Self {
426        self.draw_order = try_serialize_field(Self::descriptor_draw_order(), [draw_order]);
427        self
428    }
429
430    /// This method makes it possible to pack multiple [`crate::components::DrawOrder`] in a single component batch.
431    ///
432    /// This only makes sense when used in conjunction with [`Self::columns`]. [`Self::with_draw_order`] should
433    /// be used when logging a single row's worth of data.
434    #[inline]
435    pub fn with_many_draw_order(
436        mut self,
437        draw_order: impl IntoIterator<Item = impl Into<crate::components::DrawOrder>>,
438    ) -> Self {
439        self.draw_order = try_serialize_field(Self::descriptor_draw_order(), draw_order);
440        self
441    }
442}
443
444impl ::re_byte_size::SizeBytes for EncodedImage {
445    #[inline]
446    fn heap_size_bytes(&self) -> u64 {
447        self.blob.heap_size_bytes()
448            + self.media_type.heap_size_bytes()
449            + self.opacity.heap_size_bytes()
450            + self.draw_order.heap_size_bytes()
451    }
452}