Files
Firebird_2D/Firebird2D.KeyMapper/KeyMapper.cs
T
2025-04-20 15:37:36 +02:00

206 lines
7.3 KiB
C#

using Firebird2D.EventPipelines.EventArguments;
using Firebird2D.EventPipelines;
using SFML.Window;
using System.Runtime.CompilerServices;
using System.Text.Json;
namespace Firebird2D.KeyMapping
{
/// <summary>
/// Maps input events (keyboard, mouse, joystick) to custom Firebird events and manages their pipelines.
/// </summary>
public class KeyMapper
{
private EventBus eventBus;
// Stores registered input events by name.
private Dictionary<string, Delegate> inputEvents = [];
// Stores the expected argument type for each input event.
private Dictionary<string, Type> eventTypes = [];
// Maps event names to FirebirdEvent identifiers.
private Dictionary<string, FirebirdEvent> inputMapping = [];
// Caches active pipelines for performance.
private Dictionary<FirebirdEvent, I_Pipeline> cachedPipelines = [];
public KeyMapper(EventBus eventBus)
{
if (eventBus == null) throw new NullReferenceException(nameof(eventBus));
this.eventBus = eventBus;
}
/// <summary>
/// Registers an input event with its handler and links it to a FirebirdEvent.
/// </summary>
public void RegisterEvent<T>(string EventName, EventHandler<T> handler, FirebirdEvent eventNumber) where T : EventArgs
{
if (inputEvents.ContainsKey(EventName))
throw new ArgumentException($"Event {EventName} already exists.");
inputEvents.Add(EventName, handler);
eventTypes.Add(EventName, typeof(T));
Map(EventName, eventNumber);
}
/// <summary>
/// Maps an existing input event to a new FirebirdEvent.
/// </summary>
public void Map(string EventName, FirebirdEvent eventNumber)
{
if (inputMapping.ContainsKey(EventName))
{
RemoveMapping(EventName);
inputMapping[EventName] = eventNumber;
}
else
{
inputMapping.Add(EventName, eventNumber);
}
AjustPipeline(EventName, eventNumber);
}
/// <summary>
/// Removes the current mapping and unsubscribes from the pipeline.
/// </summary>
private void RemoveMapping(string EventName)
{
if (!inputMapping.TryGetValue(EventName, out var firebirdEvent)) return;
if (!eventTypes.TryGetValue(EventName, out var type)) return;
I_Pipeline? pipeline = eventBus.GetPipeline(firebirdEvent, type);
if (pipeline != null)
{
pipeline.Unsubscribe(inputEvents[EventName]);
if (pipeline.IsEventEmpty)
{
eventBus.DestroyPipeline(firebirdEvent, this);
cachedPipelines.Remove(firebirdEvent);
}
}
inputMapping.Remove(EventName);
}
/// <summary>
/// Creates or adjusts a pipeline to reflect current mappings.
/// </summary>
private void AjustPipeline(string EventName, FirebirdEvent eventNumber)
{
if (!eventTypes.TryGetValue(EventName, out var type)) return;
I_Pipeline pipeline = eventBus.GetOrBuildPipeline(eventNumber, type, this);
pipeline.Subscribe(inputEvents[EventName]);
}
/// <summary>
/// Serializes and saves the current mapping to a file.
/// </summary>
public void SaveMapping(string Path)
{
string json = JsonSerializer.Serialize(inputMapping);
File.WriteAllText(Path, json);
}
/// <summary>
/// Loads and applies an input mapping from a JSON file.
/// </summary>
public void LoadMapping(string Path)
{
string json = File.ReadAllText(Path);
Dictionary<string, FirebirdEvent>? keyValuePairs = JsonSerializer.Deserialize<Dictionary<string, FirebirdEvent>>(json);
if (keyValuePairs == null) throw new FileLoadException("Unable to deserialize input mapping.");
cachedPipelines.Clear();
foreach (var kvp in inputMapping)
{
RemoveMapping(kvp.Key);
}
inputMapping = keyValuePairs;
foreach (var kvp in inputMapping)
{
if (inputEvents.ContainsKey(kvp.Key))
{
AjustPipeline(kvp.Key, kvp.Value);
}
}
}
/// <summary>
/// Removes a pipeline from the internal cache.
/// </summary>
public void InvalidatePipelineCache(FirebirdEvent fbEvent)
{
cachedPipelines.Remove(fbEvent);
}
/// <summary>
/// Retrieves a cached pipeline or fetches and caches it.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private Pipeline<T>? GetOrCachePipeline<T>(FirebirdEvent fbEvent) where T : EventArgs
{
if (cachedPipelines.TryGetValue(fbEvent, out var pipelineObj) && pipelineObj is Pipeline<T> cached)
return cached;
var pipeline = eventBus?.GetPipeline(fbEvent, typeof(T)) as Pipeline<T>;
if (pipeline != null)
cachedPipelines[fbEvent] = pipeline;
return pipeline;
}
/// <summary>
/// Handles a keyboard input and dispatches the event.
/// </summary>
public void HandleKeyboardInput(KeyEvent key, InputEventType type)
{
var pipeline = GetOrCachePipeline<FirebirdKeyEventArgs>((FirebirdEvent)key.Code);
pipeline?.SendEvent(this, new FirebirdKeyEventArgs(key, type));
}
/// <summary>
/// Handles a mouse button input and dispatches the event.
/// </summary>
public void HandleMouseInput(MouseButtonEvent button, InputEventType type)
{
var pipeline = GetOrCachePipeline<FirebirdMouseButtonEventArgs>((FirebirdEvent)(button.Button + 101));
pipeline?.SendEvent(this, new FirebirdMouseButtonEventArgs(button, type));
}
/// <summary>
/// Handles a joystick button press and dispatches the event.
/// </summary>
public void HandleJoystickButtonInput(JoystickButtonEvent joystickButton, InputEventType type)
{
var pipeline = GetOrCachePipeline<FirebirdJoystickButtonEventArgs>(FirebirdEvent.JoystickButton);
pipeline?.SendEvent(this, new FirebirdJoystickButtonEventArgs(joystickButton, type));
}
/// <summary>
/// Handles mouse movement and dispatches the event.
/// </summary>
public void HandleMouseMovement(MouseMoveEvent mouseMove)
{
var pipeline = GetOrCachePipeline<MouseMoveEventArgs>(FirebirdEvent.MouseMove);
pipeline?.SendEvent(this, new MouseMoveEventArgs(mouseMove));
}
/// <summary>
/// Handles joystick movement and dispatches the event.
/// </summary>
public void HandleJoytickMove(JoystickMoveEvent joystickMove)
{
var pipeline = GetOrCachePipeline<JoystickMoveEventArgs>(FirebirdEvent.JoystickMove);
pipeline?.SendEvent(this, new JoystickMoveEventArgs(joystickMove));
}
}
}