code:
                    GNU GENERAL PUBLIC LICENSE
                       Version 2, June 1991

 Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The licenses for most software are designed to take away your
freedom to share and change it.  By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users.  This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it.  (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.)  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.

  To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have.  You must make sure that they, too, receive or can get the
source code.  And you must show them these terms so they know their
rights.

  We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.

  Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software.  If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.

  Finally, any free program is threatened constantly by software
patents.  We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary.  To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.

  The precise terms and conditions for copying, distribution and
modification follow.

                    GNU GENERAL PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License.  The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language.  (Hereinafter, translation is included without limitation in
the term "modification".)  Each licensee is addressed as "you".

Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope.  The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.

  1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.

You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.

  2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:

    a) You must cause the modified files to carry prominent notices
    stating that you changed the files and the date of any change.

    b) You must cause any work that you distribute or publish, that in
    whole or in part contains or is derived from the Program or any
    part thereof, to be licensed as a whole at no charge to all third
    parties under the terms of this License.

    c) If the modified program normally reads commands interactively
    when run, you must cause it, when started running for such
    interactive use in the most ordinary way, to print or display an
    announcement including an appropriate copyright notice and a
    notice that there is no warranty (or else, saying that you provide
    a warranty) and that users may redistribute the program under
    these conditions, and telling the user how to view a copy of this
    License.  (Exception: if the Program itself is interactive but
    does not normally print such an announcement, your work based on
    the Program is not required to print an announcement.)

These requirements apply to the modified work as a whole.  If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works.  But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.

Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.

In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.

  3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:

    a) Accompany it with the complete corresponding machine-readable
    source code, which must be distributed under the terms of Sections
    1 and 2 above on a medium customarily used for software interchange; or,

    b) Accompany it with a written offer, valid for at least three
    years, to give any third party, for a charge no more than your
    cost of physically performing source distribution, a complete
    machine-readable copy of the corresponding source code, to be
    distributed under the terms of Sections 1 and 2 above on a medium
    customarily used for software interchange; or,

    c) Accompany it with the information you received as to the offer
    to distribute corresponding source code.  (This alternative is
    allowed only for noncommercial distribution and only if you
    received the program in object code or executable form with such
    an offer, in accord with Subsection b above.)

The source code for a work means the preferred form of the work for
making modifications to it.  For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable.  However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.

If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.

  4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License.  Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.

  5. You are not required to accept this License, since you have not
signed it.  However, nothing else grants you permission to modify or
distribute the Program or its derivative works.  These actions are
prohibited by law if you do not accept this License.  Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.

  6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions.  You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.

  7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all.  For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.

If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.

It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices.  Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.

This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.

  8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded.  In such case, this License incorporates
the limitation as if written in the body of this License.

  9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

Each version is given a distinguishing version number.  If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation.  If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.

  10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission.  For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this.  Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.

                            NO WARRANTY

  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.

  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

Also add information on how to contact you by electronic and paper mail.

If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:

    Gnomovision version 69, Copyright (C) year name of author
    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.

