< Summary - ReFlex - Library

Information
Class: ReFlex.Core.Interactivity.Components.InteractionObserverBase
Assembly: ReFlex.Core.Interactivity
File(s): D:\a\reflex\reflex\library\src\Core\Interactivity\Components\InteractionObserverBase.cs
Line coverage
94%
Covered lines: 396
Uncovered lines: 25
Coverable lines: 421
Total lines: 771
Line coverage: 94%
Branch coverage
82%
Covered branches: 126
Total branches: 153
Branch coverage: 82.3%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor()100%11100%
get_Distance()100%11100%
get_MinDistance()100%11100%
get_MaxDistance()100%11100%
get_ExtremumTypeCheckNumSamples()100%11100%
set_ExtremumTypeCheckNumSamples(...)100%22100%
get_ExtremumTypeCheckRadius()100%11100%
set_ExtremumTypeCheckRadius(...)100%22100%
get_ExtremumTypeCheckFittingPercentage()100%11100%
get_ExtremumTypeCheckMethod()100%11100%
get_ExtremumMergeRadius()100%11100%
set_ExtremumMergeRadius(...)100%11100%
get_PredictionHorizonSeconds()100%11100%
set_PredictionHorizonSeconds(...)100%11100%
get_UseVelocityPrediction()100%11100%
set_UseVelocityPrediction(...)100%11100%
get_NumFramesForPrediction()100%11100%
set_NumFramesForPrediction(...)100%11100%
get_UseSecondDerivation()100%11100%
set_UseSecondDerivation(...)100%11100%
get_SecondDerivationMagnitude()100%11100%
set_SecondDerivationMagnitude(...)100%11100%
get_InteractionHistorySize()100%22100%
set_InteractionHistorySize(...)100%22100%
get_NumSmoothingFrames()50%22100%
set_NumSmoothingFrames(...)100%22100%
ValidateContactRetention(...)100%44100%
get_UseMinimumCostAssignment()100%11100%
set_UseMinimumCostAssignment(...)100%11100%
get_AssignmentMissCost()100%11100%
set_AssignmentMissCost(...)100%11100%
get_AssignmentBirthCost()100%11100%
set_AssignmentBirthCost(...)100%11100%
get_ConfidenceGainPerSecond()100%11100%
set_ConfidenceGainPerSecond(...)100%11100%
get_ConfidenceDecayPerSecond()100%11100%
set_ConfidenceDecayPerSecond(...)100%11100%
get_ContactRetentionSeconds()50%22100%
set_ContactRetentionSeconds(...)100%22100%
get_ObservationTimeoutSeconds()100%11100%
set_ObservationTimeoutSeconds(...)100%11100%
get_TouchMergeDistance2D()100%11100%
set_TouchMergeDistance2D(...)100%22100%
get_DepthScale()100%210%
set_DepthScale(...)100%22100%
get_FilterType()100%11100%
set_FilterType(...)100%22100%
get_MinAngle()100%11100%
get_MinConfidence()100%11100%
get_MaxConfidence()100%11100%
set_MaxConfidence(...)100%22100%
get_MeasurePerformance()100%11100%
get_FrameId()100%11100%
UpdateFrameId(...)100%210%
ReportPerformance(...)100%210%
CheckInitialState()100%11100%
Update()100%11100%
AdvanceTime(...)100%11100%
Publish(...)75%1212100%
Update()100%2626100%
SelectSmoothedInteractions(...)100%11100%
ConsolidateExtrema(...)100%11100%
GetTimestampSeconds()100%11100%
ComputeSmoothingValue(...)75%44100%
ComputeExtremumType(...)93.93%333398.24%
ConvertDepthValue(...)85%212086.66%
ApplyConfidenceFilter(...)100%11100%
ComputeExtremumType(...)100%11100%
RemoveExtremumsBetweenTouches(...)75%88100%
UpdatePerformanceMetrics(...)100%22100%
OnNewInteractions(...)100%22100%
CalculateAverageDistance()0%110100%
GetSample(...)100%11100%
GenerateSamples()100%22100%
UpdateSamples()100%22100%

