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 lists: bool,
69 _charge: Charge,
71}
72
73const _: () = crate::send_sync::<VertexArray>();
74
75#[derive(Debug, PartialEq)]
82#[non_exhaustive]
83pub enum Values {
84 Float(Vec<f64>),
86 Int(Vec<i64>),
88 Mixed(Vec<Component>),
92}
93
94const _: () = crate::send_sync::<Values>();
95
96impl VertexArray {
97 #[must_use]
99 pub fn from_components(dimension: usize, values: MeteredVec<Component>) -> Self {
100 let (values, charge) = values.into_parts();
101 Self::new(dimension, Values::Mixed(values), charge)
102 }
103
104 pub(crate) fn new(dimension: usize, values: Values, charge: Charge) -> Self {
107 Self {
108 dimension,
109 values,
110 lists: false,
111 _charge: charge,
112 }
113 }
114
115 pub(crate) fn into_lists(mut self) -> Self {
117 self.lists = true;
118 self
119 }
120
121 #[must_use]
127 pub fn rows_are_lists(&self) -> bool {
128 self.lists
129 }
130
131 #[must_use]
133 pub fn dimension(&self) -> usize {
134 self.dimension
135 }
136
137 fn values_len(&self) -> usize {
139 match &self.values {
140 Values::Float(v) => v.len(),
141 Values::Int(v) => v.len(),
142 Values::Mixed(v) => v.len(),
143 }
144 }
145
146 #[must_use]
150 pub fn len(&self) -> usize {
151 if self.dimension == 0 {
152 return 0;
153 }
154 self.values_len().div_ceil(self.dimension)
155 }
156
157 #[must_use]
160 pub fn tuple_len(&self, tuple: usize) -> Option<usize> {
161 if tuple >= self.len() {
162 return None;
163 }
164 let from = tuple.checked_mul(self.dimension)?;
165 Some((self.values_len() - from).min(self.dimension))
166 }
167
168 #[must_use]
170 pub fn is_empty(&self) -> bool {
171 self.len() == 0
172 }
173
174 #[must_use]
176 pub fn values(&self) -> &Values {
177 &self.values
178 }
179
180 #[must_use]
186 pub fn component(&self, tuple: usize, component: usize) -> Option<Component> {
187 if component >= self.tuple_len(tuple)? {
188 return None;
189 }
190 let at = tuple.checked_mul(self.dimension)?.checked_add(component)?;
191 match &self.values {
192 Values::Float(v) => v.get(at).copied().map(Component::Float),
193 Values::Int(v) => v.get(at).copied().map(Component::Int),
194 Values::Mixed(v) => v.get(at).copied(),
195 }
196 }
197}
198
199#[derive(Clone, Copy, Debug, PartialEq)]
201#[non_exhaustive]
202pub enum Component {
203 Float(f64),
205 Int(i64),
207}
208
209const _: () = crate::send_sync::<Component>();
210
211impl Component {
212 #[must_use]
215 #[allow(clippy::cast_precision_loss)] pub fn as_f64(self) -> f64 {
217 match self {
218 Self::Float(f) => f,
219 Self::Int(i) => i as f64,
220 }
221 }
222
223 #[must_use]
226 pub fn is_truthy(self) -> bool {
227 match self {
228 Self::Float(f) => f != 0.0,
229 Self::Int(i) => i != 0,
230 }
231 }
232}
233
234#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
238pub struct Gather {
239 pub component_byte_size: u32,
241 pub vertex_count: u32,
243 pub stream_offset: u32,
245 pub stream_stride: u32,
247 pub channel_offset: u32,
249 pub channel_dimension: u32,
251 pub swap: bool,
253}
254
255const _: () = crate::send_sync::<Gather>();
256
257impl Gather {
258 fn check(&self, len: usize) -> Result<u64, MeshError> {
262 let cbs = self.component_byte_size;
263 let dim = self.channel_dimension;
264 let max_access = self
266 .vertex_count
267 .wrapping_sub(1)
268 .wrapping_mul(self.stream_stride)
269 .wrapping_add(self.channel_offset)
270 .wrapping_add(self.stream_offset)
271 .wrapping_add(cbs.wrapping_mul(dim.wrapping_sub(1)))
272 .wrapping_add(cbs);
273 if u64::from(max_access) > u64::try_from(len).unwrap_or(u64::MAX) {
274 return Err(MeshError::OutOfBounds);
275 }
276 let wrapped = self.vertex_count.wrapping_mul(dim).wrapping_mul(cbs);
279 let exact = u128::from(self.vertex_count) * u128::from(dim) * u128::from(cbs);
280 if exact != u128::from(wrapped) {
281 return Err(MeshError::WrappedAccess);
282 }
283 Ok(u64::from(wrapped))
284 }
285
286 fn offset(&self, v: u32, d: u32) -> u32 {
289 self.stream_offset
290 .wrapping_add(self.channel_offset)
291 .wrapping_add(self.stream_stride.wrapping_mul(v))
292 .wrapping_add(self.component_byte_size.wrapping_mul(d))
293 }
294
295 fn each(
298 &self,
299 data: &[u8],
300 mut visit: impl FnMut(&[u8]) -> Result<(), MeshError>,
301 ) -> Result<(), MeshError> {
302 let cbs = usize::try_from(self.component_byte_size).unwrap_or(usize::MAX);
303 for v in 0..self.vertex_count {
304 for d in 0..self.channel_dimension {
305 let at = usize::try_from(self.offset(v, d)).unwrap_or(usize::MAX);
306 let src = at
307 .checked_add(cbs)
308 .and_then(|end| data.get(at..end))
309 .ok_or(MeshError::WrappedAccess)?;
310 visit(src)?;
311 }
312 }
313 Ok(())
314 }
315}
316
317#[derive(Debug)]
320pub struct ComponentBytes {
321 bytes: Vec<u8>,
322 _charge: Charge,
324}
325
326const _: () = crate::send_sync::<ComponentBytes>();
327
328impl ComponentBytes {
329 #[must_use]
331 pub fn as_slice(&self) -> &[u8] {
332 &self.bytes
333 }
334}
335
336pub fn unpack_vertexdata(
340 data: &[u8],
341 args: &Gather,
342 meter: &Arc<Meter>,
343) -> Result<ComponentBytes, MeshError> {
344 let length = args.check(data.len())?;
345 let n = usize::try_from(length).map_err(|_| MeshError::WrappedAccess)?;
346 let mut out = MeteredVec::<u8>::with_capacity(meter, n)?;
348 meter.count_decode(length)?;
349 let swap = args.swap && matches!(args.component_byte_size, 2 | 4);
350 if length == 0 {
355 let (bytes, charge) = out.into_parts();
356 return Ok(ComponentBytes {
357 bytes,
358 _charge: charge,
359 });
360 }
361 args.each(data, |src| {
362 if swap {
364 for &b in src.iter().rev() {
365 out.push(b)?;
366 }
367 } else {
368 out.extend_from_slice(src)?;
369 }
370 Ok(())
371 })?;
372 let (bytes, charge) = out.into_parts();
373 Ok(ComponentBytes {
374 bytes,
375 _charge: charge,
376 })
377}
378
379pub(crate) fn unpack_channel(
386 data: &[u8],
387 args: &Gather,
388 code: StructCode,
389 norm: Option<Norm>,
390 meter: &Arc<Meter>,
391) -> Result<VertexArray, MeshError> {
392 let length = args.check(data.len())?;
393 let dimension = usize::try_from(args.channel_dimension).unwrap_or(usize::MAX);
394 if dimension == 0 {
397 return Err(MeshError::Struct(StructError::ZeroLength));
398 }
399 let n = usize::try_from(u64::from(args.vertex_count) * u64::from(args.channel_dimension))
400 .map_err(|_| MeshError::WrappedAccess)?;
401 let little = args.swap;
405 if code.is_float() || norm.is_some() {
406 let mut out = MeteredVec::<f64>::with_capacity(meter, n)?;
407 meter.count_decode(length)?;
408 args.each(data, |src| {
409 out.push(match norm {
410 Some(rule) if !code.is_float() => rule.value(code, int(code, src, little)),
412 _ => float(code, src, little),
413 })?;
414 Ok(())
415 })?;
416 let (v, charge) = out.into_parts();
417 Ok(VertexArray::new(dimension, Values::Float(v), charge))
418 } else {
419 let mut out = MeteredVec::<i64>::with_capacity(meter, n)?;
420 meter.count_decode(length)?;
421 args.each(data, |src| {
422 out.push(int(code, src, little))?;
423 Ok(())
424 })?;
425 let (v, charge) = out.into_parts();
426 Ok(VertexArray::new(dimension, Values::Int(v), charge))
427 }
428}
429
430fn le(src: &[u8], little: bool) -> [u8; 4] {
433 let mut a = [0u8; 4];
434 if little {
435 a.iter_mut().zip(src).for_each(|(o, b)| *o = *b);
436 } else {
437 a.iter_mut()
438 .zip(src.iter().rev())
439 .for_each(|(o, b)| *o = *b);
440 }
441 a
442}
443
444fn int(code: StructCode, src: &[u8], little: bool) -> i64 {
446 let [a, b, c, d] = le(src, little);
447 match code {
448 StructCode::I8 => i64::from(i8::from_le_bytes([a])),
449 StructCode::U16 => i64::from(u16::from_le_bytes([a, b])),
450 StructCode::I16 => i64::from(i16::from_le_bytes([a, b])),
451 StructCode::U32 => i64::from(u32::from_le_bytes([a, b, c, d])),
452 StructCode::I32 => i64::from(i32::from_le_bytes([a, b, c, d])),
453 StructCode::U8 | StructCode::F16 | StructCode::F32 => i64::from(a),
455 }
456}
457
458fn float(code: StructCode, src: &[u8], little: bool) -> f64 {
460 let [a, b, c, d] = le(src, little);
461 match code {
462 StructCode::F16 => half(u16::from_le_bytes([a, b])),
463 _ => widen(u32::from_le_bytes([a, b, c, d])),
464 }
465}
466
467pub(crate) fn widen(bits: u32) -> f64 {
472 let f = f32::from_bits(bits);
473 if f.is_nan() {
474 let sign = u64::from(bits >> 31) << 63;
475 let payload = u64::from((bits & 0x007f_ffff) | 0x0040_0000);
476 f64::from_bits(sign | 0x7ff0_0000_0000_0000 | (payload << 29))
477 } else {
478 f64::from(f)
479 }
480}
481
482pub(crate) fn half(bits: u16) -> f64 {
490 let sign = u64::from(bits >> 15) << 63;
491 let exponent = u64::from((bits >> 10) & 0x1f);
492 let fraction = bits & 0x03ff;
493 let magnitude = match exponent {
494 0 => (f64::from(fraction) * 2f64.powi(-24)).to_bits(),
495 0x1f if fraction == 0 => f64::INFINITY.to_bits(),
496 0x1f => 0x7ff8_0000_0000_0000,
497 _ => ((exponent + 1023 - 15) << 52) | (u64::from(fraction) << 42),
498 };
499 f64::from_bits(sign | magnitude)
500}
501
502#[cfg(test)]
503mod tests {
504 use std::sync::Arc;
505
506 use unityrs_core::limits::{Charge, Meter};
507
508 use super::{Component, Gather, Values, VertexArray, half, unpack_vertexdata, widen};
509 use crate::error::MeshError;
510
511 fn args(vc: u32, soff: u32, stride: u32, choff: u32, dim: u32, cbs: u32) -> Gather {
512 Gather {
513 component_byte_size: cbs,
514 vertex_count: vc,
515 stream_offset: soff,
516 stream_stride: stride,
517 channel_offset: choff,
518 channel_dimension: dim,
519 swap: true,
520 }
521 }
522
523 #[test]
524 fn halves_and_floats_widen_as_the_oracle_does() {
525 assert_eq!(half(0x7c00), f64::INFINITY);
527 assert_eq!(half(0x7c01).to_bits(), 0x7ff8_0000_0000_0000);
528 assert_eq!(half(0x7e00).to_bits(), 0x7ff8_0000_0000_0000);
529 assert_eq!(half(0xfc01).to_bits(), 0xfff8_0000_0000_0000);
530 assert_eq!(half(0x3c00), 1.0);
531 assert_eq!(half(0x0001), 2f64.powi(-24));
532 assert_eq!(half(0x8000).to_bits(), (-0.0f64).to_bits());
533 assert_eq!(widen(0x7f80_0001).to_bits(), 0x7ff8_0000_2000_0000);
534 assert_eq!(widen(0xffa0_0005).to_bits(), 0xfffc_0000_a000_0000);
535 assert_eq!(widen(0x7fc0_0000).to_bits(), 0x7ff8_0000_0000_0000);
536 }
537
538 #[test]
539 fn every_half_widens_to_its_value() {
540 for bits in 0..=u16::MAX {
543 let (e, f) = (i32::from((bits >> 10) & 0x1f), f64::from(bits & 0x3ff));
544 if e == 0x1f {
545 continue;
546 }
547 let x = if e == 0 {
548 f / 1024.0 * 2f64.powi(-14)
549 } else {
550 (1.0 + f / 1024.0) * 2f64.powi(e - 15)
551 };
552 let want = if bits & 0x8000 != 0 { -x } else { x };
553 assert_eq!(half(bits).to_bits(), want.to_bits(), "{bits:#06x}");
554 }
555 }
556
557 #[test]
558 fn a_backward_stride_reads_as_unitypyboost_reads_it() {
559 let data: Vec<u8> = (0..12).collect();
561 let a = args(3, 8, 0xFFFF_FFFC, 0, 1, 4);
562 let out = unpack_vertexdata(&data, &a, &Meter::unlimited()).unwrap();
563 assert_eq!(out.as_slice(), &[11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]);
564 }
565
566 #[test]
567 fn a_wrapped_offset_past_the_data_is_refused() {
568 let data = [0u8; 16];
571 let a = args(8, 0xFFFF_FFF0, 4, 0, 1, 4);
572 let e = unpack_vertexdata(&data, &a, &Meter::unlimited()).unwrap_err();
573 assert!(matches!(e, MeshError::WrappedAccess), "{e:?}");
574 let a = args(8, 0, 4, 0, 1, 4);
575 let e = unpack_vertexdata(&data, &a, &Arc::clone(&Meter::unlimited())).unwrap_err();
576 assert!(matches!(e, MeshError::OutOfBounds), "{e:?}");
577 }
578
579 fn array(dimension: usize, values: Values) -> VertexArray {
580 VertexArray::new(dimension, values, Charge::zero(&Meter::unlimited()))
581 }
582
583 #[test]
584 fn a_component_is_a_python_float_or_int_by_the_form_that_holds_it() {
585 let floats = array(2, Values::Float(vec![0.5, -1.0, 2.0, 3.5]));
586 assert_eq!(floats.len(), 2);
587 assert_eq!(floats.component(0, 1), Some(Component::Float(-1.0)));
588 assert_eq!(floats.component(1, 0), Some(Component::Float(2.0)));
589 let ints = array(3, Values::Int(vec![1, -2, 3, i64::MAX, 0, -7]));
590 assert_eq!(ints.component(1, 0), Some(Component::Int(i64::MAX)));
591 assert_eq!(ints.component(0, 2), Some(Component::Int(3)));
592 assert_eq!(
594 Component::Int(i64::MAX).as_f64(),
595 9_223_372_036_854_775_808.0
596 );
597 assert_eq!(
598 Component::Int((1 << 53) + 1).as_f64(),
599 9_007_199_254_740_992.0
600 );
601 assert_eq!(Component::Float(-0.25).as_f64(), -0.25);
602 }
603
604 #[test]
605 fn a_component_past_the_tuples_or_its_tuple_is_none() {
606 let a = array(2, Values::Float(vec![1.0, 2.0, 3.0]));
607 assert_eq!(a.len(), 2);
610 assert_eq!(
611 (a.tuple_len(0), a.tuple_len(1), a.tuple_len(2)),
612 (Some(2), Some(1), None)
613 );
614 assert_eq!(a.component(0, 2), None);
615 assert_eq!(a.component(0, 1), Some(Component::Float(2.0)));
616 assert_eq!(a.component(1, 0), Some(Component::Float(3.0)));
617 assert_eq!(a.component(1, 1), None);
618 assert_eq!(a.component(2, 0), None);
619 assert_eq!(a.component(usize::MAX, 1), None);
620 assert_eq!(a.component(usize::MAX / 2 + 1, 0), None);
621 let empty = array(0, Values::Int(vec![1, 2]));
622 assert_eq!((empty.len(), empty.component(0, 0)), (0, None));
623 }
624
625 #[test]
626 fn truth_is_python_s() {
627 assert!(!Component::Float(0.0).is_truthy());
628 assert!(!Component::Float(-0.0).is_truthy());
629 assert!(Component::Float(f64::NAN).is_truthy());
630 assert!(Component::Float(f64::MIN_POSITIVE / 2.0).is_truthy());
631 assert!(!Component::Int(0).is_truthy());
632 assert!(Component::Int(-1).is_truthy());
633 }
634}