You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary.  Here is a sample; alter the names:

  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
  `Gnomovision' (which makes passes at compilers) written by James Hacker.

  <signature of Ty Coon>, 1 April 1989
  Ty Coon, President of Vice

This General Public License does not permit incorporating your program into
proprietary programs.  If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.


code:
//-------------------------------------------------------------------------
/*
Copyright (C) 1996, 2003 - 3D Realms Entertainment

This file is NOT part of Duke Nukem 3D version 1.5 - Atomic Edition
However, it is either an older version of a file that is, or is
some test code written during the development of Duke Nukem 3D.
This file is provided purely for educational interest.

Duke Nukem 3D is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

Prepared for public release: 03/21/2003 - Charlie Wiederhold, 3D Realms
*/
//-------------------------------------------------------------------------

//****************************************************************************
//
// Private header for CONTROL.C
//
//****************************************************************************

#pragma once

#ifndef control_private_h_
#define control_private_h_

#include "compat.h"
#include "control.h"
#include "keyboard.h"

#ifdef __cplusplus
extern "C" {
#endif

#define AXISUNDEFINED   0x7f
#define BUTTONUNDEFINED 0x7f
#define KEYUNDEFINED    0x7f

#define DIGITALAXISANALOGTHRESHOLD    (0x200 * 32767 / 10000)
#define MINDIGITALAXISANALOGTHRESHOLD (0x80 * 32767 / 10000)

#define DEFAULTMOUSESENSITIVITY  (25.f)
#define DEFAULTMOUSEUNIT (.031337f)
#define DEFAULTJOYUNIT (.2f)

#define INSTANT_ONOFF       0
#define TOGGLE_ONOFF        1

// this is higher than the -32767 to 32767 range of the axis
#define MAXSCALEDCONTROLVALUE  0x1ffff

#define DEFAULTAXISSCALE 65536
#define DEFAULTAXISDEADZONE 1000
#define DEFAULTAXISSATURATE 9500
#define DEFAULTAXISSENSITIVITY (DEFAULTAXISSCALE/16384.f)

#define BUTTONSET(x, value)     (CONTROL_ButtonState |= ((uint64_t)value << ((uint64_t)(x))))
#define BUTTONCLEAR(x)          (CONTROL_ButtonState &= ~((uint64_t)1 << ((uint64_t)(x))))
#define BUTTONHELDSET(x, value) (CONTROL_ButtonHeldState |= (uint64_t)(value << ((uint64_t)(x))))

typedef struct ControlFunctionFlags
{
    uint8_t active;
    uint8_t used;
    uint8_t toggle;
    uint8_t buttonheld;
    int32_t cleared;
} ControlFunctionFlags_t;

typedef struct ControlKeyMap
{
    kb_scancode keyPrimary;
    kb_scancode keySecondary;
} ControlKeyMap_t;

typedef struct ControlButtonMap
{
    uint8_t singleclicked;
    uint8_t doubleclicked;
} ControlButtonMap_t;

typedef struct ControlButtonState
{
    ControlButtonMap_t mapping;

    int     clicked;
    int     clickedState;
    int32_t clickedTime;
    int     state;
    int     clickedCount;
} ControlButtonState_t;

typedef struct ControllerAxisMap
{
    uint8_t analogmap;
    uint8_t minmap;
    uint8_t maxmap;
} ControllerAxisMap_t;

typedef struct ControllerAxisState
{
    int32_t analog;
    int8_t digital;
    int8_t digitalCleared;
} ControllerAxisState_t;

typedef struct ControllerAxis
{
    ControllerAxisMap_t mapping;
    ControllerAxisState_t axis;
    ControllerAxisState_t last;
    float sensitivity;
    uint16_t deadzone;
    uint16_t saturation;
    bool invert;
} ControllerAxis_t;

typedef struct UserInputState
{
    UserInput local;
    int32_t   clock;
    direction repeat;
    bool      buttonCleared[4];
} UserInputState_t;

#ifdef __cplusplus
}
#endif
#endif

repo_name: orochi/nblood

license: mit


code:
//-------------------------------------------------------------------------
/*
Copyright (C) 1996, 2003 - 3D Realms Entertainment

This file is part of Duke Nukem 3D version 1.5 - Atomic Edition

Duke Nukem 3D is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

Original Source: 1996 - Todd Replogle
Prepared for public release: 03/21/2003 - Charlie Wiederhold, 3D Realms
Modifications for JonoF's port by Jonathon Fowler (jf@jonof.id.au)
*/
//-------------------------------------------------------------------------

/////////////////////////////////////////////////////////////////////////////
//
//      ANIMLIB.H
//
/////////////////////////////////////////////////////////////////////////////

#pragma once

#ifndef animlib_public_h_
#define animlib_public_h_
#ifdef __cplusplus
extern "C" {
#endif

# pragma pack(push,1)

/* structure declarations for deluxe animate large page files, doesn't
   need to be in the header because there are no exposed functions
   that use any of this directly */

typedef struct lpfileheaderstruct
{
    uint32_t id;              /* 4 uint8_tacter ID == "LPF " */
    uint16_t maxLps;          /* max # largePages allowed. 256 FOR NOW.   */
    uint16_t nLps;            /* # largePages in this file. */
    uint32_t nRecords;        /* # records in this file.  65534 is current limit + ring */
    uint16_t maxRecsPerLp;    /* # records permitted in an lp. 256 FOR NOW.   */
    uint16_t lpfTableOffset;  /* Absolute Seek position of lpfTable.  1280 FOR NOW. */
    uint32_t contentType;     /* 4 character ID == "ANIM" */
    uint16_t width;           /* Width of screen in pixels. */
    uint16_t height;          /* Height of screen in pixels. */
    uint8_t variant;          /* 0==ANIM. */
    uint8_t version;          /* 0==frame rate in 18/sec, 1= 70/sec */
    uint8_t hasLastDelta;     /* 1==Last record is a delta from last-to-first frame. */
    uint8_t lastDeltaValid;   /* 0==Ignore ring frame. */
    uint8_t pixelType;        /* 0==256 color. */
    uint8_t CompressionType;  /* 1==(RunSkipDump) Only one used FOR NOW. */
    uint8_t otherRecsPerFrm;  /* 0 FOR NOW. */
    uint8_t bitmaptype;       /* 1==320x200, 256-color.  Only one implemented so far. */
    uint8_t recordTypes[32];  /* Not yet implemented. */
    uint32_t nFrames;         /* Number of actual frames in the file, includes ring frame. */
    uint16_t framesPerSecond; /* Number of frames to play per second. */
    uint16_t pad2[29];        /* 58 bytes of filler to round up to 128 bytes total. */
}
lpfileheader;                 /* (comments from original source) */

// this is the format of a large page structure
typedef struct
{
    uint16_t baseRecord;   // Number of first record in this large page.
    uint16_t nRecords;        // Number of records in lp.
    // bit 15 of "nRecords" == "has continuation from previous lp".
    // bit 14 of "nRecords" == "final record continues on next lp".
    uint16_t nBytes;                  // Total number of bytes of contents, excluding header.
} lp_descriptor;

#pragma pack(pop)

#define IMAGEBUFFERSIZE 0x10000

typedef struct
{
    uint16_t framecount;          // current frame of anim
    lpfileheader * lpheader;           // file header will be loaded into this structure
    lp_descriptor * LpArray; // arrays of large page structs used to find frames
    uint16_t curlpnum;               // initialize to an invalid Large page number
    lp_descriptor * curlp;        // header of large page currently in memory
    uint16_t * thepage;     // buffer where current large page is loaded
    uint8_t imagebuffer[IMAGEBUFFERSIZE]; // buffer where anim frame is decoded
    uint8_t * buffer;
    uint8_t pal[768];
    int32_t currentframe;
} anim_t;

//****************************************************************************
//
//      ANIM_LoadAnim ()
//
// Setup internal anim data structure
//
//****************************************************************************

int32_t ANIM_LoadAnim(uint8_t *buffer, int32_t length);

//****************************************************************************
//
//      ANIM_FreeAnim ()
//
// Free up internal anim data structure
//
//****************************************************************************

void ANIM_FreeAnim(void);

//****************************************************************************
//
//      ANIM_NumFrames ()
//
// returns the number of frames in the current anim
//
//****************************************************************************

int32_t ANIM_NumFrames(void);

//****************************************************************************
//
//      ANIM_DrawFrame ()
//
// Draw the frame to a returned buffer
//
//****************************************************************************

uint8_t * ANIM_DrawFrame(int32_t framenumber);

//****************************************************************************
//
//      ANIM_GetPalette ()
//
// return the palette of the anim
//****************************************************************************

uint8_t * ANIM_GetPalette(void);

#ifdef __cplusplus
}
#endif
#endif


code:
//-------------------------------------------------------------------------
/*
Copyright (C) 1996, 2003 - 3D Realms Entertainment

This file is part of Duke Nukem 3D version 1.5 - Atomic Edition

Duke Nukem 3D is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

Original Source: 1996 - Todd Replogle
Prepared for public release: 03/21/2003 - Charlie Wiederhold, 3D Realms
Modifications for JonoF's port by Jonathon Fowler (jf@jonof.id.au)
*/
//-------------------------------------------------------------------------

//***************************************************************************
//
// Public header for CONTROL.C.
//
//***************************************************************************

#pragma once

#ifndef control_public_h_
#define control_public_h_

#include "joystick.h"
#include "keyboard.h"
#include "mouse.h"

#ifdef __cplusplus
extern "C" {
#endif

#define MAXGAMEBUTTONS      64

#define BUTTON(x)     ((CONTROL_ButtonState >> ((uint64_t)(x))) & 1)
#define BUTTONHELD(x) ((CONTROL_ButtonHeldState >> ((uint64_t)(x))) & 1)

#define BUTTONJUSTPRESSED(x)  (BUTTON(x) && !BUTTONHELD(x))
#define BUTTONRELEASED(x)     (!BUTTON(x) && BUTTONHELD(x))
#define BUTTONSTATECHANGED(x) (BUTTON(x) != BUTTONHELD(x))

typedef enum
{
    axis_up,
    axis_down,
    axis_left,
    axis_right
} axisdirection;

typedef enum
{
    analog_turning,
    analog_strafing,
    analog_lookingupanddown,
    analog_elevation,
    analog_rolling,
    analog_moving,
    analog_maxtype
} analogcontrol;

typedef enum
{
    dir_North,
    dir_Up = dir_North,
    dir_NorthEast,
    dir_East,
    dir_Right = dir_East,
    dir_SouthEast,
    dir_South,
    dir_Down = dir_South,
    dir_SouthWest,
    dir_West,
    dir_Left = dir_West,
    dir_NorthWest,
    dir_None
} direction;

typedef struct
{
    union { bool button0, b_advance; };
    union { bool button1, b_return; };
    union { bool button2, b_escape; };
    direction dir;
} UserInput;

typedef struct
{
    int32_t dx;
    int32_t dy;
    int32_t dz;
    int32_t dyaw;
    int32_t dpitch;
    int32_t droll;
    int32_t mousex;
    int32_t mousey;
} ControlInfo;

typedef enum
{
    controltype_keyboard,
    controltype_keyboardandmouse,
    controltype_keyboardandjoystick
} controltype;

typedef enum
{
    controldevice_keyboard,
    controldevice_mouse,
    controldevice_joystick
} controldevice;

enum GameControllerButton : int
{
    CONTROLLER_BUTTON_INVALID = -1,
    CONTROLLER_BUTTON_A,
    CONTROLLER_BUTTON_B,
    CONTROLLER_BUTTON_X,
    CONTROLLER_BUTTON_Y,
    CONTROLLER_BUTTON_BACK,
    CONTROLLER_BUTTON_GUIDE,
    CONTROLLER_BUTTON_START,
    CONTROLLER_BUTTON_LEFTSTICK,
    CONTROLLER_BUTTON_RIGHTSTICK,
    CONTROLLER_BUTTON_LEFTSHOULDER,
    CONTROLLER_BUTTON_RIGHTSHOULDER,
    CONTROLLER_BUTTON_DPAD_UP,
    CONTROLLER_BUTTON_DPAD_DOWN,
    CONTROLLER_BUTTON_DPAD_LEFT,
    CONTROLLER_BUTTON_DPAD_RIGHT,
    CONTROLLER_BUTTON_MISC,
    CONTROLLER_BUTTON_PADDLE1,
    CONTROLLER_BUTTON_PADDLE2,
    CONTROLLER_BUTTON_PADDLE3,
    CONTROLLER_BUTTON_PADDLE4,
    CONTROLLER_BUTTON_MAX
};

enum GameControllerAxis : int
{
    CONTROLLER_AXIS_INVALID = -1,
    CONTROLLER_AXIS_LEFTX,
    CONTROLLER_AXIS_LEFTY,
    CONTROLLER_AXIS_RIGHTX,
    CONTROLLER_AXIS_RIGHTY,
    CONTROLLER_AXIS_TRIGGERLEFT,
    CONTROLLER_AXIS_TRIGGERRIGHT,
    CONTROLLER_AXIS_MAX
};

enum class LastSeenInput : unsigned char
{
    Keyboard,
    Joystick,
};

// GLOBALS
extern bool CONTROL_Started;
extern bool CONTROL_MousePresent;
extern bool CONTROL_JoyPresent;
extern bool CONTROL_MouseEnabled;
extern bool CONTROL_JoystickEnabled;

extern uint64_t CONTROL_ButtonState;
extern uint64_t CONTROL_ButtonHeldState;

extern LastSeenInput CONTROL_LastSeenInput;

// PROTOTYPES
void CONTROL_MapKey( int32_t which, kb_scancode key1, kb_scancode key2 );
void CONTROL_MapButton(int whichfunction, int whichbutton, int doubleclicked, controldevice device);
void CONTROL_DefineFlag( int which, int toggle );
void CONTROL_ClearAssignments( void );
// void CONTROL_GetFunctionInput( void );
void CONTROL_GetInput( ControlInfo *info );
void CONTROL_ClearButton( int whichbutton );
void CONTROL_ClearAllButtons( void );
bool CONTROL_Startup(controltype which, int32_t ( *TimeFunction )( void ), int32_t ticspersecond);
void CONTROL_Shutdown( void );

void CONTROL_MapAnalogAxis(int whichaxis, int whichanalog);
void CONTROL_MapDigitalAxis(int32_t whichaxis, int32_t whichfunction, int32_t direction);
void CONTROL_SetAnalogAxisScale(int32_t whichaxis, int32_t axisscale, controldevice device);
void CONTROL_SetAnalogAxisSensitivity(int32_t whichaxis, float axissens, controldevice device);
void CONTROL_SetAnalogAxisInvert(int32_t whichaxis, int32_t invert);

void CONTROL_ScanForControllers(void);

//void CONTROL_PrintKeyMap(void);
//void CONTROL_PrintControlFlag(int32_t which);
//void CONTROL_PrintAxes( void );

////////// KEY/MOUSE BIND STUFF //////////

#define MAXBOUNDKEYS MAXKEYBOARDSCAN
#define MAXMOUSEBUTTONS 10

typedef struct ConsoleKeyBind
{
    const char *key;
    char *cmdstr;
    char repeat;
    char laststate;
} ConsoleKeyBind_t;

// Direct use DEPRECATED:
extern ConsoleKeyBind_t CONTROL_KeyBinds[MAXBOUNDKEYS+MAXMOUSEBUTTONS];
extern bool CONTROL_BindsEnabled;

void CONTROL_ClearAllBinds(void);
void CONTROL_BindKey(int i, char const * cmd, int repeat, char const * keyname);
void CONTROL_BindMouse(int i, char const * cmd, int repeat, char const * keyname);
void CONTROL_FreeKeyBind(int i);
void CONTROL_FreeMouseBind(int i);

static inline int CONTROL_KeyIsBound(int const key)
{
    auto &bind = CONTROL_KeyBinds[key];
    return bind.cmdstr && bind.key;
}

void CONTROL_ProcessBinds(void);

UserInput *CONTROL_GetUserInput(UserInput *);
void CONTROL_ClearUserInput(UserInput *);

////////////////////

#define CONTROL_NUM_FLAGS   64
extern int32_t CONTROL_ButtonFlags[CONTROL_NUM_FLAGS];

#ifdef __cplusplus
}
#endif
#endif


code:
#ifndef __joystick_h
#define __joystick_h

#include "compat.h"

#ifdef __cplusplus
extern "C" {
#endif

#if defined(GEKKO)
#define WII_A           0x00000001
#define WII_B           0x00000002
#define WII_1           0x00000004
#define WII_2           0x00000008
#define WII_MINUS       0x00000010
#define WII_PLUS        0x00000020
#define WII_HOME        0x00000040
#define WII_Z           0x00000080
#define WII_C           0x00000100
#define WII_X           0x00000200
#define WII_Y           0x00000400
#define WII_FULL_L      0x00000800
#define WII_FULL_R      0x00001000
#define WII_ZL          0x00002000
#define WII_ZR          0x00004000
#define WII_DPAD_UP     0x00008000
#define WII_DPAD_RIGHT  0x00010000
#define WII_DPAD_DOWN   0x00020000
#define WII_DPAD_LEFT   0x00040000
#endif

#define HAT_CENTERED    0x00
#define HAT_UP          0x01
#define HAT_RIGHT       0x02
#define HAT_DOWN        0x04
#define HAT_LEFT        0x08
#define HAT_RIGHTUP	    (HAT_RIGHT|HAT_UP)
#define HAT_RIGHTDOWN   (HAT_RIGHT|HAT_DOWN)
#define HAT_LEFTUP      (HAT_LEFT|HAT_UP)
#define HAT_LEFTDOWN    (HAT_LEFT|HAT_DOWN)

// KEEPINSYNC duke3d/src/gamedefs.h, build/src/sdlayer.cpp
#define MAXJOYBUTTONS 32
#define MAXJOYBUTTONSANDHATS (MAXJOYBUTTONS+4)

// Number of JOY axes
// KEEPINSYNC duke3d/src/gamedefs.h, build/src/sdlayer.cpp
#define MAXJOYAXES 9
#define MAXJOYDIGITAL (MAXJOYAXES*2)

int32_t	JOYSTICK_GetButtons( void );
int32_t	JOYSTICK_GetControllerButtons( void );
void	JOYSTICK_ClearAllButtons( void );
int32_t	JOYSTICK_GetHat( int32_t h );
void JOYSTICK_SetDeadZone(int32_t axis, uint16_t dead, uint16_t satur);

#ifdef __cplusplus
}
#endif
#endif /* __joystick_h */


code:
//-------------------------------------------------------------------------
/*
Copyright (C) 1996, 2003 - 3D Realms Entertainment

This file is part of Duke Nukem 3D version 1.5 - Atomic Edition

Duke Nukem 3D is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

Original Source: 1996 - Todd Replogle
Prepared for public release: 03/21/2003 - Charlie Wiederhold, 3D Realms
Modifications for JonoF's port by Jonathon Fowler (jf@jonof.id.au)
*/
//-------------------------------------------------------------------------

#pragma once

#ifndef keyboard_public_h_
#define keyboard_public_h_

#include "baselayer.h"	// for the keyboard stuff
#include "scancodes.h"

#ifdef __cplusplus
extern "C" {
#endif

typedef uint8_t kb_scancode;

// translation table for taking key names to scancodes and back again
static struct
{
    const char *key;
    kb_scancode sc;
} CONSTEXPR sctokeylut[] = {
    { "Escape", 0x1 },     { "1", 0x2 },       { "2", 0x3 },       { "3", 0x4 },      { "4", 0x5 },       { "5", 0x6 },       { "6", 0x7 },
    { "7", 0x8 },          { "8", 0x9 },       { "9", 0xa },       { "0", 0xb },      { "-", 0xc },       { "=", 0xd },       { "BakSpc", 0xe },
    { "Tab", 0xf },        { "Q", 0x10 },      { "W", 0x11 },      { "E", 0x12 },     { "R", 0x13 },      { "T", 0x14 },      { "Y", 0x15 },
    { "U", 0x16 },         { "I", 0x17 },      { "O", 0x18 },      { "P", 0x19 },     { "[", 0x1a },      { "]", 0x1b },      { "Enter", 0x1c },
    { "LCtrl", 0x1d },     { "A", 0x1e },      { "S", 0x1f },      { "D", 0x20 },     { "F", 0x21 },      { "G", 0x22 },      { "H", 0x23 },
    { "J", 0x24 },         { "K", 0x25 },      { "L", 0x26 },      { ";", 0x27 },     { "'", 0x28 },      { "`", 0x29 },      { "LShift", 0x2a },
    { "Backslash", 0x2b }, { "Z", 0x2c },      { "X", 0x2d },      { "C", 0x2e },     { "V", 0x2f },      { "B", 0x30 },      { "N", 0x31 },
    { "M", 0x32 },         { ",", 0x33 },      { ".", 0x34 },      { "/", 0x35 },     { "RShift", 0x36 }, { "Kpad*", 0x37 },  { "LAlt", 0x38 },
    { "Space", 0x39 },     { "CapLck", 0x3a }, { "F1", 0x3b },     { "F2", 0x3c },    { "F3", 0x3d },     { "F4", 0x3e },     { "F5", 0x3f },
    { "F6", 0x40 },        { "F7", 0x41 },     { "F8", 0x42 },     { "F9", 0x43 },    { "F10", 0x44 },    { "NumLck", 0x45 }, { "ScrLck", 0x46 },
    { "Kpad7", 0x47 },     { "Kpad8", 0x48 },  { "Kpad9", 0x49 },  { "Kpad-", 0x4a }, { "Kpad4", 0x4b },  { "Kpad5", 0x4c },  { "Kpad6", 0x4d },
    { "Kpad+", 0x4e },     { "Kpad1", 0x4f },  { "Kpad2", 0x50 },  { "Kpad3", 0x51 }, { "Kpad0", 0x52 },  { "Kpad.", 0x53 },  { "LessThan", 0x56 },
    { "F11", 0x57 },       { "F12", 0x58 },    { "KpdEnt", 0x9c }, { "RCtrl", 0x9d }, { "Kpad/", 0xb5 },  { "RAlt", 0xb8 },   { "PrtScn", 0xb7 },
    { "Pause", 0xc5 },     { "Home", 0xc7 },   { "Up", 0xc8 },     { "PgUp", 0xc9 },  { "Left", 0xcb },   { "Right", 0xcd },  { "End", 0xcf },
    { "Down", 0xd0 },      { "PgDn", 0xd1 },   { "Insert", 0xd2 }, { "Delete", 0xd3 },
};

