re_types/archetypes/
asset3d.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/asset3d.fbs".
3
4#![allow(unused_braces)]
5#![allow(unused_imports)]
6#![allow(unused_parens)]
7#![allow(clippy::clone_on_copy)]
8#![allow(clippy::cloned_instead_of_copied)]
9#![allow(clippy::map_flatten)]
10#![allow(clippy::needless_question_mark)]
11#![allow(clippy::new_without_default)]
12#![allow(clippy::redundant_closure)]
13#![allow(clippy::too_many_arguments)]
14#![allow(clippy::too_many_lines)]
15
16use ::re_types_core::SerializationResult;
17use ::re_types_core::try_serialize_field;
18use ::re_types_core::{ComponentBatch as _, SerializedComponentBatch};
19use ::re_types_core::{ComponentDescriptor, ComponentType};
20use ::re_types_core::{DeserializationError, DeserializationResult};
21
22/// **Archetype**: A prepacked 3D asset (`.gltf`, `.glb`, `.obj`, `.stl`, etc.).
23///
24/// See also [`archetypes::Mesh3D`][crate::archetypes::Mesh3D].
25///
26/// If there are multiple [`archetypes::InstancePoses3D`][crate::archetypes::InstancePoses3D] instances logged to the same entity as a mesh,
27/// an instance of the mesh will be drawn for each transform.
28///
29/// ## Example
30///
31/// ### Simple 3D asset
32/// ```ignore
33/// use rerun::external::anyhow;
34///
35/// fn main() -> anyhow::Result<()> {
36///     let args = std::env::args().collect::<Vec<_>>();
37///     let Some(path) = args.get(1) else {
38///         anyhow::bail!("Usage: {} <path_to_asset.[gltf|glb|obj|stl]>", args[0]);
39///     };
40///
41///     let rec = rerun::RecordingStreamBuilder::new("rerun_example_asset3d").spawn()?;
42///
43///     rec.log_static("world", &rerun::ViewCoordinates::RIGHT_HAND_Z_UP())?; // Set an up-axis
44///     rec.log("world/asset", &rerun::Asset3D::from_file_path(path)?)?;
45///
46///     Ok(())
47/// }
48/// ```
49/// <center>
50/// <picture>
51///   <source media="(max-width: 480px)" srcset="https://static.rerun.io/asset3d_simple/af238578188d3fd0de3e330212120e2842a8ddb2/480w.png">
52///   <source media="(max-width: 768px)" srcset="https://static.rerun.io/asset3d_simple/af238578188d3fd0de3e330212120e2842a8ddb2/768w.png">
53///   <source media="(max-width: 1024px)" srcset="https://static.rerun.io/asset3d_simple/af238578188d3fd0de3e330212120e2842a8ddb2/1024w.png">
54///   <source media="(max-width: 1200px)" srcset="https://static.rerun.io/asset3d_simple/af238578188d3fd0de3e330212120e2842a8ddb2/1200w.png">
55///   <img src="https://static.rerun.io/asset3d_simple/af238578188d3fd0de3e330212120e2842a8ddb2/full.png" width="640">
56/// </picture>
57/// </center>
58#[derive(Clone, Debug, PartialEq, Default)]
59pub struct Asset3D {
60    /// The asset's bytes.
61    pub blob: Option<SerializedComponentBatch>,
62
63    /// The Media Type of the asset.
64    ///
65    /// Supported values:
66    /// * `model/gltf-binary`
67    /// * `model/gltf+json`
68    /// * `model/obj` (.mtl material files are not supported yet, references are silently ignored)
69    /// * `model/stl`
70    ///
71    /// If omitted, the viewer will try to guess from the data blob.
72    /// If it cannot guess, it won't be able to render the asset.
73    pub media_type: Option<SerializedComponentBatch>,
74
75    /// A color multiplier applied to the whole asset.
76    ///
77    /// For mesh who already have `albedo_factor` in materials,
78    /// it will be overwritten by actual `albedo_factor` of [`archetypes::Asset3D`][crate::archetypes::Asset3D] (if specified).
79    pub albedo_factor: Option<SerializedComponentBatch>,
80}
81
82impl Asset3D {
83    /// Returns the [`ComponentDescriptor`] for [`Self::blob`].
84    ///
85    /// The corresponding component is [`crate::components::Blob`].
86    #[inline]
87    pub fn descriptor_blob() -> ComponentDescriptor {
88        ComponentDescriptor {
89            archetype: Some("rerun.archetypes.Asset3D".into()),
90            component: "Asset3D:blob".into(),
91            component_type: Some("rerun.components.Blob".into()),
92        }
93    }
94
95    /// Returns the [`ComponentDescriptor`] for [`Self::media_type`].
96    ///
97    /// The corresponding component is [`crate::components::MediaType`].
98    #[inline]
99    pub fn descriptor_media_type() -> ComponentDescriptor {
100        ComponentDescriptor {
101            archetype: Some("rerun.archetypes.Asset3D".into()),
102            component: "Asset3D:media_type".into(),
103            component_type: Some("rerun.components.MediaType".into()),
104        }
105    }
106
107    /// Returns the [`ComponentDescriptor`] for [`Self::albedo_factor`].
108    ///
109    /// The corresponding component is [`crate::components::AlbedoFactor`].
110    #[inline]
111    pub fn descriptor_albedo_factor() -> ComponentDescriptor {
112        ComponentDescriptor {
113            archetype: Some("rerun.archetypes.Asset3D".into()),
114            component: "Asset3D:albedo_factor".into(),
115            component_type: Some("rerun.components.AlbedoFactor".into()),
116        }
117    }
118}
119
120static REQUIRED_COMPONENTS: std::sync::LazyLock<[ComponentDescriptor; 1usize]> =
121    std::sync::LazyLock::new(|| [Asset3D::descriptor_blob()]);
122
123static RECOMMENDED_COMPONENTS: std::sync::LazyLock<[ComponentDescriptor; 1usize]> =
124    std::sync::LazyLock::new(|| [Asset3D::descriptor_media_type()]);
125
126static OPTIONAL_COMPONENTS: std::sync::LazyLock<[ComponentDescriptor; 1usize]> =
127    std::sync::LazyLock::new(|| [Asset3D::descriptor_albedo_factor()]);
128
129static ALL_COMPONENTS: std::sync::LazyLock<[ComponentDescriptor; 3usize]> =
130    std::sync::LazyLock::new(|| {
131        [
132            Asset3D::descriptor_blob(),
133            Asset3D::descriptor_media_type(),
134            Asset3D::descriptor_albedo_factor(),
135        ]
136    });
137
138impl Asset3D {
139    /// The total number of components in the archetype: 1 required, 1 recommended, 1 optional
140    pub const NUM_COMPONENTS: usize = 3usize;
141}
142
143impl ::re_types_core::Archetype for Asset3D {
144    #[inline]
145    fn name() -> ::re_types_core::ArchetypeName {
146        "rerun.archetypes.Asset3D".into()
147    }
148
149    #[inline]
150    fn display_name() -> &'static str {
151        "Asset 3D"
152    }
153
154    #[inline]
155    fn required_components() -> ::std::borrow::Cow<'static, [ComponentDescriptor]> {
156        REQUIRED_COMPONENTS.as_slice().into()
157    }
158
159    #[inline]
160    fn recommended_components() -> ::std::borrow::Cow<'static, [ComponentDescriptor]> {
161        RECOMMENDED_COMPONENTS.as_slice().into()
162    }
163
164    #[inline]
165    fn optional_components() -> ::std::borrow::Cow<'static, [ComponentDescriptor]> {
166        OPTIONAL_COMPONENTS.as_slice().into()
167    }
168
169    #[inline]
170    fn all_components() -> ::std::borrow::Cow<'static, [ComponentDescriptor]> {
171        ALL_COMPONENTS.as_slice().into()
172    }
173
174    #[inline]
175    fn from_arrow_components(
176        arrow_data: impl IntoIterator<Item = (ComponentDescriptor, arrow::array::ArrayRef)>,
177    ) -> DeserializationResult<Self> {
178        re_tracing::profile_function!();
179        use ::re_types_core::{Loggable as _, ResultExt as _};
180        let arrays_by_descr: ::nohash_hasher::IntMap<_, _> = arrow_data.into_iter().collect();
181        let blob = arrays_by_descr
182            .get(&Self::descriptor_blob())
183            .map(|array| SerializedComponentBatch::new(array.clone(), Self::descriptor_blob()));
184        let media_type = arrays_by_descr
185            .get(&Self::descriptor_media_type())
186            .map(|array| {
187                SerializedComponentBatch::new(array.clone(), Self::descriptor_media_type())
188            });
189        let albedo_factor = arrays_by_descr
190            .get(&Self::descriptor_albedo_factor())
191            .map(|array| {
192                SerializedComponentBatch::new(array.clone(), Self::descriptor_albedo_factor())
193            });
194        Ok(Self {
195            blob,
196            media_type,
197            albedo_factor,
198        })
199    }
200}
201
202impl ::re_types_core::AsComponents for Asset3D {
203    #[inline]
204    fn as_serialized_batches(&self) -> Vec<SerializedComponentBatch> {
205        use ::re_types_core::Archetype as _;
206        [
207            self.blob.clone(),
208            self.media_type.clone(),
209            self.albedo_factor.clone(),
210        ]
211        .into_iter()
212        .flatten()
213        .collect()
214    }
215}
216
217impl ::re_types_core::ArchetypeReflectionMarker for Asset3D {}
218
219impl Asset3D {
220    /// Create a new `Asset3D`.
221    #[inline]
222    pub fn new(blob: impl Into<crate::components::Blob>) -> Self {
223        Self {
224            blob: try_serialize_field(Self::descriptor_blob(), [blob]),
225            media_type: None,
226            albedo_factor: None,
227        }
228    }
229
230    /// Update only some specific fields of a `Asset3D`.
231    #[inline]
232    pub fn update_fields() -> Self {
233        Self::default()
234    }
235
236    /// Clear all the fields of a `Asset3D`.
237    #[inline]
238    pub fn clear_fields() -> Self {
239        use ::re_types_core::Loggable as _;
240        Self {
241            blob: Some(SerializedComponentBatch::new(
242                crate::components::Blob::arrow_empty(),
243                Self::descriptor_blob(),
244            )),
245            media_type: Some(SerializedComponentBatch::new(
246                crate::components::MediaType::arrow_empty(),
247                Self::descriptor_media_type(),
248            )),
249            albedo_factor: Some(SerializedComponentBatch::new(
250                crate::components::AlbedoFactor::arrow_empty(),
251                Self::descriptor_albedo_factor(),
252            )),
253        }
254    }
255
256    /// Partitions the component data into multiple sub-batches.
257    ///
258    /// Specifically, this transforms the existing [`SerializedComponentBatch`]es data into [`SerializedComponentColumn`]s
259    /// instead, via [`SerializedComponentBatch::partitioned`].
260    ///
261    /// This makes it possible to use `RecordingStream::send_columns` to send columnar data directly into Rerun.
262    ///
263    /// The specified `lengths` must sum to the total length of the component batch.
264    ///
265    /// [`SerializedComponentColumn`]: [::re_types_core::SerializedComponentColumn]
266    #[inline]
267    pub fn columns<I>(
268        self,
269        _lengths: I,
270    ) -> SerializationResult<impl Iterator<Item = ::re_types_core::SerializedComponentColumn>>
271    where
272        I: IntoIterator<Item = usize> + Clone,
273    {
274        let columns = [
275            self.blob
276                .map(|blob| blob.partitioned(_lengths.clone()))
277                .transpose()?,
278            self.media_type
279                .map(|media_type| media_type.partitioned(_lengths.clone()))
280                .transpose()?,
281            self.albedo_factor
282                .map(|albedo_factor| albedo_factor.partitioned(_lengths.clone()))
283                .transpose()?,
284        ];
285        Ok(columns.into_iter().flatten())
286    }
287
288    /// Helper to partition the component data into unit-length sub-batches.
289    ///
290    /// This is semantically similar to calling [`Self::columns`] with `std::iter::take(1).repeat(n)`,
291    /// where `n` is automatically guessed.
292    #[inline]
293    pub fn columns_of_unit_batches(
294        self,
295    ) -> SerializationResult<impl Iterator<Item = ::re_types_core::SerializedComponentColumn>> {
296        let len_blob = self.blob.as_ref().map(|b| b.array.len());
297        let len_media_type = self.media_type.as_ref().map(|b| b.array.len());
298        let len_albedo_factor = self.albedo_factor.as_ref().map(|b| b.array.len());
299        let len = None
300            .or(len_blob)
301            .or(len_media_type)
302            .or(len_albedo_factor)
303            .unwrap_or(0);
304        self.columns(std::iter::repeat_n(1, len))
305    }
306
307    /// The asset's bytes.
308    #[inline]
309    pub fn with_blob(mut self, blob: impl Into<crate::components::Blob>) -> Self {
310        self.blob = try_serialize_field(Self::descriptor_blob(), [blob]);
311        self
312    }
313
314    /// This method makes it possible to pack multiple [`crate::components::Blob`] in a single component batch.
315    ///
316    /// This only makes sense when used in conjunction with [`Self::columns`]. [`Self::with_blob`] should
317    /// be used when logging a single row's worth of data.
318    #[inline]
319    pub fn with_many_blob(
320        mut self,
321        blob: impl IntoIterator<Item = impl Into<crate::components::Blob>>,
322    ) -> Self {
323        self.blob = try_serialize_field(Self::descriptor_blob(), blob);
324        self
325    }
326
327    /// The Media Type of the asset.
328    ///
329    /// Supported values:
330    /// * `model/gltf-binary`
331    /// * `model/gltf+json`
332    /// * `model/obj` (.mtl material files are not supported yet, references are silently ignored)
333    /// * `model/stl`
334    ///
335    /// If omitted, the viewer will try to guess from the data blob.
336    /// If it cannot guess, it won't be able to render the asset.
337    #[inline]
338    pub fn with_media_type(mut self, media_type: impl Into<crate::components::MediaType>) -> Self {
339        self.media_type = try_serialize_field(Self::descriptor_media_type(), [media_type]);
340        self
341    }
342
343    /// This method makes it possible to pack multiple [`crate::components::MediaType`] in a single component batch.
344    ///
345    /// This only makes sense when used in conjunction with [`Self::columns`]. [`Self::with_media_type`] should
346    /// be used when logging a single row's worth of data.
347    #[inline]
348    pub fn with_many_media_type(
349        mut self,
350        media_type: impl IntoIterator<Item = impl Into<crate::components::MediaType>>,
351    ) -> Self {
352        self.media_type = try_serialize_field(Self::descriptor_media_type(), media_type);
353        self
354    }
355
356    /// A color multiplier applied to the whole asset.
357    ///
358    /// For mesh who already have `albedo_factor` in materials,
359    /// it will be overwritten by actual `albedo_factor` of [`archetypes::Asset3D`][crate::archetypes::Asset3D] (if specified).
360    #[inline]
361    pub fn with_albedo_factor(
362        mut self,
363        albedo_factor: impl Into<crate::components::AlbedoFactor>,
364    ) -> Self {
365        self.albedo_factor = try_serialize_field(Self::descriptor_albedo_factor(), [albedo_factor]);
366        self
367    }
368
369    /// This method makes it possible to pack multiple [`crate::components::AlbedoFactor`] in a single component batch.
370    ///
371    /// This only makes sense when used in conjunction with [`Self::columns`]. [`Self::with_albedo_factor`] should
372    /// be used when logging a single row's worth of data.
373    #[inline]
374    pub fn with_many_albedo_factor(
375        mut self,
376        albedo_factor: impl IntoIterator<Item = impl Into<crate::components::AlbedoFactor>>,
377    ) -> Self {
378        self.albedo_factor = try_serialize_field(Self::descriptor_albedo_factor(), albedo_factor);
379        self
380    }
381}
382
383impl ::re_byte_size::SizeBytes for Asset3D {
384    #[inline]
385    fn heap_size_bytes(&self) -> u64 {
386        self.blob.heap_size_bytes()
387            + self.media_type.heap_size_bytes()
388            + self.albedo_factor.heap_size_bytes()
389    }
390}