ShowBase.py 87 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294
  1. """Undocumented Module"""
  2. __all__ = ['ShowBase', 'WindowControls']
  3. # This module redefines the builtin import function with one
  4. # that prints out every import it does in a hierarchical form
  5. # Annoying and very noisy, but sometimes useful
  6. #import VerboseImport
  7. from pandac.PandaModules import *
  8. # This needs to be available early for DirectGUI imports
  9. import __builtin__
  10. __builtin__.config = ConfigConfigureGetConfigConfigShowbase
  11. from direct.directnotify.DirectNotifyGlobal import *
  12. from MessengerGlobal import *
  13. from BulletinBoardGlobal import *
  14. from direct.task.TaskManagerGlobal import *
  15. from JobManagerGlobal import *
  16. from EventManagerGlobal import *
  17. from PythonUtil import *
  18. from direct.showbase import PythonUtil
  19. from direct.particles.ParticleManagerGlobal import *
  20. from PhysicsManagerGlobal import *
  21. #from direct.interval.IntervalManager import ivalMgr
  22. from direct.interval import IntervalManager
  23. from InputStateGlobal import inputState
  24. from direct.showbase.BufferViewer import BufferViewer
  25. from direct.task import Task
  26. from direct.directutil import Verify
  27. import EventManager
  28. import math,sys,os
  29. import Loader
  30. import time
  31. from direct.fsm import ClassicFSM
  32. from direct.fsm import State
  33. from direct.showbase import ExceptionVarDump
  34. import DirectObject
  35. import SfxPlayer
  36. if __debug__:
  37. from direct.directutil import DeltaProfiler
  38. import OnScreenDebug
  39. __builtin__.FADE_SORT_INDEX = 1000
  40. __builtin__.NO_FADE_SORT_INDEX = 2000
  41. ####################################################
  42. ## expermential use of inter-frame yielding...
  43. ##
  44. ## this needs to be remove and problem cleared if we adopt this model..
  45. ##
  46. ####################################################
  47. want_fifothreads = config.GetBool("want-fifothreads", 0)
  48. if want_fifothreads:
  49. class HackGraphicsEngine(GraphicsEngine):
  50. def renderFrame(self):
  51. if isinstance(Thread.getCurrentThread(), MainThread):
  52. GraphicsEngine.renderFrame(self)
  53. else:
  54. print 'renderFrame Not Main Thread %s' % (repr(Thread.getCurrentThread()))
  55. # Now ShowBase is a DirectObject. We need this so ShowBase can hang
  56. # hooks on messages, particularly on window-event. This doesn't
  57. # *seem* to cause anyone any problems.
  58. class ShowBase(DirectObject.DirectObject):
  59. notify = directNotify.newCategory("ShowBase")
  60. def __init__(self):
  61. __builtin__.__dev__ = config.GetBool('want-dev', 0)
  62. if config.GetBool('want-variable-dump', not __dev__):
  63. ExceptionVarDump.install()
  64. # Locate the directory containing the main program
  65. maindir=os.path.abspath(sys.path[0])
  66. self.mainDir = Filename.fromOsSpecific(maindir).getFullpath()
  67. ExecutionEnvironment.setEnvironmentVariable("MAIN_DIR", self.mainDir)
  68. #debug running multiplier
  69. self.debugRunningMultiplier = 4
  70. # Get the dconfig object
  71. #self.config = ConfigConfigureGetConfigConfigShowbase
  72. self.config = config
  73. # Setup wantVerifyPdb as soon as reasonable:
  74. Verify.wantVerifyPdb = self.config.GetBool('want-verify-pdb', 0)
  75. self.printEnvDebugInfo()
  76. vfs = VirtualFileSystem.getGlobalPtr()
  77. self.nextWindowIndex = 1
  78. self.__directStarted = False
  79. self.__deadInputs = 0
  80. # Store dconfig variables
  81. self.sfxActive = self.config.GetBool('audio-sfx-active', 1)
  82. self.musicActive = self.config.GetBool('audio-music-active', 1)
  83. self.wantFog = self.config.GetBool('want-fog', 1)
  84. self.wantRender2dp = self.config.GetBool('want-render2dp', 1)
  85. self.screenshotExtension = self.config.GetString('screenshot-extension', 'jpg')
  86. self.musicManager = None
  87. self.musicManagerIsValid = None
  88. self.sfxManagerList = []
  89. self.sfxManagerIsValidList = []
  90. self.wantStats = self.config.GetBool('want-pstats', 0)
  91. # Fill this in with a function to invoke when the user "exits"
  92. # the program by closing the main window.
  93. self.exitFunc = None
  94. Task.TaskManager.taskTimerVerbose = self.config.GetBool('task-timer-verbose', 0)
  95. Task.TaskManager.extendedExceptions = self.config.GetBool('extended-exceptions', 0)
  96. Task.TaskManager.pStatsTasks = self.config.GetBool('pstats-tasks', 0)
  97. # Set up the TaskManager to reset the PStats clock back
  98. # whenever we resume from a pause. This callback function is
  99. # a little hacky, but we can't call it directly from within
  100. # the TaskManager because he doesn't know about PStats (and
  101. # has to run before libpanda is even loaded).
  102. taskMgr.resumeFunc = PStatClient.resumeAfterPause
  103. if(self.config.GetBool("want-dev",0)):
  104. import profile, pstats
  105. profile.Profile.bias = float(self.config.GetString("profile-bias","0"))
  106. def f8(x):
  107. return ("%"+"8.%df"%base.config.GetInt("profile-decimals",3)) % x
  108. pstats.f8=f8
  109. # If the aspect ratio is 0 or None, it means to infer the
  110. # aspect ratio from the window size.
  111. # If you need to know the actual aspect ratio call base.getAspectRatio()
  112. self.__configAspectRatio = ConfigVariableDouble('aspect-ratio', 0).getValue()
  113. # This variable is used to see if the aspect ratio has changed when
  114. # we get a window-event.
  115. self.__oldAspectRatio = None
  116. self.windowType = self.config.GetString('window-type', 'onscreen')
  117. self.requireWindow = self.config.GetBool('require-window', 1)
  118. # base.win is the main, or only window; base.winList is a list of
  119. # *all* windows. Similarly with base.camList.
  120. self.win = None
  121. self.frameRateMeter = None
  122. self.winList = []
  123. self.winControls = []
  124. self.mainWinMinimized = 0
  125. self.pipe = None
  126. self.pipeList = []
  127. self.mouse2cam = None
  128. self.buttonThrowers = None
  129. self.mouseWatcher = None
  130. self.mouseWatcherNode = None
  131. self.pointerWatcherNodes = None
  132. self.mouseInterface = None
  133. self.drive = None
  134. self.trackball = None
  135. self.cam = None
  136. self.cam2d = None
  137. self.cam2dp = None
  138. self.camera = None
  139. self.camera2d = None
  140. self.camera2dp = None
  141. self.camList = []
  142. self.camNode = None
  143. self.camLens = None
  144. self.camFrustumVis = None
  145. # This is used for syncing multiple PCs in a distributed cluster
  146. try:
  147. # Has the cluster sync variable been set externally?
  148. self.clusterSyncFlag = clusterSyncFlag
  149. except NameError:
  150. # Has the clusterSyncFlag been set via a config variable
  151. self.clusterSyncFlag = self.config.GetBool('cluster-sync', 0)
  152. self.hidden = NodePath('hidden')
  153. # We need a graphics engine to manage the actual rendering.
  154. if want_fifothreads:
  155. self.graphicsEngine = HackGraphicsEngine()
  156. else:
  157. self.graphicsEngine = GraphicsEngine()
  158. self.setupRender()
  159. self.setupRender2d()
  160. self.setupDataGraph()
  161. if self.wantRender2dp:
  162. self.setupRender2dp()
  163. # This is a placeholder for a CollisionTraverser. If someone
  164. # stores a CollisionTraverser pointer here, we'll traverse it
  165. # in the collisionLoop task.
  166. self.shadowTrav = 0
  167. # in the collisionLoop task.
  168. self.cTrav = 0
  169. self.cTravStack = Stack()
  170. # Ditto for an AppTraverser.
  171. self.appTrav = 0
  172. # This is the DataGraph traverser, which we might as well
  173. # create now.
  174. self.dgTrav = DataGraphTraverser()
  175. # Maybe create a RecorderController to record and/or play back
  176. # the user session.
  177. self.recorder = None
  178. playbackSession = self.config.GetString('playback-session', '')
  179. recordSession = self.config.GetString('record-session', '')
  180. if playbackSession:
  181. self.recorder = RecorderController()
  182. self.recorder.beginPlayback(Filename.fromOsSpecific(playbackSession))
  183. elif recordSession:
  184. self.recorder = RecorderController()
  185. self.recorder.beginRecord(Filename.fromOsSpecific(recordSession))
  186. if self.recorder:
  187. # If we're either playing back or recording, pass the
  188. # random seed into the system so each session will have
  189. # the same random seed.
  190. import random #, whrandom
  191. seed = self.recorder.getRandomSeed()
  192. random.seed(seed)
  193. #whrandom.seed(seed & 0xff, (seed >> 8) & 0xff, (seed >> 16) & 0xff)
  194. # Now that we've set up the window structures, assign an exitfunc.
  195. self.oldexitfunc = getattr(sys, 'exitfunc', None)
  196. sys.exitfunc = self.exitfunc
  197. # Open the default rendering window.
  198. if self.windowType != 'none':
  199. props = WindowProperties.getDefault()
  200. if (self.config.GetBool('read-raw-mice', 0)):
  201. props.setRawMice(1)
  202. self.openDefaultWindow(startDirect = False, props=props)
  203. self.loader = Loader.Loader(self)
  204. self.graphicsEngine.setDefaultLoader(self.loader.loader)
  205. self.eventMgr = eventMgr
  206. self.messenger = messenger
  207. self.bboard = bulletinBoard
  208. self.taskMgr = taskMgr
  209. self.jobMgr = jobMgr
  210. # Particle manager
  211. self.particleMgr = particleMgr
  212. self.particleMgr.setFrameStepping(1)
  213. self.particleMgrEnabled = 0
  214. # Physics manager
  215. self.physicsMgr = physicsMgr
  216. integrator = LinearEulerIntegrator()
  217. self.physicsMgr.attachLinearIntegrator(integrator)
  218. self.physicsMgrEnabled = 0
  219. self.physicsMgrAngular = 0
  220. self.createBaseAudioManagers()
  221. self.createStats()
  222. self.AppHasAudioFocus = 1
  223. # Get a pointer to Panda's global ClockObject, used for
  224. # synchronizing events between Python and C.
  225. # object is exactly in sync with the TrueClock.
  226. globalClock = ClockObject.getGlobalClock()
  227. # Since we have already started up a TaskManager, and probably
  228. # a number of tasks; and since the TaskManager had to use the
  229. # TrueClock to tell time until this moment, make sure the
  230. # globalClock
  231. trueClock = TrueClock.getGlobalPtr()
  232. globalClock.setRealTime(trueClock.getShortTime())
  233. globalClock.tick()
  234. # Now we can make the TaskManager start using the new globalClock.
  235. taskMgr.globalClock = globalClock
  236. # client CPU affinity is determined by, in order:
  237. # - client-cpu-affinity-mask config
  238. # - pcalt-# (# is CPU number, 0-based)
  239. # - client-cpu-affinity config
  240. affinityMask = self.config.GetInt('client-cpu-affinity-mask', -1)
  241. if affinityMask != -1:
  242. TrueClock.getGlobalPtr().setCpuAffinity(affinityMask)
  243. else:
  244. affinity = None
  245. if 'clientIndex' in __builtin__.__dict__:
  246. affinity = abs(int(__builtin__.clientIndex))
  247. else:
  248. affinity = self.config.GetInt('client-cpu-affinity', -1)
  249. if affinity not in (None, -1):
  250. # Windows XP supports a 32-bit affinity mask
  251. TrueClock.getGlobalPtr().setCpuAffinity(1 << (affinity % 32))
  252. __builtin__.base = self
  253. __builtin__.render2d = self.render2d
  254. __builtin__.aspect2d = self.aspect2d
  255. __builtin__.render = self.render
  256. __builtin__.hidden = self.hidden
  257. __builtin__.camera = self.camera
  258. __builtin__.loader = self.loader
  259. __builtin__.taskMgr = self.taskMgr
  260. __builtin__.jobMgr = self.jobMgr
  261. __builtin__.eventMgr = self.eventMgr
  262. __builtin__.messenger = self.messenger
  263. __builtin__.bboard = self.bboard
  264. # Config needs to be defined before ShowBase is constructed
  265. #__builtin__.config = self.config
  266. __builtin__.run = self.run
  267. __builtin__.ostream = Notify.out()
  268. __builtin__.directNotify = directNotify
  269. __builtin__.giveNotify = giveNotify
  270. __builtin__.globalClock = globalClock
  271. __builtin__.vfs = vfs
  272. __builtin__.cpMgr = ConfigPageManager.getGlobalPtr()
  273. __builtin__.cvMgr = ConfigVariableManager.getGlobalPtr()
  274. __builtin__.pandaSystem = PandaSystem.getGlobalPtr()
  275. __builtin__.wantUberdog = base.config.GetBool('want-uberdog', 1)
  276. if __debug__:
  277. __builtin__.deltaProfiler = DeltaProfiler.DeltaProfiler("ShowBase")
  278. __builtin__.onScreenDebug = OnScreenDebug.OnScreenDebug()
  279. if self.wantRender2dp:
  280. __builtin__.render2dp = self.render2dp
  281. __builtin__.aspect2dp = self.aspect2dp
  282. ShowBase.notify.info('__dev__ == %s' % __dev__)
  283. # set up recording of Functor creation stacks in __dev__
  284. PythonUtil.recordFunctorCreationStacks()
  285. if __dev__ or self.config.GetBool('want-e3-hacks', False):
  286. if self.config.GetBool('track-gui-items', True):
  287. # dict of guiId to gui item, for tracking down leaks
  288. self.guiItems = {}
  289. # Now hang a hook on the window-event from Panda. This allows
  290. # us to detect when the user resizes, minimizes, or closes the
  291. # main window.
  292. self.accept('window-event', self.__windowEvent)
  293. # Transition effects (fade, iris, etc)
  294. import Transitions
  295. self.transitions = Transitions.Transitions(self.loader)
  296. # Setup the window controls - handy for multiwindow applications
  297. self.setupWindowControls()
  298. # Client sleep
  299. sleepTime = self.config.GetFloat('client-sleep', 0.0)
  300. self.clientSleep = 0.0
  301. self.setSleep(sleepTime)
  302. # Extra sleep for running 4+ clients on a single machine
  303. # adds a sleep right after the main render in igloop
  304. # tends to even out the frame rate and keeps it from going
  305. # to zero in the out of focus windows
  306. if base.config.GetBool('multi-sleep', 1):
  307. self.multiClientSleep = 1
  308. else:
  309. self.multiClientSleep = 0
  310. # Offscreen buffer viewing utility.
  311. # This needs to be allocated even if the viewer is off.
  312. self.bufferViewer = BufferViewer()
  313. if self.wantRender2dp:
  314. self.bufferViewer.setRenderParent(self.render2dp)
  315. if self.windowType != 'none':
  316. self.__doStartDirect()
  317. # Start IGLOOP
  318. self.restart()
  319. # add a collision traverser via pushCTrav and remove it via popCTrav
  320. # that way the owner of the new cTrav doesn't need to hold onto the
  321. # previous one in order to put it back
  322. def pushCTrav(self, cTrav):
  323. self.cTravStack.push(self.cTrav)
  324. self.cTrav = cTrav
  325. def popCTrav(self):
  326. self.cTrav = self.cTravStack.pop()
  327. # temp; see ToonBase.py
  328. def getExitErrorCode(self):
  329. return 0
  330. def printEnvDebugInfo(self):
  331. """
  332. Print some information about the environment that we are running
  333. in. Stuff like the model paths and other paths. Feel free to
  334. add stuff to this.
  335. """
  336. if self.config.GetBool('want-env-debug-info', 0):
  337. print "\n\nEnvironment Debug Info {"
  338. print "* model path:"
  339. print getModelPath()
  340. #print "* dna path:"
  341. #print getDnaPath()
  342. print "* texture path:"
  343. print getTexturePath()
  344. print "* sound path:"
  345. print getSoundPath()
  346. print "}"
  347. def destroy(self):
  348. """ Call this function to destroy the ShowBase and stop all
  349. its tasks, freeing all of the Panda resources. Normally, you
  350. should not need to call it explicitly, as it is bound to the
  351. exitfunc and will be called at application exit time
  352. automatically.
  353. This function is designed to be safe to call multiple times."""
  354. if getattr(self, 'musicManager', None):
  355. self.musicManager.shutdown()
  356. self.musicManager = None
  357. self.sfxManagerList = []
  358. if getattr(self, 'loader', None):
  359. self.loader.destroy()
  360. self.loader = None
  361. if getattr(self, 'graphicsEngine', None):
  362. self.graphicsEngine.removeAllWindows()
  363. try:
  364. self.direct.panel.destroy()
  365. except:
  366. pass
  367. if hasattr(self, 'win'):
  368. del self.win
  369. del self.winList
  370. del self.pipe
  371. def exitfunc(self):
  372. """
  373. This should be assigned to sys.exitfunc to be called just
  374. before Python shutdown. It guarantees that the Panda window
  375. is closed cleanly, so that we free system resources, restore
  376. the desktop and keyboard functionality, etc.
  377. """
  378. self.destroy()
  379. if self.oldexitfunc:
  380. self.oldexitfunc()
  381. def makeDefaultPipe(self):
  382. """
  383. Creates the default GraphicsPipe, which will be used to make
  384. windows unless otherwise specified.
  385. """
  386. assert self.pipe == None
  387. selection = GraphicsPipeSelection.getGlobalPtr()
  388. selection.printPipeTypes()
  389. self.pipe = selection.makeDefaultPipe()
  390. if not self.pipe:
  391. self.notify.error(
  392. "No graphics pipe is available!\n"
  393. "Your Config.prc file must name at least one valid panda display\n"
  394. "library via load-display or aux-display.")
  395. self.notify.info("Default graphics pipe is %s (%s)." % (
  396. self.pipe.getInterfaceName(), self.pipe.getType().getName()))
  397. self.pipeList.append(self.pipe)
  398. def makeAllPipes(self):
  399. """
  400. Creates all GraphicsPipes that the system knows about and fill up
  401. self.pipeList with them.
  402. """
  403. shouldPrintPipes = 0
  404. selection = GraphicsPipeSelection.getGlobalPtr()
  405. selection.loadAuxModules()
  406. # First, we should make sure the default pipe exists.
  407. if self.pipe == None:
  408. self.makeDefaultPipe()
  409. # Now go through the list of known pipes, and make each one if
  410. # we don't have one already.
  411. numPipeTypes = selection.getNumPipeTypes()
  412. for i in range(numPipeTypes):
  413. pipeType = selection.getPipeType(i)
  414. # Do we already have a pipe of this type on the list?
  415. # This operation is n-squared, but presumably there won't
  416. # be more than a handful of pipe types, so who cares.
  417. already = 0
  418. for pipe in self.pipeList:
  419. if pipe.getType() == pipeType:
  420. already = 1
  421. if not already:
  422. pipe = selection.makePipe(pipeType)
  423. if pipe:
  424. self.notify.info("Got aux graphics pipe %s (%s)." % (
  425. pipe.getInterfaceName(), pipe.getType().getName()))
  426. self.pipeList.append(pipe)
  427. else:
  428. self.notify.info("Could not make graphics pipe %s." % (
  429. pipeType.getName()))
  430. def openWindow(self, props = None, pipe = None, gsg = None,
  431. type = None, name = None, size = None, aspectRatio = None,
  432. makeCamera = 1, keepCamera = 0,
  433. scene = None, stereo = None, rawmice = 0):
  434. """
  435. Creates a window and adds it to the list of windows that are
  436. to be updated every frame.
  437. """
  438. if pipe == None:
  439. pipe = self.pipe
  440. if pipe == None:
  441. self.makeDefaultPipe()
  442. pipe = self.pipe
  443. if pipe == None:
  444. # We couldn't get a pipe.
  445. return None
  446. if isinstance(gsg, GraphicsOutput):
  447. # If the gsg is a window or buffer, it means to use the
  448. # GSG from that buffer.
  449. gsg = gsg.getGsg()
  450. # If we are using DirectX, force a new GSG to be created,
  451. # since at the moment DirectX seems to misbehave if we do
  452. # not do this. This will cause a delay while all textures
  453. # etc. are reloaded, so we should revisit this later if we
  454. # can fix the underlying bug in our DirectX support.
  455. if pipe.getType().getName().startswith('wdx'):
  456. gsg = None
  457. if type == None:
  458. type = self.windowType
  459. if props == None:
  460. props = WindowProperties.getDefault()
  461. if size != None:
  462. # If we were given an explicit size, use it; otherwise,
  463. # the size from the properties is used.
  464. props = WindowProperties(props)
  465. props.setSize(size[0], size[1])
  466. if name == None:
  467. name = 'window%s' % (self.nextWindowIndex)
  468. self.nextWindowIndex += 1
  469. win = None
  470. fbprops = FrameBufferProperties.getDefault()
  471. flags = GraphicsPipe.BFFbPropsOptional
  472. if type == 'onscreen':
  473. flags = flags | GraphicsPipe.BFRequireWindow
  474. elif type == 'offscreen':
  475. flags = flags | GraphicsPipe.BFRefuseWindow
  476. if gsg:
  477. win = self.graphicsEngine.makeOutput(pipe, name, 0, fbprops,
  478. props, flags, gsg)
  479. else:
  480. win = self.graphicsEngine.makeOutput(pipe, name, 0, fbprops,
  481. props, flags)
  482. if win == None:
  483. # Couldn't create a window!
  484. return None
  485. if hasattr(win, "requestProperties"):
  486. win.requestProperties(props)
  487. mainWindow = False
  488. if self.win == None:
  489. mainWindow = True
  490. self.win = win
  491. self.winList.append(win)
  492. # Set up a 3-d camera for the window by default.
  493. if keepCamera:
  494. self.makeCamera(win, scene = scene, aspectRatio = aspectRatio,
  495. stereo = stereo, useCamera = base.cam)
  496. elif makeCamera:
  497. self.makeCamera(win, scene = scene, aspectRatio = aspectRatio,
  498. stereo = stereo)
  499. messenger.send('open_window', [win, mainWindow])
  500. if mainWindow:
  501. messenger.send('open_main_window')
  502. return win
  503. def closeWindow(self, win, keepCamera = 0):
  504. """
  505. Closes the indicated window and removes it from the list of
  506. windows. If it is the main window, clears the main window
  507. pointer to None.
  508. """
  509. # First, remove all of the cameras associated with display
  510. # regions on the window.
  511. numRegions = win.getNumDisplayRegions()
  512. for i in range(numRegions):
  513. dr = win.getDisplayRegion(i)
  514. cam = NodePath(dr.getCamera())
  515. dr.setCamera(NodePath())
  516. if not cam.isEmpty() and \
  517. cam.node().getNumDisplayRegions() == 0 and \
  518. not keepCamera:
  519. # If the camera is used by no other DisplayRegions,
  520. # remove it.
  521. if self.camList.count(cam) != 0:
  522. self.camList.remove(cam)
  523. # Don't throw away self.camera; we want to
  524. # preserve it for reopening the window.
  525. if cam == self.cam:
  526. self.cam = None
  527. if cam == self.cam2d:
  528. self.cam2d = None
  529. if cam == self.cam2dp:
  530. self.cam2dp = None
  531. cam.removeNode()
  532. # Now we can actually close the window.
  533. self.graphicsEngine.removeWindow(win)
  534. self.winList.remove(win)
  535. mainWindow = False
  536. if win == self.win:
  537. mainWindow = True
  538. self.win = None
  539. if self.frameRateMeter:
  540. self.frameRateMeter.clearWindow()
  541. self.frameRateMeter = None
  542. messenger.send('close_window', [win, mainWindow])
  543. if mainWindow:
  544. messenger.send('close_main_window')
  545. if not self.winList:
  546. # Give the window(s) a chance to actually close before we
  547. # continue.
  548. base.graphicsEngine.renderFrame()
  549. def openDefaultWindow(self, *args, **kw):
  550. # Creates the main window for the first time, without being
  551. # too particular about the kind of graphics API that is
  552. # chosen. The suggested window type from the load-display
  553. # config variable is tried first; if that fails, the first
  554. # window type that can be successfully opened at all is
  555. # accepted. Returns true on success, false otherwise.
  556. #
  557. # This is intended to be called only once, at application
  558. # startup. It is normally called automatically unless
  559. # window-type is configured to 'none'.
  560. startDirect = kw.get('startDirect', True)
  561. if 'startDirect' in kw:
  562. del kw['startDirect']
  563. if self.win:
  564. # If we've already opened a window before, this does
  565. # little more work than openMainWindow() alone.
  566. self.openMainWindow(*args, **kw)
  567. self.graphicsEngine.openWindows()
  568. return
  569. self.openMainWindow(*args, **kw)
  570. # Give the window a chance to truly open.
  571. self.graphicsEngine.openWindows()
  572. if self.win != None and not self.isMainWindowOpen():
  573. self.notify.info("Window did not open, removing.")
  574. self.closeWindow(self.win)
  575. if self.win == None:
  576. # Try a little harder if the window wouldn't open.
  577. self.makeAllPipes()
  578. while self.win == None and len(self.pipeList) > 1:
  579. self.pipeList.remove(self.pipe)
  580. self.pipe = self.pipeList[0]
  581. self.openMainWindow(*args, **kw)
  582. self.graphicsEngine.openWindows()
  583. if self.win != None and not self.isMainWindowOpen():
  584. self.notify.info("Window did not open, removing.")
  585. self.closeWindow(self.win)
  586. if self.win == None:
  587. self.notify.warning("Unable to open '%s' window." % (
  588. self.windowType))
  589. if self.requireWindow:
  590. # Unless require-window is set to false, it is an
  591. # error not to open a window.
  592. raise StandardError, 'Could not open window.'
  593. # The default is trackball mode, which is more convenient for
  594. # ad-hoc development in Python using ShowBase. Applications
  595. # can explicitly call base.useDrive() if they prefer a drive
  596. # interface.
  597. self.mouseInterface = self.trackball
  598. self.useTrackball()
  599. if startDirect:
  600. self.__doStartDirect()
  601. return self.win != None
  602. def isMainWindowOpen(self):
  603. if self.win != None:
  604. return self.win.isValid()
  605. return 0
  606. def openMainWindow(self, *args, **kw):
  607. """
  608. Creates the initial, main window for the application, and sets
  609. up the mouse and render2d structures appropriately for it. If
  610. this method is called a second time, it will close the
  611. previous main window and open a new one, preserving the lens
  612. properties in base.camLens.
  613. The return value is true on success, or false on failure (in
  614. which case base.win may be either None, or the previous,
  615. closed window).
  616. """
  617. keepCamera = kw.get('keepCamera', 0)
  618. success = 1
  619. oldWin = self.win
  620. oldLens = self.camLens
  621. oldClearColorActive = None
  622. if self.win != None:
  623. # Close the previous window.
  624. oldClearColorActive = self.win.getClearColorActive()
  625. oldClearColor = VBase4(self.win.getClearColor())
  626. oldClearDepthActive = self.win.getClearDepthActive()
  627. oldClearDepth = self.win.getClearDepth()
  628. oldClearStencilActive = self.win.getClearStencilActive()
  629. oldClearStencil = self.win.getClearStencil()
  630. self.closeWindow(self.win, keepCamera = keepCamera)
  631. # Open a new window.
  632. self.openWindow(*args, **kw)
  633. if self.win == None:
  634. self.win = oldWin
  635. self.winList.append(oldWin)
  636. success = 0
  637. if self.win != None:
  638. if isinstance(self.win, GraphicsWindow):
  639. self.setupMouse(self.win)
  640. self.makeCamera2d(self.win)
  641. self.makeCamera2dp(self.win)
  642. if oldLens != None:
  643. # Restore the previous lens properties.
  644. self.camNode.setLens(oldLens)
  645. self.camLens = oldLens
  646. if oldClearColorActive != None:
  647. # Restore the previous clear properties.
  648. self.win.setClearColorActive(oldClearColorActive)
  649. self.win.setClearColor(oldClearColor)
  650. self.win.setClearDepthActive(oldClearDepthActive)
  651. self.win.setClearDepth(oldClearDepth)
  652. self.win.setClearStencilActive(oldClearStencilActive)
  653. self.win.setClearStencil(oldClearStencil)
  654. self.setFrameRateMeter(self.config.GetBool(
  655. 'show-frame-rate-meter', 0))
  656. return success
  657. def setSleep(self, amount):
  658. """
  659. Sets up a task that calls python 'sleep' every frame. This is a simple
  660. way to reduce the CPU usage (and frame rate) of a panda program.
  661. """
  662. if (self.clientSleep == amount):
  663. return
  664. self.clientSleep = amount
  665. if (amount == 0.0):
  666. self.taskMgr.remove('clientSleep')
  667. else:
  668. # Spawn it after igloop (at the end of each frame)
  669. self.taskMgr.remove('clientSleep')
  670. self.taskMgr.add(self.sleepCycleTask, 'clientSleep', priority = 55)
  671. def sleepCycleTask(self, task):
  672. time.sleep(self.clientSleep)
  673. return Task.cont
  674. def setFrameRateMeter(self, flag):
  675. """
  676. Turns on or off (according to flag) a standard frame rate
  677. meter in the upper-right corner of the main window.
  678. """
  679. if flag:
  680. if not self.frameRateMeter:
  681. self.frameRateMeter = FrameRateMeter('frameRateMeter')
  682. self.frameRateMeter.setupWindow(self.win)
  683. else:
  684. if self.frameRateMeter:
  685. self.frameRateMeter.clearWindow()
  686. self.frameRateMeter = None
  687. def setupWindowControls(self):
  688. if not self.winControls:
  689. winCtrl = WindowControls(
  690. self.win, mouseWatcher=self.mouseWatcher,
  691. cam=self.camera, cam2d=self.camera2d,
  692. mouseKeyboard = self.dataRoot.find("**/*"))
  693. self.winControls.append(winCtrl)
  694. def setupRender(self):
  695. """
  696. Creates the render scene graph, the primary scene graph for
  697. rendering 3-d geometry.
  698. """
  699. self.render = NodePath('render')
  700. self.render.setAttrib(RescaleNormalAttrib.makeDefault())
  701. self.render.setTwoSided(0)
  702. self.backfaceCullingEnabled = 1
  703. self.textureEnabled = 1
  704. self.wireframeEnabled = 0
  705. def setupRender2d(self):
  706. """
  707. Creates the render2d scene graph, the primary scene graph for
  708. 2-d objects and gui elements that are superimposed over the
  709. 3-d geometry in the window.
  710. """
  711. self.render2d = NodePath('render2d')
  712. # Set up some overrides to turn off certain properties which
  713. # we probably won't need for 2-d objects.
  714. # It's probably important to turn off the depth test, since
  715. # many 2-d objects will be drawn over each other without
  716. # regard to depth position.
  717. # We used to avoid clearing the depth buffer before drawing
  718. # render2d, but nowadays we clear it anyway, since we
  719. # occasionally want to put 3-d geometry under render2d, and
  720. # it's simplest (and seems to be easier on graphics drivers)
  721. # if the 2-d scene has been cleared first.
  722. self.render2d.setDepthTest(0)
  723. self.render2d.setDepthWrite(0)
  724. self.render2d.setMaterialOff(1)
  725. self.render2d.setTwoSided(1)
  726. # The normal 2-d DisplayRegion has an aspect ratio that
  727. # matches the window, but its coordinate system is square.
  728. # This means anything we parent to render2d gets stretched.
  729. # For things where that makes a difference, we set up
  730. # aspect2d, which scales things back to the right aspect
  731. # ratio.
  732. aspectRatio = self.getAspectRatio()
  733. self.aspect2d = self.render2d.attachNewNode(PGTop("aspect2d"))
  734. self.aspect2d.setScale(1.0 / aspectRatio, 1.0, 1.0)
  735. self.a2dBackground = self.aspect2d.attachNewNode("a2dBackground")
  736. # It's important to know the bounds of the aspect2d screen.
  737. self.a2dTop = 1.0
  738. self.a2dBottom = -1.0
  739. self.a2dLeft = -aspectRatio
  740. self.a2dRight = aspectRatio
  741. self.a2dTopCenter = self.aspect2d.attachNewNode("a2dTopCenter")
  742. self.a2dBottomCenter = self.aspect2d.attachNewNode("a2dBottomCenter")
  743. self.a2dLeftCenter = self.aspect2d.attachNewNode("a2dLeftCenter")
  744. self.a2dRightCenter = self.aspect2d.attachNewNode("a2dRightCenter")
  745. self.a2dTopLeft = self.aspect2d.attachNewNode("a2dTopLeft")
  746. self.a2dTopRight = self.aspect2d.attachNewNode("a2dTopRight")
  747. self.a2dBottomLeft = self.aspect2d.attachNewNode("a2dBottomLeft")
  748. self.a2dBottomRight = self.aspect2d.attachNewNode("a2dBottomRight")
  749. # Put the nodes in their places
  750. self.a2dTopCenter.setPos(0, 0, self.a2dTop)
  751. self.a2dBottomCenter.setPos(0, 0, self.a2dBottom)
  752. self.a2dLeftCenter.setPos(self.a2dLeft, 0, 0)
  753. self.a2dRightCenter.setPos(self.a2dRight, 0, 0)
  754. self.a2dTopLeft.setPos(self.a2dLeft, 0, self.a2dTop)
  755. self.a2dTopRight.setPos(self.a2dRight, 0, self.a2dTop)
  756. self.a2dBottomLeft.setPos(self.a2dLeft, 0, self.a2dBottom)
  757. self.a2dBottomRight.setPos(self.a2dRight, 0, self.a2dBottom)
  758. def setupRender2dp(self):
  759. """
  760. Creates a render2d scene graph, the secondary scene graph for
  761. 2-d objects and gui elements that are superimposed over the
  762. 2-d and 3-d geometry in the window.
  763. """
  764. self.render2dp = NodePath('render2dp')
  765. # Set up some overrides to turn off certain properties which
  766. # we probably won't need for 2-d objects.
  767. # It's probably important to turn off the depth test, since
  768. # many 2-d objects will be drawn over each other without
  769. # regard to depth position.
  770. dt = DepthTestAttrib.make(DepthTestAttrib.MNone)
  771. dw = DepthWriteAttrib.make(DepthWriteAttrib.MOff)
  772. self.render2dp.setDepthTest(0)
  773. self.render2dp.setDepthWrite(0)
  774. self.render2dp.setMaterialOff(1)
  775. self.render2dp.setTwoSided(1)
  776. # The normal 2-d DisplayRegion has an aspect ratio that
  777. # matches the window, but its coordinate system is square.
  778. # This means anything we parent to render2d gets stretched.
  779. # For things where that makes a difference, we set up
  780. # aspect2d, which scales things back to the right aspect
  781. # ratio.
  782. aspectRatio = self.getAspectRatio()
  783. self.aspect2dp = self.render2dp.attachNewNode(PGTop("aspect2dp"))
  784. self.aspect2dp.node().setStartSort(16384)
  785. self.aspect2dp.setScale(1.0 / aspectRatio, 1.0, 1.0)
  786. # It's important to know the bounds of the aspect2d screen.
  787. self.a2dpTop = 1.0
  788. self.a2dpBottom = -1.0
  789. self.a2dpLeft = -aspectRatio
  790. self.a2dpRight = aspectRatio
  791. self.a2dpTopCenter = self.aspect2dp.attachNewNode("a2dpTopCenter")
  792. self.a2dpBottomCenter = self.aspect2dp.attachNewNode("a2dpBottomCenter")
  793. self.a2dpLeftCenter = self.aspect2dp.attachNewNode("a2dpLeftCenter")
  794. self.a2dpRightCenter = self.aspect2dp.attachNewNode("a2dpRightCenter")
  795. self.a2dpTopLeft = self.aspect2dp.attachNewNode("a2dpTopLeft")
  796. self.a2dpTopRight = self.aspect2dp.attachNewNode("a2dpTopRight")
  797. self.a2dpBottomLeft = self.aspect2dp.attachNewNode("a2dpBottomLeft")
  798. self.a2dpBottomRight = self.aspect2dp.attachNewNode("a2dpBottomRight")
  799. # Put the nodes in their places
  800. self.a2dpTopCenter.setPos(0, 0, self.a2dpTop)
  801. self.a2dpBottomCenter.setPos(0, 0, self.a2dpBottom)
  802. self.a2dpLeftCenter.setPos(self.a2dpLeft, 0, 0)
  803. self.a2dpRightCenter.setPos(self.a2dpRight, 0, 0)
  804. self.a2dpTopLeft.setPos(self.a2dpLeft, 0, self.a2dpTop)
  805. self.a2dpTopRight.setPos(self.a2dpRight, 0, self.a2dpTop)
  806. self.a2dpBottomLeft.setPos(self.a2dpLeft, 0, self.a2dpBottom)
  807. self.a2dpBottomRight.setPos(self.a2dpRight, 0, self.a2dpBottom)
  808. def getAspectRatio(self, win = None):
  809. # Returns the actual aspect ratio of the indicated (or main
  810. # window), or the default aspect ratio if there is not yet a
  811. # main window.
  812. # If the config it set, we return that
  813. if self.__configAspectRatio:
  814. return self.__configAspectRatio
  815. aspectRatio = 1
  816. if win == None:
  817. win = self.win
  818. if win != None and win.hasSize():
  819. if(win.getYSize() == 0 or win.getXSize() == 0):
  820. #flub the aspect since we can't actually see anything
  821. return 1
  822. aspectRatio = float(win.getXSize()) / float(win.getYSize())
  823. else:
  824. if win == None or not hasattr(win, "getRequestedProperties"):
  825. props = WindowProperties.getDefault()
  826. else:
  827. props = win.getRequestedProperties()
  828. if not props.hasSize():
  829. props = WindowProperties.getDefault()
  830. if props.hasSize():
  831. aspectRatio = float(props.getXSize()) / float(props.getYSize())
  832. return aspectRatio
  833. def makeCamera(self, win, sort = 0, scene = None,
  834. displayRegion = (0, 1, 0, 1), stereo = None,
  835. aspectRatio = None, clearDepth = 0, clearColor = None,
  836. lens = None, camName = 'cam', mask = None,
  837. useCamera = None):
  838. """
  839. Makes a new 3-d camera associated with the indicated window,
  840. and creates a display region in the indicated subrectangle.
  841. If stereo is True, then a stereo camera is created, with a
  842. pair of DisplayRegions. If stereo is False, then a standard
  843. camera is created. If stereo is None or omitted, a stereo
  844. camera is created if the window says it can render in stereo.
  845. If useCamera is not None, it is a NodePath to be used as the
  846. camera to apply to the window, rather than creating a new
  847. camera.
  848. """
  849. # self.camera is the parent node of all cameras: a node that
  850. # we can move around to move all cameras as a group.
  851. if self.camera == None:
  852. self.camera = self.render.attachNewNode('camera')
  853. __builtin__.camera = self.camera
  854. if useCamera:
  855. # Use the existing camera node.
  856. cam = useCamera
  857. camNode = useCamera.node()
  858. assert(isinstance(camNode, Camera))
  859. lens = camNode.getLens()
  860. cam.reparentTo(self.camera)
  861. else:
  862. # Make a new Camera node.
  863. camNode = Camera(camName)
  864. if lens == None:
  865. lens = PerspectiveLens()
  866. if aspectRatio == None:
  867. aspectRatio = self.getAspectRatio(win)
  868. lens.setAspectRatio(aspectRatio)
  869. cam = self.camera.attachNewNode(camNode)
  870. if lens != None:
  871. camNode.setLens(lens)
  872. if scene != None:
  873. camNode.setScene(scene)
  874. if mask != None:
  875. if (isinstance(mask, int)):
  876. mask = BitMask32(mask)
  877. camNode.setCameraMask(mask)
  878. if self.cam == None:
  879. self.cam = cam
  880. self.camNode = camNode
  881. self.camLens = lens
  882. self.camList.append(cam)
  883. # Now, make a DisplayRegion for the camera.
  884. dr = win.makeDisplayRegion(*displayRegion)
  885. dr.setSort(sort)
  886. # By default, we do not clear 3-d display regions (the entire
  887. # window will be cleared, which is normally sufficient). But
  888. # we will if clearDepth is specified.
  889. if clearDepth:
  890. dr.setClearDepthActive(1)
  891. if clearColor:
  892. dr.setClearColorActive(1)
  893. dr.setClearColor(clearColor)
  894. dr.setCamera(cam)
  895. if stereo == None:
  896. stereo = (win.isStereo() and self.config.GetBool('default-stereo-camera', 1))
  897. if stereo:
  898. # A stereo camera!
  899. dr.setStereoChannel(Lens.SCStereo)
  900. return cam
  901. def makeCamera2d(self, win, sort = 10,
  902. displayRegion = (0, 1, 0, 1), coords = (-1, 1, -1, 1),
  903. lens = None, cameraName = None):
  904. """
  905. Makes a new camera2d associated with the indicated window, and
  906. assigns it to render the indicated subrectangle of render2d.
  907. """
  908. dr = win.makeDisplayRegion(*displayRegion)
  909. dr.setSort(sort)
  910. # Enable clearing of the depth buffer on this new display
  911. # region (see the comment in setupRender2d, above).
  912. dr.setClearDepthActive(1)
  913. left, right, bottom, top = coords
  914. # Now make a new Camera node.
  915. if (cameraName):
  916. cam2dNode = Camera('cam2d_' + cameraName)
  917. else:
  918. cam2dNode = Camera('cam2d')
  919. if lens == None:
  920. lens = OrthographicLens()
  921. lens.setFilmSize(right - left, top - bottom)
  922. lens.setFilmOffset((right + left) * 0.5, (top + bottom) * 0.5)
  923. lens.setNearFar(-1000, 1000)
  924. cam2dNode.setLens(lens)
  925. # self.camera2d is the analog of self.camera, although it's
  926. # not as clear how useful it is.
  927. if self.camera2d == None:
  928. self.camera2d = self.render2d.attachNewNode('camera2d')
  929. camera2d = self.camera2d.attachNewNode(cam2dNode)
  930. dr.setCamera(camera2d)
  931. if self.cam2d == None:
  932. self.cam2d = camera2d
  933. return camera2d
  934. def makeCamera2dp(self, win, sort = 20,
  935. displayRegion = (0, 1, 0, 1), coords = (-1, 1, -1, 1),
  936. lens = None, cameraName = None):
  937. """
  938. Makes a new camera2dp associated with the indicated window, and
  939. assigns it to render the indicated subrectangle of render2dp.
  940. """
  941. dr = win.makeDisplayRegion(*displayRegion)
  942. dr.setSort(sort)
  943. # Unlike render2d, we don't clear the depth buffer for
  944. # render2dp. Caveat emptor.
  945. left, right, bottom, top = coords
  946. # Now make a new Camera node.
  947. if (cameraName):
  948. cam2dNode = Camera('cam2dp_' + cameraName)
  949. else:
  950. cam2dNode = Camera('cam2dp')
  951. if lens == None:
  952. lens = OrthographicLens()
  953. lens.setFilmSize(right - left, top - bottom)
  954. lens.setFilmOffset((right + left) * 0.5, (top + bottom) * 0.5)
  955. lens.setNearFar(-1000, 1000)
  956. cam2dNode.setLens(lens)
  957. # self.camera2d is the analog of self.camera, although it's
  958. # not as clear how useful it is.
  959. if self.camera2dp == None:
  960. self.camera2dp = self.render2dp.attachNewNode('camera2dp')
  961. camera2dp = self.camera2dp.attachNewNode(cam2dNode)
  962. dr.setCamera(camera2dp)
  963. if self.cam2dp == None:
  964. self.cam2dp = camera2dp
  965. return camera2dp
  966. def setupDataGraph(self):
  967. """
  968. Creates the data graph and populates it with the basic input
  969. devices.
  970. """
  971. self.dataRoot = NodePath('dataRoot')
  972. # Cache the node so we do not ask for it every frame
  973. self.dataRootNode = self.dataRoot.node()
  974. self.dataUnused = NodePath('dataUnused')
  975. def setupMouse(self, win):
  976. """
  977. Creates the structures necessary to monitor the mouse input,
  978. using the indicated window. If the mouse has already been set
  979. up for a different window, those structures are deleted first.
  980. """
  981. if self.buttonThrowers != None:
  982. for bt in self.buttonThrowers:
  983. mw = bt.getParent()
  984. mk = mw.getParent()
  985. bt.removeNode()
  986. mw.removeNode()
  987. mk.removeNode()
  988. # For each mouse/keyboard device, we create
  989. # - MouseAndKeyboard
  990. # - MouseWatcher
  991. # - ButtonThrower
  992. # The ButtonThrowers are stored in a list, self.buttonThrowers.
  993. # Given a ButtonThrower, one can access the MouseWatcher and
  994. # MouseAndKeyboard using getParent.
  995. #
  996. # The MouseAndKeyboard generates mouse events and mouse
  997. # button/keyboard events; the MouseWatcher passes them through
  998. # unchanged when the mouse is not over a 2-d button, and passes
  999. # nothing through when the mouse *is* over a 2-d button. Therefore,
  1000. # objects that don't want to get events when the mouse is over a
  1001. # button, like the driveInterface, should be parented to
  1002. # MouseWatcher, while objects that want events in all cases, like the
  1003. # chat interface, should be parented to the MouseAndKeyboard.
  1004. self.buttonThrowers = []
  1005. self.pointerWatcherNodes = []
  1006. for i in range(win.getNumInputDevices()):
  1007. name = win.getInputDeviceName(i)
  1008. mk = self.dataRoot.attachNewNode(MouseAndKeyboard(win, i, name))
  1009. mw = mk.attachNewNode(MouseWatcher(name))
  1010. mb = mw.node().getModifierButtons()
  1011. mb.addButton(KeyboardButton.shift())
  1012. mb.addButton(KeyboardButton.control())
  1013. mb.addButton(KeyboardButton.alt())
  1014. mb.addButton(KeyboardButton.meta())
  1015. mw.node().setModifierButtons(mb)
  1016. bt = mw.attachNewNode(ButtonThrower(name))
  1017. if (i != 0):
  1018. bt.node().setPrefix('mousedev'+str(i)+'-')
  1019. mods = ModifierButtons()
  1020. mods.addButton(KeyboardButton.shift())
  1021. mods.addButton(KeyboardButton.control())
  1022. mods.addButton(KeyboardButton.alt())
  1023. mods.addButton(KeyboardButton.meta())
  1024. bt.node().setModifierButtons(mods)
  1025. self.buttonThrowers.append(bt)
  1026. if (win.hasPointer(i)):
  1027. self.pointerWatcherNodes.append(mw.node())
  1028. self.mouseWatcher = self.buttonThrowers[0].getParent()
  1029. self.mouseWatcherNode = self.mouseWatcher.node()
  1030. # print "ButtonThrowers = ", self.buttonThrowers
  1031. # print "PointerWatcherNodes = ", self.pointerWatcherNodes
  1032. if self.recorder:
  1033. # If we have a recorder, the mouseWatcher belongs under a
  1034. # special MouseRecorder node, which may intercept the
  1035. # mouse activity.
  1036. mw = self.buttonThrowers[0].getParent()
  1037. mouseRecorder = MouseRecorder('mouse')
  1038. self.recorder.addRecorder(
  1039. 'mouse', mouseRecorder.upcastToRecorderBase())
  1040. np = mw.getParent().attachNewNode(mouseRecorder)
  1041. mw.reparentTo(np)
  1042. # Now we have the main trackball & drive interfaces.
  1043. # useTrackball() and useDrive() switch these in and out; only
  1044. # one is in use at a given time.
  1045. self.trackball = self.dataUnused.attachNewNode(Trackball('trackball'))
  1046. self.drive = self.dataUnused.attachNewNode(DriveInterface('drive'))
  1047. self.mouse2cam = self.dataUnused.attachNewNode(Transform2SG('mouse2cam'))
  1048. self.mouse2cam.node().setNode(self.camera.node())
  1049. # A special ButtonThrower to generate keyboard events and
  1050. # include the time from the OS. This is separate only to
  1051. # support legacy code that did not expect a time parameter; it
  1052. # will eventually be folded into the normal ButtonThrower,
  1053. # above.
  1054. mw = self.buttonThrowers[0].getParent()
  1055. self.timeButtonThrower = mw.attachNewNode(ButtonThrower('timeButtons'))
  1056. self.timeButtonThrower.node().setPrefix('time-')
  1057. self.timeButtonThrower.node().setTimeFlag(1)
  1058. # Tell the gui system about our new mouse watcher.
  1059. self.aspect2d.node().setMouseWatcher(mw.node())
  1060. self.aspect2dp.node().setMouseWatcher(mw.node())
  1061. mw.node().addRegion(PGMouseWatcherBackground())
  1062. def enableSoftwareMousePointer(self):
  1063. """
  1064. Creates some geometry and parents it to render2d to show
  1065. the currently-known mouse position. Useful if the mouse
  1066. pointer is invisible for some reason.
  1067. """
  1068. mouseViz = render2d.attachNewNode('mouseViz')
  1069. lilsmiley = loader.loadModel('lilsmiley')
  1070. lilsmiley.reparentTo(mouseViz)
  1071. aspectRatio = self.getAspectRatio()
  1072. # Scale the smiley face to 32x32 pixels.
  1073. height = self.win.getYSize()
  1074. lilsmiley.setScale(
  1075. 32.0 / height / aspectRatio,
  1076. 1.0, 32.0 / height)
  1077. self.mouseWatcherNode.setGeometry(mouseViz.node())
  1078. def getAlt(self):
  1079. return self.mouseWatcherNode.getModifierButtons().isDown(
  1080. KeyboardButton.alt())
  1081. def getShift(self):
  1082. return self.mouseWatcherNode.getModifierButtons().isDown(
  1083. KeyboardButton.shift())
  1084. def getControl(self):
  1085. return self.mouseWatcherNode.getModifierButtons().isDown(
  1086. KeyboardButton.control())
  1087. def getMeta(self):
  1088. return self.mouseWatcherNode.getModifierButtons().isDown(
  1089. KeyboardButton.meta())
  1090. def addAngularIntegrator(self):
  1091. if not self.physicsMgrAngular:
  1092. self.physicsMgrAngular = 1
  1093. integrator = AngularEulerIntegrator()
  1094. self.physicsMgr.attachAngularIntegrator(integrator)
  1095. def enableParticles(self):
  1096. if not self.particleMgrEnabled:
  1097. self.particleMgrEnabled = 1
  1098. self.physicsMgrEnabled = 1
  1099. self.taskMgr.remove('manager-update')
  1100. self.taskMgr.add(self.updateManagers, 'manager-update')
  1101. def disableParticles(self):
  1102. if self.particleMgrEnabled:
  1103. self.particleMgrEnabled = 0
  1104. self.physicsMgrEnabled = 0
  1105. self.taskMgr.remove('manager-update')
  1106. def toggleParticles(self):
  1107. if self.particleMgrEnabled == 0:
  1108. self.enableParticles()
  1109. else:
  1110. self.disableParticles()
  1111. def isParticleMgrEnabled(self):
  1112. return self.particleMgrEnabled
  1113. def isPhysicsMgrEnabled(self):
  1114. return self.physicsMgrEnabled
  1115. def updateManagers(self, state):
  1116. dt = globalClock.getDt()
  1117. if (self.particleMgrEnabled == 1):
  1118. self.particleMgr.doParticles(dt)
  1119. if (self.physicsMgrEnabled == 1):
  1120. self.physicsMgr.doPhysics(dt)
  1121. return Task.cont
  1122. def createStats(self, hostname=None, port=None):
  1123. # You can specify pstats-host in your Config.prc or use ~pstats/~aipstats
  1124. # The default is localhost
  1125. if not self.wantStats:
  1126. return False
  1127. if PStatClient.isConnected():
  1128. PStatClient.disconnect()
  1129. # these default values match the C++ default values
  1130. if hostname is None:
  1131. hostname = ''
  1132. if port is None:
  1133. port = -1
  1134. PStatClient.connect(hostname, port)
  1135. return PStatClient.isConnected()
  1136. def addSfxManager(self, extraSfxManager):
  1137. # keep a list of sfx manager objects to apply settings to,
  1138. # since there may be others in addition to the one we create here
  1139. self.sfxManagerList.append(extraSfxManager)
  1140. newSfxManagerIsValid = (extraSfxManager!=None) and extraSfxManager.isValid()
  1141. self.sfxManagerIsValidList.append(newSfxManagerIsValid)
  1142. if newSfxManagerIsValid:
  1143. extraSfxManager.setActive(self.sfxActive)
  1144. def createBaseAudioManagers(self):
  1145. self.sfxPlayer = SfxPlayer.SfxPlayer()
  1146. sfxManager = AudioManager.createAudioManager()
  1147. self.addSfxManager(sfxManager)
  1148. self.musicManager = AudioManager.createAudioManager()
  1149. self.musicManagerIsValid=self.musicManager!=None \
  1150. and self.musicManager.isValid()
  1151. if self.musicManagerIsValid:
  1152. # ensure only 1 midi song is playing at a time:
  1153. self.musicManager.setConcurrentSoundLimit(1)
  1154. self.musicManager.setActive(self.musicActive)
  1155. # enableMusic/enableSoundEffects are meant to be called in response
  1156. # to a user request so sfxActive/musicActive represent how things
  1157. # *should* be, regardless of App/OS/HW state
  1158. def enableMusic(self, bEnableMusic):
  1159. # dont setActive(1) if no audiofocus
  1160. if self.AppHasAudioFocus and self.musicManagerIsValid:
  1161. self.musicManager.setActive(bEnableMusic)
  1162. self.musicActive = bEnableMusic
  1163. if bEnableMusic:
  1164. self.notify.debug("Enabling music")
  1165. else:
  1166. self.notify.debug("Disabling music")
  1167. def SetAllSfxEnables(self, bEnabled):
  1168. for i in range(len(self.sfxManagerList)):
  1169. if (self.sfxManagerIsValidList[i]):
  1170. self.sfxManagerList[i].setActive(bEnabled)
  1171. def enableSoundEffects(self, bEnableSoundEffects):
  1172. # dont setActive(1) if no audiofocus
  1173. if self.AppHasAudioFocus or (bEnableSoundEffects==0):
  1174. self.SetAllSfxEnables(bEnableSoundEffects)
  1175. self.sfxActive=bEnableSoundEffects
  1176. if bEnableSoundEffects:
  1177. self.notify.debug("Enabling sound effects")
  1178. else:
  1179. self.notify.debug("Disabling sound effects")
  1180. # enable/disableAllAudio allow a programmable global override-off
  1181. # for current audio settings. they're meant to be called when app
  1182. # loses audio focus (switched out), so we can turn off sound without
  1183. # affecting internal sfxActive/musicActive sound settings, so things
  1184. # come back ok when the app is switched back to
  1185. def disableAllAudio(self):
  1186. self.AppHasAudioFocus = 0
  1187. self.SetAllSfxEnables(0)
  1188. if self.musicManagerIsValid:
  1189. self.musicManager.setActive(0)
  1190. self.notify.debug("Disabling audio")
  1191. def enableAllAudio(self):
  1192. self.AppHasAudioFocus = 1
  1193. self.SetAllSfxEnables(self.sfxActive)
  1194. if self.musicManagerIsValid:
  1195. self.musicManager.setActive(self.musicActive)
  1196. self.notify.debug("Enabling audio")
  1197. # This function should only be in the loader but is here for
  1198. # backwards compatibility. Please do not add code here, add
  1199. # it to the loader.
  1200. def loadSfx(self, name):
  1201. return self.loader.loadSfx(name)
  1202. # This function should only be in the loader but is here for
  1203. # backwards compatibility. Please do not add code here, add
  1204. # it to the loader.
  1205. def loadMusic(self, name):
  1206. return self.loader.loadMusic(name)
  1207. def playSfx(
  1208. self, sfx, looping = 0, interrupt = 1, volume = None,
  1209. time = 0.0, node = None, listener = None, cutoff = None):
  1210. # This goes through a special player for potential localization
  1211. return self.sfxPlayer.playSfx(sfx, looping, interrupt, volume, time, node, listener, cutoff)
  1212. def playMusic(self, music, looping = 0, interrupt = 1, volume = None, time = 0.0):
  1213. if music:
  1214. if volume != None:
  1215. music.setVolume(volume)
  1216. # if interrupt was set to 0, start over even if it's
  1217. # already playing
  1218. if interrupt or (music.status() != AudioSound.PLAYING):
  1219. music.setTime(time)
  1220. music.setLoop(looping)
  1221. music.play()
  1222. def __resetPrevTransform(self, state):
  1223. # Clear out the previous velocity deltas now, after we have
  1224. # rendered (the previous frame). We do this after the render,
  1225. # so that we have a chance to draw a representation of spheres
  1226. # along with their velocities. At the beginning of the frame
  1227. # really means after the command prompt, which allows the user
  1228. # to interactively query these deltas meaningfully.
  1229. PandaNode.resetAllPrevTransform()
  1230. return Task.cont
  1231. def __dataLoop(self, state):
  1232. # traverse the data graph. This reads all the control
  1233. # inputs (from the mouse and keyboard, for instance) and also
  1234. # directly acts upon them (for instance, to move the avatar).
  1235. self.dgTrav.traverse(self.dataRootNode)
  1236. return Task.cont
  1237. def __ivalLoop(self, state):
  1238. # Execute all intervals in the global ivalMgr.
  1239. IntervalManager.ivalMgr.step()
  1240. return Task.cont
  1241. def initShadowTrav(self):
  1242. if not self.shadowTrav:
  1243. # set up the shadow collision traverser
  1244. self.shadowTrav = CollisionTraverser("base.shadowTrav")
  1245. self.shadowTrav.setRespectPrevTransform(False)
  1246. def __shadowCollisionLoop(self, state):
  1247. # run the collision traversal if we have a
  1248. # CollisionTraverser set.
  1249. if self.shadowTrav:
  1250. self.shadowTrav.traverse(self.render)
  1251. return Task.cont
  1252. def __collisionLoop(self, state):
  1253. # run the collision traversal if we have a
  1254. # CollisionTraverser set.
  1255. if self.cTrav:
  1256. self.cTrav.traverse(self.render)
  1257. if self.appTrav:
  1258. self.appTrav.traverse(self.render)
  1259. return Task.cont
  1260. def __audioLoop(self, state):
  1261. if (self.musicManager != None):
  1262. self.musicManager.update()
  1263. for x in self.sfxManagerList:
  1264. x.update()
  1265. return Task.cont
  1266. def __igLoop(self, state):
  1267. # We render the watch variables for the onScreenDebug as soon
  1268. # as we reasonably can before the renderFrame().
  1269. onScreenDebug.render()
  1270. if self.recorder:
  1271. self.recorder.recordFrame()
  1272. # Finally, render the frame.
  1273. self.graphicsEngine.renderFrame()
  1274. if self.clusterSyncFlag:
  1275. self.graphicsEngine.syncFrame()
  1276. if self.multiClientSleep:
  1277. time.sleep(0)
  1278. # We clear the text buffer for the onScreenDebug as soon
  1279. # as we reasonably can after the renderFrame().
  1280. onScreenDebug.clear()
  1281. if self.recorder:
  1282. self.recorder.playFrame()
  1283. if self.mainWinMinimized:
  1284. # If the main window is minimized, slow down the app a bit
  1285. # by sleeping here in igLoop so we don't use all available
  1286. # CPU needlessly.
  1287. # Note: this isn't quite right if multiple windows are
  1288. # open. We should base this on whether *all* windows are
  1289. # minimized, not just the main window. But it will do for
  1290. # now until someone complains.
  1291. time.sleep(0.1)
  1292. # Lerp stuff needs this event, and it must be generated in
  1293. # C++, not in Python.
  1294. throwNewFrame()
  1295. return Task.cont
  1296. def restart(self):
  1297. self.shutdown()
  1298. # __resetPrevTransform goes at the very beginning of the frame.
  1299. self.taskMgr.add(
  1300. self.__resetPrevTransform, 'resetPrevTransform', priority = -51)
  1301. # give the dataLoop task a reasonably "early" priority,
  1302. # so that it will get run before most tasks
  1303. self.taskMgr.add(self.__dataLoop, 'dataLoop', priority = -50)
  1304. self.__deadInputs = 0
  1305. # spawn the ivalLoop with a later priority, so that it will
  1306. # run after most tasks, but before igLoop.
  1307. self.taskMgr.add(self.__ivalLoop, 'ivalLoop', priority = 20)
  1308. # make the collisionLoop task run before igLoop,
  1309. # but leave enough room for the app to insert tasks
  1310. # between collisionLoop and igLoop
  1311. self.taskMgr.add(self.__collisionLoop, 'collisionLoop', priority = 30)
  1312. # do the shadowCollisionLoop after the collisionLoop and
  1313. # before the igLoop and camera updates (this moves the avatar vertically,
  1314. # to his final position for the frame):
  1315. self.taskMgr.add(
  1316. self.__shadowCollisionLoop, 'shadowCollisionLoop', priority = 44)
  1317. # give the igLoop task a reasonably "late" priority,
  1318. # so that it will get run after most tasks
  1319. self.taskMgr.add(self.__igLoop, 'igLoop', priority = 50)
  1320. # the audioLoop updates the positions of 3D sounds.
  1321. # as such, it needs to run after the cull traversal in the igLoop.
  1322. self.taskMgr.add(self.__audioLoop, 'audioLoop', priority = 60)
  1323. self.eventMgr.restart()
  1324. def shutdown(self):
  1325. self.taskMgr.remove('audioLoop')
  1326. self.taskMgr.remove('igLoop')
  1327. self.taskMgr.remove('shadowCollisionLoop')
  1328. self.taskMgr.remove('collisionLoop')
  1329. self.taskMgr.remove('dataLoop')
  1330. self.taskMgr.remove('resetPrevTransform')
  1331. self.taskMgr.remove('ivalLoop')
  1332. self.eventMgr.shutdown()
  1333. def getBackgroundColor(self, win = None):
  1334. """
  1335. Returns the current window background color. This assumes
  1336. the window is set up to clear the color each frame (this is
  1337. the normal setting).
  1338. """
  1339. if win == None:
  1340. win = self.win
  1341. return VBase4(win.getClearColor())
  1342. def setBackgroundColor(self, r = None, g = None, b = None, a = 0.0, win = None):
  1343. """
  1344. Sets the window background color to the indicated value.
  1345. This assumes the window is set up to clear the color each
  1346. frame (this is the normal setting).
  1347. The color may be either a VBase3 or a VBase4, or a 3-component
  1348. tuple, or the individual r, g, b parameters.
  1349. """
  1350. if g != None:
  1351. color = VBase4(r, g, b, a)
  1352. else:
  1353. arg = r
  1354. if isinstance(arg, VBase4):
  1355. color = arg
  1356. else:
  1357. color = VBase4(arg[0], arg[1], arg[2], a)
  1358. if win == None:
  1359. win = self.win
  1360. if win:
  1361. win.setClearColor(color)
  1362. def toggleBackface(self):
  1363. if self.backfaceCullingEnabled:
  1364. self.backfaceCullingOff()
  1365. else:
  1366. self.backfaceCullingOn()
  1367. def backfaceCullingOn(self):
  1368. if not self.backfaceCullingEnabled:
  1369. self.render.setTwoSided(0)
  1370. self.backfaceCullingEnabled = 1
  1371. def backfaceCullingOff(self):
  1372. if self.backfaceCullingEnabled:
  1373. self.render.setTwoSided(1)
  1374. self.backfaceCullingEnabled = 0
  1375. def toggleTexture(self):
  1376. if self.textureEnabled:
  1377. self.textureOff()
  1378. else:
  1379. self.textureOn()
  1380. def textureOn(self):
  1381. self.render.clearTexture()
  1382. self.textureEnabled = 1
  1383. def textureOff(self):
  1384. self.render.setTextureOff(100)
  1385. self.textureEnabled = 0
  1386. def toggleWireframe(self):
  1387. if self.wireframeEnabled:
  1388. self.wireframeOff()
  1389. else:
  1390. self.wireframeOn()
  1391. def wireframeOn(self):
  1392. self.render.setRenderModeWireframe(100)
  1393. self.render.setTwoSided(1)
  1394. self.wireframeEnabled = 1
  1395. def wireframeOff(self):
  1396. self.render.clearRenderMode()
  1397. render.setTwoSided(not self.backfaceCullingEnabled)
  1398. self.wireframeEnabled = 0
  1399. def disableMouse(self):
  1400. """
  1401. Temporarily disable the mouse control of the camera, either
  1402. via the drive interface or the trackball, whichever is
  1403. currently in use.
  1404. """
  1405. # We don't reparent the drive interface or the trackball;
  1406. # whichever one was there before will remain in the data graph
  1407. # and active. This way they won't lose button events while
  1408. # the mouse is disabled. However, we do move the mouse2cam
  1409. # object out of there, so we won't be updating the camera any
  1410. # more.
  1411. if self.mouse2cam:
  1412. self.mouse2cam.reparentTo(self.dataUnused)
  1413. def enableMouse(self):
  1414. """
  1415. Reverse the effect of a previous call to disableMouse().
  1416. useDrive() also implicitly enables the mouse.
  1417. """
  1418. if self.mouse2cam:
  1419. self.mouse2cam.reparentTo(self.mouseInterface)
  1420. def silenceInput(self):
  1421. """
  1422. This is a heavy-handed way of temporarily turning off
  1423. all inputs. Bring them back with reviveInput().
  1424. """
  1425. if not self.__deadInputs:
  1426. self.__deadInputs = taskMgr.remove('dataLoop')
  1427. def reviveInput(self):
  1428. """
  1429. Restores inputs after a previous call to silenceInput.
  1430. """
  1431. if self.__deadInputs:
  1432. self.eventMgr.doEvents()
  1433. self.dgTrav.traverse(base.dataRootNode)
  1434. self.eventMgr.eventQueue.clear()
  1435. self.taskMgr.add(self.__dataLoop, 'dataLoop', priority = -50)
  1436. self.__deadInputs = 0
  1437. def setMouseOnNode(self, newNode):
  1438. if self.mouse2cam:
  1439. self.mouse2cam.node().setNode(newNode)
  1440. def changeMouseInterface(self, changeTo):
  1441. """
  1442. Switch mouse action
  1443. """
  1444. # Get rid of the prior interface:
  1445. self.mouseInterface.reparentTo(self.dataUnused)
  1446. # Update the mouseInterface to point to the drive
  1447. self.mouseInterface = changeTo
  1448. self.mouseInterfaceNode = self.mouseInterface.node()
  1449. # Hookup the drive to the camera.
  1450. self.mouseInterface.reparentTo(self.mouseWatcher)
  1451. if self.mouse2cam:
  1452. self.mouse2cam.reparentTo(self.mouseInterface)
  1453. def useDrive(self):
  1454. """
  1455. Switch mouse action to drive mode
  1456. """
  1457. if self.drive:
  1458. self.changeMouseInterface(self.drive)
  1459. # Set the height to a good eyeheight
  1460. self.mouseInterfaceNode.reset()
  1461. self.mouseInterfaceNode.setZ(4.0)
  1462. def useTrackball(self):
  1463. """
  1464. Switch mouse action to trackball mode
  1465. """
  1466. if self.trackball:
  1467. self.changeMouseInterface(self.trackball)
  1468. def oobe(self):
  1469. """
  1470. Enable a special "out-of-body experience" mouse-interface
  1471. mode. This can be used when a "god" camera is needed; it
  1472. moves the camera node out from under its normal node and sets
  1473. the world up in trackball state. Button events are still sent
  1474. to the normal mouse action node (e.g. the DriveInterface), and
  1475. mouse events, if needed, may be sent to the normal node by
  1476. holding down the Control key.
  1477. This is different than useTrackball(), which simply changes
  1478. the existing mouse action to a trackball interface. In fact,
  1479. OOBE mode doesn't care whether useDrive() or useTrackball() is
  1480. in effect; it just temporarily layers a new trackball
  1481. interface on top of whatever the basic interface is. You can
  1482. even switch between useDrive() and useTrackball() while OOBE
  1483. mode is in effect.
  1484. This is a toggle; the second time this function is called, it
  1485. disables the mode.
  1486. """
  1487. # If oobeMode was never set, set it to false and create the
  1488. # structures we need to implement OOBE.
  1489. try:
  1490. self.oobeMode
  1491. except:
  1492. self.oobeMode = 0
  1493. self.oobeCamera = self.hidden.attachNewNode('oobeCamera')
  1494. self.oobeCameraTrackball = self.oobeCamera.attachNewNode('oobeCameraTrackball')
  1495. self.oobeLens = PerspectiveLens()
  1496. self.oobeLens.setAspectRatio(self.getAspectRatio())
  1497. self.oobeLens.setNearFar(0.1, 10000.0)
  1498. self.oobeLens.setMinFov(40)
  1499. self.oobeTrackball = self.dataUnused.attachNewNode(Trackball('oobeTrackball'), 1)
  1500. self.oobe2cam = self.oobeTrackball.attachNewNode(Transform2SG('oobe2cam'))
  1501. self.oobe2cam.node().setNode(self.oobeCameraTrackball.node())
  1502. self.oobeVis = loader.loadModel('models/misc/camera')
  1503. if self.oobeVis:
  1504. self.oobeVis.node().setFinal(1)
  1505. self.oobeCullFrustum = None
  1506. self.oobeCullFrustumVis = None
  1507. if self.oobeMode:
  1508. # Disable OOBE mode.
  1509. if self.oobeCullFrustum != None:
  1510. # First, disable OOBE cull mode.
  1511. self.oobeCull()
  1512. if self.oobeVis:
  1513. self.oobeVis.reparentTo(self.hidden)
  1514. # Restore the mouse interface node, and remove the oobe
  1515. # trackball from the data path.
  1516. self.mouseInterfaceNode.clearButton(KeyboardButton.control())
  1517. self.oobeTrackball.detachNode()
  1518. self.cam.reparentTo(self.camera)
  1519. self.camNode.setLens(self.camLens)
  1520. self.oobeCamera.reparentTo(self.hidden)
  1521. self.oobeMode = 0
  1522. bboard.post('oobeEnabled', False)
  1523. else:
  1524. bboard.post('oobeEnabled', True)
  1525. try:
  1526. cameraParent = localAvatar
  1527. except:
  1528. # Make oobeCamera be a sibling of wherever camera is now.
  1529. cameraParent = self.camera.getParent()
  1530. self.oobeCamera.reparentTo(cameraParent)
  1531. self.oobeCamera.clearMat()
  1532. # Make the regular MouseInterface node respond only when
  1533. # the control button is pressed. And the oobe node will
  1534. # respond only when control is *not* pressed.
  1535. self.mouseInterfaceNode.requireButton(KeyboardButton.control(), True)
  1536. self.oobeTrackball.node().requireButton(KeyboardButton.control(), False)
  1537. self.oobeTrackball.reparentTo(self.mouseWatcher)
  1538. # Set our initial OOB position to be just behind the camera.
  1539. mat = Mat4.translateMat(0, -10, 3) * self.camera.getMat(cameraParent)
  1540. mat.invertInPlace()
  1541. self.oobeTrackball.node().setMat(mat)
  1542. self.cam.reparentTo(self.oobeCameraTrackball)
  1543. # Don't change the camera lens--keep it with the original lens.
  1544. #self.camNode.setLens(self.oobeLens)
  1545. if self.oobeVis:
  1546. self.oobeVis.reparentTo(self.camera)
  1547. self.oobeMode = 1
  1548. def oobeCull(self):
  1549. """
  1550. While in OOBE mode (see above), cull the viewing frustum as if
  1551. it were still attached to our original camera. This allows us
  1552. to visualize the effectiveness of our bounding volumes.
  1553. """
  1554. # First, make sure OOBE mode is enabled.
  1555. try:
  1556. if not self.oobeMode:
  1557. self.oobe()
  1558. except:
  1559. self.oobe()
  1560. if self.oobeCullFrustum == None:
  1561. # Enable OOBE culling.
  1562. pnode = LensNode('oobeCull')
  1563. pnode.setLens(self.camLens)
  1564. self.oobeCullFrustum = self.camera.attachNewNode(pnode)
  1565. # Create a visible representation of the frustum.
  1566. geom = self.camLens.makeGeometry()
  1567. if geom != None:
  1568. gn = GeomNode('frustum')
  1569. gn.addGeom(geom)
  1570. self.oobeCullFrustumVis = self.oobeVis.attachNewNode(gn)
  1571. # Tell the camera to cull from here instead of its own
  1572. # origin.
  1573. self.camNode.setCullCenter(self.oobeCullFrustum)
  1574. else:
  1575. # Disable OOBE culling.
  1576. self.camNode.setCullCenter(NodePath())
  1577. self.oobeCullFrustum.removeNode()
  1578. self.oobeCullFrustum = None
  1579. if self.oobeCullFrustumVis != None:
  1580. self.oobeCullFrustumVis.removeNode()
  1581. self.oobeCullFrustumVis = None
  1582. def showCameraFrustum(self):
  1583. # Create a visible representation of the frustum.
  1584. self.removeCameraFrustum()
  1585. geom = self.camLens.makeGeometry()
  1586. if geom != None:
  1587. gn = GeomNode('frustum')
  1588. gn.addGeom(geom)
  1589. self.camFrustumVis = self.camera.attachNewNode(gn)
  1590. def removeCameraFrustum(self):
  1591. if self.camFrustumVis:
  1592. self.camFrustumVis.removeNode()
  1593. def screenshot(self, namePrefix = 'screenshot',
  1594. defaultFilename = 1, source = None,
  1595. imageComment=""):
  1596. """ Captures a screenshot from the main window or from the
  1597. specified window or Texture and writes it to a filename in the
  1598. current directory (or to a specified directory).
  1599. If defaultFilename is True, the filename is synthesized by
  1600. appending namePrefix to a default filename suffix (including
  1601. the filename extension) specified in the Config variable
  1602. screenshot-filename. Otherwise, if defaultFilename is False,
  1603. the entire namePrefix is taken to be the filename to write,
  1604. and this string should include a suitable filename extension
  1605. that will be used to determine the type of image file to
  1606. write.
  1607. Normally, the source is a GraphicsWindow, GraphicsBuffer or
  1608. DisplayRegion. If a Texture is supplied instead, it must have
  1609. a ram image (that is, if it was generated by
  1610. makeTextureBuffer() or makeCubeMap(), the parameter toRam
  1611. should have been set true). If it is a cube map texture as
  1612. generated by makeCubeMap(), namePrefix should contain the hash
  1613. mark ('#') character.
  1614. The return value is the filename if successful, or None if
  1615. there is a problem.
  1616. """
  1617. if source == None:
  1618. source = self.win
  1619. if defaultFilename:
  1620. filename = GraphicsOutput.makeScreenshotFilename(namePrefix)
  1621. else:
  1622. filename = Filename(namePrefix)
  1623. if isinstance(source, Texture):
  1624. if source.getZSize() > 1:
  1625. saved = source.write(filename, 0, 0, 1, 0)
  1626. else:
  1627. saved = source.write(filename)
  1628. else:
  1629. saved = source.saveScreenshot(filename, imageComment)
  1630. if saved:
  1631. # Announce to anybody that a screenshot has been taken
  1632. messenger.send('screenshot', [filename])
  1633. return filename
  1634. return None
  1635. def saveCubeMap(self, namePrefix = 'cube_map_#.png',
  1636. defaultFilename = 0, source = None,
  1637. camera = None, size = 128,
  1638. cameraMask = PandaNode.getAllCameraMask()):
  1639. """
  1640. Similar to screenshot(), this sets up a temporary cube map
  1641. Texture which it uses to take a series of six snapshots of the
  1642. current scene, one in each of the six cube map directions.
  1643. This requires rendering a new frame.
  1644. Unlike screenshot(), source may only be a GraphicsWindow,
  1645. GraphicsBuffer, or DisplayRegion; it may not be a Texture.
  1646. camera should be the node to which the cubemap cameras will be
  1647. parented. The default is the camera associated with source,
  1648. if source is a DisplayRegion, or base.camera otherwise.
  1649. The return value is the filename if successful, or None if
  1650. there is a problem.
  1651. """
  1652. if source == None:
  1653. source = base.win
  1654. if camera == None:
  1655. if hasattr(source, "getCamera"):
  1656. camera = source.getCamera()
  1657. if camera == None:
  1658. camera = base.camera
  1659. if hasattr(source, "getWindow"):
  1660. source = source.getWindow()
  1661. rig = NodePath(namePrefix)
  1662. buffer = source.makeCubeMap(namePrefix, size, rig, cameraMask, 1)
  1663. if buffer == None:
  1664. raise StandardError, "Could not make cube map."
  1665. # Set the near and far planes from the default lens.
  1666. lens = rig.find('**/+Camera').node().getLens()
  1667. lens.setNearFar(base.camLens.getNear(), base.camLens.getFar())
  1668. # Now render a frame to fill up the texture.
  1669. rig.reparentTo(camera)
  1670. base.graphicsEngine.openWindows()
  1671. base.graphicsEngine.renderFrame()
  1672. tex = buffer.getTexture()
  1673. saved = self.screenshot(namePrefix = namePrefix,
  1674. defaultFilename = defaultFilename,
  1675. source = tex)
  1676. base.graphicsEngine.removeWindow(buffer)
  1677. rig.removeNode()
  1678. return saved
  1679. def saveSphereMap(self, namePrefix = 'spheremap.png',
  1680. defaultFilename = 0, source = None,
  1681. camera = None, size = 256,
  1682. cameraMask = PandaNode.getAllCameraMask(),
  1683. numVertices = 1000):
  1684. """
  1685. This works much like saveCubeMap(), and uses the graphics
  1686. API's hardware cube-mapping ability to get a 360-degree view
  1687. of the world. But then it converts the six cube map faces
  1688. into a single fisheye texture, suitable for applying as a
  1689. static environment map (sphere map).
  1690. For eye-relative static environment maps, sphere maps are
  1691. often preferable to cube maps because they require only a
  1692. single texture and because they are supported on a broader
  1693. range of hardware.
  1694. The return value is the filename if successful, or None if
  1695. there is a problem.
  1696. """
  1697. if source == None:
  1698. source = base.win
  1699. if camera == None:
  1700. if hasattr(source, "getCamera"):
  1701. camera = source.getCamera()
  1702. if camera == None:
  1703. camera = base.camera
  1704. if hasattr(source, "getWindow"):
  1705. source = source.getWindow()
  1706. # First, make an offscreen buffer to convert the cube map to a
  1707. # sphere map. We make it first so we can guarantee the
  1708. # rendering order for the cube map.
  1709. toSphere = source.makeTextureBuffer(namePrefix, size, size,
  1710. Texture(), 1)
  1711. # Now make the cube map buffer.
  1712. rig = NodePath(namePrefix)
  1713. buffer = toSphere.makeCubeMap(namePrefix, size, rig, cameraMask, 0)
  1714. if buffer == None:
  1715. base.graphicsEngine.removeWindow(toSphere)
  1716. raise StandardError, "Could not make cube map."
  1717. # Set the near and far planes from the default lens.
  1718. lens = rig.find('**/+Camera').node().getLens()
  1719. lens.setNearFar(base.camLens.getNear(), base.camLens.getFar())
  1720. # Set up the scene to convert the cube map. It's just a
  1721. # simple scene, with only the FisheyeMaker object in it.
  1722. dr = toSphere.makeDisplayRegion()
  1723. camNode = Camera('camNode')
  1724. lens = OrthographicLens()
  1725. lens.setFilmSize(2, 2)
  1726. lens.setNearFar(-1000, 1000)
  1727. camNode.setLens(lens)
  1728. root = NodePath('buffer')
  1729. cam = root.attachNewNode(camNode)
  1730. dr.setCamera(cam)
  1731. fm = FisheyeMaker('card')
  1732. fm.setNumVertices(numVertices)
  1733. fm.setSquareInscribed(1, 1.1)
  1734. fm.setReflection(1)
  1735. card = root.attachNewNode(fm.generate())
  1736. card.setTexture(buffer.getTexture())
  1737. # Now render a frame. This will render out the cube map and
  1738. # then apply it to the the card in the toSphere buffer.
  1739. rig.reparentTo(camera)
  1740. base.graphicsEngine.openWindows()
  1741. base.graphicsEngine.renderFrame()
  1742. # One more frame for luck.
  1743. base.graphicsEngine.renderFrame()
  1744. saved = self.screenshot(namePrefix = namePrefix,
  1745. defaultFilename = defaultFilename,
  1746. source = toSphere.getTexture())
  1747. base.graphicsEngine.removeWindow(buffer)
  1748. base.graphicsEngine.removeWindow(toSphere)
  1749. rig.removeNode()
  1750. return saved
  1751. def movie(self, namePrefix = 'movie', duration = 1.0, fps = 30,
  1752. format = 'png', sd = 4, source = None):
  1753. """
  1754. Spawn a task to capture a movie using the screenshot function.
  1755. - namePrefix will be used to form output file names (can include
  1756. path information (e.g. '/i/beta/frames/myMovie')
  1757. - duration is the length of the movie in seconds
  1758. - fps is the frame rate of the resulting movie
  1759. - format specifies output file format (e.g. png, bmp)
  1760. - sd specifies number of significant digits for frame count in the
  1761. output file name (e.g. if sd = 4, movie_0001.png)
  1762. - source is the Window, Buffer, DisplayRegion, or Texture from which
  1763. to save the resulting images. The default is the main window.
  1764. """
  1765. globalClock.setMode(ClockObject.MNonRealTime)
  1766. globalClock.setDt(1.0/float(fps))
  1767. t = taskMgr.add(self._movieTask, namePrefix + '_task')
  1768. t.frameIndex = 0 # Frame 0 is not captured.
  1769. t.numFrames = int(duration * fps)
  1770. t.source = source
  1771. t.outputString = namePrefix + '_%0' + `sd` + 'd.' + format
  1772. t.uponDeath = lambda state: globalClock.setMode(ClockObject.MNormal)
  1773. def _movieTask(self, state):
  1774. if state.frameIndex != 0:
  1775. frameName = state.outputString % state.frameIndex
  1776. self.notify.info("Capturing frame: " + frameName)
  1777. self.screenshot(namePrefix = frameName, defaultFilename = 0,
  1778. source = state.source)
  1779. state.frameIndex += 1
  1780. if state.frameIndex > state.numFrames:
  1781. return Task.done
  1782. else:
  1783. return Task.cont
  1784. def __windowEvent(self, win):
  1785. if win == self.win:
  1786. properties = win.getProperties()
  1787. self.notify.info("Got window event: %s" % (repr(properties)))
  1788. if not properties.getOpen():
  1789. # If the user closes the main window, we should exit.
  1790. self.notify.info("User closed main window.")
  1791. self.userExit()
  1792. if properties.getMinimized() and not self.mainWinMinimized:
  1793. # If the main window is minimized, throw an event to
  1794. # stop the music.
  1795. self.mainWinMinimized = 1
  1796. messenger.send('PandaPaused')
  1797. elif not properties.getMinimized() and self.mainWinMinimized:
  1798. # If the main window is restored, throw an event to
  1799. # restart the music.
  1800. self.mainWinMinimized = 0
  1801. messenger.send('PandaRestarted')
  1802. # If we have not forced the aspect ratio, let's see if it has
  1803. # changed and update the camera lenses and aspect2d parameters
  1804. if not self.__configAspectRatio:
  1805. aspectRatio = self.getAspectRatio()
  1806. if aspectRatio != self.__oldAspectRatio:
  1807. self.__oldAspectRatio = aspectRatio
  1808. # Fix up some anything that depends on the aspectRatio
  1809. self.camLens.setAspectRatio(aspectRatio)
  1810. if aspectRatio < 1:
  1811. # If the window is TALL, lets expand the top and bottom
  1812. self.aspect2d.setScale(1.0, 1.0, aspectRatio)
  1813. self.a2dTop = 1.0 / aspectRatio
  1814. self.a2dBottom = - 1.0 / aspectRatio
  1815. self.a2dLeft = -1
  1816. self.a2dRight = 1.0
  1817. # Don't forget 2dp
  1818. self.aspect2dp.setScale(1.0, 1.0, aspectRatio)
  1819. self.a2dpTop = 1.0 / aspectRatio
  1820. self.a2dpBottom = - 1.0 / aspectRatio
  1821. self.a2dpLeft = -1
  1822. self.a2dpRight = 1.0
  1823. else:
  1824. # If the window is WIDE, lets expand the left and right
  1825. self.aspect2d.setScale(1.0 / aspectRatio, 1.0, 1.0)
  1826. self.a2dTop = 1.0
  1827. self.a2dBottom = -1.0
  1828. self.a2dLeft = -aspectRatio
  1829. self.a2dRight = aspectRatio
  1830. # Don't forget 2dp
  1831. self.aspect2dp.setScale(1.0 / aspectRatio, 1.0, 1.0)
  1832. self.a2dpTop = 1.0
  1833. self.a2dpBottom = -1.0
  1834. self.a2dpLeft = -aspectRatio
  1835. self.a2dpRight = aspectRatio
  1836. # Reposition the aspect2d marker nodes
  1837. self.a2dTopCenter.setPos(0, 0, self.a2dTop)
  1838. self.a2dBottomCenter.setPos(0, 0, self.a2dBottom)
  1839. self.a2dLeftCenter.setPos(self.a2dLeft, 0, 0)
  1840. self.a2dRightCenter.setPos(self.a2dRight, 0, 0)
  1841. self.a2dTopLeft.setPos(self.a2dLeft, 0, self.a2dTop)
  1842. self.a2dTopRight.setPos(self.a2dRight, 0, self.a2dTop)
  1843. self.a2dBottomLeft.setPos(self.a2dLeft, 0, self.a2dBottom)
  1844. self.a2dBottomRight.setPos(self.a2dRight, 0, self.a2dBottom)
  1845. # Reposition the aspect2dp marker nodes
  1846. self.a2dpTopCenter.setPos(0, 0, self.a2dpTop)
  1847. self.a2dpBottomCenter.setPos(0, 0, self.a2dpBottom)
  1848. self.a2dpLeftCenter.setPos(self.a2dpLeft, 0, 0)
  1849. self.a2dpRightCenter.setPos(self.a2dpRight, 0, 0)
  1850. self.a2dpTopLeft.setPos(self.a2dpLeft, 0, self.a2dpTop)
  1851. self.a2dpTopRight.setPos(self.a2dpRight, 0, self.a2dpTop)
  1852. self.a2dpBottomLeft.setPos(self.a2dpLeft, 0, self.a2dpBottom)
  1853. self.a2dpBottomRight.setPos(self.a2dpRight, 0, self.a2dpBottom)
  1854. # If anybody needs to update their GUI, put a callback on this event
  1855. messenger.send("aspectRatioChanged")
  1856. def userExit(self):
  1857. # The user has requested we exit the program. Deal with this.
  1858. if self.exitFunc:
  1859. self.exitFunc()
  1860. self.notify.info("Exiting ShowBase.")
  1861. self.finalizeExit()
  1862. def finalizeExit(self):
  1863. sys.exit()
  1864. # [gjeon] start wxPyhton
  1865. def startWx(self, fWantWx = 1):
  1866. self.wantWx = fWantWx
  1867. if self.wantWx:
  1868. import WxGlobal
  1869. taskMgr.remove('wxLoop')
  1870. WxGlobal.spawnWxLoop()
  1871. def startTk(self, fWantTk = 1):
  1872. self.wantTk = fWantTk
  1873. if self.wantTk:
  1874. import TkGlobal
  1875. taskMgr.remove('tkLoop')
  1876. TkGlobal.spawnTkLoop()
  1877. def startDirect(self, fWantDirect = 1, fWantTk = 1, fWantWx = 0):
  1878. self.startTk(fWantTk)
  1879. self.startWx(fWantWx)
  1880. self.wantDirect = fWantDirect
  1881. if self.wantDirect:
  1882. from direct.directtools import DirectSession
  1883. base.direct.enable()
  1884. else:
  1885. __builtin__.direct = self.direct = None
  1886. def __doStartDirect(self):
  1887. if self.__directStarted:
  1888. return
  1889. self.__directStarted = False
  1890. # Start Tk, Wx and DIRECT if specified by Config.prc
  1891. fTk = self.config.GetBool('want-tk', 0)
  1892. fWx = self.config.GetBool('want-wx', 0)
  1893. # Start DIRECT if specified in Config.prc or in cluster mode
  1894. fDirect = (self.config.GetBool('want-directtools', 0) or
  1895. (self.config.GetString("cluster-mode", '') != ''))
  1896. # Set fWantTk to 0 to avoid starting Tk with this call
  1897. self.startDirect(fWantDirect = fDirect, fWantTk = fTk, fWantWx = fWx)
  1898. def profileFrames(self, num=1):
  1899. # profile the next 'num' frames and log the results
  1900. self.taskMgr.profileFrames(num)
  1901. def run(self):
  1902. self.taskMgr.run()
  1903. # A class to encapsulate information necessary for multiwindow support.
  1904. class WindowControls:
  1905. def __init__(
  1906. self, win, cam=None, cam2d=None, mouseWatcher=None,
  1907. mouseKeyboard=None, closeCmd=lambda: 0):
  1908. self.win = win
  1909. self.camera = cam
  1910. self.camera2d = cam2d
  1911. self.mouseWatcher = mouseWatcher
  1912. self.mouseKeyboard = mouseKeyboard
  1913. self.closeCommand = closeCmd
  1914. def __str__(self):
  1915. s = "window = " + str(self.win) + "\n"
  1916. s += "camera = " + str(self.camera) + "\n"
  1917. s += "camera2d = " + str(self.camera2d) + "\n"
  1918. s += "mouseWatcher = " + str(self.mouseWatcher) + "\n"
  1919. s += "mouseAndKeyboard = " + str(self.mouseKeyboard) + "\n"
  1920. return s