#define MAXKEYBOARDSCAN  256

#define KB_KeyDown keystatus
extern kb_scancode KB_LastScan;

#define KB_GetLastScanCode() (KB_LastScan)
#define KB_SetLastScanCode(scancode) \
    {                                \
        KB_LastScan = (scancode);    \
    }
#define KB_ClearLastScanCode()       \
    {                                \
        KB_SetLastScanCode(sc_None); \
    }
#define KB_KeyPressed(scan) (keystatus[(scan)] != 0)
#define KB_ClearKeyDown(scan)      \
    {                              \
        keystatus[(scan)] = FALSE; \
    }
#define KB_UnBoundKeyPressed(scan) (keystatus[(scan)] != 0 && !CONTROL_KeyBinds[scan].cmdstr)
#define KB_GetCh keyGetChar
#define KB_KeyWaiting keyBufferWaiting
#define KB_FlushKeyboardQueue keyFlushChars
#define KB_FlushKeyboardQueueScans keyFlushScans

static inline void KB_ClearKeysDown(void)
{
    KB_LastScan = 0;
    Bmemset(keystatus, 0, sizeof(keystatus));
}

static inline void KB_KeyEvent(int32_t scancode, int32_t keypressed)
{
    if (keypressed)
        KB_LastScan = scancode;
}

static inline void KB_Startup(void) { keySetCallback(KB_KeyEvent); }
static inline void KB_Shutdown(void) { keySetCallback((void (*)(int32_t, int32_t))NULL); }
const char *  KB_ScanCodeToString( kb_scancode scancode ); // convert scancode into a string
kb_scancode KB_StringToScanCode( const char * string );  // convert a string into a scancode

#ifdef __cplusplus
}
#endif
#endif


code:
//-------------------------------------------------------------------------
/*
Copyright (C) 1996, 2003 - 3D Realms Entertainment

This file is part of Duke Nukem 3D version 1.5 - Atomic Edition

Duke Nukem 3D is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

Original Source: 1996 - Todd Replogle
Prepared for public release: 03/21/2003 - Charlie Wiederhold, 3D Realms
Modifications for JonoF's port by Jonathon Fowler (jf@jonof.id.au)
*/
//-------------------------------------------------------------------------

#pragma once

#ifndef mouse_h_
#define mouse_h_

#include "baselayer.h"

#ifdef __cplusplus
extern "C" {
#endif

enum MouseButtonFlags : uint8_t
{
    M_LEFTBUTTON   = 1,
    M_RIGHTBUTTON  = 2,
    M_MIDDLEBUTTON = 4,
    M_XBUTTON      = 8,
    M_WHEELUP      = 16,
    M_WHEELDOWN    = 32,
};

extern float   CONTROL_MouseSensitivity;
extern float   CONTROL_MouseAxesSensitivity[2];

static inline bool MOUSE_Startup(void)
{
    mouseInit();
    return ((inputdevices & DEV_MOUSE) == DEV_MOUSE);
}

static inline void    MOUSE_Shutdown(void)         { mouseUninit(); }
static inline int32_t MOUSE_GetButtons(void)       { return mouseReadButtons(); }
static inline void    MOUSE_ClearButton(int32_t b) { g_mouseBits &= ~b; }
static inline void    MOUSE_ClearAllButtons(void)  { g_mouseBits = 0; }

#ifdef __cplusplus
}
#endif
#endif /* __mouse_h */


