ShowBase.py 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175
  1. # This module redefines the builtin import function with one
  2. # that prints out every import it does in a hierarchical form
  3. # Annoying and very noisy, but sometimes useful
  4. # import VerboseImport
  5. from PandaModules import *
  6. from DirectNotifyGlobal import *
  7. from MessengerGlobal import *
  8. from TaskManagerGlobal import *
  9. from EventManagerGlobal import *
  10. from PythonUtil import *
  11. from ParticleManagerGlobal import *
  12. from PhysicsManagerGlobal import *
  13. from IntervalManager import ivalMgr
  14. import Task
  15. import EventManager
  16. import math
  17. import sys
  18. import Loader
  19. import time
  20. import FSM
  21. import State
  22. import DirectObject
  23. __builtins__["FADE_SORT_INDEX"] = 1000
  24. __builtins__["NO_FADE_SORT_INDEX"] = 2000
  25. # Now ShowBase is a DirectObject. We need this so ShowBase can hang
  26. # hooks on messages, particularly on window-event. This doesn't
  27. # *seem* to cause anyone any problems.
  28. class ShowBase(DirectObject.DirectObject):
  29. notify = directNotify.newCategory("ShowBase")
  30. def __init__(self):
  31. # Get the dconfig object
  32. self.config = ConfigConfigureGetConfigConfigShowbase
  33. if self.config.GetBool('use-vfs', 1):
  34. vfs = VirtualFileSystem.getGlobalPtr()
  35. else:
  36. vfs = None
  37. # Store dconfig variables
  38. self.wantTk = self.config.GetBool('want-tk', 0)
  39. self.sfxActive = self.config.GetBool('audio-sfx-active', 1)
  40. self.musicActive = self.config.GetBool('audio-music-active', 1)
  41. self.wantFog = self.config.GetBool('want-fog', 1)
  42. self.screenshotExtension = self.config.GetString('screenshot-extension', 'jpg')
  43. self.musicManager = None
  44. self.musicManagerIsValid = None
  45. self.sfxManagerList = []
  46. self.sfxManagerIsValidList = []
  47. self.wantDIRECT = self.config.GetBool('want-directtools', 0)
  48. self.wantStats = self.config.GetBool('want-stats', 0)
  49. # Fill this in with a function to invoke when the user "exits"
  50. # the program by closing the main window.
  51. self.exitFunc = None
  52. taskMgr.taskTimerVerbose = self.config.GetBool('task-timer-verbose', 0)
  53. taskMgr.extendedExceptions = self.config.GetBool('extended-exceptions', 0)
  54. taskMgr.pStatsTasks = self.config.GetBool('pstats-tasks', 0)
  55. # Set up the TaskManager to reset the PStats clock back
  56. # whenever we resume from a pause. This callback function is
  57. # a little hacky, but we can't call it directly from within
  58. # the TaskManager because he doesn't know about PStats (and
  59. # has to run before libpanda is even loaded).
  60. taskMgr.resumeFunc = PStatClient.resumeAfterPause
  61. fsmRedefine = self.config.GetBool('fsm-redefine', 0)
  62. State.FsmRedefine = fsmRedefine
  63. # This is used for syncing multiple PCs in a distributed cluster
  64. try:
  65. # Has the cluster sync variable been set externally?
  66. self.clusterSyncFlag = clusterSyncFlag
  67. except NameError:
  68. # Has the clusterSyncFlag been set via a config variable
  69. self.clusterSyncFlag = base.config.GetBool('cluster-sync', 0)
  70. self.hidden = NodePath('hidden')
  71. # We need a graphics engine to manage the actual rendering.
  72. self.graphicsEngine = GraphicsEngine()
  73. self.setupRender()
  74. self.setupRender2d()
  75. self.setupDataGraph()
  76. # This is a placeholder for a CollisionTraverser. If someone
  77. # stores a CollisionTraverser pointer here, we'll traverse it
  78. # in the collisionloop task.
  79. self.cTrav = 0
  80. # Ditto for an AppTraverser.
  81. self.appTrav = 0
  82. # This is the DataGraph traverser, which we might as well
  83. # create now.
  84. self.dgTrav = DataGraphTraverser()
  85. # base.win is the main, or only window; base.winList is a list of
  86. # *all* windows. Similarly with base.camList.
  87. self.win = None
  88. self.winList = []
  89. self.mainWinMinimized = 0
  90. self.pipe = None
  91. self.pipeList = []
  92. self.mak = None
  93. self.cam = None
  94. self.camList = []
  95. self.camNode = None
  96. self.camLens = None
  97. #self.camera = self.render.attachNewNode('camera')
  98. self.camera = None
  99. self.cameraList = []
  100. self.camera2d = self.render2d.attachNewNode('camera2d')
  101. # Now that we've set up the window structures, assign an exitfunc.
  102. self.oldexitfunc = getattr(sys, 'exitfunc', None)
  103. sys.exitfunc = self.exitfunc
  104. # Open the default rendering window.
  105. if self.config.GetBool('open-default-window', 1):
  106. self.openMainWindow()
  107. if self.win == None:
  108. # Try a little harder if the window wouldn't open.
  109. self.makeAllPipes()
  110. while self.win == None and len(self.pipeList) > 1:
  111. self.pipeList.remove(self.pipe)
  112. self.pipe = self.pipeList[0]
  113. self.openMainWindow()
  114. self.loader = Loader.Loader(self)
  115. self.eventMgr = eventMgr
  116. self.messenger = messenger
  117. self.taskMgr = taskMgr
  118. # Particle manager
  119. self.particleMgr = particleMgr
  120. self.particleMgr.setFrameStepping(1)
  121. self.particleMgrEnabled = 0
  122. # Physics manager
  123. self.physicsMgr = physicsMgr
  124. integrator = LinearEulerIntegrator()
  125. self.physicsMgr.attachLinearIntegrator(integrator)
  126. self.physicsMgrEnabled = 0
  127. self.physicsMgrAngular = 0
  128. self.createBaseAudioManagers()
  129. self.createStats()
  130. self.AppHasAudioFocus = 1
  131. __builtins__["base"] = self
  132. __builtins__["render2d"] = self.render2d
  133. __builtins__["aspect2d"] = self.aspect2d
  134. __builtins__["render"] = self.render
  135. __builtins__["hidden"] = self.hidden
  136. __builtins__["camera"] = self.camera
  137. __builtins__["loader"] = self.loader
  138. __builtins__["taskMgr"] = self.taskMgr
  139. __builtins__["eventMgr"] = self.eventMgr
  140. __builtins__["messenger"] = self.messenger
  141. __builtins__["config"] = self.config
  142. __builtins__["run"] = self.run
  143. __builtins__["ostream"] = Notify.out()
  144. __builtins__["directNotify"] = directNotify
  145. __builtins__["globalClock"] = ClockObject.getGlobalClock()
  146. __builtins__["vfs"] = vfs
  147. # Now hang a hook on the window-event from Panda. This allows
  148. # us to detect when the user resizes, minimizes, or closes the
  149. # main window.
  150. self.accept('window-event', self.__windowEvent)
  151. # Transition effects (fade, iris, etc)
  152. import Transitions
  153. self.transitions = Transitions.Transitions(self.loader)
  154. # Tk
  155. if self.wantTk:
  156. import TkGlobal
  157. if self.wantDIRECT:
  158. import DirectSession
  159. direct.enable()
  160. else:
  161. __builtins__["direct"] = self.direct = None
  162. self.restart()
  163. def exitfunc(self):
  164. """exitfunc(self)
  165. This should be assigned to sys.exitfunc to be called just
  166. before Python shutdown. It guarantees that the Panda window
  167. is closed cleanly, so that we free system resources, restore
  168. the desktop and keyboard functionality, etc.
  169. """
  170. self.graphicsEngine.removeAllWindows()
  171. del self.win
  172. del self.winList
  173. del self.pipe
  174. try:
  175. direct.panel.destroy()
  176. except StandardError:
  177. pass
  178. if self.oldexitfunc:
  179. self.oldexitfunc()
  180. def makeDefaultPipe(self):
  181. """makeDefaultPipe(self)
  182. Creates the default GraphicsPipe, which will be used to make
  183. windows unless otherwise specified.
  184. """
  185. assert(self.pipe == None)
  186. selection = GraphicsPipeSelection.getGlobalPtr()
  187. selection.printPipeTypes()
  188. self.pipe = selection.makeDefaultPipe()
  189. if not self.pipe:
  190. self.notify.error("No graphics pipe is available! Check your Configrc!")
  191. self.notify.info("Default graphics pipe is %s (%s)." % (self.pipe.getInterfaceName(), self.pipe.getType().getName()))
  192. self.pipeList.append(self.pipe)
  193. def makeAllPipes(self):
  194. """makeAllPipes(self)
  195. Creates all GraphicsPipes that the system knows about and fill up
  196. self.pipeList with them.
  197. """
  198. shouldPrintPipes = 0
  199. selection = GraphicsPipeSelection.getGlobalPtr()
  200. selection.loadAuxModules()
  201. # First, we should make sure the default pipe exists.
  202. if self.pipe == None:
  203. self.makeDefaultPipe()
  204. # Now go through the list of known pipes, and make each one if
  205. # we don't have one already.
  206. numPipeTypes = selection.getNumPipeTypes()
  207. for i in range(numPipeTypes):
  208. pipeType = selection.getPipeType(i)
  209. # Do we already have a pipe of this type on the list?
  210. # This operation is n-squared, but presumably there won't
  211. # be more than a handful of pipe types, so who cares.
  212. already = 0
  213. for pipe in self.pipeList:
  214. if pipe.getType() == pipeType:
  215. already = 1
  216. if not already:
  217. pipe = selection.makePipe(pipeType)
  218. if pipe:
  219. self.notify.info("Got aux graphics pipe %s (%s)." % (pipe.getInterfaceName(), pipe.getType().getName()))
  220. self.pipeList.append(pipe)
  221. else:
  222. self.notify.info("Could not make graphics pipe %s." % (pipeType.getName()))
  223. def openWindow(self):
  224. """openWindow(self)
  225. Invokes ChanConfig to create a window and adds it to the list
  226. of windows that are to be updated every frame.
  227. """
  228. if self.pipe == None:
  229. self.makeDefaultPipe()
  230. chanString = self.config.GetString('chan-config', 'single')
  231. chanConfig = ChanConfig(self.graphicsEngine, self.pipe, chanString,
  232. self.render)
  233. win = chanConfig.getWin()
  234. if win != None:
  235. # Adjust some of the window properties.
  236. props = WindowProperties()
  237. windowTitle = self.config.GetString("window-title", "");
  238. if windowTitle:
  239. props.setTitle(windowTitle)
  240. win.requestProperties(props)
  241. if self.win == None:
  242. self.win = win
  243. self.winList.append(win)
  244. self.getCameras(chanConfig)
  245. return win
  246. def closeWindow(self, win):
  247. """closeWindow(self, win)
  248. Closes the indicated window and removes it from the list of
  249. windows. If it is the main window, clears the main window
  250. pointer to None.
  251. """
  252. # First, remove all of the cameras associated with display
  253. # regions on the window.
  254. numRegions = win.getNumDisplayRegions()
  255. for i in range(numRegions):
  256. dr = win.getDisplayRegion(i)
  257. cam = NodePath(dr.getCamera())
  258. dr.setCamera(NodePath())
  259. if not cam.isEmpty() and cam.node().getNumDisplayRegions() == 0:
  260. # If the camera is used by no other DisplayRegions,
  261. # remove it.
  262. if self.camList.count(cam) != 0:
  263. self.camList.remove(cam)
  264. if not cam.isEmpty():
  265. if cam == self.cam:
  266. self.cam = None
  267. cam.removeNode()
  268. # Now we can actually close the window.
  269. self.graphicsEngine.removeWindow(win)
  270. self.winList.remove(win)
  271. if win == self.win:
  272. self.win = None
  273. def openMainWindow(self):
  274. """openMainWindow(self)
  275. Creates the initial, main window for the application, and sets
  276. up the mouse and render2d structures appropriately for it. If
  277. this method is called a second time, it will close the
  278. previous main window and open a new one, preserving the lens
  279. properties in base.camLens.
  280. The return value is true on success, or false on failure (in
  281. which case base.win may be either None, or the previous,
  282. closed window).
  283. """
  284. success = 1
  285. oldWin = self.win
  286. oldLens = self.camLens
  287. oldClearColorActive = None
  288. if self.win != None:
  289. # Close the previous window.
  290. oldClearColorActive = self.win.getClearColorActive()
  291. oldClearColor = VBase4(self.win.getClearColor())
  292. oldClearDepthActive = self.win.getClearDepthActive()
  293. oldClearDepth = self.win.getClearDepth()
  294. self.closeWindow(self.win)
  295. # Open a new window.
  296. self.openWindow()
  297. if self.win == None:
  298. self.win = oldWin
  299. self.winList.append(oldWin)
  300. success = 0
  301. if self.win != None:
  302. self.setupMouse(self.win)
  303. self.makeCamera2d(self.win, -1, 1, -1, 1)
  304. if oldLens != None:
  305. # Restore the previous lens properties.
  306. self.camNode.setLens(oldLens)
  307. self.camLens = oldLens
  308. if oldClearColorActive != None:
  309. # Restore the previous clear properties.
  310. self.win.setClearColorActive(oldClearColorActive)
  311. self.win.setClearColor(oldClearColor)
  312. self.win.setClearDepthActive(oldClearDepthActive)
  313. self.win.setClearDepth(oldClearDepth)
  314. return success
  315. def setupRender(self):
  316. """setupRender(self)
  317. Creates the render scene graph, the primary scene graph for
  318. rendering 3-d geometry.
  319. """
  320. self.render = NodePath('render')
  321. self.render.setTwoSided(0)
  322. self.backfaceCullingEnabled = 1
  323. self.textureEnabled = 1
  324. self.wireframeEnabled = 0
  325. def setupRender2d(self):
  326. """setupRender2d(self)
  327. Creates the render2d scene graph, the primary scene graph for
  328. 2-d objects and gui elements that are superimposed over the
  329. 3-d geometry in the window.
  330. """
  331. self.render2d = NodePath('render2d')
  332. # Set up some overrides to turn off certain properties which
  333. # we probably won't need for 2-d objects.
  334. # It's particularly important to turn off the depth test,
  335. # since we'll be keeping the same depth buffer already filled
  336. # by the previously-drawn 3-d scene--we don't want to pay for
  337. # a clear operation, but we also don't want to collide with
  338. # that depth buffer.
  339. dt = DepthTestAttrib.make(DepthTestAttrib.MNone)
  340. dw = DepthWriteAttrib.make(DepthWriteAttrib.MOff)
  341. #lt = LightTransition.allOff()
  342. self.render2d.node().setAttrib(dt, 1)
  343. self.render2d.node().setAttrib(dw, 1)
  344. #self.render2d.node().setAttrib(lt, 1)
  345. self.render2d.setMaterialOff(1)
  346. self.render2d.setTwoSided(1, 1)
  347. # The normal 2-d layer has an aspect ratio that matches the
  348. # window, but its coordinate system is square. This means
  349. # anything we parent to render2d gets stretched. For things
  350. # where that makes a difference, we set up aspect2d, which
  351. # scales things back to the right aspect ratio.
  352. # For now, we assume that the window will have an aspect ratio
  353. # matching that of a traditional PC screen (w / h) = (4 / 3)
  354. self.aspectRatio = self.config.GetFloat('aspect-ratio', (4.0 / 3.0))
  355. self.aspect2d = self.render2d.attachNewNode(PGTop("aspect2d"))
  356. self.aspect2d.setScale(1.0 / self.aspectRatio, 1.0, 1.0)
  357. # It's important to know the bounds of the aspect2d screen.
  358. self.a2dTop = 1.0
  359. self.a2dBottom = -1.0
  360. self.a2dLeft = -self.aspectRatio
  361. self.a2dRight = self.aspectRatio
  362. def makeCamera2d(self, win, left, right, bottom, top):
  363. """makeCamera2d(self)
  364. Makes a new camera2d associated with the indicated window, and
  365. assigns it to render the indicated subrectangle of render2d.
  366. """
  367. # First, we need to make a new layer on the window.
  368. chan = win.getChannel(0)
  369. layer = chan.makeLayer()
  370. # And make a display region to cover the whole layer.
  371. dr = layer.makeDisplayRegion()
  372. # Now make a new Camera node.
  373. cam2dNode = Camera('cam2d')
  374. lens = OrthographicLens()
  375. lens.setFilmSize(right - left, top - bottom)
  376. lens.setFilmOffset((right + left) * 0.5, (top + bottom) * 0.5)
  377. lens.setNearFar(-1000, 1000)
  378. cam2dNode.setLens(lens)
  379. cam2dNode.setScene(self.render2d)
  380. camera2d = self.camera2d.attachNewNode(cam2dNode)
  381. dr.setCamera(camera2d)
  382. return camera2d
  383. def setupDataGraph(self):
  384. """setupDataGraph(self)
  385. Creates the data graph and populates it with the basic input
  386. devices.
  387. """
  388. self.dataRoot = NodePath('dataRoot')
  389. # Cache the node so we do not ask for it every frame
  390. self.dataRootNode = self.dataRoot.node()
  391. self.dataUnused = NodePath('dataUnused')
  392. def setupMouse(self, win):
  393. """setupMouse(self, win)
  394. Creates the structures necessary to monitor the mouse input,
  395. using the indicated window. If the mouse has already been set
  396. up for a different window, this changes the mouse to reference
  397. the new window.
  398. """
  399. if self.mak != None:
  400. # The mouse has already been set up; reappropriate it.
  401. self.mak.node().setSource(win, 0)
  402. # Reset the currently-held modifier button list for good
  403. # measure.
  404. bt = base.buttonThrower.node()
  405. mb = ModifierButtons(bt.getModifierButtons())
  406. mb.allButtonsUp()
  407. bt.setModifierButtons(mb)
  408. return
  409. # The mouse has not yet been set up in this application;
  410. # create the mouse structures now.
  411. # We create both a MouseAndKeyboard object and a MouseWatcher object
  412. # for the window. The MouseAndKeyboard generates mouse events and
  413. # mouse button/keyboard events; the MouseWatcher passes them through
  414. # unchanged when the mouse is not over a 2-d button, and passes
  415. # nothing through when the mouse *is* over a 2-d button. Therefore,
  416. # objects that don't want to get events when the mouse is over a
  417. # button, like the driveInterface, should be parented to
  418. # mouseWatcher, while objects that want events in all cases, like the
  419. # chat interface, should be parented to mak.
  420. self.mak = self.dataRoot.attachNewNode(MouseAndKeyboard(win, 0, 'mak'))
  421. self.mouseWatcherNode = MouseWatcher('mouseWatcher')
  422. self.mouseWatcher = self.mak.attachNewNode(self.mouseWatcherNode)
  423. mb = self.mouseWatcherNode.getModifierButtons()
  424. mb.addButton(KeyboardButton.shift())
  425. mb.addButton(KeyboardButton.control())
  426. mb.addButton(KeyboardButton.alt())
  427. self.mouseWatcherNode.setModifierButtons(mb)
  428. # Now we have the main trackball & drive interfaces.
  429. # useTrackball() and useDrive() switch these in and out; only
  430. # one is in use at a given time.
  431. self.trackball = self.dataUnused.attachNewNode(Trackball('trackball'))
  432. self.drive = self.dataUnused.attachNewNode(DriveInterface('drive'))
  433. self.mouse2cam = self.dataUnused.attachNewNode(Transform2SG('mouse2cam'))
  434. self.mouse2cam.node().setNode(self.camera.node())
  435. # The default is trackball mode, which is more convenient for
  436. # ad-hoc development in Python using ShowBase. Applications
  437. # can explicitly call base.useDrive() if they prefer a drive
  438. # interface.
  439. self.mouseInterface = self.trackball
  440. self.useTrackball()
  441. # A ButtonThrower to generate events from the mouse and
  442. # keyboard buttons as they are pressed.
  443. self.buttonThrower = self.mouseWatcher.attachNewNode(ButtonThrower('buttons'))
  444. # Specialize the events based on whether the modifier keys are
  445. # being held down.
  446. mods = ModifierButtons()
  447. mods.addButton(KeyboardButton.shift())
  448. mods.addButton(KeyboardButton.control())
  449. mods.addButton(KeyboardButton.alt())
  450. self.buttonThrower.node().setModifierButtons(mods)
  451. # Tell the gui system about our new mouse watcher.
  452. self.aspect2d.node().setMouseWatcher(self.mouseWatcherNode)
  453. self.mouseWatcherNode.addRegion(PGMouseWatcherBackground())
  454. def enableSoftwareMousePointer(self):
  455. """enableSoftwareMousePointer(self)
  456. Creates some geometry and parents it to render2d to show
  457. the currently-known mouse position. Useful if the mouse
  458. pointer is invisible for some reason.
  459. """
  460. mouseViz = render2d.attachNewNode('mouseViz')
  461. lilsmiley = loader.loadModel('lilsmiley')
  462. lilsmiley.reparentTo(mouseViz)
  463. # Scale the smiley face to 32x32 pixels.
  464. lilsmiley.setScale(32.0 / self.win.getHeight() / self.aspectRatio, 1.0, 32.0 / self.win.getHeight())
  465. #self.mouseWatcherNode.setGeometry(mouseViz)
  466. def getCameras(self, chanConfig):
  467. """
  468. getCameras(self, chanConfig)
  469. Extracts the camera(s) out of the ChanConfig record, parents
  470. them all to base.camera, and adds them to base.camList.
  471. """
  472. for i in range(chanConfig.getNumGroups()):
  473. # Create a top level camera node for this group
  474. camera = self.render.attachNewNode(chanConfig.getGroupNode(i))
  475. self.cameraList.append(camera)
  476. # Extract camera
  477. cam = camera.find('**/+Camera')
  478. self.camList.append(cam)
  479. # Enforce our expected aspect ratio, overriding whatever
  480. # nonsense ChanConfig put in there.
  481. lens = cam.node().getLens()
  482. lens.setAspectRatio(self.aspectRatio)
  483. # Update main camera variables
  484. if self.camera == None:
  485. self.camera = self.cameraList[0]
  486. if self.cam == None:
  487. self.cam = self.camList[0]
  488. # If you need to get a handle to the camera node itself,
  489. # use self.camNode.
  490. self.camNode = self.cam.node()
  491. # If you need to adjust camera parameters, like fov or
  492. # near/far clipping planes, use self.camLens.
  493. self.camLens = self.camNode.getLens()
  494. def getAlt(self):
  495. return base.mouseWatcherNode.getModifierButtons().isDown(
  496. KeyboardButton.alt())
  497. def getShift(self):
  498. return base.mouseWatcherNode.getModifierButtons().isDown(
  499. KeyboardButton.shift())
  500. def getControl(self):
  501. return base.mouseWatcherNode.getModifierButtons().isDown(
  502. KeyboardButton.control())
  503. def addAngularIntegrator(self):
  504. """addAngularIntegrator(self)"""
  505. if (self.physicsMgrAngular == 0):
  506. self.physicsMgrAngular = 1
  507. integrator = AngularEulerIntegrator()
  508. self.physicsMgr.attachAngularIntegrator(integrator)
  509. def enableParticles(self):
  510. """enableParticles(self)"""
  511. self.particleMgrEnabled = 1
  512. self.physicsMgrEnabled = 1
  513. self.taskMgr.remove('manager-update')
  514. self.taskMgr.add(self.updateManagers, 'manager-update')
  515. def disableParticles(self):
  516. """enableParticles(self)"""
  517. self.particleMgrEnabled = 0
  518. self.physicsMgrEnabled = 0
  519. self.taskMgr.remove('manager-update')
  520. def toggleParticles(self):
  521. if self.particleMgrEnabled == 0:
  522. self.enableParticles()
  523. else:
  524. self.disableParticles()
  525. def isParticleMgrEnabled(self):
  526. return self.particleMgrEnabled
  527. def isPhysicsMgrEnabled(self):
  528. return self.physicsMgrEnabled
  529. def updateManagers(self, state):
  530. """updateManagers(self)"""
  531. dt = min(globalClock.getDt(), 0.1)
  532. if (self.particleMgrEnabled == 1):
  533. self.particleMgr.doParticles(dt)
  534. if (self.physicsMgrEnabled == 1):
  535. self.physicsMgr.doPhysics(dt)
  536. return Task.cont
  537. def createStats(self):
  538. # You must specify a pstats-host in your configrc
  539. # The default is localhost
  540. if self.wantStats:
  541. PStatClient.connect()
  542. def addSfxManager(self, extraSfxManager):
  543. # keep a list of sfx manager objects to apply settings to, since there may be others
  544. # in addition to the one we create here
  545. self.sfxManagerList.append(extraSfxManager)
  546. newSfxManagerIsValid = (extraSfxManager!=None) and extraSfxManager.isValid()
  547. self.sfxManagerIsValidList.append(newSfxManagerIsValid)
  548. if newSfxManagerIsValid:
  549. extraSfxManager.setActive(self.sfxActive)
  550. def createBaseAudioManagers(self):
  551. sfxManager = AudioManager.createAudioManager()
  552. self.addSfxManager(sfxManager)
  553. self.musicManager = AudioManager.createAudioManager()
  554. self.musicManagerIsValid=self.musicManager!=None \
  555. and self.musicManager.isValid()
  556. if self.musicManagerIsValid:
  557. self.musicManager.setMutuallyExclusive(1) # ensure only 1 midi song is playing at a time
  558. self.musicManager.setActive(self.musicActive)
  559. # enableMusic/enableSoundEffects are meant to be called in response to a user request
  560. # so sfxActive/musicActive represent how things *should* be, regardless of App/OS/HW state
  561. def enableMusic(self, bEnableMusic):
  562. # dont setActive(1) if no audiofocus
  563. if self.AppHasAudioFocus and self.musicManagerIsValid:
  564. self.musicManager.setActive(bEnableMusic)
  565. self.musicActive = bEnableMusic
  566. if bEnableMusic:
  567. self.notify.debug("Enabling music")
  568. else:
  569. self.notify.debug("Disabling music")
  570. def SetAllSfxEnables(self, bEnabled):
  571. for i in range(len(self.sfxManagerList)):
  572. if (self.sfxManagerIsValidList[i]):
  573. self.sfxManagerList[i].setActive(bEnabled)
  574. def enableSoundEffects(self, bEnableSoundEffects):
  575. # dont setActive(1) if no audiofocus
  576. if self.AppHasAudioFocus or (bEnableSoundEffects==0):
  577. self.SetAllSfxEnables(bEnableSoundEffects)
  578. self.sfxActive=bEnableSoundEffects
  579. if bEnableSoundEffects:
  580. self.notify.debug("Enabling sound effects")
  581. else:
  582. self.notify.debug("Disabling sound effects")
  583. # enable/disableAllAudio allow a programmable global override-off for current audio settings.
  584. # they're meant to be called when app loses audio focus (switched out), so we can turn off sound
  585. # without affecting internal sfxActive/musicActive sound settings, so things
  586. # come back ok when the app is switched back to
  587. def disableAllAudio(self):
  588. self.AppHasAudioFocus = 0
  589. self.SetAllSfxEnables(0)
  590. if self.musicManagerIsValid:
  591. self.musicManager.setActive(0)
  592. self.notify.debug("Disabling audio")
  593. def enableAllAudio(self):
  594. self.AppHasAudioFocus = 1
  595. self.SetAllSfxEnables(self.sfxActive)
  596. if self.musicManagerIsValid:
  597. self.musicManager.setActive(self.musicActive)
  598. self.notify.debug("Enabling audio")
  599. def loadSfx(self, name):
  600. # should return a valid sound obj even if soundMgr is invalid
  601. sound = None
  602. if (name):
  603. # showbase-created sfxManager should always be at front of list
  604. sound=self.sfxManagerList[0].getSound(name)
  605. if sound == None:
  606. self.notify.warning("Could not load sound file %s." % name)
  607. return sound
  608. def loadMusic(self, name):
  609. # should return a valid sound obj even if musicMgr is invalid
  610. sound = None
  611. if (name):
  612. sound=self.musicManager.getSound(name)
  613. if sound == None:
  614. self.notify.warning("Could not load music file %s." % name)
  615. return sound
  616. def playSfx(self, sfx, looping = 0, interrupt = 1, volume = None, time = 0.0):
  617. if sfx:
  618. if volume != None:
  619. sfx.setVolume(volume)
  620. # dont start over if it's already playing, unless "interrupt" was specified
  621. if interrupt or (sfx.status() != AudioSound.PLAYING):
  622. sfx.setTime(time)
  623. sfx.setLoop(looping)
  624. sfx.play()
  625. def playMusic(self, music, looping = 0, interrupt = 1, volume = None, time = 0.0):
  626. if music:
  627. if volume != None:
  628. music.setVolume(volume)
  629. # if interrupt was set to 0, start over even if it's already playing
  630. if interrupt or (music.status() != AudioSound.PLAYING):
  631. music.setTime(time)
  632. music.setLoop(looping)
  633. music.play()
  634. def dataloop(self, state):
  635. # traverse the data graph. This reads all the control
  636. # inputs (from the mouse and keyboard, for instance) and also
  637. # directly acts upon them (for instance, to move the avatar).
  638. self.dgTrav.traverse(self.dataRootNode)
  639. return Task.cont
  640. def ivalloop(self, state):
  641. # Execute all intervals in the global ivalMgr.
  642. ivalMgr.step()
  643. return Task.cont
  644. def collisionloop(self, state):
  645. # run the collision traversal if we have a
  646. # CollisionTraverser set.
  647. if self.cTrav:
  648. self.cTrav.traverse(self.render)
  649. if self.appTrav:
  650. self.appTrav.traverse(self.render)
  651. return Task.cont
  652. def igloop(self, state):
  653. # Finally, render the frame.
  654. self.graphicsEngine.renderFrame()
  655. if self.clusterSyncFlag:
  656. base.graphicsEngine.syncFrame()
  657. if self.mainWinMinimized:
  658. # If the main window is minimized, slow down the app a bit
  659. # by sleeping here in igloop so we don't use all available
  660. # CPU needlessly.
  661. # Note: this isn't quite right if multiple windows are
  662. # open. We should base this on whether *all* windows are
  663. # minimized, not just the main window. But it will do for
  664. # now until someone complains.
  665. time.sleep(0.1)
  666. # Lerp stuff needs this event, and it must be generated in
  667. # C++, not in Python.
  668. throwNewFrame()
  669. return Task.cont
  670. def restart(self):
  671. self.shutdown()
  672. # give the igloop task a reasonably "late" priority,
  673. # so that it will get run after most tasks
  674. self.taskMgr.add(self.igloop, 'igloop', priority = 50)
  675. # make the collisionloop task run shortly before igloop,
  676. # but leave enough room for the app to insert tasks
  677. # between collisionloop and igloop
  678. self.taskMgr.add(self.collisionloop, 'collisionloop', priority = 45)
  679. # give the dataloop task a reasonably "early" priority,
  680. # so that it will get run before most tasks
  681. self.taskMgr.add(self.dataloop, 'dataloop', priority = -50)
  682. # spawn the ivalloop with a later priority, so that it will
  683. # run after most tasks, but before igloop.
  684. self.taskMgr.add(self.ivalloop, 'ivalloop', priority = 10)
  685. self.eventMgr.restart()
  686. def shutdown(self):
  687. self.taskMgr.remove('igloop')
  688. self.taskMgr.remove('collisionloop')
  689. self.taskMgr.remove('dataloop')
  690. self.taskMgr.remove('ivalloop')
  691. self.eventMgr.shutdown()
  692. def getBackgroundColor(self):
  693. """ Returns the current window background color. This assumes
  694. the window is set up to clear the color each frame (this is
  695. the normal setting). """
  696. return VBase4(self.win.getClearColor())
  697. def setBackgroundColor(self, *args):
  698. """ Sets the window background color to the indicated value.
  699. This assumes the window is set up to clear the color each
  700. frame (this is the normal setting).
  701. The color may be either a VBase3 or a VBase4, or a 3-component
  702. tuple, or the individual r, g, b parameters.
  703. """
  704. numArgs = len(args)
  705. if numArgs == 3 or numArgs == 4:
  706. color = VBase4(args[0], args[1], args[2], 1.0)
  707. elif numArgs == 1:
  708. arg = args[0]
  709. color = VBase4(arg[0], arg[1], arg[2], 1.0)
  710. else:
  711. raise TypeError, ('Invalid number of arguments: %d, expected 1, 3, or 4.' % numArgs)
  712. self.win.setClearColor(color)
  713. def toggleBackface(self):
  714. if self.backfaceCullingEnabled:
  715. self.backfaceCullingOff()
  716. else:
  717. self.backfaceCullingOn()
  718. def backfaceCullingOn(self):
  719. if not self.backfaceCullingEnabled:
  720. self.render.setTwoSided(0)
  721. self.backfaceCullingEnabled = 1
  722. def backfaceCullingOff(self):
  723. if self.backfaceCullingEnabled:
  724. self.render.setTwoSided(1)
  725. self.backfaceCullingEnabled = 0
  726. def toggleTexture(self):
  727. if self.textureEnabled:
  728. self.textureOff()
  729. else:
  730. self.textureOn()
  731. def textureOn(self):
  732. self.render.clearTexture()
  733. self.textureEnabled = 1
  734. def textureOff(self):
  735. self.render.setTextureOff(100)
  736. self.textureEnabled = 0
  737. def toggleWireframe(self):
  738. if self.wireframeEnabled:
  739. self.wireframeOff()
  740. else:
  741. self.wireframeOn()
  742. def wireframeOn(self):
  743. self.render.setRenderModeWireframe(100);
  744. self.render.setTwoSided(1);
  745. self.wireframeEnabled = 1
  746. def wireframeOff(self):
  747. self.render.clearRenderMode()
  748. render.setTwoSided(not self.backfaceCullingEnabled)
  749. self.wireframeEnabled = 0
  750. def disableMouse(self):
  751. """
  752. Temporarily disable the mouse control of the camera, either
  753. via the drive interface or the trackball, whichever is
  754. currently in use.
  755. """
  756. # We don't reparent the drive interface or the trackball;
  757. # whichever one was there before will remain in the data graph
  758. # and active. This way they won't lose button events while
  759. # the mouse is disabled. However, we do move the mouse2cam
  760. # object out of there, so we won't be updating the camera any
  761. # more.
  762. self.mouse2cam.reparentTo(self.dataUnused)
  763. def enableMouse(self):
  764. """
  765. Reverse the effect of a previous call to disableMouse().
  766. useDrive() also implicitly enables the mouse.
  767. """
  768. self.mouse2cam.reparentTo(self.mouseInterface)
  769. def setMouseOnNode(self, newNode):
  770. self.mouse2cam.node().setNode(newNode)
  771. def useDrive(self):
  772. """
  773. Switch mouse action to drive mode
  774. """
  775. # Get rid of the trackball
  776. self.mouseInterface.reparentTo(self.dataUnused)
  777. # Update the mouseInterface to point to the drive
  778. self.mouseInterface = self.drive
  779. self.mouseInterfaceNode = self.mouseInterface.node()
  780. # Hookup the drive to the camera.
  781. self.mouseInterface.reparentTo(self.mouseWatcher)
  782. self.mouse2cam.reparentTo(self.mouseInterface)
  783. # Set the height to a good eyeheight
  784. self.mouseInterfaceNode.reset()
  785. self.mouseInterfaceNode.setZ(4.0)
  786. def useTrackball(self):
  787. """
  788. Switch mouse action to trackball mode
  789. """
  790. # Get rid of the drive
  791. self.mouseInterface.reparentTo(self.dataUnused)
  792. # Update the mouseInterface to point to the trackball
  793. self.mouseInterface = self.trackball
  794. self.mouseInterfaceNode = self.mouseInterface.node()
  795. # Hookup the trackball to the camera.
  796. self.mouseInterface.reparentTo(self.mouseWatcher)
  797. self.mouse2cam.reparentTo(self.mouseInterface)
  798. def oobe(self):
  799. """
  800. Enable a special "out-of-body experience" mouse-interface
  801. mode. This can be used when a "god" camera is needed; it
  802. moves the camera node out from under its normal node and sets
  803. the world up in trackball state. Button events are still sent
  804. to the normal mouse action node (e.g. the DriveInterface), and
  805. mouse events, if needed, may be sent to the normal node by
  806. holding down the Control key.
  807. This is different than useTrackball(), which simply changes
  808. the existing mouse action to a trackball interface. In fact,
  809. OOBE mode doesn't care whether useDrive() or useTrackball() is
  810. in effect; it just temporarily layers a new trackball
  811. interface on top of whatever the basic interface is. You can
  812. even switch between useDrive() and useTrackball() while OOBE
  813. mode is in effect.
  814. This is a toggle; the second time this function is called, it
  815. disables the mode.
  816. """
  817. # If oobeMode was never set, set it to false and create the
  818. # structures we need to implement OOBE.
  819. try:
  820. self.oobeMode
  821. except:
  822. self.oobeMode = 0
  823. self.oobeCamera = self.hidden.attachNewNode('oobeCamera')
  824. self.oobeCameraTrackball = self.oobeCamera.attachNewNode('oobeCameraTrackball')
  825. self.oobeLens = PerspectiveLens()
  826. self.oobeLens.setAspectRatio(self.aspectRatio)
  827. self.oobeLens.setNearFar(0.1, 10000.0)
  828. self.oobeLens.setFov(52.0)
  829. self.oobeTrackball = self.dataUnused.attachNewNode(Trackball('oobeTrackball'), 1)
  830. self.oobe2cam = self.oobeTrackball.attachNewNode(Transform2SG('oobe2cam'))
  831. self.oobe2cam.node().setNode(self.oobeCameraTrackball.node())
  832. self.oobeVis = loader.loadModelOnce('models/misc/camera')
  833. if self.oobeVis:
  834. self.oobeVis.node().setFinal(1)
  835. self.oobeCullFrustum = None
  836. self.oobeCullFrustumVis = None
  837. if self.oobeMode:
  838. # Disable OOBE mode.
  839. if self.oobeCullFrustum != None:
  840. # First, disable OOBE cull mode.
  841. self.oobeCull()
  842. if self.oobeVis:
  843. self.oobeVis.reparentTo(self.hidden)
  844. # Restore the mouse interface node.
  845. #self.mouseInterface.reparentTo(self.mouseWatcher)
  846. self.oobeTrackball.reparentTo(self.dataUnused)
  847. self.cam.reparentTo(self.camera)
  848. self.camNode.setLens(self.camLens)
  849. self.oobeCamera.reparentTo(self.hidden)
  850. self.oobeMode = 0
  851. else:
  852. # Make oobeCamera be a sibling of wherever camera is now.
  853. cameraParent = self.camera.getParent()
  854. self.oobeCamera.reparentTo(cameraParent)
  855. self.oobeCamera.clearMat()
  856. # Move aside the current mouse interface node and put the
  857. # oobeTrackball in its place.
  858. #self.mouseInterface.reparentTo(self.dataUnused)
  859. self.oobeTrackball.reparentTo(self.mouseWatcher)
  860. # Set our initial OOB position to be just behind the camera.
  861. mat = Mat4.translateMat(0, -10, 3) * self.camera.getMat(cameraParent)
  862. mat.invertInPlace()
  863. self.oobeTrackball.node().setMat(mat)
  864. self.cam.reparentTo(self.oobeCameraTrackball)
  865. self.camNode.setLens(self.oobeLens)
  866. if self.oobeVis:
  867. self.oobeVis.reparentTo(self.camera)
  868. self.oobeMode = 1
  869. def oobeCull(self):
  870. """
  871. While in OOBE mode (see above), cull the viewing frustum as if
  872. it were still attached to our original camera. This allows us
  873. to visualize the effectiveness of our bounding volumes.
  874. """
  875. # First, make sure OOBE mode is enabled.
  876. try:
  877. if not self.oobeMode:
  878. self.oobe()
  879. except:
  880. self.oobe()
  881. if self.oobeCullFrustum == None:
  882. # Enable OOBE culling.
  883. pnode = LensNode('oobeCull')
  884. pnode.setLens(self.camLens)
  885. self.oobeCullFrustum = self.camera.attachNewNode(pnode)
  886. # Create a visible representation of the frustum.
  887. geom = self.camLens.makeGeometry()
  888. if geom != None:
  889. gn = GeomNode('frustum')
  890. gn.addGeom(geom)
  891. self.oobeCullFrustumVis = self.oobeVis.attachNewNode(gn)
  892. # Assign each DisplayRegion shared by the camera to use
  893. # this cull frustum.
  894. numDisplayRegions = self.camNode.getNumDisplayRegions()
  895. for d in range(0, numDisplayRegions):
  896. dr = self.camNode.getDisplayRegion(d)
  897. dr.setCullFrustum(pnode)
  898. else:
  899. # Disable OOBE culling.
  900. # Assign each DisplayRegion shared by the camera to use
  901. # the default cull frustum, the camera itself.
  902. numDisplayRegions = self.camNode.getNumDisplayRegions()
  903. for d in range(0, numDisplayRegions):
  904. dr = self.camNode.getDisplayRegion(d)
  905. dr.setCullFrustum(self.camNode)
  906. self.oobeCullFrustum.removeNode()
  907. self.oobeCullFrustum = None
  908. if self.oobeCullFrustumVis != None:
  909. self.oobeCullFrustumVis.removeNode()
  910. self.oobeCullFrustumVis = None
  911. def screenshot(self, namePrefix='screenshot'):
  912. # Get the current date and time to uniquify the image (down to the second)
  913. date = time.ctime(time.time())
  914. # Get the current frame count to uniquify it even more
  915. frameCount = globalClock.getFrameCount()
  916. # Replace spaces with dashes because unix does not like spaces in the filename
  917. date = date.replace(' ', '-')
  918. date = date.replace(':', '-')
  919. imageName = ('%s-%s-%d.%s' % (namePrefix, date, frameCount, self.screenshotExtension))
  920. self.notify.info("Taking screenshot: " + imageName)
  921. takeSnapshot(self.win, imageName)
  922. # Announce to anybody that a screenshot has been taken
  923. messenger.send('screenshot')
  924. def movie(self, namePrefix = 'movie', duration = 1.0, fps = 30,
  925. format = 'rgb', sd = 4):
  926. """
  927. movie(namePrefix = 'movie', duration=1.0, fps=30, format='rgb', sd=4)
  928. Spawn a task to capture a movie using the takeSnapshot function.
  929. - namePrefix will be used to form output file names (can include
  930. path information (e.g. 'I:/beta/frames/myMovie')
  931. - duration is the length of the movie in seconds
  932. - fps is the frame rate of the resulting movie
  933. - format specifies output file format (e.g. rgb, bmp)
  934. - sd specifies number of significant digits for frame count in the
  935. output file name (e.g. if sd = 4, movie_0001.rgb)
  936. """
  937. globalClock.setMode(ClockObject.MNonRealTime)
  938. globalClock.setDt(1.0/float(fps))
  939. t = taskMgr.add(self._movieTask, namePrefix + '_task')
  940. t.endT = globalClock.getFrameTime() + duration
  941. t.frameIndex = 1
  942. t.outputString = namePrefix + '_%0' + `sd` + 'd.' + format
  943. t.uponDeath = lambda state: globalClock.setMode(ClockObject.MNormal)
  944. def _movieTask(self, state):
  945. currT = globalClock.getFrameTime()
  946. if currT >= state.endT:
  947. return Task.done
  948. else:
  949. frameName = state.outputString % state.frameIndex
  950. self.notify.info("Capturing frame: " + frameName)
  951. takeSnapshot(self.win, frameName )
  952. state.frameIndex += 1
  953. return Task.cont
  954. def __windowEvent(self, win):
  955. properties = win.getProperties()
  956. if win == self.win:
  957. if not properties.getOpen():
  958. # If the user closes the main window, we should exit.
  959. self.notify.info("User closed main window.")
  960. self.userExit()
  961. if properties.getMinimized() and not self.mainWinMinimized:
  962. # If the main window is minimized, throw an event to
  963. # stop the music.
  964. self.mainWinMinimized = 1
  965. messenger.send('PandaPaused')
  966. elif not properties.getMinimized() and self.mainWinMinimized:
  967. # If the main window is restored, throw an event to
  968. # restart the music.
  969. self.mainWinMinimized = 0
  970. messenger.send('PandaRestarted')
  971. def userExit(self):
  972. # The user has requested we exit the program. Deal with this.
  973. if self.exitFunc:
  974. self.exitFunc()
  975. self.notify.info("Exiting ShowBase.")
  976. sys.exit()
  977. def run(self):
  978. self.taskMgr.run()