MoonWorks/src/Input/Mouse.cs

94 lines
2.1 KiB
C#
Raw Normal View History

2022-04-27 18:37:35 +00:00
using System.Collections.Generic;
using SDL2;
namespace MoonWorks.Input
{
2022-02-23 05:14:32 +00:00
public class Mouse
{
2022-04-27 18:37:35 +00:00
public Button LeftButton { get; } = new Button();
public Button MiddleButton { get; } = new Button();
public Button RightButton { get; } = new Button();
2022-02-23 05:14:32 +00:00
public int X { get; private set; }
public int Y { get; private set; }
public int DeltaX { get; private set; }
public int DeltaY { get; private set; }
public int Wheel { get; internal set; }
2022-07-08 23:47:12 +00:00
public bool AnyPressed { get; private set; }
public MouseButtonCode AnyPressedButtonCode { get; private set; }
2022-02-23 05:14:32 +00:00
private bool relativeMode;
public bool RelativeMode
{
get => relativeMode;
set
{
relativeMode = value;
SDL.SDL_SetRelativeMouseMode(
relativeMode ?
SDL.SDL_bool.SDL_TRUE :
SDL.SDL_bool.SDL_FALSE
);
}
}
2022-04-27 18:37:35 +00:00
private readonly Dictionary<MouseButtonCode, Button> CodeToButton;
2022-07-08 23:47:12 +00:00
private readonly Dictionary<uint, MouseButtonCode> MaskToButtonCode;
2022-04-27 18:37:35 +00:00
public Mouse()
{
CodeToButton = new Dictionary<MouseButtonCode, Button>
{
{ MouseButtonCode.Left, LeftButton },
{ MouseButtonCode.Right, RightButton },
{ MouseButtonCode.Middle, MiddleButton }
};
2022-07-08 23:47:12 +00:00
MaskToButtonCode = new Dictionary<uint, MouseButtonCode>
{
{ SDL.SDL_BUTTON_LMASK, MouseButtonCode.Left },
{ SDL.SDL_BUTTON_MMASK, MouseButtonCode.Middle },
{ SDL.SDL_BUTTON_RMASK, MouseButtonCode.Right }
};
2022-04-27 18:37:35 +00:00
}
2022-02-23 05:14:32 +00:00
internal void Update()
{
2022-07-08 23:47:12 +00:00
AnyPressed = false;
2022-02-23 05:14:32 +00:00
var buttonMask = SDL.SDL_GetMouseState(out var x, out var y);
var _ = SDL.SDL_GetRelativeMouseState(out var deltaX, out var deltaY);
X = x;
Y = y;
DeltaX = deltaX;
DeltaY = deltaY;
2022-07-08 23:47:12 +00:00
foreach (var (mask, buttonCode) in MaskToButtonCode)
{
var pressed = IsPressed(buttonMask, mask);
var button = CodeToButton[buttonCode];
button.Update(pressed);
if (button.IsPressed)
{
AnyPressed = true;
AnyPressedButtonCode = buttonCode;
}
}
2022-04-27 18:37:35 +00:00
}
public ButtonState ButtonState(MouseButtonCode buttonCode)
{
return CodeToButton[buttonCode].State;
2022-02-23 05:14:32 +00:00
}
private bool IsPressed(uint buttonMask, uint buttonFlag)
{
return (buttonMask & buttonFlag) != 0;
}
}
}