Skip to main content

three_rs/core/
buffer_geometry.rs

1//! Port of `three.js/src/core/BufferGeometry.js`: named
2//! [`BufferAttribute`]s (typed, possibly interleaved — see
3//! [`buffer_attribute`](super::buffer_attribute)) plus a `u16`/`u32` index.
4
5use std::cell::{Cell, RefCell};
6use std::collections::HashMap;
7use std::rc::Rc;
8
9use super::buffer_attribute::{AttributeDesc, BufferAttribute, InterleavedBuffer};
10use crate::math::{Matrix3, Matrix4, Quaternion, Vector3};
11
12/// `BufferGeometry.id` — three.js' module-level `let _id = 0` counter, handed
13/// out in construction order, exactly as [`MaterialId`](crate::materials::MaterialId)
14/// is for materials.
15///
16/// The renderer keys its uploaded GPU buffers on this. It has to be an
17/// *identity*, and a never-reused one: the previous key was
18/// `Rc::as_ptr( &geometry )`, and an address is reused the moment the geometry
19/// behind it is dropped, so a new geometry allocated at a dead one's address
20/// inherited its vertex buffers — a panic when the attribute sets differed and
21/// the wrong shape, silently, when they did not (issue #58).
22///
23/// As with `MaterialId`, **`clone()` mints a fresh id**: a cloned geometry is a
24/// new object in three.js (`new BufferGeometry().copy( this )`), and one that
25/// may be mutated away from its source before it is ever drawn, so it must not
26/// be served the source's upload.
27#[derive(Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
28pub struct GeometryId(usize);
29
30impl GeometryId {
31    fn next() -> Self {
32        thread_local! {
33            static GEOMETRY_ID: Cell<usize> = const { Cell::new(0) };
34        }
35        GEOMETRY_ID.with(|id| {
36            let next = id.get();
37            id.set(next + 1);
38            GeometryId(next)
39        })
40    }
41
42    /// The number itself, for keying on.
43    pub fn get(&self) -> usize {
44        self.0
45    }
46}
47
48/// A fresh id, never a copy — see the type's docs.
49impl Clone for GeometryId {
50    fn clone(&self) -> Self {
51        Self::next()
52    }
53}
54
55impl Default for GeometryId {
56    fn default() -> Self {
57        Self::next()
58    }
59}
60
61/// `Box3`, as far as `BufferGeometry.computeBoundingBox()` needs it.
62#[derive(Clone, Copy, Debug, PartialEq)]
63pub struct BoundingBox {
64    /// `Box3.min`.
65    pub min: Vector3,
66    /// `Box3.max`.
67    pub max: Vector3,
68}
69
70impl BoundingBox {
71    /// `Box3.makeEmpty()`.
72    pub fn empty() -> Self {
73        Self {
74            min: Vector3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY),
75            max: Vector3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY),
76        }
77    }
78
79    /// `Box3.setFromBufferAttribute()`.
80    pub fn from_buffer_attribute(attribute: &BufferAttribute) -> Self {
81        let mut box3 = Self::empty();
82
83        for i in 0..attribute.count() {
84            box3.expand_by_point(&attribute.get_vector3(i));
85        }
86
87        box3
88    }
89
90    /// `Box3.expandByPoint()`.
91    pub fn expand_by_point(&mut self, point: &Vector3) -> &mut Self {
92        self.min.min(point);
93        self.max.max(point);
94        self
95    }
96
97    /// `Box3.getCenter()`.
98    pub fn center(&self) -> Vector3 {
99        Vector3::new(
100            (self.min.x + self.max.x) * 0.5,
101            (self.min.y + self.max.y) * 0.5,
102            (self.min.z + self.max.z) * 0.5,
103        )
104    }
105}
106
107/// `Sphere`, as far as `BufferGeometry.computeBoundingSphere()` needs it.
108#[derive(Clone, Copy, Debug, PartialEq)]
109pub struct BoundingSphere {
110    /// `Sphere.center`.
111    pub center: Vector3,
112    /// `Sphere.radius`.
113    pub radius: f64,
114}
115
116/// `BufferGeometry.index`: the array type three.js picks for it, `Uint16Array`
117/// or `Uint32Array`, kept distinct because the renderer uploads them at
118/// different widths.
119#[derive(Clone, Debug)]
120pub enum Index {
121    /// A `Uint16Array` index — used while every value fits in 16 bits.
122    U16(Vec<u16>),
123    /// A `Uint32Array` index.
124    U32(Vec<u32>),
125}
126
127impl Index {
128    /// `index.count` — the number of indices.
129    pub fn count(&self) -> usize {
130        match self {
131            Index::U16(v) => v.len(),
132            Index::U32(v) => v.len(),
133        }
134    }
135
136    /// `index.getX( i )` — the `i`-th vertex index.
137    pub fn get_x(&self, i: usize) -> usize {
138        match self {
139            Index::U16(v) => v[i] as usize,
140            Index::U32(v) => v[i] as usize,
141        }
142    }
143
144    /// `index.setX( i, x )`. The index carries no version of its own, so
145    /// this is for a geometry the renderer has not uploaded yet.
146    pub fn set_x(&mut self, i: usize, x: usize) -> &mut Self {
147        match self {
148            Index::U16(v) => v[i] = x as u16,
149            Index::U32(v) => v[i] = x as u32,
150        }
151        self
152    }
153}
154
155/// One entry of `BufferGeometry.groups`.
156#[derive(Clone, Copy, Debug, PartialEq, Eq)]
157pub struct Group {
158    /// The first index (or vertex, for a non-indexed geometry) this group draws.
159    pub start: usize,
160    /// How many indices (or vertices) this group draws.
161    pub count: usize,
162    /// Which entry of the mesh's material array this group draws with.
163    pub material_index: usize,
164}
165
166/// `BufferGeometry.drawRange`. `count: None` is three.js' `Infinity` ("draw
167/// everything"), which has no `usize` spelling.
168#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
169pub struct DrawRange {
170    /// `drawRange.start`.
171    pub start: usize,
172    /// `drawRange.count`; `None` is three.js' `Infinity`.
173    pub count: Option<usize>,
174}
175
176/// What a cached pair of bounds was computed from: the `position` attribute's
177/// id and version, every `position` morph target's id and version in order,
178/// and `morph_targets_relative`. The ids are the numbers, never an
179/// [`AttributeId`](super::AttributeId) clone, which would mint a fresh id and
180/// never match.
181#[derive(Clone, Debug, PartialEq)]
182struct BoundsKey {
183    position: (usize, u32),
184    morph_positions: Vec<(usize, u32)>,
185    morph_targets_relative: bool,
186}
187
188impl BoundsKey {
189    /// Whether this key still describes `geometry`'s inputs, without building
190    /// a new key (that would allocate on every call, i.e. every frame).
191    fn matches(&self, geometry: &BufferGeometry, position: &BufferAttribute) -> bool {
192        if self.position != (position.id.get(), position.version())
193            || self.morph_targets_relative != geometry.morph_targets_relative
194        {
195            return false;
196        }
197        let morph = geometry.get_morph_attribute("position").unwrap_or(&[]);
198        morph.len() == self.morph_positions.len()
199            && morph
200                .iter()
201                .zip(&self.morph_positions)
202                .all(|(attribute, &key)| (attribute.id.get(), attribute.version()) == key)
203    }
204
205    fn of(geometry: &BufferGeometry, position: &BufferAttribute) -> Self {
206        Self {
207            position: (position.id.get(), position.version()),
208            morph_positions: geometry
209                .get_morph_attribute("position")
210                .unwrap_or(&[])
211                .iter()
212                .map(|attribute| (attribute.id.get(), attribute.version()))
213                .collect(),
214            morph_targets_relative: geometry.morph_targets_relative,
215        }
216    }
217}
218
219/// The box and the sphere computed together from one [`BoundsKey`].
220#[derive(Clone, Debug)]
221struct CachedBounds {
222    key: BoundsKey,
223    bounding_box: BoundingBox,
224    bounding_sphere: BoundingSphere,
225}
226
227/// Port of `BufferGeometry`'s state: the named attribute map, the index, morph
228/// attributes, groups and the draw range.
229///
230/// `attributes` is a `Vec` of pairs rather than a `HashMap` because three.js'
231/// `attributes` is a plain object, and `toNonIndexed()` and the renderer both
232/// iterate it in insertion order.
233#[derive(Debug, Default)]
234pub struct BufferGeometry {
235    /// `BufferGeometry.id`. Read-only in spirit; see [`GeometryId`] for why a
236    /// clone gets a new one, and why the renderer keys on it.
237    pub id: GeometryId,
238    attributes: Vec<(String, BufferAttribute)>,
239    /// `BufferGeometry.index`.
240    pub index: Option<Index>,
241    /// `BufferGeometry.morphAttributes` — per name, one attribute per morph
242    /// target.
243    morph_attributes: Vec<(String, Vec<BufferAttribute>)>,
244    /// `BufferGeometry.morphTargetsRelative`.
245    pub morph_targets_relative: bool,
246    /// `BufferGeometry.groups`.
247    pub groups: Vec<Group>,
248    /// `BufferGeometry.drawRange`.
249    pub draw_range: DrawRange,
250    /// `BufferGeometry.boundingSphere` when it was computed from something
251    /// other than the `position` attribute, which
252    /// [`compute_bounding_sphere`](Self::compute_bounding_sphere) then returns
253    /// instead of recomputing.
254    ///
255    /// three.js has this for free: `computeBoundingSphere()` writes
256    /// `this.boundingSphere` and the renderer reads the *field*, so a subclass
257    /// that overrides the method (`LineSegmentsGeometry`, which must measure
258    /// `instanceStart` / `instanceEnd` rather than its fixed ±2 quad) is
259    /// automatically what culling sees. The port's method has no field behind
260    /// it, so the override lands here.
261    pub bounding_sphere: Option<BoundingSphere>,
262    /// `InstancedBufferGeometry.instanceCount`. `Some` makes this an
263    /// `InstancedBufferGeometry`: `RenderObject.getInstanceCount()` reads it
264    /// ahead of the object's own count, and its
265    /// [instanced attributes](BufferAttribute::new_instanced) step per
266    /// instance.
267    pub instance_count: Option<usize>,
268    /// `BufferGeometry.indirect` — set with
269    /// [`set_indirect`](Self::set_indirect).
270    indirect: Option<super::IndirectStorageBufferAttribute>,
271    /// The last computed box and sphere and what they were computed from; see
272    /// [`compute_bounding_sphere`](Self::compute_bounding_sphere). Behind a
273    /// `RefCell` because the geometry is shared as `Rc<BufferGeometry>` and
274    /// culling asks for its sphere through `&self` every frame (issue #133).
275    bounds: RefCell<Option<CachedBounds>>,
276}
277
278/// `BufferGeometry.clone()` — `new this.constructor().copy( this )`, whose
279/// `copy()` clones every attribute and morph attribute through one shared
280/// `data` object, so views of one [`InterleavedBuffer`] still share a single
281/// (cloned) buffer afterwards rather than each de-interleaving. A fresh
282/// [`GeometryId`] and fresh attribute ids, as for any clone.
283impl Clone for BufferGeometry {
284    fn clone(&self) -> Self {
285        let mut buffers: HashMap<usize, Rc<InterleavedBuffer>> = HashMap::new();
286        let attributes = self
287            .attributes
288            .iter()
289            .map(|(name, attribute)| (name.clone(), attribute.clone_with(&mut buffers)))
290            .collect();
291        let morph_attributes = self
292            .morph_attributes
293            .iter()
294            .map(|(name, list)| {
295                let list = list.iter().map(|a| a.clone_with(&mut buffers)).collect();
296                (name.clone(), list)
297            })
298            .collect();
299        Self {
300            id: self.id.clone(),
301            attributes,
302            index: self.index.clone(),
303            morph_attributes,
304            morph_targets_relative: self.morph_targets_relative,
305            groups: self.groups.clone(),
306            draw_range: self.draw_range,
307            bounding_sphere: self.bounding_sphere,
308            instance_count: self.instance_count,
309            indirect: self.indirect.clone(),
310            bounds: self.bounds.clone(),
311        }
312    }
313}
314
315impl BufferGeometry {
316    /// `geometry.dispose()` — drops this handle, and nothing more. A mesh
317    /// holds its geometry as an `Rc`, which is what this takes; the renderer
318    /// frees the uploaded buffers once every handle is gone, at the top of the
319    /// next render (`docs/scene-graph.md`, "Identity and eviction"). Dropping
320    /// the `Rc` does the same; this exists so three.js code ports line for
321    /// line.
322    pub fn dispose(self: std::rc::Rc<Self>) {}
323
324    /// `new BufferGeometry()`.
325    pub fn new() -> Self {
326        Self::default()
327    }
328
329    /// `geometry.setIndirect( attribute )`: the draw's arguments come from
330    /// this buffer on the GPU — `drawIndirect` for a non-indexed geometry,
331    /// `drawIndexedIndirect` for an indexed one — so the vertex and instance
332    /// counts a kernel wrote are the ones drawn, with no CPU round trip.
333    pub fn set_indirect(&mut self, indirect: super::IndirectStorageBufferAttribute) -> &mut Self {
334        self.indirect = Some(indirect);
335        self
336    }
337
338    /// `geometry.indirect`.
339    pub fn indirect(&self) -> Option<&super::IndirectStorageBufferAttribute> {
340        self.indirect.as_ref()
341    }
342
343    /// `BufferGeometry.id` — the renderer's cache key for this geometry's
344    /// uploaded buffers.
345    pub fn id(&self) -> usize {
346        self.id.get()
347    }
348
349    /// `BufferGeometry.getAttribute( name )`.
350    pub fn get_attribute(&self, name: &str) -> Option<&BufferAttribute> {
351        self.attributes
352            .iter()
353            .find(|(key, _)| key == name)
354            .map(|(_, attribute)| attribute)
355    }
356
357    /// `BufferGeometry.getAttribute( name )`, mutably.
358    ///
359    /// The `&mut` setters on [`BufferAttribute`] (`set_xyz` and the rest) do not
360    /// bump its version, so handing one out drops the cached bounds.
361    pub fn get_attribute_mut(&mut self, name: &str) -> Option<&mut BufferAttribute> {
362        self.invalidate_bounds();
363        self.attributes
364            .iter_mut()
365            .find(|(key, _)| key == name)
366            .map(|(_, attribute)| attribute)
367    }
368
369    /// `BufferGeometry.setAttribute( name, attribute )`.
370    pub fn set_attribute(&mut self, name: &str, attribute: BufferAttribute) -> &mut Self {
371        self.invalidate_bounds();
372        match self.attributes.iter_mut().find(|(key, _)| key == name) {
373            // a JS object keeps the key's original position on reassignment
374            Some(slot) => slot.1 = attribute,
375            None => self.attributes.push((name.to_string(), attribute)),
376        }
377
378        self
379    }
380
381    /// `BufferGeometry.deleteAttribute( name )`.
382    pub fn delete_attribute(&mut self, name: &str) -> &mut Self {
383        self.invalidate_bounds();
384        self.attributes.retain(|(key, _)| key != name);
385        self
386    }
387
388    /// `BufferGeometry.hasAttribute( name )`.
389    pub fn has_attribute(&self, name: &str) -> bool {
390        self.get_attribute(name).is_some()
391    }
392
393    /// `for ( const name in geometry.attributes )`, in insertion order.
394    pub fn attributes(&self) -> impl Iterator<Item = (&str, &BufferAttribute)> {
395        self.attributes
396            .iter()
397            .map(|(name, attribute)| (name.as_str(), attribute))
398    }
399
400    /// One [`AttributeDesc`] per attribute, in insertion order — what
401    /// `SetupContext::geometry_attributes` carries to the node builder.
402    /// Views of one [`InterleavedBuffer`] share a group number: the position
403    /// of the first of them.
404    ///
405    /// Rebuilt on every call (one `String` per attribute) rather than cached
406    /// on the geometry: an attribute's kind can change behind `&self` —
407    /// [`BufferAttribute::data_mut`] swaps in a new [`TypedArray`](super::TypedArray)
408    /// through a shared borrow, as can the shared array of an interleaved
409    /// view — so no `&mut` geometry path sees every change a cache would
410    /// have to drop.
411    #[doc(hidden)]
412    pub fn attribute_descs(&self) -> Vec<AttributeDesc> {
413        let mut groups: Vec<(usize, usize)> = Vec::new();
414        self.attributes
415            .iter()
416            .enumerate()
417            .map(|(i, (name, attribute))| {
418                let group = match attribute.data_buffer() {
419                    Some(data) => match groups.iter().find(|(id, _)| *id == data.id()) {
420                        Some((_, group)) => *group,
421                        None => {
422                            groups.push((data.id(), i));
423                            i
424                        }
425                    },
426                    None => i,
427                };
428                attribute.desc(name, group)
429            })
430            .collect()
431    }
432
433    /// `geometry.attributes.position`.
434    pub fn position(&self) -> Option<&BufferAttribute> {
435        self.get_attribute("position")
436    }
437
438    /// `geometry.attributes.normal`.
439    pub fn normal(&self) -> Option<&BufferAttribute> {
440        self.get_attribute("normal")
441    }
442
443    /// `geometry.attributes.uv`.
444    pub fn uv(&self) -> Option<&BufferAttribute> {
445        self.get_attribute("uv")
446    }
447
448    /// `geometry.morphAttributes[ name ]`.
449    pub fn get_morph_attribute(&self, name: &str) -> Option<&[BufferAttribute]> {
450        self.morph_attributes
451            .iter()
452            .find(|(key, _)| key == name)
453            .map(|(_, attributes)| attributes.as_slice())
454    }
455
456    /// `geometry.morphAttributes[ name ] = attributes`.
457    pub fn set_morph_attribute(
458        &mut self,
459        name: &str,
460        attributes: Vec<BufferAttribute>,
461    ) -> &mut Self {
462        self.invalidate_bounds();
463        match self
464            .morph_attributes
465            .iter_mut()
466            .find(|(key, _)| key == name)
467        {
468            Some(slot) => slot.1 = attributes,
469            None => self.morph_attributes.push((name.to_string(), attributes)),
470        }
471
472        self
473    }
474
475    /// `for ( const name in geometry.morphAttributes )`, in insertion order.
476    pub fn morph_attributes(&self) -> impl Iterator<Item = (&str, &[BufferAttribute])> {
477        self.morph_attributes
478            .iter()
479            .map(|(name, attributes)| (name.as_str(), attributes.as_slice()))
480    }
481
482    /// `BufferGeometry.addGroup( start, count, materialIndex )`.
483    pub fn add_group(&mut self, start: usize, count: usize, material_index: usize) {
484        self.groups.push(Group {
485            start,
486            count,
487            material_index,
488        });
489    }
490
491    /// `BufferGeometry.clearGroups()`.
492    pub fn clear_groups(&mut self) {
493        self.groups = Vec::new();
494    }
495
496    /// `BufferGeometry.setDrawRange( start, count )`.
497    pub fn set_draw_range(&mut self, start: usize, count: usize) {
498        self.draw_range.start = start;
499        self.draw_range.count = Some(count);
500    }
501
502    /// `BufferGeometry.setFromPoints( points )`.
503    ///
504    /// three.js overwrites an existing `position` attribute in place when there
505    /// already is one, and only allocates a fresh `Float32BufferAttribute` when
506    /// there is not; the in-place branch keeps the attribute's own count, so
507    /// extra points are dropped and missing ones leave whatever was there.
508    pub fn set_from_points(&mut self, points: &[Vector3]) -> &mut Self {
509        match self.get_attribute_mut("position") {
510            Some(position) => {
511                let count = position.count().min(points.len());
512                for (i, point) in points.iter().take(count).enumerate() {
513                    position.set_xyz(i, point.x, point.y, point.z);
514                }
515            }
516            None => {
517                let mut array = Vec::with_capacity(points.len() * 3);
518                for point in points {
519                    array.push(point.x as f32);
520                    array.push(point.y as f32);
521                    array.push(point.z as f32);
522                }
523                self.set_attribute("position", BufferAttribute::new(array, 3));
524            }
525        }
526
527        self
528    }
529
530    /// `BufferGeometry.setIndex( array )` — picks `Uint16` when it fits, the
531    /// same rule three.js uses.
532    pub fn set_index(&mut self, indices: &[u32]) {
533        let max = indices.iter().copied().max().unwrap_or(0);
534        self.index = Some(if max > 65535 {
535            Index::U32(indices.to_vec())
536        } else {
537            Index::U16(indices.iter().map(|&i| i as u16).collect())
538        });
539    }
540
541    /// `BufferGeometry.setIndex( bufferAttribute )` — keeps the array type the
542    /// source declared, which is what `BufferGeometryLoader.parse()` does.
543    pub fn set_index_attribute(&mut self, index: Index) {
544        self.index = Some(index);
545    }
546
547    /// Drops the cached bounds. The `&mut` methods that swap or hand out an
548    /// attribute call it; an edit through `array_mut()` is caught by the
549    /// version instead, once `set_needs_update()` bumps it.
550    fn invalidate_bounds(&mut self) {
551        *self.bounds.get_mut() = None;
552    }
553
554    /// The centre of `BufferGeometry.computeBoundingSphere()`'s sphere, which is
555    /// `Box3.setFromBufferAttribute( position ).getCenter()` — the only part of
556    /// the bounding sphere the render-list sort reads. Served from the same
557    /// cache as [`compute_bounding_box`](Self::compute_bounding_box).
558    pub(crate) fn bounding_sphere_center(&self) -> Vector3 {
559        match self.compute_bounding_box() {
560            Some(box3) => box3.center(),
561            None => Vector3::ZERO,
562        }
563    }
564
565    /// `BufferGeometry.computeBoundingBox()` — `Box3.setFromBufferAttribute(
566    /// position )`. `None` when there is no position attribute (three.js leaves
567    /// `boundingBox` alone in that case).
568    ///
569    /// Cached, together with the sphere; see
570    /// [`compute_bounding_sphere`](Self::compute_bounding_sphere) for when the
571    /// cache is recomputed.
572    pub fn compute_bounding_box(&self) -> Option<BoundingBox> {
573        self.cached_bounds().map(|(bounding_box, _)| bounding_box)
574    }
575
576    /// `BufferGeometry.computeBoundingSphere()`: the bounding box's centre, then
577    /// the largest distance from it to any vertex (which beats the box's own
578    /// sphere by up to sqrt(3)).
579    ///
580    /// The pub [`bounding_sphere`](Self::bounding_sphere) field, when set, is
581    /// returned as it is, ahead of anything computed here.
582    ///
583    /// Otherwise the box and the sphere are computed once and cached, keyed on
584    /// the `position` attribute's id and version, each `position` morph
585    /// target's id and version, and `morph_targets_relative`. Culling calls
586    /// this for every object every frame, so walking every vertex each time
587    /// was most of a frame for a scene of many meshes (issue #133). The cache
588    /// is dropped by the `&mut` methods that replace or hand out an attribute
589    /// (`set_attribute`, `delete_attribute`, `set_morph_attribute`,
590    /// `get_attribute_mut` and so everything built on it, `apply_matrix4` and
591    /// `set_from_points` included). An edit through
592    /// [`array_mut()`](BufferAttribute::array_mut) is seen only after
593    /// [`set_needs_update()`](BufferAttribute::set_needs_update), the same rule
594    /// the renderer's buffer upload follows. That is stricter than three.js,
595    /// whose `boundingSphere` is never invalidated by itself: there a moved
596    /// vertex needs `computeBoundingSphere()` called again by hand.
597    pub fn compute_bounding_sphere(&self) -> Option<BoundingSphere> {
598        if let Some(sphere) = self.bounding_sphere {
599            return Some(sphere);
600        }
601        self.cached_bounds()
602            .map(|(_, bounding_sphere)| bounding_sphere)
603    }
604
605    /// The cached box and sphere, recomputed first if their key has moved.
606    fn cached_bounds(&self) -> Option<(BoundingBox, BoundingSphere)> {
607        let position = self.position()?;
608
609        if let Some(cached) = self.bounds.borrow().as_ref() {
610            if cached.key.matches(self, position) {
611                return Some((cached.bounding_box, cached.bounding_sphere));
612            }
613        }
614
615        let bounding_box = self.bounding_box_from_positions(position);
616        let bounding_sphere = self.bounding_sphere_from_positions(position, &bounding_box);
617
618        *self.bounds.borrow_mut() = Some(CachedBounds {
619            key: BoundsKey::of(self, position),
620            bounding_box,
621            bounding_sphere,
622        });
623
624        Some((bounding_box, bounding_sphere))
625    }
626
627    /// `computeBoundingBox()`'s body, uncached.
628    fn bounding_box_from_positions(&self, position: &BufferAttribute) -> BoundingBox {
629        let mut bounding_box = BoundingBox::from_buffer_attribute(position);
630
631        // process morph attributes if present
632        if let Some(morph_positions) = self.get_morph_attribute("position") {
633            for morph_attribute in morph_positions {
634                let box3 = BoundingBox::from_buffer_attribute(morph_attribute);
635
636                if self.morph_targets_relative {
637                    let mut vector = Vector3::ZERO;
638                    vector.add_vectors(&bounding_box.min, &box3.min);
639                    bounding_box.expand_by_point(&vector);
640
641                    vector.add_vectors(&bounding_box.max, &box3.max);
642                    bounding_box.expand_by_point(&vector);
643                } else {
644                    bounding_box.expand_by_point(&box3.min);
645                    bounding_box.expand_by_point(&box3.max);
646                }
647            }
648        }
649
650        bounding_box
651    }
652
653    /// `computeBoundingSphere()`'s body, uncached, around `bounding_box`'s
654    /// centre.
655    fn bounding_sphere_from_positions(
656        &self,
657        position: &BufferAttribute,
658        bounding_box: &BoundingBox,
659    ) -> BoundingSphere {
660        // `_box` already has the morph targets expanded into it
661        let center = bounding_box.center();
662
663        let mut max_radius_sq: f64 = 0.0;
664
665        for i in 0..position.count() {
666            let v = position.get_vector3(i);
667            max_radius_sq = max_radius_sq.max(center.distance_to_squared(&v));
668        }
669
670        // process morph attributes if present
671        if let Some(morph_positions) = self.get_morph_attribute("position") {
672            for morph_attribute in morph_positions {
673                for j in 0..morph_attribute.count() {
674                    let mut vector = morph_attribute.get_vector3(j);
675
676                    if self.morph_targets_relative {
677                        let offset = position.get_vector3(j);
678                        vector.add(&offset);
679                    }
680
681                    max_radius_sq = max_radius_sq.max(center.distance_to_squared(&vector));
682                }
683            }
684        }
685
686        BoundingSphere {
687            center,
688            radius: max_radius_sq.sqrt(),
689        }
690    }
691
692    /// `BufferGeometry.computeVertexNormals()`.
693    ///
694    /// The accumulation runs through the `normal` attribute itself, so every
695    /// partial sum is rounded to `f32` before the next triangle adds to it.
696    /// An existing `normal` of the right count is written in place through
697    /// its setters, whatever its array kind and interleaved or not, and
698    /// marked for re-upload; a missing one (or one of another count) is
699    /// replaced by a new `Float32Array` attribute.
700    pub fn compute_vertex_normals(&mut self) {
701        let Some(count) = self.position().map(BufferAttribute::count) else {
702            return;
703        };
704
705        let needs_new = match self.normal() {
706            Some(normal) => normal.count() != count,
707            None => true,
708        };
709        if needs_new {
710            self.set_attribute("normal", BufferAttribute::new(vec![0.0; count * 3], 3));
711        }
712
713        let position = self.position().expect("three-rs: checked above");
714        let normal = self.normal().expect("three-rs: set above if missing");
715        let set_xyz = |i: usize, v: &Vector3| {
716            normal.store(i, 0, v.x);
717            normal.store(i, 1, v.y);
718            normal.store(i, 2, v.z);
719        };
720        if !needs_new {
721            for i in 0..normal.count() {
722                set_xyz(i, &Vector3::ZERO);
723            }
724        }
725
726        let mut cb = Vector3::ZERO;
727        let mut ab = Vector3::ZERO;
728
729        // indexed elements
730        if let Some(index) = &self.index {
731            let get = |i: usize| -> usize {
732                match index {
733                    Index::U16(v) => v[i] as usize,
734                    Index::U32(v) => v[i] as usize,
735                }
736            };
737
738            // three.js writes `i < index.count()`, which in JS reads past the
739            // end of the typed array for a trailing partial triangle and stores
740            // NaN; in Rust that panics, so incomplete triangles are skipped.
741            let mut i = 0;
742            while i + 2 < index.count() {
743                let (v_a, v_b, v_c) = (get(i), get(i + 1), get(i + 2));
744
745                let p_a = position.get_vector3(v_a);
746                let p_b = position.get_vector3(v_b);
747                let p_c = position.get_vector3(v_c);
748
749                cb.sub_vectors(&p_c, &p_b);
750                ab.sub_vectors(&p_a, &p_b);
751                cb.cross(&ab);
752
753                let mut n_a = normal.get_vector3(v_a);
754                let mut n_b = normal.get_vector3(v_b);
755                let mut n_c = normal.get_vector3(v_c);
756
757                n_a.add(&cb);
758                n_b.add(&cb);
759                n_c.add(&cb);
760
761                set_xyz(v_a, &n_a);
762                set_xyz(v_b, &n_b);
763                set_xyz(v_c, &n_c);
764
765                i += 3;
766            }
767        } else {
768            // As above: a position count that is not a multiple of three
769            // leaves the trailing vertices' normals at zero rather than NaN.
770            let mut i = 0;
771            while i + 2 < position.count() {
772                let p_a = position.get_vector3(i);
773                let p_b = position.get_vector3(i + 1);
774                let p_c = position.get_vector3(i + 2);
775
776                cb.sub_vectors(&p_c, &p_b);
777                ab.sub_vectors(&p_a, &p_b);
778                cb.cross(&ab);
779
780                set_xyz(i, &cb);
781                set_xyz(i + 1, &cb);
782                set_xyz(i + 2, &cb);
783
784                i += 3;
785            }
786        }
787
788        self.normalize_normals();
789        if let Some(normal) = self.normal() {
790            normal.set_needs_update();
791        }
792    }
793
794    /// `BufferGeometry.normalizeNormals()`.
795    pub fn normalize_normals(&mut self) {
796        let Some(normal) = self.get_attribute_mut("normal") else {
797            return;
798        };
799
800        for i in 0..normal.count() {
801            let mut v = normal.get_vector3(i);
802            v.normalize();
803            normal.set_xyz(i, v.x, v.y, v.z);
804        }
805    }
806
807    /// `BufferGeometry.applyMatrix4()`.
808    pub fn apply_matrix4(&mut self, matrix: &Matrix4) -> &mut Self {
809        if let Some(position) = self.get_attribute_mut("position") {
810            position.apply_matrix4(matrix);
811        }
812
813        if let Some(normal) = self.get_attribute_mut("normal") {
814            let mut normal_matrix = Matrix3::identity();
815            normal_matrix.get_normal_matrix(matrix);
816            normal.apply_normal_matrix(&normal_matrix);
817        }
818
819        self
820    }
821
822    /// `BufferGeometry.scale()`.
823    pub fn scale(&mut self, x: f64, y: f64, z: f64) -> &mut Self {
824        let mut m1 = Matrix4::identity();
825        m1.make_scale(x, y, z);
826        self.apply_matrix4(&m1)
827    }
828
829    /// `BufferGeometry.applyQuaternion()`.
830    pub fn apply_quaternion(&mut self, q: &Quaternion) -> &mut Self {
831        let mut m1 = Matrix4::identity();
832        m1.make_rotation_from_quaternion(q);
833        self.apply_matrix4(&m1)
834    }
835
836    /// `BufferGeometry.rotateX()` — rotates the geometry about the world x-axis.
837    pub fn rotate_x(&mut self, angle: f64) -> &mut Self {
838        let mut m1 = Matrix4::identity();
839        m1.make_rotation_x(angle);
840        self.apply_matrix4(&m1)
841    }
842
843    /// `BufferGeometry.rotateY()`.
844    pub fn rotate_y(&mut self, angle: f64) -> &mut Self {
845        let mut m1 = Matrix4::identity();
846        m1.make_rotation_y(angle);
847        self.apply_matrix4(&m1)
848    }
849
850    /// `BufferGeometry.rotateZ()`.
851    pub fn rotate_z(&mut self, angle: f64) -> &mut Self {
852        let mut m1 = Matrix4::identity();
853        m1.make_rotation_z(angle);
854        self.apply_matrix4(&m1)
855    }
856
857    /// `BufferGeometry.translate()`.
858    pub fn translate(&mut self, x: f64, y: f64, z: f64) -> &mut Self {
859        let mut m1 = Matrix4::identity();
860        m1.make_translation(x, y, z);
861        self.apply_matrix4(&m1)
862    }
863
864    /// `BufferGeometry.lookAt()` — rotates the geometry so its +Z points away
865    /// from `vector`, through a scratch `Object3D` exactly as three.js does.
866    pub fn look_at(&mut self, vector: &Vector3) -> &mut Self {
867        let mut object = crate::core::Object3D::default();
868        object.look_at(vector);
869        object.update_matrix();
870
871        let matrix = object.matrix;
872        self.apply_matrix4(&matrix)
873    }
874
875    /// `BufferGeometry.center()`.
876    pub fn center(&mut self) -> &mut Self {
877        let Some(bounding_box) = self.compute_bounding_box() else {
878            return self;
879        };
880
881        let mut offset = bounding_box.center();
882        offset.negate();
883
884        self.translate(offset.x, offset.y, offset.z)
885    }
886
887    /// `BufferGeometry.toNonIndexed()`.
888    pub fn to_non_indexed(&self) -> Self {
889        let Some(index) = self.index.as_ref() else {
890            // `BufferGeometry.toNonIndexed(): BufferGeometry is already
891            // non-indexed.`
892            return self.clone();
893        };
894
895        let indices: Vec<usize> = match index {
896            Index::U16(v) => v.iter().map(|&i| i as usize).collect(),
897            Index::U32(v) => v.iter().map(|&i| i as usize).collect(),
898        };
899
900        // `convertBufferAttribute()`: same kind, item size and `normalized`;
901        // an interleaved view is read through its stride and comes out plain.
902        let convert = |attribute: &BufferAttribute| attribute.gather(&indices);
903
904        let mut geometry2 = Self::new();
905
906        // attributes
907        for (name, attribute) in self.attributes() {
908            geometry2.set_attribute(name, convert(attribute));
909        }
910
911        // morph attributes
912        let morph: Vec<(String, Vec<BufferAttribute>)> = self
913            .morph_attributes()
914            .map(|(name, attributes)| {
915                (
916                    name.to_string(),
917                    attributes.iter().map(convert).collect::<Vec<_>>(),
918                )
919            })
920            .collect();
921        for (name, attributes) in morph {
922            geometry2.set_morph_attribute(&name, attributes);
923        }
924
925        geometry2.morph_targets_relative = self.morph_targets_relative;
926
927        // groups
928        for group in &self.groups {
929            geometry2.add_group(group.start, group.count, group.material_index);
930        }
931
932        geometry2
933    }
934}
935
936#[cfg(test)]
937mod tests {
938    use super::*;
939
940    fn triangle() -> BufferGeometry {
941        let mut geometry = BufferGeometry::new();
942        geometry.set_attribute(
943            "position",
944            BufferAttribute::new(vec![-1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 2.0, 0.0], 3),
945        );
946        geometry
947    }
948
949    #[test]
950    fn bounds_are_the_same_on_a_second_call() {
951        let geometry = triangle();
952        let box1 = geometry.compute_bounding_box().unwrap();
953        let sphere1 = geometry.compute_bounding_sphere().unwrap();
954        assert_eq!(geometry.compute_bounding_box().unwrap(), box1);
955        assert_eq!(geometry.compute_bounding_sphere().unwrap(), sphere1);
956        assert_eq!(geometry.bounding_sphere_center(), box1.center());
957        assert_eq!(sphere1.center, Vector3::new(0.0, 1.0, 0.0));
958    }
959
960    #[test]
961    fn an_in_place_edit_shows_after_set_needs_update() {
962        let geometry = triangle();
963        let before = geometry.compute_bounding_sphere().unwrap();
964
965        let position = geometry.position().unwrap();
966        position.array_mut()[0] = -11.0;
967        // not yet marked: the bounds, like the uploaded buffer, are stale
968        assert_eq!(geometry.compute_bounding_sphere().unwrap(), before);
969
970        position.set_needs_update();
971        let after = geometry.compute_bounding_sphere().unwrap();
972        assert_eq!(after.center, Vector3::new(-5.0, 1.0, 0.0));
973        assert_eq!(geometry.bounding_sphere_center(), after.center);
974        assert_eq!(
975            geometry.compute_bounding_box().unwrap().min,
976            Vector3::new(-11.0, 0.0, 0.0)
977        );
978    }
979
980    #[test]
981    fn set_attribute_recomputes() {
982        let mut geometry = triangle();
983        geometry.compute_bounding_sphere().unwrap();
984        geometry.set_attribute(
985            "position",
986            BufferAttribute::new(vec![10.0, 0.0, 0.0, 12.0, 0.0, 0.0], 3),
987        );
988        let sphere = geometry.compute_bounding_sphere().unwrap();
989        assert_eq!(sphere.center, Vector3::new(11.0, 0.0, 0.0));
990        assert_eq!(sphere.radius, 1.0);
991    }
992
993    #[test]
994    fn a_mutating_transform_recomputes() {
995        let mut geometry = triangle();
996        geometry.compute_bounding_sphere().unwrap();
997        geometry.translate(0.0, 0.0, 5.0);
998        assert_eq!(
999            geometry.compute_bounding_sphere().unwrap().center,
1000            Vector3::new(0.0, 1.0, 5.0)
1001        );
1002        geometry.center();
1003        assert_eq!(geometry.bounding_sphere_center(), Vector3::ZERO);
1004    }
1005
1006    #[test]
1007    fn a_clone_keeps_its_own_bounds() {
1008        let original = triangle();
1009        let original_sphere = original.compute_bounding_sphere().unwrap();
1010
1011        // the clone carries the original's cache, keyed on the original's ids
1012        let clone = original.clone();
1013        assert_eq!(clone.compute_bounding_sphere().unwrap(), original_sphere);
1014
1015        clone.position().unwrap().array_mut()[0] = -11.0;
1016        clone.position().unwrap().set_needs_update();
1017        assert_eq!(
1018            clone.compute_bounding_sphere().unwrap().center,
1019            Vector3::new(-5.0, 1.0, 0.0)
1020        );
1021        assert_eq!(original.compute_bounding_sphere().unwrap(), original_sphere);
1022
1023        original.position().unwrap().array_mut()[3] = 21.0;
1024        original.position().unwrap().set_needs_update();
1025        assert_eq!(
1026            original.compute_bounding_sphere().unwrap().center,
1027            Vector3::new(10.0, 1.0, 0.0)
1028        );
1029        assert_eq!(
1030            clone.compute_bounding_sphere().unwrap().center,
1031            Vector3::new(-5.0, 1.0, 0.0)
1032        );
1033    }
1034
1035    #[test]
1036    fn a_morph_position_edit_recomputes() {
1037        let mut geometry = triangle();
1038        geometry.set_morph_attribute(
1039            "position",
1040            vec![BufferAttribute::new(
1041                vec![-1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 2.0, 0.0],
1042                3,
1043            )],
1044        );
1045        let before = geometry.compute_bounding_box().unwrap();
1046        assert_eq!(before.max, Vector3::new(1.0, 2.0, 0.0));
1047
1048        let morph = &geometry.get_morph_attribute("position").unwrap()[0];
1049        morph.array_mut()[3] = 9.0;
1050        morph.set_needs_update();
1051        assert_eq!(
1052            geometry.compute_bounding_box().unwrap().max,
1053            Vector3::new(9.0, 2.0, 0.0)
1054        );
1055
1056        // relative targets are offsets from `position`: a key change too
1057        geometry.morph_targets_relative = true;
1058        assert_eq!(
1059            geometry.compute_bounding_box().unwrap().max,
1060            Vector3::new(10.0, 4.0, 0.0)
1061        );
1062    }
1063
1064    #[test]
1065    fn the_override_field_still_wins() {
1066        let mut geometry = triangle();
1067        geometry.compute_bounding_sphere().unwrap();
1068        let sphere = BoundingSphere {
1069            center: Vector3::new(7.0, 7.0, 7.0),
1070            radius: 3.0,
1071        };
1072        geometry.bounding_sphere = Some(sphere);
1073        assert_eq!(geometry.compute_bounding_sphere(), Some(sphere));
1074    }
1075}