code:
//-------------------------------------------------------------------------
/*
Copyright (C) 1996, 2003 - 3D Realms Entertainment

This file is part of Duke Nukem 3D version 1.5 - Atomic Edition

Duke Nukem 3D is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

Original Source: 1996 - Todd Replogle
Prepared for public release: 03/21/2003 - Charlie Wiederhold, 3D Realms
*/
//-------------------------------------------------------------------------

#pragma once

#ifndef scriplib_public_h_
#define scriplib_public_h_

#include <inttypes.h>

#ifdef __cplusplus
extern "C" {
#endif

int32_t     SCRIPT_Init(char const *name);
void        SCRIPT_Free(int32_t scripthandle);
int32_t     SCRIPT_Load(char const *filename);
void        SCRIPT_Save(int32_t scripthandle, char const *filename);
int32_t     SCRIPT_NumberSections(int32_t scripthandle);
char const *SCRIPT_Section(int32_t scripthandle, int32_t which);
int32_t     SCRIPT_NumberEntries(int32_t scripthandle, char const *sectionname);
char const *SCRIPT_Entry(int32_t scripthandle, char const *sectionname, int32_t which);
char const *SCRIPT_GetRaw(int32_t scripthandle, char const *sectionname, char const *entryname);
int32_t     SCRIPT_GetStringPtr(int32_t scripthandle, char const *sectionname, char const *entryname, char **dest);
int32_t     SCRIPT_GetString(int32_t scripthandle, char const *sectionname, char const *entryname, char *dest);
int32_t     SCRIPT_GetDoubleString(int32_t scripthandle, const char *sectionname, const char *entryname, char *dest1, char *dest2);
int32_t     SCRIPT_GetNumber(int32_t scripthandle, const char *sectionname, const char *entryname, int32_t *number);
int32_t     SCRIPT_GetBoolean(int32_t scripthandle, char const *sectionname, char const *entryname, int32_t *boole);
int32_t     SCRIPT_GetDouble(int32_t scripthandle, const char * sectionname, const char * entryname, double * number);
void        SCRIPT_PutSection(int32_t scripthandle, char const *sectionname);
void        SCRIPT_PutRaw(int32_t scripthandle, char const *sectionname, char const *entryname, char const *raw);
void        SCRIPT_PutString(int32_t scripthandle, char const *sectionname, char const *entryname, const char *string);
void        SCRIPT_PutDoubleString(int32_t scripthandle, const char *sectionname, const char *entryname, const char *string1, const char *string2);
void        SCRIPT_PutNumber(int32_t scripthandle, const char *sectionname, const char *entryname, int32_t number, int32_t hexadecimal, int32_t defaultvalue);
void        SCRIPT_PutBoolean(int32_t scripthandle, char const *sectionname, char const *entryname, int32_t boole);
void        SCRIPT_PutDouble(int32_t scripthandle, char const *sectionname, char const *entryname, double number, int32_t defaultvalue);

#ifdef __cplusplus
}
#endif
#endif


code:
//-------------------------------------------------------------------------
/*
Copyright (C) 1996, 2003 - 3D Realms Entertainment

This file is NOT part of Duke Nukem 3D version 1.5 - Atomic Edition
However, it is either an older version of a file that is, or is
some test code written during the development of Duke Nukem 3D.
This file is provided purely for educational interest.

Duke Nukem 3D is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

Prepared for public release: 03/21/2003 - Charlie Wiederhold, 3D Realms
Modifications for JonoF's port by Jonathon Fowler (jf@jonof.id.au)
*/
//-------------------------------------------------------------------------

#pragma once

#ifndef scriplib_private_h_
#define scriplib_private_h_

#include "compat.h"

#ifdef __cplusplus
extern "C" {
#endif

#define SCRIPTSECTIONSTART    ('[')
#define SCRIPTSECTIONEND      (']')
#define SCRIPTENTRYSEPARATOR  ('=')
#define SCRIPTCOMMENT         (';')
#define SCRIPTEOL             ('\n')
#define SCRIPTNULL            ('\0')
#define SCRIPTSTRINGSEPARATOR ('"')
#define SCRIPTHEXFIRST        ('0')
#define SCRIPTHEXSECOND       ('x')
#define SCRIPTSPACE           (' ')
#define SCRIPTDEFAULTVALUE    ('~')

#define MAXSCRIPTFILES 20
#define SCRIPT(scripthandle,item) (scriptfiles[(scripthandle)]->item)

typedef enum
{
    linetype_comment,
    linetype_section,
    linetype_entry
} linetype_t;

typedef struct scriptline
{
    int32_t            type;
    void *             ptr;
    struct scriptline *nextline;
    struct scriptline *prevline;
} ScriptLineType;

typedef struct scriptentry
{
    char *              name;
    char *              value;
    struct scriptentry *nextentry;
    struct scriptentry *preventry;
} ScriptEntryType;

typedef struct scriptsection
{
    char *                name;
    ScriptEntryType *     entries;
    ScriptLineType *      lastline;
    struct scriptsection *nextsection;
    struct scriptsection *prevsection;
} ScriptSectionType;

typedef struct
{
    ScriptSectionType *apScript;
    ScriptSectionType *lastsection;
    ScriptLineType *   scriptlines;
    char               scriptfilename[BMAX_PATH];
} script_t;

int32_t            SCRIPT_New(void);
void               SCRIPT_Delete(int32_t scripthandle);
void               SCRIPT_FreeSection(ScriptSectionType *section);
ScriptSectionType *SCRIPT_SectionExists(int32_t scripthandle, const char *sectionname);
ScriptSectionType *SCRIPT_AddSection(int32_t scripthandle, const char *sectionname);
ScriptEntryType *  SCRIPT_EntryExists(ScriptSectionType *section, const char *entryname);
void               SCRIPT_AddEntry(int32_t scripthandle, const char *sectionname, const char *entryname, const char *entryvalue);

#ifdef __cplusplus
}
#endif
#endif


code:
//-------------------------------------------------------------------------
/*
Copyright (C) 1996, 2003 - 3D Realms Entertainment

This file is part of Duke Nukem 3D version 1.5 - Atomic Edition

Duke Nukem 3D is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

Original Source: 1996 - Todd Replogle
Prepared for public release: 03/21/2003 - Charlie Wiederhold, 3D Realms
Modifications for JonoF's port by Jonathon Fowler (jf@jonof.id.au)
*/
//-------------------------------------------------------------------------

#include "compat.h"
#include "animlib.h"

//****************************************************************************
//
// LOCALS
//
//****************************************************************************

static anim_t * anim = NULL;

//****************************************************************************
//
//      findpage ()
//              - return the large page number a given frame resides in
//
//****************************************************************************

static inline uint16_t findpage(uint16_t framenumber)
{
    // curlpnum is initialized to 0xffff, obviously
    size_t i = anim->curlpnum & ~0xffff;
    size_t const nLps = anim->lpheader->nLps;
    bool j = true;

    if (framenumber < anim->currentframe)
        i = 0, j = false;

    // this scans the last used page and higher first and then scans the
    // previously accessed pages afterwards if it doesn't find anything
    do
    {
        for (; i < nLps; ++i)
        {
            lp_descriptor & lp = anim->LpArray[i];
            if (lp.baseRecord <= framenumber && framenumber < lp.baseRecord + lp.nRecords)
                return (uint16_t)i;
        }

        if (j && i == nLps)
        {
            // handle out of order pages... I don't think any Duke .ANM files
            // have them, but they're part of the file spec
            i = 0, j = false;
            continue;
        }

        break;
    }
    while (1);

    return (uint16_t)i;
}

//****************************************************************************
//
//      loadpage ()
//      - seek out and set pointers to the large page specified
//
//****************************************************************************

static inline void loadpage(uint16_t pagenumber, uint16_t **pagepointer)
{
    if (anim->curlpnum == pagenumber)
        return;

    anim->curlpnum = pagenumber;
    anim->curlp = &anim->LpArray[pagenumber];
    *pagepointer = (uint16_t *)(anim->buffer + 0xb00 + (pagenumber*IMAGEBUFFERSIZE) +
                                sizeof(lp_descriptor) + sizeof(uint16_t));
}

//****************************************************************************
//
//      decodeframe ()
//      - I found this less obfuscated version of the .ANM "decompressor",
//        (c) 1998 "Jari Komppa aka Sol/Trauma".  This code is public domain
//        but has been mostly rewritten by me.
//
//      - As a side note, it looks like this format came about in 1989 and
//        never went anywhere after that, and appears to have been the format
//        used by Electronic Arts' DeluxePaint Animation, which never made it
//        past version 1.0.
//
//****************************************************************************

static void decodeframe(uint8_t * srcP, uint8_t * dstP)
{
    do
    {
        {
            /* short op */
            uint8_t count = *srcP++;

            if (!count) /* short RLE */
            {
                uint8_t color = *(srcP+1);
                count = *(uint8_t *)srcP;
                srcP += sizeof(int16_t);
                Bmemset(dstP, color, count);
                dstP += count;
                continue;
            }
            else if ((count & 0x80) == 0) /* short copy */
            {
                Bmemcpy(dstP, srcP, count);
                dstP += count;
                srcP += count;
                continue;
            }
            else if ((count &= ~0x80) > 0) /* short skip */
            {
                dstP += count;
                continue;
            }
        }

        {
            /* long op */
            uint16_t count = B_LITTLE16(B_UNBUF16(srcP));
            srcP += sizeof(int16_t);

            if (!count) /* stop sign */
                return;
            else if ((count & 0x8000) == 0) /* long skip */
            {
                dstP += count;
                continue;
            }
            else if ((count &= ~0x8000) & 0x4000) /* long RLE */
            {
                uint8_t color = *srcP++;
                count &= ~0x4000;
                Bmemset(dstP, color, count);
                dstP += count;
                continue;
            }

            /* long copy */
            Bmemcpy(dstP, srcP, count);
            dstP += count;
            srcP += count;
        }
    }
    while (1);
}

