Marcel Zickler il y a 3 ans
Parent
commit
d8ca46c817
89 fichiers modifiés avec 1186 ajouts et 1503 suppressions
  1. 10 11
      Assets/Scripts/AdditionalMathf/NOrderStat.cs
  2. 7 10
      Assets/Scripts/AdditionalMathf/Quartiles.cs
  3. 28 37
      Assets/Scripts/Animation/BikeAnimation.cs
  4. 3 1
      Assets/Scripts/Animation/Rotatable.cs
  5. 4 3
      Assets/Scripts/Calibration/BikeReset.cs
  6. 3 2
      Assets/Scripts/Calibration/MovePlayerPosition.cs
  7. 17 15
      Assets/Scripts/Calibration/PersistatePlayerPosition.cs
  8. 6 4
      Assets/Scripts/Controller/Bicycle/BicycleControllerBaseBehaviour.cs
  9. 19 22
      Assets/Scripts/Controller/Bicycle/BikeSpeedBooster.cs
  10. 62 74
      Assets/Scripts/Controller/Bicycle/RbBicycleController.cs
  11. 47 49
      Assets/Scripts/Controller/Bicycle/WcBicycleController.cs
  12. 5 4
      Assets/Scripts/Controller/Bicycle/WheelConfig.cs
  13. 5 5
      Assets/Scripts/Controller/GamepadBikeController.cs
  14. 5 22
      Assets/Scripts/Controller/KeyboardBikeController.cs
  15. 3 15
      Assets/Scripts/Controller/Lean/HmdLeanController.cs
  16. 1 3
      Assets/Scripts/Controller/Lean/ILeanController.cs
  17. 3 10
      Assets/Scripts/Controller/Lean/PolarLeanController.cs
  18. 5 15
      Assets/Scripts/Controller/SensorBikeController.cs
  19. 4 4
      Assets/Scripts/Controller/ViveBikeController.cs
  20. 6 6
      Assets/Scripts/Display/BikeDataDisplay.cs
  21. 4 6
      Assets/Scripts/Display/CountdownDisplay.cs
  22. 2 6
      Assets/Scripts/Display/DebugDisplay.cs
  23. 1 3
      Assets/Scripts/Display/InFrontOfCameraDisplay.cs
  24. 31 34
      Assets/Scripts/Display/LookStraightDisplay.cs
  25. 14 15
      Assets/Scripts/Display/ViveTrackerDebugDisplay.cs
  26. 7 14
      Assets/Scripts/DuplicateManager.cs
  27. 14 14
      Assets/Scripts/Helpers.cs
  28. 5 11
      Assets/Scripts/IgnoreClipping.cs
  29. 4 11
      Assets/Scripts/Logging/Base/AsyncLogFileWriter.cs
  30. 34 47
      Assets/Scripts/Logging/Base/FileLogger.cs
  31. 1 0
      Assets/Scripts/Logging/Base/ILogable.cs
  32. 5 8
      Assets/Scripts/Logging/Base/Logging.cs
  33. 19 15
      Assets/Scripts/Logging/Data/BikeGameObjectDataLogger.cs
  34. 11 9
      Assets/Scripts/Logging/Data/BikeSensorDataLogger.cs
  35. 17 13
      Assets/Scripts/Logging/Data/FrontWheelTrackerLogger.cs
  36. 14 18
      Assets/Scripts/Logging/Data/PolarAccDataLogger.cs
  37. 14 17
      Assets/Scripts/Logging/Data/PolarEcgDataLogger.cs
  38. 8 8
      Assets/Scripts/Logging/Data/SensorDataLogger.cs
  39. 32 28
      Assets/Scripts/Logging/Data/ViveSensorDataLogger.cs
  40. 13 19
      Assets/Scripts/Logging/Events/RouteEventLogger.cs
  41. 13 10
      Assets/Scripts/Logging/FPSLogger.cs
  42. 8 4
      Assets/Scripts/Phscs/BicyclePhysics.cs
  43. 25 29
      Assets/Scripts/Plotting/DebugPlot.cs
  44. 2 5
      Assets/Scripts/Pools/Pool.cs
  45. 0 6
      Assets/Scripts/Roads/CrossingExtras.cs
  46. 10 12
      Assets/Scripts/Roads/JunctionExtras.cs
  47. 3 5
      Assets/Scripts/Roads/Road.cs
  48. 10 18
      Assets/Scripts/Roads/SlopeExtras.cs
  49. 19 25
      Assets/Scripts/Roads/StraightRoadExtras.cs
  50. 3 5
      Assets/Scripts/Roads/StreetPartMetaTag.cs
  51. 12 27
      Assets/Scripts/Routes/Route.cs
  52. 3 16
      Assets/Scripts/Routes/RouteManager.cs
  53. 31 49
      Assets/Scripts/Routes/Turn.cs
  54. 1 1
      Assets/Scripts/Routes/TurnDirectionMapper.cs
  55. 26 33
      Assets/Scripts/Sensors/BikeSensorData.cs
  56. 3 4
      Assets/Scripts/Sensors/ListenToSensors.cs
  57. 5 4
      Assets/Scripts/Sensors/Polar/PolarAccData.cs
  58. 1 1
      Assets/Scripts/Sensors/Polar/PolarEcgData.cs
  59. 1 1
      Assets/Scripts/Sensors/Polar/PolarHRData.cs
  60. 12 13
      Assets/Scripts/Sensors/Polar/PolarReceiver.cs
  61. 27 31
      Assets/Scripts/Sensors/Polar/UdpConnection.cs
  62. 27 38
      Assets/Scripts/Sensors/SensorStatus.cs
  63. 42 42
      Assets/Scripts/SicknessReduction/DynamicReductionSource.cs
  64. 18 23
      Assets/Scripts/SicknessReduction/Haptic/DataBroker.cs
  65. 2 4
      Assets/Scripts/SicknessReduction/Haptic/DeskFanController.cs
  66. 6 6
      Assets/Scripts/SicknessReduction/Haptic/EspController.cs
  67. 0 2
      Assets/Scripts/SicknessReduction/Haptic/FanController.cs
  68. 2 8
      Assets/Scripts/SicknessReduction/Haptic/VibrationController.cs
  69. 18 20
      Assets/Scripts/SicknessReduction/Visual/DoF/DynamicDoF.cs
  70. 9 10
      Assets/Scripts/SicknessReduction/Visual/IpdInfo.cs
  71. 40 41
      Assets/Scripts/SicknessReduction/Visual/Rendering/MaterialBlitFeature.cs
  72. 54 53
      Assets/Scripts/SicknessReduction/Visual/Rendering/MaterialBlitRenderPass.cs
  73. 15 15
      Assets/Scripts/SicknessReduction/Visual/Vignetting/DynamicVignetting.cs
  74. 18 19
      Assets/Scripts/SicknessReduction/Visual/Vignetting/RestrictionSuggestor.cs
  75. 10 14
      Assets/Scripts/SicknessReduction/Visual/VirtualNose.cs
  76. 88 110
      Assets/Scripts/SimpleCameraController.cs
  77. 0 3
      Assets/Scripts/SubjectManager.cs
  78. 10 10
      Assets/Scripts/Tracking/CalibratableTracker.cs
  79. 4 5
      Assets/Scripts/Tracking/CameraTracker.cs
  80. 12 22
      Assets/Scripts/Tracking/FrontWheelTracker.cs
  81. 7 10
      Assets/Scripts/Tracking/KineticLegTracker.cs
  82. 12 18
      Assets/Scripts/Tracking/MatchPlayerPositionAndCalibrate.cs
  83. 1 2
      Assets/Scripts/Tracking/TrackerIndexManager.cs
  84. 21 32
      Assets/Scripts/Wheels/ColliderAddSlopeAdjustment.cs
  85. 11 19
      Assets/Scripts/Wheels/CustomWheelCollider.cs
  86. 18 22
      Assets/Scripts/Wheels/CustomWheelColliderSlopeAdjustment.cs
  87. 18 28
      Assets/Scripts/Wheels/LerpSlopeCollider.cs
  88. 13 16
      Assets/Scripts/Wheels/SlopeCollider.cs
  89. 2 4
      Assets/Scripts/Wheels/SwitchColliderOnStanding.cs

+ 10 - 11
Assets/Scripts/AdditionalMathf/NOrderStat.cs

@@ -7,11 +7,11 @@ namespace AdditionalMathf
     public static class NOrderStatExtension
     {
         /// <summary>
-        /// Partitions the given list around a pivot element such that all elements on left of pivot are <= pivot
-        /// and the ones at thr right are > pivot. This method can be used for sorting, N-order statistics such as
-        /// as median finding algorithms.
-        /// Pivot is selected ranodmly if random number generator is supplied else its selected as last element in the list.
-        /// Reference: Introduction to Algorithms 3rd Edition, Corman et al, pp 171
+        ///     Partitions the given list around a pivot element such that all elements on left of pivot are <= pivot
+        ///     and the ones at thr right are > pivot. This method can be used for sorting, N-order statistics such as
+        ///     as median finding algorithms.
+        ///     Pivot is selected ranodmly if random number generator is supplied else its selected as last element in the list.
+        ///     Reference: Introduction to Algorithms 3rd Edition, Corman et al, pp 171
         /// </summary>
         private static int Partition<T>(this IList<T> list, int start, int end, Random rnd = null)
             where T : IComparable<T>
@@ -22,19 +22,18 @@ namespace AdditionalMathf
             var pivot = list[end];
             var lastLow = start - 1;
             for (var i = start; i < end; i++)
-            {
                 if (list[i].CompareTo(pivot) <= 0)
                     list.Swap(i, ++lastLow);
-            }
 
             list.Swap(end, ++lastLow);
             return lastLow;
         }
 
         /// <summary>
-        /// Returns Nth smallest element from the list. Here n starts from 0 so that n=0 returns minimum, n=1 returns 2nd smallest element etc.
-        /// Note: specified list would be mutated in the process.
-        /// Reference: Introduction to Algorithms 3rd Edition, Corman et al, pp 216
+        ///     Returns Nth smallest element from the list. Here n starts from 0 so that n=0 returns minimum, n=1 returns 2nd
+        ///     smallest element etc.
+        ///     Note: specified list would be mutated in the process.
+        ///     Reference: Introduction to Algorithms 3rd Edition, Corman et al, pp 216
         /// </summary>
         public static T NthOrderStatistic<T>(this IList<T> list, int n, Random rnd = null) where T : IComparable<T>
         {
@@ -67,7 +66,7 @@ namespace AdditionalMathf
         }
 
         /// <summary>
