< Summary - ReFlex - Library

Information
Class: ReFlex.Core.Interactivity.Components.InteractionSmoothingBehaviour
Assembly: ReFlex.Core.Interactivity
File(s): D:\a\reflex\reflex\library\src\Core\Interactivity\Components\InteractionSmoothingBehaviour.cs
Line coverage
91%
Covered lines: 319
Uncovered lines: 31
Coverable lines: 350
Total lines: 584
Line coverage: 91.1%
Branch coverage
88%
Covered branches: 160
Total branches: 181
Branch coverage: 88.3%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.cctor()100%11100%
.ctor(...)100%11100%
get_LastMeasurement()100%11100%
get_Samples()100%11100%
get_Smoothed()100%11100%
get_Butterworth()100%11100%
get_LastSeenFrame()100%11100%
get_LastSeenTime()100%11100%
get_LastDetectedAt()100%11100%
get_ConfidenceUpdatedAt()100%11100%
get_Confidence()100%11100%
get_MatchingPosition()100%11100%
get_TouchMergeDistance2D()100%11100%
get_UseMinimumCostAssignment()100%11100%
get_AssignmentMissCost()100%11100%
set_AssignmentMissCost(...)100%44100%
get_AssignmentBirthCost()100%11100%
set_AssignmentBirthCost(...)100%44100%
get_NumFramesHistory()100%11100%
set_NumFramesHistory(...)100%22100%
get_NumFramesSmoothing()100%11100%
set_NumFramesSmoothing(...)100%44100%
ValidateContactRetention(...)100%44100%
get_ContactRetentionSeconds()100%11100%
set_ContactRetentionSeconds(...)100%11100%
get_ObservationTimeoutSeconds()100%22100%
set_ObservationTimeoutSeconds(...)100%11100%
get_UseVelocityForMapping()100%11100%
get_UseSecondDerivation()100%11100%
get_NumFramesForPrediction()100%11100%
set_NumFramesForPrediction(...)100%11100%
get_SecondDerivationMagnitude()100%11100%
set_SecondDerivationMagnitude(...)50%66100%
get_PredictionHorizonSeconds()100%11100%
set_PredictionHorizonSeconds(...)100%66100%
get_ConfidenceDecayPerSecond()100%11100%
set_ConfidenceDecayPerSecond(...)100%44100%
get_ConfidenceGainPerSecond()100%11100%
set_ConfidenceGainPerSecond(...)100%44100%
get_CurrentFrameId()100%11100%
get_CurrentMaxId()100%11100%
get_MaxConfidence()100%11100%
get_DepthScale()100%210%
set_DepthScale(...)100%44100%
get_InteractionsFramesCache()100%11100%
Reset()100%11100%
UpdateFilterType(...)100%1515100%
Update(...)100%11100%
Update(...)100%11100%
Update(...)83.33%323088.09%
OutputAt(...)81.25%161695.65%
UpdateInteractionFramesList()100%2269.23%
UpdateCachedFrame(...)0%7280%
SmoothInteraction(...)90.9%222293.54%
MapClosestInteraction(...)100%3030100%
IsExpired(...)100%22100%
DecayConfidence(...)100%11100%
Predict(...)100%44100%
GetVelocities(...)100%88100%
AssignMaxId(...)100%11100%

File(s)

