ShowBase.py 132 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418
  1. """ This module contains `.ShowBase`, an application framework responsible
  2. for opening a graphical display, setting up input devices and creating
  3. the scene graph.
  4. The simplest way to open a ShowBase instance is to execute this code:
  5. .. code-block:: python
  6. from direct.showbase.ShowBase import ShowBase
  7. base = ShowBase()
  8. base.run()
  9. A common approach is to create your own subclass inheriting from ShowBase.
  10. Built-in global variables
  11. -------------------------
  12. Some key variables used in all Panda3D scripts are actually attributes of the
  13. ShowBase instance. When creating an instance of this class, it will write many
  14. of these variables to the built-in scope of the Python interpreter, so that
  15. they are accessible to any Python module, without the need fors extra imports.
  16. While these are handy for prototyping, we do not recommend using them in bigger
  17. projects, as it can make the code confusing to read to other Python developers,
  18. to whom it may not be obvious where these variables are originating.
  19. Refer to the :mod:`builtins` page for a listing of the variables written to the
  20. built-in scope.
  21. """
  22. __all__ = ['ShowBase', 'WindowControls']
  23. # This module redefines the builtin import function with one
  24. # that prints out every import it does in a hierarchical form
  25. # Annoying and very noisy, but sometimes useful
  26. #import VerboseImport
  27. from panda3d.core import *
  28. from panda3d.direct import throw_new_frame, init_app_for_gui
  29. from panda3d.direct import storeAccessibilityShortcutKeys, allowAccessibilityShortcutKeys
  30. from . import DConfig
  31. # Register the extension methods for NodePath.
  32. from direct.extensions_native import NodePath_extensions # pylint: disable=unused-import
  33. # This needs to be available early for DirectGUI imports
  34. import sys
  35. import builtins
  36. builtins.config = DConfig
  37. from direct.directnotify.DirectNotifyGlobal import directNotify, giveNotify
  38. from .MessengerGlobal import messenger
  39. from .BulletinBoardGlobal import bulletinBoard
  40. from direct.task.TaskManagerGlobal import taskMgr
  41. from .JobManagerGlobal import jobMgr
  42. from .EventManagerGlobal import eventMgr
  43. from .PythonUtil import Stack
  44. #from PythonUtil import *
  45. from direct.interval import IntervalManager
  46. from direct.showbase.BufferViewer import BufferViewer
  47. from direct.task import Task
  48. from . import Loader
  49. import time
  50. import atexit
  51. import importlib
  52. from direct.showbase import ExceptionVarDump
  53. from . import DirectObject
  54. from . import SfxPlayer
  55. if __debug__:
  56. from direct.showbase import GarbageReport
  57. from direct.directutil import DeltaProfiler
  58. from . import OnScreenDebug
  59. import warnings
  60. @atexit.register
  61. def exitfunc():
  62. if getattr(builtins, 'base', None) is not None:
  63. builtins.base.destroy()
  64. # Now ShowBase is a DirectObject. We need this so ShowBase can hang
  65. # hooks on messages, particularly on window-event. This doesn't
  66. # *seem* to cause anyone any problems.
  67. class ShowBase(DirectObject.DirectObject):
  68. #: The deprecated `.DConfig` interface for accessing config variables.
  69. config = DConfig
  70. notify = directNotify.newCategory("ShowBase")
  71. def __init__(self, fStartDirect=True, windowType=None):
  72. """Opens a window, sets up a 3-D and several 2-D scene graphs, and
  73. everything else needed to render the scene graph to the window.
  74. To prevent a window from being opened, set windowType to the string
  75. 'none' (or 'offscreen' to create an offscreen buffer). If this is not
  76. specified, the default value is taken from the 'window-type'
  77. configuration variable.
  78. This constructor will add various things to the Python builtins scope,
  79. including this instance itself (under the name ``base``).
  80. """
  81. #: Set if the want-dev Config.prc variable is enabled. By default, it
  82. #: is set to True except when using Python with the -O flag.
  83. self.__dev__ = self.config.GetBool('want-dev', __debug__)
  84. builtins.__dev__ = self.__dev__
  85. logStackDump = (self.config.GetBool('log-stack-dump', False) or
  86. self.config.GetBool('client-log-stack-dump', False))
  87. uploadStackDump = self.config.GetBool('upload-stack-dump', False)
  88. if logStackDump or uploadStackDump:
  89. ExceptionVarDump.install(logStackDump, uploadStackDump)
  90. if __debug__:
  91. self.__autoGarbageLogging = self.__dev__ and self.config.GetBool('auto-garbage-logging', False)
  92. #: The directory containing the main Python file of this application.
  93. self.mainDir = ExecutionEnvironment.getEnvironmentVariable("MAIN_DIR")
  94. self.main_dir = self.mainDir
  95. # This contains the global appRunner instance, as imported from
  96. # `.AppRunnerGlobal`. This is deprecated and always None nowadays.
  97. self.appRunner = None
  98. self.app_runner = self.appRunner
  99. #debug running multiplier
  100. self.debugRunningMultiplier = 4
  101. # [gjeon] to disable sticky keys
  102. if self.config.GetBool('disable-sticky-keys', 0):
  103. storeAccessibilityShortcutKeys()
  104. allowAccessibilityShortcutKeys(False)
  105. self.printEnvDebugInfo()
  106. vfs = VirtualFileSystem.getGlobalPtr()
  107. self.nextWindowIndex = 1
  108. self.__directStarted = False
  109. self.__deadInputs = 0
  110. # Store dconfig variables
  111. self.sfxActive = self.config.GetBool('audio-sfx-active', 1)
  112. self.musicActive = self.config.GetBool('audio-music-active', 1)
  113. self.wantFog = self.config.GetBool('want-fog', 1)
  114. self.wantRender2dp = self.config.GetBool('want-render2dp', 1)
  115. self.screenshotExtension = self.config.GetString('screenshot-extension', 'jpg')
  116. self.musicManager = None
  117. self.musicManagerIsValid = None
  118. self.sfxManagerList = []
  119. self.sfxManagerIsValidList = []
  120. self.wantStats = self.config.GetBool('want-pstats', 0)
  121. self.wantTk = False
  122. self.wantWx = False
  123. self.wantDirect = False
  124. #: Fill this in with a function to invoke when the user "exits"
  125. #: the program by closing the main window.
  126. self.exitFunc = None
  127. #: Add final-exit callbacks to this list. These will be called
  128. #: when sys.exit() is called, after Panda has unloaded, and
  129. #: just before Python is about to shut down.
  130. self.finalExitCallbacks = []
  131. # Set up the TaskManager to reset the PStats clock back
  132. # whenever we resume from a pause. This callback function is
  133. # a little hacky, but we can't call it directly from within
  134. # the TaskManager because he doesn't know about PStats (and
  135. # has to run before libpanda is even loaded).
  136. taskMgr.resumeFunc = PStatClient.resumeAfterPause
  137. if self.__dev__:
  138. self.__setupProfile()
  139. # If the aspect ratio is 0 or None, it means to infer the
  140. # aspect ratio from the window size.
  141. # If you need to know the actual aspect ratio call base.getAspectRatio()
  142. self.__configAspectRatio = ConfigVariableDouble('aspect-ratio', 0).getValue()
  143. # This variable is used to see if the aspect ratio has changed when
  144. # we get a window-event.
  145. self.__oldAspectRatio = None
  146. #: This is set to the value of the window-type config variable, but may
  147. #: optionally be overridden in the Showbase constructor. Should either
  148. #: be 'onscreen' (the default), 'offscreen' or 'none'.
  149. self.windowType = windowType
  150. if self.windowType is None:
  151. self.windowType = self.config.GetString('window-type', 'onscreen')
  152. self.requireWindow = self.config.GetBool('require-window', 1)
  153. #: This is the main, or only window; see `winList` for a list of *all* windows.
  154. self.win = None
  155. self.frameRateMeter = None
  156. self.sceneGraphAnalyzerMeter = None
  157. #: A list of all windows opened via `openWindow()`.
  158. self.winList = []
  159. self.winControls = []
  160. self.mainWinMinimized = 0
  161. self.mainWinForeground = 0
  162. #: Contains the :class:`~panda3d.core.GraphicsPipe` object created by
  163. #: `makeDefaultPipe()`.
  164. self.pipe = None
  165. #: The full list of :class:`~panda3d.core.GraphicsPipe` objects,
  166. #: including any auxiliary pipes. Filled by `makeAllPipes()`.
  167. self.pipeList = []
  168. self.mouse2cam = None
  169. self.buttonThrowers = None
  170. self.mouseWatcher = None
  171. #: The :class:`~panda3d.core.MouseWatcher` object, created by
  172. #: `setupMouse()`.
  173. self.mouseWatcherNode = None
  174. self.pointerWatcherNodes = None
  175. self.mouseInterface = None
  176. self.drive = None
  177. self.trackball = None
  178. self.texmem = None
  179. self.showVertices = None
  180. self.deviceButtonThrowers = []
  181. #: This is a :class:`~panda3d.core.NodePath` pointing to the
  182. #: :class:`~panda3d.core.Camera` object set up for the 3D scene.
  183. #: Usually a child of `camera`.
  184. self.cam = None
  185. #: Same as `cam`, but for the 2D scene graph.
  186. self.cam2d = None
  187. #: Same as `cam2d`, but for the 2D overlay scene graph.
  188. self.cam2dp = None
  189. #: This is the :class:`~panda3d.core.NodePath` that should be used to
  190. #: manipulate the camera. It points at the node to which the default
  191. #: camera (`cam`, `camNode`) is attached.
  192. self.camera = None
  193. #: Same as `camera`, but for the 2D scene graph. Parent of `cam2d`.
  194. self.camera2d = None
  195. #: Same as `camera2d`, but for the 2D overlay scene graph. Parent of
  196. #: `cam2dp`.
  197. self.camera2dp = None
  198. #: A list of all cameras created with `makeCamera()`, including `cam`.
  199. self.camList = []
  200. #: Convenience accessor for base.cam.node(), containing a
  201. #: :class:`~panda3d.core.Camera` object.
  202. self.camNode = None
  203. #: Convenience accessor for base.camNode.get_lens(), containing a
  204. #: :class:`~panda3d.core.Lens` object.
  205. self.camLens = None
  206. self.camFrustumVis = None
  207. self.direct = None
  208. #: This is used to store the wx.Application object used when want-wx is
  209. #: set or `startWx()` is called.
  210. self.wxApp = None
  211. self.wxAppCreated = False
  212. self.tkRoot = None
  213. self.tkRootCreated = False
  214. # This is used for syncing multiple PCs in a distributed cluster
  215. try:
  216. # Has the cluster sync variable been set externally?
  217. self.clusterSyncFlag = clusterSyncFlag
  218. except NameError:
  219. # Has the clusterSyncFlag been set via a config variable
  220. self.clusterSyncFlag = self.config.GetBool('cluster-sync', 0)
  221. # We've already created aspect2d in ShowBaseGlobal, for the
  222. # benefit of creating DirectGui elements before ShowBase.
  223. from . import ShowBaseGlobal
  224. self.hidden = ShowBaseGlobal.hidden
  225. #: The global :class:`~panda3d.core.GraphicsEngine`, as returned by
  226. #: GraphicsEngine.getGlobalPtr()
  227. self.graphicsEngine = GraphicsEngine.getGlobalPtr()
  228. self.graphics_engine = self.graphicsEngine
  229. self.setupRender()
  230. self.setupRender2d()
  231. self.setupDataGraph()
  232. if self.wantRender2dp:
  233. self.setupRender2dp()
  234. #: A placeholder for a :class:`~panda3d.core.CollisionTraverser`. If
  235. #: someone stores a CollisionTraverser pointer here, ShowBase will
  236. #: traverse it automatically in the collisionLoop task, so you won't
  237. #: need to call :meth:`~panda3d.core.CollisionTraverser.traverse()`
  238. #: yourself every frame.
  239. self.cTrav = 0
  240. self.shadowTrav = 0
  241. self.cTravStack = Stack()
  242. # Ditto for an AppTraverser.
  243. self.appTrav = 0
  244. # This is the DataGraph traverser, which we might as well
  245. # create now.
  246. self.dgTrav = DataGraphTraverser()
  247. # Maybe create a RecorderController to record and/or play back
  248. # the user session.
  249. self.recorder = None
  250. playbackSession = self.config.GetString('playback-session', '')
  251. recordSession = self.config.GetString('record-session', '')
  252. if playbackSession:
  253. self.recorder = RecorderController()
  254. self.recorder.beginPlayback(Filename.fromOsSpecific(playbackSession))
  255. elif recordSession:
  256. self.recorder = RecorderController()
  257. self.recorder.beginRecord(Filename.fromOsSpecific(recordSession))
  258. if self.recorder:
  259. # If we're either playing back or recording, pass the
  260. # random seed into the system so each session will have
  261. # the same random seed.
  262. import random #, whrandom
  263. seed = self.recorder.getRandomSeed()
  264. random.seed(seed)
  265. #whrandom.seed(seed & 0xff, (seed >> 8) & 0xff, (seed >> 16) & 0xff)
  266. # For some reason, wx needs to be initialized before the graphics window
  267. if sys.platform == "darwin":
  268. if self.config.GetBool("want-wx", 0):
  269. wx = importlib.import_module('wx')
  270. self.wxApp = wx.App()
  271. # Same goes for Tk, which uses a conflicting NSApplication
  272. if self.config.GetBool("want-tk", 0):
  273. Pmw = importlib.import_module('Pmw')
  274. self.tkRoot = Pmw.initialise()
  275. # Open the default rendering window.
  276. if self.windowType != 'none':
  277. props = WindowProperties.getDefault()
  278. if self.config.GetBool('read-raw-mice', 0):
  279. props.setRawMice(1)
  280. self.openDefaultWindow(startDirect = False, props=props)
  281. # The default is trackball mode, which is more convenient for
  282. # ad-hoc development in Python using ShowBase. Applications
  283. # can explicitly call base.useDrive() if they prefer a drive
  284. # interface.
  285. self.mouseInterface = self.trackball
  286. self.useTrackball()
  287. #: `.Loader.Loader` object.
  288. self.loader = Loader.Loader(self)
  289. self.graphicsEngine.setDefaultLoader(self.loader.loader)
  290. #: The global event manager, as imported from `.EventManagerGlobal`.
  291. self.eventMgr = eventMgr
  292. #: The global messenger, as imported from `.MessengerGlobal`.
  293. self.messenger = messenger
  294. #: The global bulletin board, as imported from `.BulletinBoardGlobal`.
  295. self.bboard = bulletinBoard
  296. #: The global task manager, as imported from `.TaskManagerGlobal`.
  297. self.taskMgr = taskMgr
  298. self.task_mgr = taskMgr
  299. #: The global job manager, as imported from `.JobManagerGlobal`.
  300. self.jobMgr = jobMgr
  301. #: If `enableParticles()` has been called, this is the particle manager
  302. #: as imported from :mod:`direct.particles.ParticleManagerGlobal`.
  303. self.particleMgr = None
  304. self.particleMgrEnabled = 0
  305. #: If `enableParticles()` has been called, this is the physics manager
  306. #: as imported from :mod:`direct.showbase.PhysicsManagerGlobal`.
  307. self.physicsMgr = None
  308. self.physicsMgrEnabled = 0
  309. self.physicsMgrAngular = 0
  310. #: This is the global :class:`~panda3d.core.InputDeviceManager`, which
  311. #: keeps track of connected input devices.
  312. self.devices = InputDeviceManager.getGlobalPtr()
  313. self.__inputDeviceNodes = {}
  314. self.createStats()
  315. self.AppHasAudioFocus = 1
  316. # Get a pointer to Panda's global ClockObject, used for
  317. # synchronizing events between Python and C.
  318. globalClock = ClockObject.getGlobalClock()
  319. # Since we have already started up a TaskManager, and probably
  320. # a number of tasks; and since the TaskManager had to use the
  321. # TrueClock to tell time until this moment, make sure the
  322. # globalClock object is exactly in sync with the TrueClock.
  323. trueClock = TrueClock.getGlobalPtr()
  324. globalClock.setRealTime(trueClock.getShortTime())
  325. globalClock.tick()
  326. # Now we can make the TaskManager start using the new globalClock.
  327. taskMgr.globalClock = globalClock
  328. # client CPU affinity is determined by, in order:
  329. # - client-cpu-affinity-mask config
  330. # - pcalt-# (# is CPU number, 0-based)
  331. # - client-cpu-affinity config
  332. # - auto-single-cpu-affinity config
  333. affinityMask = self.config.GetInt('client-cpu-affinity-mask', -1)
  334. if affinityMask != -1:
  335. TrueClock.getGlobalPtr().setCpuAffinity(affinityMask)
  336. else:
  337. # this is useful on machines that perform better with each process
  338. # assigned to a single CPU
  339. autoAffinity = self.config.GetBool('auto-single-cpu-affinity', 0)
  340. affinity = None
  341. if autoAffinity and hasattr(builtins, 'clientIndex'):
  342. affinity = abs(int(builtins.clientIndex))
  343. else:
  344. affinity = self.config.GetInt('client-cpu-affinity', -1)
  345. if (affinity in (None, -1)) and autoAffinity:
  346. affinity = 0
  347. if affinity not in (None, -1):
  348. # Windows XP supports a 32-bit affinity mask
  349. TrueClock.getGlobalPtr().setCpuAffinity(1 << (affinity % 32))
  350. # Make sure we're not making more than one ShowBase.
  351. if hasattr(builtins, 'base'):
  352. raise Exception("Attempt to spawn multiple ShowBase instances!")
  353. # DO NOT ADD TO THIS LIST. We're trying to phase out the use of
  354. # built-in variables by ShowBase. Use a Global module if necessary.
  355. builtins.base = self
  356. builtins.render2d = self.render2d
  357. builtins.aspect2d = self.aspect2d
  358. builtins.pixel2d = self.pixel2d
  359. builtins.render = self.render
  360. builtins.hidden = self.hidden
  361. builtins.camera = self.camera
  362. builtins.loader = self.loader
  363. builtins.taskMgr = self.taskMgr
  364. builtins.jobMgr = self.jobMgr
  365. builtins.eventMgr = self.eventMgr
  366. builtins.messenger = self.messenger
  367. builtins.bboard = self.bboard
  368. # Config needs to be defined before ShowBase is constructed
  369. #builtins.config = self.config
  370. builtins.ostream = Notify.out()
  371. builtins.directNotify = directNotify
  372. builtins.giveNotify = giveNotify
  373. builtins.globalClock = globalClock
  374. builtins.vfs = vfs
  375. builtins.cpMgr = ConfigPageManager.getGlobalPtr()
  376. builtins.cvMgr = ConfigVariableManager.getGlobalPtr()
  377. builtins.pandaSystem = PandaSystem.getGlobalPtr()
  378. if __debug__:
  379. builtins.deltaProfiler = DeltaProfiler.DeltaProfiler("ShowBase")
  380. self.onScreenDebug = OnScreenDebug.OnScreenDebug()
  381. builtins.onScreenDebug = self.onScreenDebug
  382. if self.wantRender2dp:
  383. builtins.render2dp = self.render2dp
  384. builtins.aspect2dp = self.aspect2dp
  385. builtins.pixel2dp = self.pixel2dp
  386. # Now add this instance to the ShowBaseGlobal module scope.
  387. builtins.run = ShowBaseGlobal.run
  388. ShowBaseGlobal.base = self
  389. ShowBaseGlobal.__dev__ = self.__dev__
  390. if self.__dev__:
  391. ShowBase.notify.debug('__dev__ == %s' % self.__dev__)
  392. else:
  393. ShowBase.notify.info('__dev__ == %s' % self.__dev__)
  394. self.createBaseAudioManagers()
  395. if self.__dev__ and self.config.GetBool('track-gui-items', False):
  396. # dict of guiId to gui item, for tracking down leaks
  397. if not hasattr(ShowBase, 'guiItems'):
  398. ShowBase.guiItems = {}
  399. # optionally restore the default gui sounds from 1.7.2 and earlier
  400. if ConfigVariableBool('orig-gui-sounds', False).getValue():
  401. from direct.gui import DirectGuiGlobals as DGG
  402. DGG.setDefaultClickSound(self.loader.loadSfx("audio/sfx/GUI_click.wav"))
  403. DGG.setDefaultRolloverSound(self.loader.loadSfx("audio/sfx/GUI_rollover.wav"))
  404. # Now hang a hook on the window-event from Panda. This allows
  405. # us to detect when the user resizes, minimizes, or closes the
  406. # main window.
  407. self.__prevWindowProperties = None
  408. self.accept('window-event', self.windowEvent)
  409. # Transition effects (fade, iris, etc)
  410. from . import Transitions
  411. #: `.Transitions.Transitions` object.
  412. self.transitions = Transitions.Transitions(self.loader)
  413. if self.win:
  414. # Setup the window controls - handy for multiwindow applications
  415. self.setupWindowControls()
  416. # Client sleep
  417. sleepTime = self.config.GetFloat('client-sleep', 0.0)
  418. self.clientSleep = 0.0
  419. self.setSleep(sleepTime)
  420. # Extra sleep for running 4+ clients on a single machine
  421. # adds a sleep right after the main render in igloop
  422. # tends to even out the frame rate and keeps it from going
  423. # to zero in the out of focus windows
  424. if self.config.GetBool('multi-sleep', 0):
  425. self.multiClientSleep = 1
  426. else:
  427. self.multiClientSleep = 0
  428. #: Utility for viewing offscreen buffers, see :mod:`.BufferViewer`.
  429. self.bufferViewer = BufferViewer(self.win, self.render2dp if self.wantRender2dp else self.render2d)
  430. if self.windowType != 'none':
  431. if fStartDirect: # [gjeon] if this is False let them start direct manually
  432. self.__doStartDirect()
  433. if self.config.GetBool('show-tex-mem', False):
  434. if not self.texmem or self.texmem.cleanedUp:
  435. self.toggleTexMem()
  436. taskMgr.finalInit()
  437. # Start IGLOOP
  438. self.restart()
  439. # add a collision traverser via pushCTrav and remove it via popCTrav
  440. # that way the owner of the new cTrav doesn't need to hold onto the
  441. # previous one in order to put it back
  442. def pushCTrav(self, cTrav):
  443. self.cTravStack.push(self.cTrav)
  444. self.cTrav = cTrav
  445. def popCTrav(self):
  446. self.cTrav = self.cTravStack.pop()
  447. def __setupProfile(self):
  448. """ Sets up the Python profiler, if available, according to
  449. some Panda config settings. """
  450. try:
  451. profile = importlib.import_module('profile')
  452. pstats = importlib.import_module('pstats')
  453. except ImportError:
  454. return
  455. profile.Profile.bias = float(self.config.GetString("profile-bias","0"))
  456. def f8(x):
  457. return ("%" + "8.%df" % self.config.GetInt("profile-decimals", 3)) % x
  458. pstats.f8 = f8
  459. # temp; see ToonBase.py
  460. def getExitErrorCode(self):
  461. return 0
  462. def printEnvDebugInfo(self):
  463. """Print some information about the environment that we are running
  464. in. Stuff like the model paths and other paths. Feel free to
  465. add stuff to this.
  466. """
  467. if self.config.GetBool('want-env-debug-info', 0):
  468. print("\n\nEnvironment Debug Info {")
  469. print("* model path:")
  470. print(getModelPath())
  471. #print "* dna path:"
  472. #print getDnaPath()
  473. print("}")
  474. def destroy(self):
  475. """ Call this function to destroy the ShowBase and stop all
  476. its tasks, freeing all of the Panda resources. Normally, you
  477. should not need to call it explicitly, as it is bound to the
  478. exitfunc and will be called at application exit time
  479. automatically.
  480. This function is designed to be safe to call multiple times."""
  481. for cb in self.finalExitCallbacks[:]:
  482. cb()
  483. # Remove the built-in base reference
  484. if getattr(builtins, 'base', None) is self:
  485. del builtins.run
  486. del builtins.base
  487. del builtins.loader
  488. del builtins.taskMgr
  489. ShowBaseGlobal = sys.modules.get('direct.showbase.ShowBaseGlobal', None)
  490. if ShowBaseGlobal:
  491. del ShowBaseGlobal.base
  492. self.aspect2d.node().removeAllChildren()
  493. self.render2d.node().removeAllChildren()
  494. self.aspect2d.reparent_to(self.render2d)
  495. # [gjeon] restore sticky key settings
  496. if self.config.GetBool('disable-sticky-keys', 0):
  497. allowAccessibilityShortcutKeys(True)
  498. self.ignoreAll()
  499. self.shutdown()
  500. if getattr(self, 'musicManager', None):
  501. self.musicManager.shutdown()
  502. self.musicManager = None
  503. for sfxManager in self.sfxManagerList:
  504. sfxManager.shutdown()
  505. self.sfxManagerList = []
  506. if getattr(self, 'loader', None):
  507. self.loader.destroy()
  508. self.loader = None
  509. if getattr(self, 'graphicsEngine', None):
  510. self.graphicsEngine.removeAllWindows()
  511. try:
  512. self.direct.panel.destroy()
  513. except:
  514. pass
  515. if hasattr(self, 'win'):
  516. del self.win
  517. del self.winList
  518. del self.pipe
  519. def makeDefaultPipe(self, printPipeTypes = None):
  520. """
  521. Creates the default GraphicsPipe, which will be used to make
  522. windows unless otherwise specified.
  523. """
  524. assert self.pipe is None
  525. if printPipeTypes is None:
  526. # When the user didn't specify an explicit setting, take the value
  527. # from the config variable. We could just omit the parameter, however
  528. # this way we can keep backward compatibility.
  529. printPipeTypes = ConfigVariableBool("print-pipe-types", True)
  530. selection = GraphicsPipeSelection.getGlobalPtr()
  531. if printPipeTypes:
  532. selection.printPipeTypes()
  533. self.pipe = selection.makeDefaultPipe()
  534. if not self.pipe:
  535. self.notify.error(
  536. "No graphics pipe is available!\n"
  537. "Your Config.prc file must name at least one valid panda display\n"
  538. "library via load-display or aux-display.")
  539. self.notify.info("Default graphics pipe is %s (%s)." % (
  540. self.pipe.getType().getName(), self.pipe.getInterfaceName()))
  541. self.pipeList.append(self.pipe)
  542. def makeModulePipe(self, moduleName):
  543. """
  544. Returns a GraphicsPipe from the indicated module,
  545. e.g. 'pandagl' or 'pandadx9'. Does not affect base.pipe or
  546. base.pipeList.
  547. :rtype: panda3d.core.GraphicsPipe
  548. """
  549. selection = GraphicsPipeSelection.getGlobalPtr()
  550. return selection.makeModulePipe(moduleName)
  551. def makeAllPipes(self):
  552. """
  553. Creates all GraphicsPipes that the system knows about and fill up
  554. `pipeList` with them.
  555. """
  556. selection = GraphicsPipeSelection.getGlobalPtr()
  557. selection.loadAuxModules()
  558. # First, we should make sure the default pipe exists.
  559. if self.pipe is None:
  560. self.makeDefaultPipe()
  561. # Now go through the list of known pipes, and make each one if
  562. # we don't have one already.
  563. numPipeTypes = selection.getNumPipeTypes()
  564. for i in range(numPipeTypes):
  565. pipeType = selection.getPipeType(i)
  566. # Do we already have a pipe of this type on the list?
  567. # This operation is n-squared, but presumably there won't
  568. # be more than a handful of pipe types, so who cares.
  569. already = 0
  570. for pipe in self.pipeList:
  571. if pipe.getType() == pipeType:
  572. already = 1
  573. if not already:
  574. pipe = selection.makePipe(pipeType)
  575. if pipe:
  576. self.notify.info("Got aux graphics pipe %s (%s)." % (
  577. pipe.getType().getName(), pipe.getInterfaceName()))
  578. self.pipeList.append(pipe)
  579. else:
  580. self.notify.info("Could not make graphics pipe %s." % (
  581. pipeType.getName()))
  582. def openWindow(self, props = None, fbprops = None, pipe = None, gsg = None,
  583. host = None, type = None, name = None, size = None,
  584. aspectRatio = None, makeCamera = True, keepCamera = False,
  585. scene = None, stereo = None, unexposedDraw = None,
  586. callbackWindowDict = None, requireWindow = None):
  587. """
  588. Creates a window and adds it to the list of windows that are
  589. to be updated every frame.
  590. :param props: the :class:`~panda3d.core.WindowProperties` that
  591. describes the window.
  592. :param fbprops: the :class:`~panda3d.core.FrameBufferProperties`
  593. indicating the requested framebuffer properties.
  594. :param type: Either 'onscreen', 'offscreen', or 'none'.
  595. :param keepCamera: If True, the existing base.cam is set up to
  596. render into the new window.
  597. :param makeCamera: If True (and keepCamera is False), a new camera is
  598. set up to render into the new window.
  599. :param unexposedDraw: If not None, it specifies the initial value
  600. of :meth:`~panda3d.core.GraphicsWindow.setUnexposedDraw()`.
  601. :param callbackWindowDict: If not None, a
  602. :class:`~panda3d.core.CallbackGraphicWindow`
  603. is created instead, which allows the caller
  604. to create the actual window with its own
  605. OpenGL context, and direct Panda's rendering
  606. into that window.
  607. :param requireWindow: If True, the function should raise an exception
  608. if the window fails to open correctly.
  609. :rtype: panda3d.core.GraphicsWindow
  610. """
  611. # Save this lambda here for convenience; we'll use it to call
  612. # down to the underlying _doOpenWindow() with all of the above
  613. # parameters.
  614. func = lambda : self._doOpenWindow(
  615. props = props, fbprops = fbprops, pipe = pipe, gsg = gsg,
  616. host = host, type = type, name = name, size = size,
  617. aspectRatio = aspectRatio, makeCamera = makeCamera,
  618. keepCamera = keepCamera, scene = scene, stereo = stereo,
  619. unexposedDraw = unexposedDraw,
  620. callbackWindowDict = callbackWindowDict)
  621. if self.win:
  622. # If we've already opened a window before, this is just a
  623. # pass-through to _doOpenWindow().
  624. win = func()
  625. self.graphicsEngine.openWindows()
  626. return win
  627. if type is None:
  628. type = self.windowType
  629. if requireWindow is None:
  630. requireWindow = self.requireWindow
  631. win = func()
  632. # Give the window a chance to truly open.
  633. self.graphicsEngine.openWindows()
  634. if win is not None and not win.isValid():
  635. self.notify.info("Window did not open, removing.")
  636. self.closeWindow(win)
  637. win = None
  638. if win is None and pipe is None:
  639. # Try a little harder if the window wouldn't open.
  640. self.makeAllPipes()
  641. try:
  642. self.pipeList.remove(self.pipe)
  643. except ValueError:
  644. pass
  645. while self.win is None and self.pipeList:
  646. self.pipe = self.pipeList[0]
  647. self.notify.info("Trying pipe type %s (%s)" % (
  648. self.pipe.getType(), self.pipe.getInterfaceName()))
  649. win = func()
  650. self.graphicsEngine.openWindows()
  651. if win is not None and not win.isValid():
  652. self.notify.info("Window did not open, removing.")
  653. self.closeWindow(win)
  654. win = None
  655. if win is None:
  656. self.pipeList.remove(self.pipe)
  657. if win is None:
  658. self.notify.warning("Unable to open '%s' window." % (type))
  659. if requireWindow:
  660. # Unless require-window is set to false, it is an
  661. # error not to open a window.
  662. raise Exception('Could not open window.')
  663. else:
  664. self.notify.info("Successfully opened window of type %s (%s)" % (
  665. win.getType(), win.getPipe().getInterfaceName()))
  666. return win
  667. def _doOpenWindow(self, props = None, fbprops = None, pipe = None,
  668. gsg = None, host = None, type = None, name = None,
  669. size = None, aspectRatio = None,
  670. makeCamera = True, keepCamera = False,
  671. scene = None, stereo = None, unexposedDraw = None,
  672. callbackWindowDict = None):
  673. if pipe is None:
  674. pipe = self.pipe
  675. if pipe is None:
  676. self.makeDefaultPipe()
  677. pipe = self.pipe
  678. if pipe is None:
  679. # We couldn't get a pipe.
  680. return None
  681. if isinstance(gsg, GraphicsOutput):
  682. # If the gsg is a window or buffer, it means to use the
  683. # GSG from that buffer.
  684. host = gsg
  685. gsg = gsg.getGsg()
  686. # If we are using DirectX, force a new GSG to be created,
  687. # since at the moment DirectX seems to misbehave if we do
  688. # not do this. This will cause a delay while all textures
  689. # etc. are reloaded, so we should revisit this later if we
  690. # can fix the underlying bug in our DirectX support.
  691. if pipe.getType().getName().startswith('wdx'):
  692. gsg = None
  693. if type is None:
  694. type = self.windowType
  695. if props is None:
  696. props = WindowProperties.getDefault()
  697. if fbprops is None:
  698. fbprops = FrameBufferProperties.getDefault()
  699. if size is not None:
  700. # If we were given an explicit size, use it; otherwise,
  701. # the size from the properties is used.
  702. props = WindowProperties(props)
  703. props.setSize(size[0], size[1])
  704. if name is None:
  705. name = 'window%s' % (self.nextWindowIndex)
  706. self.nextWindowIndex += 1
  707. win = None
  708. flags = GraphicsPipe.BFFbPropsOptional
  709. if type == 'onscreen':
  710. flags = flags | GraphicsPipe.BFRequireWindow
  711. elif type == 'offscreen':
  712. flags = flags | GraphicsPipe.BFRefuseWindow
  713. if callbackWindowDict:
  714. flags = flags | GraphicsPipe.BFRequireCallbackWindow
  715. if host:
  716. assert host.isValid()
  717. win = self.graphicsEngine.makeOutput(pipe, name, 0, fbprops,
  718. props, flags, host.getGsg(), host)
  719. elif gsg:
  720. win = self.graphicsEngine.makeOutput(pipe, name, 0, fbprops,
  721. props, flags, gsg)
  722. else:
  723. win = self.graphicsEngine.makeOutput(pipe, name, 0, fbprops,
  724. props, flags)
  725. if win is None:
  726. # Couldn't create a window!
  727. return None
  728. if unexposedDraw is not None and hasattr(win, 'setUnexposedDraw'):
  729. win.setUnexposedDraw(unexposedDraw)
  730. if callbackWindowDict:
  731. # If we asked for (and received) a CallbackGraphicsWindow,
  732. # we now have to assign the callbacks, before we start
  733. # trying to do anything with the window.
  734. for callbackName in ['Events', 'Properties', 'Render']:
  735. func = callbackWindowDict.get(callbackName, None)
  736. if not func:
  737. continue
  738. setCallbackName = 'set%sCallback' % (callbackName)
  739. setCallback = getattr(win, setCallbackName)
  740. setCallback(PythonCallbackObject(func))
  741. # We also need to set up the mouse/keyboard objects.
  742. for inputName in callbackWindowDict.get('inputDevices', ['mouse']):
  743. win.createInputDevice(inputName)
  744. if hasattr(win, "requestProperties"):
  745. win.requestProperties(props)
  746. mainWindow = False
  747. if self.win is None:
  748. mainWindow = True
  749. self.win = win
  750. if hasattr(self, 'bufferViewer'):
  751. self.bufferViewer.win = win
  752. self.winList.append(win)
  753. # Set up a 3-d camera for the window by default.
  754. if keepCamera:
  755. self.makeCamera(win, scene = scene, aspectRatio = aspectRatio,
  756. stereo = stereo, useCamera = self.cam)
  757. elif makeCamera:
  758. self.makeCamera(win, scene = scene, aspectRatio = aspectRatio,
  759. stereo = stereo)
  760. messenger.send('open_window', [win, mainWindow])
  761. if mainWindow:
  762. messenger.send('open_main_window')
  763. return win
  764. def closeWindow(self, win, keepCamera = False, removeWindow = True):
  765. """
  766. Closes the indicated window and removes it from the list of
  767. windows. If it is the main window, clears the main window
  768. pointer to None.
  769. """
  770. win.setActive(False)
  771. # First, remove all of the cameras associated with display
  772. # regions on the window.
  773. numRegions = win.getNumDisplayRegions()
  774. for i in range(numRegions):
  775. dr = win.getDisplayRegion(i)
  776. # [gjeon] remove drc in base.direct.drList
  777. if self.direct is not None:
  778. for drc in self.direct.drList:
  779. if drc.cam == dr.getCamera():
  780. self.direct.drList.displayRegionList.remove(drc)
  781. break
  782. cam = NodePath(dr.getCamera())
  783. dr.setCamera(NodePath())
  784. if not cam.isEmpty() and \
  785. cam.node().getNumDisplayRegions() == 0 and \
  786. not keepCamera:
  787. # If the camera is used by no other DisplayRegions,
  788. # remove it.
  789. if self.camList.count(cam) != 0:
  790. self.camList.remove(cam)
  791. # Don't throw away self.camera; we want to
  792. # preserve it for reopening the window.
  793. if cam == self.cam:
  794. self.cam = None
  795. if cam == self.cam2d:
  796. self.cam2d = None
  797. if cam == self.cam2dp:
  798. self.cam2dp = None
  799. cam.removeNode()
  800. # [gjeon] remove winControl
  801. for winCtrl in self.winControls:
  802. if winCtrl.win == win:
  803. self.winControls.remove(winCtrl)
  804. break
  805. # Now we can actually close the window.
  806. if removeWindow:
  807. self.graphicsEngine.removeWindow(win)
  808. self.winList.remove(win)
  809. mainWindow = False
  810. if win == self.win:
  811. mainWindow = True
  812. self.win = None
  813. if self.frameRateMeter:
  814. self.frameRateMeter.clearWindow()
  815. self.frameRateMeter = None
  816. if self.sceneGraphAnalyzerMeter:
  817. self.sceneGraphAnalyzerMeter.clearWindow()
  818. self.sceneGraphAnalyzerMeter = None
  819. messenger.send('close_window', [win, mainWindow])
  820. if mainWindow:
  821. messenger.send('close_main_window')
  822. if not self.winList:
  823. # Give the window(s) a chance to actually close before we
  824. # continue.
  825. self.graphicsEngine.renderFrame()
  826. def openDefaultWindow(self, *args, **kw):
  827. """
  828. Creates the main window for the first time, without being too
  829. particular about the kind of graphics API that is chosen.
  830. The suggested window type from the load-display config variable is
  831. tried first; if that fails, the first window type that can be
  832. successfully opened at all is accepted.
  833. This is intended to be called only once, at application startup.
  834. It is normally called automatically unless window-type is configured
  835. to 'none'.
  836. :returns: True on success, False on failure.
  837. """
  838. startDirect = kw.get('startDirect', True)
  839. if 'startDirect' in kw:
  840. del kw['startDirect']
  841. self.openMainWindow(*args, **kw)
  842. if startDirect:
  843. self.__doStartDirect()
  844. return self.win is not None
  845. def openMainWindow(self, *args, **kw):
  846. """
  847. Creates the initial, main window for the application, and sets
  848. up the mouse and render2d structures appropriately for it. If
  849. this method is called a second time, it will close the
  850. previous main window and open a new one, preserving the lens
  851. properties in base.camLens.
  852. :returns: True on success, or False on failure (in which case base.win
  853. may be either None, or the previous, closed window).
  854. """
  855. keepCamera = kw.get('keepCamera', False)
  856. success = 1
  857. oldWin = self.win
  858. oldLens = self.camLens
  859. oldClearColorActive = None
  860. if self.win is not None:
  861. # Close the previous window.
  862. oldClearColorActive = self.win.getClearColorActive()
  863. oldClearColor = VBase4(self.win.getClearColor())
  864. oldClearDepthActive = self.win.getClearDepthActive()
  865. oldClearDepth = self.win.getClearDepth()
  866. oldClearStencilActive = self.win.getClearStencilActive()
  867. oldClearStencil = self.win.getClearStencil()
  868. self.closeWindow(self.win, keepCamera = keepCamera)
  869. # Open a new window.
  870. self.openWindow(*args, **kw)
  871. if self.win is None:
  872. self.win = oldWin
  873. self.winList.append(oldWin)
  874. success = 0
  875. if self.win is not None:
  876. if isinstance(self.win, GraphicsWindow):
  877. self.setupMouse(self.win)
  878. self.makeCamera2d(self.win)
  879. if self.wantRender2dp:
  880. self.makeCamera2dp(self.win)
  881. if oldLens is not None:
  882. # Restore the previous lens properties.
  883. self.camNode.setLens(oldLens)
  884. self.camLens = oldLens
  885. if oldClearColorActive is not None:
  886. # Restore the previous clear properties.
  887. self.win.setClearColorActive(oldClearColorActive)
  888. self.win.setClearColor(oldClearColor)
  889. self.win.setClearDepthActive(oldClearDepthActive)
  890. self.win.setClearDepth(oldClearDepth)
  891. self.win.setClearStencilActive(oldClearStencilActive)
  892. self.win.setClearStencil(oldClearStencil)
  893. flag = self.config.GetBool('show-frame-rate-meter', False)
  894. if self.appRunner is not None and self.appRunner.allowPythonDev:
  895. # In an allow_python_dev p3d application, we always
  896. # start up with the frame rate meter enabled, to
  897. # provide a visual reminder that this flag has been
  898. # set.
  899. flag = True
  900. self.setFrameRateMeter(flag)
  901. flag = self.config.GetBool('show-scene-graph-analyzer-meter', False)
  902. self.setSceneGraphAnalyzerMeter(flag)
  903. return success
  904. def setSleep(self, amount):
  905. """
  906. Sets up a task that calls python 'sleep' every frame. This is a simple
  907. way to reduce the CPU usage (and frame rate) of a panda program.
  908. """
  909. if self.clientSleep == amount:
  910. return
  911. self.clientSleep = amount
  912. if amount == 0.0:
  913. self.taskMgr.remove('clientSleep')
  914. else:
  915. # Spawn it after igloop (at the end of each frame)
  916. self.taskMgr.remove('clientSleep')
  917. self.taskMgr.add(self.__sleepCycleTask, 'clientSleep', sort = 55)
  918. def __sleepCycleTask(self, task):
  919. Thread.sleep(self.clientSleep)
  920. #time.sleep(self.clientSleep)
  921. return Task.cont
  922. def setFrameRateMeter(self, flag):
  923. """
  924. Turns on or off (according to flag) a standard frame rate
  925. meter in the upper-right corner of the main window.
  926. """
  927. if flag:
  928. if not self.frameRateMeter:
  929. self.frameRateMeter = FrameRateMeter('frameRateMeter')
  930. self.frameRateMeter.setupWindow(self.win)
  931. else:
  932. if self.frameRateMeter:
  933. self.frameRateMeter.clearWindow()
  934. self.frameRateMeter = None
  935. def setSceneGraphAnalyzerMeter(self, flag):
  936. """
  937. Turns on or off (according to flag) a standard frame rate
  938. meter in the upper-right corner of the main window.
  939. """
  940. if flag:
  941. if not self.sceneGraphAnalyzerMeter:
  942. self.sceneGraphAnalyzerMeter = SceneGraphAnalyzerMeter('sceneGraphAnalyzerMeter', self.render.node())
  943. self.sceneGraphAnalyzerMeter.setupWindow(self.win)
  944. else:
  945. if self.sceneGraphAnalyzerMeter:
  946. self.sceneGraphAnalyzerMeter.clearWindow()
  947. self.sceneGraphAnalyzerMeter = None
  948. # [gjeon] now you can add more winControls after creating a showbase instance
  949. def setupWindowControls(self, winCtrl=None):
  950. if winCtrl is None:
  951. winCtrl = WindowControls(
  952. self.win, mouseWatcher=self.mouseWatcher,
  953. cam=self.camera, camNode = self.camNode, cam2d=self.camera2d,
  954. mouseKeyboard = self.dataRoot.find("**/*"))
  955. self.winControls.append(winCtrl)
  956. def setupRender(self):
  957. """
  958. Creates the render scene graph, the primary scene graph for
  959. rendering 3-d geometry.
  960. """
  961. ## This is the root of the 3-D scene graph.
  962. self.render = NodePath('render')
  963. self.render.setAttrib(RescaleNormalAttrib.makeDefault())
  964. self.render.setTwoSided(0)
  965. self.backfaceCullingEnabled = 1
  966. self.textureEnabled = 1
  967. self.wireframeEnabled = 0
  968. def setupRender2d(self):
  969. """
  970. Creates the render2d scene graph, the primary scene graph for
  971. 2-d objects and gui elements that are superimposed over the
  972. 3-d geometry in the window.
  973. """
  974. # We've already created render2d and aspect2d in ShowBaseGlobal,
  975. # for the benefit of creating DirectGui elements before ShowBase.
  976. from . import ShowBaseGlobal
  977. ## This is the root of the 2-D scene graph.
  978. self.render2d = ShowBaseGlobal.render2d
  979. # Set up some overrides to turn off certain properties which
  980. # we probably won't need for 2-d objects.
  981. # It's probably important to turn off the depth test, since
  982. # many 2-d objects will be drawn over each other without
  983. # regard to depth position.
  984. # We used to avoid clearing the depth buffer before drawing
  985. # render2d, but nowadays we clear it anyway, since we
  986. # occasionally want to put 3-d geometry under render2d, and
  987. # it's simplest (and seems to be easier on graphics drivers)
  988. # if the 2-d scene has been cleared first.
  989. self.render2d.setDepthTest(0)
  990. self.render2d.setDepthWrite(0)
  991. self.render2d.setMaterialOff(1)
  992. self.render2d.setTwoSided(1)
  993. ## The normal 2-d DisplayRegion has an aspect ratio that
  994. ## matches the window, but its coordinate system is square.
  995. ## This means anything we parent to render2d gets stretched.
  996. ## For things where that makes a difference, we set up
  997. ## aspect2d, which scales things back to the right aspect
  998. ## ratio along the X axis (Z is still from -1 to 1)
  999. self.aspect2d = ShowBaseGlobal.aspect2d
  1000. aspectRatio = self.getAspectRatio()
  1001. self.aspect2d.setScale(1.0 / aspectRatio, 1.0, 1.0)
  1002. self.a2dBackground = self.aspect2d.attachNewNode("a2dBackground")
  1003. ## The Z position of the top border of the aspect2d screen.
  1004. self.a2dTop = 1.0
  1005. ## The Z position of the bottom border of the aspect2d screen.
  1006. self.a2dBottom = -1.0
  1007. ## The X position of the left border of the aspect2d screen.
  1008. self.a2dLeft = -aspectRatio
  1009. ## The X position of the right border of the aspect2d screen.
  1010. self.a2dRight = aspectRatio
  1011. self.a2dTopCenter = self.aspect2d.attachNewNode("a2dTopCenter")
  1012. self.a2dTopCenterNs = self.aspect2d.attachNewNode("a2dTopCenterNS")
  1013. self.a2dBottomCenter = self.aspect2d.attachNewNode("a2dBottomCenter")
  1014. self.a2dBottomCenterNs = self.aspect2d.attachNewNode("a2dBottomCenterNS")
  1015. self.a2dLeftCenter = self.aspect2d.attachNewNode("a2dLeftCenter")
  1016. self.a2dLeftCenterNs = self.aspect2d.attachNewNode("a2dLeftCenterNS")
  1017. self.a2dRightCenter = self.aspect2d.attachNewNode("a2dRightCenter")
  1018. self.a2dRightCenterNs = self.aspect2d.attachNewNode("a2dRightCenterNS")
  1019. self.a2dTopLeft = self.aspect2d.attachNewNode("a2dTopLeft")
  1020. self.a2dTopLeftNs = self.aspect2d.attachNewNode("a2dTopLeftNS")
  1021. self.a2dTopRight = self.aspect2d.attachNewNode("a2dTopRight")
  1022. self.a2dTopRightNs = self.aspect2d.attachNewNode("a2dTopRightNS")
  1023. self.a2dBottomLeft = self.aspect2d.attachNewNode("a2dBottomLeft")
  1024. self.a2dBottomLeftNs = self.aspect2d.attachNewNode("a2dBottomLeftNS")
  1025. self.a2dBottomRight = self.aspect2d.attachNewNode("a2dBottomRight")
  1026. self.a2dBottomRightNs = self.aspect2d.attachNewNode("a2dBottomRightNS")
  1027. # Put the nodes in their places
  1028. self.a2dTopCenter.setPos(0, 0, self.a2dTop)
  1029. self.a2dTopCenterNs.setPos(0, 0, self.a2dTop)
  1030. self.a2dBottomCenter.setPos(0, 0, self.a2dBottom)
  1031. self.a2dBottomCenterNs.setPos(0, 0, self.a2dBottom)
  1032. self.a2dLeftCenter.setPos(self.a2dLeft, 0, 0)
  1033. self.a2dLeftCenterNs.setPos(self.a2dLeft, 0, 0)
  1034. self.a2dRightCenter.setPos(self.a2dRight, 0, 0)
  1035. self.a2dRightCenterNs.setPos(self.a2dRight, 0, 0)
  1036. self.a2dTopLeft.setPos(self.a2dLeft, 0, self.a2dTop)
  1037. self.a2dTopLeftNs.setPos(self.a2dLeft, 0, self.a2dTop)
  1038. self.a2dTopRight.setPos(self.a2dRight, 0, self.a2dTop)
  1039. self.a2dTopRightNs.setPos(self.a2dRight, 0, self.a2dTop)
  1040. self.a2dBottomLeft.setPos(self.a2dLeft, 0, self.a2dBottom)
  1041. self.a2dBottomLeftNs.setPos(self.a2dLeft, 0, self.a2dBottom)
  1042. self.a2dBottomRight.setPos(self.a2dRight, 0, self.a2dBottom)
  1043. self.a2dBottomRightNs.setPos(self.a2dRight, 0, self.a2dBottom)
  1044. ## This special root, pixel2d, uses units in pixels that are relative
  1045. ## to the window. The upperleft corner of the window is (0, 0),
  1046. ## the lowerleft corner is (xsize, -ysize), in this coordinate system.
  1047. self.pixel2d = self.render2d.attachNewNode(PGTop("pixel2d"))
  1048. self.pixel2d.setPos(-1, 0, 1)
  1049. xsize, ysize = self.getSize()
  1050. if xsize > 0 and ysize > 0:
  1051. self.pixel2d.setScale(2.0 / xsize, 1.0, 2.0 / ysize)
  1052. def setupRender2dp(self):
  1053. """
  1054. Creates a render2d scene graph, the secondary scene graph for
  1055. 2-d objects and gui elements that are superimposed over the
  1056. 2-d and 3-d geometry in the window.
  1057. """
  1058. self.render2dp = NodePath('render2dp')
  1059. # Set up some overrides to turn off certain properties which
  1060. # we probably won't need for 2-d objects.
  1061. # It's probably important to turn off the depth test, since
  1062. # many 2-d objects will be drawn over each other without
  1063. # regard to depth position.
  1064. dt = DepthTestAttrib.make(DepthTestAttrib.MNone)
  1065. dw = DepthWriteAttrib.make(DepthWriteAttrib.MOff)
  1066. self.render2dp.setDepthTest(0)
  1067. self.render2dp.setDepthWrite(0)
  1068. self.render2dp.setMaterialOff(1)
  1069. self.render2dp.setTwoSided(1)
  1070. ## The normal 2-d DisplayRegion has an aspect ratio that
  1071. ## matches the window, but its coordinate system is square.
  1072. ## This means anything we parent to render2dp gets stretched.
  1073. ## For things where that makes a difference, we set up
  1074. ## aspect2dp, which scales things back to the right aspect
  1075. ## ratio along the X axis (Z is still from -1 to 1)
  1076. self.aspect2dp = self.render2dp.attachNewNode(PGTop("aspect2dp"))
  1077. self.aspect2dp.node().setStartSort(16384)
  1078. aspectRatio = self.getAspectRatio()
  1079. self.aspect2dp.setScale(1.0 / aspectRatio, 1.0, 1.0)
  1080. ## The Z position of the top border of the aspect2dp screen.
  1081. self.a2dpTop = 1.0
  1082. ## The Z position of the bottom border of the aspect2dp screen.
  1083. self.a2dpBottom = -1.0
  1084. ## The X position of the left border of the aspect2dp screen.
  1085. self.a2dpLeft = -aspectRatio
  1086. ## The X position of the right border of the aspect2dp screen.
  1087. self.a2dpRight = aspectRatio
  1088. self.a2dpTopCenter = self.aspect2dp.attachNewNode("a2dpTopCenter")
  1089. self.a2dpBottomCenter = self.aspect2dp.attachNewNode("a2dpBottomCenter")
  1090. self.a2dpLeftCenter = self.aspect2dp.attachNewNode("a2dpLeftCenter")
  1091. self.a2dpRightCenter = self.aspect2dp.attachNewNode("a2dpRightCenter")
  1092. self.a2dpTopLeft = self.aspect2dp.attachNewNode("a2dpTopLeft")
  1093. self.a2dpTopRight = self.aspect2dp.attachNewNode("a2dpTopRight")
  1094. self.a2dpBottomLeft = self.aspect2dp.attachNewNode("a2dpBottomLeft")
  1095. self.a2dpBottomRight = self.aspect2dp.attachNewNode("a2dpBottomRight")
  1096. # Put the nodes in their places
  1097. self.a2dpTopCenter.setPos(0, 0, self.a2dpTop)
  1098. self.a2dpBottomCenter.setPos(0, 0, self.a2dpBottom)
  1099. self.a2dpLeftCenter.setPos(self.a2dpLeft, 0, 0)
  1100. self.a2dpRightCenter.setPos(self.a2dpRight, 0, 0)
  1101. self.a2dpTopLeft.setPos(self.a2dpLeft, 0, self.a2dpTop)
  1102. self.a2dpTopRight.setPos(self.a2dpRight, 0, self.a2dpTop)
  1103. self.a2dpBottomLeft.setPos(self.a2dpLeft, 0, self.a2dpBottom)
  1104. self.a2dpBottomRight.setPos(self.a2dpRight, 0, self.a2dpBottom)
  1105. ## This special root, pixel2d, uses units in pixels that are relative
  1106. ## to the window. The upperleft corner of the window is (0, 0),
  1107. ## the lowerleft corner is (xsize, -ysize), in this coordinate system.
  1108. self.pixel2dp = self.render2dp.attachNewNode(PGTop("pixel2dp"))
  1109. self.pixel2dp.node().setStartSort(16384)
  1110. self.pixel2dp.setPos(-1, 0, 1)
  1111. xsize, ysize = self.getSize()
  1112. if xsize > 0 and ysize > 0:
  1113. self.pixel2dp.setScale(2.0 / xsize, 1.0, 2.0 / ysize)
  1114. def setAspectRatio(self, aspectRatio):
  1115. """ Sets the global aspect ratio of the main window. Set it
  1116. to None to restore automatic scaling. """
  1117. self.__configAspectRatio = aspectRatio
  1118. self.adjustWindowAspectRatio(self.getAspectRatio())
  1119. def getAspectRatio(self, win = None):
  1120. # Returns the actual aspect ratio of the indicated (or main
  1121. # window), or the default aspect ratio if there is not yet a
  1122. # main window.
  1123. # If the config it set, we return that
  1124. if self.__configAspectRatio:
  1125. return self.__configAspectRatio
  1126. aspectRatio = 1
  1127. if win is None:
  1128. win = self.win
  1129. if win is not None and win.hasSize() and win.getSbsLeftYSize() != 0:
  1130. aspectRatio = float(win.getSbsLeftXSize()) / float(win.getSbsLeftYSize())
  1131. else:
  1132. if win is None or not hasattr(win, "getRequestedProperties"):
  1133. props = WindowProperties.getDefault()
  1134. else:
  1135. props = win.getRequestedProperties()
  1136. if not props.hasSize():
  1137. props = WindowProperties.getDefault()
  1138. if props.hasSize() and props.getYSize() != 0:
  1139. aspectRatio = float(props.getXSize()) / float(props.getYSize())
  1140. if aspectRatio == 0:
  1141. return 1
  1142. return aspectRatio
  1143. def getSize(self, win = None):
  1144. """
  1145. Returns the actual size of the indicated (or main window), or the
  1146. default size if there is not yet a main window.
  1147. """
  1148. if win is None:
  1149. win = self.win
  1150. if win is not None and win.hasSize():
  1151. return win.getXSize(), win.getYSize()
  1152. else:
  1153. if win is None or not hasattr(win, "getRequestedProperties"):
  1154. props = WindowProperties.getDefault()
  1155. else:
  1156. props = win.getRequestedProperties()
  1157. if not props.hasSize():
  1158. props = WindowProperties.getDefault()
  1159. return props.getXSize(), props.getYSize()
  1160. def makeCamera(self, win, sort = 0, scene = None,
  1161. displayRegion = (0, 1, 0, 1), stereo = None,
  1162. aspectRatio = None, clearDepth = 0, clearColor = None,
  1163. lens = None, camName = 'cam', mask = None,
  1164. useCamera = None):
  1165. """
  1166. Makes a new 3-d camera associated with the indicated window,
  1167. and creates a display region in the indicated subrectangle.
  1168. If stereo is True, then a stereo camera is created, with a
  1169. pair of DisplayRegions. If stereo is False, then a standard
  1170. camera is created. If stereo is None or omitted, a stereo
  1171. camera is created if the window says it can render in stereo.
  1172. If useCamera is not None, it is a NodePath to be used as the
  1173. camera to apply to the window, rather than creating a new
  1174. camera.
  1175. :rtype: panda3d.core.NodePath
  1176. """
  1177. # self.camera is the parent node of all cameras: a node that
  1178. # we can move around to move all cameras as a group.
  1179. if self.camera is None:
  1180. # We make it a ModelNode with the PTLocal flag, so that
  1181. # a wayward flatten operations won't attempt to mangle the
  1182. # camera.
  1183. self.camera = self.render.attachNewNode(ModelNode('camera'))
  1184. self.camera.node().setPreserveTransform(ModelNode.PTLocal)
  1185. builtins.camera = self.camera
  1186. self.mouse2cam.node().setNode(self.camera.node())
  1187. if useCamera:
  1188. # Use the existing camera node.
  1189. cam = useCamera
  1190. camNode = useCamera.node()
  1191. assert isinstance(camNode, Camera)
  1192. lens = camNode.getLens()
  1193. cam.reparentTo(self.camera)
  1194. else:
  1195. # Make a new Camera node.
  1196. camNode = Camera(camName)
  1197. if lens is None:
  1198. lens = PerspectiveLens()
  1199. if aspectRatio is None:
  1200. aspectRatio = self.getAspectRatio(win)
  1201. lens.setAspectRatio(aspectRatio)
  1202. cam = self.camera.attachNewNode(camNode)
  1203. if lens is not None:
  1204. camNode.setLens(lens)
  1205. if scene is not None:
  1206. camNode.setScene(scene)
  1207. if mask is not None:
  1208. if isinstance(mask, int):
  1209. mask = BitMask32(mask)
  1210. camNode.setCameraMask(mask)
  1211. if self.cam is None:
  1212. self.cam = cam
  1213. self.camNode = camNode
  1214. self.camLens = lens
  1215. self.camList.append(cam)
  1216. # Now, make a DisplayRegion for the camera.
  1217. if stereo is not None:
  1218. if stereo:
  1219. dr = win.makeStereoDisplayRegion(*displayRegion)
  1220. else:
  1221. dr = win.makeMonoDisplayRegion(*displayRegion)
  1222. else:
  1223. dr = win.makeDisplayRegion(*displayRegion)
  1224. dr.setSort(sort)
  1225. # By default, we do not clear 3-d display regions (the entire
  1226. # window will be cleared, which is normally sufficient). But
  1227. # we will if clearDepth is specified.
  1228. if clearDepth:
  1229. dr.setClearDepthActive(1)
  1230. if clearColor:
  1231. dr.setClearColorActive(1)
  1232. dr.setClearColor(clearColor)
  1233. dr.setCamera(cam)
  1234. return cam
  1235. def makeCamera2d(self, win, sort = 10,
  1236. displayRegion = (0, 1, 0, 1), coords = (-1, 1, -1, 1),
  1237. lens = None, cameraName = None):
  1238. """
  1239. Makes a new camera2d associated with the indicated window, and
  1240. assigns it to render the indicated subrectangle of render2d.
  1241. :rtype: panda3d.core.NodePath
  1242. """
  1243. dr = win.makeMonoDisplayRegion(*displayRegion)
  1244. dr.setSort(sort)
  1245. # Enable clearing of the depth buffer on this new display
  1246. # region (see the comment in setupRender2d, above).
  1247. dr.setClearDepthActive(1)
  1248. # Make any texture reloads on the gui come up immediately.
  1249. dr.setIncompleteRender(False)
  1250. left, right, bottom, top = coords
  1251. # Now make a new Camera node.
  1252. if cameraName:
  1253. cam2dNode = Camera('cam2d_' + cameraName)
  1254. else:
  1255. cam2dNode = Camera('cam2d')
  1256. if lens is None:
  1257. lens = OrthographicLens()
  1258. lens.setFilmSize(right - left, top - bottom)
  1259. lens.setFilmOffset((right + left) * 0.5, (top + bottom) * 0.5)
  1260. lens.setNearFar(-1000, 1000)
  1261. cam2dNode.setLens(lens)
  1262. # self.camera2d is the analog of self.camera, although it's
  1263. # not as clear how useful it is.
  1264. if self.camera2d is None:
  1265. self.camera2d = self.render2d.attachNewNode('camera2d')
  1266. camera2d = self.camera2d.attachNewNode(cam2dNode)
  1267. dr.setCamera(camera2d)
  1268. if self.cam2d is None:
  1269. self.cam2d = camera2d
  1270. return camera2d
  1271. def makeCamera2dp(self, win, sort = 20,
  1272. displayRegion = (0, 1, 0, 1), coords = (-1, 1, -1, 1),
  1273. lens = None, cameraName = None):
  1274. """
  1275. Makes a new camera2dp associated with the indicated window, and
  1276. assigns it to render the indicated subrectangle of render2dp.
  1277. :rtype: panda3d.core.NodePath
  1278. """
  1279. dr = win.makeMonoDisplayRegion(*displayRegion)
  1280. dr.setSort(sort)
  1281. # Unlike render2d, we don't clear the depth buffer for
  1282. # render2dp. Caveat emptor.
  1283. if hasattr(dr, 'setIncompleteRender'):
  1284. dr.setIncompleteRender(False)
  1285. left, right, bottom, top = coords
  1286. # Now make a new Camera node.
  1287. if cameraName:
  1288. cam2dNode = Camera('cam2dp_' + cameraName)
  1289. else:
  1290. cam2dNode = Camera('cam2dp')
  1291. if lens is None:
  1292. lens = OrthographicLens()
  1293. lens.setFilmSize(right - left, top - bottom)
  1294. lens.setFilmOffset((right + left) * 0.5, (top + bottom) * 0.5)
  1295. lens.setNearFar(-1000, 1000)
  1296. cam2dNode.setLens(lens)
  1297. # self.camera2d is the analog of self.camera, although it's
  1298. # not as clear how useful it is.
  1299. if self.camera2dp is None:
  1300. self.camera2dp = self.render2dp.attachNewNode('camera2dp')
  1301. camera2dp = self.camera2dp.attachNewNode(cam2dNode)
  1302. dr.setCamera(camera2dp)
  1303. if self.cam2dp is None:
  1304. self.cam2dp = camera2dp
  1305. return camera2dp
  1306. def setupDataGraph(self):
  1307. """
  1308. Creates the data graph and populates it with the basic input
  1309. devices.
  1310. """
  1311. self.dataRoot = NodePath('dataRoot')
  1312. # Cache the node so we do not ask for it every frame
  1313. self.dataRootNode = self.dataRoot.node()
  1314. # Now we have the main trackball & drive interfaces.
  1315. # useTrackball() and useDrive() switch these in and out; only
  1316. # one is in use at a given time.
  1317. self.trackball = NodePath(Trackball('trackball'))
  1318. self.drive = NodePath(DriveInterface('drive'))
  1319. self.mouse2cam = NodePath(Transform2SG('mouse2cam'))
  1320. # [gjeon] now you can create multiple mouse watchers to support multiple windows
  1321. def setupMouse(self, win, fMultiWin=False):
  1322. """
  1323. Creates the structures necessary to monitor the mouse input,
  1324. using the indicated window. If the mouse has already been set
  1325. up for a different window, those structures are deleted first.
  1326. :param fMultiWin: If True, then the previous mouse structures are not
  1327. deleted; instead, multiple windows are allowed to
  1328. monitor the mouse input. However, in this case, the
  1329. trackball controls are not set up, and must be set up
  1330. by hand if desired.
  1331. :returns: The ButtonThrower NodePath created for this window.
  1332. """
  1333. if not fMultiWin and self.buttonThrowers is not None:
  1334. for bt in self.buttonThrowers:
  1335. mw = bt.getParent()
  1336. mk = mw.getParent()
  1337. bt.removeNode()
  1338. mw.removeNode()
  1339. mk.removeNode()
  1340. bts, pws = self.setupMouseCB(win)
  1341. if fMultiWin:
  1342. return bts[0]
  1343. self.buttonThrowers = bts[:]
  1344. self.pointerWatcherNodes = pws[:]
  1345. self.mouseWatcher = self.buttonThrowers[0].getParent()
  1346. self.mouseWatcherNode = self.mouseWatcher.node()
  1347. if self.mouseInterface:
  1348. self.mouseInterface.reparentTo(self.mouseWatcher)
  1349. if self.recorder:
  1350. # If we have a recorder, the mouseWatcher belongs under a
  1351. # special MouseRecorder node, which may intercept the
  1352. # mouse activity.
  1353. mw = self.buttonThrowers[0].getParent()
  1354. mouseRecorder = MouseRecorder('mouse')
  1355. self.recorder.addRecorder('mouse', mouseRecorder)
  1356. np = mw.getParent().attachNewNode(mouseRecorder)
  1357. mw.reparentTo(np)
  1358. mw = self.buttonThrowers[0].getParent()
  1359. ## A special ButtonThrower to generate keyboard events and
  1360. ## include the time from the OS. This is separate only to
  1361. ## support legacy code that did not expect a time parameter; it
  1362. ## will eventually be folded into the normal ButtonThrower,
  1363. ## above.
  1364. self.timeButtonThrower = mw.attachNewNode(ButtonThrower('timeButtons'))
  1365. self.timeButtonThrower.node().setPrefix('time-')
  1366. self.timeButtonThrower.node().setTimeFlag(1)
  1367. # Tell the gui system about our new mouse watcher.
  1368. self.aspect2d.node().setMouseWatcher(mw.node())
  1369. self.pixel2d.node().setMouseWatcher(mw.node())
  1370. if self.wantRender2dp:
  1371. self.aspect2dp.node().setMouseWatcher(mw.node())
  1372. self.pixel2dp.node().setMouseWatcher(mw.node())
  1373. mw.node().addRegion(PGMouseWatcherBackground())
  1374. return self.buttonThrowers[0]
  1375. # [gjeon] this function is seperated from setupMouse to allow multiple mouse watchers
  1376. def setupMouseCB(self, win):
  1377. # For each mouse/keyboard device, we create
  1378. # - MouseAndKeyboard
  1379. # - MouseWatcher
  1380. # - ButtonThrower
  1381. # The ButtonThrowers are stored in a list, self.buttonThrowers.
  1382. # Given a ButtonThrower, one can access the MouseWatcher and
  1383. # MouseAndKeyboard using getParent.
  1384. #
  1385. # The MouseAndKeyboard generates mouse events and mouse
  1386. # button/keyboard events; the MouseWatcher passes them through
  1387. # unchanged when the mouse is not over a 2-d button, and passes
  1388. # nothing through when the mouse *is* over a 2-d button. Therefore,
  1389. # objects that don't want to get events when the mouse is over a
  1390. # button, like the driveInterface, should be parented to
  1391. # MouseWatcher, while objects that want events in all cases, like the
  1392. # chat interface, should be parented to the MouseAndKeyboard.
  1393. buttonThrowers = []
  1394. pointerWatcherNodes = []
  1395. for i in range(win.getNumInputDevices()):
  1396. name = win.getInputDeviceName(i)
  1397. mk = self.dataRoot.attachNewNode(MouseAndKeyboard(win, i, name))
  1398. mw = mk.attachNewNode(MouseWatcher("watcher%s" % (i)))
  1399. if win.getSideBySideStereo():
  1400. # If the window has side-by-side stereo enabled, then
  1401. # we should constrain the MouseWatcher to the window's
  1402. # DisplayRegion. This will enable the MouseWatcher to
  1403. # track the left and right halves of the screen
  1404. # individually.
  1405. mw.node().setDisplayRegion(win.getOverlayDisplayRegion())
  1406. mb = mw.node().getModifierButtons()
  1407. mb.addButton(KeyboardButton.shift())
  1408. mb.addButton(KeyboardButton.control())
  1409. mb.addButton(KeyboardButton.alt())
  1410. mb.addButton(KeyboardButton.meta())
  1411. mw.node().setModifierButtons(mb)
  1412. bt = mw.attachNewNode(ButtonThrower("buttons%s" % (i)))
  1413. if i != 0:
  1414. bt.node().setPrefix('mousedev%s-' % (i))
  1415. mods = ModifierButtons()
  1416. mods.addButton(KeyboardButton.shift())
  1417. mods.addButton(KeyboardButton.control())
  1418. mods.addButton(KeyboardButton.alt())
  1419. mods.addButton(KeyboardButton.meta())
  1420. bt.node().setModifierButtons(mods)
  1421. buttonThrowers.append(bt)
  1422. if win.hasPointer(i):
  1423. pointerWatcherNodes.append(mw.node())
  1424. return buttonThrowers, pointerWatcherNodes
  1425. def enableSoftwareMousePointer(self):
  1426. """
  1427. Creates some geometry and parents it to render2d to show
  1428. the currently-known mouse position. Useful if the mouse
  1429. pointer is invisible for some reason.
  1430. """
  1431. mouseViz = self.render2d.attachNewNode('mouseViz')
  1432. lilsmiley = self.loader.loadModel('lilsmiley')
  1433. lilsmiley.reparentTo(mouseViz)
  1434. aspectRatio = self.getAspectRatio()
  1435. # Scale the smiley face to 32x32 pixels.
  1436. height = self.win.getSbsLeftYSize()
  1437. lilsmiley.setScale(
  1438. 32.0 / height / aspectRatio,
  1439. 1.0, 32.0 / height)
  1440. self.mouseWatcherNode.setGeometry(mouseViz.node())
  1441. def getAlt(self):
  1442. """
  1443. Returns True if the alt key is currently held down.
  1444. """
  1445. return self.mouseWatcherNode.getModifierButtons().isDown(
  1446. KeyboardButton.alt())
  1447. def getShift(self):
  1448. """
  1449. Returns True if the shift key is currently held down.
  1450. """
  1451. return self.mouseWatcherNode.getModifierButtons().isDown(
  1452. KeyboardButton.shift())
  1453. def getControl(self):
  1454. """
  1455. Returns True if the control key is currently held down.
  1456. """
  1457. return self.mouseWatcherNode.getModifierButtons().isDown(
  1458. KeyboardButton.control())
  1459. def getMeta(self):
  1460. """
  1461. Returns True if the meta key is currently held down.
  1462. """
  1463. return self.mouseWatcherNode.getModifierButtons().isDown(
  1464. KeyboardButton.meta())
  1465. def attachInputDevice(self, device, prefix=None, watch=False):
  1466. """
  1467. This function attaches an input device to the data graph, which will
  1468. cause the device to be polled and generate events. If a prefix is
  1469. given and not None, it is used to prefix events generated by this
  1470. device, separated by a hyphen.
  1471. The watch argument can be set to True (as of Panda3D 1.10.3) to set up
  1472. the default MouseWatcher to receive inputs from this device, allowing
  1473. it to be polled via mouseWatcherNode and control user interfaces.
  1474. Setting this to True will also make it generate unprefixed events,
  1475. regardless of the specified prefix.
  1476. If you call this, you should consider calling detachInputDevice when
  1477. you are done with the device or when it is disconnected.
  1478. """
  1479. # Protect against the same device being attached multiple times.
  1480. assert device not in self.__inputDeviceNodes
  1481. idn = self.dataRoot.attachNewNode(InputDeviceNode(device, device.name))
  1482. # Setup the button thrower to generate events for the device.
  1483. if prefix is not None or not watch:
  1484. bt = idn.attachNewNode(ButtonThrower(device.name))
  1485. if prefix is not None:
  1486. bt.node().setPrefix(prefix + '-')
  1487. self.deviceButtonThrowers.append(bt)
  1488. assert self.notify.debug("Attached input device {0} with prefix {1}".format(device, prefix))
  1489. self.__inputDeviceNodes[device] = idn
  1490. if watch:
  1491. idn.node().addChild(self.mouseWatcherNode)
  1492. def detachInputDevice(self, device):
  1493. """
  1494. This should be called after attaching an input device using
  1495. attachInputDevice and the device is disconnected or you no longer wish
  1496. to keep polling this device for events.
  1497. You do not strictly need to call this if you expect the device to be
  1498. reconnected (but be careful that you don't reattach it).
  1499. """
  1500. if device not in self.__inputDeviceNodes:
  1501. assert device in self.__inputDeviceNodes
  1502. return
  1503. assert self.notify.debug("Detached device {0}".format(device.name))
  1504. # Remove the ButtonThrower from the deviceButtonThrowers list.
  1505. idn = self.__inputDeviceNodes[device]
  1506. for bt in self.deviceButtonThrowers:
  1507. if idn.isAncestorOf(bt):
  1508. self.deviceButtonThrowers.remove(bt)
  1509. break
  1510. idn.removeNode()
  1511. del self.__inputDeviceNodes[device]
  1512. def addAngularIntegrator(self):
  1513. """
  1514. Adds a :class:`~panda3d.physics.AngularEulerIntegrator` to the default
  1515. physics manager. By default, only a
  1516. :class:`~panda3d.physics.LinearEulerIntegrator` is attached.
  1517. """
  1518. if not self.physicsMgrAngular:
  1519. physics = importlib.import_module('panda3d.physics')
  1520. self.physicsMgrAngular = 1
  1521. integrator = physics.AngularEulerIntegrator()
  1522. self.physicsMgr.attachAngularIntegrator(integrator)
  1523. def enableParticles(self):
  1524. """
  1525. Enables the particle and physics managers, which are stored in
  1526. `particleMgr` and `physicsMgr` members, respectively. Also starts a
  1527. task to periodically update these managers.
  1528. By default, only a :class:`~panda3d.physics.LinearEulerIntegrator` is
  1529. attached to the physics manager. To attach an angular integrator,
  1530. follow this up with a call to `addAngularIntegrator()`.
  1531. """
  1532. if not self.particleMgrEnabled:
  1533. # Use importlib to prevent this import from being picked up
  1534. # by modulefinder when packaging an application.
  1535. if not self.particleMgr:
  1536. PMG = importlib.import_module('direct.particles.ParticleManagerGlobal')
  1537. self.particleMgr = PMG.particleMgr
  1538. self.particleMgr.setFrameStepping(1)
  1539. if not self.physicsMgr:
  1540. PMG = importlib.import_module('direct.showbase.PhysicsManagerGlobal')
  1541. physics = importlib.import_module('panda3d.physics')
  1542. self.physicsMgr = PMG.physicsMgr
  1543. integrator = physics.LinearEulerIntegrator()
  1544. self.physicsMgr.attachLinearIntegrator(integrator)
  1545. self.particleMgrEnabled = 1
  1546. self.physicsMgrEnabled = 1
  1547. self.taskMgr.remove('manager-update')
  1548. self.taskMgr.add(self.updateManagers, 'manager-update')
  1549. def disableParticles(self):
  1550. """
  1551. The opposite of `enableParticles()`.
  1552. """
  1553. if self.particleMgrEnabled:
  1554. self.particleMgrEnabled = 0
  1555. self.physicsMgrEnabled = 0
  1556. self.taskMgr.remove('manager-update')
  1557. def toggleParticles(self):
  1558. """
  1559. Calls `enableParticles()` or `disableParticles()` depending on the
  1560. current state.
  1561. """
  1562. if self.particleMgrEnabled == 0:
  1563. self.enableParticles()
  1564. else:
  1565. self.disableParticles()
  1566. def isParticleMgrEnabled(self):
  1567. """
  1568. Returns True if `enableParticles()` has been called.
  1569. """
  1570. return self.particleMgrEnabled
  1571. def isPhysicsMgrEnabled(self):
  1572. """
  1573. Returns True if `enableParticles()` has been called.
  1574. """
  1575. return self.physicsMgrEnabled
  1576. def updateManagers(self, state):
  1577. dt = globalClock.getDt()
  1578. if self.particleMgrEnabled:
  1579. self.particleMgr.doParticles(dt)
  1580. if self.physicsMgrEnabled:
  1581. self.physicsMgr.doPhysics(dt)
  1582. return Task.cont
  1583. def createStats(self, hostname=None, port=None):
  1584. """
  1585. If want-pstats is set in Config.prc, or the `wantStats` member is
  1586. otherwise set to True, connects to the PStats server.
  1587. This is normally called automatically from the ShowBase constructor.
  1588. """
  1589. # You can specify pstats-host in your Config.prc or use ~pstats/~aipstats
  1590. # The default is localhost
  1591. if not self.wantStats:
  1592. return False
  1593. if PStatClient.isConnected():
  1594. PStatClient.disconnect()
  1595. # these default values match the C++ default values
  1596. if hostname is None:
  1597. hostname = ''
  1598. if port is None:
  1599. port = -1
  1600. PStatClient.connect(hostname, port)
  1601. return PStatClient.isConnected()
  1602. def addSfxManager(self, extraSfxManager):
  1603. """
  1604. Adds an additional SFX audio manager to `sfxManagerList`, the list of
  1605. managers managed by ShowBase.
  1606. """
  1607. # keep a list of sfx manager objects to apply settings to,
  1608. # since there may be others in addition to the one we create here
  1609. self.sfxManagerList.append(extraSfxManager)
  1610. newSfxManagerIsValid = extraSfxManager is not None and extraSfxManager.isValid()
  1611. self.sfxManagerIsValidList.append(newSfxManagerIsValid)
  1612. if newSfxManagerIsValid:
  1613. extraSfxManager.setActive(self.sfxActive)
  1614. def createBaseAudioManagers(self):
  1615. """
  1616. Creates the default SFX and music manager. Called automatically from
  1617. the ShowBase constructor.
  1618. """
  1619. self.sfxPlayer = SfxPlayer.SfxPlayer()
  1620. sfxManager = AudioManager.createAudioManager()
  1621. self.addSfxManager(sfxManager)
  1622. self.musicManager = AudioManager.createAudioManager()
  1623. self.musicManagerIsValid = self.musicManager is not None \
  1624. and self.musicManager.isValid()
  1625. if self.musicManagerIsValid:
  1626. # ensure only 1 midi song is playing at a time:
  1627. self.musicManager.setConcurrentSoundLimit(1)
  1628. self.musicManager.setActive(self.musicActive)
  1629. # enableMusic/enableSoundEffects are meant to be called in response
  1630. # to a user request so sfxActive/musicActive represent how things
  1631. # *should* be, regardless of App/OS/HW state
  1632. def enableMusic(self, bEnableMusic):
  1633. """
  1634. Enables or disables the music manager.
  1635. """
  1636. # don't setActive(1) if no audiofocus
  1637. if self.AppHasAudioFocus and self.musicManagerIsValid:
  1638. self.musicManager.setActive(bEnableMusic)
  1639. self.musicActive = bEnableMusic
  1640. if bEnableMusic:
  1641. # This is useful when we want to play different music
  1642. # from what the manager has queued
  1643. messenger.send("MusicEnabled")
  1644. self.notify.debug("Enabling music")
  1645. else:
  1646. self.notify.debug("Disabling music")
  1647. def SetAllSfxEnables(self, bEnabled):
  1648. """Calls ``setActive(bEnabled)`` on all valid SFX managers."""
  1649. for i in range(len(self.sfxManagerList)):
  1650. if self.sfxManagerIsValidList[i]:
  1651. self.sfxManagerList[i].setActive(bEnabled)
  1652. def enableSoundEffects(self, bEnableSoundEffects):
  1653. """
  1654. Enables or disables SFX managers.
  1655. """
  1656. # don't setActive(1) if no audiofocus
  1657. if self.AppHasAudioFocus or not bEnableSoundEffects:
  1658. self.SetAllSfxEnables(bEnableSoundEffects)
  1659. self.sfxActive = bEnableSoundEffects
  1660. if bEnableSoundEffects:
  1661. self.notify.debug("Enabling sound effects")
  1662. else:
  1663. self.notify.debug("Disabling sound effects")
  1664. # enable/disableAllAudio allow a programmable global override-off
  1665. # for current audio settings. they're meant to be called when app
  1666. # loses audio focus (switched out), so we can turn off sound without
  1667. # affecting internal sfxActive/musicActive sound settings, so things
  1668. # come back ok when the app is switched back to
  1669. def disableAllAudio(self):
  1670. """
  1671. Disables all SFX and music managers, meant to be called when the app
  1672. loses audio focus.
  1673. """
  1674. self.AppHasAudioFocus = 0
  1675. self.SetAllSfxEnables(0)
  1676. if self.musicManagerIsValid:
  1677. self.musicManager.setActive(0)
  1678. self.notify.debug("Disabling audio")
  1679. def enableAllAudio(self):
  1680. """
  1681. Reenables the SFX and music managers that were active at the time
  1682. `disableAllAudio()` was called. Meant to be called when the app regains
  1683. audio focus.
  1684. """
  1685. self.AppHasAudioFocus = 1
  1686. self.SetAllSfxEnables(self.sfxActive)
  1687. if self.musicManagerIsValid:
  1688. self.musicManager.setActive(self.musicActive)
  1689. self.notify.debug("Enabling audio")
  1690. # This function should only be in the loader but is here for
  1691. # backwards compatibility. Please do not add code here, add
  1692. # it to the loader.
  1693. def loadSfx(self, name):
  1694. """
  1695. :deprecated: Use `.Loader.Loader.loadSfx()` instead.
  1696. """
  1697. if __debug__:
  1698. warnings.warn("base.loadSfx is deprecated, use base.loader.loadSfx instead.", DeprecationWarning, stacklevel=2)
  1699. return self.loader.loadSfx(name)
  1700. # This function should only be in the loader but is here for
  1701. # backwards compatibility. Please do not add code here, add
  1702. # it to the loader.
  1703. def loadMusic(self, name):
  1704. """
  1705. :deprecated: Use `.Loader.Loader.loadMusic()` instead.
  1706. """
  1707. if __debug__:
  1708. warnings.warn("base.loadMusic is deprecated, use base.loader.loadMusic instead.", DeprecationWarning, stacklevel=2)
  1709. return self.loader.loadMusic(name)
  1710. def playSfx(
  1711. self, sfx, looping = 0, interrupt = 1, volume = None,
  1712. time = 0.0, node = None, listener = None, cutoff = None):
  1713. # This goes through a special player for potential localization
  1714. return self.sfxPlayer.playSfx(sfx, looping, interrupt, volume, time, node, listener, cutoff)
  1715. def playMusic(self, music, looping = 0, interrupt = 1, volume = None, time = 0.0):
  1716. if music:
  1717. if volume is not None:
  1718. music.setVolume(volume)
  1719. # if interrupt was set to 0, start over even if it's
  1720. # already playing
  1721. if interrupt or (music.status() != AudioSound.PLAYING):
  1722. music.setTime(time)
  1723. music.setLoop(looping)
  1724. music.play()
  1725. def __resetPrevTransform(self, state):
  1726. # Clear out the previous velocity deltas now, after we have
  1727. # rendered (the previous frame). We do this after the render,
  1728. # so that we have a chance to draw a representation of spheres
  1729. # along with their velocities. At the beginning of the frame
  1730. # really means after the command prompt, which allows the user
  1731. # to interactively query these deltas meaningfully.
  1732. PandaNode.resetAllPrevTransform()
  1733. return Task.cont
  1734. def __dataLoop(self, state):
  1735. # Check if there were newly connected devices.
  1736. self.devices.update()
  1737. # traverse the data graph. This reads all the control
  1738. # inputs (from the mouse and keyboard, for instance) and also
  1739. # directly acts upon them (for instance, to move the avatar).
  1740. self.dgTrav.traverse(self.dataRootNode)
  1741. return Task.cont
  1742. def __ivalLoop(self, state):
  1743. # Execute all intervals in the global ivalMgr.
  1744. IntervalManager.ivalMgr.step()
  1745. return Task.cont
  1746. def initShadowTrav(self):
  1747. if not self.shadowTrav:
  1748. # set up the shadow collision traverser
  1749. self.shadowTrav = CollisionTraverser("base.shadowTrav")
  1750. self.shadowTrav.setRespectPrevTransform(False)
  1751. def __shadowCollisionLoop(self, state):
  1752. # run the collision traversal if we have a
  1753. # CollisionTraverser set.
  1754. if self.shadowTrav:
  1755. self.shadowTrav.traverse(self.render)
  1756. return Task.cont
  1757. def __collisionLoop(self, state):
  1758. # run the collision traversal if we have a
  1759. # CollisionTraverser set.
  1760. if self.cTrav:
  1761. self.cTrav.traverse(self.render)
  1762. if self.appTrav:
  1763. self.appTrav.traverse(self.render)
  1764. if self.shadowTrav:
  1765. self.shadowTrav.traverse(self.render)
  1766. messenger.send("collisionLoopFinished")
  1767. return Task.cont
  1768. def __audioLoop(self, state):
  1769. if self.musicManager is not None:
  1770. self.musicManager.update()
  1771. for x in self.sfxManagerList:
  1772. x.update()
  1773. return Task.cont
  1774. def __garbageCollectStates(self, state):
  1775. """ This task is started only when we have
  1776. garbage-collect-states set in the Config.prc file, in which
  1777. case we're responsible for taking out Panda's garbage from
  1778. time to time. This is not to be confused with Python's
  1779. garbage collection. """
  1780. TransformState.garbageCollect()
  1781. RenderState.garbageCollect()
  1782. return Task.cont
  1783. def __igLoop(self, state):
  1784. if __debug__:
  1785. # We render the watch variables for the onScreenDebug as soon
  1786. # as we reasonably can before the renderFrame().
  1787. self.onScreenDebug.render()
  1788. if self.recorder:
  1789. self.recorder.recordFrame()
  1790. # Finally, render the frame.
  1791. self.graphicsEngine.renderFrame()
  1792. if self.clusterSyncFlag:
  1793. self.graphicsEngine.syncFrame()
  1794. if self.multiClientSleep:
  1795. time.sleep(0)
  1796. if __debug__:
  1797. # We clear the text buffer for the onScreenDebug as soon
  1798. # as we reasonably can after the renderFrame().
  1799. self.onScreenDebug.clear()
  1800. if self.recorder:
  1801. self.recorder.playFrame()
  1802. if self.mainWinMinimized:
  1803. # If the main window is minimized, slow down the app a bit
  1804. # by sleeping here in igLoop so we don't use all available
  1805. # CPU needlessly.
  1806. # Note: this isn't quite right if multiple windows are
  1807. # open. We should base this on whether *all* windows are
  1808. # minimized, not just the main window. But it will do for
  1809. # now until someone complains.
  1810. time.sleep(0.1)
  1811. # Lerp stuff needs this event, and it must be generated in
  1812. # C++, not in Python.
  1813. throw_new_frame()
  1814. return Task.cont
  1815. def __igLoopSync(self, state):
  1816. if __debug__:
  1817. # We render the watch variables for the onScreenDebug as soon
  1818. # as we reasonably can before the renderFrame().
  1819. self.onScreenDebug.render()
  1820. if self.recorder:
  1821. self.recorder.recordFrame()
  1822. self.cluster.collectData()
  1823. # Finally, render the frame.
  1824. self.graphicsEngine.renderFrame()
  1825. if self.clusterSyncFlag:
  1826. self.graphicsEngine.syncFrame()
  1827. if self.multiClientSleep:
  1828. time.sleep(0)
  1829. if __debug__:
  1830. # We clear the text buffer for the onScreenDebug as soon
  1831. # as we reasonably can after the renderFrame().
  1832. self.onScreenDebug.clear()
  1833. if self.recorder:
  1834. self.recorder.playFrame()
  1835. if self.mainWinMinimized:
  1836. # If the main window is minimized, slow down the app a bit
  1837. # by sleeping here in igLoop so we don't use all available
  1838. # CPU needlessly.
  1839. # Note: this isn't quite right if multiple windows are
  1840. # open. We should base this on whether *all* windows are
  1841. # minimized, not just the main window. But it will do for
  1842. # now until someone complains.
  1843. time.sleep(0.1)
  1844. self.graphicsEngine.readyFlip()
  1845. self.cluster.waitForFlipCommand()
  1846. self.graphicsEngine.flipFrame()
  1847. # Lerp stuff needs this event, and it must be generated in
  1848. # C++, not in Python.
  1849. throw_new_frame()
  1850. return Task.cont
  1851. def restart(self, clusterSync=False, cluster=None):
  1852. self.shutdown()
  1853. # __resetPrevTransform goes at the very beginning of the frame.
  1854. self.taskMgr.add(
  1855. self.__resetPrevTransform, 'resetPrevTransform', sort = -51)
  1856. # give the dataLoop task a reasonably "early" sort,
  1857. # so that it will get run before most tasks
  1858. self.taskMgr.add(self.__dataLoop, 'dataLoop', sort = -50)
  1859. self.__deadInputs = 0
  1860. # spawn the ivalLoop with a later sort, so that it will
  1861. # run after most tasks, but before igLoop.
  1862. self.taskMgr.add(self.__ivalLoop, 'ivalLoop', sort = 20)
  1863. # make the collisionLoop task run before igLoop,
  1864. # but leave enough room for the app to insert tasks
  1865. # between collisionLoop and igLoop
  1866. self.taskMgr.add(self.__collisionLoop, 'collisionLoop', sort = 30)
  1867. if ConfigVariableBool('garbage-collect-states').getValue():
  1868. self.taskMgr.add(self.__garbageCollectStates, 'garbageCollectStates', sort = 46)
  1869. # give the igLoop task a reasonably "late" sort,
  1870. # so that it will get run after most tasks
  1871. self.cluster = cluster
  1872. if not clusterSync or cluster is None:
  1873. self.taskMgr.add(self.__igLoop, 'igLoop', sort = 50)
  1874. else:
  1875. self.taskMgr.add(self.__igLoopSync, 'igLoop', sort = 50)
  1876. # the audioLoop updates the positions of 3D sounds.
  1877. # as such, it needs to run after the cull traversal in the igLoop.
  1878. self.taskMgr.add(self.__audioLoop, 'audioLoop', sort = 60)
  1879. self.eventMgr.restart()
  1880. def shutdown(self):
  1881. self.taskMgr.remove('audioLoop')
  1882. self.taskMgr.remove('igLoop')
  1883. self.taskMgr.remove('shadowCollisionLoop')
  1884. self.taskMgr.remove('collisionLoop')
  1885. self.taskMgr.remove('dataLoop')
  1886. self.taskMgr.remove('resetPrevTransform')
  1887. self.taskMgr.remove('ivalLoop')
  1888. self.taskMgr.remove('garbageCollectStates')
  1889. self.eventMgr.shutdown()
  1890. def getBackgroundColor(self, win = None):
  1891. """
  1892. Returns the current window background color. This assumes
  1893. the window is set up to clear the color each frame (this is
  1894. the normal setting).
  1895. :rtype: panda3d.core.VBase4
  1896. """
  1897. if win is None:
  1898. win = self.win
  1899. return VBase4(win.getClearColor())
  1900. def setBackgroundColor(self, r = None, g = None, b = None, a = 0.0, win = None):
  1901. """
  1902. Sets the window background color to the indicated value.
  1903. This assumes the window is set up to clear the color each
  1904. frame (this is the normal setting).
  1905. The color may be either a VBase3 or a VBase4, or a 3-component
  1906. tuple, or the individual r, g, b parameters.
  1907. """
  1908. if g is not None:
  1909. color = VBase4(r, g, b, a)
  1910. else:
  1911. arg = r
  1912. if isinstance(arg, VBase4):
  1913. color = arg
  1914. else:
  1915. color = VBase4(arg[0], arg[1], arg[2], a)
  1916. if win is None:
  1917. win = self.win
  1918. if win:
  1919. win.setClearColor(color)
  1920. def toggleBackface(self):
  1921. """
  1922. Toggles between `backfaceCullingOn()` and `backfaceCullingOff()`.
  1923. """
  1924. if self.backfaceCullingEnabled:
  1925. self.backfaceCullingOff()
  1926. else:
  1927. self.backfaceCullingOn()
  1928. def backfaceCullingOn(self):
  1929. """
  1930. Disables two-sided rendering on the entire 3D scene graph.
  1931. """
  1932. if not self.backfaceCullingEnabled:
  1933. self.render.setTwoSided(0)
  1934. self.backfaceCullingEnabled = 1
  1935. def backfaceCullingOff(self):
  1936. """
  1937. Enables two-sided rendering on the entire 3D scene graph.
  1938. """
  1939. if self.backfaceCullingEnabled:
  1940. self.render.setTwoSided(1)
  1941. self.backfaceCullingEnabled = 0
  1942. def toggleTexture(self):
  1943. """
  1944. Toggles between `textureOn()` and `textureOff()`.
  1945. """
  1946. if self.textureEnabled:
  1947. self.textureOff()
  1948. else:
  1949. self.textureOn()
  1950. def textureOn(self):
  1951. """
  1952. Undoes the effects of a previous call to `textureOff()`.
  1953. """
  1954. self.render.clearTexture()
  1955. self.textureEnabled = 1
  1956. def textureOff(self):
  1957. """
  1958. Disables texturing on the entire 3D scene graph.
  1959. """
  1960. self.render.setTextureOff(100)
  1961. self.textureEnabled = 0
  1962. def toggleWireframe(self):
  1963. """
  1964. Toggles between `wireframeOn()` and `wireframeOff()`.
  1965. """
  1966. if self.wireframeEnabled:
  1967. self.wireframeOff()
  1968. else:
  1969. self.wireframeOn()
  1970. def wireframeOn(self):
  1971. """
  1972. Enables wireframe rendering on the entire 3D scene graph.
  1973. """
  1974. self.render.setRenderModeWireframe(100)
  1975. self.render.setTwoSided(1)
  1976. self.wireframeEnabled = 1
  1977. def wireframeOff(self):
  1978. """
  1979. Undoes the effects of a previous call to `wireframeOn()`.
  1980. """
  1981. self.render.clearRenderMode()
  1982. render.setTwoSided(not self.backfaceCullingEnabled)
  1983. self.wireframeEnabled = 0
  1984. def disableMouse(self):
  1985. """
  1986. Temporarily disable the mouse control of the camera, either
  1987. via the drive interface or the trackball, whichever is
  1988. currently in use.
  1989. """
  1990. # We don't reparent the drive interface or the trackball;
  1991. # whichever one was there before will remain in the data graph
  1992. # and active. This way they won't lose button events while
  1993. # the mouse is disabled. However, we do move the mouse2cam
  1994. # object out of there, so we won't be updating the camera any
  1995. # more.
  1996. if self.mouse2cam:
  1997. self.mouse2cam.detachNode()
  1998. def enableMouse(self):
  1999. """
  2000. Reverse the effect of a previous call to `disableMouse()`.
  2001. `useDrive()` also implicitly enables the mouse.
  2002. """
  2003. if self.mouse2cam:
  2004. self.mouse2cam.reparentTo(self.mouseInterface)
  2005. def silenceInput(self):
  2006. """
  2007. This is a heavy-handed way of temporarily turning off
  2008. all inputs. Bring them back with `reviveInput()`.
  2009. """
  2010. if not self.__deadInputs:
  2011. self.__deadInputs = taskMgr.remove('dataLoop')
  2012. def reviveInput(self):
  2013. """
  2014. Restores inputs after a previous call to `silenceInput()`.
  2015. """
  2016. if self.__deadInputs:
  2017. self.eventMgr.doEvents()
  2018. self.dgTrav.traverse(self.dataRootNode)
  2019. self.eventMgr.eventQueue.clear()
  2020. self.taskMgr.add(self.__dataLoop, 'dataLoop', sort = -50)
  2021. self.__deadInputs = 0
  2022. def setMouseOnNode(self, newNode):
  2023. if self.mouse2cam:
  2024. self.mouse2cam.node().setNode(newNode)
  2025. def changeMouseInterface(self, changeTo):
  2026. """
  2027. Change the mouse interface used to control the camera.
  2028. """
  2029. # Get rid of the prior interface:
  2030. self.mouseInterface.detachNode()
  2031. # Update the mouseInterface to point to the drive
  2032. self.mouseInterface = changeTo
  2033. self.mouseInterfaceNode = self.mouseInterface.node()
  2034. # Hookup the drive to the camera.
  2035. if self.mouseWatcher:
  2036. self.mouseInterface.reparentTo(self.mouseWatcher)
  2037. if self.mouse2cam:
  2038. self.mouse2cam.reparentTo(self.mouseInterface)
  2039. def useDrive(self):
  2040. """
  2041. Changes the mouse interface used for camera control to drive mode.
  2042. """
  2043. if self.drive:
  2044. self.changeMouseInterface(self.drive)
  2045. # Set the height to a good eyeheight
  2046. self.mouseInterfaceNode.reset()
  2047. self.mouseInterfaceNode.setZ(4.0)
  2048. def useTrackball(self):
  2049. """
  2050. Changes the mouse interface used for camera control to trackball mode.
  2051. """
  2052. if self.trackball:
  2053. self.changeMouseInterface(self.trackball)
  2054. def toggleTexMem(self):
  2055. """
  2056. Toggles a handy texture memory watcher utility.
  2057. See :mod:`direct.showutil.TexMemWatcher` for more information.
  2058. """
  2059. if self.texmem and not self.texmem.cleanedUp:
  2060. self.texmem.cleanup()
  2061. self.texmem = None
  2062. return
  2063. # Use importlib to prevent this import from being picked up
  2064. # by modulefinder when packaging an application.
  2065. TMW = importlib.import_module('direct.showutil.TexMemWatcher')
  2066. self.texmem = TMW.TexMemWatcher()
  2067. def toggleShowVertices(self):
  2068. """ Toggles a mode that visualizes vertex density per screen
  2069. area. """
  2070. if self.showVertices:
  2071. # Clean up the old mode.
  2072. self.showVertices.node().setActive(0)
  2073. dr = self.showVertices.node().getDisplayRegion(0)
  2074. self.win.removeDisplayRegion(dr)
  2075. self.showVertices.removeNode()
  2076. self.showVertices = None
  2077. return
  2078. dr = self.win.makeDisplayRegion()
  2079. dr.setSort(1000)
  2080. cam = Camera('showVertices')
  2081. cam.setLens(self.camLens)
  2082. # Set up a funny state to render only vertices.
  2083. override = 100000
  2084. t = NodePath('t')
  2085. t.setColor(1, 0, 1, 0.02, override)
  2086. t.setColorScale(1, 1, 1, 1, override)
  2087. t.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OIncomingAlpha, ColorBlendAttrib.OOneMinusIncomingAlpha), override)
  2088. t.setAttrib(RenderModeAttrib.make(RenderModeAttrib.MPoint, 10), override)
  2089. t.setTwoSided(True, override)
  2090. t.setBin('fixed', 0, override)
  2091. t.setDepthTest(False, override)
  2092. t.setDepthWrite(False, override)
  2093. t.setLightOff(override)
  2094. t.setShaderOff(override)
  2095. t.setFogOff(override)
  2096. t.setAttrib(AntialiasAttrib.make(AntialiasAttrib.MNone), override)
  2097. t.setAttrib(RescaleNormalAttrib.make(RescaleNormalAttrib.MNone), override)
  2098. t.setTextureOff(override)
  2099. # Make the spots round, so there's less static in the display.
  2100. # This forces software point generation on many drivers, so
  2101. # it's not on by default.
  2102. if self.config.GetBool('round-show-vertices', False):
  2103. spot = PNMImage(256, 256, 1)
  2104. spot.renderSpot((1, 1, 1, 1), (0, 0, 0, 0), 0.8, 1)
  2105. tex = Texture('spot')
  2106. tex.load(spot)
  2107. tex.setFormat(tex.FAlpha)
  2108. t.setTexture(tex, override)
  2109. t.setAttrib(TexGenAttrib.make(TextureStage.getDefault(), TexGenAttrib.MPointSprite), override)
  2110. cam.setInitialState(t.getState())
  2111. cam.setCameraMask(~PandaNode.getOverallBit())
  2112. self.showVertices = self.cam.attachNewNode(cam)
  2113. dr.setCamera(self.showVertices)
  2114. def oobe(self, cam = None):
  2115. """
  2116. Enable a special "out-of-body experience" mouse-interface
  2117. mode. This can be used when a "god" camera is needed; it
  2118. moves the camera node out from under its normal node and sets
  2119. the world up in trackball state. Button events are still sent
  2120. to the normal mouse action node (e.g. the DriveInterface), and
  2121. mouse events, if needed, may be sent to the normal node by
  2122. holding down the Control key.
  2123. This is different than `useTrackball()`, which simply changes
  2124. the existing mouse action to a trackball interface. In fact,
  2125. OOBE mode doesn't care whether `useDrive()` or `useTrackball()` is
  2126. in effect; it just temporarily layers a new trackball
  2127. interface on top of whatever the basic interface is. You can
  2128. even switch between `useDrive()` and `useTrackball()` while OOBE
  2129. mode is in effect.
  2130. This is a toggle; the second time this function is called, it
  2131. disables the mode.
  2132. """
  2133. if cam is None:
  2134. cam = self.cam
  2135. # If oobeMode was never set, set it to false and create the
  2136. # structures we need to implement OOBE.
  2137. if not hasattr(self, 'oobeMode'):
  2138. self.oobeMode = 0
  2139. self.oobeCamera = self.hidden.attachNewNode('oobeCamera')
  2140. self.oobeCameraTrackball = self.oobeCamera.attachNewNode('oobeCameraTrackball')
  2141. self.oobeLens = PerspectiveLens()
  2142. self.oobeLens.setAspectRatio(self.getAspectRatio())
  2143. self.oobeLens.setNearFar(0.1, 10000.0)
  2144. self.oobeLens.setMinFov(40)
  2145. self.oobeTrackball = NodePath(Trackball('oobeTrackball'))
  2146. self.oobe2cam = self.oobeTrackball.attachNewNode(Transform2SG('oobe2cam'))
  2147. self.oobe2cam.node().setNode(self.oobeCameraTrackball.node())
  2148. self.oobeVis = base.loader.loadModel('models/misc/camera', okMissing = True)
  2149. if not self.oobeVis:
  2150. # Sometimes we have default-model-extension set to
  2151. # egg, but the file might be a bam file.
  2152. self.oobeVis = base.loader.loadModel('models/misc/camera.bam', okMissing = True)
  2153. if not self.oobeVis:
  2154. self.oobeVis = NodePath('oobeVis')
  2155. self.oobeVis.node().setFinal(1)
  2156. self.oobeVis.setLightOff(1)
  2157. self.oobeCullFrustum = None
  2158. self.accept('oobe-down', self.__oobeButton, extraArgs = [''])
  2159. self.accept('oobe-repeat', self.__oobeButton, extraArgs = ['-repeat'])
  2160. self.accept('oobe-up', self.__oobeButton, extraArgs = ['-up'])
  2161. if self.oobeMode:
  2162. # Disable OOBE mode.
  2163. if self.oobeCullFrustum is not None:
  2164. # First, disable OOBE cull mode.
  2165. self.oobeCull(cam = cam)
  2166. if self.oobeVis:
  2167. self.oobeVis.reparentTo(self.hidden)
  2168. # Restore the mouse interface node, and remove the oobe
  2169. # trackball from the data path.
  2170. self.mouseInterfaceNode.clearButton(KeyboardButton.shift())
  2171. self.oobeTrackball.detachNode()
  2172. bt = self.buttonThrowers[0].node()
  2173. bt.setSpecificFlag(1)
  2174. bt.setButtonDownEvent('')
  2175. bt.setButtonRepeatEvent('')
  2176. bt.setButtonUpEvent('')
  2177. cam.reparentTo(self.camera)
  2178. #if cam == self.cam:
  2179. # self.camNode.setLens(self.camLens)
  2180. self.oobeCamera.reparentTo(self.hidden)
  2181. self.oobeMode = 0
  2182. self.bboard.post('oobeEnabled', False)
  2183. else:
  2184. self.bboard.post('oobeEnabled', True)
  2185. try:
  2186. cameraParent = localAvatar
  2187. except:
  2188. # Make oobeCamera be a sibling of wherever camera is now.
  2189. cameraParent = self.camera.getParent()
  2190. self.oobeCamera.reparentTo(cameraParent)
  2191. self.oobeCamera.clearMat()
  2192. # Make the regular MouseInterface node respond only when
  2193. # the shift button is pressed. And the oobe node will
  2194. # respond only when shift is *not* pressed.
  2195. self.mouseInterfaceNode.requireButton(KeyboardButton.shift(), True)
  2196. self.oobeTrackball.node().requireButton(KeyboardButton.shift(), False)
  2197. self.oobeTrackball.reparentTo(self.mouseWatcher)
  2198. # Set our initial OOB position to be just behind the camera.
  2199. mat = Mat4.translateMat(0, -10, 3) * self.camera.getMat(cameraParent)
  2200. mat.invertInPlace()
  2201. self.oobeTrackball.node().setMat(mat)
  2202. cam.reparentTo(self.oobeCameraTrackball)
  2203. # Temporarily disable button events by routing them
  2204. # through the oobe filters.
  2205. bt = self.buttonThrowers[0].node()
  2206. bt.setSpecificFlag(0)
  2207. bt.setButtonDownEvent('oobe-down')
  2208. bt.setButtonRepeatEvent('oobe-repeat')
  2209. bt.setButtonUpEvent('oobe-up')
  2210. # Don't change the camera lens--keep it with the original lens.
  2211. #if cam == self.cam:
  2212. # self.camNode.setLens(self.oobeLens)
  2213. if self.oobeVis:
  2214. self.oobeVis.reparentTo(self.camera)
  2215. self.oobeMode = 1
  2216. def __oobeButton(self, suffix, button):
  2217. if button.startswith('mouse'):
  2218. # Eat mouse buttons.
  2219. return
  2220. # Transmit other buttons.
  2221. messenger.send(button + suffix)
  2222. def oobeCull(self, cam = None):
  2223. """
  2224. While in OOBE mode (see above), cull the viewing frustum as if
  2225. it were still attached to our original camera. This allows us
  2226. to visualize the effectiveness of our bounding volumes.
  2227. """
  2228. if cam is None:
  2229. cam = self.cam
  2230. # First, make sure OOBE mode is enabled.
  2231. if not getattr(self, 'oobeMode', False):
  2232. self.oobe(cam = cam)
  2233. if self.oobeCullFrustum is None:
  2234. # Enable OOBE culling.
  2235. pnode = LensNode('oobeCull')
  2236. pnode.setLens(self.camLens)
  2237. pnode.showFrustum()
  2238. self.oobeCullFrustum = self.camera.attachNewNode(pnode)
  2239. # Tell the camera to cull from here instead of its own
  2240. # origin.
  2241. for c in self.camList:
  2242. c.node().setCullCenter(self.oobeCullFrustum)
  2243. if cam.node().isOfType(Camera):
  2244. cam.node().setCullCenter(self.oobeCullFrustum)
  2245. for c in cam.findAllMatches('**/+Camera'):
  2246. c.node().setCullCenter(self.oobeCullFrustum)
  2247. else:
  2248. # Disable OOBE culling.
  2249. for c in self.camList:
  2250. c.node().setCullCenter(NodePath())
  2251. if cam.node().isOfType(Camera):
  2252. cam.node().setCullCenter(self.oobeCullFrustum)
  2253. for c in cam.findAllMatches('**/+Camera'):
  2254. c.node().setCullCenter(NodePath())
  2255. self.oobeCullFrustum.removeNode()
  2256. self.oobeCullFrustum = None
  2257. def showCameraFrustum(self):
  2258. # Create a visible representation of the frustum.
  2259. self.removeCameraFrustum()
  2260. geom = self.camLens.makeGeometry()
  2261. if geom is not None:
  2262. gn = GeomNode('frustum')
  2263. gn.addGeom(geom)
  2264. self.camFrustumVis = self.camera.attachNewNode(gn)
  2265. def removeCameraFrustum(self):
  2266. if self.camFrustumVis:
  2267. self.camFrustumVis.removeNode()
  2268. def screenshot(self, namePrefix = 'screenshot',
  2269. defaultFilename = 1, source = None,
  2270. imageComment=""):
  2271. """ Captures a screenshot from the main window or from the
  2272. specified window or Texture and writes it to a filename in the
  2273. current directory (or to a specified directory).
  2274. If defaultFilename is True, the filename is synthesized by
  2275. appending namePrefix to a default filename suffix (including
  2276. the filename extension) specified in the Config variable
  2277. screenshot-filename. Otherwise, if defaultFilename is False,
  2278. the entire namePrefix is taken to be the filename to write,
  2279. and this string should include a suitable filename extension
  2280. that will be used to determine the type of image file to
  2281. write.
  2282. Normally, the source is a GraphicsWindow, GraphicsBuffer or
  2283. DisplayRegion. If a Texture is supplied instead, it must have
  2284. a ram image (that is, if it was generated by
  2285. makeTextureBuffer() or makeCubeMap(), the parameter toRam
  2286. should have been set true). If it is a cube map texture as
  2287. generated by makeCubeMap(), namePrefix should contain the hash
  2288. mark ('#') character.
  2289. :returns: The filename if successful, or None if there is a problem.
  2290. """
  2291. if source is None:
  2292. source = self.win
  2293. if defaultFilename:
  2294. filename = GraphicsOutput.makeScreenshotFilename(namePrefix)
  2295. else:
  2296. filename = Filename(namePrefix)
  2297. if isinstance(source, Texture):
  2298. if source.getZSize() > 1:
  2299. saved = source.write(filename, 0, 0, 1, 0)
  2300. else:
  2301. saved = source.write(filename)
  2302. else:
  2303. saved = source.saveScreenshot(filename, imageComment)
  2304. if saved:
  2305. # Announce to anybody that a screenshot has been taken
  2306. messenger.send('screenshot', [filename])
  2307. return filename
  2308. return None
  2309. def saveCubeMap(self, namePrefix = 'cube_map_#.png',
  2310. defaultFilename = 0, source = None,
  2311. camera = None, size = 128,
  2312. cameraMask = PandaNode.getAllCameraMask(),
  2313. sourceLens = None):
  2314. """
  2315. Similar to :meth:`screenshot()`, this sets up a temporary cube
  2316. map Texture which it uses to take a series of six snapshots of
  2317. the current scene, one in each of the six cube map directions.
  2318. This requires rendering a new frame.
  2319. Unlike `screenshot()`, source may only be a GraphicsWindow,
  2320. GraphicsBuffer, or DisplayRegion; it may not be a Texture.
  2321. camera should be the node to which the cubemap cameras will be
  2322. parented. The default is the camera associated with source,
  2323. if source is a DisplayRegion, or base.camera otherwise.
  2324. :returns: The filename if successful, or None if there is a problem.
  2325. """
  2326. if source is None:
  2327. source = self.win
  2328. if camera is None:
  2329. if hasattr(source, "getCamera"):
  2330. camera = source.getCamera()
  2331. if camera is None:
  2332. camera = self.camera
  2333. if sourceLens is None:
  2334. sourceLens = self.camLens
  2335. if hasattr(source, "getWindow"):
  2336. source = source.getWindow()
  2337. rig = NodePath(namePrefix)
  2338. buffer = source.makeCubeMap(namePrefix, size, rig, cameraMask, 1)
  2339. if buffer is None:
  2340. raise Exception("Could not make cube map.")
  2341. # Set the near and far planes from the default lens.
  2342. lens = rig.find('**/+Camera').node().getLens()
  2343. lens.setNearFar(sourceLens.getNear(), sourceLens.getFar())
  2344. # Now render a frame to fill up the texture.
  2345. rig.reparentTo(camera)
  2346. self.graphicsEngine.openWindows()
  2347. self.graphicsEngine.renderFrame()
  2348. self.graphicsEngine.renderFrame()
  2349. self.graphicsEngine.syncFrame()
  2350. tex = buffer.getTexture()
  2351. saved = self.screenshot(namePrefix = namePrefix,
  2352. defaultFilename = defaultFilename,
  2353. source = tex)
  2354. self.graphicsEngine.removeWindow(buffer)
  2355. rig.removeNode()
  2356. return saved
  2357. def saveSphereMap(self, namePrefix = 'spheremap.png',
  2358. defaultFilename = 0, source = None,
  2359. camera = None, size = 256,
  2360. cameraMask = PandaNode.getAllCameraMask(),
  2361. numVertices = 1000, sourceLens = None):
  2362. """
  2363. This works much like :meth:`saveCubeMap()`, and uses the
  2364. graphics API's hardware cube-mapping ability to get a 360-degree
  2365. view of the world. But then it converts the six cube map faces
  2366. into a single fisheye texture, suitable for applying as a static
  2367. environment map (sphere map).
  2368. For eye-relative static environment maps, sphere maps are often
  2369. preferable to cube maps because they require only a single
  2370. texture and because they are supported on a broader range of
  2371. hardware.
  2372. :returns: The filename if successful, or None if there is a problem.
  2373. """
  2374. if source is None:
  2375. source = self.win
  2376. if camera is None:
  2377. if hasattr(source, "getCamera"):
  2378. camera = source.getCamera()
  2379. if camera is None:
  2380. camera = self.camera
  2381. if sourceLens is None:
  2382. sourceLens = self.camLens
  2383. if hasattr(source, "getWindow"):
  2384. source = source.getWindow()
  2385. # First, make an offscreen buffer to convert the cube map to a
  2386. # sphere map. We make it first so we can guarantee the
  2387. # rendering order for the cube map.
  2388. toSphere = source.makeTextureBuffer(namePrefix, size, size,
  2389. Texture(), 1)
  2390. # Now make the cube map buffer.
  2391. rig = NodePath(namePrefix)
  2392. buffer = toSphere.makeCubeMap(namePrefix, size, rig, cameraMask, 0)
  2393. if buffer is None:
  2394. self.graphicsEngine.removeWindow(toSphere)
  2395. raise Exception("Could not make cube map.")
  2396. # Set the near and far planes from the default lens.
  2397. lens = rig.find('**/+Camera').node().getLens()
  2398. lens.setNearFar(sourceLens.getNear(), sourceLens.getFar())
  2399. # Set up the scene to convert the cube map. It's just a
  2400. # simple scene, with only the FisheyeMaker object in it.
  2401. dr = toSphere.makeMonoDisplayRegion()
  2402. camNode = Camera('camNode')
  2403. lens = OrthographicLens()
  2404. lens.setFilmSize(2, 2)
  2405. lens.setNearFar(-1000, 1000)
  2406. camNode.setLens(lens)
  2407. root = NodePath('buffer')
  2408. cam = root.attachNewNode(camNode)
  2409. dr.setCamera(cam)
  2410. fm = FisheyeMaker('card')
  2411. fm.setNumVertices(numVertices)
  2412. fm.setSquareInscribed(1, 1.1)
  2413. fm.setReflection(1)
  2414. card = root.attachNewNode(fm.generate())
  2415. card.setTexture(buffer.getTexture())
  2416. # Now render a frame. This will render out the cube map and
  2417. # then apply it to the the card in the toSphere buffer.
  2418. rig.reparentTo(camera)
  2419. self.graphicsEngine.openWindows()
  2420. self.graphicsEngine.renderFrame()
  2421. # One more frame for luck.
  2422. self.graphicsEngine.renderFrame()
  2423. self.graphicsEngine.syncFrame()
  2424. saved = self.screenshot(namePrefix = namePrefix,
  2425. defaultFilename = defaultFilename,
  2426. source = toSphere.getTexture())
  2427. self.graphicsEngine.removeWindow(buffer)
  2428. self.graphicsEngine.removeWindow(toSphere)
  2429. rig.removeNode()
  2430. return saved
  2431. def movie(self, namePrefix = 'movie', duration = 1.0, fps = 30,
  2432. format = 'png', sd = 4, source = None):
  2433. """
  2434. Spawn a task to capture a movie using the screenshot function.
  2435. Args:
  2436. namePrefix (str): used to form output file names (can
  2437. include path information (e.g. '/i/beta/frames/myMovie')
  2438. duration (float): the length of the movie in seconds
  2439. fps (float): the frame rate of the resulting movie
  2440. format (str): specifies output file format (e.g. png, bmp)
  2441. sd (int): specifies number of significant digits for frame
  2442. count in the output file name (e.g. if sd = 4, the name
  2443. will be something like movie_0001.png)
  2444. source: the Window, Buffer, DisplayRegion, or Texture from
  2445. which to save the resulting images. The default is the
  2446. main window.
  2447. Returns:
  2448. A `~direct.task.Task` that can be awaited.
  2449. """
  2450. globalClock.setMode(ClockObject.MNonRealTime)
  2451. globalClock.setDt(1.0/float(fps))
  2452. t = self.taskMgr.add(self._movieTask, namePrefix + '_task')
  2453. t.frameIndex = 0 # Frame 0 is not captured.
  2454. t.numFrames = int(duration * fps)
  2455. t.source = source
  2456. t.outputString = namePrefix + '_%0' + repr(sd) + 'd.' + format
  2457. t.setUponDeath(lambda state: globalClock.setMode(ClockObject.MNormal))
  2458. return t
  2459. def _movieTask(self, state):
  2460. if state.frameIndex != 0:
  2461. frameName = state.outputString % state.frameIndex
  2462. self.notify.info("Capturing frame: " + frameName)
  2463. self.screenshot(namePrefix = frameName, defaultFilename = 0,
  2464. source = state.source)
  2465. state.frameIndex += 1
  2466. if state.frameIndex > state.numFrames:
  2467. return Task.done
  2468. else:
  2469. return Task.cont
  2470. def windowEvent(self, win):
  2471. if win != self.win:
  2472. # This event isn't about our window.
  2473. return
  2474. properties = win.getProperties()
  2475. if properties != self.__prevWindowProperties:
  2476. self.__prevWindowProperties = properties
  2477. self.notify.debug("Got window event: %s" % (repr(properties)))
  2478. if not properties.getOpen():
  2479. # If the user closes the main window, we should exit.
  2480. self.notify.info("User closed main window.")
  2481. if __debug__:
  2482. if self.__autoGarbageLogging:
  2483. GarbageReport.b_checkForGarbageLeaks()
  2484. self.userExit()
  2485. if properties.getForeground() and not self.mainWinForeground:
  2486. self.mainWinForeground = 1
  2487. elif not properties.getForeground() and self.mainWinForeground:
  2488. self.mainWinForeground = 0
  2489. if __debug__:
  2490. if self.__autoGarbageLogging:
  2491. GarbageReport.b_checkForGarbageLeaks()
  2492. if properties.getMinimized() and not self.mainWinMinimized:
  2493. # If the main window is minimized, throw an event to
  2494. # stop the music.
  2495. self.mainWinMinimized = 1
  2496. messenger.send('PandaPaused')
  2497. elif not properties.getMinimized() and self.mainWinMinimized:
  2498. # If the main window is restored, throw an event to
  2499. # restart the music.
  2500. self.mainWinMinimized = 0
  2501. messenger.send('PandaRestarted')
  2502. # If we have not forced the aspect ratio, let's see if it has
  2503. # changed and update the camera lenses and aspect2d parameters
  2504. self.adjustWindowAspectRatio(self.getAspectRatio())
  2505. if win.hasSize() and win.getSbsLeftYSize() != 0:
  2506. self.pixel2d.setScale(2.0 / win.getSbsLeftXSize(), 1.0, 2.0 / win.getSbsLeftYSize())
  2507. if self.wantRender2dp:
  2508. self.pixel2dp.setScale(2.0 / win.getSbsLeftXSize(), 1.0, 2.0 / win.getSbsLeftYSize())
  2509. else:
  2510. xsize, ysize = self.getSize()
  2511. if xsize > 0 and ysize > 0:
  2512. self.pixel2d.setScale(2.0 / xsize, 1.0, 2.0 / ysize)
  2513. if self.wantRender2dp:
  2514. self.pixel2dp.setScale(2.0 / xsize, 1.0, 2.0 / ysize)
  2515. def adjustWindowAspectRatio(self, aspectRatio):
  2516. """ This function is normally called internally by
  2517. `windowEvent()`, but it may also be called to explicitly adjust
  2518. the aspect ratio of the render/render2d DisplayRegion, by a
  2519. class that has redefined these. """
  2520. if self.__configAspectRatio:
  2521. aspectRatio = self.__configAspectRatio
  2522. if aspectRatio != self.__oldAspectRatio:
  2523. self.__oldAspectRatio = aspectRatio
  2524. # Fix up some anything that depends on the aspectRatio
  2525. if self.camLens:
  2526. self.camLens.setAspectRatio(aspectRatio)
  2527. if aspectRatio < 1:
  2528. # If the window is TALL, lets expand the top and bottom
  2529. self.aspect2d.setScale(1.0, aspectRatio, aspectRatio)
  2530. self.a2dTop = 1.0 / aspectRatio
  2531. self.a2dBottom = - 1.0 / aspectRatio
  2532. self.a2dLeft = -1
  2533. self.a2dRight = 1.0
  2534. # Don't forget 2dp
  2535. if self.wantRender2dp:
  2536. self.aspect2dp.setScale(1.0, aspectRatio, aspectRatio)
  2537. self.a2dpTop = 1.0 / aspectRatio
  2538. self.a2dpBottom = - 1.0 / aspectRatio
  2539. self.a2dpLeft = -1
  2540. self.a2dpRight = 1.0
  2541. else:
  2542. # If the window is WIDE, lets expand the left and right
  2543. self.aspect2d.setScale(1.0 / aspectRatio, 1.0, 1.0)
  2544. self.a2dTop = 1.0
  2545. self.a2dBottom = -1.0
  2546. self.a2dLeft = -aspectRatio
  2547. self.a2dRight = aspectRatio
  2548. # Don't forget 2dp
  2549. if self.wantRender2dp:
  2550. self.aspect2dp.setScale(1.0 / aspectRatio, 1.0, 1.0)
  2551. self.a2dpTop = 1.0
  2552. self.a2dpBottom = -1.0
  2553. self.a2dpLeft = -aspectRatio
  2554. self.a2dpRight = aspectRatio
  2555. # Reposition the aspect2d marker nodes
  2556. self.a2dTopCenter.setPos(0, 0, self.a2dTop)
  2557. self.a2dTopCenterNs.setPos(0, 0, self.a2dTop)
  2558. self.a2dBottomCenter.setPos(0, 0, self.a2dBottom)
  2559. self.a2dBottomCenterNs.setPos(0, 0, self.a2dBottom)
  2560. self.a2dLeftCenter.setPos(self.a2dLeft, 0, 0)
  2561. self.a2dLeftCenterNs.setPos(self.a2dLeft, 0, 0)
  2562. self.a2dRightCenter.setPos(self.a2dRight, 0, 0)
  2563. self.a2dRightCenterNs.setPos(self.a2dRight, 0, 0)
  2564. self.a2dTopLeft.setPos(self.a2dLeft, 0, self.a2dTop)
  2565. self.a2dTopLeftNs.setPos(self.a2dLeft, 0, self.a2dTop)
  2566. self.a2dTopRight.setPos(self.a2dRight, 0, self.a2dTop)
  2567. self.a2dTopRightNs.setPos(self.a2dRight, 0, self.a2dTop)
  2568. self.a2dBottomLeft.setPos(self.a2dLeft, 0, self.a2dBottom)
  2569. self.a2dBottomLeftNs.setPos(self.a2dLeft, 0, self.a2dBottom)
  2570. self.a2dBottomRight.setPos(self.a2dRight, 0, self.a2dBottom)
  2571. self.a2dBottomRightNs.setPos(self.a2dRight, 0, self.a2dBottom)
  2572. # Reposition the aspect2dp marker nodes
  2573. if self.wantRender2dp:
  2574. self.a2dpTopCenter.setPos(0, 0, self.a2dpTop)
  2575. self.a2dpBottomCenter.setPos(0, 0, self.a2dpBottom)
  2576. self.a2dpLeftCenter.setPos(self.a2dpLeft, 0, 0)
  2577. self.a2dpRightCenter.setPos(self.a2dpRight, 0, 0)
  2578. self.a2dpTopLeft.setPos(self.a2dpLeft, 0, self.a2dpTop)
  2579. self.a2dpTopRight.setPos(self.a2dpRight, 0, self.a2dpTop)
  2580. self.a2dpBottomLeft.setPos(self.a2dpLeft, 0, self.a2dpBottom)
  2581. self.a2dpBottomRight.setPos(self.a2dpRight, 0, self.a2dpBottom)
  2582. # If anybody needs to update their GUI, put a callback on this event
  2583. messenger.send("aspectRatioChanged")
  2584. def userExit(self):
  2585. # The user has requested we exit the program. Deal with this.
  2586. if self.exitFunc:
  2587. self.exitFunc()
  2588. self.notify.info("Exiting ShowBase.")
  2589. self.finalizeExit()
  2590. def finalizeExit(self):
  2591. """
  2592. Called by `userExit()` to quit the application. The default
  2593. implementation just calls `sys.exit()`.
  2594. """
  2595. sys.exit()
  2596. # [gjeon] start wxPython
  2597. def startWx(self, fWantWx = True):
  2598. fWantWx = bool(fWantWx)
  2599. if self.wantWx != fWantWx:
  2600. self.wantWx = fWantWx
  2601. if self.wantWx:
  2602. self.spawnWxLoop()
  2603. def spawnWxLoop(self):
  2604. """ Call this method to hand the main loop over to wxPython.
  2605. This sets up a wxTimer callback so that Panda still gets
  2606. updated, but wxPython owns the main loop (which seems to make
  2607. it happier than the other way around). """
  2608. if self.wxAppCreated:
  2609. # Don't do this twice.
  2610. return
  2611. init_app_for_gui()
  2612. # Use importlib to prevent this import from being picked up
  2613. # by modulefinder when packaging an application.
  2614. wx = importlib.import_module('wx')
  2615. if not self.wxApp:
  2616. # Create a new base.wxApp.
  2617. self.wxApp = wx.App(redirect = False)
  2618. if ConfigVariableBool('wx-main-loop', True):
  2619. # Put wxPython in charge of the main loop. It really
  2620. # seems to like this better; some features of wx don't
  2621. # work properly unless this is true.
  2622. # Set a timer to run the Panda frame 60 times per second.
  2623. wxFrameRate = ConfigVariableDouble('wx-frame-rate', 60.0)
  2624. self.wxTimer = wx.Timer(self.wxApp)
  2625. self.wxTimer.Start(1000.0 / wxFrameRate.getValue())
  2626. self.wxApp.Bind(wx.EVT_TIMER, self.__wxTimerCallback)
  2627. # wx is now the main loop, not us any more.
  2628. self.run = self.wxRun
  2629. self.taskMgr.run = self.wxRun
  2630. builtins.run = self.wxRun
  2631. if self.appRunner:
  2632. self.appRunner.run = self.wxRun
  2633. else:
  2634. # Leave Panda in charge of the main loop. This is
  2635. # friendlier for IDE's and interactive editing in general.
  2636. def wxLoop(task):
  2637. # First we need to ensure that the OS message queue is
  2638. # processed.
  2639. self.wxApp.Yield()
  2640. # Now do all the wxPython events waiting on this frame.
  2641. while self.wxApp.Pending():
  2642. self.wxApp.Dispatch()
  2643. return task.again
  2644. self.taskMgr.add(wxLoop, 'wxLoop')
  2645. self.wxAppCreated = True
  2646. def __wxTimerCallback(self, event):
  2647. if Thread.getCurrentThread().getCurrentTask():
  2648. # This happens when the wxTimer expires while igLoop is
  2649. # rendering. Ignore it.
  2650. return
  2651. self.taskMgr.step()
  2652. def wxRun(self):
  2653. """ This method replaces `run()` after we have called `spawnWxLoop()`.
  2654. Since at this point wxPython now owns the main loop, this method is a
  2655. call to wxApp.MainLoop(). """
  2656. if Thread.getCurrentThread().getCurrentTask():
  2657. # This happens in the p3d environment during startup.
  2658. # Ignore it.
  2659. return
  2660. self.wxApp.MainLoop()
  2661. def startTk(self, fWantTk = True):
  2662. fWantTk = bool(fWantTk)
  2663. if self.wantTk != fWantTk:
  2664. self.wantTk = fWantTk
  2665. if self.wantTk:
  2666. self.spawnTkLoop()
  2667. def spawnTkLoop(self):
  2668. """ Call this method to hand the main loop over to Tkinter.
  2669. This sets up a timer callback so that Panda still gets
  2670. updated, but Tkinter owns the main loop (which seems to make
  2671. it happier than the other way around). """
  2672. if self.tkRootCreated:
  2673. # Don't do this twice.
  2674. return
  2675. # Use importlib to prevent this import from being picked up
  2676. # by modulefinder when packaging an application.
  2677. tkinter = importlib.import_module('_tkinter')
  2678. Pmw = importlib.import_module('Pmw')
  2679. # Create a new Tk root.
  2680. if not self.tkRoot:
  2681. self.tkRoot = Pmw.initialise()
  2682. builtins.tkroot = self.tkRoot
  2683. init_app_for_gui()
  2684. # Disable the Windows message loop, since Tcl wants to handle this all
  2685. # on its own.
  2686. ConfigVariableBool('disable-message-loop', False).value = True
  2687. if ConfigVariableBool('tk-main-loop', True):
  2688. # Put Tkinter in charge of the main loop. It really
  2689. # seems to like this better; the GUI otherwise becomes
  2690. # largely unresponsive on Mac OS X unless this is true.
  2691. # Set a timer to run the Panda frame 60 times per second.
  2692. tkFrameRate = ConfigVariableDouble('tk-frame-rate', 60.0)
  2693. self.tkDelay = int(1000.0 / tkFrameRate.getValue())
  2694. self.tkRoot.after(self.tkDelay, self.__tkTimerCallback)
  2695. # wx is now the main loop, not us any more.
  2696. self.run = self.tkRun
  2697. self.taskMgr.run = self.tkRun
  2698. builtins.run = self.tkRun
  2699. if self.appRunner:
  2700. self.appRunner.run = self.tkRun
  2701. else:
  2702. # Leave Panda in charge of the main loop. This is
  2703. # friendlier for IDE's and interactive editing in general.
  2704. def tkLoop(task):
  2705. # Do all the tkinter events waiting on this frame
  2706. # dooneevent will return 0 if there are no more events
  2707. # waiting or 1 if there are still more.
  2708. # DONT_WAIT tells tkinter not to block waiting for events
  2709. while self.tkRoot.dooneevent(tkinter.ALL_EVENTS | tkinter.DONT_WAIT):
  2710. pass
  2711. return task.again
  2712. self.taskMgr.add(tkLoop, 'tkLoop')
  2713. self.tkRootCreated = True
  2714. def __tkTimerCallback(self):
  2715. if not Thread.getCurrentThread().getCurrentTask():
  2716. self.taskMgr.step()
  2717. self.tkRoot.after(self.tkDelay, self.__tkTimerCallback)
  2718. def tkRun(self):
  2719. """ This method replaces `run()` after we have called `spawnTkLoop()`.
  2720. Since at this point Tkinter now owns the main loop, this method is a
  2721. call to tkRoot.mainloop(). """
  2722. if Thread.getCurrentThread().getCurrentTask():
  2723. # This happens in the p3d environment during startup.
  2724. # Ignore it.
  2725. return
  2726. self.tkRoot.mainloop()
  2727. def startDirect(self, fWantDirect = 1, fWantTk = 1, fWantWx = 0):
  2728. self.startTk(fWantTk)
  2729. self.startWx(fWantWx)
  2730. if self.wantDirect == fWantDirect:
  2731. return
  2732. self.wantDirect = fWantDirect
  2733. if self.wantDirect:
  2734. # Use importlib to prevent this import from being picked up
  2735. # by modulefinder when packaging an application.
  2736. DirectSession = importlib.import_module('direct.directtools.DirectSession')
  2737. self.direct = DirectSession.DirectSession()
  2738. self.direct.enable()
  2739. builtins.direct = self.direct
  2740. else:
  2741. builtins.direct = self.direct = None
  2742. def getRepository(self):
  2743. return None
  2744. def getAxes(self):
  2745. """
  2746. Loads and returns the ``models/misc/xyzAxis.bam`` model.
  2747. :rtype: panda3d.core.NodePath
  2748. """
  2749. return self.loader.loadModel("models/misc/xyzAxis.bam")
  2750. def __doStartDirect(self):
  2751. if self.__directStarted:
  2752. return
  2753. self.__directStarted = False
  2754. # Start Tk, Wx and DIRECT if specified by Config.prc
  2755. fTk = self.config.GetBool('want-tk', 0)
  2756. fWx = self.config.GetBool('want-wx', 0)
  2757. # Start DIRECT if specified in Config.prc or in cluster mode
  2758. fDirect = (self.config.GetBool('want-directtools', 0) or
  2759. (self.config.GetString("cluster-mode", '') != ''))
  2760. # Set fWantTk to 0 to avoid starting Tk with this call
  2761. self.startDirect(fWantDirect = fDirect, fWantTk = fTk, fWantWx = fWx)
  2762. def run(self): # pylint: disable=method-hidden
  2763. """This method runs the :class:`~direct.task.Task.TaskManager`
  2764. when ``self.appRunner is None``, which is to say, when we are
  2765. not running from within a p3d file. When we *are* within a p3d
  2766. file, the Panda3D runtime has to be responsible for running the
  2767. main loop, so we can't allow the application to do it.
  2768. """
  2769. if self.appRunner is None or self.appRunner.dummy or \
  2770. (self.appRunner.interactiveConsole and not self.appRunner.initialAppImport):
  2771. self.taskMgr.run()
  2772. # Snake-case aliases, for people who prefer these. We're in the process
  2773. # of migrating everyone to use the snake-case alternatives.
  2774. make_default_pipe = makeDefaultPipe
  2775. make_module_pipe = makeModulePipe
  2776. make_all_pipes = makeAllPipes
  2777. open_window = openWindow
  2778. close_window = closeWindow
  2779. open_default_window = openDefaultWindow
  2780. open_main_window = openMainWindow
  2781. set_sleep = setSleep
  2782. set_frame_rate_meter = setFrameRateMeter
  2783. set_scene_graph_analyzer_meter = setSceneGraphAnalyzerMeter
  2784. setup_window_controls = setupWindowControls
  2785. setup_render = setupRender
  2786. setup_render2d = setupRender2d
  2787. setup_render2dp = setupRender2dp
  2788. set_aspect_ratio = setAspectRatio
  2789. get_aspect_ratio = getAspectRatio
  2790. get_size = getSize
  2791. make_camera = makeCamera
  2792. make_camera2d = makeCamera2d
  2793. make_camera2dp = makeCamera2dp
  2794. setup_data_graph = setupDataGraph
  2795. setup_mouse = setupMouse
  2796. setup_mouse_cb = setupMouseCB
  2797. enable_software_mouse_pointer = enableSoftwareMousePointer
  2798. detach_input_device = detachInputDevice
  2799. attach_input_device = attachInputDevice
  2800. add_angular_integrator = addAngularIntegrator
  2801. enable_particles = enableParticles
  2802. disable_particles = disableParticles
  2803. toggle_particles = toggleParticles
  2804. create_stats = createStats
  2805. add_sfx_manager = addSfxManager
  2806. enable_music = enableMusic
  2807. enable_sound_effects = enableSoundEffects
  2808. disable_all_audio = disableAllAudio
  2809. enable_all_audio = enableAllAudio
  2810. init_shadow_trav = initShadowTrav
  2811. get_background_color = getBackgroundColor
  2812. set_background_color = setBackgroundColor
  2813. toggle_backface = toggleBackface
  2814. backface_culling_on = backfaceCullingOn
  2815. backface_culling_off = backfaceCullingOff
  2816. toggle_texture = toggleTexture
  2817. texture_on = textureOn
  2818. texture_off = textureOff
  2819. toggle_wireframe = toggleWireframe
  2820. wireframe_on = wireframeOn
  2821. wireframe_off = wireframeOff
  2822. disable_mouse = disableMouse
  2823. enable_mouse = enableMouse
  2824. silence_input = silenceInput
  2825. revive_input = reviveInput
  2826. set_mouse_on_node = setMouseOnNode
  2827. change_mouse_interface = changeMouseInterface
  2828. use_drive = useDrive
  2829. use_trackball = useTrackball
  2830. toggle_tex_mem = toggleTexMem
  2831. toggle_show_vertices = toggleShowVertices
  2832. oobe_cull = oobeCull
  2833. show_camera_frustum = showCameraFrustum
  2834. remove_camera_frustum = removeCameraFrustum
  2835. save_cube_map = saveCubeMap
  2836. save_sphere_map = saveSphereMap
  2837. start_wx = startWx
  2838. start_tk = startTk
  2839. start_direct = startDirect
  2840. # A class to encapsulate information necessary for multiwindow support.
  2841. class WindowControls:
  2842. def __init__(
  2843. self, win, cam=None, camNode=None, cam2d=None, mouseWatcher=None,
  2844. mouseKeyboard=None, closeCmd=lambda: 0, grid=None):
  2845. self.win = win
  2846. self.camera = cam
  2847. if camNode is None and cam is not None:
  2848. camNode = cam.node()
  2849. self.camNode = camNode
  2850. self.camera2d = cam2d
  2851. self.mouseWatcher = mouseWatcher
  2852. self.mouseKeyboard = mouseKeyboard
  2853. self.closeCommand = closeCmd
  2854. self.grid = grid
  2855. def __str__(self):
  2856. s = "window = " + str(self.win) + "\n"
  2857. s += "camera = " + str(self.camera) + "\n"
  2858. s += "camNode = " + str(self.camNode) + "\n"
  2859. s += "camera2d = " + str(self.camera2d) + "\n"
  2860. s += "mouseWatcher = " + str(self.mouseWatcher) + "\n"
  2861. s += "mouseAndKeyboard = " + str(self.mouseKeyboard) + "\n"
  2862. return s