-        /// Note: specified list would be mutated in the process.
+        ///     Note: specified list would be mutated in the process.
         /// </summary>
         public static T Median<T>(this IList<T> list) where T : IComparable<T>
         {

+ 7 - 10
Assets/Scripts/AdditionalMathf/Quartiles.cs

@@ -7,12 +7,6 @@ namespace AdditionalMathf
 {
     public class Quartiles
     {
-        public float Q1 { get; }
-        public float Q2 { get; }
-        public float Q3 { get; }
-
-        public float Iqr { get; }
-
         public Quartiles(IList<float> list)
         {
             if (list.Count < 4) throw new ArgumentException("list must not be empty");
@@ -28,13 +22,16 @@ namespace AdditionalMathf
             Iqr = Q3 - Q1;
         }
 
+        public float Q1 { get; }
+        public float Q2 { get; }
+        public float Q3 { get; }
+
+        public float Iqr { get; }
+
         private float ValueForFloatingIndex(IList<float> list, float index)
         {
             var i = Mathf.Max(0, index - 1);
-            if (i % 1f == 0)
-            {
-                return list[(int) i];
-            }
+            if (i % 1f == 0) return list[(int) i];
 
             var flooredIndex = Mathf.FloorToInt(i);
             var lower = list[flooredIndex];

+ 28 - 37
Assets/Scripts/Animation/BikeAnimation.cs

@@ -1,8 +1,6 @@
 using System;
 using System.Collections.Generic;
-using Controller;
 using Controller.Bicycle;
-using Sensors;
 using UnityEngine;
 
 namespace Animation
@@ -28,33 +26,8 @@ namespace Animation
     [RequireComponent(typeof(IBicycleController))]
     public class BikeAnimation : MonoBehaviour
     {
-        #region Variables
-
-        public bool pause = false; //TODO: remove, only for debugging purposes
-
-        [Header("Wheels - rotating around center")]
-        public WheelAnimationConfig rearWheel;
-
-        public WheelAnimationConfig frontWheel;
-
-        [Header("Other with defined rotation axis")]
-        public Rotatable crankSet;
-
-        public Rotatable fork;
-
-        [Header("Parameters")] public float wheelCircumference = 2.096f;
-        public float defaultCadence = 80;
-
-        private IBicycleController bicycleController;
-
-        private readonly Dictionary<Rotatable, Vector3> initialPositions = new Dictionary<Rotatable, Vector3>();
-        private readonly Dictionary<Rotatable, Quaternion> initialRotations = new Dictionary<Rotatable, Quaternion>();
-
-        #endregion
-
-
         // Start is called before the first frame update
-        void Start()
+        private void Start()
         {
             bicycleController = GetComponentInParent<IBicycleController>();
             initialPositions[crankSet] = crankSet.gameObject.transform.localPosition;
@@ -63,7 +36,7 @@ namespace Animation
             initialRotations[fork] = fork.gameObject.transform.localRotation;
         }
 
-        void Update()
+        private void Update()
         {
             var cadence = /*BikeSensorData.Instance.PowermeterData?.InstantaneousCadence ??*/
                 defaultCadence * bicycleController.CurrentSpeed / 8; //rpm*/
@@ -98,17 +71,11 @@ namespace Animation
 
             Vector3 rotateAxis;
             if (axis == Axis.X)
-            {
                 rotateAxis = t.right;
-            }
             else if (axis == Axis.Y)
-            {
                 rotateAxis = t.up;
-            }
             else
-            {
                 rotateAxis = t.forward;
-            }
 
             t.RotateAround(t.position, rotateAxis, directedAngle);
             t.localPosition = oldPos;
@@ -131,7 +98,7 @@ namespace Animation
                 axis = rotatable.rotateAround.forward;
             else
                 axis = rotatable.rotateAround.right;
-            
+
             //Debug.Log($"rotatable.rotateAround.position = {rotatable.rotateAround.position}");
             //Debug.Log($"axis = {axis}");
             //Debug.DrawLine(rotatable.rotateAround.position, rotatable.rotateAround.position+axis*5, Color.yellow);
@@ -141,12 +108,36 @@ namespace Animation
 
 
         //rotates the meshes
-        void RotateObject(GameObject obj, float multiplier)
+        private void RotateObject(GameObject obj, float multiplier)
         {
             obj.transform.Rotate(
                 Time.deltaTime * bicycleController.CurrentSpeed * (360f / 12f) * multiplier, 0,
                 0);
             //obj.transform.Rotate(Time.deltaTime * rotSpeed * (360f / oneRotationSpeed) * multiplier, 0, 0);
         }
+
+        #region Variables
+
+        public bool pause; //TODO: remove, only for debugging purposes
+
+        [Header("Wheels - rotating around center")]
+        public WheelAnimationConfig rearWheel;
+
+        public WheelAnimationConfig frontWheel;
+
+        [Header("Other with defined rotation axis")]
+        public Rotatable crankSet;
+
+        public Rotatable fork;
+
+        [Header("Parameters")] public float wheelCircumference = 2.096f;
+        public float defaultCadence = 80;
+
+        private IBicycleController bicycleController;
+
+        private readonly Dictionary<Rotatable, Vector3> initialPositions = new Dictionary<Rotatable, Vector3>();
+        private readonly Dictionary<Rotatable, Quaternion> initialRotations = new Dictionary<Rotatable, Quaternion>();
+
+        #endregion
     }
 }

+ 3 - 1
Assets/Scripts/Animation/Rotatable.cs

@@ -5,7 +5,9 @@ namespace Animation
 {
     public enum RotateAxis
     {
-        Up, Right, Forward
+        Up,
+        Right,
+        Forward
     }
 
     [Serializable]

+ 4 - 3
Assets/Scripts/Calibration/BikeReset.cs

@@ -6,11 +6,12 @@ namespace Calibration
     public class BikeReset : MonoBehaviour
     {
         public SteamVR_Action_Boolean resetPosition;
+        private Transform bikeTransform;
 
         private Vector3 initialPosition;
         private Quaternion initialRotation;
-        private Transform bikeTransform;
-        void Start()
+
+        private void Start()
         {
             bikeTransform = transform;
             initialPosition = bikeTransform.localPosition;
@@ -25,4 +26,4 @@ namespace Calibration
             bikeTransform.localRotation = initialRotation;
         }
     }
-}
+}

+ 3 - 2
Assets/Scripts/Calibration/MovePlayerPosition.cs

@@ -14,9 +14,9 @@ namespace Calibration
         public SteamVR_Action_Boolean moveLeft;
 
         public float movementSpeed = 1f;
+        private bool moveModeForwards;
 
         private Transform playerTransform;
-        private bool moveModeForwards = false;
 
         private void Start()
         {
@@ -33,7 +33,8 @@ namespace Calibration
             var backward = moveBackwards.GetState(SteamVR_Input_Sources.Any) ? 1 : 0;
 
             var x = right - left;
-            var y = moveModeForwards ? 0f : forward - backward; var z = moveModeForwards ? forward - backward : 0f;
+            var y = moveModeForwards ? 0f : forward - backward;
+            var z = moveModeForwards ? forward - backward : 0f;
 
             playerTransform.localPosition += new Vector3(x, y, z) * (Time.deltaTime * movementSpeed);
         }

+ 17 - 15
Assets/Scripts/Calibration/PersistatePlayerPosition.cs

@@ -1,39 +1,41 @@
-using System;
-using UnityEngine;
+using UnityEngine;
 using Valve.VR;
 
 namespace Calibration
 {
     public class PersistatePlayerPosition : MonoBehaviour
     {
-        private const String KEY_PLAYER_POS_X = "player_pos_x";
-        private const String KEY_PLAYER_POS_Y = "player_pos_y";
-        private const String KEY_PLAYER_POS_Z = "player_pos_z";
-    
-        private Transform playerTransform;
+        private const string KEY_PLAYER_POS_X = "player_pos_x";
+        private const string KEY_PLAYER_POS_Y = "player_pos_y";
+        private const string KEY_PLAYER_POS_Z = "player_pos_z";
 
         public SteamVR_Action_Boolean savePos;
-    
+
+        private Transform playerTransform;
+
         // Start is called before the first frame update
-        void Start()
+        private void Start()
         {
             playerTransform = GetComponent<Transform>();
             savePos.AddOnStateDownListener(OnSavePos, SteamVR_Input_Sources.Any);
             Load();
         }
 
-        private void OnSavePos(SteamVR_Action_Boolean fromaction, SteamVR_Input_Sources fromsource) => Save();
+        private void OnSavePos(SteamVR_Action_Boolean fromaction, SteamVR_Input_Sources fromsource)
+        {
+            Save();
+        }
 
-        void Load()
+        private void Load()
         {
-            if (PlayerPrefs.HasKey(KEY_PLAYER_POS_X) && PlayerPrefs.HasKey(KEY_PLAYER_POS_Y) && PlayerPrefs.HasKey(KEY_PLAYER_POS_Z))
+            if (PlayerPrefs.HasKey(KEY_PLAYER_POS_X) && PlayerPrefs.HasKey(KEY_PLAYER_POS_Y) &&
+                PlayerPrefs.HasKey(KEY_PLAYER_POS_Z))
             {
                 var x = PlayerPrefs.GetFloat(KEY_PLAYER_POS_X);
                 var y = PlayerPrefs.GetFloat(KEY_PLAYER_POS_Y);
                 var z = PlayerPrefs.GetFloat(KEY_PLAYER_POS_Z);
-                playerTransform.position = new Vector3(x,y,z);
+                playerTransform.position = new Vector3(x, y, z);
             }
-        
         }
 
         public void Save()
@@ -45,4 +47,4 @@ namespace Calibration
             PlayerPrefs.Save();
         }
     }
-}
+}

+ 6 - 4
Assets/Scripts/Controller/Bicycle/BicycleControllerBaseBehaviour.cs

@@ -4,13 +4,15 @@ namespace Controller.Bicycle
 {
     public class BicycleControllerBaseBehaviour : MonoBehaviour
     {
-        [Header("Base - Config")]
-        public BicycleControllerMode controllerMode;
+        [Header("Base - Config")] public BicycleControllerMode controllerMode;
+
         [Header("Base - Physics")] public Transform centerOfMass;
         public Rigidbody rigidBody;
-        [Header("Base - Values")]
-        public float maxLeaningAngle = 35f;
+
+        [Header("Base - Values")] public float maxLeaningAngle = 35f;
+
         public float maxSteeringAngle = 80f;
+
         [Range(0, 15)] [Tooltip("Speed in m/s")]
         public float maxSpeed = 11.111f; //40 km/h
     }

+ 19 - 22
Assets/Scripts/Controller/Bicycle/BikeSpeedBooster.cs

@@ -4,7 +4,7 @@ using UnityEngine;
 
 namespace Controller.Bicycle
 {
-    readonly struct Booster
+    internal readonly struct Booster
     {
         public float StartTime { get; }
         public float EndTime { get; }
@@ -27,19 +27,6 @@ namespace Controller.Bicycle
 
     public class BikeSpeedBooster
     {
-        #region singleton
-
-        private static readonly Lazy<BikeSpeedBooster>
-            lazy =
-                new Lazy<BikeSpeedBooster>
-                    (() => new BikeSpeedBooster());
-
-        public static BikeSpeedBooster Instance => lazy.Value;
-
-        private readonly List<Booster> activeBooster = new List<Booster>();
-
-        #endregion
-
         public const float MaxBoost = 1.4f;
         public const float MinBoost = 0.6f;
         public const float ThresholdZero = 0.05f;
@@ -48,10 +35,10 @@ namespace Controller.Bicycle
         private const float DURATION_BOOST_UPHILL_STRAIGHT = 1.5f;
         private const float DURATION_BOOST_STRAIGHT_DOWNHILL = 3.5f;
         private const float DURATION_BOOST_DOWNHILL_STRAIGHT = 5f;
-
-        private float maxSlopeDeg = 8.7f;
         private float fixedBoost = 1;
 
+        private readonly float maxSlopeDeg = 8.7f;
+
         public float Boost
         {
             get
@@ -74,10 +61,7 @@ namespace Controller.Bicycle
                     boost *= add;
                 }
 
-                foreach (var d in toDelete)
-                {
-                    activeBooster.Remove(d);
-                }
+                foreach (var d in toDelete) activeBooster.Remove(d);
 
                 return Mathf.Clamp(boost, MinBoost, MaxBoost);
             }
@@ -90,7 +74,7 @@ namespace Controller.Bicycle
 
             //going from straight to uphill -> decrease speed from straight to slope
             //-> inverse fixed boost first, then 1*fixedBoost
-            
+
             var booster = new Booster(Time.time,
                 slopeDegree < 0 ? DURATION_BOOST_STRAIGHT_DOWNHILL : DURATION_BOOST_STRAIGHT_UPHILL,
                 1f / fixedBoost, 1f);
@@ -104,7 +88,7 @@ namespace Controller.Bicycle
 
             //going from uphill to straight -> don't go to 1 immediately
             //-> boost starts at fixedBoost and increases to 1
-            
+
             var booster = new Booster(Time.time,
                 slopeDegree < 0 ? DURATION_BOOST_DOWNHILL_STRAIGHT : DURATION_BOOST_UPHILL_STRAIGHT,
                 fixedBoost, 1f);
@@ -122,5 +106,18 @@ namespace Controller.Bicycle
         {
             fixedBoost = 1;
         }
+
+        #region singleton
+
+        private static readonly Lazy<BikeSpeedBooster>
+            lazy =
+                new Lazy<BikeSpeedBooster>
+                    (() => new BikeSpeedBooster());
+
+        public static BikeSpeedBooster Instance => lazy.Value;
+
+        private readonly List<Booster> activeBooster = new List<Booster>();
+
+        #endregion
     }
 }

+ 62 - 74
Assets/Scripts/Controller/Bicycle/RbBicycleController.cs

@@ -1,67 +1,9 @@
-using System;
-using Phscs;
-using UnityEngine;
+using UnityEngine;
 
 namespace Controller.Bicycle
 {
     public class RbBicycleController : BicycleControllerBaseBehaviour, IBicycleController
     {
-        #region Variables
-
-        private Transform rbTransform;
-        private float currentSteerAngle;
-        private float currentLeaningAngle;
-        private float currentSpeedAdjusted;
-        private float previousSoeedAdjusted;
-        private const float MAX_DIF_SPEED_ADJUSTED_PER_SECOND = 10f;
-        private BikeSpeedBooster speedBooster;
-
-        [Tooltip("Needs a RbBicycleSlopeSpeedManager to be attached to this GameObject")]
-        public bool adjustSpeedToSlope = true;
-
-        public Vector3 Forward => rbTransform.forward;
-
-        public Vector3 Right => -rbTransform.right;
-
-        public Vector3 Up => rbTransform.up;
-
-        public BicycleControllerMode ControllerMode
-        {
-            get => controllerMode;
-            set => controllerMode = value;
-        }
-
-        public float CurrentSpeedSensed { private set; get; }
-
-        public float CurrentSpeed
-        {
-            get => adjustSpeedToSlope ? currentSpeedAdjusted : CurrentSpeedSensed;
-            set => CurrentSpeedSensed = Mathf.Clamp(value, 0, maxSpeed);
-        }
-
-        public float CurrentSpeedKph => CurrentSpeed * 3.6f;
-
-        public float CurrentSteerAngle
-        {
-            get => currentSteerAngle;
-            set => currentSteerAngle = Mathf.Clamp(value, -maxSteeringAngle, maxSteeringAngle);
-        }
-
-        public float CurrentLeaningAngle
-        {
-            get => currentLeaningAngle;
-            set
-            {
-                //don't lean while standing / walking to bike
-                if (rigidBody.velocity.magnitude < .5f) return;
-                currentLeaningAngle = Mathf.Clamp(value, -maxLeaningAngle, maxLeaningAngle);
-            }
-        }
-
-        public Vector3 RigidBodyVelocity => rigidBody.velocity;
-
-        #endregion
-
         private void Awake()
         {
             rbTransform = rigidBody.transform;
@@ -74,11 +16,6 @@ namespace Controller.Bicycle
             speedBooster = BikeSpeedBooster.Instance;
         }
 
-        private void OnGUI()
-        {
-            GUI.TextField(new Rect(200, 100, 400, 50), $"Boost = {speedBooster.Boost}");
-        }
-
         private void FixedUpdate()
         {
             //rigidBody.isKinematic = currentSpeed <= THRESHOLD_STANDING;
@@ -87,6 +24,11 @@ namespace Controller.Bicycle
             ApplySteerAngleAndRotation();
         }
 
+        private void OnGUI()
+        {
+            GUI.TextField(new Rect(200, 100, 400, 50), $"Boost = {speedBooster.Boost}");
+        }
+
         //TODO: maybe add some kind of rolling physics after downhill
         private void ApplyVelocity()
         {
@@ -105,13 +47,9 @@ namespace Controller.Bicycle
                 var boost = speedBooster.Boost;
                 float nextSpeedAdjusted;
                 if (boost > 1 && CurrentSpeedSensed < 5.55f) //5.55 m/s = 20 km/h
-                {
                     nextSpeedAdjusted = 5.55f * boost;
-                }
                 else
-                {
                     nextSpeedAdjusted = CurrentSpeedSensed * speedBooster.Boost;
-                }
 
                 currentSpeedAdjusted = Mathf.Max(Mathf.Max(0,
                     previousSoeedAdjusted - Time.deltaTime * MAX_DIF_SPEED_ADJUSTED_PER_SECOND), nextSpeedAdjusted);
@@ -144,21 +82,71 @@ namespace Controller.Bicycle
 
             float rectifiedZ;
             if (r.z > 180f)
-            {
                 rectifiedZ = -360 + r.z;
-            }
             else if (r.z < -180f)
-            {
                 rectifiedZ = 360 + r.z;
-            }
             else
-            {
                 rectifiedZ = r.z;
-            }
 
             var leanDif = -CurrentLeaningAngle - rectifiedZ;
             rbTransform.localRotation =
                 Quaternion.Euler(r + new Vector3(0, calculatedSteerAngle, leanDif) * Time.fixedDeltaTime);
         }
+
+        #region Variables
+
+        private Transform rbTransform;
+        private float currentSteerAngle;
+        private float currentLeaningAngle;
+        private float currentSpeedAdjusted;
+        private float previousSoeedAdjusted;
+        private const float MAX_DIF_SPEED_ADJUSTED_PER_SECOND = 10f;
+        private BikeSpeedBooster speedBooster;
+
+        [Tooltip("Needs a RbBicycleSlopeSpeedManager to be attached to this GameObject")]
+        public bool adjustSpeedToSlope = true;
+
+        public Vector3 Forward => rbTransform.forward;
+
+        public Vector3 Right => -rbTransform.right;
+
+        public Vector3 Up => rbTransform.up;
+
+        public BicycleControllerMode ControllerMode
+        {
+            get => controllerMode;
+            set => controllerMode = value;
+        }
+
+        public float CurrentSpeedSensed { private set; get; }
+
+        public float CurrentSpeed
+        {
+            get => adjustSpeedToSlope ? currentSpeedAdjusted : CurrentSpeedSensed;
+            set => CurrentSpeedSensed = Mathf.Clamp(value, 0, maxSpeed);
+        }
+
+        public float CurrentSpeedKph => CurrentSpeed * 3.6f;
+
+        public float CurrentSteerAngle
+        {
+            get => currentSteerAngle;
+            set => currentSteerAngle = Mathf.Clamp(value, -maxSteeringAngle, maxSteeringAngle);
+        }
+
+        public float CurrentLeaningAngle
+        {
+            get => currentLeaningAngle;
+            set
+            {
+                //don't lean while standing / walking to bike
+                if (rigidBody.velocity.magnitude < .5f) return;
+                currentLeaningAngle = Mathf.Clamp(value, -maxLeaningAngle, maxLeaningAngle);
+            }
+        }
+
+        public Vector3 RigidBodyVelocity => rigidBody.velocity;
+
+        #endregion
     }
 }

+ 47 - 49
Assets/Scripts/Controller/Bicycle/WcBicycleController.cs

@@ -1,60 +1,13 @@
 using System.Collections.Generic;
-using Controller.Bicycle;
 using UnityEngine;
-using UnityEngine.Serialization;
 using Valve.VR.InteractionSystem;
 
 namespace Controller.Bicycle
 {
     public class WcBicycleController : BicycleControllerBaseBehaviour, IBicycleController
     {
-        #region Variables
-
-        [Header("Visible Game Objects")] public GameObject rearWheel;
-        public GameObject frontWheel;
-        public WheelConfig wheelConfig;
-
-        [Header("Values")] public float offsetCollidersFromWheel = 0.25f;
-        public float maxBreakTorque = 2000f;
-        public float maxMotorTorque = 1000f;
-
-        public BicycleControllerMode ControllerMode { get; set; }
-
-        public float CurrentSpeed
-        {
-            get => currentSpeed;
-            set => currentSpeed = Mathf.Clamp(value, 0, maxSpeed);
-        }
-
-        public float CurrentSteerAngle
-        {
-            get => currentSteerAngle;
-            set
-            {
-                //don't lean while standing / walking to bike
-                if (rigidBody.velocity.magnitude < .5f) return;
-                currentSteerAngle = Mathf.Clamp(value, -maxSteeringAngle, maxSteeringAngle);
-            }
-        }
-
-        public float CurrentLeaningAngle
-        {
-            get => currentLeaningAngle;
-            set => currentLeaningAngle = Mathf.Clamp(value, -maxLeaningAngle, maxLeaningAngle);
-        }
-        
-        public Vector3 RigidBodyVelocity => rigidBody.velocity;
-
-        private WheelCollider[] allWheelColliders;
-        private float initialWheelColliderY;
-        private float currentSteerAngle = 0f;
-        private float currentLeaningAngle = 0f;
-        private float currentSpeed;
-
-        #endregion
-
         // Start is called before the first frame update
-        void Start()
+        private void Start()
         {
             rigidBody.centerOfMass = centerOfMass.localPosition;
             allWheelColliders = wheelConfig.AllWheels;
@@ -63,7 +16,7 @@ namespace Controller.Bicycle
         }
 
 
-        void FixedUpdate()
+        private void FixedUpdate()
         {
             ApplyColliderForces();
             Lean();
@@ -162,5 +115,50 @@ namespace Controller.Bicycle
             var oldPos = t.localPosition;
             t.localPosition = new Vector3(oldPos.x, newY, oldPos.z);
         }
+
+        #region Variables
+
+        [Header("Visible Game Objects")] public GameObject rearWheel;
+        public GameObject frontWheel;
+        public WheelConfig wheelConfig;
+
+        [Header("Values")] public float offsetCollidersFromWheel = 0.25f;
+        public float maxBreakTorque = 2000f;
+        public float maxMotorTorque = 1000f;
+
+        public BicycleControllerMode ControllerMode { get; set; }
+
+        public float CurrentSpeed
+        {
+            get => currentSpeed;
+            set => currentSpeed = Mathf.Clamp(value, 0, maxSpeed);
+        }
+
+        public float CurrentSteerAngle
+        {
+            get => currentSteerAngle;
+            set
+            {
+                //don't lean while standing / walking to bike
+                if (rigidBody.velocity.magnitude < .5f) return;
+                currentSteerAngle = Mathf.Clamp(value, -maxSteeringAngle, maxSteeringAngle);
+            }
+        }
+
+        public float CurrentLeaningAngle
+        {
+            get => currentLeaningAngle;
+            set => currentLeaningAngle = Mathf.Clamp(value, -maxLeaningAngle, maxLeaningAngle);
+        }
+
+        public Vector3 RigidBodyVelocity => rigidBody.velocity;
+
+        private WheelCollider[] allWheelColliders;
+        private float initialWheelColliderY;
+        private float currentSteerAngle;
+        private float currentLeaningAngle;
+        private float currentSpeed;
+
+        #endregion
     }
 }

+ 5 - 4
Assets/Scripts/Controller/Bicycle/WheelConfig.cs

@@ -1,8 +1,9 @@
-using UnityEngine;
+using System;
+using UnityEngine;
 
 namespace Controller.Bicycle
 {
-    [System.Serializable]
+    [Serializable]
     public class WheelConfig
     {
         public WheelCollider frontLeft;
@@ -19,7 +20,7 @@ namespace Controller.Bicycle
             var posFront = frontWheel.localPosition;
             var newXLeftFront = posFront.x - offset;
             var newXRightFront = posFront.x + offset;
-        
+
             var posRear = rearWheel.localPosition;
             var newXLeftRear = posRear.x - offset;
             var newXRightRear = posRear.x + offset;
@@ -29,7 +30,7 @@ namespace Controller.Bicycle
             var newY = localPosition.y;
             var newZFront = localPosition.z;
             var newZRear = rearLeft.transform.localPosition.z;
-        
+
             SetNewCoords(transform, newXLeftFront, newY, newZFront);
             SetNewCoords(frontRight.transform, newXRightFront, newY, newZFront);
             SetNewCoords(rearLeft.transform, newXLeftRear, newY, newZRear);

+ 5 - 5
Assets/Scripts/Controller/GamepadBikeController.cs

@@ -17,14 +17,14 @@ namespace Controller
         public float speedMultiplier = 200f;
         public float leanMultiplier = 20f;
         public float steerMultiplier = 15f;
-
-        private float accelerationLoss = 0.5f;
         private float acceleration;
-        private float lean;
-        private float steer;
+
+        private readonly float accelerationLoss = 0.5f;
         private IBicycleController bicycleController;
+        private float lean;
 
-        private float speed = 0f;
+        private float speed;
+        private float steer;
 
         private void Start()
         {

+ 5 - 22
Assets/Scripts/Controller/KeyboardBikeController.cs

@@ -6,8 +6,6 @@ namespace Controller
     [RequireComponent(typeof(IBicycleController))]
     public class KeyboardBikeController : MonoBehaviour
     {
-        private IBicycleController bicycleController;
-
         public bool steer = true;
         public bool lean = true;
         public bool accelerate = true;
@@ -17,6 +15,7 @@ namespace Controller
         public float brakeIncreasePerSecond = 5f;
         public float leaningAngleIncreasePerSecond = 2f;
         public float steeringAngleIncreasePerSecond = 2.5f;
+        private IBicycleController bicycleController;
 
         private float sensedSpeed;
 
@@ -41,49 +40,33 @@ namespace Controller
                 }
 
                 if (Input.GetKey(KeyCode.G))
-                {
-                   // sensedSpeed = Mathf.Max(0,
+                    // sensedSpeed = Mathf.Max(0,
                     //    sensedSpeed - brakeIncreasePerSecond * Time.deltaTime);
                     bicycleController.CurrentSpeed = 0f;
-                }
 
-               //bicycleController.CurrentSpeed = sensedSpeed;
+                //bicycleController.CurrentSpeed = sensedSpeed;
             }
 
             if (steer)
             {
                 if (Input.GetKey(KeyCode.F))
-                {
                     bicycleController.CurrentSteerAngle -= steeringAngleIncreasePerSecond * Time.deltaTime;
-                }
 
                 if (Input.GetKey(KeyCode.H))
-                {
                     bicycleController.CurrentSteerAngle += steeringAngleIncreasePerSecond * Time.deltaTime;
-                }
 
-                if (Input.GetKeyUp(KeyCode.F) || Input.GetKeyUp(KeyCode.H))
-                {
-                    bicycleController.CurrentSteerAngle = 0f;
-                }
+                if (Input.GetKeyUp(KeyCode.F) || Input.GetKeyUp(KeyCode.H)) bicycleController.CurrentSteerAngle = 0f;
             }
 
             if (lean)
             {
                 if (Input.GetKey(KeyCode.R))
-                {
                     bicycleController.CurrentLeaningAngle -= leaningAngleIncreasePerSecond * Time.deltaTime;
-                }
 
                 if (Input.GetKey(KeyCode.Z))
-                {
                     bicycleController.CurrentLeaningAngle += leaningAngleIncreasePerSecond * Time.deltaTime;
-                }
 
-                if (Input.GetKeyUp(KeyCode.R) || Input.GetKeyUp(KeyCode.Z))
-                {
-                    bicycleController.CurrentLeaningAngle = 0f;
-                }
+                if (Input.GetKeyUp(KeyCode.R) || Input.GetKeyUp(KeyCode.Z)) bicycleController.CurrentLeaningAngle = 0f;
             }
         }
     }

+ 3 - 15
Assets/Scripts/Controller/Lean/HmdLeanController.cs

@@ -1,24 +1,12 @@
-using System;
-using System.Collections.Generic;
-using Tracking;
+using Tracking;
 using UnityEngine;
-using UnityEngine.XR;
-using Valve.VR;
 
 namespace Controller.Lean
 {
-    public class HmdLeanController: MonoBehaviour, ILeanController
+    public class HmdLeanController : MonoBehaviour, ILeanController
     {
-        public float LeanAngle => cameraTracker.LeanRotation;
-
         public CameraTracker cameraTracker;
 
-        private void Start()
-        {
-           }
-
-        private void Update()
-        {
-        }
+        public float LeanAngle => cameraTracker.LeanRotation;
     }
 }

+ 1 - 3
Assets/Scripts/Controller/Lean/ILeanController.cs

@@ -1,6 +1,4 @@
-using UnityEngine;
-
-namespace Controller.Lean
+namespace Controller.Lean
 {
     public interface ILeanController
     {

+ 3 - 10
Assets/Scripts/Controller/Lean/PolarLeanController.cs

@@ -1,7 +1,5 @@
 using System;
 using Sensors;
-using Sensors.Polar;
-using UnityEngine;
 
 namespace Controller.Lean
 {
@@ -14,13 +12,11 @@ namespace Controller.Lean
 
     public class PolarLeanController : ILeanController
     {
-        public PolarRotationMapping polarRotationMapping;
         private float leanFactor;
+        public PolarRotationMapping polarRotationMapping;
         private BikeSensorData sensorData;
 
-        public float LeanAngle => leanAngle;
-
-        private float leanAngle = 0f;
+        public float LeanAngle { get; private set; }
 
         private void Start()
         {
@@ -31,10 +27,7 @@ namespace Controller.Lean
         private void Update()
         {
             var polarData = sensorData.PolarData;
-            if (polarData != null)
-            {
-                leanAngle = (polarData.Value.Acc.y - polarRotationMapping.center) * leanFactor;
-            }
+            if (polarData != null) LeanAngle = (polarData.Value.Acc.y - polarRotationMapping.center) * leanFactor;
         }
     }
 }

+ 5 - 15
Assets/Scripts/Controller/SensorBikeController.cs

@@ -3,10 +3,8 @@ using Controller.Bicycle;
 using Controller.Lean;
 using Sensors;
 using Sensors.ANT;
-using Sensors.Polar;
 using Tracking;
 using UnityEngine;
-using UnityEngine.Serialization;
 
 namespace Controller
 {
@@ -30,8 +28,8 @@ namespace Controller
         public bool lean = true;
 
         private IBicycleController bicycleController;
-        private BikeSensorData sensorData;
         private bool isFrontWheelTrackerNotNull;
+        private BikeSensorData sensorData;
 
         private void Start()
         {
@@ -44,20 +42,11 @@ namespace Controller
         {
             var speedData = sensorData.SpeedData;
 
-            if (speedData != null && accelerate)
-            {
-                SetSpeed(speedData.Value);
-            }
+            if (speedData != null && accelerate) SetSpeed(speedData.Value);
 
-            if (isFrontWheelTrackerNotNull && steer)
-            {
-                SetSteer();
-            }
+            if (isFrontWheelTrackerNotNull && steer) SetSteer();
 
-            if (lean)
-            {
-                SetLeaningAngle();
-            }
+            if (lean) SetLeaningAngle();
         }
 
         private void SetSteer()
@@ -65,6 +54,7 @@ namespace Controller
             bicycleController.CurrentSteerAngle =
                 frontWheelTrackerConfig.AdjustedRotation;
         }
+
         private void SetLeaningAngle()
         {
             //bicycleController.CurrentLeaningAngle = 

+ 4 - 4
Assets/Scripts/Controller/ViveBikeController.cs

@@ -11,18 +11,18 @@ namespace Controller
         public float multiplier = 40f;
 
         private IBicycleController bicycleController;
-    
+
         // Start is called before the first frame update
-        void Start()
+        private void Start()
         {
             bicycleController = GetComponent<IBicycleController>();
         }
 
         // Update is called once per frame
-        void Update()
+        private void Update()
         {
             var rot = steerPose.localRotation.y;
             bicycleController.CurrentSteerAngle = rot * multiplier;
         }
     }
-}
+}

+ 6 - 6
Assets/Scripts/Display/BikeDataDisplay.cs

@@ -8,22 +8,22 @@ namespace Display
     public class BikeDataDisplay : MonoBehaviour
     {
         public TextMeshProUGUI cadenceDisplay;
-        private bool cadenceDisplayAvailable;
         public TextMeshProUGUI heartRateDisplay;
-        private bool heartRateDisplayAvailable;
 
         public TextMeshProUGUI powerDisplay;
-        private bool powerDisplayAvailable;
-
-        private BikeSensorData sensorData;
 
         [Header("Speed")] public RbBicycleController bicycleController;
         public TextMeshProUGUI speedDisplay;
         public bool useSpeedFromBicycleController = true;
+        public TextMeshProUGUI torqueDisplay;
+        private bool cadenceDisplayAvailable;
+        private bool heartRateDisplayAvailable;
+        private bool powerDisplayAvailable;
+
+        private BikeSensorData sensorData;
 
 
         private bool speedDisplayAvailable;
-        public TextMeshProUGUI torqueDisplay;
         private bool torqueDisplayAvailable;
 
         // Start is called before the first frame update

+ 4 - 6
Assets/Scripts/Display/CountdownDisplay.cs

@@ -1,21 +1,19 @@
-using System;
-using TMPro;
+using TMPro;
 using UnityEngine;
-using Debug = System.Diagnostics.Debug;
 
 namespace Display
 {
     public class CountdownDisplay : InFrontOfCameraDisplay
     {
+        public delegate string CountdownDoneCallback();
+
         public int countdown = 3;
         public TextMeshProUGUI countdownText;
 
-        public delegate string CountdownDoneCallback();
+        private float lastTime;
 
         public CountdownDoneCallback OnCountdownDone { get; set; }
 
-        private float lastTime;
-
         protected override void Start()
         {
             base.Start();

+ 2 - 6
Assets/Scripts/Display/DebugDisplay.cs

@@ -1,6 +1,4 @@
-using System.Net;
-using System.Net.Sockets;
-using System.Text;
+using System.Text;
 using Controller.Bicycle;
 using Sensors;
 using UnityEngine;
@@ -10,9 +8,9 @@ namespace Display
     public class DebugDisplay<T> : MonoBehaviour where T : IBicycleController
     {
         public T bicycleController;
+        private readonly BikeSensorData sensorData = BikeSensorData.Instance;
 
         private string ip;
-        private readonly BikeSensorData sensorData = BikeSensorData.Instance;
         private string text;
 
 
@@ -50,7 +48,5 @@ namespace Display
 
             GUI.TextField(new Rect(x, y, width, height), text);
         }
-
-        
     }
 }

+ 1 - 3
Assets/Scripts/Display/InFrontOfCameraDisplay.cs

@@ -1,6 +1,4 @@
-using System;
-using TMPro;
-using UnityEngine;
+using UnityEngine;
 using Debug = System.Diagnostics.Debug;
 
 namespace Display

+ 31 - 34
Assets/Scripts/Display/LookStraightDisplay.cs

@@ -8,40 +8,35 @@ namespace Display
 {
     public class LookStraightDisplay : MonoBehaviour
     {
+        public delegate void DoneCallback();
+
         public Image circleImage;
         public float timeToLookStraight = 1.5f;
-
-        private Color startColor = Color.white.ColorWithAlpha(100);
-        private Color endColor = Color.green.ColorWithAlpha(100);
-
-        private float startTime;
+        private Transform camTransform;
+        private readonly Color endColor = Color.green.ColorWithAlpha(100);
 
         private List<Vector3> positions;
         private List<Quaternion> quaternions;
-        private Transform camTransform;
 
-        public delegate void DoneCallback();
+        private readonly Color startColor = Color.white.ColorWithAlpha(100);
+
+        private float startTime;
 
         public DoneCallback OnDone { get; set; }
 
-        private void OnEnable()
+
+        private void Update()
         {
-            circleImage = GetComponentInChildren<Image>();
-            ResetCircle();
+            var timePassed = Time.time - startTime;
+            var currentColor = Color.Lerp(startColor, endColor, timePassed / timeToLookStraight);
+            circleImage.color = currentColor;
 
-            var cam = Camera.main;
-            if (cam == null)
+            if (timePassed >= timeToLookStraight)
             {
-                throw new Exception("No camera available");
+                OnDone();
+                gameObject.SetActive(false);
+                Destroy(gameObject);
             }
-
-            camTransform = cam.transform;
-        }
-
-        private void ResetCircle()
-        {
-            circleImage.color = startColor;
-            startTime = Time.time;
         }
 
         private void FixedUpdate()
@@ -50,30 +45,32 @@ namespace Display
             var layerMask = 1 << gameObject.layer;
             if (Physics.Raycast(camTransform.position, camTransform.forward, out var hit, 2f, layerMask))
             {
-                Debug.DrawRay(camTransform.position, camTransform.forward*hit.distance, Color.green);
+                Debug.DrawRay(camTransform.position, camTransform.forward * hit.distance, Color.green);
                 //Debug.Log($"Hit something ({hit.collider.gameObject.layer})");
             }
             else
             {
-                Debug.DrawRay(camTransform.position, camTransform.forward*2f, Color.red);
+                Debug.DrawRay(camTransform.position, camTransform.forward * 2f, Color.red);
                 //Debug.Log("Hit nothing");
                 ResetCircle();
             }
         }
 
-
-        private void Update()
+        private void OnEnable()
         {
-            var timePassed = Time.time - startTime;
-            var currentColor = Color.Lerp(startColor, endColor, timePassed / timeToLookStraight);
-            circleImage.color = currentColor;
+            circleImage = GetComponentInChildren<Image>();
+            ResetCircle();
 
-            if (timePassed >= timeToLookStraight)
-            {
-                OnDone();
-                gameObject.SetActive(false);
-                Destroy(gameObject);
-            }
+            var cam = Camera.main;
+            if (cam == null) throw new Exception("No camera available");
+
+            camTransform = cam.transform;
+        }
+
+        private void ResetCircle()
+        {
+            circleImage.color = startColor;
+            startTime = Time.time;
         }
     }
 }

+ 14 - 15
Assets/Scripts/Display/ViveTrackerDebugDisplay.cs

@@ -1,5 +1,4 @@
-using System.Globalization;
-using TMPro;
+using TMPro;
 using Tracking;
 using UnityEngine;
 using UnityEngine.UI;
@@ -24,19 +23,19 @@ namespace Display
         public KineticLegTracker legTracker;
 
         private SteamVR_TrackedObject fwTrackedObject;
-        private SteamVR_TrackedObject legTrackedObject;
-
-        private bool isFwTrackerNull;
-        private bool islegTrackerNull;
+        private bool isbatteryTextFwNotNull;
+        private bool isbatteryTextLegNotNull;
 
         private bool isFwTrackedObjectNull;
+
+        private bool isFwTrackerNull;
         private bool isLegTrackedObjectNull;
-        private bool isrotTextNotNull;
+        private bool islegTrackerNull;
         private bool isposTextNotNull;
-        private bool isbatteryTextFwNotNull;
-        private bool isbatteryTextLegNotNull;
+        private bool isrotTextNotNull;
         private bool isstatusTextFwNotNull;
         private bool isstatusTextLegNotNull;
+        private SteamVR_TrackedObject legTrackedObject;
 
         // Start is called before the first frame update
         private void Start()
@@ -65,15 +64,15 @@ namespace Display
                 if (isposTextNotNull) posText.text = $"Pos: {fwTracker.RelativePosition.ToString()}";
                 if (isrotTextNotNull) rotText.text = $"Rot: {fwTracker.SteerRotation:n2}";
                 if (isbatteryTextFwNotNull) batteryTextFw.text = $"Battery: {fwTracker.BatteryLevel}";
-                if (isstatusTextFwNotNull) statusTextFw.text = $"Status: Connected";
+                if (isstatusTextFwNotNull) statusTextFw.text = "Status: Connected";
                 fwImage.color = Color.green;
             }
             else
             {
-                if (isposTextNotNull) posText.text = $"Pos: -";
-                if (isrotTextNotNull) rotText.text = $"Rot: -";
+                if (isposTextNotNull) posText.text = "Pos: -";
+                if (isrotTextNotNull) rotText.text = "Rot: -";
                 fwImage.color = Color.grey.ColorWithAlpha(100);
-                if (isstatusTextFwNotNull) statusTextFw.text = $"Status: Disconnected";
+                if (isstatusTextFwNotNull) statusTextFw.text = "Status: Disconnected";
             }
 
             if (!islegTrackerNull & legTracker.isActiveAndEnabled && !isLegTrackedObjectNull &&
@@ -81,12 +80,12 @@ namespace Display
             {
                 legImage.color = Color.green;
                 if (isbatteryTextLegNotNull) batteryTextLeg.text = $"Battery: {legTracker.BatteryLevel}";
-                if (isstatusTextLegNotNull) statusTextLeg.text = $"Status: Connected";
+                if (isstatusTextLegNotNull) statusTextLeg.text = "Status: Connected";
             }
             else
             {
                 legImage.color = Color.grey.ColorWithAlpha(100);
-                if (isstatusTextLegNotNull) statusTextLeg.text = $"Status: Disconnected";
+                if (isstatusTextLegNotNull) statusTextLeg.text = "Status: Disconnected";
             }
         }
     }

+ 7 - 14
Assets/Scripts/DuplicateManager.cs

@@ -1,5 +1,4 @@
-using System;
-using System.Collections.Generic;
+using System.Collections.Generic;
 using System.Linq;
 using UnityEngine;
 
@@ -31,16 +30,16 @@ public class DuplicateManager : MonoBehaviour
             }
         }
 
-        Debug.Log($"Done sorting");
+        Debug.Log("Done sorting");
 
         var objs = objectsAtPos.Values.Where(l => l.Count > 1);
         var enumerable = objs as List<GameObject>[] ?? objs.ToArray();
         Debug.LogWarning($"{enumerable.Count()} gameobjects at exact same position");
         Debug.Log("Deleting objects..");
 
-        int deleteCounter = 0;
-        int skipCounter = 0;
-        
+        var deleteCounter = 0;
+        var skipCounter = 0;
+
         foreach (var o in enumerable)
         {
             var rMap = new Dictionary<Quaternion, List<GameObject>>();
@@ -48,13 +47,9 @@ public class DuplicateManager : MonoBehaviour
             {
                 var rot = d.transform.rotation;
                 if (rMap.ContainsKey(rot))
-                {
                     rMap[rot].Add(d);
-                }
                 else
-                {
                     rMap[rot] = new List<GameObject> {d};
-                }
 
                 //Destroy(d);
             }
@@ -69,9 +64,8 @@ public class DuplicateManager : MonoBehaviour
                 if (r.Aggregate((result, item) =>
                 {
                     if (result == null) return null;
-                    else return result.name.Equals(item.name) ? item : null;
+                    return result.name.Equals(item.name) ? item : null;
                 }) != null)
-                {
                     for (var index = 1; index < r.Count; index++)
                     {
                         var gameObject1 = r[index];
@@ -87,10 +81,9 @@ public class DuplicateManager : MonoBehaviour
 
                         deleteCounter++;
                     }
-                }
             }
         }
