ifc_lite_imported_geometry/
math.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4use crate::{ImportError, MeshOutput, PointsOutput, RawMatrix, RawMesh};
5const IDENTITY: [f32; 16] = [1.,0.,0.,0.,0.,1.,0.,0.,0.,0.,1.,0.,0.,0.,0.,1.];
6pub fn stage_values(values: &[f64]) -> Vec<f32> { values.iter().map(|v| *v as f32).collect() }
7pub fn stage_transform(stack: &[RawMatrix], canonical: bool) -> Option<[f32; 16]> {
8    let mut world: Option<[f32; 16]> = None;
9    for matrix in stack {
10        let mut local = IDENTITY;
11        for row in 0..4 { for col in 0..4 {
12            if let Some(value) = matrix.get(row).and_then(|r| r.get(col)) { local[row*4+col] = *value as f32; }
13        }}
14        world = Some(match world {
15            None => local,
16            Some(parent) => {
17                let mut out = [0.; 16];
18                for row in 0..4 { for col in 0..4 {
19                    let mut sum = 0.0_f64;
20                    for k in 0..4 { sum += local[row*4+k] as f64 * parent[k*4+col] as f64; }
21                    out[row*4+col] = sum as f32;
22                }}
23                out
24            }
25        });
26        if canonical && world == Some(IDENTITY) { world = None; }
27    }
28    world
29}
30pub fn compute_normal_matrix(m: &[f32]) -> Option<Vec<f32>> {
31    let at = |i| m.get(i).copied().unwrap_or(f32::NAN) as f64;
32    let (a,b,c,d,e,f,g,h,i)=(at(0),at(1),at(2),at(4),at(5),at(6),at(8),at(9),at(10));
33    let det = a*(e*i-f*h)-b*(d*i-f*g)+c*(d*h-e*g);
34    if !det.is_finite() || det.abs() < 1e-12 { return None; }
35    let inv = 1./det;
36    Some([e*i-f*h,-(d*i-f*g),d*h-e*g,-(b*i-c*h),a*i-c*g,-(a*h-b*g),b*f-c*e,-(a*f-c*d),a*e-b*d].map(|x| (x*inv) as f32).to_vec())
37}
38fn at(values: &[f32], i: usize) -> f64 { values.get(i).copied().unwrap_or(f32::NAN) as f64 }
39/// Float offset of a vertex's first component. `None` unless all three
40/// components (`offset..=offset + 2`) are representable, so no later `+1`/`+2`
41/// can wrap (on wasm32 index 0x55555555 multiplies to exactly `usize::MAX`).
42pub(crate) fn vertex_offset(index: usize) -> Option<usize> {
43    let offset = index.checked_mul(3)?;
44    offset.checked_add(2)?;
45    Some(offset)
46}
47pub fn compute_normals(positions: &[f32], indices: &[u32]) -> Vec<f32> {
48    let mut normals = vec![0.; positions.len()];
49    for tri in indices.chunks(3) {
50        let ids = [0, 1, 2].map(|i| tri.get(i).and_then(|x| vertex_offset(*x as usize)).unwrap_or(usize::MAX - 2));
51        let (a,b,c)=(ids[0],ids[1],ids[2]);
52        let e1=[at(positions,b)-at(positions,a),at(positions,b+1)-at(positions,a+1),at(positions,b+2)-at(positions,a+2)];
53        let e2=[at(positions,c)-at(positions,a),at(positions,c+1)-at(positions,a+1),at(positions,c+2)-at(positions,a+2)];
54        let n=[e1[1]*e2[2]-e1[2]*e2[1],e1[2]*e2[0]-e1[0]*e2[2],e1[0]*e2[1]-e1[1]*e2[0]];
55        for id in ids { for (j, value) in n.iter().enumerate() { if let Some(v)=normals.get_mut(id+j) { *v=(*v as f64+value) as f32; }}}
56    }
57    for chunk in normals.chunks_mut(3) {
58        let len=(at(chunk,0).powi(2)+at(chunk,1).powi(2)+at(chunk,2).powi(2)).sqrt();
59        if len>0. { for v in chunk { *v=(*v as f64/len) as f32; } }
60    }
61    normals
62}
63fn component(row: &[f64], i: usize) -> f64 { row.get(i).copied().unwrap_or(f64::NAN) }
64fn denominator(p: [f64; 3], m: &[f32;16]) -> f64 { m[3] as f64*p[0]+m[7] as f64*p[1]+m[11] as f64*p[2]+m[15] as f64 }
65fn bad_w(w:f64)->bool { !w.is_finite() || w.abs()<1e-12 }
66fn placed(p:[f64;3],m:&[f32;16],w:f64,reciprocal:bool)->[f64;3] {
67    let mut out=[0.;3];
68    for c in 0..3 {
69        let n=m[c] as f64*p[0]+m[4+c] as f64*p[1]+m[8+c] as f64*p[2]+m[12+c] as f64;
70        out[c]=if reciprocal { n*(1./w) } else { n/w };
71    }
72    out
73}
74fn yup(p:[f64;3])->[f32;3] { [p[0] as f32,p[2] as f32,(-p[1]) as f32] }
75fn to_uint32(v:f64)->u32 {
76    if !v.is_finite() || v==0. {0} else {v.trunc().rem_euclid(4294967296.) as u32}
77}
78pub(crate) fn mesh(source:&RawMesh,stack:&[RawMatrix])->Result<MeshOutput,ImportError> {
79    let transform=stage_transform(stack,true);
80    let mut positions=Vec::with_capacity(source.points.len()*3);
81    for row in &source.points {
82        let mut p=[component(row,0),component(row,1),component(row,2)];
83        if let Some(m)=transform { let w=denominator(p,&m); if bad_w(w) {return Err(ImportError::HomogeneousMesh);} p=placed(p,&m,w,false); }
84        positions.extend(yup(p));
85    }
86    let mut indices=Vec::new();
87    if let Some(counts)=source.face_vertex_counts.as_ref().filter(|x| !x.is_empty()) {
88        // Untrusted counts. The walk ends at the first count that is not a finite
89        // non-negative integer. `offset` stays within 0..=indices.len() and a face
90        // never fans past the indices that exist, so the total number of emitted
91        // triangles is at most indices.len() and work stays bounded.
92        let len=source.face_vertex_indices.len();
93        let get=|index:usize| source.face_vertex_indices.get(index).copied().unwrap_or(f64::NAN);
94        let mut offset=0usize;
95        for &count in counts {
96            if !count.is_finite() || count<0. || count.fract()!=0. { break; }
97            let available=len-offset;
98            // Saturating: counts beyond the remaining indices clamp to them.
99            let n=if count>=available as f64 {available} else {count as usize};
100            for i in 1..n.saturating_sub(1) {
101                indices.extend([to_uint32(get(offset)),to_uint32(get(offset+i)),to_uint32(get(offset+i+1))]);
102            }
103            offset+=n;
104            if count>available as f64 { break; }
105        }
106    } else { indices.extend(source.face_vertex_indices.iter().map(|x|to_uint32(*x))); }
107    let normals=match &source.normals {
108        None=>compute_normals(&positions,&indices),
109        Some(raw)=>{
110            let normal=transform.and_then(|m|compute_normal_matrix(&m));
111            let mut out=Vec::with_capacity(raw.len()*3);
112            for row in raw {
113                let mut p=[component(row,0),component(row,1),component(row,2)];
114                if let Some(ref m)=normal {
115                    let n=[p[0]*m[0] as f64+p[1]*m[3] as f64+p[2]*m[6] as f64,p[0]*m[1] as f64+p[1]*m[4] as f64+p[2]*m[7] as f64,p[0]*m[2] as f64+p[1]*m[5] as f64+p[2]*m[8] as f64];
116                    let len=(n[0].powi(2)+n[1].powi(2)+n[2].powi(2)).sqrt();
117                    p=if len>0. {n.map(|v|v/len)}else{n};
118                }
119                out.extend(yup(p));
120            }
121            out
122        }
123    };
124    Ok(MeshOutput{positions,normals,indices})
125}
126pub(crate) fn points(source:&[f64],stack:&[RawMatrix])->Result<PointsOutput,ImportError> {
127    let transform=stage_transform(stack,false);
128    let staged=stage_values(source);
129    let mut positions=Vec::with_capacity(source.len());
130    let mut min=[f64::INFINITY;3]; let mut max=[f64::NEG_INFINITY;3];
131    for chunk in staged.chunks(3) {
132        let mut p=[at(chunk,0),at(chunk,1),at(chunk,2)];
133        if let Some(m)=transform { let w=denominator(p,&m); if chunk.len()==3 && p.iter().all(|v| v.is_finite()) && bad_w(w) {return Err(ImportError::HomogeneousPoints);} p=placed(p,&m,w,true); }
134        let out=yup(p);
135        positions.extend_from_slice(&out[..chunk.len()]);
136        for j in 0..3 { let v=if j<chunk.len(){out[j] as f64}else{f64::NAN}; if v<min[j]{min[j]=v;}
137            if v>max[j]{max[j]=v;} }
138    }
139    Ok(PointsOutput{positions,min,max})
140}