###Joystick Gremlin plugin, to stop axis movement on button press
### damien // deltasimelectronics.com
### September 2024

import gremlin
from gremlin.user_plugin import *


physical_axis = PhysicalInputVariable(
        "Physical Axis",
        "Physical axis input",
        [gremlin.common.InputType.JoystickAxis]
)

virtual_axis = VirtualInputVariable(
        "vJoy Axis",
        "Virtual axis output",
        [gremlin.common.InputType.JoystickAxis]
)

physical_btn = PhysicalInputVariable(
        "Button",
        "Button which will zero the axis.",
        [gremlin.common.InputType.JoystickButton]
)

mode = ModeVariable("Mode", "Mode in which to use these settings")

# Decorators for the physical axis and button
dec_axis = physical_axis.create_decorator(mode.value)
dec_btn = physical_btn.create_decorator(mode.value)

# Storage for the axis value and button state
axis_value = 0.0
btn_state = 0

def update_vjoy(vjoy):
    if btn_state == 0:
        vjoy[virtual_axis.vjoy_id].axis(virtual_axis.input_id).value = axis_value

    if btn_state == 1:
        vjoy[virtual_axis.vjoy_id].axis(virtual_axis.input_id).value = 0
        

@dec_axis.axis(physical_axis.input_id)
def axis_1(event, vjoy):
    global axis_value
    axis_value = event.value
    update_vjoy(vjoy)
    

@dec_btn.button(physical_btn.input_id)
def button_1(event, vjoy):
    global btn_state
    btn_state = 1 if event.is_pressed else 0
    update_vjoy(vjoy)