-        
+
         Debug.LogWarning($"Deleted {deleteCounter} items!");
         Debug.LogWarning($"Skipped {skipCounter} items!");
     }

+ 14 - 14
Assets/Scripts/Helpers.cs

@@ -15,7 +15,6 @@ public class Helpers
             v3 = Vector3.Cross(normal, Vector3.forward).normalized * normal.magnitude;
         else
             v3 = Vector3.Cross(normal, Vector3.up).normalized * normal.magnitude;
-        ;
 
         var corner0 = position + v3;
         var corner2 = position - v3;
@@ -35,14 +34,14 @@ public class Helpers
 
     public static void DrawLine(Vector3 p1, Vector3 p2, float width)
     {
-        int count = 1 + Mathf.CeilToInt(width); // how many lines are needed.
+        var count = 1 + Mathf.CeilToInt(width); // how many lines are needed.
         if (count == 1)
         {
             Gizmos.DrawLine(p1, p2);
         }
         else
         {
-            Camera c = Camera.current;
+            var c = Camera.current;
             if (c == null)
             {
                 Debug.LogError("Camera.current is null");
@@ -52,14 +51,14 @@ public class Helpers
             var scp1 = c.WorldToScreenPoint(p1);
             var scp2 = c.WorldToScreenPoint(p2);
 
-            Vector3 v1 = (scp2 - scp1).normalized; // line direction
-            Vector3 n = Vector3.Cross(v1, Vector3.forward); // normal vector
+            var v1 = (scp2 - scp1).normalized; // line direction
+            var n = Vector3.Cross(v1, Vector3.forward); // normal vector
 
-            for (int i = 0; i < count; i++)
+            for (var i = 0; i < count; i++)
             {
-                Vector3 o = 0.99f * n * width * ((float) i / (count - 1) - 0.5f);
-                Vector3 origin = c.ScreenToWorldPoint(scp1 + o);
-                Vector3 destiny = c.ScreenToWorldPoint(scp2 + o);
+                var o = 0.99f * n * width * ((float) i / (count - 1) - 0.5f);
+                var origin = c.ScreenToWorldPoint(scp1 + o);
+                var destiny = c.ScreenToWorldPoint(scp2 + o);
                 Gizmos.DrawLine(origin, destiny);
             }
         }
@@ -84,11 +83,13 @@ public class Helpers
         return (long) Mathf.Round(f);
     }
 
-    public static Vector3 Vector3Abs(Vector3 value) =>
-        new Vector3(Mathf.Abs(value.x), Mathf.Abs(value.y), Mathf.Abs(value.z));
+    public static Vector3 Vector3Abs(Vector3 value)
+    {
+        return new Vector3(Mathf.Abs(value.x), Mathf.Abs(value.y), Mathf.Abs(value.z));
+    }
 
     /// <summary>
-    /// Remove outliers using the interquartile range method
+    ///     Remove outliers using the interquartile range method
     /// </summary>
     /// <param name="collection">A collection of floats, from which outliers are to be removed</param>
     /// <returns>A collection without the outliers</returns>
@@ -99,7 +100,7 @@ public class Helpers
         var range = 1.5f * quartiles.Iqr;
 
         // see https://www.statology.org/outliers-excel/
-        return collection.Where((v) => v >= quartiles.Q1 - range && v <= quartiles.Q3 + range);
+        return collection.Where(v => v >= quartiles.Q1 - range && v <= quartiles.Q3 + range);
     }
 
     public static IPAddress GetIPAddress()
@@ -113,5 +114,4 @@ public class Helpers
 
         return usedIp;
     }
-
 }

+ 5 - 11
Assets/Scripts/IgnoreClipping.cs

@@ -1,6 +1,4 @@
-using System.Collections;
-using System.Collections.Generic;
-using UnityEngine;
+using UnityEngine;
 
 public class IgnoreClipping : MonoBehaviour
 {
@@ -9,18 +7,14 @@ public class IgnoreClipping : MonoBehaviour
 
     public int smallObjectsLayer = 14;
     public float smallObjectsDistance = 200f;
-    
-    void Start()
+
+    private void Start()
     {
         var cam = GetComponent<Camera>();
         var distances = new float[32];
-        for (int i = 0; i < distances.Length; i++)
-        {
-            distances[i] = preClippingDistance;
-        }
+        for (var i = 0; i < distances.Length; i++) distances[i] = preClippingDistance;
         distances[ignoreClippingLayer] = 0f;
         distances[smallObjectsLayer] = smallObjectsDistance;
         cam.layerCullDistances = distances;
     }
-
-}
+}

+ 4 - 11
Assets/Scripts/Logging/Base/AsyncLogFileWriter.cs

@@ -13,10 +13,7 @@ namespace Logging.Base
         public AsyncLogFileWriter(string path)
         {
             var fileInfo = new FileInfo(path);
-            if (!fileInfo.Directory?.Exists ?? false)
-            {
-                fileInfo.Directory?.Create();
-            }
+            if (!fileInfo.Directory?.Exists ?? false) fileInfo.Directory?.Create();
             writer = new StreamWriter(path) {AutoFlush = true};
         }
 
@@ -25,7 +22,7 @@ namespace Logging.Base
         {
             await writer.WriteLineAsync($"{xValue}\t{string.Join("\t", values)}");
         }
-        
+
         public async Task WriteDataLine<T>(IEnumerable<T> values)
         {
             await writer.WriteLineAsync($"{string.Join("\t", values)}");
@@ -34,12 +31,9 @@ namespace Logging.Base
         public async Task WriteDataLines<T>(IEnumerable<IEnumerable<T>> lines)
         {
             //This method is ultimately called by an Update Method. Unity doesn't await Update
-           
+
             var sb = new StringBuilder();
-            foreach (var l in lines)
-            {
-                sb.Append($"{string.Join("\t", l)}\n");
-            }
+            foreach (var l in lines) sb.Append($"{string.Join("\t", l)}\n");
 
             await writer.WriteAsync(sb.ToString());
         }
@@ -48,6 +42,5 @@ namespace Logging.Base
         {
             writer?.Close();
         }
-        
     }
 }

+ 34 - 47
Assets/Scripts/Logging/Base/FileLogger.cs

@@ -8,35 +8,12 @@ namespace Logging.Base
 {
     public class FileLogger
     {
-        #region signleton
-
-        private static Lazy<FileLogger>
-            instance =
-                new Lazy<FileLogger>
-                    (() => new FileLogger());
-
-        public static FileLogger Instance => instance.Value;
-
-        public static void DestroyInstance()
-        {
-            if (instance.IsValueCreated)
-            {
-                instance.Value.Dispose();
-                instance =
-                    new Lazy<FileLogger>
-                        (() => new FileLogger());
-            }
-        }
-
-        #endregion
+        private readonly List<ILogable> logables;
 
         private readonly DateTime startTimestamp;
-        private AsyncLogFileWriter writer;
-        private readonly List<ILogable> logables;
-        private bool writerAvailable = false;
         private readonly Dictionary<string, Dictionary<long, string[]>> waitingBuffers;
-        public string SubFolderName { get; set; }
-        public string Condition { get; set; }
+        private AsyncLogFileWriter writer;
+        private bool writerAvailable;
 
         private FileLogger()
         {
@@ -45,16 +22,19 @@ namespace Logging.Base
             logables = new List<ILogable>();
         }
 
-        public void RegisterLogable(ILogable l) => logables.Add(l);
+        public string SubFolderName { get; set; }
+        public string Condition { get; set; }
+
+        public void RegisterLogable(ILogable l)
+        {
+            logables.Add(l);
+        }
 
 
         private IEnumerable<string> MergedHeaders()
         {
             var headers = new List<string> {"timestamp"};
-            foreach (var l in logables)
-            {
-                headers.AddRange(l.HeaderNames);
-            }
+            foreach (var l in logables) headers.AddRange(l.HeaderNames);
 
             return headers.ToArray();
         }
@@ -83,18 +63,11 @@ namespace Logging.Base
                 var hasWaiting = waitingBuffers.TryGetValue(logableKey, out var waiting);
 
                 if (hasWaiting)
-                {
                     foreach (var waitingTs in waiting.Keys)
-                    {
                         if (waitingTs <= minEnd)
-                        {
                             allTimestamps.Add(waitingTs);
-                        }
-                    }
-                }
 
                 foreach (var t in timestamps)
-                {
                     if (t >= minBegin && t <= minEnd)
                     {
                         allTimestamps.Add(t);
@@ -102,15 +75,10 @@ namespace Logging.Base
                     else
                     {
                         if (waitingBuffers.ContainsKey(l.Key))
-                        {
                             waitingBuffers[l.Key][t] = bufferLines[t];
-                        }
                         else
-                        {
                             waitingBuffers[l.Key] = new Dictionary<long, string[]> {{t, bufferLines[t]}};
-                        }
                     }
-                }
             }
 
             logables.ForEach(l => allTimestamps.UnionWith(l.BufferLines.Keys.Where(k => k >= minBegin && k <= minEnd)));
@@ -185,12 +153,31 @@ namespace Logging.Base
 
         private void Dispose()
         {
-            if (writerAvailable)
-            {
-                writer.Dispose();
-            }
+            if (writerAvailable) writer.Dispose();
 
             logables.Clear();
         }
+
+        #region signleton
+
+        private static Lazy<FileLogger>
+            instance =
+                new Lazy<FileLogger>
+                    (() => new FileLogger());
+
+        public static FileLogger Instance => instance.Value;
+
+        public static void DestroyInstance()
+        {
+            if (instance.IsValueCreated)
+            {
+                instance.Value.Dispose();
+                instance =
+                    new Lazy<FileLogger>
+                        (() => new FileLogger());
+            }
+        }
+
+        #endregion
     }
 }

+ 1 - 0
Assets/Scripts/Logging/Base/ILogable.cs

@@ -11,6 +11,7 @@ namespace Logging.Base
 
         void ClearBuffer();
     }
+
     public interface ISerializableLog<T>
     {
         void Log(T value);

+ 5 - 8
Assets/Scripts/Logging/Base/Logging.cs

@@ -8,11 +8,11 @@ namespace Logging.Base
         public float writeInterval = 1f;
         public SubjectManager subjectManager;
         public ConditionManager conditionManager;
-
-        private float prevLogTimestamp;
         private FileLogger logger;
         private Task previousLogUpdateTask = Task.CompletedTask;
 
+        private float prevLogTimestamp;
+
         private void Awake()
         {
             gameObject.SetActive(false);
@@ -27,9 +27,9 @@ namespace Logging.Base
 
         private void Update()
         {
-            if(!previousLogUpdateTask.IsCompleted) return;
+            if (!previousLogUpdateTask.IsCompleted) return;
             var time = Time.time;
-            var dif =  time - prevLogTimestamp;
+            var dif = time - prevLogTimestamp;
             if (dif >= writeInterval)
             {
                 prevLogTimestamp = time;
@@ -39,10 +39,7 @@ namespace Logging.Base
 
         private async void OnDestroy()
         {
-            if (logger != null)
-            {
-                await logger.UpdateRegisteredLogs();
-            }
+            if (logger != null) await logger.UpdateRegisteredLogs();
             FileLogger.DestroyInstance();
         }
     }

+ 19 - 15
Assets/Scripts/Logging/Data/BikeGameObjectDataLogger.cs

@@ -1,4 +1,5 @@
-using System.Collections.Generic;
+using System;
+using System.Collections.Generic;
 using System.Globalization;
 using Logging.Base;
 using UnityEngine;
@@ -33,19 +34,22 @@ namespace Logging.Data
             this.velocityZ = velocityZ;
         }
 
-        public KeyValuePair<long, string[]> Serialize() => new KeyValuePair<long, string[]>(
-            timestamp, new[]
-            {
-                positionX.ToString("F6", CultureInfo.InvariantCulture),
-                positionY.ToString("F6", CultureInfo.InvariantCulture),
-                positionZ.ToString("F6", CultureInfo.InvariantCulture),
-                rotationX.ToString("F6", CultureInfo.InvariantCulture),
-                rotationY.ToString("F6", CultureInfo.InvariantCulture),
-                rotationZ.ToString("F6", CultureInfo.InvariantCulture),
-                velocityX.ToString("F6", CultureInfo.InvariantCulture),
-                velocityY.ToString("F6", CultureInfo.InvariantCulture),
-                velocityZ.ToString("F6", CultureInfo.InvariantCulture)
-            });
+        public KeyValuePair<long, string[]> Serialize()
+        {
+            return new KeyValuePair<long, string[]>(
+                timestamp, new[]
+                {
+                    positionX.ToString("F6", CultureInfo.InvariantCulture),
+                    positionY.ToString("F6", CultureInfo.InvariantCulture),
+                    positionZ.ToString("F6", CultureInfo.InvariantCulture),
+                    rotationX.ToString("F6", CultureInfo.InvariantCulture),
+                    rotationY.ToString("F6", CultureInfo.InvariantCulture),
+                    rotationZ.ToString("F6", CultureInfo.InvariantCulture),
+                    velocityX.ToString("F6", CultureInfo.InvariantCulture),
+                    velocityY.ToString("F6", CultureInfo.InvariantCulture),
+                    velocityZ.ToString("F6", CultureInfo.InvariantCulture)
+                });
+        }
     }
 
     public class BikeGameObjectDataLogger : SensorDataLogger<BikeGameObjectDataLog>
@@ -74,7 +78,7 @@ namespace Logging.Data
 
         public override IEnumerable<BikeGameObjectDataLog> ReadLog(IEnumerable<IEnumerable<string>> lines)
         {
-            throw new System.NotImplementedException(); //TODO
+            throw new NotImplementedException(); //TODO
         }
     }
 }

+ 11 - 9
Assets/Scripts/Logging/Data/BikeSensorDataLogger.cs

@@ -26,24 +26,26 @@ namespace Logging.Data
             this.power = power;
         }
 
-        public KeyValuePair<long, string[]> Serialize() => new KeyValuePair<long, string[]>(timestamp, new[]
+        public KeyValuePair<long, string[]> Serialize()
         {
-            speed.ToString("F4", CultureInfo.InvariantCulture),
-            cadence.ToString("F4", CultureInfo.InvariantCulture),
-            heartRate.ToString(),
-            torque.ToString("F4", CultureInfo.InvariantCulture),
-            power.ToString("F4", CultureInfo.InvariantCulture)
-        });
+            return new KeyValuePair<long, string[]>(timestamp, new[]
+            {
+                speed.ToString("F4", CultureInfo.InvariantCulture),
+                cadence.ToString("F4", CultureInfo.InvariantCulture),
+                heartRate.ToString(),
+                torque.ToString("F4", CultureInfo.InvariantCulture),
+                power.ToString("F4", CultureInfo.InvariantCulture)
+            });
+        }
     }
 
     public class BikeSensorDataLogger : SensorDataLogger<BikeSensorDataLog>
     {
-        public override string Key => "bike_sensor_data";
-
         [Tooltip("Uses Heart Rate transmitted by bluetooth instead of ANT+")]
         public bool usePolarHeartRate;
 
         private BikeSensorData bikeSensorData;
+        public override string Key => "bike_sensor_data";
 
         public override void Start()
         {

+ 17 - 13
Assets/Scripts/Logging/Data/FrontWheelTrackerLogger.cs

@@ -1,4 +1,5 @@
-using System.Collections.Generic;
+using System;
+using System.Collections.Generic;
 using System.Globalization;
 using Logging.Base;
 using Tracking;
@@ -36,18 +37,21 @@ namespace Logging.Data
             this.debugFrontWheelTrackerRelativePositionZ = debugFrontWheelTrackerRelativePositionZ;
         }
 
-        public KeyValuePair<long, string[]> Serialize() => new KeyValuePair<long, string[]>(timestamp, new[]
+        public KeyValuePair<long, string[]> Serialize()
         {
-            debugLegTrackerPositionX.ToString("F4", CultureInfo.InvariantCulture),
-            debugLegTrackerPositionY.ToString("F4", CultureInfo.InvariantCulture),
-            debugLegTrackerPositionZ.ToString("F4", CultureInfo.InvariantCulture),
-            debugPosOnBikePlaneX.ToString("F4", CultureInfo.InvariantCulture),
-            debugPosOnBikePlaneY.ToString("F4", CultureInfo.InvariantCulture),
-            debugPosOnBikePlaneZ.ToString("F4", CultureInfo.InvariantCulture),
-            debugFrontWheelTrackerRelativePositionX.ToString("F4", CultureInfo.InvariantCulture),
-            debugFrontWheelTrackerRelativePositionY.ToString("F4", CultureInfo.InvariantCulture),
-            debugFrontWheelTrackerRelativePositionZ.ToString("F4", CultureInfo.InvariantCulture)
-        });
+            return new KeyValuePair<long, string[]>(timestamp, new[]
+            {
+                debugLegTrackerPositionX.ToString("F4", CultureInfo.InvariantCulture),
+                debugLegTrackerPositionY.ToString("F4", CultureInfo.InvariantCulture),
+                debugLegTrackerPositionZ.ToString("F4", CultureInfo.InvariantCulture),
+                debugPosOnBikePlaneX.ToString("F4", CultureInfo.InvariantCulture),
+                debugPosOnBikePlaneY.ToString("F4", CultureInfo.InvariantCulture),
+                debugPosOnBikePlaneZ.ToString("F4", CultureInfo.InvariantCulture),
+                debugFrontWheelTrackerRelativePositionX.ToString("F4", CultureInfo.InvariantCulture),
+                debugFrontWheelTrackerRelativePositionY.ToString("F4", CultureInfo.InvariantCulture),
+                debugFrontWheelTrackerRelativePositionZ.ToString("F4", CultureInfo.InvariantCulture)
+            });
+        }
     }
 
     public class FrontWheelTrackerLogger : SensorDataLogger<FrontWheelTrackerData>
@@ -74,7 +78,7 @@ namespace Logging.Data
 
         public override IEnumerable<FrontWheelTrackerData> ReadLog(IEnumerable<IEnumerable<string>> lines)
         {
-            throw new System.NotImplementedException(); //TODO
+            throw new NotImplementedException(); //TODO
         }
     }
 }

+ 14 - 18
Assets/Scripts/Logging/Data/PolarAccDataLogger.cs

@@ -23,23 +23,24 @@ namespace Logging.Data
             this.accZ = accZ;
         }
 