//****************************************************************************
//
//      renderframe ()
//      - draw the frame sepcified from the large page in the buffer pointed to
//
//****************************************************************************

static void renderframe(uint16_t framenumber, uint16_t *pagepointer)
{
    uint16_t offset = 0;
    uint16_t frame = framenumber - anim->curlp->baseRecord;

    while (frame--) offset += B_LITTLE16(pagepointer[frame]);

    if (offset >= anim->curlp->nBytes)
        return;

    uint8_t *ppointer = (uint8_t *)(pagepointer) + anim->curlp->nRecords*2 + offset + 4;

    if ((ppointer-4)[1])
    {
        uint16_t const temp = B_LITTLE16(((uint16_t *)(ppointer-4))[1]);
        ppointer += temp + (temp & 1);
    }

    decodeframe((uint8_t *)ppointer, (uint8_t *)anim->imagebuffer);
}

//****************************************************************************
//
//      drawframe ()
//      - high level frame draw routine
//
//****************************************************************************

static inline void drawframe(uint16_t framenumber)
{
    loadpage(findpage(framenumber), &anim->thepage);
    renderframe(framenumber, anim->thepage);
}

// <length> is the file size, for consistency checking.
int32_t ANIM_LoadAnim(uint8_t *buffer, int32_t length)
{
    length -= sizeof(lpfileheader)+128+768;
    if (length < 0)
        return -1;

    anim = (anim_t *)Xrealloc(anim, sizeof(anim_t));

    anim->curlpnum = 0xffff;
    anim->currentframe = -1;

    // this just modifies the data in-place instead of copying it elsewhere now
    lpfileheader & lpheader = *(anim->lpheader = (lpfileheader *)(anim->buffer = buffer));

    lpheader.id              = B_LITTLE32(lpheader.id);
    lpheader.maxLps          = B_LITTLE16(lpheader.maxLps);
    lpheader.nLps            = B_LITTLE16(lpheader.nLps);
    lpheader.nRecords        = B_LITTLE32(lpheader.nRecords);
    lpheader.maxRecsPerLp    = B_LITTLE16(lpheader.maxRecsPerLp);
    lpheader.lpfTableOffset  = B_LITTLE16(lpheader.lpfTableOffset);
    lpheader.contentType     = B_LITTLE32(lpheader.contentType);
    lpheader.width           = B_LITTLE16(lpheader.width);
    lpheader.height          = B_LITTLE16(lpheader.height);
    lpheader.nFrames         = B_LITTLE32(lpheader.nFrames);
    lpheader.framesPerSecond = B_LITTLE16(lpheader.framesPerSecond);

    length -= lpheader.nLps * sizeof(lp_descriptor);
    if (length < 0)
        return -2;

    buffer += sizeof(lpfileheader)+128;

    // load the color palette
    for (uint8_t * pal = anim->pal, * pal_end = pal+768; pal < pal_end; pal += 3, buffer += 4)
    {
        pal[2] = buffer[0];
        pal[1] = buffer[1];
        pal[0] = buffer[2];
    }

    // set up large page descriptors
    anim->LpArray = (lp_descriptor *)buffer;

    // theoretically we should be able to play files with more than 256 frames now
    // assuming the utilities to create them can make them that way
    for (lp_descriptor * lp = anim->LpArray, * lp_end = lp+lpheader.nLps; lp < lp_end; ++lp)
    {
        lp->baseRecord = B_LITTLE16(lp->baseRecord);
        lp->nRecords   = B_LITTLE16(lp->nRecords);
        lp->nBytes     = B_LITTLE16(lp->nBytes);
    }

    return 0;
}

void ANIM_FreeAnim(void)
{
    DO_FREE_AND_NULL(anim);
}

int32_t ANIM_NumFrames(void)
{
    return anim->lpheader->nRecords;
}

uint8_t * ANIM_DrawFrame(int32_t framenumber)
{
    uint32_t cnt = anim->currentframe;

    // handle first play and looping or rewinding
    if (cnt > (uint32_t)framenumber)
        cnt = 0;

    do drawframe(cnt++);
    while (cnt < (uint32_t)framenumber);

    anim->currentframe = framenumber;
    return anim->imagebuffer;
}

uint8_t * ANIM_GetPalette(void)
{
    return anim->pal;
}


code:
/*
 * control.c
 * MACT library controller handling
 *
 * Derived from MACT386.LIB disassembly by Jonathon Fowler
 *
 */

#include "control.h"

#include "_control.h"
#include "baselayer.h"
#include "build.h"
#include "common.h"
#include "compat.h"
#include "joystick.h"
#include "keyboard.h"
#include "mouse.h"
#include "osd.h"
#include "pragmas.h"

#ifdef __ANDROID__
#include "android.h"
#endif

// TODO: add mact cvars and make this user configurable
#define USERINPUTDELAY 500
#define USERINPUTFASTDELAY 60

bool CONTROL_Started         = false;
bool CONTROL_MouseEnabled    = false;
bool CONTROL_MousePresent    = false;
bool CONTROL_JoyPresent      = false;
bool CONTROL_JoystickEnabled = false;

uint64_t CONTROL_ButtonState     = 0;
uint64_t CONTROL_ButtonHeldState = 0;

LastSeenInput CONTROL_LastSeenInput;

float CONTROL_MouseAxesSensitivity[2] = { DEFAULTMOUSESENSITIVITY, DEFAULTMOUSESENSITIVITY };
float CONTROL_MouseSensitivity     = DEFAULTMOUSESENSITIVITY;
float CONTROL_MouseSensitivityUnit = DEFAULTMOUSEUNIT;
float CONTROL_JoySensitivityUnit   = DEFAULTJOYUNIT;

static int32_t CONTROL_NumMouseButtons  = 0;
static int32_t CONTROL_NumJoyButtons    = 0;
static int32_t CONTROL_NumJoyAxes       = 0;

static ControlFunctionFlags_t CONTROL_Flags[CONTROL_NUM_FLAGS];

static ControlKeyMap_t CONTROL_KeyMapping[CONTROL_NUM_FLAGS];

static ControllerAxis_t joyAxes[MAXJOYAXES];

static ControlButtonState_t mouseButtons[MAXMOUSEBUTTONS];
static ControlButtonState_t joyButtons[MAXJOYBUTTONS];

static UserInputState_t userInput;

static int32_t (*ExtGetTime)(void);
static int32_t ticrate;
static uint8_t CONTROL_DoubleClickSpeed;

int32_t CONTROL_ButtonFlags[CONTROL_NUM_FLAGS];
ConsoleKeyBind_t CONTROL_KeyBinds[MAXBOUNDKEYS + MAXMOUSEBUTTONS];
bool CONTROL_BindsEnabled = 0;

#define CONTROL_CheckRange(which) ((unsigned)which >= (unsigned)CONTROL_NUM_FLAGS)
#define BIND(x, s, r, k) do { Xfree(x.cmdstr); x.cmdstr = s; x.repeat = r; x.key = k; } while (0)

void CONTROL_ClearAllBinds(void)
{
    for (int i=0; i<MAXBOUNDKEYS; i++)
        CONTROL_FreeKeyBind(i);
    for (int i=0; i<MAXMOUSEBUTTONS; i++)
        CONTROL_FreeMouseBind(i);
}

void CONTROL_BindKey(int i, char const * const cmd, int repeat, char const * const keyname)
{
    BIND(CONTROL_KeyBinds[i], Xstrdup(cmd), repeat, keyname);
}

void CONTROL_BindMouse(int i, char const * const cmd, int repeat, char const * const keyname)
{
    BIND(CONTROL_KeyBinds[MAXBOUNDKEYS + i], Xstrdup(cmd), repeat, keyname);
}

void CONTROL_FreeKeyBind(int i)
{
    BIND(CONTROL_KeyBinds[i], NULL, 0, NULL);
}

void CONTROL_FreeMouseBind(int i)
{
    BIND(CONTROL_KeyBinds[MAXBOUNDKEYS + i], NULL, 0, NULL);
}

static void controlUpdateMouseState(ControlInfo *const info)
{
    vec2_t input;
    mouseReadPos(&input.x, &input.y);

    vec2f_t finput = { input.x * CONTROL_MouseSensitivityUnit * CONTROL_MouseSensitivity * CONTROL_MouseAxesSensitivity[0],
                       input.y * CONTROL_MouseSensitivityUnit * CONTROL_MouseSensitivity * CONTROL_MouseAxesSensitivity[1] };

    info->mousex = Blrintf(clamp(finput.x, -MAXSCALEDCONTROLVALUE, MAXSCALEDCONTROLVALUE));
    info->mousey = Blrintf(clamp(finput.y, -MAXSCALEDCONTROLVALUE, MAXSCALEDCONTROLVALUE));
}

static int32_t controlGetTime(void)
{
    static int32_t t = 0;
    t += 5;
    return t;
}

static void controlSetFlag(int which, int active)
{
    if (CONTROL_CheckRange(which)) return;

    ControlFunctionFlags_t &flags = CONTROL_Flags[which];

    if (flags.toggle == INSTANT_ONOFF)
        flags.active = active;
    else if (active)
        flags.buttonheld = FALSE;
    else if (flags.buttonheld == FALSE)
    {
        flags.buttonheld = TRUE;
        flags.active = (flags.active ? FALSE : TRUE);
    }
}

static int32_t controlKeyboardFunctionPressed(int32_t which)
{
    if (CONTROL_CheckRange(which) || !CONTROL_Flags[which].used)
        return FALSE;

    int r = 0;
    auto &mapped = CONTROL_KeyMapping[which];

    if (mapped.keyPrimary != KEYUNDEFINED && !CONTROL_KeyBinds[mapped.keyPrimary].cmdstr)
        r = !!KB_KeyDown[mapped.keyPrimary];

    if (mapped.keySecondary != KEYUNDEFINED && !CONTROL_KeyBinds[mapped.keySecondary].cmdstr)
        r |= !!KB_KeyDown[mapped.keySecondary];

    return r;
}