File(s)

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

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.Diagnostics;
 4using System.Linq;
 5using System.Threading.Tasks;
 6using ReFlex.Core.Common.Components;
 7using ReFlex.Core.Common.Interfaces;
 8using ReFlex.Core.Common.Util;
 9using ReFlex.Core.Interactivity.Interfaces;
 10using ReFlex.Core.Interactivity.Util;
 11using Math = System.Math;
 12
 13namespace ReFlex.Core.Interactivity.Components
 14{
 15    public abstract class InteractionObserverBase : IInteractionObserver, IPerformanceReporter
 16    {
 17        #region Fields
 18
 25819        private readonly Stopwatch _stopWatch = new();
 20
 21        // Configuration access shares the frame/publication lock. Never hold it across Analyze awaits.
 25822        private readonly object _trackingSync = new();
 23        private readonly InteractionSmoothingBehaviour _smoothingBehaviour;
 25824        private int _numSmoothingFrames = 5;
 25825        private int _historySize = 25;
 25826        private double _contactRetentionSeconds = .1;
 25827        private float _touchMergeDistance2d = 64f;
 25828        private float _depthScale = 100.0f;
 29        private FilterType _filterType;
 30        private float _maxConfidence;
 25831        private float _extremumMergeRadius = ExtremumConsolidator.DefaultRadius;
 32        private int _extremumTypeCheckRadius;
 33        private int _extremumTypeCheckNumSamples;
 34
 25835        private Tuple<int, int>[] _fixedSamples = Array.Empty<Tuple<int, int>>();
 25836        private Tuple<int, int>[] _stochasticSamples = Array.Empty<Tuple<int, int>>();
 37
 38        #endregion
 39
 40        #region Properties
 41
 42        /// <summary>
 43        /// Gets or sets the distance.
 44        /// </summary>
 45        /// <value>
 46        /// The distance.
 47        /// </value>
 208848        public float Distance { get; set; }
 49
 50        /// <summary>
 51        /// Gets or sets the minimum depth.
 52        /// </summary>
 53        /// <value>
 54        /// The maximum depth.
 55        /// </value>
 126656        public float MinDistance { get; set; }
 57
 58        /// <summary>
 59        /// Gets or sets the maximum depth.
 60        /// </summary>
 61        /// <value>
 62        /// The maximum depth.
 63        /// </value>
 49064        public float MaxDistance { get; set; }
 65
 66        /// <summary>
 67        /// defines how many points should be checked to determine the type of the extremum
 68        /// </summary>
 69        public int ExtremumTypeCheckNumSamples
 70        {
 57814671            get => _extremumTypeCheckNumSamples;
 72            set
 18673            {
 18674                if (_extremumTypeCheckNumSamples == value)
 2275                    return;
 16476                _extremumTypeCheckNumSamples = value;
 16477                UpdateSamples();
 18678            }
 79        }
 80
 81        /// <summary>
 82        /// The pixel radius in which the points are sampled for deriving the type of the local extremum
 83        /// </summary>
 84        public int ExtremumTypeCheckRadius
 85        {
 33045686            get => _extremumTypeCheckRadius;
 87            set
 18688            {
 18689                if (_extremumTypeCheckRadius == value)
 2090                    return;
 16691                _extremumTypeCheckRadius = value;
 16692                UpdateSamples();
 18693            }
 94        }
 95
 96        /// <summary>
 97        /// Which ratio of "correctly aligned" points should match to distinguish between Undefined or Minimum/Maximum ?
 98        /// </summary>
 35699        public float ExtremumTypeCheckFittingPercentage { get; set; }
 100
 101        /// <summary>
 102        /// Defines how neighboring the points are sampled for determining the type of extremum.
 103        /// </summary>
 834104        public ExtremumTypeCheckMethod ExtremumTypeCheckMethod { get; set; }
 105
 106        /// <summary>Euclidean radius in sensor pixels for consolidating same-type extrema before ID assignment; zero di
 107        public float ExtremumMergeRadius
 108        {
 960109            get { lock (_trackingSync) return _extremumMergeRadius; }
 248110            set { lock (_trackingSync) _extremumMergeRadius = ExtremumConsolidator.ValidateRadius(value); }
 111        }
 112
 113        public double PredictionHorizonSeconds
 114        {
 24115            get { lock (_trackingSync) return _smoothingBehaviour.PredictionHorizonSeconds; }
 224116            set { lock (_trackingSync) _smoothingBehaviour.PredictionHorizonSeconds = value; }
 117        }
 118
 119        public bool UseVelocityPrediction
 120        {
 48121            get { lock (_trackingSync) return _smoothingBehaviour.UseVelocityForMapping; }
 304122            set { lock (_trackingSync) _smoothingBehaviour.UseVelocityForMapping = value; }
 123        }
 124        public int NumFramesForPrediction
 125        {
 24126            get { lock (_trackingSync) return _smoothingBehaviour.NumFramesForPrediction; }
 232127            set { lock (_trackingSync) _smoothingBehaviour.NumFramesForPrediction = value; }
 128        }
 129        public bool UseSecondDerivation
 130        {
 24131            get { lock (_trackingSync) return _smoothingBehaviour.UseSecondDerivation; }
 224132            set { lock (_trackingSync) _smoothingBehaviour.UseSecondDerivation = value; }
 133        }
 134        public float SecondDerivationMagnitude
 135        {
 24136            get { lock (_trackingSync) return _smoothingBehaviour.SecondDerivationMagnitude; }
 224137            set { lock (_trackingSync) _smoothingBehaviour.SecondDerivationMagnitude = value; }
 138        }
 139
 140        public int InteractionHistorySize
 141        {
 3032142            get { lock (_trackingSync) return _smoothingBehaviour?.NumFramesHistory ?? _historySize; }
 143            set
 120144            {
 120145                lock (_trackingSync)
 120146                {
 120147                    _historySize = Math.Max(0, value);
 120148                    if (_smoothingBehaviour != null)
 120149                    {
 120150                        _smoothingBehaviour.NumFramesHistory = _historySize;
 151                        // update depending smoothing/filter values
 120152                        NumSmoothingFrames = _numSmoothingFrames;
 120153                    }
 120154                }
 120155            }
 156        }
 157
 158        public int NumSmoothingFrames
 159        {
 96160            get { lock (_trackingSync) return _smoothingBehaviour?.NumFramesSmoothing ?? _numSmoothingFrames; }
 161            set
 492162            {
 492163                lock (_trackingSync)
 492164                {
 492165                    _numSmoothingFrames = Math.Clamp(value, 0, InteractionHistorySize);
 492166                    if (_smoothingBehaviour != null)
 492167                        _smoothingBehaviour.NumFramesSmoothing = _numSmoothingFrames;
 492168                }
 492169            }
 170        }
 171
 172        private static double ValidateContactRetention(double value) =>
 326173            double.IsFinite(value) && value >= 0 ? value :
 326174                throw new ArgumentOutOfRangeException(nameof(value), "Contact retention must be finite and non-negative 
 175
 176        public bool UseMinimumCostAssignment
 177        {
 24178            get { lock (_trackingSync) return _smoothingBehaviour.UseMinimumCostAssignment; }
 232179            set { lock (_trackingSync) _smoothingBehaviour.UseMinimumCostAssignment = value; }
 180        }
 181
 182        public float AssignmentMissCost
 183        {
 24184            get { lock (_trackingSync) return _smoothingBehaviour.AssignmentMissCost; }
 232185            set { lock (_trackingSync) _smoothingBehaviour.AssignmentMissCost = value; }
 186        }
 187
 188        public float AssignmentBirthCost
 189        {
 32190            get { lock (_trackingSync) return _smoothingBehaviour.AssignmentBirthCost; }
 240191            set { lock (_trackingSync) _smoothingBehaviour.AssignmentBirthCost = value; }
 192        }
 193
 194        public float ConfidenceGainPerSecond
 195        {
 48196            get { lock (_trackingSync) return _smoothingBehaviour.ConfidenceGainPerSecond; }
 242197            set { lock (_trackingSync) _smoothingBehaviour.ConfidenceGainPerSecond = value; }
 198        }
 199        public float ConfidenceDecayPerSecond
 200        {
 48201            get { lock (_trackingSync) return _smoothingBehaviour.ConfidenceDecayPerSecond; }
 242202            set { lock (_trackingSync) _smoothingBehaviour.ConfidenceDecayPerSecond = value; }
 203        }
 204
 205        public double ContactRetentionSeconds
 206        {
 120207            get { lock (_trackingSync) return _smoothingBehaviour?.ContactRetentionSeconds ?? _contactRetentionSeconds; 
 208            set
 326209            {
 326210                lock (_trackingSync)
 326211                {
 326212                    _contactRetentionSeconds = ValidateContactRetention(value);
 320213                    if (_smoothingBehaviour != null)
 320214                        _smoothingBehaviour.ContactRetentionSeconds = _contactRetentionSeconds;
 320215                }
 320216            }
 217        }
 218
 219        /// <summary>Maximum sensor/processing silence and acceptable observation age, in seconds.</summary>
 220        public double ObservationTimeoutSeconds
 221        {
 376222            get { lock (_trackingSync) return _smoothingBehaviour.ObservationTimeoutSeconds; }
 1256223            set { lock (_trackingSync) _smoothingBehaviour.ObservationTimeoutSeconds = value; }
 224        }
 225
 226        public float TouchMergeDistance2D
 227        {
 24228            get { lock (_trackingSync) return _touchMergeDistance2d; }
 229            set
 352230            {
 352231                lock (_trackingSync)
 352232                {
 352233                    _touchMergeDistance2d = value;
 352234                    if (_smoothingBehaviour != null)
 352235                        _smoothingBehaviour.TouchMergeDistance2D = value;
 352236                }
 352237            }
 238        }
 239
 240        public float DepthScale
 241        {
 0242            get { lock (_trackingSync) return _depthScale; }
 243            set
 314244            {
 314245                lock (_trackingSync)
 314246                {
 314247                    if (_smoothingBehaviour != null)
 314248                        _smoothingBehaviour.DepthScale = value;
 314249                    _depthScale = value;
 314250                }
 314251            }
 252        }
 253
 254        public FilterType FilterType
 255        {
 32256            get { lock (_trackingSync) return _filterType; }
 257            set
 356258            {
 356259                lock (_trackingSync)
 356260                {
 356261                    _filterType = value;
 356262                    if (_smoothingBehaviour != null)
 356263                        _smoothingBehaviour.UpdateFilterType(_filterType);
 356264                }
 356265            }
 266        }
 267
 268
 269        /// <summary>
 270        /// Gets or sets the minimum angle.
 271        /// </summary>
 272        /// <value>
 273        /// The minimum angle.
 274        /// </value>
 84275        public virtual float MinAngle { get; set; }
 276
 277        /// <summary>
 278        /// Gets or sets the minimum confidence.
 279        /// </summary>
 280        /// <value>
 281        /// The minimum confidence.
 282        /// </value>
 394283        public virtual float MinConfidence { get; set; }
 284
 285        /// <summary>
 286        /// Gets or sets the maximum confidence.
 287        /// </summary>
 288        /// <value>
 289        /// The maximum confidence.
 290        /// </value>
 291        public virtual float MaxConfidence
 292        {
 1520293            get { lock (_trackingSync) return _maxConfidence; }
 294            set
 364295            {
 364296                lock (_trackingSync)
 364297                {
 364298                    _maxConfidence = value;
 364299                    if (_smoothingBehaviour != null)
 364300                        _smoothingBehaviour.MaxConfidence = (int) MaxConfidence;
 364301                }
 364302            }
 303        }
 304
 2280305        public bool MeasurePerformance { get; set; }
 306
 240307        protected int FrameId { get; private set; }
 308
 309        #region Abstract Members
 310
 311        public abstract ObserverType Type { get; }
 312        public abstract PointCloud3 PointCloud { get; set; }
 313        public abstract VectorField2 VectorField { get; set; }
 314
 315        public event EventHandler<IList<Interaction>> NewInteractions;
 316        public event EventHandler<IList<InteractionVelocity>> NewVelocities;
 317
 318        public event EventHandler<PerformanceDataItem> PerformanceDataUpdated;
 319
 320        public event EventHandler<IList<InteractionFrame>> InteractionHistoryUpdated;
 321
 322        #endregion
 323
 324        #region Constructor
 325
 258326        protected InteractionObserverBase()
 258327        {
 258328            _smoothingBehaviour = new InteractionSmoothingBehaviour(InteractionHistorySize);
 258329            ObservationTimeoutSeconds = 1;
 258330            NumSmoothingFrames = _numSmoothingFrames;
 258331            ContactRetentionSeconds = _contactRetentionSeconds;
 258332            TouchMergeDistance2D = _touchMergeDistance2d;
 258333            DepthScale = _depthScale;
 258334            MaxConfidence = _maxConfidence;
 258335            FilterType = _filterType;
 258336        }
 337
 338        #endregion
 339
 340        public void UpdateFrameId(int frameId)
 0341        {
 0342            FrameId = frameId;
 0343        }
 344
 345        #endregion
 346
 347        protected abstract Task<Tuple<IEnumerable<Interaction>, ProcessPerformance>> Analyze(ProcessPerformance performa
 348
 0349        protected virtual Task ReportPerformance(ProcessPerformance performance) => Task.CompletedTask;
 350
 351        protected virtual Task<ProcessingResult> CheckInitialState()
 94352        {
 94353          return Task.FromResult(new ProcessingResult(ProcessServiceStatus.Available));
 94354        }
 355
 356        private double? _observationTime;
 357
 358        public async Task<ProcessingResult> Update(TrackingObservation observation)
 92359        {
 92360            PointCloud = observation.PointCloud;
 92361            VectorField = observation.VectorField;
 92362            _observationTime = observation.TimestampSeconds;
 184363            try { return await Update(); }
 276364            finally { _observationTime = null; }
 90365        }
 366
 367        public void AdvanceTime(double timestampSeconds)
 36368        {
 72369            lock (_trackingSync) Publish(_smoothingBehaviour.OutputAt(timestampSeconds));
 36370        }
 371
 372        private void Publish(InteractionFrame frame)
 262373        {
 262374            var selected = SelectSmoothedInteractions(frame.Interactions).ToList();
 262375            var published = ApplyConfidenceFilter(selected).ToList();
 540376            var publishedIds = published.Select(item => item.TouchId).ToHashSet();
 556377            var selectedIds = selected.Select(item => item.TouchId).ToHashSet();
 378            // Diagnostics include hidden tracks and are captured before any external callbacks.
 262379            var velocities = _smoothingBehaviour.GetVelocities(frame);
 1198380            foreach (var velocity in velocities)
 206381            {
 206382                velocity.Width = PointCloud?.SizeX ?? 0;
 206383                velocity.Height = PointCloud?.SizeY ?? 0;
 206384                velocity.IsPublished = publishedIds.Contains(velocity.TouchId);
 206385                velocity.SuppressionReason = velocity.IsPublished ? "" :
 206386                    selectedIds.Contains(velocity.TouchId) ? "confidence" : "observer-selection";
 206387            }
 262388            OnNewInteractions(published);
 262389            NewVelocities?.Invoke(this, velocities);
 262390        }
 391
 392        public virtual async Task<ProcessingResult> Update()
 242393        {
 242394            var processResult = await CheckInitialState();
 395
 242396            if (processResult.ServiceStatus != ProcessServiceStatus.Available)
 14397            {
 14398              AdvanceTime(GetTimestampSeconds());
 14399              UpdatePerformanceMetrics(new ProcessPerformance(), DateTime.Now.Ticks);
 14400              return processResult;
 401            }
 402
 228403            var timestampSeconds = _observationTime ?? GetTimestampSeconds();
 228404            var observationCloud = PointCloud;
 228405            var processingDateTime = DateTime.Now.Ticks;
 406
 228407            if (MeasurePerformance)
 2408            {
 2409              _stopWatch.Start();
 2410            }
 411
 228412            var processed = await Analyze(processResult.PerformanceMeasurement);
 413
 226414            var candidates = processed.Item1;
 226415            var perfItem = processed.Item2;
 416
 226417            if (MeasurePerformance)
 2418            {
 2419                _stopWatch.Stop();
 2420                perfItem.Update = _stopWatch.Elapsed - perfItem.Preparation;
 2421                _stopWatch.Reset();
 2422            }
 423
 226424            if (MeasurePerformance)
 2425            {
 2426                _stopWatch.Start();
 2427            }
 428
 226429            var interactions =  ConvertDepthValue(candidates.ToList());
 430
 226431            if (MeasurePerformance)
 2432            {
 2433                _stopWatch.Stop();
 2434                perfItem.ConvertDepthValue = _stopWatch.Elapsed;
 2435                _stopWatch.Reset();
 2436            }
 437
 226438            if (MeasurePerformance)
 2439            {
 2440              _stopWatch.Start();
 2441            }
 442
 226443            var processedInteractions = ComputeExtremumType(interactions, observationCloud.AsJaggedArray());
 444
 226445            var cleanedUpInteractions = RemoveExtremumsBetweenTouches(processedInteractions);
 446
 226447            if (MeasurePerformance)
 2448            {
 2449              _stopWatch.Stop();
 2450              perfItem.ComputeExtremumType = _stopWatch.Elapsed;
 2451              _stopWatch.Reset();
 2452            }
 453
 454
 226455            if (MeasurePerformance)
 2456            {
 2457                _stopWatch.Start();
 2458            }
 459
 460            Task reportTask;
 226461            lock (_trackingSync)
 226462            {
 226463                var measurements = ConsolidateExtrema(cleanedUpInteractions);
 226464                var processedAt = Math.Max(timestampSeconds, GetTimestampSeconds());
 465                // Reject an actually late result before it can mutate or revive tracking state.
 226466                var frame = _observationTime.HasValue && processedAt > timestampSeconds + ObservationTimeoutSeconds
 226467                    ? _smoothingBehaviour.OutputAt(processedAt)
 226468                    : ComputeSmoothingValue(measurements, timestampSeconds, processedAt);
 469
 226470                if (MeasurePerformance)
 2471                {
 2472                    _stopWatch.Stop();
 2473                    perfItem.Smoothing = _stopWatch.Elapsed;
 2474                    _stopWatch.Reset();
 2475                }
 476
 477                // Populate optional remote stage timings before publishing the shared dictionary.
 226478                reportTask = MeasurePerformance ? ReportPerformance(perfItem) : Task.CompletedTask;
 226479                processResult.PerformanceMeasurement = perfItem;
 226480                UpdatePerformanceMetrics(perfItem, processingDateTime);
 481
 226482                Publish(frame);
 226483            }
 484
 226485            await reportTask;
 486
 226487            return processResult;
 240488        }
 489
 490        /// <summary>Limits the smoothed output without changing the tracking history.</summary>
 491        protected virtual IEnumerable<Interaction> SelectSmoothedInteractions(IEnumerable<Interaction> interactions)
 256492            => interactions;
 493
 494        protected virtual IList<Interaction> ConsolidateExtrema(IList<Interaction> interactions)
 226495            => ExtremumConsolidator.Consolidate(interactions, ExtremumMergeRadius);
 496
 497        /// <summary>Monotonic observation time captured before Analyze, including remote work.</summary>
 74498        protected virtual double GetTimestampSeconds() => (double)Stopwatch.GetTimestamp() / Stopwatch.Frequency;
 499
 500        protected InteractionFrame ComputeSmoothingValue(IList<Interaction> rawInteractions, double? timestampSeconds = 
 501            double? processedTimestampSeconds = null)
 220502        {
 220503            var capturedAt = timestampSeconds ?? GetTimestampSeconds();
 220504            var result = _smoothingBehaviour.Update(rawInteractions, capturedAt, processedTimestampSeconds ?? capturedAt
 220505            InteractionHistoryUpdated?.Invoke(this, _smoothingBehaviour.InteractionsFramesCache);
 506
 220507            return result;
 220508        }
 509
 510        protected virtual ExtremumDescription ComputeExtremumType(Point3[][] pointsArray, int xPos, int yPos)
 486511        {
 486512            if (ExtremumTypeCheckMethod == ExtremumTypeCheckMethod.Global)
 352513            {
 514                // Global skips neighbourhood validation, but retains the same sensor-depth
 515                // convention as the spatial classifier: pushes are minima, pulls maxima.
 352516                var depth = pointsArray[xPos][yPos].Z;
 352517                var type = !float.IsFinite(depth) || depth == Distance ? ExtremumType.Undefined
 352518                    : depth < Distance ? ExtremumType.Minimum : ExtremumType.Maximum;
 352519                return new ExtremumDescription
 352520                {
 352521                    Type = type,
 352522                    NumFittingPoints = type == ExtremumType.Undefined ? 0 : ExtremumTypeCheckNumSamples,
 352523                    PercentageFittingPoints = type == ExtremumType.Undefined ? 0 : 1.0f
 352524                };
 525            }
 526
 134527            var xMax = pointsArray.Length - 1;
 134528            var yMax = xMax > 0 ? pointsArray[0].Length - 1 : 0;
 529
 530            // refZ is the absolute distance from sensor
 134531            var refZ = Math.Abs(pointsArray[xPos][yPos].Z);
 532
 134533            var numCloser = 0;
 134534            var numFarther = 0;
 535
 536            Tuple<int, int>[] samples;
 134537            switch (ExtremumTypeCheckMethod)
 538            {
 539                case ExtremumTypeCheckMethod.StochasticStatic:
 30540                    samples = _stochasticSamples;
 30541                    break;
 542                case ExtremumTypeCheckMethod.StochasticDynamic:
 30543                    samples = GenerateSamples();
 30544                    break;
 545                case ExtremumTypeCheckMethod.Global:
 0546                    throw new ArgumentException("invalid Method 'Global' at this point.");
 547                case ExtremumTypeCheckMethod.FixedRadius:
 548                default:
 74549                    samples = _fixedSamples;
 74550                    break;
 551            }
 552
 329260553            for (var i = 0; i < samples.Length; i++)
 164496554            {
 164496555                var sample = GetSample(pointsArray, xPos, yPos, samples, i, xMax, yMax);
 164496556                if (Math.Abs(sample.Z) > refZ)
 98756557                    numFarther++;
 558                else
 65740559                    numCloser++;
 164496560            }
 561
 562
 134563            var ratioMax = ExtremumTypeCheckNumSamples > 0 ? (float)numCloser / ExtremumTypeCheckNumSamples : 0;
 134564            var ratioMin = ExtremumTypeCheckNumSamples > 0 ? (float)numFarther / ExtremumTypeCheckNumSamples : 0;
 565
 134566            if (numCloser > numFarther && ratioMax > ExtremumTypeCheckFittingPercentage)
 52567            {
 52568                return new ExtremumDescription
 52569                {
 52570                    Type = ExtremumType.Maximum,
 52571                    NumFittingPoints = numCloser,
 52572                    PercentageFittingPoints = ratioMax
 52573                };
 574            }
 575
 82576            if (numFarther > numCloser && ratioMin > ExtremumTypeCheckFittingPercentage)
 50577            {
 50578                return new ExtremumDescription
 50579                {
 50580                    Type = ExtremumType.Minimum,
 50581                    NumFittingPoints = numFarther,
 50582                    PercentageFittingPoints = ratioMin
 50583                };
 584            }
 585
 32586            return new ExtremumDescription
 32587            {
 32588                Type = ExtremumType.Undefined,
 32589                NumFittingPoints = Math.Max(numCloser, numFarther),
 32590                PercentageFittingPoints = Math.Max(ratioMin, ratioMax)
 32591            };
 592
 486593        }
 594
 595        protected List<Interaction> ConvertDepthValue(List<Interaction> interactions)
 234596        {
 234597            var result = new List<Interaction>();
 598
 1510599            foreach (var item in interactions)
 404600            {
 404601                if (item?.Position == null || !float.IsFinite(item.Position.Z) ||
 404602                    Math.Abs(item.Position.Z - Distance) <= MinDistance)
 24603                    continue;
 604
 380605                if (item.Position.Z < Distance)
 364606                {
 364607                    item.Type = InteractionType.Push;
 364608                    var depth = (Distance - item.Position.Z - MinDistance) / (MinDistance - MaxDistance);
 609
 364610                    if (depth > 0)
 0611                        continue;
 612
 364613                    if (depth < -1)
 0614                        depth = -1;
 615
 364616                    item.Position.Z = depth;
 364617                }
 618                else
 16619                {
 16620                    item.Type = InteractionType.Pull;
 16621                    var depth = (item.Position.Z - MinDistance - Distance) / (MaxDistance - MinDistance);
 622
 16623                    if (depth < 0)
 0624                        continue;
 625
 16626                    if (depth > 1)
 0627                        depth = 1;
 628
 16629                    item.Position.Z = depth;
 16630                }
 631
 380632                result.Add(item);
 380633            }
 634
 234635            return result;
 234636        }
 637
 638        protected IEnumerable<Interaction> ApplyConfidenceFilter(IEnumerable<Interaction> interactions)
 262639        {
 556640            return interactions.ToArray().Where(item => item.Confidence > MinConfidence);
 262641        }
 642
 643        protected List<Interaction> ComputeExtremumType(List<Interaction> interactions, Point3[][] pointsArray)
 226644        {
 226645            interactions.ForEach(interaction =>
 598646                interaction.ExtremumDescription = ComputeExtremumType(pointsArray, (int)interaction.Position.X, (int)int
 647
 226648            return interactions;
 226649        }
 650
 651        /// <summary>
 652        /// generic approach: removes all maximums below the surface and all minimums above the surface. Removal is base
 653        /// Points witch <see cref="ExtremumType.Undefined"/> are also removed.
 654        /// </summary>
 655        /// <param name="interactions">the list of preprocessed interactions with valid ExtremumDescription</param>
 656        /// <returns></returns>
 657        protected List<Interaction> RemoveExtremumsBetweenTouches(List<Interaction> interactions)
 226658        {
 226659          return interactions.Where((touch) =>
 226660            // invalid or undefined ExtremumType
 372661            touch.ExtremumDescription != null && touch.ExtremumDescription.Type != ExtremumType.Undefined &&
 372662            // minimums below the surface
 372663            ((touch.Position.Z < 0 && touch.ExtremumDescription.Type == ExtremumType.Minimum) ||
 372664             // maximums above the surface
 372665             (touch.Position.Z > 0 && touch.ExtremumDescription.Type == ExtremumType.Maximum))
 226666
 226667          ).ToList();
 226668        }
 669
 670        protected void UpdatePerformanceMetrics(ProcessPerformance perfItem, long startTime)
 240671        {
 240672            var pData = new PerformanceDataItem
 240673            {
 240674                FrameId = Convert.ToInt32(FrameId),
 240675                FrameStart = startTime,
 240676                FrameEnd = DateTime.Now.Ticks,
 240677                Process = perfItem,
 240678                Stage = PerformanceDataStage.ProcessingData
 240679            };
 680
 240681            PerformanceDataUpdated?.Invoke(this, pData);
 240682        }
 683
 262684        protected void OnNewInteractions(List<Interaction> args) => NewInteractions?.Invoke(this, args);
 685
 686        /// <summary>
 687        /// Calculates the average distance for the currently stored PointCloud.
 688        /// </summary>
 689        /// <returns></returns>
 690        public float CalculateAverageDistance()
 0691        {
 0692            var sum = 0f;
 0693            var points = PointCloud?.AsArray();
 694
 0695            if (points == null)
 0696                return sum;
 697
 0698            var numValidSamples = 0;
 699
 0700            for (var i = 0; i < points.Length; ++i)
 0701            {
 0702                if (!points[i].IsValid || points[i].IsFiltered)
 0703                    continue;
 704
 0705                numValidSamples++;
 0706                sum += points[i].Z;
 0707            }
 708
 0709            return (float) decimal.Round((decimal) (sum / numValidSamples), 2);
 0710        }
 711
 712        private static Point3 GetSample(Point3[][] pointsArray, int xPos, int yPos, Tuple<int, int>[] samples, int i, in
 164496713        {
 164496714            var xIdx = xPos + samples[i].Item1;
 164496715            xIdx = Math.Min(Math.Max(xIdx, 0), xMax);
 716
 164496717            var yIdx = yPos + samples[i].Item2;
 164496718            yIdx = Math.Min(Math.Max(yIdx, 0), yMax);
 164496719            var sample = pointsArray[xIdx][yIdx];
 720
 164496721            return sample;
 164496722        }
 723
 724        private Tuple<int, int>[] GenerateSamples()
 360725        {
 360726            var result = new List<Tuple<int, int>>();
 727
 360728            var rnd = new Random();
 729
 360730            var min = (int)Math.Floor(0.5f * ExtremumTypeCheckRadius);
 360731            var max = ExtremumTypeCheckRadius;
 360732            var range = max - min;
 733
 494416734            for (var i = 0; i < ExtremumTypeCheckNumSamples; i++)
 246848735            {
 736                // One draw per axis encodes both magnitude and sign. Map [-range, -1]
 737                // to [-(max - 1), -min] and [0, range - 1] to [min, max - 1].
 246848738                var x = rnd.Next(-range, range);
 246848739                var y = rnd.Next(-range, range);
 740                // A 0/-1 sign mask avoids an unpredictable branch for each axis.
 246848741                var xSign = x >> 31;
 246848742                var ySign = y >> 31;
 246848743                var xStochastic = x + (min ^ xSign) - 2 * xSign;
 246848744                var yStochastic = y + (min ^ ySign) - 2 * ySign;
 745
 246848746                result.Add(new Tuple<int, int>(xStochastic, yStochastic));
 246848747            }
 748
 360749            return result.ToArray();
 360750        }
 751
 752        private void UpdateSamples()
 330753        {
 330754            var samplesFixed = new List<Tuple<int, int>>();
 755
 330388756            for (var i = 0; i < ExtremumTypeCheckNumSamples; i++)
 164864757            {
 164864758                var p = (double)i / ExtremumTypeCheckNumSamples;
 164864759                var xFixed = (int) Math.Floor(ExtremumTypeCheckRadius * Math.Cos(p * 2 * Math.PI));
 164864760                var yFixed = (int) Math.Floor(ExtremumTypeCheckRadius * Math.Sin(p * 2 * Math.PI));
 761
 164864762                samplesFixed.Add(new Tuple<int, int>(xFixed, yFixed));
 164864763            }
 330764            _fixedSamples = samplesFixed.ToArray();
 765
 330766            _stochasticSamples = GenerateSamples();
 330767        }
 768
 769
 770    }
 771}

Methods/Properties

.ctor()
get_Distance()
get_MinDistance()
get_MaxDistance()
get_ExtremumTypeCheckNumSamples()
set_ExtremumTypeCheckNumSamples(System.Int32)
get_ExtremumTypeCheckRadius()
set_ExtremumTypeCheckRadius(System.Int32)
get_ExtremumTypeCheckFittingPercentage()
get_ExtremumTypeCheckMethod()
get_ExtremumMergeRadius()
set_ExtremumMergeRadius(System.Single)
get_PredictionHorizonSeconds()
set_PredictionHorizonSeconds(System.Double)
get_UseVelocityPrediction()
set_UseVelocityPrediction(System.Boolean)
get_NumFramesForPrediction()
set_NumFramesForPrediction(System.Int32)
get_UseSecondDerivation()
set_UseSecondDerivation(System.Boolean)
get_SecondDerivationMagnitude()
set_SecondDerivationMagnitude(System.Single)
get_InteractionHistorySize()
set_InteractionHistorySize(System.Int32)
get_NumSmoothingFrames()
set_NumSmoothingFrames(System.Int32)
ValidateContactRetention(System.Double)
get_UseMinimumCostAssignment()
set_UseMinimumCostAssignment(System.Boolean)
get_AssignmentMissCost()
set_AssignmentMissCost(System.Single)
get_AssignmentBirthCost()
set_AssignmentBirthCost(System.Single)
get_ConfidenceGainPerSecond()
set_ConfidenceGainPerSecond(System.Single)
get_ConfidenceDecayPerSecond()
set_ConfidenceDecayPerSecond(System.Single)
get_ContactRetentionSeconds()
set_ContactRetentionSeconds(System.Double)
get_ObservationTimeoutSeconds()
set_ObservationTimeoutSeconds(System.Double)
get_TouchMergeDistance2D()
set_TouchMergeDistance2D(System.Single)
get_DepthScale()
set_DepthScale(System.Single)
get_FilterType()
set_FilterType(ReFlex.Core.Interactivity.Util.FilterType)
get_MinAngle()
get_MinConfidence()
get_MaxConfidence()
set_MaxConfidence(System.Single)
get_MeasurePerformance()
get_FrameId()
UpdateFrameId(System.Int32)
ReportPerformance(ReFlex.Core.Common.Util.ProcessPerformance)
CheckInitialState()
Update()
AdvanceTime(System.Double)
Publish(ReFlex.Core.Common.Components.InteractionFrame)
Update()
SelectSmoothedInteractions(System.Collections.Generic.IEnumerable`1<ReFlex.Core.Common.Components.Interaction>)
ConsolidateExtrema(System.Collections.Generic.IList`1<ReFlex.Core.Common.Components.Interaction>)
GetTimestampSeconds()
ComputeSmoothingValue(System.Collections.Generic.IList`1<ReFlex.Core.Common.Components.Interaction>,System.Nullable`1<System.Double>,System.Nullable`1<System.Double>)
ComputeExtremumType(ReFlex.Core.Common.Components.Point3[][],System.Int32,System.Int32)
ConvertDepthValue(System.Collections.Generic.List`1<ReFlex.Core.Common.Components.Interaction>)
ApplyConfidenceFilter(System.Collections.Generic.IEnumerable`1<ReFlex.Core.Common.Components.Interaction>)
ComputeExtremumType(System.Collections.Generic.List`1<ReFlex.Core.Common.Components.Interaction>,ReFlex.Core.Common.Components.Point3[][])
RemoveExtremumsBetweenTouches(System.Collections.Generic.List`1<ReFlex.Core.Common.Components.Interaction>)
UpdatePerformanceMetrics(ReFlex.Core.Common.Util.ProcessPerformance,System.Int64)
OnNewInteractions(System.Collections.Generic.List`1<ReFlex.Core.Common.Components.Interaction>)
CalculateAverageDistance()
GetSample(ReFlex.Core.Common.Components.Point3[][],System.Int32,System.Int32,System.Tuple`2<System.Int32,System.Int32>[],System.Int32,System.Int32,System.Int32)
GenerateSamples()
UpdateSamples()