-        public KeyValuePair<long, string[]> Serialize() =>
-            new KeyValuePair<long, string[]>(timestamp, new[]
+        public KeyValuePair<long, string[]> Serialize()
+        {
+            return new KeyValuePair<long, string[]>(timestamp, new[]
             {
                 accX.ToString("F4", CultureInfo.InvariantCulture),
                 accY.ToString("F4", CultureInfo.InvariantCulture),
-                accZ.ToString("F4", CultureInfo.InvariantCulture),
+                accZ.ToString("F4", CultureInfo.InvariantCulture)
             });
+        }
     }
 
     public class PolarAccDataLogger : SensorDataLogger<PolarAccDataLog>
     {
-        public override string Key => "polar_acc_data";
-
         private long startTimeAcc = -1;
-        private TimeSync timeSync;
 
         private IDisposable sub;
+        private TimeSync timeSync;
+        public override string Key => "polar_acc_data";
 
         public override async void Start()
         {
@@ -54,17 +55,17 @@ namespace Logging.Data
             sub = bikeSensorData.RawAccData?.Subscribe(data => OnData(data));
         }
 
+        private void OnDestroy()
+        {
+            sub?.Dispose();
+        }
+
         private void OnData(in AccData data)
         {
             if (timeSync.DifDataStreamStart < 0)
-            {
                 timeSync.DifDataStreamStart = (long) (DateTime.Now - timeSync.StartTime).TotalMilliseconds;
-            }
 
-            if (startTimeAcc < 0)
-            {
-                startTimeAcc = data.Timestamp;
-            }
+            if (startTimeAcc < 0) startTimeAcc = data.Timestamp;
 
             if (BikeSensorData.Instance.PolarConfig == null) return;
 
@@ -80,12 +81,7 @@ namespace Logging.Data
 
         public override IEnumerable<PolarAccDataLog> ReadLog(IEnumerable<IEnumerable<string>> lines)
         {
-            throw new System.NotImplementedException(); //TODO
-        }
-
-        private void OnDestroy()
-        {
-            sub?.Dispose();
+            throw new NotImplementedException(); //TODO
         }
     }
 }

+ 14 - 17
Assets/Scripts/Logging/Data/PolarEcgDataLogger.cs

@@ -19,22 +19,24 @@ namespace Logging.Data
             this.ecg = ecg;
         }
 
-        public KeyValuePair<long, string[]> Serialize() =>
-            new KeyValuePair<long, string[]>(timestamp, new[]
+        public KeyValuePair<long, string[]> Serialize()
+        {
+            return new KeyValuePair<long, string[]>(timestamp, new[]
             {
                 ecg.ToString("F4", CultureInfo.InvariantCulture)
             });
+        }
     }
 
     public class PolarEcgDataLogger : SensorDataLogger<PolarSensorEcgLog>
     {
-        public override string Key => "polar_ecg_data";
+        private const int ECG_SAMPLE_RATE = 130;
 
         private long startTime = -1;
-        private TimeSync timeSync;
-        private const int ECG_SAMPLE_RATE = 130;
 
         private IDisposable sub;
+        private TimeSync timeSync;
+        public override string Key => "polar_ecg_data";
 
         public override async void Start()
         {
@@ -49,17 +51,17 @@ namespace Logging.Data
             sub = bikeSensorData.RawEcgData?.Subscribe(data => OnData(data));
         }
 
+        private void OnDestroy()
+        {
+            sub?.Dispose();
+        }
+
         private void OnData(in EcgData data)
         {
             if (timeSync.DifDataStreamStart < 0)
-            {
                 timeSync.DifDataStreamStart = (long) (DateTime.Now - timeSync.StartTime).TotalMilliseconds;
-            }
 
-            if (startTime < 0)
-            {
-                startTime = data.Timestamp;
-            }
+            if (startTime < 0) startTime = data.Timestamp;
 
             var internalTimestamp =
                 (data.Timestamp - startTime) / 1000000;
@@ -73,12 +75,7 @@ namespace Logging.Data
 
         public override IEnumerable<PolarSensorEcgLog> ReadLog(IEnumerable<IEnumerable<string>> lines)
         {
-            throw new System.NotImplementedException(); //TODO
-        }
-
-        private void OnDestroy()
-        {
-            sub?.Dispose();
+            throw new NotImplementedException(); //TODO
         }
     }
 }

+ 8 - 8
Assets/Scripts/Logging/Data/SensorDataLogger.cs

@@ -8,14 +8,6 @@ namespace Logging.Data
 {
     public abstract class SensorDataLogger<T> : MonoBehaviour, ILogable, ISerializableLog<T> where T : ISerializable
     {
-        public abstract string Key { get; }
-
-        public IEnumerable<string> HeaderNames =>
-            typeof(T).GetFields(BindingFlags.Instance | BindingFlags.NonPublic).Select(f => f.Name)
-                .Where(f => !f.Equals("timestamp"));
-
-        public Dictionary<long, string[]> BufferLines { get; private set; }
-
         public virtual void Awake()
         {
             gameObject.SetActive(GameManager.LOG_TO_FILE);
@@ -27,6 +19,14 @@ namespace Logging.Data
             FileLogger.Instance.RegisterLogable(this);
         }
 
+        public abstract string Key { get; }
+
+        public IEnumerable<string> HeaderNames =>
+            typeof(T).GetFields(BindingFlags.Instance | BindingFlags.NonPublic).Select(f => f.Name)
+                .Where(f => !f.Equals("timestamp"));
+
+        public Dictionary<long, string[]> BufferLines { get; private set; }
+
         public void ClearBuffer()
         {
             BufferLines.Clear();

+ 32 - 28
Assets/Scripts/Logging/Data/ViveSensorDataLogger.cs

@@ -1,4 +1,5 @@
-using System.Collections.Generic;
+using System;
+using System.Collections.Generic;
 using System.Globalization;
 using Logging.Base;
 using Tracking;
@@ -6,7 +7,7 @@ using UnityEngine;
 
 namespace Logging.Data
 {
-    public readonly struct ViveSensorDataLog: ISerializable
+    public readonly struct ViveSensorDataLog : ISerializable
     {
         private readonly long timestamp;
         private readonly float steerAngle;
@@ -59,31 +60,34 @@ namespace Logging.Data
         }
 
 
-        public KeyValuePair<long, string[]> Serialize() => new KeyValuePair<long, string[]>
-        (timestamp,
-            new[]
-            {
-                steerAngle.ToString("F6", CultureInfo.InvariantCulture),
-                frontWheelTrackerPositionX.ToString("F6", CultureInfo.InvariantCulture),
-                frontWheelTrackerPositionY.ToString("F6", CultureInfo.InvariantCulture),
-                frontWheelTrackerPositionZ.ToString("F6", CultureInfo.InvariantCulture),
-                frontWheelTrackerRotationX.ToString("F6", CultureInfo.InvariantCulture),
-                frontWheelTrackerRotationY.ToString("F6", CultureInfo.InvariantCulture),
-                frontWheelTrackerRotationZ.ToString("F6", CultureInfo.InvariantCulture),
-                kineticTrackerPositionX.ToString("F6", CultureInfo.InvariantCulture),
-                kineticTrackerPositionY.ToString("F6", CultureInfo.InvariantCulture),
-                kineticTrackerPositionZ.ToString("F6", CultureInfo.InvariantCulture),
-                kineticTrackerRotationX.ToString("F6", CultureInfo.InvariantCulture),
-                kineticTrackerRotationY.ToString("F6", CultureInfo.InvariantCulture),
-                kineticTrackerRotationZ.ToString("F6", CultureInfo.InvariantCulture),
-                hmdPositionX.ToString("F6", CultureInfo.InvariantCulture),
-                hmdPositionY.ToString("F6", CultureInfo.InvariantCulture),
-                hmdPositionZ.ToString("F6", CultureInfo.InvariantCulture),
-                hmdRotationX.ToString("F6", CultureInfo.InvariantCulture),
-                hmdRotationY.ToString("F6", CultureInfo.InvariantCulture),
-                hmdRotationZ.ToString("F6", CultureInfo.InvariantCulture),
-            }
-        );
+        public KeyValuePair<long, string[]> Serialize()
+        {
+            return new KeyValuePair<long, string[]>
+            (timestamp,
+                new[]
+                {
+                    steerAngle.ToString("F6", CultureInfo.InvariantCulture),
+                    frontWheelTrackerPositionX.ToString("F6", CultureInfo.InvariantCulture),
+                    frontWheelTrackerPositionY.ToString("F6", CultureInfo.InvariantCulture),
+                    frontWheelTrackerPositionZ.ToString("F6", CultureInfo.InvariantCulture),
+                    frontWheelTrackerRotationX.ToString("F6", CultureInfo.InvariantCulture),
+                    frontWheelTrackerRotationY.ToString("F6", CultureInfo.InvariantCulture),
+                    frontWheelTrackerRotationZ.ToString("F6", CultureInfo.InvariantCulture),
+                    kineticTrackerPositionX.ToString("F6", CultureInfo.InvariantCulture),
+                    kineticTrackerPositionY.ToString("F6", CultureInfo.InvariantCulture),
+                    kineticTrackerPositionZ.ToString("F6", CultureInfo.InvariantCulture),
+                    kineticTrackerRotationX.ToString("F6", CultureInfo.InvariantCulture),
+                    kineticTrackerRotationY.ToString("F6", CultureInfo.InvariantCulture),
+                    kineticTrackerRotationZ.ToString("F6", CultureInfo.InvariantCulture),
+                    hmdPositionX.ToString("F6", CultureInfo.InvariantCulture),
+                    hmdPositionY.ToString("F6", CultureInfo.InvariantCulture),
+                    hmdPositionZ.ToString("F6", CultureInfo.InvariantCulture),
+                    hmdRotationX.ToString("F6", CultureInfo.InvariantCulture),
+                    hmdRotationY.ToString("F6", CultureInfo.InvariantCulture),
+                    hmdRotationZ.ToString("F6", CultureInfo.InvariantCulture)
+                }
+            );
+        }
     }
 
     public class ViveSensorDataLogger : SensorDataLogger<ViveSensorDataLog>
@@ -115,7 +119,7 @@ namespace Logging.Data
 
         public override IEnumerable<ViveSensorDataLog> ReadLog(IEnumerable<IEnumerable<string>> lines)
         {
-            throw new System.NotImplementedException();
+            throw new NotImplementedException();
         }
     }
 }

+ 13 - 19
Assets/Scripts/Logging/Events/RouteEventLogger.cs

@@ -31,23 +31,26 @@ namespace Logging.Events
             this.eventRoute = eventRoute;
         }
 
-        public KeyValuePair<long, string[]> Serialize() => new KeyValuePair<long, string[]>(timestamp, new[]
+        public KeyValuePair<long, string[]> Serialize()
         {
-            eventRoute.ToString()
-        });
+            return new KeyValuePair<long, string[]>(timestamp, new[]
+            {
+                eventRoute.ToString()
+            });
+        }
     }
 
     public class RouteEventLogger : SensorDataLogger<RouteEventData>
     {
-        public override string Key => "route_events";
         public GameObject routes;
 
         [CanBeNull] private Route activeRoute;
         private bool activeRouteAvailable;
-        private IEnumerable<Turn> turns;
+        private StraightRoadExtras finish;
 
         private StraightRoadExtras start;
-        private StraightRoadExtras finish;
+        private IEnumerable<Turn> turns;
+        public override string Key => "route_events";
 
         public override void Start()
         {
@@ -65,16 +68,10 @@ namespace Logging.Events
         {
             var e = RouteEvent.None;
             if (start.ArcState == TriggerState.Inside)
-            {
                 e = RouteEvent.Start;
-            }else if (finish.ArcState == TriggerState.Inside)
-            {
+            else if (finish.ArcState == TriggerState.Inside)
                 e = RouteEvent.Finish;
-            }
-            else if(activeRouteAvailable)
-            {
-                e = EventForActiveRoute();
-            }
+            else if (activeRouteAvailable) e = EventForActiveRoute();
 
             Log(new RouteEventData(Helpers.RoundToLong(Time.time * 1000f), e));
         }
@@ -82,11 +79,8 @@ namespace Logging.Events
         private RouteEvent EventForActiveRoute()
         {
             var currentTurn = turns.FirstOrDefault(t => t.BikeTriggerState == TriggerState.Inside);
-            if (currentTurn == null)
-            {
-                return RouteEvent.None;
-            }
-            
+            if (currentTurn == null) return RouteEvent.None;
+
             switch (currentTurn.comingFrom)
             {
                 case RoadDirection.West:

+ 13 - 10
Assets/Scripts/Logging/FPSLogger.cs

@@ -1,4 +1,5 @@
-using System.Collections.Generic;
+using System;
+using System.Collections.Generic;
 using Logging.Base;
 using Logging.Data;
 using UnityEngine;
@@ -16,20 +17,22 @@ namespace Logging
             this.fps = fps;
         }
 
-        public KeyValuePair<long, string[]> Serialize() => new KeyValuePair<long, string[]>(timestamp, new[]
+        public KeyValuePair<long, string[]> Serialize()
         {
-            fps.ToString()
-        });
+            return new KeyValuePair<long, string[]>(timestamp, new[]
+            {
+                fps.ToString()
+            });
+        }
     }
 
     public class FPSLogger : SensorDataLogger<FPSData>
     {
-        public override string Key => "fps";
-
-        const float FPSMeasurePeriod = 0.5f;
-        private int fpsAccumulator = 0;
-        private float fpsNextPeriod = 0;
+        private const float FPSMeasurePeriod = 0.5f;
         private int currentFps;
+        private int fpsAccumulator;
+        private float fpsNextPeriod;
+        public override string Key => "fps";
 
 
         public override void Start()
@@ -56,7 +59,7 @@ namespace Logging
 
         public override IEnumerable<FPSData> ReadLog(IEnumerable<IEnumerable<string>> lines)
         {
-            throw new System.NotImplementedException();
+            throw new NotImplementedException();
         }
     }
 }

+ 8 - 4
Assets/Scripts/Phscs/BicyclePhysics.cs

@@ -9,9 +9,10 @@ namespace Phscs
         private const float D = 1.226f; //air density; kg/m3
 
         /// <summary>
-        /// Returns a speed in m/s for a bike riding a gradient with the same power it would be ridden in the flat with the input speed.
-        /// Using formula from http://www.sportsci.org/jour/9804/dps.html. Assuming v=s and neglecting rolling resistance
-        /// The speed is calculated by solving k_aAs_1^3d = k_aAs_2^3d + giMs_2 for s_2
+        ///     Returns a speed in m/s for a bike riding a gradient with the same power it would be ridden in the flat with the
+        ///     input speed.
+        ///     Using formula from http://www.sportsci.org/jour/9804/dps.html. Assuming v=s and neglecting rolling resistance
+        ///     The speed is calculated by solving k_aAs_1^3d = k_aAs_2^3d + giMs_2 for s_2
         /// </summary>
         /// <param name="speedFlat">Speed the bike would have in flat terrain</param>
         /// <param name="systemMass">Mass of bike + rider</param>
@@ -58,6 +59,9 @@ namespace Phscs
             return result;
         }
 
-        private static float Qbrt(float x) => x < 0 ? -Mathf.Pow(-x, 1f / 3f) : Mathf.Pow(x, 1f / 3f);
+        private static float Qbrt(float x)
+        {
+            return x < 0 ? -Mathf.Pow(-x, 1f / 3f) : Mathf.Pow(x, 1f / 3f);
+        }
     }
 }

+ 25 - 29
Assets/Scripts/Plotting/DebugPlot.cs

@@ -1,43 +1,20 @@
 using System;
 using System.Collections.Generic;
 using System.Diagnostics;
-using System.IO;
-using Logging;
 using Logging.Base;
-using UnityEngine;
 
 namespace Plotting
 {
     public class DebugPlot
     {
-        #region signleton
-
-        private static Lazy<DebugPlot>
-            instance =
-                new Lazy<DebugPlot>
-                    (() => new DebugPlot());
+        private Process plottingProc;
 
-        public static DebugPlot Instance => instance.Value;
+        private readonly List<AsyncLogFileWriter> plotWriters = new List<AsyncLogFileWriter>();
 
-        public static void DestroyInstance()
+        private DebugPlot()
         {
-            if (instance.IsValueCreated)
-            {
-                instance.Value.Dispose();
-                instance =
-                    new Lazy<DebugPlot>
-                        (() => new DebugPlot());
-            }
         }
 
-        #endregion
-
-        private List<AsyncLogFileWriter> plotWriters = new List<AsyncLogFileWriter>();
-        private Process plottingProc;
-
-        private DebugPlot()
-        { }
-
         public AsyncLogFileWriter StartPlotting(string path)
         {
             var writer = new AsyncLogFileWriter(path);
@@ -47,16 +24,35 @@ namespace Plotting
 
         public void ShowPlots()
         {
-            plottingProc = Process.Start("CMD.exe",$"/C cd Assets/Plotting & python plot.py");
+            plottingProc = Process.Start("CMD.exe", "/C cd Assets/Plotting & python plot.py");
         }
 
         private void Dispose()
         {
             plottingProc?.Kill();
-            foreach (var p in plotWriters)
+            foreach (var p in plotWriters) p.Dispose();
+        }
+
+        #region signleton
+
+        private static Lazy<DebugPlot>
+            instance =
+                new Lazy<DebugPlot>
+                    (() => new DebugPlot());
+
+        public static DebugPlot Instance => instance.Value;
+
+        public static void DestroyInstance()
+        {
+            if (instance.IsValueCreated)
             {
-                p.Dispose();
+                instance.Value.Dispose();
+                instance =
+                    new Lazy<DebugPlot>
+                        (() => new DebugPlot());
             }
         }
+
+        #endregion
     }
 }

+ 2 - 5
Assets/Scripts/Pools/Pool.cs

@@ -1,8 +1,5 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
+using System.Collections.Generic;
 using UnityEngine;
-using Object = UnityEngine.Object;
 
 namespace Pools
 {
@@ -11,9 +8,9 @@ namespace Pools
         public int initialSize = 10;
         public int amountIncrease = 5;
         public GameObject prefab;
+        private HashSet<GameObject> active;
 
         private Queue<GameObject> inactive;
-        private HashSet<GameObject> active;
 
         private void Awake()
         {

+ 0 - 6
Assets/Scripts/Roads/CrossingExtras.cs

@@ -1,10 +1,4 @@
 using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Security.Cryptography;
-using Controller.Bicycle;
-using JetBrains.Annotations;
-using Pools;
 using Routes;
 using UnityEngine;
 

+ 10 - 12
Assets/Scripts/Roads/JunctionExtras.cs

@@ -8,12 +8,11 @@ namespace Roads
     [Serializable]
     public struct JunctionData
     {
-        [SerializeField]
-        private Transform north;
-        [SerializeField]
-        private Transform east;
-        [SerializeField]
-        private Transform south;
+        [SerializeField] private Transform north;
+
+        [SerializeField] private Transform east;
+
+        [SerializeField] private Transform south;
 
         [CanBeNull]
         public Transform GetEast(float yRotation)
@@ -46,7 +45,7 @@ namespace Roads
                     return east;
                 default:
                     return null;
-            } 
+            }
         }
 
         [CanBeNull]
@@ -63,7 +62,7 @@ namespace Roads
                     return north;
                 default:
                     return null;
-            } 
+            }
         }
 
         [CanBeNull]
@@ -80,15 +79,14 @@ namespace Roads
                     return north;
                 default:
                     return null;
-            } 
+            }
         }
-        
     }
-    
+
     public class JunctionExtras : Turn
     {
         public JunctionData junctionData;
-        
+
         protected override Transform RoadDirectionToTransform(RoadDirection position)
         {
             var rotation = transform.rotation.eulerAngles.y;

+ 3 - 5
Assets/Scripts/Roads/Road.cs

@@ -1,11 +1,9 @@
-using UnityEngine.UIElements;
-
-namespace Roads
+namespace Roads
 {
     public interface IRoad
     {
         float SlopeDeg { get; }
-        
-        float MinY { get;  }
+
+        float MinY { get; }
     }
 }

+ 10 - 18
Assets/Scripts/Roads/SlopeExtras.cs

@@ -1,5 +1,4 @@
-using System;
-using Controller.Bicycle;
+using Controller.Bicycle;
 using UnityEngine;
 
 namespace Roads
@@ -9,16 +8,16 @@ namespace Roads
     {
         private const float TOLERANCE_ANGLE = 1f;
 
-        private StraightRoadExtras straightRoadExtras;
-        private BikeSpeedBooster booster;
-
         public bool firstOrLast;
+        private BikeSpeedBooster booster;
+        private bool isFirst;
 
         private Vector3 lowerPos;
-        private Vector3 upperPos;
 
-        private int slopePrefix = 0;
-        private bool isFirst = false;
+        private int slopePrefix;
+
+        private StraightRoadExtras straightRoadExtras;
+        private Vector3 upperPos;
 
         private void OnEnable()
         {
@@ -36,34 +35,27 @@ namespace Roads
             {
                 var bikePos = other.ClosestPointOnBounds(lowerPos);
                 if ((bikePos - lowerPos).magnitude < (bikePos - upperPos).magnitude)
-                {
                     //coming from lower pos -> uphill
                     slopePrefix = 1;
-                }
                 else
-                {
                     slopePrefix = -1;
-                }
 
                 var directedSlope = slopePrefix * straightRoadExtras.SlopeDeg;
                 booster.SetFixedBoostForSlope(directedSlope);
 
                 isFirst = other.transform.rotation.eulerAngles.x < TOLERANCE_ANGLE;
-                if (firstOrLast && isFirst)
-                {
-                    booster.AddBoosterForFirstAndSlope(directedSlope);
-                }
+                if (firstOrLast && isFirst) booster.AddBoosterForFirstAndSlope(directedSlope);
             }
         }
 
         private void OnTriggerExit(Collider other)
         {
             //Debug.Log($"EXIT bike rotation = {other.transform.rotation.eulerAngles}");
-            
+
             if (other.CompareTag("bike") && firstOrLast)
             {
                 var isLast = !isFirst && other.transform.rotation.eulerAngles.x > TOLERANCE_ANGLE;
-                if(!isLast) return;
+                if (!isLast) return;
                 booster.AddBoosterForLastAndSlope(slopePrefix * straightRoadExtras.SlopeDeg);
                 booster.ResetFixedBoost(); //on straight road again
             }

+ 19 - 25
Assets/Scripts/Roads/StraightRoadExtras.cs

@@ -1,7 +1,4 @@
-using System;
-using Controller.Bicycle;
-using Pools;
-using Routes;
+using Routes;
 using UnityEngine;
 
 namespace Roads
@@ -9,46 +6,30 @@ namespace Roads
     [RequireComponent(typeof(BoxCollider))]
     public class StraightRoadExtras : MonoBehaviour, IRoad
     {
+        public delegate void OnArcEnteredEvent();
+
+        public delegate void OnArcPassedEvent();
+
         public GameObject arcPrefab;
 
         private GameObject arc;
         private bool hasArc;
         public TriggerState ArcState { get; private set; } = TriggerState.Outside;
 
-        public float SlopeDeg { get; private set; }
-
-        public float MinY { get; private set; }
-
-        public delegate void OnArcEnteredEvent();
-
-        public delegate void OnArcPassedEvent();
-
-        public event OnArcEnteredEvent OnArcEntered;
-        public event OnArcPassedEvent OnArcPassed;
-
         private void Start()
         {
             SlopeDeg = transform.localRotation.eulerAngles.z;
             MinY = GetComponent<BoxCollider>().bounds.center.y;
         }
 
-        public void ShowArc()
-        {
-            arc = Instantiate(arcPrefab, transform);
-            hasArc = arc != null;
-        }
-
         private void OnTriggerEnter(Collider other)
         {
             if (other.CompareTag("bike"))
-            {
                 if (hasArc)
                 {
                     OnArcEntered?.Invoke();
                     ArcState = TriggerState.Inside;
-                } 
-            }
-            
+                }
         }
 
         private void OnTriggerExit(Collider other)
@@ -60,5 +41,18 @@ namespace Roads
                 OnArcPassed?.Invoke();
             }
         }
+
+        public float SlopeDeg { get; private set; }
+
+        public float MinY { get; private set; }
+
+        public event OnArcEnteredEvent OnArcEntered;
+        public event OnArcPassedEvent OnArcPassed;
+
+        public void ShowArc()
+        {
+            arc = Instantiate(arcPrefab, transform);
+            hasArc = arc != null;
+        }
     }
 }

