Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
109 changes: 109 additions & 0 deletions Assets/Tests/InputSystem/CoreTests_Devices.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2669,6 +2669,115 @@ public void Devices_CanCheckAnyKeyOnKeyboard()
Assert.That(keyboard.anyKey.isPressed, Is.True);
}

// UUM-144317: anyKey stays pressed while any key is held, so a key going down while another one was held
// did not register as a press.
[Test]
[Category("Devices")]
public void Devices_AnyKeyOnKeyboard_WasPressedThisFrame_WhenKeyGoesDownWhileAnotherIsHeld()
{
var keyboard = InputSystem.AddDevice<Keyboard>();

// Start tracking frame presses.
Assert.That(keyboard.anyKey.wasPressedThisFrame, Is.False);

Press(keyboard.leftShiftKey);
Assert.That(keyboard.anyKey.wasPressedThisFrame, Is.True);

InputSystem.Update();
Assert.That(keyboard.anyKey.wasPressedThisFrame, Is.False);

Press(keyboard.aKey);
Assert.That(keyboard.anyKey.wasPressedThisFrame, Is.True);
Assert.That(keyboard.anyKey.wasReleasedThisFrame, Is.False);

// Releasing one of the held keys is neither a press nor a release.
Release(keyboard.aKey);
Assert.That(keyboard.anyKey.isPressed, Is.True);
Assert.That(keyboard.anyKey.wasPressedThisFrame, Is.False);
Assert.That(keyboard.anyKey.wasReleasedThisFrame, Is.False);

Release(keyboard.leftShiftKey);
Assert.That(keyboard.anyKey.wasPressedThisFrame, Is.False);
Assert.That(keyboard.anyKey.wasReleasedThisFrame, Is.True);
}

// Same as above, but with full state events like the ones the platform backends send.
[Test]
[Category("Devices")]
public void Devices_AnyKeyOnKeyboard_WasPressedThisFrame_WhenKeyGoesDownWhileAnotherIsHeld_WithFullStateEvents()
{
var keyboard = InputSystem.AddDevice<Keyboard>();

Assert.That(keyboard.anyKey.wasPressedThisFrame, Is.False);

InputSystem.QueueStateEvent(keyboard, new KeyboardState(Key.LeftShift));
InputSystem.Update();
Assert.That(keyboard.anyKey.wasPressedThisFrame, Is.True);

InputSystem.QueueStateEvent(keyboard, new KeyboardState(Key.LeftShift));
InputSystem.Update();
Assert.That(keyboard.anyKey.wasPressedThisFrame, Is.False);

InputSystem.QueueStateEvent(keyboard, new KeyboardState(Key.LeftShift, Key.A));
InputSystem.Update();
Assert.That(keyboard.anyKey.wasPressedThisFrame, Is.True);
}

// The first query, which starts tracking frame presses, can come in the frame the key goes down.
[Test]
[Category("Devices")]
public void Devices_AnyKeyOnKeyboard_WasPressedThisFrame_WhenFirstQueriedAsKeyGoesDownWhileAnotherIsHeld()
{
var keyboard = InputSystem.AddDevice<Keyboard>();

Press(keyboard.leftShiftKey);
Press(keyboard.aKey);

Assert.That(keyboard.anyKey.wasPressedThisFrame, Is.True);
Assert.That(keyboard.anyKey.wasPressedThisFrame, Is.True);

InputSystem.Update();
Assert.That(keyboard.anyKey.wasPressedThisFrame, Is.False);
}

