-
Notifications
You must be signed in to change notification settings - Fork 0
/
shipSystem.py
250 lines (217 loc) · 11.4 KB
/
shipSystem.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
import sandbox
from direct.actor.Actor import Actor
from direct.interval.LerpInterval import LerpHprInterval
from direct.stdpy.file import *
from panda3d.bullet import BulletDebugNode, BulletRigidBodyNode, BulletSphereShape
from panda3d.core import LPoint3d, NodePath, Vec3
import graphicsComponents
import physics
import shipComponents
import universals
import glob
import re
import yaml
from pandac.PandaModules import loadPrcFileData
loadPrcFileData("", "notify-level-ITF-ShipSystem debug")
from direct.directnotify.DirectNotify import DirectNotify
log = DirectNotify().newCategory("ITF-ShipSystem")
#Conversion factor from SI to units used in game
CONVERT = 1000.0
shipClasses = {}
class ShipSystem(sandbox.EntitySystem):
def init(self):
self.accept("setPlayerStations", self.setPlayerStation)
self.accept("setShipID", self.setShipID)
self.accept('shipClassList', self.checkClasses)
self.accept('shipUpdate', self.shipUpdate)
self.accept('shipUpdates', self.shipUpdates)
self.accept('spawnShip', self.spawnShip)
self.accept('setTarget', self.setTarget)
self.accept('playerDisconnected', self.playerDisconnected)
self.shipid = None # This is for clients to id who the controlling
# ship is for quick lookup
sandbox.ships = NodePath("ships")
sandbox.ships.reparentTo(sandbox.base.render)
def process(self, entity):
#TODO: Turret tracking here
# Turret tracking done here
mesh = entity.getComponent(graphicsComponents.RenderComponent).mesh
turrets = entity.getComponent(shipComponents.TurretsComponent)
for turretEntityID in turrets.turretIDs:
turret = sandbox.entities[turretEntityID].getComponent(shipComponents.TurretComponent)
#target = sandbox.entities[turret.targetID].getComponent(shipComponents.BulletPhysicsComponent)
if turret.targetID is None:
continue
targetRender = sandbox.entities[turret.targetID].getComponent(graphicsComponents.RenderComponent)
traverser = mesh.controlJoint(None, 'modelRoot', (turret.name + ' traverser').replace(' ', '-'))
hpr = mesh.getHpr(targetRender.mesh)
shipClass = shipClasses[entity.getComponent(shipComponents.InfoComponent).shipClass]
rotationSpeed = shipClass['weapons'][turret.name]['rotationSpeed']
deltaH = (360 / float(rotationSpeed)) * globalClock.getDt()
directionDistance =\
sandbox.mathextra.signedAngularDistance(
hpr[0],
traverser.getH()
)
if directionDistance > 0.1:
traverser.setH(traverser.setH(traverser.getH + deltaH))
elif directionDistance < -0.1:
traverser.setH(traverser.setH(traverser.getH - deltaH))
def setTarget(self, masterShipID, data):
# TODO: Support client sending specific turrets
# Get ship turrets
allTurrets = sandbox.getEntitiesByComponentType(shipComponents.TurretComponent)
turrets = []
for turret in allTurrets:
if turret.getComponent(shipComponents.TurretComponent).parentID == masterShipID:
if data.turretId == -1:
turrets.append(turret.getComponent(shipComponents.TurretComponent))
elif data.turretId == turrent.id:
turrets.append(turret.getComponent(shipComponents.TurretComponent))
for turret in turrets:
turret.targetID = data.targetId
def setShipID(self, data):
self.shipid = data.id
universals.shipid = data.id
def checkClasses(self, shipClasses2):
for ship in shipClasses2.shipClass:
if ship.className not in shipClasses:
import sys
sandbox.log.warning("Ship type " + ship.folder + ' does not exist!')
sandbox.log.warning("Current DB: " + str(shipClasses))
sys.exit(1)
def loadShipClasses(self):
shippaths = glob.glob('ships/*/ship.yaml')
for yamlPath in shippaths:
shipFile = open(yamlPath)
ship = yaml.load(shipFile)
re1 = '.*?' # Non-greedy match on filler
re2 = '(?:[a-z][a-z]+)' # Uninteresting: word
re3 = '.*?' # Non-greedy match on filler
re4 = '((?:[a-z][a-z]+))' # Word 1
rg = re.compile(re1 + re2 + re3 + re4, re.IGNORECASE | re.DOTALL)
m = rg.search(yamlPath)
#ship['path'] = 'ships/' + ship['mesh'] + '/'
ship['path'] = m.group(1) + '/' + ship['mesh']
ship['folder'] = m.group(1)
shipFile.close()
#TODO switch class name to folder name
shipClasses[ship['class']] = ship
universals.log.info("Loaded " + ship['mesh'])
def shipUpdate(self, ship, playerShip=False):
if ship.id not in sandbox.entities:
#self.spawnShip(ship.name, ship.className, playerShip, entityid=ship.id)
self.spawnShip(ship.name, ship.className, playerShip=True, entityid=ship.id, turrets=ship.turrets)
sandbox.send('updateStationGUI')
#TODO: Request for full info from server and just return if no name or class?
physicsComponent = sandbox.entities[ship.id].getComponent(shipComponents.BulletPhysicsComponent)
physicsComponent.setTruePos(ship.x, ship.y)
physicsComponent.nodePath.setHpr(ship.h, 0, 0)
physicsComponent.node.setLinearVelocity((ship.dx, ship.dy, 0))
physicsComponent.node.setAngularVelocity((0, 0, ship.dh))
physicsComponent.currentThrust = ship.thrust
physicsComponent.currentTorque = ship.torque
def shipUpdates(self, ships):
for ship in ships.ship:
self.shipUpdate(ship)
def spawnShip(
self, shipName, shipClass, spawnPoint=LPoint3d(0, 0, 0),
playerShip=False, entityid=-1, turrets=None
):
if shipName == '' or shipClass == '':
return
if entityid == -1:
ship = sandbox.createEntity()
else:
ship = sandbox.addEntity(entityid)
if playerShip:
component = shipComponents.PlayerComponent()
ship.addComponent(component)
else:
component = shipComponents.AIPilotComponent()
ship.addComponent(component)
shape = BulletSphereShape(1)
velocity = Vec3(0, 0, 0)
truex = spawnPoint.getX()
truey = spawnPoint.getY()
component = physics.addNewBody(shipName, shape, shipClasses[shipClass]['mass'], truex, truey, velocity)
ship.addComponent(component)
component = shipComponents.ThrustComponent()
for engine in shipClasses[shipClass]['engines']:
component.forward += engine['thrust'] / CONVERT
component.heading = shipClasses[shipClass]['torque'] / CONVERT
ship.addComponent(component)
component = shipComponents.InfoComponent()
component.shipClass = shipClass
component.name = shipName
ship.addComponent(component)
component = graphicsComponents.RenderComponent()
#component.mesh = sandbox.base.loader.loadModel('ships/' + shipClasses[shipClass]['path'])
component.mesh = Actor('ships/' + shipClasses[shipClass]['path'])
component.mesh.reparentTo(sandbox.ships)
component.mesh.getPart('modelRoot').setPythonTag('entityID', ship.id)
component.mesh.setScale(1 / CONVERT)
if universals.runClient and not playerShip:
sandbox.send('makePickable', [component.mesh])
ship.addComponent(component)
# Load turret info here. Also check if gun is actually on ship!
def containsAny(string, check):
return 1 in [c in string for c in check]
turretsComponent = shipComponents.TurretsComponent()
if not turrets:
for weapon in shipClasses[shipClass]['weapons']:
turretEntity = sandbox.createEntity()
turret = shipComponents.TurretComponent()
if not containsAny(shipClasses[shipClass]['weapons'][weapon]['decay'], 'abcdefghijklmnopqrstuvwyz'):
turret.decay = lambda x: eval(shipClasses[shipClass]['weapons'][weapon]['decay'])
turret.name = weapon
turret.damage = shipClasses[shipClass]['weapons'][weapon]['damage']
if 'traverser' in shipClasses[shipClass]['weapons'][weapon]['joints']:
turret.traverser = shipClasses[shipClass]['weapons'][weapon]['joints']['traverser']['axes']
if 'elevator' in shipClasses[shipClass]['weapons'][weapon]['joints']:
turret.elevator = shipClasses[shipClass]['weapons'][weapon]['joints']['elevator']['axes']
turret.parentID = ship.id
turretEntity.addComponent(turret)
turretsComponent.turretIDs.append(turretEntity.id)
if turrets:
for t in turrets:
turretEntity = sandbox.addEntity(t.turretid)
turret = shipComponents.TurretComponent()
weapon = t.turretName
if not containsAny(shipClasses[shipClass]['weapons'][weapon]['decay'], 'abcdefghijklmnopqrstuvwyz'):
turret.decay = lambda x: eval(shipClasses[shipClass]['weapons'][weapon]['decay'])
turret.name = weapon
turret.damage = shipClasses[shipClass]['weapons'][weapon]['damage']
if 'traverser' in shipClasses[shipClass]['weapons'][weapon]['joints']:
turret.traverser = shipClasses[shipClass]['weapons'][weapon]['joints']['traverser']['axes']
if 'elevator' in shipClasses[shipClass]['weapons'][weapon]['joints']:
turret.elevator = shipClasses[shipClass]['weapons'][weapon]['joints']['elevator']['axes']
turret.parentID = ship.id
turretEntity.addComponent(turret)
turretsComponent.turretIDs.append(turretEntity.id)
ship.addComponent(turretsComponent)
#sandbox.send("shipGenerated", [ship, playerShip])
log.info("Ship spawned: " + shipName + " " + shipClass)
#TODO Transmit player's ship data
#TODO Broadcast new ship data
#TODO Prioritize updating new client of surroundings
def getPlayerShipEntities(self):
return sandbox.getEntitiesByComponentType(shipComponents.PlayerComponent)
def setPlayerStation(self, netAddress, shipid, stations):
entity = sandbox.entities[shipid]
playerComponent = entity.getComponent(shipComponents.PlayerComponent)
acceptedStations = []
for stationName in universals.playerStations:
if getattr(playerComponent, stationName) == 0 and hasattr(stations, stationName):
if getattr(stations, stationName) == 1:
setattr(playerComponent, stationName, netAddress)
acceptedStations.append(stationName)
sandbox.send("confirmPlayerStations", [netAddress, shipid, acceptedStations])
def playerDisconnected(self, address):
ships = self.getPlayerShipEntities()
for ship in ships:
playerComponent = sandbox.entities[ship.id].getComponent(shipComponents.PlayerComponent)
for stationName in universals.playerStations:
if getattr(playerComponent, stationName) == address:
setattr(playerComponent, stationName, 0)
sandbox.send('stationEmptied', [ship.id, stationName])