D:\a\reflex\reflex\library\src\Core\Interactivity\Components\InteractionSmoothingBehaviour.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.Diagnostics;
 4using System.Linq;
 5using NLog;
 6using ReFlex.Core.Common.Components;
 7using ReFlex.Core.Common.Util;
 8using ReFlex.Core.Filtering.Components;
 9using ReFlex.Core.Interactivity.Util;
 10using Math = System.Math;
 11
 12namespace ReFlex.Core.Interactivity.Components
 13{
 14    public class InteractionSmoothingBehaviour
 15    {
 216        private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
 17
 18        #region Fields
 19
 68820        private List<InteractionFrame> _interactionFrames = new List<InteractionFrame>();
 21
 22        private sealed class Track
 23        {
 1839824            public Interaction LastMeasurement { get; set; }
 1356225            public List<(double Time, Interaction Measurement)> Samples { get; } = new();
 360626            public Interaction Smoothed { get; set; }
 60027            public ButterworthFilter Butterworth { get; set; }
 1619628            public int LastSeenFrame { get; set; }
 770029            public double LastSeenTime { get; set; }
 891430            public double LastDetectedAt { get; set; }
 417231            public double ConfidenceUpdatedAt { get; set; }
 937432            public float Confidence { get; set; }
 960433            public Point3 MatchingPosition { get; set; }
 34        }
 35
 68836        private readonly Dictionary<int, Track> _tracks = new();
 37        private int _numFramesHistory;
 38        private int _numFramesSmoothing;
 68839        private int _requestedNumFramesForPrediction = 3;
 68840        private float _secondDerivationMagnitude = .5f;
 68841        private double _contactRetentionSeconds = .1;
 42
 43        private double? _timestampSeconds;
 44        private double? _processedTimestampSeconds;
 45        private double? _observationTimeoutSeconds;
 68846        private double _predictionHorizonSeconds = .05;
 68847        private float _confidenceDecayPerSecond = 30;
 68848        private float _confidenceGainPerSecond = 30;
 49        public const float DefaultAssignmentMissCost = .5f;
 50        public const float DefaultAssignmentBirthCost = .5f;
 68851        private float _assignmentMissCost = DefaultAssignmentMissCost;
 68852        private float _assignmentBirthCost = DefaultAssignmentBirthCost;
 68853        private int _frameId = 0;
 68854        private int _maxTouchId = 0;
 68855        private FilterType _type = FilterType.None;
 56        private IPointFilter _filter;
 57
 68858        private float _depthScale = 500f;
 59
 60        #endregion
 61
 62        #region Properties
 63
 64        /// <summary>
 65        /// Strict Manhattan-distance gate in sensor pixels. The legacy helper named
 66        /// Point3.Squared2DDistance computes |dx| + |dy|, not squared Euclidean distance.
 67        /// </summary>
 393068        public float TouchMergeDistance2D { get; set; } = 64f;
 69
 70        /// <summary>Use global minimum-cost assignment; false restores greedy one-to-one matching.
 71        /// Changing this strategy preserves all existing contact state and history.</summary>
 305872        public bool UseMinimumCostAssignment { get; set; } = true;
 73
 74        /// <summary>Cost of leaving a live track unmatched for one observation. Distances are
 75        /// normalized by TouchMergeDistance2D; this does not change retention or confidence.</summary>
 76        public float AssignmentMissCost
 77        {
 384278            get => _assignmentMissCost;
 28879            set => _assignmentMissCost = float.IsFinite(value) && value >= 0
 28880                ? value : throw new ArgumentOutOfRangeException(nameof(value));
 81        }
 82
 83        /// <summary>Cost of starting a new track, in the same normalized units as AssignmentMissCost.</summary>
 84        public float AssignmentBirthCost
 85        {
 365086            get => _assignmentBirthCost;
 29087            set => _assignmentBirthCost = float.IsFinite(value) && value >= 0
 29088                ? value : throw new ArgumentOutOfRangeException(nameof(value));
 89        }
 90
 91        /// <summary>Maximum stored frames; zero disables tracking and smoothing.</summary>
 92        public int NumFramesHistory
 93        {
 1234694            get => _numFramesHistory;
 95            set
 83496            {
 83497                _numFramesHistory = Math.Max(0, value);
 83498                NumFramesSmoothing = _numFramesSmoothing;
 83499                UpdateInteractionFramesList();
 834100                if (_numFramesHistory == 0)
 26101                    _tracks.Clear();
 834102                UpdateFilterType(_type);
 834103            }
 104        }
 105
 106        public int NumFramesSmoothing
 107        {
 6442108            get => _numFramesSmoothing;
 109            set
 1388110            {
 1388111                var bounded = Math.Clamp(value, 0, NumFramesHistory);
 1388112                if (_numFramesSmoothing != bounded)
 1554113                    foreach (var track in _tracks.Values) track.Butterworth = null;
 1388114                _numFramesSmoothing = bounded;
 1388115                UpdateFilterType(_type);
 1388116            }
 117        }
 118
 119        private static double ValidateContactRetention(double value) =>
 1064120            double.IsFinite(value) && value >= 0 ? value :
 1064121                throw new ArgumentOutOfRangeException(nameof(value), "Contact retention must be finite and non-negative 
 122
 123        /// <summary>Maximum elapsed seconds since the last measurement, inclusive; independent of history capacity.</su
 124        public double ContactRetentionSeconds
 125        {
 5622126            get => _contactRetentionSeconds;
 750127            set => _contactRetentionSeconds = ValidateContactRetention(value);
 128        }
 129
 130        /// <summary>Timeout without a completed sensor observation. Standalone callers retain the
 131        /// legacy retention deadline unless they explicitly configure a separate observation timeout.</summary>
 132        public double ObservationTimeoutSeconds
 133        {
 5392134            get => _observationTimeoutSeconds ?? ContactRetentionSeconds;
 314135            set => _observationTimeoutSeconds = ValidateContactRetention(value);
 136        }
 137
 2826138        public bool UseVelocityForMapping { get; set; }
 2546139        public bool UseSecondDerivation { get; set; }
 140        /// <summary>Effective sample capacity. Preserve the requested value so history growth restores it.</summary>
 141        public int NumFramesForPrediction
 142        {
 4156143            get => Math.Min(_requestedNumFramesForPrediction, NumFramesHistory);
 154144            set => _requestedNumFramesForPrediction = Math.Max(2, value);
 145        }
 146        public float SecondDerivationMagnitude
 147        {
 1226148            get => _secondDerivationMagnitude;
 56149            set => _secondDerivationMagnitude = float.IsFinite(value) && value >= 0 && value <= 1
 56150                ? value : throw new ArgumentOutOfRangeException(nameof(value));
 151        }
 152
 153        /// <summary>Explicit diagnostic forecast horizon; matching always uses the actual frame time.</summary>
 154        public double PredictionHorizonSeconds
 155        {
 792156            get => _predictionHorizonSeconds;
 144157            set => _predictionHorizonSeconds = double.IsFinite(value) && value >= 0 && value <= 1
 144158                ? value : throw new ArgumentOutOfRangeException(nameof(value));
 159        }
 160
 161        /// <summary>Loss of confidence per second without measurements; zero disables decay.</summary>
 162        public float ConfidenceDecayPerSecond
 163        {
 750164            get => _confidenceDecayPerSecond;
 102165            set => _confidenceDecayPerSecond = float.IsFinite(value) && value >= 0
 102166                ? value : throw new ArgumentOutOfRangeException(nameof(value));
 167        }
 168
 169        /// <summary>Confirmation gained per observed second; missing intervals never earn confidence.</summary>
 170        public float ConfidenceGainPerSecond
 171        {
 1806172            get => _confidenceGainPerSecond;
 84173            set => _confidenceGainPerSecond = float.IsFinite(value) && value >= 0
 84174                ? value : throw new ArgumentOutOfRangeException(nameof(value));
 175        }
 176
 792177        public int CurrentFrameId => _frameId;
 508178        public int CurrentMaxId => _maxTouchId;
 179
 180        /// <summary>Saturation ceiling only. Reaching it never ends a measured contact.</summary>
 4064181        public int MaxConfidence { get; set; }
 182
 183        public float DepthScale
 184        {
 0185            get => _depthScale;
 332186            set => _depthScale = float.IsFinite(value) && value > 0
 332187                ? value : throw new ArgumentOutOfRangeException(nameof(value), "Depth scale must be finite and positive.
 188        }
 189
 2194190        public InteractionFrame[] InteractionsFramesCache => _interactionFrames
 20870191            .Select(frame => new InteractionFrame(frame.FrameId,
 47686192                frame.Interactions.Select(interaction => new Interaction(interaction)).ToList(), frame.TimestampSeconds)
 193
 194        #endregion
 195
 196        #region Constructor
 197
 688198        public InteractionSmoothingBehaviour(int numFramesHistory)
 688199        {
 688200            NumFramesHistory = numFramesHistory;
 688201        }
 202
 203        #endregion
 204
 205        #region public Methods
 206
 207        public void Reset()
 14208        {
 14209            _frameId = 0;
 14210            _timestampSeconds = null;
 14211            _processedTimestampSeconds = null;
 14212            _maxTouchId = 0;
 14213            _interactionFrames.Clear();
 14214            _tracks.Clear();
 14215        }
 216
 217        public void UpdateFilterType(FilterType type)
 2640218        {
 2640219            if (_type != type)
 210220                foreach (var track in _tracks.Values) track.Butterworth = null;
 2640221            _type = type;
 222
 2640223            switch (type)
 224            {
 225                case FilterType.MovingAverage:
 46226                    _filter = new SimpleMovingAverageFilter(Math.Max(1, NumFramesSmoothing));
 46227                    break;
 228                case FilterType.WeightedMovingAverage:
 14229                    _filter = new WeightedMovingAverageFilter(Math.Max(1, NumFramesSmoothing));
 14230                    break;
 231                case FilterType.PolynomialFit:
 6232                    _filter = new PolynomialFitFilter();
 6233                    break;
 234                case FilterType.WeightedPolynomialFit:
 2235                    _filter = new WeightedPolynomialFitFilter();
 2236                    break;
 237                case FilterType.SavitzkyGolay:
 16238                {
 16239                    var sidePoints = Math.Max(0, (NumFramesSmoothing - 1) / 2);
 16240                    var order = Math.Min(sidePoints, 3);
 16241                    _filter = new SavitzkyGolayFilter(sidePoints, order);
 16242                    break;
 243                }
 244                case FilterType.Butterworth:
 8245                    _filter = new ButterworthFilter();
 8246                    break;
 247                default:
 2548248                    _filter = null;
 2548249                    break;
 250            }
 251
 2640252            Logger.Info($"switched Interaction Processing Smoothing Filter to {_filter?.GetType().FullName ?? "None\""}"
 2640253        }
 254
 255        public InteractionFrame Update(IList<Interaction> rawInteractions) =>
 12256            Update(rawInteractions, (double)Stopwatch.GetTimestamp() / Stopwatch.Frequency);
 257
 258        /// <summary>
 259        /// Process one observation frame at a strictly increasing monotonic timestamp in seconds.
 260        /// Callers with capture timestamps may supply them here. Invalid times are rejected before
 261        /// mutating tracking state; Interaction.Time remains the legacy wall-clock field.
 262        /// </summary>
 263        public InteractionFrame Update(IList<Interaction> rawInteractions, double timestampSeconds)
 2084264            => Update(rawInteractions, timestampSeconds, timestampSeconds);
 265
 266        /// <summary>Motion uses capture time; liveness and confidence decay use completion time.
 267        /// Slow but continuously successful observations must not look like missing detections.</summary>
 268        public InteractionFrame Update(IList<Interaction> rawInteractions, double timestampSeconds, double processedTime
 2304269        {
 2304270            if (!double.IsFinite(timestampSeconds) ||
 2304271                (_timestampSeconds.HasValue && timestampSeconds <= _timestampSeconds.Value))
 8272                throw new ArgumentOutOfRangeException(nameof(timestampSeconds), "Frame times must be finite and strictly
 2296273            if (!double.IsFinite(processedTimestampSeconds) || processedTimestampSeconds < timestampSeconds ||
 2296274                (_processedTimestampSeconds.HasValue && processedTimestampSeconds < _processedTimestampSeconds.Value))
 0275                throw new ArgumentOutOfRangeException(nameof(processedTimestampSeconds));
 2296276            _timestampSeconds = timestampSeconds;
 2296277            _processedTimestampSeconds = processedTimestampSeconds;
 2296278            _frameId++;
 279
 280            // Only internal copies are assigned IDs or retained in the tracking history.
 5214281            var candidates = rawInteractions.Take(20).Select(item => new Interaction(item)).ToList();
 2296282            var mappedInteractionIds = MapClosestInteraction(candidates);
 2296283            var newFrame = new InteractionFrame(_frameId, mappedInteractionIds, timestampSeconds);
 284
 285            // With history disabled, still publish current measurements, using fresh IDs each frame.
 2296286            if (NumFramesHistory == 0)
 32287            {
 32288                _tracks.Clear();
 32289                return newFrame;
 290            }
 291
 2264292            _interactionFrames.Add(newFrame);
 2264293            UpdateInteractionFramesList();
 2264294            var result = new InteractionFrame(_frameId, timestampSeconds);
 15464295            foreach (var pair in _tracks.OrderBy(pair => pair.Key).ToArray())
 3382296            {
 3382297                var missingFrames = _frameId - pair.Value.LastSeenFrame;
 3382298                if (IsExpired(pair.Value, processedTimestampSeconds, _frameId))
 0299                {
 300                    // Ended tracks are removed permanently, even while their measurements remain cached.
 0301                    _tracks.Remove(pair.Key);
 0302                    continue;
 303                }
 304
 3382305                var smoothed = missingFrames == 0 ? SmoothInteraction(pair.Key)
 3382306                    : new Interaction(pair.Value.Smoothed ?? pair.Value.LastMeasurement);
 6272307                if (missingFrames == 0) pair.Value.Smoothed = new Interaction(smoothed);
 3382308                if (smoothed == null)
 0309                    continue;
 3382310                if (missingFrames > 0)
 492311                {
 492312                    DecayConfidence(pair.Value, processedTimestampSeconds);
 492313                    smoothed.TrackingState = InteractionTrackingState.Lost;
 492314                }
 3382315                smoothed.Confidence = pair.Value.Confidence;
 3382316                result.Interactions.Add(smoothed);
 3382317            }
 318
 2264319            return result;
 2296320        }
 321
 322        /// <summary>Age publication without inventing a sensor observation or changing the measured
 323        /// sample clock. Expiry is permanent; confidence during sensor gaps is projected from live state.</summary>
 324        public InteractionFrame OutputAt(double timestampSeconds, bool markLost = true)
 264325        {
 264326            if (!double.IsFinite(timestampSeconds) || (_processedTimestampSeconds.HasValue && timestampSeconds < _proces
 0327                throw new ArgumentOutOfRangeException(nameof(timestampSeconds));
 264328            var output = new InteractionFrame(_frameId, timestampSeconds);
 1276329            foreach (var pair in _tracks.OrderBy(pair => pair.Key).ToArray())
 242330            {
 242331                var track = pair.Value;
 242332                if (IsExpired(track, timestampSeconds, _frameId))
 18333                {
 18334                    _tracks.Remove(pair.Key);
 18335                    continue;
 336                }
 224337                var item = new Interaction(track.Smoothed ?? track.LastMeasurement);
 224338                if (markLost || track.LastSeenFrame != _frameId)
 222339                {
 222340                    item.TrackingState = InteractionTrackingState.Lost;
 222341                    item.Confidence = Math.Max(0, track.Confidence - (float)(ConfidenceDecayPerSecond *
 222342                        (timestampSeconds - track.ConfidenceUpdatedAt)));
 222343                }
 2344                else item.Confidence = track.Confidence;
 224345                output.Interactions.Add(item);
 224346            }
 264347            return output;
 264348        }
 349
 350        #endregion
 351
 352        /// <summary>
 353        /// order list of frames by frame id descending and remove old frames
 354        /// </summary>
 355        private void UpdateInteractionFramesList()
 3098356        {
 3098357            if (_interactionFrames.Count > NumFramesHistory)
 908358            {
 359                try
 908360                {
 12032361                    _interactionFrames = _interactionFrames.OrderByDescending(frame => frame.FrameId)
 908362                        .Take(NumFramesHistory).ToList();
 908363                }
 0364                catch (Exception e)
 0365                {
 0366                    Logger.Error(e, $"Exception catched in {GetType()}.{nameof(this.UpdateInteractionFramesList)}.");
 0367                }
 368
 908369            }
 3098370        }
 371
 372        /// <summary>
 373        /// replaces the frame in the cache with the updated frame (if FrameId is existing, otherwise, nothing is change
 374        /// </summary>
 375        /// <param name="updatedFrame">Frame containing updated values</param>
 376        public void UpdateCachedFrame(InteractionFrame updatedFrame)
 0377        {
 0378          var frameIdxToBeReplaced = _interactionFrames.FindIndex((f) => f.FrameId == updatedFrame.FrameId);
 0379          if (frameIdxToBeReplaced < 0)
 0380            return;
 381
 382          // _interactionFrames[frameIdxToBeReplaced] = updatedFrame;
 0383          _interactionFrames[frameIdxToBeReplaced].Interactions.ForEach((interaction) =>
 0384          {
 0385            var updatedInteraction =
 0386              updatedFrame.Interactions.FirstOrDefault((update) => update.TouchId == interaction.TouchId);
 0387            if (updatedInteraction != null)
 0388            {
 0389              interaction.Confidence = updatedInteraction.Confidence;
 0390              if (_tracks.TryGetValue(interaction.TouchId, out var track) && track.LastSeenFrame == updatedFrame.FrameId
 0391                  track.Confidence = Math.Clamp(updatedInteraction.Confidence, 0, Math.Max(0, MaxConfidence));
 0392              interaction.ExtremumDescription = new Interaction(updatedInteraction).ExtremumDescription;
 0393
 0394            }
 0395          });
 0396        }
 397
 398        /// <summary>
 399        /// Apply smoothing according to chosen filter type.
 400        /// Extracts touches of a given id from frames history and  sends them to smoothing algorithm
 401        /// </summary>
 402        /// <param name="touchId">the id of the touch, which should be smoothed</param>
 403        /// <returns>Interaction (last entry in history) with smoothed position</returns>
 404        private Interaction SmoothInteraction(int touchId)
 2890405        {
 2890406            var track = _tracks[touchId];
 407            // A type transition starts a new smoothing segment; motion in XY may remain continuous.
 2890408            var samples = track.Samples.AsEnumerable().Reverse()
 10364409                .TakeWhile(sample => sample.Measurement.Type == track.LastMeasurement.Type).Reverse().ToArray();
 10362410            var interactionsHistory = samples.Select(sample => new Interaction(sample.Measurement)).ToList();
 2890411            var smooth = new Interaction(track.LastMeasurement);
 2890412            if (_type == FilterType.Butterworth && NumFramesSmoothing > 0)
 286413            {
 286414                track.Butterworth ??= new ButterworthFilter();
 286415                smooth.Position = track.Butterworth.ProcessSample(track.LastMeasurement.Position, track.LastSeenTime);
 286416                if (Math.Sign(smooth.Position.Z) != Math.Sign(track.LastMeasurement.Position.Z))
 0417                    smooth.Position.Z = track.LastMeasurement.Position.Z;
 286418                return smooth;
 419            }
 420
 8690421            var raw = interactionsHistory.Select(interaction => interaction.Position).ToList();
 422
 2604423            if (NumFramesSmoothing > 0 &&
 2604424                smooth != null && raw.Count >= NumFramesSmoothing &&
 2604425                _type != FilterType.None && _filter != null)
 140426            {
 820427                var framesForSmoothing = raw.TakeLast(NumFramesSmoothing).Select(point => new Point3(point)).ToList();
 820428                framesForSmoothing.ForEach(p => p.Z *= _depthScale);
 820429                var timestamps = samples.Select(sample => sample.Time).TakeLast(NumFramesSmoothing).ToArray();
 140430                var filtered = _filter is Base2DFilter temporalFilter
 140431                    ? temporalFilter.Process(framesForSmoothing, timestamps)
 140432                    : _filter.Process(framesForSmoothing);
 140433                smooth.Position = new Point3(filtered.Last());
 140434                smooth.Position.Z /= _depthScale;
 140435                if (Math.Sign(smooth.Position.Z) != Math.Sign(track.LastMeasurement.Position.Z))
 0436                    smooth.Position.Z = track.LastMeasurement.Position.Z;
 140437            }
 438
 2604439            return smooth;
 2890440        }
 441
 442
 443
 444        /// <summary>
 445        /// One-to-one assignment to forecasts using the selected minimum-cost or legacy greedy strategy.
 446        /// A candidate and a track may each participate in only one pair. Unmatched candidates
 447        /// start new tracks; unmatched tracks may bridge the configured elapsed time.
 448        /// With prediction disabled or insufficient samples, falls back to the last measurement.
 449        /// </summary>
 450        private List<Interaction> MapClosestInteraction(List<Interaction> candidates)
 2296451        {
 452            // Explicitly missing detections use contact retention. A sensor/processing gap uses
 453            // its separate timeout, measured since the last successful completion, not capture.
 7012454            foreach (var id in _tracks.Where(pair =>
 2372455                         IsExpired(pair.Value, _processedTimestampSeconds.Value, _frameId - 1))
 2358456                     .Select(pair => pair.Key).ToArray())
 62457                _tracks.Remove(id);
 458
 12724459            foreach (var candidate in candidates)
 2918460                candidate.TouchId = -1;
 461
 11508462            foreach (var track in _tracks.Values)
 2310463                track.MatchingPosition = Predict(track, _timestampSeconds.Value);
 464
 4606465            var targets = _tracks.Select(pair => (TouchId: pair.Key, Position: pair.Value.MatchingPosition)).ToArray();
 2296466            var assignedIds = UseMinimumCostAssignment
 2296467                ? MinimumCostContactAssignment.Assign(candidates, targets, TouchMergeDistance2D, AssignmentMissCost, Ass
 2296468                : GreedyContactAssignment.Assign(candidates, targets, TouchMergeDistance2D);
 10428469            for (var index = 0; index < candidates.Count; index++)
 2918470            {
 2918471                var touchId = assignedIds[index];
 2918472                if (touchId < 0)
 1100473                    continue;
 1818474                var candidate = candidates[index];
 1818475                candidate.TouchId = touchId;
 1818476                candidate.TrackingState = InteractionTrackingState.Confirmed;
 1818477                var track = _tracks[touchId];
 478                // Continue decay through the last lost interval before recovering. A new detection
 479                // gains confidence only over continuously observed intervals, never over a lost interval.
 1818480                if (track.LastSeenFrame < _frameId - 1)
 24481                    DecayConfidence(track, _processedTimestampSeconds.Value);
 1818482                var gain = track.LastSeenFrame == _frameId - 1
 1818483                    ? ConfidenceGainPerSecond * (_timestampSeconds.Value - track.LastSeenTime) : 0;
 1818484                candidate.Confidence = (float)Math.Min(track.Confidence + gain, Math.Max(0, MaxConfidence));
 1818485            }
 486
 12724487            foreach (var candidate in candidates)
 2918488            {
 2918489                if (candidate.TouchId < 0)
 1100490                {
 1100491                    AssignMaxId(candidate);
 1100492                    candidate.TrackingState = InteractionTrackingState.Tentative;
 1100493                    candidate.Confidence = Math.Clamp(candidate.Confidence, 0, Math.Max(0, MaxConfidence));
 1100494                }
 2918495                var matchingPosition = _tracks.TryGetValue(candidate.TouchId, out var previous)
 2918496                    ? previous.MatchingPosition : candidate.Position;
 2918497                var current = previous ?? new Track();
 2918498                if (previous != null && previous.LastMeasurement.Type != candidate.Type)
 2499                    current.Butterworth = null;
 2918500                current.LastMeasurement = candidate;
 2918501                current.LastSeenFrame = _frameId;
 2918502                current.LastSeenTime = _timestampSeconds.Value;
 2918503                current.LastDetectedAt = _processedTimestampSeconds.Value;
 2918504                current.Confidence = candidate.Confidence;
 2918505                current.ConfidenceUpdatedAt = _processedTimestampSeconds.Value;
 2918506                current.MatchingPosition = (Point3)matchingPosition.Copy();
 2918507                current.Samples.Add((_timestampSeconds.Value, new Interaction(candidate)));
 2918508                var capacity = Math.Max(1, Math.Max(NumFramesSmoothing, NumFramesForPrediction));
 2918509                if (current.Samples.Count > capacity)
 1258510                    current.Samples.RemoveRange(0, current.Samples.Count - capacity);
 2918511                _tracks[candidate.TouchId] = current;
 2918512            }
 3720513            return candidates.OrderBy(candidate => candidate.TouchId).ToList();
 2296514        }
 515
 516        private bool IsExpired(Track track, double now, int latestObservationFrame)
 5996517            => now > track.LastDetectedAt + (track.LastSeenFrame == latestObservationFrame
 5996518                ? ObservationTimeoutSeconds : ContactRetentionSeconds);
 519
 520        private void DecayConfidence(Track track, double timestampSeconds)
 516521        {
 516522            track.Confidence = Math.Max(0, track.Confidence - (float)(ConfidenceDecayPerSecond *
 516523                (timestampSeconds - track.ConfidenceUpdatedAt)));
 516524            track.ConfidenceUpdatedAt = timestampSeconds;
 516525        }
 526
 527        private Point3 Predict(Track track, double targetTime)
 2324528        {
 2324529            if (!UseVelocityForMapping)
 1366530                return (Point3)track.LastMeasurement.Position.Copy();
 958531            var motion = ContactMotion.Estimate(track.Samples, track.LastSeenTime, NumFramesForPrediction, UseSecondDeri
 958532            var forecast = ContactMotion.Forecast(track.LastMeasurement.Position, motion,
 958533                SecondDerivationMagnitude, (float)(targetTime - track.LastSeenTime));
 958534            return UseSecondDerivation ? forecast.PredictedPositionAdvanced : forecast.PredictedPositionBasic;
 2324535        }
 536
 537        /// <summary>
 538        /// Atomic diagnostics for this output frame. Positions use the uncalibrated sensor raster;
 539        /// forecasts have an explicit time horizon, matching positions were used at this frame timestamp.
 540        /// Never combines asynchronously delivered interaction/velocity messages in the frontend.
 541        /// </summary>
 542        public List<InteractionVelocity> GetVelocities(InteractionFrame output)
 318543        {
 318544            var result = new List<InteractionVelocity>();
 318545            if (!UseVelocityForMapping)
 90546                return result;
 1212547            foreach (var interaction in output.Interactions)
 264548            {
 264549                if (!_tracks.TryGetValue(interaction.TouchId, out var track))
 2550                    continue;
 262551                var motion = ContactMotion.Estimate(track.Samples, track.LastSeenTime, NumFramesForPrediction, UseSecond
 262552                var item = ContactMotion.Forecast(track.LastMeasurement.Position, motion,
 262553                    SecondDerivationMagnitude, (float)(output.TimestampSeconds + PredictionHorizonSeconds - track.LastSe
 262554                item.TouchId = interaction.TouchId;
 262555                item.FrameId = _frameId;
 262556                item.LastMeasuredFrameId = track.LastSeenFrame;
 262557                item.TimestampSeconds = output.TimestampSeconds;
 262558                item.LastMeasuredTimestampSeconds = track.LastSeenTime;
 262559                item.PredictionTimestampSeconds = output.TimestampSeconds + PredictionHorizonSeconds;
 262560                item.PredictionHorizonSeconds = PredictionHorizonSeconds;
 262561                item.Confidence = interaction.Confidence;
 262562                item.SampleCount = motion.Count;
 262563                item.IsPredicted = interaction.TrackingState == InteractionTrackingState.Lost;
 262564                item.UseSecondDerivation = UseSecondDerivation;
 262565                item.SmoothedPosition = (Point3)interaction.Position.Copy();
 262566                item.MatchingPosition = !item.IsPredicted
 262567                    ? (Point3)track.MatchingPosition.Copy() : Predict(track, output.TimestampSeconds);
 262568                result.Add(item);
 262569            }
 228570            return result;
 318571        }
 572
 573        /// <summary>
 574        /// Assigns a new id to the given point and increments current maximum touch id.
 575        /// </summary>
 576        /// <param name="interaction">the touch point which should get a new unique id</param>
 577        private void AssignMaxId(Interaction interaction)
 1100578        {
 1100579            interaction.TouchId = _maxTouchId;
 1100580            _maxTouchId++;
 1100581        }
 582
 583    }
 584}

Methods/Properties

.cctor()
.ctor(System.Int32)
get_LastMeasurement()
get_Samples()
get_Smoothed()
get_Butterworth()
get_LastSeenFrame()
get_LastSeenTime()
get_LastDetectedAt()
get_ConfidenceUpdatedAt()
get_Confidence()
get_MatchingPosition()
get_TouchMergeDistance2D()
get_UseMinimumCostAssignment()
get_AssignmentMissCost()
set_AssignmentMissCost(System.Single)
get_AssignmentBirthCost()
set_AssignmentBirthCost(System.Single)
get_NumFramesHistory()
set_NumFramesHistory(System.Int32)
get_NumFramesSmoothing()
set_NumFramesSmoothing(System.Int32)
ValidateContactRetention(System.Double)
get_ContactRetentionSeconds()
set_ContactRetentionSeconds(System.Double)
get_ObservationTimeoutSeconds()
set_ObservationTimeoutSeconds(System.Double)
get_UseVelocityForMapping()
get_UseSecondDerivation()
get_NumFramesForPrediction()
set_NumFramesForPrediction(System.Int32)
get_SecondDerivationMagnitude()
set_SecondDerivationMagnitude(System.Single)
get_PredictionHorizonSeconds()
set_PredictionHorizonSeconds(System.Double)
get_ConfidenceDecayPerSecond()
set_ConfidenceDecayPerSecond(System.Single)
get_ConfidenceGainPerSecond()
set_ConfidenceGainPerSecond(System.Single)
get_CurrentFrameId()
get_CurrentMaxId()
get_MaxConfidence()
get_DepthScale()
set_DepthScale(System.Single)
get_InteractionsFramesCache()
Reset()
UpdateFilterType(ReFlex.Core.Interactivity.Util.FilterType)
Update(System.Collections.Generic.IList`1<ReFlex.Core.Common.Components.Interaction>)
Update(System.Collections.Generic.IList`1<ReFlex.Core.Common.Components.Interaction>,System.Double)
Update(System.Collections.Generic.IList`1<ReFlex.Core.Common.Components.Interaction>,System.Double,System.Double)
OutputAt(System.Double,System.Boolean)
UpdateInteractionFramesList()
UpdateCachedFrame(ReFlex.Core.Common.Components.InteractionFrame)
SmoothInteraction(System.Int32)
MapClosestInteraction(System.Collections.Generic.List`1<ReFlex.Core.Common.Components.Interaction>)
IsExpired(ReFlex.Core.Interactivity.Components.InteractionSmoothingBehaviour/Track,System.Double,System.Int32)
DecayConfidence(ReFlex.Core.Interactivity.Components.InteractionSmoothingBehaviour/Track,System.Double)
Predict(ReFlex.Core.Interactivity.Components.InteractionSmoothingBehaviour/Track,System.Double)
GetVelocities(ReFlex.Core.Common.Components.InteractionFrame)
AssignMaxId(ReFlex.Core.Common.Components.Interaction)