#if UNITY_EDITOR
// Changing settings refreshes press tracking for both editor and player state, whichever of the two is current.
// That must not mix them up.
[Test]
[Category("Devices")]
public void Devices_AnyKeyOnKeyboard_WasPressedThisFrame_KeepsEditorAndPlayerStateApart_WhenSettingsChange()
{
runtime.runInBackground = true;
InputSystem.settings.backgroundBehavior = InputSettings.BackgroundBehavior.IgnoreFocus;
InputSystem.settings.editorInputBehaviorInPlayMode = default;

var keyboard = InputSystem.AddDevice<Keyboard>();

// Player state: Shift is held.
InputSystem.QueueStateEvent(keyboard, new KeyboardState(Key.LeftShift));
InputSystem.Update(InputUpdateType.Dynamic);
Assert.That(keyboard.anyKey.wasPressedThisFrame, Is.True);

// Without game view focus, keyboard input goes to the editor. Editor state: Shift and A are held.
ScheduleFocusChangedEvent(applicationHasFocus: false);
InputSystem.Update(InputUpdateType.Dynamic);
InputSystem.QueueStateEvent(keyboard, new KeyboardState(Key.LeftShift, Key.A));
InputSystem.Update(InputUpdateType.Editor);
Assert.That(keyboard.aKey.isPressed, Is.True);

// Change a setting while player state is current.
InputSystem.Update(InputUpdateType.Dynamic);
InputSystem.settings.defaultDeadzoneMin = 0.2f;

// Releasing Shift in the editor must not make A, which is still held, look newly pressed.
InputSystem.QueueStateEvent(keyboard, new KeyboardState(Key.A));
InputSystem.Update(InputUpdateType.Editor);
Assert.That(keyboard.aKey.isPressed, Is.True);
Assert.That(keyboard.anyKey.wasPressedThisFrame, Is.False);
}

#endif

[Test]
[Category("Devices")]
public void Devices_AnyKeyOnKeyboard_DoesNotReactToIMESelected()
Expand Down
38 changes: 38 additions & 0 deletions Assets/Tests/InputSystem/Plugins/WebGLTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,44 @@ public void Devices_SupportsWebGLJoysticks()
AssertButtonPress(joystick, new TestJoystickState());
}

// The Trigger control of WebGL joysticks covers the float values of all buttons. A value change of a held
// button can set bits in that state, which must not count as another press.
[Test]
[Category("Devices")]
public void Devices_WebGLJoystickTrigger_WasPressedThisFrame_IsFalse_WhenValueOfHeldButtonChanges()
{
runtime.ReportNewInputDevice(new InputDeviceDescription
{
interfaceName = "WebGL",
deviceClass = "Gamepad",
product = "WebGL test joystick",
capabilities = new WebGLDeviceCapabilities
{
mapping = "",
numAxes = 3,
numButtons = 3
}.ToJson()
});

InputSystem.Update();

var joystick = InputSystem.GetDevice<WebGLJoystick>();
var trigger = (ButtonControl)joystick.TryGetChildControl("Trigger");

// Start tracking frame presses.
Assert.That(trigger.wasPressedThisFrame, Is.False);

InputSystem.QueueStateEvent(joystick, new TestJoystickState {button1 = 1.0f});
InputSystem.Update();
Assert.That(trigger.wasPressedThisFrame, Is.True);

// 0.75 has a bit set that 1.0 doesn't have.
InputSystem.QueueStateEvent(joystick, new TestJoystickState {button1 = 0.75f});
InputSystem.Update();
Assert.That(trigger.isPressed, Is.True);
Assert.That(trigger.wasPressedThisFrame, Is.False);
}

