-
Notifications
You must be signed in to change notification settings - Fork 40
/
mupen64plus_env.py
488 lines (394 loc) · 18.1 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
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
import sys
PY3_OR_LATER = sys.version_info[0] >= 3
if PY3_OR_LATER:
# Python 3 specific definitions
from http.server import BaseHTTPRequestHandler, HTTPServer
else:
# Python 2 specific definitions
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import abc
import array
from contextlib import contextmanager
import inspect
import itertools
import json
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 mss
###############################################
class ImageHelper:
def GetPixelColor(self, image_array, x, y):
base_pixel = image_array[y][x]
red = base_pixel[0]
green = base_pixel[1]
blue = base_pixel[2]
return (red, green, blue)
###############################################
### Variables & Constants ###
###############################################
# The width, height, and depth of the emulator window:
SCR_W = 640
SCR_H = 480
SCR_D = 3
MILLISECOND = 1.0 / 1000.0
IMAGE_HELPER = ImageHelper()
###############################################
class Mupen64PlusEnv(gym.Env):
__metaclass__ = abc.ABCMeta
metadata = {'render.modes': ['human']}
def __init__(self):
self.viewer = None
self.reset_count = 0
self.step_count = 0
self.running = True
self.episode_over = False
self.pixel_array = None
self._base_load_config()
self._base_validate_config()
self.frame_skip = self.config['FRAME_SKIP']
if self.frame_skip < 1:
self.frame_skip = 1
self.controller_server, self.controller_server_thread = self._start_controller_server()
initial_disp = os.environ["DISPLAY"]
cprint('Initially on DISPLAY %s' % initial_disp, 'red')
# If the EXTERNAL_EMULATOR environment variable is True, we are running the
# emulator out-of-process (likely via docker/docker-compose). If not, we need
# to start the emulator in-process here
external_emulator = os.environ.has_key("EXTERNAL_EMULATOR") and os.environ["EXTERNAL_EMULATOR"] == 'True'
if not external_emulator:
self.xvfb_process, self.emulator_process = \
self._start_emulator(rom_name=self.config['ROM_NAME'],
gfx_plugin=self.config['GFX_PLUGIN'],
input_driver_path=self.config['INPUT_DRIVER_PATH'])
# TODO: Test and cleanup:
# May need to initialize this after the DISPLAY env var has been set
# so it attaches to the correct X display; otherwise screenshots may
# come from the wrong place. This used to be true when we were using
# wxPython for screenshots. Untested after switching to mss.
cprint('Calling mss.mss() with DISPLAY %s' % os.environ["DISPLAY"], 'red')
self.mss_grabber = mss.mss()
time.sleep(2) # Give mss a couple seconds to initialize; also may not be necessary
# Restore the DISPLAY env var
os.environ["DISPLAY"] = initial_disp
cprint('Changed back to DISPLAY %s' % os.environ["DISPLAY"], 'red')
with self.controller_server.frame_skip_disabled():
self._navigate_menu()
self.observation_space = \
spaces.Box(low=0, high=255, shape=(SCR_H, SCR_W, 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
[ 0, 1], # LB Button
[ 0, 1], # Z Button
[ 0, 1], # C Right Button
[ 0, 1], # C Left Button
[ 0, 1], # C Down Button
[ 0, 1], # C Up Button
[ 0, 1], # D-Pad Right Button
[ 0, 1], # D-Pad Left Button
[ 0, 1], # D-Pad Down Button
[ 0, 1], # D-Pad Up Button
[ 0, 1], # Start Button
])
def _base_load_config(self):
self.config = yaml.safe_load(open(os.path.join(os.path.dirname(inspect.stack()[0][1]), "config.yml")))
self._load_config()
@abc.abstractmethod
def _load_config(self):
return
def _base_validate_config(self):
if 'ROM_NAME' not in self.config:
raise AssertionError('ROM_NAME configuration is required')
if 'GFX_PLUGIN' not in self.config:
raise AssertionError('GFX_PLUGIN configuration is required')
self._validate_config()
@abc.abstractmethod
def _validate_config(self):
return
def _step(self, action):
#cprint('Step %i: %s' % (self.step_count, action), 'green')
self._act(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 _act(self, action, count=1):
for _ in itertools.repeat(None, count):
self.controller_server.send_controls(ControllerState(action))
def _wait(self, count=1, wait_for='Unknown'):
self._act(ControllerState.NO_OP, count=count)
def _press_button(self, button, times=1):
for _ in itertools.repeat(None, times):
self._act(button) # Press
self._act(ControllerState.NO_OP) # and release
def _observe(self):
#cprint('Observe called!', 'yellow')
if self.config['USE_XVFB']:
offset_x = 0
offset_y = 0
else:
offset_x = self.config['OFFSET_X']
offset_y = self.config['OFFSET_Y']
image_array = \
np.array(self.mss_grabber.grab({"top": offset_y,
"left": offset_x,
"width": SCR_W,
"height": SCR_H}),
dtype=np.uint8)
# drop the alpha channel and flip red and blue channels (BGRA -> RGB)
self.pixel_array = np.flip(image_array[:, :, :3], 2)
return self.pixel_array
@abc.abstractmethod
def _navigate_menu(self):
return
@abc.abstractmethod
def _get_reward(self):
#cprint('Get Reward called!', 'yellow')
return 0
@abc.abstractmethod
def _evaluate_end_state(self):
#cprint('Evaluate End State called!', 'yellow')
return False
@abc.abstractmethod
def _reset(self):
cprint('Reset called!', 'yellow')
self.reset_count += 1
self.step_count = 0
return self._observe()
def _render(self, mode='human', close=False):
if close:
if hasattr(self, 'viewer') and self.viewer is not None:
self.viewer.close()
self.viewer = None
return
img = self.pixel_array
if mode == 'rgb_array':
return img
elif mode == 'human':
if not hasattr(self, 'viewer') or self.viewer is None:
from gym.envs.classic_control import rendering
self.viewer = rendering.SimpleImageViewer()
self.viewer.imshow(img)
def _close(self):
cprint('Close called!', 'yellow')
self.running = False
self._kill_emulator()
self._stop_controller_server()
def _start_controller_server(self):
server = ControllerHTTPServer(server_address = ('', self.config['PORT_NUMBER']),
control_timeout = self.config['ACTION_TIMEOUT'],
frame_skip = self.frame_skip) # TODO: Environment argument (with issue #26)
server_thread = threading.Thread(target=server.serve_forever, args=())
server_thread.daemon = True
server_thread.start()
print('ControllerHTTPServer started on port ', self.config['PORT_NUMBER'])
return server, server_thread
def _stop_controller_server(self):
#cprint('Stop Controller Server called!', 'yellow')
if hasattr(self, 'controller_server'):
self.controller_server.shutdown()
def _start_emulator(self,
rom_name,
gfx_plugin,
input_driver_path,
res_w=SCR_W,
res_h=SCR_H,
res_d=SCR_D):
rom_path = os.path.abspath(
os.path.join(os.path.dirname(inspect.stack()[0][1]),
'../ROMs',
rom_name))
if not os.path.isfile(rom_path):
msg = "ROM not found: " + rom_path
cprint(msg, 'red')
raise Exception(msg)
input_driver_path = os.path.abspath(os.path.expanduser(input_driver_path))
if not os.path.isfile(input_driver_path):
msg = "Input driver not found: " + input_driver_path
cprint(msg, 'red')
raise Exception(msg)
cmd = [self.config['MUPEN_CMD'],
"--nospeedlimit",
"--nosaveoptions",
"--resolution",
"%ix%i" % (res_w, res_h),
"--gfx", gfx_plugin,
"--audio", "dummy",
"--input", input_driver_path,
rom_path]
xvfb_proc = None
if self.config['USE_XVFB']:
display_num = -1
success = False
# If we couldn't find an open display number after 15 attempts, give up
while not success and display_num <= 15:
display_num += 1
xvfb_cmd = [self.config['XVFB_CMD'],
":" + str(display_num),
"-screen",
"0",
"%ix%ix%i" % (res_w, res_h, res_d * 8),
"-fbdir",
self.config['TMP_DIR']]
cprint('Starting xvfb with command: %s' % xvfb_cmd, 'yellow')
xvfb_proc = subprocess.Popen(xvfb_cmd, shell=False, stderr=subprocess.STDOUT)
time.sleep(2) # Give xvfb a couple seconds to start up
# Poll the process to see if it exited early
# (most likely due to a server already active on the display_num)
if xvfb_proc.poll() is None:
success = True
print('') # new line
if not success:
msg = "Failed to initialize Xvfb!"
cprint(msg, 'red')
raise Exception(msg)
os.environ["DISPLAY"] = ":" + str(display_num)
cprint('Using DISPLAY %s' % os.environ["DISPLAY"], 'blue')
cprint('Changed to DISPLAY %s' % os.environ["DISPLAY"], 'red')
cmd = [self.config['VGLRUN_CMD'], "-d", ":" + str(display_num)] + cmd
cprint('Starting emulator with comand: %s' % cmd, 'yellow')
emulator_process = subprocess.Popen(cmd,
env=os.environ.copy(),
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 xvfb_proc, emulator_process
def _kill_emulator(self):
#cprint('Kill Emulator called!', 'yellow')
try:
self._act(ControllerState.NO_OP)
if self.emulator_process is not None:
self.emulator_process.kill()
if self.xvfb_process is not None:
self.xvfb_process.terminate()
except AttributeError:
pass # We may be shut down during intialization before these attributes have been set
###############################################
class EmulatorMonitor:
def monitor_emulator(self, emulator):
emu_return = emulator.poll()
while emu_return is None:
time.sleep(2)
if emulator is not None:
emu_return = emulator.poll()
else:
print('Emulator reference is no longer valid. Shutting down?')
return
# TODO: this means our environment died... need to die too
print('Emulator closed with code: ' + str(emu_return))
###############################################
class ControllerState(object):
# Controls [ JX, JY, A, B, RB, LB, Z, CR, CL, CD, CU, DR, DL, DD, DU, S]
NO_OP = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
START_BUTTON = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
A_BUTTON = [ 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
B_BUTTON = [ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
RB_BUTTON = [ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
CR_BUTTON = [ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0]
CL_BUTTON = [ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]
CD_BUTTON = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0]
CU_BUTTON = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
JOYSTICK_UP = [ 0, 127, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
JOYSTICK_DOWN = [ 0, -128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
JOYSTICK_LEFT = [-128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
JOYSTICK_RIGHT = [ 127, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
def __init__(self, controls=NO_OP):
self.X_AXIS = controls[0]
self.Y_AXIS = controls[1]
self.A_BUTTON = controls[2]
self.B_BUTTON = controls[3]
self.R_TRIG = controls[4]
self.L_TRIG = controls[5]
self.Z_TRIG = controls[6]
self.R_CBUTTON = controls[7]
self.L_CBUTTON = controls[8]
self.D_CBUTTON = controls[9]
self.U_CBUTTON = controls[10]
self.R_DPAD = controls[11]
self.L_DPAD = controls[12]
self.D_DPAD = controls[13]
self.U_DPAD = controls[14]
self.START_BUTTON = controls[15]
def to_json(self):
return json.dumps(self.__dict__)
###############################################
class ControllerHTTPServer(HTTPServer, object):
def __init__(self, server_address, control_timeout, frame_skip):
self.control_timeout = control_timeout
self.controls = ControllerState()
self.controls_updated = threading.Event()
self.response_sent = threading.Event()
self.running = True
self.responses_sent = 0
self.frame_skip = frame_skip
self.frame_skip_enabled = True
super(ControllerHTTPServer, self).__init__(server_address, self.ControllerRequestHandler)
def send_controls(self, controls):
self.responses_sent = 0
self.controls = controls
# Tell the request handler that the controls have been updated so it can send the response now:
self.controls_updated.set()
# Wait for response to actually be sent before returning:
if self.running:
self.response_sent.wait()
self.response_sent.clear()
def shutdown(self):
self.running = False
# Make sure we aren't blocking on anything:
self.response_sent.set()
self.controls_updated.set()
# Shutdown the server:
if PY3_OR_LATER:
super().shutdown()
super().server_close()
else:
super(ControllerHTTPServer, self).shutdown()
super(ControllerHTTPServer, self).server_close()
# http://preshing.com/20110920/the-python-with-statement-by-example/#implementing-the-context-manager-as-a-generator
@contextmanager
def frame_skip_disabled(self):
self.frame_skip_enabled = False
yield True
self.frame_skip_enabled = True
class ControllerRequestHandler(BaseHTTPRequestHandler, object):
def log_message(self, fmt, *args):
pass
def write_response(self, resp_code, resp_data):
self.send_response(resp_code)
self.send_header("Content-type", "application/json")
self.end_headers()
self.wfile.write(resp_data.encode())
def do_GET(self):
# Wait for the controls to be updated before responding:
if self.server.running:
self.server.controls_updated.wait()
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 (Issue #4)
self.write_response(500, "SHUTDOWN")
else:
### respond with controller output
self.write_response(200, self.server.controls.to_json())
self.server.responses_sent += 1
# If we have sent the controls 'n' times now...
if self.server.responses_sent >= self.server.frame_skip or not self.server.frame_skip_enabled:
# ...we fire the response_sent event so the next action can happen:
self.server.controls_updated.clear()
self.server.response_sent.set()
###############################################