+ 3 - 5
Assets/Scripts/Roads/StreetPartMetaTag.cs

@@ -1,7 +1,4 @@
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using UnityEngine;
+using UnityEngine;
 
 public class StreetPartMetaTag : MonoBehaviour
 {
@@ -9,9 +6,10 @@ public class StreetPartMetaTag : MonoBehaviour
     public const string TAG_UNEVEN = "street_uneven";
 
     private const float SLOPE_THRES = .5f;
+
     private void Awake()
     {
         var slope = transform.parent.localRotation.eulerAngles.z;
         tag = Mathf.Abs(slope) <= SLOPE_THRES ? TAG_EVEN : TAG_UNEVEN;
     }
-}
+}

+ 12 - 27
Assets/Scripts/Routes/Route.cs

@@ -1,9 +1,7 @@
 using System;
 using System.Collections.Generic;
 using Roads;
-using UnityEditor;
 using UnityEngine;
-using UnityEngine.Rendering;
 
 namespace Routes
 {
@@ -37,6 +35,10 @@ namespace Routes
 
     public class Route : MonoBehaviour
     {
+        public delegate void OnFinishPassedEvent();
+
+        public delegate void OnStartEnteredEvent();
+
         public List<RouteItem> items;
 
         public StraightRoadExtras start;
@@ -49,14 +51,6 @@ namespace Routes
 
         private int VisibleEnd => Math.Min(items.Count, VisibleStart + visibleLength);
 
-        public delegate void OnStartEnteredEvent();
-
-        public event OnStartEnteredEvent OnStartEntered;
-        
-        public delegate void OnFinishPassedEvent();
-
-        public event OnFinishPassedEvent OnFinishPassed;
-
         private void Start()
         {
             start.ShowArc();
@@ -66,20 +60,18 @@ namespace Routes
             visibleStart = 0;
             visibleLength = routeManager.visibleLength;
 
-            items.ForEach((item) => item.turn.OnTriggerExitBicycle = NextTurn);
+            items.ForEach(item => item.turn.OnTriggerExitBicycle = NextTurn);
             UpdateRouteItems();
         }
 
+        public event OnStartEnteredEvent OnStartEntered;
+
+        public event OnFinishPassedEvent OnFinishPassed;
+
         private void SetupEvents()
         {
-            start.OnArcEntered += () =>
-            {
-               OnStartEntered?.Invoke();
-            };
-            finish.OnArcPassed += () =>
-            {
-                OnFinishPassed?.Invoke();
-            };
+            start.OnArcEntered += () => { OnStartEntered?.Invoke(); };
+            finish.OnArcPassed += () => { OnFinishPassed?.Invoke(); };
         }
 
         private void NextTurn()
@@ -91,22 +83,15 @@ namespace Routes
 
         private void UpdateRouteItems()
         {
-            if (VisibleEnd == items.Count - 1)
-            {
-                finish.ShowArc();
-            }
+            if (VisibleEnd == items.Count - 1) finish.ShowArc();
 
             for (var i = 0; i < VisibleEnd; i++)
             {
                 var item = items[i];
                 if (i >= VisibleStart)
-                {
                     item.Apply();
-                }
                 else
-                {
                     item.Clear();
-                }
             }
         }
     }

+ 3 - 16
Assets/Scripts/Routes/RouteManager.cs

@@ -17,10 +17,7 @@ namespace Routes
 
         private void Start()
         {
-            for (var i = 0; i < routes.Length; i++)
-            {
-                routes[i].gameObject.SetActive(i == selectedRoute);
-            }
+            for (var i = 0; i < routes.Length; i++) routes[i].gameObject.SetActive(i == selectedRoute);
 
             routes[selectedRoute].OnStartEntered += OnOnStartEntered;
             routes[selectedRoute].OnFinishPassed += OnOnFinishPassed;
@@ -36,25 +33,15 @@ namespace Routes
             var startRotationEuler = startTransform.rotation.eulerAngles;
 
             var difStartFirstTurn = firstTurnPos - startTransform.position;
-            Vector3 bikeDirection = Vector3.zero;
+            var bikeDirection = Vector3.zero;
 
             if (difStartFirstTurn.x > 1)
-            {
                 bikeDirection = new Vector3(-1, 0, 0);
-            }
             else if (difStartFirstTurn.z > 1)
-            {
                 bikeDirection = new Vector3(0, 0, -1);
-            }
             else if (difStartFirstTurn.x < -1)
-            {
                 bikeDirection = new Vector3(1, 0, 0);
-
-            }
-            else if (difStartFirstTurn.z < -1)
-            {
-                bikeDirection = new Vector3(0, 0, 1);
-            }
+            else if (difStartFirstTurn.z < -1) bikeDirection = new Vector3(0, 0, 1);
 
             bicycleGameObject = bicycle.gameObject;
             bicycleGameObject.transform.position =

+ 31 - 49
Assets/Scripts/Routes/Turn.cs

@@ -4,16 +4,14 @@ using System.Linq;
 using JetBrains.Annotations;
 using Pools;
 using Roads;
-using UnityEditor;
 using UnityEngine;
-using Valve.VR.InteractionSystem;
 
 namespace Routes
 {
     public enum TriggerState
     {
         Inside,
-        Outside,
+        Outside
     }
 
     public enum RoadDirection
@@ -56,28 +54,24 @@ namespace Routes
 
     public abstract class Turn : MonoBehaviour, IRoad
     {
+        private static readonly RoadDirection[] allDirections =
+            {RoadDirection.West, RoadDirection.North, RoadDirection.East, RoadDirection.South};
+
         public RoadDirection comingFrom;
         public RoadDirection goingTo;
 
         [CanBeNull] private Pool arrowPool;
 
         private bool arrowPoolAvailable;
-        private TurnDirection turnDirection;
-        private List<GameObject> usedArrows = new List<GameObject>();
 
         private Collider trigger;
-
-        private static readonly RoadDirection[] allDirections =
-            {RoadDirection.West, RoadDirection.North, RoadDirection.East, RoadDirection.South};
+        private TurnDirection turnDirection;
+        private readonly List<GameObject> usedArrows = new List<GameObject>();
 
         public Action OnTriggerExitBicycle { get; set; }
 
         public TriggerState BikeTriggerState { get; private set; } = TriggerState.Outside;
 
-        public float SlopeDeg { get; private set; }
-        
-        public float MinY { get; private set; }
-
         private void Awake()
         {
             arrowPool = FindObjectsOfType<Pool>().FirstOrDefault(o => o.CompareTag("ArrowPool"));
@@ -93,6 +87,25 @@ namespace Routes
             UpdateArrows();
         }
 
+        private void OnTriggerEnter(Collider other)
+        {
+            if (other.CompareTag("bike")) BikeTriggerState = TriggerState.Inside;
+        }
+
+        private void OnTriggerExit(Collider other)
+        {
+            if (other.CompareTag("bike") && OnTriggerExitBicycle != null)
+            {
+                OnTriggerExitBicycle();
+                trigger.enabled = false;
+                BikeTriggerState = TriggerState.Outside;
+            }
+        }
+
+        public float SlopeDeg { get; private set; }
+
+        public float MinY { get; private set; }
+
         [CanBeNull]
         protected abstract Transform RoadDirectionToTransform(RoadDirection position);
 
@@ -118,50 +131,38 @@ namespace Routes
                 {
                     if (turnDirection == TurnDirection.Left ||
                         turnDirection == TurnDirection.Straight && goingTo == RoadDirection.South)
-                    {
                         t.rotation = Quaternion.Euler(0, 90, 0);
-                        //arrows.transform.Rotate(Vector3.up, 90);
-                    }
+                    //arrows.transform.Rotate(Vector3.up, 90);
                     else if (turnDirection == TurnDirection.Right ||
                              turnDirection == TurnDirection.Straight && goingTo == RoadDirection.North)
-                    {
                         t.rotation = Quaternion.Euler(0, 270, 0);
-                        //arrows.transform.Rotate(Vector3.up, 90);
-                    }
+                    //arrows.transform.Rotate(Vector3.up, 90);
 
                     break;
                 }
                 case RoadDirection.North:
                     if (turnDirection == TurnDirection.Left ||
                         turnDirection == TurnDirection.Straight && goingTo == RoadDirection.West)
-                    {
                         t.rotation = Quaternion.Euler(0, 180, 0);
-                        //arrows.transform.Rotate(Vector3.up, 180);
-                    }
+                    //arrows.transform.Rotate(Vector3.up, 180);
 
                     break;
                 case RoadDirection.East:
                     if (turnDirection == TurnDirection.Right ||
                         turnDirection == TurnDirection.Straight && goingTo == RoadDirection.South)
-                    {
                         t.rotation = Quaternion.Euler(0, 90, 0);
-                        //arrows.transform.Rotate(Vector3.up, 90);
-                    }
+                    //arrows.transform.Rotate(Vector3.up, 90);
                     else if (turnDirection == TurnDirection.Left ||
                              turnDirection == TurnDirection.Straight && goingTo == RoadDirection.North)
-                    {
                         t.rotation = Quaternion.Euler(0, 270, 0);
-                        //arrows.transform.Rotate(Vector3.up, -90);
-                    }
+                    //arrows.transform.Rotate(Vector3.up, -90);
 
                     break;
                 case RoadDirection.South:
                     if (turnDirection == TurnDirection.Right ||
                         turnDirection == TurnDirection.Straight && goingTo == RoadDirection.West)
-                    {
                         t.rotation = Quaternion.Euler(0, 180, 0);
-                        //arrows.transform.Rotate(Vector3.up, 180);
-                    }
+                    //arrows.transform.Rotate(Vector3.up, 180);
 
                     break;
                 case RoadDirection.None:
@@ -216,24 +217,5 @@ namespace Routes
 
             trigger.enabled = true;
         }
-
-        private void OnTriggerExit(Collider other)
-        {
-            if (other.CompareTag("bike") && OnTriggerExitBicycle != null)
-            {
-                OnTriggerExitBicycle();
-                trigger.enabled = false;
-                BikeTriggerState = TriggerState.Outside;
-            }
-        }
-        
-        private void OnTriggerEnter(Collider other)
-        {
-            if (other.CompareTag("bike"))
-            {
-                BikeTriggerState = TriggerState.Inside;
-            }
-            
-        }
     }
 }

+ 1 - 1
Assets/Scripts/Routes/TurnDirectionMapper.cs

@@ -2,7 +2,7 @@
 
 namespace Routes
 {
-     static class TurnDirectionMapper
+    internal static class TurnDirectionMapper
     {
         private static readonly Dictionary<RoadDirection, TurnDirection> fromSouth =
             new Dictionary<RoadDirection, TurnDirection>

+ 26 - 33
Assets/Scripts/Sensors/BikeSensorData.cs

@@ -12,49 +12,40 @@ namespace Sensors
 {
     public sealed class BikeSensorData
     {
-        #region singleton
+        private readonly Subject<object> polarReceiverAvailable = new Subject<object>();
+        [CanBeNull] private HrReceiver hrReceiver;
+        [CanBeNull] private PolarReceiver polarReceiver;
 
-        private static readonly Lazy<BikeSensorData>
-            lazy =
-                new Lazy<BikeSensorData>
-                    (() => new BikeSensorData());
+        [CanBeNull] private PowerMeterReceiver powerMeterReceiver;
+        [CanBeNull] private SpeedSensorReceiver speedSensorReceiver;
 
-        public static BikeSensorData Instance => lazy.Value;
+        private BikeSensorData()
+        {
+            PolarReceiverAvailable = polarReceiverAvailable.ToTask();
+        }
 
-        #endregion
+        public SpeedSensorData? SpeedData =>
+            speedSensorReceiver?.Connected ?? false ? speedSensorReceiver?.SensorData : null;
 
-        [CanBeNull] private PowerMeterReceiver powerMeterReceiver;
-        [CanBeNull] private SpeedSensorReceiver speedSensorReceiver;
-        [CanBeNull] private HrReceiver hrReceiver;
-        [CanBeNull] private PolarReceiver polarReceiver;
+        public PowermeterSensorData? PowermeterData =>
+            powerMeterReceiver?.Connected ?? false ? powerMeterReceiver?.SensorData : null;
 
-        public SpeedSensorData? SpeedData => speedSensorReceiver?.Connected ?? false ? speedSensorReceiver?.SensorData : null;
-        public PowermeterSensorData? PowermeterData => powerMeterReceiver?.Connected ?? false ? powerMeterReceiver?.SensorData : null;
         public HrSensorData? HrData => hrReceiver?.Connected ?? false ? hrReceiver?.SensorData : null;
         public PolarSensorData? PolarData => polarReceiver?.SensorData;
         [CanBeNull] public IObservable<EcgData> RawEcgData => polarReceiver?.RawEcgData;
         [CanBeNull] public IObservable<AccData> RawAccData => polarReceiver?.RawAccData;
 
         public PolarSensorConfig? PolarConfig => polarReceiver?.SensorConfig;
-
-        private readonly Subject<object> polarReceiverAvailable = new Subject<object>();
         public Task PolarReceiverAvailable { get; }
 
-        private BikeSensorData()
-        {
-            PolarReceiverAvailable = polarReceiverAvailable.ToTask();
-        }
-
         public void StartListening(SpeedSensorConfig? speedSensorConfig = null,
             PolarSensorConfig? polarSensorConfig = null, int? powermeterId = null, int? hrAntId = null)
         {
             if (speedSensorConfig != null)
             {
-                if(speedSensorReceiver != null)
-                {
+                if (speedSensorReceiver != null)
                     throw new InvalidConstraintException(
                         "BikeSensorData: Already listening to Speed Sensor");
-                }
                 speedSensorReceiver = new SpeedSensorReceiver(speedSensorConfig.Value);
                 try
                 {
@@ -69,11 +60,9 @@ namespace Sensors
 
             if (hrAntId != null)
             {
-                if(hrReceiver != null)
-                {
+                if (hrReceiver != null)
                     throw new InvalidConstraintException(
                         "BikeSensorData: Already listening to HR Sensor");
-                }
                 hrReceiver = new HrReceiver(hrAntId.Value);
                 try
                 {
@@ -89,37 +78,30 @@ namespace Sensors
             if (powermeterId != null)
             {
                 if (powerMeterReceiver != null)
-                {
                     throw new InvalidConstraintException(
                         "BikeSensorData: Already listening to Power Sensor");
-                }
                 powerMeterReceiver = new PowerMeterReceiver(powermeterId.Value);
                 try
                 {
                     powerMeterReceiver.StartScan();
-                    
                 }
                 catch (ANT_Exception e)
                 {
                     Debug.Log($"Could not initialize PowerMeter Receiver: {e}");
                     powerMeterReceiver = null;
                 }
-
             }
 
             if (polarSensorConfig != null)
             {
                 if (polarReceiver != null)
-                {
                     throw new InvalidConstraintException(
                         "BikeSensorData: Already listening to Polar Sensor");
-                }
                 polarReceiver = new PolarReceiver(polarSensorConfig.Value);
                 polarReceiver.StartListening();
                 polarReceiverAvailable.OnNext(null);
                 polarReceiverAvailable.OnCompleted();
             }
-        
         }
 
         public void Dispose()
@@ -133,5 +115,16 @@ namespace Sensors
             powerMeterReceiver = null;
             hrReceiver = null;
         }
+
+        #region singleton
+
+        private static readonly Lazy<BikeSensorData>
+            lazy =
+                new Lazy<BikeSensorData>
+                    (() => new BikeSensorData());
+
+        public static BikeSensorData Instance => lazy.Value;
+
+        #endregion
     }
 }

+ 3 - 4
Assets/Scripts/Sensors/ListenToSensors.cs

@@ -1,5 +1,4 @@
-using System;
-using Sensors.ANT;
+using Sensors.ANT;
 using Sensors.Polar;
 using UnityEngine;
 
@@ -9,8 +8,8 @@ namespace Sensors
     {
         public SpeedSensorConfig speedSensorConfig;
         public PolarSensorConfig polarSensorConfig;
-        public int hrAntId = 0;
-        public int powerMeterId = 0;
+        public int hrAntId;
+        public int powerMeterId;
 
         private void Start()
         {

+ 5 - 4
Assets/Scripts/Sensors/Polar/PolarAccData.cs

@@ -10,10 +10,10 @@ namespace Sensors.Polar
         public long Timestamp { get; }
         public List<Vector3> Values { get; }
 
-        AccData(long timestamp, List<Vector3> values)
+        private AccData(long timestamp, List<Vector3> values)
         {
-            this.Timestamp = timestamp;
-            this.Values = values;
+            Timestamp = timestamp;
+            Values = values;
         }
 
         public static AccData FromString(string s)
@@ -23,7 +23,8 @@ namespace Sensors.Polar
             {
                 var t = long.Parse(data[0]);
                 var tupleStrings = data[1].Split(',').Select(item => item.Replace("(", "").Replace(")", ""));
-                var floats = tupleStrings.Select(s1 => s1.Split('/').Select(value => float.Parse(value)).ToList()).ToList();
+                var floats = tupleStrings.Select(s1 => s1.Split('/').Select(value => float.Parse(value)).ToList())
+                    .ToList();
                 return new AccData(t, floats.Select(a => new Vector3(a[0], a[1], a[2])).ToList());
             }
 

+ 1 - 1
Assets/Scripts/Sensors/Polar/PolarEcgData.cs

@@ -9,7 +9,7 @@ namespace Sensors.Polar
         public long Timestamp { get; }
         public List<float> Values { get; }
 
-        EcgData(long timestamp, List<float> values)
+        private EcgData(long timestamp, List<float> values)
         {
             Timestamp = timestamp;
             Values = values;

+ 1 - 1
Assets/Scripts/Sensors/Polar/PolarHRData.cs

@@ -9,7 +9,7 @@ namespace Sensors.Polar
         public List<long> RrsMs { get; }
         public int HeartRate { get; }
 
-        HRData(List<long> rrsMs, int heartRate)
+        private HRData(List<long> rrsMs, int heartRate)
         {
             RrsMs = rrsMs;
             HeartRate = heartRate;

+ 12 - 13
Assets/Scripts/Sensors/Polar/PolarReceiver.cs

@@ -2,11 +2,10 @@
 using System.Threading.Tasks;
 using UniRx;
 using UnityEngine;
-using UnityEngine.Serialization;
 
 namespace Sensors.Polar
 {
-    [System.Serializable]
+    [Serializable]
     public struct PolarSensorConfig
     {
         public int port;
@@ -30,26 +29,26 @@ namespace Sensors.Polar
 
     public class PolarReceiver
     {
-        private UdpConnection connection;
-        private PolarSensorData sensorData;
+        private readonly Subject<AccData> rawAccDataSubject = new Subject<AccData>();
 
         private readonly Subject<EcgData> rawEcgDataSubject = new Subject<EcgData>();
-        private readonly Subject<AccData> rawAccDataSubject = new Subject<AccData>();
         private readonly Subject<HRData> rawHRDataSubject = new Subject<HRData>();
+        private UdpConnection connection;
+        private PolarSensorData sensorData;
+
+        public PolarReceiver(PolarSensorConfig config)
+        {
+            SensorConfig = config;
+        }
 
         public IObservable<EcgData> RawEcgData => rawEcgDataSubject.AsObservable();
         public IObservable<AccData> RawAccData => rawAccDataSubject.AsObservable();
-        
+
         public IObservable<HRData> RawHRData => rawHRDataSubject.AsObservable();
 
-        public PolarSensorConfig SensorConfig { get; private set; }
+        public PolarSensorConfig SensorConfig { get; }
         public PolarSensorData SensorData => sensorData;
 
-        public PolarReceiver(PolarSensorConfig config)
-        {
-            SensorConfig = config;
-        }
-
         public void StartListening()
         {
             connection = new UdpConnection(SensorConfig.ipAddress, SensorConfig.port, OnAccData, OnEcgData, OnHRData);
@@ -85,7 +84,7 @@ namespace Sensors.Polar
             rawEcgDataSubject.OnNext(data);
             sensorData.EcgValue = data.Values[0]; //TODO
         }
-        
+
         private void OnHRData(HRData data)
         {
             rawHRDataSubject.OnNext(data);

+ 27 - 31
Assets/Scripts/Sensors/Polar/UdpConnection.cs

@@ -3,7 +3,6 @@ using System.Net;
 using System.Net.Sockets;
 using System.Text;
 using System.Threading.Tasks;
-using UnityEngine;
 
 namespace Sensors.Polar
 {
@@ -12,55 +11,52 @@ namespace Sensors.Polar
         //public int port = 9090;
         //public String ipAddress = "192.168.1.7";
 
-        private UdpClient client;
+        private readonly UdpClient client;
 
-        private bool listening = false;
-        private Action<AccData> onAccData;
-        private Action<EcgData> onEcgData;
-        private Action<HRData> onHRData;
+        private bool listening;
+        private readonly Action<AccData> onAccData;
+        private readonly Action<EcgData> onEcgData;
+        private readonly Action<HRData> onHRData;
 
-        public UdpConnection(String ipAddress, int port, Action<AccData> onAccData, Action<EcgData> onEcgData, Action<HRData> onHrData)
+        public UdpConnection(string ipAddress, int port, Action<AccData> onAccData, Action<EcgData> onEcgData,
+            Action<HRData> onHrData)
         {
             this.onAccData = onAccData;
             this.onEcgData = onEcgData;
-            this.onHRData = onHrData;
+            onHRData = onHrData;
             var parsedAddress = IPAddress.Parse(ipAddress);
             client = new UdpClient(new IPEndPoint(parsedAddress, port));
         }
 
-        public void Listen() => Task.Run(async () =>
+        public void Listen()
         {
-            listening = true;
-            while (listening)
+            Task.Run(async () =>
             {
-                var result = await client.ReceiveAsync();
-                string receivedStr = Encoding.UTF8.GetString(result.Buffer);
-
-                var data = receivedStr.Split(':');
-                if (data.Length == 2)
+                listening = true;
+                while (listening)
                 {
-                    var name = data[0];
-                    if (name.Equals("ACC"))
-                    {
-                        onAccData(AccData.FromString(data[1]));
-                    }else if (name.Equals("ECG"))
-                    {
-                        onEcgData(EcgData.FromString(data[1]));
-                    }else if (name.Equals("HR"))
+                    var result = await client.ReceiveAsync();
+                    var receivedStr = Encoding.UTF8.GetString(result.Buffer);
+
+                    var data = receivedStr.Split(':');
+                    if (data.Length == 2)
                     {
-                        onHRData(HRData.FromString(data[1]));
+                        var name = data[0];
+                        if (name.Equals("ACC"))
+                            onAccData(AccData.FromString(data[1]));
+                        else if (name.Equals("ECG"))
+                            onEcgData(EcgData.FromString(data[1]));
+                        else if (name.Equals("HR")) onHRData(HRData.FromString(data[1]));
                     }
-                
+
+                    //Debug.Log($"RECEIVED DATA VIA UDP: {receivedStr}");
                 }
-            
-                //Debug.Log($"RECEIVED DATA VIA UDP: {receivedStr}");
-            }
-        });
+            });
+        }
 
         public void StopListening()
         {
             listening = false;
         }
-    
     }
 }

+ 27 - 38
Assets/Scripts/Sensors/SensorStatus.cs

@@ -1,15 +1,8 @@
-using System;
-using Controller;
-using Controller.Bicycle;
-using Display;
-using Sensors.ANT;
-using Sensors.Polar;
+using Controller;
 using SicknessReduction.Haptic;
 using TMPro;
 using Tracking;
 using UnityEngine;
-using UnityEngine.SceneManagement;
-using UnityEngine.UI;
 using Valve.VR;
 
 namespace Sensors
@@ -31,39 +24,18 @@ namespace Sensors
         public bool waitForHr = true;
         public bool waitForPolar = true;
         public bool waitForPower = true;
-        public bool waitForMqtt = false;
+        public bool waitForMqtt;
+        private DataBroker dataBroker;
 
         private SteamVR_TrackedObject fwObject;
         private SteamVR_TrackedObject legObject;
-        private DataBroker dataBroker;
-        private bool mqttReady;
         private string mqttClient;
+        private bool mqttReady;
         private string mqttTopic;
 
         private bool PolarReady => BikeSensorData.Instance.PolarData.HasValue &&
                                    BikeSensorData.Instance.PolarData.Value.Acc != Vector3.zero;
 
-        private void OnEnable()
-        {
-            sensorBikeController.enabled = false;
-            if (waitForMqtt)
-            {
-                dataBroker = DataBroker.Instance;
-                dataBroker.onClientSubscribed = onClientSubscribedToTopic;
-            }
-            else
-            {
-                mqttStatusText.enabled = false;
-            }
-        }
-
-        private void onClientSubscribedToTopic(string clientName, string topic)
-        {
-            mqttClient = clientName;
-            mqttTopic = topic;
-            mqttReady = true;
-        }
-
         private void Start()
         {
             fwObject = fwTracker.GetComponent<SteamVR_TrackedObject>();
@@ -77,8 +49,8 @@ namespace Sensors
             var powerData = BikeSensorData.Instance.PowermeterData;
             var polarData = BikeSensorData.Instance.PolarData;
             hrStatusText.text = hrData.HasValue
-                    ? $"Heart Rate: Connected ({hrData?.HeartRate})"
-                    : "Heart Rate: Disconnected";
+                ? $"Heart Rate: Connected ({hrData?.HeartRate})"
+                : "Heart Rate: Disconnected";
             speedStatusText.text =
                 speedData.HasValue ? $"Speed: Connected ({speedData?.SpeedKmh}) " : "Speed: Disconnected";
             powerStatusText.text = powerData.HasValue
@@ -88,11 +60,9 @@ namespace Sensors
                 ? $"Polar: Connected ({polarData?.Acc}, {polarData?.EcgValue})"
                 : "Polar: Disconnected";
             if (waitForMqtt)
-            {
                 mqttStatusText.text = mqttReady
                     ? $"Mqtt: Connected ({mqttClient}, {mqttTopic})"
                     : "Mqtt: Disconnected";
-            }
 
 
             if (!(waitForTrackers && (!fwObject.isValid || !legObject.isValid)
@@ -101,10 +71,22 @@ namespace Sensors
                   || waitForPower && !powerData.HasValue
                   || waitForPolar && !PolarReady
                   || waitForMqtt && !mqttReady)
-            )
-            {
+                )
                 //TODO: show text, that we are ready and start on button press
                 Destroy(gameObject);
+        }
+
+        private void OnEnable()
+        {
+            sensorBikeController.enabled = false;
+            if (waitForMqtt)
+            {
+                dataBroker = DataBroker.Instance;
+                dataBroker.onClientSubscribed = onClientSubscribedToTopic;
+            }
+            else
+            {
+                mqttStatusText.enabled = false;
             }
         }
 
@@ -112,5 +94,12 @@ namespace Sensors
         {
             sensorBikeController.enabled = true;
         }
+
+        private void onClientSubscribedToTopic(string clientName, string topic)
+        {
+            mqttClient = clientName;
+            mqttTopic = topic;
+            mqttReady = true;
+        }
     }
 }

+ 42 - 42
Assets/Scripts/SicknessReduction/DynamicReductionSource.cs

@@ -1,5 +1,4 @@
-using System;
-using Controller.Bicycle;
+using Controller.Bicycle;
 using SicknessReduction.Visual.Vignetting;
 using UnityEngine;
 using UnityEngine.Serialization;
@@ -9,45 +8,6 @@ namespace SicknessReduction
 {
     public class DynamicReductionSource : MonoBehaviour
     {
-        #region vars
-
-        public RbBicycleController bikeController;
-        public LerpSlopeCollider slopeCollider;
-
-        [Header("Configuration")] public bool useSpeed = true;
-        public bool useSteer = true;
-        public bool useSlope = true;
-        public float minSpeedForRestriction = 0.28f;
-
-        public float speedMultiplier = 1f;
-        public float slopeMultiplier = 1f;
-        public float steerMultiplier = 1f;
-
-        [Header("Restriction Data")] public float minValue = 0.3f;
-        public float maxValue = 0.7f;
-        public float maxValueChangePerSecond = 0.8f;
-
-        [FormerlySerializedAs("threshold")] [Tooltip("Depending on Vignetting source -> deg or deg/s")]
-        public float steerThreshold = 4f;
-        public float speedThreshold = 1f;
-        public float slopeThreshold = 1f;
-
-        public float maxValueAtSpeed = 8.33f; //30kmh
-        public float maxValueAtSteerAngle = 15f;
-        public float maxValueAtSlope = 8.531f;
-
-        private float currentSlopeDeg;
-
-        private ValueBasedRestrictionSuggestor steerAngleSuggestor;
-        private ValueBasedRestrictionSuggestor slopeSuggestor;
-        private ValueAndTimeBasedRestrictionSuggestor speedSuggestor;
-
-        protected float currentValue;
-
-        public float CurrentValue => currentValue;
-
-        #endregion
-        
         protected virtual void Start()
         {
             if (bikeController == null) Debug.LogError("bike controller = null!");
@@ -73,7 +33,7 @@ namespace SicknessReduction
                 currentValue = 0;
                 return;
             }
-            
+
             if (useSteer) steerAngleSuggestor.Value = bikeController.CurrentSteerAngle;
             if (useSpeed) speedSuggestor.UpdateValue(bikeController.CurrentSpeed);
             if (useSlope) slopeSuggestor.Value = currentSlopeDeg;
@@ -93,5 +53,45 @@ namespace SicknessReduction
 
             //Debug.Log($"SuggestionValue = {currentValue}");
         }
+
+        #region vars
+
+        public RbBicycleController bikeController;
+        public LerpSlopeCollider slopeCollider;
+
+        [Header("Configuration")] public bool useSpeed = true;
+        public bool useSteer = true;
+        public bool useSlope = true;
+        public float minSpeedForRestriction = 0.28f;
+
+        public float speedMultiplier = 1f;
+        public float slopeMultiplier = 1f;
+        public float steerMultiplier = 1f;
+
+        [Header("Restriction Data")] public float minValue = 0.3f;
+        public float maxValue = 0.7f;
+        public float maxValueChangePerSecond = 0.8f;
+
+        [FormerlySerializedAs("threshold")] [Tooltip("Depending on Vignetting source -> deg or deg/s")]
+        public float steerThreshold = 4f;
+
+        public float speedThreshold = 1f;
+        public float slopeThreshold = 1f;
+
+        public float maxValueAtSpeed = 8.33f; //30kmh
+        public float maxValueAtSteerAngle = 15f;
+        public float maxValueAtSlope = 8.531f;
+
+        private float currentSlopeDeg;
+
+        private ValueBasedRestrictionSuggestor steerAngleSuggestor;
+        private ValueBasedRestrictionSuggestor slopeSuggestor;
+        private ValueAndTimeBasedRestrictionSuggestor speedSuggestor;
+
+        protected float currentValue;
+
+        public float CurrentValue => currentValue;
+
+        #endregion
     }
 }

+ 18 - 23
Assets/Scripts/SicknessReduction/Haptic/DataBroker.cs

@@ -1,41 +1,18 @@
 using System;
-using System.Net;
 using System.Threading.Tasks;
 using Makaretu.Dns;
 using MQTTnet;
 using MQTTnet.Server;
-using Sensors;
 using UnityEngine;
 
 namespace SicknessReduction.Haptic
 {
     public sealed class DataBroker
     {
-        #region signleton
-
-        private static readonly Lazy<DataBroker>
-            lazy =
-                new Lazy<DataBroker>
-                    (() => new DataBroker());
-
-        public static DataBroker Instance => lazy.Value;
-
-        public static void DisposeInstance()
-        {
-            if (!Instance.disposed)
-            {
-                Instance.Dispose();
-            }
-        }
-
-        #endregion
-
         private readonly IMqttServer server;
         private readonly Task serverStarted;
         private bool disposed;
 
-        public Action<string, string> onClientSubscribed { set; get; }
-
         private DataBroker()
         {
             server = new MqttFactory().CreateMqttServer();
@@ -50,6 +27,8 @@ namespace SicknessReduction.Haptic
             //await PublishBla();
         }
 
+        public Action<string, string> onClientSubscribed { set; get; }
+
         public async Task AwaitServerStarted()
         {
             await serverStarted;
@@ -74,5 +53,21 @@ namespace SicknessReduction.Haptic
             await server.StopAsync();
             disposed = true;
         }
+
+        #region signleton
+
+        private static readonly Lazy<DataBroker>
+            lazy =
+                new Lazy<DataBroker>
+                    (() => new DataBroker());
+
+        public static DataBroker Instance => lazy.Value;
+
+        public static void DisposeInstance()
+        {
+            if (!Instance.disposed) Instance.Dispose();
+        }
+
+        #endregion
     }
 }

+ 2 - 4
Assets/Scripts/SicknessReduction/Haptic/DeskFanController.cs

@@ -1,6 +1,4 @@
-using System;
-using System.Diagnostics;
-using System.Threading.Tasks;
+using System.Threading.Tasks;
 using Controller.Bicycle;
 using UnityEngine;
 
@@ -20,9 +18,9 @@ namespace SicknessReduction.Haptic
         public float maxValueAtSpeed = 6.94f; //25km/h
         public float speedUntilNoFan = 1.94f; //2kmh
         public RbBicycleController bicycleController;
-        private int previousFanValue;
 
         public bool useReductionSource = true;
+        private int previousFanValue;
         private DynamicReductionSource reductionSource;
 
 

+ 6 - 6
Assets/Scripts/SicknessReduction/Haptic/EspController.cs

@@ -1,17 +1,16 @@
-using System;
-using UnityEngine;
+using UnityEngine;
 
 namespace SicknessReduction.Haptic
 {
     public abstract class EspController : MonoBehaviour
     {
         protected DataBroker Broker;
-        protected bool DoUpdate { private set; get; }
-        protected bool PreviousUpdateActive;
         private bool brokerAvailable;
+        private float lastTs;
+        protected bool PreviousUpdateActive;
 
-        private float publishWaitTime = 0.05f; //20Hz
-        private float lastTs = 0f;
+        private readonly float publishWaitTime = 0.05f; //20Hz
+        protected bool DoUpdate { private set; get; }
 
         protected virtual async void Start()
         {
@@ -27,6 +26,7 @@ namespace SicknessReduction.Haptic
                 DoUpdate = false;
                 return;
             }
+
             var t = Time.time;
             if (t - lastTs >= publishWaitTime)
             {

+ 0 - 2
Assets/Scripts/SicknessReduction/Haptic/FanController.cs

@@ -36,9 +36,7 @@ namespace SicknessReduction.Haptic
             {
                 previousFanCycle = cycle;
                 for (var i = 0; i < NUM_CHANNELS; i++)
-                {
                     await Broker.Publish(TOPIC.Replace(CHANNEL_NUMBER_PLACEHOLDER, $"{i}"), $"{cycle}");
-                }
             }
         }
 

+ 2 - 8
Assets/Scripts/SicknessReduction/Haptic/VibrationController.cs

@@ -25,12 +25,12 @@ namespace SicknessReduction.Haptic
         public VibrationControllerMode mode;
         public int fixedCycleRpm;
 
+        private int currentCycle;
+
         private bool initialCyclePublished;
         private int previousCadence = -1;
         private DynamicReductionSource reductionSource;
 
-        private int currentCycle = 0;
-
         protected override void Start()
         {
             base.Start();
@@ -49,7 +49,6 @@ namespace SicknessReduction.Haptic
 
             if (!DoUpdate || PreviousUpdateActive) return;
             if (reductionValue > 0)
-            {
                 switch (mode)
                 {
                     case VibrationControllerMode.Continuous:
@@ -64,11 +63,8 @@ namespace SicknessReduction.Haptic
                     default:
                         throw new ArgumentOutOfRangeException();
                 }
-            }
             else
-            {
                 await StopVibrating();
-            }
 
             PreviousUpdateActive = false;
         }
@@ -124,10 +120,8 @@ namespace SicknessReduction.Haptic
         private async Task VibrateContinuous(int cycleValue)
         {
             if (Math.Abs(cycleValue - currentCycle) > 0)
-            {
                 //Debug.Log($"Sending Cycle {cycleValue}");
                 await Broker.Publish(TOPIC_CYCLE, $"{cycleValue}");
-            }
         }
 
         private async Task PublishCadence(int cadence)

+ 18 - 20
Assets/Scripts/SicknessReduction/Visual/DoF/DynamicDoF.cs

@@ -2,7 +2,6 @@
 using System.Collections.Generic;
 using System.Linq;
 using UnityEngine;
-using UnityEngine.EventSystems;
 using UnityEngine.Rendering;
 using UnityEngine.Rendering.Universal;
 
@@ -15,13 +14,13 @@ namespace SicknessReduction.Visual.DoF
         public float min;
         public float max;
     }
-    
+
     //TODO: look at https://catlikecoding.com/unity/tutorials/advanced-rendering/depth-of-field/ or pseudocode in paper
     public class DynamicDoF : MonoBehaviour
     {
         private const int NUMBER_OF_RAYS = 9; // Carneige, Rhee (2015)
         private const float RAY_OFFSET = 6f; //Exact value not mentioned in paper
-        
+
         public CocRadius cocRadius; //Carneige, Rhee (2015)
 
         public float refocusTimePerMeter = 0.0000017f; //seconds; Carneige, Rhee (2015)
@@ -36,12 +35,12 @@ namespace SicknessReduction.Visual.DoF
         private Transform cameraTransform;
         private DepthOfField doF;
         private bool doFAvailable;
+        private readonly Vector3[] ends = new Vector3[NUMBER_OF_RAYS];
         private float maxCocRadius;
 
-        private List<float> rayDistances = new List<float>(NUMBER_OF_RAYS);
-        private Vector3[] ends = new Vector3[NUMBER_OF_RAYS];
-      
-        
+        private readonly List<float> rayDistances = new List<float>(NUMBER_OF_RAYS);
+
+
         //TODO: debug, remove
         //public GameObject gizmoPrefab;
         //private GameObject[] hits =  new GameObject[NUMBER_OF_RAYS];
@@ -55,7 +54,7 @@ namespace SicknessReduction.Visual.DoF
             {
                 hits[i] = Instantiate(gizmoPrefab);
                 hits[i].SetActive(false);
-            } *///TODO: debug, remove
+            } */ //TODO: debug, remove
             doF = (DepthOfField) postProcessProfile.components.FirstOrDefault(c => c is DepthOfField);
             doFAvailable = doF != null;
             if (doFAvailable)
@@ -78,10 +77,8 @@ namespace SicknessReduction.Visual.DoF
             if (!doFAvailable) return;
             var focusDistance = CastRays();
             if (focusDistance < 0)
-            {
                 focusDistance = doF.focusDistance.value;
-                //return;
-            }
+            //return;
 
             /*For real-time performance, we
 simply assume all users will take a static 500 ms
@@ -97,14 +94,17 @@ distances that takes ≈ 1.7*/
             doF.focalLength.value = 1;
 
             //var coc = maxFactorRadiusCOC * 1 / Mathf.Pow(focusDistance, pow);
-            var coc = Mathf.Clamp(cocRadius.factor * (-Mathf.Log(focusDistance) + 1.9f * Mathf.Exp(1)), cocRadius.min, cocRadius.max);
+            var coc = Mathf.Clamp(cocRadius.factor * (-Mathf.Log(focusDistance) + 1.9f * Mathf.Exp(1)), cocRadius.min,
+                cocRadius.max);
             //Debug.Log($"COC = {coc}, focusDistance = {focusDistance}");
             //var coc = maxFactorRadiusCOC * 1 - ()
             doF.aperture.value = ApertureForCocAndFocusDistance(coc, focusDistance);
         }
 
-        private float ApertureForCocAndFocusDistance(float coc, float focusDistance) =>
-            1 / (1000 * coc * (focusDistance - 0.001f));
+        private float ApertureForCocAndFocusDistance(float coc, float focusDistance)
+        {
+            return 1 / (1000 * coc * (focusDistance - 0.001f));
+        }
 
         private float CastRays()
         {
@@ -113,7 +113,7 @@ distances that takes ≈ 1.7*/
             var up = cameraTransform.up;
 
             var adjustedForward = Vector3.RotateTowards(forward, up, offsetFromCenter * Mathf.Deg2Rad, 0f);
-            
+
             var start = position + forward * playerCamera.nearClipPlane;
 
             ends[0] = position + adjustedForward * playerCamera.farClipPlane;
@@ -131,14 +131,12 @@ distances that takes ≈ 1.7*/
             {
                 var end = ends[i];
                 if (Physics.Linecast(start, end, out var hit, Physics.DefaultRaycastLayers))
-                {
                     /*Debug.DrawLine(start, hit.point, Color.green);
-                    hits[i].transform.position = hit.point;
-                    hits[i].transform.localScale = Vector3.one * (hit.distance * 0.01f); 
-                    hits[i].SetActive(true);*/
+                        hits[i].transform.position = hit.point;
+                        hits[i].transform.localScale = Vector3.one * (hit.distance * 0.01f); 
+                        hits[i].SetActive(true);*/
                     //Debug.Log("DoF - Hit, Distance = " + hit.distance);
                     rayDistances.Add(hit.distance);
-                }
                 /*else
                 {
                     hits[i].SetActive(false);

+ 9 - 10
Assets/Scripts/SicknessReduction/Visual/IpdInfo.cs

@@ -1,16 +1,13 @@
-using System;
-using UnityEngine;
+using UnityEngine;
 using Valve.VR;
 
 namespace SicknessReduction.Visual
 {
     public class IpdInfo : MonoBehaviour
     {
-        private SteamVR_Events.Action ipdChangedAction;
-
         public delegate void OnIpdChangedEvent(float ipdMeters);
 
-        public event OnIpdChangedEvent onIpdChanged; // data event
+        private SteamVR_Events.Action ipdChangedAction;
 
         private void OnEnable()
         {
@@ -19,6 +16,13 @@ namespace SicknessReduction.Visual
             ipdChangedAction.enabled = true;
         }
 
+        private void OnDisable()
+        {
+            ipdChangedAction.enabled = false;
+        }
+
+        public event OnIpdChangedEvent onIpdChanged; // data event
+
         private void OnIpdChanged(VREvent_t vrEvent)
         {
             var ipdMeters = vrEvent.data.ipd.ipdMeters;
@@ -26,11 +30,6 @@ namespace SicknessReduction.Visual
             Debug.Log($"IPD changed to {ipdMeters}");
         }
 
-        private void OnDisable()
-        {
-            ipdChangedAction.enabled = false;
-        }
-
         private void OnDeviceConnected(int index, bool connected)
         {
             if (index < 0) return;

+ 40 - 41
Assets/Scripts/SicknessReduction/Visual/Rendering/MaterialBlitFeature.cs

@@ -1,51 +1,50 @@
-using UnityEngine;
+using System;
+using UnityEngine;
 using UnityEngine.Rendering.Universal;
 
 namespace SicknessReduction.Visual.Rendering
 {
-  public class MaterialBlitFeature : ScriptableRendererFeature
-  {
-    [System.Serializable]
-    public class MyFeatureSettings
+    public class MaterialBlitFeature : ScriptableRendererFeature
     {
-      // we're free to put whatever we want here, public fields will be exposed in the inspector
-      public bool IsEnabled = true;
-      public RenderPassEvent WhenToInsert = RenderPassEvent.AfterRendering;
-      public Material MaterialToBlit;
-    }
+        // MUST be named "settings" (lowercase) to be shown in the Render Features inspector
+        public MyFeatureSettings settings = new MyFeatureSettings();
+        private MaterialBlitRenderPass myRenderPass;
 
-    // MUST be named "settings" (lowercase) to be shown in the Render Features inspector
-    public MyFeatureSettings settings = new MyFeatureSettings();
+        private RenderTargetHandle renderTextureHandle;
 
-    RenderTargetHandle renderTextureHandle;
-    MaterialBlitRenderPass myRenderPass;
+        public override void Create()
+        {
+            myRenderPass = new MaterialBlitRenderPass(
+                "Material Blit Render Pass",
+                settings.WhenToInsert,
+                settings.MaterialToBlit
+            );
+        }
 
-    public override void Create()
-    {
-      myRenderPass = new MaterialBlitRenderPass(
-        "Material Blit Render Pass",
-        settings.WhenToInsert,
-        settings.MaterialToBlit
-      );
-    }
-  
-    // called every frame once per camera
-    public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingData renderingData)
-    {
-      if (!settings.IsEnabled)
-      {
-        // we can do nothing this frame if we want
-        return;
-      }
-    
-      // Gather up and pass any extra information our pass will need.
-      // In this case we're getting the camera's color buffer target
-      var cameraColorTargetIdent = renderer.cameraColorTarget;
-      myRenderPass.Setup(cameraColorTargetIdent);
+        // called every frame once per camera
+        public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingData renderingData)
+        {
+            if (!settings.IsEnabled)
+                // we can do nothing this frame if we want
+                return;
+
+            // Gather up and pass any extra information our pass will need.
+            // In this case we're getting the camera's color buffer target
+            var cameraColorTargetIdent = renderer.cameraColorTarget;
+            myRenderPass.Setup(cameraColorTargetIdent);
+
+            // Ask the renderer to add our pass.
+            // Could queue up multiple passes and/or pick passes to use
+            renderer.EnqueuePass(myRenderPass);
+        }
 
-      // Ask the renderer to add our pass.
-      // Could queue up multiple passes and/or pick passes to use
-      renderer.EnqueuePass(myRenderPass);
+        [Serializable]
+        public class MyFeatureSettings
+        {
+            // we're free to put whatever we want here, public fields will be exposed in the inspector
+            public bool IsEnabled = true;
+            public RenderPassEvent WhenToInsert = RenderPassEvent.AfterRendering;
+            public Material MaterialToBlit;
+        }
     }
-  }
-}
+}

+ 54 - 53
Assets/Scripts/SicknessReduction/Visual/Rendering/MaterialBlitRenderPass.cs

@@ -4,67 +4,68 @@ using UnityEngine.Rendering.Universal;
 
 namespace SicknessReduction.Visual.Rendering
 {
-  class MaterialBlitRenderPass : ScriptableRenderPass
-  {
-    // used to label this pass in Unity's Frame Debug utility
-    string profilerTag;
+    internal class MaterialBlitRenderPass : ScriptableRenderPass
+    {
+        private RenderTargetIdentifier cameraColorTargetIdent;
 
-    Material materialToBlit;
-    RenderTargetIdentifier cameraColorTargetIdent;
-    RenderTargetHandle tempTexture;
+        private readonly Material materialToBlit;
 
-    public MaterialBlitRenderPass(string profilerTag,
-      RenderPassEvent renderPassEvent, Material materialToBlit)
-    {
-      this.profilerTag = profilerTag;
-      this.renderPassEvent = renderPassEvent;
-      this.materialToBlit = materialToBlit;
-    }
+        // used to label this pass in Unity's Frame Debug utility
+        private readonly string profilerTag;
+        private RenderTargetHandle tempTexture;
 
-    // This isn't part of the ScriptableRenderPass class and is our own addition.
-    // For this custom pass we need the camera's color target, so that gets passed in.
-    public void Setup(RenderTargetIdentifier cameraColorTargetIdent)
-    {
-      this.cameraColorTargetIdent = cameraColorTargetIdent;
-    }
+        public MaterialBlitRenderPass(string profilerTag,
+            RenderPassEvent renderPassEvent, Material materialToBlit)
+        {
+            this.profilerTag = profilerTag;
+            this.renderPassEvent = renderPassEvent;
+            this.materialToBlit = materialToBlit;
+        }
 
-    // called each frame before Execute, use it to set up things the pass will need
-    public override void Configure(CommandBuffer cmd, RenderTextureDescriptor cameraTextureDescriptor)
-    {
-      // create a temporary render texture that matches the camera
-      cmd.GetTemporaryRT(tempTexture.id, cameraTextureDescriptor);
-    }
+        // This isn't part of the ScriptableRenderPass class and is our own addition.
+        // For this custom pass we need the camera's color target, so that gets passed in.
+        public void Setup(RenderTargetIdentifier cameraColorTargetIdent)
+        {
+            this.cameraColorTargetIdent = cameraColorTargetIdent;
+        }
 
-    // Execute is called for every eligible camera every frame. It's not called at the moment that
-    // rendering is actually taking place, so don't directly execute rendering commands here.
-    // Instead use the methods on ScriptableRenderContext to set up instructions.
-    // RenderingData provides a bunch of (not very well documented) information about the scene
-    // and what's being rendered.
-    public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
-    {
-      // fetch a command buffer to use
-      CommandBuffer cmd = CommandBufferPool.Get(profilerTag);
-      cmd.Clear();
+        // called each frame before Execute, use it to set up things the pass will need
+        public override void Configure(CommandBuffer cmd, RenderTextureDescriptor cameraTextureDescriptor)
+        {
+            // create a temporary render texture that matches the camera
+            cmd.GetTemporaryRT(tempTexture.id, cameraTextureDescriptor);
+        }
 
-      // the actual content of our custom render pass!
-      // we apply our material while blitting to a temporary texture
-      cmd.Blit(cameraColorTargetIdent, tempTexture.Identifier(), materialToBlit, 0);
+        // Execute is called for every eligible camera every frame. It's not called at the moment that
+        // rendering is actually taking place, so don't directly execute rendering commands here.
+        // Instead use the methods on ScriptableRenderContext to set up instructions.
+        // RenderingData provides a bunch of (not very well documented) information about the scene
+        // and what's being rendered.
+        public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
+        {
+            // fetch a command buffer to use
+            var cmd = CommandBufferPool.Get(profilerTag);
+            cmd.Clear();
 
-      // ...then blit it back again 
-      cmd.Blit(tempTexture.Identifier(), cameraColorTargetIdent);
+            // the actual content of our custom render pass!
+            // we apply our material while blitting to a temporary texture
+            cmd.Blit(cameraColorTargetIdent, tempTexture.Identifier(), materialToBlit, 0);
 
-      // don't forget to tell ScriptableRenderContext to actually execute the commands
-      context.ExecuteCommandBuffer(cmd);
+            // ...then blit it back again 
+            cmd.Blit(tempTexture.Identifier(), cameraColorTargetIdent);
 
-      // tidy up after ourselves
-      cmd.Clear();
-      CommandBufferPool.Release(cmd);
-    }
+            // don't forget to tell ScriptableRenderContext to actually execute the commands
+            context.ExecuteCommandBuffer(cmd);
 
-    // called after Execute, use it to clean up anything allocated in Configure
-    public override void FrameCleanup(CommandBuffer cmd)
-    {
-      cmd.ReleaseTemporaryRT(tempTexture.id);
+            // tidy up after ourselves
+            cmd.Clear();
+            CommandBufferPool.Release(cmd);
+        }
+
+        // called after Execute, use it to clean up anything allocated in Configure
+        public override void FrameCleanup(CommandBuffer cmd)
+        {
+            cmd.ReleaseTemporaryRT(tempTexture.id);
+        }
     }
-  }
-}
+}

+ 15 - 15
Assets/Scripts/SicknessReduction/Visual/Vignetting/DynamicVignetting.cs

@@ -1,13 +1,10 @@
 using System.Linq;
-using Controller.Bicycle;
 using SicknessReduction.Visual.Rendering;
-using UnityEditor.Recorder.Input;
 using UnityEngine;
 using UnityEngine.Rendering.Universal;
 
 namespace SicknessReduction.Visual.Vignetting
 {
-
     public class DynamicVignetting : DynamicReductionSource
     {
         //TODO: cite https://www.researchgate.net/publication/326760789_Assessing_vignetting_as_a_means_to_reduce_VR_sickness_during_amplified_head_rotations
@@ -17,13 +14,15 @@ namespace SicknessReduction.Visual.Vignetting
 
         [Header("Unity Objects")] public ForwardRendererData forwardRenderer;
         public Transform hmd;
-        
+
         [Range(0, 1)] public float distInnerOuterRadius = .05f;
 
         //TODO: figure out what angular velocity means in my context
         private MaterialBlitFeature blitFeature;
-        private Material blitFeatureMaterial;
         private bool blitFeatureAvailable;
+        private Material blitFeatureMaterial;
+        private static readonly int OFOV = Shader.PropertyToID("_OFOV");
+        private static readonly int IFOV = Shader.PropertyToID("_IFOV");
 
         protected override void Start()
         {
@@ -35,8 +34,10 @@ namespace SicknessReduction.Visual.Vignetting
             {
                 Debug.LogError("VignetteBlitFilter not available!");
                 return;
-            };
-            
+            }
+
+            ;
+
             // ReSharper disable once PossibleNullReferenceException
             blitFeature.SetActive(true);
             blitFeatureMaterial = blitFeature.settings.MaterialToBlit;
@@ -58,14 +59,6 @@ namespace SicknessReduction.Visual.Vignetting
             {
                 blitFeature.SetActive(false);
             }
-            
-        }
-
-        private void UpdateMaterial()
-        {
-            var r = Mathf.Clamp(1 - currentValue, 0, 1);
-            blitFeatureMaterial.SetFloat("_OFOV", r);
-            blitFeatureMaterial.SetFloat("_IFOV", Mathf.Clamp(r - distInnerOuterRadius, 0, 1));
         }
 
         private void OnDestroy()
@@ -73,5 +66,12 @@ namespace SicknessReduction.Visual.Vignetting
             if (!blitFeatureAvailable) return;
             blitFeature.SetActive(false);
         }
+
+        private void UpdateMaterial()
+        {
+            var r = Mathf.Clamp(1 - currentValue, 0, 1);
+            blitFeatureMaterial.SetFloat(OFOV, r);
+            blitFeatureMaterial.SetFloat(IFOV, Mathf.Clamp(r - distInnerOuterRadius, 0, 1));
+        }
     }
 }

+ 18 - 19
Assets/Scripts/SicknessReduction/Visual/Vignetting/RestrictionSuggestor.cs

@@ -2,7 +2,6 @@
 using System.Collections.Generic;
 using System.Linq;
 using UnityEngine;
-using Valve.VR.InteractionSystem;
 
 namespace SicknessReduction.Visual.Vignetting
 {
@@ -13,10 +12,10 @@ namespace SicknessReduction.Visual.Vignetting
 
     public abstract class RestrictionSuggestor : IRestrectionSuggestor
     {
-        protected readonly float threshold;
-        protected readonly float minRestriction;
         protected readonly float maxRestriction;
         protected readonly float maxValue;
+        protected readonly float minRestriction;
+        protected readonly float threshold;
 
         protected RestrictionSuggestor(float threshold, float minRestriction, float maxRestriction,
             float maxValue)
@@ -27,14 +26,22 @@ namespace SicknessReduction.Visual.Vignetting
             this.maxValue = maxValue;
         }
 
-        protected float LerpedSuggestion(float value) => Mathf.Lerp(minRestriction, maxRestriction,
-            (value - threshold) / (maxValue - threshold));
-
         public abstract float Suggestion { get; }
+
+        protected float LerpedSuggestion(float value)
+        {
+            return Mathf.Lerp(minRestriction, maxRestriction,
+                (value - threshold) / (maxValue - threshold));
+        }
     }
 
     public class ValueBasedRestrictionSuggestor : RestrictionSuggestor
     {
+        public ValueBasedRestrictionSuggestor(float threshold, float minRestriction, float maxRestriction,
+            float maxValue) : base(threshold, minRestriction, maxRestriction, maxValue)
+        {
+        }
+
         public override float Suggestion
         {
             get
@@ -47,22 +54,17 @@ namespace SicknessReduction.Visual.Vignetting
         }
 
         public float Value { set; get; } = 0f;
-
-
-        public ValueBasedRestrictionSuggestor(float threshold, float minRestriction, float maxRestriction,
-            float maxValue) : base(threshold, minRestriction, maxRestriction, maxValue)
-        {
-        }
     }
 
     public class ValueAndTimeBasedRestrictionSuggestor : RestrictionSuggestor
     {
-        private readonly float tolerance;
         private readonly float timespan;
+        private readonly float tolerance;
         private readonly Dictionary<float, float> values = new Dictionary<float, float>();
         private float value;
 
-        public ValueAndTimeBasedRestrictionSuggestor(float threshold, float minRestriction, float maxRestriction, float maxValue, float tolerance, float timespan) : base(threshold, minRestriction, maxRestriction, maxValue)
+        public ValueAndTimeBasedRestrictionSuggestor(float threshold, float minRestriction, float maxRestriction,
+            float maxValue, float tolerance, float timespan) : base(threshold, minRestriction, maxRestriction, maxValue)
         {
             this.tolerance = tolerance;
             this.timespan = timespan;
@@ -93,8 +95,8 @@ namespace SicknessReduction.Visual.Vignetting
 
     public abstract class QueueBasedRestrictionSuggestor<T> : RestrictionSuggestor
     {
-        protected Queue<Tuple<float, T>> values;
         protected int bufferSize;
+        protected Queue<Tuple<float, T>> values;
 
         public QueueBasedRestrictionSuggestor(float threshold, float minRestriction, float maxRestriction,
             float maxValue, int bufferSize = 10) : base(threshold, minRestriction, maxRestriction, maxValue)
@@ -105,10 +107,7 @@ namespace SicknessReduction.Visual.Vignetting
 
         public void AddValue(T value)
         {
-            if (values.Count >= bufferSize)
-            {
-                values.Dequeue();
-            }
+            if (values.Count >= bufferSize) values.Dequeue();
 
             values.Enqueue(new Tuple<float, T>(Time.time, value));
         }

+ 10 - 14
Assets/Scripts/SicknessReduction/Visual/VirtualNose.cs

@@ -1,5 +1,4 @@
-using System;
-using UnityEngine;
+using UnityEngine;
 
 namespace SicknessReduction.Visual
 {
@@ -14,8 +13,8 @@ namespace SicknessReduction.Visual
         public Vector3 scaleAt70;
 
         private Camera cam;
-        private GameObject nose;
         private IpdInfo ipdInfo;
+        private GameObject nose;
 
         private void OnEnable()
         {
@@ -27,10 +26,7 @@ namespace SicknessReduction.Visual
             }
 
             ipdInfo = GetComponentInParent<IpdInfo>();
-            if (ipdInfo == null)
-            {
-                Debug.LogError("No IPD Info found as parent of virtual nose");
-            }
+            if (ipdInfo == null) Debug.LogError("No IPD Info found as parent of virtual nose");
 
             if (adjustToIpd) ipdInfo.onIpdChanged += AdjustToIpd;
 
@@ -38,6 +34,13 @@ namespace SicknessReduction.Visual
             nose.transform.localPosition = Vector3.forward * cam.nearClipPlane;
         }
 
+        private void OnDisable()
+        {
+            ipdInfo.onIpdChanged -= AdjustToIpd;
+            if (nose == null) return;
+            Destroy(nose);
+        }
+
         private void AdjustToIpd(float ipdMeters)
         {
             var ipdMm = Mathf.Round(ipdMeters * 1000f);
@@ -46,12 +49,5 @@ namespace SicknessReduction.Visual
             nose.transform.localScale = Vector3.Lerp(scaleAt58, scaleAt70, ipdFactor);
             nose.transform.localPosition = Vector3.forward * cam.nearClipPlane + padding;
         }
-
-        private void OnDisable()
-        {
-            ipdInfo.onIpdChanged -= AdjustToIpd;
-            if (nose == null) return;
-            Destroy(nose);
-        }
     }
 }

+ 88 - 110
Assets/Scripts/SimpleCameraController.cs

@@ -1,127 +1,44 @@
-using UnityEngine;
+using UnityEditor;
+using UnityEngine;
 
 namespace UnityTemplateProjects
 {
     public class SimpleCameraController : MonoBehaviour
     {
-        class CameraState
-        {
-            public float yaw;
-            public float pitch;
-            public float roll;
-            public float x;
-            public float y;
-            public float z;
-
-            public void SetFromTransform(Transform t)
-            {
-                pitch = t.eulerAngles.x;
-                yaw = t.eulerAngles.y;
-                roll = t.eulerAngles.z;
-                x = t.position.x;
-                y = t.position.y;
-                z = t.position.z;
-            }
-
-            public void Translate(Vector3 translation)
-            {
-                Vector3 rotatedTranslation = Quaternion.Euler(pitch, yaw, roll) * translation;
-
-                x += rotatedTranslation.x;
-                y += rotatedTranslation.y;
-                z += rotatedTranslation.z;
-            }
-
-            public void LerpTowards(CameraState target, float positionLerpPct, float rotationLerpPct)
-            {
-                yaw = Mathf.Lerp(yaw, target.yaw, rotationLerpPct);
-                pitch = Mathf.Lerp(pitch, target.pitch, rotationLerpPct);
-                roll = Mathf.Lerp(roll, target.roll, rotationLerpPct);
-                
-                x = Mathf.Lerp(x, target.x, positionLerpPct);
-                y = Mathf.Lerp(y, target.y, positionLerpPct);
-                z = Mathf.Lerp(z, target.z, positionLerpPct);
-            }
-
-            public void UpdateTransform(Transform t)
-            {
-                t.eulerAngles = new Vector3(pitch, yaw, roll);
-                t.position = new Vector3(x, y, z);
-            }
-        }
-        
-        CameraState m_TargetCameraState = new CameraState();
-        CameraState m_InterpolatingCameraState = new CameraState();
-
-        [Header("Movement Settings")]
-        [Tooltip("Exponential boost factor on translation, controllable by mouse wheel.")]
+        [Header("Movement Settings")] [Tooltip("Exponential boost factor on translation, controllable by mouse wheel.")]
         public float boost = 3.5f;
 
-        [Tooltip("Time it takes to interpolate camera position 99% of the way to the target."), Range(0.001f, 1f)]
+        [Tooltip("Time it takes to interpolate camera position 99% of the way to the target.")] [Range(0.001f, 1f)]
         public float positionLerpTime = 0.2f;
 
         [Header("Rotation Settings")]
         [Tooltip("X = Change in mouse position.\nY = Multiplicative factor for camera rotation.")]
-        public AnimationCurve mouseSensitivityCurve = new AnimationCurve(new Keyframe(0f, 0.5f, 0f, 5f), new Keyframe(1f, 2.5f, 0f, 0f));
+        public AnimationCurve mouseSensitivityCurve =
+            new AnimationCurve(new Keyframe(0f, 0.5f, 0f, 5f), new Keyframe(1f, 2.5f, 0f, 0f));
 
-        [Tooltip("Time it takes to interpolate camera rotation 99% of the way to the target."), Range(0.001f, 1f)]
+        [Tooltip("Time it takes to interpolate camera rotation 99% of the way to the target.")] [Range(0.001f, 1f)]
         public float rotationLerpTime = 0.01f;
 
         [Tooltip("Whether or not to invert our Y axis for mouse input to rotation.")]
-        public bool invertY = false;
+        public bool invertY;
 
-        void OnEnable()
-        {
-            m_TargetCameraState.SetFromTransform(transform);
-            m_InterpolatingCameraState.SetFromTransform(transform);
-        }
+        private readonly CameraState m_InterpolatingCameraState = new CameraState();
 
-        Vector3 GetInputTranslationDirection()
-        {
-            Vector3 direction = new Vector3();
-            if (Input.GetKey(KeyCode.W))
-            {
-                direction += Vector3.forward;
-            }
-            if (Input.GetKey(KeyCode.S))
-            {
-                direction += Vector3.back;
-            }
-            if (Input.GetKey(KeyCode.A))
-            {
-                direction += Vector3.left;
-            }
-            if (Input.GetKey(KeyCode.D))
-            {
-                direction += Vector3.right;
-            }
-            if (Input.GetKey(KeyCode.Q))
-            {
-                direction += Vector3.down;
-            }
-            if (Input.GetKey(KeyCode.E))
-            {
-                direction += Vector3.up;
-            }
-            return direction;
-        }
-        
-        void Update()
+        private readonly CameraState m_TargetCameraState = new CameraState();
+
+        private void Update()
         {
             // Exit Sample  
             if (Input.GetKey(KeyCode.Escape))
             {
                 Application.Quit();
-				#if UNITY_EDITOR
-				UnityEditor.EditorApplication.isPlaying = false; 
-				#endif
+#if UNITY_EDITOR
+                EditorApplication.isPlaying = false;
+#endif
             }
 
             // Hide and lock cursor when right mouse button pressed
-            if (Input.GetMouseButtonDown(1))
-            {
-                Cursor.lockState = CursorLockMode.Locked;
-            }
+            if (Input.GetMouseButtonDown(1)) Cursor.lockState = CursorLockMode.Locked;
 
             // Unlock and show cursor when right mouse button released
             if (Input.GetMouseButtonUp(1))
@@ -133,23 +50,21 @@ namespace UnityTemplateProjects
             // Rotation
             if (Input.GetMouseButton(1))
             {
-                var mouseMovement = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y") * (invertY ? 1 : -1));
-                
+                var mouseMovement =
+                    new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y") * (invertY ? 1 : -1));
+
                 var mouseSensitivityFactor = mouseSensitivityCurve.Evaluate(mouseMovement.magnitude);
 
                 m_TargetCameraState.yaw += mouseMovement.x * mouseSensitivityFactor;
                 m_TargetCameraState.pitch += mouseMovement.y * mouseSensitivityFactor;
             }
-            
+
             // Translation
             var translation = GetInputTranslationDirection() * Time.deltaTime;
 
             // Speed up movement when shift key held
-            if (Input.GetKey(KeyCode.LeftShift))
-            {
-                translation *= 10.0f;
-            }
-            
+            if (Input.GetKey(KeyCode.LeftShift)) translation *= 10.0f;
+
             // Modify movement by a boost factor (defined in Inspector and modified in play mode through the mouse scroll wheel)
             boost += Input.mouseScrollDelta.y * 0.2f;
             translation *= Mathf.Pow(2.0f, boost);
@@ -158,12 +73,75 @@ namespace UnityTemplateProjects
 
             // Framerate-independent interpolation
             // Calculate the lerp amount, such that we get 99% of the way to our target in the specified time
-            var positionLerpPct = 1f - Mathf.Exp((Mathf.Log(1f - 0.99f) / positionLerpTime) * Time.deltaTime);
-            var rotationLerpPct = 1f - Mathf.Exp((Mathf.Log(1f - 0.99f) / rotationLerpTime) * Time.deltaTime);
+            var positionLerpPct = 1f - Mathf.Exp(Mathf.Log(1f - 0.99f) / positionLerpTime * Time.deltaTime);
+            var rotationLerpPct = 1f - Mathf.Exp(Mathf.Log(1f - 0.99f) / rotationLerpTime * Time.deltaTime);
             m_InterpolatingCameraState.LerpTowards(m_TargetCameraState, positionLerpPct, rotationLerpPct);
 
             m_InterpolatingCameraState.UpdateTransform(transform);
         }
-    }
 
+        private void OnEnable()
+        {
+            m_TargetCameraState.SetFromTransform(transform);
+            m_InterpolatingCameraState.SetFromTransform(transform);
+        }
+
+        private Vector3 GetInputTranslationDirection()
+        {
+            var direction = new Vector3();
+            if (Input.GetKey(KeyCode.W)) direction += Vector3.forward;
+            if (Input.GetKey(KeyCode.S)) direction += Vector3.back;
+            if (Input.GetKey(KeyCode.A)) direction += Vector3.left;
+            if (Input.GetKey(KeyCode.D)) direction += Vector3.right;
+            if (Input.GetKey(KeyCode.Q)) direction += Vector3.down;
+            if (Input.GetKey(KeyCode.E)) direction += Vector3.up;
+            return direction;
+        }
+
+        private class CameraState
+        {
+            public float pitch;
+            public float roll;
+            public float x;
+            public float y;
+            public float yaw;
+            public float z;
+
+            public void SetFromTransform(Transform t)
+            {
+                pitch = t.eulerAngles.x;
+                yaw = t.eulerAngles.y;
+                roll = t.eulerAngles.z;
+                x = t.position.x;
+                y = t.position.y;
+                z = t.position.z;
+            }
+
+            public void Translate(Vector3 translation)
+            {
+                var rotatedTranslation = Quaternion.Euler(pitch, yaw, roll) * translation;
+
+                x += rotatedTranslation.x;
+                y += rotatedTranslation.y;
+                z += rotatedTranslation.z;
+            }
+
+            public void LerpTowards(CameraState target, float positionLerpPct, float rotationLerpPct)
+            {
+                yaw = Mathf.Lerp(yaw, target.yaw, rotationLerpPct);
+                pitch = Mathf.Lerp(pitch, target.pitch, rotationLerpPct);
+                roll = Mathf.Lerp(roll, target.roll, rotationLerpPct);
+
+                x = Mathf.Lerp(x, target.x, positionLerpPct);
+                y = Mathf.Lerp(y, target.y, positionLerpPct);
+                z = Mathf.Lerp(z, target.z, positionLerpPct);
+            }
+
+            public void UpdateTransform(Transform t)
+            {
+                t.eulerAngles = new Vector3(pitch, yaw, roll);
+                t.position = new Vector3(x, y, z);
+            }
+        }
+    }
 }

+ 0 - 3
Assets/Scripts/SubjectManager.cs

@@ -1,5 +1,4 @@
 using System;
-using Logging.Base;
 using UnityEngine;
 
 public class SubjectManager : MonoBehaviour
@@ -9,8 +8,6 @@ public class SubjectManager : MonoBehaviour
     private void OnEnable()
     {
         if (string.IsNullOrEmpty(subjectIdentifier))
-        {
             throw new Exception("You have to specify a subject for the experiment!");
-        }
     }
 }

+ 10 - 10
Assets/Scripts/Tracking/CalibratableTracker.cs

@@ -5,6 +5,11 @@ namespace Tracking
 {
     public abstract class CalibratableTracker : MonoBehaviour
     {
+        public Transform bicycleTransform;
+
+        private Transform trackerTransform;
+        private Vector3 zeroPos;
+        private Vector3 zeroRot;
         protected abstract string KeyPrefix { get; }
 
         private string KeyPosX => $"{KeyPrefix}_vive_tracker_pos_x";
@@ -15,17 +20,11 @@ namespace Tracking
         private string KeyRotY => $"{KeyPrefix}_vive_tracker_rot_y";
         private string KeyRotZ => $"{KeyPrefix}_vive_tracker_rot_z";
 
-        private Transform trackerTransform;
-        private Vector3 zeroRot;
-        private Vector3 zeroPos;
-
-        public Transform bicycleTransform;
-
         public Vector3 RelativeRotation
         {
             get
             {
-                if(trackerTransform == null) return Vector3.zero; //TODO: something smarter
+                if (trackerTransform == null) return Vector3.zero; //TODO: something smarter
                 var newVal = trackerTransform.localRotation.eulerAngles - zeroRot;
                 var x = newVal.x;
                 var y = newVal.y;
@@ -40,7 +39,10 @@ namespace Tracking
                 return new Vector3(x, y, z);
             }
         }
-        public Vector3 RelativePosition => trackerTransform == null ? Vector3.zero : trackerTransform.localPosition - zeroPos;
+
+        public Vector3 RelativePosition =>
+            trackerTransform == null ? Vector3.zero : trackerTransform.localPosition - zeroPos;
+
         public Vector3 ZeroRot => zeroRot;
         public Vector3 ZeroPos => zeroPos;
 
@@ -82,13 +84,11 @@ namespace Tracking
 
         public void OnConnectedChanged(SteamVR_Action_Pose pose, SteamVR_Input_ActionScopes sources, bool connected)
         {
-            
         }
 
         public void OnConnectedChanged()
         {
             Debug.Log("connected changed");
-            
         }
     }
 }

+ 4 - 5
Assets/Scripts/Tracking/CameraTracker.cs

@@ -1,14 +1,13 @@
-using System;
-using UnityEngine;
+using UnityEngine;
 
 namespace Tracking
 {
-    public class CameraTracker: CalibratableTracker
+    public class CameraTracker : CalibratableTracker
     {
+        public KineticLegTracker legTracker;
         public float LeanRotation { get; private set; }
-        
+
         protected override string KeyPrefix => "cam";
-        public KineticLegTracker legTracker;
 
         private void Update()
         {

+ 12 - 22
Assets/Scripts/Tracking/FrontWheelTracker.cs

@@ -1,7 +1,5 @@
-using System;
-using System.Collections.Generic;
+using System.Collections.Generic;
 using System.Linq;
-using UnityEditor;
 using UnityEngine;
 using Valve.VR;
 
@@ -9,15 +7,14 @@ namespace Tracking
 {
     public class FrontWheelTracker : CalibratableTracker, IViveTracker
     {
-        protected override string KeyPrefix => "fw";
         public float trackerDistanceToWheelCenterPoint;
         public KineticLegTracker legTracker;
         public int framesToConsider = 10;
         public bool useTrackerRotationInsteadOfPosition;
         public string id;
-        public string Id => id;
-        public SteamVR_TrackedObject TrackedObject => GetComponent<SteamVR_TrackedObject>();
-        public float BatteryLevel { get; set; }
+
+        private Queue<float> previousValues;
+        protected override string KeyPrefix => "fw";
 
         public float SteerRotation => framesToConsider > 1
             ? CalculateSteerRotationMultiFrame()
@@ -25,16 +22,15 @@ namespace Tracking
 
         public Vector3 DebugPosOnBikePlane { private set; get; }
 
-        private Queue<float> previousValues;
-
         private void OnEnable()
         {
-            if (framesToConsider > 1)
-            {
-                previousValues = new Queue<float>(framesToConsider);
-            }
+            if (framesToConsider > 1) previousValues = new Queue<float>(framesToConsider);
         }
 
+        public string Id => id;
+        public SteamVR_TrackedObject TrackedObject => GetComponent<SteamVR_TrackedObject>();
+        public float BatteryLevel { get; set; }
+
         private float CalculateSteerRotationSingleFrame()
         {
             if (useTrackerRotationInsteadOfPosition) return RelativeRotation.y;
@@ -45,10 +41,7 @@ namespace Tracking
         private float CalculateSteerRotationMultiFrame()
         {
             var angleThisFrame = CalculateSteerRotationSingleFrame();
-            if (previousValues.Count > framesToConsider)
-            {
-                previousValues.Dequeue();
-            }
+            if (previousValues.Count > framesToConsider) previousValues.Dequeue();
 
             previousValues.Enqueue(angleThisFrame);
 
@@ -59,11 +52,8 @@ namespace Tracking
         private Vector3 GetPosOnBikePlane()
         {
             //legTracker position is added to compensate movements of the whole installation
-            Vector3 legTrackerPos = Vector3.zero;
-            if (legTracker.isActiveAndEnabled)
-            {
-                legTrackerPos = legTracker.RelativePosition;
-            }
+            var legTrackerPos = Vector3.zero;
+            if (legTracker.isActiveAndEnabled) legTrackerPos = legTracker.RelativePosition;
 
             var posOnBikePlane = Vector3.ProjectOnPlane(RelativePosition + legTrackerPos, bicycleTransform.up);
             DebugPosOnBikePlane = posOnBikePlane;

+ 7 - 10
Assets/Scripts/Tracking/KineticLegTracker.cs

@@ -1,5 +1,4 @@
-using UnityEngine;
-using Valve.VR;
+using Valve.VR;
 
 namespace Tracking
 {
@@ -7,18 +6,16 @@ namespace Tracking
     {
         public bool calibrateOnStart = true;
         public string id;
-        public string Id => id;
-        public SteamVR_TrackedObject TrackedObject => GetComponent<SteamVR_TrackedObject>();
-        public float BatteryLevel { get; set; }
         protected override string KeyPrefix => "kl";
-        
+
         protected override void Start()
         {
             base.Start();
-            if (calibrateOnStart)
-            {
-                Calibrate();
-            }
+            if (calibrateOnStart) Calibrate();
         }
+
+        public string Id => id;
+        public SteamVR_TrackedObject TrackedObject => GetComponent<SteamVR_TrackedObject>();
+        public float BatteryLevel { get; set; }
     }
 }

+ 12 - 18
Assets/Scripts/Tracking/MatchPlayerPositionAndCalibrate.cs

@@ -1,8 +1,6 @@
-using System;
-using System.Collections;
+using System.Collections;
 using Display;
 using UnityEngine;
-using UnityEngine.Serialization;
 using Valve.VR;
 
 namespace Tracking
@@ -32,16 +30,16 @@ namespace Tracking
         public LookStraightDisplay lookStraightHud;
         public CameraTracker hmdTracker;
         public Transform bikeTransform;
-
-        private Transform fwtTransform;
-        private Transform legTransform;
-        private Transform playerTransform;
+        private bool autoSet;
 
         private SteamVR_TrackedObject fwTrackedObject;
+
+        private Transform fwtTransform;
         private SteamVR_TrackedObject legTrackedObject;
+        private Transform legTransform;
 
         private int matching;
-        private bool autoSet;
+        private Transform playerTransform;
 
         private void Start()
         {
@@ -53,6 +51,12 @@ namespace Tracking
             legTrackedObject = frontWheelTracker.GetComponent<SteamVR_TrackedObject>();
         }
 
+        private void Update()
+        {
+            AutoCalibration();
+            DoMatching();
+        }
+
         public void Match()
         {
             matching = 1;
@@ -101,12 +105,6 @@ namespace Tracking
             legTracker.gameObject.SetActive(false);
         }
 
-        private void Update()
-        {
-            AutoCalibration();
-            DoMatching();
-        }
-
         private void AutoCalibration()
         {
             if (calibrationMode == CalibrationMode.None || autoSet || !fwTrackedObject.isValid ||
@@ -142,13 +140,9 @@ namespace Tracking
             {
                 MatchLeg();
                 if (calibrationMode == CalibrationMode.MatchOnly || calibrationMode == CalibrationMode.None)
-                {
                     matching = 0;
-                }
                 else
-                {
                     matching++;
-                }
             }
             else if (matching == 3)
             {

+ 1 - 2
Assets/Scripts/Tracking/TrackerIndexManager.cs

@@ -3,7 +3,6 @@ using System.Linq;
 using System.Text;
 using UnityEngine;
 using Valve.VR;
-using Debug = UnityEngine.Debug;
 
 namespace Tracking
 {
@@ -34,7 +33,7 @@ namespace Tracking
             var error = ETrackedPropertyError.TrackedProp_Success;
             var batteryLevel = OpenVR.System.GetFloatTrackedDeviceProperty((uint) index,
                 ETrackedDeviceProperty.Prop_DeviceBatteryPercentage_Float, ref error);
-            
+
             if (error != ETrackedPropertyError.TrackedProp_Success)
             {
                 Debug.LogWarning($"Could not get serial number for tracker at index {index}");

+ 21 - 32
Assets/Scripts/Wheels/ColliderAddSlopeAdjustment.cs

@@ -1,37 +1,29 @@
-using System.Collections;
-using System.Collections.Generic;
-using UnityEngine;
-
+using UnityEngine;
 
 public class ColliderAddSlopeAdjustment : MonoBehaviour
 {
+    private const float RAYCAST_DIST = 0.2f;
+
     [Header("Steering Direction Config")]
-    [Tooltip("A Transform that has an Axis that always shows into steering direction. It is assumed, that this transform is always on the floor!")]
+    [Tooltip(
+        "A Transform that has an Axis that always shows into steering direction. It is assumed, that this transform is always on the floor!")]
     public Transform steerTransform;
+
     public Axis steerTransformForward = Axis.Z;
-    public bool backwardIsForward = false;
+    public bool backwardIsForward;
     public int collisionLayer = 11;
+    private readonly float rayLength = 10f; //TODO: calculate -> front wheel
 
-    private const float RAYCAST_DIST = 0.2f;
-    private float rayLength = 10f; //TODO: calculate -> front wheel
-
-
-    // Start is called before the first frame update
-    void Start()
+    private void FixedUpdate()
     {
-        
-    }
-
-    void FixedUpdate()
-    {
-        bool hit = AdjustSlope(); //Check above ground -> ascending
-        if(!hit) AdjustSlope(underground: true); //Check underground -> descending
+        var hit = AdjustSlope(); //Check above ground -> ascending
+        if (!hit) AdjustSlope(true); //Check underground -> descending
     }
 
     private bool AdjustSlope(bool underground = false)
     {
         var hitDistLower = CastRay(underground: underground);
-        var hitDistUpper = CastRay(dist: RAYCAST_DIST, underground:underground);
+        var hitDistUpper = CastRay(RAYCAST_DIST, underground);
 
         if (hitDistLower != null && hitDistUpper != null)
         {
@@ -54,23 +46,20 @@ public class ColliderAddSlopeAdjustment : MonoBehaviour
         var layerMask = 1 << collisionLayer;
         RaycastHit hit;
         var forward = CalculateForward();
-        var position = steerTransform.position + Vector3.up * (dist - (underground ? 1 : 0)); // TODO: probably needs to be transformed to local axes
+        var position =
+            steerTransform.position +
+            Vector3.up * (dist - (underground ? 1 : 0)); // TODO: probably needs to be transformed to local axes
         // Does the ray intersect any objects excluding the player layer
-        if (Physics.Raycast(position,forward , out hit, rayLength, layerMask))
+        if (Physics.Raycast(position, forward, out hit, rayLength, layerMask))
         {
             Debug.DrawRay(position, forward * hit.distance, Color.yellow);
-            if (hit.collider.isTrigger)
-            {
-                return null;
-            }
+            if (hit.collider.isTrigger) return null;
             return hit.distance;
             //Debug.Log("Did Hit: ");
         }
-        else
-        {
-            Debug.DrawRay(position, forward * rayLength, Color.white);
-            //Debug.Log("Did not Hit");
-        }
+
+        Debug.DrawRay(position, forward * rayLength, Color.white);
+        //Debug.Log("Did not Hit");
 
         return null;
     }
@@ -93,4 +82,4 @@ public class ColliderAddSlopeAdjustment : MonoBehaviour
 
         return backwardIsForward ? -forward : forward;
     }
-}
+}

+ 11 - 19
Assets/Scripts/Wheels/CustomWheelCollider.cs

@@ -1,5 +1,4 @@
-using System;
-using System.Linq;
+using System.Linq;
 using UnityEngine;
 
 public struct HitInfo
@@ -9,8 +8,8 @@ public struct HitInfo
 
     public HitInfo(float timestamp, RaycastHit hit)
     {
-        this.Timestamp = timestamp;
-        this.Hit = hit;
+        Timestamp = timestamp;
+        Hit = hit;
     }
 }
 
@@ -20,13 +19,14 @@ public class CustomWheelCollider : MonoBehaviour
     public int numberOfRays;
 
     public int collisionLayer = 11;
+
+    private Vector3[] rayDirections;
     //[Range(10f,90f)]
     //public float maxDetectableAngle = 45f;
 
     private Transform t;
-    private Vector3[] rayDirections;
 
-    public HitInfo? CurrentHit { private set; get; } = null;
+    public HitInfo? CurrentHit { private set; get; }
     public int CurrentHitNumber { private set; get; }
 
     private void Start()
@@ -38,10 +38,7 @@ public class CustomWheelCollider : MonoBehaviour
     private void FixedUpdate()
     {
         var results = new HitInfo?[numberOfRays];
-        for (var i = 0; i < numberOfRays; i++)
-        {
-            results[i] = CastRay(i);
-        }
+        for (var i = 0; i < numberOfRays; i++) results[i] = CastRay(i);
 
         CurrentHit = results.FirstOrDefault(r => r != null);
         CurrentHitNumber = results.Count(r => r != null);
@@ -55,10 +52,7 @@ public class CustomWheelCollider : MonoBehaviour
         var anglePerRot = 360f / numberOfRays;
         var directions = new Vector3[numberOfRays];
 
-        for (var i = 0; i < numberOfRays; i++)
-        {
-            directions[i] = CalculateRayDirection(i * anglePerRot * Mathf.Deg2Rad);
-        }
+        for (var i = 0; i < numberOfRays; i++) directions[i] = CalculateRayDirection(i * anglePerRot * Mathf.Deg2Rad);
 
         return directions;
     }
@@ -94,10 +88,8 @@ public class CustomWheelCollider : MonoBehaviour
             //Debug.Log("Did Hit: ");
             return new HitInfo(Time.fixedTime, hit);
         }
-        else
-        {
-            Debug.DrawRay(t.position, direction * radius, Color.white);
-            return null;
-        }
+
+        Debug.DrawRay(t.position, direction * radius, Color.white);
+        return null;
     }
 }

+ 18 - 22
Assets/Scripts/Wheels/CustomWheelColliderSlopeAdjustment.cs

@@ -1,7 +1,4 @@
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using UnityEngine;
+using UnityEngine;
 
 public class CustomWheelColliderSlopeAdjustment : MonoBehaviour
 {
@@ -11,16 +8,11 @@ public class CustomWheelColliderSlopeAdjustment : MonoBehaviour
     public float timeDifferenceTolerance = 0.0001f;
 
     public Vector3 dif; //TODO: remove
+    private float angle;
 
-    private Transform t;
-
-    private bool isHitting = false;
-    private float angle = 0f;
+    private bool isHitting;
 
-    private void OnGUI()
-    {
-        GUI.TextField(new Rect(Screen.width - 200, 10, 190, 80), $"Hitting? {isHitting}\nAngle: {angle:n2}\nrw: {rearWheel.CurrentHit?.Hit.point}\nfw: {frontWheel.CurrentHit?.Hit.point}");
-    }
+    private Transform t;
 
     private void Start()
     {
@@ -37,23 +29,27 @@ public class CustomWheelColliderSlopeAdjustment : MonoBehaviour
             Rotate();
             return;
         }
+
         if (rearWheel.CurrentHitNumber > 1)
         {
             angle = .5f;
             Rotate();
             return;
         }
-        
+
         //TODO: this is probably called almost never
         if (frontWheel.CurrentHit == null || rearWheel.CurrentHit == null) return;
-            
+
         var fwHit = frontWheel.CurrentHit.Value;
         var rwHit = rearWheel.CurrentHit.Value;
 
-        if (fwHit.Timestamp - rwHit.Timestamp <= timeDifferenceTolerance)
-        {
-            UpdateTransformRotation(fwHit, rwHit);
-        }
+        if (fwHit.Timestamp - rwHit.Timestamp <= timeDifferenceTolerance) UpdateTransformRotation(fwHit, rwHit);
+    }
+
+    private void OnGUI()
+    {
+        GUI.TextField(new Rect(Screen.width - 200, 10, 190, 80),
+            $"Hitting? {isHitting}\nAngle: {angle:n2}\nrw: {rearWheel.CurrentHit?.Hit.point}\nfw: {frontWheel.CurrentHit?.Hit.point}");
     }
 
     private void UpdateTransformRotation(HitInfo fwHit, HitInfo rwHit)
@@ -61,9 +57,9 @@ public class CustomWheelColliderSlopeAdjustment : MonoBehaviour
         isHitting = true;
         dif = t.TransformPoint(fwHit.Hit.point) - t.TransformPoint(rwHit.Hit.point);
         angle = -Mathf.Atan(dif.y / dif.z) * Mathf.Rad2Deg; //TODO: is it that easy?
-        
+
         Debug.DrawLine(rwHit.Hit.point, rwHit.Hit.point + t.right, Color.red);
-        
+
         Rotate();
         //t.RotateAround(rotatePoint.position, t.right, angle) ;
         //t.localRotation = Quaternion.Euler(t.localRotation.eulerAngles + Vector3.right * angle);
@@ -71,7 +67,7 @@ public class CustomWheelColliderSlopeAdjustment : MonoBehaviour
 
     private void Rotate()
     {
-        t.RotateAround(rotatePoint.position, t.right, angle) ;
+        t.RotateAround(rotatePoint.position, t.right, angle);
         angle = 0f;
     }
-}
+}

+ 18 - 28
Assets/Scripts/Wheels/LerpSlopeCollider.cs

@@ -1,5 +1,4 @@
 using System;
-using Controller.Bicycle;
 using Roads;
 using UnityEngine;
 
@@ -7,39 +6,29 @@ namespace Wheels
 {
     public class LerpSlopeCollider : MonoBehaviour
     {
+        public delegate void OnSlopeChangedEvent(float timestamp, float slope);
+
+        private const float TOLERANCE = 0.005f;
+        private const float MAX_RAYCAST_LENGTH = 2f;
         public int collisionLayer = 1;
 
         public Transform rearWheelContact;
         public Transform frontWheelContact;
         public Rigidbody bike;
-
-        private const float TOLERANCE = 0.005f;
-        private const float MAX_RAYCAST_LENGTH = 2f;
-
-        private float distanceUntilCompletelyRotated;
         private Transform bikeTransform;
-        private float currentFrontWheelSlope;
         private float currentFrontWheelMinY;
+        private float currentFrontWheelSlope;
+
+        private float distanceUntilCompletelyRotated;
         private bool rotate;
         public int SlopeDirection { private set; get; } = 1;
 
-        public delegate void OnSlopeChangedEvent(float timestamp, float slope);
-        public event OnSlopeChangedEvent OnSlopeChanged;
-
         private void Start()
         {
             bikeTransform = bike.transform;
             distanceUntilCompletelyRotated = Vector3.Distance(frontWheelContact.position, rearWheelContact.position);
         }
 
-        private void OnGUI()
-        {
-            GUI.TextField(new Rect(10, 200, 200, 20), $"Direction = {SlopeDirection}");
-            GUI.TextField(new Rect(10, 220, 200, 20), $"MinY = {currentFrontWheelMinY}");
-            GUI.TextField(new Rect(10, 250, 200, 20), $"rotation.x = {bikeTransform.localRotation.eulerAngles.x:n2}");
-            GUI.TextField(new Rect(10, 270, 200, 20), $"Slope = {currentFrontWheelSlope}");
-        }
-
         private void FixedUpdate()
         {
             var fwHit = CastRay(frontWheelContact.position, Vector3.down);
@@ -64,6 +53,16 @@ namespace Wheels
             RotateIfNeeded();
         }
 
+        private void OnGUI()
+        {
+            GUI.TextField(new Rect(10, 200, 200, 20), $"Direction = {SlopeDirection}");
+            GUI.TextField(new Rect(10, 220, 200, 20), $"MinY = {currentFrontWheelMinY}");
+            GUI.TextField(new Rect(10, 250, 200, 20), $"rotation.x = {bikeTransform.localRotation.eulerAngles.x:n2}");
+            GUI.TextField(new Rect(10, 270, 200, 20), $"Slope = {currentFrontWheelSlope}");
+        }
+
+        public event OnSlopeChangedEvent OnSlopeChanged;
+
         private IRoad CastRay(Vector3 pos, Vector3 direction)
         {
             var layerMask = 1 << collisionLayer;
@@ -85,13 +84,8 @@ namespace Wheels
             {
                 var bikeAngle = bikeTransform.localRotation.eulerAngles.x;
                 if (bikeAngle < -180)
-                {
                     bikeAngle = Mathf.Abs(360 + bikeAngle);
-                }
-                else if (bikeAngle > 180)
-                {
-                    bikeAngle = Mathf.Abs(-360 + bikeAngle);
-                }
+                else if (bikeAngle > 180) bikeAngle = Mathf.Abs(-360 + bikeAngle);
 
                 var slopeDif = SlopeDirection * (currentFrontWheelSlope - bikeAngle);
                 if (Mathf.Abs(currentFrontWheelSlope - bikeAngle) <
@@ -105,15 +99,11 @@ namespace Wheels
                 var rot = slopeDif * Time.fixedDeltaTime * forwardBikeSpeed / distanceUntilCompletelyRotated;
 
                 if (slopeDif > 0) //lift front wheel
-                {
                     bikeTransform.RotateAround(frontWheelContact.position, -frontWheelContact.right,
                         rot);
-                }
                 else //dip front wheel
-                {
                     bikeTransform.RotateAround(frontWheelContact.position, frontWheelContact.right,
                         -rot);
-                }
             }
         }
     }

+ 13 - 16
Assets/Scripts/Wheels/SlopeCollider.cs

@@ -1,5 +1,4 @@
-using System;
-using UnityEngine;
+using UnityEngine;
 
 namespace Wheels
 {
@@ -34,14 +33,13 @@ namespace Wheels
 
     public class SlopeCollider : MonoBehaviour
     {
+        private const float THRESHOLD = 0.003f;
         public int collisionLayer = 1;
         public SphereCollider rearWheelCollider;
         public SphereCollider frontWheelCollider;
         public Transform bike;
-
-        private const float THRESHOLD = 0.003f;
-        private float distRwFw;
         private RotateDirection currentRotateDirection = RotateDirection.Unknown;
+        private float distRwFw;
         private Transform frontWheelContactPoint;
         private Transform rearWheelContactPoint;
 
@@ -59,10 +57,7 @@ namespace Wheels
             var fwHit = DrawRay(fwContact);
             var rwHit = DrawRay(rwContact);
 
-            if (!fwHit.HasValue || !rwHit.HasValue)
-            {
-                return;
-            }
+            if (!fwHit.HasValue || !rwHit.HasValue) return;
 
             //Debug.Log("----Slope Collider----");
             //Debug.Log($"\tfwHit: {fwHit}");
@@ -77,7 +72,7 @@ namespace Wheels
             if (fwDist >= THRESHOLD && rwDist >= THRESHOLD)
             {
                 var deltaY = fwDist <= rwDist ? fwDist : rwDist;
-                bike.Translate(0,-deltaY,0);
+                bike.Translate(0, -deltaY, 0);
                 //Debug.Log($"Translated {-deltaY} on y");
             }
             else if (fw.distance >= THRESHOLD)
@@ -199,11 +194,12 @@ namespace Wheels
             // Does the ray intersect any objects excluding the player layer
             if (Physics.Raycast(start, -bike.up, out hit, 20f, layerMask))
             {
-                Debug.DrawRay(start, -bike.up * hit.distance, Color.green);
+                var up = bike.up;
+                Debug.DrawRay(start, -up * hit.distance, Color.green);
                 //Debug.DrawRay(hit.point, hit.normal, Color.blue);
                 var isUneven = hit.collider.gameObject.CompareTag(StreetPartMetaTag.TAG_UNEVEN);
-                var first = -(-bike.up * hit.distance);
-                var second = (hit.normal);
+                var first = -(-up * hit.distance);
+                var second = hit.normal;
                 var angle = Mathf.Acos(Vector3.Dot(first, second) / first.magnitude * second.magnitude) * Mathf.Rad2Deg;
                 //Debug.Log("Dot Product: " + Vector3.Dot(first, second));
                 //Debug.Log("Angle: " + angle);
@@ -212,11 +208,12 @@ namespace Wheels
 
             if (Physics.Raycast(start, bike.up, out hit, 20f, layerMask))
             {
-                Debug.DrawRay(start, -bike.up * hit.distance, Color.green);
+                var up = bike.up;
+                Debug.DrawRay(start, -up * hit.distance, Color.green);
                 //Debug.DrawRay(hit.point, hit.normal, Color.blue);
                 var isUneven = hit.collider.gameObject.CompareTag(StreetPartMetaTag.TAG_UNEVEN);
-                var first = -(-bike.up * hit.distance);
-                var second = (hit.normal);
+                var first = -(-up * hit.distance);
+                var second = hit.normal;
                 var angle = Mathf.Acos(Vector3.Dot(first, second) / first.magnitude * second.magnitude) * Mathf.Rad2Deg;
                 //Debug.Log("Dot Product: " + Vector3.Dot(first, second));
                 //Debug.Log("Angle: " + angle);

+ 2 - 4
Assets/Scripts/Wheels/SwitchColliderOnStanding.cs

@@ -12,20 +12,18 @@ namespace Wheels
         [Range(0f, 5f)] public float speedThreshold = 0.5f;
         public bool rbToKinematicWhenStanding = true;
 
-        private float lastFrameSpeed = -1f;
+        private readonly float lastFrameSpeed = -1f;
 
         // Update is called once per frame
-        void Update()
+        private void Update()
         {
             var thisFrameSpeed = bikeController.CurrentSpeed;
             if (lastFrameSpeed >= 0f
                 && (lastFrameSpeed <= speedThreshold && thisFrameSpeed <= speedThreshold
                     ||
                     lastFrameSpeed > speedThreshold && thisFrameSpeed > speedThreshold))
-            {
                 //no change
                 return;
-            }
 
             if (thisFrameSpeed <= speedThreshold)
             {