diff --git a/.changeset/tactical-view.md b/.changeset/tactical-view.md new file mode 100644 index 000000000..260337812 --- /dev/null +++ b/.changeset/tactical-view.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +The tactical view is a camera of its own: scroll out past a bump to a three-quarters top-down view over the grid, drag to move it, scroll back in through the bump to return to your ship. diff --git a/Assets/Resources/Aetheria.inputactions b/Assets/Resources/Aetheria.inputactions index fc4f5f71c..8201c8471 100644 --- a/Assets/Resources/Aetheria.inputactions +++ b/Assets/Resources/Aetheria.inputactions @@ -46,6 +46,26 @@ "initialStateCheck": true, "priority": 0 }, + { + "name": "Pan", + "type": "Button", + "id": "591eacf3-8726-4393-8a6d-f09410b745a4", + "expectedControlType": "Button", + "processors": "", + "interactions": "", + "initialStateCheck": false, + "priority": 0 + }, + { + "name": "Point", + "type": "Value", + "id": "f0ec75bc-84a5-4ea4-8e0f-e72f725e6b9d", + "expectedControlType": "Vector2", + "processors": "", + "interactions": "", + "initialStateCheck": true, + "priority": 0 + }, { "name": "Target Reticle", "type": "Button", @@ -374,6 +394,39 @@ "isComposite": false, "isPartOfComposite": false }, + { + "name": "", + "id": "e4e6d330-0963-4690-8e53-a1b52c5c6bce", + "path": "/leftButton", + "interactions": "", + "processors": "", + "groups": "Keyboard&Mouse", + "action": "Pan", + "isComposite": false, + "isPartOfComposite": false + }, + { + "name": "", + "id": "fe708e7d-0f9e-4b03-b983-d60e769e4292", + "path": "/middleButton", + "interactions": "", + "processors": "", + "groups": "Keyboard&Mouse", + "action": "Pan", + "isComposite": false, + "isPartOfComposite": false + }, + { + "name": "", + "id": "8ad98e17-f4bd-4d92-8300-f562b96f3750", + "path": "/position", + "interactions": "", + "processors": "", + "groups": "Keyboard&Mouse", + "action": "Point", + "isComposite": false, + "isPartOfComposite": false + }, { "name": "", "id": "5211a58c-428b-4ee6-820d-2f67789806d6", diff --git a/Assets/Scripts/AetheriaInput.cs b/Assets/Scripts/AetheriaInput.cs index 615c4b8cf..d9248909e 100644 --- a/Assets/Scripts/AetheriaInput.cs +++ b/Assets/Scripts/AetheriaInput.cs @@ -132,6 +132,26 @@ public partial class @AetheriaInput: IInputActionCollection2, IDisposable ""initialStateCheck"": true, ""priority"": 0 }, + { + ""name"": ""Pan"", + ""type"": ""Button"", + ""id"": ""591eacf3-8726-4393-8a6d-f09410b745a4"", + ""expectedControlType"": ""Button"", + ""processors"": """", + ""interactions"": """", + ""initialStateCheck"": false, + ""priority"": 0 + }, + { + ""name"": ""Point"", + ""type"": ""Value"", + ""id"": ""f0ec75bc-84a5-4ea4-8e0f-e72f725e6b9d"", + ""expectedControlType"": ""Vector2"", + ""processors"": """", + ""interactions"": """", + ""initialStateCheck"": true, + ""priority"": 0 + }, { ""name"": ""Target Reticle"", ""type"": ""Button"", @@ -460,6 +480,39 @@ public partial class @AetheriaInput: IInputActionCollection2, IDisposable ""isComposite"": false, ""isPartOfComposite"": false }, + { + ""name"": """", + ""id"": ""e4e6d330-0963-4690-8e53-a1b52c5c6bce"", + ""path"": ""/leftButton"", + ""interactions"": """", + ""processors"": """", + ""groups"": ""Keyboard&Mouse"", + ""action"": ""Pan"", + ""isComposite"": false, + ""isPartOfComposite"": false + }, + { + ""name"": """", + ""id"": ""fe708e7d-0f9e-4b03-b983-d60e769e4292"", + ""path"": ""/middleButton"", + ""interactions"": """", + ""processors"": """", + ""groups"": ""Keyboard&Mouse"", + ""action"": ""Pan"", + ""isComposite"": false, + ""isPartOfComposite"": false + }, + { + ""name"": """", + ""id"": ""8ad98e17-f4bd-4d92-8300-f562b96f3750"", + ""path"": ""/position"", + ""interactions"": """", + ""processors"": """", + ""groups"": ""Keyboard&Mouse"", + ""action"": ""Point"", + ""isComposite"": false, + ""isPartOfComposite"": false + }, { ""name"": """", ""id"": ""5211a58c-428b-4ee6-820d-2f67789806d6"", @@ -1325,6 +1378,8 @@ public partial class @AetheriaInput: IInputActionCollection2, IDisposable m_Player_Look = m_Player.FindAction("Look", throwIfNotFound: true); m_Player_MinimapZoom = m_Player.FindAction("Minimap Zoom", throwIfNotFound: true); m_Player_Zoom = m_Player.FindAction("Zoom", throwIfNotFound: true); + m_Player_Pan = m_Player.FindAction("Pan", throwIfNotFound: true); + m_Player_Point = m_Player.FindAction("Point", throwIfNotFound: true); m_Player_TargetReticle = m_Player.FindAction("Target Reticle", throwIfNotFound: true); m_Player_TargetPrevious = m_Player.FindAction("Target Previous", throwIfNotFound: true); m_Player_TargetNext = m_Player.FindAction("Target Next", throwIfNotFound: true); @@ -1445,6 +1500,8 @@ public partial class @AetheriaInput: IInputActionCollection2, IDisposable private readonly InputAction m_Player_Look; private readonly InputAction m_Player_MinimapZoom; private readonly InputAction m_Player_Zoom; + private readonly InputAction m_Player_Pan; + private readonly InputAction m_Player_Point; private readonly InputAction m_Player_TargetReticle; private readonly InputAction m_Player_TargetPrevious; private readonly InputAction m_Player_TargetNext; @@ -1488,6 +1545,14 @@ public partial class @AetheriaInput: IInputActionCollection2, IDisposable /// public InputAction @Zoom => m_Wrapper.m_Player_Zoom; /// + /// Provides access to the underlying input action "Player/Pan". + /// + public InputAction @Pan => m_Wrapper.m_Player_Pan; + /// + /// Provides access to the underlying input action "Player/Point". + /// + public InputAction @Point => m_Wrapper.m_Player_Point; + /// /// Provides access to the underlying input action "Player/TargetReticle". /// public InputAction @TargetReticle => m_Wrapper.m_Player_TargetReticle; @@ -1585,6 +1650,12 @@ public partial class @AetheriaInput: IInputActionCollection2, IDisposable @Zoom.started += instance.OnZoom; @Zoom.performed += instance.OnZoom; @Zoom.canceled += instance.OnZoom; + @Pan.started += instance.OnPan; + @Pan.performed += instance.OnPan; + @Pan.canceled += instance.OnPan; + @Point.started += instance.OnPoint; + @Point.performed += instance.OnPoint; + @Point.canceled += instance.OnPoint; @TargetReticle.started += instance.OnTargetReticle; @TargetReticle.performed += instance.OnTargetReticle; @TargetReticle.canceled += instance.OnTargetReticle; @@ -1653,6 +1724,12 @@ public partial class @AetheriaInput: IInputActionCollection2, IDisposable @Zoom.started -= instance.OnZoom; @Zoom.performed -= instance.OnZoom; @Zoom.canceled -= instance.OnZoom; + @Pan.started -= instance.OnPan; + @Pan.performed -= instance.OnPan; + @Pan.canceled -= instance.OnPan; + @Point.started -= instance.OnPoint; + @Point.performed -= instance.OnPoint; + @Point.canceled -= instance.OnPoint; @TargetReticle.started -= instance.OnTargetReticle; @TargetReticle.performed -= instance.OnTargetReticle; @TargetReticle.canceled -= instance.OnTargetReticle; @@ -2141,6 +2218,20 @@ public partial class @AetheriaInput: IInputActionCollection2, IDisposable /// void OnZoom(InputAction.CallbackContext context); /// + /// Method invoked when associated input action "Pan" is either , or . + /// + /// + /// + /// + void OnPan(InputAction.CallbackContext context); + /// + /// Method invoked when associated input action "Point" is either , or . + /// + /// + /// + /// + void OnPoint(InputAction.CallbackContext context); + /// /// Method invoked when associated input action "Target Reticle" is either , or . /// /// diff --git a/Assets/Scripts/Gameplay/ActionGameManager.cs b/Assets/Scripts/Gameplay/ActionGameManager.cs index b610e17ba..1b3b120a7 100644 --- a/Assets/Scripts/Gameplay/ActionGameManager.cs +++ b/Assets/Scripts/Gameplay/ActionGameManager.cs @@ -352,10 +352,21 @@ public class ActionGameManager : MonoBehaviour ZoneRenderer.MinimapDistance = Settings.MinimapZoomLevels[_zoomLevelIndex]; }; - // The tactical view is the camera pulled far out (ruling tactical-view-is-zoom-out): the wheel is the only input, - // and TacticalView the one owner of how far. + // The tactical view is a distinct camera over the grid (ruling tactical-view-distinct-mode): the wheel is one axis + // from the chase view through a detent into it, and TacticalView the one owner of where on that axis the camera is. _tactical = new TacticalView(Settings.TacticalZoomStep, Settings.TacticalBlendStart, Settings.TacticalBlendEnd, - Settings.TacticalTimeScale, Settings.TacticalFitPerRadius); + Settings.TacticalTimeScale, Settings.TacticalFitPerRadius, Settings.DetentResistance, Settings.DetentRelaxTime, + Settings.ViewEaseTime); + // The view rig: the chase camera (child 0) and the tactical camera (child 1) mixed by the blend, built here so the + // scene stays as authored. The mix is a function of the eased distance, not a brain blend on a priority switch. + var rig = new GameObject("View Rig"); + _viewRig = rig.AddComponent(); + _viewRig.Priority = FollowCamera.Priority; + FollowCamera.transform.SetParent(rig.transform, false); + FollowCamera.transform.SetAsFirstSibling(); + var tacticalCamera = new GameObject("Tactical Camera"); + tacticalCamera.transform.SetParent(rig.transform, false); + _tacticalCamera = tacticalCamera.AddComponent(); _tacticalFade = ScriptableObject.CreateInstance(); _tacticalFade.enabled.Override(true); _tacticalFade.Background.Override(Settings.TacticalBackground); @@ -372,8 +383,9 @@ public class ActionGameManager : MonoBehaviour { var scroll = context.ReadValue(); if (scroll == 0 || !Flying) return; - _tactical.Step(-Mathf.Sign(scroll), BaseFollowDistance(CurrentEntity)); - ApplyFraming(CurrentEntity); + var was = _tactical.Tactical; + _tactical.Scroll(-Mathf.Sign(scroll)); + if (_tactical.Tactical != was) EnablePlayerInput(); }; Input.Global.ZoneMap.performed += context => @@ -761,11 +773,14 @@ public class ActionGameManager : MonoBehaviour return success ?? false; } + // The one writer of the cursor lock and the action bar while playing: the tactical view frees the cursor and gives the + // mouse buttons to Pan, so the bar is off there. It is re-applied whenever Tactical changes. public void EnablePlayerInput() { - Cursor.lockState = CursorLockMode.Locked; + Cursor.lockState = _tactical.Tactical ? CursorLockMode.None : CursorLockMode.Locked; Input.Player.Enable(); - foreach (var a in _actionBarActions) a.Enable(); + foreach (var a in _actionBarActions) + if (_tactical.Tactical) a.Disable(); else a.Enable(); } public void DisablePlayerInput() @@ -999,7 +1014,7 @@ public class ActionGameManager : MonoBehaviour ZoneRenderer.PerspectiveEntity = DockedEntity; DockingBay = dockingBay; DockCamera.enabled = true; - FollowCamera.enabled = false; + _viewRig.enabled = false; var orbital = (OrbitalEntity) entity; DockCamera.Follow = ZoneRenderer.EntityInstances[orbital].transform; var parentOrbit = Zone.Orbits[orbital.OrbitData].Data.Parent.Key; @@ -1101,7 +1116,6 @@ public class ActionGameManager : MonoBehaviour if(_incomingLockIndicator.indicator != null) _incomingLockIndicator.indicator.GetComponent().ReturnToPool(); _incomingLockIndicator = default; DisablePlayerInput(); - Cursor.lockState = CursorLockMode.None; GameplayUI.gameObject.SetActive(false); foreach(var subscription in _shipSubscriptions) subscription.Dispose(); @@ -1148,7 +1162,7 @@ public class ActionGameManager : MonoBehaviour } CurrentEntity = entity; - _tactical.Reset(entity.Zone.Pack.Radius); + _tactical.Reset(entity.Zone.Pack.Radius, BaseFollowDistance(entity), DrawAhead.Position(entity, Clock.Lead).xz); DeathPost.weight = 0; ZoneRenderer.PerspectiveEntity = CurrentEntity; @@ -1156,12 +1170,11 @@ public class ActionGameManager : MonoBehaviour DockedEntity = null; DockingBay = null; DockCamera.enabled = false; - FollowCamera.enabled = true; + _viewRig.enabled = true; if (length(CurrentEntity.Direction) > .1f) _viewDirection = float3(CurrentEntity.Direction.x,0,CurrentEntity.Direction.y); - - Cursor.lockState = CursorLockMode.Locked; + EnablePlayerInput(); GameplayUI.gameObject.SetActive(true); ShipPanel.Display(CurrentEntity, true); @@ -1286,6 +1299,10 @@ public class ActionGameManager : MonoBehaviour } private CinemachineFramingTransposer _framingTransposer; + private CinemachineMixingCamera _viewRig; + private CinemachineVirtualCamera _tacticalCamera; + // The grid point the Pan drag holds under the cursor; one gesture's state, nothing else. + private float2? _grab; private TacticalView _tactical; private TacticalFade _tacticalFade; private PostProcessVolume _tacticalVolume; @@ -1306,28 +1323,56 @@ public class ActionGameManager : MonoBehaviour private float BaseFollowDistance(Entity entity) => Settings.FollowCameraDistancePerReach * Contacts.Radius(entity); - // The one writer of the follow camera's distance: the hull's framed distance times the tactical zoom. It asks - // ZoneRenderer, the one writer of the far clip, to see the whole zone from there. + // The one writer of the follow camera's distance: the eased view distance. It asks ZoneRenderer, the one writer of the + // far clip, to see the whole zone from there. private void ApplyFraming(Entity entity) { if (_framingTransposer == null) _framingTransposer = FollowCamera.GetCinemachineComponent(); - var distance = _tactical.Distance(BaseFollowDistance(entity)); + var distance = _tactical.Distance; _framingTransposer.m_CameraDistance = distance; ZoneRenderer.FarClipNeeded = distance + 2 * entity.Zone.Pack.Radius; } - // Everything the tactical view shows is read off the camera distance: the fade, the schematic, the map icons' size - // and the minimap cameras. Time is the Update line that feeds the clock. - private float TacticalBlend() => Flying && _framingTransposer != null - ? _tactical.Blend(_framingTransposer.m_CameraDistance) - : 0f; + // The one writer of the tactical camera: three-quarters top-down over the view target on the grid surface, the chase + // view's yaw held, at the eased distance. Its lens is the chase camera's, so the far clip is the one writer's. + private void PoseTactical() + { + var target = _tactical.Target; + var target3 = new Vector3(target.x, DrawAhead.Height(CurrentEntity.Zone, target, Clock.Lead), target.y); + var rotation = Quaternion.Euler(Settings.TacticalPitch, _entityYawPitch.x * Mathf.Rad2Deg, 0); + _tacticalCamera.transform.SetPositionAndRotation(target3 - rotation * Vector3.forward * _tactical.Distance, rotation); + _tacticalCamera.m_Lens = FollowCamera.m_Lens; + } + + // Drag: the grid point under the cursor when the button went down stays under it. + private void PanTarget() + { + if (!Input.Player.Pan.IsPressed()) + { + _grab = null; + return; + } + var height = DrawAhead.Height(CurrentEntity.Zone, _tactical.Target, Clock.Lead); + var ray = ZoneRenderer.MainCamera.ScreenPointToRay(Input.Player.Point.ReadValue()); + if (!new Plane(Vector3.up, new Vector3(0, height, 0)).Raycast(ray, out var hit)) return; + var point = ray.GetPoint(hit); + var ground = float2(point.x, point.z); + if (_grab is { } grab) _tactical.Pan(grab - ground); + else _grab = ground; + } + + // Everything the tactical view shows is read off the eased camera distance: the fade, the rig's mix, the schematic, the + // map icons' size and the minimap cameras. Time is the Update line that feeds the clock. + private float TacticalBlend() => Flying ? _tactical.Blend(_tactical.Distance) : 0f; private void ShowTactical(float blend) { + _viewRig.SetWeight(0, 1 - blend); + _viewRig.SetWeight(1, blend); _tacticalVolume.weight = blend; _schematicCamera.enabled = blend > 0; - ZoneRenderer.Map.SetTacticalScale(blend > 0 ? _framingTransposer.m_CameraDistance * Settings.TacticalIconSize : 0); + ZoneRenderer.Map.SetTacticalScale(blend > 0 ? _tactical.Distance * Settings.TacticalIconSize : 0); foreach (var camera in ZoneRenderer.MinimapCameras) camera.enabled = blend == 0; } @@ -1476,6 +1521,15 @@ public class ActionGameManager : MonoBehaviour void Update() { + if (Flying) + { + _tactical.Tick(Time.unscaledDeltaTime); + _tactical.Track(DrawAhead.Position(CurrentEntity, Clock.Lead).xz); + if (_tactical.Tactical) PanTarget(); + else _grab = null; + ApplyFraming(CurrentEntity); + PoseTactical(); + } var blend = TacticalBlend(); ShowTactical(blend); if (!RunLive) return; @@ -1499,10 +1553,14 @@ public class ActionGameManager : MonoBehaviour indicator.Value.Place.Target = DrawAhead.Position(indicator.Key, Clock.Lead).ToUnity(); PlaceFill(indicator.Value, indicator.Key); } - var look = Input.Player.Look.ReadValue(); - var sensitivity = PlayerSettings.InputSettings.Sensitivity; - _entityYawPitch = float2(_entityYawPitch.x + look.x * sensitivity.x, clamp(_entityYawPitch.y + look.y * sensitivity.y, -.45f * PI, .45f * PI)); - _viewDirection = mul(float3(0, 0, 1), CultMath.float3x3.Euler(float3(_entityYawPitch.yx, 0), RotationOrder.YXZ)); + // The tactical view does not steer: the aim and the chase yaw hold while the mouse pans the view. + if (!_tactical.Tactical) + { + var look = Input.Player.Look.ReadValue(); + var sensitivity = PlayerSettings.InputSettings.Sensitivity; + _entityYawPitch = float2(_entityYawPitch.x + look.x * sensitivity.x, clamp(_entityYawPitch.y + look.y * sensitivity.y, -.45f * PI, .45f * PI)); + _viewDirection = mul(float3(0, 0, 1), CultMath.float3x3.Euler(float3(_entityYawPitch.yx, 0), RotationOrder.YXZ)); + } CurrentEntity.Command.Aim = _viewDirection; HeatstrokePost.weight = saturate(unlerp(0, Settings.GameplaySettings.SevereHeatstrokeRiskThreshold, CurrentEntity.Heatstroke)); var severeHeatstrokeLerp = saturate(unlerp(Settings.GameplaySettings.SevereHeatstrokeRiskThreshold, 1, CurrentEntity.Heatstroke)); diff --git a/Assets/Scripts/Gameplay/GameSettings.cs b/Assets/Scripts/Gameplay/GameSettings.cs index 81a2f257f..e5e4c2b92 100644 --- a/Assets/Scripts/Gameplay/GameSettings.cs +++ b/Assets/Scripts/Gameplay/GameSettings.cs @@ -24,12 +24,22 @@ public class GameSettings : ScriptableObject public int AsteroidMeshCount = 5; public float MinimapAsteroidSize = 3; public float MinimapIconSize = 1f / 32; - // Tactical view (rulings tactical-view-is-zoom-out, tactical-view-in-runs-slow-time): one wheel notch multiplies the - // follow camera distance by this. + // Tactical view (rulings tactical-view-distinct-mode, tactical-view-in-runs-slow-time): one wheel notch multiplies the + // camera distance by this, in either view. Every feel constant here (step, band, detent, ease, pitch) is a placeholder + // the operator tunes by eye. public float TacticalZoomStep = 1.25f; - // The camera distance (m) where the scene starts to fade to the schematic, and where it is fully faded. + // The camera distance (m) where the scene starts to fade to the schematic: the chase view's farthest distance and the + // detent band's near edge; and where it is fully faded: the tactical view's nearest distance and the band's far edge. public float TacticalBlendStart = 250; public float TacticalBlendEnd = 1000; + // Inside the detent band a notch moves the view this fraction as far as outside it (lower holds harder). + public float DetentResistance = .6f; + // Seconds, e-folding, for the band to push the view back to the edge it came from. + public float DetentRelaxTime = .4f; + // Seconds the camera takes to settle on where the wheel put it (critically damped). + public float ViewEaseTime = .15f; + // The tactical camera's pitch down from the horizon, degrees. + public float TacticalPitch = 55; // Sim seconds per real second at full fade (about 100x slower). public float TacticalTimeScale = .01f; // The farthest zoom, as a multiple of the zone radius. diff --git a/Assets/Scripts/ServerShared/TacticalView.cs b/Assets/Scripts/ServerShared/TacticalView.cs index 2be82591c..55b78687e 100644 --- a/Assets/Scripts/ServerShared/TacticalView.cs +++ b/Assets/Scripts/ServerShared/TacticalView.cs @@ -2,47 +2,128 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ +using CultMath; using static CultMath.math; -// The one owner of the flight camera's zoom (rulings tactical-view-is-zoom-out, tactical-view-in-runs-slow-time). -// Nothing stores an "in tactical" state: the tactical view is how far out the camera is. Zoom is the only state; -// distance, blend and the time rate are derived from it, each frame, by whoever draws or steps. +// The one owner of the view (rulings tactical-view-distinct-mode, tactical-view-in-runs-slow-time). One scalar, the camera +// distance in log space, is the view: flight owns [ln base, ln BlendStart], the tactical view owns [ln BlendEnd, ln max], +// and the band between is a detent the player scrolls through with intent. Scroll moves a commanded position; an eased +// position follows it on a critically damped spring and is what the camera is. Nothing stores a mode: Tactical is derived +// from the commanded position against the band's crest, and Blend, TimeRate and the rig weight are derived from the +// eased distance, by whoever draws or steps. +// Every feel constant (notch step, detent resistance and relaxation, ease time, the band's edges) is a placeholder the +// operator tunes by eye (GameSettings). public sealed class TacticalView { private readonly float _zoomStep, _blendStart, _blendEnd, _timeScale, _fitPerRadius; - private float _zoneRadius; + private readonly float _detentResistance, _detentRelaxTime, _easeTime; + private readonly float _lnStart, _lnEnd, _crest; + private float _lnBase, _lnMax, _zoneRadius; - public TacticalView(float zoomStep, float blendStart, float blendEnd, float timeScale, float fitPerRadius) + public TacticalView(float zoomStep, float blendStart, float blendEnd, float timeScale, float fitPerRadius, + float detentResistance, float detentRelaxTime, float easeTime) { _zoomStep = zoomStep; _blendStart = blendStart; _blendEnd = blendEnd; _timeScale = timeScale; _fitPerRadius = fitPerRadius; + _detentResistance = detentResistance; + _detentRelaxTime = detentRelaxTime; + _easeTime = easeTime; + _lnStart = log(blendStart); + _lnEnd = log(blendEnd); + _crest = (_lnStart + _lnEnd) / 2; } - // The multiple of the framed distance the camera sits at, >= 1. - public float Zoom { get; private set; } = 1; + // Commanded and eased positions and the ease velocity, in ln metres; the grid point the tactical camera looks at. + public float Commanded { get; private set; } + private float _eased, _velocity; + public float2 Target { get; private set; } - // The farthest the camera goes: the whole zone in view. - public float MaxDistance => _zoneRadius * _fitPerRadius; + // Derived, never stored: the commanded position is past the detent's crest. + public bool Tactical => Commanded > _crest; - // Each notch multiplies Zoom by ZoomStep (negative notches zoom in). Never inside the hull's framing, never past - // the whole zone. - public void Step(float notches, float baseDistance) - { - var ceiling = MaxDistance > baseDistance && baseDistance > 0 ? MaxDistance / baseDistance : 1f; - Zoom = clamp(Zoom * pow(_zoomStep, notches), 1f, ceiling); - } - - // Back to the hull's own framing, in the zone the camera is now in. - public void Reset(float zoneRadius) + // What the camera is: the eased position. + public float Distance => exp(_eased); + + // Back to the hull's own framing over the ship, in the zone the camera is now in. + public void Reset(float zoneRadius, float baseDistance, float2 shipXZ) { + _lnBase = log(baseDistance); + _lnMax = max(log(max(zoneRadius * _fitPerRadius, _blendEnd)), _lnBase); _zoneRadius = zoneRadius; - Zoom = 1; + Commanded = _eased = _lnBase; + _velocity = 0; + Target = shipXZ; } - public float Distance(float baseDistance) => min(baseDistance * Zoom, max(MaxDistance, baseDistance)); + // Each notch (positive zooms out) moves the commanded position by ln ZoomStep. Inside a view it moves freely. A notch + // that carries it deeper into the band moves it DetentResistance times as far there; one that carries it past the + // crest commits, and the position jumps to the band's far edge. Symmetric from the tactical side. + public void Scroll(float notches) + { + var step = log(_zoomStep); + var count = (int) abs(notches); + var sign = notches < 0 ? -1f : 1f; + for (var i = 0; i < count; i++) Notch(sign * step); + } + + private void Notch(float delta) + { + // Depth is how far into the band from the edge on the commanded side; negative is out in that view's free range. + var side = Tactical ? -1f : 1f; + var edge = Tactical ? _lnEnd : _lnStart; + var depth = side * (Commanded - edge); + var deeper = side * delta; + if (deeper <= 0) + { + Commanded = clamp(Commanded + delta, _lnBase, _lnMax); + return; + } + var free = min(deeper, max(-depth, 0f)); + var newDepth = depth + free + (deeper - free) * _detentResistance; + if (newDepth > _crest - _lnStart) + { + Commanded = Tactical ? _lnStart : _lnEnd; + return; + } + Commanded = clamp(edge + side * newDepth, _lnBase, _lnMax); + } + + // Real seconds: the band's relaxation toward the edge on the commanded side of the crest (it never crosses the crest), + // then the critically damped ease of the eased position toward the commanded one. + public void Tick(float realSeconds) + { + if (realSeconds <= 0) return; + if (Commanded > _lnStart && Commanded < _lnEnd) + { + var edge = Tactical ? _lnEnd : _lnStart; + Commanded = edge + (Commanded - edge) * exp(-realSeconds / _detentRelaxTime); + } + // Exact solution of x'' = -2w(x' + w(x - c)) over dt: no overshoot from rest, stable at any dt. + var w = 2 / _easeTime; + var offset = _eased - Commanded; + var carried = _velocity + w * offset; + var decay = exp(-w * realSeconds); + _eased = Commanded + (offset + carried * realSeconds) * decay; + _velocity = (_velocity - w * carried * realSeconds) * decay; + } + + // The target rides the ship while flying; only a tactical player moves it. + public void Track(float2 shipXZ) + { + if (!Tactical) Target = shipXZ; + } + + // Move the target over the grid by a ground delta, never off the zone. + public void Pan(float2 groundDelta) + { + if (!Tactical) return; + var moved = Target + groundDelta; + var reach = length(moved); + Target = reach > _zoneRadius && reach > 0 ? moved * (_zoneRadius / reach) : moved; + } // 0 at or below the band's near edge, 1 at or above its far edge, smooth in the logarithm of distance between. public float Blend(float distance) diff --git a/tests/Aetheria.Shared.Tests/TacticalViewTests.cs b/tests/Aetheria.Shared.Tests/TacticalViewTests.cs index 8882e5895..f77dfe407 100644 --- a/tests/Aetheria.Shared.Tests/TacticalViewTests.cs +++ b/tests/Aetheria.Shared.Tests/TacticalViewTests.cs @@ -3,38 +3,219 @@ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ using System; +using CultMath; using Xunit; -// TacticalView owns the flight camera's zoom; blend and time rate are derived from the distance, never stored. +// TacticalView owns the view: one eased log-distance axis with a detent between flight and tactical. Blend and time rate +// are derived from the eased distance, never stored. The constants are the placeholders GameSettings holds for the operator. public sealed class TacticalViewTests { private const float Radius = 20000, Fit = 2, Start = 250, End = 1000, Scale = .01f, BaseDistance = 30; + private const float Step = 1.25f, Resistance = .6f, Relax = .4f, Ease = .15f; + private static readonly float LnStep = MathF.Log(Step); - private static TacticalView Make() + private static TacticalView Make(float radius = Radius) { - var view = new TacticalView(1.25f, Start, End, Scale, Fit); - view.Reset(Radius); + var view = new TacticalView(Step, Start, End, Scale, Fit, Resistance, Relax, Ease); + view.Reset(radius, BaseDistance, new float2(100, -50)); return view; } + // Notches at a rate: the real time between them is ticked first, so a held scroll feeds the relaxation too. + private static void Flick(TacticalView view, int notches, float perSecond, float direction = 1) + { + for (var i = 0; i < notches; i++) + { + view.Tick(1 / perSecond); + view.Scroll(direction); + } + } + + // A fast scroll, 20 notches a second, until the view changes; the notches it took. + private static int Cross(TacticalView view, float direction = 1) + { + var was = view.Tactical; + var notches = 0; + while (view.Tactical == was && notches < 30) + { + view.Tick(.05f); + view.Scroll(direction); + notches++; + } + return notches; + } + + private static void Settle(TacticalView view) + { + for (var i = 0; i < 200; i++) view.Tick(.02f); + } + + // The flight's farthest edge: ten notches carry it just into the band, and the band relaxes it to the edge. + private static void ToFlightEdge(TacticalView view) + { + view.Scroll(10); + Settle(view); + Assert.Equal(MathF.Log(Start), view.Commanded, 3); + } + [Fact] - public void ZoomIsClampedToFlightAndTheWholeZone() + public void ScrollMovesFreelyInsideEachView() { var view = Make(); - view.Step(-5, BaseDistance); - Assert.Equal(1f, view.Zoom); - Assert.Equal(BaseDistance, view.Distance(BaseDistance)); - for (var i = 0; i < 200; i++) view.Step(1, BaseDistance); - Assert.Equal(Radius * Fit, view.Distance(BaseDistance)); - Assert.True(view.Zoom <= Radius * Fit / BaseDistance + 1e-3f); - view.Step(1, BaseDistance); - Assert.Equal(Radius * Fit, view.Distance(BaseDistance)); - view.Step(-2, BaseDistance); - Assert.True(view.Distance(BaseDistance) < Radius * Fit); - view.Reset(Radius); - Assert.Equal(BaseDistance, view.Distance(BaseDistance)); - // A hull framed wider than the zone's fit still never sits closer than its own framing. - Assert.Equal(Radius * Fit * 2, view.Distance(Radius * Fit * 2)); + var lnBase = MathF.Log(BaseDistance); + view.Scroll(-5); + Assert.Equal(lnBase, view.Commanded, 5); + view.Scroll(3); + Assert.Equal(lnBase + 3 * LnStep, view.Commanded, 4); + view.Scroll(-1); + Assert.Equal(lnBase + 2 * LnStep, view.Commanded, 4); + Assert.False(view.Tactical); + + ToFlightEdge(view); + Assert.InRange(Cross(view), 1, 12); + Assert.True(view.Tactical); + Assert.Equal(MathF.Log(End), view.Commanded, 4); + view.Scroll(2); + Assert.Equal(MathF.Log(End) + 2 * LnStep, view.Commanded, 4); + view.Scroll(-1); + Assert.Equal(MathF.Log(End) + LnStep, view.Commanded, 4); + view.Scroll(500); + Assert.Equal(MathF.Log(Radius * Fit), view.Commanded, 4); + // A zone smaller than the band's far edge still reaches that edge and no farther. + var tiny = Make(10); + ToFlightEdge(tiny); + Cross(tiny); + tiny.Scroll(100); + Assert.Equal(MathF.Log(End), tiny.Commanded, 4); + } + + [Fact] + public void DetentHoldsASlowScroll() + { + var view = Make(); + ToFlightEdge(view); + Flick(view, 40, 5); + Assert.False(view.Tactical); + Assert.True(view.Commanded > MathF.Log(Start)); + Settle(view); + Assert.Equal(MathF.Log(Start), view.Commanded, 3); + Assert.False(view.Tactical); + } + + [Fact] + public void DetentYieldsToAFastScroll() + { + var view = Make(); + ToFlightEdge(view); + var notches = 0; + while (!view.Tactical && notches < 10) + { + view.Tick(.05f); + view.Scroll(1); + notches++; + } + Assert.True(view.Tactical); + Assert.Equal(MathF.Log(End), view.Commanded, 5); + } + + [Fact] + public void DetentIsSymmetric() + { + var view = Make(); + ToFlightEdge(view); + Assert.InRange(Cross(view), 1, 12); + Assert.True(view.Tactical); + Settle(view); + Flick(view, 40, 5, -1); + Assert.True(view.Tactical); + Settle(view); + Assert.Equal(MathF.Log(End), view.Commanded, 3); + Assert.InRange(Cross(view, -1), 1, 12); + Assert.False(view.Tactical); + Assert.Equal(MathF.Log(Start), view.Commanded, 5); + } + + [Fact] + public void TickNeverFlipsTactical() + { + // The commanded position sampled across the whole band, from both views, then ticked every which way. + foreach (var fromTactical in new[] { false, true }) + foreach (var notches in new[] { 1, 2, 3, 4, 5, 6 }) + foreach (var dt in new[] { .001f, .05f, .4f, 3f, 100f }) + { + var view = Make(); + ToFlightEdge(view); + if (fromTactical) Assert.InRange(Cross(view), 1, 12); + view.Scroll(fromTactical ? -notches : notches); + var was = view.Tactical; + for (var i = 0; i < 5; i++) + { + view.Tick(dt); + Assert.Equal(was, view.Tactical); + } + } + } + + [Fact] + public void BlendFollowsTheEasedDistance() + { + var view = Make(); + ToFlightEdge(view); + var before = view.Distance; + Cross(view); + Assert.True(view.Tactical); + // The committing scroll moved the commanded position, not the camera: the eased distance is still near flight's edge. + Assert.True(view.Distance < End); + var last = view.Distance; + var lastBlend = view.Blend(last); + Assert.True(last >= before - 1e-3f); + for (var i = 0; i < 600; i++) + { + view.Tick(.005f); + Assert.True(view.Distance >= last - 1e-3f); + Assert.True(view.Distance <= End * 1.0001f); + Assert.True(view.Blend(view.Distance) >= lastBlend - 1e-6f); + last = view.Distance; + lastBlend = view.Blend(last); + } + Assert.Equal(End, view.Distance, 0); + Assert.Equal(1f, view.Blend(view.Distance), 2); + } + + [Fact] + public void RightAfterACommitDistanceAndBlendAreUnchanged() + { + var view = Make(); + ToFlightEdge(view); + var distance = view.Distance; + var blend = view.Blend(distance); + for (var i = 0; i < 8; i++) view.Scroll(1); + Assert.True(view.Tactical); + Assert.Equal(distance, view.Distance, 3); + Assert.Equal(blend, view.Blend(view.Distance), 5); + } + + [Fact] + public void TargetTracksTheShipOnlyInFlight() + { + var view = Make(); + Assert.Equal(new float2(100, -50), view.Target); + view.Pan(new float2(5, 5)); + Assert.Equal(new float2(100, -50), view.Target); + view.Track(new float2(7, 8)); + Assert.Equal(new float2(7, 8), view.Target); + ToFlightEdge(view); + Cross(view); + Assert.True(view.Tactical); + view.Track(new float2(-900, 900)); + Assert.Equal(new float2(7, 8), view.Target); + view.Pan(new float2(10, -4)); + Assert.Equal(new float2(17, 4), view.Target); + view.Pan(new float2(1e6f, 0)); + Assert.Equal(Radius, MathF.Sqrt(view.Target.x * view.Target.x + view.Target.y * view.Target.y), 1); + view.Reset(Radius, BaseDistance, new float2(3, 4)); + Assert.Equal(new float2(3, 4), view.Target); + Assert.False(view.Tactical); } [Fact]