summaryrefslogtreecommitdiff
path: root/src/Noddybox.Emulation.Xna.Input/Joystick/JoystickDriver.cs
blob: 7e96df66ea9b0806333e112790a284ee8f8ef169 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
// This file is part of the Noddybox.Emulation C# suite.
//
// Noddybox.Emulation 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 3 of the License, or
// (at your option) any later version.
//
// Noddybox.Emulation 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 Noddybox.Emulation.  If not, see <http://www.gnu.org/licenses/>.
//
// Copyright (c) 2012 Ian Cowburn
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input.Touch;

namespace Noddybox.Emulation.Xna.Input.Joystick
{
    /// <summary>
    /// Displays and drives the joystick.  Unlike the keyboard this is not
    /// not done event driven, but as a clasic Joystick interface.
    /// </summary>
    public class JoystickDriver
    {
        #region Event arguments

        /// <summary>
        /// Event data when the digital joystick state changes
        /// </summary>
        public class DigitalJoystickEventArgs : EventArgs
        {
            /// <summary>
            /// The joystick state.
            /// </summary>
            public DigitalJoystickState State {get; private set;}

            public bool[] Buttons {get; private set;}

            public DigitalJoystickEventArgs(DigitalJoystickState state, bool[] buttons)
            {
                State = state;
                Buttons = buttons;
            }
        }

        /// <summary>
        /// Event data when the analogue joystick state changes
        /// </summary>
        public class AnalogueJoystickEventArgs : EventArgs
        {
            /// <summary>
            /// The joystick state.
            /// </summary>
            public Vector2 State {get; private set;}

            public bool[] Buttons {get; private set;}

            public AnalogueJoystickEventArgs(Vector2 state, bool[] buttons)
            {
                State = state;
                Buttons = buttons;
            }
        }

        #endregion

        #region Private data

        private InputManager manager;
        private bool subscribed;
        private JoystickType joystickType;

        private Texture2D backgroundImage;
        private Texture2D joystickImage;
        private Texture2D buttonImage;

        private DigitalJoystickState digital;
        private Vector2 analogue;
        private Vector2 contact;
        private int stickId;
        private bool[] button;
        private int[] buttonId;

        private Vector2 backgroundPosition;
        private Vector2 joystickPosition;
        private Vector2[] buttonPositions;
        private float deadzone;
        private bool deadzoneBreached;
        private float stickSize;
        private int numButtons;

        private Vector2 joystickOffset;
        private Vector2 buttonOffset;
        private int joystickSize;
        private int buttonSize;

        private JoystickLock joylock;

        private Vector2[] digitalPositions;
        private DigitalJoystickState[] digitalAngles;

        #endregion

        #region Private members

