ShowBase.py 132 KB

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