ShowBase.py 92 KB

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