summaryrefslogtreecommitdiffstats
path: root/gearboy/src/Input.cpp
blob: acc1e3fc3ea0df5dd5cde281b99cd775b669dff9 (plain) (blame)
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
/*
 * Gearboy - Nintendo Game Boy Emulator
 * Copyright (C) 2012  Ignacio Sanchez

 * 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 3 of the License, or
 * 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, see http://www.gnu.org/licenses/
 *
 */

#include "Input.h"
#include "Memory.h"
#include "Processor.h"

Input::Input(Memory* pMemory, Processor* pProcessor)
{
    m_pMemory = pMemory;
    m_pProcessor = pProcessor;
    m_JoypadState = 0xFF;
    m_P1 = 0xFF;
    m_iInputCycles = 0;
}

void Input::Init()
{
    Reset();
}

void Input::Reset()
{
    m_JoypadState = 0xFF;
    m_P1 = 0xFF;
    m_iInputCycles = 0;
}

void Input::KeyPressed(Gameboy_Keys key)
{
    m_JoypadState = UnsetBit(m_JoypadState, key);
}

void Input::KeyReleased(Gameboy_Keys key)
{
    m_JoypadState = SetBit(m_JoypadState, key);
}

void Input::Update()
{
    u8 current = m_P1 & 0xF0;

    switch (current & 0x30)
    {
        case 0x10:
        {
            u8 topJoypad = (m_JoypadState >> 4) & 0x0F;
            current |= topJoypad;
            break;
        }
        case 0x20:
        {
            u8 bottomJoypad = m_JoypadState & 0x0F;
            current |= bottomJoypad;
            break;
        }
        case 0x30:
            current |= 0x0F;
            break;
    }

    if ((m_P1 & ~current & 0x0F) != 0)
        m_pProcessor->RequestInterrupt(Processor::Joypad_Interrupt);

    m_P1 = current;
}

void Input::SaveState(std::ostream& stream)
{
    using namespace std;

    stream.write(reinterpret_cast<const char*> (&m_JoypadState), sizeof(m_JoypadState));
    stream.write(reinterpret_cast<const char*> (&m_P1), sizeof(m_P1));
    stream.write(reinterpret_cast<const char*> (&m_iInputCycles), sizeof(m_iInputCycles));
}

void Input::LoadState(std::istream& stream)
{
    using namespace std;

    stream.read(reinterpret_cast<char*> (&m_JoypadState), sizeof(m_JoypadState));
    stream.read(reinterpret_cast<char*> (&m_P1), sizeof(m_P1));
    stream.read(reinterpret_cast<char*> (&m_iInputCycles), sizeof(m_iInputCycles));
}