| | | 1 | | using System.Collections.Generic; |
| | | 2 | | using System.Linq; |
| | | 3 | | using ReFlex.Core.Common.Components; |
| | | 4 | | |
| | | 5 | | namespace ReFlex.Core.Interactivity.Util; |
| | | 6 | | |
| | | 7 | | /// <summary>Assigns measurements to matching positions without mutating contact lifecycle state.</summary> |
| | | 8 | | internal static class MinimumCostContactAssignment |
| | | 9 | | { |
| | | 10 | | public static int[] Assign(List<Interaction> candidates, IReadOnlyList<(int TouchId, Point3 Position)> targets, |
| | | 11 | | float distanceLimit, float missCost, float birthCost) |
| | 2290 | 12 | | { |
| | 3384 | 13 | | var tracks = targets.OrderBy(pair => pair.TouchId).ToArray(); |
| | | 14 | | // Canonical order makes equal-cost decisions independent of detector enumeration. |
| | 5198 | 15 | | var orderedCandidates = candidates.Select((candidate, index) => (Candidate: candidate, Index: index)) |
| | 1416 | 16 | | .OrderBy(item => item.Candidate.Position.X) |
| | 1416 | 17 | | .ThenBy(item => item.Candidate.Position.Y) |
| | 3706 | 18 | | .ThenBy(item => item.Index).ToArray(); |
| | 2290 | 19 | | var costs = new double[orderedCandidates.Length, tracks.Length + orderedCandidates.Length]; |
| | 10396 | 20 | | for (var row = 0; row < orderedCandidates.Length; row++) |
| | 2908 | 21 | | { |
| | 12244 | 22 | | for (var column = 0; column < tracks.Length; column++) |
| | 3214 | 23 | | { |
| | 3214 | 24 | | var distance = Point3.Squared2DDistance(orderedCandidates[row].Candidate.Position, |
| | 3214 | 25 | | tracks[column].Position); |
| | | 26 | | // The full objective includes tracks.Length * missCost. Matching a |
| | | 27 | | // track removes its miss cost; omitting that constant gives this rectangular problem. |
| | 3214 | 28 | | costs[row, column] = float.IsFinite(distance) && distance < distanceLimit |
| | 3214 | 29 | | ? (double)distance / distanceLimit - missCost |
| | 3214 | 30 | | : double.PositiveInfinity; |
| | 3214 | 31 | | } |
| | 16224 | 32 | | for (var column = tracks.Length; column < costs.GetLength(1); column++) |
| | 5204 | 33 | | costs[row, column] = column == tracks.Length + row |
| | 5204 | 34 | | ? birthCost : double.PositiveInfinity; |
| | 2908 | 35 | | } |
| | | 36 | | |
| | 2290 | 37 | | var assignment = MinimumCostAssignment.Solve(costs); |
| | 2290 | 38 | | var ids = Enumerable.Repeat(-1, candidates.Count).ToArray(); |
| | 10396 | 39 | | for (var row = 0; row < orderedCandidates.Length; row++) |
| | 2908 | 40 | | if (assignment[row] < tracks.Length) |
| | 1814 | 41 | | ids[orderedCandidates[row].Index] = tracks[assignment[row]].TouchId; |
| | 2290 | 42 | | return ids; |
| | 2290 | 43 | | } |
| | | 44 | | } |