[Test]
[Category("Devices")]
public void Devices_CanHaveWebGLJoystickWithBadRegexInName()
Expand Down
1 change: 1 addition & 0 deletions Packages/com.unity.inputsystem/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
- Fixed touch input from Unity Remote 5 being ignored in Unity 6000.5 and newer. [UUM-155327](https://issuetracker.unity3d.com/product/unity/issues/guid/UUM-155327)
- Fixed actions enabled during startup, for example in an Entities system's `OnCreate`, being disabled when entering Play Mode with domain reload disabled and in Player builds. [UUM-151403](https://issuetracker.unity3d.com/product/unity/issues/guid/UUM-151403)
- Fixed the Player Input component Inspector not showing the action map events after the Behavior is set to Invoke Unity Events, until the GameObject was selected again. [UUM-150956](https://issuetracker.unity3d.com/product/unity/issues/guid/UUM-150956)
- Fixed `Keyboard.anyKey.wasPressedThisFrame` not returning true when a key is pressed while another key is held. This means it can now be true several times without `wasReleasedThisFrame` in between. [UUM-144317](https://issuetracker.unity3d.com/product/unity/issues/guid/UUM-144317)
- Fixed a control declared for several variants at once (for example `"variants" : "A;B"`) only merging with derived layouts under its first variant; derived overrides for the other variants lost the base control's layout, offset, format and usages. [UUM-160829](https://issuetracker.unity3d.com/product/unity/issues/guid/UUM-160829)

## [1.20.1] - 2026-10-05
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine.InputSystem.Layouts;
using UnityEngine.InputSystem.LowLevel;
using UnityEngine.InputSystem.Utilities;

////REVIEW: generalize this to AnyButton and add to more devices?

Expand All @@ -13,12 +15,22 @@
/// <remarks>
/// This control is used by <see cref="Keyboard.anyKey"/> to create a button
/// that is toggled on as long as any of the keys on the keyboard is pressed.
///
/// For <see cref="Keyboard.anyKey"/>, <see cref="ButtonControl.wasPressedThisFrame"/> is true in any
/// frame in which a key goes down, even if other keys are already held.
/// <see cref="ButtonControl.wasReleasedThisFrame"/> is only true in the frame in which the last held key
/// is released. This means that there can be several presses in a row without a release in between.
/// </remarks>
/// <seealso cref="Keyboard.anyKey"/>
[InputControlLayout(hideInUI = true)]
public class AnyKeyControl : ButtonControl
{
////TODO: wasPressedThisFrame and wasReleasedThisFrame
// The state as of the last press state update, to find keys that went down since. The editor has its own
// state buffers, so it gets its own copy.
private byte[] m_LastState;
#if UNITY_EDITOR
private byte[] m_LastStateEditor;
#endif

/// <summary>
/// Default initialization. Sets state size to 1 bit and format to
Expand All @@ -35,5 +47,65 @@
{
return this.CheckStateIsAtDefault(statePtr) ? 0.0f : 1.0f;
}

internal override unsafe bool CheckForRepress(bool editorState, bool startTracking)
{
// Only on keyboards is each bit of the state a key, so that a bit going from 0 to 1 is a key going down.
// Other devices use this control over other kinds of state, such as the float button values of WebGL
// joysticks, where a value change can also set bits. Check the device rather than set a flag in
// Keyboard.FinishSetup, because the precompiled FastKeyboard doesn't call it.
if (!(device is Keyboard))
return false;

#if UNITY_EDITOR
ref var lastState = ref editorState ? ref m_LastStateEditor : ref m_LastState;
#else
ref var lastState = ref m_LastState;
#endif

// Press tracking for editor and player state can be updated while the other one is current (for example
// after a settings change), so read the state buffers of the requested one rather than the current ones.
var updateType = editorState ? InputUpdateType.Editor : InputUpdateType.Dynamic;
var statePtr = (byte*)GetStatePtr(updateType, previousFrame: false);
if (statePtr == null)
return false;

Check warning on line 71 in Packages/com.unity.inputsystem/InputSystem/Runtime/Controls/AnyKeyControl.cs

View check run for this annotation

Codecov GitHub.com / codecov/patch

Packages/com.unity.inputsystem/InputSystem/Runtime/Controls/AnyKeyControl.cs#L71

Added line #L71 was not covered by tests
statePtr += m_StateBlock.byteOffset;

var sizeInBytes = (int)((m_StateBlock.bitOffset + m_StateBlock.sizeInBits + 7) >> 3);
var isNewSnapshot = lastState == null || lastState.Length != sizeInBytes;
if (isNewSnapshot)
lastState = new byte[sizeInBytes];

var keyWentDown = false;
fixed(byte* lastStatePtr = lastState)
{
// Compare against the previous frame when tracking starts, so that a key that went down in this
// frame still counts.
if (startTracking)
{
var previousStatePtr = (byte*)GetStatePtr(updateType, previousFrame: true) + m_StateBlock.byteOffset;
UnsafeUtility.MemCpy(lastStatePtr, previousStatePtr, sizeInBytes);
}
else if (isNewSnapshot)
{
UnsafeUtility.MemCpy(lastStatePtr, statePtr, sizeInBytes);
return false;
}

var endBit = m_StateBlock.bitOffset + m_StateBlock.sizeInBits;
for (var bit = m_StateBlock.bitOffset; bit < endBit; ++bit)
{
if (MemoryHelpers.ReadSingleBit(statePtr, bit) && !MemoryHelpers.ReadSingleBit(lastStatePtr, bit))
Comment thread
K-Tone marked this conversation as resolved.
Resolved
{
keyWentDown = true;
break;
}
}

UnsafeUtility.MemCpy(lastStatePtr, statePtr, sizeInBytes);
}

return keyWentDown;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -215,28 +215,35 @@
// When we start caring about inter-frame presses, use the info we have to set up the alternate path.
// If we don't do this, users could call wasPressedThisFrame/wasReleasedThisFrame twice for the first time in
// a single frame, and the returned value may be incorrect until the next frame.
private void BeginTestingForFramePresses(bool currentlyPressed, bool pressedLastFrame)
// Returns whether the button was pressed in the last update of the device.
private bool BeginTestingForFramePresses(bool currentlyPressed, bool pressedLastFrame)
{
needsToCheckFramePress = true;
device.m_ButtonControlsCheckingPressState.Add(this);

#if UNITY_EDITOR
if (InputUpdate.s_LatestUpdateType.IsEditorUpdate())
{
var wasPressedAgain = CheckForRepress(true, startTracking: true);
var wasPressed = currentlyPressed && (!pressedLastFrame || wasPressedAgain);

Check warning on line 228 in Packages/com.unity.inputsystem/InputSystem/Runtime/Controls/ButtonControl.cs

View check run for this annotation

Codecov GitHub.com / codecov/patch

Packages/com.unity.inputsystem/InputSystem/Runtime/Controls/ButtonControl.cs#L227-L228

Added lines #L227 - L228 were not covered by tests
m_LastUpdateWasPressEditor = currentlyPressed;
if (currentlyPressed && !pressedLastFrame)
if (wasPressed)

Check warning on line 230 in Packages/com.unity.inputsystem/InputSystem/Runtime/Controls/ButtonControl.cs

View check run for this annotation

Codecov GitHub.com / codecov/patch

Packages/com.unity.inputsystem/InputSystem/Runtime/Controls/ButtonControl.cs#L230

Added line #L230 was not covered by tests
m_UpdateCountLastPressedEditor = device.m_CurrentUpdateStepCount;
else if (pressedLastFrame && !currentlyPressed)
m_UpdateCountLastReleasedEditor = device.m_CurrentUpdateStepCount;
return wasPressed;

Check warning on line 234 in Packages/com.unity.inputsystem/InputSystem/Runtime/Controls/ButtonControl.cs

View check run for this annotation

Codecov GitHub.com / codecov/patch

Packages/com.unity.inputsystem/InputSystem/Runtime/Controls/ButtonControl.cs#L234

Added line #L234 was not covered by tests
}
else
#endif
{
var wasPressedAgain = CheckForRepress(false, startTracking: true);
var wasPressed = currentlyPressed && (!pressedLastFrame || wasPressedAgain);
m_LastUpdateWasPress = currentlyPressed;
if (currentlyPressed && !pressedLastFrame)
if (wasPressed)
m_UpdateCountLastPressed = device.m_CurrentUpdateStepCount;
else if (pressedLastFrame && !currentlyPressed)
m_UpdateCountLastReleased = device.m_CurrentUpdateStepCount;
return wasPressed;
}
}

Expand Down Expand Up @@ -288,9 +295,9 @@
{
var currentlyPressed = IsValueConsideredPressed(value);
var pressedLastFrame = IsValueConsideredPressed(ReadValueFromPreviousFrame());
BeginTestingForFramePresses(currentlyPressed, pressedLastFrame);
var wasPressed = BeginTestingForFramePresses(currentlyPressed, pressedLastFrame);

return device.wasUpdatedThisFrame && currentlyPressed && !pressedLastFrame;
return device.wasUpdatedThisFrame && wasPressed;
}

#if UNITY_EDITOR
Expand Down Expand Up @@ -349,6 +356,7 @@
internal void UpdateWasPressed()
{
var isNowPressed = IsValueConsideredPressed(value);
var wasPressedAgain = CheckForRepress(false, startTracking: false);

if (m_LastUpdateWasPress != isNowPressed)
{
Expand All @@ -359,12 +367,26 @@

m_LastUpdateWasPress = isNowPressed;
}
else if (isNowPressed && wasPressedAgain)
{
m_UpdateCountLastPressed = device.m_CurrentUpdateStepCount;
}
}

// Lets a button that is made up of several inputs, such as AnyKeyControl, report a new press while it is
// already held, when another of its inputs goes down. Called on every press state update, and once when
// press tracking starts, in which case it compares against the previous frame. Returns true if there was
// such a press since the previous call.
internal virtual bool CheckForRepress(bool editorState, bool startTracking)
{
return false;
}

#if UNITY_EDITOR
internal void UpdateWasPressedEditor()
{
var isNowPressed = IsValueConsideredPressed(value);
var wasPressedAgain = CheckForRepress(true, startTracking: false);

if (m_LastUpdateWasPressEditor != isNowPressed)
{
Expand All @@ -375,6 +397,10 @@

m_LastUpdateWasPressEditor = isNowPressed;
}
else if (isNowPressed && wasPressedAgain)
{
m_UpdateCountLastPressedEditor = device.m_CurrentUpdateStepCount;
}

Check warning on line 403 in Packages/com.unity.inputsystem/InputSystem/Runtime/Controls/ButtonControl.cs

View check run for this annotation

Codecov GitHub.com / codecov/patch

Packages/com.unity.inputsystem/InputSystem/Runtime/Controls/ButtonControl.cs#L401-L403

Added lines #L401 - L403 were not covered by tests
}

#endif // UNITY_EDITOR
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -923,6 +923,18 @@
/// </value>
protected internal unsafe void* previousFrameStatePtr => InputStateBuffers.GetBackBufferForDevice(GetDeviceIndex());

// Like currentStatePtr and previousFrameStatePtr, but reads the state buffers of the given update type
// instead of the ones of the current update.
internal unsafe void* GetStatePtr(InputUpdateType updateType, bool previousFrame)
{
var buffers = InputSystem.manager.m_StateBuffers.GetDoubleBuffersFor(updateType);
if (!buffers.valid)
return null;

Check warning on line 932 in Packages/com.unity.inputsystem/InputSystem/Runtime/Controls/InputControl.cs

View check run for this annotation

Codecov GitHub.com / codecov/patch

Packages/com.unity.inputsystem/InputSystem/Runtime/Controls/InputControl.cs#L932

Added line #L932 was not covered by tests

var deviceIndex = GetDeviceIndex();
return previousFrame ? buffers.GetBackBuffer(deviceIndex) : buffers.GetFrontBuffer(deviceIndex);
}

/// <summary>
/// The default state data buffer
/// </summary>
Expand Down
Loading