PythonUtil.py 135 KB

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