#if 0
void CONTROL_ClearKeyboardFunction(int32_t which)
{
    if (CONTROL_CheckRange(which) || !CONTROL_Flags[which].used)
        return;

    auto &mapped = CONTROL_KeyMapping[which];

    if (mapped.key1 != KEYUNDEFINED)
        KB_KeyDown[mapped.key1] = 0;

    if (mapped.key2 != KEYUNDEFINED)
        KB_KeyDown[mapped.key2] = 0;
}
#endif

void CONTROL_DefineFlag(int which, int toggle)
{
    if (CONTROL_CheckRange(which)) return;

    ControlFunctionFlags_t &flags = CONTROL_Flags[which];

    flags.active     = FALSE;
    flags.buttonheld = FALSE;
    flags.cleared    = 0;
    flags.toggle     = toggle;
    flags.used       = TRUE;
}

void CONTROL_MapKey(int32_t which, kb_scancode key1, kb_scancode key2)
{
    if (CONTROL_CheckRange(which)) return;

    CONTROL_KeyMapping[which].keyPrimary = key1 ? key1 : KEYUNDEFINED;
    CONTROL_KeyMapping[which].keySecondary = key2 ? key2 : KEYUNDEFINED;
}

#if 0
void CONTROL_PrintKeyMap(void)
{
    int32_t i;

    for (i=0; i<CONTROL_NUM_FLAGS; i++)
    {
        initprintf("function %2d key1=%3x key2=%3x\n",
                   i, CONTROL_KeyMapping[i].key1, CONTROL_KeyMapping[i].key2);
    }
}

void CONTROL_PrintControlFlag(int32_t which)
{
    initprintf("function %2d active=%d used=%d toggle=%d buttonheld=%d cleared=%d\n",
               which, CONTROL_Flags[which].active, CONTROL_Flags[which].used,
               CONTROL_Flags[which].toggle, CONTROL_Flags[which].buttonheld,
               CONTROL_Flags[which].cleared);
}

void CONTROL_PrintAxes(void)
{
    int32_t i;

    initprintf("numjoyaxes=%d\n", CONTROL_NumJoyAxes);
    for (i=0; i<CONTROL_NumJoyAxes; i++)
    {
        initprintf("axis=%d analog=%d digital1=%d digital2=%d\n",
                   i, CONTROL_JoyAxesMap[i].analogmap,
                   CONTROL_JoyAxesMap[i].minmap, CONTROL_JoyAxesMap[i].maxmap);
    }
}
#endif

void CONTROL_MapButton(int whichfunction, int whichbutton, int doubleclicked, controldevice device)
{
    ControlButtonMap_t *set;

    if (CONTROL_CheckRange(whichfunction)) whichfunction = BUTTONUNDEFINED;

    switch (device)
    {
    case controldevice_mouse:
        if ((unsigned)whichbutton >= (unsigned)MAXMOUSEBUTTONS)
            return;
        set = &mouseButtons[whichbutton].mapping;
        break;

    case controldevice_joystick:
        if ((unsigned)whichbutton >= (unsigned)MAXJOYBUTTONS)
            return;
        set = &joyButtons[whichbutton].mapping;
        break;

    default:
        return;
    }

    if (doubleclicked)
        set->doubleclicked = whichfunction;
    else
        set->singleclicked = whichfunction;
}

void CONTROL_MapAnalogAxis(int whichaxis, int whichanalog)
{
    ControllerAxisMap_t &set = joyAxes[whichaxis].mapping;

    if ((unsigned)whichanalog >= (unsigned)analog_maxtype && whichanalog != -1)
        return;

    set.analogmap = whichanalog;
}

void JOYSTICK_SetDeadZone(int32_t axis, uint16_t dead, uint16_t satur)
{
    joyAxes[axis].deadzone = dead;
    joyAxes[axis].saturation = satur;
}

void CONTROL_SetAnalogAxisScale(int32_t whichaxis, int32_t axisscale, controldevice device)
{
    float *set;

    switch (device)
    {
    case controldevice_mouse:
        if ((unsigned) whichaxis >= ARRAY_SIZE(CONTROL_MouseAxesSensitivity))
            return;

        set = &CONTROL_MouseAxesSensitivity[whichaxis];
        break;

    case controldevice_joystick:
        if ((unsigned) whichaxis >= (unsigned) MAXJOYAXES)
            return;

        set = &joyAxes[whichaxis].sensitivity;
        break;

    default:
        return;
    }

    *set = (float)axisscale / 24576.f;
}

void CONTROL_SetAnalogAxisSensitivity(int32_t whichaxis, float axissens, controldevice device)
{
    float *set;

    switch (device)
    {
    case controldevice_mouse:
        if ((unsigned) whichaxis >= ARRAY_SIZE(CONTROL_MouseAxesSensitivity))
            return;

        set = &CONTROL_MouseAxesSensitivity[whichaxis];
        break;

    case controldevice_joystick:
        if ((unsigned) whichaxis >= (unsigned) MAXJOYAXES)
            return;

        set = &joyAxes[whichaxis].sensitivity;
        break;

    default:
        return;
    }

    *set = axissens;
}

void CONTROL_SetAnalogAxisInvert(int32_t whichaxis, int32_t invert)
{
    bool *set = &joyAxes[whichaxis].invert;
    *set = invert;
}

void CONTROL_MapDigitalAxis(int32_t whichaxis, int32_t whichfunction, int32_t direction)
{
    ControllerAxisMap_t &set = joyAxes[whichaxis].mapping;

    if (CONTROL_CheckRange(whichfunction)) whichfunction = AXISUNDEFINED;

    switch (direction)  	// JBF: this is all very much a guess. The ASM puzzles me.
    {
    case axis_up:
    case axis_left:
        set.minmap = whichfunction;
        break;
    case axis_down:
    case axis_right:
        set.maxmap = whichfunction;
        break;
    default:
        break;
    }
}

void CONTROL_ClearAssignments(void)
{
    memset(joyAxes, 0, sizeof(joyAxes));
    memset(joyButtons, 0, sizeof(joyButtons));

    for (auto &i : joyButtons)
    {
        i.mapping.doubleclicked = BUTTONUNDEFINED;
        i.mapping.singleclicked = BUTTONUNDEFINED;
    }

    memset(mouseButtons, 0, sizeof(mouseButtons));

    for (auto &i : mouseButtons)
    {
        i.mapping.doubleclicked = BUTTONUNDEFINED;
        i.mapping.singleclicked = BUTTONUNDEFINED;
    }

    memset(CONTROL_KeyMapping, KEYUNDEFINED, sizeof(CONTROL_KeyMapping));

    for (auto & i : CONTROL_MouseAxesSensitivity)
        i = DEFAULTMOUSESENSITIVITY;

    for (auto & i : joyAxes)
        i.sensitivity = DEFAULTAXISSENSITIVITY;
}

static int controlHandleClickStates(int32_t bits, int32_t tm, int32_t NumButtons, ControlButtonState_t *const b)
{
    int32_t i=NumButtons-1;
    int retval = 0;

    for (; i>=0; i--)
    {
        int const bs = (bits >> i) & 1;

        b[i].state  = bs;
        b[i].clickedState = FALSE;

        if (bs)
        {
            retval = 1;

            if (b[i].clicked == FALSE)
            {
                b[i].clicked = TRUE;

                if (b[i].clickedCount == 0 || tm > b[i].clickedTime)
                {
                    b[i].clickedTime  = tm + CONTROL_DoubleClickSpeed;
                    b[i].clickedCount = 1;
                }
                else if (tm < b[i].clickedTime)
                {
                    b[i].clickedState = TRUE;
                    b[i].clickedTime  = 0;
                    b[i].clickedCount = 2;
                }
            }
            else if (b[i].clickedCount == 2)
            {
                b[i].clickedState = TRUE;
            }

            continue;
        }

        if (b[i].clickedCount == 2)
            b[i].clickedCount = 0;

        b[i].clicked = FALSE;
    }

    return retval;
}

static void controlUpdateButtonStates(void)
{
    int32_t const t = ExtGetTime();

    if (CONTROL_MouseEnabled)
        controlHandleClickStates(MOUSE_GetButtons(), t, CONTROL_NumMouseButtons, mouseButtons);

    if (CONTROL_JoystickEnabled)
    {
        if (controlHandleClickStates(JOYSTICK_GetButtons(), t, CONTROL_NumJoyButtons, joyButtons))
            CONTROL_LastSeenInput = LastSeenInput::Joystick;
    }
}

static int controllerDigitizeAxis(int axis)
{
    ControllerAxisState_t &set     = joyAxes[axis].axis;
    ControllerAxisState_t &lastset = joyAxes[axis].last;

    set.digitalCleared = lastset.digitalCleared;

    if (set.analog > 0)
    {
        if (set.analog > DIGITALAXISANALOGTHRESHOLD || (set.analog > MINDIGITALAXISANALOGTHRESHOLD && lastset.digital == 1))
            set.digital = 1;
        else
            set.digitalCleared = 0;

        return 1;
    }
    else if (set.analog < 0)
    {
        if (set.analog < -DIGITALAXISANALOGTHRESHOLD || (set.analog < -MINDIGITALAXISANALOGTHRESHOLD && lastset.digital == -1))
            set.digital = -1;
        else
            set.digitalCleared = 0;

        return 1;
    }
    else
        set.digitalCleared = 0;

    return 0;
}

static inline int32_t joydist(int x, int y) { return ksqrt(x * x + y * y); }

