-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathmupen64plus_env.py
252 lines (194 loc) · 8.14 KB
/
mupen64plus_env.py
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
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import abc
import array
import inspect
import os
import subprocess
import threading
import time
from termcolor import cprint
import yaml
import gym
from gym import error, spaces, utils
from gym.utils import seeding
import numpy as np
import wx
wx.App()
###############################################
class ImageHelper:
BLACK_PIXEL = (0, 0, 0)
def GetPixelColor(self, image_array, x, y):
base_pixel = (x + (y * config['SCR_W'])) * 3
red = image_array[base_pixel + 0]
green = image_array[base_pixel + 1]
blue = image_array[base_pixel + 2]
return (red, green, blue)
###############################################
### Variables & Constants ###
###############################################
config = yaml.safe_load(open(os.path.join(os.path.dirname(inspect.stack()[0][1]), "config.yml")))
MILLIS_50 = 50.0 / 1000.0
IMAGE_HELPER = ImageHelper()
###############################################
class Mupen64PlusEnv(gym.Env):
__metaclass__ = abc.ABCMeta
metadata = {'render.modes': ['human']}
def __init__(self, rom_path):
self.step_count = 0
self.running = True
self.episode_over = False
self.numpy_array = None
self.pixel_array = array.array('B', [0] * (config['SCR_W'] *
config['SCR_H'] *
config['SCR_D']))
self.controller_server, self.controller_server_thread = self._start_controller_server()
self.emulator_process = self._start_emulator(rom_path=rom_path)
self._navigate_menu()
self.observation_space = \
spaces.Box(low=0, high=255, shape=(config['SCR_H'], config['SCR_W'], config['SCR_D']))
self.action_space = spaces.MultiDiscrete([[-80, 80], # Joystick X-axis
[-80, 80], # Joystick Y-axis
[0, 1], # A Button
[0, 1], # B Button
[0, 1]]) # RB Button
def _step(self, action):
#cprint('Step %i: %s' % (self.step_count, action), 'green')
self.controller_server.send_controls(action)
obs = self._observe()
self.episode_over = self._evaluate_end_state()
reward = self._get_reward()
self.step_count += 1
return obs, reward, self.episode_over, {}
def _observe(self):
#cprint('Observe called!', 'red')
bmp = wx.Bitmap(config['SCR_W'], config['SCR_H'])
wx.MemoryDC(bmp).Blit(0, 0,
config['SCR_W'], config['SCR_H'],
wx.ScreenDC(),
config['OFFSET_X'], config['OFFSET_Y'])
bmp.CopyToBuffer(self.pixel_array)
self.numpy_array = np.frombuffer(self.pixel_array, dtype=np.uint8)
self.numpy_array = \
self.numpy_array.reshape(config['SCR_H'], config['SCR_W'], config['SCR_D'])
return self.numpy_array
@abc.abstractmethod
def _navigate_menu(self):
return
@abc.abstractmethod
def _get_reward(self):
#cprint('Get Reward called!', 'red')
return 0
@abc.abstractmethod
def _evaluate_end_state(self):
#cprint('Evaluate End State called!', 'red')
return False
@abc.abstractmethod
def _reset(self):
cprint('Reset called!', 'red')
return self._observe()
def _render(self, mode='human', close=False):
# TODO: Implement xvfb support for background execution,
# and implement this render method to display the window
pass
def _close(self):
cprint('Close called!', 'red')
self.running = False
self._kill_emulator()
self._stop_controller_server()
def _start_controller_server(self):
server = ControllerHTTPServer(('', config['PORT_NUMBER']),
config['ACTION_TIMEOUT'])
server_thread = threading.Thread(target=server.serve_forever, args=())
server_thread.daemon = True
server_thread.start()
print('ControllerHTTPServer started on port ', config['PORT_NUMBER'])
return server, server_thread
def _stop_controller_server(self):
#cprint('Stop Controller Server called!', 'red')
if self.controller_server is not None:
self.controller_server.shutdown()
def _start_emulator(self,
rom_path,
res_w=config['SCR_W'],
res_h=config['SCR_H'],
input_driver_path=config['INPUT_DRIVER_PATH']):
cmd = config['MUPEN_CMD'] + \
" --resolution %ix%i" \
" --input %s" \
" %s" \
% (res_w, res_h,
input_driver_path,
rom_path)
print('Starting emulator with comand: %s' % cmd)
emulator_process = subprocess.Popen(cmd.split(' '),
shell=False,
stderr=subprocess.STDOUT)
emu_mon = EmulatorMonitor()
monitor_thread = threading.Thread(target=emu_mon.monitor_emulator,
args=[emulator_process])
monitor_thread.daemon = True
monitor_thread.start()
return emulator_process
def _kill_emulator(self):
#cprint('Kill Emulator called!', 'red')
self.controller_server.send_controls(ControllerHTTPServer.NOOP)
if self.emulator_process is not None:
self.emulator_process.kill()
###############################################
class EmulatorMonitor:
def monitor_emulator(self, emulator):
emu_return = emulator.poll()
while emu_return is None:
time.sleep(2)
emu_return = emulator.poll()
# TODO: this means our environment died... need to die too
print('Emulator closed with code: ' + str(emu_return))
###############################################
class ControllerHTTPServer(HTTPServer, object):
# Buttons
NOOP = [0, 0, 0, 0, 0]
A_BUTTON = [0, 0, 1, 0, 0]
B_BUTTON = [0, 0, 0, 1, 0]
RB_BUTTON = [0, 0, 0, 0, 1]
JOYSTICK_UP = [0, 80, 0, 0, 0]
JOYSTICK_DOWN = [0, -80, 0, 0, 0]
JOYSTICK_LEFT = [-80, 0, 0, 0, 0]
JOYSTICK_RIGHT = [80, 0, 0, 0, 0]
def __init__(self, server_address, control_timeout):
self.control_timeout = control_timeout
self.controls = ControllerHTTPServer.NOOP
self.hold_response = True
self.running = True
super(ControllerHTTPServer, self).__init__(server_address, self.ControllerRequestHandler)
def send_controls(self, controls):
#print('Send controls called')
self.controls = controls
self.hold_response = False
# Wait for controls to be sent:
start = time.time()
while not self.hold_response and time.time() < start + self.control_timeout:
time.sleep(MILLIS_50)
def shutdown(self):
self.running = False
super(ControllerHTTPServer, self).shutdown()
class ControllerRequestHandler(BaseHTTPRequestHandler, object):
def log_message(self, format, *args):
pass
def write_response(self, resp_code, resp_data):
self.send_response(resp_code)
self.send_header("Content-type", "text/plain")
self.end_headers()
self.wfile.write(resp_data)
def do_GET(self):
while self.server.running and self.server.hold_response:
time.sleep(MILLIS_50)
if not self.server.running:
print('Sending SHUTDOWN response')
# TODO: This sometimes fails with a broken pipe because
# the emulator has already stopped. Should handle gracefully
self.write_response(500, "SHUTDOWN")
### respond with controller output
self.write_response(200, self.server.controls)
self.server.hold_response = True
return
###############################################