        /// <summary>
        /// Update the analogue position with the passed state.  This also applies the joylock clamp.
        /// </summary>
        /// <param name="v">The touch screen location.</param>
        /// <returns>True if the state was changed.</returns>
        private bool UpdatePosition(Vector2 v)
        {
            v -= contact;

            switch(joylock)
            {
                case JoystickLock.TwoWayVertical:
                    v.X = 0;
                    break;

                case JoystickLock.TwoWayHorizontal:
                    v.Y = 0;
                    break;

                case JoystickLock.FourWay:
                    if (Math.Abs(v.Y) > Math.Abs(v.X))
                    {
                        v.X = 0;
                    }
                    else
                    {
                        v.Y = 0;
                    }
                    break;

                case JoystickLock.EightWay:
                    break;
            }

            if (v.Length() > stickSize)
            {
                v.Normalize();
                v *= stickSize;
            }

            if (v != analogue)
            {
                analogue = v;
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// Update the digital position with the new analogue state.
        /// </summary>
        /// <param name="v"></param>
        /// <returns>True if the state was changed.</returns>
        private bool UpdatePosition()
        {
            DigitalJoystickState newState = DigitalJoystickState.Centre;

            if (analogue.Length() > deadzone)
            {
                float angle = MathHelper.ToDegrees((float)Math.Atan2(analogue.Y, analogue.X)) + 22.5f;

                while (angle < 0)
                {
                    angle += 360;
                }

                System.Diagnostics.Debug.WriteLine("original angle = {0}", angle);

                angle = Math.Min(angle / 45, 7);

                newState = digitalAngles[(int)angle];
                System.Diagnostics.Debug.WriteLine("calced angle = {0} / {1}", angle, newState);
            }

            if (newState != digital)
            {
                digital = newState;
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// Updates the joystick.
        /// </summary>
        private void TouchScreenHandler(object sender, InputManager.TouchLocationEventArgs e)
        {
            bool stateChanged = false;

            // Handle release of stick or buttons
            //
            if (e.Location.State == TouchLocationState.Released)
            {
                if (stickId == e.Location.Id)
                {
                    stickId = 0;
                    digital = DigitalJoystickState.Centre;
                    analogue = Vector2.Zero;
                    stateChanged = true;
                    e.Handled = true;
                }
                else
                {
                    for(int f = 0; !e.Handled && f < numButtons; f++)
                    {
                        if (buttonId[f] == e.Location.Id)
                        {
                            buttonId[f] = 0;
                            button[f] = false;
                            stateChanged = true;
                            e.Handled = true;
                        }
                    }
                }
            }

            // Handle hold of stick
            //
            if (e.Location.State == TouchLocationState.Moved && e.Location.Id == stickId)
            {
                e.Handled = true;

                if (!deadzoneBreached)
                {
                    float l = (contact - e.Location.Position).Length();

                    if (l > deadzone)
                    {
                        deadzoneBreached = true;
                    }
                }

                if (joystickType == JoystickType.Digital && deadzoneBreached && UpdatePosition(e.Location.Position))
                {
                    stateChanged = UpdatePosition();
                }
                else if (joystickType == JoystickType.Analogue && deadzoneBreached)
                {
                    stateChanged = UpdatePosition(e.Location.Position);
                }
            }

            // Handle touch of stick or buttons
            //
            if (e.Location.State == TouchLocationState.Pressed)
            {
                float l = (joystickPosition - e.Location.Position).Length();

                if (l < joystickSize)
                {
                    contact = e.Location.Position;
                    stickId = e.Location.Id;
                    deadzoneBreached = false;
                    e.Handled = true;
                }
                else
                {
                    for(int f = 0; !e.Handled && f < numButtons; f++)
                    {
                        if ((buttonPositions[f] - e.Location.Position).Length() < buttonSize)
                        {
                            e.Handled = true;
                            button[f] = true;
                            buttonId[f] = e.Location.Id;
                            stateChanged = true;
                        }
                    }
                }
            }

            if (stateChanged && joystickType == JoystickType.Digital && DigitalEvent != null)
            {
                DigitalEvent(this, new DigitalJoystickEventArgs(digital, button));
            }
            else if (stateChanged && joystickType == JoystickType.Analogue && AnalogueEvent != null)
            {
                AnalogueEvent(this, new AnalogueJoystickEventArgs(analogue, button));
            }
        }

        #endregion

        #region Public members

        /// <summary>
        /// Set the type of joystick lock.
        /// </summary>
        public JoystickLock LockType {set {joylock = value;}}


        /// <summary>
        /// Stops consuming inputs and resets joystick and fire buttons.
        /// </summary>
        /// <param name="generateEvents">Generates events for cleared state.</param>
        public void StopJoytstickUpdates(bool generateEvents)
        {
            if (subscribed)
            {
                manager.TouchEvent -= TouchScreenHandler;
                subscribed = false;

                digital = DigitalJoystickState.Centre;
                analogue = Vector2.Zero;
                stickId = 0;
                deadzoneBreached = false;
                
                for(int f = 0; f < numButtons; f++)
                {
                    button[f] = false;
                    buttonId[f] = 0;
                }

                if (generateEvents && joystickType == JoystickType.Digital && DigitalEvent != null)
                {
                    DigitalEvent(this, new DigitalJoystickEventArgs(digital, button));
                }
                else if (generateEvents && joystickType == JoystickType.Analogue && AnalogueEvent != null)
                {
                    AnalogueEvent(this, new AnalogueJoystickEventArgs(analogue, button));
                }
            }
        }

        /// <summary>
        /// Stops consuming inputs and resets joystick and fire buttons.  Generates events for the cleared state.
        /// </summary>
        public void StopJoystickUpdates()
        {
            StopJoytstickUpdates(true);
        }

        /// <summary>
        /// Starts consuming inputs.
        /// </summary>
        public void StartJoystickUpdates()
        {
            if (!subscribed)
            {
                manager.TouchEvent += TouchScreenHandler;
                subscribed = true;
            }
        }

        /// <summary>
        /// Draw the joystick
        /// </summary>
        /// <param name="spriteBatch"></param>
        public void Draw(SpriteBatch spriteBatch)
        {
            spriteBatch.Draw(backgroundImage, backgroundPosition, Color.White);

            if (joystickType == JoystickType.Digital)
            {
                spriteBatch.Draw(joystickImage, joystickPosition + digitalPositions[(int)digital],
                                 null, Color.White, 0f, joystickOffset, 1f, SpriteEffects.None, 0f);
            }
            else
            {
                spriteBatch.Draw(joystickImage, joystickPosition + analogue,
                                 null, Color.White, 0f, joystickOffset, 1f, SpriteEffects.None, 0f);
            }

            for(int f = 0; f < numButtons; f++)
            {
                spriteBatch.Draw(buttonImage, buttonPositions[f],
                                    null, button[f] ? Color.LightGray : Color.White, 0f, buttonOffset, button[f] ? 0.9f : 1f, SpriteEffects.None, 0f);
            }
        }

        #endregion

        #region Events

        public EventHandler<DigitalJoystickEventArgs> DigitalEvent;

        public EventHandler<AnalogueJoystickEventArgs> AnalogueEvent;

        #endregion

        #region Constructors

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="manager">The input manager to attach to.</param>
        /// <param name="graphics">The graphics device to associate textures with.</param>
        /// <param name="joystickType">The type of joystick.</param>
        /// <param name="backgroundImage">The image for the joystick background.</param>
        /// <param name="joystickImage">The image for the joystick knob.</param>
        /// <param name="buttonImage">The image for a joystick button.</param>
        /// <param name="backgroundPosition">Where to draw and offset the joystick background to.</param>
        /// <param name="joystickPosition">Where to centre the joystick. Note this is absolute.</param>
        /// <param name="buttonPositions">Positions for the buttons.</param>
        /// <param name="deadzone">Deadzone radius where joystick movement is not picked up.</param>
        /// <param name="stickSize">The maximum radius that the joystick can move.</param>
        public JoystickDriver(InputManager manager, GraphicsDevice graphics, JoystickType joystickType,
                              Texture2D backgroundImage, Texture2D joystickImage, Texture2D buttonImage,
                              Vector2 backgroundPosition, Vector2 joystickPosition, Vector2[] buttonPositions,
                              float deadzone, float stickSize)
        {
            this.manager = manager;
            this.joystickType = joystickType;
            this.backgroundImage = backgroundImage;
            this.joystickImage = joystickImage;
            this.buttonImage = buttonImage;

            this.backgroundPosition = backgroundPosition;
            this.joystickPosition = joystickPosition + backgroundPosition;

            this.joystickSize = Math.Min(joystickImage.Width, joystickImage.Height) / 2;
            this.joystickOffset = new Vector2(joystickImage.Width / 2f, joystickImage.Height / 2f);
            
            if (buttonImage != null)
            {
                this.buttonSize = Math.Min(buttonImage.Width, buttonImage.Height) / 2;
                this.buttonOffset = new Vector2(buttonImage.Width / 2f, buttonImage.Height / 2f);
                this.numButtons = buttonPositions.Length;

                this.button = new bool[numButtons];
                this.buttonId = new int[numButtons];
                this.buttonPositions = new Vector2[numButtons];

                for(int f = 0; f < numButtons; f++)
                {
                    this.buttonPositions[f] = backgroundPosition + buttonPositions[f] + buttonOffset;
                }
            }
            else
            {
                this.buttonSize = 0;
                this.buttonOffset = Vector2.Zero;
                this.numButtons = 0;
            }

            this.deadzone = deadzone;
            this.deadzoneBreached = false;
            this.stickSize = stickSize;

            this.digital = DigitalJoystickState.Centre;
            this.joylock = JoystickLock.EightWay;
            this.analogue = Vector2.Zero;

            this.digitalPositions = new Vector2[16];

            this.digitalPositions[(int)DigitalJoystickState.Centre] = Vector2.Zero;

            this.digitalPositions[(int)DigitalJoystickState.Up] = new Vector2(0, -stickSize);
            this.digitalPositions[(int)DigitalJoystickState.Down] = new Vector2(0, stickSize);
            this.digitalPositions[(int)DigitalJoystickState.Left] = new Vector2(-stickSize, 0);
            this.digitalPositions[(int)DigitalJoystickState.Right] = new Vector2(stickSize, 0);

            this.digitalPositions[(int)DigitalJoystickState.UpLeft] = new Vector2(-stickSize, -stickSize);
            this.digitalPositions[(int)DigitalJoystickState.UpRight] = new Vector2(stickSize, -stickSize);
            this.digitalPositions[(int)DigitalJoystickState.DownLeft] = new Vector2(-stickSize, stickSize);
            this.digitalPositions[(int)DigitalJoystickState.DownRight] = new Vector2(stickSize, stickSize);

            this.digitalAngles = new DigitalJoystickState[8]
            {
                //DigitalJoystickState.Up,
                //DigitalJoystickState.UpRight,
                //DigitalJoystickState.Right,
                //DigitalJoystickState.DownRight,
                //DigitalJoystickState.Down,
                //DigitalJoystickState.DownLeft,
                //DigitalJoystickState.Left,
                //DigitalJoystickState.UpLeft
                DigitalJoystickState.Right,
                DigitalJoystickState.DownRight,
                DigitalJoystickState.Down,
                DigitalJoystickState.DownLeft,
                DigitalJoystickState.Left,
                DigitalJoystickState.UpLeft,
                DigitalJoystickState.Up,
                DigitalJoystickState.UpRight
            };

            StartJoystickUpdates();
        }

        #endregion
    }
}