1use std::sync::Arc;
53
54use unityrs_core::limits::{Charge, Meter, MeteredVec};
55
56use crate::error::{MeshError, StructError};
57use crate::format::{Norm, StructCode};
58
59#[derive(Debug)]
65pub struct VertexArray {
66 dimension: usize,
67 values: Values,
68 _charge: Charge,
70}
71
72const _: () = crate::send_sync::<VertexArray>();
73
74#[derive(Debug, PartialEq)]
81#[non_exhaustive]
82pub enum Values {
83 Float(Vec<f64>),
85 Int(Vec<i64>),
87 Mixed(Vec<Component>),
91}
92
93const _: () = crate::send_sync::<Values>();
94
95impl VertexArray {
96 #[must_use]
98 pub fn from_components(dimension: usize, values: MeteredVec<Component>) -> Self {
99 let (values, charge) = values.into_parts();
100 Self::new(dimension, Values::Mixed(values), charge)
101 }
102
103 pub(crate) fn new(dimension: usize, values: Values, charge: Charge) -> Self {
106 Self {
107 dimension,
108 values,
109 _charge: charge,
110 }
111 }
112
113 #[must_use]
115 pub fn dimension(&self) -> usize {
116 self.dimension
117 }
118
119 fn values_len(&self) -> usize {
121 match &self.values {
122 Values::Float(v) => v.len(),
123 Values::Int(v) => v.len(),
124 Values::Mixed(v) => v.len(),
125 }
126 }
127
128 #[must_use]
132 pub fn len(&self) -> usize {
133 if self.dimension == 0 {
134 return 0;
135 }
136 self.values_len().div_ceil(self.dimension)
137 }
138
139 #[must_use]
142 pub fn tuple_len(&self, tuple: usize) -> Option<usize> {
143 if tuple >= self.len() {
144 return None;
145 }
146 let from = tuple.checked_mul(self.dimension)?;
147 Some((self.values_len() - from).min(self.dimension))
148 }
149
150 #[must_use]
152 pub fn is_empty(&self) -> bool {
153 self.len() == 0
154 }
155
156 #[must_use]
158 pub fn values(&self) -> &Values {
159 &self.values
160 }
161
162 #[must_use]
168 pub fn component(&self, tuple: usize, component: usize) -> Option<Component> {
169 if component >= self.tuple_len(tuple)? {
170 return None;
171 }
172 let at = tuple.checked_mul(self.dimension)?.checked_add(component)?;
173 match &self.values {
174 Values::Float(v) => v.get(at).copied().map(Component::Float),
175 Values::Int(v) => v.get(at).copied().map(Component::Int),
176 Values::Mixed(v) => v.get(at).copied(),
177 }
178 }
179}
180
181#[derive(Clone, Copy, Debug, PartialEq)]
183#[non_exhaustive]
184pub enum Component {
185 Float(f64),
187 Int(i64),
189}
190
191const _: () = crate::send_sync::<Component>();
192
193impl Component {
194 #[must_use]
197 #[allow(clippy::cast_precision_loss)] pub fn as_f64(self) -> f64 {
199 match self {
200 Self::Float(f) => f,
201 Self::Int(i) => i as f64,
202 }
203 }
204
205 #[must_use]
208 pub fn is_truthy(self) -> bool {
209 match self {
210 Self::Float(f) => f != 0.0,
211 Self::Int(i) => i != 0,
212 }
213 }
214}
215
216#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
220pub struct Gather {
221 pub component_byte_size: u32,
223 pub vertex_count: u32,
225 pub stream_offset: u32,
227 pub stream_stride: u32,
229 pub channel_offset: u32,
231 pub channel_dimension: u32,
233 pub swap: bool,
235}
236
237const _: () = crate::send_sync::<Gather>();
238
239impl Gather {
240 fn check(&self, len: usize) -> Result<u64, MeshError> {
244 let cbs = self.component_byte_size;
245 let dim = self.channel_dimension;
246 let max_access = self
248 .vertex_count
249 .wrapping_sub(1)
250 .wrapping_mul(self.stream_stride)
251 .wrapping_add(self.channel_offset)
252 .wrapping_add(self.stream_offset)
253 .wrapping_add(cbs.wrapping_mul(dim.wrapping_sub(1)))
254 .wrapping_add(cbs);
255 if u64::from(max_access) > u64::try_from(len).unwrap_or(u64::MAX) {
256 return Err(MeshError::OutOfBounds);
257 }
258 let wrapped = self.vertex_count.wrapping_mul(dim).wrapping_mul(cbs);
261 let exact = u128::from(self.vertex_count) * u128::from(dim) * u128::from(cbs);
262 if exact != u128::from(wrapped) {
263 return Err(MeshError::WrappedAccess);
264 }
265 Ok(u64::from(wrapped))
266 }
267
268 fn offset(&self, v: u32, d: u32) -> u32 {
271 self.stream_offset
272 .wrapping_add(self.channel_offset)
273 .wrapping_add(self.stream_stride.wrapping_mul(v))
274 .wrapping_add(self.component_byte_size.wrapping_mul(d))
275 }
276
277 fn each(
280 &self,
281 data: &[u8],
282 mut visit: impl FnMut(&[u8]) -> Result<(), MeshError>,
283 ) -> Result<(), MeshError> {
284 let cbs = usize::try_from(self.component_byte_size).unwrap_or(usize::MAX);
285 for v in 0..self.vertex_count {
286 for d in 0..self.channel_dimension {
287 let at = usize::try_from(self.offset(v, d)).unwrap_or(usize::MAX);
288 let src = at
289 .checked_add(cbs)
290 .and_then(|end| data.get(at..end))
291 .ok_or(MeshError::WrappedAccess)?;
292 visit(src)?;
293 }
294 }
295 Ok(())
296 }
297}
298
299#[derive(Debug)]
302pub struct ComponentBytes {
303 bytes: Vec<u8>,
304 _charge: Charge,
306}
307
308const _: () = crate::send_sync::<ComponentBytes>();
309
310impl ComponentBytes {
311 #[must_use]
313 pub fn as_slice(&self) -> &[u8] {
314 &self.bytes
315 }
316}
317
318pub fn unpack_vertexdata(
322 data: &[u8],
323 args: &Gather,
324 meter: &Arc<Meter>,
325) -> Result<ComponentBytes, MeshError> {
326 let length = args.check(data.len())?;
327 let n = usize::try_from(length).map_err(|_| MeshError::WrappedAccess)?;
328 let mut out = MeteredVec::<u8>::with_capacity(meter, n)?;
330 meter.count_decode(length)?;
331 let swap = args.swap && matches!(args.component_byte_size, 2 | 4);
332 if length == 0 {
337 let (bytes, charge) = out.into_parts();
338 return Ok(ComponentBytes {
339 bytes,
340 _charge: charge,
341 });
342 }
343 args.each(data, |src| {
344 if swap {
346 for &b in src.iter().rev() {
347 out.push(b)?;
348 }
349 } else {
350 out.extend_from_slice(src)?;
351 }
352 Ok(())
353 })?;
354 let (bytes, charge) = out.into_parts();
355 Ok(ComponentBytes {
356 bytes,
357 _charge: charge,
358 })
359}
360
361pub(crate) fn unpack_channel(
368 data: &[u8],
369 args: &Gather,
370 code: StructCode,
371 norm: Option<Norm>,
372 meter: &Arc<Meter>,
373) -> Result<VertexArray, MeshError> {
374 let length = args.check(data.len())?;
375 let dimension = usize::try_from(args.channel_dimension).unwrap_or(usize::MAX);
376 if dimension == 0 {
379 return Err(MeshError::Struct(StructError::ZeroLength));
380 }
381 let n = usize::try_from(u64::from(args.vertex_count) * u64::from(args.channel_dimension))
382 .map_err(|_| MeshError::WrappedAccess)?;
383 let little = args.swap;
387 if code.is_float() || norm.is_some() {
388 let mut out = MeteredVec::<f64>::with_capacity(meter, n)?;
389 meter.count_decode(length)?;
390 args.each(data, |src| {
391 out.push(match norm {
392 Some(rule) if !code.is_float() => rule.value(code, int(code, src, little)),
394 _ => float(code, src, little),
395 })?;
396 Ok(())
397 })?;
398 let (v, charge) = out.into_parts();
399 Ok(VertexArray::new(dimension, Values::Float(v), charge))
400 } else {
401 let mut out = MeteredVec::<i64>::with_capacity(meter, n)?;
402 meter.count_decode(length)?;
403 args.each(data, |src| {
404 out.push(int(code, src, little))?;
405 Ok(())
406 })?;
407 let (v, charge) = out.into_parts();
408 Ok(VertexArray::new(dimension, Values::Int(v), charge))
409 }
410}
411
412fn le(src: &[u8], little: bool) -> [u8; 4] {
415 let mut a = [0u8; 4];
416 if little {
417 a.iter_mut().zip(src).for_each(|(o, b)| *o = *b);
418 } else {
419 a.iter_mut()
420 .zip(src.iter().rev())
421 .for_each(|(o, b)| *o = *b);
422 }
423 a
424}
425
426fn int(code: StructCode, src: &[u8], little: bool) -> i64 {
428 let [a, b, c, d] = le(src, little);
429 match code {
430 StructCode::I8 => i64::from(i8::from_le_bytes([a])),
431 StructCode::U16 => i64::from(u16::from_le_bytes([a, b])),
432 StructCode::I16 => i64::from(i16::from_le_bytes([a, b])),
433 StructCode::U32 => i64::from(u32::from_le_bytes([a, b, c, d])),
434 StructCode::I32 => i64::from(i32::from_le_bytes([a, b, c, d])),
435 StructCode::U8 | StructCode::F16 | StructCode::F32 => i64::from(a),
437 }
438}
439
440fn float(code: StructCode, src: &[u8], little: bool) -> f64 {
442 let [a, b, c, d] = le(src, little);
443 match code {
444 StructCode::F16 => half(u16::from_le_bytes([a, b])),
445 _ => widen(u32::from_le_bytes([a, b, c, d])),
446 }
447}
448
449pub(crate) fn widen(bits: u32) -> f64 {
454 let f = f32::from_bits(bits);
455 if f.is_nan() {
456 let sign = u64::from(bits >> 31) << 63;
457 let payload = u64::from((bits & 0x007f_ffff) | 0x0040_0000);
458 f64::from_bits(sign | 0x7ff0_0000_0000_0000 | (payload << 29))
459 } else {
460 f64::from(f)
461 }
462}
463
464pub(crate) fn half(bits: u16) -> f64 {
472 let sign = u64::from(bits >> 15) << 63;
473 let exponent = u64::from((bits >> 10) & 0x1f);
474 let fraction = bits & 0x03ff;
475 let magnitude = match exponent {
476 0 => (f64::from(fraction) * 2f64.powi(-24)).to_bits(),
477 0x1f if fraction == 0 => f64::INFINITY.to_bits(),
478 0x1f => 0x7ff8_0000_0000_0000,
479 _ => ((exponent + 1023 - 15) << 52) | (u64::from(fraction) << 42),
480 };
481 f64::from_bits(sign | magnitude)
482}
483
484#[cfg(test)]
485mod tests {
486 use std::sync::Arc;
487
488 use unityrs_core::limits::{Charge, Meter};
489
490 use super::{Component, Gather, Values, VertexArray, half, unpack_vertexdata, widen};
491 use crate::error::MeshError;
492
493 fn args(vc: u32, soff: u32, stride: u32, choff: u32, dim: u32, cbs: u32) -> Gather {
494 Gather {
495 component_byte_size: cbs,
496 vertex_count: vc,
497 stream_offset: soff,
498 stream_stride: stride,
499 channel_offset: choff,
500 channel_dimension: dim,
501 swap: true,
502 }
503 }
504
505 #[test]
506 fn halves_and_floats_widen_as_the_oracle_does() {
507 assert_eq!(half(0x7c00), f64::INFINITY);
509 assert_eq!(half(0x7c01).to_bits(), 0x7ff8_0000_0000_0000);
510 assert_eq!(half(0x7e00).to_bits(), 0x7ff8_0000_0000_0000);
511 assert_eq!(half(0xfc01).to_bits(), 0xfff8_0000_0000_0000);
512 assert_eq!(half(0x3c00), 1.0);
513 assert_eq!(half(0x0001), 2f64.powi(-24));
514 assert_eq!(half(0x8000).to_bits(), (-0.0f64).to_bits());
515 assert_eq!(widen(0x7f80_0001).to_bits(), 0x7ff8_0000_2000_0000);
516 assert_eq!(widen(0xffa0_0005).to_bits(), 0xfffc_0000_a000_0000);
517 assert_eq!(widen(0x7fc0_0000).to_bits(), 0x7ff8_0000_0000_0000);
518 }
519
520 #[test]
521 fn every_half_widens_to_its_value() {
522 for bits in 0..=u16::MAX {
525 let (e, f) = (i32::from((bits >> 10) & 0x1f), f64::from(bits & 0x3ff));
526 if e == 0x1f {
527 continue;
528 }
529 let x = if e == 0 {
530 f / 1024.0 * 2f64.powi(-14)
531 } else {
532 (1.0 + f / 1024.0) * 2f64.powi(e - 15)
533 };
534 let want = if bits & 0x8000 != 0 { -x } else { x };
535 assert_eq!(half(bits).to_bits(), want.to_bits(), "{bits:#06x}");
536 }
537 }
538
539 #[test]
540 fn a_backward_stride_reads_as_unitypyboost_reads_it() {
541 let data: Vec<u8> = (0..12).collect();
543 let a = args(3, 8, 0xFFFF_FFFC, 0, 1, 4);
544 let out = unpack_vertexdata(&data, &a, &Meter::unlimited()).unwrap();
545 assert_eq!(out.as_slice(), &[11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]);
546 }
547
548 #[test]
549 fn a_wrapped_offset_past_the_data_is_refused() {
550 let data = [0u8; 16];
553 let a = args(8, 0xFFFF_FFF0, 4, 0, 1, 4);
554 let e = unpack_vertexdata(&data, &a, &Meter::unlimited()).unwrap_err();
555 assert!(matches!(e, MeshError::WrappedAccess), "{e:?}");
556 let a = args(8, 0, 4, 0, 1, 4);
557 let e = unpack_vertexdata(&data, &a, &Arc::clone(&Meter::unlimited())).unwrap_err();
558 assert!(matches!(e, MeshError::OutOfBounds), "{e:?}");
559 }
560
561 fn array(dimension: usize, values: Values) -> VertexArray {
562 VertexArray::new(dimension, values, Charge::zero(&Meter::unlimited()))
563 }
564
565 #[test]
566 fn a_component_is_a_python_float_or_int_by_the_form_that_holds_it() {
567 let floats = array(2, Values::Float(vec![0.5, -1.0, 2.0, 3.5]));
568 assert_eq!(floats.len(), 2);
569 assert_eq!(floats.component(0, 1), Some(Component::Float(-1.0)));
570 assert_eq!(floats.component(1, 0), Some(Component::Float(2.0)));
571 let ints = array(3, Values::Int(vec![1, -2, 3, i64::MAX, 0, -7]));
572 assert_eq!(ints.component(1, 0), Some(Component::Int(i64::MAX)));
573 assert_eq!(ints.component(0, 2), Some(Component::Int(3)));
574 assert_eq!(
576 Component::Int(i64::MAX).as_f64(),
577 9_223_372_036_854_775_808.0
578 );
579 assert_eq!(
580 Component::Int((1 << 53) + 1).as_f64(),
581 9_007_199_254_740_992.0
582 );
583 assert_eq!(Component::Float(-0.25).as_f64(), -0.25);
584 }
585
586 #[test]
587 fn a_component_past_the_tuples_or_its_tuple_is_none() {
588 let a = array(2, Values::Float(vec![1.0, 2.0, 3.0]));
589 assert_eq!(a.len(), 2);
592 assert_eq!(
593 (a.tuple_len(0), a.tuple_len(1), a.tuple_len(2)),
594 (Some(2), Some(1), None)
595 );
596 assert_eq!(a.component(0, 2), None);
597 assert_eq!(a.component(0, 1), Some(Component::Float(2.0)));
598 assert_eq!(a.component(1, 0), Some(Component::Float(3.0)));
599 assert_eq!(a.component(1, 1), None);
600 assert_eq!(a.component(2, 0), None);
601 assert_eq!(a.component(usize::MAX, 1), None);
602 assert_eq!(a.component(usize::MAX / 2 + 1, 0), None);
603 let empty = array(0, Values::Int(vec![1, 2]));
604 assert_eq!((empty.len(), empty.component(0, 0)), (0, None));
605 }
606
607 #[test]
608 fn truth_is_python_s() {
609 assert!(!Component::Float(0.0).is_truthy());
610 assert!(!Component::Float(-0.0).is_truthy());
611 assert!(Component::Float(f64::NAN).is_truthy());
612 assert!(Component::Float(f64::MIN_POSITIVE / 2.0).is_truthy());
613 assert!(!Component::Int(0).is_truthy());
614 assert!(Component::Int(-1).is_truthy());
615 }
616}