2
0

ShowBase.py 132 KB

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