static void controlUpdateAxisState(int index, ControlInfo *const info)
{
    int const  in  = joystick.pAxis[index];
    auto &     a   = joyAxes[index];
    auto const out = &a.axis;

    a.last = a.axis;
    *out = {};

    int axisScaled10k = klabs(in * 10000 / 32767);

    if (axisScaled10k >= a.saturation)
        out->analog = 32767 * ksgn(in);
    else
    {
        // this assumes there are two sticks comprised of axes 0 and 1, and 2 and 3... because when isGameController is true, there are
        if (index <= CONTROLLER_AXIS_LEFTY || (joystick.isGameController && (index <= CONTROLLER_AXIS_RIGHTY)))
            axisScaled10k = min(10000, joydist(joystick.pAxis[index & ~1], joystick.pAxis[index | 1]) * 10000 / 32767);

        if (axisScaled10k < a.deadzone)
            out->analog = 0;
        else
            out->analog = in * (axisScaled10k - a.deadzone) / a.saturation;
    }

    if (controllerDigitizeAxis(index))
        CONTROL_LastSeenInput = LastSeenInput::Joystick;

    int const invert = !!a.invert;
    int const clamped = Blrintf(clamp<float>(a.axis.analog * CONTROL_JoySensitivityUnit * a.sensitivity, -MAXSCALEDCONTROLVALUE, MAXSCALEDCONTROLVALUE));
    a.axis.analog  = (clamped ^ -invert) + invert;

    switch (a.mapping.analogmap)
    {
        case analog_turning:          info->dyaw   += a.axis.analog; break;
        case analog_strafing:         info->dx     += a.axis.analog; break;
        case analog_lookingupanddown: info->dpitch += a.axis.analog; break;
        case analog_elevation:        info->dy     += a.axis.analog; break;
        case analog_rolling:          info->droll  += a.axis.analog; break;
        case analog_moving:           info->dz     += a.axis.analog; break;
        default: break;
    }
}

static void controlPollDevices(ControlInfo *const info)
{
    memset(info, 0, sizeof(ControlInfo));
    handleevents();

#ifdef __ANDROID__
    CONTROL_Android_PollDevices(info);
#endif

    if (CONTROL_MouseEnabled)
        controlUpdateMouseState(info);

    if (CONTROL_JoystickEnabled)
    {
        for (int i=joystick.numAxes-1; i>=0; i--)
            controlUpdateAxisState(i, info);
    }

    controlUpdateButtonStates();
}

static void controlUpdateFlagsFromAxes(int32_t *const p1)
{
    if (CONTROL_NumJoyAxes)
    {
        int axis = CONTROL_NumJoyAxes - 1;
        int retval = 0;

        do
        {
            auto &a = joyAxes[axis];
            if (!a.axis.digital)
                continue;

            int const j = (a.axis.digital < 0) ? a.mapping.minmap : a.mapping.maxmap;

            if (j != AXISUNDEFINED)
            {
                p1[j] = 1;
                retval = 1;
            }
        }
        while (axis--);

        if (retval)
            CONTROL_LastSeenInput = LastSeenInput::Joystick;
    }
}

static void controlUpdateFlagsFromButtons(int32_t *const p1)
{
    if (CONTROL_NumMouseButtons)
    {
        int i = CONTROL_NumMouseButtons-1, j;

        do
        {
            if (!CONTROL_KeyBinds[MAXBOUNDKEYS + i].cmdstr)
            {
                j = mouseButtons[i].mapping.doubleclicked;
                if (j != KEYUNDEFINED)
                    p1[j] |= mouseButtons[i].clickedState;

                j = mouseButtons[i].mapping.singleclicked;
                if (j != KEYUNDEFINED)
                    p1[j] |= mouseButtons[i].state;
            }

            if (!CONTROL_BindsEnabled)
                continue;

            if (CONTROL_KeyBinds[MAXBOUNDKEYS + i].cmdstr && mouseButtons[i].state)
            {
                if (CONTROL_KeyBinds[MAXBOUNDKEYS + i].repeat || (CONTROL_KeyBinds[MAXBOUNDKEYS + i].laststate == 0))
                    OSD_Dispatch(CONTROL_KeyBinds[MAXBOUNDKEYS + i].cmdstr, true);
            }
            CONTROL_KeyBinds[MAXBOUNDKEYS + i].laststate = mouseButtons[i].state;
        }
        while (i--);
    }

    if (CONTROL_NumJoyButtons)
    {
        int i=CONTROL_NumJoyButtons-1, j;
        int retval = 0;

        do
        {
            j = joyButtons[i].mapping.doubleclicked;
            if (j != KEYUNDEFINED)
            {
                auto const state = joyButtons[i].clickedState;
                p1[j] |= state;
                retval |= state;
            }

            j = joyButtons[i].mapping.singleclicked;
            if (j != KEYUNDEFINED)
            {
                auto const state = joyButtons[i].state;
                p1[j] |= state;
                retval |= state;
            }
        }
        while (i--);

        if (retval)
            CONTROL_LastSeenInput = LastSeenInput::Joystick;
    }
}

void CONTROL_ClearButton(int whichbutton)
{
    if (CONTROL_CheckRange(whichbutton)) return;

#ifdef __ANDROID__
    CONTROL_Android_ClearButton(whichbutton);
#endif

    BUTTONCLEAR(whichbutton);
    CONTROL_Flags[whichbutton].cleared = TRUE;
}

void CONTROL_ClearAllButtons(void)
{
    CONTROL_ButtonHeldState = 0;
    CONTROL_ButtonState = 0;

    for (auto & c : CONTROL_Flags)
        c.cleared = TRUE;
}

void CONTROL_ProcessBinds(void)
{
    if (!CONTROL_BindsEnabled)
        return;

    int i = MAXBOUNDKEYS-1;

    do
    {
        if (CONTROL_KeyBinds[i].cmdstr)
        {
            auto const keyPressed = KB_KeyPressed(i);

            if (keyPressed && (CONTROL_KeyBinds[i].repeat || (CONTROL_KeyBinds[i].laststate == 0)))
            {
                CONTROL_LastSeenInput = LastSeenInput::Keyboard;
                OSD_Dispatch(CONTROL_KeyBinds[i].cmdstr, true);
            }

            CONTROL_KeyBinds[i].laststate = keyPressed;
        }
    }
    while (i--);
}

static void controlUpdateGameFunctions(void)
{
    controlUpdateFlagsFromButtons(CONTROL_ButtonFlags);
    controlUpdateFlagsFromAxes(CONTROL_ButtonFlags);

    CONTROL_ButtonHeldState = CONTROL_ButtonState;
    CONTROL_ButtonState = 0;

    int i = CONTROL_NUM_FLAGS-1;

    do
    {
        controlSetFlag(i, controlKeyboardFunctionPressed(i) | CONTROL_ButtonFlags[i]);

        if (CONTROL_Flags[i].cleared == FALSE) BUTTONSET(i, CONTROL_Flags[i].active);
        else if (CONTROL_Flags[i].active == FALSE) CONTROL_Flags[i].cleared = 0;
    }
    while (i--);

    memset(CONTROL_ButtonFlags, 0, sizeof(CONTROL_ButtonFlags));
}

void CONTROL_GetInput(ControlInfo *info)
{
#ifdef __ANDROID__
    CONTROL_Android_PollDevices(info);
#endif
    controlPollDevices(info);
    controlUpdateGameFunctions();
    inputchecked = 1;
}

static void CONTROL_ResetJoystickValues()
{
    CONTROL_NumJoyAxes      = min(MAXJOYAXES, joystick.numAxes);
    CONTROL_NumJoyButtons   = min(MAXJOYBUTTONS, joystick.numButtons + 4 * (joystick.numHats > 0));
    CONTROL_JoystickEnabled = CONTROL_JoyPresent = !!((inputdevices & DEV_JOYSTICK) >> 2);
}

void CONTROL_ScanForControllers()
{
    joyScanDevices();
    CONTROL_ResetJoystickValues();
}

bool CONTROL_Startup(controltype which, int32_t(*TimeFunction)(void), int32_t ticspersecond)
{
    UNREFERENCED_PARAMETER(which);

    if (CONTROL_Started) return false;

    static osdcvardata_t cvars_mact [] =
    {
        { "in_mousexsens", "horizontal mouse sensitivity multiplier", (void *)&CONTROL_MouseAxesSensitivity[0], CVAR_FLOAT, 0, 100 },
        { "in_mouseysens", "vertical mouse sensitivity multiplier",   (void *)&CONTROL_MouseAxesSensitivity[1], CVAR_FLOAT, 0, 100 },
        { "in_mouseunit",  "base mouse input unit",                   (void *)&CONTROL_MouseSensitivityUnit,    CVAR_FLOAT, 0, 1 },
        { "in_joyunit",    "base controller input unit",              (void *)&CONTROL_JoySensitivityUnit,      CVAR_FLOAT, 0, 1 },
        { "sensitivity",   "master mouse sensitivity multiplier",     (void *)&CONTROL_MouseSensitivity,        CVAR_FLOAT, 0, 100 },
    };

    for (auto& cv : cvars_mact)
        OSD_RegisterCvar(&cv, osdcmd_cvar_set);

    ExtGetTime = TimeFunction ? TimeFunction : controlGetTime;

    // what the fuck???
    ticrate = ticspersecond;
    CONTROL_DoubleClickSpeed = (ticspersecond * 57) / 100;

    if (CONTROL_DoubleClickSpeed <= 0)
        CONTROL_DoubleClickSpeed = 1;

    if (initinput(CONTROL_ScanForControllers))
        return true;

    KB_Startup();

    CONTROL_NumMouseButtons = MAXMOUSEBUTTONS;
    CONTROL_MousePresent    = MOUSE_Startup();

    if (!(CONTROL_MouseEnabled = CONTROL_MousePresent))
        DVLOG_F(LOG_INPUT, "No mice found.");

    CONTROL_ResetJoystickValues();

#ifdef GEKKO
    if (!CONTROL_JoyPresent)
        DVLOG_F(LOG_INPUT, "No controllers found.");
#endif

    CONTROL_ButtonState     = 0;
    CONTROL_ButtonHeldState = 0;

    for (auto & CONTROL_Flag : CONTROL_Flags)
        CONTROL_Flag.used = FALSE;

    CONTROL_Started = TRUE;

    return false;
}

