PythonUtil.py 128 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961
  1. """Undocumented Module"""
  2. __all__ = ['enumerate', 'unique', 'indent', 'nonRepeatingRandomList',
  3. 'writeFsmTree', 'StackTrace', 'traceFunctionCall', 'traceParentCall',
  4. 'printThisCall', 'tron', 'trace', 'troff', 'getClassLineage', 'pdir',
  5. '_pdir', '_is_variadic', '_has_keywordargs', '_varnames', '_getcode',
  6. 'Signature', 'doc', 'adjust', 'difference', 'intersection', 'union',
  7. 'sameElements', 'makeList', 'makeTuple', 'list2dict', 'invertDict',
  8. 'invertDictLossless', 'uniqueElements', 'disjoint', 'contains',
  9. 'replace', 'reduceAngle', 'fitSrcAngle2Dest', 'fitDestAngle2Src',
  10. 'closestDestAngle2', 'closestDestAngle', 'binaryRepr', 'profileFunc',
  11. 'profiled', 'startProfile', 'printProfile', 'getSetterName',
  12. 'getSetter', 'Functor', 'Stack', 'Queue', 'ParamObj',
  13. 'POD', 'bound', 'lerp', 'average', 'addListsByValue',
  14. 'boolEqual', 'lineupPos', 'formatElapsedSeconds', 'solveQuadratic',
  15. 'stackEntryInfo', 'lineInfo', 'callerInfo', 'lineTag',
  16. 'findPythonModule', 'describeException', 'mostDerivedLast',
  17. 'clampScalar', 'weightedChoice', 'randFloat', 'normalDistrib',
  18. 'weightedRand', 'randUint31', 'randInt32', 'randUint32',
  19. 'SerialNumGen', 'serialNum', 'uniqueName', 'Enum', 'Singleton',
  20. 'SingletonError', 'printListEnum', 'safeRepr',
  21. 'fastRepr', 'tagRepr', 'tagWithCaller', 'isDefaultValue', 'set_trace', 'pm',
  22. 'ScratchPad', 'Sync', 'RefCounter', 'itype', 'getNumberedTypedString',
  23. 'getNumberedTypedSortedString', 'getNumberedTypedSortedStringWithReferrers',
  24. 'getNumberedTypedSortedStringWithReferrersGen',
  25. 'printNumberedTyped', 'DelayedCall', 'DelayedFunctor',
  26. 'FrameDelayedCall', 'SubframeCall', 'ArgumentEater', 'ClassTree', 'getBase',
  27. 'HotkeyBreaker','logMethodCalls','GoldenRatio',
  28. 'GoldenRectangle', 'pivotScalar', 'rad90', 'rad180', 'rad270', 'rad360',
  29. 'nullGen', 'loopGen', 'makeFlywheelGen', 'flywheel', 'choice',
  30. 'printStack', 'printReverseStack', 'listToIndex2item', 'listToItem2index',
  31. 'pandaBreak','pandaTrace','formatTimeCompact','DestructiveScratchPad',
  32. 'deeptype','getProfileResultString','StdoutCapture','StdoutPassthrough',
  33. 'Averager', 'getRepository', 'formatTimeExact', 'startSuperLog', 'endSuperLog',
  34. 'typeName', 'safeTypeName', 'histogramDict', ]
  35. import types
  36. import string
  37. import re
  38. import math
  39. import operator
  40. import inspect
  41. import os
  42. import sys
  43. import random
  44. import time
  45. import new
  46. import gc
  47. #if __debug__:
  48. import traceback
  49. import __builtin__
  50. from StringIO import StringIO
  51. import marshal
  52. from direct.directutil import Verify
  53. # Don't import libpandaexpressModules, which doesn't get built until
  54. # genPyCode.
  55. import direct.extensions_native.extension_native_helpers
  56. from libpandaexpress import ConfigVariableBool
  57. ScalarTypes = (types.FloatType, types.IntType, types.LongType)
  58. import __builtin__
  59. if not hasattr(__builtin__, 'enumerate'):
  60. def enumerate(L):
  61. """Returns (0, L[0]), (1, L[1]), etc., allowing this syntax:
  62. for i, item in enumerate(L):
  63. ...
  64. enumerate is a built-in feature in Python 2.3, which implements it
  65. using an iterator. For now, we can use this quick & dirty
  66. implementation that returns a list of tuples that is completely
  67. constructed every time enumerate() is called.
  68. """
  69. return zip(xrange(len(L)), L)
  70. __builtin__.enumerate = enumerate
  71. else:
  72. enumerate = __builtin__.enumerate
  73. """
  74. # with one integer positional arg, this uses about 4/5 of the memory of the Functor class below
  75. def Functor(function, *args, **kArgs):
  76. argsCopy = args[:]
  77. def functor(*cArgs, **ckArgs):
  78. kArgs.update(ckArgs)
  79. return function(*(argsCopy + cArgs), **kArgs)
  80. return functor
  81. """
  82. class Functor:
  83. def __init__(self, function, *args, **kargs):
  84. assert callable(function), "function should be a callable obj"
  85. self._function = function
  86. self._args = args
  87. self._kargs = kargs
  88. if hasattr(self._function, '__name__'):
  89. self.__name__ = self._function.__name__
  90. else:
  91. self.__name__ = str(itype(self._function))
  92. if hasattr(self._function, '__doc__'):
  93. self.__doc__ = self._function.__doc__
  94. else:
  95. self.__doc__ = self.__name__
  96. def destroy(self):
  97. del self._function
  98. del self._args
  99. del self._kargs
  100. del self.__name__
  101. del self.__doc__
  102. def _do__call__(self, *args, **kargs):
  103. _kargs = self._kargs.copy()
  104. _kargs.update(kargs)
  105. return self._function(*(self._args + args), **_kargs)
  106. # this method is used in place of __call__ if we are recording creation stacks
  107. def _exceptionLoggedCreationStack__call__(self, *args, **kargs):
  108. try:
  109. return self._do__call__(*args, **kargs)
  110. except Exception, e:
  111. print '-->Functor creation stack (%s): %s' % (
  112. self.__name__, self.getCreationStackTraceCompactStr())
  113. raise
  114. __call__ = _do__call__
  115. def __repr__(self):
  116. s = 'Functor(%s' % self._function.__name__
  117. for arg in self._args:
  118. try:
  119. argStr = repr(arg)
  120. except:
  121. argStr = 'bad repr: %s' % arg.__class__
  122. s += ', %s' % argStr
  123. for karg, value in self._kargs.items():
  124. s += ', %s=%s' % (karg, repr(value))
  125. s += ')'
  126. return s
  127. class Stack:
  128. def __init__(self):
  129. self.__list = []
  130. def push(self, item):
  131. self.__list.append(item)
  132. def top(self):
  133. # return the item on the top of the stack without popping it off
  134. return self.__list[-1]
  135. def pop(self):
  136. return self.__list.pop()
  137. def clear(self):
  138. self.__list = []
  139. def isEmpty(self):
  140. return len(self.__list) == 0
  141. def __len__(self):
  142. return len(self.__list)
  143. class Queue:
  144. # FIFO queue
  145. # interface is intentionally identical to Stack (LIFO)
  146. def __init__(self):
  147. self.__list = []
  148. def push(self, item):
  149. self.__list.append(item)
  150. def top(self):
  151. # return the next item at the front of the queue without popping it off
  152. return self.__list[0]
  153. def front(self):
  154. return self.__list[0]
  155. def back(self):
  156. return self.__list[-1]
  157. def pop(self):
  158. return self.__list.pop(0)
  159. def clear(self):
  160. self.__list = []
  161. def isEmpty(self):
  162. return len(self.__list) == 0
  163. def __len__(self):
  164. return len(self.__list)
  165. if __debug__:
  166. q = Queue()
  167. assert q.isEmpty()
  168. q.clear()
  169. assert q.isEmpty()
  170. q.push(10)
  171. assert not q.isEmpty()
  172. q.push(20)
  173. assert not q.isEmpty()
  174. assert len(q) == 2
  175. assert q.front() == 10
  176. assert q.back() == 20
  177. assert q.top() == 10
  178. assert q.top() == 10
  179. assert q.pop() == 10
  180. assert len(q) == 1
  181. assert not q.isEmpty()
  182. assert q.pop() == 20
  183. assert len(q) == 0
  184. assert q.isEmpty()
  185. def unique(L1, L2):
  186. """Return a list containing all items in 'L1' that are not in 'L2'"""
  187. L2 = dict([(k, None) for k in L2])
  188. return [item for item in L1 if item not in L2]
  189. def indent(stream, numIndents, str):
  190. """
  191. Write str to stream with numIndents in front of it
  192. """
  193. # To match emacs, instead of a tab character we will use 4 spaces
  194. stream.write(' ' * numIndents + str)
  195. def nonRepeatingRandomList(vals, max):
  196. random.seed(time.time())
  197. #first generate a set of random values
  198. valueList=range(max)
  199. finalVals=[]
  200. for i in range(vals):
  201. index=int(random.random()*len(valueList))
  202. finalVals.append(valueList[index])
  203. valueList.remove(valueList[index])
  204. return finalVals
  205. def writeFsmTree(instance, indent = 0):
  206. if hasattr(instance, 'parentFSM'):
  207. writeFsmTree(instance.parentFSM, indent-2)
  208. elif hasattr(instance, 'fsm'):
  209. name = ''
  210. if hasattr(instance.fsm, 'state'):
  211. name = instance.fsm.state.name
  212. print "%s: %s"%(instance.fsm.name, name)
  213. #if __debug__: #RAU accdg to Darren its's ok that StackTrace is not protected by __debug__
  214. # DCR: if somebody ends up using StackTrace in production, either
  215. # A) it will be OK because it hardly ever gets called, or
  216. # B) it will be easy to track it down (grep for StackTrace)
  217. class StackTrace:
  218. def __init__(self, label="", start=0, limit=None):
  219. """
  220. label is a string (or anything that be be a string)
  221. that is printed as part of the trace back.
  222. This is just to make it easier to tell what the
  223. stack trace is referring to.
  224. start is an integer number of stack frames back
  225. from the most recent. (This is automatically
  226. bumped up by one to skip the __init__ call
  227. to the StackTrace).
  228. limit is an integer number of stack frames
  229. to record (or None for unlimited).
  230. """
  231. self.label = label
  232. if limit is not None:
  233. self.trace = traceback.extract_stack(sys._getframe(1+start),
  234. limit=limit)
  235. else:
  236. self.trace = traceback.extract_stack(sys._getframe(1+start))
  237. def compact(self):
  238. r = ''
  239. comma = ','
  240. for filename, lineNum, funcName, text in self.trace:
  241. r += '%s.%s:%s%s' % (filename[:filename.rfind('.py')][filename.rfind('\\')+1:], funcName, lineNum, comma)
  242. if len(r):
  243. r = r[:-len(comma)]
  244. return r
  245. def reverseCompact(self):
  246. r = ''
  247. comma = ','
  248. for filename, lineNum, funcName, text in self.trace:
  249. r = '%s.%s:%s%s%s' % (filename[:filename.rfind('.py')][filename.rfind('\\')+1:], funcName, lineNum, comma, r)
  250. if len(r):
  251. r = r[:-len(comma)]
  252. return r
  253. def __str__(self):
  254. r = "Debug stack trace of %s (back %s frames):\n"%(
  255. self.label, len(self.trace),)
  256. for i in traceback.format_list(self.trace):
  257. r+=i
  258. r+="***** NOTE: This is not a crash. This is a debug stack trace. *****"
  259. return r
  260. def printStack():
  261. print StackTrace(start=1).compact()
  262. return True
  263. def printReverseStack():
  264. print StackTrace(start=1).reverseCompact()
  265. return True
  266. def printVerboseStack():
  267. print StackTrace(start=1)
  268. return True
  269. #-----------------------------------------------------------------------------
  270. def traceFunctionCall(frame):
  271. """
  272. return a string that shows the call frame with calling arguments.
  273. e.g.
  274. foo(x=234, y=135)
  275. """
  276. f = frame
  277. co = f.f_code
  278. dict = f.f_locals
  279. n = co.co_argcount
  280. if co.co_flags & 4: n = n+1
  281. if co.co_flags & 8: n = n+1
  282. r=''
  283. if dict.has_key('self'):
  284. r = '%s.'%(dict['self'].__class__.__name__,)
  285. r+="%s("%(f.f_code.co_name,)
  286. comma=0 # formatting, whether we should type a comma.
  287. for i in range(n):
  288. name = co.co_varnames[i]
  289. if name=='self':
  290. continue
  291. if comma:
  292. r+=', '
  293. else:
  294. # ok, we skipped the first one, the rest get commas:
  295. comma=1
  296. r+=name
  297. r+='='
  298. if dict.has_key(name):
  299. v=str(dict[name])
  300. if len(v)>2000:
  301. # r+="<too big for debug>"
  302. r += (str(dict[name])[:2000] + "...")
  303. else:
  304. r+=str(dict[name])
  305. else: r+="*** undefined ***"
  306. return r+')'
  307. def traceParentCall():
  308. return traceFunctionCall(sys._getframe(2))
  309. def printThisCall():
  310. print traceFunctionCall(sys._getframe(1))
  311. return 1 # to allow "assert printThisCall()"
  312. if __debug__:
  313. def lineage(obj, verbose=0, indent=0):
  314. """
  315. return instance or class name in as a multiline string.
  316. Usage: print lineage(foo)
  317. (Based on getClassLineage())
  318. """
  319. r=""
  320. if type(obj) == types.ListType:
  321. r+=(" "*indent)+"python list\n"
  322. elif type(obj) == types.DictionaryType:
  323. r+=(" "*indent)+"python dictionary\n"
  324. elif type(obj) == types.ModuleType:
  325. r+=(" "*indent)+str(obj)+"\n"
  326. elif type(obj) == types.InstanceType:
  327. r+=lineage(obj.__class__, verbose, indent)
  328. elif type(obj) == types.ClassType:
  329. r+=(" "*indent)
  330. if verbose:
  331. r+=obj.__module__+"."
  332. r+=obj.__name__+"\n"
  333. for c in obj.__bases__:
  334. r+=lineage(c, verbose, indent+2)
  335. return r
  336. def tron():
  337. sys.settrace(trace)
  338. def trace(frame, event, arg):
  339. if event == 'line':
  340. pass
  341. elif event == 'call':
  342. print traceFunctionCall(sys._getframe(1))
  343. elif event == 'return':
  344. print "returning"
  345. elif event == 'exception':
  346. print "exception"
  347. return trace
  348. def troff():
  349. sys.settrace(None)
  350. #-----------------------------------------------------------------------------
  351. def getClassLineage(obj):
  352. """
  353. print object inheritance list
  354. """
  355. if type(obj) == types.DictionaryType:
  356. # Just a dictionary, return dictionary
  357. return [obj]
  358. elif (type(obj) == types.InstanceType):
  359. # Instance, make a list with the instance and its class interitance
  360. return [obj] + getClassLineage(obj.__class__)
  361. elif ((type(obj) == types.ClassType) or
  362. (type(obj) == types.TypeType)):
  363. # Class or type, see what it derives from
  364. lineage = [obj]
  365. for c in obj.__bases__:
  366. lineage = lineage + getClassLineage(c)
  367. return lineage
  368. # New FFI objects are types that are not defined.
  369. # but they still act like classes
  370. elif hasattr(obj, '__class__'):
  371. # Instance, make a list with the instance and its class interitance
  372. return [obj] + getClassLineage(obj.__class__)
  373. else:
  374. # Not what I'm looking for
  375. return []
  376. def pdir(obj, str = None, width = None,
  377. fTruncate = 1, lineWidth = 75, wantPrivate = 0):
  378. # Remove redundant class entries
  379. uniqueLineage = []
  380. for l in getClassLineage(obj):
  381. if type(l) == types.ClassType:
  382. if l in uniqueLineage:
  383. break
  384. uniqueLineage.append(l)
  385. # Pretty print out directory info
  386. uniqueLineage.reverse()
  387. for obj in uniqueLineage:
  388. _pdir(obj, str, width, fTruncate, lineWidth, wantPrivate)
  389. print
  390. def _pdir(obj, str = None, width = None,
  391. fTruncate = 1, lineWidth = 75, wantPrivate = 0):
  392. """
  393. Print out a formatted list of members and methods of an instance or class
  394. """
  395. def printHeader(name):
  396. name = ' ' + name + ' '
  397. length = len(name)
  398. if length < 70:
  399. padBefore = int((70 - length)/2.0)
  400. padAfter = max(0, 70 - length - padBefore)
  401. header = '*' * padBefore + name + '*' * padAfter
  402. print header
  403. print
  404. def printInstanceHeader(i, printHeader = printHeader):
  405. printHeader(i.__class__.__name__ + ' INSTANCE INFO')
  406. def printClassHeader(c, printHeader = printHeader):
  407. printHeader(c.__name__ + ' CLASS INFO')
  408. def printDictionaryHeader(d, printHeader = printHeader):
  409. printHeader('DICTIONARY INFO')
  410. # Print Header
  411. if type(obj) == types.InstanceType:
  412. printInstanceHeader(obj)
  413. elif type(obj) == types.ClassType:
  414. printClassHeader(obj)
  415. elif type (obj) == types.DictionaryType:
  416. printDictionaryHeader(obj)
  417. # Get dict
  418. if type(obj) == types.DictionaryType:
  419. dict = obj
  420. # FFI objects are builtin types, they have no __dict__
  421. elif not hasattr(obj, '__dict__'):
  422. dict = {}
  423. else:
  424. dict = obj.__dict__
  425. # Adjust width
  426. if width:
  427. maxWidth = width
  428. else:
  429. maxWidth = 10
  430. keyWidth = 0
  431. aproposKeys = []
  432. privateKeys = []
  433. remainingKeys = []
  434. for key in dict.keys():
  435. if not width:
  436. keyWidth = len(key)
  437. if str:
  438. if re.search(str, key, re.I):
  439. aproposKeys.append(key)
  440. if (not width) and (keyWidth > maxWidth):
  441. maxWidth = keyWidth
  442. else:
  443. if key[:1] == '_':
  444. if wantPrivate:
  445. privateKeys.append(key)
  446. if (not width) and (keyWidth > maxWidth):
  447. maxWidth = keyWidth
  448. else:
  449. remainingKeys.append(key)
  450. if (not width) and (keyWidth > maxWidth):
  451. maxWidth = keyWidth
  452. # Sort appropriate keys
  453. if str:
  454. aproposKeys.sort()
  455. else:
  456. privateKeys.sort()
  457. remainingKeys.sort()
  458. # Print out results
  459. if wantPrivate:
  460. keys = aproposKeys + privateKeys + remainingKeys
  461. else:
  462. keys = aproposKeys + remainingKeys
  463. format = '%-' + `maxWidth` + 's'
  464. for key in keys:
  465. value = dict[key]
  466. if callable(value):
  467. strvalue = `Signature(value)`
  468. else:
  469. strvalue = `value`
  470. if fTruncate:
  471. # Cut off line (keeping at least 1 char)
  472. strvalue = strvalue[:max(1, lineWidth - maxWidth)]
  473. print (format % key)[:maxWidth] + '\t' + strvalue
  474. # Magic numbers: These are the bit masks in func_code.co_flags that
  475. # reveal whether or not the function has a *arg or **kw argument.
  476. _POS_LIST = 4
  477. _KEY_DICT = 8
  478. def _is_variadic(function):
  479. return function.func_code.co_flags & _POS_LIST
  480. def _has_keywordargs(function):
  481. return function.func_code.co_flags & _KEY_DICT
  482. def _varnames(function):
  483. return function.func_code.co_varnames
  484. def _getcode(f):
  485. """
  486. _getcode(f)
  487. This function returns the name and function object of a callable
  488. object.
  489. """
  490. def method_get(f):
  491. return f.__name__, f.im_func
  492. def function_get(f):
  493. return f.__name__, f
  494. def instance_get(f):
  495. if hasattr(f, '__call__'):
  496. method = f.__call__
  497. if (type(method) == types.MethodType):
  498. func = method.im_func
  499. else:
  500. func = method
  501. return ("%s%s" % (f.__class__.__name__, '__call__'), func)
  502. else:
  503. s = ("Instance %s of class %s does not have a __call__ method" %
  504. (f, f.__class__.__name__))
  505. raise TypeError, s
  506. def class_get(f):
  507. if hasattr(f, '__init__'):
  508. return f.__name__, f.__init__.im_func
  509. else:
  510. return f.__name__, lambda: None
  511. codedict = { types.UnboundMethodType: method_get,
  512. types.MethodType: method_get,
  513. types.FunctionType: function_get,
  514. types.InstanceType: instance_get,
  515. types.ClassType: class_get,
  516. }
  517. try:
  518. return codedict[type(f)](f)
  519. except KeyError:
  520. if callable(f): # eg, built-in functions and methods
  521. # raise ValueError, "type %s not supported yet." % type(f)
  522. return f.__name__, None
  523. else:
  524. raise TypeError, ("object %s of type %s is not callable." %
  525. (f, type(f)))
  526. class Signature:
  527. def __init__(self, func):
  528. self.type = type(func)
  529. self.name, self.func = _getcode(func)
  530. def ordinary_args(self):
  531. n = self.func.func_code.co_argcount
  532. return _varnames(self.func)[0:n]
  533. def special_args(self):
  534. n = self.func.func_code.co_argcount
  535. x = {}
  536. #
  537. if _is_variadic(self.func):
  538. x['positional'] = _varnames(self.func)[n]
  539. if _has_keywordargs(self.func):
  540. x['keyword'] = _varnames(self.func)[n+1]
  541. elif _has_keywordargs(self.func):
  542. x['keyword'] = _varnames(self.func)[n]
  543. else:
  544. pass
  545. return x
  546. def full_arglist(self):
  547. base = list(self.ordinary_args())
  548. x = self.special_args()
  549. if x.has_key('positional'):
  550. base.append(x['positional'])
  551. if x.has_key('keyword'):
  552. base.append(x['keyword'])
  553. return base
  554. def defaults(self):
  555. defargs = self.func.func_defaults
  556. args = self.ordinary_args()
  557. mapping = {}
  558. if defargs is not None:
  559. for i in range(-1, -(len(defargs)+1), -1):
  560. mapping[args[i]] = defargs[i]
  561. else:
  562. pass
  563. return mapping
  564. def __repr__(self):
  565. if self.func:
  566. defaults = self.defaults()
  567. specials = self.special_args()
  568. l = []
  569. for arg in self.ordinary_args():
  570. if defaults.has_key(arg):
  571. l.append(arg + '=' + str(defaults[arg]))
  572. else:
  573. l.append(arg)
  574. if specials.has_key('positional'):
  575. l.append('*' + specials['positional'])
  576. if specials.has_key('keyword'):
  577. l.append('**' + specials['keyword'])
  578. return "%s(%s)" % (self.name, string.join(l, ', '))
  579. else:
  580. return "%s(?)" % self.name
  581. def doc(obj):
  582. if (isinstance(obj, types.MethodType)) or \
  583. (isinstance(obj, types.FunctionType)):
  584. print obj.__doc__
  585. def adjust(command = None, dim = 1, parent = None, **kw):
  586. """
  587. adjust(command = None, parent = None, **kw)
  588. Popup and entry scale to adjust a parameter
  589. Accepts any Slider keyword argument. Typical arguments include:
  590. command: The one argument command to execute
  591. min: The min value of the slider
  592. max: The max value of the slider
  593. resolution: The resolution of the slider
  594. text: The label on the slider
  595. These values can be accessed and/or changed after the fact
  596. >>> vg = adjust()
  597. >>> vg['min']
  598. 0.0
  599. >>> vg['min'] = 10.0
  600. >>> vg['min']
  601. 10.0
  602. """
  603. # Make sure we enable Tk
  604. from direct.tkwidgets import Valuator
  605. # Set command if specified
  606. if command:
  607. kw['command'] = lambda x: apply(command, x)
  608. if parent is None:
  609. kw['title'] = command.__name__
  610. kw['dim'] = dim
  611. # Create toplevel if needed
  612. if not parent:
  613. vg = apply(Valuator.ValuatorGroupPanel, (parent,), kw)
  614. else:
  615. vg = apply(Valuator.ValuatorGroup, (parent,), kw)
  616. vg.pack(expand = 1, fill = 'x')
  617. return vg
  618. def difference(a, b):
  619. """
  620. difference(list, list):
  621. """
  622. if not a: return b
  623. if not b: return a
  624. d = []
  625. for i in a:
  626. if (i not in b) and (i not in d):
  627. d.append(i)
  628. for i in b:
  629. if (i not in a) and (i not in d):
  630. d.append(i)
  631. return d
  632. def intersection(a, b):
  633. """
  634. intersection(list, list):
  635. """
  636. if not a: return []
  637. if not b: return []
  638. d = []
  639. for i in a:
  640. if (i in b) and (i not in d):
  641. d.append(i)
  642. for i in b:
  643. if (i in a) and (i not in d):
  644. d.append(i)
  645. return d
  646. def union(a, b):
  647. """
  648. union(list, list):
  649. """
  650. # Copy a
  651. c = a[:]
  652. for i in b:
  653. if (i not in c):
  654. c.append(i)
  655. return c
  656. def sameElements(a, b):
  657. if len(a) != len(b):
  658. return 0
  659. for elem in a:
  660. if elem not in b:
  661. return 0
  662. for elem in b:
  663. if elem not in a:
  664. return 0
  665. return 1
  666. def makeList(x):
  667. """returns x, converted to a list"""
  668. if type(x) is types.ListType:
  669. return x
  670. elif type(x) is types.TupleType:
  671. return list(x)
  672. else:
  673. return [x,]
  674. def makeTuple(x):
  675. """returns x, converted to a tuple"""
  676. if type(x) is types.ListType:
  677. return tuple(x)
  678. elif type(x) is types.TupleType:
  679. return x
  680. else:
  681. return (x,)
  682. def list2dict(L, value=None):
  683. """creates dict using elements of list, all assigned to same value"""
  684. return dict([(k, value) for k in L])
  685. def listToIndex2item(L):
  686. """converts list to dict of list index->list item"""
  687. d = {}
  688. for i, item in enumerate(L):
  689. d[i] = item
  690. return d
  691. assert listToIndex2item(['a','b']) == {0: 'a', 1: 'b',}
  692. def listToItem2index(L):
  693. """converts list to dict of list item->list index
  694. This is lossy if there are duplicate list items"""
  695. d = {}
  696. for i, item in enumerate(L):
  697. d[item] = i
  698. return d
  699. assert listToItem2index(['a','b']) == {'a': 0, 'b': 1,}
  700. def invertDict(D, lossy=False):
  701. """creates a dictionary by 'inverting' D; keys are placed in the new
  702. dictionary under their corresponding value in the old dictionary.
  703. It is an error if D contains any duplicate values.
  704. >>> old = {'key1':1, 'key2':2}
  705. >>> invertDict(old)
  706. {1: 'key1', 2: 'key2'}
  707. """
  708. n = {}
  709. for key, value in D.items():
  710. if not lossy and value in n:
  711. raise 'duplicate key in invertDict: %s' % value
  712. n[value] = key
  713. return n
  714. def invertDictLossless(D):
  715. """similar to invertDict, but values of new dict are lists of keys from
  716. old dict. No information is lost.
  717. >>> old = {'key1':1, 'key2':2, 'keyA':2}
  718. >>> invertDictLossless(old)
  719. {1: ['key1'], 2: ['key2', 'keyA']}
  720. """
  721. n = {}
  722. for key, value in D.items():
  723. n.setdefault(value, [])
  724. n[value].append(key)
  725. return n
  726. def uniqueElements(L):
  727. """are all elements of list unique?"""
  728. return len(L) == len(list2dict(L))
  729. def disjoint(L1, L2):
  730. """returns non-zero if L1 and L2 have no common elements"""
  731. used = dict([(k, None) for k in L1])
  732. for k in L2:
  733. if k in used:
  734. return 0
  735. return 1
  736. def contains(whole, sub):
  737. """
  738. Return 1 if whole contains sub, 0 otherwise
  739. """
  740. if (whole == sub):
  741. return 1
  742. for elem in sub:
  743. # The first item you find not in whole, return 0
  744. if elem not in whole:
  745. return 0
  746. # If you got here, whole must contain sub
  747. return 1
  748. def replace(list, old, new, all=0):
  749. """
  750. replace 'old' with 'new' in 'list'
  751. if all == 0, replace first occurrence
  752. otherwise replace all occurrences
  753. returns the number of items replaced
  754. """
  755. if old not in list:
  756. return 0
  757. if not all:
  758. i = list.index(old)
  759. list[i] = new
  760. return 1
  761. else:
  762. numReplaced = 0
  763. for i in xrange(len(list)):
  764. if list[i] == old:
  765. numReplaced += 1
  766. list[i] = new
  767. return numReplaced
  768. rad90 = math.pi / 2.
  769. rad180 = math.pi
  770. rad270 = 1.5 * math.pi
  771. rad360 = 2. * math.pi
  772. def reduceAngle(deg):
  773. """
  774. Reduces an angle (in degrees) to a value in [-180..180)
  775. """
  776. return (((deg + 180.) % 360.) - 180.)
  777. def fitSrcAngle2Dest(src, dest):
  778. """
  779. given a src and destination angle, returns an equivalent src angle
  780. that is within [-180..180) of dest
  781. examples:
  782. fitSrcAngle2Dest(30, 60) == 30
  783. fitSrcAngle2Dest(60, 30) == 60
  784. fitSrcAngle2Dest(0, 180) == 0
  785. fitSrcAngle2Dest(-1, 180) == 359
  786. fitSrcAngle2Dest(-180, 180) == 180
  787. """
  788. return dest + reduceAngle(src - dest)
  789. def fitDestAngle2Src(src, dest):
  790. """
  791. given a src and destination angle, returns an equivalent dest angle
  792. that is within [-180..180) of src
  793. examples:
  794. fitDestAngle2Src(30, 60) == 60
  795. fitDestAngle2Src(60, 30) == 30
  796. fitDestAngle2Src(0, 180) == -180
  797. fitDestAngle2Src(1, 180) == 180
  798. """
  799. return src + (reduceAngle(dest - src))
  800. def closestDestAngle2(src, dest):
  801. # The function above didn't seem to do what I wanted. So I hacked
  802. # this one together. I can't really say I understand it. It's more
  803. # from impirical observation... GRW
  804. diff = src - dest
  805. if diff > 180:
  806. # if the difference is greater that 180 it's shorter to go the other way
  807. return dest - 360
  808. elif diff < -180:
  809. # or perhaps the OTHER other way...
  810. return dest + 360
  811. else:
  812. # otherwise just go to the original destination
  813. return dest
  814. def closestDestAngle(src, dest):
  815. # The function above didn't seem to do what I wanted. So I hacked
  816. # this one together. I can't really say I understand it. It's more
  817. # from impirical observation... GRW
  818. diff = src - dest
  819. if diff > 180:
  820. # if the difference is greater that 180 it's shorter to go the other way
  821. return src - (diff - 360)
  822. elif diff < -180:
  823. # or perhaps the OTHER other way...
  824. return src - (360 + diff)
  825. else:
  826. # otherwise just go to the original destination
  827. return dest
  828. def binaryRepr(number, max_length = 32):
  829. # This will only work reliably for relatively small numbers.
  830. # Increase the value of max_length if you think you're going
  831. # to use long integers
  832. assert number < 2L << max_length
  833. shifts = map (operator.rshift, max_length * [number], \
  834. range (max_length - 1, -1, -1))
  835. digits = map (operator.mod, shifts, max_length * [2])
  836. if not digits.count (1): return 0
  837. digits = digits [digits.index (1):]
  838. return string.join (map (repr, digits), '')
  839. class StdoutCapture:
  840. # redirects stdout to a string
  841. def __init__(self):
  842. self._oldStdout = sys.stdout
  843. sys.stdout = self
  844. self._string = ''
  845. def destroy(self):
  846. sys.stdout = self._oldStdout
  847. del self._oldStdout
  848. def getString(self):
  849. return self._string
  850. # internal
  851. def write(self, string):
  852. self._string = ''.join([self._string, string])
  853. class StdoutPassthrough(StdoutCapture):
  854. # like StdoutCapture but also allows output to go through to the OS as normal
  855. # internal
  856. def write(self, string):
  857. self._string = ''.join([self._string, string])
  858. self._oldStdout.write(string)
  859. # constant profile defaults
  860. PyUtilProfileDefaultFilename = 'profiledata'
  861. PyUtilProfileDefaultLines = 80
  862. PyUtilProfileDefaultSorts = ['cumulative', 'time', 'calls']
  863. _ProfileResultStr = ''
  864. def getProfileResultString():
  865. # if you called profile with 'log' not set to True,
  866. # you can call this function to get the results as
  867. # a string
  868. global _ProfileResultStr
  869. return _ProfileResultStr
  870. def profileFunc(callback, name, terse, log=True):
  871. global _ProfileResultStr
  872. if 'globalProfileFunc' in __builtin__.__dict__:
  873. # rats. Python profiler is not re-entrant...
  874. base.notify.warning(
  875. 'PythonUtil.profileStart(%s): aborted, already profiling %s'
  876. #'\nStack Trace:\n%s'
  877. % (name, __builtin__.globalProfileFunc,
  878. #StackTrace()
  879. ))
  880. return
  881. __builtin__.globalProfileFunc = callback
  882. __builtin__.globalProfileResult = [None]
  883. prefix = '***** START PROFILE: %s *****' % name
  884. if log:
  885. print prefix
  886. startProfile(cmd='globalProfileResult[0]=globalProfileFunc()', callInfo=(not terse), silent=not log)
  887. suffix = '***** END PROFILE: %s *****' % name
  888. if log:
  889. print suffix
  890. else:
  891. _ProfileResultStr = '%s\n%s\n%s' % (prefix, _ProfileResultStr, suffix)
  892. result = globalProfileResult[0]
  893. del __builtin__.__dict__['globalProfileFunc']
  894. del __builtin__.__dict__['globalProfileResult']
  895. return result
  896. def profiled(category=None, terse=False):
  897. """ decorator for profiling functions
  898. turn categories on and off via "want-profile-categoryName 1"
  899. e.g.
  900. @profiled('particles')
  901. def loadParticles():
  902. ...
  903. want-profile-particles 1
  904. """
  905. assert type(category) in (types.StringType, types.NoneType), "must provide a category name for @profiled"
  906. # allow profiling in published versions
  907. """
  908. try:
  909. null = not __dev__
  910. except:
  911. null = not __debug__
  912. if null:
  913. # if we're not in __dev__, just return the function itself. This
  914. # results in zero runtime overhead, since decorators are evaluated
  915. # at module-load.
  916. def nullDecorator(f):
  917. return f
  918. return nullDecorator
  919. """
  920. def profileDecorator(f):
  921. def _profiled(*args, **kArgs):
  922. name = '(%s) %s from %s' % (category, f.func_name, f.__module__)
  923. # showbase might not be loaded yet, so don't use
  924. # base.config. Instead, query the ConfigVariableBool.
  925. if (category is None) or ConfigVariableBool('want-profile-%s' % category, 0).getValue():
  926. return profileFunc(Functor(f, *args, **kArgs), name, terse)
  927. else:
  928. return f(*args, **kArgs)
  929. _profiled.__doc__ = f.__doc__
  930. return _profiled
  931. return profileDecorator
  932. # intercept profile-related file operations to avoid disk access
  933. movedOpenFuncs = []
  934. movedDumpFuncs = []
  935. movedLoadFuncs = []
  936. profileFilenames = set()
  937. profileFilenameList = Stack()
  938. profileFilename2file = {}
  939. profileFilename2marshalData = {}
  940. def _profileOpen(filename, *args, **kArgs):
  941. # this is a replacement for the file open() builtin function
  942. # for use during profiling, to intercept the file open
  943. # operation used by the Python profiler and profile stats
  944. # systems
  945. if filename in profileFilenames:
  946. # if this is a file related to profiling, create an
  947. # in-RAM file object
  948. if filename not in profileFilename2file:
  949. file = StringIO()
  950. file._profFilename = filename
  951. profileFilename2file[filename] = file
  952. else:
  953. file = profileFilename2file[filename]
  954. else:
  955. file = movedOpenFuncs[-1](filename, *args, **kArgs)
  956. return file
  957. def _profileMarshalDump(data, file):
  958. # marshal.dump doesn't work with StringIO objects
  959. # simulate it
  960. if isinstance(file, StringIO) and hasattr(file, '_profFilename'):
  961. if file._profFilename in profileFilenames:
  962. profileFilename2marshalData[file._profFilename] = data
  963. return None
  964. return movedDumpFuncs[-1](data, file)
  965. def _profileMarshalLoad(file):
  966. # marshal.load doesn't work with StringIO objects
  967. # simulate it
  968. if isinstance(file, StringIO) and hasattr(file, '_profFilename'):
  969. if file._profFilename in profileFilenames:
  970. return profileFilename2marshalData[file._profFilename]
  971. return movedLoadFuncs[-1](file)
  972. def _installProfileCustomFuncs(filename):
  973. assert filename not in profileFilenames
  974. profileFilenames.add(filename)
  975. profileFilenameList.push(filename)
  976. movedOpenFuncs.append(__builtin__.open)
  977. __builtin__.open = _profileOpen
  978. movedDumpFuncs.append(marshal.dump)
  979. marshal.dump = _profileMarshalDump
  980. movedLoadFuncs.append(marshal.load)
  981. marshal.load = _profileMarshalLoad
  982. def _getProfileResultFileInfo(filename):
  983. return (profileFilename2file.get(filename, None),
  984. profileFilename2marshalData.get(filename, None))
  985. def _setProfileResultsFileInfo(filename, info):
  986. f, m = info
  987. if f:
  988. profileFilename2file[filename] = f
  989. if m:
  990. profileFilename2marshalData[filename] = m
  991. def _clearProfileResultFileInfo(filename):
  992. profileFilename2file.pop(filename, None)
  993. profileFilename2marshalData.pop(filename, None)
  994. def _removeProfileCustomFuncs(filename):
  995. assert profileFilenameList.top() == filename
  996. marshal.load = movedLoadFuncs.pop()
  997. marshal.dump = movedDumpFuncs.pop()
  998. __builtin__.open = movedOpenFuncs.pop()
  999. profileFilenames.remove(filename)
  1000. profileFilenameList.pop()
  1001. profileFilename2file.pop(filename, None)
  1002. # don't let marshalled data pile up
  1003. profileFilename2marshalData.pop(filename, None)
  1004. # call this from the prompt, and break back out to the prompt
  1005. # to stop profiling
  1006. #
  1007. # OR to do inline profiling, you must make a globally-visible
  1008. # function to be profiled, i.e. to profile 'self.load()', do
  1009. # something like this:
  1010. #
  1011. # def func(self=self):
  1012. # self.load()
  1013. # import __builtin__
  1014. # __builtin__.func = func
  1015. # PythonUtil.startProfile(cmd='func()', filename='profileData')
  1016. # del __builtin__.func
  1017. #
  1018. def _profileWithoutGarbageLeak(cmd, filename):
  1019. # The profile module isn't necessarily installed on every Python
  1020. # installation, so we import it here, instead of in the module
  1021. # scope.
  1022. import profile
  1023. # this is necessary because the profile module creates a memory leak
  1024. Profile = profile.Profile
  1025. statement = cmd
  1026. sort = -1
  1027. retVal = None
  1028. #### COPIED FROM profile.run ####
  1029. prof = Profile()
  1030. try:
  1031. prof = prof.run(statement)
  1032. except SystemExit:
  1033. pass
  1034. if filename is not None:
  1035. prof.dump_stats(filename)
  1036. else:
  1037. #return prof.print_stats(sort) #DCR
  1038. retVal = prof.print_stats(sort) #DCR
  1039. #################################
  1040. # eliminate the garbage leak
  1041. del prof.dispatcher
  1042. return retVal
  1043. def startProfile(filename=PyUtilProfileDefaultFilename,
  1044. lines=PyUtilProfileDefaultLines,
  1045. sorts=PyUtilProfileDefaultSorts,
  1046. silent=0,
  1047. callInfo=1,
  1048. useDisk=False,
  1049. cmd='run()'):
  1050. # uniquify the filename to allow multiple processes to profile simultaneously
  1051. filename = '%s.%s%s' % (filename, randUint31(), randUint31())
  1052. if not useDisk:
  1053. # use a RAM file
  1054. _installProfileCustomFuncs(filename)
  1055. _profileWithoutGarbageLeak(cmd, filename)
  1056. if silent:
  1057. extractProfile(filename, lines, sorts, callInfo)
  1058. else:
  1059. printProfile(filename, lines, sorts, callInfo)
  1060. if not useDisk:
  1061. # discard the RAM file
  1062. _removeProfileCustomFuncs(filename)
  1063. else:
  1064. os.remove(filename)
  1065. # call these to see the results again, as a string or in the log
  1066. def printProfile(filename=PyUtilProfileDefaultFilename,
  1067. lines=PyUtilProfileDefaultLines,
  1068. sorts=PyUtilProfileDefaultSorts,
  1069. callInfo=1):
  1070. import pstats
  1071. s = pstats.Stats(filename)
  1072. s.strip_dirs()
  1073. for sort in sorts:
  1074. s.sort_stats(sort)
  1075. s.print_stats(lines)
  1076. if callInfo:
  1077. s.print_callees(lines)
  1078. s.print_callers(lines)
  1079. # same args as printProfile
  1080. def extractProfile(*args, **kArgs):
  1081. global _ProfileResultStr
  1082. # capture print output
  1083. sc = StdoutCapture()
  1084. # print the profile output, redirected to the result string
  1085. printProfile(*args, **kArgs)
  1086. # make a copy of the print output
  1087. _ProfileResultStr = sc.getString()
  1088. # restore stdout to what it was before
  1089. sc.destroy()
  1090. def getSetterName(valueName):
  1091. # getSetterName('color') -> 'setColor'
  1092. # getSetterName('color', 'get') -> 'getColor'
  1093. return '%s%s%s' % (prefix, string.upper(valueName[0]), valueName[1:])
  1094. def getSetter(targetObj, valueName):
  1095. # getSetter(smiley, 'pos') -> smiley.setPos
  1096. return getattr(targetObj, getSetterName(valueName, prefix))
  1097. def mostDerivedLast(classList):
  1098. """pass in list of classes. sorts list in-place, with derived classes
  1099. appearing after their bases"""
  1100. def compare(a, b):
  1101. if issubclass(a, b):
  1102. result=1
  1103. elif issubclass(b, a):
  1104. result=-1
  1105. else:
  1106. result=0
  1107. #print a, b, result
  1108. return result
  1109. classList.sort(compare)
  1110. """
  1111. ParamObj/ParamSet
  1112. =================
  1113. These two classes support you in the definition of a formal set of
  1114. parameters for an object type. The parameters may be safely queried/set on
  1115. an object instance at any time, and the object will react to newly-set
  1116. values immediately.
  1117. ParamSet & ParamObj also provide a mechanism for atomically setting
  1118. multiple parameter values before allowing the object to react to any of the
  1119. new values--useful when two or more parameters are interdependent and there
  1120. is risk of setting an illegal combination in the process of applying a new
  1121. set of values.
  1122. To make use of these classes, derive your object from ParamObj. Then define
  1123. a 'ParamSet' subclass that derives from the parent class' 'ParamSet' class,
  1124. and define the object's parameters within its ParamSet class. (see examples
  1125. below)
  1126. The ParamObj base class provides 'get' and 'set' functions for each
  1127. parameter if they are not defined. These default implementations
  1128. respectively set the parameter value directly on the object, and expect the
  1129. value to be available in that location for retrieval.
  1130. Classes that derive from ParamObj can optionally declare a 'get' and 'set'
  1131. function for each parameter. The setter should simply store the value in a
  1132. location where the getter can find it; it should not do any further
  1133. processing based on the new parameter value. Further processing should be
  1134. implemented in an 'apply' function. The applier function is optional, and
  1135. there is no default implementation.
  1136. NOTE: the previous value of a parameter is available inside an apply
  1137. function as 'self.getPriorValue()'
  1138. The ParamSet class declaration lists the parameters and defines a default
  1139. value for each. ParamSet instances represent a complete set of parameter
  1140. values. A ParamSet instance created with no constructor arguments will
  1141. contain the default values for each parameter. The defaults may be
  1142. overriden by passing keyword arguments to the ParamSet's constructor. If a
  1143. ParamObj instance is passed to the constructor, the ParamSet will extract
  1144. the object's current parameter values.
  1145. ParamSet.applyTo(obj) sets all of its parameter values on 'obj'.
  1146. SETTERS AND APPLIERS
  1147. ====================
  1148. Under normal conditions, a call to a setter function, i.e.
  1149. cam.setFov(90)
  1150. will actually result in the following calls being made:
  1151. cam.setFov(90)
  1152. cam.applyFov()
  1153. Calls to several setter functions, i.e.
  1154. cam.setFov(90)
  1155. cam.setViewType('cutscene')
  1156. will result in this call sequence:
  1157. cam.setFov(90)
  1158. cam.applyFov()
  1159. cam.setViewType('cutscene')
  1160. cam.applyViewType()
  1161. Suppose that you desire the view type to already be set to 'cutscene' at
  1162. the time when applyFov() is called. You could reverse the order of the set
  1163. calls, but suppose that you also want the fov to be set properly at the
  1164. time when applyViewType() is called.
  1165. In this case, you can 'lock' the params, i.e.
  1166. cam.lockParams()
  1167. cam.setFov(90)
  1168. cam.setViewType('cutscene')
  1169. cam.unlockParams()
  1170. This will result in the following call sequence:
  1171. cam.setFov(90)
  1172. cam.setViewType('cutscene')
  1173. cam.applyFov()
  1174. cam.applyViewType()
  1175. NOTE: Currently the order of the apply calls following an unlock is not
  1176. guaranteed.
  1177. EXAMPLE CLASSES
  1178. ===============
  1179. Here is an example of a class that uses ParamSet/ParamObj to manage its
  1180. parameters:
  1181. class Camera(ParamObj):
  1182. class ParamSet(ParamObj.ParamSet):
  1183. Params = {
  1184. 'viewType': 'normal',
  1185. 'fov': 60,
  1186. }
  1187. ...
  1188. def getViewType(self):
  1189. return self.viewType
  1190. def setViewType(self, viewType):
  1191. self.viewType = viewType
  1192. def applyViewType(self):
  1193. if self.viewType == 'normal':
  1194. ...
  1195. def getFov(self):
  1196. return self.fov
  1197. def setFov(self, fov):
  1198. self.fov = fov
  1199. def applyFov(self):
  1200. base.camera.setFov(self.fov)
  1201. ...
  1202. EXAMPLE USAGE
  1203. =============
  1204. cam = Camera()
  1205. ...
  1206. # set up for the cutscene
  1207. savedSettings = cam.ParamSet(cam)
  1208. cam.setViewType('closeup')
  1209. cam.setFov(90)
  1210. ...
  1211. # cutscene is over, set the camera back
  1212. savedSettings.applyTo(cam)
  1213. del savedSettings
  1214. """
  1215. class ParamObj:
  1216. # abstract base for classes that want to support a formal parameter
  1217. # set whose values may be queried, changed, 'bulk' changed (defer reaction
  1218. # to changes until multiple changes have been performed), and
  1219. # extracted/stored/applied all at once (see documentation above)
  1220. # ParamSet subclass: container of parameter values. Derived class must
  1221. # derive a new ParamSet class if they wish to define new params. See
  1222. # documentation above.
  1223. class ParamSet:
  1224. Params = {
  1225. # base class does not define any parameters, but they would
  1226. # appear here as 'name': defaultValue,
  1227. #
  1228. # WARNING: default values of mutable types that do not copy by
  1229. # value (dicts, lists etc.) will be shared by all class instances
  1230. # if default value is callable, it will be called to get actual
  1231. # default value
  1232. #
  1233. # for example:
  1234. #
  1235. # class MapArea(ParamObj):
  1236. # class ParamSet(ParamObj.ParamSet):
  1237. # Params = {
  1238. # 'spawnIndices': Functor(list, [1,5,22]),
  1239. # }
  1240. #
  1241. }
  1242. def __init__(self, *args, **kwArgs):
  1243. self.__class__._compileDefaultParams()
  1244. if len(args) == 1 and len(kwArgs) == 0:
  1245. # extract our params from an existing ParamObj instance
  1246. obj = args[0]
  1247. self.paramVals = {}
  1248. for param in self.getParams():
  1249. self.paramVals[param] = getSetter(obj, param, 'get')()
  1250. else:
  1251. assert len(args) == 0
  1252. if __debug__:
  1253. for arg in kwArgs.keys():
  1254. assert arg in self.getParams()
  1255. self.paramVals = dict(kwArgs)
  1256. def getValue(self, param):
  1257. if param in self.paramVals:
  1258. return self.paramVals[param]
  1259. return self._Params[param]
  1260. def applyTo(self, obj):
  1261. # Apply our entire set of params to a ParamObj
  1262. obj.lockParams()
  1263. for param in self.getParams():
  1264. getSetter(obj, param)(self.getValue(param))
  1265. obj.unlockParams()
  1266. def extractFrom(self, obj):
  1267. # Extract our entire set of params from a ParamObj
  1268. obj.lockParams()
  1269. for param in self.getParams():
  1270. self.paramVals[param] = getSetter(obj, param, 'get')()
  1271. obj.unlockParams()
  1272. @classmethod
  1273. def getParams(cls):
  1274. # returns safely-mutable list of param names
  1275. cls._compileDefaultParams()
  1276. return cls._Params.keys()
  1277. @classmethod
  1278. def getDefaultValue(cls, param):
  1279. cls._compileDefaultParams()
  1280. dv = cls._Params[param]
  1281. if callable(dv):
  1282. dv = dv()
  1283. return dv
  1284. @classmethod
  1285. def _compileDefaultParams(cls):
  1286. if cls.__dict__.has_key('_Params'):
  1287. # we've already compiled the defaults for this class
  1288. return
  1289. bases = list(cls.__bases__)
  1290. # bring less-derived classes to the front
  1291. mostDerivedLast(bases)
  1292. cls._Params = {}
  1293. for c in (bases + [cls]):
  1294. # make sure this base has its dict of param defaults
  1295. c._compileDefaultParams()
  1296. if c.__dict__.has_key('Params'):
  1297. # apply this class' default param values to our dict
  1298. cls._Params.update(c.Params)
  1299. def __repr__(self):
  1300. argStr = ''
  1301. for param in self.getParams():
  1302. argStr += '%s=%s,' % (param,
  1303. repr(self.getValue(param)))
  1304. return '%s.%s(%s)' % (
  1305. self.__class__.__module__, self.__class__.__name__, argStr)
  1306. # END PARAMSET SUBCLASS
  1307. def __init__(self, *args, **kwArgs):
  1308. assert issubclass(self.ParamSet, ParamObj.ParamSet)
  1309. # If you pass in a ParamSet obj, its values will be applied to this
  1310. # object in the constructor.
  1311. params = None
  1312. if len(args) == 1 and len(kwArgs) == 0:
  1313. # if there's one argument, assume that it's a ParamSet
  1314. params = args[0]
  1315. elif len(kwArgs) > 0:
  1316. assert len(args) == 0
  1317. # if we've got keyword arguments, make a ParamSet out of them
  1318. params = self.ParamSet(**kwArgs)
  1319. self._paramLockRefCount = 0
  1320. # these hold the current value of parameters while they are being set to
  1321. # a new value, to support getPriorValue()
  1322. self._curParamStack = []
  1323. self._priorValuesStack = []
  1324. # insert stub funcs for param setters, to handle locked params
  1325. for param in self.ParamSet.getParams():
  1326. # set the default value on the object
  1327. setattr(self, param, self.ParamSet.getDefaultValue(param))
  1328. setterName = getSetterName(param)
  1329. getterName = getSetterName(param, 'get')
  1330. # is there a setter defined?
  1331. if not hasattr(self, setterName):
  1332. # no; provide the default
  1333. def defaultSetter(self, value, param=param):
  1334. #print '%s=%s for %s' % (param, value, id(self))
  1335. setattr(self, param, value)
  1336. self.__class__.__dict__[setterName] = defaultSetter
  1337. # is there a getter defined?
  1338. if not hasattr(self, getterName):
  1339. # no; provide the default. If there is no value set, return
  1340. # the default
  1341. def defaultGetter(self, param=param,
  1342. default=self.ParamSet.getDefaultValue(param)):
  1343. return getattr(self, param, default)
  1344. self.__class__.__dict__[getterName] = defaultGetter
  1345. # have we already installed a setter stub?
  1346. origSetterName = '%s_ORIG' % (setterName,)
  1347. if not hasattr(self, origSetterName):
  1348. # move the original setter aside
  1349. origSetterFunc = getattr(self.__class__, setterName)
  1350. setattr(self.__class__, origSetterName, origSetterFunc)
  1351. """
  1352. # if the setter is a direct member of this instance, move the setter
  1353. # aside
  1354. if setterName in self.__dict__:
  1355. self.__dict__[setterName + '_MOVED'] = self.__dict__[setterName]
  1356. setterFunc = self.__dict__[setterName]
  1357. """
  1358. # install a setter stub that will a) call the real setter and
  1359. # then the applier, or b) call the setter and queue the
  1360. # applier, depending on whether our params are locked
  1361. """
  1362. setattr(self, setterName, new.instancemethod(
  1363. Functor(setterStub, param, setterFunc), self, self.__class__))
  1364. """
  1365. def setterStub(self, value, param=param, origSetterName=origSetterName):
  1366. # should we apply the value now or should we wait?
  1367. # if this obj's params are locked, we track which values have
  1368. # been set, and on unlock, we'll call the applyers for those
  1369. # values
  1370. if self._paramLockRefCount > 0:
  1371. priorValues = self._priorValuesStack[-1]
  1372. if param not in priorValues:
  1373. try:
  1374. priorValue = getSetter(self, param, 'get')()
  1375. except:
  1376. priorValue = None
  1377. priorValues[param] = priorValue
  1378. self._paramsSet[param] = None
  1379. getattr(self, origSetterName)(value)
  1380. else:
  1381. # prepare for call to getPriorValue
  1382. try:
  1383. priorValue = getSetter(self, param, 'get')()
  1384. except:
  1385. priorValue = None
  1386. self._priorValuesStack.append({
  1387. param: priorValue,
  1388. })
  1389. getattr(self, origSetterName)(value)
  1390. # call the applier, if there is one
  1391. applier = getattr(self, getSetterName(param, 'apply'), None)
  1392. if applier is not None:
  1393. self._curParamStack.append(param)
  1394. applier()
  1395. self._curParamStack.pop()
  1396. self._priorValuesStack.pop()
  1397. if hasattr(self, 'handleParamChange'):
  1398. self.handleParamChange((param,))
  1399. setattr(self.__class__, setterName, setterStub)
  1400. if params is not None:
  1401. params.applyTo(self)
  1402. def destroy(self):
  1403. """
  1404. for param in self.ParamSet.getParams():
  1405. setterName = getSetterName(param)
  1406. self.__dict__[setterName].destroy()
  1407. del self.__dict__[setterName]
  1408. """
  1409. pass
  1410. def setDefaultParams(self):
  1411. # set all the default parameters on ourself
  1412. self.ParamSet().applyTo(self)
  1413. def getCurrentParams(self):
  1414. params = self.ParamSet()
  1415. params.extractFrom(self)
  1416. return params
  1417. def lockParams(self):
  1418. self._paramLockRefCount += 1
  1419. if self._paramLockRefCount == 1:
  1420. self._handleLockParams()
  1421. def unlockParams(self):
  1422. if self._paramLockRefCount > 0:
  1423. self._paramLockRefCount -= 1
  1424. if self._paramLockRefCount == 0:
  1425. self._handleUnlockParams()
  1426. def _handleLockParams(self):
  1427. # this will store the names of the parameters that are modified
  1428. self._paramsSet = {}
  1429. # this will store the values of modified params (from prior to
  1430. # the lock).
  1431. self._priorValuesStack.append({})
  1432. def _handleUnlockParams(self):
  1433. for param in self._paramsSet:
  1434. # call the applier, if there is one
  1435. applier = getattr(self, getSetterName(param, 'apply'), None)
  1436. if applier is not None:
  1437. self._curParamStack.append(param)
  1438. applier()
  1439. self._curParamStack.pop()
  1440. self._priorValuesStack.pop()
  1441. if hasattr(self, 'handleParamChange'):
  1442. self.handleParamChange(tuple(self._paramsSet.keys()))
  1443. del self._paramsSet
  1444. def paramsLocked(self):
  1445. return self._paramLockRefCount > 0
  1446. def getPriorValue(self):
  1447. # call this within an apply function to find out what the prior value
  1448. # of the param was
  1449. return self._priorValuesStack[-1][self._curParamStack[-1]]
  1450. def __repr__(self):
  1451. argStr = ''
  1452. for param in self.ParamSet.getParams():
  1453. try:
  1454. value = getSetter(self, param, 'get')()
  1455. except:
  1456. value = '<unknown>'
  1457. argStr += '%s=%s,' % (param, repr(value))
  1458. return '%s(%s)' % (self.__class__.__name__, argStr)
  1459. if __debug__:
  1460. class ParamObjTest(ParamObj):
  1461. class ParamSet(ParamObj.ParamSet):
  1462. Params = {
  1463. 'num': 0,
  1464. }
  1465. def applyNum(self):
  1466. self.priorValue = self.getPriorValue()
  1467. pto = ParamObjTest()
  1468. assert pto.getNum() == 0
  1469. pto.setNum(1)
  1470. assert pto.priorValue == 0
  1471. assert pto.getNum() == 1
  1472. pto.lockParams()
  1473. pto.setNum(2)
  1474. # make sure applyNum is not called until we call unlockParams
  1475. assert pto.priorValue == 0
  1476. assert pto.getNum() == 2
  1477. pto.unlockParams()
  1478. assert pto.priorValue == 1
  1479. assert pto.getNum() == 2
  1480. """
  1481. POD (Plain Ol' Data)
  1482. Like ParamObj/ParamSet, but without lock/unlock/getPriorValue and without
  1483. appliers. Similar to a C++ struct, but with auto-generated setters and
  1484. getters.
  1485. Use POD when you want the generated getters and setters of ParamObj, but
  1486. efficiency is a concern and you don't need the bells and whistles provided
  1487. by ParamObj.
  1488. POD.__init__ *MUST* be called. You should NOT define your own data getters
  1489. and setters. Data values may be read, set, and modified directly. You will
  1490. see no errors if you define your own getters/setters, but there is no
  1491. guarantee that they will be called--and they will certainly be bypassed by
  1492. POD internally.
  1493. EXAMPLE CLASSES
  1494. ===============
  1495. Here is an example of a class heirarchy that uses POD to manage its data:
  1496. class Enemy(POD):
  1497. DataSet = {
  1498. 'faction': 'navy',
  1499. }
  1500. class Sailor(Enemy):
  1501. DataSet = {
  1502. 'build': HUSKY,
  1503. 'weapon': Cutlass(scale=.9),
  1504. }
  1505. EXAMPLE USAGE
  1506. =============
  1507. s = Sailor(faction='undead', build=SKINNY)
  1508. # make two copies of s
  1509. s2 = s.makeCopy()
  1510. s3 = Sailor(s)
  1511. # example sets
  1512. s2.setWeapon(Musket())
  1513. s3.build = TALL
  1514. # example gets
  1515. faction2 = s2.getFaction()
  1516. faction3 = s3.faction
  1517. """
  1518. class POD:
  1519. DataSet = {
  1520. # base class does not define any data items, but they would
  1521. # appear here as 'name': defaultValue,
  1522. #
  1523. # WARNING: default values of mutable types that do not copy by
  1524. # value (dicts, lists etc.) will be shared by all class instances.
  1525. # if default value is callable, it will be called to get actual
  1526. # default value
  1527. #
  1528. # for example:
  1529. #
  1530. # class MapData(POD):
  1531. # DataSet = {
  1532. # 'spawnIndices': Functor(list, [1,5,22]),
  1533. # }
  1534. }
  1535. def __init__(self, **kwArgs):
  1536. self.__class__._compileDefaultDataSet()
  1537. if __debug__:
  1538. # make sure all of the keyword arguments passed in
  1539. # are present in our data set
  1540. for arg in kwArgs.keys():
  1541. assert arg in self.getDataNames(), (
  1542. "unknown argument for %s: '%s'" % (
  1543. self.__class__, arg))
  1544. # assign each of our data items directly to self
  1545. for name in self.getDataNames():
  1546. # if a value has been passed in for a data item, use
  1547. # that value, otherwise use the default value
  1548. if name in kwArgs:
  1549. getSetter(self, name)(kwArgs[name])
  1550. else:
  1551. getSetter(self, name)(self.getDefaultValue(name))
  1552. def setDefaultValues(self):
  1553. # set all the default data values on ourself
  1554. for name in self.getDataNames():
  1555. getSetter(self, name)(self.getDefaultValue(name))
  1556. # this functionality used to be in the constructor, triggered by a single
  1557. # positional argument; that was conflicting with POD subclasses that wanted
  1558. # to define different behavior for themselves when given a positional
  1559. # constructor argument
  1560. def copyFrom(self, other, strict=False):
  1561. # if 'strict' is true, other must have a value for all of our data items
  1562. # otherwise we'll use the defaults
  1563. for name in self.getDataNames():
  1564. if hasattr(other, getSetterName(name, 'get')):
  1565. setattr(self, name, getSetter(other, name, 'get')())
  1566. else:
  1567. if strict:
  1568. raise "object '%s' doesn't have value '%s'" % (other, name)
  1569. else:
  1570. setattr(self, name, self.getDefaultValue(name))
  1571. # support 'p = POD.POD().copyFrom(other)' syntax
  1572. return self
  1573. def makeCopy(self):
  1574. # returns a duplicate of this object
  1575. return self.__class__().copyFrom(self)
  1576. def applyTo(self, obj):
  1577. # Apply our entire set of data to another POD
  1578. for name in self.getDataNames():
  1579. getSetter(obj, name)(getSetter(self, name, 'get')())
  1580. def getValue(self, name):
  1581. return getSetter(self, name, 'get')()
  1582. @classmethod
  1583. def getDataNames(cls):
  1584. # returns safely-mutable list of datum names
  1585. cls._compileDefaultDataSet()
  1586. return cls._DataSet.keys()
  1587. @classmethod
  1588. def getDefaultValue(cls, name):
  1589. cls._compileDefaultDataSet()
  1590. dv = cls._DataSet[name]
  1591. # this allows us to create a new mutable object every time we ask
  1592. # for its default value, i.e. if the default value is dict, this
  1593. # method will return a new empty dictionary object every time. This
  1594. # will cause problems if the intent is to store a callable object
  1595. # as the default value itself; we need a way to specify that the
  1596. # callable *is* the default value and not a default-value creation
  1597. # function
  1598. if callable(dv):
  1599. dv = dv()
  1600. return dv
  1601. @classmethod
  1602. def _compileDefaultDataSet(cls):
  1603. if cls.__dict__.has_key('_DataSet'):
  1604. # we've already compiled the defaults for this class
  1605. return
  1606. # create setters & getters for this class
  1607. if cls.__dict__.has_key('DataSet'):
  1608. for name in cls.DataSet:
  1609. setterName = getSetterName(name)
  1610. if not hasattr(cls, setterName):
  1611. def defaultSetter(self, value, name=name):
  1612. setattr(self, name, value)
  1613. cls.__dict__[setterName] = defaultSetter
  1614. getterName = getSetterName(name, 'get')
  1615. if not hasattr(cls, getterName):
  1616. def defaultGetter(self, name=name):
  1617. return getattr(self, name)
  1618. cls.__dict__[getterName] = defaultGetter
  1619. # this dict will hold all of the aggregated default data values for
  1620. # this particular class, including values from its base classes
  1621. cls._DataSet = {}
  1622. bases = list(cls.__bases__)
  1623. # process in reverse of inheritance order, so that base classes listed first
  1624. # will take precedence over later base classes
  1625. bases.reverse()
  1626. for curBase in bases:
  1627. # skip multiple-inheritance base classes that do not derive from POD
  1628. if issubclass(curBase, POD):
  1629. # make sure this base has its dict of data defaults
  1630. curBase._compileDefaultDataSet()
  1631. # grab all inherited data default values
  1632. cls._DataSet.update(curBase._DataSet)
  1633. # pull in our own class' default values if any are specified
  1634. if 'DataSet' in cls.__dict__:
  1635. cls._DataSet.update(cls.DataSet)
  1636. def __repr__(self):
  1637. argStr = ''
  1638. for name in self.getDataNames():
  1639. argStr += '%s=%s,' % (name, repr(getSetter(self, name, 'get')()))
  1640. return '%s(%s)' % (self.__class__.__name__, argStr)
  1641. if __debug__:
  1642. class PODtest(POD):
  1643. DataSet = {
  1644. 'foo': dict,
  1645. }
  1646. p1 = PODtest()
  1647. p2 = PODtest()
  1648. assert hasattr(p1, 'foo')
  1649. # make sure the getter is working
  1650. assert p1.getFoo() is p1.foo
  1651. p1.getFoo()[1] = 2
  1652. assert p1.foo[1] == 2
  1653. # make sure that each instance gets its own copy of a mutable
  1654. # data item
  1655. assert p1.foo is not p2.foo
  1656. assert len(p1.foo) == 1
  1657. assert len(p2.foo) == 0
  1658. # make sure the setter is working
  1659. p2.setFoo({10:20})
  1660. assert p2.foo[10] == 20
  1661. # make sure modifications to mutable data items don't affect other
  1662. # instances
  1663. assert p1.foo[1] == 2
  1664. class DerivedPOD(PODtest):
  1665. DataSet = {
  1666. 'bar': list,
  1667. }
  1668. d1 = DerivedPOD()
  1669. # make sure that derived instances get their own copy of mutable
  1670. # data items
  1671. assert hasattr(d1, 'foo')
  1672. assert len(d1.foo) == 0
  1673. # make sure derived instances get their own items
  1674. assert hasattr(d1, 'bar')
  1675. assert len(d1.bar) == 0
  1676. def bound(value, bound1, bound2):
  1677. """
  1678. returns value if value is between bound1 and bound2
  1679. otherwise returns bound that is closer to value
  1680. """
  1681. if bound1 > bound2:
  1682. return min(max(value, bound2), bound1)
  1683. else:
  1684. return min(max(value, bound1), bound2)
  1685. def lerp(v0, v1, t):
  1686. """
  1687. returns a value lerped between v0 and v1, according to t
  1688. t == 0 maps to v0, t == 1 maps to v1
  1689. """
  1690. return v0 + ((v1 - v0) * t)
  1691. def getShortestRotation(start, end):
  1692. """
  1693. Given two heading values, return a tuple describing
  1694. the shortest interval from 'start' to 'end'. This tuple
  1695. can be used to lerp a camera between two rotations
  1696. while avoiding the 'spin' problem.
  1697. """
  1698. start, end = start % 360, end % 360
  1699. if abs(end - start) > 180:
  1700. if end < start:
  1701. end += 360
  1702. else:
  1703. start += 360
  1704. return (start, end)
  1705. def average(*args):
  1706. """ returns simple average of list of values """
  1707. val = 0.
  1708. for arg in args:
  1709. val += arg
  1710. return val / len(args)
  1711. class Averager:
  1712. def __init__(self, name):
  1713. self._name = name
  1714. self.reset()
  1715. def reset(self):
  1716. self._total = 0.
  1717. self._count = 0
  1718. def addValue(self, value):
  1719. self._total += value
  1720. self._count += 1
  1721. def getAverage(self):
  1722. return self._total / self._count
  1723. def getCount(self):
  1724. return self._count
  1725. def addListsByValue(a, b):
  1726. """
  1727. returns a new array containing the sums of the two array arguments
  1728. (c[0] = a[0 + b[0], etc.)
  1729. """
  1730. c = []
  1731. for x, y in zip(a, b):
  1732. c.append(x + y)
  1733. return c
  1734. def boolEqual(a, b):
  1735. """
  1736. returns true if a and b are both true or both false.
  1737. returns false otherwise
  1738. (a.k.a. xnor -- eXclusive Not OR).
  1739. """
  1740. return (a and b) or not (a or b)
  1741. def lineupPos(i, num, spacing):
  1742. """
  1743. use to line up a series of 'num' objects, in one dimension,
  1744. centered around zero
  1745. 'i' is the index of the object in the lineup
  1746. 'spacing' is the amount of space between objects in the lineup
  1747. """
  1748. assert num >= 1
  1749. assert i >= 0 and i < num
  1750. pos = float(i) * spacing
  1751. return pos - ((float(spacing) * (num-1))/2.)
  1752. def formatElapsedSeconds(seconds):
  1753. """
  1754. Returns a string of the form "mm:ss" or "hh:mm:ss" or "n days",
  1755. representing the indicated elapsed time in seconds.
  1756. """
  1757. sign = ''
  1758. if seconds < 0:
  1759. seconds = -seconds
  1760. sign = '-'
  1761. # We use math.floor() instead of casting to an int, so we avoid
  1762. # problems with numbers that are too large to represent as
  1763. # type int.
  1764. seconds = math.floor(seconds)
  1765. hours = math.floor(seconds / (60 * 60))
  1766. if hours > 36:
  1767. days = math.floor((hours + 12) / 24)
  1768. return "%s%d days" % (sign, days)
  1769. seconds -= hours * (60 * 60)
  1770. minutes = (int)(seconds / 60)
  1771. seconds -= minutes * 60
  1772. if hours != 0:
  1773. return "%s%d:%02d:%02d" % (sign, hours, minutes, seconds)
  1774. else:
  1775. return "%s%d:%02d" % (sign, minutes, seconds)
  1776. def solveQuadratic(a, b, c):
  1777. # quadratic equation: ax^2 + bx + c = 0
  1778. # quadratic formula: x = [-b +/- sqrt(b^2 - 4ac)] / 2a
  1779. # returns None, root, or [root1, root2]
  1780. # a cannot be zero.
  1781. if a == 0.:
  1782. return None
  1783. # calculate the determinant (b^2 - 4ac)
  1784. D = (b * b) - (4. * a * c)
  1785. if D < 0:
  1786. # there are no solutions (sqrt(negative number) is undefined)
  1787. return None
  1788. elif D == 0:
  1789. # only one root
  1790. return (-b) / (2. * a)
  1791. else:
  1792. # OK, there are two roots
  1793. sqrtD = math.sqrt(D)
  1794. twoA = 2. * a
  1795. root1 = ((-b) - sqrtD) / twoA
  1796. root2 = ((-b) + sqrtD) / twoA
  1797. return [root1, root2]
  1798. def stackEntryInfo(depth=0, baseFileName=1):
  1799. """
  1800. returns the sourcefilename, line number, and function name of
  1801. an entry in the stack.
  1802. 'depth' is how far back to go in the stack; 0 is the caller of this
  1803. function, 1 is the function that called the caller of this function, etc.
  1804. by default, strips off the path of the filename; override with baseFileName
  1805. returns (fileName, lineNum, funcName) --> (string, int, string)
  1806. returns (None, None, None) on error
  1807. """
  1808. try:
  1809. stack = None
  1810. frame = None
  1811. try:
  1812. stack = inspect.stack()
  1813. # add one to skip the frame associated with this function
  1814. frame = stack[depth+1]
  1815. filename = frame[1]
  1816. if baseFileName:
  1817. filename = os.path.basename(filename)
  1818. lineNum = frame[2]
  1819. funcName = frame[3]
  1820. result = (filename, lineNum, funcName)
  1821. finally:
  1822. del stack
  1823. del frame
  1824. except:
  1825. result = (None, None, None)
  1826. return result
  1827. def lineInfo(baseFileName=1):
  1828. """
  1829. returns the sourcefilename, line number, and function name of the
  1830. code that called this function
  1831. (answers the question: 'hey lineInfo, where am I in the codebase?')
  1832. see stackEntryInfo, above, for info on 'baseFileName' and return types
  1833. """
  1834. return stackEntryInfo(1, baseFileName)
  1835. def callerInfo(baseFileName=1, howFarBack=0):
  1836. """
  1837. returns the sourcefilename, line number, and function name of the
  1838. caller of the function that called this function
  1839. (answers the question: 'hey callerInfo, who called me?')
  1840. see stackEntryInfo, above, for info on 'baseFileName' and return types
  1841. """
  1842. return stackEntryInfo(2+howFarBack, baseFileName)
  1843. def lineTag(baseFileName=1, verbose=0, separator=':'):
  1844. """
  1845. returns a string containing the sourcefilename and line number
  1846. of the code that called this function
  1847. (equivalent to lineInfo, above, with different return type)
  1848. see stackEntryInfo, above, for info on 'baseFileName'
  1849. if 'verbose' is false, returns a compact string of the form
  1850. 'fileName:lineNum:funcName'
  1851. if 'verbose' is true, returns a longer string that matches the
  1852. format of Python stack trace dumps
  1853. returns empty string on error
  1854. """
  1855. fileName, lineNum, funcName = callerInfo(baseFileName)
  1856. if fileName is None:
  1857. return ''
  1858. if verbose:
  1859. return 'File "%s", line %s, in %s' % (fileName, lineNum, funcName)
  1860. else:
  1861. return '%s%s%s%s%s' % (fileName, separator, lineNum, separator,
  1862. funcName)
  1863. def findPythonModule(module):
  1864. # Look along the python load path for the indicated filename.
  1865. # Returns the located pathname, or None if the filename is not
  1866. # found.
  1867. filename = module + '.py'
  1868. for dir in sys.path:
  1869. pathname = os.path.join(dir, filename)
  1870. if os.path.exists(pathname):
  1871. return pathname
  1872. return None
  1873. def describeException(backTrace = 4):
  1874. # When called in an exception handler, returns a string describing
  1875. # the current exception.
  1876. def byteOffsetToLineno(code, byte):
  1877. # Returns the source line number corresponding to the given byte
  1878. # offset into the indicated Python code module.
  1879. import array
  1880. lnotab = array.array('B', code.co_lnotab)
  1881. line = code.co_firstlineno
  1882. for i in range(0, len(lnotab), 2):
  1883. byte -= lnotab[i]
  1884. if byte <= 0:
  1885. return line
  1886. line += lnotab[i+1]
  1887. return line
  1888. infoArr = sys.exc_info()
  1889. exception = infoArr[0]
  1890. exceptionName = getattr(exception, '__name__', None)
  1891. extraInfo = infoArr[1]
  1892. trace = infoArr[2]
  1893. stack = []
  1894. while trace.tb_next:
  1895. # We need to call byteOffsetToLineno to determine the true
  1896. # line number at which the exception occurred, even though we
  1897. # have both trace.tb_lineno and frame.f_lineno, which return
  1898. # the correct line number only in non-optimized mode.
  1899. frame = trace.tb_frame
  1900. module = frame.f_globals.get('__name__', None)
  1901. lineno = byteOffsetToLineno(frame.f_code, frame.f_lasti)
  1902. stack.append("%s:%s, " % (module, lineno))
  1903. trace = trace.tb_next
  1904. frame = trace.tb_frame
  1905. module = frame.f_globals.get('__name__', None)
  1906. lineno = byteOffsetToLineno(frame.f_code, frame.f_lasti)
  1907. stack.append("%s:%s, " % (module, lineno))
  1908. description = ""
  1909. for i in range(len(stack) - 1, max(len(stack) - backTrace, 0) - 1, -1):
  1910. description += stack[i]
  1911. description += "%s: %s" % (exceptionName, extraInfo)
  1912. return description
  1913. def clampScalar(value, a, b):
  1914. # calling this ought to be faster than calling both min and max
  1915. if a < b:
  1916. if value < a:
  1917. return a
  1918. elif value > b:
  1919. return b
  1920. else:
  1921. return value
  1922. else:
  1923. if value < b:
  1924. return b
  1925. elif value > a:
  1926. return a
  1927. else:
  1928. return value
  1929. def pivotScalar(scalar, pivot):
  1930. # reflect scalar about pivot; see tests below
  1931. return pivot + (pivot - scalar)
  1932. if __debug__:
  1933. assert pivotScalar(1, 0) == -1
  1934. assert pivotScalar(-1, 0) == 1
  1935. assert pivotScalar(3, 5) == 7
  1936. assert pivotScalar(10, 1) == -8
  1937. def weightedChoice(choiceList, rng=random.random, sum=None):
  1938. """given a list of (weight, item) pairs, chooses an item based on the
  1939. weights. rng must return 0..1. if you happen to have the sum of the
  1940. weights, pass it in 'sum'."""
  1941. # TODO: add support for dicts
  1942. if sum is None:
  1943. sum = 0.
  1944. for weight, item in choiceList:
  1945. sum += weight
  1946. rand = rng()
  1947. accum = rand * sum
  1948. for weight, item in choiceList:
  1949. accum -= weight
  1950. if accum <= 0.:
  1951. return item
  1952. # rand is ~1., and floating-point error prevented accum from hitting 0.
  1953. # Or you passed in a 'sum' that was was too large.
  1954. # Return the last item.
  1955. return item
  1956. def randFloat(a, b=0., rng=random.random):
  1957. """returns a random float in [a, b]
  1958. call with single argument to generate random float between arg and zero
  1959. """
  1960. return lerp(a, b, rng())
  1961. def normalDistrib(a, b, gauss=random.gauss):
  1962. """
  1963. NOTE: assumes a < b
  1964. Returns random number between a and b, using gaussian distribution, with
  1965. mean=avg(a, b), and a standard deviation that fits ~99.7% of the curve
  1966. between a and b.
  1967. For ease of use, outlying results are re-computed until result is in [a, b]
  1968. This should fit the remaining .3% of the curve that lies outside [a, b]
  1969. uniformly onto the curve inside [a, b]
  1970. ------------------------------------------------------------------------
  1971. http://www-stat.stanford.edu/~naras/jsm/NormalDensity/NormalDensity.html
  1972. The 68-95-99.7% Rule
  1973. ====================
  1974. All normal density curves satisfy the following property which is often
  1975. referred to as the Empirical Rule:
  1976. 68% of the observations fall within 1 standard deviation of the mean.
  1977. 95% of the observations fall within 2 standard deviations of the mean.
  1978. 99.7% of the observations fall within 3 standard deviations of the mean.
  1979. Thus, for a normal distribution, almost all values lie within 3 standard
  1980. deviations of the mean.
  1981. ------------------------------------------------------------------------
  1982. In calculating our standard deviation, we divide (b-a) by 6, since the
  1983. 99.7% figure includes 3 standard deviations _on_either_side_ of the mean.
  1984. """
  1985. while True:
  1986. r = gauss((a+b)*.5, (b-a)/6.)
  1987. if (r >= a) and (r <= b):
  1988. return r
  1989. def weightedRand(valDict, rng=random.random):
  1990. """
  1991. pass in a dictionary with a selection -> weight mapping. Eg.
  1992. {"Choice 1": 10,
  1993. "Choice 2": 30,
  1994. "bear": 100}
  1995. -Weights need not add up to any particular value.
  1996. -The actual selection will be returned.
  1997. """
  1998. selections = valDict.keys()
  1999. weights = valDict.values()
  2000. totalWeight = 0
  2001. for weight in weights:
  2002. totalWeight += weight
  2003. # get a random value between 0 and the total of the weights
  2004. randomWeight = rng() * totalWeight
  2005. # find the index that corresponds with this weight
  2006. for i in range(len(weights)):
  2007. totalWeight -= weights[i]
  2008. if totalWeight <= randomWeight:
  2009. return selections[i]
  2010. assert True, "Should never get here"
  2011. return selections[-1]
  2012. def randUint31(rng=random.random):
  2013. """returns a random integer in [0..2^31).
  2014. rng must return float in [0..1]"""
  2015. return int(rng() * 0x7FFFFFFF)
  2016. def randInt32(rng=random.random):
  2017. """returns a random integer in [-2147483648..2147483647].
  2018. rng must return float in [0..1]
  2019. """
  2020. i = int(rng() * 0x7FFFFFFF)
  2021. if rng() < .5:
  2022. i *= -1
  2023. return i
  2024. def randUint32(rng=random.random):
  2025. """returns a random integer in [0..2^32).
  2026. rng must return float in [0..1]"""
  2027. return long(rng() * 0xFFFFFFFFL)
  2028. class SerialNumGen:
  2029. """generates serial numbers"""
  2030. def __init__(self, start=None):
  2031. if start is None:
  2032. start = 0
  2033. self.__counter = start-1
  2034. def next(self):
  2035. self.__counter += 1
  2036. return self.__counter
  2037. _serialGen = SerialNumGen()
  2038. def serialNum():
  2039. global _serialGen
  2040. return _serialGen.next()
  2041. def uniqueName(name):
  2042. global _serialGen
  2043. return '%s-%s' % (name, _serialGen.next())
  2044. class EnumIter:
  2045. def __init__(self, enum):
  2046. self._values = enum._stringTable.keys()
  2047. self._index = 0
  2048. def __iter__(self):
  2049. return self
  2050. def next(self):
  2051. if self._index >= len(self._values):
  2052. raise StopIteration
  2053. self._index += 1
  2054. return self._values[self._index-1]
  2055. class Enum:
  2056. """Pass in list of strings or string of comma-separated strings.
  2057. Items are accessible as instance.item, and are assigned unique,
  2058. increasing integer values. Pass in integer for 'start' to override
  2059. starting value.
  2060. Example:
  2061. >>> colors = Enum('red, green, blue')
  2062. >>> colors.red
  2063. 0
  2064. >>> colors.green
  2065. 1
  2066. >>> colors.blue
  2067. 2
  2068. >>> colors.getString(colors.red)
  2069. 'red'
  2070. """
  2071. if __debug__:
  2072. # chars that cannot appear within an item string.
  2073. InvalidChars = string.whitespace
  2074. def _checkValidIdentifier(item):
  2075. invalidChars = string.whitespace+string.punctuation
  2076. invalidChars = invalidChars.replace('_','')
  2077. invalidFirstChars = invalidChars+string.digits
  2078. if item[0] in invalidFirstChars:
  2079. raise SyntaxError, ("Enum '%s' contains invalid first char" %
  2080. item)
  2081. if not disjoint(item, invalidChars):
  2082. for char in item:
  2083. if char in invalidChars:
  2084. raise SyntaxError, (
  2085. "Enum\n'%s'\ncontains illegal char '%s'" %
  2086. (item, char))
  2087. return 1
  2088. _checkValidIdentifier = staticmethod(_checkValidIdentifier)
  2089. def __init__(self, items, start=0):
  2090. if type(items) == types.StringType:
  2091. items = items.split(',')
  2092. self._stringTable = {}
  2093. # make sure we don't overwrite an existing element of the class
  2094. assert self._checkExistingMembers(items)
  2095. assert uniqueElements(items)
  2096. i = start
  2097. for item in items:
  2098. # remove leading/trailing whitespace
  2099. item = string.strip(item)
  2100. # is there anything left?
  2101. if len(item) == 0:
  2102. continue
  2103. # make sure there are no invalid characters
  2104. assert Enum._checkValidIdentifier(item)
  2105. self.__dict__[item] = i
  2106. self._stringTable[i] = item
  2107. i += 1
  2108. def __iter__(self):
  2109. return EnumIter(self)
  2110. def getString(self, value):
  2111. return self._stringTable[value]
  2112. def __contains__(self, value):
  2113. return value in self._stringTable
  2114. def __len__(self):
  2115. return len(self._stringTable)
  2116. def copyTo(self, obj):
  2117. # copies all members onto obj
  2118. for name, value in self._stringTable:
  2119. setattr(obj, name, value)
  2120. if __debug__:
  2121. def _checkExistingMembers(self, items):
  2122. for item in items:
  2123. if hasattr(self, item):
  2124. return 0
  2125. return 1
  2126. ############################################################
  2127. # class: Singleton
  2128. # Purpose: This provides a base metaclass for all classes
  2129. # that require one and only one instance.
  2130. #
  2131. # Example: class mySingleton:
  2132. # __metaclass__ = PythonUtil.Singleton
  2133. # def __init__(self, ...):
  2134. # ...
  2135. #
  2136. # Note: This class is based on Python's New-Style Class
  2137. # design. An error will occur if a defined class
  2138. # attemps to inherit from a Classic-Style Class only,
  2139. # ie: class myClassX:
  2140. # def __init__(self, ...):
  2141. # ...
  2142. #
  2143. # class myNewClassX(myClassX):
  2144. # __metaclass__ = PythonUtil.Singleton
  2145. # def __init__(self, ...):
  2146. # myClassX.__init__(self, ...)
  2147. # ...
  2148. #
  2149. # This causes problems because myNewClassX is a
  2150. # New-Style class that inherits from only a
  2151. # Classic-Style base class. There are two ways
  2152. # simple ways to resolve this issue.
  2153. #
  2154. # First, if possible, make myClassX a
  2155. # New-Style class by inheriting from object
  2156. # object. IE: class myClassX(object):
  2157. #
  2158. # If for some reason that is not an option, make
  2159. # myNewClassX inherit from object and myClassX.
  2160. # IE: class myNewClassX(object, myClassX):
  2161. ############################################################
  2162. class Singleton(type):
  2163. def __init__(cls, name, bases, dic):
  2164. super(Singleton, cls).__init__(name, bases, dic)
  2165. cls.instance=None
  2166. def __call__(cls, *args, **kw):
  2167. if cls.instance is None:
  2168. cls.instance=super(Singleton, cls).__call__(*args, **kw)
  2169. return cls.instance
  2170. class SingletonError(ValueError):
  2171. """ Used to indicate an inappropriate value for a Singleton."""
  2172. def printListEnumGen(l):
  2173. # log each individual item with a number in front of it
  2174. digits = 0
  2175. n = len(l)
  2176. while n > 0:
  2177. digits += 1
  2178. n /= 10
  2179. format = '%0' + '%s' % digits + 'i:%s'
  2180. for i in range(len(l)):
  2181. print format % (i, l[i])
  2182. yield None
  2183. def printListEnum(l):
  2184. for result in printListEnumGen(l):
  2185. pass
  2186. # base class for all Panda C++ objects
  2187. # libdtoolconfig doesn't seem to have this, grab it off of PandaNode
  2188. dtoolSuperBase = None
  2189. def _getDtoolSuperBase():
  2190. global dtoolSuperBase
  2191. from pandac.PandaModules import PandaNode
  2192. dtoolSuperBase = PandaNode('').__class__.__bases__[0].__bases__[0].__bases__[0]
  2193. assert repr(dtoolSuperBase) == "<type 'libdtoolconfig.DTOOL_SUPPER_BASE111'>"
  2194. safeReprNotify = None
  2195. def _getSafeReprNotify():
  2196. global safeReprNotify
  2197. from direct.directnotify.DirectNotifyGlobal import directNotify
  2198. safeReprNotify = directNotify.newCategory("safeRepr")
  2199. def safeRepr(obj):
  2200. global dtoolSuperBase
  2201. if dtoolSuperBase is None:
  2202. _getDtoolSuperBase()
  2203. global safeReprNotify
  2204. if safeReprNotify is None:
  2205. _getSafeReprNotify()
  2206. if isinstance(obj, dtoolSuperBase):
  2207. # repr of C++ object could crash, particularly if the object has been deleted
  2208. # log that we're calling repr
  2209. safeReprNotify.info('calling repr on instance of %s.%s' % (obj.__class__.__module__, obj.__class__.__name__))
  2210. sys.stdout.flush()
  2211. try:
  2212. return repr(obj)
  2213. except:
  2214. return '<** FAILED REPR OF %s instance at %s **>' % (obj.__class__.__name__, hex(id(obj)))
  2215. def safeReprTypeOnFail(obj):
  2216. global dtoolSuperBase
  2217. if dtoolSuperBase is None:
  2218. _getDtoolSuperBase()
  2219. global safeReprNotify
  2220. if safeReprNotify is None:
  2221. _getSafeReprNotify()
  2222. if isinstance(obj, dtoolSuperBase):
  2223. return type(obj)
  2224. try:
  2225. return repr(obj)
  2226. except:
  2227. return '<** FAILED REPR OF %s instance at %s **>' % (obj.__class__.__name__, hex(id(obj)))
  2228. def fastRepr(obj, maxLen=200, strFactor=10, _visitedIds=None):
  2229. """ caps the length of iterable types, so very large objects will print faster.
  2230. also prevents infinite recursion """
  2231. try:
  2232. if _visitedIds is None:
  2233. _visitedIds = set()
  2234. if id(obj) in _visitedIds:
  2235. return '<ALREADY-VISITED %s>' % itype(obj)
  2236. if type(obj) in (types.TupleType, types.ListType):
  2237. s = ''
  2238. s += {types.TupleType: '(',
  2239. types.ListType: '[',}[type(obj)]
  2240. if maxLen is not None and len(obj) > maxLen:
  2241. o = obj[:maxLen]
  2242. ellips = '...'
  2243. else:
  2244. o = obj
  2245. ellips = ''
  2246. _visitedIds.add(id(obj))
  2247. for item in o:
  2248. s += fastRepr(item, maxLen, _visitedIds=_visitedIds)
  2249. s += ', '
  2250. _visitedIds.remove(id(obj))
  2251. s += ellips
  2252. s += {types.TupleType: ')',
  2253. types.ListType: ']',}[type(obj)]
  2254. return s
  2255. elif type(obj) is types.DictType:
  2256. s = '{'
  2257. if maxLen is not None and len(obj) > maxLen:
  2258. o = obj.keys()[:maxLen]
  2259. ellips = '...'
  2260. else:
  2261. o = obj.keys()
  2262. ellips = ''
  2263. _visitedIds.add(id(obj))
  2264. for key in o:
  2265. value = obj[key]
  2266. s += '%s: %s, ' % (fastRepr(key, maxLen, _visitedIds=_visitedIds),
  2267. fastRepr(value, maxLen, _visitedIds=_visitedIds))
  2268. _visitedIds.remove(id(obj))
  2269. s += ellips
  2270. s += '}'
  2271. return s
  2272. elif type(obj) is types.StringType:
  2273. if maxLen is not None:
  2274. maxLen *= strFactor
  2275. if maxLen is not None and len(obj) > maxLen:
  2276. return safeRepr(obj[:maxLen])
  2277. else:
  2278. return safeRepr(obj)
  2279. else:
  2280. r = safeRepr(obj)
  2281. maxLen *= strFactor
  2282. if len(r) > maxLen:
  2283. r = r[:maxLen]
  2284. return r
  2285. except:
  2286. return '<** FAILED REPR OF %s **>' % obj.__class__.__name__
  2287. def tagRepr(obj, tag):
  2288. """adds a string onto the repr output of an instance"""
  2289. def reprWithTag(oldRepr, tag, self):
  2290. return oldRepr() + '::<TAG=' + tag + '>'
  2291. oldRepr = getattr(obj, '__repr__', None)
  2292. if oldRepr is None:
  2293. def stringer(s):
  2294. return s
  2295. oldRepr = Functor(stringer, repr(obj))
  2296. stringer = None
  2297. obj.__repr__ = new.instancemethod(Functor(reprWithTag, oldRepr, tag), obj, obj.__class__)
  2298. reprWithTag = None
  2299. return obj
  2300. def tagWithCaller(obj):
  2301. """add info about the caller of the caller"""
  2302. tagRepr(obj, str(callerInfo(howFarBack=1)))
  2303. def isDefaultValue(x):
  2304. return x == type(x)()
  2305. def notNone(A, B):
  2306. # returns A if not None, B otherwise
  2307. if A is None:
  2308. return B
  2309. return A
  2310. def appendStr(obj, st):
  2311. """adds a string onto the __str__ output of an instance"""
  2312. def appendedStr(oldStr, st, self):
  2313. return oldStr() + st
  2314. oldStr = getattr(obj, '__str__', None)
  2315. if oldStr is None:
  2316. def stringer(s):
  2317. return s
  2318. oldStr = Functor(stringer, str(obj))
  2319. stringer = None
  2320. obj.__str__ = new.instancemethod(Functor(appendedStr, oldStr, st), obj, obj.__class__)
  2321. appendedStr = None
  2322. return obj
  2323. # convenience shortcuts for __dev__ debugging
  2324. # we don't have the __dev__ flag at this point
  2325. try:
  2326. import pdb
  2327. set_trace = pdb.set_trace
  2328. # set_trace that can be asserted
  2329. def setTrace():
  2330. set_trace()
  2331. return True
  2332. pm = pdb.pm
  2333. except:
  2334. # we're in production, there is no pdb module. assign these to something so that the
  2335. # __builtin__ exports will work
  2336. # references in the code should either be if __dev__'d or asserted
  2337. set_trace = None
  2338. setTrace = None
  2339. pm = None
  2340. class ScratchPad:
  2341. """empty class to stick values onto"""
  2342. def __init__(self, **kArgs):
  2343. for key, value in kArgs.iteritems():
  2344. setattr(self, key, value)
  2345. self._keys = set(kArgs.keys())
  2346. def add(self, **kArgs):
  2347. for key, value in kArgs.iteritems():
  2348. setattr(self, key, value)
  2349. self._keys.update(kArgs.keys())
  2350. def destroy(self):
  2351. for key in self._keys:
  2352. delattr(self, key)
  2353. class DestructiveScratchPad(ScratchPad):
  2354. # automatically calls destroy() on elements passed to __init__
  2355. def add(self, **kArgs):
  2356. for key, value in kArgs.iteritems():
  2357. if hasattr(self, key):
  2358. getattr(self, key).destroy()
  2359. setattr(self, key, value)
  2360. self._keys.update(kArgs.keys())
  2361. def destroy(self):
  2362. for key in self._keys:
  2363. getattr(self, key).destroy()
  2364. ScratchPad.destroy(self)
  2365. class Sync:
  2366. _SeriesGen = SerialNumGen()
  2367. def __init__(self, name, other=None):
  2368. self._name = name
  2369. if other is None:
  2370. self._series = self._SeriesGen.next()
  2371. self._value = 0
  2372. else:
  2373. self._series = other._series
  2374. self._value = other._value
  2375. def invalidate(self):
  2376. self._value = None
  2377. def change(self):
  2378. self._value += 1
  2379. def sync(self, other):
  2380. if (self._series != other._series) or (self._value != other._value):
  2381. self._series = other._series
  2382. self._value = other._value
  2383. return True
  2384. else:
  2385. return False
  2386. def isSynced(self, other):
  2387. return ((self._series == other._series) and
  2388. (self._value == other._value))
  2389. def __repr__(self):
  2390. return '%s(%s)<family=%s,value=%s>' % (self.__class__.__name__,
  2391. self._name, self._series, self._value)
  2392. class RefCounter:
  2393. def __init__(self, byId=False):
  2394. self._byId = byId
  2395. self._refCounts = {}
  2396. def _getKey(self, item):
  2397. if self._byId:
  2398. key = id(item)
  2399. else:
  2400. key = item
  2401. def inc(self, item):
  2402. key = self._getKey(item)
  2403. self._refCounts.setdefault(key, 0)
  2404. self._refCounts[key] += 1
  2405. def dec(self, item):
  2406. """returns True if ref count has hit zero"""
  2407. key = self._getKey(item)
  2408. self._refCounts[key] -= 1
  2409. result = False
  2410. if self._refCounts[key] == 0:
  2411. result = True
  2412. del self._refCounts[key]
  2413. return result
  2414. def itype(obj):
  2415. # version of type that gives more complete information about instance types
  2416. global dtoolSuperBase
  2417. t = type(obj)
  2418. if t is types.InstanceType:
  2419. return '%s of <class %s>>' % (repr(types.InstanceType)[:-1],
  2420. str(obj.__class__))
  2421. else:
  2422. # C++ object instances appear to be types via type()
  2423. # check if this is a C++ object
  2424. if dtoolSuperBase is None:
  2425. _getDtoolSuperBase()
  2426. if isinstance(obj, dtoolSuperBase):
  2427. return '%s of %s>' % (repr(types.InstanceType)[:-1],
  2428. str(obj.__class__))
  2429. return t
  2430. def deeptype(obj, maxLen=100, _visitedIds=None):
  2431. if _visitedIds is None:
  2432. _visitedIds = set()
  2433. if id(obj) in _visitedIds:
  2434. return '<ALREADY-VISITED %s>' % itype(obj)
  2435. t = type(obj)
  2436. if t in (types.TupleType, types.ListType):
  2437. s = ''
  2438. s += {types.TupleType: '(',
  2439. types.ListType: '[',}[type(obj)]
  2440. if maxLen is not None and len(obj) > maxLen:
  2441. o = obj[:maxLen]
  2442. ellips = '...'
  2443. else:
  2444. o = obj
  2445. ellips = ''
  2446. _visitedIds.add(id(obj))
  2447. for item in o:
  2448. s += deeptype(item, maxLen, _visitedIds=_visitedIds)
  2449. s += ', '
  2450. _visitedIds.remove(id(obj))
  2451. s += ellips
  2452. s += {types.TupleType: ')',
  2453. types.ListType: ']',}[type(obj)]
  2454. return s
  2455. elif type(obj) is types.DictType:
  2456. s = '{'
  2457. if maxLen is not None and len(obj) > maxLen:
  2458. o = obj.keys()[:maxLen]
  2459. ellips = '...'
  2460. else:
  2461. o = obj.keys()
  2462. ellips = ''
  2463. _visitedIds.add(id(obj))
  2464. for key in o:
  2465. value = obj[key]
  2466. s += '%s: %s, ' % (deeptype(key, maxLen, _visitedIds=_visitedIds),
  2467. deeptype(value, maxLen, _visitedIds=_visitedIds))
  2468. _visitedIds.remove(id(obj))
  2469. s += ellips
  2470. s += '}'
  2471. return s
  2472. else:
  2473. return str(itype(obj))
  2474. def getNumberedTypedString(items, maxLen=5000, numPrefix=''):
  2475. """get a string that has each item of the list on its own line,
  2476. and each item is numbered on the left from zero"""
  2477. digits = 0
  2478. n = len(items)
  2479. while n > 0:
  2480. digits += 1
  2481. n /= 10
  2482. digits = digits
  2483. format = numPrefix + '%0' + '%s' % digits + 'i:%s \t%s'
  2484. first = True
  2485. s = ''
  2486. snip = '<SNIP>'
  2487. for i in xrange(len(items)):
  2488. if not first:
  2489. s += '\n'
  2490. first = False
  2491. objStr = fastRepr(items[i])
  2492. if len(objStr) > maxLen:
  2493. objStr = '%s%s' % (objStr[:(maxLen-len(snip))], snip)
  2494. s += format % (i, itype(items[i]), objStr)
  2495. return s
  2496. def getNumberedTypedSortedString(items, maxLen=5000, numPrefix=''):
  2497. """get a string that has each item of the list on its own line,
  2498. the items are stringwise-sorted, and each item is numbered on
  2499. the left from zero"""
  2500. digits = 0
  2501. n = len(items)
  2502. while n > 0:
  2503. digits += 1
  2504. n /= 10
  2505. digits = digits
  2506. format = numPrefix + '%0' + '%s' % digits + 'i:%s \t%s'
  2507. snip = '<SNIP>'
  2508. strs = []
  2509. for item in items:
  2510. objStr = fastRepr(item)
  2511. if len(objStr) > maxLen:
  2512. objStr = '%s%s' % (objStr[:(maxLen-len(snip))], snip)
  2513. strs.append(objStr)
  2514. first = True
  2515. s = ''
  2516. strs.sort()
  2517. for i in xrange(len(strs)):
  2518. if not first:
  2519. s += '\n'
  2520. first = False
  2521. objStr = strs[i]
  2522. s += format % (i, itype(items[i]), strs[i])
  2523. return s
  2524. def getNumberedTypedSortedStringWithReferrersGen(items, maxLen=10000, numPrefix=''):
  2525. """get a string that has each item of the list on its own line,
  2526. the items are stringwise-sorted, the object's referrers are shown,
  2527. and each item is numbered on the left from zero"""
  2528. digits = 0
  2529. n = len(items)
  2530. while n > 0:
  2531. digits += 1
  2532. n /= 10
  2533. digits = digits
  2534. format = numPrefix + '%0' + '%s' % digits + 'i:%s @ %s \t%s'
  2535. snip = '<SNIP>'
  2536. strs = []
  2537. for item in items:
  2538. strs.append(fastRepr(item))
  2539. strs.sort()
  2540. for i in xrange(len(strs)):
  2541. item = items[i]
  2542. objStr = strs[i]
  2543. objStr += ', \tREFERRERS=['
  2544. referrers = gc.get_referrers(item)
  2545. for ref in referrers:
  2546. objStr += '%s@%s, ' % (itype(ref), id(ref))
  2547. objStr += ']'
  2548. if len(objStr) > maxLen:
  2549. objStr = '%s%s' % (objStr[:(maxLen-len(snip))], snip)
  2550. yield format % (i, itype(items[i]), id(items[i]), objStr)
  2551. def getNumberedTypedSortedStringWithReferrers(items, maxLen=10000, numPrefix=''):
  2552. """get a string that has each item of the list on its own line,
  2553. the items are stringwise-sorted, the object's referrers are shown,
  2554. and each item is numbered on the left from zero"""
  2555. s = ''
  2556. for line in getNumberedTypedSortedStringWithReferrersGen(items, maxLen, numPrefix):
  2557. s += '%s\n' % line
  2558. return s
  2559. def printNumberedTyped(items, maxLen=5000):
  2560. """print out each item of the list on its own line,
  2561. with each item numbered on the left from zero"""
  2562. digits = 0
  2563. n = len(items)
  2564. while n > 0:
  2565. digits += 1
  2566. n /= 10
  2567. digits = digits
  2568. format = '%0' + '%s' % digits + 'i:%s \t%s'
  2569. for i in xrange(len(items)):
  2570. objStr = fastRepr(items[i])
  2571. if len(objStr) > maxLen:
  2572. snip = '<SNIP>'
  2573. objStr = '%s%s' % (objStr[:(maxLen-len(snip))], snip)
  2574. print format % (i, itype(items[i]), objStr)
  2575. def printNumberedTypesGen(items, maxLen=5000):
  2576. digits = 0
  2577. n = len(items)
  2578. while n > 0:
  2579. digits += 1
  2580. n /= 10
  2581. digits = digits
  2582. format = '%0' + '%s' % digits + 'i:%s'
  2583. for i in xrange(len(items)):
  2584. print format % (i, itype(items[i]))
  2585. yield None
  2586. def printNumberedTypes(items, maxLen=5000):
  2587. """print out the type of each item of the list on its own line,
  2588. with each item numbered on the left from zero"""
  2589. for result in printNumberedTypesGen(items, maxLen):
  2590. yield result
  2591. class DelayedCall:
  2592. """ calls a func after a specified delay """
  2593. def __init__(self, func, name=None, delay=None):
  2594. if name is None:
  2595. name = 'anonymous'
  2596. if delay is None:
  2597. delay = .01
  2598. self._func = func
  2599. self._taskName = 'DelayedCallback-%s' % name
  2600. self._delay = delay
  2601. self._finished = False
  2602. self._addDoLater()
  2603. def destroy(self):
  2604. self._finished = True
  2605. self._removeDoLater()
  2606. def finish(self):
  2607. if not self._finished:
  2608. self._doCallback()
  2609. self.destroy()
  2610. def _addDoLater(self):
  2611. taskMgr.doMethodLater(self._delay, self._doCallback, self._taskName)
  2612. def _removeDoLater(self):
  2613. taskMgr.remove(self._taskName)
  2614. def _doCallback(self, task):
  2615. self._finished = True
  2616. func = self._func
  2617. del self._func
  2618. func()
  2619. class FrameDelayedCall:
  2620. """ calls a func after N frames """
  2621. def __init__(self, name, callback, frames=None, cancelFunc=None):
  2622. # checkFunc is optional; called every frame, if returns True, FrameDelay is cancelled
  2623. # and callback is not called
  2624. if frames is None:
  2625. frames = 1
  2626. self._name = name
  2627. self._frames = frames
  2628. self._callback = callback
  2629. self._cancelFunc = cancelFunc
  2630. self._taskName = uniqueName('%s-%s' % (self.__class__.__name__, self._name))
  2631. self._finished = False
  2632. self._startTask()
  2633. def destroy(self):
  2634. self._finished = True
  2635. self._stopTask()
  2636. def finish(self):
  2637. if not self._finished:
  2638. self._finished = True
  2639. self._callback()
  2640. self.destroy()
  2641. def _startTask(self):
  2642. taskMgr.add(self._frameTask, self._taskName)
  2643. self._counter = 0
  2644. def _stopTask(self):
  2645. taskMgr.remove(self._taskName)
  2646. def _frameTask(self, task):
  2647. if self._cancelFunc and self._cancelFunc():
  2648. self.destroy()
  2649. return task.done
  2650. self._counter += 1
  2651. if self._counter >= self._frames:
  2652. self.finish()
  2653. return task.done
  2654. return task.cont
  2655. class DelayedFunctor:
  2656. """ Waits for this object to be called, then calls supplied functor after a delay.
  2657. Effectively inserts a time delay between the caller and the functor. """
  2658. def __init__(self, functor, name=None, delay=None):
  2659. self._functor = functor
  2660. self._name = name
  2661. # FunctionInterval requires __name__
  2662. self.__name__ = self._name
  2663. self._delay = delay
  2664. def _callFunctor(self):
  2665. cb = Functor(self._functor, *self._args, **self._kwArgs)
  2666. del self._functor
  2667. del self._name
  2668. del self._delay
  2669. del self._args
  2670. del self._kwArgs
  2671. del self._delayedCall
  2672. del self.__name__
  2673. cb()
  2674. def __call__(self, *args, **kwArgs):
  2675. self._args = args
  2676. self._kwArgs = kwArgs
  2677. self._delayedCall = DelayedCall(self._callFunctor, self._name, self._delay)
  2678. class SubframeCall:
  2679. """Calls a callback at a specific time during the frame using the
  2680. task system"""
  2681. def __init__(self, functor, taskPriority, name=None):
  2682. self._functor = functor
  2683. self._name = name
  2684. self._taskName = uniqueName('SubframeCall-%s' % self._name)
  2685. taskMgr.add(self._doCallback,
  2686. self._taskName,
  2687. priority=taskPriority)
  2688. def _doCallback(self, task):
  2689. functor = self._functor
  2690. del self._functor
  2691. functor()
  2692. del self._name
  2693. self._taskName = None
  2694. return task.done
  2695. def cleanup(self):
  2696. if (self._taskName):
  2697. taskMgr.remove(self._taskName)
  2698. self._taskName = None
  2699. class ArgumentEater:
  2700. def __init__(self, numToEat, func):
  2701. self._numToEat = numToEat
  2702. self._func = func
  2703. def destroy(self):
  2704. del self._func
  2705. def __call__(self, *args, **kwArgs):
  2706. self._func(*args[self._numToEat:], **kwArgs)
  2707. class ClassTree:
  2708. def __init__(self, instanceOrClass):
  2709. if type(instanceOrClass) in (types.ClassType, types.TypeType):
  2710. cls = instanceOrClass
  2711. else:
  2712. cls = instanceOrClass.__class__
  2713. self._cls = cls
  2714. self._bases = []
  2715. for base in self._cls.__bases__:
  2716. if base not in (types.ObjectType, types.TypeType):
  2717. self._bases.append(ClassTree(base))
  2718. def getAllClasses(self):
  2719. # returns set of this class and all base classes
  2720. classes = set()
  2721. classes.add(self._cls)
  2722. for base in self._bases:
  2723. classes.update(base.getAllClasses())
  2724. return classes
  2725. def _getStr(self, indent=None, clsLeftAtIndent=None):
  2726. # indent is how far to the right to indent (i.e. how many levels
  2727. # deep in the hierarchy from the most-derived)
  2728. #
  2729. # clsLeftAtIndent is an array of # of classes left to be
  2730. # printed at each level of the hierarchy; most-derived is
  2731. # at index 0
  2732. if indent is None:
  2733. indent = 0
  2734. clsLeftAtIndent = [1]
  2735. s = ''
  2736. if (indent > 1):
  2737. for i in range(1, indent):
  2738. # if we have not printed all base classes at
  2739. # this indent level, keep printing the vertical
  2740. # column
  2741. if clsLeftAtIndent[i] > 0:
  2742. s += ' |'
  2743. else:
  2744. s += ' '
  2745. if (indent > 0):
  2746. s += ' +'
  2747. s += self._cls.__name__
  2748. clsLeftAtIndent[indent] -= 1
  2749. """
  2750. ### show the module to the right of the class name
  2751. moduleIndent = 48
  2752. if len(s) >= moduleIndent:
  2753. moduleIndent = (len(s) % 4) + 4
  2754. padding = moduleIndent - len(s)
  2755. s += padding * ' '
  2756. s += self._cls.__module__
  2757. ###
  2758. """
  2759. if len(self._bases):
  2760. newList = list(clsLeftAtIndent)
  2761. newList.append(len(self._bases))
  2762. bases = self._bases
  2763. # print classes with fewer bases first
  2764. bases.sort(lambda x,y: len(x._bases)-len(y._bases))
  2765. for base in bases:
  2766. s += '\n%s' % base._getStr(indent+1, newList)
  2767. return s
  2768. def __repr__(self):
  2769. return self._getStr()
  2770. def report(types = [], xform = None, notifyFunc = None, dConfigParam = []):
  2771. """
  2772. This is a decorator generating function. Use is similar to
  2773. a @decorator, except you must be sure to call it as a function.
  2774. It actually returns the decorator which is then used to transform
  2775. your decorated function. Confusing at first, I know.
  2776. Decoration occurs at function definition time.
  2777. If __dev__ is not defined, or resolves to False, this function
  2778. has no effect and no wrapping/transform occurs. So in production,
  2779. it's as if the report has been asserted out.
  2780. Parameters::
  2781. types : A subset list of ['timeStamp', 'frameCount', 'avLocation']
  2782. This allows you to specify certain useful bits of info.
  2783. module: Prints the module that this report statement
  2784. can be found in.
  2785. args: Prints the arguments as they were passed to
  2786. this function.
  2787. timeStamp: Adds the current frame time to the output.
  2788. deltaStamp: Adds the current AI synched frame time to
  2789. the output
  2790. frameCount: Adds the current frame count to the output.
  2791. Usually cleaner than the timeStamp output.
  2792. avLocation: Adds the localAvatar's network location
  2793. to the output. Useful for interest debugging.
  2794. interests: Prints the current interest state after the
  2795. report.
  2796. stackTrace: Prints a stack trace after the report.
  2797. prefix: Optional string to prepend to output, just before the function.
  2798. Allows for easy grepping and is useful when merging AI/Client
  2799. reports into a single file.
  2800. notifyFunc: A notify function such as info, debug, warning, etc.
  2801. By default the report will be printed to stdout. This
  2802. will allow you send the report to a designated 'notify'
  2803. output.
  2804. dConfigParam: A list of Config.prc string variables.
  2805. By default the report will always print. If you
  2806. specify this param, it will only print if one of the
  2807. specified config strings resolve to True.
  2808. """
  2809. def decorator(f):
  2810. return f
  2811. try:
  2812. if not (__dev__ or config.GetBool('force-reports', 0)):
  2813. return decorator
  2814. # determine whether we should use the decorator
  2815. # based on the value of dConfigParam.
  2816. doPrint = False
  2817. if not dConfigParam:
  2818. doPrint = True
  2819. else:
  2820. if not isinstance(dConfigParam, (list,tuple)):
  2821. dConfigParamList = (dConfigParam,)
  2822. else:
  2823. dConfigParamList = dConfigParam
  2824. dConfigParamList = [param for param in dConfigParamList \
  2825. if config.GetBool('want-%s-report' % (param,), 0)]
  2826. doPrint = bool(dConfigParamList)
  2827. pass
  2828. if not doPrint:
  2829. return decorator
  2830. # Determine any prefixes defined in our Config.prc.
  2831. if prefix:
  2832. prefixes = set([prefix])
  2833. else:
  2834. prefixes = set()
  2835. pass
  2836. for param in dConfigParamList:
  2837. prefix = config.GetString('prefix-%s-report' % (param,), '')
  2838. if prefix:
  2839. prefixes.add(prefix)
  2840. pass
  2841. pass
  2842. except NameError,e:
  2843. return decorator
  2844. from direct.distributed.ClockDelta import globalClockDelta
  2845. def decorator(f):
  2846. def wrap(*args,**kwargs):
  2847. if args:
  2848. rArgs = [args[0].__class__.__name__ + ', ']
  2849. else:
  2850. rArgs = []
  2851. if 'args' in types:
  2852. rArgs += [`x`+', ' for x in args[1:]] + \
  2853. [ x + ' = ' + '%s, ' % `y` for x,y in kwargs.items()]
  2854. if not rArgs:
  2855. rArgs = '()'
  2856. else:
  2857. rArgs = '(' + reduce(str.__add__,rArgs)[:-2] + ')'
  2858. outStr = '%s%s' % (f.func_name, rArgs)
  2859. # Insert prefix place holder, if needed
  2860. if prefixes:
  2861. outStr = '%%s %s' % (outStr,)
  2862. preStr = ''
  2863. if 'module' in types:
  2864. outStr = '%s {M:%s}' % (outStr, f.__module__.split('.')[-1])
  2865. if 'frameCount' in types:
  2866. outStr = '%8d : %s' % (globalClock.getFrameCount(), outStr)
  2867. if 'timeStamp' in types:
  2868. outStr = '%8.3f : %s' % (globalClock.getFrameTime(), outStr)
  2869. if 'deltaStamp' in types:
  2870. outStr = '%8.2f : %s' % (globalClock.getRealTime() - \
  2871. globalClockDelta.delta, outStr)
  2872. if 'avLocation' in types:
  2873. outStr = '%s : %s' % (outStr, str(localAvatar.getLocation()))
  2874. if xform:
  2875. outStr = '%s : %s' % (outStr, xform(args[0]))
  2876. if prefixes:
  2877. for prefix in prefixes:
  2878. if notifyFunc:
  2879. notifyFunc(outStr % (prefix,))
  2880. else:
  2881. print outStr % (prefix,)
  2882. else:
  2883. if notifyFunc:
  2884. notifyFunc(outStr)
  2885. else:
  2886. print outStr
  2887. if 'interests' in types:
  2888. base.cr.printInterestSets()
  2889. if 'stackTrace' in types:
  2890. print StackTrace()
  2891. return f(*args,**kwargs)
  2892. wrap.func_name = f.func_name
  2893. wrap.func_dict = f.func_dict
  2894. wrap.func_doc = f.func_doc
  2895. wrap.__module__ = f.__module__
  2896. return wrap
  2897. return decorator
  2898. def getBase():
  2899. try:
  2900. return base
  2901. except:
  2902. return simbase
  2903. def getRepository():
  2904. try:
  2905. return base.cr
  2906. except:
  2907. return simbase.air
  2908. exceptionLoggedNotify = None
  2909. def exceptionLogged(append=True):
  2910. """decorator that outputs the function name and all arguments
  2911. if an exception passes back through the stack frame
  2912. if append is true, string is appended to the __str__ output of
  2913. the exception. if append is false, string is printed to the log
  2914. directly. If the output will take up many lines, it's recommended
  2915. to set append to False so that the exception stack is not hidden
  2916. by the output of this decorator.
  2917. """
  2918. try:
  2919. null = not __dev__
  2920. except:
  2921. null = not __debug__
  2922. if null:
  2923. # if we're not in __dev__, just return the function itself. This
  2924. # results in zero runtime overhead, since decorators are evaluated
  2925. # at module-load.
  2926. def nullDecorator(f):
  2927. return f
  2928. return nullDecorator
  2929. def _decoratorFunc(f, append=append):
  2930. global exceptionLoggedNotify
  2931. if exceptionLoggedNotify is None:
  2932. from direct.directnotify.DirectNotifyGlobal import directNotify
  2933. exceptionLoggedNotify = directNotify.newCategory("ExceptionLogged")
  2934. def _exceptionLogged(*args, **kArgs):
  2935. try:
  2936. return f(*args, **kArgs)
  2937. except Exception, e:
  2938. try:
  2939. s = '%s(' % f.func_name
  2940. for arg in args:
  2941. s += '%s, ' % arg
  2942. for key, value in kArgs.items():
  2943. s += '%s=%s, ' % (key, value)
  2944. if len(args) or len(kArgs):
  2945. s = s[:-2]
  2946. s += ')'
  2947. if append:
  2948. appendStr(e, '\n%s' % s)
  2949. else:
  2950. exceptionLoggedNotify.info(s)
  2951. except:
  2952. exceptionLoggedNotify.info(
  2953. '%s: ERROR IN PRINTING' % f.func_name)
  2954. raise
  2955. _exceptionLogged.__doc__ = f.__doc__
  2956. return _exceptionLogged
  2957. return _decoratorFunc
  2958. # class 'decorator' that records the stack at the time of creation
  2959. # be careful with this, it creates a StackTrace, and that can take a
  2960. # lot of CPU
  2961. def recordCreationStack(cls):
  2962. if not hasattr(cls, '__init__'):
  2963. raise 'recordCreationStack: class \'%s\' must define __init__' % cls.__name__
  2964. cls.__moved_init__ = cls.__init__
  2965. def __recordCreationStack_init__(self, *args, **kArgs):
  2966. self._creationStackTrace = StackTrace(start=1)
  2967. return self.__moved_init__(*args, **kArgs)
  2968. def getCreationStackTrace(self):
  2969. return self._creationStackTrace
  2970. def getCreationStackTraceCompactStr(self):
  2971. return self._creationStackTrace.compact()
  2972. def printCreationStackTrace(self):
  2973. print self._creationStackTrace
  2974. cls.__init__ = __recordCreationStack_init__
  2975. cls.getCreationStackTrace = getCreationStackTrace
  2976. cls.getCreationStackTraceCompactStr = getCreationStackTraceCompactStr
  2977. cls.printCreationStackTrace = printCreationStackTrace
  2978. return cls
  2979. # like recordCreationStack but stores the stack as a compact stack list-of-strings
  2980. # scales well for memory usage
  2981. def recordCreationStackStr(cls):
  2982. if not hasattr(cls, '__init__'):
  2983. raise 'recordCreationStackStr: class \'%s\' must define __init__' % cls.__name__
  2984. cls.__moved_init__ = cls.__init__
  2985. def __recordCreationStackStr_init__(self, *args, **kArgs):
  2986. # store as list of strings to conserve memory
  2987. self._creationStackTraceStrLst = StackTrace(start=1).compact().split(',')
  2988. return self.__moved_init__(*args, **kArgs)
  2989. def getCreationStackTraceCompactStr(self):
  2990. return string.join(self._creationStackTraceStrLst, ',')
  2991. def printCreationStackTrace(self):
  2992. print string.join(self._creationStackTraceStrLst, ',')
  2993. cls.__init__ = __recordCreationStackStr_init__
  2994. cls.getCreationStackTraceCompactStr = getCreationStackTraceCompactStr
  2995. cls.printCreationStackTrace = printCreationStackTrace
  2996. return cls
  2997. # class 'decorator' that logs all method calls for a particular class
  2998. def logMethodCalls(cls):
  2999. if not hasattr(cls, 'notify'):
  3000. raise 'logMethodCalls: class \'%s\' must have a notify' % cls.__name__
  3001. for name in dir(cls):
  3002. method = getattr(cls, name)
  3003. if callable(method):
  3004. def getLoggedMethodCall(method):
  3005. def __logMethodCall__(obj, *args, **kArgs):
  3006. s = '%s(' % method.__name__
  3007. for arg in args:
  3008. try:
  3009. argStr = repr(arg)
  3010. except:
  3011. argStr = 'bad repr: %s' % arg.__class__
  3012. s += '%s, ' % argStr
  3013. for karg, value in kArgs.items():
  3014. s += '%s=%s, ' % (karg, repr(value))
  3015. if len(args) or len(kArgs):
  3016. s = s[:-2]
  3017. s += ')'
  3018. obj.notify.info(s)
  3019. return method(obj, *args, **kArgs)
  3020. return __logMethodCall__
  3021. setattr(cls, name, getLoggedMethodCall(method))
  3022. __logMethodCall__ = None
  3023. return cls
  3024. # http://en.wikipedia.org/wiki/Golden_ratio
  3025. GoldenRatio = (1. + math.sqrt(5.)) / 2.
  3026. class GoldenRectangle:
  3027. @staticmethod
  3028. def getLongerEdge(shorter):
  3029. return shorter * GoldenRatio
  3030. @staticmethod
  3031. def getShorterEdge(longer):
  3032. return longer / GoldenRatio
  3033. class HotkeyBreaker:
  3034. def __init__(self,breakKeys = []):
  3035. from direct.showbase.DirectObject import DirectObject
  3036. self.do = DirectObject()
  3037. self.breakKeys = {}
  3038. if not isinstance(breakKeys, (list,tuple)):
  3039. breakKeys = (breakKeys,)
  3040. for key in breakKeys:
  3041. self.addBreakKey(key)
  3042. def addBreakKey(self,breakKey):
  3043. if __dev__:
  3044. self.do.accept(breakKey,self.breakFunc,extraArgs = [breakKey])
  3045. def removeBreakKey(self,breakKey):
  3046. if __dev__:
  3047. self.do.ignore(breakKey)
  3048. def breakFunc(self,breakKey):
  3049. if __dev__:
  3050. self.breakKeys[breakKey] = True
  3051. def setBreakPt(self, breakKey = None, persistent = False):
  3052. if __dev__:
  3053. if not breakKey:
  3054. import pdb;pdb.set_trace()
  3055. return True
  3056. else:
  3057. if self.breakKeys.get(breakKey,False):
  3058. if not persistent:
  3059. self.breakKeys.pop(breakKey)
  3060. import pdb;pdb.set_trace()
  3061. return True
  3062. return True
  3063. def clearBreakPt(self, breakKey):
  3064. if __dev__:
  3065. return bool(self.breakKeys.pop(breakKey,None))
  3066. def nullGen():
  3067. # generator that ends immediately
  3068. if False:
  3069. # yield that never runs but still exists, making this func a generator
  3070. yield None
  3071. def loopGen(l):
  3072. # generator that yields the items of an iterable object forever
  3073. def _gen(l):
  3074. while True:
  3075. for item in l:
  3076. yield item
  3077. gen = _gen(l)
  3078. # don't leak
  3079. _gen = None
  3080. return gen
  3081. def makeFlywheelGen(objects, countList=None, countFunc=None, scale=None):
  3082. # iterates and finally yields a flywheel generator object
  3083. # the number of appearances for each object is controlled by passing in
  3084. # a list of counts, or a functor that returns a count when called with
  3085. # an object from the 'objects' list.
  3086. # if scale is provided, all counts are scaled by the scale value and then int()'ed.
  3087. def flywheel(index2objectAndCount):
  3088. # generator to produce a sequence whose elements appear a specific number of times
  3089. while len(index2objectAndCount):
  3090. keyList = index2objectAndCount.keys()
  3091. for key in keyList:
  3092. if index2objectAndCount[key][1] > 0:
  3093. yield index2objectAndCount[key][0]
  3094. index2objectAndCount[key][1] -= 1
  3095. if index2objectAndCount[key][1] <= 0:
  3096. del index2objectAndCount[key]
  3097. # if we were not given a list of counts, create it by calling countFunc
  3098. if countList is None:
  3099. countList = []
  3100. for object in objects:
  3101. yield None
  3102. countList.append(countFunc(object))
  3103. if scale is not None:
  3104. # scale the counts if we've got a scale factor
  3105. for i in xrange(len(countList)):
  3106. yield None
  3107. if countList[i] > 0:
  3108. countList[i] = max(1, int(countList[i] * scale))
  3109. # create a dict for the flywheel to use during its iteration to efficiently select
  3110. # the objects for the sequence
  3111. index2objectAndCount = {}
  3112. for i in xrange(len(countList)):
  3113. yield None
  3114. index2objectAndCount[i] = [objects[i], countList[i]]
  3115. # create the flywheel generator
  3116. yield flywheel(index2objectAndCount)
  3117. def flywheel(*args, **kArgs):
  3118. # create a flywheel generator
  3119. # see arguments and comments in flywheelGen above
  3120. # example usage:
  3121. """
  3122. >>> for i in flywheel([1,2,3], countList=[10, 5, 1]):
  3123. ... print i,
  3124. ...
  3125. 1 2 3 1 2 1 2 1 2 1 2 1 1 1 1 1
  3126. """
  3127. for flywheel in makeFlywheelGen(*args, **kArgs):
  3128. pass
  3129. return flywheel
  3130. if __debug__:
  3131. f = flywheel(['a','b','c','d'], countList=[11,20,3,4])
  3132. obj2count = {}
  3133. for obj in f:
  3134. obj2count.setdefault(obj, 0)
  3135. obj2count[obj] += 1
  3136. assert obj2count['a'] == 11
  3137. assert obj2count['b'] == 20
  3138. assert obj2count['c'] == 3
  3139. assert obj2count['d'] == 4
  3140. f = flywheel([1,2,3,4], countFunc=lambda x: x*2)
  3141. obj2count = {}
  3142. for obj in f:
  3143. obj2count.setdefault(obj, 0)
  3144. obj2count[obj] += 1
  3145. assert obj2count[1] == 2
  3146. assert obj2count[2] == 4
  3147. assert obj2count[3] == 6
  3148. assert obj2count[4] == 8
  3149. f = flywheel([1,2,3,4], countFunc=lambda x: x, scale = 3)
  3150. obj2count = {}
  3151. for obj in f:
  3152. obj2count.setdefault(obj, 0)
  3153. obj2count[obj] += 1
  3154. assert obj2count[1] == 1 * 3
  3155. assert obj2count[2] == 2 * 3
  3156. assert obj2count[3] == 3 * 3
  3157. assert obj2count[4] == 4 * 3
  3158. def quickProfile(name="unnamed"):
  3159. import pstats
  3160. def profileDecorator(f):
  3161. if(not config.GetBool("use-profiler",0)):
  3162. return f
  3163. def _profiled(*args, **kArgs):
  3164. # must do this in here because we don't have base/simbase
  3165. # at the time that PythonUtil is loaded
  3166. if(not config.GetBool("profile-debug",0)):
  3167. #dumb timings
  3168. st=globalClock.getRealTime()
  3169. f(*args,**kArgs)
  3170. s=globalClock.getRealTime()-st
  3171. print "Function %s.%s took %s seconds"%(f.__module__, f.__name__,s)
  3172. else:
  3173. import profile as prof, pstats
  3174. #detailed profile, stored in base.stats under (
  3175. if(not hasattr(base,"stats")):
  3176. base.stats={}
  3177. if(not base.stats.get(name)):
  3178. base.stats[name]=[]
  3179. prof.runctx('f(*args, **kArgs)', {'f':f,'args':args,'kArgs':kArgs},None,"t.prof")
  3180. s=pstats.Stats("t.prof")
  3181. #p=hotshot.Profile("t.prof")
  3182. #p.runctx('f(*args, **kArgs)', {'f':f,'args':args,'kArgs':kArgs},None)
  3183. #s = hotshot.stats.load("t.prof")
  3184. s.strip_dirs()
  3185. s.sort_stats("cumulative")
  3186. base.stats[name].append(s)
  3187. _profiled.__doc__ = f.__doc__
  3188. return _profiled
  3189. return profileDecorator
  3190. def getTotalAnnounceTime():
  3191. td=0
  3192. for objs in base.stats.values():
  3193. for stat in objs:
  3194. td+=getAnnounceGenerateTime(stat)
  3195. return td
  3196. def getAnnounceGenerateTime(stat):
  3197. val=0
  3198. stats=stat.stats
  3199. for i in stats.keys():
  3200. if(i[2]=="announceGenerate"):
  3201. newVal=stats[i][3]
  3202. if(newVal>val):
  3203. val=newVal
  3204. return val
  3205. def choice(condition, ifTrue, ifFalse):
  3206. # equivalent of C++ (condition ? ifTrue : ifFalse)
  3207. if condition:
  3208. return ifTrue
  3209. else:
  3210. return ifFalse
  3211. class MiniLog:
  3212. def __init__(self, name):
  3213. self.indent = 1
  3214. self.name = name
  3215. self.lines = []
  3216. def __str__(self):
  3217. return '%s\nMiniLog: %s\n%s\n%s\n%s' % \
  3218. ('*'*50, self.name, '-'*50, '\n'.join(self.lines), '*'*50)
  3219. def enterFunction(self, funcName, *args, **kw):
  3220. rArgs = [`x`+', ' for x in args] + \
  3221. [ x + ' = ' + '%s, ' % `y` for x,y in kw.items()]
  3222. if not rArgs:
  3223. rArgs = '()'
  3224. else:
  3225. rArgs = '(' + reduce(str.__add__,rArgs)[:-2] + ')'
  3226. line = '%s%s' % (funcName, rArgs)
  3227. self.appendFunctionCall(line)
  3228. self.indent += 1
  3229. return line
  3230. def exitFunction(self):
  3231. self.indent -= 1
  3232. return self.indent
  3233. def appendFunctionCall(self, line):
  3234. self.lines.append(' '*(self.indent*2) + line)
  3235. return line
  3236. def appendLine(self, line):
  3237. self.lines.append(' '*(self.indent*2) + '<< ' + line + ' >>')
  3238. return line
  3239. def flush(self):
  3240. outStr = str(self)
  3241. self.indent = 0
  3242. self.lines = []
  3243. return outStr
  3244. class MiniLogSentry:
  3245. def __init__(self, log, funcName, *args, **kw):
  3246. self.log = log
  3247. if self.log:
  3248. self.log.enterFunction(funcName, *args, **kw)
  3249. def __del__(self):
  3250. if self.log:
  3251. self.log.exitFunction()
  3252. del self.log
  3253. def logBlock(id, msg):
  3254. print '<< LOGBLOCK(%03d)' % id
  3255. print str(msg)
  3256. print '/LOGBLOCK(%03d) >>' % id
  3257. class HierarchyException(Exception):
  3258. JOSWILSO = 0
  3259. def __init__(self, owner, description):
  3260. self.owner = owner
  3261. self.desc = description
  3262. def __str__(self):
  3263. return '(%s): %s' % (self.owner, self.desc)
  3264. def __repr__(self):
  3265. return 'HierarchyException(%s)' % (self.owner, )
  3266. # __dev__ is not defined at import time, call this after it's defined
  3267. def recordFunctorCreationStacks():
  3268. global Functor
  3269. from pandac.PandaModules import ConfigConfigureGetConfigConfigShowbase as config
  3270. if __dev__ and config.GetBool('record-functor-creation-stacks', 1):
  3271. if not hasattr(Functor, '_functorCreationStacksRecorded'):
  3272. Functor = recordCreationStackStr(Functor)
  3273. Functor._functorCreationStacksRecorded = True
  3274. Functor.__call__ = Functor._exceptionLoggedCreationStack__call__
  3275. def formatTimeCompact(seconds):
  3276. # returns string in format '1d3h22m43s'
  3277. result = ''
  3278. a = int(seconds)
  3279. seconds = a % 60
  3280. a /= 60
  3281. if a > 0:
  3282. minutes = a % 60
  3283. a /= 60
  3284. if a > 0:
  3285. hours = a % 24
  3286. a /= 24
  3287. if a > 0:
  3288. days = a
  3289. result += '%sd' % days
  3290. result += '%sh' % hours
  3291. result += '%sm' % minutes
  3292. result += '%ss' % seconds
  3293. return result
  3294. if __debug__:
  3295. ftc = formatTimeCompact
  3296. assert ftc(0) == '0s'
  3297. assert ftc(1) == '1s'
  3298. assert ftc(60) == '1m0s'
  3299. assert ftc(64) == '1m4s'
  3300. assert ftc(60*60) == '1h0m0s'
  3301. assert ftc(24*60*60) == '1d0h0m0s'
  3302. assert ftc(24*60*60 + 2*60*60 + 34*60 + 12) == '1d2h34m12s'
  3303. del ftc
  3304. def formatTimeExact(seconds):
  3305. # like formatTimeCompact but leaves off '0 seconds', '0 minutes' etc. for
  3306. # times that are e.g. 1 hour, 3 days etc.
  3307. # returns string in format '1d3h22m43s'
  3308. result = ''
  3309. a = int(seconds)
  3310. seconds = a % 60
  3311. a /= 60
  3312. if a > 0:
  3313. minutes = a % 60
  3314. a /= 60
  3315. if a > 0:
  3316. hours = a % 24
  3317. a /= 24
  3318. if a > 0:
  3319. days = a
  3320. result += '%sd' % days
  3321. if hours or minutes or seconds:
  3322. result += '%sh' % hours
  3323. if minutes or seconds:
  3324. result += '%sm' % minutes
  3325. if seconds or result == '':
  3326. result += '%ss' % seconds
  3327. return result
  3328. if __debug__:
  3329. fte = formatTimeExact
  3330. assert fte(0) == '0s'
  3331. assert fte(1) == '1s'
  3332. assert fte(2) == '2s'
  3333. assert fte(61) == '1m1s'
  3334. assert fte(60) == '1m'
  3335. assert fte(60*60) == '1h'
  3336. assert fte(24*60*60) == '1d'
  3337. assert fte((24*60*60) + (2 * 60)) == '1d0h2m'
  3338. del fte
  3339. class AlphabetCounter:
  3340. # object that produces 'A', 'B', 'C', ... 'AA', 'AB', etc.
  3341. def __init__(self):
  3342. self._curCounter = ['A']
  3343. def next(self):
  3344. result = ''.join([c for c in self._curCounter])
  3345. index = -1
  3346. while True:
  3347. curChar = self._curCounter[index]
  3348. if curChar is 'Z':
  3349. nextChar = 'A'
  3350. carry = True
  3351. else:
  3352. nextChar = chr(ord(self._curCounter[index])+1)
  3353. carry = False
  3354. self._curCounter[index] = nextChar
  3355. if carry:
  3356. if (-index) == len(self._curCounter):
  3357. self._curCounter = ['A',] + self._curCounter
  3358. break
  3359. else:
  3360. index -= 1
  3361. carry = False
  3362. else:
  3363. break
  3364. return result
  3365. if __debug__:
  3366. def testAlphabetCounter():
  3367. tempList = []
  3368. ac = AlphabetCounter()
  3369. for i in xrange(26*3):
  3370. tempList.append(ac.next())
  3371. assert tempList == [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
  3372. 'AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ',
  3373. 'BA','BB','BC','BD','BE','BF','BG','BH','BI','BJ','BK','BL','BM','BN','BO','BP','BQ','BR','BS','BT','BU','BV','BW','BX','BY','BZ',]
  3374. ac = AlphabetCounter()
  3375. num = 26 # A-Z
  3376. num += (26*26) # AA-ZZ
  3377. num += 26 # AAZ
  3378. num += 1 # ABA
  3379. num += 2 # ABC
  3380. for i in xrange(num):
  3381. x = ac.next()
  3382. assert x == 'ABC'
  3383. testAlphabetCounter()
  3384. del testAlphabetCounter
  3385. globalPdb = None
  3386. traceCalled = False
  3387. def setupPdb():
  3388. import pdb;
  3389. class pandaPdb(pdb.Pdb):
  3390. def stop_here(self, frame):
  3391. global traceCalled
  3392. if(traceCalled):
  3393. result = pdb.Pdb.stop_here(self, frame)
  3394. if(result == True):
  3395. traceCalled = False
  3396. return result
  3397. if frame is self.stopframe:
  3398. return True
  3399. return False
  3400. global globalPdb
  3401. globalPdb = pandaPdb()
  3402. globalPdb.reset()
  3403. sys.settrace(globalPdb.trace_dispatch)
  3404. def pandaTrace():
  3405. if __dev__:
  3406. if not globalPdb:
  3407. setupPdb()
  3408. global traceCalled
  3409. globalPdb.set_trace(sys._getframe().f_back)
  3410. traceCalled = True
  3411. packageMap = {
  3412. "toontown":"$TOONTOWN",
  3413. "direct":"$DIRECT",
  3414. "otp":"$OTP",
  3415. "pirates":"$PIRATES",
  3416. }
  3417. #assuming . dereferncing for nice linking to imports
  3418. def pandaBreak(dotpath, linenum, temporary = 0, cond = None):
  3419. if __dev__:
  3420. from pandac.PandaModules import Filename
  3421. if not globalPdb:
  3422. setupPdb()
  3423. dirs = dotpath.split(".")
  3424. root = Filename.expandFrom(packageMap[dirs[0]]).toOsSpecific()
  3425. filename = root + "\\src"
  3426. for d in dirs[1:]:
  3427. filename="%s\\%s"%(filename,d)
  3428. print filename
  3429. globalPdb.set_break(filename+".py", linenum, temporary, cond)
  3430. class Default:
  3431. # represents 'use the default value'
  3432. # useful for keyword arguments to virtual methods
  3433. pass
  3434. superLogFile = None
  3435. def startSuperLog():
  3436. global superLogFile
  3437. if(not superLogFile):
  3438. superLogFile = open("c:\\temp\\superLog.txt", "w")
  3439. def trace_dispatch(a,b,c):
  3440. if(b=='call' and a.f_code.co_name != '?' and a.f_code.co_name.find("safeRepr")<0):
  3441. vars = dict(a.f_locals)
  3442. if(vars.has_key('self')):
  3443. del vars['self']
  3444. if(vars.has_key('__builtins__')):
  3445. del vars['__builtins__']
  3446. for i in vars:
  3447. vars[i] = safeReprTypeOnFail(vars[i])
  3448. superLogFile.write( "%s(%s):%s:%s\n"%(a.f_code.co_filename.split("\\")[-1],a.f_code.co_firstlineno, a.f_code.co_name, vars))
  3449. return trace_dispatch
  3450. sys.settrace(trace_dispatch)
  3451. def endSuperLog():
  3452. global superLogFile
  3453. if(superLogFile):
  3454. sys.settrace(None)
  3455. superLogFile.close()
  3456. superLogFile = None
  3457. def isInteger(n):
  3458. return type(n) in (types.IntType, types.LongType)
  3459. def configIsToday(configName):
  3460. # returns true if config string is a valid representation of today's date
  3461. today = time.localtime()
  3462. confStr = config.GetString(configName, '')
  3463. for format in ('%m/%d/%Y', '%m-%d-%Y', '%m.%d.%Y'):
  3464. try:
  3465. confDate = time.strptime(confStr, format)
  3466. except ValueError:
  3467. pass
  3468. else:
  3469. if (confDate.tm_year == today.tm_year and
  3470. confDate.tm_mon == today.tm_mon and
  3471. confDate.tm_mday == today.tm_mday):
  3472. return True
  3473. return False
  3474. def typeName(o):
  3475. if hasattr(o, '__class__'):
  3476. return o.__class__.__name__
  3477. else:
  3478. return o.__name__
  3479. def safeTypeName(o):
  3480. try:
  3481. return typeName(o)
  3482. except:
  3483. pass
  3484. try:
  3485. return type(o)
  3486. except:
  3487. pass
  3488. return '<failed safeTypeName()>'
  3489. def histogramDict(l):
  3490. d = {}
  3491. for e in l:
  3492. d.setdefault(e, 0)
  3493. d[e] += 1
  3494. return d
  3495. import __builtin__
  3496. __builtin__.Functor = Functor
  3497. __builtin__.Stack = Stack
  3498. __builtin__.Queue = Queue
  3499. __builtin__.Enum = Enum
  3500. __builtin__.SerialNumGen = SerialNumGen
  3501. __builtin__.ScratchPad = ScratchPad
  3502. __builtin__.DestructiveScratchPad = DestructiveScratchPad
  3503. __builtin__.uniqueName = uniqueName
  3504. __builtin__.serialNum = serialNum
  3505. __builtin__.profiled = profiled
  3506. __builtin__.set_trace = set_trace
  3507. __builtin__.setTrace = setTrace
  3508. __builtin__.pm = pm
  3509. __builtin__.itype = itype
  3510. __builtin__.exceptionLogged = exceptionLogged
  3511. __builtin__.appendStr = appendStr
  3512. __builtin__.bound = bound
  3513. __builtin__.lerp = lerp
  3514. __builtin__.notNone = notNone
  3515. __builtin__.clampScalar = clampScalar
  3516. __builtin__.makeList = makeList
  3517. __builtin__.makeTuple = makeTuple
  3518. __builtin__.printStack = printStack
  3519. __builtin__.printReverseStack = printReverseStack
  3520. __builtin__.printVerboseStack = printVerboseStack
  3521. __builtin__.DelayedCall = DelayedCall
  3522. __builtin__.DelayedFunctor = DelayedFunctor
  3523. __builtin__.FrameDelayedCall = FrameDelayedCall
  3524. __builtin__.SubframeCall = SubframeCall
  3525. __builtin__.ArgumentEater = ArgumentEater
  3526. __builtin__.ClassTree = ClassTree
  3527. __builtin__.invertDict = invertDict
  3528. __builtin__.invertDictLossless = invertDictLossless
  3529. __builtin__.getBase = getBase
  3530. __builtin__.getRepository = getRepository
  3531. __builtin__.safeRepr = safeRepr
  3532. __builtin__.fastRepr = fastRepr
  3533. __builtin__.nullGen = nullGen
  3534. __builtin__.flywheel = flywheel
  3535. __builtin__.loopGen = loopGen
  3536. __builtin__.StackTrace = StackTrace
  3537. __builtin__.choice = choice
  3538. __builtin__.report = report
  3539. __builtin__.MiniLog = MiniLog
  3540. __builtin__.MiniLogSentry = MiniLogSentry
  3541. __builtin__.logBlock = logBlock
  3542. __builtin__.HierarchyException = HierarchyException
  3543. __builtin__.pdir = pdir
  3544. __builtin__.deeptype = deeptype
  3545. __builtin__.Default = Default
  3546. __builtin__.isInteger = isInteger
  3547. __builtin__.configIsToday = configIsToday
  3548. __builtin__.typeName = typeName
  3549. __builtin__.safeTypeName = safeTypeName
  3550. __builtin__.histogramDict = histogramDict