-
Notifications
You must be signed in to change notification settings - Fork 1
/
aether.py
368 lines (323 loc) · 16.1 KB
/
aether.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
import threading
from mujoco_py import load_model_from_path, MjSim
import math
import time
import numpy as np
from helpers.endless import Endless
from strategy import Athena
from control import Zeus
from simulator.viewer import Viewer
class Aether:
"""
Deus do espaço e do paraíso
Faz a conexão entre o simulador e os módulos do programa
"""
def __init__(self):
# DEFINIÇÕES
self.field_width = 640
self.field_height = 480
self.cascadeTime = 0
self.cascadeLoops = 1
self.cascadeLastTime = 0
# PREPARAÇÃO
model = load_model_from_path("simulator/scene.xml")
self.sim = MjSim(model)
self.viewer = Viewer(self.sim, self)
self.ball_joint = self.sim.model.get_joint_qpos_addr("Ball")[0]
self.robot_joints = [
self.sim.model.get_joint_qpos_addr("Robot_01")[0],
self.sim.model.get_joint_qpos_addr("Robot_02")[0],
self.sim.model.get_joint_qpos_addr("Robot_03")[0],
self.sim.model.get_joint_qpos_addr("Robot_04")[0],
self.sim.model.get_joint_qpos_addr("Robot_05")[0],
self.sim.model.get_joint_qpos_addr("Robot_06")[0]
]
# EXECUÇÃO
# prepara os módulos
self.enabled = [False] * 6 # [False, False, False, True, True, True]
self.athena = [
Athena(),
Athena()
]
self.zeus = [
Zeus(),
Zeus()
]
Endless.setup(self.field_width, self.field_height)
self.athena[0].setup(3, 0.8)
self.athena[1].setup(3, 0.8)
self.zeus[0].setup(3)
self.zeus[1].setup(3)
# inicializa o loop dos dados
self.pause = False
self.loopThread1 = threading.Thread(target=self.loopTeam, args=[0])
self.loopThread2 = threading.Thread(target=self.loopTeam, args=[1])
self.loopThread1.daemon = True
self.loopThread2.daemon = True
self.loopThread1.start()
self.loopThread2.start()
self.showInfos(0)
self.showInfos(1)
def run(self):
while True:
self.sim.step()
self.viewer.render()
def loopTeam(self, team):
while True:
time.sleep(0.0000000001)
if self.pause or \
(not self.enabled[3 * team] and not self.enabled[3 * team + 1] and not self.enabled[3 * team + 2]):
continue
# executa nossos módulos
positions = self.generatePositions(team)
commands = self.athena[team].getTargets(positions)
velocities = self.zeus[team].getVelocities(commands)
# aplica resultados na simulação
if self.enabled[0 + 3 * team]:
self.sim.data.ctrl[0 + 6 * team] = self.convertVelocity(velocities[0]["vLeft"])
self.sim.data.ctrl[1 + 6 * team] = self.convertVelocity(velocities[0]["vRight"])
if self.enabled[1 + 3 * team]:
self.sim.data.ctrl[2 + 6 * team] = self.convertVelocity(velocities[1]["vLeft"])
self.sim.data.ctrl[3 + 6 * team] = self.convertVelocity(velocities[1]["vRight"])
if self.enabled[2 + 3 * team]:
self.sim.data.ctrl[4 + 6 * team] = self.convertVelocity(velocities[2]["vLeft"])
self.sim.data.ctrl[5 + 6 * team] = self.convertVelocity(velocities[2]["vRight"])
# mostra resultados
self.showInfos(team, positions, commands)
# indicadores 3D
for i in range(3):
position = positions[0][i]["position"]
self.setObjectPose("indicator_" + str(i + 3 * team + 1), position, team, 0.2, velocities[i]["vector"])
# self.setObjectPose("virtual_robot_1", velocities["virtualPos"], team=0)
# HELPERS
def showInfos(self, team, positions=None, commands=None):
infos = []
for i in range(3):
if self.enabled[i + 3 * team] and positions and commands:
# informações que todos os robôs tem
robot = "X: " + "{:.1f}".format(positions[0][i]["position"][0])
robot += ", Y: " + "{:.1f}".format(positions[0][i]["position"][1])
robot += ", O: " + "{:.1f}".format(positions[0][i]["orientation"])
robot += ", T: " + commands[i]["tactics"]
robot += ", C: " + commands[i]["command"]
if commands[i]["command"] == "lookAt":
if type(commands[i]["data"]["target"]) is tuple:
robot += "(" + "{:.1f}".format(commands[i]["data"]["target"][0]) + ", "
robot += "{:.1f}".format(commands[i]["data"]["target"][1]) + ")"
else:
robot += "(" + "{:.1f}".format(commands[i]["data"]["target"]) + ")"
elif commands[i]["command"] == "goTo":
robot += "(" + "{:.1f}".format(commands[i]["data"]["target"]["position"][0]) + ", "
robot += "{:.1f}".format(commands[i]["data"]["target"]["position"][1]) + ", "
if type(commands[i]["data"]["target"]["orientation"]) is tuple:
robot += "(" + "{:.1f}".format(commands[i]["data"]["target"]["orientation"][0]) + ", "
robot += "{:.1f}".format(commands[i]["data"]["target"]["orientation"][1]) + ") )"
else:
robot += "{:.1f}".format(commands[i]["data"]["target"]["orientation"]) + ")"
elif commands[i]["command"] == "spin":
robot += "(" + commands[i]["data"]["direction"] + ")"
else:
robot = "[OFF]"
infos.append(robot)
self.viewer.infos["robots" + str(team + 1)] = infos
if team == 0:
if positions:
self.viewer.infos["ball"] = "X: " + "{:.2f}".format(positions[2]["position"][0]) + ", Y: " + \
"{:.2f}".format(positions[2]["position"][1])
fps = self.getFPS()
if fps:
self.viewer.infos["fps"] = fps
if commands:
# indicadores 3D
# print(commands[0]["futureBall"])
self.setObjectPose("virtual_ball", commands[0]["futureBall"], 0, 0.022)
for i in range(3):
if commands[i]["command"] == "goTo":
target = commands[i]["data"]["target"]["position"]
targetOrientation = commands[i]["data"]["target"]["orientation"]
if type(targetOrientation) is tuple:
position = positions[0][i]["position"]
targetOrientation = math.atan2(position[1] - targetOrientation[1],
-(position[0] - targetOrientation[0]))
self.setObjectPose("target_" + str(i + 1), target, 0, 0.01, targetOrientation)
def getFPS(self):
# calcula o fps e manda pra interface
self.cascadeTime += time.time() - self.cascadeLastTime
self.cascadeLoops += 1
self.cascadeLastTime = time.time()
if self.cascadeTime > 1:
fps = self.cascadeLoops / self.cascadeTime
self.cascadeTime = self.cascadeLoops = 0
return "{:.2f}".format(fps)
return None
# FUNÇÕES
def reset(self):
for i in range(6):
self.enabled[i] = False
self.showInfos(0)
self.showInfos(1)
self.sim.reset()
def startStop(self, pause):
self.pause = pause
def moveBall(self, direction, keepVel=False):
if not keepVel:
for i in range(6):
self.sim.data.qvel[self.ball_joint + i] = 0
if direction == 0: # UP
self.sim.data.qpos[self.ball_joint + 1] += 0.01
elif direction == 1: # DOWN
self.sim.data.qpos[self.ball_joint + 1] -= 0.01
elif direction == 2: # LEFT
self.sim.data.qpos[self.ball_joint] -= 0.01
elif direction == 3: # RIGHT
self.sim.data.qpos[self.ball_joint] += 0.01
def toggleRobot(self, robotId, moveOut=False):
if self.sim.data.qpos[self.robot_joints[robotId] + 1] >= 1:
self.enabled[robotId] = False
if moveOut:
self.sim.data.qpos[self.robot_joints[robotId] + 1] = 0
elif moveOut:
self.enabled[robotId] = False
self.sim.data.qpos[self.robot_joints[robotId]] = -0.62 + 0.25 * robotId
self.sim.data.qpos[self.robot_joints[robotId] + 1] = 1.5
self.sim.data.qpos[self.robot_joints[robotId] + 2] = 0.04
self.sim.data.ctrl[robotId] = self.sim.data.ctrl[robotId + 1] = 0
elif self.enabled[robotId]:
self.enabled[robotId] = False
self.sim.data.ctrl[robotId] = self.sim.data.ctrl[robotId + 1] = 0
else:
self.enabled[robotId] = True
self.showInfos(0 if robotId < 3 else 1)
def convertPositionX(self, coord, team):
"""Traz o valor pra positivo e multiplica pela proporção (largura máxima)/(posição x máxima)
Args:
coord: Coordenada da posição no mundo da simulação a ser convertida
team: Time que está pedindo a conversão (0 ou 1)
Returns:
Coordenada da posição na proporção utilizada pela estratégia
"""
if team == 0:
return (coord + 0.8083874182591296) * self.field_width / 1.6167748365182593
else:
return -(coord - 0.8083874182591296) * self.field_width / 1.6167748365182593
def convertPositionY(self, coord, team):
"""Traz o valor pra positivo e multiplica pela proporção (altura máxima)/(posição y máxima)
Args:
coord: Coordenada da posição no mundo da simulação a ser convertida
team: Time que está pedindo a conversão (0 ou 1)
Returns:
Coordenada da posição na proporção utilizada pela estratégia
"""
if team == 0:
return (coord + 0.58339083) * self.field_height / 1.16678166
else:
return -(coord - 0.58339083) * self.field_height / 1.16678166
@staticmethod
def convertVelocity(vel):
return vel * 30
def setObjectPose(self, objectName, newPos, team=0, height=0.04, newOrientation=0):
"""Seta a posição e orientação de um objeto no simulador
Args:
objectName: Nome do objeto a ter a pose alterada. Esse nome deve ser de um mocap configurado na cena.
Se o objeto for virtual_robot_i, o robô é amarelo se i <= 3, azul caso contrário
newPos: (x, y), 'x' e 'y' valores em pixels
team: índice do time (valor em pixels inverte de acordo com o time)
height: altura do objeto no universo
newOrientation: orientação Z em radianos do objeto
"""
if team == 0:
x = (newPos[0] / self.field_width) * 1.6167748365182593 - 0.8083874182591296
y = (newPos[1] / self.field_height) * 1.16678166 - 0.58339083
else:
x = -(newPos[0] / self.field_width) * 1.6167748365182593 + 0.8083874182591296
y = -(newPos[1] / self.field_height) * 1.16678166 + 0.58339083
# conversão de eulerAngles para quaternions (wikipedia)
newQuat = [math.sin(newOrientation / 2), 0, 0, math.cos(newOrientation / 2)]
self.sim.data.set_mocap_quat(objectName, newQuat)
self.sim.data.set_mocap_pos(objectName, np.array([x, y, height]))
def generatePositions(self, team):
"""Cria o vetor de posições no formato esperado pela estratégia
O 'sim.data.qpos' possui, em cada posição, o seguinte:
0: pos X
1: pos Y
2: pos Z
3: quat component w
4: quat component x
5: quat component y
6: quat component z
Returns:
Vetor de posições no formato correto
"""
r1 = math.pi * team - math.atan2(
2 * (
self.sim.data.qpos[self.robot_joints[3 * team] + 3] * self.sim.data.qpos[self.robot_joints[3 * team] + 6] +
self.sim.data.qpos[self.robot_joints[3 * team] + 4] * self.sim.data.qpos[self.robot_joints[3 * team] + 6]
),
1 - 2 * (
self.sim.data.qpos[self.robot_joints[3 * team] + 5] * self.sim.data.qpos[self.robot_joints[3 * team] + 5] +
self.sim.data.qpos[self.robot_joints[3 * team] + 6] * self.sim.data.qpos[self.robot_joints[3 * team] + 6]
)
)
r2 = math.pi * team - math.atan2(
2 * (
self.sim.data.qpos[self.robot_joints[1 + 3 * team] + 3] * self.sim.data.qpos[self.robot_joints[1 + 3 * team] + 6] +
self.sim.data.qpos[self.robot_joints[1 + 3 * team] + 4] * self.sim.data.qpos[self.robot_joints[1 + 3 * team] + 6]
),
1 - 2 * (
self.sim.data.qpos[self.robot_joints[1 + 3 * team] + 5] * self.sim.data.qpos[self.robot_joints[1 + 3 * team] + 5] +
self.sim.data.qpos[self.robot_joints[1 + 3 * team] + 6] * self.sim.data.qpos[self.robot_joints[1 + 3 * team] + 6]
)
)
r3 = math.pi * team - math.atan2(
2 * (
self.sim.data.qpos[self.robot_joints[2 + 3 * team] + 3] * self.sim.data.qpos[self.robot_joints[2 + 3 * team] + 6] +
self.sim.data.qpos[self.robot_joints[2 + 3 * team] + 4] * self.sim.data.qpos[self.robot_joints[2 + 3 * team] + 6]
),
1 - 2 * (
self.sim.data.qpos[self.robot_joints[2 + 3 * team] + 5] * self.sim.data.qpos[self.robot_joints[2 + 3 * team] + 5] +
self.sim.data.qpos[self.robot_joints[2 + 3 * team] + 6] * self.sim.data.qpos[self.robot_joints[2 + 3 * team] + 6]
)
)
return [
[ # robôs aliados
{
"position": (self.convertPositionX(self.sim.data.qpos[self.robot_joints[3 * team]], team),
self.convertPositionY(self.sim.data.qpos[self.robot_joints[3 * team] + 1], team)),
"orientation": r1,
"robotLetter": "A"
},
{
"position": (self.convertPositionX(self.sim.data.qpos[self.robot_joints[1 + 3 * team]], team),
self.convertPositionY(self.sim.data.qpos[self.robot_joints[1 + 3 * team] + 1], team)),
"orientation": r2,
"robotLetter": "B"
},
{
"position": (self.convertPositionX(self.sim.data.qpos[self.robot_joints[2 + 3 * team]], team),
self.convertPositionY(self.sim.data.qpos[self.robot_joints[2 + 3 * team] + 1], team)),
"orientation": r3,
"robotLetter": "C"
}
],
[ # robôs adversários
{
"position": (self.convertPositionX(self.sim.data.qpos[self.robot_joints[(3 + 3 * team) % 6]], team),
self.convertPositionY(self.sim.data.qpos[self.robot_joints[(3 + 3 * team) % 6] + 1], team)),
},
{
"position": (self.convertPositionX(self.sim.data.qpos[self.robot_joints[(4 + 3 * team) % 6]], team),
self.convertPositionY(self.sim.data.qpos[self.robot_joints[(4 + 3 * team) % 6] + 1], team)),
},
{
"position": (self.convertPositionX(self.sim.data.qpos[self.robot_joints[(5 + 3 * team) % 6]], team),
self.convertPositionY(self.sim.data.qpos[self.robot_joints[(5 + 3 * team) % 6] + 1], team)),
}
],
{ # bola
"position": (self.convertPositionX(self.sim.data.qpos[self.ball_joint], team),
self.convertPositionY(self.sim.data.qpos[self.ball_joint + 1], team))
}
]
if __name__ == "__main__":
aether = Aether()
aether.run()