void CONTROL_Shutdown(void)
{
    if (!CONTROL_Started)
        return;

    CONTROL_ClearAllBinds();

    MOUSE_Shutdown();
    uninitinput();

    CONTROL_Started = FALSE;
}

// temporary hack until input is unified

#define SCALEAXIS(x) (joyAxes[CONTROLLER_AXIS_ ## x].axis.analog * 10000 / 32767)
#define SATU(x) (joyAxes[CONTROLLER_AXIS_ ## x].saturation)

UserInput *CONTROL_GetUserInput(UserInput *info)
{
    if (info == nullptr)
        info = &userInput.local;

    direction newdir = dir_None;

    if ((joyAxes[CONTROLLER_AXIS_LEFTY].axis.digital == -1 && SCALEAXIS(LEFTY) <= -SATU(LEFTY))
        || (JOYSTICK_GetControllerButtons() & (1 << CONTROLLER_BUTTON_DPAD_UP)))
        newdir = dir_Up;
    else if ((joyAxes[CONTROLLER_AXIS_LEFTY].axis.digital == 1 && SCALEAXIS(LEFTY) >= SATU(LEFTY))
                || (JOYSTICK_GetControllerButtons() & (1 << CONTROLLER_BUTTON_DPAD_DOWN)))
        newdir = dir_Down;
    else if ((joyAxes[CONTROLLER_AXIS_LEFTX].axis.digital == -1 && SCALEAXIS(LEFTX) <= -SATU(LEFTX))
                || (JOYSTICK_GetControllerButtons() & (1 << CONTROLLER_BUTTON_DPAD_LEFT)))
        newdir = dir_Left;
    else if ((joyAxes[CONTROLLER_AXIS_LEFTX].axis.digital == 1 && SCALEAXIS(LEFTX) >= SATU(LEFTX))
                || (JOYSTICK_GetControllerButtons() & (1 << CONTROLLER_BUTTON_DPAD_RIGHT)))
        newdir = dir_Right;

    // allow the user to press the dpad as fast as they like without being rate limited
    if (newdir == dir_None)
    {
        userInput.clock = -1;
        userInput.repeat = dir_None;
    }

    info->dir = (ExtGetTime() >= userInput.clock) ? newdir : dir_None;

    if (KB_KeyDown[sc_kpad_8] || KB_KeyDown[sc_UpArrow])
        info->dir = dir_Up;
    else if (KB_KeyDown[sc_kpad_2] || KB_KeyDown[sc_DownArrow])
        info->dir = dir_Down;
    else if (KB_KeyDown[sc_kpad_4] || KB_KeyDown[sc_LeftArrow])
        info->dir = dir_Left;
    else if (KB_KeyDown[sc_kpad_6] || KB_KeyDown[sc_RightArrow])
        info->dir = dir_Right;

    info->b_advance = KB_KeyPressed(sc_Enter) || KB_KeyPressed(sc_kpad_Enter) || (MOUSE_GetButtons() & M_LEFTBUTTON)
                    || (JOYSTICK_GetControllerButtons() & (1 << CONTROLLER_BUTTON_A));
    info->b_return   = KB_KeyPressed(sc_Escape) || (MOUSE_GetButtons() & M_RIGHTBUTTON) || (JOYSTICK_GetControllerButtons() & (1 << CONTROLLER_BUTTON_B));
    info->b_escape = KB_KeyPressed(sc_Escape) || (JOYSTICK_GetControllerButtons() & (1 << CONTROLLER_BUTTON_START));

#if defined(GEKKO)
    if (JOYSTICK_GetButtons()&(WII_A))
        info->b_advance = true;

    if (JOYSTICK_GetButtons()&(WII_B|WII_HOME))
        info->b_return = true;

    if (JOYSTICK_GetButtons() & WII_HOME)
        info->b_escape = true;
#endif

    if (userInput.buttonCleared[1])
    {
        if (!info->b_advance)
            userInput.buttonCleared[1] = false;
        else
            info->b_advance = false;
    }

    if (userInput.buttonCleared[2])
    {
        if (!info->b_return)
            userInput.buttonCleared[2] = false;
        else
            info->b_return = false;
    }

    if (userInput.buttonCleared[3])
    {
        if (!info->b_escape)
            userInput.buttonCleared[3] = false;
        else
            info->b_escape = false;
    }

    return info;
}

#undef SCALEAXIS
#undef SATU

void CONTROL_ClearUserInput(UserInput * info)
{
    if (info == nullptr)
        info = &userInput.local;

    // for keyboard keys we want the OS repeat rate, so just clear them
    KB_ClearKeyDown(sc_UpArrow);
    KB_ClearKeyDown(sc_kpad_8);
    KB_ClearKeyDown(sc_DownArrow);
    KB_ClearKeyDown(sc_kpad_2);
    KB_ClearKeyDown(sc_LeftArrow);
    KB_ClearKeyDown(sc_kpad_4);
    KB_ClearKeyDown(sc_RightArrow);
    KB_ClearKeyDown(sc_kpad_6);

    // the OS doesn't handle repeat for joystick inputs so we have to do it ourselves
    if (info->dir != dir_None)
    {
        auto const clk = ExtGetTime();

        if (userInput.repeat == info->dir)
            userInput.clock = clk + ((ticrate * USERINPUTFASTDELAY) / 1000);
        else
        {
            userInput.repeat = info->dir;
            userInput.clock = clk + ((ticrate * USERINPUTDELAY) / 1000);
        }

        userInput.buttonCleared[0] = true;
    }

    if (info->b_advance)
    {
        KB_ClearKeyDown(sc_kpad_Enter);
        KB_ClearKeyDown(sc_Enter);
        MOUSE_ClearButton(M_LEFTBUTTON);
        userInput.buttonCleared[1] = true;
    }

    if (info->b_return)
    {
        KB_ClearKeyDown(sc_Escape);
        MOUSE_ClearButton(M_RIGHTBUTTON);
        userInput.buttonCleared[2] = true;
    }

    if (info->b_escape)
    {
        KB_ClearKeyDown(sc_Escape);
        userInput.buttonCleared[3] = true;
    }
    inputchecked = 1;
}


code:
/*
 * joystick.c
 * MACT library -to- Build Port Joystick Glue
 *
 * by Hendricks266
 *
 * We needed raw joystick access for the Wii port.
 * We only had raw mouse and keyboard access.
 * I made raw joystick access.
 *
 */
//-------------------------------------------------------------------------
/*
Duke Nukem Copyright (C) 1996, 2003 3D Realms Entertainment

This file is part of Duke Nukem 3D version 1.5 - Atomic Edition

Duke Nukem 3D is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
//-------------------------------------------------------------------------

#include "compat.h"

#include "joystick.h"
#include "baselayer.h"

#include "keyboard.h"
#include "_control.h"

int32_t JOYSTICK_GetButtons(void)
{
    int32_t buttons;

    joyReadButtons(&buttons);

    if (joystick.numHats > 0)
    {
        int32_t hat = JOYSTICK_GetHat(0);
        if (hat != 0)
            buttons |= hat << min(MAXJOYBUTTONS, joystick.numButtons);
    }

    return buttons;
}
int32_t JOYSTICK_GetControllerButtons(void)
{
    if (!joystick.isGameController)
        return 0;

    int32_t buttons;
    joyReadButtons(&buttons);
    return buttons;
}

void JOYSTICK_ClearAllButtons(void)
{
    joystick.bits = 0;
}

int32_t JOYSTICK_GetHat(int32_t h)
{
    if (h>=0 && h<joystick.numHats)
    {
        if (joystick.pHat[h] == -1)
            return (HAT_CENTERED);
        else
        {
            static const int32_t hatstate[] = { HAT_UP, HAT_RIGHTUP, HAT_RIGHT, HAT_RIGHTDOWN, HAT_DOWN, HAT_LEFTDOWN, HAT_LEFT, HAT_LEFTUP };
            int32_t val;

            // thanks SDL for this much more sensible method
            val = ((joystick.pHat[0] + 4500 / 2) % 36000) / 4500;
            if (val < 8)
                return hatstate[val];
        }
    }
    return 0;
}


code:
/*
 * keyboard.c
 * MACT library -to- JonoF's Build Port Keyboard Glue
 *
 * by Jonathon Fowler
 *
 * Since we don't have the source to the MACT library I've had to
 * concoct some magic to glue its idea of controllers into that of
 * my Build port.
 *
 */
//-------------------------------------------------------------------------
/*
Duke Nukem Copyright (C) 1996, 2003 3D Realms Entertainment

This file is part of Duke Nukem 3D version 1.5 - Atomic Edition

Duke Nukem 3D is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
//-------------------------------------------------------------------------

#include "compat.h"

#include "keyboard.h"
#include "control.h"

kb_scancode KB_LastScan;

// this is horrible!
const char *KB_ScanCodeToString(kb_scancode scancode)
{
    for (auto &s : sctokeylut)
        if (s.sc == scancode)
            return s.key;

    return "";
}

kb_scancode KB_StringToScanCode(const char * string)
{
    for (auto &s : sctokeylut)
        if (!Bstrcasecmp(s.key, string))
            return s.sc;

    return 0;
}