-
Notifications
You must be signed in to change notification settings - Fork 0
/
TagClientRepository.py
1151 lines (957 loc) · 41.7 KB
/
TagClientRepository.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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from direct.distributed.ClientRepositoryBase import ClientRepositoryBase
from direct.distributed.MsgTypes import *
from direct.distributed.PyDatagram import PyDatagram
from direct.distributed.PyDatagramIterator import PyDatagramIterator
from direct.gui.DirectGui import *
from direct.showbase.DirectObject import DirectObject
from direct.interval.IntervalGlobal import *
from pandac.PandaModules import *
from TagPlayer import TagPlayer
from TagAvatar import TagAvatar
from PlayerList import PlayerList
from PosterFSM import PosterFSM
import Globals
import Cell
import sys
import random
import math
import os
# Using ClientRepositoryBase since AstronClientRepository
# is not finished and possibly not usable yet.
class TagClientRepository(ClientRepositoryBase):
# Degrees per second of rotation
rotateSpeed = 90
# Units per second of motion
moveSpeed = 8
taskChain = 'net'
def __init__(self, playerName = None, threadedNet = True):
dcFileNames = ['direct.dc', 'tagger.dc']
ClientRepositoryBase.__init__(self, dcFileNames = dcFileNames,
connectMethod = self.CM_NET,
threadedNet = threadedNet)
self.GameGlobalsId = 1000
self.zoneInterest = None
self.visInterest = None
self.avatarManager = self.generateGlobalObject(1001, 'TagAvatarManager')
base.transitions.FadeModelName = 'models/fade'
# Allow some time for other processes. This also allows time
# each frame for the network thread to run.
base.setSleep(0.01)
# If we're using OpenGL, we can enable shaders. (DirectX
# shader support is still kind of spotty, even for simple
# shaders like these.)
if base.pipe and base.pipe.getInterfaceName() == 'OpenGL':
Globals.EnableShaders = True
self.gotMusic = False
self.__getMusic()
# For the browse button.
self.posterDefaultDir = Filename.getHomeDirectory().toOsSpecific()
# Load a fun font to be the default text font.
labelFont = loader.loadFont('models/amsterdam.ttf', okMissing = True)
if labelFont:
# Make a fuzzy halo behind the font so it looks kind of
# airbrushy
labelFont.setOutline(VBase4(0, 0, 0, 1), 2.0, 0.9)
TextNode.setDefaultFont(labelFont)
base.disableMouse()
if base.mouseWatcher:
mb = ModifierButtons()
mb.addButton(KeyboardButton.control())
base.mouseWatcher.node().setModifierButtons(mb)
base.buttonThrowers[0].node().setModifierButtons(mb)
taskMgr.setupTaskChain('loadPoster', numThreads = 4,
threadPriority = TPLow)
#taskMgr.setupTaskChain('net', numThreads = 1, threadPriority = TPLow, frameSync = True)
# Set up a text property called "tag" that renders using the
# tag font, in white, with a shadow. This is used for
# rendering the art-painting awards at the end of the round.
tpMgr = TextPropertiesManager.getGlobalPtr()
tp = TextProperties()
tagFont = loader.loadFont('models/one8seven.ttf', okMissing = True)
if tagFont:
tp.setFont(tagFont)
tp.setTextColor(1, 1, 1, 1)
tp.setShadow(0.05, 0.05)
tp.setTextScale(1.5)
tpMgr.setProperties('tag', tp)
# If we're running from the web, get the gameInfo block from
# the HTML tokens.
self.gameInfo = None
if base.appRunner:
gameInfoName = base.appRunner.getToken('gameInfo')
if gameInfoName:
self.gameInfo = base.appRunner.evalScript(gameInfoName, needsResponse = True)
# Expose the changePoster() method.
base.appRunner.main.changePoster = self.changePoster
print "self.gameInfo = %s" % (self.gameInfo)
# Also be prepared to update the web form with the table of
# players and the local player's score.
self.playerTable = None
self.scoreTable = None
if base.appRunner and base.appRunner.dom:
self.playerTable = base.appRunner.dom.document.getElementById('playerTable')
self.scoreTable = base.appRunner.dom.document.getElementById('scoreTable')
print "self.playerTable = %s, scoreTable = %s" % (self.playerTable, self.scoreTable)
self.playerList = PlayerList(self.playerTable)
self.onscreenScoreLeft = None
# When we join a game, we'll prefer to join *this* game.
self.nextGameId = 0
self.chooseGameTask = None
self.allGames = []
# No game, no avatar (yet).
self.robot = None
self.game = None
self.player = None
self.av = None
self.avCell = None
self.paintThing = None
self.keyMap = {}
for key in Globals.ControlKeys:
self.keyMap[key] = False
self.dlnp = render.attachNewNode(DirectionalLight('dlnp'))
self.dlnp.node().setColor((0.8, 0.8, 0.8, 1))
render.setLight(self.dlnp)
self.alnp = render.attachNewNode(AmbientLight('alnp'))
self.alnp.node().setColor((0.2, 0.2, 0.2, 1))
render.setLight(self.alnp)
if base.camera:
self.dlnp.reparentTo(base.camera)
# Set up the poster FSM to switch the poster modes.
self.posterFSM = PosterFSM(base.appRunner)
# A node to hold all avatars.
self.avRoot = render.attachNewNode('avRoot')
# The root of the maze.
self.mazeRoot = render.attachNewNode('maze')
if Globals.EnableShaders:
#self.mazeRoot.setShaderAuto()
s = loader.loadShader('models/nopaint_normal.sha')
self.mazeRoot.setShader(s)
self.mazeRoot.setShaderInput('alight0', self.alnp)
self.mazeRoot.setShaderInput('dlight0', self.dlnp)
# Initial poster data.
self.posterData = ('', 0)
cvar = ConfigVariableFilename('tag-poster', '')
filename = cvar.getValue()
if filename:
self.readTagPoster(filename)
# Choose a bright paint color.
h = random.random()
s = random.random() * 0.3 + 0.7
v = random.random() * 0.3 + 0.7
self.playerColor = self.hsv2rgb(h, s, v)
# Get the game's version.
self.gameVersion = getattr(self.gameInfo, 'server-version', None)
if not self.gameVersion:
self.gameVersion = base.config.GetString('server-version', 'tagger-dev')
# Get the player's name.
name = playerName
if not name:
name = getattr(self.gameInfo, 'name', None)
if not name:
name = base.config.GetString('player-name', '')
if name:
# Use the provided name.
self.playerName = name
self.startConnect()
else:
# Prompt the user.
# Start with the wall model in the background.
wall = loader.loadModel('models/wall')
wall.reparentTo(base.camera)
wall.setPos(0, 5, -2.5)
wall.setScale(10)
if Globals.EnableShaders:
wall.setShaderAuto()
self.nameWall = wall
c = self.playerColor
self.nameLabel = DirectLabel(
text = 'Enter your street name:',
text_align = TextNode.ALeft,
text_fg = (c[0], c[1], c[2], 1),
text_shadow = (0, 0, 0, 1),
pos = (-0.9, 0, 0.45),
relief = None,
scale = 0.2)
tagFont = loader.loadFont('models/one8seven.ttf')
cardModel = loader.loadModel('models/nametag_card')
cardTex = cardModel.findTexture('*')
self.nameEntry = DirectEntry(
pos = (-0.9, 0, 0.1),
focus = True,
relief = DGG.TEXTUREBORDER,
frameColor = (c[0], c[1], c[2], 0.6),
frameTexture = cardTex,
borderWidth = (0.2, 0.2),
pad = (0.0, -0.2),
borderUvWidth = (0.1, 0.1),
text_font = tagFont,
width = 12, scale = 0.15,
command = self.enteredName)
self.nameButton = DirectButton(
text = 'Enter game',
frameColor = (c[0], c[1], c[2], 1),
scale = 0.15,
pos = (0, 0, -0.5),
relief = DGG.RAISED,
borderWidth = (0.05, 0.05),
pad = (0.8, 0.3),
command = self.enteredName)
def enteredName(self, name = None):
""" The user has entered his/her nickname. Launch the
game. """
self.playerName = self.nameEntry.get()
if not self.playerName:
# Disallow entering with no name.
self.nameLabel['text'] = 'You must enter a name!'
return
self.nameLabel.destroy()
self.nameEntry.destroy()
self.nameButton.destroy()
self.nameWall.removeNode()
self.startConnect()
def lostConnection(self):
# This should be overridden by a derived class to handle an
# unexpectedly lost connection to the gameserver.
self.notify.warning("Lost connection to gameserver.")
if self.robot:
self.exit()
cbMgr = CullBinManager.getGlobalPtr()
cbMgr.addBin('gui-popup', cbMgr.BTUnsorted, 60)
self.failureText = OnscreenText(
'Lost connection to gameserver.\nPress ESC to quit.',
scale = 0.15, fg = (1, 0, 0, 1), shadow = (0, 0, 0, 1),
pos = (0, 0.2))
self.failureText.setBin('gui-popup', 0)
base.transitions.fadeScreen(alpha = 1)
render.hide()
self.ignore('escape')
self.accept('escape', self.exit)
self.accept('control-escape', self.exit)
def exit(self):
#if self.gotMusic:
# self.musicTrackFilename.unlink()
if self.isConnected():
self.sendDisconnect()
self.disconnect()
sys.exit()
def startConnect(self):
self.url = None
if self.gameInfo and getattr(self.gameInfo, 'server_url', None):
self.url = URLSpec(self.gameInfo.server_url)
if not self.url:
tcpPort = base.config.GetInt('server-port', Globals.ServerPort)
hostname = base.config.GetString('server-host', Globals.ServerHost)
if not hostname:
hostname = 'localhost'
self.url = URLSpec('g://%s:%s' % (hostname, tcpPort))
self.waitingText = OnscreenText(
'Connecting to %s.\nPress ESC to cancel.' % (self.url),
scale = 0.1, fg = (1, 1, 1, 1), shadow = (0, 0, 0, 1))
self.connect([self.url],
successCallback = self.connectSuccess,
failureCallback = self.connectFailure)
def escape(self):
""" The user pressed escape. Exit the client. """
self.exit()
def connectFailure(self, statusCode, statusString):
self.waitingText.destroy()
self.failureText = OnscreenText(
'Failed to connect to %s:\n%s.\nPress ESC to quit.' % (self.url, statusString),
scale = 0.15, fg = (1, 0, 0, 1), shadow = (0, 0, 0, 1),
pos = (0, 0.2))
def makeWaitingText(self):
if self.waitingText:
self.waitingText.destroy()
self.waitingText = OnscreenText(
'Waiting for server.',
scale = 0.1, fg = (1, 1, 1, 1), shadow = (0, 0, 0, 1))
def connectSuccess(self):
""" Successfully connected. But we still can't really do
anything until we send an CLIENT_HELLO message. """
self.makeWaitingText()
dg = PyDatagram()
dg.addUint16(CLIENT_HELLO)
dg.addUint32(self.hashVal)
dg.addString(self.gameVersion)
self.send(dg)
# Make sure we have interest in the TimeManager zone, so we
# always see it even if we switch to another zone.
#self.setInterestZones([1])
# We must wait for the TimeManager to be fully created and
# synced before we can enter zone 2 and wait for the game
# object.
#self.acceptOnce(self.uniqueName('gotTimeSync'), self.syncReady)
def handleDatagram(self, di):
msgType = self.getMsgType()
if msgType == CLIENT_HELLO_RESP:
self.handleHelloResp()
elif msgType == CLIENT_OBJECT_SET_FIELD:
self.handleUpdateField(di)
elif msgType == CLIENT_ENTER_OBJECT_REQUIRED:
self.handleGenerate(di)
elif msgType == CLIENT_ENTER_OBJECT_REQUIRED_OTHER:
self.handleGenerate(di, True)
elif msgType == CLIENT_DONE_INTEREST_RESP:
self.handleInterestDoneMessage(di)
elif msgType == CLIENT_ENTER_OBJECT_REQUIRED_OWNER:
self.handleGenerateOwner(di)
elif msgType == CLIENT_ENTER_OBJECT_REQUIRED_OTHER_OWNER:
self.handleGenerateOwner(di, True)
elif msgType == CLIENT_OBJECT_LEAVING:
self.handleDelete(di)
elif msgType == CLIENT_EJECT:
self.handleGoGetLost(di)
def handleHelloResp(self):
self.startHeartbeat()
self.acceptOnce('accessResponse', self.handleResponse)
self.avatarManager.requestAccess()
def sendHeartbeat(self):
dg = PyDatagram()
dg.addUint16(CLIENT_HEARTBEAT)
self.send(dg)
def sendDisconnect(self):
print 'Sending disconnect messsage'
dg = PyDatagram()
dg.addUint16(CLIENT_DISCONNECT)
self.send(dg)
def handleGenerate(self, di, other = False):
doId = di.getUint32()
parentId = di.getUint32()
zoneId = di.getUint32()
classId = di.getUint16()
dclass = self.dclassesByNumber[classId]
dclass.startGenerate()
if other:
self.generateWithRequiredOtherFields(dclass, doId, di, parentId, zoneId)
else:
self.generateWithRequiredFields(dclass, doId, di, parentId, zoneId)
dclass.stopGenerate()
print dclass.getName()
def handleGenerateOwner(self, di, other = False):
doId = di.getUint32()
parentId = di.getUint32()
zoneId = di.getUint32()
classId = di.getUint16()
dclass = self.dclassesByNumber[classId]
dclass.startGenerate()
# Copied from ClientRepositoryBase and make it support
# generating only required fields.
if doId in self.doId2ownerView:
# ...it is in our dictionary.
# Just update it.
self.notify.error('duplicate owner generate for %s (%s)' % (
doId, dclass.getName()))
distObj = self.doId2ownerView[doId]
assert distObj.dclass == dclass
distObj.generate()
if other:
distObj.updateRequiredOtherFields(dclass, di)
else:
distObj.updateRequiredFields(dclass, di)
# updateRequiredOtherFields calls announceGenerate
elif self.cacheOwner.contains(doId):
# ...it is in the cache.
# Pull it out of the cache:
distObj = self.cacheOwner.retrieve(doId)
assert distObj.dclass == dclass
# put it in the dictionary:
self.doId2ownerView[doId] = distObj
# and update it.
distObj.generate()
if other:
distObj.updateRequiredOtherFields(dclass, di)
else:
distObj.updateRequiredFields(dclass, di)
# updateRequiredOtherFields calls announceGenerate
else:
# ...it is not in the dictionary or the cache.
# Construct a new one
classDef = dclass.getOwnerClassDef()
if classDef == None:
self.notify.error("Could not create an undefined %s object. Have you created an owner view?" % (dclass.getName()))
distObj = classDef(self)
distObj.dclass = dclass
# Assign it an Id
distObj.doId = doId
# Put the new do in the dictionary
self.doId2ownerView[doId] = distObj
# Update the required fields
distObj.generateInit() # Only called when constructed
distObj.generate()
if other:
distObj.updateRequiredOtherFields(dclass, di)
else:
distObj.updateRequiredFields(dclass, di)
# updateRequiredOtherFields calls announceGenerate
dclass.stopGenerate()
print dclass.getName()
if distObj.dclass.getName() == 'TagPlayer':
player = self.doId2do.get(doId)
if player:
self.localPlayerGenerated(player)
else:
self.acceptOnce('generate-%d' % doId, self.localPlayerGenerated, [player])
elif distObj.dclass.getName() == 'TagAvatar':
av = self.doId2do.get(doId)
if av:
self.localAvatarGenerated(av)
else:
self.acceptOnce('generate-%d' % doId, self.localAvatarGenerated, [av])
def handleDelete(self, di):
doId = di.getUint32()
if doId in self.doId2do:
obj = self.doId2do[doId]
del self.doId2do[doId]
obj.deleteOrDelay()
def localPlayerGenerated(self, player):
self.player = player
self.player.setupLocalPlayer(self)
self.player.setPoster(self.posterData)
def locateAvatar(self, zoneId):
if self.av:
dg = PyDatagram()
dg.addUint16(CLIENT_OBJECT_LOCATION)
dg.addUint32(self.av.doId)
dg.addUint32(self.timeManager.doId)
dg.addUint32(zoneId)
self.send(dg)
def handleResponse(self, resp):
if resp == 1:
self.acceptOnce(self.uniqueName('gotTimeSync'), self.syncReady)
self.mgrInterest = self.addInterest(self.GameGlobalsId, 1, 'game manager')
def syncReady(self):
""" Now we've got the TimeManager manifested, and we're in
sync with the server time. Now we can enter the world. Check
to see if we've received our doIdBase yet. """
self.waitForGame()
#if self.haveCreateAuthority():
# self.gotCreateReady()
#else:
# Not yet, keep waiting a bit longer.
# self.accept(self.uniqueName('createReady'), self.gotCreateReady)
def gotCreateReady(self):
""" Ready to enter the world. Expand our interest to include
zone 2, and wait for a TagGame to show up. """
if not self.haveCreateAuthority():
# Not ready yet.
return
self.ignore(self.uniqueName('createReady'))
self.waitForGame()
def joinGame(self, game):
""" Now we're involved in a game. """
self.ignore(self.uniqueName('joinGame'))
self.accept(self.uniqueName('enterMaze'), self.enterMaze)
if self.chooseGameTask:
taskMgr.remove(self.chooseGameTask)
self.chooseGameTask = None
self.game = game
self.objInterest = self.addInterest(self.timeManager.doId, self.game.objZone, 'game objects')
if not self.player:
self.game.d_requestPlayer()
# Manifest a player. The player always has our "base" doId.
#self.player = TagPlayer(self, name = self.playerName,
# color = self.playerColor,
# gameId = self.game.doId)
#self.createDistributedObject(distObj = self.player, zoneId = self.game.objZone, doId = self.doIdBase, reserveDoId = True)
#self.player.setupLocalPlayer(self)
# Set the saved poster data, and also transmit it to the AI.
#self.player.setPoster(self.posterData)
self.game.sendUpdate('setPoster', [self.posterData])
self.accept(self.uniqueName('resetGame'), self.resetGame)
def resetGame(self):
""" Exit the game and wait for a new one. """
taskMgr.remove('moveAvatar')
self.ignoreAll()
self.stopPaint()
self.nextGameId = 0
if self.game:
self.nextGameId = self.game.nextGameId
self.game.cleanup()
self.game = None
#if self.av:
# self.sendDeleteMsg(self.av.doId)
# self.av = None
#if self.player:
# self.sendDeleteMsg(self.player.doId)
# self.player = None
self.waitForGame()
def waitForGame(self):
""" Wait for a game to be generated for us to join. """
self.makeWaitingText()
self.accept(self.uniqueName('joinGame'), self.joinGame)
self.gamesListInterest = self.addInterest(self.timeManager.doId, 2, 'games list')
if self.chooseGameTask:
taskMgr.remove(self.chooseGameTask)
self.chooseGameTask = None
if self.nextGameId:
game = self.doId2do.get(self.nextGameId)
if game:
# We already have the game we're waiting for.
game.d_requestJoin()
# If we're waiting for a particular game, give it time to
# show up.
self.chooseGameTask = taskMgr.doMethodLater(15, self.__chooseGame, 'chooseGame')
else:
# Otherwise, take whatever we get.
self.chooseGameTask = taskMgr.doMethodLater(1, self.__chooseGame, 'chooseGame')
def __chooseGame(self, task):
""" Selects one of the available games to join at random. """
self.chooseGameTask = None
# Choose a game to join at random.
availableGames = []
for game in self.allGames:
if game.gameActive and not game.rejectedMe:
availableGames.append(game)
if not availableGames:
# Hmm, no games to choose. Ask for a new one.
self.timeManager.d_requestNewGame()
self.waitForGame()
return
game = random.choice(availableGames)
game.d_requestJoin()
def enterMaze(self, maze):
self.ignore(self.uniqueName('enterMaze'))
# We've got a maze.
self.maze = maze
#self.setInterestZones([1, 2])
if self.waitingText:
self.waitingText.destroy()
self.waitingText = None
# If we're not running in a web and don't have a web-based
# score table, then create an onscreen score table.
if not self.scoreTable:
tnp = base.a2dTopRight.attachNewNode('onscreenScore')
self.onscreenScoreLeft = TextNode('onscreenScoreLeft')
self.onscreenScoreLeft.setShadow(0.05, 0.05)
self.onscreenScoreRight = TextNode('onscreenScoreRight')
self.onscreenScoreRight.setShadow(0.05, 0.05)
self.onscreenScoreRight.setAlign(TextNode.ARight)
l = tnp.attachNewNode(self.onscreenScoreLeft)
l.setX(-12)
r = tnp.attachNewNode(self.onscreenScoreRight)
tnp.setScale(0.07)
tnp.setPos(-0.1, 0, -0.1)
self.player.setScore(0)
# A CollisionTraverser to detect when the avatar hits walls.
self.avTrav = CollisionTraverser('avTrav')
self.avTrav.setRespectPrevTransform(True)
# A separate CollisionTraverser to ensure the camera still has
# a line-of-sight to the avatar.
self.camTrav = CollisionTraverser('camTrav')
self.camSeg = CollisionSegment((0, 0, 0), (0, 1, 0))
camSegNode = CollisionNode('camSeg')
camSegNode.addSolid(self.camSeg)
self.camSegNP = base.camera.attachNewNode(camSegNode)
self.camSegNP.setCollideMask(BitMask32(0))
camSegNode.setFromCollideMask(Globals.WallBit)
self.camSegHandler = CollisionHandlerEvent()
self.camSegHandler.setInPattern('blockVis')
self.camSegHandler.setOutPattern('unblockVis')
self.camTrav.addCollider(self.camSegNP, self.camSegHandler)
self.accept('blockVis', self.blockVis)
self.accept('unblockVis', self.unblockVis)
# And yet another CollisionTraverser to detect where the spray
# paint is being applied.
self.paintTrav = CollisionTraverser('paintTrav')
self.paintRay = CollisionSegment((0, 0, 0), (0, 1, 0))
paintRayNode = CollisionNode('paintRay')
paintRayNode.addSolid(self.paintRay)
self.paintRayNP = base.cam.attachNewNode(paintRayNode)
self.paintRayNP.setCollideMask(BitMask32(0))
paintRayNode.setFromCollideMask(Globals.WallBit | Globals.FloorBit | Globals.AvatarBit | Globals.SelfBit)
self.paintRayQueue = CollisionHandlerQueue()
self.paintTrav.addCollider(self.paintRayNP, self.paintRayQueue)
#self.paintTrav.showCollisions(render)
# A buffer for rendering the false-color avatar offscreen.
self.avbuf = None
if base.win:
self.avbufTex = Texture('avbuf')
self.avbuf = base.win.makeTextureBuffer('avbuf', 256, 256, self.avbufTex, True)
cam = Camera('avbuf')
cam.setLens(base.camNode.getLens())
self.avbufCam = base.cam.attachNewNode(cam)
dr = self.avbuf.makeDisplayRegion()
dr.setCamera(self.avbufCam)
self.avbuf.setActive(False)
self.avbuf.setClearColor((1, 0, 0, 1))
cam.setCameraMask(Globals.AvBufMask)
base.camNode.setCameraMask(Globals.CamMask)
# avbuf renders everything it sees with the gradient texture.
tex = loader.loadTexture('models/gradient.png')
np = NodePath('np')
np.setTexture(tex, 100)
np.setColor((1, 1, 1, 1), 100)
np.setColorScaleOff(100)
np.setTransparency(TransparencyAttrib.MNone, 100)
np.setLightOff(100)
cam.setInitialState(np.getState())
render.hide(Globals.AvBufMask)
# Manifest an avatar for ourselves.
if self.av:
self.localAvatarGenerated(self.av)
else:
self.game.d_requestAvatar(self.player.doId)
#self.av = TagAvatar(self, playerId = self.player.doId)
#x = random.uniform(0, maze.xsize * Globals.MazeScale)
#y = random.uniform(0, maze.ysize * Globals.MazeScale)
#h = random.uniform(0, 360)
#self.av.setPosHpr(x, y, 0, h, 0, 0)
#self.createDistributedObject(distObj = self.av, zoneId = 2)
#self.av.setupLocalAvatar(self)
#self.player.b_setAvId(self.av.doId)
def localAvatarGenerated(self, av):
self.av = av
x = random.uniform(0, self.maze.xsize * Globals.MazeScale)
y = random.uniform(0, self.maze.ysize * Globals.MazeScale)
h = random.uniform(0, 360)
self.av.setPosHpr(x, y, 0, h, 0, 0)
self.av.setupLocalAvatar(self)
# The camera arm follows behind the avatar.
self.cameraArmHinge = self.av.attachNewNode('cameraArmHinge')
self.cameraArm = self.cameraArmHinge.attachNewNode('cameraArm')
self.cameraArm.setPos(0, -10, 2)
base.camera.setPosHpr(self.cameraArm, 0, 0, 0, 0, 0, 0)
# Sound effect while painting.
self.spraySfx = loader.loadSfx('models/spray_middle.ogg')
if self.spraySfx:
self.spraySfx.setLoop(True)
# Listen for movement control keys.
for key in Globals.ControlKeys:
self.accept(key, self.setKey, [key, True])
self.accept('control-' + key, self.setKey, [key, True])
self.accept(key + '-up', self.setKey, [key, False])
# Holding mouse button 3, or control-mouse 1 (for macs),
# activates camera-mouse mode.
self.accept('mouse3', self.enableCameraMouse, [True])
self.accept('control-mouse1', self.enableCameraMouse, [True])
self.accept('mouse3-up', self.enableCameraMouse, [False])
self.accept('mouse1-up', self.enableCameraMouse, [False])
self.cameraMouseStart = None
# Holding mouse button 1 paints.
self.accept('mouse1', self.startPaint)
# Now add the task that manages the avatar and camera
# positions each frame.
taskMgr.remove('moveAvatar')
taskMgr.add(self.moveAvatar, 'moveAvatar')
# Let the DistributedSmoothNode take care of broadcasting the
# position updates several times a second.
self.av.startPosHprBroadcast()
def enableCameraMouse(self, enable):
self.stopPaint()
self.cameraMouseStart = None
if enable and base.mouseWatcherNode.hasMouse():
# Record the starting position of the mouse pointer.
mpos = base.mouseWatcherNode.getMouse()
self.cameraMouseStart = (mpos.getX(), mpos.getY())
self.cameraMouseOrigHpr = self.cameraArmHinge.getHpr()
# While in camera mouse mode, the camera is directly
# parented to the camera arm.
base.camera.wrtReparentTo(self.cameraArm)
base.camera.setScale(1)
else:
# When no longer in camera mouse mode, the camera is
# attached to render, and lags a little behind the camera
# arm.
base.camera.wrtReparentTo(render)
base.camera.setScale(1)
def blockVis(self, entry):
""" A wall is between the camera and the avatar. Make it
transparent. """
## normal = entry.getSurfaceNormal(base.camera)
## if normal[1] > 0:
## # This wall is facing the wrong way; it doesn't count.
## return
sx, sy, dir = entry.getIntoNodePath().getNetPythonTag('step')
cell = Cell.MazeCells.get((sx, sy), None)
if cell:
cell.setFade(dir, True)
def unblockVis(self, entry):
""" The wall is no longer between the camera and the avatar.
Make it opaque again. """
sx, sy, dir = entry.getIntoNodePath().getNetPythonTag('step')
cell = Cell.MazeCells.get((sx, sy), None)
if cell:
cell.setFade(dir, False)
def startPaint(self):
taskMgr.add(self.doPaint, 'doPaint')
if self.spraySfx:
self.spraySfx.play()
def stopPaint(self):
taskMgr.remove('doPaint')
if self.spraySfx:
self.spraySfx.stop()
if self.paintThing:
self.paintThing.clearPaint()
self.paintThing = None
def doPaint(self, task):
# The user is holding down the mouse button. Apply spray
# paint to whatever surface is under the mouse.
if not base.mouseWatcherNode.hasMouse():
# Mouse not in the window.
return task.cont
mpos = base.mouseWatcherNode.getMouse()
self.paintRay.setFromLens(base.camNode, mpos.getX(), mpos.getY())
self.paintTrav.traverse(render)
self.paintRayQueue.sortEntries()
# Find the first entry with a normal pointing torwards the
# camera.
for entry in self.paintRayQueue.getEntries():
normal = entry.getSurfaceNormal(base.cam)
if normal[1] > 0:
# Facing the wrong way.
continue
paintType = entry.getIntoNodePath().getNetTag('paintType')
if not paintType:
# Not paintable.
continue
if paintType == 'cell':
if self.__paintCell(entry):
return task.cont
elif paintType == 'avatar':
if self.__paintAvatar(entry):
return task.cont
return task.cont
def __paintCell(self, entry):
""" Paints onto the cell wall, ceiling, or floor. Returns
true on success, false on failure. """
# Check the wall's normal first; it must be pointed vaguely
# towards the avatar to count.
point = entry.getSurfacePoint(self.av.center)
normal = entry.getSurfaceNormal(self.av.center)
d = normal.dot(point)
if d > 0:
# The wall is facing the wrong way; it doesn't count.
return False
# The length of the point (treated as a vector), as seen from
# the avatar, represents the distance to this point on the
# wall. We attenuate the paint color based on this distance.
distance = point.length()
alpha = min(5.0 / (distance + 0.0001), 1.0)
alpha = alpha * alpha
# Now get the point in world coordinates, to determine the
# paint location.
point = entry.getSurfacePoint(render)
point = Point3(point[0] / Globals.MazeScale,
point[1] / Globals.MazeScale,
point[2] / Globals.MazeZScale)
sx, sy, dir = entry.getIntoNodePath().getNetPythonTag('step')
dx = point[0] - sx
dy = point[1] - sy
cell = Cell.MazeCells.get((sx, sy), None)
if cell and not cell.getFade(dir):
if cell is not self.paintThing:
cell.clearPaint()
colorBrush, whiteBrush = self.player.getBrushes(alpha)
cell.paint(colorBrush, whiteBrush, dx, dy, point[2], dir)
self.paintThing = cell
return True
return False
def __paintAvatar(self, entry):
""" Paints onto an avatar. Returns true on success, false on
failure (because there are no avatar pixels under the mouse,
for instance). """
# First, we have to render the avatar in its false-color
# image, to determine which part of its texture is under the
# mouse.
if not self.avbuf:
return False
avId = entry.getIntoNodePath().getNetPythonTag('avId')
av = self.doId2do.get(avId)
if not av:
return False
mpos = base.mouseWatcherNode.getMouse()
av.showThrough(Globals.AvBufMask)
self.avbuf.setActive(True)
base.graphicsEngine.renderFrame()
av.show(Globals.AvBufMask)
self.avbuf.setActive(False)
# Now we have the rendered image in self.avbufTex.
if not self.avbufTex.hasRamImage():
print "Weird, no image in avbufTex."
return False
p = PNMImage()
self.avbufTex.store(p)
ix = int((1 + mpos.getX()) * p.getXSize() * 0.5)
iy = int((1 - mpos.getY()) * p.getYSize() * 0.5)
x = 1
if ix >= 0 and ix < p.getXSize() and iy >= 0 and iy < p.getYSize():
s = p.getBlue(ix, iy)
t = p.getGreen(ix, iy)
x = p.getRed(ix, iy)
if x > 0.5:
# Off the avatar.
return False
# At point (s, t) on the avatar's map.
# Get the distance to the avatar, for attenuation.
distance = self.av.getDistance(av)
alpha = min(5.0 / (distance + 0.0001), 1.0)
alpha = alpha * alpha
if av is not self.paintThing:
av.clearPaint()
colorBrush, whiteBrush = self.player.getBrushes(alpha)
av.paint(colorBrush, whiteBrush, s, t)
self.paintThing = av
return True
def changeAvZone(self, zoneId):
""" Move the avatar into the indicated zone. """
# Move our avatar into the indicated zone
self.setObjectZone(self.av, zoneId)
def setKey(self, key, value):
self.keyMap[key] = value
def __determineCell(self, node):
""" Returns the cell that the indicated node is positioned
within, or None if it is not within any cell. """
sx = int(node.getX() / Globals.MazeScale)
sy = int(node.getY() / Globals.MazeScale)
cell = Cell.MazeCells.get((sx, sy), None)
return cell
def moveAvatar(self, task):
""" Moves the avatar according to the WASD or arrow keys. """
# The amount of time elapsed since last frame.
dt = globalClock.getDt()
# Record the current position in case he goes off the grid.
origPos = self.av.getPos()
# The current position determines the active cell.
self.avCell = self.__determineCell(self.av)
moving = False
if self.keyMap['arrow_left'] or self.keyMap['a']:
self.av.setH(self.av.getH() + dt * Globals.TurnPerSecond)
moving = True
if self.keyMap['arrow_right'] or self.keyMap['d']:
self.av.setH(self.av.getH() - dt * Globals.TurnPerSecond)
moving = True
if self.keyMap['arrow_down'] or self.keyMap['s']:
self.av.setFluidY(self.av, -dt * Globals.BackwardPerSecond)
moving = True
if self.keyMap['arrow_up'] or self.keyMap['w']:
self.av.setFluidY(self.av, dt * Globals.ForwardPerSecond)
moving = True
# Play the run animation if we're moving.
if moving:
self.av.setMoving(True)