forked from panda3d/panda3d
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
410 lines (311 loc) · 13.2 KB
/
main.py
File metadata and controls
410 lines (311 loc) · 13.2 KB
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
"""
Show how to use libRocket in Panda3D.
"""
import sys
from panda3d.core import loadPrcFile, loadPrcFileData, Point3,Vec4, Mat4, LoaderOptions # @UnusedImport
from panda3d.core import DirectionalLight, AmbientLight, PointLight
from panda3d.core import Texture, PNMImage
from panda3d.core import PandaSystem
import random
from direct.interval.LerpInterval import LerpHprInterval, LerpPosInterval, LerpFunc
from direct.showbase.ShowBase import ShowBase
# workaround: https://www.panda3d.org/forums/viewtopic.php?t=10062&p=99697#p99054
#from panda3d import rocket
import _rocketcore as rocket
from panda3d.rocket import RocketRegion, RocketInputHandler
loadPrcFileData("", "model-path $MAIN_DIR/assets")
import console
global globalClock
class MyApp(ShowBase):
def __init__(self):
ShowBase.__init__(self)
self.win.setClearColor(Vec4(0.2, 0.2, 0.2, 1))
self.disableMouse()
self.render.setShaderAuto()
dlight = DirectionalLight('dlight')
alight = AmbientLight('alight')
dlnp = self.render.attachNewNode(dlight)
alnp = self.render.attachNewNode(alight)
dlight.setColor((0.8, 0.8, 0.5, 1))
alight.setColor((0.2, 0.2, 0.2, 1))
dlnp.setHpr(0, -60, 0)
self.render.setLight(dlnp)
self.render.setLight(alnp)
# Put lighting on the main scene
plight = PointLight('plight')
plnp = self.render.attachNewNode(plight)
plnp.setPos(0, 0, 10)
self.render.setLight(plnp)
self.render.setLight(alnp)
self.loadRocketFonts()
self.loadingTask = None
#self.startModelLoadingAsync()
self.startModelLoading()
self.inputHandler = RocketInputHandler()
self.mouseWatcher.attachNewNode(self.inputHandler)
self.openLoadingDialog()
def loadRocketFonts(self):
""" Load fonts referenced from e.g. 'font-family' RCSS directives.
Note: the name of the font as used in 'font-family'
is not always the same as the filename;
open the font in your OS to see its display name.
"""
rocket.LoadFontFace("modenine.ttf")
def startModelLoading(self):
self.monitorNP = None
self.keyboardNP = None
self.loadingError = False
self.taskMgr.doMethodLater(1, self.loadModels, 'loadModels')
def loadModels(self, task):
self.monitorNP = self.loader.loadModel("monitor")
self.keyboardNP = self.loader.loadModel("takeyga_kb")
def startModelLoadingAsync(self):
"""
NOTE: this seems to invoke a few bugs (crashes, sporadic model
reading errors, etc) so is disabled for now...
"""
self.monitorNP = None
self.keyboardNP = None
self.loadingError = False
# force the "loading" to take some time after the first run...
options = LoaderOptions()
options.setFlags(options.getFlags() | LoaderOptions.LFNoCache)
def gotMonitorModel(model):
if not model:
self.loadingError = True
self.monitorNP = model
self.loader.loadModel("monitor", loaderOptions=options, callback=gotMonitorModel)
def gotKeyboardModel(model):
if not model:
self.loadingError = True
self.keyboardNP = model
self.loader.loadModel("takeyga_kb", loaderOptions=options, callback=gotKeyboardModel)
def openLoadingDialog(self):
self.userConfirmed = False
self.windowRocketRegion = RocketRegion.make('pandaRocket', self.win)
self.windowRocketRegion.setActive(1)
self.windowRocketRegion.setInputHandler(self.inputHandler)
self.windowContext = self.windowRocketRegion.getContext()
self.loadingDocument = self.windowContext.LoadDocument("loading.rml")
if not self.loadingDocument:
raise AssertionError("did not find loading.rml")
self.loadingDots = 0
el = self.loadingDocument.GetElementById('loadingLabel')
self.loadingText = el.first_child
self.stopLoadingTime = globalClock.getFrameTime() + 3
self.loadingTask = self.taskMgr.add(self.cycleLoading, 'doc changer')
# note: you may encounter errors like 'KeyError: 'document'"
# when invoking events using methods from your own scripts with this
# obvious code:
#
# self.loadingDocument.AddEventListener('aboutToClose',
# self.onLoadingDialogDismissed, True)
#
# A workaround is to define callback methods in standalone Python
# files with event, self, and document defined to None.
#
# see https://www.panda3d.org/forums/viewtopic.php?f=4&t=16412
#
# Or, use this indirection technique to work around the problem,
# by publishing the app into the context, then accessing it through
# the document's context...
self.windowContext.app = self
self.loadingDocument.AddEventListener('aboutToClose',
'document.context.app.handleAboutToClose()', True)
self.loadingDocument.Show()
def handleAboutToClose(self):
self.userConfirmed = True
if self.monitorNP and self.keyboardNP:
self.onLoadingDialogDismissed()
def attachCustomRocketEvent(self, document, rocketEventName, pandaHandler, once=False):
# handle custom event
# note: you may encounter errors like 'KeyError: 'document'"
# when invoking events using methods from your own scripts with this
# obvious code:
#
# self.loadingDocument.AddEventListener('aboutToClose',
# self.onLoadingDialogDismissed, True)
#
# see https://www.panda3d.org/forums/viewtopic.php?f=4&t=16412
# this technique converts Rocket events to Panda3D events
pandaEvent = 'panda.' + rocketEventName
document.AddEventListener(
rocketEventName,
"messenger.send('" + pandaEvent + "', [event])")
if once:
self.acceptOnce(pandaEvent, pandaHandler)
else:
self.accept(pandaEvent, pandaHandler)
def cycleLoading(self, task):
"""
Update the "loading" text in the initial window until
the user presses Space, Enter, or Escape or clicks (see loading.rxml)
or sufficient time has elapsed (self.stopLoadingTime).
"""
text = self.loadingText
now = globalClock.getFrameTime()
if self.monitorNP and self.keyboardNP:
text.text = "Ready"
if now > self.stopLoadingTime or self.userConfirmed:
self.onLoadingDialogDismissed()
return task.done
elif self.loadingError:
text.text = "Assets not found"
else:
count = 5
intv = int(now * 4) % count # @UndefinedVariable
text.text = "Loading" + ("." * (1+intv)) + (" " * (2 - intv))
return task.cont
def onLoadingDialogDismissed(self):
""" Once a models are loaded, stop 'loading' and proceed to 'start' """
if self.loadingDocument:
if self.loadingTask:
self.taskMgr.remove(self.loadingTask)
self.loadingTask = None
self.showStarting()
def fadeOut(self, element, time):
""" Example updating RCSS attributes from code
by modifying the 'color' RCSS attribute to slowly
change from solid to transparent.
element: the Rocket element whose style to modify
time: time in seconds for fadeout
"""
# get the current color from RCSS effective style
color = element.style.color
# convert to RGBA form
prefix = color[:color.rindex(',')+1].replace('rgb(', 'rgba(')
def updateAlpha(t):
# another way of setting style on a specific element
attr = 'color: ' + prefix + str(int(t)) +');'
element.SetAttribute('style', attr)
alphaInterval = LerpFunc(updateAlpha,
duration=time,
fromData=255,
toData=0,
blendType='easeIn')
return alphaInterval
def showStarting(self):
""" Models are loaded, so update the dialog,
fade out, then transition to the console. """
self.loadingText.text = 'Starting...'
alphaInterval = self.fadeOut(self.loadingText, 0.5)
alphaInterval.setDoneEvent('fadeOutFinished')
def fadeOutFinished():
if self.loadingDocument:
self.loadingDocument.Close()
self.loadingDocument = None
self.createConsole()
self.accept('fadeOutFinished', fadeOutFinished)
alphaInterval.start()
def createConsole(self):
""" Create the in-world console, which displays
a RocketRegion in a GraphicsBuffer, which appears
in a Texture on the monitor model. """
self.monitorNP.reparentTo(self.render)
self.monitorNP.setScale(1.5)
self.keyboardNP.reparentTo(self.render)
self.keyboardNP.setHpr(-90, 0, 15)
self.keyboardNP.setScale(20)
self.placeItems()
self.setupRocketConsole()
# re-enable mouse
mat=Mat4(self.camera.getMat())
mat.invertInPlace()
self.mouseInterfaceNode.setMat(mat)
self.enableMouse()
def placeItems(self):
self.camera.setPos(0, -20, 0)
self.camera.setHpr(0, 0, 0)
self.monitorNP.setPos(0, 0, 1)
self.keyboardNP.setPos(0, -5, -2.5)
def setupRocketConsole(self):
"""
Place a new rocket window onto a texture
bound to the front of the monitor.
"""
self.win.setClearColor(Vec4(0.5, 0.5, 0.8, 1))
faceplate = self.monitorNP.find("**/Faceplate")
assert faceplate
mybuffer = self.win.makeTextureBuffer("Console Buffer", 1024, 512)
tex = mybuffer.getTexture()
tex.setMagfilter(Texture.FTLinear)
tex.setMinfilter(Texture.FTLinear)
faceplate.setTexture(tex, 1)
self.rocketConsole = RocketRegion.make('console', mybuffer)
self.rocketConsole.setInputHandler(self.inputHandler)
self.consoleContext = self.rocketConsole.getContext()
self.console = console.Console(self, self.consoleContext, 40, 13, self.handleCommand)
self.console.addLine("Panda DOS")
self.console.addLine("type 'help'")
self.console.addLine("")
self.console.allowEditing(True)
def handleCommand(self, command):
if command is None:
# hack for Ctrl-Break
self.spewInProgress = False
self.console.addLine("*** break ***")
self.console.allowEditing(True)
return
command = command.strip()
if not command:
return
tokens = [x.strip() for x in command.split(' ')]
command = tokens[0].lower()
if command == 'help':
self.console.addLines([
"Sorry, this is utter fakery.",
"You won't get much more",
"out of this simulation unless",
"you program it yourself. :)"
])
elif command == 'dir':
self.console.addLines([
"Directory of C:\\:",
"HELP COM 72 05-06-2015 14:07",
"DIR COM 121 05-06-2015 14:11",
"SPEW COM 666 05-06-2015 15:02",
" 2 Files(s) 859 Bytes.",
" 0 Dirs(s) 7333 Bytes free.",
""])
elif command == 'cls':
self.console.cls()
elif command == 'echo':
self.console.addLine(' '.join(tokens[1:]))
elif command == 'ver':
self.console.addLine('Panda DOS v0.01 in Panda3D ' + PandaSystem.getVersionString())
elif command == 'spew':
self.startSpew()
elif command == 'exit':
self.console.setPrompt("System is shutting down NOW!")
self.terminateMonitor()
else:
self.console.addLine("command not found")
def startSpew(self):
self.console.allowEditing(False)
self.console.addLine("LINE NOISE 1.0")
self.console.addLine("")
self.spewInProgress = True
# note: spewage always occurs in 'doMethodLater';
# time.sleep() would be pointless since the whole
# UI would be frozen during the wait.
self.queueSpew(2)
def queueSpew(self, delay=0.1):
self.taskMgr.doMethodLater(delay, self.spew, 'spew')
def spew(self, task):
# generate random spewage, just like on TV!
if not self.spewInProgress:
return
def randchr():
return chr(int(random.random() < 0.25 and 32 or random.randint(32, 127)))
line = ''.join([randchr() for _ in range(40) ])
self.console.addLine(line)
self.queueSpew()
def terminateMonitor(self):
alphaInterval = self.fadeOut(self.console.getTextContainer(), 2)
alphaInterval.setDoneEvent('fadeOutFinished')
def fadeOutFinished():
sys.exit(0)
self.accept('fadeOutFinished', fadeOutFinished)
alphaInterval.start()
app = MyApp()
app.run()