1use base64::Engine as _;
54use hpr_core::frames::LaunchFrame;
55use hpr_core::geodesy::Geodetic;
56use schemars::JsonSchema;
57use serde::{Deserialize, Serialize};
58use serde_json::{Value, json};
59
60use crate::filter::median;
61use crate::log::{Channel, FlightLog, Quantity};
62use crate::readings::{Reading, Readings};
63use crate::timeline;
64
65pub const REACH_M: f64 = 200_000.0;
68pub const FASTEST_M_S: f64 = 1_500.0;
73pub const FIX_SCATTER_M: f64 = 200.0;
75pub const HEIGHT_SCATTER_M: f64 = 50.0;
77pub const PAD_FIXES: usize = 20;
79pub const CZML_EPOCH: &str = "2000-01-01T12:00:00Z";
81pub const UNKNOWN_PAD: (f64, f64, f64) = (0.0, 0.0, 0.0);
83pub const PAD_HEIGHT_LIMIT_M: f64 = 20_000.0;
86pub const BELOW_PAD_M: f64 = 500.0;
90pub const CLOCK_LIMIT_S: f64 = 1e10;
93pub const LONGEST_LOG_S: f64 = 1e7;
95pub const OPENING_ROWS: usize = 9;
97const MARKER_RADIUS_M: f64 = 5.0;
99
100#[derive(Debug, Clone, Copy)]
102pub struct Input<'a> {
103 pub name: &'a str,
105 pub log: &'a FlightLog,
107 pub read: &'a Readings,
109}
110
111#[derive(Debug, Clone, Copy, PartialEq)]
113pub struct StatedPad {
114 pub latitude_deg: f64,
116 pub longitude_deg: f64,
118 pub height_m: Option<f64>,
120}
121
122#[derive(Debug, Clone, PartialEq, thiserror::Error)]
124#[non_exhaustive]
125pub enum GhostError {
126 #[error("no logs to lay out")]
128 NoLogs,
129 #[error("{name}: the log holds no height and no usable GNSS track")]
131 NoTrack {
132 name: String,
134 },
135 #[error("{name}: the log has no liftoff to share a timeline by ({reason})")]
137 NotOnTimeline {
138 name: String,
140 reason: String,
142 },
143 #[error("the pad isn't a place: {what}")]
145 BadPad {
146 what: String,
148 },
149 #[error("{name}: the track can't be drawn: {what}")]
151 BadTrack {
152 name: String,
154 what: String,
156 },
157}
158
159#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
161#[serde(rename_all = "snake_case")]
162#[non_exhaustive]
163pub enum PadFrom {
164 Stated,
166 FixesBeforeLiftoff,
168 FirstFix,
171 Unknown,
173}
174
175#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, JsonSchema)]
177pub struct Pad {
178 pub latitude_deg: Option<f64>,
180 pub longitude_deg: Option<f64>,
182 pub height_m: Option<f64>,
186 pub height_stated: bool,
188 pub from: PadFrom,
190 pub first_fix_after_liftoff_s: Option<f64>,
193}
194
195#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
197#[serde(rename_all = "snake_case")]
198#[non_exhaustive]
199pub enum UpFrom {
200 LogAltitude,
202 AltitudeLessPad,
205 GnssAltitude,
207 Unknown,
209}
210
211#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
213pub struct FixCounts {
214 pub given: usize,
216 pub kept: usize,
218 pub not_a_place: usize,
220 pub clock_back: usize,
222 pub out_of_reach: usize,
224 pub too_fast: usize,
226}
227
228#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
230pub struct Track {
231 pub name: String,
233 pub logger: String,
235 pub synced: bool,
237 pub liftoff_s: Option<f64>,
239 pub liftoff_bound_s: Option<f64>,
242 pub up_from: UpFrom,
244 pub time_s: Vec<f64>,
246 pub east_m: Vec<Option<f64>>,
248 pub north_m: Vec<Option<f64>>,
250 pub up_m: Vec<Option<f64>>,
253 pub fixes: FixCounts,
255 pub widest_fix_gap_s: Option<f64>,
257 pub moments_left_out: usize,
260 pub heights_too_fast: usize,
262 pub heights_below_pad: usize,
264}
265
266#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
268pub struct Ghost {
269 pub format: String,
271 pub version: u32,
273 pub frame: String,
275 pub pad: Pad,
277 pub tracks: Vec<Track>,
279}
280
281#[derive(Debug, Default)]
283struct Fixes {
284 time_s: Vec<f64>,
285 latitude_deg: Vec<f64>,
286 longitude_deg: Vec<f64>,
287 height_m: Vec<Option<f64>>,
288 counts: FixCounts,
289}
290
291fn channel(log: &FlightLog, quantity: Quantity) -> Option<&Channel> {
293 log.channels_of(quantity).next()
294}
295
296fn frame_at(latitude_deg: f64, longitude_deg: f64, height_m: f64) -> Option<LaunchFrame> {
298 let origin = Geodetic::from_degrees(latitude_deg, longitude_deg, height_m).ok()?;
299 LaunchFrame::wgs84(origin).ok()
300}
301
302fn east_north(frame: &LaunchFrame, latitude_deg: f64, longitude_deg: f64) -> Option<(f64, f64)> {
304 let point =
305 Geodetic::from_degrees(latitude_deg, longitude_deg, frame.origin().height_m).ok()?;
306 let enu = frame.enu_from_geodetic(point);
307 Some((enu.x, enu.y))
308}
309
310fn wrapped_deg(longitude_deg: f64) -> f64 {
313 if (-180.0..180.0).contains(&longitude_deg) {
314 longitude_deg
315 } else {
316 (longitude_deg + 180.0).rem_euclid(360.0) - 180.0
317 }
318}
319
320fn median_longitude(longitudes_deg: &[f64]) -> Option<f64> {
330 let middle_and_spread = |mut values: Vec<f64>| -> Option<(f64, f64)> {
331 let middle = median(&mut values)?;
332 let mut off: Vec<f64> = values.iter().map(|v| (v - middle).abs()).collect();
333 Some((middle, median(&mut off)?))
334 };
335 let (plain, spread) = middle_and_spread(longitudes_deg.to_vec())?;
336 if spread <= 90.0 {
337 return Some(plain);
338 }
339 let turned: Vec<f64> = longitudes_deg
340 .iter()
341 .map(|&lon| if lon < 0.0 { lon + 360.0 } else { lon })
342 .collect();
343 middle_and_spread(turned).map(|(middle, _)| wrapped_deg(middle))
344}
345
346fn a_place(latitude_deg: f64, longitude_deg: f64) -> bool {
348 latitude_deg.abs() <= 90.0
349 && longitude_deg.abs() <= 180.0
350 && !(latitude_deg.abs() < 0.01 && longitude_deg.abs() < 0.01)
351}
352
353fn opening_outliers(samples: &[(f64, f64)], scatter_m: f64) -> usize {
356 let mut opening = samples[..samples.len().min(OPENING_ROWS)].to_vec();
357 opening.sort_by(|a, b| a.1.total_cmp(&b.1));
358 let Some(&(middle_s, middle)) = opening.get(opening.len() / 2) else {
359 return 0;
360 };
361 samples
362 .iter()
363 .position(|(time, value)| {
364 (value - middle).abs() <= FASTEST_M_S * (time - middle_s).abs() + scatter_m
365 })
366 .unwrap_or(0)
367}
368
369fn clock_test(times: &[f64]) -> impl Fn(f64) -> bool + use<> {
372 let mut opening: Vec<f64> = times
373 .iter()
374 .copied()
375 .filter(|time| time.abs() <= CLOCK_LIMIT_S)
376 .take(OPENING_ROWS)
377 .collect();
378 let middle = median(&mut opening).unwrap_or(0.0);
379 move |time: f64| time.abs() <= CLOCK_LIMIT_S && (time - middle).abs() <= LONGEST_LOG_S
380}
381
382fn screened_fixes(log: &FlightLog) -> Fixes {
384 let mut out = Fixes::default();
385 let (Some(latitude), Some(longitude)) = (
386 channel(log, Quantity::Latitude),
387 channel(log, Quantity::Longitude),
388 ) else {
389 return out;
390 };
391 let rows = latitude.values.len().min(longitude.values.len());
392 let height = channel(log, Quantity::GnssAltitude).filter(|c| c.values.len() == rows);
393 out.counts.given = rows;
394 let in_clock = clock_test(&latitude.time_s);
395 let mut places = Vec::new();
396 for row in 0..rows {
397 let (lat, lon, time) = (
398 latitude.values[row],
399 longitude.values[row],
400 latitude.time_s.get(row).copied().unwrap_or(f64::NAN),
401 );
402 if in_clock(time) && a_place(lat, lon) {
403 places.push((row, time, lat, lon));
404 } else {
405 out.counts.not_a_place += 1;
406 }
407 }
408 let latitudes: Vec<f64> = places.iter().map(|p| p.2).collect();
409 let longitudes: Vec<f64> = places.iter().map(|p| p.3).collect();
410 let (Some(mid_lat), Some(mid_lon)) = (
412 median(&mut latitudes.clone()),
413 median_longitude(&longitudes),
414 ) else {
415 return out;
416 };
417 let Some(frame) = frame_at(mid_lat, mid_lon, 0.0) else {
418 out.counts.not_a_place += places.len();
419 return out;
420 };
421 let mut within = Vec::with_capacity(places.len());
422 for (row, time, lat, lon) in places {
423 let Some((east, north)) = east_north(&frame, lat, lon) else {
424 out.counts.not_a_place += 1;
425 continue;
426 };
427 if east.hypot(north) > REACH_M {
428 out.counts.out_of_reach += 1;
429 continue;
430 }
431 within.push((row, time, lat, lon, east, north));
432 }
433 let easts: Vec<(f64, f64)> = within.iter().map(|fix| (fix.1, fix.4)).collect();
434 let norths: Vec<(f64, f64)> = within.iter().map(|fix| (fix.1, fix.5)).collect();
435 let opening =
436 opening_outliers(&easts, FIX_SCATTER_M).max(opening_outliers(&norths, FIX_SCATTER_M));
437 out.counts.too_fast += opening;
438 let mut last: Option<(f64, f64, f64)> = None;
439 for &(row, time, lat, lon, east, north) in within.iter().skip(opening) {
440 if let Some((t, e, n)) = last {
441 if time <= t {
442 out.counts.clock_back += 1;
443 continue;
444 }
445 if (east - e).hypot(north - n) > FASTEST_M_S * (time - t) + FIX_SCATTER_M {
446 out.counts.too_fast += 1;
447 continue;
448 }
449 }
450 last = Some((time, east, north));
451 out.time_s.push(time);
452 out.latitude_deg.push(lat);
453 out.longitude_deg.push(lon);
454 out.height_m.push(
455 height
456 .map(|c| c.values[row])
457 .filter(|h| h.is_finite() && *h != 0.0),
458 );
459 out.counts.kept += 1;
460 }
461 out
462}
463
464fn liftoff_of(read: &Readings) -> Option<(f64, f64)> {
466 match timeline::place(read) {
467 Reading::Read(placed) => Some((placed.zero_s, placed.bound_s)),
468 Reading::Withheld(_) => None,
469 }
470}
471
472fn pad_of(
474 stated: Option<StatedPad>,
475 logs: &[(Option<(f64, f64)>, Fixes)],
476) -> Result<(Pad, Option<f64>), GhostError> {
477 let before = logs.iter().find_map(|(liftoff, fixes)| {
479 let (zero_s, _) = (*liftoff)?;
480 let end = fixes.time_s.iter().take_while(|t| **t < zero_s).count();
481 (end > 0).then_some((fixes, end.saturating_sub(PAD_FIXES)..end))
482 });
483 let from_fixes = before.as_ref().map(|(fixes, range)| {
484 let mut lat = fixes.latitude_deg[range.clone()].to_vec();
485 let lon = &fixes.longitude_deg[range.clone()];
486 let mut height: Vec<f64> = fixes.height_m[range.clone()]
487 .iter()
488 .flatten()
489 .copied()
490 .collect();
491 (median(&mut lat), median_longitude(lon), median(&mut height))
492 });
493 let first = logs
494 .iter()
495 .find(|(_, fixes)| !fixes.time_s.is_empty())
496 .map(|(liftoff, fixes)| {
497 let late = liftoff
498 .map(|(zero_s, _)| fixes.time_s[0] - zero_s)
499 .filter(|late| *late >= 0.0);
500 (fixes, late)
501 });
502 let height_of_fixes = from_fixes
505 .and_then(|(_, _, height)| height)
506 .or_else(|| match first {
507 Some((fixes, None)) if before.is_none() => fixes.height_m[0],
508 _ => None,
509 });
510 if let Some(pad) = stated {
511 if !(pad.latitude_deg.abs() <= 90.0 && pad.longitude_deg.abs() <= 180.0) {
512 return Err(GhostError::BadPad {
513 what: format!(
514 "latitude {} and longitude {} are out of range",
515 pad.latitude_deg, pad.longitude_deg
516 ),
517 });
518 }
519 if pad
520 .height_m
521 .is_some_and(|h| h.is_nan() || h.abs() > PAD_HEIGHT_LIMIT_M)
522 {
523 return Err(GhostError::BadPad {
524 what: format!("its height is past {PAD_HEIGHT_LIMIT_M} m, or not a number"),
525 });
526 }
527 let height_m = pad.height_m.or(height_of_fixes);
528 return Ok((
529 Pad {
530 latitude_deg: Some(pad.latitude_deg),
531 longitude_deg: Some(pad.longitude_deg),
532 height_m,
533 height_stated: pad.height_m.is_some(),
534 from: PadFrom::Stated,
535 first_fix_after_liftoff_s: None,
536 },
537 height_of_fixes.or(height_m),
540 ));
541 }
542 if let Some((Some(lat), Some(lon), _)) = from_fixes {
543 return Ok((
544 Pad {
545 latitude_deg: Some(lat),
546 longitude_deg: Some(lon),
547 height_m: height_of_fixes,
548 height_stated: false,
549 from: PadFrom::FixesBeforeLiftoff,
550 first_fix_after_liftoff_s: None,
551 },
552 height_of_fixes,
553 ));
554 }
555 if let Some((fixes, late)) = first {
556 return Ok((
557 Pad {
558 latitude_deg: Some(fixes.latitude_deg[0]),
559 longitude_deg: Some(fixes.longitude_deg[0]),
560 height_m: height_of_fixes,
561 height_stated: false,
562 from: PadFrom::FirstFix,
563 first_fix_after_liftoff_s: late,
564 },
565 height_of_fixes,
566 ));
567 }
568 Ok((
569 Pad {
570 latitude_deg: None,
571 longitude_deg: None,
572 height_m: None,
573 height_stated: false,
574 from: PadFrom::Unknown,
575 first_fix_after_liftoff_s: None,
576 },
577 None,
578 ))
579}
580
581struct Heights {
583 from: UpFrom,
584 time_s: Vec<f64>,
585 up_m: Vec<Option<f64>>,
586}
587
588fn column_pad(column: &Channel, liftoff: Option<(f64, f64)>) -> Option<f64> {
591 let usable = || {
592 column
593 .time_s
594 .iter()
595 .zip(&column.values)
596 .filter(|(time, value)| time.is_finite() && value.is_finite())
597 };
598 let before: Vec<f64> = liftoff.map_or_else(Vec::new, |(zero_s, _)| {
599 usable()
600 .filter(|(time, _)| **time < zero_s)
601 .map(|(_, value)| *value)
602 .collect()
603 });
604 let mut values = if before.is_empty() {
605 usable().take(PAD_FIXES).map(|(_, value)| *value).collect()
606 } else {
607 before[before.len().saturating_sub(PAD_FIXES)..].to_vec()
608 };
609 median(&mut values)
610}
611
612fn heights_of(
615 log: &FlightLog,
616 fixes: &Fixes,
617 liftoff: Option<(f64, f64)>,
618 gnss_zero_m: Option<f64>,
619) -> Option<Heights> {
620 let above_ground = channel(log, Quantity::AltitudeAboveGround);
623 let other_zero = channel(log, Quantity::Altitude).or(channel(log, Quantity::AltitudeMsl));
624 if let (None, Some(column)) = (above_ground, other_zero)
625 && let Some(pad) = column_pad(column, liftoff)
626 {
627 return Some(Heights {
628 from: UpFrom::AltitudeLessPad,
629 time_s: column.time_s.clone(),
630 up_m: column.values.iter().map(|h| Some(*h - pad)).collect(),
631 });
632 }
633 if !log.altitude_m.is_empty() && log.altitude_m.len() == log.time_s.len() {
634 return Some(Heights {
635 from: UpFrom::LogAltitude,
636 time_s: log.time_s.clone(),
637 up_m: log.altitude_m.iter().map(|h| Some(*h)).collect(),
638 });
639 }
640 if let Some(column) = above_ground {
641 return Some(Heights {
642 from: UpFrom::LogAltitude,
643 time_s: column.time_s.clone(),
644 up_m: column.values.iter().map(|h| Some(*h)).collect(),
645 });
646 }
647 if fixes.time_s.is_empty() {
648 return None;
649 }
650 let zero = gnss_zero_m.filter(|_| fixes.height_m.iter().any(Option::is_some));
651 Some(Heights {
652 from: if zero.is_some() {
653 UpFrom::GnssAltitude
654 } else {
655 UpFrom::Unknown
656 },
657 time_s: fixes.time_s.clone(),
658 up_m: fixes
659 .height_m
660 .iter()
661 .map(|h| zero.and_then(|zero| h.map(|h| h - zero)))
662 .collect(),
663 })
664}
665
666fn join(times: &[f64], values: &[f64], at: f64, cursor: &mut usize) -> Option<f64> {
669 let (&first, &last) = (times.first()?, times.last()?);
670 if at < first || at > last {
671 return None;
672 }
673 while *cursor + 1 < times.len() && times[*cursor + 1] < at {
674 *cursor += 1;
675 }
676 let (a, b) = (*cursor, (*cursor + 1).min(times.len() - 1));
677 if times[b] <= times[a] {
678 return Some(values[a]);
679 }
680 let weight = ((at - times[a]) / (times[b] - times[a])).clamp(0.0, 1.0);
681 Some(values[a] + weight * (values[b] - values[a]))
682}
683
684fn track_of(
686 input: Input<'_>,
687 liftoff: Option<(f64, f64)>,
688 fixes: &Fixes,
689 pad: &Pad,
690 gnss_zero_m: Option<f64>,
691) -> Result<Track, GhostError> {
692 let heights =
693 heights_of(input.log, fixes, liftoff, gnss_zero_m).ok_or_else(|| GhostError::NoTrack {
694 name: input.name.to_owned(),
695 })?;
696 let frame = match (pad.latitude_deg, pad.longitude_deg) {
697 (Some(lat), Some(lon)) => frame_at(lat, lon, 0.0),
698 _ => None,
699 };
700 let (fix_east, fix_north): (Vec<f64>, Vec<f64>) = match &frame {
701 Some(frame) => fixes
702 .latitude_deg
703 .iter()
704 .zip(&fixes.longitude_deg)
705 .map(|(lat, lon)| east_north(frame, *lat, *lon).unwrap_or((f64::NAN, f64::NAN)))
706 .unzip(),
707 None => Default::default(),
708 };
709 let zero_s = liftoff.map_or(0.0, |(zero_s, _)| zero_s);
710 let mut track = Track {
711 name: input.name.to_owned(),
712 logger: input.log.logger.clone(),
713 synced: liftoff.is_some(),
714 liftoff_s: liftoff.map(|(zero_s, _)| zero_s),
715 liftoff_bound_s: liftoff.map(|(_, bound_s)| bound_s),
716 up_from: heights.from,
717 time_s: Vec::with_capacity(heights.time_s.len()),
718 east_m: Vec::with_capacity(heights.time_s.len()),
719 north_m: Vec::with_capacity(heights.time_s.len()),
720 up_m: Vec::with_capacity(heights.time_s.len()),
721 fixes: fixes.counts,
722 widest_fix_gap_s: fixes
723 .time_s
724 .windows(2)
725 .map(|pair| pair[1] - pair[0])
726 .reduce(f64::max),
727 moments_left_out: 0,
728 heights_too_fast: 0,
729 heights_below_pad: 0,
730 };
731 let in_clock = clock_test(&heights.time_s);
732 let above_floor = |height: f64| height >= -BELOW_PAD_M;
733 let candidates: Vec<(usize, (f64, f64))> = heights
735 .time_s
736 .iter()
737 .zip(&heights.up_m)
738 .enumerate()
739 .filter_map(|(row, (&time, &up))| {
740 let height = up.filter(|h| h.is_finite() && above_floor(*h))?;
741 in_clock(time).then_some((row, (time, height)))
742 })
743 .collect();
744 let samples: Vec<(f64, f64)> = candidates.iter().map(|(_, sample)| *sample).collect();
745 let first_row = candidates
746 .get(opening_outliers(&samples, HEIGHT_SCATTER_M))
747 .map_or(0, |(row, _)| *row);
748 let has_heights = heights.from != UpFrom::Unknown;
749 let (mut east_cursor, mut north_cursor) = (0, 0);
750 let mut last = f64::NEG_INFINITY;
751 let mut last_up: Option<(f64, f64)> = None;
752 for (row, (&time, &up)) in heights.time_s.iter().zip(&heights.up_m).enumerate() {
753 if !in_clock(time)
754 || time <= last
755 || up.is_some_and(|h| !h.is_finite())
756 || (has_heights && up.is_none())
757 {
758 track.moments_left_out += 1;
759 continue;
760 }
761 if up.is_some_and(|height| !above_floor(height)) {
762 track.heights_below_pad += 1;
763 continue;
764 }
765 if row < first_row {
766 track.heights_too_fast += 1;
767 continue;
768 }
769 if let (Some(height), Some((t, held))) = (up, last_up)
770 && (height - held).abs() > FASTEST_M_S * (time - t) + HEIGHT_SCATTER_M
771 {
772 track.heights_too_fast += 1;
773 continue;
774 }
775 last = time;
776 if let Some(height) = up {
777 last_up = Some((time, height));
778 }
779 track.time_s.push(time - zero_s);
780 track
781 .east_m
782 .push(join(&fixes.time_s, &fix_east, time, &mut east_cursor));
783 track
784 .north_m
785 .push(join(&fixes.time_s, &fix_north, time, &mut north_cursor));
786 track.up_m.push(up);
787 }
788 if track.time_s.is_empty() {
789 return Err(GhostError::NoTrack {
790 name: input.name.to_owned(),
791 });
792 }
793 Ok(track)
794}
795
796pub fn build(logs: &[Input<'_>], pad: Option<StatedPad>) -> Result<Ghost, GhostError> {
798 if logs.is_empty() {
799 return Err(GhostError::NoLogs);
800 }
801 let mut placed = Vec::with_capacity(logs.len());
802 for input in logs {
803 let liftoff = liftoff_of(input.read);
804 if liftoff.is_none()
805 && logs.len() > 1
806 && let Reading::Withheld(withheld) = &input.read.liftoff
807 {
808 return Err(GhostError::NotOnTimeline {
809 name: input.name.to_owned(),
810 reason: withheld.detail.clone(),
811 });
812 }
813 placed.push((liftoff, screened_fixes(input.log)));
814 }
815 let (pad, gnss_zero_m) = pad_of(pad, &placed)?;
816 let tracks = logs
817 .iter()
818 .zip(&placed)
819 .map(|(input, (liftoff, fixes))| track_of(*input, *liftoff, fixes, &pad, gnss_zero_m))
820 .collect::<Result<Vec<Track>, GhostError>>()?;
821 Ok(Ghost {
822 format: "hpr-ghost".to_owned(),
823 version: 1,
824 frame: "east, north and up from the pad, m, on WGS 84; time from liftoff, s".to_owned(),
825 pad,
826 tracks,
827 })
828}
829
830fn drawn(track: &Track) -> Vec<[f64; 4]> {
832 let nearest = |values: &[Option<f64>]| -> Vec<f64> {
833 let mut filled: Vec<f64> = Vec::with_capacity(values.len());
834 let mut held = values.iter().flatten().next().copied().unwrap_or(0.0);
835 for value in values {
836 held = value.unwrap_or(held);
837 filled.push(held);
838 }
839 filled
840 };
841 let (east, north) = (nearest(&track.east_m), nearest(&track.north_m));
842 track
843 .time_s
844 .iter()
845 .enumerate()
846 .map(|(i, time)| [*time, east[i], north[i], track.up_m[i].unwrap_or(0.0)])
847 .collect()
848}
849
850fn assumed(ghost: &Ghost, track: &Track) -> String {
852 let mut words = vec![format!(
853 "{}: seconds from {}; east, north and up from the pad.",
854 track.name,
855 if track.synced {
856 "liftoff, by the log's reading"
857 } else {
858 "the log's own zero: it has no liftoff"
859 }
860 )];
861 if ghost.pad.from == PadFrom::Unknown {
862 words.push("The pad's place isn't known: it is drawn at 0N 0E.".to_owned());
863 } else if ghost.pad.height_m.is_none() {
864 words.push(
865 "The pad's height isn't known: the path starts on the WGS 84 ellipsoid, which can be \
866 far under or over the ground."
867 .to_owned(),
868 );
869 } else if !ghost.pad.height_stated {
870 words.push(
871 "The pad's height is the receiver's, drawn as if above the ellipsoid: off by the \
872 local geoid, within about 110 m, if it states sea level."
873 .to_owned(),
874 );
875 }
876 if ghost.pad.from == PadFrom::FirstFix {
877 words.push("The pad is the track's first fix.".to_owned());
878 }
879 if track.fixes.kept == 0 {
880 words.push("The log has no GNSS track: a straight vertical line.".to_owned());
881 } else if track.east_m.iter().any(Option::is_none) {
882 words.push("Outside the fixes it is held at the nearest.".to_owned());
883 }
884 if track.up_from == UpFrom::Unknown {
885 words.push("The log holds no height above the pad: drawn at 0.".to_owned());
886 }
887 if track.up_from == UpFrom::AltitudeLessPad {
888 words.push(
889 "The log's altitude states no zero at the pad: taken less its own reading there, or \
890 its first rows' with no liftoff."
891 .to_owned(),
892 );
893 }
894 let left_out = track.moments_left_out + track.heights_too_fast + track.heights_below_pad;
895 if left_out > 0 {
896 words.push(format!(
897 "{left_out} of the log's rows are left out: a line crosses each gap."
898 ));
899 }
900 words.join(" ")
901}
902
903impl Ghost {
904 fn check(&self) -> Result<(), GhostError> {
907 let bad = |name: &str, what: &str| GhostError::BadTrack {
908 name: name.to_owned(),
909 what: what.to_owned(),
910 };
911 if self.tracks.is_empty() {
912 return Err(GhostError::NoLogs);
913 }
914 if let (Some(lat), Some(lon)) = (self.pad.latitude_deg, self.pad.longitude_deg)
915 && frame_at(lat, lon, self.pad.height_m.unwrap_or(0.0)).is_none()
916 {
917 return Err(GhostError::BadPad {
918 what: format!("latitude {lat} and longitude {lon}"),
919 });
920 }
921 for track in &self.tracks {
922 let moments = track.time_s.len();
923 if moments == 0 {
924 return Err(bad(&track.name, "it has no moments"));
925 }
926 if track.east_m.len() != moments
927 || track.north_m.len() != moments
928 || track.up_m.len() != moments
929 {
930 return Err(bad(&track.name, "its columns differ in length"));
931 }
932 if track
933 .time_s
934 .iter()
935 .any(|t| t.is_nan() || t.abs() > CLOCK_LIMIT_S)
936 || track.time_s.windows(2).any(|pair| pair[1] <= pair[0])
937 {
938 return Err(bad(
939 &track.name,
940 "its clock doesn't go forward inside its limit",
941 ));
942 }
943 let finite = |values: &[Option<f64>]| values.iter().flatten().all(|v| v.is_finite());
944 if !finite(&track.east_m) || !finite(&track.north_m) || !finite(&track.up_m) {
945 return Err(bad(&track.name, "a place isn't a number"));
946 }
947 }
948 Ok(())
949 }
950
951 #[allow(
955 clippy::cast_possible_truncation,
956 reason = "under 1e14 milliseconds, by the clock's limit: far inside i64"
957 )]
958 fn czml_time(seconds: f64, up: bool) -> String {
959 let scaled = seconds * 1000.0;
960 let ms = (if up {
962 scaled.ceil() + 1.0
963 } else {
964 scaled.floor() - 1.0
965 }) as i64
966 + 12 * 3_600_000;
967 let (days, ms) = (ms.div_euclid(86_400_000), ms.rem_euclid(86_400_000));
968 let (year, month, day) = date_from_days(days);
969 format!(
970 "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}.{:03}Z",
971 ms / 3_600_000,
972 ms / 60_000 % 60,
973 ms / 1000 % 60,
974 ms % 1000
975 )
976 }
977
978 fn czml_zero_s(&self) -> f64 {
980 if self.tracks.iter().any(|track| track.synced) {
981 return 0.0;
982 }
983 self.tracks
984 .iter()
985 .filter_map(|track| track.time_s.first())
986 .copied()
987 .fold(f64::INFINITY, f64::min)
988 }
989
990 pub fn to_czml(&self) -> Result<String, GhostError> {
996 self.check()?;
997 let (lat, lon, height) = (
998 self.pad.latitude_deg.unwrap_or(UNKNOWN_PAD.0),
999 self.pad.longitude_deg.unwrap_or(UNKNOWN_PAD.1),
1000 self.pad.height_m.unwrap_or(UNKNOWN_PAD.2),
1001 );
1002 let frame = frame_at(lat, lon, height);
1003 let zero_s = self.czml_zero_s();
1006 let span =
1007 self.tracks
1008 .iter()
1009 .fold((f64::INFINITY, f64::NEG_INFINITY), |(start, end), track| {
1010 (
1011 start.min(track.time_s.first().copied().unwrap_or(0.0) - zero_s),
1012 end.max(track.time_s.last().copied().unwrap_or(0.0) - zero_s),
1013 )
1014 });
1015 let (start, end) = (
1016 Self::czml_time(span.0, false),
1017 Self::czml_time(span.1, true),
1018 );
1019 let mut packets = vec![json!({
1020 "id": "document",
1021 "name": "FusionSpace HPR ghost",
1022 "version": "1.0",
1023 "clock": {
1024 "interval": format!("{start}/{end}"),
1025 "currentTime": start,
1026 "multiplier": 1,
1027 },
1028 })];
1029 for (index, track) in self.tracks.iter().enumerate() {
1030 let mut cartesian = Vec::with_capacity(track.time_s.len() * 4);
1031 for [time, east, north, up] in drawn(track) {
1032 let at = frame
1033 .as_ref()
1034 .map_or(hpr_core::DVec3::ZERO, |frame: &LaunchFrame| {
1035 frame.ecef_from_enu(hpr_core::DVec3::new(east, north, up))
1036 });
1037 cartesian.extend([time - zero_s, at.x, at.y, at.z]);
1038 }
1039 let color = TRACK_COLORS[index % TRACK_COLORS.len()];
1040 packets.push(json!({
1041 "id": format!("track-{}", index + 1),
1042 "name": track.name,
1043 "description": escaped(&assumed(self, track)),
1044 "availability": format!(
1045 "{}/{}",
1046 Self::czml_time(track.time_s[0] - zero_s, false),
1047 Self::czml_time(track.time_s[track.time_s.len() - 1] - zero_s, true),
1048 ),
1049 "point": {"pixelSize": 8, "color": {"rgba": color}},
1050 "path": {"width": 2, "material": {"solidColor": {"color": {"rgba": color}}}},
1051 "position": {
1052 "epoch": CZML_EPOCH,
1053 "referenceFrame": "FIXED",
1054 "interpolationAlgorithm": "LINEAR",
1055 "interpolationDegree": 1,
1056 "cartesian": cartesian,
1057 },
1058 }));
1059 }
1060 Ok(Value::Array(packets).to_string())
1061 }
1062
1063 #[allow(
1067 clippy::cast_possible_truncation,
1068 reason = "glTF holds 32-bit floats: the module docs size the loss"
1069 )]
1070 pub fn to_gltf(&self) -> Result<String, GhostError> {
1075 self.check()?;
1076 let mut buffer = Bytes::default();
1077 let mut accessors = Vec::new();
1078 let mut meshes = Vec::new();
1079 let mut nodes = Vec::new();
1080 let mut samplers = Vec::new();
1081 let mut channels = Vec::new();
1082 let mut materials = Vec::new();
1083 let t0 = self
1084 .tracks
1085 .iter()
1086 .filter_map(|track| track.time_s.first())
1087 .copied()
1088 .fold(f64::INFINITY, f64::min);
1089 let marker_points = {
1091 let r = MARKER_RADIUS_M as f32;
1092 [
1093 [r, 0.0, 0.0],
1094 [-r, 0.0, 0.0],
1095 [0.0, r, 0.0],
1096 [0.0, -r, 0.0],
1097 [0.0, 0.0, r],
1098 [0.0, 0.0, -r],
1099 ]
1100 };
1101 let marker_position = buffer.vec3(&marker_points, &mut accessors);
1102 let marker_position = buffer.same_bytes_for_a_mesh(marker_position, &mut accessors);
1103 let marker_indices = buffer.indices(
1104 &[
1105 0, 2, 4, 2, 1, 4, 1, 3, 4, 3, 0, 4, 2, 0, 5, 1, 2, 5, 3, 1, 5, 0, 3, 5,
1106 ],
1107 &mut accessors,
1108 );
1109 for (index, track) in self.tracks.iter().enumerate() {
1110 let mut times: Vec<f32> = Vec::with_capacity(track.time_s.len());
1111 let mut places: Vec<[f32; 3]> = Vec::with_capacity(track.time_s.len());
1112 for [time, east, north, up] in drawn(track) {
1113 let time = (time - t0) as f32;
1115 if times.last().is_none_or(|last| time > *last) {
1116 times.push(time);
1117 places.push([east as f32, up as f32, -north as f32]);
1118 }
1119 }
1120 let input = buffer.scalars(×, &mut accessors);
1121 let output = buffer.vec3(&places, &mut accessors);
1122 let line = buffer.same_bytes_for_a_mesh(output, &mut accessors);
1125 let material = materials.len();
1126 let color = TRACK_COLORS[index % TRACK_COLORS.len()];
1127 materials.push(json!({
1128 "name": track.name,
1129 "pbrMetallicRoughness": {
1130 "baseColorFactor": [
1131 f64::from(color[0]) / 255.0,
1132 f64::from(color[1]) / 255.0,
1133 f64::from(color[2]) / 255.0,
1134 1.0,
1135 ],
1136 },
1137 }));
1138 meshes.push(json!({
1139 "name": format!("{} path", track.name),
1140 "primitives": [{"attributes": {"POSITION": line}, "mode": 3, "material": material}],
1141 }));
1142 meshes.push(json!({
1143 "name": format!("{} marker", track.name),
1144 "primitives": [{
1145 "attributes": {"POSITION": marker_position},
1146 "indices": marker_indices,
1147 "material": material,
1148 }],
1149 }));
1150 nodes.push(json!({
1151 "name": format!("{} path", track.name),
1152 "mesh": meshes.len() - 2,
1153 "extras": {"description": assumed(self, track)},
1154 }));
1155 let moving = nodes.len();
1156 nodes.push(json!({
1157 "name": format!("{} marker", track.name),
1158 "mesh": meshes.len() - 1,
1159 "translation": places[0],
1160 }));
1161 channels.push(json!({
1162 "sampler": samplers.len(),
1163 "target": {"node": moving, "path": "translation"},
1164 }));
1165 samplers.push(json!({"input": input, "output": output, "interpolation": "LINEAR"}));
1166 }
1167 let scene: Vec<usize> = (0..nodes.len()).collect();
1168 let base64 = base64::engine::general_purpose::STANDARD.encode(&buffer.bytes);
1169 Ok(json!({
1170 "asset": {"version": "2.0", "generator": "FusionSpace HPR"},
1171 "extras": {
1172 "first_moment_s": t0,
1173 "frame": "+x east, +y up, -z north, m, from the pad",
1174 "pad": self.pad,
1175 },
1176 "scene": 0,
1177 "scenes": [{"nodes": scene}],
1178 "nodes": nodes,
1179 "meshes": meshes,
1180 "materials": materials,
1181 "animations": [{"name": "flight", "channels": channels, "samplers": samplers}],
1182 "accessors": accessors,
1183 "bufferViews": buffer.views,
1184 "buffers": [{
1185 "byteLength": buffer.bytes.len(),
1186 "uri": format!("data:application/octet-stream;base64,{base64}"),
1187 }],
1188 })
1189 .to_string())
1190 }
1191}
1192
1193fn date_from_days(days: i64) -> (i64, i64, i64) {
1196 let z = days - 60;
1198 let era = z.div_euclid(146_097);
1199 let day_of_era = z.rem_euclid(146_097);
1200 let year_of_era =
1201 (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
1202 let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
1203 let shifted_month = (5 * day_of_year + 2) / 153;
1204 let day = day_of_year - (153 * shifted_month + 2) / 5 + 1;
1205 let month = if shifted_month < 10 {
1206 shifted_month + 3
1207 } else {
1208 shifted_month - 9
1209 };
1210 let year = 2000 + year_of_era + era * 400 + i64::from(month <= 2);
1211 (year, month, day)
1212}
1213
1214fn escaped(text: &str) -> String {
1216 text.replace('&', "&")
1217 .replace('<', "<")
1218 .replace('>', ">")
1219}
1220
1221const TRACK_COLORS: [[u8; 4]; 4] = [
1224 [255, 122, 26, 255],
1225 [120, 200, 255, 255],
1226 [190, 240, 150, 255],
1227 [255, 220, 120, 255],
1228];
1229
1230const ARRAY_BUFFER: u32 = 34962;
1232const ELEMENT_ARRAY_BUFFER: u32 = 34963;
1233
1234#[derive(Default)]
1236struct Bytes {
1237 bytes: Vec<u8>,
1238 views: Vec<Value>,
1239}
1240
1241impl Bytes {
1242 fn same_bytes_for_a_mesh(&mut self, accessor: usize, accessors: &mut Vec<Value>) -> usize {
1244 let mut copy = accessors[accessor].clone();
1245 let view = copy["bufferView"]
1246 .as_u64()
1247 .and_then(|view| usize::try_from(view).ok())
1248 .unwrap_or(0);
1249 let mut own = self.views[view].clone();
1250 own["target"] = json!(ARRAY_BUFFER);
1251 self.views.push(own);
1252 copy["bufferView"] = json!(self.views.len() - 1);
1253 accessors.push(copy);
1254 accessors.len() - 1
1255 }
1256
1257 fn view(&mut self, data: &[u8]) -> usize {
1259 while !self.bytes.len().is_multiple_of(4) {
1260 self.bytes.push(0);
1261 }
1262 self.views.push(json!({
1263 "buffer": 0,
1264 "byteOffset": self.bytes.len(),
1265 "byteLength": data.len(),
1266 }));
1267 self.bytes.extend_from_slice(data);
1268 self.views.len() - 1
1269 }
1270
1271 fn scalars(&mut self, values: &[f32], accessors: &mut Vec<Value>) -> usize {
1273 let data: Vec<u8> = values.iter().flat_map(|v| v.to_le_bytes()).collect();
1274 let view = self.view(&data);
1275 let (least, most) = values
1276 .iter()
1277 .fold((f32::INFINITY, f32::NEG_INFINITY), |(a, b), v| {
1278 (a.min(*v), b.max(*v))
1279 });
1280 accessors.push(json!({
1281 "bufferView": view,
1282 "componentType": 5126,
1283 "count": values.len(),
1284 "type": "SCALAR",
1285 "min": [least],
1286 "max": [most],
1287 }));
1288 accessors.len() - 1
1289 }
1290
1291 fn vec3(&mut self, values: &[[f32; 3]], accessors: &mut Vec<Value>) -> usize {
1293 let data: Vec<u8> = values
1294 .iter()
1295 .flatten()
1296 .flat_map(|v| v.to_le_bytes())
1297 .collect();
1298 let view = self.view(&data);
1299 let bound = |pick: fn(f32, f32) -> f32, start: f32| -> [f32; 3] {
1300 values.iter().fold([start; 3], |held, v| {
1301 [
1302 pick(held[0], v[0]),
1303 pick(held[1], v[1]),
1304 pick(held[2], v[2]),
1305 ]
1306 })
1307 };
1308 accessors.push(json!({
1309 "bufferView": view,
1310 "componentType": 5126,
1311 "count": values.len(),
1312 "type": "VEC3",
1313 "min": bound(f32::min, f32::INFINITY),
1314 "max": bound(f32::max, f32::NEG_INFINITY),
1315 }));
1316 accessors.len() - 1
1317 }
1318
1319 fn indices(&mut self, values: &[u16], accessors: &mut Vec<Value>) -> usize {
1321 let data: Vec<u8> = values.iter().flat_map(|v| v.to_le_bytes()).collect();
1322 let view = self.view(&data);
1323 self.views[view]["target"] = json!(ELEMENT_ARRAY_BUFFER);
1324 accessors.push(json!({
1325 "bufferView": view,
1326 "componentType": 5123,
1327 "count": values.len(),
1328 "type": "SCALAR",
1329 }));
1330 accessors.len() - 1
1331 }
1332}
1333
1334#[cfg(test)]
1335mod tests {
1336 use super::*;
1337 use crate::import;
1338 use crate::readings;
1339
1340 fn climb() -> FlightLog {
1342 let mut text = String::from("Time (s),Barometric altitude AGL (m)\n");
1343 for row in 0..400 {
1344 let t = f64::from(row) * 0.1;
1345 let up = if t < 10.0 {
1346 0.0
1347 } else if t < 13.0 {
1348 0.5 * 60.0 * (t - 10.0).powi(2)
1349 } else {
1350 270.0 + 180.0 * (t - 13.0) - 4.9 * (t - 13.0).powi(2)
1351 };
1352 text.push_str(&format!("{t:.2},{:.2}\n", up.max(0.0)));
1353 }
1354 import::read_one(text.as_bytes(), None, None).unwrap()
1355 }
1356
1357 fn no_height() -> FlightLog {
1359 let mut log = climb();
1360 log.time_s.clear();
1361 log.altitude_m.clear();
1362 log.channels.clear();
1363 log
1364 }
1365
1366 fn with_fixes(mut log: FlightLog, fixes: &[(f64, f64, f64)], height: Option<f64>) -> FlightLog {
1368 let time: Vec<f64> = fixes.iter().map(|f| f.0).collect();
1369 let mut add = |quantity, values: Vec<f64>| {
1370 log.channels.push(Channel {
1371 column: format!("{quantity:?}"),
1372 quantity,
1373 time_s: time.clone(),
1374 values,
1375 });
1376 };
1377 add(Quantity::Latitude, fixes.iter().map(|f| f.1).collect());
1378 add(Quantity::Longitude, fixes.iter().map(|f| f.2).collect());
1379 if let Some(height) = height {
1380 add(Quantity::GnssAltitude, vec![height; fixes.len()]);
1381 }
1382 log
1383 }
1384
1385 fn built(log: &FlightLog, pad: Option<StatedPad>) -> Result<Ghost, GhostError> {
1386 let read = readings::read(log);
1387 build(
1388 &[Input {
1389 name: "a.csv",
1390 log,
1391 read: &read,
1392 }],
1393 pad,
1394 )
1395 }
1396
1397 fn little_ghost(east: Option<f64>, up: Option<f64>) -> Ghost {
1398 Ghost {
1399 format: "hpr-ghost".to_owned(),
1400 version: 1,
1401 frame: String::new(),
1402 pad: Pad {
1403 latitude_deg: Some(0.0),
1404 longitude_deg: Some(0.0),
1405 height_m: Some(0.0),
1406 height_stated: true,
1407 from: PadFrom::Stated,
1408 first_fix_after_liftoff_s: None,
1409 },
1410 tracks: vec![Track {
1411 name: "a.csv".to_owned(),
1412 logger: "a".to_owned(),
1413 synced: true,
1414 liftoff_s: Some(0.0),
1415 liftoff_bound_s: Some(1.0),
1416 up_from: UpFrom::LogAltitude,
1417 time_s: vec![0.0, 1.0],
1418 east_m: vec![east, Some(1.0)],
1419 north_m: vec![Some(2.0), Some(2.0)],
1420 up_m: vec![up, Some(3.0)],
1421 fixes: FixCounts::default(),
1422 widest_fix_gap_s: None,
1423 moments_left_out: 0,
1424 heights_too_fast: 0,
1425 heights_below_pad: 0,
1426 }],
1427 }
1428 }
1429
1430 #[test]
1431 fn time_counts_from_liftoff_and_a_barometer_alone_is_a_vertical_line() {
1432 let log = climb();
1433 let ghost = built(&log, None).unwrap();
1434 let track = &ghost.tracks[0];
1435 let zero = track.liftoff_s.unwrap();
1436 assert!((9.0..11.0).contains(&zero), "{zero}");
1437 assert!(track.synced);
1438 let column = channel(&log, Quantity::AltitudeAboveGround).unwrap();
1439 assert_eq!(track.time_s[0], column.time_s[0] - zero);
1440 assert_eq!(track.up_from, UpFrom::LogAltitude);
1441 assert_eq!(ghost.pad.from, PadFrom::Unknown);
1442 assert!(track.east_m.iter().all(Option::is_none));
1443 assert!(track.north_m.iter().all(Option::is_none));
1444 let i = column.values.iter().position(|h| *h > 1_000.0).unwrap();
1446 assert_eq!(track.up_m[i], Some(column.values[i]));
1447 }
1448
1449 #[test]
1450 fn east_and_north_match_the_ellipsoids_radii_of_curvature() {
1451 let (lat, lon, step) = (39.39_f64, -8.29, 1e-3);
1456 let fixes = [
1457 (5.0, lat, lon),
1458 (9.0, lat, lon),
1459 (20.0, lat + step, lon + step),
1460 ];
1461 let ghost = built(&with_fixes(climb(), &fixes, None), None).unwrap();
1462 assert_eq!(ghost.pad.from, PadFrom::FixesBeforeLiftoff);
1463 assert_eq!(ghost.pad.latitude_deg, Some(lat));
1464 let track = &ghost.tracks[0];
1465 let zero = track.liftoff_s.unwrap();
1466 let i = track
1467 .time_s
1468 .iter()
1469 .position(|t| (t + zero - 20.0).abs() < 1e-9)
1470 .unwrap();
1471 let (m, n) = (6_361_145.5_f64, 6_386_751.8_f64);
1472 let north = m * step.to_radians();
1473 let east = n * lat.to_radians().cos() * step.to_radians();
1474 assert!((track.north_m[i].unwrap() - north).abs() < 0.005, "{north}");
1475 assert!((track.east_m[i].unwrap() - east).abs() < 0.005, "{east}");
1476 assert_eq!(*track.east_m.last().unwrap(), None);
1478 let j = track
1479 .time_s
1480 .iter()
1481 .position(|t| (t + zero - 14.5).abs() < 1e-9)
1482 .unwrap();
1483 assert!((track.north_m[j].unwrap() - north / 2.0).abs() < 0.005);
1484 assert_eq!(track.widest_fix_gap_s, Some(11.0));
1485 }
1486
1487 #[test]
1488 fn the_pad_is_the_median_of_the_last_fixes_before_liftoff() {
1489 let (lat, lon) = (39.39, -8.29);
1492 let mut fixes: Vec<(f64, f64, f64)> = (0..10)
1493 .map(|k| (0.1 * f64::from(k), lat + 0.01, lon))
1494 .collect();
1495 fixes.extend((10..30).map(|k| (0.1 * f64::from(k), lat, lon)));
1496 fixes[20].1 = lat + 0.001;
1497 fixes.push((20.0, lat + 0.005, lon));
1498 let ghost = built(&with_fixes(climb(), &fixes, None), None).unwrap();
1499 assert_eq!(ghost.pad.from, PadFrom::FixesBeforeLiftoff);
1500 assert_eq!(ghost.pad.latitude_deg, Some(lat));
1501 assert_eq!(ghost.pad.longitude_deg, Some(lon));
1502 }
1503
1504 #[test]
1508 fn the_pages_meridian_example_takes_minus_180() {
1509 let taken = median_longitude(&[179.9, -179.9, 179.8, -179.8]);
1510 assert_eq!(taken.map(f64::to_bits), Some((-180.0f64).to_bits()));
1511 assert_eq!(median_longitude(&[10.25, 10.75, 10.5]), Some(10.5));
1512 assert_eq!(median_longitude(&[]), None);
1513 }
1514
1515 #[test]
1519 fn a_track_across_the_180th_meridian_keeps_its_fixes_and_its_pad() {
1520 let lat = -16.5;
1521 let mut fixes: Vec<(f64, f64, f64)> = (0..30)
1522 .map(|k| {
1523 let lon = if k % 2 == 0 { 179.999_99 } else { -179.999_99 };
1524 (0.1 * f64::from(k), lat, lon)
1525 })
1526 .collect();
1527 fixes.push((20.0, lat + 0.000_1, -179.999_9));
1529 fixes.push((21.0, lat + 0.000_2, 179.999_9));
1530 let ghost = built(&with_fixes(climb(), &fixes, None), None).unwrap();
1531 let counts = ghost.tracks[0].fixes;
1532 assert_eq!((counts.kept, counts.out_of_reach), (32, 0), "{counts:?}");
1533 assert_eq!(ghost.pad.from, PadFrom::FixesBeforeLiftoff);
1534 let pad = ghost.pad.longitude_deg.unwrap();
1535 assert!(180.0 - pad.abs() < 1e-4, "{pad}");
1536 assert!((-180.0..=180.0).contains(&pad), "{pad}");
1537 let mut fixes: Vec<(f64, f64, f64)> = (0..30)
1541 .map(|k| {
1542 let lon = if k % 2 == 1 { 89.999_99 } else { 90.000_01 };
1543 (0.1 * f64::from(k), lat, lon)
1544 })
1545 .collect();
1546 fixes[0].2 = -90.0;
1547 let ghost = built(&with_fixes(climb(), &fixes, None), None).unwrap();
1548 let counts = ghost.tracks[0].fixes;
1549 assert_eq!((counts.kept, counts.out_of_reach), (29, 1), "{counts:?}");
1550 let pad = ghost.pad.longitude_deg.unwrap();
1551 assert!((pad - 90.0).abs() < 1e-4, "{pad}");
1552 }
1553
1554 #[test]
1555 fn a_first_fix_after_liftoff_says_how_late_it_was() {
1556 let ghost = built(&with_fixes(climb(), &[(20.0, 39.39, -8.29)], None), None).unwrap();
1557 assert_eq!(ghost.pad.from, PadFrom::FirstFix);
1558 let zero = ghost.tracks[0].liftoff_s.unwrap();
1559 assert_eq!(ghost.pad.first_fix_after_liftoff_s, Some(20.0 - zero));
1560 }
1561
1562 #[test]
1563 fn each_bad_fix_is_left_out_and_counted_by_its_own_reason() {
1564 let (lat, lon) = (39.39, -8.29);
1565 let fixes = [
1566 (1.0, lat, lon),
1567 (2.0, 0.0, 0.0), (3.0, 95.0, lon), (4.0, f64::NAN, lon), (5.0, lat, lon),
1571 (5.0, lat, lon), (4.5, lat, lon), (6.0, lat, -lon), (7.0, lat + 0.09, lon), (8.0, lat, lon),
1576 ];
1577 let ghost = built(&with_fixes(climb(), &fixes, None), None).unwrap();
1578 let counts = ghost.tracks[0].fixes;
1579 assert_eq!(
1580 counts,
1581 FixCounts {
1582 given: 10,
1583 kept: 3,
1584 not_a_place: 3,
1585 clock_back: 2,
1586 out_of_reach: 1,
1587 too_fast: 1,
1588 }
1589 );
1590 }
1591
1592 #[test]
1593 fn a_fast_track_inside_the_envelope_is_kept() {
1594 let (lat, lon) = (39.39, -8.29);
1596 let fixes: Vec<(f64, f64, f64)> = (0..11)
1597 .map(|k| (f64::from(k), lat + f64::from(k) * 1_200.0 / 110_950.0, lon))
1598 .collect();
1599 let ghost = built(&with_fixes(climb(), &fixes, None), None).unwrap();
1600 assert_eq!(ghost.tracks[0].fixes.kept, 11);
1601 }
1602
1603 #[test]
1604 fn a_height_no_flight_could_reach_is_left_out() {
1605 let mut log = climb();
1606 let column = log
1607 .channels
1608 .iter_mut()
1609 .find(|c| c.quantity == Quantity::AltitudeAboveGround)
1610 .unwrap();
1611 let n = column.values.len();
1612 column.values[n - 2] = 90_000.0;
1613 column.values[n - 1] = -90_000.0;
1614 let ghost = built(&log, None).unwrap();
1615 let track = &ghost.tracks[0];
1616 assert_eq!(track.heights_too_fast, 1);
1618 assert_eq!(track.heights_below_pad, 1);
1619 assert_eq!(track.time_s.len(), n - 2);
1620 assert!(track.up_m.iter().flatten().all(|h| h.abs() < 90_000.0));
1621 }
1622
1623 #[test]
1624 fn gnss_altitude_is_measured_from_the_pads() {
1625 let (lat, lon) = (39.39, -8.29);
1626 let fixes = [(0.0, lat, lon), (1.0, lat, lon)];
1627 let mut log = with_fixes(no_height(), &fixes, Some(1_400.0));
1628 log.channels.last_mut().unwrap().values = vec![1_400.0, 1_500.0];
1629 let ghost = built(&log, None).unwrap();
1630 let track = &ghost.tracks[0];
1631 assert_eq!(track.up_from, UpFrom::GnssAltitude);
1632 assert_eq!(ghost.pad.from, PadFrom::FirstFix);
1633 assert_eq!(ghost.pad.height_m, Some(1_400.0));
1634 assert_eq!(track.up_m, vec![Some(0.0), Some(100.0)]);
1635 assert!(!track.synced);
1636 }
1637
1638 #[test]
1639 fn a_place_alone_has_no_height_and_nothing_is_refused() {
1640 let (lat, lon) = (39.39, -8.29);
1641 let ghost = built(
1642 &with_fixes(no_height(), &[(0.0, lat, lon), (1.0, lat, lon)], None),
1643 None,
1644 );
1645 assert_eq!(ghost.unwrap().tracks[0].up_from, UpFrom::Unknown);
1646 }
1647
1648 #[test]
1649 fn a_log_with_nothing_to_draw_is_refused_by_name() {
1650 assert_eq!(
1651 built(&no_height(), None),
1652 Err(GhostError::NoTrack {
1653 name: "a.csv".to_owned()
1654 })
1655 );
1656 }
1657
1658 #[test]
1659 fn a_log_with_no_liftoff_cant_join_others_on_a_timeline() {
1660 let good = climb();
1661 let bad = with_fixes(no_height(), &[(0.0, 39.39, -8.29)], None);
1662 let (read_good, read_bad) = (readings::read(&good), readings::read(&bad));
1663 let inputs = [
1664 Input {
1665 name: "good.csv",
1666 log: &good,
1667 read: &read_good,
1668 },
1669 Input {
1670 name: "bad.csv",
1671 log: &bad,
1672 read: &read_bad,
1673 },
1674 ];
1675 let Err(GhostError::NotOnTimeline { name, .. }) = build(&inputs, None) else {
1676 panic!("a log with no liftoff joined a timeline");
1677 };
1678 assert_eq!(name, "bad.csv");
1679 assert_eq!(build(&[], None), Err(GhostError::NoLogs));
1680 }
1681
1682 #[test]
1683 fn a_stated_pad_wins_and_must_be_a_place() {
1684 let log = with_fixes(climb(), &[(5.0, 39.39, -8.29)], Some(1_000.0));
1685 let stated = StatedPad {
1686 latitude_deg: 39.4,
1687 longitude_deg: -8.3,
1688 height_m: None,
1689 };
1690 let ghost = built(&log, Some(stated)).unwrap();
1691 assert_eq!(ghost.pad.from, PadFrom::Stated);
1692 assert_eq!(ghost.pad.latitude_deg, Some(39.4));
1693 assert_eq!(ghost.pad.height_m, Some(1_000.0));
1694 let far = StatedPad {
1695 latitude_deg: 91.0,
1696 ..stated
1697 };
1698 assert!(matches!(
1699 built(&log, Some(far)),
1700 Err(GhostError::BadPad { what }) if what.contains("out of range")
1701 ));
1702 let huge = StatedPad {
1703 height_m: Some(1e300),
1704 ..stated
1705 };
1706 assert!(matches!(
1707 built(&log, Some(huge)),
1708 Err(GhostError::BadPad { what }) if what.contains("height")
1709 ));
1710 let nan = StatedPad {
1711 height_m: Some(f64::NAN),
1712 ..stated
1713 };
1714 assert!(matches!(
1715 built(&log, Some(nan)),
1716 Err(GhostError::BadPad { what }) if what.contains("height")
1717 ));
1718 }
1719
1720 #[test]
1721 fn czml_is_earth_fixed_on_its_epoch_by_hand() {
1722 let text = little_ghost(Some(1.0), Some(3.0)).to_czml().unwrap();
1725 let packets: Value = serde_json::from_str(&text).unwrap();
1726 assert_eq!(packets[0]["id"], "document");
1727 assert_eq!(packets[0]["version"], "1.0");
1728 assert_eq!(
1729 packets[0]["clock"]["interval"],
1730 "2000-01-01T11:59:59.999Z/2000-01-01T12:00:01.001Z"
1731 );
1732 let position = &packets[1]["position"];
1733 assert_eq!(position["epoch"], "2000-01-01T12:00:00Z");
1734 assert_eq!(position["referenceFrame"], "FIXED");
1735 let numbers = position["cartesian"].as_array().unwrap();
1736 assert_eq!(numbers.len(), 8);
1737 let at = |i: usize| numbers[i].as_f64().unwrap();
1738 assert_eq!(at(4), 1.0);
1739 assert!((at(5) - 6_378_140.0).abs() < 1e-6, "{}", at(5));
1740 assert!((at(6) - 1.0).abs() < 1e-6);
1741 assert!((at(7) - 2.0).abs() < 1e-6);
1742 }
1743
1744 #[test]
1745 fn czml_dates_carry_over_midnight_and_back() {
1746 assert_eq!(Ghost::czml_time(0.0, false), "2000-01-01T11:59:59.999Z");
1747 assert_eq!(Ghost::czml_time(43_200.0, true), "2000-01-02T00:00:00.001Z");
1748 assert_eq!(
1749 Ghost::czml_time(-43_201.0, false),
1750 "1999-12-31T23:59:58.999Z"
1751 );
1752 }
1753
1754 #[test]
1755 fn what_a_drawing_assumes_it_says() {
1756 let mut ghost = little_ghost(None, None);
1757 ghost.tracks[0].fixes.kept = 1;
1758 assert_eq!(drawn(&ghost.tracks[0])[0], [0.0, 1.0, 2.0, 0.0]);
1760 assert!(assumed(&ghost, &ghost.tracks[0]).contains("held at the nearest"));
1761 ghost.pad.from = PadFrom::Unknown;
1762 ghost.tracks[0].fixes.kept = 0;
1763 ghost.tracks[0].up_from = UpFrom::Unknown;
1764 let words = assumed(&ghost, &ghost.tracks[0]);
1765 assert!(words.contains("drawn at 0N 0E"), "{words}");
1766 assert!(words.contains("straight vertical line"), "{words}");
1767 assert!(words.contains("no height"), "{words}");
1768 }
1769
1770 #[test]
1771 fn gltfs_bytes_are_what_the_spec_lays_out_by_hand() {
1772 let text = little_ghost(Some(1.0), Some(3.0)).to_gltf().unwrap();
1773 let gltf: Value = serde_json::from_str(&text).unwrap();
1774 assert_eq!(gltf["asset"]["version"], "2.0");
1775 let uri = gltf["buffers"][0]["uri"].as_str().unwrap();
1776 let body = uri
1777 .strip_prefix("data:application/octet-stream;base64,")
1778 .unwrap();
1779 let bytes = base64::engine::general_purpose::STANDARD
1780 .decode(body)
1781 .unwrap();
1782 assert_eq!(gltf["buffers"][0]["byteLength"], bytes.len());
1783 assert_eq!(bytes[..4], [0x00, 0x00, 0xA0, 0x40]);
1785 assert_eq!(bytes[120..128], [0, 0, 0, 0, 0x00, 0x00, 0x80, 0x3F]);
1788 let single = |value: f32| value.to_le_bytes();
1789 assert_eq!(bytes[128..132], single(1.0));
1790 assert_eq!(bytes[132..136], single(3.0));
1791 assert_eq!(bytes[136..140], single(-2.0));
1792 assert_eq!(single(-2.0), [0x00, 0x00, 0x00, 0xC0]);
1793 assert_eq!(gltf["extras"]["first_moment_s"], 0.0);
1795 let sampler = &gltf["animations"][0]["samplers"][0];
1796 assert_eq!(sampler["interpolation"], "LINEAR");
1797 assert_eq!(
1798 gltf["accessors"][sampler["input"].as_u64().unwrap() as usize]["min"][0],
1799 0.0
1800 );
1801 assert_eq!(
1802 gltf["accessors"][sampler["input"].as_u64().unwrap() as usize]["max"][0],
1803 1.0
1804 );
1805 let line = gltf["meshes"][0]["primitives"][0]["attributes"]["POSITION"]
1807 .as_u64()
1808 .unwrap();
1809 let output = sampler["output"].as_u64().unwrap();
1810 assert_ne!(line, output);
1811 let view = |accessor: u64| {
1812 gltf["bufferViews"][gltf["accessors"][accessor as usize]["bufferView"]
1813 .as_u64()
1814 .unwrap() as usize]
1815 .clone()
1816 };
1817 assert_eq!(view(line)["byteOffset"], view(output)["byteOffset"]);
1818 assert_eq!(view(line)["target"], 34962);
1819 assert_eq!(view(output)["target"], Value::Null);
1820 }
1821
1822 #[test]
1823 fn two_moments_a_float_cant_part_become_one_in_gltf() {
1824 let mut ghost = little_ghost(Some(1.0), Some(3.0));
1825 ghost.tracks[0].time_s = vec![1_000.0, 1_000.000_01, 1_001.0];
1826 ghost.tracks[0].east_m = vec![Some(1.0), Some(2.0), Some(3.0)];
1827 ghost.tracks[0].north_m = vec![Some(0.0); 3];
1828 ghost.tracks[0].up_m = vec![Some(0.0); 3];
1829 let gltf: Value = serde_json::from_str(&ghost.to_gltf().unwrap()).unwrap();
1830 let input = gltf["animations"][0]["samplers"][0]["input"]
1831 .as_u64()
1832 .unwrap() as usize;
1833 assert_eq!(gltf["accessors"][input]["count"], 3);
1835 ghost.tracks[0].time_s = vec![0.0, 1_000.0, 1_000.000_01, 1_001.0];
1837 ghost.tracks[0].east_m = vec![Some(0.0), Some(1.0), Some(2.0), Some(3.0)];
1838 ghost.tracks[0].north_m = vec![Some(0.0); 4];
1839 ghost.tracks[0].up_m = vec![Some(0.0); 4];
1840 let gltf: Value = serde_json::from_str(&ghost.to_gltf().unwrap()).unwrap();
1841 assert_eq!(gltf["accessors"][input]["count"], 3);
1842 }
1843
1844 fn table(header: &str, rows: impl Iterator<Item = String>) -> FlightLog {
1846 let mut text = format!("{header}\n");
1847 for row in rows {
1848 text.push_str(&row);
1849 text.push('\n');
1850 }
1851 import::read_one(text.as_bytes(), None, None).unwrap()
1852 }
1853
1854 fn receiver(heights: &[f64]) -> FlightLog {
1856 let mut log = no_height();
1857 let fixes: Vec<(f64, f64, f64)> = (0..heights.len())
1858 .map(|i| (i as f64 * 0.5, 40.0, -105.0))
1859 .collect();
1860 log = with_fixes(log, &fixes, Some(0.0));
1861 let height = log
1862 .channels
1863 .iter_mut()
1864 .find(|c| c.quantity == Quantity::GnssAltitude)
1865 .unwrap();
1866 height.values = heights.to_vec();
1867 log
1868 }
1869
1870 #[test]
1871 fn a_moment_with_no_height_is_left_out_not_drawn_at_the_pad() {
1872 let mut heights: Vec<f64> = (0..40).map(|i| 1_400.0 + f64::from(i) * 20.0).collect();
1873 heights[20] = f64::NAN;
1874 heights[21] = 0.0;
1875 let ghost = built(&receiver(&heights), None).unwrap();
1876 let track = &ghost.tracks[0];
1877 assert_eq!(track.up_from, UpFrom::GnssAltitude);
1878 assert_eq!(track.moments_left_out, 2);
1879 assert_eq!(track.time_s.len(), 38);
1880 assert!(track.up_m.iter().all(Option::is_some));
1881 assert!(!track.time_s.contains(&10.0) && !track.time_s.contains(&10.5));
1882 assert!(assumed(&ghost, track).contains("2 of the log's rows are left out"));
1883 }
1884
1885 #[test]
1886 fn a_height_far_under_the_pad_is_left_out_and_one_inside_the_floor_kept() {
1887 let mut heights = vec![1_400.0; 30];
1888 heights[10] = 1_400.0 - BELOW_PAD_M + 1.0;
1891 heights[20] = 1_400.0 - BELOW_PAD_M - 1.0;
1892 let ghost = built(&receiver(&heights), None).unwrap();
1893 let track = &ghost.tracks[0];
1894 assert_eq!(track.heights_below_pad, 1);
1895 assert_eq!(track.heights_too_fast, 0);
1896 assert_eq!(track.up_m[10], Some(1.0 - BELOW_PAD_M));
1897 assert_eq!(track.time_s.len(), 29);
1898 assert!(track.up_m.iter().flatten().all(|h| *h >= -BELOW_PAD_M));
1899 }
1900
1901 #[test]
1902 fn a_column_of_another_zero_is_taken_less_its_own_pad() {
1903 for header in [
1904 "Time (s),Altitude (m)",
1905 "Time (s),Barometric altitude MSL (m)",
1906 ] {
1907 let log = table(
1908 header,
1909 (0..200).map(|i| {
1910 let t = f64::from(i) * 0.1;
1911 format!("{t:.1},{:.1}", 1_400.0 + (t - 10.0).max(0.0) * 100.0)
1912 }),
1913 );
1914 let ghost = built(&log, None).unwrap();
1915 let track = &ghost.tracks[0];
1916 assert_eq!(track.up_from, UpFrom::AltitudeLessPad, "{header}");
1917 assert_eq!(track.up_m[0], Some(0.0), "{header}");
1918 let top = track.up_m.iter().flatten().copied().fold(0.0, f64::max);
1919 assert!((top - 990.0).abs() < 1e-6, "{header}: {top}");
1920 assert!(
1921 assumed(&ghost, track).contains("its own reading"),
1922 "{header}"
1923 );
1924 }
1925 }
1926
1927 #[test]
1928 fn a_height_above_ground_stays_as_the_log_wrote_it() {
1929 let ghost = built(&climb(), None).unwrap();
1930 assert_eq!(ghost.tracks[0].up_from, UpFrom::LogAltitude);
1931 }
1932
1933 #[test]
1934 fn the_pads_height_never_comes_from_a_fix_in_flight() {
1935 let fixes: Vec<(f64, f64, f64)> = (0..40).map(|i| (f64::from(i), 40.0, -105.0)).collect();
1937 let mut log = with_fixes(climb(), &fixes, Some(0.0));
1938 let height = log
1939 .channels
1940 .iter_mut()
1941 .find(|c| c.quantity == Quantity::GnssAltitude)
1942 .unwrap();
1943 height.values = (0..40)
1944 .map(|i| if i < 30 { f64::NAN } else { 3_000.0 })
1945 .collect();
1946 let ghost = built(&log, None).unwrap();
1947 assert_eq!(ghost.pad.from, PadFrom::FixesBeforeLiftoff);
1948 assert_eq!(ghost.pad.height_m, None);
1949 assert!(assumed(&ghost, &ghost.tracks[0]).contains("isn't known"));
1950
1951 let late: Vec<(f64, f64, f64)> = (0..10)
1953 .map(|i| (20.0 + f64::from(i), 40.0, -105.0))
1954 .collect();
1955 let ghost = built(&with_fixes(climb(), &late, Some(3_000.0)), None).unwrap();
1956 assert_eq!(ghost.pad.from, PadFrom::FirstFix);
1957 assert_eq!(ghost.pad.height_m, None);
1958 }
1959
1960 #[test]
1961 fn a_stated_pad_height_doesnt_move_a_receivers_heights() {
1962 let heights: Vec<f64> = (0..40).map(|i| 1_400.0 + f64::from(i)).collect();
1963 let stated = StatedPad {
1964 latitude_deg: 40.0,
1965 longitude_deg: -105.0,
1966 height_m: Some(1_380.0),
1967 };
1968 let ghost = built(&receiver(&heights), Some(stated)).unwrap();
1969 assert_eq!(ghost.pad.height_m, Some(1_380.0));
1970 assert_eq!(ghost.tracks[0].up_m[0], Some(0.0));
1971 assert!(!assumed(&ghost, &ghost.tracks[0]).contains("receiver's"));
1972
1973 let place = StatedPad {
1975 height_m: None,
1976 ..stated
1977 };
1978 let ghost = built(&receiver(&heights), Some(place)).unwrap();
1979 assert_eq!(ghost.pad.height_m, Some(1_400.0));
1980 assert!(assumed(&ghost, &ghost.tracks[0]).contains("local geoid"));
1981 }
1982
1983 #[test]
1984 fn a_receivers_pad_height_says_what_it_stands_for() {
1985 let heights = vec![1_400.0; 30];
1986 let ghost = built(&receiver(&heights), None).unwrap();
1987 assert!(assumed(&ghost, &ghost.tracks[0]).contains("local geoid"));
1988 }
1989
1990 #[test]
1991 fn one_bad_first_row_doesnt_shut_out_the_flight() {
1992 for bad in [30_000.0, 90_000.0, -40_000.0] {
1993 let log = table(
1994 "Time (s),Barometric altitude AGL (m)",
1995 std::iter::once(format!("-0.1,{bad}")).chain((0..400).map(|i| {
1996 let t = f64::from(i) * 0.1;
1997 format!("{t:.1},{:.1}", (t - 10.0).max(0.0) * 50.0)
1998 })),
1999 );
2000 let track = built(&log, None).unwrap().tracks.remove(0);
2001 assert_eq!(track.heights_too_fast + track.heights_below_pad, 1, "{bad}");
2002 assert_eq!(track.time_s.len(), 400, "{bad}");
2003 assert!(track.up_m.iter().flatten().all(|h| *h < 1_600.0), "{bad}");
2004 }
2005 }
2006
2007 #[test]
2008 fn one_bad_first_fix_doesnt_shut_out_the_track() {
2009 let mut fixes = vec![(-0.1, 40.5, -105.0)];
2010 fixes.extend((0..30).map(|i| (f64::from(i) * 0.1, 40.0, -105.0)));
2011 let track = built(&with_fixes(no_height(), &fixes, Some(1_400.0)), None)
2012 .unwrap()
2013 .tracks
2014 .remove(0);
2015 assert_eq!(track.fixes.too_fast, 1);
2016 assert_eq!(track.fixes.kept, 30);
2017 }
2018
2019 #[test]
2020 fn the_opening_finds_a_good_first_row_and_a_quick_start_stays() {
2021 let samples: Vec<(f64, f64)> = (0..20)
2023 .map(|i| (f64::from(i) * 0.1, f64::from(i) * 100.0))
2024 .collect();
2025 assert_eq!(opening_outliers(&samples, HEIGHT_SCATTER_M), 0);
2026 assert_eq!(opening_outliers(&[], HEIGHT_SCATTER_M), 0);
2027 let mut two_bad = samples.clone();
2028 two_bad[0].1 = 50_000.0;
2029 two_bad[1].1 = -50_000.0;
2030 assert_eq!(opening_outliers(&two_bad, HEIGHT_SCATTER_M), 2);
2031 }
2032
2033 #[test]
2034 fn dates_are_the_calendars() {
2035 for (days, date) in [
2037 (0, (2000, 1, 1)),
2038 (30, (2000, 1, 31)),
2039 (31, (2000, 2, 1)),
2040 (59, (2000, 2, 29)),
2041 (60, (2000, 3, 1)),
2042 (365, (2000, 12, 31)),
2043 (366, (2001, 1, 1)),
2044 (-1, (1999, 12, 31)),
2045 (-31, (1999, 12, 1)),
2046 (-32, (1999, 11, 30)),
2047 (36_583, (2100, 2, 28)),
2048 (36_584, (2100, 3, 1)),
2049 ] {
2050 assert_eq!(date_from_days(days), date, "{days}");
2051 }
2052 assert_eq!(
2053 Ghost::czml_time(3e6 + 0.0015, false),
2054 "2000-02-05T05:20:00.000Z"
2055 );
2056 }
2057
2058 #[test]
2059 fn a_garbage_clock_is_left_out_and_writes_nothing_wrong() {
2060 for last in ["1.1e7", "1e17", "1e19", "1e39", "1e300"] {
2061 let log = table(
2062 "Time (s),Barometric altitude AGL (m)",
2063 (0..400)
2064 .map(|i| {
2065 let t = f64::from(i) * 0.1;
2066 format!("{t:.1},{:.1}", (t - 10.0).max(0.0) * 50.0)
2067 })
2068 .chain(std::iter::once(format!("{last},0"))),
2069 );
2070 let ghost = built(&log, None).unwrap();
2071 assert_eq!(ghost.tracks[0].time_s.len(), 400, "{last}");
2072 assert_eq!(ghost.tracks[0].moments_left_out, 1, "{last}");
2073 let czml: Value = serde_json::from_str(&ghost.to_czml().unwrap()).unwrap();
2074 assert!(
2075 czml[0]["clock"]["interval"]
2076 .as_str()
2077 .unwrap()
2078 .contains("2000-01-01")
2079 );
2080 let gltf: Value = serde_json::from_str(&ghost.to_gltf().unwrap()).unwrap();
2081 assert!(
2082 gltf["accessors"]
2083 .as_array()
2084 .unwrap()
2085 .iter()
2086 .all(|a| { !a.to_string().contains("null") }),
2087 "{last}"
2088 );
2089 }
2090 }
2091
2092 #[test]
2093 fn a_unix_clock_starts_czml_at_its_first_moment() {
2094 let heights: Vec<f64> = (0..30).map(|i| 1_400.0 + f64::from(i)).collect();
2095 let mut log = receiver(&heights);
2096 for channel in &mut log.channels {
2097 for time in &mut channel.time_s {
2098 *time += 1.7e9;
2099 }
2100 }
2101 let ghost = built(&log, None).unwrap();
2102 assert!(ghost.tracks[0].time_s[0] > 1.6e9);
2103 let czml: Value = serde_json::from_str(&ghost.to_czml().unwrap()).unwrap();
2104 assert_eq!(
2105 czml[0]["clock"]["interval"],
2106 "2000-01-01T11:59:59.999Z/2000-01-01T12:00:14.501Z"
2107 );
2108 assert_eq!(czml[1]["position"]["cartesian"][0], 0.0);
2109 }
2110
2111 #[test]
2112 fn a_name_is_text_in_czmls_description() {
2113 let mut ghost = little_ghost(Some(1.0), Some(1.0));
2114 ghost.tracks[0].name = "<img src=x>&.csv".to_owned();
2115 let czml: Value = serde_json::from_str(&ghost.to_czml().unwrap()).unwrap();
2116 assert!(
2117 czml[1]["description"]
2118 .as_str()
2119 .unwrap()
2120 .starts_with("<img src=x>&.csv")
2121 );
2122 }
2123
2124 #[test]
2125 fn a_ghost_from_elsewhere_is_refused_not_a_panic() {
2126 let refused = |edit: fn(&mut Ghost)| {
2127 let mut ghost = little_ghost(Some(1.0), Some(1.0));
2128 edit(&mut ghost);
2129 assert!(ghost.to_czml().is_err());
2130 assert!(ghost.to_gltf().is_err());
2131 };
2132 refused(|g| g.tracks.clear());
2133 refused(|g| g.tracks[0].time_s.clear());
2134 refused(|g| {
2135 g.tracks[0].east_m.pop();
2136 });
2137 refused(|g| {
2138 g.tracks[0].north_m.pop();
2139 });
2140 refused(|g| {
2141 g.tracks[0].up_m.pop();
2142 });
2143 refused(|g| g.tracks[0].time_s[1] = 0.0);
2144 refused(|g| g.tracks[0].time_s[1] = 1e300);
2145 refused(|g| g.tracks[0].time_s[1] = f64::NAN);
2146 refused(|g| g.tracks[0].east_m[0] = Some(f64::INFINITY));
2147 refused(|g| g.pad.latitude_deg = Some(200.0));
2148 let ok = little_ghost(Some(1.0), Some(1.0));
2149 assert!(ok.to_czml().is_ok() && ok.to_gltf().is_ok());
2150 }
2151}